Core/DmlrCoreDatabase.cs

Static settings store for the DMLR Ultra addon. Holds four per-module quality tiers (Normal or Xtreme), loads and saves them to a cookie and to dmlr-core-db.json, smooths FPS and ping/jitter metrics in TickMetrics, and pushes the derived values into the scene's RenderAttributes.

File Access
using Sandbox;
using System;

namespace DmlrAddon;

/// <summary>
/// Palier Next-Gen à 2 options (Normal &amp; Extrême) pour chacun des 4 modules DMLR Ultra.
/// </summary>
public enum DmlrTier
{
	Normal = 0,
	Xtreme = 1
}

public enum DmlrMapFogMode
{
	OrigineMap = 0,
	Etendu = 1,
	Xtreme = 2,
	Degage = 3
}

/// <summary>
/// BASE DE CODAGE 1 · Moteur de Données &amp; Logique DMLR Ultra (Surcouche DLSS/FSR + Frame Gen s&amp;box).
///  1. Game Diamantine       : Upscaler RCAS 1080p→4K · 2K→8K · 4K→12K + couleurs éclatantes + noir absolu
///  2. Frame Magique ∞       : Frame Gen Normal (×2) ou Infini (∞) + Réflexe &amp; Bouclier Anti-Chutes FPS
///  3. Liaison Multiverselle : Stabilisateur Anti-Pics Ping &amp; Jitter (Solo + Multi 32–64+ joueurs)
///  4. Render Distance Xtreme: Portée Next-Gen (120 000 / 250 000) + Fog réversible &amp; Culling adaptatif
/// 100 % non-intrusif ("cerise sur le gâteau") · Ne touche jamais aux réglages vidéo natifs de s&amp;box.
/// </summary>
public static class DmlrCoreDatabase
{
	public sealed class CoreRecord
	{
		public int SchemaVersion { get; set; } = 4;

		// 1. Game Diamantine · Upscaler DLSS/FSR maison (Normal / Extrême)
		public DmlrTier DiamantineTier { get; set; } = DmlrTier.Xtreme;

		// 2. Frame Magique · Frame Gen + Anti-Chutes FPS (Normal ×2 / Extrême ∞ Infini)
		public DmlrTier FrameMagiqueTier { get; set; } = DmlrTier.Xtreme;

		// 3. Liaison Multiverselle · Anti-Pics Ping & Jitter Solo/Multi (Normal / Extrême)
		public DmlrTier MultiversalTier { get; set; } = DmlrTier.Xtreme;

		// 4. Render Distance Xtreme · Horizon & Culling Anti-Lag (Normal 120 000 / Extrême 250 000)
		public DmlrTier RenderDistanceTier { get; set; } = DmlrTier.Xtreme;
	}

	private const string StorePath = "dmlr-core-db.json";
	private const string GlobalCookieKey = "dmlr.global.core.v4";
	private static bool _loaded;

	public static CoreRecord Current { get; private set; } = new();
	public static int Revision { get; private set; }
	public static string StatusMessage { get; private set; } = "";

	// ── Télémétrie temps réel (zéro allocation par frame + Bouclier Anti-Chutes FPS & Anti-Pics Ping) ──
	private static float _smoothedFps = 120f;
	private static float _smoothedMs = 8.3f;
	private static float _worstWindowMs = 8.3f;
	private static float _smoothedLow1Fps = 110f;
	private static float _smoothedPing = 1f;
	private static float _smoothedJitter = 0f;
	private static float _lastRawPing = 1f;

	private static float _governorClock;
	private static float _uiDisplayClock;
	private static float _dynamicBias = 1.0f;
	private static float _lastPushedBias = -1f;
	private static int _lastPushedRevision = -1;

	public static int DisplayFps { get; private set; } = 120;
	public static int DisplayLow1Fps { get; private set; } = 110;
	public static int DisplayStabilityPct { get; private set; } = 99;
	public static int DisplayPingMs { get; private set; } = 1;
	public static int DisplayJitterMs { get; private set; } = 0;

