서버 연결 — 로그인 화면을 타이틀 씬에서 · 로그아웃 뒤 타이틀 씬으로 (PD 2026-11-17 요구 ③)

- PD 「유저가 게임 내 옵션에서 로그아웃 시 타이틀 화면에서는 다시 로그인 화면이 제공되어야 하고, 이미 접속한 이력이 있을 경우에는 마지막에 로그인 했던 소셜 계정으로 로그인되어야」
- 타이틀 씬 분리와 합쳐진 뒤 접속 일꾼(ServerSync)이 게임 씬에서 만들어져 로그인 화면이 로비 위에 뜨고 로그아웃 뒤 게임 씬이 다시 열리던 것을 고침
- ServerLink 가 씬 열림을 듣다가 서버 모드에서 타이틀 씬이 열리면 일꾼을 그 씬에서 만든다(씬이 바뀌어도 남김) → 로그인까지 타이틀에서 · 게임 씬의 세션이 이어받아(Attach) 계정 상태만 받는다 · 타이틀 쪽 파일 수정 없음
- ServerLink.Restart = 타이틀을 거쳐 들어온 실행이면 타이틀 씬으로(게임 씬을 바로 연 개발 · 테스트 실행은 그 씬을 다시 연다)
- 타이틀 씬에 없던 버튼 입력 장치(EventSystem)를 로그인 화면 · 다시 시도 안내가 뜰 때 만든다
- 확인: 재컴파일 오류 0 · ServerLinkTests 15 통과 + 1 건너뜀(기존 14 그대로 + 타이틀 씬 시작 2건) · BootFlowTests 8 · TitleScreenTests 8

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
깃 관리자 2026-11-17 18:06:53 +09:00
parent 01bcec9913
commit 2e363fda9c
3 changed files with 284 additions and 24 deletions

View File

