Files
Rhyculator/Assets/Script/SongInfo.cs
T
2026-10-24 11:55:22 +08:00

88 lines
3.5 KiB
C#

using System;
using System.IO;
using System.Text.RegularExpressions;
// 一個已匯入曲包的資訊(來自 config.json 與資料夾內的檔案)
// 曲包格式見 RhyculatorMaker 的 README
public class SongInfo
{
public const int LevelCount = 3;
public static readonly string[] LevelNames = { "easy", "normal", "hard" }; // level 1..3
public static readonly string[] MusicNames = { "music.ogg", "music.wav", "music.mp3" };
public const string ConfigName = "config.json";
public const string ImageName = "image.png";
public const string VideoName = "video.mp4";
private static readonly Regex IdPattern = new Regex("^[a-z0-9][a-z0-9-]{1,63}$");
public string id;
public string name;
public string artist;
public string charter;
public double bpm;
public int beatOffsetMs;
public int offsetMs; // 判定時間微調:正值 = 所有音符的判定點往後移
public int previewStartMs;
public int previewLengthMs;
public readonly int[] levelNum = new int[LevelCount + 1]; // [1..3] 難度數字,0 = 未填
public string dir;
public static string LevelName(int level) => level >= 1 && level <= LevelCount ? LevelNames[level - 1] : "normal";
public static bool IsValidId(string id) => id != null && IdPattern.IsMatch(id);
public bool HasLevel(int level) => level >= 1 && level <= LevelCount && File.Exists(ChartPath(level));
public string ChartPath(int level) => Path.Combine(dir, LevelName(level) + ".json");
public string ImagePath => Path.Combine(dir, ImageName);
public string VideoPath
{
get { string p = Path.Combine(dir, VideoName); return File.Exists(p) ? p : null; }
}
public string MusicPath
{
get
{
foreach (var n in MusicNames)
{
string p = Path.Combine(dir, n);
if (File.Exists(p)) return p;
}
return null;
}
}
// 第一個有譜面的難度,沒有則 0
public int FirstLevel()
{
for (int l = 1; l <= LevelCount; l++) if (HasLevel(l)) return l;
return 0;
}
// 解析 config.json;缺必要欄位時丟 FormatException
public static SongInfo FromConfig(string configJson, string dir)
{
var cfg = MiniJson.AsObject(MiniJson.Parse(configJson));
if (cfg == null) throw new FormatException("config.json 不是 JSON 物件");
var s = new SongInfo { dir = dir };
s.id = MiniJson.GetString(cfg, "id", "").Trim();
if (!IsValidId(s.id)) throw new FormatException("config.json 的 id 無效(只能用小寫英數字與 -)");
s.name = MiniJson.GetString(cfg, "name", "").Trim();
if (s.name == "") throw new FormatException("config.json 缺少 name");
s.artist = MiniJson.GetString(cfg, "artist", "");
s.charter = MiniJson.GetString(cfg, "charter", "");
s.bpm = MiniJson.GetNumber(cfg, "bpm", 0);
s.beatOffsetMs = MiniJson.GetInt(cfg, "beat_offset", 0);
s.offsetMs = MiniJson.GetInt(cfg, "offset", 0);
s.previewStartMs = MiniJson.GetInt(cfg, "preview_start", 0);
s.previewLengthMs = MiniJson.GetInt(cfg, "preview_length", 15000);
for (int l = 1; l <= LevelCount; l++)
s.levelNum[l] = MiniJson.GetInt(cfg, LevelNames[l - 1] + "_num", 0);
return s;
}
public static SongInfo FromDir(string dir)
=> FromConfig(File.ReadAllText(Path.Combine(dir, ConfigName)), dir);
}