	public static int NativeFps => Math.Max( 1, (int)MathF.Round( _smoothedFps ) );
	public static float NativeMs => _smoothedMs;
	public static float DynamicGovernorBias => _dynamicBias;
	public static bool IsAntiDropEngaged => _dynamicBias < 0.92f;

	public static int ConnectedPlayers { get; internal set; } = 1;
	public static int NearbyPlayers { get; internal set; } = 1;
	public static int OptimizedEntities { get; internal set; } = 0;
	public static int OptimizedLights { get; internal set; } = 0;
	public static int ActiveWorldRenderers { get; internal set; } = 0;
	public static int CulledWorldRenderers { get; internal set; } = 0;

	public static bool IsMultiplayer => ConnectedPlayers > 1;
	public static string SessionLabel => IsMultiplayer ? $"Multijoueur · {ConnectedPlayers} joueurs" : "Solo · 1 joueur";

	public static int LocalPingMs
	{
		get
		{
			int raw = (int)MathF.Round( Connection.Local?.Ping ?? 0f );
			return raw > 0 ? raw : 1;
		}
	}

	// ── Paramètres calculés proprement à partir des 2 paliers (Normal / Extrême) ──
	public static bool IsDiamantineXtreme => Current.DiamantineTier == DmlrTier.Xtreme;
	public static bool IsFrameInfinite => Current.FrameMagiqueTier == DmlrTier.Xtreme;
	public static bool IsMultiversalXtreme => Current.MultiversalTier == DmlrTier.Xtreme;
	public static bool IsRenderDistanceXtreme => Current.RenderDistanceTier == DmlrTier.Xtreme;

	public static float CrystalSharpness => IsDiamantineXtreme ? 0.90f : 0.48f;
	public static float CameraZFar => IsRenderDistanceXtreme ? 250000f : 120000f;
	public static DmlrMapFogMode MapFogMode => IsRenderDistanceXtreme ? DmlrMapFogMode.Xtreme : DmlrMapFogMode.Etendu;
	public static float VegetationDistanceScale => IsRenderDistanceXtreme ? 2.25f : 1.25f;

	public static int ActiveFrameMultiplier => IsFrameInfinite ? 4 : 2;
	public static int EffectiveFps => Math.Max( 1, (int)MathF.Round( _smoothedFps * ActiveFrameMultiplier ) );
	public static string FrameBadgeGlyph => IsFrameInfinite ? "∞" : "×2";
	public static string FrameEffectiveDisplay => $"{EffectiveFps} FPS";
	public static string FrameIntervalDisplay => IsFrameInfinite
		? $"∞ · {_smoothedMs / ActiveFrameMultiplier:0.1} ms"
		: $"{_smoothedMs / ActiveFrameMultiplier:0.1} ms";
	public static float ReflexLatencyMs => _smoothedMs * (IsFrameInfinite ? 0.68f : 0.84f);

	public static string ScreenTierLabel
	{
		get
		{
			int w = (int)MathF.Round( Screen.Width );
			int h = (int)MathF.Round( Screen.Height );
			if ( h >= 1800 || w >= 3200 ) return "4K";
			if ( h >= 1300 || w >= 2300 ) return "2K";
			return "1080p";
		}
	}

	// 1080p → 4K · 2K → 8K · 4K → 12K en Extrême (et palier intermédiaire en Normal)
	public static string DiamantineTargetLabel => IsDiamantineXtreme
		? (ScreenTierLabel switch { "4K" => "12K", "2K" => "8K", _ => "4K" })
		: (ScreenTierLabel switch { "4K" => "8K", "2K" => "4K", _ => "2K" });

	public static string DiamantineBoostBadge => $"{ScreenTierLabel} → {DiamantineTargetLabel}";

