Compare commits

..

9 Commits

Author SHA1 Message Date
Kei-Luna
e5ecdc7f2a Rename the log file 2026-05-15 14:47:41 +09:00
Kei-Luna
30c52b6aa8 account delete command 2026-05-15 14:12:40 +09:00
Kei-Luna
3ffb7ebf29 Small fix(login system) 2026-05-15 14:05:58 +09:00
Kei-Luna
400db16f39 Character level-up implemented. 2026-05-15 10:14:35 +09:00
Kei-Luna
42b1ad1024 Changed the location where client save data is stored to the MikuSB directory. 2026-05-15 09:19:00 +09:00
Naruse
5aa5ef92d0 Update version.txt 2026-05-13 19:59:33 +08:00
Naruse
c34ad5eb1e unlock more furniture 2026-05-13 19:58:53 +08:00
Naruse
8a597e24b6 add system change furniture 2026-05-13 19:42:10 +08:00
Naruse
9763f1f8d9 auto create account if not exist 2026-05-13 19:08:02 +08:00
13 changed files with 504 additions and 28 deletions

View File

@@ -0,0 +1,18 @@
namespace MikuSB.Data.Excel;
[ResourceEntity("house/FurniturePos.json")]
public class HouseFurniturePosExcel : ExcelResource
{
public uint AreaId { get; set; }
public uint GroupId { get; set; }
public override uint GetId()
{
return (AreaId << 48) | (GroupId << 32);
}
public override void Loaded()
{
GameData.HouseFurniturePosData.TryAdd(GetId(), this);
}
}

View File

@@ -31,6 +31,7 @@ public static class GameData
public static Dictionary<uint, WeaponPartsExcel> WeaponPartsData { get; private set; } = [];
public static Dictionary<uint, GuideExcel> GuideData { get; private set; } = [];
public static Dictionary<uint, DormGiftExcel> DormGiftData { get; private set; } = [];
public static Dictionary<uint, HouseFurniturePosExcel> HouseFurniturePosData { get; private set; } = [];
}
public static class GameResourceTemplateId

View File

@@ -222,9 +222,16 @@ public class HelpTextCHS
public class AccountTextCHS
{
public string Desc => "管理 SDK 登录使用的账号映射";
public string Usage => "用法: /account create <邮箱> <UID>";
public string Usage =>
"用法: /account create <邮箱> <UID>\n" +
"用法: /account delete <邮箱|UID>\n" +
"用法: /account list";
public string Created => "已创建账号映射: {0} -> UID {1}";
public string CreateFailed => "创建账号映射失败: {0}";
public string Deleted => "已删除账号映射: {0} -> UID {1}";
public string DeleteFailed => "删除账号映射失败: {0}";
public string DeleteOnline => "账号在线时无法删除: {0} -> UID {1}";
public string NotFound => "未找到账号: {0}";
}
/// <summary>

View File

@@ -222,9 +222,16 @@ public class HelpTextCHT
public class AccountTextCHT
{
public string Desc => "管理 SDK 登入使用的帳號映射";
public string Usage => "用法: /account create <郵箱> <UID>";
public string Usage =>
"用法: /account create <郵箱> <UID>\n" +
"用法: /account delete <郵箱|UID>\n" +
"用法: /account list";
public string Created => "已建立帳號映射: {0} -> UID {1}";
public string CreateFailed => "建立帳號映射失敗: {0}";
public string Deleted => "已刪除帳號映射: {0} -> UID {1}";
public string DeleteFailed => "刪除帳號映射失敗: {0}";
public string DeleteOnline => "帳號在線時無法刪除: {0} -> UID {1}";
public string NotFound => "未找到帳號: {0}";
}
/// <summary>

View File

