TH1/Unity/Assets/Scripts/TH1_Logic/Steam/SteamTestManager.cs
2025-09-02 20:10:15 +08:00

441 lines
15 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.IO;
using UnityEngine;
using Steamworks;
using TH1_Logic.Steam;
using Logic.CrashSight;
namespace TH1_Logic.Steam
{
/// <summary>
/// Steam测试管理器 - 用于在Unity编辑器中测试Steam功能
/// </summary>
public class SteamTestManager : MonoBehaviour
{
[Header("Steam 连接状态")]
public bool IsSteamInitialized = false;
public bool IsLoggedIn = false;
public string CurrentUserName = "";
public CSteamID CurrentUserID;
[Header("测试配置")]
[SerializeField] private bool autoInitialize = true;
[SerializeField] private bool enableDebugLog = true;
[Header("房间测试")]
[SerializeField] private int maxLobbyMembers = 4;
private void Awake()
{
// 确保只有一个实例
if (FindObjectsOfType<SteamTestManager>().Length > 1)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
}
private void Start()
{
if (autoInitialize)
{
StartCoroutine(InitializeSteam());
}
}
/// <summary>
/// 初始化Steam
/// </summary>
private IEnumerator InitializeSteam()
{
LogSystem.LogInfo("开始初始化Steam...");
LogSystem.LogInfo($"启动方式检测: {(SteamAPI.RestartAppIfNecessary(new Steamworks.AppId_t(480)) ? "Steam启动" : "Steam启动")}");
// 检查Steam是否运行
if (!SteamAPI.IsSteamRunning())
{
LogSystem.LogError("Steam客户端未运行请先启动Steam。");
yield break;
}
// 检查steam_appid.txt文件状态
CheckSteamAppIdFile();
// 初始化Steam API
IsSteamInitialized = SteamAPI.Init();
if (!IsSteamInitialized)
{
LogSystem.LogError("Steam API初始化失败");
LogSystem.LogError("可能的原因:");
LogSystem.LogError("1. Steam客户端未运行");
LogSystem.LogError("2. steam_appid.txt文件配置错误开发环境");
LogSystem.LogError("3. 没有以Steam方式启动应用开发环境");
LogSystem.LogError("4. Steam App ID不匹配");
yield break;
}
LogSystem.LogInfo("Steam API初始化成功");
// 等待一帧确保Steam完全初始化
yield return null;
// 检查用户登录状态
try
{
CheckUserLoginStatus();
}
catch (System.Exception e)
{
LogSystem.LogError($"检查用户登录状态异常: {e.Message}");
}
// 显示启动信息
DisplayLaunchInfo();
// 初始化Steam房间管理器
try
{
InitializeSteamLobbyManager();
}
catch (System.Exception e)
{
LogSystem.LogError($"Steam房间管理器初始化异常: {e.Message}");
}
LogSystem.LogInfo("Steam测试环境初始化完成");
}
/// <summary>
/// 检查steam_appid.txt文件状态
/// </summary>
private void CheckSteamAppIdFile()
{
string steamAppIdPath = Path.Combine(Directory.GetCurrentDirectory(), "steam_appid.txt");
if (File.Exists(steamAppIdPath))
{
try
{
string content = File.ReadAllText(steamAppIdPath).Trim();
LogSystem.LogInfo($"发现steam_appid.txt文件App ID: {content}");
}
catch (System.Exception e)
{
LogSystem.LogWarning($"读取steam_appid.txt失败: {e.Message}");
}
}
else
{
LogSystem.LogInfo("未发现steam_appid.txt文件 - 这在Steam平台发布时是正常的");
}
}
/// <summary>
/// 显示启动信息
/// </summary>
private void DisplayLaunchInfo()
{
if (!IsSteamInitialized) return;
// 获取当前App ID
var currentAppId = SteamUtils.GetAppID();
LogSystem.LogInfo($"当前Steam App ID: {currentAppId}");
// 检查启动方式
bool launchedViaSteam = SteamApps.BIsSubscribedApp(currentAppId);
LogSystem.LogInfo($"通过Steam启动: {(launchedViaSteam ? "" : "")}");
// 显示Steam环境信息
LogSystem.LogInfo($"Steam语言: {SteamApps.GetCurrentGameLanguage()}");
LogSystem.LogInfo($"Steam服务器连接: {(SteamUser.BLoggedOn() ? "" : "")}");
// 检查DLC和订阅状态
if (currentAppId.m_AppId == 480) // Spacewar测试应用
{
LogSystem.LogInfo("当前使用Spacewar测试应用 - 适用于开发测试");
}
else
{
LogSystem.LogInfo($"当前使用正式应用ID: {currentAppId.m_AppId}");
}
}
/// <summary>
/// 检查用户登录状态
/// </summary>
private void CheckUserLoginStatus()
{
if (!IsSteamInitialized) return;
IsLoggedIn = SteamUser.BLoggedOn();
if (IsLoggedIn)
{
CurrentUserID = SteamUser.GetSteamID();
CurrentUserName = SteamFriends.GetPersonaName();
LogSystem.LogInfo($"Steam用户已登录: {CurrentUserName} ({CurrentUserID})");
}
else
{
LogSystem.LogWarning("Steam用户未登录");
}
}
/// <summary>
/// 初始化Steam房间管理器
/// </summary>
private void InitializeSteamLobbyManager()
{
if (!IsSteamInitialized || !IsLoggedIn) return;
try
{
// 初始化房间管理器
SteamLobbyManager.Instance.InitCallbacks();
// 订阅事件
SteamLobbyManager.Instance.OnLobbyCreatedEvent += OnLobbyCreated;
SteamLobbyManager.Instance.OnLobbyEnteredEvent += OnLobbyEntered;
SteamLobbyManager.Instance.OnLobbyLeftEvent += OnLobbyLeft;
SteamLobbyManager.Instance.OnMemberJoinedEvent += OnMemberJoined;
SteamLobbyManager.Instance.OnMemberLeftEvent += OnMemberLeft;
SteamLobbyManager.Instance.OnHostChangedEvent += OnHostChanged;
SteamLobbyManager.Instance.OnLobbyErrorEvent += OnLobbyError;
// 订阅P2P事件
SimpleP2P.Instance.OnPeerConnectedEvent += OnP2PPeerConnected;
SimpleP2P.Instance.OnPeerDisconnectedEvent += OnP2PPeerDisconnected;
SimpleP2P.Instance.OnMessageReceivedEvent += OnP2PMessageReceived;
SimpleP2P.Instance.OnConnectionErrorEvent += OnP2PConnectionError;
LogSystem.LogInfo("Steam房间管理器初始化成功");
}
catch (System.Exception e)
{
LogSystem.LogError($"Steam房间管理器初始化失败: {e.Message}");
}
}
private void Update()
{
if (IsSteamInitialized)
{
// 更新Steam回调
SteamAPI.RunCallbacks();
// 更新P2P消息
SteamLobbyManager.Instance.Update();
}
}
private void OnDestroy()
{
if (IsSteamInitialized)
{
SteamLobbyManager.Instance.Cleanup();
SteamAPI.Shutdown();
LogSystem.LogInfo("Steam API已关闭");
}
}
#region
private void OnLobbyCreated(CSteamID lobbyId)
{
LogSystem.LogInfo($"[测试] 房间创建成功: {lobbyId}");
}
private void OnLobbyEntered(CSteamID lobbyId)
{
LogSystem.LogInfo($"[测试] 进入房间: {lobbyId}");
LogSystem.LogInfo($"[测试] 房间成员数: {SteamLobbyManager.Instance.GetMemberCount()}/{SteamLobbyManager.Instance.GetMemberLimit()}");
}
private void OnLobbyLeft()
{
LogSystem.LogInfo("[测试] 离开房间");
}
private void OnMemberJoined(CSteamID memberId)
{
string memberName = SteamFriends.GetFriendPersonaName(memberId);
LogSystem.LogInfo($"[测试] 成员加入: {memberName} ({memberId})");
}
private void OnMemberLeft(CSteamID memberId)
{
string memberName = SteamFriends.GetFriendPersonaName(memberId);
LogSystem.LogInfo($"[测试] 成员离开: {memberName} ({memberId})");
}
private void OnHostChanged(CSteamID oldHost, CSteamID newHost)
{
string oldHostName = SteamFriends.GetFriendPersonaName(oldHost);
string newHostName = SteamFriends.GetFriendPersonaName(newHost);
LogSystem.LogInfo($"[测试] 房主变更: {oldHostName} -> {newHostName}");
}
private void OnLobbyError(string error)
{
LogSystem.LogError($"[测试] 房间错误: {error}");
}
#endregion
#region P2P事件处理
private void OnP2PPeerConnected(CSteamID peerId)
{
string peerName = SteamFriends.GetFriendPersonaName(peerId);
LogSystem.LogInfo($"[测试] P2P连接建立: {peerName} ({peerId})");
}
private void OnP2PPeerDisconnected(CSteamID peerId)
{
string peerName = SteamFriends.GetFriendPersonaName(peerId);
LogSystem.LogInfo($"[测试] P2P连接断开: {peerName} ({peerId})");
}
private void OnP2PMessageReceived(CSteamID senderId, byte[] data)
{
string senderName = SteamFriends.GetFriendPersonaName(senderId);
string message = System.Text.Encoding.UTF8.GetString(data);
LogSystem.LogInfo($"[测试] 收到P2P消息 from {senderName}: {message}");
}
private void OnP2PConnectionError(string error)
{
LogSystem.LogError($"[测试] P2P连接错误: {error}");
}
#endregion
#region - Inspector中调用
[ContextMenu("创建测试房间")]
public void TestCreateLobby()
{
if (!CanPerformLobbyAction()) return;
LogSystem.LogInfo("[测试] 创建房间...");
SteamLobbyManager.Instance.CreateFriendsLobby(maxLobbyMembers);
}
[ContextMenu("离开房间")]
public void TestLeaveLobby()
{
if (!SteamLobbyManager.Instance.IsInLobby)
{
LogSystem.LogWarning("[测试] 当前不在房间中");
return;
}
LogSystem.LogInfo("[测试] 离开房间...");
SteamLobbyManager.Instance.LeaveLobby();
}
[ContextMenu("发送测试消息")]
public void TestSendMessage()
{
if (!SteamLobbyManager.Instance.IsInLobby)
{
LogSystem.LogWarning("[测试] 当前不在房间中,无法发送消息");
return;
}
string testMessage = $"测试消息 from {CurrentUserName} at {System.DateTime.Now:HH:mm:ss}";
byte[] data = System.Text.Encoding.UTF8.GetBytes(testMessage);
LogSystem.LogInfo($"[测试] 广播消息: {testMessage}");
SteamLobbyManager.Instance.BroadcastMessage(data, true);
}
[ContextMenu("显示在线好友")]
public void TestShowOnlineFriends()
{
if (!CanPerformLobbyAction()) return;
var friends = SteamLobbyManager.Instance.GetOnlineFriends();
LogSystem.LogInfo($"[测试] 在线好友数量: {friends.Count}");
foreach (var friend in friends)
{
LogSystem.LogInfo($"[测试] 好友: {friend.name} ({friend.id})");
}
}
[ContextMenu("打开邀请界面")]
public void TestOpenInviteOverlay()
{
if (!SteamLobbyManager.Instance.IsInLobby)
{
LogSystem.LogWarning("[测试] 当前不在房间中,无法邀请好友");
return;
}
LogSystem.LogInfo("[测试] 打开Steam邀请界面...");
SteamLobbyManager.Instance.OpenInviteOverlay();
}
private bool CanPerformLobbyAction()
{
if (!IsSteamInitialized)
{
LogSystem.LogError("[测试] Steam未初始化");
return false;
}
if (!IsLoggedIn)
{
LogSystem.LogError("[测试] Steam用户未登录");
return false;
}
return true;
}
#endregion
#region GUI显示状态
private void OnGUI()
{
if (!enableDebugLog) return;
GUILayout.BeginArea(new Rect(10, 10, 300, 400));
GUILayout.BeginVertical("box");
GUILayout.Label("Steam 测试状态", GUI.skin.label);
GUILayout.Label($"Steam初始化: {(IsSteamInitialized ? "" : "")}");
GUILayout.Label($"用户登录: {(IsLoggedIn ? "" : "")}");
if (IsLoggedIn)
{
GUILayout.Label($"用户: {CurrentUserName}");
GUILayout.Label($"ID: {CurrentUserID}");
}
GUILayout.Space(10);
GUILayout.Label("房间状态", GUI.skin.label);
GUILayout.Label($"当前状态: {SteamLobbyManager.Instance.CurrentState}");
GUILayout.Label($"在房间中: {(SteamLobbyManager.Instance.IsInLobby ? "" : "")}");
GUILayout.Label($"是房主: {(SteamLobbyManager.Instance.IsLobbyOwner ? "" : "")}");
if (SteamLobbyManager.Instance.IsInLobby)
{
GUILayout.Label($"房间ID: {SteamLobbyManager.Instance.CurrentLobby}");
GUILayout.Label($"成员数: {SteamLobbyManager.Instance.GetMemberCount()}/{SteamLobbyManager.Instance.GetMemberLimit()}");
GUILayout.Label($"P2P连接数: {SimpleP2P.Instance.GetConnectionCount()}");
}
GUILayout.EndVertical();
GUILayout.EndArea();
}
#endregion
}
}