using System.Collections.Generic;
using System.IO;
using System.Text;
using TKS.OutGame;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
namespace TKS.EditorTools
{
///
/// 아웃게임 표(Assets/Data/OutGame/*.csv · 기획 tables/ 사본 22장 = A 12 + C 10) → ScriptableObject 18개(Assets/Resources/OutGame/).
/// 메뉴 TKS/Import OutGame Data 또는 CLI: Unity.exe -batchmode -nographics -projectPath <proj> -executeMethod TKS.EditorTools.DataImporter.Import -quit
/// 형식·참조 오류가 하나라도 있으면 자산을 건드리지 않는다(콘솔 error 로 행 번호 보고).
///
public static class DataImporter
{
public const string AssetFolder = "Assets/Resources/OutGame";
[MenuItem("TKS/Import OutGame Data (아웃게임 데이터 임포트)")]
public static void Import()
{
ImportAll();
}
///
/// 임무 표 5장만 임포트(2026-11-20 · 임무 메뉴) → MissionDb.asset 하나만 쓴다(다른 아웃게임 자산은 건드리지 않음 · 오류 시 자산 불변).
/// CLI: -executeMethod TKS.EditorTools.DataImporter.ImportMissions
///
[MenuItem("TKS/Import Missions (임무 표 임포트)")]
public static void ImportMissions()
{
var dir = Path.Combine(Application.dataPath, OutGameTables.Folder);
var texts = new string[OutGameTables.MissionFiles.Length];
for (int i = 0; i < texts.Length; i++)
{
var p = Path.Combine(dir, OutGameTables.MissionFiles[i]);
texts[i] = File.Exists(p) ? File.ReadAllText(p, Encoding.UTF8) : null;
}
var errors = new System.Collections.Generic.List();
var chests = AssetDatabase.LoadAssetAtPath(AssetFolder + "/ChestDb.asset");
var db = OutGameTables.ParseMissionsOnly(texts, chests, errors);
if (errors.Count > 0)
{
foreach (var e in errors) Debug.LogError("[TKS] 임무 표 오류 · " + e);
Debug.LogError("[TKS] 임무 임포트 중단(오류 " + errors.Count + ") · 자산 변경 없음");
Object.DestroyImmediate(db);
return;
}
var path = AssetFolder + "/MissionDb.asset";
var existing = AssetDatabase.LoadAssetAtPath(path);
db.name = "MissionDb";
if (existing == null) AssetDatabase.CreateAsset(db, path);
else
{
EditorUtility.CopySerialized(db, existing);
existing.name = "MissionDb";
EditorUtility.SetDirty(existing);
Object.DestroyImmediate(db);
}
AssetDatabase.SaveAssets();
var d = AssetDatabase.LoadAssetAtPath(path);
Debug.Log("[TKS] 임무 임포트 완료 · 임무 " + d.missions.Count + " · 구간 " + d.rewards.Count + " · 업적 " + d.achievements.Count + " · 카운터 " + d.counters.Count + " · " + path);
}
///
/// 각성 · 진화 표만 임포트(2026-11-20) — 전체 표를 해석·검증(참조 검사)한 뒤 EvolveTable(evolve_stars) · AwakenDb · LevelTable(hero_levels · ★ 최대 레벨과 짝) 세 자산만 쓴다(오류 시 불변).
/// CLI: -executeMethod TKS.EditorTools.DataImporter.ImportAwaken
///
[MenuItem("TKS/Import Awaken · Evolve (각성·진화 표 임포트)")]
public static void ImportAwaken()
{
var r = OutGameTables.Parse(ReadFiles());
if (r.errors.Count > 0)
{
foreach (var e in r.errors) Debug.LogError("[TKS] 아웃게임 표 오류 · " + e);
Debug.LogError("[TKS] 각성·진화 임포트 중단(오류 " + r.errors.Count + ") · 자산 변경 없음");
OutGameTables.Destroy(r);
return;
}
string msg = "[TKS] 각성·진화 임포트 완료 · ★ " + r.data.Evolve.rows.Count + " · 등급 " + r.data.Awaken.grades.Count + " · 능력치 " + r.data.Awaken.stats.Count + " · 비서 " + r.data.Awaken.items.Count + " · 각성 칸 " + r.data.Awaken.slots.Count + " · 스킬 단계 " + r.data.Awaken.skillSteps.Count + " · 영웅 최고 Lv " + r.data.Levels.MaxLevel;
foreach (ScriptableObject so in new ScriptableObject[] { r.data.Evolve, r.data.Awaken, r.data.Levels })
{
var name = so.GetType().Name;
var path = AssetFolder + "/" + name + ".asset";
var existing = AssetDatabase.LoadAssetAtPath(path, so.GetType()) as ScriptableObject;
so.name = name;
if (existing == null) AssetDatabase.CreateAsset(so, path);
else
{
EditorUtility.CopySerialized(so, existing);
existing.name = name;
EditorUtility.SetDirty(existing);
}
}
AssetDatabase.SaveAssets();
foreach (var so in r.data.All)
if (so != null && !AssetDatabase.Contains(so)) Object.DestroyImmediate(so); // 쓰지 않은 해석본(자산이 된 것은 그대로)
Debug.Log(msg);
}
///
/// 장비 등급 7 · 병종 장비 · 장별 드랍 표만 임포트(2026-11-20) — 전체 해석·검증 뒤 GearDb · HeroDb(hero_gear) · PromotionTable · AwakenDb(awaken_slots) 넷만 쓴다(오류 시 불변 ·
/// 다른 작업의 표 변경이 다른 자산에 섞이지 않게). CLI: -executeMethod TKS.EditorTools.DataImporter.ImportGear
///
[MenuItem("TKS/Import Gear (장비 등급 · 드랍 표 임포트)")]
public static void ImportGear()
{
var r = OutGameTables.Parse(ReadFiles());
if (r.errors.Count > 0)
{
foreach (var e in r.errors) Debug.LogError("[TKS] 아웃게임 표 오류 · " + e);
Debug.LogError("[TKS] 장비 임포트 중단(오류 " + r.errors.Count + ") · 자산 변경 없음");
OutGameTables.Destroy(r);
return;
}
var g = r.data.Gear;
string msg = "[TKS] 장비 임포트 완료 · 장비 " + g.items.Count + " · 등급 " + g.grades.Count + " · 병종 부위 " + g.kinds.Count + " · 장 " + g.chapterDrops.Count + " · 스테이지 지정 " + g.stageDrops.Count + " · 승급 " + r.data.Promotion.rows.Count;
foreach (ScriptableObject so in new ScriptableObject[] { r.data.Gear, r.data.Heroes, r.data.Promotion, r.data.Awaken })
{
var name = so.GetType().Name;
var path = AssetFolder + "/" + name + ".asset";
var existing = AssetDatabase.LoadAssetAtPath(path, so.GetType()) as ScriptableObject;
so.name = name;
if (existing == null) AssetDatabase.CreateAsset(so, path);
else
{
EditorUtility.CopySerialized(so, existing);
existing.name = name;
EditorUtility.SetDirty(existing);
}
}
AssetDatabase.SaveAssets();
foreach (var so in r.data.All)
if (so != null && !AssetDatabase.Contains(so)) Object.DestroyImmediate(so);
if (OutGameData.Default != null)
{
OutGameData.Default.Gear.InvalidateIndex();
OutGameData.Default.Heroes.InvalidateIndex();
}
Debug.Log(msg);
}
///
/// 외형(코스튬) 표 임포트(2026-11-20) — 전체 해석·검증 뒤 CostumeDb 하나만 쓴다 + 영웅 유닛 그림(Resources/Units/<art>/<clip>/f###.png)의 알파 경계를 계산해 넣는다
/// (프레임 윗선 이동 · 기준점 자동 = costume_config anchor_fallback · 실행 중 텍스처는 읽기 불가라 임포트 때 계산). CLI: -executeMethod TKS.EditorTools.DataImporter.ImportCostume
///
[MenuItem("TKS/Import Costume (외형 표 · 유닛 알파 경계 임포트)")]
public static void ImportCostume()
{
var r = OutGameTables.Parse(ReadFiles());
if (r.errors.Count > 0)
{
foreach (var e in r.errors) Debug.LogError("[TKS] 아웃게임 표 오류 · " + e);
Debug.LogError("[TKS] 외형 임포트 중단(오류 " + r.errors.Count + ") · 자산 변경 없음");
OutGameTables.Destroy(r);
return;
}
var t = r.data.Costume;
var arts = new HashSet();
foreach (var h in r.data.Heroes.heroes)
if (!h.isSoldier && !string.IsNullOrEmpty(h.art)) arts.Add(h.art);
var tex = new Texture2D(2, 2);
foreach (var art in arts)
{
var dir = Path.Combine(Application.dataPath, "Resources/Units/" + art);
if (!Directory.Exists(dir)) continue;
foreach (var clipDir in Directory.GetDirectories(dir))
{
string clip = Path.GetFileName(clipDir);
foreach (var png in Directory.GetFiles(clipDir, "f*.png"))
{
int idx;
if (!int.TryParse(Path.GetFileNameWithoutExtension(png).Substring(1), out idx)) continue;
if (!tex.LoadImage(File.ReadAllBytes(png))) continue;
var px = tex.GetPixels32();
int w = tex.width, hgt = tex.height, l = w, rr = -1, top = hgt, bot = -1;
for (int y = 0; y < hgt; y++)
{
int row = y * w;
for (int x = 0; x < w; x++)
{
if (px[row + x].a < 26) continue;
int ty = hgt - 1 - y; // 왼쪽 위 0
if (x < l) l = x;
if (x > rr) rr = x;
if (ty < top) top = ty;
if (ty > bot) bot = ty;
}
}
if (rr < 0) continue;
t.frames.Add(new CostumeDb.Frame { art = art, clip = clip, index = idx, w = w, h = hgt, left = l, top = top, right = rr, bottom = bot });
}
}
}
Object.DestroyImmediate(tex);
string msg = "[TKS] 외형 임포트 완료 · 부위 " + t.slots.Count + " · 꾸미기 " + t.items.Count + " · 기준점 " + t.anchors.Count + " · 유닛 " + arts.Count + " · 프레임 경계 " + t.frames.Count;
const string path = AssetFolder + "/CostumeDb.asset";
var existing = AssetDatabase.LoadAssetAtPath(path);
t.name = "CostumeDb";
if (existing == null) AssetDatabase.CreateAsset(t, path);
else
{
EditorUtility.CopySerialized(t, existing);
existing.name = "CostumeDb";
EditorUtility.SetDirty(existing);
}
AssetDatabase.SaveAssets();
foreach (var so in r.data.All)
if (so != null && !AssetDatabase.Contains(so)) Object.DestroyImmediate(so);
Debug.Log(msg);
}
/// 영웅 정보 표 임포트(2026-11-20) — 전체 해석·검증 뒤 HeroInfoDb 하나만 쓴다. CLI: -executeMethod TKS.EditorTools.DataImporter.ImportHeroInfo
[MenuItem("TKS/Import Hero Info (영웅 정보 표 임포트)")]
public static void ImportHeroInfo()
{
var r = OutGameTables.Parse(ReadFiles());
if (r.errors.Count > 0)
{
foreach (var e in r.errors) Debug.LogError("[TKS] 아웃게임 표 오류 · " + e);
Debug.LogError("[TKS] 영웅 정보 임포트 중단(오류 " + r.errors.Count + ") · 자산 변경 없음");
OutGameTables.Destroy(r);
return;
}
var t = r.data.HeroInfo;
string msg = "[TKS] 영웅 정보 임포트 완료 · 능력치 " + t.stats.Count + " · 성장 내역 " + t.sources.Count + " · 열전 " + t.chronicle.Count;
const string path = AssetFolder + "/HeroInfoDb.asset";
var existing = AssetDatabase.LoadAssetAtPath(path);
t.name = "HeroInfoDb";
if (existing == null) AssetDatabase.CreateAsset(t, path);
else
{
EditorUtility.CopySerialized(t, existing);
existing.name = "HeroInfoDb";
EditorUtility.SetDirty(existing);
}
AssetDatabase.SaveAssets();
foreach (var so in r.data.All)
if (so != null && !AssetDatabase.Contains(so)) Object.DestroyImmediate(so);
Debug.Log(msg);
}
public static string[] ReadFiles()
{
var dir = Path.Combine(Application.dataPath, OutGameTables.Folder);
var texts = new string[OutGameTables.Files.Length];
for (int i = 0; i < texts.Length; i++)
{
var p = Path.Combine(dir, OutGameTables.Files[i]);
texts[i] = File.Exists(p) ? File.ReadAllText(p, Encoding.UTF8) : null;
}
return texts;
}
public static bool ImportAll()
{
var r = OutGameTables.Parse(ReadFiles());
if (r.errors.Count > 0)
{
foreach (var e in r.errors) Debug.LogError("[TKS] 아웃게임 표 오류 · " + e);
Debug.LogError("[TKS] 아웃게임 임포트 중단(오류 " + r.errors.Count + ") · 자산 변경 없음");
OutGameTables.Destroy(r);
return false;
}
if (!AssetDatabase.IsValidFolder("Assets/Resources")) AssetDatabase.CreateFolder("Assets", "Resources");
if (!AssetDatabase.IsValidFolder(AssetFolder)) AssetDatabase.CreateFolder("Assets/Resources", "OutGame");
foreach (var so in r.data.All)
{
var name = so.GetType().Name;
var path = AssetFolder + "/" + name + ".asset";
var existing = AssetDatabase.LoadAssetAtPath(path, so.GetType()) as ScriptableObject;
so.name = name;
if (existing == null) AssetDatabase.CreateAsset(so, path);
else
{
EditorUtility.CopySerialized(so, existing);
existing.name = name;
if (existing is HeroDb) ((HeroDb)existing).InvalidateIndex();
if (existing is GearDb) ((GearDb)existing).InvalidateIndex();
EditorUtility.SetDirty(existing);
Object.DestroyImmediate(so);
}
}
AssetDatabase.SaveAssets();
var sb = new StringBuilder("[TKS] 아웃게임 임포트 완료 ·");
foreach (var kv in r.rowCounts) sb.Append(' ').Append(kv.Key).Append(' ').Append(kv.Value);
Debug.Log(sb.Append(" · ").Append(AssetFolder).ToString());
return true;
}
///
/// 아웃게임 화면 검증 캡처(GUI 에디터 · 사본 프로젝트 권장 · 세이브 = 메모리 전용이라 실제 save.json 불변):
/// Unity.exe -projectPath <copy> -executeMethod TKS.EditorTools.DataImporter.CaptureOutGame -outgameDir <dir>
/// 로비 · 영웅 목록 · 영웅 상세 · 편성 · 뽑기 · 뽑기 결과 · 월드맵 팝업 · 전투 결과 PNG + log · 끝나면 스스로 종료.
///
public static void CaptureOutGame()
{
string dir = GetArg("-outgameDir");
if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Directory.GetCurrentDirectory(), "Logs", "outgame_capture");
ImportAll();
EditorSceneManager.OpenScene(ProjectSetup.ScenePath, OpenSceneMode.Single);
SessionState.SetBool(SaveStore.MemoryFlagKey, true);
SessionState.SetString(OutGameCaptureDriver.DirKey, dir);
Debug.Log("[TKS] 아웃게임 캡처 시작 → " + dir);
EditorApplication.EnterPlaymode();
}
///
/// 스킬 화면 검증 캡처(GUI 에디터 · 사본 프로젝트 권장 · 세이브 = 메모리 전용 · PD #1093 B):
/// Unity.exe -projectPath <copy> -executeMethod TKS.EditorTools.DataImporter.CaptureSkills -skillDir <dir>
/// 스킬 레벨업 · 스킬 버튼 · 액티브 발동 · 패시브 표시 PNG 4장 + log · 끝나면 스스로 종료.
///
public static void CaptureSkills()
{
string dir = GetArg("-skillDir");
if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Directory.GetCurrentDirectory(), "Logs", "skill_capture");
ImportAll();
EditorSceneManager.OpenScene(ProjectSetup.ScenePath, OpenSceneMode.Single);
SessionState.SetBool(SaveStore.MemoryFlagKey, true);
SessionState.SetString(SkillCaptureDriver.DirKey, dir);
Debug.Log("[TKS] 스킬 캡처 시작 → " + dir);
EditorApplication.EnterPlaymode();
}
///
/// 아웃게임 2차 화면 검증 캡처(GUI 에디터 · 사본 프로젝트 권장 · 세이브 = 메모리 전용 · PD #1093 C):
/// Unity.exe -projectPath <copy> -executeMethod TKS.EditorTools.DataImporter.CaptureC -cDir <dir>
/// 훈련 · 순찰 · 개발 · 보물 보유/세트/상자 · 탑 · 던전 · 투기장 · 도감 PNG 10장 + log · 끝나면 스스로 종료.
///
public static void CaptureC()
{
string dir = GetArg("-cDir");
if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Directory.GetCurrentDirectory(), "Logs", "outgame_c_capture");
ImportAll();
EditorSceneManager.OpenScene(ProjectSetup.ScenePath, OpenSceneMode.Single);
SessionState.SetBool(SaveStore.MemoryFlagKey, true);
SessionState.SetString(OutGameCaptureDriverC.DirKey, dir);
Debug.Log("[TKS] 아웃게임 2차 캡처 시작 → " + dir);
EditorApplication.EnterPlaymode();
}
///
/// UI 리뉴얼 검증 캡처(GUI 에디터 · 사본 프로젝트 권장 · 세이브 = 메모리 전용 · PD #1100):
/// Unity.exe -projectPath <copy> -executeMethod TKS.EditorTools.DataImporter.CaptureUI -uiDir <dir>
/// 화면 10종 + 팝업(1080×1920) + 1536×2048 2장 PNG + log · 끝나면 스스로 종료.
/// -uiOnly hero_list*,hero_detail = 그 화면만 찍고(정확한 이름 또는 「접두*」) 다 찍으면 바로 종료(PD 2026-11-09 「수정된 화면만 체크」 · 이름 = capture_log 의 shot 파일 이름에서 번호 뺀 것).
///
public static void CaptureUI()
{
string dir = GetArg("-uiDir");
if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Directory.GetCurrentDirectory(), "Logs", "ui_capture");
ImportAll();
UIThemeImporter.Import();
EditorSceneManager.OpenScene(ProjectSetup.ScenePath, OpenSceneMode.Single);
SessionState.SetBool(SaveStore.MemoryFlagKey, true);
SessionState.SetString(UICaptureDriver.DirKey, dir);
SessionState.SetString(UICaptureDriver.OnlyKey, GetArg("-uiOnly") ?? "");
Debug.Log("[TKS] UI 캡처 시작 → " + dir);
EditorApplication.EnterPlaymode();
}
static string GetArg(string name)
{
var args = System.Environment.GetCommandLineArgs();
for (int i = 0; i < args.Length - 1; i++)
if (args[i] == name) return args[i + 1];
return null;
}
}
}