diff --git a/Assets/Scripts/OutGame/Net/ServerSession.cs b/Assets/Scripts/OutGame/Net/ServerSession.cs index 17eae6c5..356b4fac 100644 --- a/Assets/Scripts/OutGame/Net/ServerSession.cs +++ b/Assets/Scripts/OutGame/Net/ServerSession.cs @@ -1267,6 +1267,23 @@ namespace TKS.OutGame.Net static void Init() { Apply(); + FromTitle = false; + UnityEngine.SceneManagement.SceneManager.sceneLoaded -= OnSceneLoaded; // 도메인 리로드를 끈 에디터에서 두 번 걸리지 않게 + UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded; + } + + /// 타이틀 씬을 거쳐 들어왔는가 — 타이틀부터 다시 시작할 때(Restart) 돌아갈 곳을 정한다. + public static bool FromTitle { get; private set; } + + /// + /// 타이틀 씬이 열리면(서버 모드) 그 씬에서 접속 · 로그인을 시작한다 — 로그인 화면이 타이틀 위에 뜨고, 로그인이 끝나야 타이틀이 다음으로 넘어간다 + /// (타이틀 화면은 접속 일꾼이 있는지 · 끝났는지만 본다 — UI/TitleScreen 의 PressReady). 일꾼은 씬이 바뀌어도 남아 게임 씬의 세션이 이어받는다. + /// + static void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) + { + if (!ServerConfig.Active || scene.name != BootScenes.Title) return; + FromTitle = true; + ServerSync.CreateAtTitle(); } /// 서버 모드면 세션을 ServerSession 으로 만들고, 기기 사본을 따로 둔 파일에 쓴다(기존 save.json 을 덮지 않는다). @@ -1289,6 +1306,8 @@ namespace TKS.OutGame.Net public static void ForceForTest(string url, int gameId) { ServerClient.ClearMemory(); // 테스트마다 새 계정으로 시작한다 + ServerSync.Drop(); // 앞 테스트가 타이틀 씬에서 만든 일꾼(씬이 바뀌어도 남는다)을 치운다 + FromTitle = false; ServerConfig.ForceForTest(url, gameId); Apply(); } @@ -1304,12 +1323,13 @@ namespace TKS.OutGame.Net /// /// 타이틀부터 다시 시작한다(로그아웃 · 계정 삭제 · 다른 기기에서 접속해 세션이 끊김 · 기존 연동 계정으로 들어감) — - /// 지금 씬을 다시 열어 접속 일꾼이 새로 로그인하게 한다(저장한 증표가 없으면 로그인 화면). + /// 타이틀 씬으로 돌아가 접속 일꾼이 새로 로그인하게 한다(저장한 증표가 없으면 타이틀 위에 로그인 화면). + /// 타이틀 씬을 거치지 않고 게임 씬을 바로 연 경우(개발 · 테스트)에는 그 씬을 다시 연다. /// public static void Restart() { - if (ServerSync.Instance != null) UnityEngine.Object.Destroy(ServerSync.Instance.gameObject); - UnityEngine.SceneManagement.SceneManager.LoadScene(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name); + ServerSync.Drop(); + UnityEngine.SceneManagement.SceneManager.LoadScene(FromTitle ? BootScenes.Title : UnityEngine.SceneManagement.SceneManager.GetActiveScene().name); } /// @@ -1321,6 +1341,8 @@ namespace TKS.OutGame.Net { SkipSignupTimezone = false; LoginUi = false; + FromTitle = false; + ServerSync.Drop(); ServerClient.ClearMemory(); ServerConfig.ClearForce(); Apply(); diff --git a/Assets/Scripts/OutGame/Net/ServerSync.cs b/Assets/Scripts/OutGame/Net/ServerSync.cs index 9fa3f5c5..565b4179 100644 --- a/Assets/Scripts/OutGame/Net/ServerSync.cs +++ b/Assets/Scripts/OutGame/Net/ServerSync.cs @@ -2,6 +2,7 @@ using System; using System.Collections; using System.Collections.Generic; using UnityEngine; +using UnityEngine.EventSystems; using UnityEngine.UI; namespace TKS.OutGame.Net @@ -14,14 +15,21 @@ namespace TKS.OutGame.Net /// 4. 거절: 서버가 요청을 받아 주지 않으면(기기와 서버가 어긋남) 남은 요청을 버리고 서버 상태로 되돌린다. /// 5. 끊김: 연결 문제는 몇 번 조용히 다시 보내고, 그래도 안 되면 화면을 막고 「다시 시도」를 받는다. /// 6. 로그인: 저장한 증표로 이어 하기 → 없으면 로그인 화면(게스트 · 소셜). 다른 기기에서 같은 계정으로 접속하면 이쪽은 안내 뒤 타이틀로 돌아간다. + /// 7. 타이틀 씬: 타이틀 씬이 열리면 세션 없이 먼저 만들어져(ServerLink) 로그인까지 하고, 씬이 바뀌어도 남아 게임 씬의 세션이 이어받는다(Attach) — + /// 로그인 화면은 타이틀 위에 뜨고, 계정 상태는 게임 씬에서 받는다. 게임 씬을 바로 열면(개발 · 테스트) 전 과정을 그 씬에서 한다. /// public class ServerSync : MonoBehaviour { public static ServerSync Instance { get; private set; } public ServerClient Client { get; private set; } - /// 접속이 끝나 계정 상태를 받았는가. + /// 다음으로 넘어가도 되는가 — 타이틀 씬(세션 없음)에서는 로그인이 끝났는가 · 게임 씬에서는 계정 상태까지 받았는가. public bool Ready { get; private set; } + /// 타이틀 씬에서 만들어져 게임 씬의 세션을 기다리는 중인가. + public bool AtTitle + { + get { return session == null; } + } /// 보내는 중이거나 보낼 것이 남았는가. public bool Busy { @@ -63,6 +71,10 @@ namespace TKS.OutGame.Net readonly Queue queue = new Queue(); ServerSession session; + // 서버 기준 정보(재화 목록) 응답 — 타이틀 씬에서 받아 두었다가 세션이 생기면 넘긴다 + readonly ServerResult goods = new ServerResult(); + // 타이틀 씬에서 로그인까지 끝낸 뒤 세션이 이어받았다 = 접속 루틴이 계정 수신부터 한다(한 번만) + bool loggedIn; bool sending; bool dirty; float reconcileAt; @@ -83,7 +95,26 @@ namespace TKS.OutGame.Net internal static ServerSync Create(ServerSession session) { - if (Instance != null) Destroy(Instance.gameObject); // 씬을 다시 연 경우 — 앞 세션의 일꾼을 치운다 + if (Instance != null && Instance.AtTitle) + { + Instance.Attach(session); // 타이틀 씬에서 로그인한 일꾼을 이어 쓴다 + return Instance; + } + Drop(); // 씬을 다시 연 경우 — 앞 세션의 일꾼을 치운다 + return Make(session); + } + + /// 타이틀 씬에서 — 세션 없이 만들어 로그인까지 한다. 씬이 바뀌어도 남는다. + internal static ServerSync CreateAtTitle() + { + Drop(); + var s = Make(null); + DontDestroyOnLoad(s.gameObject); + return s; + } + + static ServerSync Make(ServerSession session) + { var go = new GameObject("ServerSync"); var s = go.AddComponent(); s.session = session; @@ -93,6 +124,30 @@ namespace TKS.OutGame.Net return s; } + /// 지금 일꾼을 치운다(타이틀부터 다시 시작 · 테스트 정리). + internal static void Drop() + { + if (Instance == null) return; + Destroy(Instance.gameObject); + Instance = null; + } + + /// + /// 게임 씬의 세션이 타이틀 씬에서 만든 일꾼을 이어받는다 — 로그인 증표와 받아 둔 기준 정보를 그대로 쓰고 계정 상태부터 받는다. + /// 타이틀에서 로그인이 끝나기 전에 넘어왔으면(정상 흐름에서는 없음) 접속을 처음부터 다시 한다. + /// + void Attach(ServerSession s) + { + StopAllCoroutines(); // 타이틀에서 돌던 접속 루틴을 끝내고 세션과 함께 다시 돈다 + LoginPanel.Close(); + if (overlay != null) Destroy(overlay); // 타이틀 씬 카메라에 그리던 안내 — 이 씬 카메라로 다시 만든다 + overlay = null; + session = s; + loggedIn = Ready; + Ready = false; + StartCoroutine(Run()); + } + void OnDestroy() { if (Instance == this) Instance = null; @@ -113,7 +168,9 @@ namespace TKS.OutGame.Net IEnumerator Run() { + if (AtTitle) yield return null; // 타이틀 씬의 Start(카메라 준비)가 끝난 뒤에 시작한다 yield return Connect(); + if (AtTitle) yield break; // 타이틀 씬 = 로그인까지 — 게임 씬의 세션이 이어받을 때(Attach) 다시 돈다 while (true) { if (queue.Count == 0) @@ -135,29 +192,46 @@ namespace TKS.OutGame.Net { ShowOverlay("서버에 접속하는 중…", false); - yield return Client.Send("GET", "/games/" + ServerConfig.GameId + "/status", null, false, r); - if (!r.ok) + if (!loggedIn) { - yield return AskRetry("서버에 접속할 수 없습니다", r); - continue; - } - if (r.Str("status") != "NORMAL") - { - yield return AskRetry("서버 점검 중입니다 (" + r.Str("status") + ")", null); - continue; - } + yield return Client.Send("GET", "/games/" + ServerConfig.GameId + "/status", null, false, r); + if (!r.ok) + { + yield return AskRetry("서버에 접속할 수 없습니다", r); + continue; + } + if (r.Str("status") != "NORMAL") + { + yield return AskRetry("서버 점검 중입니다 (" + r.Str("status") + ")", null); + continue; + } - yield return Client.Send("GET", "/tks/config", null, false, r); - if (!r.ok || !session.LoadGoodsTable(r)) - { - yield return AskRetry("서버 기준 정보를 받지 못했습니다", r); - continue; - } + yield return Client.Send("GET", "/tks/config", null, false, goods); + if (!goods.ok) + { + yield return AskRetry("서버 기준 정보를 받지 못했습니다", goods); + continue; + } - yield return Authenticate(r); - if (!r.ok) + yield return Authenticate(r); + if (!r.ok) + { + yield return AskRetry("로그인하지 못했습니다", r); + continue; + } + } + loggedIn = false; // 아래에서 막혀 다시 시도할 때는 처음부터 한다 + + if (AtTitle) { - yield return AskRetry("로그인하지 못했습니다", r); + // 타이틀 씬 — 로그인까지 끝났다. 타이틀이 「Press Any Key」를 띄우고, 계정 상태는 게임 씬의 세션이 이어받아 받는다 + Ready = true; + HideOverlay(); + yield break; + } + if (!session.LoadGoodsTable(goods)) + { + yield return AskRetry("서버 기준 정보를 받지 못했습니다", goods); continue; } ShowOverlay("서버에 접속하는 중…", false); @@ -202,6 +276,7 @@ namespace TKS.OutGame.Net HideOverlay(); string method = null, socialId = null; var cam = OutGameRoot.Instance != null && OutGameRoot.Instance.Cam != null ? OutGameRoot.Instance.Cam : Camera.main; + EnsureInput(); LoginPanel.Show(transform, cam, Client.LastMethod, Client.LastSocialId, notice, (m, id) => { method = m; @@ -466,8 +541,21 @@ namespace TKS.OutGame.Net retryPressed = true; } + /// + /// 버튼 누름을 받는 장치가 씬에 없으면 만든다 — 타이틀 씬은 키 · 터치만 읽어서 장치가 없다(게임 씬은 전투 HUD 가 만든다). + /// 지금 씬에 만들어 씬과 함께 사라지게 한다(이 일꾼은 씬을 넘어가므로 자식으로 두지 않는다). + /// + static void EnsureInput() + { + if (EventSystem.current != null || FindFirstObjectByType() != null) return; + var es = new GameObject("EventSystem"); + es.AddComponent(); + es.AddComponent(); + } + void ShowOverlay(string msg, bool button, string buttonLabel = "다시 시도") { + if (button) EnsureInput(); if (overlay == null) BuildOverlay(); overlayText.text = msg; overlayButton.SetActive(button); diff --git a/Assets/Tests/PlayMode/ServerLinkTests.cs b/Assets/Tests/PlayMode/ServerLinkTests.cs index 2deba372..6bea59c3 100644 --- a/Assets/Tests/PlayMode/ServerLinkTests.cs +++ b/Assets/Tests/PlayMode/ServerLinkTests.cs @@ -5,8 +5,10 @@ using NUnit.Framework; using TKS.OutGame; using TKS.OutGame.Net; using UnityEngine; +using UnityEngine.EventSystems; using UnityEngine.SceneManagement; using UnityEngine.TestTools; +using UnityEngine.UI; namespace TKS.Tests { @@ -820,6 +822,154 @@ namespace TKS.Tests Assert.AreEqual("INVALID_GUEST_USER", link.Message, "이미 소셜 계정인 계정"); } + // ---------- 타이틀 씬에서 시작 (실제 실행 순서 = Splash → Title → Battle · 위 테스트들은 게임 씬을 바로 연다) ---------- + + /// 타이틀 씬을 연다(서버 모드 · 로그인 화면 사용) — 접속 일꾼이 타이틀 씬에서 만들어진다. + IEnumerator BootAtTitle() + { + WorldProgress.Reset(); + SaveStore.UseMemory(true); + ServerLink.ForceForTest(TestUrl(), ServerConfig.GameId); + ServerLink.LoginUi = true; + SceneManager.LoadScene(BootScenes.Title); + yield return AtTitle(null); + } + + /// 타이틀 씬이 열리고 새 접속 일꾼이 만들어지기를 기다린다(old = 앞 일꾼 · 처음이면 null). + IEnumerator AtTitle(ServerSync old) + { + yield return Until(() => SceneManager.GetActiveScene().name == BootScenes.Title && TitleScreen.Current != null + && ServerSync.Instance != null && ServerSync.Instance != old, 15f, "타이틀 씬"); + sync = ServerSync.Instance; + og = null; + Assert.IsTrue(sync.AtTitle, "접속 일꾼이 타이틀 씬에서 만들어진다"); + Assert.IsTrue(OutGameRoot.Instance == null, "타이틀 씬 = 타이틀만(로비 없음)"); + } + + /// 타이틀 위의 로그인 화면에서 고르고 로그인이 끝나기를 기다린다. method = null 이면 화면 없이 이어 하기(저장한 로그인)를 기대한다. + IEnumerator TitleLogin(string method, string devId) + { + if (method != null) + { + yield return Until(() => LoginPanel.Current != null || sync.Ready || sync.LastError != null, 20f, "타이틀의 로그인 화면"); + Assert.IsNotNull(LoginPanel.Current, "타이틀 위에 로그인 화면이 뜬다(자동으로 들어가지 않는다): " + sync.LastError); + LoginPanel.Current.Choose(method, devId); + yield return null; + yield return null; + } + yield return Until(() => sync.Ready || sync.LastError != null || LoginPanel.Current != null, 30f, "로그인"); + if (LoginPanel.Current != null && method != null && method != ServerClient.MethodGuest && LoginPanel.Current.Notice.Contains("SOCIAL_INVALID_TOKEN")) + Assert.Ignore("서버가 시험용 소셜 계정을 받지 않는다 — 서버 .env 에 SOCIAL_PROVIDER=fake 를 넣고 다시 켜면 돈다"); + Assert.IsNull(LoginPanel.Current, method == null ? "저장한 로그인으로 화면 없이 들어간다" : "로그인 화면이 닫힌다: " + (LoginPanel.Current != null ? LoginPanel.Current.Notice : "")); + Assert.IsTrue(sync.Ready, "로그인 실패: " + sync.LastError); + Assert.AreEqual(BootScenes.Title, SceneManager.GetActiveScene().name, "로그인은 타이틀 씬에서 끝난다"); + } + + /// 타이틀을 눌러 게임 씬에 들어간다 — 타이틀에서 로그인한 일꾼을 게임 씬의 세션이 이어받아 계정 상태를 받는다. + IEnumerator EnterGame() + { + var atTitle = sync; + var ts = TitleScreen.Current; + ts.SkipIntro(); + yield return Until(() => ts.PressReady, 10f, "로그인 뒤 Press Any Key"); + ts.Press(); + yield return Until(() => SceneManager.GetActiveScene().name == BootScenes.Game && OutGameRoot.Instance != null && SceneSwitch.Current == null, 15f, "누름 → 게임 씬"); + og = OutGameRoot.Instance; + bm = BattleManager.Instance; + wm = WorldMapScreen.Instance; + sync = ServerSync.Instance; + Assert.AreSame(atTitle, sync, "타이틀에서 로그인한 일꾼을 게임 씬의 세션이 이어받는다(다시 로그인하지 않는다)"); + Assert.IsFalse(sync.AtTitle); + Assert.IsInstanceOf(og.Session); + yield return Until(() => sync.Ready || sync.LastError != null, 30f, "계정 수신"); + Assert.IsTrue(sync.Ready, "서버 접속 실패: " + sync.LastError); + Assert.IsNull(LoginPanel.Current, "로비 위에는 로그인 화면이 뜨지 않는다"); + } + + /// + /// 타이틀 씬에서 시작 — 처음 실행이면 타이틀 위에 로그인 화면이 뜨고, 로그인이 끝나야 「Press Any Key」로 게임 씬에 들어간다. + /// 다음 실행(타이틀부터 다시 시작)은 로그인 화면 없이 마지막에 로그인한 계정으로 이어 한다. + /// + [UnityTest] + public IEnumerator Title_FirstRun_LoginOnTitle_ThenEntersGame_NextRunResumes() + { + yield return BootAtTitle(); + yield return Until(() => LoginPanel.Current != null || sync.Ready || sync.LastError != null, 20f, "타이틀의 로그인 화면"); + Assert.IsNotNull(LoginPanel.Current, "처음 실행 = 타이틀 위에 로그인 화면: " + sync.LastError); + + // 로그인 전에는 타이틀이 다음으로 넘어가지 않는다(등장 연출을 건너뛰고 눌러도) + var ts = TitleScreen.Current; + ts.SkipIntro(); + for (float until = Time.unscaledTime + 2f; Time.unscaledTime < until;) yield return null; + Assert.IsFalse(ts.PressReady, "로그인이 끝나기 전에는 Press Any Key 가 뜨지 않는다"); + ts.Press(); + Assert.IsFalse(ts.Leaving, "로그인 전 누름 = 게임 씬으로 가지 않는다"); + yield return CaptureUtil.Capture(Camera.main, 720, 1280, System.IO.Path.Combine("Temp", "tks_title_login.png")); + + // 타이틀 씬에서도 버튼이 눌린다 — 화면 좌표로 쏜 누름이 「게스트로 시작」 버튼에 닿는다(타이틀 씬에는 원래 버튼 누름을 받는 장치가 없다) + Button guest = null; + foreach (var btn in LoginPanel.Current.GetComponentsInChildren