	public static string DiamantineSummary => IsDiamantineXtreme
		? $"Extrême · {DiamantineBoostBadge} · Upscaler RCAS + Couleurs éclatantes + Noir Absolu"
		: $"Normal · {DiamantineBoostBadge} · Upscaler RCAS équilibré & couleurs naturelles";

	public static string FrameSummary => IsFrameInfinite
		? $"Extrême · Frame Gen ∞ Infini · Anti-Chutes FPS actif (Stab. {DisplayStabilityPct}%)"
		: $"Normal · Frame Gen ×2 · Réflexe Actif & lissage anti-chutes (Stab. {DisplayStabilityPct}%)";

	public static string MultiversalSummary => IsMultiversalXtreme
		? $"Extrême · Anti-Pics Ping (±{DisplayJitterMs} ms) · Solo lourd + Serveurs 32–64+ joueurs"
		: $"Normal · Anti-Pics Ping (±{DisplayJitterMs} ms) · Solo + Serveurs ≤16 joueurs";

	public static string RenderDistanceSummary => IsRenderDistanceXtreme
		? "Extrême · ZFar 250 000 · Terrain ClipMap Max · Fog ×2,0 & culling adaptatif anti-lag"
		: "Normal · ZFar 120 000 · Horizon fluide · Fog ×1,45 & ombres équilibrées";

	public static bool IsAllXtreme =>
		IsDiamantineXtreme && IsFrameInfinite && IsMultiversalXtreme && IsRenderDistanceXtreme;

	public static void EnsureLoaded( Scene scene )
	{
		if ( _loaded ) return;
		_loaded = true;
		try
		{
			CoreRecord loaded = null;
			if ( Game.Cookies is not null )
			{
				loaded = Game.Cookies.Get<CoreRecord>( GlobalCookieKey, null );
			}
			if ( loaded is null && FileSystem.Data.FileExists( StorePath ) )
			{
				loaded = FileSystem.Data.ReadJson<CoreRecord>( StorePath );
			}
			if ( loaded is not null )
			{
				Current = Sanitize( loaded );
				Game.Cookies?.Set( GlobalCookieKey, Current );
				FileSystem.Data.WriteJson( StorePath, Current );
			}
		}
		catch ( Exception e )
		{
			Log.Warning( $"[DMLR Ultra] Load fallback: {e.Message}" );
		}
		Apply( scene, save: false );
	}

	public static void SetDiamantine( DmlrTier tier, Scene scene )
	{
		EnsureLoaded( scene );
		Current.DiamantineTier = tier;
		StatusMessage = tier == DmlrTier.Xtreme
			? $"1 · Game Diamantine : Extrême ({DiamantineBoostBadge} · DLSS/FSR Ultra + Noir Absolu)."
			: $"1 · Game Diamantine : Normal ({DiamantineBoostBadge} · Upscaler équilibré).";
		Apply( scene, save: true );
	}

	public static void SetFrameMagique( DmlrTier tier, Scene scene )
	{
		EnsureLoaded( scene );
		Current.FrameMagiqueTier = tier;
		StatusMessage = tier == DmlrTier.Xtreme
			? "2 · Frame Magique : Extrême ∞ Infini + Bouclier Anti-Chutes FPS activé."
			: "2 · Frame Magique : Normal (×2 fluide) + Stabilisateur FPS activé.";
		Apply( scene, save: true );
	}

	public static void SetMultiversal( DmlrTier tier, Scene scene )
	{
		EnsureLoaded( scene );
		Current.MultiversalTier = tier;
		StatusMessage = tier == DmlrTier.Xtreme
			? "3 · Liaison Multiverselle : Extrême (Anti-Pics Ping · Solo lourd + Multi 32–64+)."
			: "3 · Liaison Multiverselle : Normal (Anti-Pics Ping · Solo + Serveurs ≤16).";
		Apply( scene, save: true );
	}

