RustToDust/client/Main.cs

397 lines
14 KiB
C#

using System;
using Godot;
using RustToDust.Core;
using RustToDust.Ymir;
namespace RustToDust.Client;
/// <summary>
/// Root Godot node for Rust to Dust.
/// Godot physics is Dummy; <see cref="ArenaSession"/> owns 100% of vehicle, thermal, spectator, and terrain physics at 60 Hz.
/// </summary>
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 _cameraYaw;
private float _cameraPitch = Mathf.DegToRad(12f);
private float _cameraZoom = 1.0f;
private Vector3 _cameraSmoothedAnchor = 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 float CameraYaw => _cameraYaw;
public override void _Ready()
{
SetupLightingAndSky();
_terrain = new TerrainRenderer { Name = "Terrain" };
AddChild(_terrain);
_arena = new ArenaRenderer { Name = "Arena" };
AddChild(_arena);
_camera = new Camera3D
{
Name = "ShoulderCamera",
Current = true,
Fov = 58f,
Far = 1800f
};
AddChild(_camera);
_hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw) { 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;
_cameraYaw = p.Yaw;
_cameraPitch = Mathf.DegToRad(12f);
_cameraZoom = 1.0f;
_cameraSmoothedAnchor = ComputeTargetAnchor(p);
_terrain.InvalidateAll();
_terrain.Sync(_session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds);
UpdateCamera(1f);
_hud.Sync(_session);
if (DisplayServer.GetName() != "headless" && !_hud.GarageExpanded)
{
Input.MouseMode = Input.MouseModeEnum.Captured;
}
}
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 InputEventMouseMotion mm && Input.MouseMode == Input.MouseModeEnum.Captured)
{
_cameraYaw -= mm.Relative.X * 0.0028f;
_cameraPitch = Math.Clamp(
_cameraPitch + mm.Relative.Y * 0.0024f,
Mathf.DegToRad(-18f),
Mathf.DegToRad(38f));
return;
}
if (@event is InputEventKey key && key.Pressed && !key.Echo)
{
switch (key.Keycode)
{
case Key.E:
_interactQueued = true;
break;
case Key.Tab:
_hud.ToggleGarage();
if (DisplayServer.GetName() != "headless")
{
Input.MouseMode = _hud.GarageExpanded
? Input.MouseModeEnum.Visible
: Input.MouseModeEnum.Captured;
}
break;
case Key.T:
_hud.ToggleThermal();
break;
case Key.R:
Reset(_seed + 1);
break;
case Key.Escape:
if (_hud.GarageExpanded)
{
_hud.ToggleGarage();
if (DisplayServer.GetName() != "headless")
{
Input.MouseMode = Input.MouseModeEnum.Visible;
}
}
else if (DisplayServer.GetName() != "headless")
{
Input.MouseMode = Input.MouseMode == Input.MouseModeEnum.Captured
? Input.MouseModeEnum.Visible
: Input.MouseModeEnum.Captured;
}
break;
}
}
else if (@event is InputEventMouseButton mb && mb.Pressed)
{
if (mb.ButtonIndex == MouseButton.WheelUp)
{
_cameraZoom = Math.Clamp(_cameraZoom - 0.08f, 0.75f, 1.6f);
}
else if (mb.ButtonIndex == MouseButton.WheelDown)
{
_cameraZoom = Math.Clamp(_cameraZoom + 0.08f, 0.75f, 1.6f);
}
else if (mb.ButtonIndex == MouseButton.Left &&
Input.MouseMode == Input.MouseModeEnum.Visible &&
!_hud.GarageExpanded &&
!_hud.IsPointerOverInteractiveHud(mb.Position) &&
DisplayServer.GetName() != "headless")
{
Input.MouseMode = Input.MouseModeEnum.Captured;
}
}
}
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);
bool pointerOnHud = Input.MouseMode != Input.MouseModeEnum.Captured &&
_hud.IsPointerOverInteractiveHud(GetViewport().GetMousePosition());
bool fire = !pointerOnHud && Input.IsMouseButtonPressed(MouseButton.Left);
var (aimX, aimY, aimZ) = ComputeCenterScreenAim();
return new PlayerInput(
Throttle: throttle,
Steer: steer,
AimWorldX: aimX,
AimWorldZ: aimZ,
Fire: fire,
InteractPickup: _interactQueued,
Brake: brake,
AimWorldY: aimY);
}
private (float AimX, float AimY, float AimZ) ComputeCenterScreenAim()
{
var player = Session.State.Player;
Vector2 screenSize = GetViewport().GetVisibleRect().Size;
if (screenSize.X < 2f || screenSize.Y < 2f)
{
return (
player.X + MathF.Sin(_cameraYaw) * 40f,
player.Y,
player.Z + MathF.Cos(_cameraYaw) * 40f);
}
Vector2 center = screenSize * 0.5f;
Vector3 rayOrigin = _camera.ProjectRayOrigin(center);
Vector3 rayDir = _camera.ProjectRayNormal(center);
const float maxAimDist = 450f;
ulong playerStableId = ArenaSession.ContenderStableIdBase + (ulong)player.Id;
Vector3 castOrigin = rayOrigin;
float remainingDist = maxAimDist;
float boxDist = maxAimDist;
Vector3 boxHitPt = Vector3.Zero;
bool hasBoxHit = false;
// Cast against Ymir world, skipping the player's own chassis if hit along the shoulder ray.
for (int attempt = 0; attempt < 2; attempt++)
{
var hit = Session.World.CastRayClosest(
(castOrigin.X, castOrigin.Y, castOrigin.Z),
(rayDir.X * remainingDist, rayDir.Y * remainingDist, rayDir.Z * remainingDist));
if (!hit.Hit)
{
break;
}
var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z);
if (hit.StableId == playerStableId)
{
float skip = rayOrigin.DistanceTo(pt) + 0.4f;
castOrigin = rayOrigin + rayDir * skip;
remainingDist = MathF.Max(1f, maxAimDist - skip);
continue;
}
boxHitPt = pt;
boxDist = rayOrigin.DistanceTo(pt);
hasBoxHit = true;
break;
}
bool hasTerrainHit = Session.State.Terrain.Raycast(
rayOrigin.X, rayOrigin.Y, rayOrigin.Z,
rayDir.X, rayDir.Y, rayDir.Z,
maxDistance: boxDist,
out float tx, out float ty, out float tz, out float terrainDist);
if (hasTerrainHit && terrainDist <= boxDist)
{
return (tx, ty, tz);
}
if (hasBoxHit)
{
return (boxHitPt.X, boxHitPt.Y, boxHitPt.Z);
}
Vector3 farPt = rayOrigin + rayDir * 320f;
return (farPt.X, farPt.Y, farPt.Z);
}
private Vector3 ComputeTargetAnchor(ContenderState p)
{
var spec = p.Grid.Spec;
float heightT = Math.Clamp((spec.HalfHeight - 0.75f) / (2.35f - 0.75f), 0f, 1.2f);
float upOffset = Mathf.Lerp(3.2f, 6.5f, heightT);
float rightOffset = Mathf.Lerp(1.6f, 2.8f, heightT);
var camRight = new Vector3(-MathF.Cos(_cameraYaw), 0f, MathF.Sin(_cameraYaw));
return new Vector3(p.X, p.Y + (upOffset - spec.HalfHeight), p.Z) + camRight * rightOffset;
}
private void UpdateCamera(float dt)
{
var p = Session.State.Player;
var spec = p.Grid.Spec;
float heightT = Math.Clamp((spec.HalfHeight - 0.75f) / (2.35f - 0.75f), 0f, 1.2f);
float backDist = Mathf.Lerp(7.5f, 12.5f, heightT) * _cameraZoom;
Vector3 targetAnchor = ComputeTargetAnchor(p);
float blend = dt >= 1f ? 1f : 1f - MathF.Exp(-dt * 16f);
_cameraSmoothedAnchor = _cameraSmoothedAnchor.Lerp(targetAnchor, blend);
var camFwdHoriz = new Vector3(MathF.Sin(_cameraYaw), 0f, MathF.Cos(_cameraYaw));
var lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized();
// Pull camera forward along arm if terrain or static cover blocks the shoulder-to-camera ray
float effectiveBack = backDist;
if (Session.State.Terrain.Raycast(
_cameraSmoothedAnchor.X, _cameraSmoothedAnchor.Y, _cameraSmoothedAnchor.Z,
-lookDir.X, -lookDir.Y, -lookDir.Z,
backDist,
out _, out _, out _, out float terrainDist))
{
effectiveBack = MathF.Min(effectiveBack, MathF.Max(1.6f, terrainDist - 0.6f));
}
var boxHit = Session.World.CastRayClosest(
(_cameraSmoothedAnchor.X, _cameraSmoothedAnchor.Y, _cameraSmoothedAnchor.Z),
(-lookDir.X * effectiveBack, -lookDir.Y * effectiveBack, -lookDir.Z * effectiveBack));
if (boxHit.Hit && boxHit.StableId < ArenaSession.ContenderStableIdBase)
{
var pt = new Vector3(boxHit.Point.X, boxHit.Point.Y, boxHit.Point.Z);
effectiveBack = MathF.Min(effectiveBack, MathF.Max(1.6f, _cameraSmoothedAnchor.DistanceTo(pt) - 0.5f));
}
Vector3 camPos = _cameraSmoothedAnchor - lookDir * effectiveBack;
float minTerrainY = Session.State.Terrain.SampleHeight(camPos.X, camPos.Z) + 1.2f;
if (camPos.Y < minTerrainY)
{
camPos.Y = minTerrainY;
}
_camera.GlobalPosition = camPos;
_camera.LookAt(camPos + lookDir * 60f, 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,
FogMode = Godot.Environment.FogModeEnum.Depth,
FogLightColor = new Color(0.76f, 0.57f, 0.39f),
FogDensity = 0.72f,
FogDepthBegin = 380f,
FogDepthEnd = 1100f
};
AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = env });
}
}