ThreeKingdomsSlingshot/Assets/Scripts/Runtime/Gimmicks/GimmickView.cs

711 lines
36 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;
using System.Collections.Generic;
using UnityEngine;
namespace TKS
{
/// <summary>
/// 기믹 표시(PD #1097 §6): 스프라이트(Resources/Gimmicks/Art/&lt;art&gt;)가 있으면 모양에 맞춰 늘리고, 없으면 색 도형 + 이름 글자.
/// 장애물 = 내구 핍 · 피격 흔들림 · 파괴 파편 → 잔해(art_broken) · 함정 = 발동 전 숨김 · 불 = 꺼지면 회색 · 군기 = 점령 진영 색.
/// 정렬 = 배경(−20~−16) 위 · 유닛(−6~) 아래.
/// </summary>
public class GimmickView
{
public const int ZoneOrder = -15;
public const int RiverOrder = -14;
public const int BridgeOrder = -13;
public const int BlockOrder = -12;
public const int LabelOrder = -11;
public const int OverUnitOrder = 1; // 유닛 몸(0) 위 · 체력 바(2·3) 아래 — 안개 덩어리(obj_layer over)
public const string ArtFolder = "Gimmicks/Art/";
static Material polyMaterial;
readonly GimmickInstance g;
readonly Transform root;
Transform body;
Renderer fill;
TextMesh label;
readonly List<SpriteRenderer> pips = new List<SpriteRenderer>();
Color baseColor;
Coroutine shake;
// 그림 표 방식(GimmickArt) — style == null 이면 예전 색 도형/늘린 그림
GimmickArt.Style style;
readonly List<SpriteRenderer> objs = new List<SpriteRenderer>(); // 세운 물체(말뚝 · 덤불 · 불꽃 · 성루 · 바위 …)
SpriteRenderer flag; // 군기 깃발(점령 진영 색)
float artTop; // 세운 그림의 위 끝(내구 핍 자리)
float fade = 1f; // 사라짐 연출 불투명도
bool revealed; // 함정 드러남
bool stripV; // strip 세로 구간 = sprite_v 마디 사용(상태 반영도 같은 이름 목록)
bool patchLong; // patch 가 긴 통째 그림(sprite_long)을 골랐음 → sprite_alt 두 번째 이름(긴 것의 상태 그림)
readonly HashSet<SpriteRenderer> cleared = new HashSet<SpriteRenderer>(); // 걷힌 안개 덩어리
public GimmickView(GimmickInstance inst)
{
g = inst;
root = inst.Go.transform;
Build();
}
public Transform Body
{
get { return body; }
}
public bool Visible
{
get { return body != null && body.gameObject.activeSelf; }
}
public string LabelText
{
get { return label != null ? label.text : ""; }
}
public int PipCount
{
get { return pips.Count; }
}
public static Color ColorOf(GimmickDef d)
{
switch (d.zone)
{
case GimmickZone.Poison: return new Color(0.55f, 0.25f, 0.75f, 0.45f);
case GimmickZone.Slow: return new Color(0.42f, 0.32f, 0.16f, 0.5f);
case GimmickZone.Burn: return new Color(1f, 0.45f, 0.1f, 0.5f);
case GimmickZone.Slide: return new Color(0.6f, 0.88f, 1f, 0.5f);
case GimmickZone.High: return new Color(0.78f, 0.66f, 0.4f, 0.38f);
case GimmickZone.Fog: return new Color(0.92f, 0.92f, 0.96f, 0.42f);
case GimmickZone.Capture: return new Color(0.75f, 0.75f, 0.75f, 0.3f);
case GimmickZone.Trap: return new Color(0.3f, 0.18f, 0.08f, 0.85f);
case GimmickZone.River: return new Color(0.2f, 0.45f, 0.85f, 0.9f);
}
if (d.id == GimmickIds.Bridge) return new Color(0.62f, 0.46f, 0.26f, 1f);
if (d.id == GimmickIds.Boulder) return new Color(0.52f, 0.52f, 0.55f, 1f);
if (d.projectile == GimmickProjectile.Destroy) return new Color(0.78f, 0.22f, 0.15f, 1f);
if (d.strategistClear) return new Color(0.2f, 0.42f, 0.18f, 1f); // 가시덤불
if (d.projectile == GimmickProjectile.Pass) return new Color(0.58f, 0.4f, 0.2f, 1f); // 목책
if (d.durable) return new Color(0.42f, 0.27f, 0.14f, 1f); // 성문
return new Color(0.46f, 0.46f, 0.43f, 1f); // 성벽
}
static int OrderOf(GimmickInstance i)
{
if (i.Zone == GimmickZone.River) return RiverOrder;
if (i.IsBridge) return BridgeOrder;
return i.IsBlock ? BlockOrder : ZoneOrder;
}
void Build()
{
var bgo = new GameObject("Body");
bgo.transform.SetParent(root, false);
body = bgo.transform;
baseColor = ColorOf(g.Def);
int order = OrderOf(g);
var s = g.Shape;
// 그림 표(gimmick_art.csv)에 줄이 있으면 모양에 맞춰 굽거나 비율 유지로 세운다(PD 2026-11-10) · 없거나 그림이 없으면 예전 방식
style = s.Type == GimmickShapeType.Poly ? null : GimmickArt.Get(g.Def.id);
if (style != null && !BuildArt(order)) style = null;
if (style == null)
{
var art = string.IsNullOrEmpty(g.Def.art) ? null : Resources.Load<Sprite>(ArtFolder + g.Def.art);
if (s.Type == GimmickShapeType.Poly)
{
fill = MakePoly(body, s, baseColor, order);
}
else
{
Vector2 size = s.Type == GimmickShapeType.Circle ? new Vector2(s.R * 2f, s.R * 2f) : s.Size;
var sr = ProceduralSprites.NewSprite(body, "Fill", art != null ? art : (s.Type == GimmickShapeType.Circle ? ProceduralSprites.Circle : ProceduralSprites.Square), art != null ? Color.white : baseColor, 1f, order);
Vector2 native = sr.sprite.bounds.size;
sr.transform.localScale = new Vector3(size.x / Mathf.Max(0.001f, native.x), size.y / Mathf.Max(0.001f, native.y), 1f);
sr.transform.localRotation = Quaternion.Euler(0f, 0f, s.Type == GimmickShapeType.Rect ? s.Rot : 0f);
fill = sr;
if (art != null) baseColor = Color.white;
if (g.Zone == GimmickZone.Fog) sr.maskInteraction = SpriteMaskInteraction.VisibleOutsideMask; // 책사 광역이 걷은 자리(SpriteMask)는 안 그림
}
}
float h = Mathf.Clamp(Mathf.Min(s.Type == GimmickShapeType.Rect ? Mathf.Min(s.Size.x, s.Size.y) : s.BoundingRadius) * 0.55f, 0.22f, 0.5f);
label = TextUtil.CreateWorldText(body, g.Def.nameKo, h, new Color(1f, 1f, 1f, g.IsBlock ? 0.95f : 0.75f), LabelOrder);
label.gameObject.name = "Label";
if (g.Zone == GimmickZone.River && s.Type == GimmickShapeType.Rect) label.transform.localPosition = (Vector3)(s.LocalAxisX * s.Size.x * 0.3f); // 다리 글자와 겹치지 않게
if (style != null) label.gameObject.SetActive(false); // 그림이 있으면 이름 글자 없음(기획서 §6 「그림 · 없으면 색 도형 + 이름」) · 글자 값은 계속 갱신
if (g.Def.durable && g.MaxHp > 0)
{
float top = s.Type == GimmickShapeType.Rect ? Mathf.Abs(s.Size.y) * 0.5f + 0.18f : s.BoundingRadius + 0.18f;
if (style != null) top = Mathf.Max(top, artTop + 0.1f); // 세운 그림(말뚝·성문) 위로
const float w = 0.16f, gap = 0.05f;
float total = g.MaxHp * w + (g.MaxHp - 1) * gap;
for (int i = 0; i < g.MaxHp; i++)
{
var p = ProceduralSprites.NewSprite(body, "Pip", ProceduralSprites.Square, Color.white, 1f, LabelOrder);
p.transform.localPosition = new Vector3(-total * 0.5f + w * 0.5f + i * (w + gap), top, 0f);
p.transform.localScale = new Vector3(w, 0.1f, 1f);
var ps = UISkin.WorldSprite("pip", 460f); // 팩 둥근 칸 핍(PD #1100 · 외곽선)
if (ps != null)
{
p.sprite = ps;
p.drawMode = SpriteDrawMode.Sliced;
p.transform.localScale = Vector3.one;
p.size = new Vector2(w, 0.12f);
}
pips.Add(p);
}
}
if (g.Zone == GimmickZone.Trap) body.gameObject.SetActive(false); // 함정 = 숨김(아군 조준선 미표시 · 적 AI 는 인지)
Refresh();
}
// ---------- 그림 표 방식(PD 2026-11-10 지형 화풍 반영) ----------
/// <summary>모양 반폭·반높이(원 = 반지름).</summary>
Vector2 Half
{
get
{
var s = g.Shape;
return s.Type == GimmickShapeType.Circle ? new Vector2(s.R, s.R) : new Vector2(Mathf.Abs(s.Size.x) * 0.5f, Mathf.Abs(s.Size.y) * 0.5f);
}
}
Vector2 Local(float lx, float ly)
{
var s = g.Shape;
if (s.Type != GimmickShapeType.Rect || Mathf.Abs(s.Rot) < 0.01f) return new Vector2(lx, ly);
return (Vector2)(Quaternion.Euler(0f, 0f, s.Rot) * new Vector3(lx, ly, 0f));
}
SpriteRenderer Baked(string key, int order)
{
var st = GimmickArt.Get(key);
var sp = GimmickArt.BakeZone(st, g.Shape);
if (sp == null) return null;
var sr = ProceduralSprites.NewSprite(body, "Fill", sp, Color.white, 1f, order);
sr.transform.localRotation = Quaternion.Euler(0f, 0f, g.Shape.Type == GimmickShapeType.Rect ? g.Shape.Rot : 0f);
if (g.Zone == GimmickZone.Fog) sr.maskInteraction = SpriteMaskInteraction.VisibleOutsideMask; // 책사 광역이 걷은 자리는 안 그림
return sr;
}
/// <summary>patch = 9-slice 덩어리 그림을 모양 크기로(외곽선·모서리 두께 고정) · ext_b/ext_t = 모양 밖으로 더 그리는 두께 띠·절벽.</summary>
SpriteRenderer Patch(string key, int order)
{
var st = GimmickArt.Get(key);
if (st == null) return null;
var half = Half;
string whole = null; // 9-slice 대신 통째로 늘릴 그림(원형 = 둥근 전용 · 가로세로비 ≤ oval_max = 타원 웅덩이 · QA B2·B5·B6)
if (g.Shape.Type == GimmickShapeType.Circle && st.spriteRound.Length > 0) whole = st.spriteRound;
else if (st.spriteOval.Length > 0 && Mathf.Max(half.x, half.y) / Mathf.Max(0.01f, Mathf.Min(half.x, half.y)) <= st.ovalMax) whole = st.spriteOval;
else if (st.spriteLong.Length > 0) whole = st.spriteLong; // 가로로 긴 모양 = 긴 통째 그림(굽이진 물가 · QA B2 · PD 2026-11-10 자연 지형)
var sp = GimmickArt.PatchSprite(st, whole);
if (sp == null) return null;
if (key == style?.key) patchLong = whole != null && whole == st.spriteLong && whole != st.spriteOval;
var sr = ProceduralSprites.NewSprite(body, "Fill", sp, Color.white, 1f, order);
sr.drawMode = SpriteDrawMode.Sliced;
float hgt = half.y * 2f;
if (whole != null && st.keepAspect > 0f) // 통째 그림의 원래 가로세로비를 일부 살림(둥근 모양을 원에 억지로 맞춰 찌그러지지 않게)
hgt = Mathf.Lerp(hgt, half.x * 2f * sp.rect.height / Mathf.Max(1f, sp.rect.width), st.keepAspect);
sr.size = new Vector2(half.x * 2f + st.extW, hgt + st.extB + st.extT);
sr.transform.localPosition = (Vector3)Local(0f, (st.extT - st.extB) * 0.5f);
sr.transform.localRotation = Quaternion.Euler(0f, 0f, g.Shape.Type == GimmickShapeType.Rect ? g.Shape.Rot : 0f);
if (g.Zone == GimmickZone.Fog) sr.maskInteraction = SpriteMaskInteraction.VisibleOutsideMask;
return sr;
}
/// <summary>바닥 그림 = 표의 mode 가 patch 면 9-slice · 아니면 굽기(zone).</summary>
SpriteRenderer Ground(string key, int order)
{
var st = GimmickArt.Get(key);
if (st == null) return null;
return st.mode == "patch" ? Patch(key, order) : Baked(key, order);
}
/// <summary>책사 광역이 걷은 안개 = 그 반경 안 구름 덩어리만 사라짐(Fable 1안 · PD 2026-11-10).</summary>
public void ClearPuffs(Vector2 c, float r)
{
if (style == null) return;
foreach (var o in objs)
{
if (o == null || cleared.Contains(o) || !o.gameObject.activeInHierarchy) continue;
Vector2 p = o.bounds.center;
if (Vector2.Distance(p, c) > r) continue;
cleared.Add(o);
Fx.Run(FadeOut(o, 0.35f));
}
}
static IEnumerator FadeOut(SpriteRenderer o, float dur)
{
float t = 0f, a0 = o != null ? o.color.a : 0f;
while (t < dur && o != null)
{
t += Time.deltaTime;
var c = o.color;
c.a = a0 * (1f - t / dur);
o.color = c;
yield return null;
}
if (o != null) o.gameObject.SetActive(false);
}
/// <summary>물체 1개 = 비율 유지 · 폭 width · 불투명 아래 끝 = bottom(몸 기준 좌표).</summary>
SpriteRenderer Obj(string name, Vector2 bottomCenter, float width, int order)
{
var sp = GimmickArt.Art(name);
if (sp == null || width <= 0f) return null;
var sr = ProceduralSprites.NewSprite(body, "Art", sp, Color.white, 1f, order);
float k = width / Mathf.Max(0.001f, sp.bounds.size.x);
sr.transform.localScale = new Vector3(k, k, 1f);
sr.transform.localPosition = new Vector3(bottomCenter.x - sp.bounds.center.x * k, bottomCenter.y - sp.bounds.min.y * k, 0f);
artTop = Mathf.Max(artTop, bottomCenter.y + sp.bounds.size.y * k);
objs.Add(sr);
return sr;
}
bool BuildArt(int order)
{
var st = style;
var half = Half;
artTop = half.y;
int seed = Mathf.Abs(Mathf.RoundToInt(g.Shape.Center.x * 73f + g.Shape.Center.y * 151f)) % 997 + 1;
switch (st.mode)
{
case "zone":
fill = Baked(st.key, order);
break;
case "patch":
fill = Patch(st.key, st.objOver ? OverUnitOrder : order); // obj_layer over = 그림 1장이 유닛 몸 위(안개)
break;
case "object":
Obj(st.sprite, Local(0f, -half.y + st.objDy), half.x * 2f * st.objW, BlockOrder);
break;
case "scatter":
{
int objOrder = st.objOver ? OverUnitOrder : BlockOrder;
if (st.baseKey.Length > 0)
{
fill = Ground(st.baseKey, st.objGround ? order - 1 : order); // objGround = 물체(물결)가 바닥 바로 위 · 다리·장애물보다 아래
if (st.objGround) objOrder = order;
}
var rng = new System.Random(seed);
int nx = Mathf.Max(1, Mathf.RoundToInt(half.x * 2f / st.cellW)), ny = Mathf.Max(1, Mathf.RoundToInt(half.y * 2f / st.cellH));
var pts = new List<Vector2>();
for (int yy = 0; yy < ny; yy++)
{
for (int xx = 0; xx < nx; xx++)
{
float lx = -half.x + (xx + 0.5f) * half.x * 2f / nx + ((float)rng.NextDouble() - 0.5f) * st.cellW * 0.25f;
float ly = -half.y + (yy + 0.5f) * half.y * 2f / ny + ((float)rng.NextDouble() - 0.5f) * st.cellH * 0.25f;
if (g.Shape.Type == GimmickShapeType.Circle && Mathf.Sqrt(lx * lx + ly * ly) > half.x * st.circleFill) continue; // 원 안 채움 정도(표 circle_fill)
pts.Add(new Vector2(lx, ly));
}
}
if (pts.Count == 0 && st.edge.Length == 0) pts.Add(Vector2.zero);
if (st.sprite.Length == 0) pts.Clear();
// 가장자리 소품(QA B2 · 곧은 변을 덩어리 굴곡으로 끊음): edge = top | bottom | both · 원 = 둘레
var edgePts = new List<Vector2>();
if (st.edge.Length > 0 && st.edgeSprite.Length > 0)
{
if (g.Shape.Type == GimmickShapeType.Circle)
{
int n = Mathf.Max(3, Mathf.RoundToInt(2f * Mathf.PI * half.x / st.edgeGap));
for (int i = 0; i < n; i++)
{
float an = (i + (float)rng.NextDouble() * 0.4f) * Mathf.PI * 2f / n;
float sy = Mathf.Sin(an);
if ((st.edge == "top" && sy < 0.2f) || (st.edge == "bottom" && sy > -0.2f)) continue;
edgePts.Add(new Vector2(Mathf.Cos(an) * half.x, sy * half.y));
}
}
else
{
int n = Mathf.Max(2, Mathf.RoundToInt(half.x * 2f / st.edgeGap));
foreach (float ey in st.edge == "top" ? new[] { half.y } : st.edge == "bottom" ? new[] { -half.y } : new[] { half.y, -half.y })
{
for (int i = 0; i < n; i++)
{
float ex = -half.x + (i + 0.5f) * half.x * 2f / n + ((float)rng.NextDouble() - 0.5f) * st.edgeGap * 0.5f;
edgePts.Add(new Vector2(Mathf.Clamp(ex, -half.x + st.edgeW * 0.4f, half.x - st.edgeW * 0.4f), ey));
}
}
}
}
pts.Sort((a, b) => b.y.CompareTo(a.y)); // 위(먼 것)부터
var names = st.sprite.Split(';'); // 여러 그림이면 칸마다 무작위(늪 = 갈대 · 연잎)
foreach (var p in pts)
{
float w = st.objW * (1f + ((float)rng.NextDouble() * 2f - 1f) * st.jitter);
var o = Obj(names[rng.Next(names.Length)].Trim(), Local(p.x, p.y - w * 0.3f), w, objOrder);
if (o != null && st.flip && rng.NextDouble() < 0.5) o.flipX = true;
}
var enames = st.edgeSprite.Split(';');
edgePts.Sort((a, b) => b.y.CompareTo(a.y));
foreach (var p in edgePts)
{
float w = st.edgeW * (1f + ((float)rng.NextDouble() * 2f - 1f) * st.jitter);
var o = Obj(enames[rng.Next(enames.Length)].Trim(), Local(p.x, p.y - w * 0.35f), w, BlockOrder);
if (o != null && st.flip && rng.NextDouble() < 0.5) o.flipX = true;
}
break;
}
case "strip":
{
bool vertical = half.y > half.x;
float len = (vertical ? half.y : half.x) * 2f;
stripV = vertical && st.spriteV.Length > 0;
if (stripV) // 세로 구간 = 세로 마디(폭 = 모양 폭 · 높이 = 간격에 맞춰 세로만 살짝 늘림 · 이음 없이 이어 붙임)
{
var vn = st.spriteV.Split(';');
var mid = GimmickArt.Art(StripName(vn, 1, 3));
if (mid == null) break;
float pw = half.x * 2f, ph = pw * mid.bounds.size.y / Mathf.Max(0.001f, mid.bounds.size.x);
int nv = Mathf.Max(1, Mathf.RoundToInt(len / ph));
float pv = len / nv;
for (int i = 0; i < nv; i++)
{
var o = Obj(StripName(vn, i, nv), Local(0f, len * 0.5f - (i + 1) * pv), pw, BlockOrder);
if (o == null) continue;
var sc = o.transform.localScale;
float sy = pv / Mathf.Max(0.001f, o.sprite.bounds.size.y * sc.y);
float bot = o.transform.localPosition.y + o.sprite.bounds.min.y * sc.y;
o.transform.localScale = new Vector3(sc.x, sc.y * sy, 1f);
o.transform.localPosition = new Vector3(o.transform.localPosition.x, bot - o.sprite.bounds.min.y * sc.y * sy, 0f);
}
break;
}
int n = Mathf.Max(1, Mathf.RoundToInt(len / st.period));
float per = len / n;
if (st.shadow > 0f && !vertical) // 바닥 그림자(QA M2 · 세워 둔 느낌) = 납작한 타원 한 줄
{
var sh = ProceduralSprites.NewSprite(body, "Shadow", ProceduralSprites.Circle, new Color(0.25f, 0.15f, 0.08f, st.shadow), 1f, BlockOrder - 1);
var nb = sh.sprite.bounds.size;
sh.transform.localScale = new Vector3((len + st.objW * 0.4f) / nb.x, 0.32f / nb.y, 1f);
sh.transform.localPosition = (Vector3)Local(0f, -half.y + st.objDy + 0.06f);
}
for (int i = 0; i < n; i++)
{
float t = -len * 0.5f + (i + 0.5f) * per;
string nm = StripName(st.sprite.Split(';'), i, n);
float sw = st.objW * per / st.period; // 마디 폭 = 간격에 맞춰 살짝 늘림(이음 없이 이어 붙임)
var o = vertical ? Obj(nm, Local(0f, (len * 0.5f - (i + 0.5f) * per) - st.period * 0.5f + st.objDy), sw, BlockOrder)
: Obj(nm, Local(t, -half.y + st.objDy), sw, BlockOrder);
if (o != null && st.flip && (i % 2) == 1) o.flipX = true; // 마디 좌우 번갈아(같은 마디 반복 티 줄임)
}
break;
}
case "gate":
{
fill = Ground(st.baseKey, BlockOrder - 1); // 성루(BlockOrder)가 성벽 바닥 위에 오게
var wall = GimmickArt.Get(st.baseKey);
float drop = wall != null ? wall.Drop : 0f;
Obj(st.sprite, Local(0f, -half.y - drop + st.objDy), Mathf.Min(half.x * 2f, st.objW), BlockOrder);
break;
}
case "banner":
fill = Ground(st.baseKey, order);
flag = Obj(st.sprite, Local(0f, st.objDy), st.objW, BlockOrder);
break;
}
if (fill == null && objs.Count == 0) return false;
baseColor = Color.white;
return true;
}
/// <summary>strip 그림 이름: 1개 = 전부 같음 · 3개 = 왼끝 · 가운데(반복) · 오른끝(녹각 목책 · PD 2026-11-10 예시).</summary>
static string StripName(string[] names, int i, int n)
{
if (names.Length < 3) return names[0].Trim();
return (i == 0 ? names[0] : i == n - 1 ? names[2] : names[1]).Trim();
}
static Sprite StripPick(string[] names, int i, int n)
{
if (names.Length == 0 || names[0].Trim().Length == 0) return null;
return GimmickArt.Art(StripName(names, i, n));
}
/// <summary>그림 표 방식의 상태 반영(잔해 · 불 꺼짐 · 점령 · 함정 노출).</summary>
void RefreshArt()
{
var st = style;
bool alt = (g.Broken && (st.mode == "strip" || st.mode == "gate" || st.mode == "object")) || (g.Out && st.mode == "scatter") || ((revealed || g.Revealed) && st.mode == "object");
var mainNames = (stripV ? st.spriteV : st.sprite).Split(';');
var altNames = stripV ? mainNames : st.spriteAlt.Split(';');
for (int oi = 0; oi < objs.Count; oi++)
{
var o = objs[oi];
if (o == null) continue;
var want = StripPick(alt ? altNames : mainNames, oi, objs.Count);
if (alt && want == null) want = StripPick(mainNames, oi, objs.Count);
if (st.mode == "scatter" && !alt) continue; // 흩뿌림은 칸마다 다른 그림 · 평상시엔 바꾸지 않음
if (want != null && o.sprite != want)
{
// 바꾼 그림도 같은 폭 · 같은 아래 끝
float w = o.sprite.bounds.size.x * o.transform.localScale.x;
float bottom = o.transform.localPosition.y + o.sprite.bounds.min.y * o.transform.localScale.y;
float cx = o.transform.localPosition.x + o.sprite.bounds.center.x * o.transform.localScale.x;
float k = w / Mathf.Max(0.001f, want.bounds.size.x);
o.sprite = want;
o.transform.localScale = new Vector3(k, k, 1f);
o.transform.localPosition = new Vector3(cx - want.bounds.center.x * k, bottom - want.bounds.min.y * k, 0f);
}
}
if (st.mode == "patch" && st.spriteAlt.Length > 0 && fill is SpriteRenderer) // 통째 그림 상태 교체(불 꺼짐 = 숯 · 부서짐) · 크기 유지
{
var psr = (SpriteRenderer)fill;
var an = st.spriteAlt.Split(';'); // 「둥근·타원;긴」 = 고른 통째 그림에 맞는 상태 그림(불 꺼짐 · 2026-11-11)
var want = (g.Out || g.Broken) ? GimmickArt.PatchSprite(st, an[patchLong && an.Length > 1 ? 1 : 0].Trim()) : null;
if (want != null && psr.sprite != want)
{
var keep = psr.size;
psr.sprite = want;
psr.size = keep;
}
}
if (st.mode == "gate" && g.Broken && st.baseAlt.Length > 0 && fill is SpriteRenderer)
{
var sp = GimmickArt.BakeZone(GimmickArt.Get(st.baseAlt), g.Shape);
if (sp != null) ((SpriteRenderer)fill).sprite = sp;
}
Color fc = Color.white, oc = Color.white;
if (g.Out) fc = st.outTint;
if (g.Zone == GimmickZone.Capture)
{
Color own = g.Owner == (int)Faction.Player ? new Color(0.25f, 0.55f, 0.95f) : g.Owner == (int)Faction.Enemy ? new Color(0.9f, 0.3f, 0.25f) : Color.white;
fc = own;
if (flag != null) flag.color = new Color(Mathf.Lerp(1f, own.r, 0.65f), Mathf.Lerp(1f, own.g, 0.65f), Mathf.Lerp(1f, own.b, 0.65f), fade);
}
var fsr = fill as SpriteRenderer;
if (fsr != null) fsr.color = new Color(fc.r, fc.g, fc.b, fade * (st.mode == "patch" ? st.alpha : 1f)); // patch 불투명도 = 표 alpha(안개 반투명)
foreach (var o in objs)
{
if (o != null && o != flag && !cleared.Contains(o)) o.color = new Color(oc.r, oc.g, oc.b, fade * st.objA);
}
}
static Renderer MakePoly(Transform parent, GimmickShape s, Color color, int order)
{
var go = new GameObject("Fill");
go.transform.SetParent(parent, false);
var mf = go.AddComponent<MeshFilter>();
var mr = go.AddComponent<MeshRenderer>();
if (polyMaterial == null) polyMaterial = new Material(Shader.Find("Sprites/Default"));
mr.sharedMaterial = polyMaterial;
mr.sortingOrder = order;
var mesh = new Mesh();
var verts = new Vector3[s.Points.Length];
var cols = new Color[s.Points.Length];
for (int i = 0; i < verts.Length; i++)
{
verts[i] = s.Points[i] - s.Center;
cols[i] = color;
}
mesh.vertices = verts;
mesh.colors = cols;
mesh.triangles = Triangulate(s.Points);
mf.sharedMesh = mesh;
return mr;
}
/// <summary>귀 자르기 삼각 분할(단순 다각형).</summary>
public static int[] Triangulate(Vector2[] pts)
{
var tris = new List<int>();
var idx = new List<int>();
float area = 0f;
for (int i = 0, j = pts.Length - 1; i < pts.Length; j = i++) area += pts[j].x * pts[i].y - pts[i].x * pts[j].y;
for (int i = 0; i < pts.Length; i++) idx.Add(area > 0f ? i : pts.Length - 1 - i);
int guard = 0;
while (idx.Count > 3 && guard++ < 1000)
{
bool cut = false;
for (int i = 0; i < idx.Count; i++)
{
int a = idx[(i + idx.Count - 1) % idx.Count], b = idx[i], c = idx[(i + 1) % idx.Count];
Vector2 pa = pts[a], pb = pts[b], pc = pts[c];
if ((pb.x - pa.x) * (pc.y - pa.y) - (pb.y - pa.y) * (pc.x - pa.x) <= 0f) continue;
bool inside = false;
foreach (int k in idx)
{
if (k == a || k == b || k == c) continue;
if (InTri(pts[k], pa, pb, pc)) { inside = true; break; }
}
if (inside) continue;
tris.Add(a); tris.Add(b); tris.Add(c);
idx.RemoveAt(i);
cut = true;
break;
}
if (!cut) break;
}
if (idx.Count == 3) { tris.Add(idx[0]); tris.Add(idx[1]); tris.Add(idx[2]); }
return tris.ToArray();
}
static bool InTri(Vector2 p, Vector2 a, Vector2 b, Vector2 c)
{
float d1 = (p.x - b.x) * (a.y - b.y) - (a.x - b.x) * (p.y - b.y);
float d2 = (p.x - c.x) * (b.y - c.y) - (b.x - c.x) * (p.y - c.y);
float d3 = (p.x - a.x) * (c.y - a.y) - (c.x - a.x) * (p.y - a.y);
bool neg = d1 < 0 || d2 < 0 || d3 < 0, pos = d1 > 0 || d2 > 0 || d3 > 0;
return !(neg && pos);
}
/// <summary>상태(내구 · 잔해 · 군기 · 불 꺼짐 · 함정 노출)를 그림에 반영.</summary>
public void Refresh()
{
if (body == null) return;
Color c = baseColor;
string text = g.Def.nameKo;
if (g.Broken)
{
c = Color.Lerp(baseColor, new Color(0.2f, 0.18f, 0.15f, 0.55f), 0.6f);
text = g.Def.nameKo + " 잔해";
var broken = string.IsNullOrEmpty(g.Def.artBroken) ? null : Resources.Load<Sprite>(ArtFolder + g.Def.artBroken);
var sr = fill as SpriteRenderer;
if (broken != null && sr != null)
{
sr.sprite = broken;
c = Color.white;
}
}
if (g.Out)
{
c = new Color(0.35f, 0.33f, 0.3f, 0.35f);
text = "꺼진 잔해";
}
if (g.Zone == GimmickZone.Capture)
{
c = g.Owner == (int)Faction.Player ? new Color(0.25f, 0.55f, 0.95f, 0.35f) : g.Owner == (int)Faction.Enemy ? new Color(0.9f, 0.3f, 0.25f, 0.35f) : baseColor;
text = g.Owner < 0 ? g.Def.nameKo : g.Def.nameKo + (g.Owner == (int)Faction.Player ? "(아군)" : "(적군)");
}
if (g.Zone == GimmickZone.Burn && g.BurnLeft > 0) text = g.Def.nameKo + " " + g.BurnLeft;
if (style != null) RefreshArt();
else SetColor(c);
if (label != null) label.text = text;
for (int i = 0; i < pips.Count; i++)
{
pips[i].color = i < g.Hp ? UISkin.Col("pip_on", new Color(1f, 0.85f, 0.3f)) : UISkin.Col("pip_off", new Color(0.15f, 0.15f, 0.15f, 0.8f));
pips[i].gameObject.SetActive(!g.Broken);
}
}
void SetColor(Color c)
{
var sr = fill as SpriteRenderer;
if (sr != null) sr.color = c;
var mr = fill as MeshRenderer;
if (mr != null)
{
var mf = mr.GetComponent<MeshFilter>();
if (mf != null && mf.sharedMesh != null)
{
var cols = new Color[mf.sharedMesh.vertexCount];
for (int i = 0; i < cols.Length; i++) cols[i] = c;
mf.sharedMesh.colors = cols;
}
}
}
/// <summary>피격 흔들림.</summary>
public void Shake()
{
if (body == null || Fx.Runner == null) return;
if (shake != null) Fx.Runner.StopCoroutine(shake);
shake = Fx.Run(ShakeRoutine());
}
IEnumerator ShakeRoutine()
{
float t = 0f;
const float dur = 0.25f;
while (t < dur && body != null)
{
t += Time.deltaTime;
float k = 1f - t / dur;
body.localPosition = new Vector3(Mathf.Sin(t * 70f) * 0.09f * k, Mathf.Cos(t * 55f) * 0.05f * k, 0f);
yield return null;
}
if (body != null) body.localPosition = Vector3.zero;
shake = null;
}
/// <summary>파괴 파편(작은 조각이 흩어지며 사라짐) → 잔해 표시.</summary>
public void Shatter()
{
Fx.Run(ShatterRoutine(g.Shape.Center, style != null ? style.debris : baseColor));
Refresh();
}
static IEnumerator ShatterRoutine(Vector2 c, Color color)
{
var bits = new List<SpriteRenderer>();
var vel = new List<Vector2>();
for (int i = 0; i < 10; i++)
{
var sr = ProceduralSprites.NewSprite(null, "Debris", ProceduralSprites.Square, new Color(color.r, color.g, color.b, 1f), 0.16f, 7);
sr.transform.position = new Vector3(c.x, c.y, 0f);
float a = i * Mathf.PI * 2f / 10f + Random.value * 0.4f;
vel.Add(new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * (1.5f + Random.value * 1.5f));
bits.Add(sr);
}
float t = 0f;
const float dur = 0.5f;
while (t < dur)
{
t += Time.deltaTime;
for (int i = 0; i < bits.Count; i++)
{
bits[i].transform.position += (Vector3)(vel[i] * Time.deltaTime);
var col = bits[i].color;
col.a = 1f - t / dur;
bits[i].color = col;
}
yield return null;
}
foreach (var b in bits) Object.Destroy(b.gameObject);
}
/// <summary>함정 발동(드러났다 사라짐) · 덤불 제거(흐려지며 사라짐).</summary>
public void Vanish(bool reveal)
{
if (body == null) return;
if (reveal)
{
body.gameObject.SetActive(true);
revealed = true;
}
Refresh();
Fx.Run(VanishRoutine(reveal ? 0.7f : 0.35f));
}
IEnumerator VanishRoutine(float dur)
{
float t = 0f;
while (t < dur && body != null)
{
t += Time.deltaTime;
if (style != null)
{
fade = 1f - t / dur;
RefreshArt();
yield return null;
continue;
}
var c = baseColor;
c.a = baseColor.a * (1f - t / dur);
SetColor(c);
yield return null;
}
if (body != null) body.gameObject.SetActive(false);
}
}
}