	public static void SetRenderDistance( DmlrTier tier, Scene scene )
	{
		EnsureLoaded( scene );
		Current.RenderDistanceTier = tier;
		StatusMessage = tier == DmlrTier.Xtreme
			? "4 · Render Distance Xtreme : Extrême (250 000 + Fog ×2 + Culling adaptatif)."
			: "4 · Render Distance Xtreme : Normal (120 000 + Fog ×1,45).";
		Apply( scene, save: true );
	}

	public static void ApplyAll( DmlrTier tier, Scene scene )
	{
		EnsureLoaded( scene );
		Current.DiamantineTier = tier;
		Current.FrameMagiqueTier = tier;
		Current.MultiversalTier = tier;
		Current.RenderDistanceTier = tier;
		StatusMessage = tier == DmlrTier.Xtreme
			? "DMLR Ultra : les 4 modules sont en ⚡ EXTRÊME (DLSS/FSR + Frame Gen ∞ + Anti-Lag)."
			: "DMLR Ultra : les 4 modules sont en Normal équilibré.";
		Apply( scene, save: true );
	}

	public static void ResetCore( Scene scene )
	{
		Current = new CoreRecord();
		StatusMessage = "DMLR Ultra réinitialisé (Extrême · DLSS/FSR + Frame Gen ∞).";
		Apply( scene, save: true );
	}

	public static void SetStatus( string msg )
	{
		StatusMessage = msg ?? "";
		Revision++;
	}

	public static void Apply( Scene scene, bool save )
	{
		if ( save )
		{
			try
			{
				Game.Cookies?.Set( GlobalCookieKey, Current );
				FileSystem.Data.WriteJson( StorePath, Current );
			}
			catch ( Exception e ) { Log.Warning( $"[DMLR Ultra] Save error: {e.Message}" ); }
		}
		Revision++;
		if ( scene is not null && scene.IsValid() )
		{
			PushUniversalUniforms( scene );
			DmlrWorldEngine.ApplyImmediate( scene );
		}
	}

	public static void TickMetrics( float dt, Scene scene )
	{
		if ( !_loaded ) EnsureLoaded( scene );
		if ( dt > 0.0001f && dt < 0.5f )
		{
			float frameMs = dt * 1000f;
			_smoothedFps = MathX.Lerp( _smoothedFps, 1f / dt, 0.08f );
			_smoothedMs = MathX.Lerp( _smoothedMs, frameMs, 0.08f );

			// Détection instantanée des micro-pics de frame-time (1% Low)
			if ( frameMs > _worstWindowMs )
				_worstWindowMs = frameMs;

			// Régulateur Anti-Chutes FPS rapide à la baisse, progressif à la remontée (anti-pompage)
			_governorClock += dt;
			float govPeriod = IsFrameInfinite ? 0.35f : 0.65f;
			if ( _governorClock >= govPeriod )
			{
				_governorClock = 0f;
				float lowFps = 1000f / Math.Max( _worstWindowMs, 1f );
				float spikeRatio = _smoothedMs > 0.1f ? (_worstWindowMs / _smoothedMs) : 1f;
				_smoothedLow1Fps = MathX.Lerp( _smoothedLow1Fps, lowFps, 0.30f );
				_worstWindowMs = _smoothedMs;

				float target;
				if ( _smoothedFps < 45f || _smoothedLow1Fps < 32f ) target = 0.58f;
				else if ( _smoothedFps < 60f || _smoothedLow1Fps < 45f || spikeRatio > 1.45f ) target = 0.74f;
				else if ( _smoothedFps < 82f ) target = 0.88f;
				else target = 1.00f;

				// Réaction immédiate si chute détectée, remontée douce sinon
				float blend = target < _dynamicBias ? 0.55f : 0.18f;
				_dynamicBias = MathX.Lerp( _dynamicBias, target, blend );
			}

			// Suivi Ping + Jitter réseau (anti-pics ping) et rafraîchissement HUD lissé à 2 Hz
			_uiDisplayClock += dt;
			if ( _uiDisplayClock >= 0.50f )
			{
				_uiDisplayClock = 0f;

				float rawPing = LocalPingMs;
				float deltaPing = MathF.Abs( rawPing - _lastRawPing );
				_lastRawPing = rawPing;
				_smoothedPing = MathX.Lerp( _smoothedPing, rawPing, 0.35f );
				_smoothedJitter = MathX.Lerp( _smoothedJitter, deltaPing, 0.30f );

				DisplayFps = NativeFps;
				DisplayLow1Fps = Math.Clamp( (int)MathF.Round( _smoothedLow1Fps ), 1, DisplayFps );
				DisplayStabilityPct = Math.Clamp( (int)MathF.Round( (DisplayLow1Fps / (float)Math.Max( 1, DisplayFps )) * 100f ), 50, 100 );
				DisplayPingMs = Math.Max( 1, (int)MathF.Round( _smoothedPing ) );
				DisplayJitterMs = Math.Max( 0, (int)MathF.Round( _smoothedJitter ) );
			}
		}

		if ( scene is not null && scene.IsValid() && (_lastPushedRevision != Revision || MathF.Abs( _lastPushedBias - _dynamicBias ) > 0.01f) )
		{
			_lastPushedRevision = Revision;
			_lastPushedBias = _dynamicBias;
			PushUniversalUniforms( scene );
		}
	}

