ThreeKingdomsSlingshot/Assets/Scripts/Runtime/Tutorial/TutorialDirector.cs

1035 lines
47 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.Generic;
using TKS.OutGame;
using UnityEngine;
namespace TKS
{
/// <summary>
/// 1장 학습 판 안내 진행(개발 요청서 C5 · 2026-11-12) — tutorial_guide.csv 를 n_step 순서대로:
/// 앞 단계가 닫힌 뒤 e_trigger 가 맞으면 띄우고, b_lock 1 이면 가리킨 것만 누를 수 있다. 안내는 그 판을 처음 할 때만(클리어 기록) · fail 카드는 매번.
/// 닫힘 = 카드: 탭 · 끌기: 그 행동이 끝남 · 강조·띠: tutorial_config guide_auto_close_sec 뒤 또는 탭 · 누름: 대상을 누름.
/// 끌기 단계 바로 다음이 unit_select 단계면 「조준 안내」 — 그 유닛을 잡고 있는 동안 그 문구·대상을 보여 주고, 쏘면 둘 다 끝난다(손을 떼어 취소하면 끌기 안내로 돌아감).
/// 그 밖: 남은 턴 칩(턴 제한 판) · 안내가 가리키는 함정 보이기(1-7) · 클리어 결말 카드(첫 클리어) · 편성 화면 안내(before_battle).
/// 전장 조작 막기 = SlingshotInput 이 BlocksInput · AllowPress · SnapAim · AllowShot 을 물어본다. 가상 실행(Sim.Active) 중에는 아무 사건도 받지 않는다.
/// </summary>
public class TutorialDirector : MonoBehaviour
{
public static TutorialDirector Current { get; private set; }
const float MinCardSec = 0.35f; // 카드가 뜨자마자 닫히지 않게
const float MinTapSec = 0.2f;
const float HolePad = 18f;
struct Evt
{
public GuideTrigger trig;
public int turn;
public Unit unit;
}
BattleManager battle;
Camera cam;
CameraController camCtrl;
TutorialGuideUI ui;
TutorialPlan plan;
bool guideOn;
bool firstPlay;
readonly List<TutorialGuideRow> steps = new List<TutorialGuideRow>();
readonly List<TutorialGuideRow> failSteps = new List<TutorialGuideRow>();
readonly Queue<TutorialGuideRow> overlay = new Queue<TutorialGuideRow>(); // 결말 · 실패 · 편성 화면 안내
readonly List<Evt> happened = new List<Evt>();
readonly Dictionary<int, GimmickInstance> gimmicks = new Dictionary<int, GimmickInstance>();
readonly HashSet<string> beforeShown = new HashSet<string>();
string beforeChecked = "";
int index;
TutorialGuideRow active;
bool activeOverlay;
TutorialGuideRow hint; // 끌기 안내 중 유닛을 잡았을 때의 조준 안내(다음 단계)
float shownAt;
bool aiming;
bool fired;
bool movedCamera;
bool swallow;
Unit lastActor;
BattlePhase lastPhase = BattlePhase.Setup;
bool bossHold;
bool bossDone;
RectTransform skillButton;
public TutorialPlan Plan
{
get { return plan; }
}
public bool GuideOn
{
get { return guideOn; }
}
public TutorialGuideRow ActiveStep
{
get { return active; }
}
/// <summary>조준 안내가 떠 있으면 그 단계.</summary>
public TutorialGuideRow HintStep
{
get { return hint; }
}
public int StepIndex
{
get { return index; }
}
public int StepCount
{
get { return steps.Count; }
}
public TutorialGuideUI Ui
{
get { return ui; }
}
public static TutorialDirector Ensure(BattleManager bm)
{
if (Current != null && Current.battle == bm) return Current;
var go = new GameObject("TutorialDirector");
go.transform.SetParent(bm.transform, false);
var d = go.AddComponent<TutorialDirector>();
d.Init(bm);
return d;
}
void Init(BattleManager bm)
{
Current = this;
battle = bm;
cam = Camera.main;
camCtrl = cam != null ? cam.GetComponent<CameraController>() : null;
if (cam != null) ui = TutorialGuideUI.Create(transform, cam);
bm.PhaseChanged += OnPhase;
bm.UnitActing += OnUnitActing;
bm.Changed += RefreshTurnChip;
}
void OnDestroy()
{
if (Current == this) Current = null;
if (battle == null) return;
battle.PhaseChanged -= OnPhase;
battle.UnitActing -= OnUnitActing;
battle.Changed -= RefreshTurnChip;
}
float Num(string key, float fallback)
{
var db = plan != null ? plan.Db : TutorialTables.Db;
return db != null ? db.Num(key, fallback) : fallback;
}
// ---------- 판 시작 ----------
/// <summary>전투 시작(BattleManager.Begin · 유닛·기믹 배치 뒤 · 첫 턴 전). p = 그 판의 학습 판 계획(null = 일반 판).</summary>
public void BeginStage(TutorialPlan p)
{
plan = p;
steps.Clear();
failSteps.Clear();
overlay.Clear();
happened.Clear();
gimmicks.Clear();
index = 0;
active = null;
hint = null;
activeOverlay = aiming = fired = movedCamera = swallow = false;
bossHold = bossDone = false;
lastActor = null;
lastPhase = BattlePhase.Setup;
guideOn = false;
RefreshInfo();
RefreshTurnChip();
if (p == null || ui == null) return;
firstPlay = !TutorialRules.Cleared(p.Row.chapter, p.Row.stage);
var rows = p.Guide(); // 연의 전기 막 = 덮어쓴 문구(Resources/Scenario/scenario_guide.csv)
foreach (var g in rows)
{
if (g.trigger == GuideTrigger.Fail) failSteps.Add(g);
else if (g.trigger != GuideTrigger.BeforeBattle && firstPlay) steps.Add(g);
}
guideOn = steps.Count > 0;
// 배치 표 기믹 슬롯 ↔ 전장 기믹(같은 id · 같은 자리)
var layer = battle.Gimmicks;
if (layer != null)
{
foreach (var r in p.Layout)
{
if (r.side != TutSide.Gimmick) continue;
foreach (var g in layer.Items)
{
if (g.Id != r.gimmickId || Vector2.Distance(g.Shape.Center, r.pos) > 0.05f || gimmicks.ContainsValue(g)) continue;
gimmicks[r.slot] = g;
break;
}
}
}
// 안내가 가리키는 함정은 이 판에서 자리를 보여 준다(1-7 「이번만 함정 자리를 보여 줍니다」 · 클리어 뒤 다시 해도 같음)
foreach (var g in rows)
{
foreach (var slot in g.Target.AllSlots())
{
GimmickInstance gi;
if (gimmicks.TryGetValue(slot, out gi) && gi.Zone == GimmickZone.Trap && gi.View != null && gi.View.Body != null) gi.View.Body.gameObject.SetActive(true);
}
}
happened.Add(new Evt { trig = GuideTrigger.StageStart });
}
/// <summary>보스 등장 연출(C2)이 시작될 때 부른다 — 끝나면 NotifyBossIntroEnd. 부르지 않으면 첫 아군 턴에 boss_intro_end 로 본다.</summary>
public void HoldBossIntro()
{
bossHold = true;
}
public void NotifyBossIntroEnd()
{
if (bossDone) return;
bossHold = false;
bossDone = true;
Add(GuideTrigger.BossIntroEnd, battle.TurnNumber, null);
TryAdvance();
}
// ---------- 전투 사건 ----------
void Add(GuideTrigger trig, int turn, Unit u)
{
if (!guideOn) return;
happened.Add(new Evt { trig = trig, turn = turn, unit = u });
}
void OnPhase(BattlePhase p)
{
if (Sim.Active) return;
var prev = lastPhase;
lastPhase = p;
RefreshTurnChip();
if (p == BattlePhase.Setup)
{
BeginStage(null); // 전투 없음(월드맵·로비)
return;
}
if (plan == null) return;
int turn = battle.TurnNumber;
if (prev == BattlePhase.Resolving)
{
Add(GuideTrigger.ActionEnd, turn, lastActor);
if (active != null && !activeOverlay && active.mode == GuideMode.Drag && fired) CloseActive(false, true);
}
switch (p)
{
case BattlePhase.PlayerTurn:
if (prev != BattlePhase.Resolving)
{
Add(GuideTrigger.TurnStart, turn, null);
if (!bossHold && !bossDone)
{
bossDone = true;
Add(GuideTrigger.BossIntroEnd, turn, null);
}
}
break;
case BattlePhase.EnemyTurn:
Add(GuideTrigger.EnemyTurn, turn, null);
// 잠기지 않은 끌기·누름 안내는 아군 턴이 끝나면 닫는다
if (active != null && !activeOverlay && !active.locked && (active.mode == GuideMode.Drag || active.mode == GuideMode.Tap)) CloseActive(false, false);
break;
case BattlePhase.StageClear:
EndGuide();
if (firstPlay && !string.IsNullOrEmpty(plan.Row.clearKo))
overlay.Enqueue(new TutorialGuideRow { chapter = plan.Row.chapter, stage = plan.Row.stage, mode = GuideMode.Popup, locked = true, textKo = plan.Row.clearKo });
break;
case BattlePhase.Defeat:
EndGuide();
foreach (var f in failSteps) overlay.Enqueue(f);
break;
}
TryAdvance();
}
void OnUnitActing(Unit u)
{
if (Sim.Active || u == null) return;
lastActor = u;
if (u.Faction != Faction.Player || active == null || activeOverlay) return;
if (active.mode == GuideMode.Drag && u == FromUnit(active))
{
fired = true;
aiming = false;
RefreshInfo();
}
else if (!active.locked && active.mode == GuideMode.Tap) CloseActive(false, false);
}
/// <summary>유닛을 골랐다(SlingshotInput.Select).</summary>
public void OnSelect(Unit u)
{
if (u == null || plan == null || !guideOn) return;
bool canAct = u.Faction == Faction.Player && battle.CanAct(u);
if (canAct) Add(GuideTrigger.UnitSelect, battle.TurnNumber, u);
if (active != null && !activeOverlay)
{
if (active.mode == GuideMode.Tap && active.Target.kind == GuideTargetKind.Slots && IsTargetUnit(active, u)) CloseActive(false, false);
else if (active.mode == GuideMode.Drag && canAct && !fired && u == FromUnit(active))
{
aiming = true;
hint = NextAimHint();
RefreshInfo();
}
}
TryAdvance();
}
/// <summary>당기다가 쏘지 않고 손을 뗐다.</summary>
public void OnAimCancelled()
{
if (!aiming) return;
aiming = false;
hint = null;
RefreshInfo();
}
/// <summary>스킬 버튼을 눌렀다.</summary>
public void NotifySkillTap()
{
if (active == null || activeOverlay) return;
if (active.Target.kind == GuideTargetKind.Ui && active.Target.ui == "skill" && (active.mode == GuideMode.Tap || active.mode == GuideMode.Highlight)) CloseActive(false, false);
}
void EndGuide()
{
active = null;
hint = null;
activeOverlay = aiming = fired = false;
index = steps.Count;
RefreshInfo();
}
// ---------- 단계 진행 ----------
TutorialGuideRow NextAimHint()
{
return index + 1 < steps.Count && steps[index + 1].trigger == GuideTrigger.UnitSelect ? steps[index + 1] : null;
}
static bool NeedsPlayerTurn(TutorialGuideRow s)
{
return s.locked || s.mode == GuideMode.Popup || s.mode == GuideMode.Drag || s.mode == GuideMode.Tap;
}
/// <summary>그 단계의 조건을 채운 사건 위치(없으면 −1 · after_step = −2).</summary>
int Match(TutorialGuideRow s)
{
if (s.trigger == GuideTrigger.AfterStep) return -2;
Unit want = null;
if (s.trigger == GuideTrigger.UnitSelect && s.Target.kind == GuideTargetKind.Slots)
{
foreach (var slot in s.Target.slots)
{
var r = plan.SlotRow(slot);
if (r != null && r.side == TutSide.Ally) want = plan.UnitAt(slot);
}
}
for (int i = 0; i < happened.Count; i++)
{
var e = happened[i];
if (e.trig != s.trigger) continue;
if (s.turn > 0 && e.turn != s.turn && s.trigger != GuideTrigger.StageStart && s.trigger != GuideTrigger.BossIntroEnd) continue;
if (want != null && e.unit != want) continue;
return i;
}
return -1;
}
/// <summary>턴이 지나 더는 일어날 수 없는 단계(건너뜀).</summary>
bool Stale(TutorialGuideRow s)
{
if (s.turn <= 0 || battle.TurnNumber <= s.turn) return false;
return s.trigger == GuideTrigger.ActionEnd || s.trigger == GuideTrigger.EnemyTurn || s.trigger == GuideTrigger.TurnStart || s.trigger == GuideTrigger.UnitSelect;
}
void TryAdvance()
{
if (active != null || ui == null) return;
if (overlay.Count > 0)
{
Show(overlay.Dequeue(), true);
return;
}
if (!guideOn || plan == null) return;
if (ScenarioEvent.Running) return; // 연출 중에는 안내를 띄우지 않는다(연출이 끝나면 다음 Update · Poll 에서 띄움 · 2026-11-19 적 턴 연출 뒤 반격 카드)
var ph = battle.Phase;
if (ph == BattlePhase.Setup || ph == BattlePhase.StageClear || ph == BattlePhase.Defeat) return;
while (index < steps.Count)
{
var s = steps[index];
int at = Match(s);
if (at != -1)
{
// 아군 턴까지 기다림 — 적 턴 시작 카드(enemy_turn popup)만 적 턴에 바로 띄움(적은 BattleManager 에서 카드가 닫힐 때까지 기다림 · 2026-11-19 연의 1막 반격 카드가 2턴에야 뜨던 문제)
bool enemyCard = enemyGate && s.trigger == GuideTrigger.EnemyTurn && s.mode == GuideMode.Popup && ph == BattlePhase.EnemyTurn; // 적 턴 연출(enemy_turn)이 끝난 뒤 BattleManager 가 Poll 로 부를 때만
if (NeedsPlayerTurn(s) && ph != BattlePhase.PlayerTurn && !enemyCard) return;
if (at >= 0) happened.RemoveRange(0, at + 1);
Show(s, false);
return;
}
if (!Stale(s)) return;
index++;
}
}
/// <summary>떠 있는 안내가 없으면 지금 띄울 안내를 찾는다(BattleManager 적 턴 — 연출 직후 카드가 같은 프레임에 뜨게).</summary>
public void Poll()
{
if (active != null) return;
enemyGate = true;
TryAdvance();
enemyGate = false;
}
bool enemyGate;
/// <summary>
/// 끌기 시범(카드 + 끌기 대상 slot:A>slot:B · 2026-11-19 PD 「화살표를 끌어 당기는 연출을 함께」) — SlingshotInput 이 실제 조준 화살표 · 게이지로 그린다.
/// k = 끈 정도(0~1 · 손가락과 같은 주기) · gaugeSec = 화살표가 뜬 뒤 흐른 시간(게이지 표시선).
/// </summary>
public bool DemoAim(out Unit u, out Vector2 to, out float k, out float gaugeSec)
{
u = null;
to = Vector2.zero;
k = gaugeSec = 0f;
if (active == null || active.mode != GuideMode.Popup || active.Target.kind != GuideTargetKind.Drag) return false;
u = FromUnit(active);
if (u == null || !u.IsAlive) return false;
to = DragPoint(active);
float cycle = Mathf.Max(0.3f, ScenarioData.EvCfg("guide_demo_cycle_sec")); // 표 = scenario_event_config.csv(연의 전기 F5 로 다시 읽힘)
float t = ((Time.unscaledTime - shownAt) % cycle) / cycle;
k = DemoPull(t);
gaugeSec = t < 0.15f ? 0f : (t - 0.15f) * cycle;
return true;
}
/// <summary>시범 주기 안의 끈 정도 — 0~0.15 누름 · ~0.6 끌기 · ~0.9 멈춤(게이지가 오감) · ~1 놓음.</summary>
static float DemoPull(float t)
{
return t < 0.15f ? 0f : t < 0.6f ? Mathf.SmoothStep(0f, 1f, (t - 0.15f) / 0.45f) : t < 0.9f ? 1f : 0f;
}
void Show(TutorialGuideRow s, bool isOverlay)
{
active = s;
activeOverlay = isOverlay;
hint = null;
aiming = fired = false;
shownAt = Time.unscaledTime;
FocusCamera(s);
refocus = true; // 다음 프레임에 한 번 더 — 같은 순간 아군 턴 시작 초점(GameBootstrap)이 덮어쓰지 않게(2026-11-19 PD 「포커싱이 끝나야 카메라가 이동」)
RefreshInfo();
}
bool refocus;
/// <summary>byTap = 화면을 눌러 닫음(그 누름이 전장 조작으로 새지 않게) · byAction = 끌기 안내의 행동이 끝나 닫힘.</summary>
void CloseActive(bool byTap, bool byAction)
{
var row = active;
if (row == null) return;
bool wasOverlay = activeOverlay;
bool hadHint = !wasOverlay && row.mode == GuideMode.Drag && byAction && NextAimHint() != null;
active = null;
hint = null;
activeOverlay = aiming = fired = false;
if (!wasOverlay) index += hadHint ? 2 : 1; // 조준 안내는 끌기와 함께 끝난다
if (byTap && (row.locked || row.mode == GuideMode.Popup)) swallow = true;
RefreshInfo();
TryAdvance();
if (active == null && movedCamera) RestoreCamera();
}
/// <summary>테스트·검증 캡처: 화면을 누른 것처럼 지금 안내(카드 · 강조 · 띠)를 닫는다.</summary>
public void TapForTest()
{
if (active == null) return;
if (active.mode == GuideMode.Popup || ((active.mode == GuideMode.Highlight || active.mode == GuideMode.Bar) && !WaitsForSkill(active))) CloseActive(false, false);
}
// ---------- 입력(SlingshotInput 이 물어봄) ----------
/// <summary>화면 누름을 전장 조작·결과 넘기기로 보내지 않는다(카드 · 잠긴 강조·띠 · 방금 탭으로 닫은 누름).</summary>
public bool BlocksInput
{
get
{
if (swallow) return true;
if (active == null) return false;
if (active.mode == GuideMode.Popup) return true;
return active.locked && (active.mode == GuideMode.Highlight || active.mode == GuideMode.Bar) && !WaitsForSkill(active);
}
}
/// <summary>잠금 안내가 떠 있다(가리킨 것만 누를 수 있다 · 화면 끌기·확대 막힘).</summary>
public bool Locked
{
get { return active != null && active.locked; }
}
static bool WaitsForSkill(TutorialGuideRow s)
{
return s.locked && s.mode == GuideMode.Highlight && s.Target.kind == GuideTargetKind.Ui && s.Target.ui == "skill";
}
/// <summary>잠금 안내 중 이 누름을 받아도 되는가 — under = 누른 자리의 아군 유닛(없으면 null).</summary>
public bool AllowPress(Vector2 screen, Unit under)
{
if (active == null || !active.locked) return true;
bool overSkill = OverSkillButton(screen);
switch (active.mode)
{
case GuideMode.Drag:
return !fired && !overSkill && under != null && under == FromUnit(active);
case GuideMode.Tap:
if (active.Target.kind == GuideTargetKind.Ui) return active.Target.ui == "skill" && overSkill;
return !overSkill && under != null && IsTargetUnit(active, under);
case GuideMode.Highlight:
return WaitsForSkill(active) && overSkill;
}
return false;
}
/// <summary>
/// 잠긴 끌기 안내 중 snap 단계(연의 scenario_guide b_snap)만 — 어느 쪽으로 끌어도 **방향만** 목표로 맞춘다 · 세기 = 플레이어가 당긴 그대로 ·
/// 그 밖의 잠긴 끌기 = 맞추지 않음(자연스러운 좌우 조준 · 발사는 허용 각도 안만 = AllowShot)
/// (2026-11-18 PD 「항상 플레이어가 조작할 유닛의 슬링샷 파워는 제약 없이 조절이 가능해야 해」 — 그 전 = 표 drag_lock_shot_pull 세기로 고정 →
/// 1막 시작처럼 적과 가까울 때 화살표 세기를 늘릴 수 없었음).
/// </summary>
public Vector2 SnapAim(Unit u, Vector2 target)
{
if (active == null || !active.locked || active.mode != GuideMode.Drag || u == null || u != FromUnit(active)) return target;
Vector2 want = DragPoint(active) - u.Position;
Vector2 aim = target - u.Position;
if (want.sqrMagnitude < 1e-4f || aim.sqrMagnitude < 1e-4f) return target;
if (!active.snap)
{
// 조준 범위(f_aim_deg) = 목표 방향 ± 도 안에서만 — 밖으로 끌면 가장자리에 머묾(엉뚱한 방향 돌진으로 안내한 적이 바뀌지 않게 · 2026-11-19 PD) · 0 = 그대로
if (active.aimDeg <= 0f) return target; // 맞춤 없음(2026-11-18 PD 「적이 근접할 때 화살표가 좌우로 자연스럽지 않고 특정 자리에 붙음」)
float ang = Vector2.SignedAngle(want, aim);
if (Mathf.Abs(ang) <= active.aimDeg) return target;
Vector2 edge = Quaternion.Euler(0f, 0f, Mathf.Sign(ang) * active.aimDeg) * want.normalized;
return u.Position + edge * aim.magnitude; // 전장 안으로 자르지 않음 = 가장자리에서도 세기를 끝까지(벽에 닿으면 이동 처리가 튕김 · 2026-11-19 PD 「화면 가장자리에서는 슬롯 파워를 세게 할 수 없음」)
}
// snap 단계 = 어느 쪽으로 끌어도 목표 방향(2026-11-18 PD 「정해진 방향으로 무조건 쏠 수 있도록 유도」) · 각도 검사 없음
float max = SkillMods.SlingMax(u);
if (aim.magnitude < max * MinPull - 0.01f) return target; // 덜 당김 = 그대로 보여 주고 발사는 거부
return u.Position + want.normalized * aim.magnitude; // 전장 안으로 자르지 않음 = 가장자리에서도 세기를 끝까지(벽에 닿으면 이동 처리가 튕김 · 2026-11-19 PD 「화면 가장자리에서는 슬롯 파워를 세게 할 수 없음」)
}
/// <summary>이 발사를 허용하는가 — 잠긴 끌기 안내 = 그 유닛 · 목표 방향 · 최소 당김 이상 / 그 밖의 잠금 안내 = 발사 불가.</summary>
public bool AllowShot(Unit u, Vector2 target)
{
if (active == null || !active.locked) return true;
if (active.mode != GuideMode.Drag || u == null || u != FromUnit(active)) return false;
Vector2 want = DragPoint(active) - u.Position;
Vector2 aim = target - u.Position;
if (want.sqrMagnitude < 1e-4f || aim.sqrMagnitude < 1e-4f) return false;
if (Vector2.Angle(want, aim) > Num("drag_lock_angle_deg", 0f) + 0.5f) return false;
Vector2 full = u.Position + aim.normalized * SkillMods.SlingMax(u); // 최소 당김 = 최대 거리 기준(전장 끝으로 줄이지 않음)
return aim.magnitude >= Vector2.Distance(full, u.Position) * MinPull - 0.02f;
}
/// <summary>지금 잠긴 끌기 단계의 최소 당김 — 단계 값(연의 f_min_pull)이 있으면 그것 · 없으면 표 drag_lock_min_pull.</summary>
float MinPull
{
get { return active != null && active.minPull >= 0f ? active.minPull : Num("drag_lock_min_pull", 0f); }
}
bool OverSkillButton(Vector2 screen)
{
var rt = SkillButton;
return rt != null && rt.gameObject.activeInHierarchy && RectTransformUtility.RectangleContainsScreenPoint(rt, screen, cam);
}
RectTransform SkillButton
{
get
{
if (skillButton == null && battle.Hud != null)
{
var t = battle.Hud.transform.Find("Info/SkillButton");
skillButton = t as RectTransform;
}
return skillButton;
}
}
// ---------- 대상 ----------
Unit FromUnit(TutorialGuideRow s)
{
return plan != null && s.Target.kind == GuideTargetKind.Drag ? plan.UnitAt(s.Target.from) : null;
}
/// <summary>끌기 안내의 쏠 곳(대상 슬롯의 지금 자리 또는 전장 좌표 점).</summary>
Vector2 DragPoint(TutorialGuideRow s)
{
var t = s.Target;
if (t.to <= 0) return t.point;
Vector2 p;
return SlotCenter(t.to, out p) ? p : t.point;
}
bool IsTargetUnit(TutorialGuideRow s, Unit u)
{
if (plan == null || s.Target.kind != GuideTargetKind.Slots) return false;
foreach (var slot in s.Target.slots)
if (plan.UnitAt(slot) == u) return true;
return false;
}
bool SlotCenter(int slot, out Vector2 p)
{
p = Vector2.zero;
if (plan == null) return false;
var u = plan.UnitAt(slot);
if (u != null)
{
p = u.Position;
return u.IsAlive;
}
GimmickInstance g;
if (gimmicks.TryGetValue(slot, out g) && !g.Removed)
{
p = g.Shape.Center;
return true;
}
var r = plan.SlotRow(slot);
if (r == null) return false;
p = r.pos;
return r.side == TutSide.Gimmick; // 배치 자리(기믹 연결이 없을 때)
}
/// <summary>그 단계가 가리키는 전장 대상의 사각(전장 좌표 가운데·반 크기 · round = 유닛·원 기믹).</summary>
void WorldTargets(TutorialGuideRow s, List<Vector2> centers, List<Vector2> halves, List<bool> rounds)
{
if (plan == null) return;
var t = s.Target;
var slots = new List<int>();
if (t.kind == GuideTargetKind.Slots) slots.AddRange(t.slots);
else if (t.kind == GuideTargetKind.Drag)
{
slots.Add(t.from);
if (t.to > 0) slots.Add(t.to);
}
foreach (var slot in slots)
{
var u = plan.UnitAt(slot);
if (u != null)
{
if (!u.IsAlive) continue;
if (u.View != null && u.View.HasArt)
{
// 그림(발 = −0.55 R · 키 = ArtHeight) 전체를 감싼다
float h = u.ArtHeight + 0.3f;
centers.Add(u.Position + new Vector2(0f, -u.Radius * 0.55f + u.ArtHeight * 0.5f));
halves.Add(new Vector2(Mathf.Max(u.Radius * 1.5f, h * 0.42f), h * 0.5f));
}
else
{
centers.Add(u.Position);
halves.Add(Vector2.one * u.Radius * 1.5f);
}
rounds.Add(true);
continue;
}
GimmickInstance g;
if (!gimmicks.TryGetValue(slot, out g) || g.Removed) continue;
bool circle = g.Shape.Type == GimmickShapeType.Circle;
centers.Add(g.Shape.Center);
halves.Add(circle ? Vector2.one * g.Shape.R * 1.25f : g.Shape.Size * 0.5f + Vector2.one * 0.15f);
rounds.Add(circle);
}
}
/// <summary>UI 대상(남은 턴 · 스킬 버튼 · 편성 화면 출전 칸)의 캔버스 사각.</summary>
bool UiTarget(TutorialGuideRow s, out Rect rect)
{
rect = new Rect();
if (s.Target.kind != GuideTargetKind.Ui || ui == null) return false;
switch (s.Target.ui)
{
case "turn":
if (!ui.TurnChipVisible) return false;
rect = ui.UiRect(ui.TurnChip);
return true;
case "skill":
var sb = SkillButton;
if (sb == null || !sb.gameObject.activeInHierarchy) return false;
rect = ui.UiRect(sb);
return true;
case "lineup":
var root = OutGameRoot.Instance;
if (root == null || root.Formation == null || root.Formation.Rt == null) return false;
bool any = false;
foreach (var rt in root.Formation.Rt.GetComponentsInChildren<RectTransform>(false))
{
string n = rt.name;
if (n.Length != 5 || !n.StartsWith("Slot") || !char.IsDigit(n[4])) continue;
var r = ui.UiRect(rt);
rect = any ? Rect.MinMaxRect(Mathf.Min(rect.xMin, r.xMin), Mathf.Min(rect.yMin, r.yMin), Mathf.Max(rect.xMax, r.xMax), Mathf.Max(rect.yMax, r.yMax)) : r;
any = true;
}
return any;
}
return false;
}
// ---------- 카메라 ----------
readonly List<Vector2> tmpC = new List<Vector2>();
readonly List<Vector2> tmpH = new List<Vector2>();
readonly List<bool> tmpR = new List<bool>();
/// <summary>대상이 화면 밖이면 대상들의 가운데로 화면을 옮긴다.</summary>
/// <summary>force = 이미 가운데여도 초점을 다시 건다(다른 곳이 같은 프레임에 초점을 옮겼을 수 있음).</summary>
void FocusCamera(TutorialGuideRow s, bool force = false)
{
if (camCtrl == null || plan == null) return;
tmpC.Clear();
tmpH.Clear();
tmpR.Clear();
WorldTargets(s, tmpC, tmpH, tmpR);
if (s.Target.kind == GuideTargetKind.Drag && s.Target.to <= 0)
{
tmpC.Add(s.Target.point);
tmpH.Add(Vector2.one * 0.5f);
}
if (tmpC.Count == 0) return;
Vector2 min = tmpC[0] - tmpH[0], max = tmpC[0] + tmpH[0];
for (int i = 1; i < tmpC.Count; i++)
{
min = Vector2.Min(min, tmpC[i] - tmpH[i]);
max = Vector2.Max(max, tmpC[i] + tmpH[i]);
}
var view = camCtrl.ViewRect;
// 위 턴 띠 · 유닛 판(2026-11-19 위로 옮김) · 맨 위 카드(끌기 시범) · 위 띠(끌기 안내 = 유닛 판 아래) · 아래 패시브 글자 뒤로 가지 않게
bool deepTop = s.mode == GuideMode.Drag || (s.mode == GuideMode.Popup && s.Target.kind == GuideTargetKind.Drag);
float topF = deepTop ? 0.35f : 0.27f, botF = 0.14f, sideF = 0.08f;
// 대상 전체 = 쓸 수 있는 화면(위 · 아래 판 사이) 가운데 · 다 안 들어가면 그만큼 넓힘(넓히기만) — 대상이 화면 안이어도 한쪽에 치우쳐 아래 · 위가 쓸데없이 보이지 않게
// (2026-11-19 PD 「관우가 바위를 쳐서 황건적을 공격하는 상황을 알 수 있게 · 슬링샷 구도가 하단을 쓸데없이 너무 많이 노출」 · 그 전 = 화면 안이면 그대로)
float aspect = view.width / Mathf.Max(0.01f, view.height);
float needH = Mathf.Max((max.y - min.y) / Mathf.Max(0.2f, 1f - topF - botF), (max.x - min.x) / Mathf.Max(0.2f, (1f - 2f * sideF) * aspect));
float h = Mathf.Max(view.height, needH);
Vector2 goal = (min + max) * 0.5f - new Vector2(0f, (botF - topF) * h * 0.5f);
bool widen = h > view.height + 0.01f;
if (!widen && !force && Vector2.Distance(goal, view.center) < 0.3f) return;
camCtrl.StopFollow();
if (widen) camCtrl.ZoomTo(h, goal); // 기준점 = 새 가운데(초점 이동과 함께 그 자리로 모임)
camCtrl.FocusOn(goal);
movedCamera = true;
}
/// <summary>아군(구출 대상 제외) 쪽으로 화면을 되돌린다(GameBootstrap 의 아군 턴 초점과 같은 식).</summary>
void RestoreCamera()
{
movedCamera = false;
if (camCtrl == null || battle.Phase != BattlePhase.PlayerTurn) return;
Vector2 sum = Vector2.zero;
int n = 0;
foreach (var p in battle.AliveUnits(Faction.Player))
{
if (p.Npc || ScenarioEvent.Absent(p)) continue;
sum += p.Position;
n++;
}
if (n > 0) camCtrl.FocusOn(sum / n + new Vector2(0f, battle.Config.cameraViewHeight * 0.2f));
}
// ---------- 표시 ----------
/// <summary>띠·카드·누름 막이(단계가 바뀔 때만).</summary>
void RefreshInfo()
{
if (ui == null) return;
if (active == null)
{
ui.SetBar("");
ui.SetCard("");
ui.SetBlocker(false);
return;
}
if (active.mode == GuideMode.Popup)
{
ui.SetBar("");
ui.SetCard(active.textKo);
ui.SetBlocker(true);
return;
}
ui.SetCard("");
// 끌기 안내 = 그 유닛을 누르고 있는 동안(aiming) 띠를 걷음 · 쏘지 않고 놓으면(OnAimCancelled) 다시(2026-11-19 PD 「장비를 터치한 상태가 되면 제거 · 터치 해제 상태로 전환할 경우에만」)
bool holding = aiming && active.mode == GuideMode.Drag;
ui.SetBar(fired ? "" : hint != null ? hint.textKo : holding ? "" : active.textKo);
ui.SetBlocker(active.locked && (active.mode == GuideMode.Highlight || active.mode == GuideMode.Bar) && !WaitsForSkill(active));
}
void RefreshTurnChip()
{
if (ui == null) return;
var ph = battle.Phase;
bool on = plan != null && plan.TurnLimit > 0 && (ph == BattlePhase.PlayerTurn || ph == BattlePhase.Resolving || ph == BattlePhase.EnemyTurn);
ui.SetTurnsLeft(on ? "남은 턴 " + Mathf.Max(0, plan.TurnLimit - battle.TurnNumber + 1) : "");
}
void Update()
{
if (ui == null) return;
if (swallow && !Input.GetMouseButton(0) && !Input.GetMouseButtonUp(0)) swallow = false;
PollBeforeBattle();
if (refocus)
{
refocus = false;
if (active != null && !activeOverlay) FocusCamera(active, true);
}
if (active != null)
{
float age = Time.unscaledTime - shownAt;
bool down = Input.GetMouseButtonDown(0);
switch (active.mode)
{
case GuideMode.Popup:
if (down && age > MinCardSec) CloseActive(true, false);
break;
case GuideMode.Highlight:
case GuideMode.Bar:
if (WaitsForSkill(active)) break;
if (down && age > MinTapSec) CloseActive(true, false);
else if (age > Num("guide_auto_close_sec", 1.5f)) CloseActive(false, false);
break;
case GuideMode.Drag:
case GuideMode.Tap:
// 가리킨 유닛이 쓰러졌거나 이번 턴에 더 움직일 수 없으면 건너뛴다(잠금에 갇히지 않게)
if (!activeOverlay && !fired && battle.Phase == BattlePhase.PlayerTurn && !TargetUsable(active)) CloseActive(false, false);
break;
}
}
else TryAdvance();
Draw();
}
bool TargetUsable(TutorialGuideRow s)
{
if (s.mode == GuideMode.Drag)
{
var u = FromUnit(s);
return u != null && u.IsAlive && battle.CanAct(u);
}
if (s.Target.kind != GuideTargetKind.Slots) return true;
foreach (var slot in s.Target.slots)
{
var u = plan.UnitAt(slot);
if (u != null && u.IsAlive) return true;
}
return false;
}
void Draw()
{
ui.BeginFrame();
var row = active;
if (row != null && !(row.mode == GuideMode.Drag && fired))
{
var shown = hint ?? row;
float pulse = 1f + 0.06f * Mathf.Sin(Time.unscaledTime * 6f);
tmpC.Clear();
tmpH.Clear();
tmpR.Clear();
WorldTargets(shown, tmpC, tmpH, tmpR);
var rects = new List<Rect>();
for (int i = 0; i < tmpC.Count; i++) rects.Add(ui.WorldRect(tmpC[i], tmpH[i]));
Rect uiRect;
bool hasUi = UiTarget(shown, out uiRect);
if (hasUi)
{
rects.Add(uiRect);
tmpR.Add(false);
}
bool dim = row.mode == GuideMode.Popup || (row.mode == GuideMode.Highlight && !aiming);
if (dim)
{
if (rects.Count == 0) ui.Dim(Num("dim_alpha", 0.5f), null);
else
{
var hole = rects[0];
for (int i = 1; i < rects.Count; i++)
hole = Rect.MinMaxRect(Mathf.Min(hole.xMin, rects[i].xMin), Mathf.Min(hole.yMin, rects[i].yMin), Mathf.Max(hole.xMax, rects[i].xMax), Mathf.Max(hole.yMax, rects[i].yMax));
ui.Dim(Num("dim_alpha", 0.5f), Rect.MinMaxRect(hole.xMin - HolePad, hole.yMin - HolePad, hole.xMax + HolePad, hole.yMax + HolePad));
}
}
for (int i = 0; i < rects.Count; i++) ui.Frame(rects[i], tmpR[i], pulse);
// 띠·카드가 가리키는 대상(과 당기는 손가락)을 덮지 않게 자리를 고른다
if (row.mode == GuideMode.Popup)
{
if (rects.Count == 0) ui.PlaceCard(0);
else ui.PlaceCard(PickCard(rects)); // 대상(특히 첫 대상 = 조작할 유닛)을 덮지 않는 자리(2026-11-19 PD 「튜토리얼이 핵심적으로 조작해야 할 유닛을 가리지 않도록」)
}
else
{
bool low = row.mode == GuideMode.Drag; // 끄는 손가락은 화면 아래쪽의 유닛에서 출발한다
foreach (var r in rects)
if (r.yMin < ui.BarZoneTop) low = true;
ui.PlaceBar(low);
}
if (row.mode == GuideMode.Drag) DrawDrag(row);
else if (row.mode == GuideMode.Popup) DrawDemoFinger(); // 카드 + 끌기 시범 = 손가락(화살표 · 게이지 = SlingshotInput)
else if (row.mode == GuideMode.Tap && rects.Count > 0)
{
float press = 0.5f + 0.5f * Mathf.Sin(Time.unscaledTime * 6f);
ui.Finger(rects[0].center, press, 1f);
}
}
ui.EndFrame();
}
/// <summary>카드 자리 고르기 — 맨 위(낮은 카드) → 아래 → 위 → 가운데 순으로, 1차 = 대상 전부를 덮지 않는 곳 · 2차 = 첫 대상(조작할 유닛 · 끌기 시작 유닛)만 덮지 않는 곳 · 없으면 맨 위.</summary>
int PickCard(List<Rect> rects)
{
for (int pass = 0; pass < 2; pass++)
foreach (int w in CardOrder)
{
var cr = ui.CardRect(w);
int n = pass == 0 ? rects.Count : 1;
bool hit = false;
for (int i = 0; i < n && !hit; i++)
{
var r = rects[i];
if (Rect.MinMaxRect(r.xMin - HolePad, r.yMin - HolePad, r.xMax + HolePad, r.yMax + HolePad).Overlaps(cr)) hit = true;
}
if (!hit) return w;
}
return 2;
}
static readonly int[] CardOrder = { 2, -1, 1, 0 };
void DrawDrag(TutorialGuideRow row)
{
var u = FromUnit(row);
if (u == null || !u.IsAlive) return;
Vector2 to = DragPoint(row);
Vector2 dir = to - u.Position;
if (dir.sqrMagnitude < 1e-4f) return;
dir.Normalize();
if (row.Target.to <= 0)
{
var r = ui.WorldRect(to, Vector2.one * u.Radius);
ui.AimEnd(r.center, Mathf.Max(r.width, r.height)); // 점 목표 = 조준선 끝 고리(슬롯 목표는 테두리가 이미 있다)
}
if (aiming) return; // 유닛을 잡고 있는 동안 = 손가락 숨김(조준 화살표가 보인다)
// 게이지 조작(PD 2026-11-16): 손가락은 유닛에서 목표 쪽으로 끈다(끈 거리는 방향만 정하므로 목표를 넘지 않게)
float pull = Mathf.Min(SkillMods.SlingMax(u) * Num("finger_pull_ratio", 1f), Vector2.Distance(to, u.Position));
Vector2 a = ui.ToCanvas(u.Position);
Vector2 b = ClampToward(a, ui.ToCanvas(u.Position + dir * pull), ui.SafeRect);
float cycle = Mathf.Max(0.3f, Num("finger_cycle_sec", 1.6f));
float t = ((Time.unscaledTime - shownAt) % cycle) / cycle;
// 0~0.15 누름 · ~0.7 끌기 · ~0.85 멈춤 · ~1 놓음
float k = t < 0.15f ? 0f : t < 0.7f ? Mathf.SmoothStep(0f, 1f, (t - 0.15f) / 0.55f) : 1f;
float alpha = t < 0.08f ? t / 0.08f : t > 0.88f ? 1f - (t - 0.88f) / 0.12f : 1f;
Vector2 p = Vector2.Lerp(a, b, k);
if (k > 0.02f) ui.Line(a, p, alpha);
ui.Finger(p, t < 0.85f ? 1f : 0f, alpha);
}
/// <summary>끌기 시범의 손가락 — 유닛을 누르고 목표 쪽으로 끔(화살표 끝까지 · 놓을 때 사라짐).</summary>
void DrawDemoFinger()
{
Unit u;
Vector2 to;
float k, gs;
if (!DemoAim(out u, out to, out k, out gs)) return;
Vector2 a = ui.ToCanvas(u.Position);
// 손가락 끝 = 그 화살표를 만드는 실제 손가락 자리(끌기 조준 = 화살표 ÷ drag_gain + 조준 시작 반경 · 게이지 조작 = 방향만 → 표 finger_pull_ratio)
Vector2 reach = DemoReach(u, to);
float rl = reach.magnitude;
if (rl < 1e-4f) return;
float fl = AimRules.DragMode
? rl / Mathf.Max(0.01f, IbUi.Num("drag_gain", 2f)) + u.Radius * battle.Config.aimStartRadiusRatio
: Mathf.Min(SkillMods.SlingMax(u) * Num("finger_pull_ratio", 1f), rl);
Vector2 b = ClampToward(a, ui.ToCanvas(u.Position + reach / rl * fl), ui.SafeRect);
float cycle = Mathf.Max(0.3f, ScenarioData.EvCfg("guide_demo_cycle_sec"));
float t = ((Time.unscaledTime - shownAt) % cycle) / cycle;
if (t >= 0.9f) return; // 놓음
float alpha = t < 0.08f ? t / 0.08f : 1f;
ui.Finger(Vector2.Lerp(a, b, k), 1f, alpha);
}
/// <summary>시범에서 끝까지 끌었을 때 유닛 → 화살표 끝(목표 쪽 · 최대 거리와 목표 거리 중 짧은 쪽).</summary>
public static Vector2 DemoReach(Unit u, Vector2 to)
{
Vector2 d = to - u.Position;
float len = d.magnitude;
if (len < 1e-4f) return Vector2.zero;
return d / len * Mathf.Min(len, SkillMods.SlingMax(u));
}
/// <summary>b 가 범위 밖이면 a 쪽으로 당겨 범위 안에 넣는다(a 가 밖이면 그대로).</summary>
static Vector2 ClampToward(Vector2 a, Vector2 b, Rect r)
{
if (r.Contains(b) || !r.Contains(a)) return b;
float lo = 0f, hi = 1f;
for (int i = 0; i < 12; i++)
{
float mid = (lo + hi) * 0.5f;
if (r.Contains(Vector2.Lerp(a, b, mid))) lo = mid;
else hi = mid;
}
return Vector2.Lerp(a, b, lo);
}
// ---------- 편성 화면 안내(before_battle) ----------
/// <summary>전투 밖에서 편성 화면이 열려 있으면, 다음에 깰 판의 before_battle 안내를 한 번 띄운다(그 판을 깨기 전 · 앱을 켠 동안 1회).</summary>
void PollBeforeBattle()
{
if (active != null || overlay.Count > 0 || battle.Phase != BattlePhase.Setup || !TutorialRules.Enabled) return;
var root = OutGameRoot.Instance;
if (root == null || root.Formation == null || root.Formation.Rt == null || !root.Formation.Rt.gameObject.activeInHierarchy) return;
var db = TutorialTables.Db;
if (db == null || battle.Config == null) return;
BalanceConfig.StageDef next = null;
foreach (var st in battle.Config.stages)
{
if (TutorialRules.Cleared(st.chapter, st.stage)) continue;
next = st;
break;
}
if (next == null) return;
string key = next.chapter + "-" + next.stage;
if (key == beforeChecked) return;
beforeChecked = key;
if (!beforeShown.Add(key)) return;
foreach (var g in db.Guide(next.chapter, next.stage))
if (g.trigger == GuideTrigger.BeforeBattle) overlay.Enqueue(g);
TryAdvance();
}
}
}