using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using TKS.OutGame;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace TKS.Tests
{
///
/// 맵 경계 · 가림층 실측(PD 2026-11-26 「전 맵 디자인을 실측한 후 콜라이더 · 레이어 · 새 맵도 같은 규칙」) — 판정 도구(Play 중 script eval 로 부름):
/// TKS.Tests.MapBoundsRunner.Launch("stage:1-3,scn:hulao,scn:chibi");
/// 대상마다 전투를 열고 ① 바닥 그림 · 걷는 땅 · 가림층 수 ② 모든 유닛이 걷는 땅 안인가 ③ 아래로 쏜 아군이 아래 경계에서 튕겨 걷는 땅 안에 남는가
/// ④ 전장 전체 · 아래 끝 · 위 끝 캡처(아래 끝 = 아군 1기를 아래 가림층 뒤에 세워 실루엣 확인)를 Temp/SlingProbe/mapbounds_<대상>_*.png 와 mapbounds.txt 로 남긴다.
///
public class MapBoundsRunner : MonoBehaviour
{
static string Dir
{
get { return Path.Combine(Application.dataPath, "..", "Temp", "SlingProbe"); }
}
public static void Launch(string targets)
{
var go = new GameObject("MapBoundsRunner");
DontDestroyOnLoad(go);
var r = go.AddComponent();
r.StartCoroutine(r.Run(targets));
}
readonly StringBuilder log = new StringBuilder();
int errors;
IEnumerator Run(string targets)
{
Directory.CreateDirectory(Dir);
string done = Path.Combine(Dir, "mapbounds_done.txt");
if (File.Exists(done)) File.Delete(done);
Application.LogCallback onLog = (msg, stack, type) =>
{
if (type != LogType.Error && type != LogType.Exception) return;
errors++;
if (errors <= 12) log.AppendLine("ERROR " + msg + " | " + (stack ?? "").Split('\n')[0]);
};
Application.logMessageReceived += onLog;
var prevMode = ScenarioEvent.Mode;
ScenarioEvent.Mode = TutorialMode.ForceOn; // 연의 편 바닥 · 소품은 연출이 켜져야 깔림(메모리 저장 = 꺼짐)
SaveStore.UseMemory(true);
SceneManager.LoadScene("Battle");
yield return null;
yield return null;
float t0 = Time.realtimeSinceStartup;
while (OutGameRoot.Instance == null && Time.realtimeSinceStartup - t0 < 20f) yield return null;
foreach (var raw in targets.Split(','))
{
string t = raw.Trim();
if (t.Length == 0) continue;
yield return One(t);
}
ScenarioEvent.Mode = prevMode;
Application.logMessageReceived -= onLog;
log.AppendLine("errors " + errors);
File.WriteAllText(Path.Combine(Dir, "mapbounds.txt"), log.ToString(), Encoding.UTF8);
File.WriteAllText(done, "ok");
Destroy(gameObject);
}
IEnumerator One(string t)
{
var bm = BattleManager.Instance;
log.AppendLine("== " + t);
bool danger = t.EndsWith("+danger"); // 적 위험 범위 켜고 그 테두리를 크게 찍음(2026-11-26 「적의 공격 범위가 해상도가 깨져 보임」)
if (danger) t = t.Substring(0, t.Length - 7);
bool prevDanger = DangerZone.On;
if (danger) DangerZone.On = true; // 끝나면 되돌림(PlayerPrefs)
string label = t.Replace(':', '_') + (danger ? "_danger" : "");
if (t.StartsWith("stage:"))
{
var p = t.Substring(6).Split('-');
var wm = WorldMapScreen.Instance;
if (wm == null || !wm.HasData) { log.AppendLine(" 월드맵 없음"); yield break; }
wm.EnterStage(int.Parse(p[0]), int.Parse(p[1]));
}
else if (t.StartsWith("scn:"))
{
string id = t.Substring(4);
var root = OutGameRoot.Instance;
ScenarioData.Reload();
ContentTables.Reload();
ScenarioProps.Reload();
var stage = new BalanceConfig.StageDef { title = id, subtitle = "연의 전기", kind = StageKind.Normal, aiAccuracy = 1f, aiAggroRange = 999f };
var rules = new ScenarioRules { BattleId = id, Hard = false, Config = root.Battle.Config };
var why = rules.Prepare(stage);
if (why != null) { log.AppendLine(" 준비 실패 " + why); yield break; }
root.StartMode(ScenarioModeRules.Kind, id, 0, stage, rules.TurnLimitValue, ArenaScreen.ScenarioPage, rules);
}
float t0 = Time.realtimeSinceStartup;
yield return null;
bm = BattleManager.Instance;
while (bm.Phase != BattlePhase.PlayerTurn && Time.realtimeSinceStartup - t0 < 40f)
{
ScenarioEvent.SkipForTest();
ScenarioEvent.TapForTest();
yield return null;
}
yield return new WaitForSecondsRealtime(0.3f);
var board = bm.Board;
var mb = board.Bounds;
log.AppendLine(" phase " + bm.Phase + " · 바닥 " + (mb != null ? mb.File : "(경계 없음)") + " · 걷는 땅 점 " + (mb != null && mb.Walk != null ? mb.Walk.Length : 0) +
" · 벽 " + (mb != null ? mb.WallCount : 0) + " · 가림층 " + (mb != null ? mb.CoverCount : 0));
int outside = 0;
foreach (var f in new[] { Faction.Player, Faction.Enemy })
foreach (var u in bm.AliveUnits(f))
{
Vector2 c = board.ClampInside(u.Position, u.Radius);
if ((c - u.Position).sqrMagnitude > 1e-4f)
{
outside++;
log.AppendLine(" 밖: " + u.DisplayName + " " + V(u.Position) + " → " + V(c));
}
}
log.AppendLine(" 유닛 " + bm.Units.Count + " · 걷는 땅 밖 " + outside);
Capture(label + "_all", 0f, 17.2f);
if (danger)
{
yield return null;
yield return null;
Unit e0 = null;
foreach (var e in bm.AliveUnits(Faction.Enemy)) if (e0 == null || e.Position.y > e0.Position.y) e0 = e; // 가장 위(적 진영) 적 = 원 윗변이 열린 땅
if (e0 != null)
{
float reach = DangerZone.Reach(e0, 0.5f);
Vector2 at = e0.Position + new Vector2(0.35f, 0.94f).normalized * reach;
CaptureAt(label + "_zone", at, 1.6f);
log.AppendLine(" 위험 범위 켬 · 테두리 확대 캡처 " + V(at));
}
DangerZone.On = prevDanger;
}
float bottom, top;
board.EdgesAt(0f, out bottom, out top); // 가운데 세로줄의 아래 · 위 끝(걷는 땅)
Capture(label + "_mid", 0f, 6f);
// 아래 끝: 아군 1기를 아래 경계 바로 위(가림층 뒤)에 세움 → 실루엣
Unit low = null;
foreach (var u in bm.AliveUnits(Faction.Player))
if (low == null || u.Position.y < low.Position.y) low = u;
if (low != null)
{
Vector2 keep = low.Position;
low.Position = board.ClampInside(new Vector2(keep.x, bottom - 1f), low.Radius);
Physics2D.SyncTransforms();
yield return null;
yield return null;
Capture(label + "_bottom", bottom + 4.5f, 6f);
low.Position = keep;
Physics2D.SyncTransforms();
}
Capture(label + "_top", top - 4.5f, 6f);
// 튕김: 가장 아래 아군을 아래로 쏨 → 경계에서 튕겨 걷는 땅 안
if (low != null && bm.CanAct(low))
{
Vector2 from = low.Position;
var aim = from + new Vector2(0.15f, -9f);
if (bm.RequestPlayerAction(low, aim))
{
float w0 = Time.realtimeSinceStartup;
float minY = from.y;
while (bm.Phase == BattlePhase.Resolving && Time.realtimeSinceStartup - w0 < 20f)
{
minY = Mathf.Min(minY, low.Position.y);
yield return null;
}
Vector2 c = board.ClampInside(low.Position, low.Radius);
log.AppendLine(" 아래로 쏨 " + low.DisplayName + " " + V(from) + " → 끝 " + V(low.Position) + " · 가장 아래 y " + minY.ToString("0.00", CultureInfo.InvariantCulture) +
" · 아래 경계 y " + bottom.ToString("0.00", CultureInfo.InvariantCulture) + " · 끝이 걷는 땅 " + ((c - low.Position).sqrMagnitude < 1e-4f ? "안" : "밖"));
Capture(label + "_bounce", bottom + 4.5f, 6f);
}
}
}
static string V(Vector2 v)
{
return "(" + v.x.ToString("0.00", CultureInfo.InvariantCulture) + ", " + v.y.ToString("0.00", CultureInfo.InvariantCulture) + ")";
}
static void Capture(string name, float y, float size)
{
CaptureAt(name, new Vector2(0f, y), size);
}
static void CaptureAt(string name, Vector2 at, float size)
{
var main = Camera.main;
if (main == null) return;
var go = new GameObject("MapBoundsCam");
var cam = go.AddComponent();
cam.CopyFrom(main);
cam.transform.position = new Vector3(at.x, at.y, main.transform.position.z);
cam.orthographicSize = size;
var rt = new RenderTexture(720, 1280, 24);
cam.targetTexture = rt;
cam.Render();
RenderTexture.active = rt;
var tex = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
tex.Apply();
File.WriteAllBytes(Path.Combine(Dir, "mapbounds_" + name + ".png"), tex.EncodeToPNG());
cam.targetTexture = null;
RenderTexture.active = null;
Destroy(rt);
Destroy(tex);
Destroy(go);
}
}
}