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>
This commit is contained in:
183
Assets/Scripts/Net/LanBeacon.cs
Normal file
183
Assets/Scripts/Net/LanBeacon.cs
Normal file
@ -0,0 +1,183 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public struct LanGame
|
||||
{
|
||||
public string ip, name;
|
||||
public ushort port;
|
||||
public int members, max;
|
||||
public float seen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Games on the local network find each other without Steam: a LAN host shouts its port once a second on UDP, and the game
|
||||
/// browser listens. Everything runs on the main thread from <see cref="Tick"/>; the sockets never block.
|
||||
/// </summary>
|
||||
public static class LanBeacon
|
||||
{
|
||||
public const int Port = 47797;
|
||||
const string Tag = "GCT1";
|
||||
const float Every = 1f, Forget = 4f;
|
||||
|
||||
static UdpClient _send, _listen;
|
||||
static string _name;
|
||||
static ushort _gamePort;
|
||||
static float _next;
|
||||
static readonly string Nonce = Guid.NewGuid().ToString("N").Substring(0, 8);
|
||||
static readonly Dictionary<string, LanGame> _found = new Dictionary<string, LanGame>();
|
||||
static List<IPEndPoint> _targets;
|
||||
|
||||
public static bool Hosting => _send != null;
|
||||
|
||||
// ───────────────────────── hosting ─────────────────────────
|
||||
|
||||
public static void Host(string name, ushort gamePort)
|
||||
{
|
||||
Stop();
|
||||
try
|
||||
{
|
||||
_send = new UdpClient(AddressFamily.InterNetwork) { EnableBroadcast = true };
|
||||
_name = name.Replace("|", "/");
|
||||
_gamePort = gamePort;
|
||||
_targets = Targets();
|
||||
_next = 0f;
|
||||
Debug.Log($"[LAN] announcing on port {Port}, game on {gamePort}, {_targets.Count} target(s)");
|
||||
}
|
||||
catch (Exception e) { Debug.LogWarning("[LAN] can't announce: " + e.Message); _send = null; }
|
||||
}
|
||||
|
||||
public static void Stop()
|
||||
{
|
||||
_send?.Close();
|
||||
_send = null;
|
||||
}
|
||||
|
||||
/// <summary>The broadcast address of every network the PC is on, plus itself for a second copy on the same PC.</summary>
|
||||
static List<IPEndPoint> Targets()
|
||||
{
|
||||
var list = new List<IPEndPoint> { new IPEndPoint(IPAddress.Broadcast, Port), new IPEndPoint(IPAddress.Loopback, Port) };
|
||||
try
|
||||
{
|
||||
foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
|
||||
{
|
||||
if (nic.OperationalStatus != OperationalStatus.Up || nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
|
||||
foreach (var a in nic.GetIPProperties().UnicastAddresses)
|
||||
{
|
||||
if (a.Address.AddressFamily != AddressFamily.InterNetwork || a.IPv4Mask == null) continue;
|
||||
var ip = a.Address.GetAddressBytes();
|
||||
var mask = a.IPv4Mask.GetAddressBytes();
|
||||
if (mask.Length != 4 || mask[0] == 0) continue;
|
||||
for (int i = 0; i < 4; i++) ip[i] = (byte)(ip[i] | ~mask[i]);
|
||||
var to = new IPEndPoint(new IPAddress(ip), Port);
|
||||
if (!list.Exists(t => t.Equals(to))) list.Add(to);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e) { Debug.LogWarning("[LAN] can't list networks: " + e.Message); }
|
||||
return list;
|
||||
}
|
||||
|
||||
// ───────────────────────── looking ─────────────────────────
|
||||
|
||||
public static void Listen()
|
||||
{
|
||||
if (_listen != null) return;
|
||||
_found.Clear();
|
||||
try
|
||||
{
|
||||
_listen = new UdpClient(AddressFamily.InterNetwork);
|
||||
_listen.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
_listen.Client.Bind(new IPEndPoint(IPAddress.Any, Port));
|
||||
}
|
||||
catch (Exception e) { Debug.LogWarning("[LAN] can't listen: " + e.Message); _listen?.Close(); _listen = null; }
|
||||
}
|
||||
|
||||
public static void StopListening()
|
||||
{
|
||||
_listen?.Close();
|
||||
_listen = null;
|
||||
}
|
||||
|
||||
/// <summary>Games heard in the last few seconds, other than our own.</summary>
|
||||
public static List<LanGame> Found()
|
||||
{
|
||||
var list = new List<LanGame>();
|
||||
foreach (var g in _found.Values) if (Time.unscaledTime - g.seen < Forget) list.Add(g);
|
||||
list.Sort((a, b) => string.CompareOrdinal(a.name, b.name));
|
||||
return list;
|
||||
}
|
||||
|
||||
// ───────────────────────── pump ─────────────────────────
|
||||
|
||||
public static void Tick(int members, int max)
|
||||
{
|
||||
if (_send != null && Time.unscaledTime >= _next)
|
||||
{
|
||||
_next = Time.unscaledTime + Every;
|
||||
var bytes = Encoding.UTF8.GetBytes($"{Tag}|{NetSession.Version}|{Nonce}|{_gamePort}|{members}|{max}|{_name}");
|
||||
foreach (var to in _targets)
|
||||
try { _send.Send(bytes, bytes.Length, to); }
|
||||
catch (SocketException) { } // a network that went away: the others still hear
|
||||
}
|
||||
|
||||
if (_listen == null) return;
|
||||
try
|
||||
{
|
||||
while (_listen.Available > 0)
|
||||
{
|
||||
var from = new IPEndPoint(IPAddress.Any, 0);
|
||||
var data = _listen.Receive(ref from);
|
||||
Heard(Encoding.UTF8.GetString(data), from.Address);
|
||||
}
|
||||
}
|
||||
catch (Exception e) { Debug.LogWarning("[LAN] listening stopped: " + e.Message); StopListening(); }
|
||||
}
|
||||
|
||||
static void Heard(string msg, IPAddress from)
|
||||
{
|
||||
var p = msg.Split(new[] { '|' }, 7);
|
||||
if (p.Length < 7 || p[0] != Tag || p[1] != NetSession.Version) return;
|
||||
if (p[2] == Nonce) return;
|
||||
if (!ushort.TryParse(p[3], out ushort port) || !int.TryParse(p[4], out int members) || !int.TryParse(p[5], out int max)) return;
|
||||
string key = p[2];
|
||||
// the same host is heard on the network and on loopback: keep the network address, so others can type it too
|
||||
string ip = from.ToString();
|
||||
if (_found.TryGetValue(key, out var old) && IPAddress.IsLoopback(from) && !IPAddress.Parse(old.ip).Equals(IPAddress.Loopback)) ip = old.ip;
|
||||
_found[key] = new LanGame { ip = ip, port = port, members = members, max = max, name = p[6], seen = Time.unscaledTime };
|
||||
}
|
||||
|
||||
// ───────────────────────── ports ─────────────────────────
|
||||
|
||||
/// <summary>The wanted port if nothing on this PC holds it, otherwise any free one.</summary>
|
||||
public static ushort FreePort(ushort want)
|
||||
{
|
||||
try { using (new UdpClient(want)) return want; }
|
||||
catch (SocketException) { }
|
||||
using (var any = new UdpClient(0)) return (ushort)((IPEndPoint)any.Client.LocalEndPoint).Port;
|
||||
}
|
||||
|
||||
/// <summary>This PC's addresses on the local network, for players who type them in.</summary>
|
||||
public static string MyAddresses()
|
||||
{
|
||||
var list = new List<string>();
|
||||
try
|
||||
{
|
||||
foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
|
||||
{
|
||||
if (nic.OperationalStatus != OperationalStatus.Up || nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
|
||||
foreach (var a in nic.GetIPProperties().UnicastAddresses)
|
||||
if (a.Address.AddressFamily == AddressFamily.InterNetwork && !a.Address.ToString().StartsWith("169.254.")) list.Add(a.Address.ToString());
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
return string.Join(", ", list);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Net/LanBeacon.cs.meta
Normal file
2
Assets/Scripts/Net/LanBeacon.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8bec1fc82f385b447bfdf6b2a7b84fd5
|
||||
375
Assets/Scripts/Net/NetSession.cs
Normal file
375
Assets/Scripts/Net/NetSession.cs
Normal file
@ -0,0 +1,375 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using Steamworks;
|
||||
using Unity.Netcode;
|
||||
using Unity.Netcode.Transports.UTP;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public struct LobbyInfo
|
||||
{
|
||||
public CSteamID id;
|
||||
public string name;
|
||||
public int members, max;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Front door for multiplayer: Steam lobbies (create / browse / invite / join from friends list)
|
||||
/// plus UnityTransport for a solo game, a game on the local network and local multi-instance testing.
|
||||
/// </summary>
|
||||
public class NetSession : MonoBehaviour
|
||||
{
|
||||
public const string GameKey = "grasscutter";
|
||||
public const string Version = "0.1";
|
||||
public const int MaxPlayers = 16;
|
||||
const ushort LocalPort = 7777;
|
||||
|
||||
public static NetSession Instance { get; private set; }
|
||||
|
||||
public enum State { Menu, Connecting, InGame }
|
||||
public enum LobbyKind { Friends, Invite, Public, Solo, Lan }
|
||||
public State Current { get; private set; } = State.Menu;
|
||||
public CSteamID LobbyId { get; private set; } = CSteamID.Nil;
|
||||
public LobbyKind Kind { get; private set; }
|
||||
public bool InLobby => LobbyId.IsValid() && LobbyId != CSteamID.Nil;
|
||||
/// <summary>The port a LAN game listens on, for the pause screen to show.</summary>
|
||||
public ushort LanPort { get; private set; }
|
||||
|
||||
public event Action<string> StatusChanged;
|
||||
public event Action<string> Failed;
|
||||
/// <summary>Steam wants to join another of our lobbies while a game is on: the UI asks.</summary>
|
||||
public event Action<CSteamID> JoinAsked;
|
||||
public event Action<List<LobbyInfo>> LobbyListReceived;
|
||||
public event Action Started;
|
||||
public event Action Ended;
|
||||
|
||||
NetworkManager _nm;
|
||||
SteamSocketsTransport _steamTransport;
|
||||
UnityTransport _utp;
|
||||
|
||||
Callback<LobbyCreated_t> _lobbyCreated;
|
||||
Callback<LobbyEnter_t> _lobbyEnter;
|
||||
Callback<LobbyDataUpdate_t> _lobbyData;
|
||||
CSteamID _asked = CSteamID.Nil;
|
||||
Callback<GameLobbyJoinRequested_t> _joinRequested;
|
||||
Callback<LobbyMatchList_t> _lobbyList;
|
||||
Callback<GameRichPresenceJoinRequested_t> _richJoin;
|
||||
|
||||
bool _leaving;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
Instance = this;
|
||||
_nm = GetComponent<NetworkManager>();
|
||||
_steamTransport = GetComponent<SteamSocketsTransport>();
|
||||
_utp = GetComponent<UnityTransport>();
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
_nm.ConnectionApprovalCallback = Approve;
|
||||
_nm.OnClientDisconnectCallback += OnClientDisconnect;
|
||||
_nm.OnClientConnectedCallback += OnClientConnected;
|
||||
|
||||
if (SteamManager.Initialized)
|
||||
{
|
||||
_lobbyCreated = Callback<LobbyCreated_t>.Create(OnLobbyCreated);
|
||||
_lobbyEnter = Callback<LobbyEnter_t>.Create(OnLobbyEnter);
|
||||
_joinRequested = Callback<GameLobbyJoinRequested_t>.Create(e => AskToJoin(e.m_steamIDLobby));
|
||||
_lobbyData = Callback<LobbyDataUpdate_t>.Create(OnLobbyData);
|
||||
_lobbyList = Callback<LobbyMatchList_t>.Create(OnLobbyList);
|
||||
_richJoin = Callback<GameRichPresenceJoinRequested_t>.Create(e => ParseConnectString(e.m_rgchConnect));
|
||||
SteamManager.SetRichPresence("In the main menu");
|
||||
}
|
||||
|
||||
// Launched via "Join game" from the Steam friends list while the game was closed.
|
||||
var arg = CommandLine.Get("+connect_lobby");
|
||||
if (!string.IsNullOrEmpty(arg) && ulong.TryParse(arg, out ulong lobby)) JoinLobby(new CSteamID(lobby));
|
||||
else if (CommandLine.Has("-localhost")) HostLocal();
|
||||
else if (CommandLine.Get("-connect") is string addr && ParseAddress(addr, out var ip, out var port)) JoinLocal(ip, port);
|
||||
}
|
||||
|
||||
void ParseConnectString(string s)
|
||||
{
|
||||
if (string.IsNullOrEmpty(s)) return;
|
||||
var parts = s.Split(' ');
|
||||
for (int i = 0; i < parts.Length - 1; i++)
|
||||
if (parts[i] == "+connect_lobby" && ulong.TryParse(parts[i + 1], out ulong id)) AskToJoin(new CSteamID(id));
|
||||
}
|
||||
|
||||
// ───────────────────────── hosting ─────────────────────────
|
||||
|
||||
public void Host(LobbyKind kind)
|
||||
{
|
||||
if (Current != State.Menu) return;
|
||||
Kind = kind;
|
||||
if (kind == LobbyKind.Lan) { HostLan(); return; }
|
||||
if (kind == LobbyKind.Solo || !SteamManager.Initialized) { Kind = LobbyKind.Solo; HostSolo(); return; }
|
||||
SetState(State.Connecting, Loc.Pack("Creating lobby…"));
|
||||
SteamMatchmaking.CreateLobby(kind == LobbyKind.Public ? ELobbyType.k_ELobbyTypePublic : kind == LobbyKind.Invite ? ELobbyType.k_ELobbyTypePrivate : ELobbyType.k_ELobbyTypeFriendsOnly, MaxPlayers);
|
||||
}
|
||||
|
||||
void OnLobbyCreated(LobbyCreated_t e)
|
||||
{
|
||||
if (e.m_eResult != EResult.k_EResultOK)
|
||||
{
|
||||
Fail(Loc.Pack("Couldn't create a Steam lobby ({0})", e.m_eResult.ToString()));
|
||||
return;
|
||||
}
|
||||
LobbyId = new CSteamID(e.m_ulSteamIDLobby);
|
||||
SteamMatchmaking.SetLobbyData(LobbyId, "game", GameKey);
|
||||
SteamMatchmaking.SetLobbyData(LobbyId, "ver", Version);
|
||||
SteamMatchmaking.SetLobbyData(LobbyId, "name", SteamManager.MyName + "'s Mow Base");
|
||||
SteamMatchmaking.SetLobbyData(LobbyId, "host", SteamManager.MySteamId.m_SteamID.ToString());
|
||||
SteamMatchmaking.SetLobbyJoinable(LobbyId, true);
|
||||
|
||||
UseTransport(_steamTransport);
|
||||
if (!_nm.StartHost()) { Fail(Loc.Pack("Failed to start host")); return; }
|
||||
SteamManager.SetRichPresence("Mowing an overgrown planet", "+connect_lobby " + LobbyId.m_SteamID);
|
||||
EnterGame();
|
||||
}
|
||||
|
||||
/// <summary>Nobody else can come in: the server listens on this PC only, on whatever port is free.</summary>
|
||||
void HostSolo()
|
||||
{
|
||||
SetState(State.Connecting, Loc.Pack("Starting…"));
|
||||
UseTransport(_utp);
|
||||
_utp.SetConnectionData("127.0.0.1", LanBeacon.FreePort(LocalPort), "127.0.0.1");
|
||||
if (!_nm.StartHost()) { Fail(Loc.Pack("Failed to start the game")); return; }
|
||||
EnterGame();
|
||||
}
|
||||
|
||||
/// <summary>Open to the local network, and announced on it so the game browser on other PCs lists it.</summary>
|
||||
void HostLan()
|
||||
{
|
||||
SetState(State.Connecting, Loc.Pack("Starting a LAN game…"));
|
||||
UseTransport(_utp);
|
||||
LanPort = LanBeacon.FreePort(LocalPort);
|
||||
_utp.SetConnectionData("127.0.0.1", LanPort, "0.0.0.0");
|
||||
if (!_nm.StartHost()) { Fail(Loc.Pack("Failed to start a LAN game (port {0})", LanPort.ToString())); return; }
|
||||
LanBeacon.Host(SteamManager.MyName + "'s Mow Base", LanPort);
|
||||
EnterGame();
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (LanBeacon.Hosting && Current == State.InGame) LanBeacon.Tick(_nm.ConnectedClientsIds.Count, MaxPlayers);
|
||||
else LanBeacon.Tick(0, MaxPlayers);
|
||||
}
|
||||
|
||||
/// <summary>Test runs: -localhost hosts on port 7777 for -connect instances on the same PC.</summary>
|
||||
public void HostLocal()
|
||||
{
|
||||
if (Current != State.Menu) return;
|
||||
SetState(State.Connecting, Loc.Pack("Starting…"));
|
||||
UseTransport(_utp);
|
||||
// a dev bot started while someone plays on this PC takes the next free port instead of failing (or -port N)
|
||||
_utp.SetConnectionData("127.0.0.1", ushort.TryParse(CommandLine.Get("-port"), out var port) ? port : CommandLine.Has("-autodemo") ? LanBeacon.FreePort(LocalPort) : LocalPort, "0.0.0.0");
|
||||
if (!_nm.StartHost()) { Fail(Loc.Pack("Failed to start host")); return; }
|
||||
EnterGame();
|
||||
}
|
||||
|
||||
// ───────────────────────── joining ─────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Steam was asked to join a lobby. In the menu that just happens. In a game, whoever is playing is asked first, and
|
||||
/// only about our own lobbies: on the shared test AppID an invite can come from any other game.
|
||||
/// </summary>
|
||||
void AskToJoin(CSteamID lobby)
|
||||
{
|
||||
if (CommandLine.Has("-autodemo")) return;
|
||||
if (Current != State.InGame) { JoinLobby(lobby); return; }
|
||||
if (lobby == LobbyId) return;
|
||||
_asked = lobby;
|
||||
SteamMatchmaking.RequestLobbyData(lobby);
|
||||
}
|
||||
|
||||
void OnLobbyData(LobbyDataUpdate_t e)
|
||||
{
|
||||
if (e.m_ulSteamIDLobby != _asked.m_SteamID || e.m_ulSteamIDMember != e.m_ulSteamIDLobby) return;
|
||||
var lobby = _asked;
|
||||
_asked = CSteamID.Nil;
|
||||
if (e.m_bSuccess != 0 && SteamMatchmaking.GetLobbyData(lobby, "game") == GameKey) JoinAsked?.Invoke(lobby);
|
||||
else Failed?.Invoke(Loc.Pack("That invite isn't for a Grass Cutters Together game"));
|
||||
}
|
||||
|
||||
public void JoinLobby(CSteamID lobby)
|
||||
{
|
||||
if (!SteamManager.Initialized) return;
|
||||
if (Current == State.InGame) Leave();
|
||||
if (Current == State.Connecting) return;
|
||||
SetState(State.Connecting, Loc.Pack("Joining lobby…"));
|
||||
SteamMatchmaking.JoinLobby(lobby);
|
||||
}
|
||||
|
||||
void OnLobbyEnter(LobbyEnter_t e)
|
||||
{
|
||||
var lobby = new CSteamID(e.m_ulSteamIDLobby);
|
||||
// The host also receives LobbyEnter for its own lobby — ignore that one.
|
||||
if (_nm.IsHost && lobby == LobbyId) return;
|
||||
if (e.m_EChatRoomEnterResponse != (uint)EChatRoomEnterResponse.k_EChatRoomEnterResponseSuccess)
|
||||
{
|
||||
Fail(Loc.Pack("Couldn't join the lobby (it may be full or closed)"));
|
||||
return;
|
||||
}
|
||||
if (SteamMatchmaking.GetLobbyData(lobby, "game") != GameKey)
|
||||
{
|
||||
SteamMatchmaking.LeaveLobby(lobby);
|
||||
Fail(Loc.Pack("That lobby isn't a Grass Cutters Together game"));
|
||||
return;
|
||||
}
|
||||
LobbyId = lobby;
|
||||
var owner = SteamMatchmaking.GetLobbyOwner(lobby);
|
||||
if (owner == SteamManager.MySteamId) { Fail(Loc.Pack("You are the owner of this lobby")); return; }
|
||||
_steamTransport.ConnectToSteamId = owner.m_SteamID;
|
||||
UseTransport(_steamTransport);
|
||||
SetState(State.Connecting, Loc.Pack("Connecting to {0}…", SteamFriends.GetFriendPersonaName(owner)));
|
||||
_nm.NetworkConfig.ConnectionData = Encoding.UTF8.GetBytes(Version);
|
||||
if (!_nm.StartClient()) Fail(Loc.Pack("Failed to start client"));
|
||||
}
|
||||
|
||||
/// <summary>"192.168.1.20" or "192.168.1.20:7778": a LAN game, by address.</summary>
|
||||
public static bool ParseAddress(string text, out string ip, out ushort port)
|
||||
{
|
||||
ip = null; port = LocalPort;
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
text = text.Trim();
|
||||
int colon = text.LastIndexOf(':');
|
||||
if (colon > 0)
|
||||
{
|
||||
if (!ushort.TryParse(text.Substring(colon + 1), out port) || port == 0) return false;
|
||||
text = text.Substring(0, colon);
|
||||
}
|
||||
if (!System.Net.IPAddress.TryParse(text, out var addr) || addr.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) return false;
|
||||
ip = addr.ToString();
|
||||
return true;
|
||||
}
|
||||
|
||||
public void JoinLocal(string ip, ushort port = LocalPort)
|
||||
{
|
||||
if (Current != State.Menu) return;
|
||||
SetState(State.Connecting, Loc.Pack("Connecting to {0}…", ip + (port == LocalPort ? "" : ":" + port)));
|
||||
UseTransport(_utp);
|
||||
Kind = LobbyKind.Lan;
|
||||
_utp.SetConnectionData(ip, port);
|
||||
_nm.NetworkConfig.ConnectionData = Encoding.UTF8.GetBytes(Version);
|
||||
if (!_nm.StartClient()) Fail(Loc.Pack("Failed to start client"));
|
||||
}
|
||||
|
||||
public void RequestLobbyList()
|
||||
{
|
||||
if (!SteamManager.Initialized) { LobbyListReceived?.Invoke(new List<LobbyInfo>()); return; }
|
||||
SteamMatchmaking.AddRequestLobbyListStringFilter("game", GameKey, ELobbyComparison.k_ELobbyComparisonEqual);
|
||||
SteamMatchmaking.AddRequestLobbyListFilterSlotsAvailable(1);
|
||||
SteamMatchmaking.AddRequestLobbyListDistanceFilter(ELobbyDistanceFilter.k_ELobbyDistanceFilterWorldwide);
|
||||
SteamMatchmaking.AddRequestLobbyListResultCountFilter(50);
|
||||
SteamMatchmaking.RequestLobbyList();
|
||||
}
|
||||
|
||||
void OnLobbyList(LobbyMatchList_t e)
|
||||
{
|
||||
var list = new List<LobbyInfo>();
|
||||
for (int i = 0; i < e.m_nLobbiesMatching; i++)
|
||||
{
|
||||
var id = SteamMatchmaking.GetLobbyByIndex(i);
|
||||
if (SteamMatchmaking.GetLobbyData(id, "ver") != Version) continue;
|
||||
list.Add(new LobbyInfo
|
||||
{
|
||||
id = id,
|
||||
name = SteamMatchmaking.GetLobbyData(id, "name"),
|
||||
members = SteamMatchmaking.GetNumLobbyMembers(id),
|
||||
max = SteamMatchmaking.GetLobbyMemberLimit(id),
|
||||
});
|
||||
}
|
||||
LobbyListReceived?.Invoke(list);
|
||||
}
|
||||
|
||||
public void InviteFriends()
|
||||
{
|
||||
if (SteamManager.Initialized && InLobby) SteamFriends.ActivateGameOverlayInviteDialog(LobbyId);
|
||||
}
|
||||
|
||||
// ───────────────────────── lifecycle ─────────────────────────
|
||||
|
||||
void UseTransport(NetworkTransport t) => _nm.NetworkConfig.NetworkTransport = t;
|
||||
|
||||
void Approve(NetworkManager.ConnectionApprovalRequest req, NetworkManager.ConnectionApprovalResponse res)
|
||||
{
|
||||
bool isHostSelf = req.ClientNetworkId == NetworkManager.ServerClientId;
|
||||
string ver = req.Payload != null && req.Payload.Length > 0 ? Encoding.UTF8.GetString(req.Payload) : "";
|
||||
bool full = _nm.ConnectedClientsIds.Count >= MaxPlayers;
|
||||
res.Approved = isHostSelf || (!full && ver == Version);
|
||||
res.Reason = full ? Loc.Pack("The depot is full") : Loc.Pack("Version mismatch");
|
||||
res.CreatePlayerObject = true;
|
||||
res.Pending = false;
|
||||
}
|
||||
|
||||
void OnClientConnected(ulong id)
|
||||
{
|
||||
if (!_nm.IsServer && id == _nm.LocalClientId) EnterGame();
|
||||
}
|
||||
|
||||
void OnClientDisconnect(ulong id)
|
||||
{
|
||||
if (_leaving) return;
|
||||
// We (a client) were disconnected from the host.
|
||||
if (!_nm.IsServer && (id == _nm.LocalClientId || id == NetworkManager.ServerClientId))
|
||||
{
|
||||
string reason = string.IsNullOrEmpty(_nm.DisconnectReason) ? Loc.Pack("Lost connection to the host") : _nm.DisconnectReason;
|
||||
Leave(reason);
|
||||
}
|
||||
}
|
||||
|
||||
void EnterGame()
|
||||
{
|
||||
SetState(State.InGame, "");
|
||||
if (!SteamManager.Initialized || !InLobby) SteamManager.SetRichPresence("Mowing an overgrown planet");
|
||||
Started?.Invoke();
|
||||
}
|
||||
|
||||
public void Leave(string reason = null)
|
||||
{
|
||||
if (Current == State.Menu && !_nm.IsListening) return;
|
||||
_leaving = true;
|
||||
try
|
||||
{
|
||||
if (_nm.IsServer && TeamState.Instance) TeamState.Instance.Save();
|
||||
if (_nm.IsListening) _nm.Shutdown();
|
||||
LanBeacon.Stop();
|
||||
if (SteamManager.Initialized && InLobby) SteamMatchmaking.LeaveLobby(LobbyId);
|
||||
LobbyId = CSteamID.Nil;
|
||||
SteamManager.SetRichPresence("In the main menu");
|
||||
}
|
||||
finally { _leaving = false; }
|
||||
SetState(State.Menu, "");
|
||||
Ended?.Invoke();
|
||||
if (!string.IsNullOrEmpty(reason)) Failed?.Invoke(reason);
|
||||
}
|
||||
|
||||
void Fail(string msg)
|
||||
{
|
||||
Debug.LogWarning("[Net] " + msg);
|
||||
if (_nm.IsListening) _nm.Shutdown();
|
||||
LanBeacon.Stop();
|
||||
if (SteamManager.Initialized && InLobby) SteamMatchmaking.LeaveLobby(LobbyId);
|
||||
LobbyId = CSteamID.Nil;
|
||||
SetState(State.Menu, "");
|
||||
Failed?.Invoke(msg);
|
||||
}
|
||||
|
||||
void SetState(State s, string status)
|
||||
{
|
||||
Current = s;
|
||||
StatusChanged?.Invoke(status);
|
||||
}
|
||||
|
||||
void OnApplicationQuit()
|
||||
{
|
||||
LanBeacon.Stop();
|
||||
LanBeacon.StopListening();
|
||||
if (SteamManager.Initialized && InLobby) SteamMatchmaking.LeaveLobby(LobbyId);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Net/NetSession.cs.meta
Normal file
2
Assets/Scripts/Net/NetSession.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 370390ac5be896d4aa7587f486aeb15d
|
||||
170
Assets/Scripts/Net/SteamManager.cs
Normal file
170
Assets/Scripts/Net/SteamManager.cs
Normal file
@ -0,0 +1,170 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Net/SteamManager.cs.meta
Normal file
2
Assets/Scripts/Net/SteamManager.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8274c665a87cea14d9a402ed2b7ad3ef
|
||||
273
Assets/Scripts/Net/SteamSocketsTransport.cs
Normal file
273
Assets/Scripts/Net/SteamSocketsTransport.cs
Normal file
@ -0,0 +1,273 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using Steamworks;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Netcode for GameObjects transport over Steam Networking Sockets (P2P through Valve's relay).
|
||||
/// The host listens on virtual port 0; clients connect to the host's SteamID.
|
||||
/// </summary>
|
||||
public class SteamSocketsTransport : NetworkTransport
|
||||
{
|
||||
const int MaxMessagesPerPoll = 256;
|
||||
|
||||
public ulong ConnectToSteamId;
|
||||
|
||||
struct Pending
|
||||
{
|
||||
public NetworkEvent type;
|
||||
public ulong clientId;
|
||||
public byte[] data;
|
||||
public int length;
|
||||
}
|
||||
|
||||
readonly Queue<Pending> _events = new Queue<Pending>();
|
||||
readonly Dictionary<ulong, HSteamNetConnection> _byClient = new Dictionary<ulong, HSteamNetConnection>();
|
||||
readonly Dictionary<uint, ulong> _byConn = new Dictionary<uint, ulong>();
|
||||
readonly IntPtr[] _msgPtrs = new IntPtr[MaxMessagesPerPoll];
|
||||
|
||||
Callback<SteamNetConnectionStatusChangedCallback_t> _statusCb;
|
||||
HSteamListenSocket _listen = HSteamListenSocket.Invalid;
|
||||
HSteamNetPollGroup _pollGroup = HSteamNetPollGroup.Invalid;
|
||||
HSteamNetConnection _serverConn = HSteamNetConnection.Invalid;
|
||||
bool _isServer, _running;
|
||||
ulong _nextClientId = 1;
|
||||
IntPtr _sendPtr;
|
||||
int _sendPtrSize;
|
||||
|
||||
public override ulong ServerClientId => 0;
|
||||
|
||||
public override bool IsSupported => SteamManager.Initialized;
|
||||
|
||||
public override void Initialize(NetworkManager networkManager = null)
|
||||
{
|
||||
if (!SteamManager.Initialized) Debug.LogError("[SteamTransport] Steam is not initialized.");
|
||||
}
|
||||
|
||||
public override bool StartServer()
|
||||
{
|
||||
if (!SteamManager.Initialized) return false;
|
||||
_isServer = true;
|
||||
_running = true;
|
||||
_statusCb ??= Callback<SteamNetConnectionStatusChangedCallback_t>.Create(OnStatus);
|
||||
_listen = SteamNetworkingSockets.CreateListenSocketP2P(0, 0, null);
|
||||
_pollGroup = SteamNetworkingSockets.CreatePollGroup();
|
||||
Debug.Log("[SteamTransport] Listening for P2P connections");
|
||||
return _listen != HSteamListenSocket.Invalid;
|
||||
}
|
||||
|
||||
public override bool StartClient()
|
||||
{
|
||||
if (!SteamManager.Initialized || ConnectToSteamId == 0) return false;
|
||||
_isServer = false;
|
||||
_running = true;
|
||||
_statusCb ??= Callback<SteamNetConnectionStatusChangedCallback_t>.Create(OnStatus);
|
||||
var identity = new SteamNetworkingIdentity();
|
||||
identity.SetSteamID(new CSteamID(ConnectToSteamId));
|
||||
_serverConn = SteamNetworkingSockets.ConnectP2P(ref identity, 0, 0, null);
|
||||
Debug.Log($"[SteamTransport] Connecting to {ConnectToSteamId}");
|
||||
return _serverConn != HSteamNetConnection.Invalid;
|
||||
}
|
||||
|
||||
void OnStatus(SteamNetConnectionStatusChangedCallback_t cb)
|
||||
{
|
||||
if (!_running) return;
|
||||
var conn = cb.m_hConn;
|
||||
var state = cb.m_info.m_eState;
|
||||
switch (state)
|
||||
{
|
||||
case ESteamNetworkingConnectionState.k_ESteamNetworkingConnectionState_Connecting:
|
||||
if (_isServer && cb.m_info.m_hListenSocket != HSteamListenSocket.Invalid)
|
||||
{
|
||||
var r = SteamNetworkingSockets.AcceptConnection(conn);
|
||||
if (r != EResult.k_EResultOK)
|
||||
{
|
||||
Debug.LogWarning($"[SteamTransport] Accept failed: {r}");
|
||||
SteamNetworkingSockets.CloseConnection(conn, 0, "accept failed", false);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case ESteamNetworkingConnectionState.k_ESteamNetworkingConnectionState_Connected:
|
||||
if (_isServer)
|
||||
{
|
||||
ulong id = _nextClientId++;
|
||||
_byClient[id] = conn;
|
||||
_byConn[conn.m_HSteamNetConnection] = id;
|
||||
SteamNetworkingSockets.SetConnectionPollGroup(conn, _pollGroup);
|
||||
Enqueue(NetworkEvent.Connect, id);
|
||||
Debug.Log($"[SteamTransport] Client {id} connected ({cb.m_info.m_identityRemote.GetSteamID()})");
|
||||
}
|
||||
else
|
||||
{
|
||||
Enqueue(NetworkEvent.Connect, ServerClientId);
|
||||
Debug.Log("[SteamTransport] Connected to host");
|
||||
}
|
||||
break;
|
||||
|
||||
case ESteamNetworkingConnectionState.k_ESteamNetworkingConnectionState_ClosedByPeer:
|
||||
case ESteamNetworkingConnectionState.k_ESteamNetworkingConnectionState_ProblemDetectedLocally:
|
||||
Debug.Log($"[SteamTransport] Connection closed: {state} {cb.m_info.m_szEndDebug}");
|
||||
if (_isServer)
|
||||
{
|
||||
if (_byConn.TryGetValue(conn.m_HSteamNetConnection, out ulong cid))
|
||||
{
|
||||
_byConn.Remove(conn.m_HSteamNetConnection);
|
||||
_byClient.Remove(cid);
|
||||
Enqueue(NetworkEvent.Disconnect, cid);
|
||||
}
|
||||
}
|
||||
else if (conn == _serverConn)
|
||||
{
|
||||
_serverConn = HSteamNetConnection.Invalid;
|
||||
Enqueue(NetworkEvent.Disconnect, ServerClientId);
|
||||
}
|
||||
SteamNetworkingSockets.CloseConnection(conn, 0, "closed", false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Enqueue(NetworkEvent type, ulong clientId, byte[] data = null, int length = 0)
|
||||
{
|
||||
_events.Enqueue(new Pending { type = type, clientId = clientId, data = data, length = length });
|
||||
}
|
||||
|
||||
public override NetworkEvent PollEvent(out ulong clientId, out ArraySegment<byte> payload, out float receiveTime)
|
||||
{
|
||||
receiveTime = Time.realtimeSinceStartup;
|
||||
if (_events.Count == 0) PumpMessages();
|
||||
if (_events.Count > 0)
|
||||
{
|
||||
var e = _events.Dequeue();
|
||||
clientId = e.clientId;
|
||||
payload = e.data != null ? new ArraySegment<byte>(e.data, 0, e.length) : default;
|
||||
return e.type;
|
||||
}
|
||||
clientId = 0;
|
||||
payload = default;
|
||||
return NetworkEvent.Nothing;
|
||||
}
|
||||
|
||||
void PumpMessages()
|
||||
{
|
||||
if (!_running) return;
|
||||
int count;
|
||||
if (_isServer)
|
||||
{
|
||||
if (_pollGroup == HSteamNetPollGroup.Invalid) return;
|
||||
count = SteamNetworkingSockets.ReceiveMessagesOnPollGroup(_pollGroup, _msgPtrs, MaxMessagesPerPoll);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_serverConn == HSteamNetConnection.Invalid) return;
|
||||
count = SteamNetworkingSockets.ReceiveMessagesOnConnection(_serverConn, _msgPtrs, MaxMessagesPerPoll);
|
||||
}
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var msg = SteamNetworkingMessage_t.FromIntPtr(_msgPtrs[i]);
|
||||
ulong cid = ServerClientId;
|
||||
if (_isServer && !_byConn.TryGetValue(msg.m_conn.m_HSteamNetConnection, out cid))
|
||||
{
|
||||
SteamNetworkingMessage_t.Release(_msgPtrs[i]);
|
||||
continue;
|
||||
}
|
||||
int size = msg.m_cbSize;
|
||||
// Each queued message needs its own buffer because several can be queued before NGO consumes them.
|
||||
var buf = new byte[size];
|
||||
Marshal.Copy(msg.m_pData, buf, 0, size);
|
||||
SteamNetworkingMessage_t.Release(_msgPtrs[i]);
|
||||
Enqueue(NetworkEvent.Data, cid, buf, size);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Send(ulong clientId, ArraySegment<byte> payload, NetworkDelivery delivery)
|
||||
{
|
||||
HSteamNetConnection conn;
|
||||
if (_isServer)
|
||||
{
|
||||
if (!_byClient.TryGetValue(clientId, out conn)) return;
|
||||
}
|
||||
else conn = _serverConn;
|
||||
if (conn == HSteamNetConnection.Invalid) return;
|
||||
|
||||
int flags = delivery switch
|
||||
{
|
||||
NetworkDelivery.Unreliable => Constants.k_nSteamNetworkingSend_UnreliableNoNagle,
|
||||
NetworkDelivery.UnreliableSequenced => Constants.k_nSteamNetworkingSend_UnreliableNoNagle,
|
||||
_ => Constants.k_nSteamNetworkingSend_ReliableNoNagle,
|
||||
};
|
||||
|
||||
int len = payload.Count;
|
||||
if (_sendPtrSize < len)
|
||||
{
|
||||
if (_sendPtr != IntPtr.Zero) Marshal.FreeHGlobal(_sendPtr);
|
||||
_sendPtrSize = Mathf.NextPowerOfTwo(Mathf.Max(len, 1024));
|
||||
_sendPtr = Marshal.AllocHGlobal(_sendPtrSize);
|
||||
}
|
||||
Marshal.Copy(payload.Array, payload.Offset, _sendPtr, len);
|
||||
var res = SteamNetworkingSockets.SendMessageToConnection(conn, _sendPtr, (uint)len, flags, out _);
|
||||
if (res != EResult.k_EResultOK && res != EResult.k_EResultNoConnection)
|
||||
Debug.LogWarning($"[SteamTransport] Send failed: {res} ({len} bytes)");
|
||||
}
|
||||
|
||||
public override ulong GetCurrentRtt(ulong clientId)
|
||||
{
|
||||
HSteamNetConnection conn = _isServer ? (_byClient.TryGetValue(clientId, out var c) ? c : HSteamNetConnection.Invalid) : _serverConn;
|
||||
if (conn == HSteamNetConnection.Invalid) return 0;
|
||||
var status = new SteamNetConnectionRealTimeStatus_t();
|
||||
var lanes = new SteamNetConnectionRealTimeLaneStatus_t();
|
||||
if (SteamNetworkingSockets.GetConnectionRealTimeStatus(conn, ref status, 0, ref lanes) == EResult.k_EResultOK)
|
||||
return (ulong)Mathf.Max(0, status.m_nPing);
|
||||
return 0;
|
||||
}
|
||||
|
||||
public override void DisconnectRemoteClient(ulong clientId)
|
||||
{
|
||||
if (_byClient.TryGetValue(clientId, out var conn))
|
||||
{
|
||||
SteamNetworkingSockets.CloseConnection(conn, 0, "kicked", true);
|
||||
_byClient.Remove(clientId);
|
||||
_byConn.Remove(conn.m_HSteamNetConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public override void DisconnectLocalClient()
|
||||
{
|
||||
if (_serverConn != HSteamNetConnection.Invalid)
|
||||
{
|
||||
SteamNetworkingSockets.CloseConnection(_serverConn, 0, "leaving", true);
|
||||
_serverConn = HSteamNetConnection.Invalid;
|
||||
}
|
||||
}
|
||||
|
||||
public override void Shutdown()
|
||||
{
|
||||
if (!_running) return;
|
||||
_running = false;
|
||||
if (SteamManager.Initialized)
|
||||
{
|
||||
foreach (var c in _byClient.Values) SteamNetworkingSockets.CloseConnection(c, 0, "shutdown", false);
|
||||
if (_serverConn != HSteamNetConnection.Invalid) SteamNetworkingSockets.CloseConnection(_serverConn, 0, "shutdown", false);
|
||||
if (_listen != HSteamListenSocket.Invalid) SteamNetworkingSockets.CloseListenSocket(_listen);
|
||||
if (_pollGroup != HSteamNetPollGroup.Invalid) SteamNetworkingSockets.DestroyPollGroup(_pollGroup);
|
||||
}
|
||||
_byClient.Clear();
|
||||
_byConn.Clear();
|
||||
_events.Clear();
|
||||
_listen = HSteamListenSocket.Invalid;
|
||||
_pollGroup = HSteamNetPollGroup.Invalid;
|
||||
_serverConn = HSteamNetConnection.Invalid;
|
||||
_nextClientId = 1;
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
if (_sendPtr != IntPtr.Zero) { Marshal.FreeHGlobal(_sendPtr); _sendPtr = IntPtr.Zero; }
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Net/SteamSocketsTransport.cs.meta
Normal file
2
Assets/Scripts/Net/SteamSocketsTransport.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 77733383c016f1542b24703c9ad0e0c8
|
||||
Reference in New Issue
Block a user