RustToDust/client/InventoryGridControl.cs

746 lines
25 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// Godot Control owning <c>inventory_grid.gdshader</c>:
/// packs a <see cref="ChassisGrid"/> into a 3W x H RGBA8 nearest-filter data texture
/// and a W x H RGBA8 bilinear temperature texture, tracks hover and hit-pulse decay,
/// and provides accurate mouse-to-cell hit-testing for HUD and Garage schematics.
/// </summary>
public partial class InventoryGridControl : Control
{
private static readonly Color ColBgIntact = Color.FromHtml("#263022");
private static readonly Color ColBgArmorFull = Color.FromHtml("#4b6136");
private static readonly Color ColBgDamaged = Color.FromHtml("#8a3c22");
private static readonly Color ColBgStripped = Color.FromHtml("#2b1210");
private static readonly Color ColBorderHull = Color.FromHtml("#7a856e");
private static readonly Color ColBorderRadiatorCell = Color.FromHtml("#44d9e8");
private static readonly Color ColBorderWeapon = Color.FromHtml("#e08a4a");
private static readonly Color ColBorderEngine = Color.FromHtml("#e6b838");
private static readonly Color ColBorderRadiator = Color.FromHtml("#44d9e8");
private static readonly Color ColBorderArmor = Color.FromHtml("#9bb06a");
private static readonly Color ColBorderUtility = Color.FromHtml("#4ba8a5");
private static readonly Color ColGold = Color.FromHtml("#e6b838");
private static readonly Color ColTextLight = Color.FromHtml("#e4dfd2");
// 8-neighbor offsets in Aetheria mask order: N, E, S, W, NE, SE, SW, NW (screen Y-down)
private static readonly (int Dx, int Dy)[] Offsets8 =
{
(0, -1), (1, 0), (0, 1), (-1, 0),
(1, -1), (1, 1), (-1, 1), (-1, -1)
};
private static Shader? _sharedShader;
private readonly TextureRect _gridSurface;
private readonly LabelsOverlay _labelsOverlay;
private readonly ShaderMaterial _material;
private Image? _dataImage;
private ImageTexture? _dataTex;
private Image? _tempImage;
private ImageTexture? _tempTex;
private int _gridWidth;
private int _gridHeight;
private ChassisGrid? _grid;
private ChassisSpec? _spec;
private int _selectedCargoIndex = -1;
private int _lastHitSequence = -1;
private HardpointSpec?[,] _hardpointLookup = new HardpointSpec?[0, 0];
private float[,] _prevArmor = new float[0, 0];
private float[,] _prevTemp = new float[0, 0];
private float[,] _hitPulse = new float[0, 0];
private int _lastSelectedCargoIndex = int.MinValue;
private string? _lastSelectedCargoId;
private int _lastMountedSig = int.MinValue;
private Vector2I? _hoveredCell;
private bool _dataDirty;
private bool _tempDirty;
public InventoryGridControl()
{
MouseFilter = MouseFilterEnum.Stop;
_sharedShader ??= GD.Load<Shader>("res://inventory_grid.gdshader");
_material = new ShaderMaterial { Shader = _sharedShader };
_gridSurface = new TextureRect
{
Name = "GridShaderSurface",
MouseFilter = MouseFilterEnum.Ignore,
ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize,
StretchMode = TextureRect.StretchModeEnum.Scale,
Material = _material
};
_gridSurface.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(_gridSurface);
_labelsOverlay = new LabelsOverlay(this)
{
Name = "GridLabelsOverlay",
MouseFilter = MouseFilterEnum.Ignore
};
_labelsOverlay.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(_labelsOverlay);
MouseExited += OnMouseExited;
}
public ShaderMaterial ShaderMaterial => _material;
public Control ShaderSurface => _gridSurface;
public ChassisGrid? Grid => _grid;
public Vector2I? HoveredCell => _hoveredCell;
public HardpointSpec? HoveredHardpoint =>
_hoveredCell is { } c && _grid is not null && c.X >= 0 && c.Y >= 0 && c.X < _gridWidth && c.Y < _gridHeight
? _hardpointLookup[c.X, c.Y]
: null;
internal int LabelsDrawCount => _labelsOverlay.DrawCount;
internal string? GetLastDrawnLabel(string hardpointId) =>
_labelsOverlay.LastDrawnTags.TryGetValue(hardpointId, out string? tag) ? tag : null;
public event Action<int, int>? CellClicked;
public event Action<string>? HardpointClicked;
public event Action<Vector2I?, HardpointSpec?>? HoverChanged;
public override void _Notification(int what)
{
if (what == NotificationResized)
{
SyncRectUniform();
_labelsOverlay.QueueRedraw();
}
}
public override void _Process(double delta)
{
float dt = (float)delta;
bool anyPulse = false;
for (int y = 0; y < _gridHeight; y++)
{
for (int x = 0; x < _gridWidth; x++)
{
if (_hitPulse[x, y] > 0f)
{
_hitPulse[x, y] = MathF.Max(0f, _hitPulse[x, y] - dt * 2.8f);
anyPulse = true;
}
}
}
if (anyPulse && _grid is not null)
{
PackDataTexture(_grid);
FlushTextures();
}
}
public override void _GuiInput(InputEvent @event)
{
if (@event is InputEventMouseMotion mm)
{
UpdateHover(mm.Position);
return;
}
if (@event is InputEventMouseButton mb && mb.Pressed && mb.ButtonIndex == MouseButton.Left)
{
UpdateHover(mb.Position);
if (TryGetCellAt(mb.Position, out var cell) && _grid is not null && _grid.Spec.IsActive(cell.X, cell.Y))
{
CellClicked?.Invoke(cell.X, cell.Y);
var hp = _hardpointLookup[cell.X, cell.Y];
if (hp is not null)
{
HardpointClicked?.Invoke(hp.Id);
}
AcceptEvent();
}
}
}
public void SetGrid(ChassisGrid grid, int selectedCargoIndex = -1)
{
if (grid is null) throw new ArgumentNullException(nameof(grid));
bool gridIdentityChanged = !ReferenceEquals(_grid, grid)
|| !ReferenceEquals(_spec, grid.Spec)
|| _gridWidth != grid.Spec.Width
|| _gridHeight != grid.Spec.Height;
_grid = grid;
_spec = grid.Spec;
_selectedCargoIndex = selectedCargoIndex;
string? selectedCargoId = selectedCargoIndex >= 0 && selectedCargoIndex < grid.Cargo.Count
? grid.Cargo[selectedCargoIndex].Id
: null;
if (gridIdentityChanged)
{
EnsureBackingBuffers(grid);
_lastSelectedCargoIndex = selectedCargoIndex;
_lastSelectedCargoId = selectedCargoId;
_lastMountedSig = ComputeMountedSignature(grid);
SnapshotTemperatures(grid);
PackDataTexture(grid);
PackTempTexture(grid);
FlushTextures();
SyncRectUniform();
_labelsOverlay.QueueRedraw();
return;
}
bool dataChanged = DetectHits(grid);
int mountedSig = ComputeMountedSignature(grid);
if (_lastSelectedCargoIndex != selectedCargoIndex ||
!string.Equals(_lastSelectedCargoId, selectedCargoId, StringComparison.Ordinal) ||
_lastMountedSig != mountedSig)
{
_lastSelectedCargoIndex = selectedCargoIndex;
_lastSelectedCargoId = selectedCargoId;
_lastMountedSig = mountedSig;
dataChanged = true;
}
bool tempChanged = HasTemperatureChanged(grid);
if (dataChanged)
{
PackDataTexture(grid);
}
if (tempChanged)
{
SnapshotTemperatures(grid);
PackTempTexture(grid);
}
if (dataChanged || tempChanged)
{
_labelsOverlay.QueueRedraw();
FlushTextures();
}
}
public void TriggerHitPulse(int x, int y, float intensity = 1f)
{
if (_grid is null || x < 0 || y < 0 || x >= _gridWidth || y >= _gridHeight) return;
if (!_grid.Spec.IsActive(x, y)) return;
_hitPulse[x, y] = Math.Clamp(intensity, 0f, 1f);
PackDataTexture(_grid);
FlushTextures();
}
public bool TryGetCellAt(Vector2 localPos, out Vector2I cell)
{
cell = default;
if (_grid is null || _gridWidth <= 0 || _gridHeight <= 0) return false;
ComputeCellLayout(out float cellSize, out Vector2 origin);
if (cellSize <= 0.5f) return false;
Vector2 rel = (localPos - origin) / cellSize;
int cx = Mathf.FloorToInt(rel.X);
int cy = Mathf.FloorToInt(rel.Y);
if (cx < 0 || cy < 0 || cx >= _gridWidth || cy >= _gridHeight) return false;
cell = new Vector2I(cx, cy);
return true;
}
public HardpointSpec? GetHardpointAt(int x, int y)
{
if (x < 0 || y < 0 || x >= _gridWidth || y >= _gridHeight) return null;
return _hardpointLookup[x, y];
}
public void ComputeCellLayout(out float cellSize, out Vector2 origin)
{
int w = Math.Max(1, _gridWidth);
int h = Math.Max(1, _gridHeight);
Vector2 size = Size;
if (size.X < 2f || size.Y < 2f)
{
size = CustomMinimumSize;
}
cellSize = MathF.Min(size.X / w, size.Y / h);
origin = (size - new Vector2(w * cellSize, h * cellSize)) * 0.5f;
}
private void OnMouseExited()
{
if (_hoveredCell.HasValue)
{
_hoveredCell = null;
HoverChanged?.Invoke(null, null);
if (_grid is not null)
{
PackDataTexture(_grid);
FlushTextures();
}
}
}
private void UpdateHover(Vector2 localPos)
{
Vector2I? next = null;
if (TryGetCellAt(localPos, out var c) && _grid is not null && _grid.Spec.IsActive(c.X, c.Y))
{
next = c;
}
if (_hoveredCell == next) return;
_hoveredCell = next;
HoverChanged?.Invoke(next, HoveredHardpoint);
if (_grid is not null)
{
PackDataTexture(_grid);
FlushTextures();
}
}
private void EnsureBackingBuffers(ChassisGrid grid)
{
int w = grid.Spec.Width;
int h = grid.Spec.Height;
bool dimsChanged = w != _gridWidth || h != _gridHeight || _dataTex is null || _tempTex is null;
_gridWidth = w;
_gridHeight = h;
_hardpointLookup = new HardpointSpec?[w, h];
for (int i = 0; i < grid.Spec.Hardpoints.Length; i++)
{
var hp = grid.Spec.Hardpoints[i];
for (int dy = 0; dy < hp.Height; dy++)
{
for (int dx = 0; dx < hp.Width; dx++)
{
int hx = hp.X + dx;
int hy = hp.Y + dy;
if (hx >= 0 && hy >= 0 && hx < w && hy < h && grid.Spec.IsActive(hx, hy))
{
_hardpointLookup[hx, hy] = hp;
}
}
}
}
_prevArmor = new float[w, h];
_prevTemp = new float[w, h];
_hitPulse = new float[w, h];
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
_prevArmor[x, y] = grid.Armor[x, y];
_prevTemp[x, y] = grid.Temperature[x, y];
}
}
_lastHitSequence = grid.HitSequence;
bool hadHover = _hoveredCell.HasValue;
_hoveredCell = null;
if (dimsChanged)
{
_dataImage = Image.CreateEmpty(Math.Max(1, w * 3), Math.Max(1, h), false, Image.Format.Rgba8);
_dataTex = ImageTexture.CreateFromImage(_dataImage);
_tempImage = Image.CreateEmpty(Math.Max(1, w), Math.Max(1, h), false, Image.Format.Rgba8);
_tempTex = ImageTexture.CreateFromImage(_tempImage);
_gridSurface.Texture = _dataTex;
_material.SetShaderParameter("data_tex", _dataTex);
_material.SetShaderParameter("temp_tex", _tempTex);
}
_material.SetShaderParameter("grid_size", new Vector2(w, h));
if (hadHover)
{
HoverChanged?.Invoke(null, null);
}
}
private bool DetectHits(ChassisGrid grid)
{
bool changed = false;
if (grid.HitSequence != _lastHitSequence)
{
_lastHitSequence = grid.HitSequence;
if (grid.LastHitX >= 0 && grid.LastHitY >= 0 && grid.LastHitX < _gridWidth && grid.LastHitY < _gridHeight)
{
_hitPulse[grid.LastHitX, grid.LastHitY] = 1f;
}
changed = true;
}
for (int y = 0; y < _gridHeight; y++)
{
for (int x = 0; x < _gridWidth; x++)
{
float arm = grid.Armor[x, y];
if (arm < _prevArmor[x, y] - 0.05f)
{
_hitPulse[x, y] = 1f;
_prevArmor[x, y] = arm;
changed = true;
}
else if (MathF.Abs(arm - _prevArmor[x, y]) > 0.01f)
{
_prevArmor[x, y] = arm;
changed = true;
}
}
}
return changed;
}
private static int ComputeMountedSignature(ChassisGrid grid)
{
var hc = new HashCode();
hc.Add(grid.Mounted.Count);
for (int i = 0; i < grid.Mounted.Count; i++)
{
var m = grid.Mounted[i];
hc.Add(m.HardpointId);
hc.Add(m.Spec.Id);
hc.Add(m.CurrentPerformance > 0.05f);
}
return hc.ToHashCode();
}
private bool HasTemperatureChanged(ChassisGrid grid)
{
for (int y = 0; y < _gridHeight; y++)
{
for (int x = 0; x < _gridWidth; x++)
{
if (MathF.Abs(grid.Temperature[x, y] - _prevTemp[x, y]) >= 0.25f)
{
return true;
}
}
}
return false;
}
private void SnapshotTemperatures(ChassisGrid grid)
{
for (int y = 0; y < _gridHeight; y++)
{
for (int x = 0; x < _gridWidth; x++)
{
_prevTemp[x, y] = grid.Temperature[x, y];
}
}
}
private void PackDataTexture(ChassisGrid grid)
{
if (_dataImage is null) return;
var spec = grid.Spec;
ModuleSpec? selectedCargo = _selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count
? grid.Cargo[_selectedCargoIndex]
: null;
HardpointSpec? hoveredHp = HoveredHardpoint;
for (int y = 0; y < _gridHeight; y++)
{
for (int x = 0; x < _gridWidth; x++)
{
if (!spec.IsActive(x, y))
{
var zero = new Color(0f, 0f, 0f, 0f);
_dataImage.SetPixel(x * 3 + 0, y, zero);
_dataImage.SetPixel(x * 3 + 1, y, zero);
_dataImage.SetPixel(x * 3 + 2, y, zero);
continue;
}
var hp = _hardpointLookup[x, y];
var mounted = hp is not null ? grid.GetMountedOn(hp.Id) : null;
float maxArm = MathF.Max(1f, grid.MaxArmor[x, y]);
float arm = grid.Armor[x, y];
float armRatio = Math.Clamp(arm / maxArm, 0f, 1f);
bool stripped = arm <= 0.01f;
bool isBorder = grid.BorderCells[x, y];
bool isCompatible = hp is not null && selectedCargo is not null && ChassisGrid.CanFit(hp, selectedCargo);
bool isHovered = (_hoveredCell is { } hc && hc.X == x && hc.Y == y)
|| (hoveredHp is not null && ReferenceEquals(hp, hoveredHp));
// 3x+0: Cell / item fill & armor tint
Color fill;
if (stripped)
{
fill = ColBgStripped;
}
else
{
Color armorCol = armRatio > 0.5f
? ColBgIntact.Lerp(ColBgArmorFull, (armRatio - 0.5f) * 2f)
: ColBgDamaged.Lerp(ColBgIntact, armRatio * 2f);
if (mounted is not null)
{
Color modTint = mounted.Spec.IsImperial ? ColGold : KindColor(hp!.Kind);
fill = armorCol.Lerp(modTint, 0.28f);
}
else
{
fill = armorCol;
}
}
fill.A = stripped ? 0.92f : 0.86f;
// 3x+1: Border / L-bracket / pipe accent color
Color accent;
if (hp is not null)
{
if (isCompatible)
{
accent = ColGold;
}
else if (mounted is { Spec.IsImperial: true })
{
accent = ColGold;
}
else
{
accent = KindColor(hp.Kind);
if (mounted is null)
{
accent = accent.Lerp(ColBorderHull, 0.45f);
}
}
accent.A = 0.96f;
}
else if (isBorder)
{
accent = ColBorderHull.Lerp(ColBorderRadiatorCell, 0.28f);
accent.A = 0.72f;
}
else
{
accent = ColBorderHull;
accent.A = 0.62f;
}
// 3x+2.R: 8-bit neighbor mismatch mask (Aetheria rule)
byte mask = 0;
for (int i = 0; i < Offsets8.Length; i++)
{
int nx = x + Offsets8[i].Dx;
int ny = y + Offsets8[i].Dy;
bool match;
if (!spec.IsActive(nx, ny))
{
match = false;
}
else if (hp is not null)
{
match = ReferenceEquals(_hardpointLookup[nx, ny], hp);
}
else
{
match = _hardpointLookup[nx, ny] is null;
}
if (!match)
{
mask |= (byte)(1 << i);
}
}
// 3x+2.G: flags byte
int flags = 1; // bit 0: present
if (mounted is not null) flags |= 2; // bit 1: mounted module / item
if (isHovered) flags |= 4; // bit 2: hovered
if (stripped) flags |= 8; // bit 3: stripped / Armor == 0
if (isCompatible) flags |= 16; // bit 4: compatible cargo drop target
if (isBorder) flags |= 32; // bit 5: border radiator cell
float pulse = Math.Clamp(_hitPulse[x, y], 0f, 1f);
var meta = new Color(mask / 255f, flags / 255f, 0f, pulse);
_dataImage.SetPixel(x * 3 + 0, y, fill);
_dataImage.SetPixel(x * 3 + 1, y, accent);
_dataImage.SetPixel(x * 3 + 2, y, meta);
}
}
_dataDirty = true;
}
private void PackTempTexture(ChassisGrid grid)
{
if (_tempImage is null) return;
var spec = grid.Spec;
// First pass: active cells
for (int y = 0; y < _gridHeight; y++)
{
for (int x = 0; x < _gridWidth; x++)
{
if (!spec.IsActive(x, y)) continue;
float t = grid.Temperature[x, y];
float normTemp = Math.Clamp((t - ChassisGrid.AmbientTemp) / 180f, 0f, 1f);
float stress = normTemp * 0.25f;
var hp = _hardpointLookup[x, y];
var mounted = hp is not null ? grid.GetMountedOn(hp.Id) : null;
if (mounted is not null)
{
float highPlateau = mounted.Spec.OptimalTemp + mounted.Spec.PlateauWidth * 0.5f;
if (t > highPlateau)
{
float overSpan = MathF.Max(1f, mounted.Spec.MaxTemp - highPlateau);
stress = 0.5f + 0.5f * Math.Clamp((t - highPlateau) / overSpan, 0f, 1f);
}
else
{
stress = 0.5f * Math.Clamp(mounted.CurrentPerformance, 0f, 1f);
}
}
_tempImage.SetPixel(x, y, new Color(normTemp, stress, 1f, 1f));
}
}
// Second pass: extrapolate boundary temperature into inactive neighbor cells
// so bilinear filter_linear sampling stays smooth without cold zero bleed at hull edges.
for (int y = 0; y < _gridHeight; y++)
{
for (int x = 0; x < _gridWidth; x++)
{
if (spec.IsActive(x, y)) continue;
float sumR = 0f;
float sumG = 0f;
int count = 0;
for (int i = 0; i < Offsets8.Length; i++)
{
int nx = x + Offsets8[i].Dx;
int ny = y + Offsets8[i].Dy;
if (spec.IsActive(nx, ny))
{
var c = _tempImage.GetPixel(nx, ny);
sumR += c.R;
sumG += c.G;
count++;
}
}
if (count > 0)
{
_tempImage.SetPixel(x, y, new Color(sumR / count, sumG / count, 0f, 1f));
}
else
{
_tempImage.SetPixel(x, y, new Color(0f, 0f, 0f, 1f));
}
}
}
_tempDirty = true;
}
private void FlushTextures()
{
if (_dataDirty && _dataTex is not null && _dataImage is not null)
{
_dataTex.Update(_dataImage);
_dataDirty = false;
}
if (_tempDirty && _tempTex is not null && _tempImage is not null)
{
_tempTex.Update(_tempImage);
_tempDirty = false;
}
}
private void SyncRectUniform()
{
Vector2 size = Size;
if (size.X < 2f || size.Y < 2f)
{
size = CustomMinimumSize;
}
_material.SetShaderParameter("rect_size", size);
}
private static Color KindColor(HardpointKind kind) => kind switch
{
HardpointKind.Weapon => ColBorderWeapon,
HardpointKind.Engine => ColBorderEngine,
HardpointKind.Radiator => ColBorderRadiator,
HardpointKind.Armor => ColBorderArmor,
HardpointKind.Utility => ColBorderUtility,
_ => ColTextLight
};
private sealed partial class LabelsOverlay : Control
{
private readonly InventoryGridControl _owner;
public int DrawCount { get; private set; }
public readonly Dictionary<string, string> LastDrawnTags = new(StringComparer.Ordinal);
public LabelsOverlay(InventoryGridControl owner) => _owner = owner;
public override void _Draw()
{
DrawCount++;
LastDrawnTags.Clear();
var grid = _owner._grid;
if (grid is null) return;
_owner.ComputeCellLayout(out float cellSize, out Vector2 origin);
if (cellSize < 14f) return;
var spec = grid.Spec;
int fontSize = cellSize >= 38f ? 10 : 9;
float alpha = 0.95f;
for (int i = 0; i < spec.Hardpoints.Length; i++)
{
var hp = spec.Hardpoints[i];
var mounted = grid.GetMountedOn(hp.Id);
var pos = origin + new Vector2(hp.X * cellSize, hp.Y * cellSize);
float maxW = MathF.Max(12f, hp.Width * cellSize - 6f);
string tag = mounted is not null
? $"{mounted.Spec.Kind.ToString()[..1]}:{mounted.CurrentTemp:F0}°"
: hp.Kind.ToString()[..3].ToUpperInvariant();
LastDrawnTags[hp.Id] = tag;
Color col = mounted is { Spec.IsImperial: true } ? ColGold : ColTextLight;
col.A = alpha;
// Dark shadow for crisp legibility over bright thermal glow
DrawString(
UiFonts.Regular,
pos + new Vector2(7f, fontSize + 6f),
tag,
HorizontalAlignment.Left,
maxW - 2f,
fontSize,
new Color(0.04f, 0.05f, 0.04f, alpha * 0.9f));
DrawString(
UiFonts.Regular,
pos + new Vector2(6f, fontSize + 5f),
tag,
HorizontalAlignment.Left,
maxW - 2f,
fontSize,
col);
}
}
}
}