ThreeKingdomsSlingshot/Assets/Scripts/OutGame/Arena/ArenaTower.cs

914 lines
44 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;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace TKS.OutGame
{
/// <summary>
/// 천하제일 탑 화면(PD 2026-11-18 「B안으로 진행해」 · 아트 시안 content_screens_2/tower/final/mock/mock_t_b*.png · Fable QA r1 · r2 PASS) —
/// 하늘(땅 그림 + 위로 반복 띠 · 시차) 위에 100층 탑(꼭대기 조각 + 반복 층 95 + 받침 조각)을 쌓고, 층마다 현판 글자(깬 층 금색 · 못 깬 층 회갈색 + 어둡게 · 10층마다 붉은 보스 현판) ·
/// 도전할 층 = 문 빛 + 번짐(덧셈) + 금 화살표 · 아래 정보 판(층 · 적 편성 얼굴 · 배율 · 첫 클리어 보상 · 최고 층 · 입장권 + 광고 · 도전).
/// 끌어서 위아래 층 구경(보이는 조각만 그림) · 처음 = 도전할 층이 화면 위쪽 가운데.
/// 기능 = 예전 더미 화면(ArenaScreen.BuildTower)과 같음: 입장권 · 광고 · 도전(StartMode) · 순위 표(서버 모드 · 최고 층 칩).
/// 표(Resources/UI/Tower · C45): 설정 tower_screen(키 · 값) · 층 자리 tower_marks(납품 그대로) · 글자 tower_text(UiText) · 부품 parts/(탑 조각 3 = 단독 · 작은 부품 = 아틀라스 UI_Tower) · 하늘 2장.
/// 층(P41): 화면(Event) → Back(하늘 · 탑 · 현판 글자 = 끌 때만 바뀜 · Frame) · Fx(문 빛 숨 · 화살표 흔들림 · Frame) · Input(끌기 받는 칸 · Event + 레이캐스터) · Chrome(재화 바 뒤 띠 · Static) · Panel(정보 판 · Event + 레이캐스터).
/// </summary>
public class ArenaTower
{
public const string Table = "UI/Tower/tower_screen";
/// <summary>층 자리(조각 png px · 왼쪽 위 0,0 · 아래로 +).</summary>
public struct Mark
{
public int floor;
public Rect plaque;
public Rect door;
}
readonly ArenaScreen screen;
readonly Dictionary<string, string> kv = new Dictionary<string, string>();
readonly List<Mark> topMarks = new List<Mark>();
readonly List<Mark> baseMarks = new List<Mark>();
readonly Dictionary<string, Text> texts = new Dictionary<string, Text>();
Mark floorMark;
Sprite spTop, spFloor, spBase, spSkyLow, spSkyBand, spGlow, spHalo, spArrow;
float topH, floorH, baseH, towerW, totalH;
int floors, tiles;
public RectTransform View { get; private set; }
public RectTransform Back { get; private set; }
public RectTransform Fx { get; private set; }
public RectTransform InputLayer { get; private set; }
public RectTransform Chrome { get; private set; }
public RectTransform Panel { get; private set; }
public bool Built { get; private set; }
/// <summary>지금 화면 맨 위 = 탑 좌표 y(디자인 px · 탑 꼭대기 조각 위끝 = 0).</summary>
public float Cam { get; private set; }
/// <summary>도전할 층(빛 · 화살표) · 정보 판 층.</summary>
public int Current { get; private set; }
/// <summary>보이는 탑 조각 · 현판 글자 수(테스트).</summary>
public int VisiblePieces { get; private set; }
public int VisiblePlaques { get; private set; }
/// <summary>정보 판 적 칸 수(테스트).</summary>
public int EnemyCards { get; private set; }
ArenaTower(ArenaScreen s)
{
screen = s;
}
OutGameSession S
{
get { return screen.S; }
}
// ---------- 표 ----------
/// <summary>설정 표 · 층 자리 표 · 글자 표를 읽는다(그림은 처음 열 때) · 표가 없으면 null(호출 쪽 = 예전 더미 화면).</summary>
public static ArenaTower Load(ArenaScreen s)
{
var rows = UiText.Rows(Table);
if (rows == null) return null;
var tw = new ArenaTower(s);
foreach (var r in rows)
{
string k, v;
if (!r.TryGetValue("s_key", out k) || k.Length == 0) continue;
r.TryGetValue("s_value", out v);
tw.kv[k] = v ?? "";
}
UiText.Use(tw.S_("texts"));
if (!tw.LoadMarks() || !UiText.Has(tw.S_("title_key"))) return null;
return tw;
}
public string S_(string key, string def = "")
{
string v;
return kv.TryGetValue(key, out v) && v.Length > 0 ? v : def;
}
string[] L(string key)
{
return S_(key).Split('|');
}
static float F(string v, float def = 0f)
{
float f;
return v != null && float.TryParse(v.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out f) ? f : def;
}
static float At(string[] a, int i, float def = 0f)
{
return a != null && i < a.Length && a[i].Trim().Length > 0 ? F(a[i], def) : def;
}
static string Str(string[] a, int i)
{
return a != null && i < a.Length ? a[i].Trim() : "";
}
static Color Col(string[] a, int i, Color def)
{
Color c;
return a != null && i < a.Length && ColorUtility.TryParseHtmlString(a[i].Trim(), out c) ? c : def;
}
static string N(float v, string fmt = "0.00")
{
return v.ToString(fmt, CultureInfo.InvariantCulture);
}
bool LoadMarks()
{
var rows = UiText.Rows(S_("marks"));
if (rows == null) return false;
bool hasFloor = false;
var tops = new SortedDictionary<int, Mark>();
var bases = new SortedDictionary<int, Mark>();
foreach (var r in rows)
{
string piece;
if (!r.TryGetValue("s_piece", out piece) || piece.Length == 0) continue;
Func<string, float> g = c =>
{
string v;
return r.TryGetValue(c, out v) ? F(v) : 0f;
};
var m = new Mark
{
floor = (int)g("n_floor"),
plaque = Rect.MinMaxRect(g("n_px0"), g("n_py0"), g("n_px1"), g("n_py1")),
door = Rect.MinMaxRect(g("n_dx0"), g("n_dy0"), g("n_dx1"), g("n_dy1")),
};
int idx = (int)g("n_idx");
if (piece == "top") tops[idx] = m;
else if (piece == "base") bases[idx] = m;
else if (piece == "floor")
{
floorMark = m;
hasFloor = true;
}
}
topMarks.AddRange(tops.Values);
baseMarks.AddRange(bases.Values);
var fl = L("floors");
floors = (int)At(fl, 0, 100f);
tiles = floors - topMarks.Count - baseMarks.Count;
return hasFloor && topMarks.Count > 0 && baseMarks.Count > 0 && tiles > 0;
}
// ---------- 층 좌표 ----------
/// <summary>층 n 의 조각 위끝(탑 좌표) · 현판 · 문(조각 px).</summary>
public Mark MarkOf(int n, out float y0)
{
int nt = topMarks.Count, nb = baseMarks.Count;
if (n > floors - nt)
{
y0 = 0f;
return topMarks[Mathf.Clamp(floors - n, 0, nt - 1)];
}
if (n > nb)
{
y0 = topH + (floors - nt - n) * floorH;
return floorMark;
}
y0 = topH + tiles * floorH;
return baseMarks[Mathf.Clamp(nb - n, 0, nb - 1)];
}
/// <summary>층 n 의 문 가운데(탑 좌표 y).</summary>
public float DoorMid(int n)
{
float y0;
var m = MarkOf(n, out y0);
return y0 + m.door.center.y;
}
// ---------- 만들기 ----------
/// <summary>slot(화면 전체 · 제목 띠 뒤)에 처음 한 번 층을 만들고 도전 층에 맞춘 뒤 정보 판을 다시 채운다 · 그림이 없으면 false(호출 쪽 = 예전 더미 화면).</summary>
public bool Show(RectTransform slot)
{
if (!Built && !Build(slot)) return false;
Current = ArenaRules.TowerNext(S.Db, S.Save);
FocusCurrent();
BuildPanel();
return true;
}
Sprite Part(string name)
{
return name.Length > 0 ? Resources.Load<Sprite>(S_("parts") + "/" + name) : null;
}
bool Build(RectTransform slot)
{
spTop = Part(S_("piece_top"));
spFloor = Part(S_("piece_floor"));
spBase = Part(S_("piece_base"));
spSkyLow = Resources.Load<Sprite>(S_("sky_low"));
spSkyBand = Resources.Load<Sprite>(S_("sky_band"));
if (spTop == null || spFloor == null || spBase == null || spSkyLow == null || spSkyBand == null)
{
Debug.LogWarning("[TKS] 천하제일 탑 그림 없음: " + S_("parts") + " · " + S_("sky_low"));
return false;
}
var gl = L("glow");
spGlow = Part(Str(gl, 0));
spHalo = Part(Str(gl, 1));
spArrow = Part(Str(L("arrow"), 0));
topH = spTop.rect.height;
floorH = spFloor.rect.height;
baseH = spBase.rect.height;
towerW = spFloor.rect.width;
totalH = topH + tiles * floorH + baseH;
View = slot;
Back = UiLayer.Group("Back", View, UiRate.Frame); // 끌 때만 바뀜(스크롤 내용 = Frame)
Fx = UiLayer.Group("Fx", View, UiRate.Frame); // 문 빛 숨 · 화살표 흔들림(매 프레임)
InputLayer = UiLayer.Group("Input", View, UiRate.Event, true);
Chrome = UiLayer.Group("Chrome", View, UiRate.Static);
Panel = UiLayer.Group("Panel", View, UiRate.Event, true);
skyRoot = UiKit.Fill("Sky", Back);
pieceRoot = UiKit.Fill("Pieces", Back);
overRoot = UiKit.Fill("Plates", Back);
textRoot = UiKit.Fill("Floors", Back);
BuildFx();
var hit = UiKit.Fill("Drag", InputLayer);
var hi = hit.gameObject.AddComponent<Image>();
hi.color = new Color(0f, 0f, 0f, 0f);
hi.canvasRenderer.cullTransparentMesh = true; // 안 그리고 누름만 받음
drag = hit.gameObject.AddComponent<TowerDrag>();
drag.owner = this;
UiKit.Paint(UiKit.TopBand("TopBand", Chrome, 0f, OutGameRoot.TopBarH), UiKit.Col("band_top", UiKit.Bg), false); // 재화 바 뒤 띠(시안 .top)
Built = true;
return true;
}
RectTransform skyRoot, pieceRoot, overRoot, textRoot;
readonly List<Image> skyPool = new List<Image>();
readonly List<Image> piecePool = new List<Image>();
readonly List<Image> overPool = new List<Image>();
readonly List<Text> textPool = new List<Text>();
Image glowImg, haloBig, haloSmall, arrowL, arrowR;
TowerDrag drag;
// 화면 크기(캔버스 단위) · 디자인 배율 z(폭 1080 기준 · 세로가 모자란 태블릿 = 1920 기준)
float Wv, Hv, Z, Ytop, Ypanel;
void Measure()
{
var r = View.rect;
Wv = r.width;
Hv = r.height;
Z = Mathf.Min(Wv / 1080f, Hv / 1920f);
if (Z <= 0f) Z = 1f;
var pn = L("panel");
Ytop = OutGameRoot.TopBarH + OutGameRoot.HeaderH;
Ypanel = Hv - OutGameRoot.TabBarH - At(pn, 1, 16f) * Z - At(pn, 3, 508f) * Z;
}
float CamMin
{
get { return -(Ytop + 80f * Z) / Z; } // 꼭대기 구슬이 제목 띠 아래 80 px 까지
}
float CamMax
{
get { return totalH - (Ypanel + At(L("focus"), 1, 200f) * Z) / Z; } // 받침 아래끝이 정보 판 위끝 + 표 focus[1] 보다 위로 오지 않게
}
/// <summary>도전할 층 문 가운데 = 제목 띠 아래 ~ 정보 판 위 사이 focus 비율 자리.</summary>
public void FocusCurrent()
{
Measure();
float yf = Ytop + (Ypanel - Ytop) * At(L("focus"), 0, 0.5245f);
if (drag != null) drag.Stop();
SetCam(DoorMid(Current) - yf / Z, true);
}
internal void Resized()
{
if (!Built || !View.gameObject.activeInHierarchy) return;
FocusCurrent();
BuildPanel();
}
/// <summary>끌기 · 미끄러짐 · 맞춤 → 범위 안으로 자르고 바뀌었으면 다시 놓음.</summary>
public bool SetCam(float cam, bool force = false)
{
Measure();
float c = Mathf.Clamp(cam, CamMin, Mathf.Max(CamMin, CamMax));
if (!force && Mathf.Abs(c - Cam) < 0.01f) return false;
Cam = c;
Layout();
return c != cam;
}
static void Place(RectTransform rt, float x, float y, float w, float h)
{
rt.anchorMin = rt.anchorMax = new Vector2(0f, 1f);
rt.pivot = new Vector2(0f, 1f);
var p = new Vector2(x, -y);
var s = new Vector2(w, h);
if (rt.anchoredPosition != p) rt.anchoredPosition = p;
if (rt.sizeDelta != s) rt.sizeDelta = s;
}
Image Pooled(List<Image> pool, int i, RectTransform parent, string name)
{
while (pool.Count <= i)
{
var rt = UiKit.Rect(name + pool.Count, parent, new Vector2(0f, 1f), new Vector2(0f, 1f), Vector2.zero, Vector2.one);
var im = rt.gameObject.AddComponent<Image>();
im.raycastTarget = false;
pool.Add(im);
}
var img = pool[i];
if (!img.gameObject.activeSelf) img.gameObject.SetActive(true);
return img;
}
static void HideFrom<T>(List<T> pool, int n) where T : Component
{
for (int i = n; i < pool.Count; i++)
if (pool[i].gameObject.activeSelf) pool[i].gameObject.SetActive(false);
}
static void SetSprite(Image im, Sprite sp, bool flip)
{
if (im.sprite != sp) im.sprite = sp;
var s = new Vector3(flip ? -1f : 1f, 1f, 1f);
if (im.rectTransform.localScale != s) im.rectTransform.localScale = s;
}
/// <summary>보이는 하늘 · 조각 · 현판만 놓는다(끌 때마다 · 값이 같으면 쓰지 않음).</summary>
void Layout()
{
float tx = Wv * 0.5f + (F(S_("tower_x"), 540f) - 540f) * Z;
float x0 = tx - towerW * 0.5f * Z;
Func<float, float> Y = yw => (yw - Cam) * Z;
// 하늘: 땅 그림의 받침 행 = 받침 아래끝(시차) · 그 위로 띠
var sk = L("sky");
float gMin = Ypanel + At(L("focus"), 1, 200f) * Z;
float gs = Y(totalH);
float bgG = gMin + (gs - gMin) * At(sk, 1, 0.5f);
float ks = Wv / spSkyLow.rect.width; // 하늘 = 화면 폭 덮음
float lowTop = bgG - At(sk, 0, 1760f) * ks;
int si = 0;
float lowH = spSkyLow.rect.height * ks;
if (lowTop < Hv && lowTop + lowH > 0f)
{
var im = Pooled(skyPool, si++, skyRoot, "Sky");
SetSprite(im, spSkyLow, false);
Place(im.rectTransform, 0f, lowTop, Wv, lowH + 1f);
}
float bh = spSkyBand.rect.height * ks;
for (int i = 1; lowTop - (i - 1) * bh > 0f; i++)
{
float y = lowTop - i * bh;
if (y > Hv) continue;
var im = Pooled(skyPool, si++, skyRoot, "Sky");
SetSprite(im, spSkyBand, i % 2 == 1);
im.rectTransform.pivot = new Vector2(0.5f, 1f);
var p = new Vector2(Wv * 0.5f, -y);
im.rectTransform.anchorMin = im.rectTransform.anchorMax = new Vector2(0f, 1f);
if (im.rectTransform.anchoredPosition != p) im.rectTransform.anchoredPosition = p;
var sz = new Vector2(Wv, bh + 1f);
if (im.rectTransform.sizeDelta != sz) im.rectTransform.sizeDelta = sz;
}
HideFrom(skyPool, si);
// 탑 조각(보이는 것만)
int pi = 0;
float vt = Cam, vb = Cam + Hv / Z;
Action<Sprite, float, float> piece = (sp, yw, h) =>
{
if (yw + h < vt || yw > vb) return;
var im = Pooled(piecePool, pi++, pieceRoot, "Piece");
SetSprite(im, sp, false);
Place(im.rectTransform, x0, Y(yw), towerW * Z, h * Z + 0.5f);
};
piece(spTop, 0f, topH);
int t0 = Mathf.Max(0, Mathf.FloorToInt((vt - topH) / floorH) - 1);
int t1 = Mathf.Min(tiles - 1, Mathf.CeilToInt((vb - topH) / floorH) + 1);
for (int i = t0; i <= t1; i++) piece(spFloor, topH + i * floorH, floorH);
piece(spBase, topH + tiles * floorH, baseH);
HideFrom(piecePool, pi);
VisiblePieces = pi;
// 현판(층 글자 · 보스 바탕 · 못 깬 층 어둡게)
var pl = L("plaque");
var pc = L("plaque_col");
var lk = L("plaque_lock");
var bs = L("plaque_boss");
int best = S.Save.arena.towerFloor;
int bossEvery = Mathf.Max(1, (int)At(bs, 2, 10f));
int oi = 0, ti = 0;
for (int n = 1; n <= floors; n++)
{
float y0;
var m = MarkOf(n, out y0);
if (y0 + m.plaque.yMax < vt || y0 + m.plaque.yMin > vb) continue;
float ix0 = x0 + (m.plaque.xMin + At(pl, 2, 7f)) * Z, ix1 = x0 + (m.plaque.xMax - At(pl, 2, 7f)) * Z;
float iy0 = Y(y0 + m.plaque.yMin + At(pl, 3, 6f)), iy1 = Y(y0 + m.plaque.yMax - At(pl, 4, 10f));
bool boss = n % bossEvery == 0;
bool done = n <= best, cur = n == Current && best < floors;
bool lockd = !done && !cur;
if (boss)
{
var bi = Pooled(overPool, oi++, overRoot, "Plate");
SetSprite(bi, null, false);
var c = Col(bs, 0, new Color(0.7f, 0.21f, 0.15f));
c.a = At(bs, 1, 0.92f);
if (bi.color != c) bi.color = c;
Place(bi.rectTransform, ix0, iy0, ix1 - ix0, iy1 - iy0);
}
if (lockd)
{
var li = Pooled(overPool, oi++, overRoot, "Plate");
SetSprite(li, null, false);
var c = Col(lk, 0, Color.black);
c.a = At(lk, 1, 0.32f);
if (li.color != c) li.color = c;
Place(li.rectTransform, ix0, iy0, ix1 - ix0, iy1 - iy0);
}
var t = PooledText(ti++);
int fs = Mathf.Max(8, Mathf.RoundToInt(Mathf.Min((iy1 - iy0) * At(pl, 0, 0.98f), (ix1 - ix0) / At(pl, 1, 2.6f))));
var col = lockd ? (boss ? Col(pc, 2, Color.white) : Col(pc, 1, Color.gray)) : Col(pc, 0, Color.yellow);
string s = UiText.F("tower_floor", new[] { n.ToString(CultureInfo.InvariantCulture) });
if (t.text != s) t.text = s;
if (t.fontSize != fs) t.fontSize = fs;
t.color = col;
var ol = t.GetComponent<Outline>();
if (ol != null)
{
var d = new Vector2(fs * At(pc, 4, 0.2f) * 0.5f, -fs * At(pc, 4, 0.2f) * 0.5f);
if (ol.effectDistance != d) ol.effectDistance = d;
}
Place(t.rectTransform, ix0, iy0, ix1 - ix0, iy1 - iy0);
}
HideFrom(overPool, oi);
HideFrom(textPool, ti);
VisiblePlaques = ti;
PlaceFx(x0);
}
Text PooledText(int i)
{
while (textPool.Count <= i)
{
var t = UiKit.Title(UiKit.Label(textRoot, "", 24, Color.white, TextAnchor.MiddleCenter, new Vector2(0f, 1f), new Vector2(0f, 1f), Vector2.zero, Vector2.one));
t.name = "Floor" + textPool.Count;
t.horizontalOverflow = HorizontalWrapMode.Overflow;
t.verticalOverflow = VerticalWrapMode.Overflow;
t.raycastTarget = false;
var ol = t.gameObject.AddComponent<Outline>();
ol.effectColor = Col(L("plaque_col"), 3, Color.black);
textPool.Add(t);
}
var tx = textPool[i];
if (!tx.gameObject.activeSelf) tx.gameObject.SetActive(true);
return tx;
}
// ---------- 도전 층 문 빛 · 화살표 ----------
void BuildFx()
{
Func<string, Sprite, Image> mk = (name, sp) =>
{
var rt = UiKit.Rect(name, Fx, new Vector2(0f, 1f), new Vector2(0f, 1f), Vector2.zero, Vector2.one);
var im = rt.gameObject.AddComponent<Image>();
im.sprite = sp;
im.raycastTarget = false;
return im;
};
var add = GachaCutscene.AddMat; // 뽑기 연출 덧셈 재질(시안 plus-lighter) · 없으면 보통 섞기
haloBig = mk("HaloBig", spHalo);
glowImg = mk("Glow", spGlow);
haloSmall = mk("HaloSmall", spHalo);
if (add != null) haloBig.material = haloSmall.material = add;
arrowL = mk("ArrowL", spArrow);
arrowR = mk("ArrowR", spArrow);
arrowR.rectTransform.localScale = new Vector3(-1f, 1f, 1f);
fxDoor = Rect.zero;
}
Rect fxDoor; // 도전 층 문(화면 캔버스 px · 비면 숨김)
float fxArrow;
void PlaceFx(float x0)
{
bool on = Current >= 1 && S.Save.arena.towerFloor < floors;
Rect d = Rect.zero;
if (on)
{
float y0;
var m = MarkOf(Current, out y0);
d = Rect.MinMaxRect(x0 + m.door.xMin * Z, (y0 + m.door.yMin - Cam) * Z, x0 + m.door.xMax * Z, (y0 + m.door.yMax - Cam) * Z);
if (d.yMax < 0f || d.yMin > Hv) on = false;
}
if (Fx.gameObject.activeSelf != on) Fx.gameObject.SetActive(on);
if (!on) return;
fxDoor = d;
var gl = L("glow");
float dw = d.width, dh = d.height, cx = d.center.x;
float bw = dw * At(gl, 2, 2.2f), bhh = dh * At(gl, 3, 1.6f);
Place(haloBig.rectTransform, cx - bw * 0.5f, d.yMin + dh * At(gl, 4, 0.55f) - bhh * 0.5f, bw, bhh);
Place(glowImg.rectTransform, d.xMin, d.yMin, dw, dh);
float sw = dw * At(gl, 5, 1.1f), sh = dh * At(gl, 6, 0.9f);
Place(haloSmall.rectTransform, cx - sw * 0.5f, d.yMin + dh * At(gl, 7, 0.2f), sw, sh);
var ar = L("arrow");
float az = Mathf.Max(At(ar, 2, 42f) * Z, dw * At(ar, 1, 0.56f));
fxArrow = az;
float ah = az * (spArrow != null ? spArrow.rect.height / Mathf.Max(1f, spArrow.rect.width) : 1.17f);
float ay = d.center.y - ah * 0.5f;
arrowL.rectTransform.pivot = new Vector2(0.5f, 0f);
arrowR.rectTransform.pivot = new Vector2(0.5f, 0f);
PlaceArrow(arrowL, d.xMin - az * At(ar, 3, 0.72f), ay, az, ah);
PlaceArrow(arrowR, d.xMax + az * At(ar, 3, 0.72f), ay, az, ah);
}
static void PlaceArrow(Image im, float cx, float y, float w, float h)
{
var rt = im.rectTransform;
rt.anchorMin = rt.anchorMax = new Vector2(0f, 1f);
rt.pivot = new Vector2(0.5f, 0.5f);
var p = new Vector2(cx, -(y + h * 0.5f));
if (rt.anchoredPosition != p) rt.anchoredPosition = p;
var s = new Vector2(w, h);
if (rt.sizeDelta != s) rt.sizeDelta = s;
}
/// <summary>매 프레임(Fx 층): 문 빛 숨 · 화살표가 문 쪽으로 흔들림.</summary>
internal void Animate(float t)
{
if (!Fx.gameObject.activeInHierarchy) return;
var gp = L("glow_pulse");
float per = Mathf.Max(0.1f, At(gp, 0, 1.6f));
float u = 0.5f - 0.5f * Mathf.Cos(t * Mathf.PI * 2f / per);
float a = Mathf.Lerp(At(gp, 1, 0.82f), At(gp, 2, 1f), u);
float ha = At(L("glow"), 8, 0.85f) * a;
glowImg.color = new Color(1f, 1f, 1f, a);
haloBig.color = haloSmall.color = new Color(1f, 1f, 1f, ha);
var ar = L("arrow");
float bob = Mathf.Sin(t * Mathf.PI * 2f / Mathf.Max(0.1f, At(ar, 5, 1.2f))) * At(ar, 4, 6f) * Z;
float gap = fxArrow * At(ar, 3, 0.72f);
float cy = -fxDoor.center.y;
var pl = new Vector2(fxDoor.xMin - gap + bob, cy);
var pr = new Vector2(fxDoor.xMax + gap - bob, cy);
arrowL.rectTransform.anchoredPosition = pl;
arrowR.rectTransform.anchoredPosition = pr;
}
// ---------- 정보 판 ----------
static RectTransform At(Transform p, string name, float x, float y, float w, float h)
{
return UiKit.At(p, name, x, y, w, h);
}
Text Lab(Transform p, string name, string s, float size, Color c, TextAnchor a, float x, float y, float w, float h, bool stroke)
{
var t = UiKit.Label(p, s, Mathf.RoundToInt(size), c, a, new Vector2(0f, 1f), new Vector2(0f, 1f), new Vector2(x, -y), new Vector2(w, h));
UiKit.Title(t, stroke);
t.horizontalOverflow = HorizontalWrapMode.Overflow;
t.raycastTarget = false;
t.name = name;
texts[name] = t;
return t;
}
/// <summary>정보 판 글자(테스트 · 없으면 null).</summary>
public string TextOf(string name)
{
Text t;
return texts.TryGetValue(name, out t) && t != null ? t.text : null;
}
void BuildPanel()
{
UiKit.Clear(Panel);
texts.Clear();
Measure();
var db = S.Db;
var d = S.Save;
int n = Current;
var f = db.Tower.Get(n);
var stage = ArenaRules.TowerStage(db, screen.Root.Battle.Config, n);
var pn = L("panel");
float pw = At(pn, 2, 1040f) * Z, ph = At(pn, 3, 508f) * Z;
var box = At(Panel, "Board", (Wv - pw) * 0.5f, Ypanel, pw, ph);
var bc = Col(pn, 4, UiKit.Dark);
bc.a = At(pn, 5, 0.97f);
UiKit.Skin(box, "card", bc, true); // 판 = 누름 막음(뒤 탑 끌기와 겹치지 않게)
float pt = At(pn, 6, 18f) * Z, pl = At(pn, 7, 26f) * Z;
var rc = L("right");
float rw = At(rc, 0, 330f) * Z;
float lw = pw - pl * 2f - rw - pl;
// 왼쪽 열: 층 · 편성 · 적 · 배율 · 보상
var tf = L("title_font");
float y = pt;
float tfs = At(tf, 0, 76f) * Z;
var title = Lab(box, "Floor", UiText.F("tower_floor", new[] { n.ToString(CultureInfo.InvariantCulture) }), tfs, Col(tf, 1, Color.yellow), TextAnchor.MiddleLeft, pl, y, lw, tfs * 1.05f, true);
if (n % Mathf.Max(1, (int)At(L("plaque_boss"), 2, 10f)) == 0)
{
var bt = L("boss_tag");
float bh = At(bt, 0, 32f) * Z + 10f * Z;
var tag = UiKit.Skin(At(box, "BossTag", pl + title.preferredWidth + At(bt, 3, 12f) * Z, y + (tfs * 1.05f - bh) * 0.5f, 0f, bh), "chip", Col(bt, 2, UiKit.Red));
var tt = UiKit.Title(UiKit.FillLabel(tag.transform, UiText.T("tower_boss_tag"), Mathf.RoundToInt(At(bt, 1, 20f) * Z), Color.white), true);
tt.horizontalOverflow = HorizontalWrapMode.Overflow;
tag.rectTransform.sizeDelta = new Vector2(Mathf.Ceil(tt.preferredWidth) + 28f * Z, bh);
}
y += tfs * 1.05f;
var lf = L("line_font");
y += At(lf, 2, 2f) * Z;
float lfs = At(lf, 0, 23f) * Z;
string tmpl = f != null ? f.templateStage : "-";
Lab(box, "Template", UiText.F("tower_template", new[] { tmpl, stage != null ? stage.subtitle : "" }), lfs, Col(lf, 1, Color.white), TextAnchor.MiddleLeft, pl, y, lw, lfs * 1.4f, false);
y += lfs * 1.4f;
y = Section(box, "SecEnemy", UiText.T("tower_enemies"), pl, y, lw);
y = EnemyRow(box, stage, pl, y, lw);
var mu = L("mult");
y += At(mu, 3, 8f) * Z;
float mh = At(mu, 0, 42f) * Z;
int mfs = Mathf.RoundToInt(At(mu, 1, 23f) * Z);
float mx = pl;
if (f != null)
{
mx += Chip(box, "Hp", UiText.F("tower_hp", new[] { N(f.hpMult) }), mx, y, mh, mfs) + At(mu, 2, 10f) * Z;
Chip(box, "Atk", UiText.F("tower_atk", new[] { N(f.atkMult) }), mx, y, mh, mfs);
}
y += mh;
y = Section(box, "SecReward", UiText.T("tower_reward"), pl, y, lw);
var rwd = L("reward");
var ri = L("reward_icons");
float rs = At(rwd, 0, 76f) * Z, rg = At(rwd, 1, 20f) * Z;
float rx = pl;
if (f != null)
{
UiKit.RewardTile(box, "RwGem", rx, y, rs, "gear_white_", Str(ri, 0), f.rewardGem.ToString(CultureInfo.InvariantCulture), false);
rx += rs + rg;
UiKit.RewardTile(box, "RwBp", rx, y, rs, "gear_white_", Str(ri, 1), f.rewardBlueprint.ToString(CultureInfo.InvariantCulture), false);
rx += rs + rg;
if (!string.IsNullOrEmpty(f.chest)) UiKit.RewardTile(box, "RwChest", rx, y, rs, "gear_white_", UISkin.Has("chest_" + f.chest) ? "chest_" + f.chest : Str(ri, 2), "", false);
}
// 오른쪽 열: 최고 층(순위) · 입장권 + 광고 · 도전
float rx0 = pw - pl - rw;
float ry = pt + At(rc, 1, 6f) * Z; // 판 위 여백 + 열 위 여백(시안 padding 18 + 6 · 게임 QA r1 M9)
var be = L("best");
float beh = At(be, 0, 44f) * Z;
bool rank = S.RankAvailable;
var bestChip = UiKit.Skin(At(box, "Best", rx0, ry, rw, beh), "chip", UiKit.Col("chip_dark", UiKit.Dark), rank);
var bestT = UiKit.Title(UiKit.FillLabel(bestChip.transform, UiText.F(rank ? "tower_best_rank" : "tower_best", new[] { d.arena.towerFloor.ToString(CultureInfo.InvariantCulture), db.Tower.Top.ToString(CultureInfo.InvariantCulture) }), Mathf.RoundToInt(At(be, 1, 22f) * Z), Color.white), true);
bestT.horizontalOverflow = HorizontalWrapMode.Overflow;
bestT.name = "Best";
texts["Best"] = bestT;
if (rank) bestChip.gameObject.AddComponent<Button>().onClick.AddListener(() => Net.RankPanel.Open(screen.Root, ArenaRules.Tower));
ry += beh + 14f * Z;
var tk = L("ticket");
float th = At(tk, 0, 58f) * Z, adw = At(tk, 3, 112f) * Z, tg = At(tk, 6, 8f) * Z;
float tcw = rw - adw - tg;
var tchip = UiKit.Skin(At(box, "Ticket", rx0, ry, tcw, th), "chip", UiKit.Col("chip_dark", UiKit.Dark));
float tis = At(tk, 2, 38f) * Z;
var tic = UiKit.Icon(tchip.transform, "cur_ticket", new Vector2(0f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(th * 0.5f + 4f * Z, 0f), tis);
UiKit.DropShadow(tic, 3f);
string tkS = UiText.F("tower_ticket", new[] { d.arena.towerTickets.ToString(CultureInfo.InvariantCulture) }) + " <size=" + Mathf.RoundToInt(At(tk, 1, 24f) * Z * 0.8f) + "><color=#9AA3C0>" + UiText.F("tower_ticket_max", new[] { db.Economy.TowerTicketsDaily.ToString(CultureInfo.InvariantCulture) }) + "</color></size>";
var tt2 = Lab(tchip.transform, "TicketText", tkS, At(tk, 1, 24f) * Z, Color.white, TextAnchor.MiddleLeft, th + 6f * Z, 0f, tcw - th - 10f * Z, th, true);
tt2.supportRichText = true;
bool adOk = d.dailyC.towerAd < 1;
var adB = UiKit.SkinBtn(box, "Ad", adOk ? "btn_l_yellow" : "btn_gray", UiKit.White, "", 10, UiKit.Ink, rx0 + tcw + tg, ry, adw, th, () =>
{
screen.Root.Toast(S.TowerAd() ?? UiText.F("tower_ad_toast", new[] { S.Db.Economy.TowerAdTickets.ToString(CultureInfo.InvariantCulture) }));
if (screen.Page == 1) screen.Refresh();
});
adB.interactable = adOk;
var adL = adB.GetComponentInChildren<Text>();
if (adL != null) adL.gameObject.SetActive(false);
var inkY = UiKit.Col("text_on_yellow", UiKit.Ink);
Lab(adB.transform, "AdText", UiText.F("tower_ad", new[] { db.Economy.TowerAdTickets.ToString(CultureInfo.InvariantCulture) }), At(tk, 4, 21f) * Z, inkY, TextAnchor.MiddleCenter, 0f, 4f * Z, adw, th * 0.52f, false);
Lab(adB.transform, "AdCount", UiText.F("tower_ad_count", new[] { d.dailyC.towerAd.ToString(CultureInfo.InvariantCulture) }), At(tk, 5, 16f) * Z, inkY, TextAnchor.MiddleCenter, 0f, th * 0.48f, adw, th * 0.4f, false);
ry += th + At(L("go"), 4, 14f) * Z;
GoButton(box, n, stage, rx0, ry, rw);
}
float Section(Transform box, string name, string s, float x, float y, float w)
{
var sf = L("sec_font");
y += At(sf, 2, 10f) * Z;
float fs = At(sf, 0, 27f) * Z;
Lab(box, name, s, fs, Col(sf, 1, Color.yellow), TextAnchor.MiddleLeft, x, y, w, fs * 1.2f, true);
return y + fs * 1.2f + At(sf, 3, 12f) * Z;
}
float Chip(Transform box, string name, string s, float x, float y, float h, int fs)
{
var c = UiKit.Skin(At(box, name, x, y, 10f, h), "chip", UiKit.Col("chip_dark", UiKit.Dark));
var t = UiKit.Title(UiKit.FillLabel(c.transform, s, fs, Color.white), true);
t.horizontalOverflow = HorizontalWrapMode.Overflow;
t.name = name;
texts[name] = t;
float w = Mathf.Ceil(t.preferredWidth) + 36f * Z;
c.rectTransform.sizeDelta = new Vector2(w, h);
return w;
}
/// <summary>적 편성 = 무장(보스 먼저) · 병종별 묶음 — 얼굴(대기 첫 프레임 · 그림 없으면 병종 아이콘) + ×수 + 이름 · 칸 수 상한(표).</summary>
float EnemyRow(Transform box, BalanceConfig.StageDef stage, float x, float y, float w)
{
EnemyCards = 0;
var en = L("enemy");
float dd = At(en, 0, 88f) * Z, gap = At(en, 1, 20f) * Z;
int max = (int)At(en, 2, 5f);
float nfs = At(en, 3, 20f) * Z;
float rowH = dd + nfs * 1.5f + 2f * Z;
if (stage == null) return y + rowH;
var groups = new List<KeyValuePair<BalanceConfig.EnemySpawn, int>>();
Action<bool> collect = gen =>
{
foreach (UnitType ut in new[] { UnitType.Infantry, UnitType.Spear, UnitType.Cavalry, UnitType.Archer, UnitType.Strategist })
foreach (var e in stage.enemies)
{
if (e.isGeneral != gen || e.type != ut) continue;
int k = groups.FindIndex(g => !gen && g.Key.type == e.type && g.Key.art == e.art);
if (k >= 0) groups[k] = new KeyValuePair<BalanceConfig.EnemySpawn, int>(groups[k].Key, groups[k].Value + 1);
else groups.Add(new KeyValuePair<BalanceConfig.EnemySpawn, int>(e, 1));
}
};
collect(true); // 무장(보스 · 엘리트) 먼저 · 무장은 한 명씩
groups.Sort((a, b) => (b.Key.isBoss ? 1 : 0) - (a.Key.isBoss ? 1 : 0));
collect(false);
float cx = x;
for (int i = 0; i < groups.Count && i < max; i++)
{
var e = groups[i].Key;
var cell = At(box, "Enemy" + i, cx, y, dd + gap, rowH);
FaceCell(cell, e, dd, en);
var cnt = UiKit.Skin(UiKit.Rect("Cnt", cell, new Vector2(0f, 1f), new Vector2(1f, 1f), new Vector2(dd + 8f * Z, -(dd - 30f * Z)), new Vector2(10f, 30f * Z)), "chip", UiKit.Col("chip_dark", UiKit.Dark));
var ct = UiKit.Title(UiKit.FillLabel(cnt.transform, "x" + groups[i].Value.ToString(CultureInfo.InvariantCulture), Mathf.RoundToInt(At(en, 5, 24f) * Z), Color.white), true);
ct.horizontalOverflow = HorizontalWrapMode.Overflow;
cnt.rectTransform.sizeDelta = new Vector2(Mathf.Ceil(ct.preferredWidth) + 16f * Z, 30f * Z);
string nm = e.isGeneral ? (string.IsNullOrEmpty(e.name) ? UiText.T("tower_general") : e.name) : UiText.T("tower_cls_" + e.type.ToString().ToLowerInvariant());
Lab(cell, "EnemyName" + i, nm, nfs, Col(en, 4, Color.white), TextAnchor.MiddleCenter, -gap * 0.5f, dd + 4f * Z, dd + gap * 2f, nfs * 1.4f, false);
cx += dd + gap;
EnemyCards++;
}
return y + rowH;
}
void FaceCell(RectTransform cell, BalanceConfig.EnemySpawn e, float d, string[] en)
{
float bw = 5f * Z;
var outer = UiKit.Rect("Face", cell, new Vector2(0f, 1f), new Vector2(0f, 1f), Vector2.zero, new Vector2(d, d));
var oi = outer.gameObject.AddComponent<Image>();
oi.sprite = UiKit.Circle;
oi.color = new Color(0.08f, 0.09f, 0.16f);
oi.raycastTarget = false;
float di = d - 2f * bw;
var inner = UiKit.Rect("In", outer, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, new Vector2(di, di));
var ii = inner.gameObject.AddComponent<Image>();
ii.sprite = UiKit.Circle;
ii.color = e.isBoss || e.isGeneral ? Col(en, 6, UiKit.Red) : Col(en, 7, UiKit.Dark);
ii.raycastTarget = false;
inner.gameObject.AddComponent<Mask>().showMaskGraphic = true;
var sp = UiKit.ArtSprite(e.art);
if (sp != null)
{
float aw = di * At(en, 8, 1.72f);
float ah = aw * sp.rect.height / Mathf.Max(1f, sp.rect.width);
var a = UiKit.Rect("Art", inner, new Vector2(0f, 1f), new Vector2(0f, 1f), new Vector2(di * At(en, 9, -0.36f), -di * At(en, 10, -0.06f)), new Vector2(aw, ah));
var ai = a.gameObject.AddComponent<Image>();
ai.sprite = sp;
ai.raycastTarget = false;
// 병종 = 왼쪽 아래 작은 아이콘(표 enemy 칸 11~13 = 크기 · x · y · 얼굴 원 지름 × · 원판 없는 스티커 아이콘이라 조금 크게 · PD 2026-11-22)
var ic = UiKit.Icon(cell, UiKit.TypeSymbolId(e.type), new Vector2(0f, 1f), new Vector2(0.5f, 0.5f), new Vector2(d * At(en, 12, 0.12f), -d * At(en, 13, 0.86f)), d * At(en, 11, 0.36f));
if (ic != null) UiKit.DropShadow(ic, 2f);
}
else UiKit.Icon(inner, UiKit.TypeSymbolId(e.type), new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, di * 0.66f);
if (e.isBoss)
{
var bt = L("boss_tag");
var tag = UiKit.Skin(UiKit.Rect("Boss", cell, new Vector2(0f, 1f), new Vector2(0.5f, 0.5f), new Vector2(d * 0.5f, -8f * Z), new Vector2(10f, 30f * Z)), "chip", Col(bt, 2, UiKit.Red));
var t = UiKit.Title(UiKit.FillLabel(tag.transform, UiText.T("tower_boss_tag").Split(' ')[0], Mathf.RoundToInt(17f * Z), Color.white), true);
t.horizontalOverflow = HorizontalWrapMode.Overflow;
tag.rectTransform.sizeDelta = new Vector2(Mathf.Ceil(t.preferredWidth) + 18f * Z, 30f * Z);
}
}
void GoButton(Transform box, int n, BalanceConfig.StageDef stage, float x, float y, float w)
{
var g = L("go");
float h = At(g, 0, 104f) * Z;
var why = ArenaRules.CanTower(S.Db, S.Save, S.Now);
if (stage == null && why == null) why = UiText.T("tower_no_stage");
bool ok = why == null;
// btn_l_red = 흰 바탕 스킨 + 붉은 틴트(테마 · 월드맵 출정 버튼과 같음)
var b = UiKit.SkinBtn(box, "Go", ok ? "btn_l_red" : "btn_gray", ok ? UISkin.Col("red", UiKit.Red) : UiKit.White, "", 10, Color.white, x, y, w, h, () =>
{
var wv = S.EnterTower();
if (wv != null)
{
screen.Root.Toast(wv);
return;
}
screen.Root.StartMode(ArenaRules.Tower, "", n, ArenaRules.TowerStage(S.Db, screen.Root.Battle.Config, n), 0, 1);
});
b.interactable = ok;
var bl = b.GetComponentInChildren<Text>();
if (bl != null) bl.gameObject.SetActive(false);
if (ok)
{
Lab(b.transform, "GoText", UiText.T("tower_go"), At(g, 1, 44f) * Z, Color.white, TextAnchor.MiddleCenter, 0f, h * 0.06f, w, h * 0.56f, true);
float cfs = At(g, 2, 24f) * Z, ics = At(g, 3, 30f) * Z;
var ct = Lab(b.transform, "GoCost", UiText.T("tower_go_cost"), cfs, Color.white, TextAnchor.MiddleCenter, ics * 0.5f, h * 0.56f, w, h * 0.3f, true);
var ic = UiKit.Icon(b.transform, "cur_ticket", new Vector2(0f, 1f), new Vector2(0.5f, 0.5f), new Vector2(w * 0.5f - ct.preferredWidth * 0.5f - ics * 0.1f, -(h * 0.56f + h * 0.15f)), ics);
UiKit.DropShadow(ic, 2f);
}
else Lab(b.transform, "GoText", why, At(g, 2, 24f) * Z * 1.1f, Color.white, TextAnchor.MiddleCenter, 0f, 0f, w, h, true);
}
// ---------- 끌기 ----------
/// <summary>탑 끌기(세로) · 놓으면 미끄러짐(표 scroll) · 매 프레임 문 빛 연출 호출.</summary>
public class TowerDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public ArenaTower owner;
float vel;
bool dragging;
Canvas root;
public void Stop()
{
vel = 0f;
dragging = false;
}
float Scale()
{
if (root == null)
{
var c = GetComponentInParent<Canvas>();
root = c != null ? c.rootCanvas : null;
}
return root != null && root.scaleFactor > 0f ? root.scaleFactor : 1f;
}
public void OnBeginDrag(PointerEventData e)
{
dragging = true;
vel = 0f;
}
public void OnDrag(PointerEventData e)
{
if (owner == null) return;
float dy = e.delta.y / Scale() / Mathf.Max(0.01f, owner.Z); // 위로 끌면(+) 탑이 손을 따라 올라감 = 아래층이 보임 = cam(화면 맨 위 탑 좌표) 증가
owner.SetCam(owner.Cam + dy);
float dt = Mathf.Max(Time.unscaledDeltaTime, 0.001f);
vel = Mathf.Lerp(vel, dy / dt, 0.5f);
}
public void OnEndDrag(PointerEventData e)
{
dragging = false;
var sc = owner != null ? owner.L("scroll") : null;
float vmax = At(sc, 1, 2400f);
vel = Mathf.Clamp(vel, -vmax, vmax);
}
Vector2 lastSize;
void OnRectTransformDimensionsChange()
{
if (owner == null || !owner.Built) return;
var sz = ((RectTransform)transform).rect.size;
if ((sz - lastSize).sqrMagnitude < 0.01f) return;
lastSize = sz;
owner.Resized(); // 화면 크기 바뀜(회전 · 창) = 다시 맞춤
}
void Update()
{
if (owner == null) return;
owner.Animate(Time.unscaledTime);
if (dragging || Mathf.Abs(vel) < 1f) return;
float dt = Time.unscaledDeltaTime;
float tau = Mathf.Max(0.01f, At(owner.L("scroll"), 0, 0.135f));
if (owner.SetCam(owner.Cam + vel * dt)) vel = 0f; // 끝에 닿음
vel *= Mathf.Exp(-dt / tau);
}
}
}
}