	public static void PushUniversalUniforms( Scene scene )
	{
		if ( scene?.RenderAttributes is null ) return;

		float vegScale = VegetationDistanceScale * MathX.Lerp( 0.78f, 1.0f, _dynamicBias );
		float diamBoost = IsDiamantineXtreme ? 1.0f : 0.55f;
		float deepBlack = IsDiamantineXtreme ? 1.0f : 0.35f;
		float frameCode = IsFrameInfinite ? 99f : 2f;

		var perfVec = new Vector4( vegScale, vegScale, _dynamicBias, 1f );
		var dlssVec = new Vector4( _dynamicBias, CrystalSharpness, frameCode, IsFrameInfinite ? 5f : 3f );
		var boostVec = new Vector4( diamBoost, IsRenderDistanceXtreme ? 1.0f : 0.55f, deepBlack, frameCode );
		var multiVec = new Vector4( IsMultiversalXtreme ? 1f : 0f, DisplayJitterMs, 1f, ConnectedPlayers );

		scene.RenderAttributes.Set( "DmlrPerfQuality", perfVec );
		scene.RenderAttributes.Set( "DmlrDiamantineBoost", boostVec );
		scene.RenderAttributes.Set( "DmlrMultiversalState", multiVec );
		scene.RenderAttributes.Set( "FantasyPerfQuality", perfVec );
		scene.RenderAttributes.Set( "g_vDlss5State", dlssVec );
		scene.RenderAttributes.Set( "g_vDiamantineMapBoost", boostVec );
		scene.RenderAttributes.Set( "g_vMultiversalState", multiVec );
	}

	private static CoreRecord Sanitize( CoreRecord d )
	{
		if ( !Enum.IsDefined( typeof( DmlrTier ), d.DiamantineTier ) ) d.DiamantineTier = DmlrTier.Xtreme;
		if ( !Enum.IsDefined( typeof( DmlrTier ), d.FrameMagiqueTier ) ) d.FrameMagiqueTier = DmlrTier.Xtreme;
		if ( !Enum.IsDefined( typeof( DmlrTier ), d.MultiversalTier ) ) d.MultiversalTier = DmlrTier.Xtreme;
		if ( !Enum.IsDefined( typeof( DmlrTier ), d.RenderDistanceTier ) ) d.RenderDistanceTier = DmlrTier.Xtreme;
		return d;
	}
}