From 72c4babeb552d05a351610a9170b6603f0b9527f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 4 Dec 2026 17:16:38 +0100 Subject: [PATCH] Wire InventoryGridControl and panel_chrome into Hud, replacing manual schematic and StyleBoxFlat --- client/Hud.cs | 363 +++++++++-------- client/InventoryGridControl.cs | 694 +++++++++++++++++++++++++++++++++ client/Main.cs | 3 + 3 files changed, 897 insertions(+), 163 deletions(-) create mode 100644 client/InventoryGridControl.cs diff --git a/client/Hud.cs b/client/Hud.cs index 35b00c9..a8df0f5 100644 --- a/client/Hud.cs +++ b/client/Hud.cs @@ -42,20 +42,22 @@ public partial class Hud : CanvasLayer private RadarWidget _radar = null!; private CrosshairOverlay _crosshair = null!; - private SchematicPanel _schematic = null!; + private InventoryGridControl _schematic = null!; + private Button _thermalButton = null!; + private Label _hoverLabel = null!; private VBoxContainer _cargoList = null!; private Label _cargoHeader = null!; private Label _garageDetails = null!; - private PanelContainer _topLeftPanel = null!; - private PanelContainer _topRightPanel = null!; - private PanelContainer _bottomLeftPanel = null!; - private PanelContainer _chyronPanel = null!; + private ChromePanel _topLeftPanel = null!; + private ChromePanel _topRightPanel = null!; + private ChromePanel _bottomLeftPanel = null!; + private ChromePanel _chyronPanel = null!; private VBoxContainer _chyronBox = null!; private readonly Label[] _chyronLabels = new Label[3]; private BroadcastFeed? _lastBroadcastFeed; private long _lastChyronVersion = -1; - private PanelContainer _outcomeBanner = null!; + private ChromePanel _outcomeBanner = null!; private Label _outcomeLabel = null!; private int _selectedCargoIndex = -1; @@ -71,15 +73,43 @@ public partial class Hud : CanvasLayer } public bool GarageExpanded => _garageExpanded; + public bool ThermalMode => _schematic.ThermalEnabled; + public InventoryGridControl Schematic => _schematic; + + public IEnumerable GetChromeMaterials() + { + yield return _topLeftPanel.ChromeMaterial; + yield return _topRightPanel.ChromeMaterial; + yield return _bottomLeftPanel.ChromeMaterial; + yield return _chyronPanel.ChromeMaterial; + yield return _outcomeBanner.ChromeMaterial; + } public void ToggleGarage() { _garageExpanded = !_garageExpanded; _garageDetails.Visible = _garageExpanded; - _schematic.CustomMinimumSize = _garageExpanded ? new Vector2(236f, 250f) : new Vector2(180f, 190f); + _schematic.CustomMinimumSize = _garageExpanded ? new Vector2(228f, 232f) : new Vector2(180f, 188f); _schematic.QueueRedraw(); } + public void ToggleThermal() => SetThermalMode(!_schematic.ThermalEnabled); + + public void SetThermalMode(bool enabled, bool instant = false) + { + if (instant) + { + _schematic.SetThermalInstant(enabled); + } + else + { + _schematic.ThermalEnabled = enabled; + } + _thermalButton.ButtonPressed = enabled; + _thermalButton.Modulate = enabled ? CyanCol : TextMuted; + _thermalButton.Text = enabled ? "[T] CONDUITS: ON" : "[T] CONDUITS"; + } + public override void _Ready() { BuildCrosshair(); @@ -100,6 +130,30 @@ public partial class Hud : CanvasLayer || (_outcomeBanner.Visible && _outcomeBanner.GetGlobalRect().HasPoint(screenPos)); } + public bool HasPanelOverlapOrClip(Vector2 viewportSize) + { + var panels = new[] { _topLeftPanel, _topRightPanel, _bottomLeftPanel, _chyronPanel }; + var bounds = new Rect2(Vector2.Zero, viewportSize + new Vector2(1f, 1f)); + for (int i = 0; i < panels.Length; i++) + { + if (!panels[i].Visible) continue; + var ri = panels[i].GetGlobalRect(); + if (!bounds.Encloses(ri)) + { + return true; + } + for (int j = i + 1; j < panels.Length; j++) + { + if (!panels[j].Visible) continue; + if (ri.Intersects(panels[j].GetGlobalRect())) + { + return true; + } + } + } + return false; + } + public void Sync(ArenaSession session) { var state = session.State; @@ -162,7 +216,6 @@ public partial class Hud : CanvasLayer // Schematic + Cargo _schematic.SetGrid(player.Grid, _selectedCargoIndex); - _schematic.QueueRedraw(); SyncCargoButtons(player.Grid); if (_garageExpanded) @@ -177,12 +230,14 @@ public partial class Hud : CanvasLayer if (state.Phase == MatchPhase.Victory) { _outcomeBanner.Visible = true; + _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", OliveCol); _outcomeLabel.Text = "VICTORY — LAST RIG STANDING\n[R] New Drop"; _outcomeLabel.Modulate = OliveCol; } else if (state.Phase == MatchPhase.Defeat) { _outcomeBanner.Visible = true; + _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", RedCol); _outcomeLabel.Text = "CHASSIS DESTROYED\n[R] Redeploy"; _outcomeLabel.Modulate = RedCol; } @@ -202,7 +257,7 @@ public partial class Hud : CanvasLayer private void BuildTopLeft() { - var panel = CreateStyledPanel(); + var panel = CreateStyledPanel(OliveCol); _topLeftPanel = panel; panel.AnchorLeft = 0f; panel.AnchorTop = 0f; @@ -268,7 +323,7 @@ public partial class Hud : CanvasLayer _promptLabel.AddThemeFontSizeOverride("font_size", 14); vbox.AddChild(_promptLabel); - _controlsHint = new Label { Text = "WASD Drive | Mouse Aim | LMB Fire | E Loot/Swap | Tab Garage | Wheel Zoom" }; + _controlsHint = new Label { Text = "WASD Drive | Mouse Aim | LMB Fire | E Loot/Swap | Tab Garage | T Conduits | Wheel Zoom" }; _controlsHint.AddThemeColorOverride("font_color", TextMuted); _controlsHint.AddThemeFontSizeOverride("font_size", 11); vbox.AddChild(_controlsHint); @@ -276,7 +331,7 @@ public partial class Hud : CanvasLayer private void BuildTopRightRadar() { - var panel = CreateStyledPanel(); + var panel = CreateStyledPanel(OrangeCol); _topRightPanel = panel; panel.AnchorLeft = 1f; panel.AnchorRight = 1f; @@ -304,7 +359,7 @@ public partial class Hud : CanvasLayer private void BuildBottomLeftSchematic() { - _bottomLeftPanel = CreateStyledPanel(); + _bottomLeftPanel = CreateStyledPanel(OrangeCol); _bottomLeftPanel.AnchorLeft = 0f; _bottomLeftPanel.AnchorTop = 1f; _bottomLeftPanel.AnchorBottom = 1f; @@ -322,18 +377,49 @@ public partial class Hud : CanvasLayer leftCol.AddThemeConstantOverride("separation", 4); hbox.AddChild(leftCol); - var title = new Label { Text = "AETHERIA HEAT & HARDPOINTS" }; + var headRow = new HBoxContainer(); + headRow.AddThemeConstantOverride("separation", 6); + leftCol.AddChild(headRow); + + var title = new Label + { + Text = "HARDPOINTS & HEAT", + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; title.AddThemeColorOverride("font_color", OrangeCol); title.AddThemeFontSizeOverride("font_size", 12); - leftCol.AddChild(title); + headRow.AddChild(title); - _schematic = new SchematicPanel(OnHardpointClicked) + _thermalButton = new Button { - CustomMinimumSize = new Vector2(180f, 190f) + Text = "[T] CONDUITS", + ToggleMode = true, + FocusMode = Control.FocusModeEnum.None, + Modulate = TextMuted }; + _thermalButton.AddThemeFontSizeOverride("font_size", 10); + _thermalButton.Pressed += () => SetThermalMode(_thermalButton.ButtonPressed); + headRow.AddChild(_thermalButton); + + _schematic = new InventoryGridControl + { + CustomMinimumSize = new Vector2(180f, 188f) + }; + _schematic.HardpointClicked += OnHardpointClicked; + _schematic.HoverChanged += OnSchematicHoverChanged; leftCol.AddChild(_schematic); - var rightCol = new VBoxContainer { CustomMinimumSize = new Vector2(178f, 0f) }; + _hoverLabel = new Label + { + Text = "HOVER CELL FOR TELEMETRY", + ClipText = true, + CustomMinimumSize = new Vector2(180f, 15f) + }; + _hoverLabel.AddThemeColorOverride("font_color", TextMuted); + _hoverLabel.AddThemeFontSizeOverride("font_size", 10); + leftCol.AddChild(_hoverLabel); + + var rightCol = new VBoxContainer { CustomMinimumSize = new Vector2(176f, 0f) }; rightCol.AddThemeConstantOverride("separation", 4); hbox.AddChild(rightCol); @@ -349,20 +435,22 @@ public partial class Hud : CanvasLayer _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); + _garageDetails.CustomMinimumSize = new Vector2(204f, 0f); hbox.AddChild(_garageDetails); } private void BuildBottomCenterChyron() { - _chyronPanel = CreateStyledPanel(); + _chyronPanel = CreateStyledPanel(GoldCol); var panel = _chyronPanel; - panel.AnchorLeft = 0.5f; - panel.AnchorRight = 0.5f; + panel.AnchorLeft = 1f; + panel.AnchorRight = 1f; panel.AnchorTop = 1f; panel.AnchorBottom = 1f; - panel.OffsetLeft = -150f; - panel.OffsetRight = 460f; + panel.GrowHorizontal = Control.GrowDirection.Begin; + panel.GrowVertical = Control.GrowDirection.Begin; + panel.OffsetLeft = -584f; + panel.OffsetRight = -14f; panel.OffsetTop = -104f; panel.OffsetBottom = -14f; AddChild(panel); @@ -396,7 +484,7 @@ public partial class Hud : CanvasLayer private void BuildOutcomeBanner() { - _outcomeBanner = CreateStyledPanel(); + _outcomeBanner = CreateStyledPanel(OliveCol, cornerLen: 16f, borderPx: 2f); _outcomeBanner.AnchorLeft = 0.5f; _outcomeBanner.AnchorRight = 0.5f; _outcomeBanner.AnchorTop = 0.28f; @@ -430,6 +518,37 @@ public partial class Hud : CanvasLayer } } + private void OnSchematicHoverChanged(Vector2I? cell, HardpointSpec? hp) + { + var grid = _schematic.Grid; + if (cell is null || grid is null) + { + _hoverLabel.Text = "HOVER CELL FOR TELEMETRY"; + _hoverLabel.AddThemeColorOverride("font_color", TextMuted); + return; + } + + var c = cell.Value; + float arm = grid.Armor[c.X, c.Y]; + float maxArm = grid.MaxArmor[c.X, c.Y]; + float temp = grid.Temperature[c.X, c.Y]; + if (hp is not null) + { + var mounted = grid.GetMountedOn(hp.Id); + _hoverLabel.Text = mounted is not null + ? $"{hp.Kind.ToString().ToUpperInvariant()}: {mounted.Spec.Name} {mounted.CurrentTemp:F0}°C ({mounted.CurrentPerformance * 100f:F0}%)" + : $"{hp.Kind.ToString().ToUpperInvariant()} SLOT [{hp.Width}x{hp.Height}] EMPTY"; + _hoverLabel.AddThemeColorOverride("font_color", arm <= 0.01f ? RedCol : TextLight); + } + else + { + _hoverLabel.Text = arm <= 0.01f + ? $"CELL ({c.X},{c.Y}) STRIPPED! {temp:F0}°C" + : $"HULL ({c.X},{c.Y}) ARM {arm:F0}/{maxArm:F0} {temp:F0}°C"; + _hoverLabel.AddThemeColorOverride("font_color", arm <= 0.01f ? RedCol : TextMuted); + } + } + private void SyncCargoButtons(ChassisGrid grid) { int hash = grid.Cargo.Count * 97 + (_selectedCargoIndex + 10); @@ -468,7 +587,8 @@ public partial class Hud : CanvasLayer { Text = $"{(mod.IsImperial ? "★ " : "")}{mod.Name}", SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, - Alignment = HorizontalAlignment.Left + Alignment = HorizontalAlignment.Left, + FocusMode = Control.FocusModeEnum.None }; selectBtn.AddThemeFontSizeOverride("font_size", 11); if (_selectedCargoIndex == idx) @@ -486,7 +606,7 @@ public partial class Hud : CanvasLayer }; row.AddChild(selectBtn); - var fitBtn = new Button { Text = "FIT" }; + var fitBtn = new Button { Text = "FIT", FocusMode = Control.FocusModeEnum.None }; fitBtn.AddThemeFontSizeOverride("font_size", 11); fitBtn.Pressed += () => AutoFitCargo(grid, idx); row.AddChild(fitBtn); @@ -591,22 +711,62 @@ public partial class Hud : CanvasLayer return string.Join("\n", lines); } - private static PanelContainer CreateStyledPanel() + private static ChromePanel CreateStyledPanel(Color accentColor, float cornerLen = 12f, float borderPx = 1.5f) { - var panel = new PanelContainer(); - var style = new StyleBoxFlat + return new ChromePanel(accentColor, cornerLen, borderPx); + } + + private sealed partial class ChromePanel : PanelContainer + { + private static Shader? _sharedChromeShader; + private static ImageTexture? _sharedWhiteTex; + private readonly ShaderMaterial _material; + + public ChromePanel(Color accentColor, float cornerLen, float borderPx) { - 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; + _sharedChromeShader ??= GD.Load("res://panel_chrome.gdshader"); + if (_sharedWhiteTex is null) + { + var img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + img.SetPixel(0, 0, Colors.White); + _sharedWhiteTex = ImageTexture.CreateFromImage(img); + } + + _material = new ShaderMaterial { Shader = _sharedChromeShader }; + _material.SetShaderParameter("bg_color", new Color(BgDark.R, BgDark.G, BgDark.B, 0.88f)); + _material.SetShaderParameter("border_color", BorderCol); + _material.SetShaderParameter("accent_color", accentColor); + _material.SetShaderParameter("corner_len", cornerLen); + _material.SetShaderParameter("border_px", borderPx); + Material = _material; + + var empty = new StyleBoxEmpty + { + ContentMarginLeft = 10, + ContentMarginRight = 10, + ContentMarginTop = 8, + ContentMarginBottom = 8 + }; + AddThemeStyleboxOverride("panel", empty); + } + + public ShaderMaterial ChromeMaterial => _material; + + public override void _Notification(int what) + { + if (what == NotificationResized) + { + _material.SetShaderParameter("rect_size", Size); + QueueRedraw(); + } + } + + public override void _Draw() + { + if (Size.X < 2f || Size.Y < 2f || _sharedWhiteTex is null) return; + _material.SetShaderParameter("rect_size", Size); + DrawTextureRect(_sharedWhiteTex, new Rect2(Vector2.Zero, Size), false, Colors.White); + } } private sealed partial class CrosshairOverlay : Control @@ -844,127 +1004,4 @@ public partial class Hud : CanvasLayer 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/InventoryGridControl.cs b/client/InventoryGridControl.cs new file mode 100644 index 0000000..863f42e --- /dev/null +++ b/client/InventoryGridControl.cs @@ -0,0 +1,694 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Godot Control owning inventory_grid.gdshader: +/// packs a 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. +/// +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 int _selectedCargoIndex = -1; + private int _lastHitSequence = -1; + + private HardpointSpec?[,] _hardpointLookup = new HardpointSpec?[0, 0]; + private float[,] _prevArmor = new float[0, 0]; + private float[,] _hitPulse = new float[0, 0]; + + private Vector2I? _hoveredCell; + private bool _thermalEnabled; + private float _thermalBlend; + private bool _dataDirty; + private bool _tempDirty; + + public InventoryGridControl() + { + MouseFilter = MouseFilterEnum.Stop; + + _sharedShader ??= GD.Load("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; + + public bool ThermalEnabled + { + get => _thermalEnabled; + set + { + if (_thermalEnabled == value) return; + _thermalEnabled = value; + } + } + + public float ThermalBlend => _thermalBlend; + + public void SetThermalInstant(bool enabled) + { + _thermalEnabled = enabled; + _thermalBlend = enabled ? 1f : 0f; + _material.SetShaderParameter("thermal_mode", _thermalBlend); + _labelsOverlay.QueueRedraw(); + } + + public event Action? CellClicked; + public event Action? HardpointClicked; + public event Action? HoverChanged; + + public override void _Notification(int what) + { + if (what == NotificationResized) + { + SyncRectUniform(); + _labelsOverlay.QueueRedraw(); + } + } + + public override void _Process(double delta) + { + float dt = (float)delta; + bool needUniform = false; + + float targetThermal = _thermalEnabled ? 1f : 0f; + if (MathF.Abs(_thermalBlend - targetThermal) > 0.001f) + { + float t = dt >= 0.25f ? 1f : 1f - MathF.Exp(-dt * 14f); + _thermalBlend = Mathf.Lerp(_thermalBlend, targetThermal, t); + if (MathF.Abs(_thermalBlend - targetThermal) < 0.005f) + { + _thermalBlend = targetThermal; + } + needUniform = true; + _labelsOverlay.QueueRedraw(); + } + + if (needUniform) + { + _material.SetShaderParameter("thermal_mode", _thermalBlend); + } + + 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) + || _gridWidth != grid.Spec.Width + || _gridHeight != grid.Spec.Height; + + _grid = grid; + _selectedCargoIndex = selectedCargoIndex; + + if (gridIdentityChanged) + { + EnsureBackingBuffers(grid); + } + else + { + DetectHits(grid); + } + + PackDataTexture(grid); + PackTempTexture(grid); + FlushTextures(); + SyncRectUniform(); + _labelsOverlay.QueueRedraw(); + } + + 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]; + _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]; + } + } + _lastHitSequence = grid.HitSequence; + _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)); + _material.SetShaderParameter("thermal_mode", _thermalBlend); + } + + private void DetectHits(ChassisGrid grid) + { + 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; + } + } + + 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; + } + } + } + + 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)) + { + _dataImage.SetPixel(x * 3 + 0, y, Colors.Transparent); + _dataImage.SetPixel(x * 3 + 1, y, Colors.Transparent); + _dataImage.SetPixel(x * 3 + 2, y, Colors.Transparent); + 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 + + // 3x+2.B: 4-bit N/E/S/W thermal conductivity pipe mask + byte cond = 0; + for (int i = 0; i < 4; i++) + { + int nx = x + Offsets8[i].Dx; + int ny = y + Offsets8[i].Dy; + if (spec.IsActive(nx, ny)) + { + cond |= (byte)(1 << i); + } + } + + float pulse = Math.Clamp(_hitPulse[x, y], 0f, 1f); + var meta = new Color(mask / 255f, flags / 255f, cond / 255f, 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 LabelsOverlay(InventoryGridControl owner) => _owner = owner; + + public override void _Draw() + { + 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 = Mathf.Lerp(0.95f, 0.55f, _owner._thermalBlend); + + 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(); + + Color col = mounted is { Spec.IsImperial: true } ? ColGold : ColTextLight; + col.A = alpha; + + // Dark shadow for crisp legibility over bright thermal glow + DrawString( + ThemeDB.FallbackFont, + pos + new Vector2(7f, fontSize + 6f), + tag, + HorizontalAlignment.Left, + maxW - 2f, + fontSize, + new Color(0.04f, 0.05f, 0.04f, alpha * 0.9f)); + + DrawString( + ThemeDB.FallbackFont, + pos + new Vector2(6f, fontSize + 5f), + tag, + HorizontalAlignment.Left, + maxW - 2f, + fontSize, + col); + } + } + } +} diff --git a/client/Main.cs b/client/Main.cs index 8c7f53a..f95f60a 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -129,6 +129,9 @@ public partial class Main : Node3D : Input.MouseModeEnum.Captured; } break; + case Key.T: + _hud.ToggleThermal(); + break; case Key.R: Reset(_seed + 1); break;