Files
grass-cutters/Assets/Scripts/Net/SteamManager.cs
NiemandKG d1c3761e58 Grass Cutters Together: the project as of moon-sweepers f3666f0
A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and
Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date.
Images, audio, models and binaries go through Git LFS (.gitattributes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 18:44:40 +06:00

171 lines
6.6 KiB
C#

using System;
using Steamworks;
using UnityEngine;
namespace GrassCutter
{
/// <summary>Owns the Steam API lifetime (AppID 5551720, Grass Cutters Together), pumps callbacks, tracks the overlay.</summary>
[DefaultExecutionOrder(-1000)]
public class SteamManager : MonoBehaviour
{
public const uint AppId = 5551720;
public static SteamManager Instance { get; private set; }
public static bool Initialized { get; private set; }
public static bool OverlayActive { get; private set; }
public static event Action<bool> OverlayChanged;
Callback<GameOverlayActivated_t> _overlayCb;
SteamAPIWarningMessageHook_t _warningHook;
public static CSteamID MySteamId => Initialized ? SteamUser.GetSteamID() : CSteamID.Nil;
public static string MyName
{
get
{
if (Initialized) return SteamFriends.GetPersonaName();
return string.IsNullOrEmpty(Environment.UserName) ? "Popper" : Environment.UserName;
}
}
void Awake()
{
if (Instance != null) { Destroy(gameObject); return; }
Instance = this;
DontDestroyOnLoad(gameObject);
Debug.Log("[Steam] initializing…");
if (CommandLine.Has("-nosteam")) { Debug.Log("[Steam] disabled by -nosteam"); return; }
if (!Packsize.Test()) Debug.LogError("[Steam] Packsize test failed — wrong Steamworks.NET platform binaries.");
if (!DllCheck.Test()) Debug.LogError("[Steam] DllCheck failed — steam_api64.dll mismatch.");
try
{
#if !UNITY_EDITOR
// When launched outside Steam without steam_appid.txt this relaunches through Steam.
// Dev builds ship steam_appid.txt next to the exe, so skip the check entirely there.
bool devAppId = System.IO.File.Exists(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Application.dataPath) ?? ".", "steam_appid.txt"));
if (!devAppId && SteamAPI.RestartAppIfNecessary(new AppId_t(AppId)))
{
Debug.Log("[Steam] Relaunching through Steam");
Application.Quit();
return;
}
#endif
var res = SteamAPI.InitEx(out string err);
Initialized = res == ESteamAPIInitResult.k_ESteamAPIInitResult_OK;
if (!Initialized)
{
Debug.LogWarning($"[Steam] Init failed ({res}): {err}. Is Steam running? Falling back to offline mode.");
return;
}
}
catch (DllNotFoundException e)
{
Debug.LogError("[Steam] steam_api64.dll not found: " + e.Message);
return;
}
_warningHook = (severity, text) => Debug.LogWarning("[Steam] " + text);
SteamClient.SetWarningMessageHook(_warningHook);
_overlayCb = Callback<GameOverlayActivated_t>.Create(OnOverlay);
// Warm up the relay network so P2P connects fast when the player hosts/joins.
SteamNetworkingUtils.InitRelayNetworkAccess();
Debug.Log($"[Steam] OK as {SteamFriends.GetPersonaName()} ({SteamUser.GetSteamID()}), AppID {SteamUtils.GetAppID()}");
Invoke(nameof(LogOverlay), 3f);
}
/// <summary>Player.log line that tells whether Shift+Tab can work in this run (overlay hooked + graphics API).</summary>
void LogOverlay()
{
if (!Initialized) return;
bool hooked = false;
try
{
foreach (System.Diagnostics.ProcessModule m in System.Diagnostics.Process.GetCurrentProcess().Modules)
if (m.ModuleName.StartsWith("GameOverlayRenderer", StringComparison.OrdinalIgnoreCase)) { hooked = true; break; }
}
catch (Exception e) { Debug.LogWarning("[Steam] module scan failed: " + e.Message); }
Debug.Log($"[Steam] overlay: enabled={SteamUtils.IsOverlayEnabled()} rendererLoaded={hooked} gfx={SystemInfo.graphicsDeviceType}");
}
void OnOverlay(GameOverlayActivated_t e)
{
OverlayActive = e.m_bActive != 0;
OverlayChanged?.Invoke(OverlayActive);
}
void Update()
{
if (Initialized) SteamAPI.RunCallbacks();
}
void OnApplicationQuit()
{
Shutdown();
}
void OnDestroy()
{
if (Instance == this) Shutdown();
}
static void Shutdown()
{
if (!Initialized) return;
Initialized = false;
SteamAPI.Shutdown();
}
public static void SetRichPresence(string status, string connect = null)
{
if (!Initialized) return;
SteamFriends.SetRichPresence("status", status);
SteamFriends.SetRichPresence("steam_display", "#Status");
SteamFriends.SetRichPresence("connect", connect ?? "");
}
/// <summary>Returns the Steam avatar for a user as a texture (may be null until Steam has downloaded it).</summary>
public static Texture2D GetAvatar(CSteamID id)
{
if (!Initialized) return null;
int handle = SteamFriends.GetLargeFriendAvatar(id);
if (handle <= 0) return null;
if (!SteamUtils.GetImageSize(handle, out uint w, out uint h) || w == 0) return null;
var data = new byte[w * h * 4];
if (!SteamUtils.GetImageRGBA(handle, data, data.Length)) return null;
var tex = new Texture2D((int)w, (int)h, TextureFormat.RGBA32, false);
// Steam images are top-down; flip rows for Unity.
var flipped = new byte[data.Length];
int row = (int)w * 4;
for (int y = 0; y < h; y++) Buffer.BlockCopy(data, y * row, flipped, ((int)h - 1 - y) * row, row);
tex.LoadRawTextureData(flipped);
tex.Apply();
return tex;
}
}
public static class CommandLine
{
static string[] _args;
static string[] Args => _args ??= Environment.GetCommandLineArgs();
public static bool Has(string flag)
{
foreach (var a in Args) if (string.Equals(a, flag, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
public static string Get(string flag, string fallback = null)
{
var a = Args;
for (int i = 0; i < a.Length - 1; i++)
if (string.Equals(a[i], flag, StringComparison.OrdinalIgnoreCase)) return a[i + 1];
return fallback;
}
}
}