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

81 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
// 譜面展開後的一個事件(slide 的每一格各是一個事件)
public struct ChartEvent
{
public double hitTime; // 判定時間(秒,已含曲包的 offset)
public string type; // tap / hold / slide
public int x, y;
public int holdMs;
}
// 讀取 Maker 統一格式的譜面:
// {"format":1,"divisor":4,"notes":[{"t":1216,"lane":"L","type":"tap","pos":{"x":0,"y":3}}, ...]}
// lane / locked 是製譜用的欄位,遊戲忽略;沒有座標、座標超出格子、型別不認識的音符略過並計入 skipped
public static class ChartLoader
{
public const int Columns = 5;
public const int Rows = 6;
public static List<ChartEvent> LoadFile(string path, int offsetMs, out int skipped)
=> Parse(File.ReadAllText(path), offsetMs, out skipped);
public static List<ChartEvent> Parse(string json, int offsetMs, out int skipped)
{
skipped = 0;
var events = new List<ChartEvent>();
object root = MiniJson.Parse(json);
// 也接受只有 notes 陣列的檔案
var notes = MiniJson.AsList(root) ?? MiniJson.AsList(MiniJson.Get(MiniJson.AsObject(root), "notes"));
if (notes == null) throw new FormatException("譜面缺少 notes 陣列");
double offset = offsetMs / 1000.0;
foreach (var item in notes)
{
var n = MiniJson.AsObject(item);
if (n == null || !MiniJson.TryGetNumber(n, "t", out double tMs)) { skipped++; continue; }
string type = MiniJson.GetString(n, "type", "tap");
double t = tMs / 1000.0 + offset;
bool hasEnd = MiniJson.TryGetNumber(n, "end", out double endMs);
if (type == "slide")
{
var cells = new List<(int x, int y)>();
var path = MiniJson.AsList(MiniJson.Get(n, "path"));
if (path != null)
foreach (var p in path)
if (TryCell(MiniJson.AsObject(p), out int cx, out int cy)) cells.Add((cx, cy));
if (cells.Count == 0) { skipped++; continue; }
// 路徑的格子平均分布在 t ~ end:第一格在 t、最後一格在 end
double end = hasEnd ? endMs / 1000.0 + offset : t;
double interval = cells.Count > 1 ? (end - t) / (cells.Count - 1) : 0;
for (int i = 0; i < cells.Count; i++)
events.Add(new ChartEvent { hitTime = t + interval * i, type = "slide", x = cells[i].x, y = cells[i].y });
}
else if (type == "tap" || type == "hold")
{
if (!TryCell(MiniJson.AsObject(MiniJson.Get(n, "pos")), out int x, out int y)) { skipped++; continue; }
int holdMs = type == "hold" && hasEnd ? (int)Math.Max(0, endMs - tMs) : 0;
events.Add(new ChartEvent { hitTime = t, type = type, x = x, y = y, holdMs = holdMs });
}
else skipped++;
}
events.Sort((a, b) => a.hitTime.CompareTo(b.hitTime));
return events;
}
private static bool TryCell(Dictionary<string, object> pos, out int x, out int y)
{
x = y = 0;
if (pos == null) return false;
if (!MiniJson.TryGetNumber(pos, "x", out double dx) || !MiniJson.TryGetNumber(pos, "y", out double dy)) return false;
x = (int)dx;
y = (int)dy;
return x >= 0 && x < Columns && y >= 0 && y < Rows;
}
}