@@ -188,9 +188,16 @@ public class HelpTextEN
public class AccountTextEN
{
public string Desc => "Manage account mappings for SDK logins";
public string Usage => "Usage: /account create <email> <uid>";
public string Usage =>
"Usage: /account create <email> <uid>\n" +
"Usage: /account delete <email|uid>\n" +
"Usage: /account list";
public string Created => "Created account mapping: {0} -> UID {1}";
public string CreateFailed => "Failed to create account mapping: {0}";
public string Deleted => "Deleted account mapping: {0} -> UID {1}";
public string DeleteFailed => "Failed to delete account mapping: {0}";
public string DeleteOnline => "Cannot delete account while online: {0} -> UID {1}";
public string NotFound => "Account not found: {0}";
}
/// <summary>

View File

@@ -19,6 +19,11 @@ public static class ConfigManager
//LoadHotfixData();
}
public static void SaveConfig()
{
SaveData(Config, ConfigFilePath);
}
private static void LoadConfigData()
{
var file = new FileInfo(ConfigFilePath);
@@ -43,9 +48,26 @@ public static class ConfigManager
Config = JsonConvert.DeserializeObject<ConfigContainer>(json)!;
}
Config.Loader.Arguments = NormalizeLoaderArguments(Config.Loader.Arguments);
SaveData(Config, ConfigFilePath);
}
private static string[] NormalizeLoaderArguments(string[]? arguments)
{
var result = new List<string>(arguments ?? []);
var userDataDirectory = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "Client_User_Data"));
Directory.CreateDirectory(userDataDirectory);
var userDirArgument = $"-userdir={userDataDirectory}";
var existingIndex = result.FindIndex(x => x.StartsWith("-userdir=", StringComparison.OrdinalIgnoreCase));
if (existingIndex >= 0)
result[existingIndex] = userDirArgument;
else
result.Add(userDirArgument);
return result.ToArray();
}
private static void LoadHotfixData()
{
var file = new FileInfo(HotfixFilePath);

View File

@@ -2,6 +2,7 @@ using MikuSB.Database;
using MikuSB.Database.Account;
using MikuSB.Enums.Player;
using MikuSB.Internationalization;
using MikuSB.GameServer.Server;
using System.Text;
namespace MikuSB.GameServer.Command.Commands;
@@ -37,6 +38,42 @@ public class CommandAccount : ICommands
}
}
[CommandMethod("delete")]
public async ValueTask Delete(CommandArg arg)
{
if (!await arg.CheckArgCnt(1))
return;
var identifier = arg.Args[0].Trim();
var account = int.TryParse(identifier, out var uid) && uid > 0
? AccountData.GetAccountByUid(uid)
: AccountData.GetAccountByUserName(identifier);
if (account == null)
{
await arg.SendMsg(I18NManager.Translate("Game.Command.Account.NotFound", identifier));
return;
}
try
{
if (Listener.GetActiveConnection(account.Uid) != null)
{
await arg.SendMsg(I18NManager.Translate("Game.Command.Account.DeleteOnline", account.Username,
account.Uid.ToString()));
return;
}
AccountData.DeleteAccount(account.Uid);
await arg.SendMsg(I18NManager.Translate("Game.Command.Account.Deleted", account.Username,
account.Uid.ToString()));
}
catch (Exception ex)
{
await arg.SendMsg(I18NManager.Translate("Game.Command.Account.DeleteFailed", ex.Message));
}
}
[CommandMethod("list")]
public async ValueTask List(CommandArg arg)
{

View File

@@ -327,20 +327,49 @@ public class PlayerInstance(PlayerGameData data)
private static IEnumerable<(uint Gid, uint Sid, uint Value)> BuildGirlFurnitureAttrs()
{
// Unlock some furniture slots for every girl
// Each furniture attr int stores 10 slots using 3 bits per slot
// Value below means slot 0..9 = 1
const uint furnitureUnlockedValue = 153391689;
var groupFurnitureByArea = new Dictionary<uint, uint>();
foreach (var pos in GameData.HouseFurniturePosData.Values)
{
var areaId = pos.AreaId;
var groupId = pos.GroupId;
uint selectedIndex = 1;
var shift = (groupId - 1) * 3;
if (!groupFurnitureByArea.TryGetValue(areaId, out var packed)) packed = 0;
packed |= (selectedIndex << (int)shift);
groupFurnitureByArea[areaId] = packed;
}
for (uint girlId = 0; girlId <= 50; girlId++)
{
// FurnitureStart..FurnitureEnd = 10..19
var baseSid = girlId * 50;
for (uint offset = 10; offset <= 19; offset++)
{
uint sid = (girlId * 50) + offset;
yield return (101, sid, furnitureUnlockedValue);
}
yield return (101, baseSid + offset, furnitureUnlockedValue);
if (groupFurnitureByArea.TryGetValue(girlId, out var groupValue))
yield return (101, baseSid + 20, groupValue);
}
// Massage room furniture
// 10010..10019
for (uint sid = 10010; sid <= 10019; sid++)
yield return (101, sid, furnitureUnlockedValue);
// Massage room group state
yield return (101, 10020, 1);
// Hot spring furniture
// 15001..15010
for (uint sid = 15001; sid <= 15010; sid++)
yield return (101, sid, furnitureUnlockedValue);
// Beach furniture
// 17101..17110
for (uint sid = 17101; sid <= 17110; sid++)
yield return (101, sid, furnitureUnlockedValue);
for (uint sid = 30000; sid < 31000; sid++)
yield return (101, sid, furnitureUnlockedValue);
}
private static IEnumerable<(uint Gid, uint Sid, uint Value)> BuildLobbyBootstrapAttrs()

View File

@@ -0,0 +1,296 @@
using MikuSB.Data;
using MikuSB.Database;
using MikuSB.Database.Inventory;
using MikuSB.Database.Player;
using MikuSB.Enums.Item;
using MikuSB.Proto;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MikuSB.GameServer.Server.CallGS.Handlers.Girl;
[CallGSApi("GirlCard_UpdateLevel")]
public class GirlCard_UpdateLevel : ICallGSHandler
{
private const uint CashGroupId = 1;
private const uint SilverMoneyType = 3;
private const uint SilverSid = SilverMoneyType * 2 + 1;
private const uint RoleMaxLevel = 80;
public async Task Handle(Connection connection, string param, ushort seqNo)
{
var player = connection.Player!;
var req = JsonSerializer.Deserialize<GirlCardUpdateLevelParam>(param);
if (req == null || req.Id == 0 || req.Materials == null || req.Materials.Count == 0)
{
await CallGSRouter.SendScript(connection, "GirlCard_UpdateLevel", "{\"sErr\":\"error.BadParam\"}");
return;
}
var card = player.CharacterManager.GetCharacterByGUID((uint)req.Id);
if (card == null)
{
await CallGSRouter.SendScript(connection, "GirlCard_UpdateLevel", "{\"sErr\":\"error.BadParam\"}");
return;
}
var cardTemplate = GameData.CardData.Values.FirstOrDefault(x =>
GameResourceTemplateId.FromGdpl(x.Genre, x.Detail, x.Particular, x.Level) == card.TemplateId);
if (cardTemplate == null)
{
await CallGSRouter.SendScript(connection, "GirlCard_UpdateLevel", "{\"sErr\":\"error.BadParam\"}");
return;
}
var levelCap = GetCardLevelCap(player.Data.Level, cardTemplate.LevelLimitID);
if (levelCap == 0)
{
levelCap = card.Level;
}
if (card.Level >= RoleMaxLevel)
{
await CallGSRouter.SendScript(connection, "GirlCard_UpdateLevel", "{\"sErr\":\"tip.card_max_level\"}");
return;
}
var requestedMaterials = new Dictionary<uint, uint>();
foreach (var row in req.Materials)
{
if (row == null || row.Id == 0 || row.Num == 0)
continue;
requestedMaterials[(uint)row.Id] = requestedMaterials.GetValueOrDefault((uint)row.Id) + row.Num;
}
if (requestedMaterials.Count == 0)
{
await CallGSRouter.SendScript(connection, "GirlCard_UpdateLevel", "{\"sErr\":\"tip.material_not_enough\"}");
return;
}
ulong totalExp = 0;
ulong totalSilverCost = 0;
foreach (var (itemId, count) in requestedMaterials)
{
var item = player.InventoryManager.GetNormalItem(itemId);
if (item == null || item.ItemCount < count)
{
await CallGSRouter.SendScript(connection, "GirlCard_UpdateLevel", "{\"sErr\":\"tip.material_not_enough\"}");
return;
}
if (!GameData.SuppliesData.TryGetValue((uint)item.TemplateId, out var supplies) || supplies.ProvideExp == 0)
{
await CallGSRouter.SendScript(connection, "GirlCard_UpdateLevel", "{\"sErr\":\"error.BadParam\"}");
return;
}
totalExp += (ulong)supplies.ProvideExp * count;
totalSilverCost += (ulong)supplies.ConsumeGold * count;
}
var silverAttr = GetOrCreateAttr(player.Data, CashGroupId, SilverSid);
if ((ulong)silverAttr.Val < totalSilverCost)
{
await CallGSRouter.SendScript(connection, "GirlCard_UpdateLevel", "{\"sErr\":\"tip.material_not_enough\"}");
return;
}
var syncItems = new List<Item>();
foreach (var (itemId, count) in requestedMaterials)
{
var item = player.InventoryManager.GetNormalItem(itemId)!;
item.ItemCount -= count;
if (item.ItemCount == 0)
{
player.InventoryManager.InventoryData.Items.Remove(item.UniqueId);
syncItems.Add(BuildRemovedProto(item));
}
else
{
syncItems.Add(item.ToProto());
}
}
silverAttr.Val -= checked((uint)totalSilverCost);
var (newLevel, newExp) = ApplyCardExp(card.Level, card.Exp, totalExp, levelCap);
card.Level = newLevel;
card.Exp = checked((int)newExp);
syncItems.Add(card.ToProto());
DatabaseHelper.SaveDatabaseType(player.InventoryManager.InventoryData);
DatabaseHelper.SaveDatabaseType(player.CharacterManager.CharacterData);
DatabaseHelper.SaveDatabaseType(player.Data);
var sync = new NtfSyncPlayer();
sync.Items.AddRange(syncItems);
sync.Custom[player.ToPackedAttrKey(CashGroupId, SilverSid)] = silverAttr.Val;
sync.Custom[player.ToShiftedAttrKey(CashGroupId, SilverSid)] = silverAttr.Val;
await CallGSRouter.SendScript(connection, "GirlCard_UpdateLevel", "null", sync);
}
private static PlayerAttr GetOrCreateAttr(PlayerGameData data, uint gid, uint sid)
{
var attr = data.Attrs.FirstOrDefault(x => x.Gid == gid && x.Sid == sid);
if (attr != null)
return attr;
attr = new PlayerAttr
{
Gid = gid,
Sid = sid,
Val = 0
};
data.Attrs.Add(attr);
return attr;
}
private static Item BuildRemovedProto(BaseGameItemInfo item)
{
var proto = item.ToProto();
proto.Count = 0;
return proto;
}
private static uint GetCardLevelCap(uint playerLevel, int levelLimitId)
{
var limits = LoadCardLevelLimit(levelLimitId);
if (limits.Count == 0)
return 0;
uint nearestAccountLevel = 0;
uint nearestCardLevel = 0;
foreach (var (accountLevel, cardLevel) in limits)
{
if (accountLevel < playerLevel)
{
nearestAccountLevel = accountLevel;
nearestCardLevel = cardLevel;
continue;
}
if (accountLevel == playerLevel)
return Math.Min(cardLevel, RoleMaxLevel);
var distance = accountLevel - nearestAccountLevel;
if (distance == 0)
return Math.Min(cardLevel, RoleMaxLevel);
var percent = (playerLevel - nearestAccountLevel) / (double)distance;
var interpolated = (uint)Math.Floor(nearestCardLevel + ((cardLevel - nearestCardLevel) * percent));
return Math.Min(interpolated, RoleMaxLevel);
}
return Math.Min(nearestCardLevel, RoleMaxLevel);
}
private static List<(uint AccountLevel, uint CardLevel)> LoadCardLevelLimit(int levelLimitId)
{
var path = Path.Combine(
AppContext.BaseDirectory,
"Resources",
"item",
"level_limit.json");
if (!File.Exists(path))
return [];
using var doc = JsonDocument.Parse(File.ReadAllText(path));
var result = new List<(uint AccountLevel, uint CardLevel)>();
foreach (var row in doc.RootElement.EnumerateArray())
{
if (!row.TryGetProperty("ID", out var idProp) || idProp.GetInt32() != levelLimitId)
continue;
if (!row.TryGetProperty("Type", out var typeProp) || typeProp.GetInt32() != 1)
continue;
if (!row.TryGetProperty("Limit", out var limitProp) || limitProp.ValueKind != JsonValueKind.Object)
continue;
foreach (var property in limitProp.EnumerateObject())
{
if (!uint.TryParse(property.Name, out var accountLevel))
continue;
uint cardLevel;
if (property.Value.ValueKind == JsonValueKind.Number)
{
cardLevel = property.Value.GetUInt32();
}
else if (property.Value.ValueKind == JsonValueKind.String &&
uint.TryParse(property.Value.GetString(), out var parsed))
{
cardLevel = parsed;
}
else
{
continue;
}
result.Add((accountLevel, cardLevel));
}
break;
}
result.Sort((a, b) => a.AccountLevel.CompareTo(b.AccountLevel));
return result;
}
private static (uint Level, ulong Exp) ApplyCardExp(uint level, int currentExp, ulong addedExp, uint levelCap)
{
var destLevel = level == 0 ? 1u : level;
var destExp = (ulong)Math.Max(0, currentExp) + addedExp;
if (levelCap > 0 && destLevel >= levelCap)
return (destLevel, destExp);
while (destLevel < RoleMaxLevel)
{
var needExp = GetCardNeedExp(destLevel);
if (needExp == 0 || destExp < needExp)
break;
destExp -= needExp;
destLevel++;
if (levelCap > 0 && destLevel >= levelCap)
return (levelCap, destExp);
}
return (destLevel, destExp);
}
private static uint GetCardNeedExp(uint currentLevel)
{
if (GameData.UpgradeExpData.TryGetValue((int)currentLevel, out var row))
return row.CardNeedExp;
return 0;
}
}
internal sealed class GirlCardUpdateLevelParam
{
[JsonPropertyName("Id")]
public int Id { get; set; }
[JsonPropertyName("tbMaterials")]
public List<GirlCardLevelMaterial> Materials { get; set; } = [];
}
internal sealed class GirlCardLevelMaterial
{
[JsonPropertyName("Id")]
public int Id { get; set; }
[JsonPropertyName("Num")]
public uint Num { get; set; }
}

View File

@@ -293,11 +293,14 @@ public sealed class LaunchOptions
public static LaunchOptions FromConfig(IEnumerable<string>? extraGameArguments = null)
{
var config = ConfigManager.Config;
var serverBaseDirectory = AppContext.BaseDirectory;
var gamePath = ResolvePath(config.Loader.GamePath, AppContext.BaseDirectory);
var patchPaths = ResolvePatchPaths(config.Loader.PatchPaths, AppContext.BaseDirectory);
var patchPaths = ResolvePatchPaths(config.Loader.PatchPaths, serverBaseDirectory);
var gameArgs = new List<string>(config.Loader.Arguments ?? []);
if (extraGameArguments is not null)
gameArgs.AddRange(extraGameArguments.Where(x => !string.IsNullOrWhiteSpace(x)));
gameArgs = EnsureUserDirArgument(gameArgs, serverBaseDirectory);
PersistResolvedArgumentsIfChanged(config, gameArgs);
var env = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (config.Loader.SetAllProxy && config.Proxy.Enabled)
@@ -330,6 +333,31 @@ public sealed class LaunchOptions
};
}
private static List<string> EnsureUserDirArgument(List<string> gameArgs, string baseDirectory)
{
var userDataDirectory = Path.GetFullPath(Path.Combine(baseDirectory, "Client_User_Data"));
Directory.CreateDirectory(userDataDirectory);
var userDirArgument = $"-userdir={userDataDirectory}";
var existingIndex = gameArgs.FindIndex(x => x.StartsWith("-userdir=", StringComparison.OrdinalIgnoreCase));
if (existingIndex >= 0)
gameArgs[existingIndex] = userDirArgument;
else
gameArgs.Add(userDirArgument);
return gameArgs;
}
private static void PersistResolvedArgumentsIfChanged(Configuration.ConfigContainer config, List<string> gameArgs)
{
var currentArgs = config.Loader.Arguments ?? [];
if (currentArgs.SequenceEqual(gameArgs, StringComparer.Ordinal))
return;
config.Loader.Arguments = gameArgs.ToArray();
ConfigManager.SaveConfig();
}
private static string? ResolvePath(string? value, string baseDirectory)
{
if (string.IsNullOrWhiteSpace(value))

View File

@@ -22,16 +22,35 @@ public class LoaderManager : MikuSB
public static void InitConfig()
{
// Initialize log
var counter = 0;
FileInfo file;
while (true)
var logDir = ConfigManager.Config.Path.LogPath;
var logFile = new FileInfo(Path.Combine(logDir, "Server.log"));
logFile.Directory?.Create();
if (logFile.Exists)
{
file = new FileInfo(ConfigManager.Config.Path.LogPath + $"/{DateTime.Now:yyyy-MM-dd}-{++counter}.log");
if (file is not { Exists: false, Directory: not null }) continue;
file.Directory.Create();
break;
// Read start time from first log line, fall back to file creation time
DateTime logStartTime;
try
{
var firstLine = File.ReadLines(logFile.FullName).FirstOrDefault() ?? "";
// Format: [HH:mm:ss] ...
var timeStr = firstLine.Length >= 10 ? firstLine[1..9] : "";
var dateStr = logFile.CreationTime.ToString("yyyy-MM-dd");
logStartTime = DateTime.TryParse($"{dateStr} {timeStr}", out var parsed)
? parsed
: logFile.CreationTime;
}
catch
{
logStartTime = logFile.CreationTime;
}
var backupName = $"Server-backup-{logStartTime:yyyy.MM.dd-HH.mm.ss}.log";
var backupFile = new FileInfo(Path.Combine(logDir, backupName));
logFile.MoveTo(backupFile.FullName, overwrite: true);
}
Logger.SetLogFile(file);
Logger.SetLogFile(new FileInfo(Path.Combine(logDir, "Server.log")));
// Init all directories
try

View File

@@ -270,12 +270,17 @@ public class RouteController : ControllerBase
var finalEmail = email ?? form_email ?? await GetJsonBodyValue("email");
if (!string.IsNullOrWhiteSpace(finalEmail))
{
var accountByEmail = AccountData.GetAccountByEmail(finalEmail);
if (accountByEmail == null)
return BuildLoginFailedResponse("Account not found.");
var normalizedEmail = finalEmail.Trim();
var accountData = AccountData.GetAccountByEmail(normalizedEmail);
if (accountData == null)
{
if (!ConfigManager.Config.ServerOption.AutoCreateUser) return BuildLoginFailedResponse("Account not found.");
AccountData.CreateAccount(normalizedEmail, 0, "123456");
accountData = AccountData.GetAccountByEmail(normalizedEmail)!;
}
var finalUidValue = accountByEmail.Uid.ToString();
var finalTokenValue = accountByEmail.GenerateComboToken();
var finalUidValue = accountData.Uid.ToString();
var finalTokenValue = accountData.GenerateComboToken();
object emailLoginRsp = new
{
@@ -286,14 +291,14 @@ public class RouteController : ControllerBase
isFirstLogin = false,
isNeedKoreaSciAuth = false,
ksOpenId = $"ks_{finalUidValue}",
nickname = accountByEmail.Username,
nickname = accountData.Username,
passportId = finalUidValue,
playerFillAgeUrl = "",
status = 0,
thirdPartyUid = "",
token = finalTokenValue,
type = "guest",
uid = accountByEmail.Uid
uid = accountData.Uid
},
msg = "操作成功"
};

View File

@@ -1 +1 @@
v=2.8
v=3.0