- One empty scene; App builds the canvas, safe-area layout and a shared 5x6 Grid in code. Pages (Intro, Main, Choose, Play, Account, Settings) replace 5 scenes, 5 prefabs and the per-cell spawner/display components. - Packs: the game reads Rhyculator/package/ (with All files access) or the app folder, like a plugged-in USB stick. Zips stay where they are and are extracted to a cache keyed by name/size/mtime; folders are read directly. Scans run every second on a background thread. Old songs/ imports and inbox zips are migrated automatically. - Download packs by 8-char code from the new pack website, or via rhyculator://pack/<code> links; opened/shared zips go into the package folder. - Play: pause/resume/retry, auto-pause on background, combo and progress bar; judging and scoring unchanged. Choose page fits 9:16 screens; empty state, pack delete. Android back key handled everywhere. - Slimming: removed TextMesh Pro, unused 2D/Timeline/VisualScripting/etc. packages and modules, scene template, unused sprites; menu theme wav (20MB) -> ogg (2.3MB). Build profile replaced by explicit settings in BuildAndroid. - Tests: PackLibrary/PackReader/migration/serializer tests (39 passing). Co-Authored-By: Claude Opus 5.5 <[email protected]>
439 lines
16 KiB
C#
439 lines
16 KiB
C#
using System;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using UnityEngine;
|
||
using UnityEngine.Networking;
|
||
using UnityEngine.UI;
|
||
using UnityEngine.Video;
|
||
|
||
// 遊玩:載入曲包的音樂、譜面與影片,判定、計分,結束後上傳成績並顯示結算
|
||
// 音樂用 PlayScheduled 排在 DSP 時鐘上,音符時間與音訊同一個時間基準,不會累積誤差
|
||
public class PlayPage : Page, IPausable
|
||
{
|
||
private const double LeadIn = 1.0; // 音樂開始前的準備時間,讓開頭的音符也有完整的出現動畫
|
||
private const double ResumeRewind = 1.0; // 暫停後接續時倒回的秒數
|
||
private const int HoldFullScore = 212;
|
||
private const int SlideScore = 106;
|
||
private const float VideoAlpha = 0.4f;
|
||
|
||
private readonly SongInfo song;
|
||
private readonly int level;
|
||
|
||
private enum State { Loading, Playing, Paused, Finished }
|
||
private State state = State.Loading;
|
||
|
||
private ChartPlayer chart;
|
||
private AudioClip clip;
|
||
private VideoPlayer video;
|
||
private RenderTexture videoTexture;
|
||
private bool videoStarted;
|
||
private readonly PlayResult result = new PlayResult();
|
||
|
||
private Text scoreText, comboText;
|
||
private RectTransform progress;
|
||
private Button pauseButton;
|
||
private Dialog pauseDialog;
|
||
private GameObject overlay;
|
||
|
||
// 按住中的 Hold(可同時多個)
|
||
private class ActiveHold
|
||
{
|
||
public int x, y, fingerId;
|
||
public double hitTime, duration;
|
||
public Judgement head;
|
||
}
|
||
private readonly List<ActiveHold> holds = new List<ActiveHold>();
|
||
|
||
public PlayPage(SongInfo song, int level)
|
||
{
|
||
this.song = song;
|
||
this.level = level;
|
||
}
|
||
|
||
public override void Enter()
|
||
{
|
||
Library.Paused = true;
|
||
App.Music.Stop();
|
||
SongClock.Stop();
|
||
Grid.NoteExpired += OnExpired;
|
||
|
||
var title = Ui.Label(Top, $"{song.name} <color=#{ColorUtility.ToHtmlStringRGB(Ui.LevelColors[level])}>{SongInfo.LevelName(level).ToUpper()} {song.levelNum[level]}</color>", 34, Ui.Muted);
|
||
title.horizontalOverflow = HorizontalWrapMode.Overflow;
|
||
Ui.Place(title.rectTransform, new Vector2(0.5f, 1), new Vector2(0, -50), new Vector2(760, 60));
|
||
pauseButton = Ui.Button(Top, "II", Pause, 44);
|
||
Ui.Place((RectTransform)pauseButton.transform, new Vector2(1, 1), new Vector2(-40, -30), new Vector2(120, 100));
|
||
|
||
scoreText = Ui.Label(Top, "載入中…", 120, Color.white);
|
||
scoreText.fontStyle = FontStyle.Bold;
|
||
Ui.Place(scoreText.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, 0), new Vector2(1000, 160));
|
||
comboText = Ui.Label(Top, "", 44, Ui.Accent);
|
||
Ui.Place(comboText.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, -110), new Vector2(1000, 60));
|
||
|
||
var bar = Ui.Image(Top, null, new Color(1, 1, 1, 0.12f));
|
||
Ui.Place(bar.rectTransform, new Vector2(0.5f, 0), new Vector2(0, 0), new Vector2(980, 8));
|
||
progress = Ui.Image(bar.transform, null, Ui.Accent).rectTransform;
|
||
progress.anchorMin = Vector2.zero;
|
||
progress.anchorMax = new Vector2(0, 1);
|
||
progress.offsetMin = progress.offsetMax = Vector2.zero;
|
||
|
||
App.StartCoroutine(Load());
|
||
}
|
||
|
||
// ---------- 載入 ----------
|
||
|
||
IEnumerator Load()
|
||
{
|
||
try
|
||
{
|
||
chart = new ChartPlayer(ChartLoader.LoadFile(song.ChartPath(level), song.offsetMs, out int skipped));
|
||
if (skipped > 0) Debug.LogWarning($"[Play] {song.id} 略過 {skipped} 個無法使用的音符");
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
Fail("譜面讀取失敗:" + e.Message);
|
||
yield break;
|
||
}
|
||
|
||
string musicPath = song.MusicPath;
|
||
if (musicPath == null) { Fail("曲包沒有音樂"); yield break; }
|
||
using (var www = LoadAudio(musicPath))
|
||
{
|
||
yield return www.SendWebRequest();
|
||
if (state != State.Loading) yield break; // 載入中就離開了
|
||
if (www.result != UnityWebRequest.Result.Success) { Fail("音樂載入失敗:" + www.error); yield break; }
|
||
clip = DownloadHandlerAudioClip.GetContent(www);
|
||
}
|
||
if (clip == null || clip.length <= 0f) { Fail("音樂無法解碼"); yield break; }
|
||
|
||
if (Prefs.GetBool(Prefs.VideoBackground, true) && song.VideoPath != null) SetupVideo(song.VideoPath);
|
||
|
||
var music = App.Music;
|
||
music.clip = clip;
|
||
music.loop = false;
|
||
music.time = 0;
|
||
double start = AudioSettings.dspTime + LeadIn;
|
||
music.PlayScheduled(start);
|
||
SongClock.Begin(start);
|
||
state = State.Playing;
|
||
scoreText.text = "0";
|
||
Debug.Log($"[Play] {song.id} {SongInfo.LevelName(level)}: {chart.Count} events, clip {clip.length:0.0}s");
|
||
}
|
||
|
||
void Fail(string message)
|
||
{
|
||
state = State.Finished;
|
||
Toast.Show(message);
|
||
App.Go(new ChoosePage());
|
||
}
|
||
|
||
// 本機檔案 → UnityWebRequest 用的 file:// 網址(處理空白與 Windows 路徑)
|
||
public static string FileUrl(string path) => new Uri(Path.GetFullPath(path)).AbsoluteUri;
|
||
|
||
// ogg / mp3 保持壓縮(整首不解壓,省記憶體);wav 開壓縮模式在 Android 上會讓主執行緒卡死,直接載入
|
||
public static UnityWebRequest LoadAudio(string path)
|
||
{
|
||
AudioType type = Path.GetExtension(path).ToLowerInvariant() switch
|
||
{
|
||
".ogg" => AudioType.OGGVORBIS,
|
||
".mp3" => AudioType.MPEG,
|
||
_ => AudioType.WAV,
|
||
};
|
||
var www = UnityWebRequestMultimedia.GetAudioClip(FileUrl(path), type);
|
||
((DownloadHandlerAudioClip)www.downloadHandler).compressed = type != AudioType.WAV;
|
||
return www;
|
||
}
|
||
|
||
// 曲包的 video.mp4:畫在格子後方當背景,聲音一律用 music 檔
|
||
void SetupVideo(string path)
|
||
{
|
||
var go = new GameObject("PackVideo");
|
||
go.transform.SetParent(App.transform, false);
|
||
video = go.AddComponent<VideoPlayer>();
|
||
video.playOnAwake = false;
|
||
video.source = VideoSource.Url;
|
||
video.url = FileUrl(path);
|
||
video.renderMode = VideoRenderMode.RenderTexture;
|
||
video.audioOutputMode = VideoAudioOutputMode.None;
|
||
video.isLooping = false;
|
||
video.skipOnDrop = true;
|
||
video.prepareCompleted += vp =>
|
||
{
|
||
videoTexture = new RenderTexture((int)vp.width, (int)vp.height, 0);
|
||
vp.targetTexture = videoTexture;
|
||
var bg = App.Background;
|
||
bg.texture = videoTexture;
|
||
bg.color = new Color(1, 1, 1, VideoAlpha);
|
||
var fit = bg.GetComponent<AspectRatioFitter>() ?? bg.gameObject.AddComponent<AspectRatioFitter>();
|
||
fit.aspectMode = AspectRatioFitter.AspectMode.EnvelopeParent;
|
||
fit.aspectRatio = (float)vp.width / Mathf.Max(1, vp.height);
|
||
};
|
||
video.Prepare();
|
||
}
|
||
|
||
// ---------- 遊玩 ----------
|
||
|
||
public override void Tick(List<GridTouch> touches)
|
||
{
|
||
if (state != State.Playing) return;
|
||
double now = SongClock.Now;
|
||
|
||
if (video != null && !videoStarted && now >= 0 && video.isPrepared)
|
||
{
|
||
if (now > 0.05) video.time = now; // 準備得比音樂慢:從目前位置接上
|
||
video.Play();
|
||
App.Background.enabled = true;
|
||
videoStarted = true;
|
||
}
|
||
|
||
// Hold 按滿時間 → 自動結算
|
||
for (int i = holds.Count - 1; i >= 0; i--)
|
||
if (now >= holds[i].hitTime + holds[i].duration)
|
||
FinishHold(holds[i], now);
|
||
|
||
foreach (var t in touches)
|
||
{
|
||
if (t.ended)
|
||
{
|
||
var h = holds.Find(a => a.fingerId == t.fingerId);
|
||
if (h != null) FinishHold(h, now);
|
||
continue;
|
||
}
|
||
if (!t.OnCell) continue;
|
||
if (!Grid.HasNote(t.x, t.y))
|
||
{
|
||
Grid.Flash(t.x, t.y, CellFlash.White); // 空按也亮白色(不覆蓋判定色)
|
||
continue;
|
||
}
|
||
|
||
// 按下的精確時間(觸控事件時間回推),不受幀率影響
|
||
double pressTime = now - t.pressAge;
|
||
switch (Grid.NoteTypeAt(t.x, t.y))
|
||
{
|
||
case NoteType.Tap:
|
||
if (t.began) ProcessTap(t.x, t.y, pressTime);
|
||
break;
|
||
case NoteType.Hold:
|
||
if (t.began) StartHold(t, pressTime, now);
|
||
break;
|
||
case NoteType.Slide:
|
||
// 不提早判定:到達判定點後手指在格子上即算接到(可延遲到判定窗結束)
|
||
if (now >= Grid.HitTime(t.x, t.y))
|
||
{
|
||
Grid.Flash(t.x, t.y, CellFlash.Blue);
|
||
Grid.ClearNote(t.x, t.y);
|
||
AddScore(Judgement.Perfect, SlideScore);
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
|
||
if (clip != null)
|
||
{
|
||
progress.anchorMax = new Vector2(Mathf.Clamp01((float)(now / clip.length)), 1);
|
||
// 歌曲(含結尾緩衝)結束
|
||
if (now > clip.length + NoteJudge.BadWindow + 0.5) App.StartCoroutine(Finish());
|
||
}
|
||
}
|
||
|
||
public override void LateTick()
|
||
{
|
||
if (state == State.Playing) chart.Tick(Grid, SongClock.Now);
|
||
}
|
||
|
||
// 只做判定,不給分、不清除(None = 不在判定範圍)
|
||
Judgement JudgeHead(int x, int y, double pressTime)
|
||
{
|
||
Judgement j = NoteJudge.Evaluate(pressTime - Grid.HitTime(x, y));
|
||
return j == Judgement.Miss ? Judgement.None : j;
|
||
}
|
||
|
||
void ProcessTap(int x, int y, double pressTime)
|
||
{
|
||
Judgement j = JudgeHead(x, y, pressTime);
|
||
if (j == Judgement.None) return;
|
||
Grid.Flash(x, y, FlashFor(j));
|
||
AddScore(j, NoteJudge.Score(j));
|
||
Grid.ClearNote(x, y);
|
||
}
|
||
|
||
void StartHold(GridTouch t, double pressTime, double now)
|
||
{
|
||
int holdMs = Grid.HoldMs(t.x, t.y);
|
||
double hit = Grid.HitTime(t.x, t.y);
|
||
Judgement j = JudgeHead(t.x, t.y, pressTime);
|
||
if (j == Judgement.None || holdMs <= 0) return;
|
||
|
||
// Hold 頭判先記住,按滿才給分
|
||
Grid.Flash(t.x, t.y, FlashFor(j));
|
||
Grid.ClearNote(t.x, t.y);
|
||
var h = new ActiveHold { x = t.x, y = t.y, fingerId = t.fingerId, hitTime = hit, duration = holdMs / 1000.0, head = j };
|
||
holds.Add(h);
|
||
Grid.StartRing(t.x, t.y, (float)(hit + h.duration - now));
|
||
}
|
||
|
||
void FinishHold(ActiveHold h, double now)
|
||
{
|
||
if (now >= h.hitTime + h.duration - 0.02)
|
||
{
|
||
// 按滿:頭判分數 + 持續段分數
|
||
Grid.Flash(h.x, h.y, CellFlash.Blue);
|
||
AddScore(h.head, NoteJudge.Score(h.head) + HoldFullScore);
|
||
}
|
||
else
|
||
{
|
||
// 提早放開:亮紅色、不給分
|
||
Grid.Flash(h.x, h.y, CellFlash.Red);
|
||
AddScore(Judgement.Miss, 0);
|
||
}
|
||
Grid.StopRing(h.x, h.y);
|
||
holds.Remove(h);
|
||
}
|
||
|
||
void OnExpired(int x, int y, NoteType type)
|
||
{
|
||
if (state != State.Playing) return;
|
||
Grid.Flash(x, y, CellFlash.Red);
|
||
AddScore(Judgement.Miss, 0);
|
||
}
|
||
|
||
void AddScore(Judgement j, int amount)
|
||
{
|
||
result.Add(j, amount);
|
||
scoreText.text = result.score.ToString();
|
||
comboText.text = result.combo >= 5 ? $"{result.combo} COMBO" : "";
|
||
}
|
||
|
||
public static CellFlash FlashFor(Judgement j) => j switch
|
||
{
|
||
Judgement.Perfect => CellFlash.Blue,
|
||
Judgement.Fast => CellFlash.Green,
|
||
Judgement.Slow => CellFlash.Orange,
|
||
_ => CellFlash.Red,
|
||
};
|
||
|
||
// ---------- 暫停 ----------
|
||
|
||
public void OnAppPause()
|
||
{
|
||
if (state == State.Playing) Pause();
|
||
}
|
||
|
||
void Pause()
|
||
{
|
||
if (state != State.Playing) return;
|
||
state = State.Paused;
|
||
SongClock.Pause();
|
||
App.Music.Pause();
|
||
if (video != null && video.isPlaying) video.Pause();
|
||
// 按住中的 Hold 以目前進度結算(放開的手指在暫停期間收不到)
|
||
for (int i = holds.Count - 1; i >= 0; i--) FinishHold(holds[i], SongClock.Now);
|
||
|
||
pauseDialog = new Dialog(App.Overlay, "暫停");
|
||
pauseDialog.cancellable = false;
|
||
pauseDialog.AddClose("離開", () => Quit());
|
||
pauseDialog.AddClose("重來", () => App.Go(new PlayPage(song, level)));
|
||
pauseDialog.AddClose("繼續", Resume, primary: true);
|
||
}
|
||
|
||
void Resume()
|
||
{
|
||
// 倒回一點再接續,讓玩家有時間準備
|
||
double resumeAt = SongClock.PausedAt - ResumeRewind;
|
||
var music = App.Music;
|
||
double dsp = AudioSettings.dspTime + 0.1;
|
||
if (resumeAt >= 0)
|
||
{
|
||
music.time = (float)resumeAt;
|
||
music.PlayScheduled(dsp);
|
||
SongClock.Resume(resumeAt, dsp);
|
||
}
|
||
else
|
||
{
|
||
music.time = 0;
|
||
music.PlayScheduled(dsp - resumeAt);
|
||
SongClock.Resume(0, dsp - resumeAt);
|
||
}
|
||
// 影片在 Tick 裡對齊目前時間後重新播放
|
||
if (video != null && video.isPlaying) video.Pause();
|
||
videoStarted = false;
|
||
App.Input.IgnoreCurrentTouches();
|
||
state = State.Playing;
|
||
}
|
||
|
||
public override void Back()
|
||
{
|
||
if (state == State.Playing) Pause();
|
||
else if (state == State.Finished && overlay != null) Quit();
|
||
else if (state == State.Loading) Quit();
|
||
}
|
||
|
||
void Quit()
|
||
{
|
||
state = State.Finished;
|
||
App.Go(new ChoosePage());
|
||
}
|
||
|
||
// ---------- 結算 ----------
|
||
|
||
IEnumerator Finish()
|
||
{
|
||
state = State.Finished;
|
||
pauseButton.gameObject.SetActive(false);
|
||
PlayResult.Last = result;
|
||
Debug.Log($"[Play] song={song.id} level={level} notes={chart.Count} {result}");
|
||
|
||
string status;
|
||
if (!Prefs.LoggedIn) status = "未登入,成績不會上傳";
|
||
else
|
||
{
|
||
Api.Response r = null;
|
||
// 曲包不在伺服器上註冊過時,伺服器會用這些資訊建立歌曲資料
|
||
yield return Api.Game(new Dictionary<string, object>
|
||
{
|
||
["request"] = "user_play",
|
||
["uid"] = Prefs.UserId,
|
||
["token"] = PlayerPrefs.GetString(Prefs.Token, ""),
|
||
["song"] = song.id,
|
||
["title"] = song.name,
|
||
["artist"] = song.artist,
|
||
["bpm"] = song.bpm,
|
||
["duration_sec"] = Mathf.RoundToInt(clip.length),
|
||
["level"] = level,
|
||
["level_num"] = song.levelNum[level],
|
||
["score"] = result.score,
|
||
}, x => r = x);
|
||
status = r.error == null ? "成績已上傳" : "成績上傳失敗:" + r.error;
|
||
}
|
||
if (App.Current != this) yield break;
|
||
|
||
scoreText.gameObject.SetActive(false);
|
||
comboText.gameObject.SetActive(false);
|
||
overlay = ResultOverlay.Show(result, chart.Count, Ui.Font, status);
|
||
|
||
// 等待一次新的點擊(忽略結算出現前就按著的手指)
|
||
yield return new WaitForSecondsRealtime(0.6f);
|
||
while (App.Current == this && !GridInput.AnyNewTap()) yield return null;
|
||
if (App.Current == this) Quit();
|
||
}
|
||
|
||
public override void Exit()
|
||
{
|
||
state = State.Finished;
|
||
Grid.NoteExpired -= OnExpired;
|
||
Library.Paused = false;
|
||
SongClock.Stop();
|
||
App.Music.Stop();
|
||
if (App.Music.clip == clip) App.Music.clip = null;
|
||
if (clip != null) UnityEngine.Object.Destroy(clip);
|
||
if (video != null) UnityEngine.Object.Destroy(video.gameObject);
|
||
if (videoTexture != null)
|
||
{
|
||
App.Background.texture = null;
|
||
videoTexture.Release();
|
||
UnityEngine.Object.Destroy(videoTexture);
|
||
}
|
||
if (overlay != null) UnityEngine.Object.Destroy(overlay);
|
||
}
|
||
}
|