using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class SkillAssetImportSummary { public int SkillInfoCount { get; init; } public int SkillCodeCount { get; init; } public int SkillCodeApplyCount { get; init; } public int TamerSkillCount { get; init; } public int AreaCheckCount { get; init; } public int InvalidInvokeRateCount { get; init; } public int IgnoredMemorySkillCount { get; init; } public int DeletedSkillInfoCount { get; init; } public int DeletedSkillCodeCount { get; init; } public int DeletedSkillCodeApplyCount { get; init; } public int DeletedTamerSkillCount { get; init; } public int InsertedSkillInfoCount => SkillInfoCount; public int InsertedSkillCodeCount => SkillCodeCount; public int InsertedSkillCodeApplyCount => SkillCodeApplyCount; public int InsertedTamerSkillCount => TamerSkillCount; } public static class SkillAssetImporter { private const int FixedTamerSkillDurationSeconds = 30; public static SkillAssetImportSummary ValidateXml( string skillXmlPath, string tamerSkillXmlPath, string areaCheckXmlPath) { SkillImportPackage package = LoadPackage(skillXmlPath, tamerSkillXmlPath, areaCheckXmlPath); return new SkillAssetImportSummary { SkillInfoCount = package.SkillInfo.Count, SkillCodeCount = package.SkillCodes.Count, SkillCodeApplyCount = package.SkillCodeApplies.Count, TamerSkillCount = package.TamerSkills.Count, AreaCheckCount = package.AreaCheckCount, InvalidInvokeRateCount = package.InvalidInvokeRateCount, IgnoredMemorySkillCount = package.IgnoredMemorySkillCount }; } public static SkillAssetImportSummary ImportReplace( string connectionString, string skillXmlPath, string tamerSkillXmlPath, string areaCheckXmlPath) { SkillImportPackage package = LoadPackage(skillXmlPath, tamerSkillXmlPath, areaCheckXmlPath); if (package.SkillInfo.Count == 0) { throw new InvalidOperationException("Skill.xml does not contain any SkillData rows."); } using SqlConnection connection = new(connectionString); connection.Open(); using SqlTransaction transaction = connection.BeginTransaction(); try { int deletedSkillCodeApplyCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[SkillCodeApply];"); int deletedSkillCodeCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[SkillCode];"); int deletedSkillInfoCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[SkillInfo];"); int deletedTamerSkillCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[TamerSkill];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[SkillCodeApply];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[SkillCode];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[TamerSkill];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[SkillInfo];"); InsertSkillInfo(connection, transaction, package.SkillInfo); InsertSkillCode(connection, transaction, package.SkillCodes); InsertSkillCodeApply(connection, transaction, package.SkillCodeApplies); InsertTamerSkill(connection, transaction, package.TamerSkills); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[SkillInfo]', RESEED, {package.SkillInfo.Count});"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[SkillCode]', RESEED, {package.SkillCodes.Count});"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[SkillCodeApply]', RESEED, {package.SkillCodeApplies.Count});"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[TamerSkill]', RESEED, {package.TamerSkills.Count});"); transaction.Commit(); return new SkillAssetImportSummary { SkillInfoCount = package.SkillInfo.Count, SkillCodeCount = package.SkillCodes.Count, SkillCodeApplyCount = package.SkillCodeApplies.Count, TamerSkillCount = package.TamerSkills.Count, AreaCheckCount = package.AreaCheckCount, InvalidInvokeRateCount = package.InvalidInvokeRateCount, IgnoredMemorySkillCount = package.IgnoredMemorySkillCount, DeletedSkillInfoCount = deletedSkillInfoCount, DeletedSkillCodeCount = deletedSkillCodeCount, DeletedSkillCodeApplyCount = deletedSkillCodeApplyCount, DeletedTamerSkillCount = deletedTamerSkillCount }; } catch { TryDisableIdentityInsert(connection, transaction, "[Asset].[SkillInfo]"); TryDisableIdentityInsert(connection, transaction, "[Asset].[SkillCode]"); TryDisableIdentityInsert(connection, transaction, "[Asset].[SkillCodeApply]"); TryDisableIdentityInsert(connection, transaction, "[Asset].[TamerSkill]"); transaction.Rollback(); throw; } } private static SkillImportPackage LoadPackage(string skillXmlPath, string tamerSkillXmlPath, string areaCheckXmlPath) { List skillInfo = new(); List skillCodes = new(); List skillCodeApplies = new(); int invalidInvokeRateCount = 0; int ignoredMemorySkillCount = 0; XDocument skillDocument = LoadDocument(skillXmlPath, "Skill.xml"); XElement skillRoot = RequireRoot(skillDocument, "SkillDataArray", "Skill.xml"); int skillInfoId = 1; int skillCodeId = 1; int skillCodeApplyId = 1; foreach (XElement skillElement in skillRoot.Elements("SkillData")) { string context = BuildSkillContext(skillElement, skillInfoId); List applyElements = skillElement.Element("SkillApply")?.Elements("IncreaseApply").ToList() ?? new List(); if (applyElements.Count != 3) { throw new InvalidOperationException($"{context} must contain exactly 3 IncreaseApply rows."); } int memorySkill = ReadRequiredInt(skillElement, "s_nMemorySkill", context); if (memorySkill != 0) { ignoredMemorySkillCount++; } SkillCodeRecord skillCode = new() { Id = skillCodeId, SkillCode = ReadRequiredInt(skillElement, "s_dwID", context), Comment = ReadOptionalString(skillElement, "s_szComment", 500) }; skillCodes.Add(skillCode); int[] conditionValues = new int[3]; for (int index = 0; index < applyElements.Count; index++) { XElement applyElement = applyElements[index]; string applyContext = $"{context} IncreaseApply #{index + 1}"; int rawInvokeRate = ReadRequiredInt(applyElement, "s_nInvoke_Rate", applyContext); bool invokeRateIsValid = rawInvokeRate >= 0 && rawInvokeRate <= 10000; if (!invokeRateIsValid) { invalidInvokeRateCount++; } int value = ReadRequiredInt(applyElement, "s_nB", applyContext); conditionValues[index] = value; skillCodeApplies.Add(new SkillCodeApplyRecord { Id = skillCodeApplyId++, SkillCodeAssetId = skillCode.Id, Type = ReadRequiredInt(applyElement, "s_nID", applyContext), Attribute = ReadRequiredInt(applyElement, "s_nA", applyContext), Value = value, Chance = invokeRateIsValid ? (int)Math.Round(rawInvokeRate / 100.0d, MidpointRounding.AwayFromZero) : 0, AdditionalValue = ReadRequiredInt(applyElement, "s_nC", applyContext), IncreaseValue = ReadRequiredInt(applyElement, "s_nIncrease_B_Point", applyContext) }); } skillInfo.Add(new SkillInfoRecord { Id = skillInfoId++, SkillId = skillCode.SkillCode, Name = ReadOptionalString(skillElement, "s_szName", 50), DSUsage = ReadRequiredInt(skillElement, "s_nUseDS", context), HPUsage = ReadRequiredInt(skillElement, "s_nUseHP", context), Value = 0, CastingTime = ReadRequiredDecimal(skillElement, "s_fCastingTime", context), Cooldown = RoundRequiredFloatToInt(skillElement, "s_fCooldownTime", context), MaxLevel = ReadRequiredTinyInt(skillElement, "s_nMaxLevel", context), RequiredPoints = ReadRequiredTinyInt(skillElement, "s_nLevelupPoint", context), Target = ReadRequiredTinyInt(skillElement, "s_nTarget", context), AreaOfEffect = ReadRequiredInt(skillElement, "s_nAttSphere", context), AoEMinDamage = RoundRequiredFloatToInt(skillElement, "s_fAttRange_MinDmg", context), AoEMaxDamage = RoundRequiredFloatToInt(skillElement, "s_fAttRange_MaxDmg", context), Range = RoundRequiredFloatToInt(skillElement, "s_fAttRange", context), UnlockLevel = ReadRequiredTinyInt(skillElement, "s_nLimitLevel", context), MemoryChips = 0, FirstConditionCode = conditionValues[0], SecondConditionCode = conditionValues[1], ThirdConditionCode = conditionValues[2], Type = ReadRequiredInt(skillElement, "s_nAttType", context), Description = ReadOptionalString(skillElement, "s_szComment", 500), FamilyType = ReadRequiredTinyInt(skillElement, "s_nFamilyType", context), SkillType = ReadRequiredInt(skillElement, "s_nSkillType", context) }); skillCodeId++; } List tamerSkills = LoadTamerSkills(tamerSkillXmlPath); int areaCheckCount = LoadAreaCheckCount(areaCheckXmlPath); return new SkillImportPackage { SkillInfo = skillInfo, SkillCodes = skillCodes, SkillCodeApplies = skillCodeApplies, TamerSkills = tamerSkills, AreaCheckCount = areaCheckCount, InvalidInvokeRateCount = invalidInvokeRateCount, IgnoredMemorySkillCount = ignoredMemorySkillCount }; } private static List LoadTamerSkills(string tamerSkillXmlPath) { XDocument document = LoadDocument(tamerSkillXmlPath, "TamerSkill.xml"); XElement root = RequireRoot(document, "TamerSkillArray", "TamerSkill.xml"); List records = new(); int identity = 1; foreach (XElement element in root.Elements("TamerSkill")) { string context = $"TamerSkill row {identity}"; records.Add(new TamerSkillRecord { Id = identity++, SkillId = ReadRequiredInt(element, "s_nIndex", context), SkillCode = ReadRequiredInt(element, "s_dwSkillCode", context), Duration = FixedTamerSkillDurationSeconds, Type = ReadRequiredInt(element, "s_nType", context), BuffId = ReadRequiredInt(element, "s_dwFactor2", context) }); } return records; } private static int LoadAreaCheckCount(string areaCheckXmlPath) { XDocument document = LoadDocument(areaCheckXmlPath, "AreaCheck.xml"); XElement root = RequireRoot(document, "AreaCheckArray", "AreaCheck.xml"); int count = 0; foreach (XElement element in root.Elements("AreaCheck")) { count++; string context = $"AreaCheck row {count}"; _ = ReadRequiredInt(element, "s_dwIndex", context); int areaCount = element.Element("s_nArea")?.Elements("Area").Count() ?? 0; if (areaCount != 30) { throw new InvalidOperationException($"{context} must contain exactly 30 Area values."); } } return count; } private static void InsertSkillInfo(SqlConnection connection, SqlTransaction transaction, List records) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[SkillInfo] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[SkillInfo] ([Id], [SkillId], [Name], [DSUsage], [HPUsage], [Value], [CastingTime], [Cooldown], [MaxLevel], [RequiredPoints], [Target], [AreaOfEffect], [AoEMinDamage], [AoEMaxDamage], [Range], [UnlockLevel], [MemoryChips], [FirstConditionCode], [SecondConditionCode], [ThirdConditionCode], [Type], [Description], [FamilyType], [SkillType]) VALUES (@Id, @SkillId, @Name, @DSUsage, @HPUsage, @Value, @CastingTime, @Cooldown, @MaxLevel, @RequiredPoints, @Target, @AreaOfEffect, @AoEMinDamage, @AoEMaxDamage, @Range, @UnlockLevel, @MemoryChips, @FirstConditionCode, @SecondConditionCode, @ThirdConditionCode, @Type, @Description, @FamilyType, @SkillType);", connection, transaction); AddParameters(command, "@Id", "@SkillId", "@Name", "@DSUsage", "@HPUsage", "@Value", "@CastingTime", "@Cooldown", "@MaxLevel", "@RequiredPoints", "@Target", "@AreaOfEffect", "@AoEMinDamage", "@AoEMaxDamage", "@Range", "@UnlockLevel", "@MemoryChips", "@FirstConditionCode", "@SecondConditionCode", "@ThirdConditionCode", "@Type", "@Description", "@FamilyType", "@SkillType"); foreach (SkillInfoRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@SkillId"].Value = record.SkillId; command.Parameters["@Name"].Value = record.Name; command.Parameters["@DSUsage"].Value = record.DSUsage; command.Parameters["@HPUsage"].Value = record.HPUsage; command.Parameters["@Value"].Value = record.Value; command.Parameters["@CastingTime"].Value = record.CastingTime; command.Parameters["@Cooldown"].Value = record.Cooldown; command.Parameters["@MaxLevel"].Value = record.MaxLevel; command.Parameters["@RequiredPoints"].Value = record.RequiredPoints; command.Parameters["@Target"].Value = record.Target; command.Parameters["@AreaOfEffect"].Value = record.AreaOfEffect; command.Parameters["@AoEMinDamage"].Value = record.AoEMinDamage; command.Parameters["@AoEMaxDamage"].Value = record.AoEMaxDamage; command.Parameters["@Range"].Value = record.Range; command.Parameters["@UnlockLevel"].Value = record.UnlockLevel; command.Parameters["@MemoryChips"].Value = record.MemoryChips; command.Parameters["@FirstConditionCode"].Value = record.FirstConditionCode; command.Parameters["@SecondConditionCode"].Value = record.SecondConditionCode; command.Parameters["@ThirdConditionCode"].Value = record.ThirdConditionCode; command.Parameters["@Type"].Value = record.Type; command.Parameters["@Description"].Value = record.Description; command.Parameters["@FamilyType"].Value = record.FamilyType; command.Parameters["@SkillType"].Value = record.SkillType; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[SkillInfo] OFF;"); } private static void InsertSkillCode(SqlConnection connection, SqlTransaction transaction, List records) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[SkillCode] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[SkillCode] ([Id], [SkillCode], [Comment]) VALUES (@Id, @SkillCode, @Comment);", connection, transaction); AddParameters(command, "@Id", "@SkillCode", "@Comment"); foreach (SkillCodeRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@SkillCode"].Value = record.SkillCode; command.Parameters["@Comment"].Value = record.Comment; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[SkillCode] OFF;"); } private static void InsertSkillCodeApply(SqlConnection connection, SqlTransaction transaction, List records) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[SkillCodeApply] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[SkillCodeApply] ([Id], [Type], [Attribute], [Value], [AdditionalValue], [SkillCodeAssetId], [IncreaseValue], [Chance]) VALUES (@Id, @Type, @Attribute, @Value, @AdditionalValue, @SkillCodeAssetId, @IncreaseValue, @Chance);", connection, transaction); AddParameters(command, "@Id", "@Type", "@Attribute", "@Value", "@AdditionalValue", "@SkillCodeAssetId", "@IncreaseValue", "@Chance"); foreach (SkillCodeApplyRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@Type"].Value = record.Type; command.Parameters["@Attribute"].Value = record.Attribute; command.Parameters["@Value"].Value = record.Value; command.Parameters["@AdditionalValue"].Value = record.AdditionalValue; command.Parameters["@SkillCodeAssetId"].Value = record.SkillCodeAssetId; command.Parameters["@IncreaseValue"].Value = record.IncreaseValue; command.Parameters["@Chance"].Value = record.Chance; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[SkillCodeApply] OFF;"); } private static void InsertTamerSkill(SqlConnection connection, SqlTransaction transaction, List records) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[TamerSkill] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[TamerSkill] ([Id], [SkillId], [SkillCode], [Duration], [BuffId], [Type]) VALUES (@Id, @SkillId, @SkillCode, @Duration, @BuffId, @Type);", connection, transaction); AddParameters(command, "@Id", "@SkillId", "@SkillCode", "@Duration", "@BuffId", "@Type"); foreach (TamerSkillRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@SkillId"].Value = record.SkillId; command.Parameters["@SkillCode"].Value = record.SkillCode; command.Parameters["@Duration"].Value = record.Duration; command.Parameters["@BuffId"].Value = record.BuffId; command.Parameters["@Type"].Value = record.Type; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[TamerSkill] OFF;"); } private static XDocument LoadDocument(string xmlPath, string fileName) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException($"{fileName} not found.", xmlPath); } return XDocument.Load(xmlPath); } private static XElement RequireRoot(XDocument document, string rootName, string fileName) { XElement? root = document.Root; if (root == null || root.Name.LocalName != rootName) { throw new InvalidOperationException($"{fileName} root node must be <{rootName}>."); } return root; } private static string BuildSkillContext(XElement skillElement, int rowIndex) { string skillId = skillElement.Element("s_dwID")?.Value?.Trim() ?? "?"; string name = skillElement.Element("s_szName")?.Value?.Trim() ?? string.Empty; if (string.IsNullOrWhiteSpace(name)) { return $"Skill row {rowIndex} (SkillId={skillId})"; } return $"Skill row {rowIndex} (SkillId={skillId}, Name={name})"; } private static int ReadRequiredInt(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } if (!int.TryParse(element.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)) { throw new InvalidOperationException($"{recordContext} has invalid integer value in '{elementName}': '{element.Value}'."); } return value; } private static byte ReadRequiredTinyInt(XElement parent, string elementName, string recordContext) { int value = ReadRequiredInt(parent, elementName, recordContext); if (value < byte.MinValue || value > byte.MaxValue) { throw new InvalidOperationException($"{recordContext} has out-of-range tinyint value in '{elementName}': '{value}'."); } return (byte)value; } private static decimal ReadRequiredDecimal(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } if (!decimal.TryParse(element.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal value)) { throw new InvalidOperationException($"{recordContext} has invalid decimal value in '{elementName}': '{element.Value}'."); } return Math.Round(value, 2, MidpointRounding.AwayFromZero); } private static int RoundRequiredFloatToInt(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } if (!decimal.TryParse(element.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal value)) { throw new InvalidOperationException($"{recordContext} has invalid float value in '{elementName}': '{element.Value}'."); } if (value < int.MinValue || value > int.MaxValue) { throw new InvalidOperationException($"{recordContext} has out-of-range int value in '{elementName}': '{element.Value}'."); } return (int)Math.Round(value, 0, MidpointRounding.AwayFromZero); } private static string ReadOptionalString(XElement parent, string elementName, int maxLength) { string value = parent.Element(elementName)?.Value?.Trim() ?? string.Empty; if (value.Length <= maxLength) { return value; } return value.Substring(0, maxLength); } private static int ExecuteScalarInt(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); object? result = command.ExecuteScalar(); return Convert.ToInt32(result, CultureInfo.InvariantCulture); } private static void ExecuteNonQuery(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); command.ExecuteNonQuery(); } private static void AddParameters(SqlCommand command, params string[] names) { foreach (string name in names) { command.Parameters.Add(new SqlParameter(name, DBNull.Value)); } } private static void TryDisableIdentityInsert(SqlConnection connection, SqlTransaction transaction, string tableName) { try { ExecuteNonQuery(connection, transaction, $"SET IDENTITY_INSERT {tableName} OFF;"); } catch { // Best-effort cleanup before rollback. } } private sealed class SkillImportPackage { public List SkillInfo { get; init; } = new(); public List SkillCodes { get; init; } = new(); public List SkillCodeApplies { get; init; } = new(); public List TamerSkills { get; init; } = new(); public int AreaCheckCount { get; init; } public int InvalidInvokeRateCount { get; init; } public int IgnoredMemorySkillCount { get; init; } } private sealed class SkillInfoRecord { public int Id { get; init; } public int SkillId { get; init; } public string Name { get; init; } = string.Empty; public int DSUsage { get; init; } public int HPUsage { get; init; } public int Value { get; init; } public decimal CastingTime { get; init; } public int Cooldown { get; init; } public byte MaxLevel { get; init; } public byte RequiredPoints { get; init; } public byte Target { get; init; } public int AreaOfEffect { get; init; } public int AoEMinDamage { get; init; } public int AoEMaxDamage { get; init; } public int Range { get; init; } public byte UnlockLevel { get; init; } public byte MemoryChips { get; init; } public int FirstConditionCode { get; init; } public int SecondConditionCode { get; init; } public int ThirdConditionCode { get; init; } public int Type { get; init; } public string Description { get; init; } = string.Empty; public byte FamilyType { get; init; } public int SkillType { get; init; } } private sealed class SkillCodeRecord { public int Id { get; init; } public int SkillCode { get; init; } public string Comment { get; init; } = string.Empty; } private sealed class SkillCodeApplyRecord { public int Id { get; init; } public int Type { get; init; } public int Attribute { get; init; } public int Value { get; init; } public int Chance { get; init; } public int AdditionalValue { get; init; } public int IncreaseValue { get; init; } public int SkillCodeAssetId { get; init; } } private sealed class TamerSkillRecord { public int Id { get; init; } public int SkillId { get; init; } public int SkillCode { get; init; } public int Duration { get; init; } public int Type { get; init; } public int BuffId { get; init; } } } }