411 lines
18 KiB
C#
411 lines
18 KiB
C#
using System.Collections.Generic;
|
|
using System.Globalization;
|
|
using UnityEngine;
|
|
|
|
namespace TKS
|
|
{
|
|
/// <summary>
|
|
/// 맵 경계 충돌 · 가림층(PD 2026-11-26 「배경 오브젝트에 유닛들이 튕겨지게 · 성채는 부술 수 없는 맵 경계 · 깃발이나 성채처럼 유닛을 가릴 수 있는 배경 오브젝트는
|
|
/// 가려진 유닛을 실루엣으로 · 모든 맵에 공통 · 새 맵이 추가될 때도 같은 규칙이 기본 사양」).
|
|
/// 표(SOT) = Resources/Board/board_bounds.csv(그림 원본 px · Tools/map_bounds.py 머리말) · 가림층 그림 = Resources/Board/Covers/<그림>__<id> + board_covers.csv(도구가 생성).
|
|
/// 바닥 그림이 바뀔 때마다(Board.FitArt 뒤) 다시 만든다:
|
|
/// · walk = 걷는 땅 테두리 → 닫힌 EdgeCollider2D + BoardWall(전장 벽과 같은 판정 = 튕김 · 적 AI 예측 · 화살 막힘) · Board.ClampInside 가 이 안으로 보정
|
|
/// · wall = 안쪽 막힌 구조물(PolygonCollider2D + BoardWall) · ClampInside 가 밖으로 밀어냄
|
|
/// · cover = 구조물 모양 그림을 유닛과 같은 정렬(0)로 땅에 닿는 줄 기준 앞뒤 정렬 + SpriteMask → 뒤에 선 유닛은 반투명 실루엣(UnitView ghost)
|
|
/// </summary>
|
|
public class MapBounds : MonoBehaviour
|
|
{
|
|
class Row
|
|
{
|
|
public string kind, id;
|
|
public float w, h;
|
|
public Vector2[] pts;
|
|
}
|
|
|
|
class CoverRow
|
|
{
|
|
public string id;
|
|
public float x, y, w, h, baseY, imgW, imgH;
|
|
}
|
|
|
|
static Dictionary<string, List<Row>> rows;
|
|
static Dictionary<string, List<CoverRow>> coverRows;
|
|
public static readonly List<string> Errors = new List<string>();
|
|
|
|
/// <summary>지금 판의 바닥 그림 이름(경계 줄이 없으면 null).</summary>
|
|
public string File { get; private set; }
|
|
|
|
Vector2[] walk;
|
|
readonly List<Vector2[]> walls = new List<Vector2[]>();
|
|
|
|
/// <summary>걷는 땅 테두리(월드 · 없으면 null) — 테스트 · 캡처 확인용.</summary>
|
|
public Vector2[] Walk
|
|
{
|
|
get { return walk; }
|
|
}
|
|
|
|
public int WallCount
|
|
{
|
|
get { return walls.Count; }
|
|
}
|
|
|
|
public int CoverCount { get; private set; }
|
|
|
|
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
|
static void ResetStatics()
|
|
{
|
|
rows = null;
|
|
coverRows = null;
|
|
covers.Clear();
|
|
}
|
|
|
|
/// <summary>표를 다시 읽게 함(다음 Build 때).</summary>
|
|
public static void Reload()
|
|
{
|
|
rows = null;
|
|
coverRows = null;
|
|
}
|
|
|
|
// ---------- 표 ----------
|
|
|
|
static void Load()
|
|
{
|
|
if (rows != null) return;
|
|
rows = new Dictionary<string, List<Row>>();
|
|
coverRows = new Dictionary<string, List<CoverRow>>();
|
|
Errors.Clear();
|
|
string text = StageTable.ResourceText("Board/board_bounds");
|
|
if (!string.IsNullOrEmpty(text))
|
|
foreach (var r in StageTable.ReadCsv(text, "board_bounds.csv", Errors))
|
|
{
|
|
string file = S(r, "s_file");
|
|
var row = new Row { kind = S(r, "s_kind"), id = S(r, "s_id"), w = F(r, "n_w"), h = F(r, "n_h"), pts = Pts(S(r, "s_points")) };
|
|
if (file.Length == 0) continue;
|
|
if (row.w <= 0f || row.h <= 0f) Errors.Add("board_bounds.csv " + file + "/" + row.id + ": n_w · n_h 없음");
|
|
else if (row.kind != "cover" && row.pts.Length < 3) Errors.Add("board_bounds.csv " + file + "/" + row.id + ": 점 3개 미만");
|
|
else Add(rows, file, row);
|
|
}
|
|
text = StageTable.ResourceText("Board/board_covers");
|
|
if (!string.IsNullOrEmpty(text))
|
|
foreach (var r in StageTable.ReadCsv(text, "board_covers.csv", Errors))
|
|
Add(coverRows, S(r, "s_file"), new CoverRow
|
|
{
|
|
id = S(r, "s_id"), x = F(r, "n_x"), y = F(r, "n_y"), w = F(r, "n_w"), h = F(r, "n_h"), baseY = F(r, "f_base"), imgW = F(r, "n_img_w"), imgH = F(r, "n_img_h"),
|
|
});
|
|
foreach (var e in Errors) Debug.LogError("[TKS] 맵 경계 표 " + e);
|
|
}
|
|
|
|
static void Add<T>(Dictionary<string, List<T>> d, string k, T v)
|
|
{
|
|
List<T> l;
|
|
if (!d.TryGetValue(k, out l)) d[k] = l = new List<T>();
|
|
l.Add(v);
|
|
}
|
|
|
|
static Vector2[] Pts(string s)
|
|
{
|
|
var list = new List<Vector2>();
|
|
foreach (var p in s.Split(';'))
|
|
{
|
|
var xy = p.Trim().Split(new[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
|
|
float x, y;
|
|
if (xy.Length == 2 && float.TryParse(xy[0], NumberStyles.Float, CultureInfo.InvariantCulture, out x) && float.TryParse(xy[1], NumberStyles.Float, CultureInfo.InvariantCulture, out y))
|
|
list.Add(new Vector2(x, y));
|
|
}
|
|
return list.ToArray();
|
|
}
|
|
|
|
static string S(Dictionary<string, string> r, string k)
|
|
{
|
|
string v;
|
|
return r.TryGetValue(k, out v) ? v.Trim() : "";
|
|
}
|
|
|
|
static float F(Dictionary<string, string> r, string k)
|
|
{
|
|
float v;
|
|
return float.TryParse(S(r, k), NumberStyles.Float, CultureInfo.InvariantCulture, out v) ? v : 0f;
|
|
}
|
|
|
|
/// <summary>이 바닥 그림에 걷는 땅 줄이 있는가(새 맵 점검 · 시험).</summary>
|
|
public static bool HasWalk(string file)
|
|
{
|
|
Load();
|
|
List<Row> l;
|
|
return file != null && rows.TryGetValue(file, out l) && l.Exists(r => r.kind == "walk");
|
|
}
|
|
|
|
// ---------- 만들기 ----------
|
|
|
|
/// <summary>판의 바닥 그림(file)이 artRect(월드 · 바깥 여분 포함)에 놓였을 때 경계 · 가림층을 새로 만든다(앞 것은 지움). 표에 줄이 없으면 null.</summary>
|
|
public static MapBounds Build(Board board, MapBounds old, string file, Rect artRect)
|
|
{
|
|
if (old != null)
|
|
{
|
|
old.gameObject.SetActive(false);
|
|
Destroy(old.gameObject);
|
|
}
|
|
Load();
|
|
List<Row> list;
|
|
if (string.IsNullOrEmpty(file) || !rows.TryGetValue(file, out list)) return null;
|
|
var go = new GameObject("MapBounds_" + file);
|
|
go.transform.SetParent(board.transform, false);
|
|
var mb = go.AddComponent<MapBounds>();
|
|
mb.File = file;
|
|
foreach (var r in list)
|
|
{
|
|
if (r.kind == "cover") continue;
|
|
var w = new Vector2[r.pts.Length];
|
|
for (int i = 0; i < w.Length; i++) w[i] = ToWorld(r.pts[i], r.w, r.h, artRect);
|
|
if (r.kind == "walk")
|
|
{
|
|
mb.walk = w;
|
|
var eg = new GameObject("Walk_" + r.id);
|
|
eg.transform.SetParent(go.transform, false);
|
|
var ec = eg.AddComponent<EdgeCollider2D>();
|
|
var loop = new Vector2[w.Length + 1];
|
|
for (int i = 0; i < w.Length; i++) loop[i] = eg.transform.InverseTransformPoint(w[i]);
|
|
loop[w.Length] = loop[0];
|
|
ec.points = loop;
|
|
eg.AddComponent<BoardWall>();
|
|
}
|
|
else if (r.kind == "wall")
|
|
{
|
|
mb.walls.Add(w);
|
|
var wg = new GameObject("Wall_" + r.id);
|
|
wg.transform.SetParent(go.transform, false);
|
|
var pc = wg.AddComponent<PolygonCollider2D>();
|
|
var loc = new Vector2[w.Length];
|
|
for (int i = 0; i < w.Length; i++) loc[i] = wg.transform.InverseTransformPoint(w[i]);
|
|
pc.SetPath(0, loc);
|
|
wg.AddComponent<BoardWall>();
|
|
}
|
|
else Debug.LogError("[TKS] 맵 경계 표 board_bounds.csv " + file + "/" + r.id + ": s_kind 「" + r.kind + "」 모름(walk · wall · cover)");
|
|
}
|
|
List<CoverRow> cl;
|
|
if (coverRows.TryGetValue(file, out cl))
|
|
foreach (var c in cl)
|
|
if (mb.MakeCover(file, c, artRect)) mb.CoverCount++;
|
|
Physics2D.SyncTransforms();
|
|
return mb;
|
|
}
|
|
|
|
static Vector2 ToWorld(Vector2 px, float w, float h, Rect art)
|
|
{
|
|
return new Vector2(art.xMin + px.x / w * art.width, art.yMax - px.y / h * art.height);
|
|
}
|
|
|
|
bool MakeCover(string file, CoverRow c, Rect art)
|
|
{
|
|
var tex = Resources.Load<Texture2D>("Board/Covers/" + file + "__" + c.id);
|
|
if (tex == null || c.imgW <= 0f || c.imgH <= 0f || c.w <= 0f || c.h <= 0f)
|
|
{
|
|
Debug.LogWarning("[TKS] 맵 가림층 그림 없음: Board/Covers/" + file + "__" + c.id + " → python -I Tools/map_bounds.py bake");
|
|
return false;
|
|
}
|
|
Vector2 tl = ToWorld(new Vector2(c.x, c.y), c.imgW, c.imgH, art), br = ToWorld(new Vector2(c.x + c.w, c.y + c.h), c.imgW, c.imgH, art);
|
|
float ww = br.x - tl.x, wh = tl.y - br.y;
|
|
float baseW = ToWorld(new Vector2(0f, c.baseY), c.imgW, c.imgH, art).y;
|
|
Vector2 pivot = new Vector2((tl.x + br.x) * 0.5f, baseW + SortLift);
|
|
var sp = Sprite.Create(tex, new Rect(0f, 0f, tex.width, tex.height), new Vector2(0.5f, (pivot.y - br.y) / wh), tex.width / ww, 0, SpriteMeshType.FullRect);
|
|
sp.name = tex.name;
|
|
var go = new GameObject("Cover_" + c.id);
|
|
go.transform.SetParent(transform, false);
|
|
go.transform.position = new Vector3(pivot.x, pivot.y, 0f);
|
|
Attach(go, sp);
|
|
return true;
|
|
}
|
|
|
|
// ---------- 가림층(지도 · 소품 공용) ----------
|
|
|
|
/// <summary>
|
|
/// 가림층 앞뒤 정렬의 기준 올림(월드) — 유닛 그림은 몸 가운데(발 + 키 ÷ 2)로 정렬되므로 가림층 기준점 = 땅에 닿는 줄 + 이 값
|
|
/// (표 ib_ui map_cover_sort_lift · 발이 땅 줄보다 위 = 유닛이 뒤 = 가려짐).
|
|
/// </summary>
|
|
public static float SortLift
|
|
{
|
|
get { return IbUi.Num("map_cover_sort_lift", 0.7f); }
|
|
}
|
|
|
|
struct CoverRef
|
|
{
|
|
public SpriteRenderer sr;
|
|
}
|
|
|
|
static readonly List<CoverRef> covers = new List<CoverRef>();
|
|
|
|
/// <summary>
|
|
/// go 에 가림 그림을 붙인다: 유닛과 같은 정렬(0) · 기준점(pivot) 정렬 → 기준점보다 위(뒤)의 유닛을 덮음 + 같은 모양 SpriteMask(뒤에 가린 유닛 = 실루엣이 비침).
|
|
/// 소품(ScenarioProps)도 같은 함수 · 부서지면 Detach.
|
|
/// </summary>
|
|
public static SpriteRenderer Attach(GameObject go, Sprite sp)
|
|
{
|
|
var sr = go.GetComponent<SpriteRenderer>();
|
|
if (sr == null) sr = go.AddComponent<SpriteRenderer>();
|
|
sr.sprite = sp;
|
|
sr.sortingOrder = 0;
|
|
sr.spriteSortPoint = SpriteSortPoint.Pivot;
|
|
var mask = go.GetComponent<SpriteMask>();
|
|
if (mask == null) mask = go.AddComponent<SpriteMask>();
|
|
mask.sprite = sp;
|
|
mask.alphaCutoff = IbUi.Num("map_cover_mask_cutoff", 0.35f);
|
|
covers.Add(new CoverRef { sr = sr });
|
|
return sr;
|
|
}
|
|
|
|
/// <summary>가림을 끈다(부서진 소품 = 바닥에 남는 잔해는 유닛 아래로).</summary>
|
|
public static void Detach(SpriteRenderer sr, int floorOrder)
|
|
{
|
|
if (sr == null) return;
|
|
covers.RemoveAll(c => c.sr == sr || c.sr == null);
|
|
var mask = sr.GetComponent<SpriteMask>();
|
|
if (mask != null) Destroy(mask);
|
|
sr.spriteSortPoint = SpriteSortPoint.Center;
|
|
sr.sortingOrder = floorOrder;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 유닛 실루엣(UnitView ghost)을 켜도 되는가: 유닛 그림이 겹친 가림층 가운데 그 유닛이 뒤에 선 것이 하나라도 있으면 true ·
|
|
/// 겹친 가림층이 모두 유닛 뒤에 있으면(유닛이 앞) false(앞에 선 유닛 위에 실루엣이 덧칠되지 않게) · 가림층과 안 겹치면 true(성루 지붕 등 기믹 마스크는 그대로).
|
|
/// </summary>
|
|
public static bool GhostAllowed(Bounds unit)
|
|
{
|
|
bool front = false;
|
|
for (int i = covers.Count - 1; i >= 0; i--)
|
|
{
|
|
var sr = covers[i].sr;
|
|
if (sr == null)
|
|
{
|
|
covers.RemoveAt(i);
|
|
continue;
|
|
}
|
|
if (!sr.enabled || !sr.gameObject.activeInHierarchy) continue;
|
|
var b = sr.bounds;
|
|
if (unit.max.x < b.min.x || unit.min.x > b.max.x || unit.max.y < b.min.y || unit.min.y > b.max.y) continue;
|
|
if (unit.center.y > sr.transform.position.y) return true; // 유닛 정렬점(몸 가운데)이 가림층 기준점보다 위 = 뒤
|
|
front = true;
|
|
}
|
|
return !front;
|
|
}
|
|
|
|
// ---------- 자리 보정(Board.ClampInside) ----------
|
|
|
|
const float Eps = 0.01f;
|
|
|
|
/// <summary>반지름 radius 원이 걷는 땅 안 · 막힌 구조물 밖에 오도록 p 를 가장 가까운 자리로 옮긴다.</summary>
|
|
public Vector2 Clamp(Vector2 p, float radius)
|
|
{
|
|
for (int it = 0; it < 4; it++)
|
|
{
|
|
bool moved = false;
|
|
if (walk != null)
|
|
{
|
|
Vector2 q, segN;
|
|
float d = Nearest(walk, p, out q, out segN);
|
|
bool inside = Inside(walk, p);
|
|
if (!inside || d < radius)
|
|
{
|
|
Vector2 inward = inside ? p - q : q - p;
|
|
if (inward.sqrMagnitude < 1e-8f) inward = Inside(walk, q + segN * 0.05f) ? segN : -segN;
|
|
p = q + inward.normalized * (radius + Eps);
|
|
moved = true;
|
|
}
|
|
}
|
|
foreach (var w in walls)
|
|
{
|
|
Vector2 q, segN;
|
|
float d = Nearest(w, p, out q, out segN);
|
|
bool inside = Inside(w, p);
|
|
if (inside || d < radius)
|
|
{
|
|
p = PushOut(w, p, radius);
|
|
moved = true;
|
|
}
|
|
}
|
|
if (!moved) break;
|
|
}
|
|
return p;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 막힌 구조물 w 밖으로 — 변마다 「변 밖 radius 자리」 후보를 내고 걷는 땅 안에 드는 가장 가까운 후보(벽에 붙은 구조물이면 벽 쪽 변은 건너뜀) ·
|
|
/// 그런 후보가 없으면 가장 가까운 변.
|
|
/// </summary>
|
|
Vector2 PushOut(Vector2[] w, Vector2 p, float radius)
|
|
{
|
|
Vector2 best = p, any = p;
|
|
float bestD = float.MaxValue, anyD = float.MaxValue;
|
|
for (int i = 0, j = w.Length - 1; i < w.Length; j = i++)
|
|
{
|
|
Vector2 a = w[j], b = w[i], ab = b - a;
|
|
float l2 = ab.sqrMagnitude;
|
|
if (l2 < 1e-8f) continue;
|
|
Vector2 c = a + ab * Mathf.Clamp01(Vector2.Dot(p - a, ab) / l2);
|
|
Vector2 n = new Vector2(-ab.y, ab.x).normalized;
|
|
if (Inside(w, c + n * 0.05f)) n = -n; // 바깥쪽
|
|
Vector2 cand = c + n * (radius + Eps);
|
|
float dd = (cand - p).sqrMagnitude;
|
|
if (dd < anyD)
|
|
{
|
|
anyD = dd;
|
|
any = cand;
|
|
}
|
|
if (dd < bestD && (walk == null || (Inside(walk, cand) && Dist(walk, cand) >= radius)))
|
|
{
|
|
bestD = dd;
|
|
best = cand;
|
|
}
|
|
}
|
|
return bestD < float.MaxValue ? best : any;
|
|
}
|
|
|
|
static float Dist(Vector2[] poly, Vector2 p)
|
|
{
|
|
Vector2 q, n;
|
|
return Nearest(poly, p, out q, out n);
|
|
}
|
|
|
|
/// <summary>점 p 가 걷는 땅 안(막힌 구조물 밖)인가 — 반지름 무시.</summary>
|
|
public bool Walkable(Vector2 p)
|
|
{
|
|
if (walk != null && !Inside(walk, p)) return false;
|
|
foreach (var w in walls)
|
|
if (Inside(w, p)) return false;
|
|
return true;
|
|
}
|
|
|
|
static bool Inside(Vector2[] poly, Vector2 p)
|
|
{
|
|
bool c = false;
|
|
for (int i = 0, j = poly.Length - 1; i < poly.Length; j = i++)
|
|
{
|
|
Vector2 a = poly[i], b = poly[j];
|
|
if ((a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x) c = !c;
|
|
}
|
|
return c;
|
|
}
|
|
|
|
static float Nearest(Vector2[] poly, Vector2 p, out Vector2 q, out Vector2 segNormal)
|
|
{
|
|
float best = float.MaxValue;
|
|
q = p;
|
|
segNormal = Vector2.up;
|
|
for (int i = 0, j = poly.Length - 1; i < poly.Length; j = i++)
|
|
{
|
|
Vector2 a = poly[j], b = poly[i], ab = b - a;
|
|
float l2 = ab.sqrMagnitude;
|
|
float t = l2 > 1e-8f ? Mathf.Clamp01(Vector2.Dot(p - a, ab) / l2) : 0f;
|
|
Vector2 c = a + ab * t;
|
|
float d = (p - c).magnitude;
|
|
if (d < best)
|
|
{
|
|
best = d;
|
|
q = c;
|
|
segNormal = l2 > 1e-8f ? new Vector2(-ab.y, ab.x).normalized : Vector2.up;
|
|
}
|
|
}
|
|
return best;
|
|
}
|
|
}
|
|
}
|