render: unified MultiMeshPartPool with MechPaint, PomDecalPool, and per-weapon VFX

This commit is contained in:
Meta Vens 2026-12-04 23:56:30 +01:00
commit 2529ba62d2
9 changed files with 2593 additions and 871 deletions

File diff suppressed because it is too large Load diff

View file

@ -7,7 +7,8 @@ namespace RustToDust.Client;
/// <summary>
/// Manages physically detached armor plates and sheared hardpoint gear as tumbling,
/// terrain-bouncing debris pieces that settle and fade out cleanly after 8 seconds.
/// terrain-bouncing debris pieces submitted directly into <see cref="MultiMeshPartPool"/>
/// (zero per-piece Node3D/MeshInstance3D/StandardMaterial3D allocations).
/// </summary>
public partial class DebrisSystem : Node3D
{
@ -18,11 +19,15 @@ public partial class DebrisSystem : Node3D
private sealed class DebrisPiece
{
public required Node3D Node;
public required Vector3 Velocity;
public required Vector3 AngularVelocity;
public required List<StandardMaterial3D> FadeMaterials;
public required float[] BaseAlphas;
public required ArrayMesh Mesh;
public Vector3 Position;
public Basis Rotation;
public Vector3 Scale;
public Vector3 Velocity;
public Vector3 AngularVelocity;
public float RoleIndex;
public float Scorch;
public float HeatGlow;
public float Age;
public float Lifetime;
public bool Settled;
@ -33,60 +38,51 @@ public partial class DebrisSystem : Node3D
public int ActiveCount => _pieces.Count;
public bool TryGetPiecePosition(int index, out Vector3 position)
{
if (index >= 0 && index < _pieces.Count)
{
position = _pieces[index].Position;
return true;
}
position = Vector3.Zero;
return false;
}
public void ClearAll()
{
for (int i = 0; i < _pieces.Count; i++)
{
if (GodotObject.IsInstanceValid(_pieces[i].Node))
{
_pieces[i].Node.QueueFree();
}
}
_pieces.Clear();
for (int i = GetChildCount() - 1; i >= 0; i--)
{
Node ch = GetChild(i);
RemoveChild(ch);
ch.QueueFree();
}
}
/// <summary>
/// Reparents <paramref name="part"/> from its vehicle hierarchy at its exact world transform
/// into <see cref="DebrisSystem"/> and launches it with an outward blast impulse and tumble.
/// Registers a detached rigid part or sheared gear mesh at its world transform
/// and launches it with an outward blast impulse and tumble.
/// </summary>
public void SpawnDetachedPart(
Node3D part,
ArrayMesh mesh,
Transform3D worldXform,
Vector3 blastOriginWorld,
Vector3 inheritedVelocity,
float roleIndex,
float impulseScale = 1.0f,
bool applyScorch = true)
{
if (!GodotObject.IsInstanceValid(part))
if (mesh is null || mesh.GetSurfaceCount() == 0)
{
return;
}
// Evict oldest settled or oldest piece if we hit the cap so debris never leaks indefinitely
while (_pieces.Count >= MaxActiveDebris)
{
RemoveAt(0);
_pieces.RemoveAt(0);
}
Transform3D worldXform = part.IsInsideTree() ? part.GlobalTransform : part.Transform;
Node? oldParent = part.GetParent();
oldParent?.RemoveChild(part);
AddChild(part);
if (part.IsInsideTree() && IsInsideTree())
Vector3 scale = worldXform.Basis.Scale;
if (!scale.IsFinite() || scale.LengthSquared() < 1e-6f)
{
part.GlobalTransform = worldXform;
}
else
{
part.Transform = worldXform;
scale = Vector3.One;
}
Basis rot = worldXform.Basis.Orthonormalized();
Vector3 outward = worldXform.Origin - blastOriginWorld;
outward.Y = 0f;
@ -109,21 +105,17 @@ public partial class DebrisSystem : Node3D
(NextFloat() * 2f - 1f) * 7.5f,
(NextFloat() * 2f - 1f) * 7.5f);
var fadeMats = new List<StandardMaterial3D>();
PrepareInstanceMaterials(part, fadeMats, applyScorch);
var baseAlphas = new float[fadeMats.Count];
for (int i = 0; i < fadeMats.Count; i++)
{
baseAlphas[i] = fadeMats[i].AlbedoColor.A;
}
_pieces.Add(new DebrisPiece
{
Node = part,
Mesh = mesh,
Position = worldXform.Origin,
Rotation = rot,
Scale = scale,
Velocity = vel,
AngularVelocity = angVel,
FadeMaterials = fadeMats,
BaseAlphas = baseAlphas,
RoleIndex = roleIndex,
Scorch = applyScorch ? 0.85f : 0.15f,
HeatGlow = applyScorch ? 0.45f : 0f,
Age = 0f,
Lifetime = DefaultLifetime,
Settled = false
@ -141,30 +133,28 @@ public partial class DebrisSystem : Node3D
for (int i = _pieces.Count - 1; i >= 0; i--)
{
DebrisPiece p = _pieces[i];
if (!GodotObject.IsInstanceValid(p.Node))
p.Age += stepDt;
if (p.Age >= p.Lifetime)
{
_pieces.RemoveAt(i);
continue;
}
p.Age += stepDt;
if (p.Age >= p.Lifetime)
if (p.HeatGlow > 0f)
{
RemoveAt(i);
continue;
p.HeatGlow = MathF.Max(0f, p.HeatGlow - stepDt * 0.22f);
}
if (!p.Settled)
{
p.Velocity += new Vector3(0f, Gravity * stepDt, 0f);
Vector3 pos = p.Node.Position + p.Velocity * stepDt;
Vector3 pos = p.Position + p.Velocity * stepDt;
Basis basis = p.Node.Basis;
Basis rot = p.Rotation;
float spinLen = p.AngularVelocity.Length();
if (spinLen > 1e-4f)
{
basis = new Basis(p.AngularVelocity / spinLen, spinLen * stepDt) * basis;
basis = basis.Orthonormalized();
rot = (new Basis(p.AngularVelocity / spinLen, spinLen * stepDt) * rot).Orthonormalized();
}
float floorY = terrain.SampleHeight(pos.X, pos.Z) + 0.10f;
@ -187,94 +177,29 @@ public partial class DebrisSystem : Node3D
}
}
p.Node.Position = pos;
p.Node.Basis = basis;
p.Position = pos;
p.Rotation = rot;
}
}
}
// Smooth alpha fade during final 2 seconds
public void SubmitToPool(MultiMeshPartPool pool)
{
for (int i = 0; i < _pieces.Count; i++)
{
DebrisPiece p = _pieces[i];
float remaining = p.Lifetime - p.Age;
if (remaining < FadeDuration)
{
float alphaFrac = Math.Clamp(remaining / FadeDuration, 0f, 1f);
for (int m = 0; m < p.FadeMaterials.Count; m++)
{
StandardMaterial3D sm = p.FadeMaterials[m];
if (sm.Transparency == BaseMaterial3D.TransparencyEnum.Disabled)
{
sm.Transparency = BaseMaterial3D.TransparencyEnum.Alpha;
}
Color col = sm.AlbedoColor;
col.A = p.BaseAlphas[m] * alphaFrac;
sm.AlbedoColor = col;
}
}
float alpha = remaining < FadeDuration
? Math.Clamp(remaining / FadeDuration, 0.02f, 1f)
: 1f;
float sinkY = remaining < FadeDuration ? (1f - alpha) * 0.65f : 0f;
Vector3 scale = p.Scale * (remaining < FadeDuration ? (0.35f + 0.65f * alpha) : 1f);
Transform3D xf = new(p.Rotation * Basis.FromScale(scale), p.Position - new Vector3(0f, sinkY, 0f));
Color custom = new(p.Scorch, p.HeatGlow, p.RoleIndex, alpha);
pool.Submit(p.Mesh, in xf, in custom, wantsShadow: false);
}
}
private void RemoveAt(int index)
{
DebrisPiece p = _pieces[index];
_pieces.RemoveAt(index);
if (GodotObject.IsInstanceValid(p.Node))
{
if (p.Node.GetParent() == this)
{
RemoveChild(p.Node);
}
p.Node.QueueFree();
}
}
private static void PrepareInstanceMaterials(Node cur, List<StandardMaterial3D> outMats, bool applyScorch)
{
if (cur is MeshInstance3D mi && mi.Mesh is not null)
{
if (mi.MaterialOverride is StandardMaterial3D ov)
{
var copy = (StandardMaterial3D)ov.Duplicate();
if (applyScorch)
{
ApplyScorchTint(copy);
}
mi.MaterialOverride = copy;
outMats.Add(copy);
}
else
{
int surfCount = mi.Mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
Material? src = mi.GetActiveMaterial(s);
StandardMaterial3D copy = src is StandardMaterial3D sm
? (StandardMaterial3D)sm.Duplicate()
: new StandardMaterial3D { AlbedoColor = new Color(0.28f, 0.25f, 0.23f), Roughness = 0.78f, Metallic = 0.45f };
if (applyScorch)
{
ApplyScorchTint(copy);
}
mi.SetSurfaceOverrideMaterial(s, copy);
outMats.Add(copy);
}
}
}
int count = cur.GetChildCount();
for (int i = 0; i < count; i++)
{
PrepareInstanceMaterials(cur.GetChild(i), outMats, applyScorch);
}
}
private static void ApplyScorchTint(StandardMaterial3D mat)
{
Color c = mat.AlbedoColor;
mat.AlbedoColor = new Color(c.R * 0.42f + 0.04f, c.G * 0.36f + 0.03f, c.B * 0.34f + 0.02f, c.A);
mat.Roughness = MathF.Max(mat.Roughness, 0.78f);
mat.EmissionEnabled = true;
mat.Emission = new Color(0.95f, 0.32f, 0.06f);
mat.EmissionEnergyMultiplier = 0.35f;
}
private float NextFloat()
{
uint x = _rngState;

247
client/MultiMeshPartPool.cs Normal file
View file

@ -0,0 +1,247 @@
using System;
using System.Collections.Generic;
using Godot;
namespace RustToDust.Client;
/// <summary>
/// Unified MultiMeshInstance3D part pool sharing <c>mech_paint.gdshader</c> in vertex-material mode.
/// Collapses all live vehicle limbs, armor chunks, mounted gear, salvage drops, and tumbling debris
/// sharing the same single-surface <see cref="ArrayMesh"/> into one <see cref="MultiMeshInstance3D"/>
/// draw call with per-instance <c>INSTANCE_CUSTOM = (scorch, heat_glow, role_tint_index, alpha)</c>.
/// </summary>
public partial class MultiMeshPartPool : Node3D
{
private readonly record struct PendingInstance(
Transform3D Xform,
Color Custom,
bool WantsShadow,
Vector3 WorldCenter,
float ScaledRadius);
private sealed class PoolBucket
{
public required ArrayMesh Mesh;
public required Vector3 LocalCenter;
public required float LocalRadius;
public required MultiMesh MultiMesh;
public required MultiMeshInstance3D Node;
public readonly List<PendingInstance> Pending = new(16);
}
private readonly Dictionary<ulong, PoolBucket> _buckets = new();
private readonly List<PoolBucket> _bucketList = new();
private readonly Plane[] _frustumPlanes = new Plane[6];
private ShaderMaterial _sharedMat = null!;
private bool _hasFrustum;
private Vector3 _camPos;
public int BucketCount => _bucketList.Count;
public int ActiveBucketCount { get; private set; }
public int TotalSubmittedInstances { get; private set; }
public override void _Ready()
{
Shader shader = GD.Load<Shader>("res://mech_paint.gdshader")
?? throw new InvalidOperationException("Failed to load res://mech_paint.gdshader for MultiMeshPartPool.");
_sharedMat = new ShaderMaterial { Shader = shader };
_sharedMat.SetShaderParameter("use_vertex_material", true);
_sharedMat.SetShaderParameter("heat_emission_energy", 2.6f);
}
public void EnsureInitialized()
{
if (_sharedMat is null)
{
_Ready();
}
}
public void BeginFrame(Camera3D? cam)
{
EnsureInitialized();
TotalSubmittedInstances = 0;
for (int i = 0; i < _bucketList.Count; i++)
{
_bucketList[i].Pending.Clear();
}
if (cam is not null && cam.IsInsideTree())
{
_camPos = cam.GlobalPosition;
var planes = cam.GetFrustum();
if (planes.Count >= 6)
{
for (int i = 0; i < 6; i++)
{
_frustumPlanes[i] = planes[i];
}
_hasFrustum = true;
return;
}
}
_hasFrustum = false;
}
public void Submit(
ArrayMesh mesh,
in Transform3D worldXform,
in Color customData,
bool wantsShadow)
{
if (mesh is null || mesh.GetSurfaceCount() == 0)
{
return;
}
PoolBucket bucket = GetOrCreateBucket(mesh);
Basis b = worldXform.Basis;
float maxScaleSq = MathF.Max(
b.Column0.LengthSquared(),
MathF.Max(b.Column1.LengthSquared(), b.Column2.LengthSquared()));
float scale = MathF.Sqrt(MathF.Max(0.0001f, maxScaleSq));
float scaledRadius = bucket.LocalRadius * scale;
Vector3 worldCenter = worldXform * bucket.LocalCenter;
if (_hasFrustum && !IsSphereInFrustum(worldCenter, scaledRadius))
{
return;
}
bool castShadow = wantsShadow && bucket.LocalRadius >= 0.55f;
if (castShadow && _hasFrustum)
{
float maxShadowDist = 85f + scaledRadius;
if (worldCenter.DistanceSquaredTo(_camPos) > maxShadowDist * maxShadowDist)
{
castShadow = false;
}
}
bucket.Pending.Add(new PendingInstance(worldXform, customData, castShadow, worldCenter, scaledRadius));
TotalSubmittedInstances++;
}
public void EndFrame()
{
int active = 0;
for (int i = 0; i < _bucketList.Count; i++)
{
PoolBucket bucket = _bucketList[i];
int count = bucket.Pending.Count;
if (count == 0)
{
bucket.MultiMesh.VisibleInstanceCount = 0;
bucket.Node.Visible = false;
continue;
}
active++;
if (bucket.MultiMesh.InstanceCount < count)
{
bucket.MultiMesh.InstanceCount = Math.Max(16, count * 2);
}
Vector3 aabbMin = new(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
Vector3 aabbMax = new(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
bool anyShadow = false;
for (int k = 0; k < count; k++)
{
PendingInstance inst = bucket.Pending[k];
bucket.MultiMesh.SetInstanceTransform(k, inst.Xform);
bucket.MultiMesh.SetInstanceCustomData(k, inst.Custom);
if (inst.WantsShadow)
{
anyShadow = true;
}
Vector3 r = new(inst.ScaledRadius, inst.ScaledRadius, inst.ScaledRadius);
Vector3 lo = inst.WorldCenter - r;
Vector3 hi = inst.WorldCenter + r;
aabbMin = new Vector3(MathF.Min(aabbMin.X, lo.X), MathF.Min(aabbMin.Y, lo.Y), MathF.Min(aabbMin.Z, lo.Z));
aabbMax = new Vector3(MathF.Max(aabbMax.X, hi.X), MathF.Max(aabbMax.Y, hi.Y), MathF.Max(aabbMax.Z, hi.Z));
}
bucket.MultiMesh.VisibleInstanceCount = count;
bucket.Node.CustomAabb = new Aabb(aabbMin, aabbMax - aabbMin);
bucket.Node.CastShadow = anyShadow
? GeometryInstance3D.ShadowCastingSetting.On
: GeometryInstance3D.ShadowCastingSetting.Off;
bucket.Node.Visible = true;
}
ActiveBucketCount = active;
}
public void ClearAll()
{
for (int i = 0; i < _bucketList.Count; i++)
{
PoolBucket bucket = _bucketList[i];
bucket.Pending.Clear();
bucket.MultiMesh.VisibleInstanceCount = 0;
bucket.Node.Visible = false;
}
ActiveBucketCount = 0;
TotalSubmittedInstances = 0;
}
private PoolBucket GetOrCreateBucket(ArrayMesh mesh)
{
ulong id = mesh.GetInstanceId();
if (_buckets.TryGetValue(id, out PoolBucket? existing))
{
return existing;
}
Aabb aabb = mesh.GetAabb();
Vector3 localCenter = aabb.GetCenter();
float localRadius = MathF.Max(0.2f, aabb.Size.Length() * 0.5f);
var mm = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform3D,
UseCustomData = true,
Mesh = mesh,
InstanceCount = 16,
VisibleInstanceCount = 0
};
var mmi = new MultiMeshInstance3D
{
Name = $"MMPool_{_bucketList.Count}",
Multimesh = mm,
MaterialOverride = _sharedMat,
Visible = false,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off
};
AddChild(mmi);
var created = new PoolBucket
{
Mesh = mesh,
LocalCenter = localCenter,
LocalRadius = localRadius,
MultiMesh = mm,
Node = mmi
};
_buckets[id] = created;
_bucketList.Add(created);
return created;
}
private bool IsSphereInFrustum(Vector3 center, float radius)
{
float margin = radius + 1.5f;
for (int i = 0; i < 6; i++)
{
if (_frustumPlanes[i].DistanceTo(center) > margin)
{
return false;
}
}
return true;
}
}

440
client/PomDecalPool.cs Normal file
View file

@ -0,0 +1,440 @@
using System;
using System.IO;
using Godot;
using RustToDust.Core;
using RustToDust.Ymir;
namespace RustToDust.Client;
/// <summary>
/// Live 4x4 Parallax Occlusion Mapping (POM) combat decal pool rendered in 1 draw call
/// using <c>decal_pom.gdshader</c> and <c>assets/decals/decal_atlas_*.png</c>.
/// Supports terrain impacts, static cover impacts, and vehicle-cell-attached scars
/// that cool smoothly over 3.5s, ride with moving limbs/turrets, and fade when armor detaches.
/// </summary>
public partial class PomDecalPool : Node3D
{
public const int MaxDecals = 512;
private const float HeatCoolDuration = 3.5f;
private const float DetachFadeDuration = 0.35f;
private const float EndFadeDuration = 2.0f;
private struct DecalSlot
{
public bool Active;
public float Age;
public float Lifetime;
public float TileIndex;
public float InitialHeat;
public float BaseOpacity;
public float DepthScale;
public Transform3D WorldXform;
public bool IsAttached;
public VehicleVisualInstance? Visual;
public Node3D? Pivot;
public Transform3D LocalToPivot;
public ChassisGrid? Grid;
public int CellX;
public int CellY;
public float DetachedFadeRemaining;
}
private readonly DecalSlot[] _slots = new DecalSlot[MaxDecals];
private int _writeCursor;
private long _lastProcessedHitId;
private MatchState? _boundState;
private MultiMesh _multiMesh = null!;
private MultiMeshInstance3D _instanceNode = null!;
private ShaderMaterial _material = null!;
private ImageTexture _albedoTex = null!;
private ImageTexture _normalTex = null!;
private ImageTexture _ormhTex = null!;
public int ActiveCount { get; private set; }
public override void _Ready()
{
Shader shader = GD.Load<Shader>("res://decal_pom.gdshader")
?? throw new InvalidOperationException("Failed to load res://decal_pom.gdshader");
string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory();
string assetsDir = Directory.GetParent(vehiclesDir)?.FullName
?? throw new DirectoryNotFoundException("Could not locate assets directory.");
string decalsDir = Path.Combine(assetsDir, "decals");
_albedoTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_albedo.png"));
_normalTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_normal.png"));
_ormhTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_ormh.png"));
_material = new ShaderMaterial { Shader = shader };
_material.SetShaderParameter("albedo_tex", _albedoTex);
_material.SetShaderParameter("normal_tex", _normalTex);
_material.SetShaderParameter("ormh_tex", _ormhTex);
_material.SetShaderParameter("use_instance_custom", true);
_material.SetShaderParameter("default_depth_scale", 0.06f);
_material.SetShaderParameter("normal_offset", 0.012f);
_material.SetShaderParameter("heat_emission_energy", 2.8f);
_multiMesh = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform3D,
UseCustomData = true,
Mesh = new QuadMesh { Size = Vector2.One },
InstanceCount = MaxDecals,
VisibleInstanceCount = 0
};
_instanceNode = new MultiMeshInstance3D
{
Name = "PomDecalsBatch",
Multimesh = _multiMesh,
MaterialOverride = _material,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 180f, 1800f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
AddChild(_instanceNode);
}
public void EnsureInitialized()
{
if (_multiMesh is null)
{
_Ready();
}
}
public void ClearAll()
{
Array.Clear(_slots, 0, _slots.Length);
_writeCursor = 0;
_lastProcessedHitId = 0;
ActiveCount = 0;
if (_multiMesh is not null)
{
_multiMesh.VisibleInstanceCount = 0;
_instanceNode.Visible = false;
}
}
public void Sync(
ArenaSession session,
float dt,
Func<bool, int, VehicleVisualInstance?> getVisual)
{
EnsureInitialized();
var state = session.State;
if (!ReferenceEquals(_boundState, state))
{
_boundState = state;
ClearAll();
}
var hits = state.HitEvents;
for (int i = 0; i < hits.Count; i++)
{
var ev = hits[i];
if (ev.EventId <= _lastProcessedHitId)
{
continue;
}
_lastProcessedHitId = ev.EventId;
StampHit(ev, state, getVisual);
}
UpdateAndCommit(dt);
}
public void StampTestDecal(
Vector3 worldPos,
Vector3 worldNormal,
float size,
int tileIndex,
float heat = 0.95f,
float depth = 0.085f)
{
EnsureInitialized();
Transform3D xf = BuildSurfaceTransform(worldPos, worldNormal, size, (float)_writeCursor * 1.17f);
AllocateSlot(new DecalSlot
{
Active = true,
Age = 0f,
Lifetime = 26f,
TileIndex = tileIndex,
InitialHeat = heat,
BaseOpacity = 1f,
DepthScale = depth,
WorldXform = xf,
DetachedFadeRemaining = -1f
});
}
private void StampHit(
in HitFeedbackEvent ev,
MatchState state,
Func<bool, int, VehicleVisualInstance?> getVisual)
{
if (ev.IsAirburst && ev.TargetKind == HitTargetKind.StaticCover && ev.TargetId < 0)
{
return;
}
bool isVehicle = ev.TargetKind == HitTargetKind.Contender || ev.TargetKind == HitTargetKind.Spectator;
int tile;
float size;
float heat;
float depth;
float lifetime;
switch (ev.WeaponClass)
{
case WeaponVisualClass.ThermalBeam:
tile = string.Equals(ev.WeaponId, "gilded_lance", StringComparison.Ordinal) || !isVehicle
? 14 // molten plasma crater
: 14;
size = isVehicle
? (string.Equals(ev.WeaponId, "gilded_lance", StringComparison.Ordinal) ? 0.78f : 0.56f)
: (string.Equals(ev.WeaponId, "gilded_lance", StringComparison.Ordinal) ? 2.10f : 1.35f);
heat = 1.0f;
depth = 0.095f;
lifetime = 26f;
break;
case WeaponVisualClass.Explosive:
bool isRecoilless = string.Equals(ev.WeaponId, "recoilless", StringComparison.Ordinal);
tile = isVehicle ? 13 : 15; // shrapnel gouge on armor, blast scorch on ground
size = isVehicle ? (isRecoilless ? 0.88f : 0.66f) : (isRecoilless ? 3.20f : 1.75f);
heat = isRecoilless ? 0.98f : 0.82f;
depth = isRecoilless ? 0.095f : 0.075f;
lifetime = 28f;
break;
case WeaponVisualClass.Autocannon:
tile = (ev.EventId % 3 == 0) ? 13 : 12; // AP hole or shrapnel gouge
size = isVehicle ? 0.54f : 0.92f;
heat = 0.90f;
depth = 0.088f;
lifetime = 24f;
break;
default: // KineticLight (mg_762, pd_flak)
tile = string.Equals(ev.WeaponId, "pd_flak", StringComparison.Ordinal) ? 13 : 12;
size = isVehicle ? 0.36f : 0.58f;
heat = 0.78f;
depth = 0.078f;
lifetime = 20f;
break;
}
Vector3 hitPos = new(ev.HitX, ev.HitY, ev.HitZ);
Vector3 normal = new(ev.NormalX, ev.NormalY, ev.NormalZ);
if (normal.LengthSquared() < 1e-4f) normal = Vector3.Up;
normal = normal.Normalized();
if (isVehicle)
{
bool isContender = ev.TargetKind == HitTargetKind.Contender;
VehicleVisualInstance? vis = getVisual(isContender, ev.TargetId);
if (vis is null || !vis.Root.IsInsideTree() || !vis.Root.Visible)
{
return;
}
ChassisGrid? grid = null;
if (isContender)
{
if (ev.TargetId >= 0 && ev.TargetId < state.Contenders.Count)
grid = state.Contenders[ev.TargetId].Grid;
}
else
{
var specs = state.Spectators.Spectators;
for (int si = 0; si < specs.Count; si++)
{
if (specs[si].Id == ev.TargetId)
{
grid = specs[si].Grid;
break;
}
}
}
if (grid is null || grid.IsDestroyed)
{
return;
}
Vector3 rayDir = (vis.Root.GlobalPosition - hitPos);
if (rayDir.LengthSquared() < 1e-4f) rayDir = -normal;
rayDir = rayDir.Normalized();
Vector3 rayOrigin = hitPos - rayDir * 0.75f;
if (vis.TryRayHitAttachedPart(rayOrigin, rayDir, out Node3D? hitPivot, out Transform3D localToPivot, size) &&
hitPivot is not null)
{
AllocateSlot(new DecalSlot
{
Active = true,
Age = 0f,
Lifetime = lifetime,
TileIndex = tile,
InitialHeat = heat,
BaseOpacity = 1f,
DepthScale = depth,
IsAttached = true,
Visual = vis,
Pivot = hitPivot,
LocalToPivot = localToPivot,
Grid = grid,
CellX = ev.CellX,
CellY = ev.CellY,
DetachedFadeRemaining = -1f
});
return;
}
// Fallback: attach to Root if sculpted geometry ray glanced past edge
Transform3D worldXf = BuildSurfaceTransform(hitPos, normal, size, ev.EventId * 0.73f);
AllocateSlot(new DecalSlot
{
Active = true,
Age = 0f,
Lifetime = lifetime,
TileIndex = tile,
InitialHeat = heat,
BaseOpacity = 1f,
DepthScale = depth,
IsAttached = true,
Visual = vis,
Pivot = vis.Root,
LocalToPivot = vis.Root.GlobalTransform.AffineInverse() * worldXf,
Grid = grid,
CellX = ev.CellX,
CellY = ev.CellY,
DetachedFadeRemaining = -1f
});
return;
}
// Terrain or StaticCover decal
Transform3D groundXf = BuildSurfaceTransform(hitPos + normal * 0.045f, normal, size, ev.EventId * 1.13f);
AllocateSlot(new DecalSlot
{
Active = true,
Age = 0f,
Lifetime = lifetime,
TileIndex = tile,
InitialHeat = heat,
BaseOpacity = 0.96f,
DepthScale = depth,
WorldXform = groundXf,
DetachedFadeRemaining = -1f
});
}
private void UpdateAndCommit(float dt)
{
float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f;
int visibleIdx = 0;
for (int i = 0; i < MaxDecals; i++)
{
ref DecalSlot s = ref _slots[i];
if (!s.Active)
{
continue;
}
s.Age += stepDt;
if (s.Age >= s.Lifetime)
{
s.Active = false;
continue;
}
Transform3D xf = s.WorldXform;
float opacity = s.BaseOpacity;
if (s.IsAttached)
{
if (s.Visual is null || s.Pivot is null || !GodotObject.IsInstanceValid(s.Pivot) ||
!s.Pivot.IsInsideTree() || !s.Visual.Root.Visible)
{
s.Active = false;
continue;
}
if (s.DetachedFadeRemaining < 0f && s.Grid is not null)
{
bool cellStripped = s.Grid.IsDestroyed ||
(s.CellX >= 0 && s.CellX < s.Grid.Spec.Width &&
s.CellY >= 0 && s.CellY < s.Grid.Spec.Height &&
s.Grid.Armor[s.CellX, s.CellY] <= 0.01f);
if (cellStripped)
{
s.DetachedFadeRemaining = DetachFadeDuration;
}
}
if (s.DetachedFadeRemaining >= 0f)
{
s.DetachedFadeRemaining -= stepDt;
if (s.DetachedFadeRemaining <= 0f)
{
s.Active = false;
continue;
}
opacity *= Math.Clamp(s.DetachedFadeRemaining / DetachFadeDuration, 0f, 1f);
}
xf = s.Pivot.GlobalTransform * s.LocalToPivot;
}
float remaining = s.Lifetime - s.Age;
if (remaining < EndFadeDuration)
{
opacity *= Math.Clamp(remaining / EndFadeDuration, 0f, 1f);
}
float heatGlow = s.InitialHeat * MathF.Max(0f, 1f - s.Age / HeatCoolDuration);
_multiMesh.SetInstanceTransform(visibleIdx, xf);
_multiMesh.SetInstanceCustomData(visibleIdx, new Color(s.TileIndex, heatGlow, opacity, s.DepthScale));
visibleIdx++;
}
ActiveCount = visibleIdx;
_multiMesh.VisibleInstanceCount = visibleIdx;
_instanceNode.Visible = visibleIdx > 0;
}
private void AllocateSlot(in DecalSlot slot)
{
_slots[_writeCursor] = slot;
_writeCursor = (_writeCursor + 1) % MaxDecals;
}
private static Transform3D BuildSurfaceTransform(Vector3 worldPos, Vector3 worldNormal, float size, float spinRad)
{
Vector3 n = worldNormal.LengthSquared() > 1e-6f ? worldNormal.Normalized() : Vector3.Up;
Vector3 upRef = MathF.Abs(n.Y) > 0.92f ? Vector3.Forward : Vector3.Up;
Vector3 right = upRef.Cross(n).Normalized();
Vector3 up = n.Cross(right).Normalized();
Basis spin = new(n, spinRad);
right = spin * right;
up = spin * up;
return new Transform3D(new Basis(right * size, up * size, n), worldPos);
}
private static ImageTexture LoadTextureWithMips(string path)
{
var img = Image.LoadFromFile(path);
if (img is null)
{
throw new FileNotFoundException($"Could not load POM decal texture '{path}'.", path);
}
img.GenerateMipmaps();
return ImageTexture.CreateFromImage(img);
}
}

View file

@ -41,6 +41,13 @@ public sealed class VehicleAssetCache : IDisposable
NodePath RelativePath,
bool HasProtectedDescendant);
public sealed record RigidPartTemplate(
NodePath PivotPath,
ArrayMesh Mesh,
int CellX,
int CellY,
string Kind);
public sealed class VehicleTemplate
{
public required VehiclePackage Package { get; init; }
@ -48,12 +55,18 @@ public sealed class VehicleAssetCache : IDisposable
public required Node3D SceneTemplate { get; init; }
public required ArrayMesh BakedStaticMesh { get; init; }
public required ArrayMesh BakedLodFarMesh { get; init; }
public required ArrayMesh SingleSurfaceStaticMesh { get; init; }
public required ArrayMesh SingleSurfaceLodFarMesh { get; init; }
public required Vector3[] FarRayTris { get; init; }
public required Aabb FarRayAabb { get; init; }
public required float MinY { get; init; }
public required float MaxY { get; init; }
public required IReadOnlyDictionary<string, GlbAnchorInfo> Anchors { get; init; }
public required IReadOnlyDictionary<string, GlbJointInfo> Joints { get; init; }
public required IReadOnlyDictionary<string, NodePath> NodesByOriginalName { get; init; }
public required IReadOnlyList<GlbPartNodeInfo> DetachableParts { get; init; }
public required IReadOnlyList<RigidPartTemplate> StaticRigidParts { get; init; }
public required IReadOnlyList<RigidPartTemplate> DetachableRigidParts { get; init; }
public required IReadOnlyList<NodePath> MobilityNodePaths { get; init; }
}
@ -63,9 +76,11 @@ public sealed class VehicleAssetCache : IDisposable
public required string GlbPath { get; init; }
public required Node3D SceneTemplate { get; init; }
public required ArrayMesh BakedDropMesh { get; init; }
public required ArrayMesh SingleSurfaceMesh { get; init; }
public required Vector3 Size { get; init; }
public required float MinY { get; init; }
public required Vector3 LocalModelForward { get; init; }
public required IReadOnlyDictionary<string, Vector3> PartCentroidsLocal { get; init; }
}
public static readonly string[] ExpectedGearIds =
@ -75,6 +90,7 @@ public sealed class VehicleAssetCache : IDisposable
private readonly Dictionary<string, VehicleTemplate> _vehicles = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, GearTemplate> _gear = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, ArrayMesh> _gearVariantMeshes = new(StringComparer.OrdinalIgnoreCase);
private readonly string _vehiclesDir;
private readonly string _gearDir;
private bool _disposed;
@ -153,6 +169,26 @@ public sealed class VehicleAssetCache : IDisposable
return template;
}
public ArrayMesh GetOrBuildGearVariantMesh(
string moduleId,
string gearGlbId,
Color? paintTint,
Color? accentTint)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_gearVariantMeshes.TryGetValue(moduleId, out ArrayMesh? cached))
{
return cached;
}
GearTemplate tpl = GetOrLoadGear(gearGlbId);
ArrayMesh mesh = !paintTint.HasValue && !accentTint.HasValue
? tpl.SingleSurfaceMesh
: CollapseToSingleSurfaceMechPaintMesh(tpl.BakedDropMesh, paintTint, accentTint);
_gearVariantMeshes[moduleId] = mesh;
return mesh;
}
private static VehicleTemplate LoadVehicleTemplate(VehiclePackage pkg, string glbPath)
{
byte[] jsonBytes = ReadGlbJsonChunk(glbPath);
@ -443,10 +479,24 @@ public sealed class VehicleAssetCache : IDisposable
}
// C: Build single-node BakedStaticMesh + decimated BakedLodFarMesh (>130m) per template
ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false);
ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true);
ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false, bakeVertexColor: false);
ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true, bakeVertexColor: false);
ArrayMesh bakedLodFarMesh = DecimateMeshGrid(bakedCoarseStatic, cellSize: 0.45f, targetMinY: minY);
ArrayMesh singleSurfaceStatic = CollapseToSingleSurfaceMechPaintMesh(bakedStaticMesh);
ArrayMesh singleSurfaceLodFar = CollapseToSingleSurfaceMechPaintMesh(bakedLodFarMesh);
Vector3[] farRayTris = ExtractFlatTriangles(singleSurfaceLodFar);
Aabb farRayAabb = singleSurfaceLodFar.GetAabb().Grow(0.20f);
// D: Extract single-surface MechPaint rigid parts (static limbs + detachable armor chunks)
// and strip all MeshInstance3D nodes from SceneTemplate so live rigs have zero MeshInstance3D children!
ExtractRigidPartsAndStripMeshes(
sceneRoot,
protectedNodes,
mergedDetachableInfos,
out var staticRigidParts,
out var detachableRigidParts);
return new VehicleTemplate
{
Package = pkg,
@ -454,12 +504,18 @@ public sealed class VehicleAssetCache : IDisposable
SceneTemplate = sceneRoot,
BakedStaticMesh = bakedStaticMesh,
BakedLodFarMesh = bakedLodFarMesh,
SingleSurfaceStaticMesh = singleSurfaceStatic,
SingleSurfaceLodFarMesh = singleSurfaceLodFar,
FarRayTris = farRayTris,
FarRayAabb = farRayAabb,
MinY = minY,
MaxY = maxY,
Anchors = anchors,
Joints = joints,
NodesByOriginalName = survivingNames,
DetachableParts = mergedDetachableInfos,
StaticRigidParts = staticRigidParts,
DetachableRigidParts = detachableRigidParts,
MobilityNodePaths = mobilityPaths
};
}
@ -489,8 +545,10 @@ public sealed class VehicleAssetCache : IDisposable
ClearOwnerRecursive(sceneRoot);
ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax);
var partCentroids = CollectGearPartCentroids(sceneRoot);
MergeGearSubMeshes(sceneRoot, gearId);
ArrayMesh bakedDropMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false, bakeVertexColor: false);
ArrayMesh singleSurfaceMesh = CollapseToSingleSurfaceMechPaintMesh(bakedDropMesh);
Vector3 localFwd = new Vector3(0f, 0f, 1f);
return new GearTemplate
@ -499,9 +557,11 @@ public sealed class VehicleAssetCache : IDisposable
GlbPath = glbPath,
SceneTemplate = sceneRoot,
BakedDropMesh = bakedDropMesh,
SingleSurfaceMesh = singleSurfaceMesh,
Size = bMax - bMin,
MinY = bMin.Y,
LocalModelForward = localFwd
LocalModelForward = localFwd,
PartCentroidsLocal = partCentroids
};
}
@ -887,6 +947,453 @@ public sealed class VehicleAssetCache : IDisposable
return BuildMergedArrayMesh(items, coarseMaterials, bakeVertexColor) ?? new ArrayMesh();
}
private static Dictionary<string, Vector3> CollectGearPartCentroids(Node3D sceneRoot)
{
var result = new Dictionary<string, Vector3>(StringComparer.OrdinalIgnoreCase);
var allMeshes = new List<MeshInstance3D>();
CollectAllMeshInstances(sceneRoot, allMeshes);
for (int i = 0; i < allMeshes.Count; i++)
{
MeshInstance3D mi = allMeshes[i];
if (!PreservedGearPartNames.Contains(mi.Name) || mi.Mesh is null)
{
continue;
}
Transform3D toRoot = ComputeRelativeTransform(sceneRoot, mi);
Vector3 sum = Vector3.Zero;
int count = 0;
int surfCount = mi.Mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
var arr = mi.Mesh.SurfaceGetArrays(s);
if (arr.Count > (int)Mesh.ArrayType.Vertex &&
arr[(int)Mesh.ArrayType.Vertex].VariantType == Variant.Type.PackedVector3Array)
{
Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
for (int v = 0; v < verts.Length; v++)
{
sum += toRoot * verts[v];
count++;
}
}
}
if (count > 0)
{
result[mi.Name] = sum / count;
}
}
return result;
}
private static void ExtractRigidPartsAndStripMeshes(
Node3D sceneRoot,
HashSet<Node> protectedNodes,
List<GlbPartNodeInfo> detachableInfos,
out List<RigidPartTemplate> staticPartsOut,
out List<RigidPartTemplate> detachablePartsOut)
{
staticPartsOut = new List<RigidPartTemplate>();
detachablePartsOut = new List<RigidPartTemplate>();
var detachableSet = new Dictionary<MeshInstance3D, GlbPartNodeInfo>();
for (int i = 0; i < detachableInfos.Count; i++)
{
var dp = detachableInfos[i];
if (sceneRoot.GetNodeOrNull(dp.RelativePath) is MeshInstance3D dmi)
{
detachableSet[dmi] = dp;
}
}
// 1. Extract detachable per-cell armor chunks in their rigidParent's local space
foreach (var (mi, dp) in detachableSet)
{
if (!CanMergeMeshInstance(mi) || mi.Mesh is null)
{
continue;
}
Node3D rigidParent = protectedNodes.Contains(mi)
? mi
: FindNearestProtectedParent(mi, sceneRoot, protectedNodes);
Transform3D relXf = ReferenceEquals(mi, rigidParent)
? Transform3D.Identity
: ComputeRelativeTransform(rigidParent, mi);
var single = new List<(Mesh Mesh, Transform3D RelXf)>(1) { (mi.Mesh, relXf) };
ArrayMesh? collapsed = CollapseToSingleSurfaceMechPaintMesh(single);
if (collapsed is not null)
{
detachablePartsOut.Add(new RigidPartTemplate(
BuildRelativeNodePath(sceneRoot, rigidParent),
collapsed,
dp.CellX,
dp.CellY,
dp.Kind));
}
}
// 2. Group remaining non-detachable rigid meshes by rigidParent and collapse each to 1 surface
var allMeshes = new List<MeshInstance3D>();
CollectAllMeshInstances(sceneRoot, allMeshes);
var staticByPivot = new Dictionary<Node3D, List<(Mesh Mesh, Transform3D RelXf)>>();
for (int i = 0; i < allMeshes.Count; i++)
{
MeshInstance3D mi = allMeshes[i];
if (detachableSet.ContainsKey(mi) || !CanMergeMeshInstance(mi) || mi.Mesh is null)
{
continue;
}
Node3D rigidParent = protectedNodes.Contains(mi)
? mi
: FindNearestProtectedParent(mi, sceneRoot, protectedNodes);
Transform3D relXf = ReferenceEquals(mi, rigidParent)
? Transform3D.Identity
: ComputeRelativeTransform(rigidParent, mi);
if (!staticByPivot.TryGetValue(rigidParent, out var list))
{
list = new List<(Mesh, Transform3D)>();
staticByPivot[rigidParent] = list;
}
list.Add((mi.Mesh, relXf));
}
foreach (var (rigidParent, items) in staticByPivot)
{
ArrayMesh? collapsed = CollapseToSingleSurfaceMechPaintMesh(items);
if (collapsed is not null)
{
staticPartsOut.Add(new RigidPartTemplate(
BuildRelativeNodePath(sceneRoot, rigidParent),
collapsed,
-1,
-1,
"static"));
}
}
// 3. Strip all MeshInstance3D nodes from sceneRoot:
// - Protected MeshInstance3Ds become plain Node3D pivots preserving Name, Transform, and children.
// - Non-protected MeshInstance3Ds are removed cleanly.
for (int i = 0; i < allMeshes.Count; i++)
{
MeshInstance3D mi = allMeshes[i];
if (!GodotObject.IsInstanceValid(mi) || ReferenceEquals(mi, sceneRoot))
{
continue;
}
if (protectedNodes.Contains(mi))
{
ReplaceMeshInstanceWithPivot(mi);
}
else
{
ReparentChildrenAndRemove(mi);
}
}
}
private static void ReplaceMeshInstanceWithPivot(MeshInstance3D mi)
{
Node? parent = mi.GetParent();
if (parent is null)
{
return;
}
int idx = mi.GetIndex();
var pivot = new Node3D
{
Name = mi.Name,
Transform = mi.Transform
};
parent.RemoveChild(mi);
parent.AddChild(pivot);
parent.MoveChild(pivot, idx);
while (mi.GetChildCount() > 0)
{
Node ch = mi.GetChild(0);
mi.RemoveChild(ch);
pivot.AddChild(ch);
}
mi.QueueFree();
}
private static Vector3[] ExtractFlatTriangles(ArrayMesh mesh)
{
var tris = new List<Vector3>();
int surfCount = mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
var arr = mesh.SurfaceGetArrays(s);
if (arr.Count <= (int)Mesh.ArrayType.Vertex ||
arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
{
continue;
}
Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
int[]? indices = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array
? arr[(int)Mesh.ArrayType.Index].AsInt32Array()
: null;
int triCount = (indices is not null ? indices.Length : verts.Length) / 3;
for (int t = 0; t < triCount; t++)
{
int i0 = indices is not null ? indices[t * 3] : t * 3;
int i1 = indices is not null ? indices[t * 3 + 1] : t * 3 + 1;
int i2 = indices is not null ? indices[t * 3 + 2] : t * 3 + 2;
tris.Add(verts[i0]);
tris.Add(verts[i1]);
tris.Add(verts[i2]);
}
}
return tris.ToArray();
}
public static ArrayMesh CollapseToSingleSurfaceMechPaintMesh(
ArrayMesh src,
Color? gearPaintTint = null,
Color? gearAccentTint = null)
{
var list = new List<(Mesh Mesh, Transform3D RelXf)>(1) { (src, Transform3D.Identity) };
return CollapseToSingleSurfaceMechPaintMesh(list, gearPaintTint, gearAccentTint) ?? new ArrayMesh();
}
private static ArrayMesh? CollapseToSingleSurfaceMechPaintMesh(
List<(Mesh Mesh, Transform3D RelXf)> sources,
Color? gearPaintTint = null,
Color? gearAccentTint = null)
{
int totalVerts = 0;
int totalIndices = 0;
var chunks = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, Vector3 LinearCol, int Band, float Rough, int VertCount, int IdxCount)>();
for (int i = 0; i < sources.Count; i++)
{
var (mesh, relXf) = sources[i];
int surfCount = mesh.GetSurfaceCount();
var am = mesh as ArrayMesh;
for (int s = 0; s < surfCount; s++)
{
if (am is not null && am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles)
{
continue;
}
var arr = mesh.SurfaceGetArrays(s);
if (arr.Count <= (int)Mesh.ArrayType.Vertex ||
arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
{
continue;
}
Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
if (verts.Length == 0)
{
continue;
}
int idxCount = verts.Length;
if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array)
{
idxCount = arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length;
}
if (idxCount < 3)
{
continue;
}
ClassifyMaterialForMechPaint(mesh.SurfaceGetMaterial(s), gearPaintTint, gearAccentTint, out Vector3 linCol, out int band, out float rough);
chunks.Add((arr, relXf, linCol, band, rough, verts.Length, idxCount));
totalVerts += verts.Length;
totalIndices += idxCount;
}
}
if (totalVerts == 0 || totalIndices == 0)
{
return null;
}
var outVerts = new Vector3[totalVerts];
var outNorms = new Vector3[totalVerts];
var outColors = new Color[totalVerts];
var outUvs = new Vector2[totalVerts];
var outUv2s = new Vector2[totalVerts];
var outIndices = new int[totalIndices];
int vOff = 0;
int iOff = 0;
for (int c = 0; c < chunks.Count; c++)
{
var (arr, relXf, linCol, band, rough, vCount, idxCount) = chunks[c];
Vector3[] srcV = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
bool flipWinding = relXf.Basis.Determinant() < 0f;
Basis normBasis = relXf.Basis.Inverse().Transposed();
for (int v = 0; v < vCount; v++)
{
outVerts[vOff + v] = relXf * srcV[v];
}
if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array)
{
Vector3[] srcN = arr[(int)Mesh.ArrayType.Normal].AsVector3Array();
for (int v = 0; v < vCount; v++)
{
Vector3 n = normBasis * srcN[v];
outNorms[vOff + v] = n.LengthSquared() > 1e-10f ? n.Normalized() : Vector3.Up;
}
}
else
{
for (int v = 0; v < vCount; v++) outNorms[vOff + v] = Vector3.Up;
}
if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray)
{
Array.Copy(arr[(int)Mesh.ArrayType.Color].AsColorArray(), 0, outColors, vOff, vCount);
}
else
{
// Gear or unbaked submesh: neutral cavity AO, crisp edge highlight, steady rest height above mud line
var defaultCol = new Color(0.86f, 0.36f, 0.50f, 0.65f);
for (int v = 0; v < vCount; v++) outColors[vOff + v] = defaultCol;
}
var uv0 = new Vector2(linCol.X, linCol.Y);
var uv1 = new Vector2(linCol.Z, band * 2.0f + rough);
for (int v = 0; v < vCount; v++)
{
outUvs[vOff + v] = uv0;
outUv2s[vOff + v] = uv1;
}
bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array;
int[]? srcIdx = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null;
if (!flipWinding)
{
if (srcIdx is not null)
{
for (int k = 0; k < idxCount; k++) outIndices[iOff + k] = srcIdx[k] + vOff;
}
else
{
for (int k = 0; k < idxCount; k++) outIndices[iOff + k] = k + vOff;
}
}
else
{
for (int k = 0; k + 2 < idxCount; k += 3)
{
int a = srcIdx is not null ? srcIdx[k] : k;
int bIdx = srcIdx is not null ? srcIdx[k + 1] : k + 1;
int cIdx = srcIdx is not null ? srcIdx[k + 2] : k + 2;
outIndices[iOff + k] = a + vOff;
outIndices[iOff + k + 1] = cIdx + vOff;
outIndices[iOff + k + 2] = bIdx + vOff;
}
}
vOff += vCount;
iOff += idxCount;
}
var surfArrays = new Godot.Collections.Array();
surfArrays.Resize((int)Mesh.ArrayType.Max);
surfArrays[(int)Mesh.ArrayType.Vertex] = outVerts;
surfArrays[(int)Mesh.ArrayType.Normal] = outNorms;
surfArrays[(int)Mesh.ArrayType.Color] = outColors;
surfArrays[(int)Mesh.ArrayType.TexUV] = outUvs;
surfArrays[(int)Mesh.ArrayType.TexUV2] = outUv2s;
surfArrays[(int)Mesh.ArrayType.Index] = outIndices;
var outMesh = new ArrayMesh();
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surfArrays);
return outMesh;
}
private static void ClassifyMaterialForMechPaint(
Material? mat,
Color? gearPaintTint,
Color? gearAccentTint,
out Vector3 linearColor,
out int band,
out float roughness)
{
if (mat is not StandardMaterial3D sm)
{
linearColor = new Vector3(0.08f, 0.09f, 0.06f);
band = 3;
roughness = 0.58f;
return;
}
string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant();
roughness = Math.Clamp(sm.Roughness, 0.08f, 0.90f);
if (mName.Contains("lamp") || mName.Contains("glow") || mName.Contains("cyan") ||
mName.Contains("amber") || mName.Contains("optic_red"))
{
Color eCol = (sm.EmissionEnabled ? sm.Emission : sm.AlbedoColor).SrgbToLinear();
linearColor = new Vector3(eCol.R, eCol.G, eCol.B);
band = 5;
roughness = 0.22f;
return;
}
if (mName.Contains("olive") || mName.Contains("khaki") || mName.Contains("armour") || mName.Contains("armor"))
{
if (gearPaintTint.HasValue)
{
Color c = gearPaintTint.Value.SrgbToLinear();
linearColor = new Vector3(c.R, c.G, c.B);
band = 6;
roughness = 0.56f;
return;
}
Color b = sm.AlbedoColor.SrgbToLinear();
linearColor = new Vector3(b.R, b.G, b.B);
band = 3;
roughness = 0.58f;
return;
}
if (mName.Contains("ivory") && gearPaintTint.HasValue)
{
Color c = gearPaintTint.Value.SrgbToLinear();
linearColor = new Vector3(c.R, c.G, c.B);
band = 6;
roughness = 0.42f;
return;
}
if (mName.Contains("signal") || mName.Contains("orange") || mName.Contains("hazard"))
{
if (gearAccentTint.HasValue)
{
Color c = gearAccentTint.Value.SrgbToLinear();
linearColor = new Vector3(c.R, c.G, c.B);
band = 7;
roughness = 0.42f;
return;
}
Color b = sm.AlbedoColor.SrgbToLinear();
linearColor = new Vector3(b.R, b.G, b.B);
band = 4;
roughness = 0.44f;
return;
}
if (gearAccentTint.HasValue && (mName.Contains("copper") || mName.Contains("gold")))
{
Color c = gearAccentTint.Value.SrgbToLinear();
linearColor = new Vector3(c.R, c.G, c.B);
band = 7;
roughness = 0.36f;
return;
}
Color lin = sm.AlbedoColor.SrgbToLinear();
linearColor = new Vector3(lin.R, lin.G, lin.B);
band = sm.Metallic >= 0.70f ? 2 : (sm.Metallic >= 0.35f ? 1 : 0);
}
private static void PruneEmptyNonProtectedNodes(Node cur, Node sceneRoot, HashSet<Node> protectedNodes)
{
for (int i = cur.GetChildCount() - 1; i >= 0; i--)

View file

@ -875,12 +875,108 @@ public static class VehicleRigAnimator
}
var list = new List<WalkerFootSample>();
var stack = new List<Node3D>();
float cutoffY = visual.Template.MinY + 0.75f;
int count = visual.ModelRoot.GetChildCount();
for (int i = 0; i < count; i++)
var parts = visual.StaticParts;
for (int i = 0; i < parts.Count; i++)
{
CollectFootSamplesRecursive(visual.ModelRoot.GetChild(i), Transform3D.Identity, cutoffY, stack, list);
var part = parts[i];
if (!GodotObject.IsInstanceValid(part.Pivot))
{
continue;
}
// Build chain from ModelRoot -> part.Pivot
var chain = new List<Node3D>();
Transform3D toModel = Transform3D.Identity;
for (Node? cur = part.Pivot; cur is Node3D n3d && !ReferenceEquals(cur, visual.ModelRoot); cur = cur.GetParent())
{
chain.Add(n3d);
toModel = n3d.Transform * toModel;
}
chain.Reverse();
Aabb aabb = part.Mesh.GetAabb();
float aabbMinY = float.PositiveInfinity;
for (int c = 0; c < 8; c++)
{
Vector3 corner = aabb.Position + new Vector3(
(c & 1) != 0 ? aabb.Size.X : 0f,
(c & 2) != 0 ? aabb.Size.Y : 0f,
(c & 4) != 0 ? aabb.Size.Z : 0f);
float wy = (toModel * corner).Y;
if (wy < aabbMinY)
{
aabbMinY = wy;
}
}
if (aabbMinY >= cutoffY)
{
continue;
}
var bestPts = new Vector3[FootSupportDirs.Length];
var bestDots = new float[FootSupportDirs.Length];
for (int d = 0; d < FootSupportDirs.Length; d++)
{
bestDots[d] = float.NegativeInfinity;
}
bool anyVert = false;
int surfCount = part.Mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
var arrays = part.Mesh.SurfaceGetArrays(s);
if (arrays.Count <= (int)Mesh.ArrayType.Vertex ||
arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
{
continue;
}
Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array();
for (int v = 0; v < verts.Length; v++)
{
Vector3 localPt = verts[v];
Vector3 mPt = toModel * localPt;
for (int d = 0; d < FootSupportDirs.Length; d++)
{
float score = mPt.Dot(FootSupportDirs[d]);
if (score > bestDots[d])
{
bestDots[d] = score;
bestPts[d] = localPt;
}
}
anyVert = true;
}
}
if (anyVert)
{
var unique = new List<Vector3>(FootSupportDirs.Length);
for (int d = 0; d < bestPts.Length; d++)
{
bool dup = false;
for (int u = 0; u < unique.Count; u++)
{
if ((unique[u] - bestPts[d]).LengthSquared() < 1e-6f)
{
dup = true;
break;
}
}
if (!dup)
{
unique.Add(bestPts[d]);
}
}
list.Add(new WalkerFootSample
{
ChainFromModelRoot = chain.ToArray(),
LocalPoints = unique.ToArray()
});
}
}
st.FootSamples = list;
}
@ -898,117 +994,6 @@ public static class VehicleRigAnimator
new(-0.45f, -1f, -0.45f),
};
private static void CollectFootSamplesRecursive(
Node cur,
Transform3D parentToModel,
float cutoffY,
List<Node3D> stack,
List<WalkerFootSample> list)
{
Transform3D toModel = parentToModel;
bool pushed = false;
if (cur is Node3D n3d)
{
toModel = parentToModel * n3d.Transform;
stack.Add(n3d);
pushed = true;
}
if (cur is MeshInstance3D mi && mi.Mesh is { } mesh)
{
Aabb aabb = mesh.GetAabb();
float aabbMinY = float.PositiveInfinity;
for (int c = 0; c < 8; c++)
{
Vector3 corner = aabb.Position + new Vector3(
(c & 1) != 0 ? aabb.Size.X : 0f,
(c & 2) != 0 ? aabb.Size.Y : 0f,
(c & 4) != 0 ? aabb.Size.Z : 0f);
float wy = (toModel * corner).Y;
if (wy < aabbMinY)
{
aabbMinY = wy;
}
}
if (aabbMinY < cutoffY)
{
var bestPts = new Vector3[FootSupportDirs.Length];
var bestDots = new float[FootSupportDirs.Length];
for (int d = 0; d < FootSupportDirs.Length; d++)
{
bestDots[d] = float.NegativeInfinity;
}
bool anyVert = false;
int surfCount = mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
var arrays = mesh.SurfaceGetArrays(s);
if (arrays.Count <= (int)Mesh.ArrayType.Vertex ||
arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
{
continue;
}
Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array();
for (int v = 0; v < verts.Length; v++)
{
Vector3 localPt = verts[v];
Vector3 mPt = toModel * localPt;
for (int d = 0; d < FootSupportDirs.Length; d++)
{
float score = mPt.Dot(FootSupportDirs[d]);
if (score > bestDots[d])
{
bestDots[d] = score;
bestPts[d] = localPt;
}
}
anyVert = true;
}
}
if (anyVert)
{
var unique = new List<Vector3>(FootSupportDirs.Length);
for (int d = 0; d < bestPts.Length; d++)
{
bool dup = false;
for (int u = 0; u < unique.Count; u++)
{
if ((unique[u] - bestPts[d]).LengthSquared() < 1e-6f)
{
dup = true;
break;
}
}
if (!dup)
{
unique.Add(bestPts[d]);
}
}
list.Add(new WalkerFootSample
{
ChainFromModelRoot = stack.ToArray(),
LocalPoints = unique.ToArray()
});
}
}
}
int childCount = cur.GetChildCount();
for (int i = 0; i < childCount; i++)
{
CollectFootSamplesRecursive(cur.GetChild(i), toModel, cutoffY, stack, list);
}
if (pushed)
{
stack.RemoveAt(stack.Count - 1);
}
}
private static void ApplyWalkerFloorClearance(VehicleVisualInstance visual, RigState st, string rootNodeName)
{
var samples = st.FootSamples;

File diff suppressed because it is too large Load diff

View file

@ -44,12 +44,16 @@ uniform float wet_top : hint_range(0.1, 6.0) = 2.80;
uniform float scorch : hint_range(0.0, 1.0) = 0.0;
uniform float heat_glow : hint_range(0.0, 1.0) = 0.0;
uniform float heat_emission_energy : hint_range(0.0, 8.0) = 2.6;
uniform bool use_vertex_material = false;
varying vec3 v_local_pos;
varying vec3 v_local_nrm;
varying vec4 v_color;
varying vec4 v_mat_data;
varying float v_scorch;
varying float v_heat;
varying float v_role;
varying float v_alpha;
// Safe remapping helper supporting inverted bounds (lo > hi) without GLSL smoothstep UB.
float map_range(float v, float lo, float hi, float out_lo, float out_hi) {
@ -120,11 +124,80 @@ void vertex() {
v_local_pos = VERTEX;
v_local_nrm = NORMAL;
v_color = COLOR;
v_mat_data = vec4(UV.x, UV.y, UV2.x, UV2.y);
v_scorch = clamp(max(INSTANCE_CUSTOM.x, scorch), 0.0, 1.0);
v_heat = clamp(max(INSTANCE_CUSTOM.y, heat_glow), 0.0, 1.0);
v_role = INSTANCE_CUSTOM.z;
v_alpha = use_vertex_material ? clamp(INSTANCE_CUSTOM.w, 0.0, 1.0) : 1.0;
}
void resolve_role_armor(int role, out vec3 col, out float met, out float rgh) {
if (role == 1) {
col = vec3(0.109, 0.074, 0.054); met = 0.26; rgh = 0.58; // Rival (#5d4d42)
} else if (role == 2) {
col = vec3(0.791, 0.479, 0.039); met = 0.72; rgh = 0.30; // SpectatorTourist (#e6b838)
} else if (role == 3) {
col = vec3(0.026, 0.195, 0.188); met = 0.32; rgh = 0.50; // SpectatorPatron (#2d7a78)
} else if (role == 4) {
col = vec3(0.011, 0.011, 0.016); met = 0.45; rgh = 0.42; // SpectatorExemplar (#1b1b22)
} else if (role == 5) {
col = vec3(0.089, 0.105, 0.107); met = 0.55; rgh = 0.48; // SalvageDrop (#545b5c)
} else {
col = vec3(0.076, 0.095, 0.051); met = 0.28; rgh = 0.58; // Player (#4e5740)
}
}
void resolve_role_accent(int role, out vec3 col, out float met, out float rgh, out float emit_e) {
emit_e = 0.0;
if (role == 1) {
col = vec3(0.468, 0.068, 0.032); met = 0.20; rgh = 0.46; // Rival (#b64a32)
} else if (role == 2) {
col = vec3(0.896, 0.823, 0.687); met = 0.16; rgh = 0.38; // SpectatorTourist (#f2ead8)
} else if (role == 3) {
col = vec3(0.392, 0.147, 0.037); met = 0.65; rgh = 0.36; // SpectatorPatron (#a86c36)
} else if (role == 4) {
col = vec3(0.584, 0.023, 0.023); met = 0.25; rgh = 0.36; emit_e = 0.65; // SpectatorExemplar (#c92a2a)
} else if (role == 5) {
col = vec3(0.058, 0.694, 0.807); met = 0.22; rgh = 0.34; emit_e = 0.45; // SalvageDrop (#44d9e8)
} else {
col = vec3(0.694, 0.150, 0.020); met = 0.18; rgh = 0.44; // Player (#d96c27)
}
}
void fragment() {
vec3 mat_base_col = base_color.rgb;
float mat_rough = roughness;
float mat_metal = metallic;
float mat_wear = wear;
float mat_mud = mud;
float mat_static_emit = 0.0;
if (use_vertex_material) {
int band = int(floor((v_mat_data.w + 0.5) * 0.5));
mat_rough = clamp(v_mat_data.w - float(band) * 2.0, 0.08, 0.95);
mat_base_col = clamp(v_mat_data.rgb, vec3(0.0), vec3(1.0));
int role = int(floor(v_role + 0.5));
if (band == 0) {
mat_metal = 0.12;
} else if (band == 1) {
mat_metal = 0.55;
} else if (band == 2) {
mat_metal = 0.85;
} else if (band == 3) {
resolve_role_armor(role, mat_base_col, mat_metal, mat_rough);
} else if (band == 4) {
resolve_role_accent(role, mat_base_col, mat_metal, mat_rough, mat_static_emit);
} else if (band == 5) {
mat_metal = 0.15;
mat_static_emit = 1.85;
mat_wear = 0.0;
mat_mud = 0.0;
} else if (band == 6) {
mat_metal = 0.26;
} else {
mat_metal = 0.65;
}
}
vec3 pos = v_local_pos * noise_scale;
vec3 nrm = normalize(v_local_nrm);
float up = nrm.y;
@ -134,85 +207,97 @@ void fragment() {
float island_rand = clamp(v_color.b, 0.0, 1.0);
float height_m = clamp(v_color.a, 0.0, 1.0) * 6.0;
// Layer 1: Base paint + per-island tone variation + 2-octave 3D object-space mottle
// Shared rotated multi-scale 3D noise basis (5 lookups total vs 352 hashes across 6 layers)
const mat3 rot = mat3(
vec3(0.80, -0.48, 0.36),
vec3(0.60, 0.64, -0.48),
vec3(0.00, 0.60, 0.80)
);
vec3 rpos = rot * pos;
float n_macro = noise3d(pos * 0.85);
float n_mid = noise3d(rpos * 3.8 + vec3(17.3, 9.1, 23.7));
float n_fine = noise3d(pos * 10.5 + vec3(5.7, 31.4, 11.2));
float n_speck = noise3d(rpos * 27.0 + vec3(11.1, 3.7, 19.4));
float n_streak = noise3d(pos * vec3(13.0, 0.5, 13.0));
// Layer 1: Base paint + per-island tone variation + multi-octave mottle
float rand2 = fract(island_rand * 7.31 + 0.37);
vec3 hsv = rgb_to_hsv(base_color.rgb);
vec3 hsv = rgb_to_hsv(mat_base_col);
hsv.x = fract(hsv.x + (rand2 - 0.5) * tone_variation * 0.14);
hsv.y = clamp(hsv.y * (1.0 + (rand2 - 0.5) * tone_variation * 0.75), 0.0, 1.0);
hsv.z = clamp(hsv.z * (1.0 + (island_rand * 2.0 - 1.0) * tone_variation * 0.65), 0.01, 2.0);
vec3 col = hsv_to_rgb(hsv);
float blotch = fbm2(pos * 0.75);
float speck = fbm2(pos * 26.0);
float mid_n = fbm2(pos * 4.5);
float blotch = n_macro * 0.70 + n_mid * 0.30;
float mid_n = n_mid * 0.68 + n_fine * 0.32;
float shade = map_range(blotch, 0.25, 0.75, -0.14, 0.14)
+ map_range(speck, 0.25, 0.75, -0.07, 0.07)
+ map_range(n_speck, 0.25, 0.75, -0.07, 0.07)
+ map_range(mid_n, 0.25, 0.75, -0.09, 0.09);
col *= clamp(1.0 + shade * mottle, 0.55, 1.35);
// Layer 2: Cavity grime darkening + roughness boost from (1 - AO)
float cavity = clamp(map_range(occ, 0.90, 0.42, 0.0, 1.0) * map_range(fbm2(pos * 5.0), 0.30, 0.65, 0.45, 1.0) * grime, 0.0, 1.0);
float film = clamp(map_range(fbm2(pos * 2.1), 0.54, 0.72, 0.0, 1.0) * 0.30 * grime, 0.0, 1.0);
float cavity = clamp(map_range(occ, 0.90, 0.42, 0.0, 1.0) * map_range(mid_n, 0.30, 0.65, 0.45, 1.0) * grime, 0.0, 1.0);
float film = clamp(map_range(n_macro * 0.5 + n_mid * 0.5, 0.54, 0.72, 0.0, 1.0) * 0.30 * grime, 0.0, 1.0);
float grime_amt = max(cavity, film);
col = mix(col, grime_color.rgb, min(grime_amt, 0.85));
// Layer 3: Vertical rain/oil streaks on upright surfaces boosted by cavity
vec3 stretch = pos * vec3(13.0, 0.5, 13.0);
float upright = map_range(abs(up), 0.80, 0.35, 0.0, 1.0);
float under = map_range(occ, 0.96, 0.65, 0.40, 1.0);
float broken = map_range(noise3d(pos * 1.4), 0.35, 0.55, 0.15, 1.0);
float dark_run = clamp(map_range(fbm2(stretch), 0.52, 0.68, 0.0, 1.0) * upright * under * broken * streaks, 0.0, 1.0);
float pale_run = clamp(map_range(fbm2(stretch + vec3(31.0, 5.0, 17.0)), 0.62, 0.76, 0.0, 1.0) * upright * 0.28 * streaks, 0.0, 1.0);
float broken = map_range(n_macro, 0.35, 0.55, 0.15, 1.0);
float streak_mix = n_streak * 0.72 + n_fine * 0.28;
float dark_run = clamp(map_range(streak_mix, 0.52, 0.68, 0.0, 1.0) * upright * under * broken * streaks, 0.0, 1.0);
float pale_run = clamp(map_range(1.0 - streak_mix, 0.62, 0.76, 0.0, 1.0) * upright * 0.28 * streaks, 0.0, 1.0);
col = mix(col, dust_color.rgb, pale_run);
col = mix(col, grime_color.rgb, dark_run * 0.85);
// Layer 4: Pale dust on upward-facing normals (v_local_nrm.y)
float dust_amt = clamp(map_range(up, 0.45, 0.95, 0.0, 1.0) * map_range(fbm2(pos * 3.0), 0.25, 0.70, 0.25, 1.0) * dust * 0.55, 0.0, 1.0);
float dust_amt = clamp(map_range(up, 0.45, 0.95, 0.0, 1.0) * map_range(mid_n, 0.25, 0.70, 0.25, 1.0) * dust * 0.55, 0.0, 1.0);
col = mix(col, dust_color.rgb, dust_amt);
// Layer 5: Metallic edge chipping + thin primer_color halo from edge_curvature * noise
float exposed = map_range(occ, 0.42, 0.88, 0.0, 1.0);
float edge_sharp = pow(edge, 1.85);
float chip_n = map_range(fbm2(pos * 6.5), 0.30, 0.72, 0.0, 0.44)
+ map_range(noise3d(pos * 46.0), 0.30, 0.70, -0.06, 0.06);
float wear_level = chip_n + edge_sharp * exposed * wear * 0.56;
float scuff = map_range(fbm2(pos * 4.5), 0.68, 0.72, 0.0, 1.0) * clamp(wear / 1.8, 0.0, 1.0) * 0.55;
float chip_n = map_range(n_mid * 0.6 + n_fine * 0.4, 0.30, 0.72, 0.0, 0.44)
+ map_range(n_speck, 0.30, 0.70, -0.06, 0.06);
float wear_level = chip_n + edge_sharp * exposed * mat_wear * 0.56;
float scuff = map_range(mid_n, 0.68, 0.72, 0.0, 1.0) * clamp(mat_wear / 1.8, 0.0, 1.0) * 0.55;
float chip_metal_mask = clamp(max(map_range(wear_level, 0.76, 0.80, 0.0, 1.0), scuff * 0.85), 0.0, 1.0);
float primer_mask = clamp(max(map_range(wear_level, 0.71, 0.75, 0.0, 1.0), scuff), 0.0, 1.0);
col = mix(col, primer_color.rgb, primer_mask * 0.75);
col = mix(col, chip_color.rgb, chip_metal_mask);
// Layer 6: Lower-hull/foot mud & wet gloss driven by rest_height (COLOR.a)
float wet_amt = clamp(map_range(height_m, wet_top, 0.0, 0.0, 1.0) * wet, 0.0, 1.0);
float wet_amt = clamp(map_range(height_m, wet_top, 0.0, 0.0, 1.0) * wet * clamp(mat_mud, 0.0, 1.0), 0.0, 1.0);
col *= (1.0 - 0.50 * wet_amt);
float mud_n = fbm2(pos * 3.2);
float mud_n = n_macro * 0.35 + n_mid * 0.65;
float thick = map_range(height_m, mud_top, 0.0, 0.0, 1.0)
* map_range(mud_n, 0.35, 0.62, 0.1, 1.5)
* map_range(occ, 0.95, 0.50, 0.7, 1.6) * mud;
float splash = map_range(fbm2(pos * 11.0), 0.62, 0.66, 0.0, 1.0)
* map_range(height_m, mud_top * 2.2, mud_top * 0.4, 0.0, 1.0) * mud * 0.85;
* map_range(occ, 0.95, 0.50, 0.7, 1.6) * mat_mud;
float splash = map_range(n_fine, 0.62, 0.66, 0.0, 1.0)
* map_range(height_m, mud_top * 2.2, mud_top * 0.4, 0.0, 1.0) * mat_mud * 0.85;
float mud_amt = clamp(max(map_range(thick, 0.20, 0.50, 0.0, 1.0), splash), 0.0, 1.0);
col = mix(col, mud_color.rgb * map_range(mud_n, 0.30, 0.70, 0.70, 1.30), mud_amt);
// PBR metallic & roughness synthesis
float out_metallic = mix(metallic, chip_metallic, chip_metal_mask);
float out_metallic = mix(mat_metal, chip_metallic, chip_metal_mask);
out_metallic *= (1.0 - mud_amt) * (1.0 - grime_amt * 0.70);
float out_rough = roughness + grime_amt * 0.22 + (1.0 - occ) * 0.12 * clamp(grime, 0.0, 1.0);
float out_rough = mat_rough + grime_amt * 0.22 + (1.0 - occ) * 0.12 * clamp(grime, 0.0, 1.0);
out_rough = mix(out_rough, chip_roughness, chip_metal_mask);
out_rough -= wet_amt * 0.18;
out_rough += mud_amt * 0.18;
out_rough = clamp(out_rough, 0.12, 0.98);
// Live combat channel 1: scorch (char/soot darkening + matte roughness)
float soot_pat = mix(0.65, 1.0, fbm2(pos * 4.5));
float soot_pat = mix(0.65, 1.0, mid_n);
float scorch_mask = clamp(v_scorch * soot_pat, 0.0, 1.0);
col = mix(col, vec3(0.022, 0.018, 0.016), scorch_mask * 0.88);
out_metallic *= (1.0 - scorch_mask * 0.75);
out_rough = mix(out_rough, 0.94, scorch_mask);
// Live combat channel 2: heat_glow (incandescent orange-red emission without cloning material)
float heat_mod = mix(0.25, 1.15, pow(edge, 1.4) * 0.6 + fbm2(pos * 3.8) * 0.4);
float heat_mod = mix(0.25, 1.15, pow(edge, 1.4) * 0.6 + mid_n * 0.4);
float h_val = clamp(v_heat * heat_mod, 0.0, 1.0);
vec3 heat_col = mix(vec3(0.85, 0.12, 0.01), vec3(1.0, 0.52, 0.10), smoothstep(0.25, 0.95, h_val));
@ -221,5 +306,5 @@ void fragment() {
ROUGHNESS = out_rough;
AO = mix(1.0, occ, 0.65);
AO_LIGHT_AFFECT = 0.65;
EMISSION = heat_col * (pow(v_heat, 1.35) * heat_mod * heat_emission_energy);
EMISSION = mat_base_col * mat_static_emit + heat_col * (pow(v_heat, 1.35) * heat_mod * heat_emission_energy);
}

View file

@ -314,14 +314,6 @@ public partial class Smoke : Node
Check(mappedHp is { Id: "hp.weapon.main" },
$"Expected GetHardpointAt(1,1) to return hp.weapon.main, got {mappedHp?.Id ?? "null"}");
// Toggle thermal mode off -> on -> off
_main.Hud.SetThermalMode(true, instant: true);
Check(_main.Hud.ThermalMode && MathF.Abs(schematic.ThermalBlend - 1f) < 0.01f,
"Expected ThermalMode to activate immediately");
_main.Hud.SetThermalMode(false, instant: true);
Check(!_main.Hud.ThermalMode && MathF.Abs(schematic.ThermalBlend) < 0.01f,
"Expected ThermalMode to deactivate immediately");
// Regression check (Finding 3): same-dimension SwapChassis updates _hardpointLookup and clears hover state
schematic._GuiInput(new InputEventMouseMotion { Position = probePos });
Check(schematic.HoveredCell == new Vector2I(1, 1) && schematic.HoveredHardpoint is { Id: "hp.weapon.main" },
@ -383,7 +375,7 @@ public partial class Smoke : Node
return;
}
// GPU verification on OpenGL 3.3: render isolated InventoryGridControl (tactical + thermal) & panel_chrome.gdshader
// GPU verification on OpenGL 3.3: render isolated InventoryGridControl (ambient vs live bilinear heat) & panel_chrome.gdshader
var gridVp = new SubViewport
{
Size = new Vector2I(240, 240),
@ -398,36 +390,42 @@ public partial class Smoke : Node
gridVp.AddChild(vpGrid);
AddChild(gridVp);
var coolGrid = new ChassisGrid(Catalog.Ironclad);
coolGrid.TryMount(Catalog.Recoilless, "hp.weapon.main");
coolGrid.TryMount(Catalog.Mg762, "hp.weapon.coax");
coolGrid.TryMount(Catalog.TurboCore, "hp.engine.rear");
coolGrid.TryMount(Catalog.CopperRad, "hp.radiator.l");
coolGrid.TryMount(Catalog.WeldedPlate, "hp.armor.front");
coolGrid.Armor[0, 0] = 0f;
vpGrid.SetGrid(coolGrid);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var coolImg = gridVp.GetTexture().GetImage();
int coolOpaque = CountNonZeroAlphaPixels(coolImg, 0.08f);
GD.Print($"SMOKE INFO: InventoryGrid GPU cool opaque pixels={coolOpaque}");
Check(coolOpaque > 4000, $"Expected > 4000 rendered pixels from InventoryGrid shader, got {coolOpaque}");
vpGrid.SetGrid(testGrid);
vpGrid.TriggerHitPulse(1, 1, 1f);
vpGrid.SetThermalInstant(false);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var tacticalImg = gridVp.GetTexture().GetImage();
int tacticalOpaque = CountNonZeroAlphaPixels(tacticalImg, 0.08f);
GD.Print($"SMOKE INFO: InventoryGrid GPU tactical opaque pixels={tacticalOpaque}");
Check(tacticalOpaque > 4000, $"Expected > 4000 rendered pixels from InventoryGrid tactical shader, got {tacticalOpaque}");
var hotImg = gridVp.GetTexture().GetImage();
int hotOpaque = CountNonZeroAlphaPixels(hotImg, 0.08f);
int heatDiff = CountDifferentPixels(coolImg, hotImg, 0.05f);
GD.Print($"SMOKE INFO: InventoryGrid GPU hot opaque={hotOpaque}, diff vs cool={heatDiff}");
Check(hotOpaque > 4000, $"Expected > 4000 rendered pixels from heated InventoryGrid shader, got {hotOpaque}");
Check(heatDiff > 400, $"Expected always-active temp_tex + hit pulse to visibly change > 400 pixels, got {heatDiff}");
vpGrid.SetThermalInstant(true);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var thermalImg = gridVp.GetTexture().GetImage();
int thermalOpaque = CountNonZeroAlphaPixels(thermalImg, 0.08f);
int modeDiff = CountDifferentPixels(tacticalImg, thermalImg, 0.05f);
GD.Print($"SMOKE INFO: InventoryGrid GPU thermal opaque={thermalOpaque}, diff vs tactical={modeDiff}");
Check(thermalOpaque > 4000, $"Expected > 4000 rendered pixels from InventoryGrid thermal shader, got {thermalOpaque}");
Check(modeDiff > 500, $"Expected thermal conduit toggle to visibly change > 500 pixels, got {modeDiff}");
// Finding 2 GPU check: overheated (350C+, thermal_mode = 1.0f) must obey blend_premul_alpha (out_rgb <= out_a)
// Finding 2 GPU check: overheated (350C..550C+) must obey blend_premul_alpha (out_rgb <= out_a)
testGrid.InjectHardpointHeat("hp.engine.rear", 45000f);
testGrid.InjectHardpointHeat("hp.weapon.main", 25000f);
testGrid.StepHeat(0.05f);
float hotTemp = testGrid.Temperature[1, 3];
Check(hotTemp >= 350f, $"Expected overheated cell >= 350C for premul test, got {hotTemp:F1}C");
vpGrid.SetGrid(testGrid);
vpGrid.SetThermalInstant(true);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
@ -436,7 +434,7 @@ public partial class Smoke : Node
GD.Print($"SMOKE INFO: InventoryGrid GPU overheat ({hotTemp:F1}C) premul violations={premulViolations}");
Check(premulViolations == 0, $"Expected 0 blend_premul_alpha violations (max(RGB) > A + 0.01) on overheated grid, got {premulViolations}");
// Finding 1 GPU check: asymmetric Raptor chassis with thermal_mode = 1.0f must leave 0 lit pixels in inactive cell holes
// Finding 1 GPU check: asymmetric heated Raptor chassis must leave 0 lit pixels in inactive cell holes
var raptorGrid = new ChassisGrid(Catalog.Raptor);
Check(raptorGrid.TryMount(Catalog.CopperRad, "hp.radiator.sh_l"), "Expected CopperRad on Raptor hp.radiator.sh_l");
Check(raptorGrid.TryMount(Catalog.CopperRad, "hp.radiator.sh_r"), "Expected CopperRad on Raptor hp.radiator.sh_r");
@ -447,7 +445,6 @@ public partial class Smoke : Node
raptorGrid.StepHeat(0.25f);
vpGrid.SetGrid(raptorGrid);
vpGrid.SetThermalInstant(true);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
@ -480,7 +477,6 @@ public partial class Smoke : Node
raptorGrid.Cargo.Clear();
Check(raptorGrid.TryAddCargo(Catalog.Autocannon), "Expected Autocannon in Raptor Cargo[0]");
vpGrid.SetGrid(raptorGrid, selectedCargoIndex: 0);
vpGrid.SetThermalInstant(false);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
@ -650,6 +646,8 @@ public partial class Smoke : Node
if (pkg is null) continue;
var vis = VehicleVisualInstance.Create(cache, spec.Id, VehicleVisualRole.Player);
Check(CountMeshInstances(vis.Root) == 0,
$"Expected zero MeshInstance3D children on MultiMesh rig '{spec.Id}', got {CountMeshInstances(vis.Root)}");
Check(vis.BoundHardpointCount == spec.Hardpoints.Length,
$"Expected {spec.Hardpoints.Length} bound hardpoints on '{spec.Id}', got {vis.BoundHardpointCount}");
Check(vis.Joints.Count == pkg.Joints.Count,
@ -663,7 +661,7 @@ public partial class Smoke : Node
foreach (var m in grid.Mounted)
{
var gNode = vis.GetMountedGearNode(m.HardpointId);
if (gNode is not null && CountMeshInstances(gNode) > 0)
if (gNode is not null)
{
mountedMeshes++;
if (m.Spec.Kind == HardpointKind.Weapon)
@ -675,18 +673,18 @@ public partial class Smoke : Node
"recoilless" => ("sight_tube", "breech_band"),
_ => ("condenser_ring_2", "ivory_cowl")
};
Vector3? frontC = ComputeSubtreeVertexCentroidInAncestor(gNode, vis.ModelRoot, frontPart);
Vector3? rearC = ComputeSubtreeVertexCentroidInAncestor(gNode, vis.ModelRoot, rearPart);
Check(frontC.HasValue && rearC.HasValue,
bool hasCentroids = vis.TryGetMountedWeaponCentroidsInModel(
m.HardpointId, frontPart, rearPart, out Vector3 frontC, out Vector3 rearC);
Check(hasCentroids,
$"Missing weapon submeshes '{frontPart}'/'{rearPart}' on '{spec.Id}.{m.HardpointId}' ({m.Spec.Id})");
if (frontC.HasValue && rearC.HasValue)
if (hasCentroids)
{
Vector3 muzzleDir = (frontC.Value - rearC.Value).Normalized();
Vector3 muzzleDir = (frontC - rearC).Normalized();
if (m.Spec.Id == "recoilless")
{
GD.Print($"SMOKE INFO: recoilless {spec.Id}.{m.HardpointId} sight_tube={frontC.Value} breech={rearC.Value} dir={muzzleDir}");
Check(frontC.Value.Z > rearC.Value.Z + 0.20f,
$"Expected recoilless sight_tube (+Z) ahead of breech_band on '{spec.Id}.{m.HardpointId}', got sight={frontC.Value}, breech={rearC.Value}");
GD.Print($"SMOKE INFO: recoilless {spec.Id}.{m.HardpointId} sight_tube={frontC} breech={rearC} dir={muzzleDir}");
Check(frontC.Z > rearC.Z + 0.20f,
$"Expected recoilless sight_tube (+Z) ahead of breech_band on '{spec.Id}.{m.HardpointId}', got sight={frontC}, breech={rearC}");
}
Check(muzzleDir.Z > 0.75f,
$"Expected weapon '{m.Spec.Id}' on '{spec.Id}.{m.HardpointId}' mesh geometry to point forward (+Z), got dir={muzzleDir}");
@ -800,15 +798,15 @@ public partial class Smoke : Node
Check(anvilVis.GetMountedGearNode("hp.weapon.siege_l") is null,
"Expected hp.weapon.siege_l gear to shear off when hardpoint becomes non-operational");
if (debris.GetChildCount() > 0 && debris.GetChild(0) is Node3D firstPiece)
if (debris.TryGetPiecePosition(0, out Vector3 p0))
{
Vector3 p0 = firstPiece.Position;
for (int s = 0; s < 25; s++)
{
debris.Step(1f / 60f, _main.Session.State.Terrain);
}
float moved = firstPiece.Position.DistanceTo(p0);
Check(moved > 0.1f && !HasNaN(firstPiece.Transform),
debris.TryGetPiecePosition(0, out Vector3 p1);
float moved = p1.DistanceTo(p0);
Check(moved > 0.1f && p1.IsFinite(),
$"Expected debris piece to travel/fall > 0.1m under blast + gravity, got {moved:F3}m");
}
@ -848,12 +846,11 @@ public partial class Smoke : Node
debris.QueueFree();
}
// 5. All 15 ChassisDrop salvage wrecks ground within 0.05m of terrain & PickedUp frees drop nodes cleanly
// 5. All 15 ChassisDrop salvage wrecks ground within 0.05m of terrain & PickedUp frees drops cleanly
{
var drops = _main.Session.State.GroundDrops;
int baseCount = drops.Count;
_main.Arena.Sync(_main.Session, 1.0f, 1f / 60f);
int dropNodesBefore = _main.Arena.DropGroupChildCount;
int trackedBefore = _main.Arena.ActiveDropVisualCount;
int nextId = 90000;
@ -876,37 +873,30 @@ public partial class Smoke : Node
for (int i = 0; i < added.Count; i++)
{
var d = added[i];
Node3D? dropNode = _main.Arena.GetNodeOrNull<Node3D>($"GroundDrops/Drop_{d.Id}");
Check(dropNode is not null, $"Missing Drop_{d.Id} node for ChassisDrop '{d.Chassis!.Id}'");
if (dropNode is not null)
bool hasDrop = _main.Arena.TryGetChassisDropVisual(d.Id, out var dropVis, out _);
Check(hasDrop && dropVis is not null, $"Missing ChassisDrop visual for Drop_{d.Id} ('{d.Chassis!.Id}')");
if (hasDrop && dropVis is not null)
{
Node3D? actorNode = dropNode.GetNodeOrNull<Node3D>($"Actor_{d.Chassis!.Id}");
Check(actorNode is not null, $"Missing Actor_{d.Chassis!.Id} under Drop_{d.Id}");
if (actorNode is not null)
{
float minWorldY = ComputeSubtreeMinWorldY(actorNode, dropNode.Position.Y);
float terrainY = _main.Session.State.Terrain.SampleHeight(d.X, d.Z);
float err = MathF.Abs(minWorldY - terrainY);
if (err > maxGroundErr) maxGroundErr = err;
Check(err <= 0.05f,
$"ChassisDrop '{d.Chassis!.Id}' buried/floating: minWorldY={minWorldY:F4}m terrainY={terrainY:F4}m err={err:F4}m");
}
dropVis.SetLodState(useStaticLod: false, castShadows: false);
float minWorldY = dropVis.ComputeMinVertexY();
float terrainY = _main.Session.State.Terrain.SampleHeight(d.X, d.Z);
float err = MathF.Abs(minWorldY - terrainY);
if (err > maxGroundErr) maxGroundErr = err;
Check(err <= 0.05f,
$"ChassisDrop '{d.Chassis!.Id}' buried/floating: minWorldY={minWorldY:F4}m terrainY={terrainY:F4}m err={err:F4}m");
}
}
GD.Print($"SMOKE INFO: ChassisDrop max ground err={maxGroundErr:F4}m across {added.Count} chassis");
// Also verify far LOD (BakedLodFarMesh) ChassisDrop grounding stays <= 0.05m across all 15 chassis
// Also verify far LOD (SingleSurfaceLodFarMesh) ChassisDrop grounding stays <= 0.05m across all 15 chassis
float maxFarGroundErr = 0f;
for (int i = 0; i < added.Count; i++)
{
var d = added[i];
Node3D? dropNode = _main.Arena.GetNodeOrNull<Node3D>($"GroundDrops/Drop_{d.Id}");
Node3D? actorNode = dropNode?.GetNodeOrNull<Node3D>($"Actor_{d.Chassis!.Id}");
MeshInstance3D? dropMesh = actorNode?.GetNodeOrNull<MeshInstance3D>($"Model_{d.Chassis!.Id}");
if (dropNode is not null && actorNode is not null && dropMesh is not null)
if (_main.Arena.TryGetChassisDropVisual(d.Id, out var dropVis, out _) && dropVis is not null)
{
dropMesh.Mesh = cache.GetOrLoadVehicle(d.Chassis!.Id).BakedLodFarMesh;
float minFarWorldY = ComputeSubtreeMinWorldY(actorNode, dropNode.Position.Y);
dropVis.SetLodState(useStaticLod: true, castShadows: false);
float minFarWorldY = dropVis.ComputeMinVertexY();
float terrainY = _main.Session.State.Terrain.SampleHeight(d.X, d.Z);
float err = MathF.Abs(minFarWorldY - terrainY);
if (err > maxFarGroundErr) maxFarGroundErr = err;
@ -924,8 +914,6 @@ public partial class Smoke : Node
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
Check(_main.Arena.ActiveDropVisualCount == trackedBefore,
$"Expected picked-up drops removed from _dropVisuals ({trackedBefore}), got {_main.Arena.ActiveDropVisualCount}");
Check(_main.Arena.DropGroupChildCount == dropNodesBefore,
$"Expected picked-up drop nodes freed from GroundDrops ({dropNodesBefore}), got {_main.Arena.DropGroupChildCount}");
drops.RemoveRange(baseCount, added.Count);
}
@ -946,7 +934,7 @@ public partial class Smoke : Node
foreach (var (wId, footNodeName, pelvisNodeName, checkSagittal) in walkerChecks)
{
var vis = VehicleVisualInstance.Create(cache, wId, VehicleVisualRole.Player);
float restMinY = ComputeSubtreeMinWorldY(vis.ModelRoot, 0f, relativeToModelRoot: true);
float restMinY = vis.ComputeMinVertexY(relativeToModelRoot: true);
float worstRelMinY = float.PositiveInfinity;
float minFootZ = float.PositiveInfinity, maxFootZ = float.NegativeInfinity;
float minFootX = float.PositiveInfinity, maxFootX = float.NegativeInfinity;
@ -959,7 +947,7 @@ public partial class Smoke : Node
for (int step = 0; step < 48; step++)
{
VehicleRigAnimator.Update(vis, in walkInp, Basis.Identity);
float curMinY = ComputeSubtreeMinWorldY(vis.ModelRoot, 0f, relativeToModelRoot: true);
float curMinY = vis.ComputeMinVertexY(relativeToModelRoot: true);
float relMinY = curMinY - restMinY;
if (relMinY < worstRelMinY) worstRelMinY = relMinY;
Check(!float.IsNaN(curMinY), $"NaN vertex Y on walker '{wId}' step {step}");
@ -1099,6 +1087,21 @@ public partial class Smoke : Node
debris.QueueFree();
}
// 10. MultiMeshPartPool & PomDecalPool sanity: live arena submits into MultiMeshPartPool and PomDecalPool stamps impacts cleanly
{
_main.Arena.PomDecals.StampTestDecal(
new Vector3(_main.Session.State.Player.X + 2f, _main.Session.State.Terrain.SampleHeight(_main.Session.State.Player.X + 2f, _main.Session.State.Player.Z) + 0.03f, _main.Session.State.Player.Z),
Vector3.Up, 1.2f, tileIndex: 14);
_main.Arena.Sync(_main.Session, 1.6f, 1f / 60f);
Check(_main.Arena.PartPool.TotalSubmittedInstances > 0,
$"Expected MultiMeshPartPool to submit active instances, got {_main.Arena.PartPool.TotalSubmittedInstances}");
Check(_main.Arena.PomDecals.ActiveCount >= 1,
$"Expected PomDecalPool to hold >= 1 active decal, got {_main.Arena.PomDecals.ActiveCount}");
_main.Hud.PushTestHitArc(_main.Session.State.Player.X + 20f, _main.Session.State.Player.Z + 10f, WeaponVisualClass.Explosive);
Check(_main.Hud.ActiveHitArcCount >= 1, "Expected CrosshairOverlay to accept incoming hit arc");
}
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}