@ -1267,6 +1267,23 @@ namespace TKS.OutGame.Net
static void Init()
{
Apply();
FromTitle = false;
UnityEngine.SceneManagement.SceneManager.sceneLoaded -= OnSceneLoaded; // 도메인 리로드를 끈 에디터에서 두 번 걸리지 않게
UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded;
}
/// <summary>타이틀 씬을 거쳐 들어왔는가 — 타이틀부터 다시 시작할 때(Restart) 돌아갈 곳을 정한다.</summary>
public static bool FromTitle { get; private set; }
/// <summary>
/// 타이틀 씬이 열리면(서버 모드) 그 씬에서 접속 · 로그인을 시작한다 — 로그인 화면이 타이틀 위에 뜨고, 로그인이 끝나야 타이틀이 다음으로 넘어간다
/// (타이틀 화면은 접속 일꾼이 있는지 · 끝났는지만 본다 — UI/TitleScreen 의 PressReady). 일꾼은 씬이 바뀌어도 남아 게임 씬의 세션이 이어받는다.
/// </summary>
static void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode)
{
if (!ServerConfig.Active || scene.name != BootScenes.Title) return;
FromTitle = true;
ServerSync.CreateAtTitle();
}
/// <summary>서버 모드면 세션을 ServerSession 으로 만들고, 기기 사본을 따로 둔 파일에 쓴다(기존 save.json 을 덮지 않는다).</summary>
@ -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
/// <summary>
/// 타이틀부터 다시 시작한다(로그아웃 · 계정 삭제 · 다른 기기에서 접속해 세션이 끊김 · 기존 연동 계정으로 들어감) —
/// 지금 씬을 다시 열어 접속 일꾼이 새로 로그인하게 한다(저장한 증표가 없으면 로그인 화면).
/// 타이틀 씬으로 돌아가 접속 일꾼이 새로 로그인하게 한다(저장한 증표가 없으면 타이틀 위에 로그인 화면).
/// 타이틀 씬을 거치지 않고 게임 씬을 바로 연 경우(개발 · 테스트)에는 그 씬을 다시 연다.
/// </summary>
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);
}
/// <summary>
@ -1321,6 +1341,8 @@ namespace TKS.OutGame.Net
{
SkipSignupTimezone = false;
LoginUi = false;
FromTitle = false;
ServerSync.Drop();
ServerClient.ClearMemory();
ServerConfig.ClearForce();
Apply();

View File

@ -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) —
/// 로그인 화면은 타이틀 위에 뜨고, 계정 상태는 게임 씬에서 받는다. 게임 씬을 바로 열면(개발 · 테스트) 전 과정을 그 씬에서 한다.
/// </summary>
public class ServerSync : MonoBehaviour
{
public static ServerSync Instance { get; private set; }
public ServerClient Client { get; private set; }
/// <summary>접속이 끝나 계정 상태를 받았는가.</summary>
/// <summary>다음으로 넘어가도 되는가 — 타이틀 씬(세션 없음)에서는 로그인이 끝났는가 · 게임 씬에서는 계정 상태까지 받았는가.</summary>
public bool Ready { get; private set; }
/// <summary>타이틀 씬에서 만들어져 게임 씬의 세션을 기다리는 중인가.</summary>
public bool AtTitle
{
get { return session == null; }
}
/// <summary>보내는 중이거나 보낼 것이 남았는가.</summary>
public bool Busy
{
@ -63,6 +71,10 @@ namespace TKS.OutGame.Net
readonly Queue<Item> queue = new Queue<Item>();
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);
}
/// <summary>타이틀 씬에서 — 세션 없이 만들어 로그인까지 한다. 씬이 바뀌어도 남는다.</summary>
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<ServerSync>();
s.session = session;
@ -93,6 +124,30 @@ namespace TKS.OutGame.Net
return s;
}
/// <summary>지금 일꾼을 치운다(타이틀부터 다시 시작 · 테스트 정리).</summary>
internal static void Drop()
{
if (Instance == null) return;
Destroy(Instance.gameObject);
Instance = null;
}
/// <summary>
/// 게임 씬의 세션이 타이틀 씬에서 만든 일꾼을 이어받는다 — 로그인 증표와 받아 둔 기준 정보를 그대로 쓰고 계정 상태부터 받는다.
/// 타이틀에서 로그인이 끝나기 전에 넘어왔으면(정상 흐름에서는 없음) 접속을 처음부터 다시 한다.
/// </summary>
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;
}
/// <summary>
/// 버튼 누름을 받는 장치가 씬에 없으면 만든다 — 타이틀 씬은 키 · 터치만 읽어서 장치가 없다(게임 씬은 전투 HUD 가 만든다).
/// 지금 씬에 만들어 씬과 함께 사라지게 한다(이 일꾼은 씬을 넘어가므로 자식으로 두지 않는다).
/// </summary>
static void EnsureInput()
{
if (EventSystem.current != null || FindFirstObjectByType<EventSystem>() != null) return;
var es = new GameObject("EventSystem");
es.AddComponent<EventSystem>();
es.AddComponent<StandaloneInputModule>();
}
void ShowOverlay(string msg, bool button, string buttonLabel = "다시 시도")
{
if (button) EnsureInput();
if (overlay == null) BuildOverlay();
overlayText.text = msg;
overlayButton.SetActive(button);

View File

@ -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 · 위 테스트들은 게임 씬을 바로 연다) ----------
/// <summary>타이틀 씬을 연다(서버 모드 · 로그인 화면 사용) — 접속 일꾼이 타이틀 씬에서 만들어진다.</summary>
IEnumerator BootAtTitle()
{
WorldProgress.Reset();
SaveStore.UseMemory(true);
ServerLink.ForceForTest(TestUrl(), ServerConfig.GameId);
ServerLink.LoginUi = true;
SceneManager.LoadScene(BootScenes.Title);
yield return AtTitle(null);
}
/// <summary>타이틀 씬이 열리고 새 접속 일꾼이 만들어지기를 기다린다(old = 앞 일꾼 · 처음이면 null).</summary>
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, "타이틀 씬 = 타이틀만(로비 없음)");
}
/// <summary>타이틀 위의 로그인 화면에서 고르고 로그인이 끝나기를 기다린다. method = null 이면 화면 없이 이어 하기(저장한 로그인)를 기대한다.</summary>
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, "로그인은 타이틀 씬에서 끝난다");
}
/// <summary>타이틀을 눌러 게임 씬에 들어간다 — 타이틀에서 로그인한 일꾼을 게임 씬의 세션이 이어받아 계정 상태를 받는다.</summary>
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<ServerSession>(og.Session);
yield return Until(() => sync.Ready || sync.LastError != null, 30f, "계정 수신");
Assert.IsTrue(sync.Ready, "서버 접속 실패: " + sync.LastError);
Assert.IsNull(LoginPanel.Current, "로비 위에는 로그인 화면이 뜨지 않는다");
}
/// <summary>
/// 타이틀 씬에서 시작 — 처음 실행이면 타이틀 위에 로그인 화면이 뜨고, 로그인이 끝나야 「Press Any Key」로 게임 씬에 들어간다.
/// 다음 실행(타이틀부터 다시 시작)은 로그인 화면 없이 마지막에 로그인한 계정으로 이어 한다.
/// </summary>
[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<Button>())
if (btn.name == "Guest") guest = btn;
Assert.IsNotNull(guest, "게스트로 시작 버튼");
Assert.IsNotNull(EventSystem.current, "타이틀 씬에 버튼 누름을 받는 장치가 있다");
var rt = (RectTransform)guest.transform;
var hits = new List<RaycastResult>();
EventSystem.current.RaycastAll(new PointerEventData(EventSystem.current) { position = RectTransformUtility.WorldToScreenPoint(Camera.main, rt.TransformPoint(rt.rect.center)) }, hits);
Assert.IsTrue(hits.Count > 0 && hits[0].gameObject.GetComponentInParent<Button>() == guest, "화면 누름이 게스트로 시작 버튼에 닿는다");
yield return TitleLogin(ServerClient.MethodGuest, null);
yield return EnterGame();
var s = og.Session;
Assert.IsTrue(s.IsNewUser, "새 게스트 계정");
Assert.AreEqual(s.Db.Economy.StartGold, s.Save.gold, "계정 상태를 받아 로비에 채운다(골드 = start_gold)");
var a = new ServerResult();
yield return Who(a);
Assert.AreEqual("guest", a.Str("accountType"));
// 다음 실행 — 타이틀 씬에서 로그인 화면 없이 이어 한다
var old = sync;
ServerLink.Restart(); // 앱을 다시 켠 것과 같다
yield return AtTitle(old);
yield return TitleLogin(null, null);
yield return EnterGame();
var b = new ServerResult();
yield return Who(b);
Assert.AreEqual(a.Str("userId"), b.Str("userId"), "같은 계정으로 이어 한다");
}
/// <summary>
/// 타이틀 씬을 거쳐 들어온 뒤 옵션에서 로그아웃하면 게임 씬이 아니라 타이틀 씬으로 돌아가 로그인 화면이 뜨고(마지막 로그인 방식 표시),
/// 다시 로그인하면 그 계정으로 게임 씬에 들어간다.
/// </summary>
[UnityTest]
public IEnumerator Title_Logout_ReturnsToTitleLoginScreen()
{
string id = NewSocialId("ul");
yield return BootAtTitle();
yield return TitleLogin(SocialSignIn.Google, id);
yield return EnterGame();
var a = new ServerResult();
yield return Who(a);
Assert.AreEqual("oauth", a.Str("accountType"));
var old = sync;
string fail = null;
sync.Logout(why => fail = why);
yield return AtTitle(old);
Assert.IsNull(fail, "로그아웃: " + fail);
yield return Until(() => LoginPanel.Current != null || sync.Ready || sync.LastError != null, 20f, "타이틀의 로그인 화면");
Assert.IsNotNull(LoginPanel.Current, "로그아웃 뒤 = 타이틀 위에 로그인 화면: " + sync.LastError);
Assert.IsFalse(sync.Client.HasSaved, "로그아웃하면 이어 할 증표가 남지 않는다");
Assert.AreEqual(SocialSignIn.Google, sync.Client.LastMethod, "마지막에 로그인한 소셜 계정을 기억한다");
yield return CaptureUtil.Capture(Camera.main, 720, 1280, System.IO.Path.Combine("Temp", "tks_title_login_after_logout.png"));
yield return TitleLogin(SocialSignIn.Google, id);
yield return EnterGame();
var b = new ServerResult();
yield return Who(b);
Assert.AreEqual(a.Str("userId"), b.Str("userId"), "다시 로그인하면 그 계정 그대로");
}
static long DeviceOffsetMin()
{
return (long)Math.Round(TimeZoneInfo.Local.GetUtcOffset(DateTime.Now).TotalMinutes);