Rebuild the game as a single code-driven scene with a package-folder pack source

- 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]>
This commit is contained in:
SahikandClaude Opus 5.5 committed 2026-10-24 14:18:54 +08:00
1 parent 6d5f66ac6a
commit ddd5fdc28b
295 files changed
+3854 -82126

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
// 伺服器呼叫(回應一律用 MiniJson 解析)
public static class Api
{
public class Response
{
public Dictionary<string, object> data; // 解析失敗或連線失敗時為 null
public string error; // 給玩家看的錯誤;成功時為 null
public string Status => MiniJson.GetString(data, "status", "");
public string Reason => MiniJson.GetString(data, "reason", "");
public bool Ok => error == null && (Status == "success" || Status == "send" || Status == "found" || Status == "not_found");
public string Str(string key) => MiniJson.GetString(data, key, "");
public int Int(string key) => MiniJson.GetInt(data, key, 0);
}
public static IEnumerator Game(Dictionary<string, object> body, Action<Response> done)
=> Post(ServerConfig.GameServerUrl + "/", body, done);
public static IEnumerator Verify(Dictionary<string, object> body, Action<Response> done)
=> Post(ServerConfig.VerifyServerUrl + "/", body, done);
public static IEnumerator Post(string url, Dictionary<string, object> body, Action<Response> done)
{
using var www = new UnityWebRequest(url, "POST");
www.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(MiniJson.Serialize(body)));
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
www.timeout = 10;
yield return www.SendWebRequest();
done(Parse(www));
}
public static IEnumerator Get(string url, Action<Response> done)
{
using var www = UnityWebRequest.Get(url);
www.timeout = 10;
yield return www.SendWebRequest();
done(Parse(www));
}
// 伺服器回 4xx/5xx 時 body 仍是 JSON,照樣解析
static Response Parse(UnityWebRequest www)
{
var r = new Response();
try { r.data = MiniJson.AsObject(MiniJson.Parse(www.downloadHandler.text)); }
catch { r.data = null; }
if (r.data == null)
r.error = www.result == UnityWebRequest.Result.ConnectionError ? "無法連線到伺服器" : "伺服器回傳異常";
else if (r.Status == "fail" || r.Status == "failed")
r.error = r.Reason;
if (r.error != null) Debug.LogWarning($"[Api] {www.url}: {r.error} ({www.error})");
return r;
}
// 以曲包代碼下載到 package 資料夾;progress 0~1;完成時 done(錯誤或 null, 曲名)
public static IEnumerator DownloadPack(string code, Action<float> progress, Action<string, string> done)
{
code = code.Trim().ToLowerInvariant();
Response info = null;
yield return Get($"{ServerConfig.GameServerUrl}/api/packs/{UnityWebRequest.EscapeURL(code)}", r => info = r);
if (info.error != null)
{
done(info.Reason == "not_found" ? "找不到這個代碼的曲包" : info.error, null);
yield break;
}
var pack = MiniJson.AsObject(MiniJson.Get(info.data, "pack"));
string title = MiniJson.GetString(pack, "title", code);
string url = ServerConfig.GameServerUrl + MiniJson.GetString(pack, "download", $"/p/{code}/download");
string dir = PackStorage.PackageDir;
Directory.CreateDirectory(dir);
string part = Path.Combine(dir, $".{code}.part");
using (var www = UnityWebRequest.Get(url))
{
www.downloadHandler = new DownloadHandlerFile(part) { removeFileOnAbort = true };
var op = www.SendWebRequest();
while (!op.isDone)
{
progress?.Invoke(www.downloadProgress);
yield return null;
}
if (www.result != UnityWebRequest.Result.Success)
{
try { File.Delete(part); } catch { }
done("下載失敗:" + www.error, title);
yield break;
}
}
// 同一個曲包的舊版本(代碼相同)換成新下載的
var old = Library.Find(code);
if (old != null) PackStorage.DeleteSource(old);
string target = PackStorage.UniquePath(dir, $"{SafeName(title)} [{code}]", ".zip");
File.Move(part, target);
// 讓掃描不必等「剛寫入」的緩衝時間
File.SetLastWriteTimeUtc(target, DateTime.UtcNow - PackLibrary.SettleTime - TimeSpan.FromSeconds(1));
Library.Rescan();
done(null, title);
}
static string SafeName(string s)
{
foreach (char c in Path.GetInvalidFileNameChars()) s = s.Replace(c, '_');
foreach (char c in "\\/:*?\"<>|") s = s.Replace(c, '_');
s = s.Trim();
return s.Length > 60 ? s.Substring(0, 60) : (s == "" ? "pack" : s);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ec2d9a420eee6e042b20268b397edc96
+151
View File
@@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
// 曲包清單(遊戲其他地方都透過這裡取得曲目)
// 開啟遊戲、回到前景時立即掃描 package 資料夾,之後每秒一次;掃描在背景執行緒進行
public class Library : MonoBehaviour
{
public static IReadOnlyList<SongInfo> Songs { get; private set; } = new List<SongInfo>();
public static bool Loaded { get; private set; }
public static string PackageDir { get; private set; }
// 曲包清單有變(新增、刪除、更新)
public static event Action Changed;
// 有新的曲包出現(不含第一次掃描)
public static event Action<SongInfo> Added;
// 遊玩中暫停掃描,避免 IO 影響幀率
public static bool Paused;
private static Library instance;
private Task<PackLibrary.ScanResult> running;
private float nextScan;
private bool first = true;
public static void Create()
{
if (instance != null) return;
var go = new GameObject("Library");
DontDestroyOnLoad(go);
instance = go.AddComponent<Library>();
}
// 立即重新掃描(例如取得權限、下載完成後)
public static void Rescan()
{
if (instance != null) instance.nextScan = 0;
}
public static SongInfo Find(string id)
{
foreach (var s in Songs) if (s.id == id) return s;
return null;
}
public static SongInfo Current
{
get
{
var s = Find(PlayerPrefs.GetString(Prefs.Song, ""));
return s ?? (Songs.Count > 0 ? Songs[0] : null);
}
set
{
if (value == null) return;
PlayerPrefs.SetString(Prefs.Song, value.id);
}
}
void OnApplicationFocus(bool focus)
{
if (focus) nextScan = 0;
}
void Update()
{
if (running != null)
{
if (!running.IsCompleted) return;
Apply(running);
running = null;
}
if (Paused || Time.unscaledTime < nextScan) return;
nextScan = Time.unscaledTime + 1f;
string packageDir = PackStorage.PackageDir;
string cacheDir = PackStorage.CacheDir;
if (packageDir != PackageDir)
{
// 位置改變(取得權限):搬過去並重新開始
PackageDir = packageDir;
PackLibrary.ResetState();
first = true;
}
running = Task.Run(() =>
{
PackStorage.Migrate(packageDir);
return PackLibrary.Scan(packageDir, cacheDir);
});
}
void Apply(Task<PackLibrary.ScanResult> task)
{
if (task.IsFaulted)
{
Debug.LogWarning("[Library] 掃描失敗:" + task.Exception?.GetBaseException().Message);
return;
}
var r = task.Result;
foreach (var e in r.errors) Toast.Show("曲包有問題:" + e);
if (r.pending) nextScan = Time.unscaledTime + 0.5f;
if (r.changed || !Loaded)
{
Songs = r.songs;
Loaded = true;
Debug.Log($"[Library] {Songs.Count} 個曲包 @ {PackageDir}");
Changed?.Invoke();
}
if (!first)
foreach (var s in r.added)
{
Toast.Show($"已加入「{s.name}」");
Added?.Invoke(s);
}
first = false;
ReadImportError();
ReadPendingDownload();
}
// 曲包網站的「在遊戲中下載」連結(rhyculator://pack/<code>):Java 端把代碼寫在這個檔案
public static event Action<string> DownloadRequested;
static void ReadPendingDownload()
{
string path = Path.Combine(PackStorage.PrivateRoot, PackStorage.PendingDownloadFile);
if (!File.Exists(path)) return;
string code = "";
try { code = File.ReadAllText(path).Trim().ToLowerInvariant(); } catch { }
try { File.Delete(path); } catch { }
if (System.Text.RegularExpressions.Regex.IsMatch(code, "^[a-z0-9]{8}$")) DownloadRequested?.Invoke(code);
}
// Java 端讀取「開啟 / 分享」進來的檔案失敗時留下的訊息
static void ReadImportError()
{
string path = Path.Combine(PackStorage.PrivateRoot, PackStorage.ImportErrorFile);
if (!File.Exists(path)) return;
string detail = "";
try { detail = File.ReadAllText(path); } catch { }
try { File.Delete(path); } catch { }
Debug.LogWarning("[Library] " + detail);
Toast.Show(detail.Contains("Permission Denial") || detail.Contains("SecurityException")
? "沒有讀取這個檔案的權限,請從檔案管理員用「開啟」或「分享」送給 Rhyculator"
: "無法讀取檔案:" + detail);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6d3343d5a8659b64fabd125d9f91790a
+168
View File
@@ -0,0 +1,168 @@
using System;
using System.IO;
using UnityEngine;
// 曲包資料夾的位置
// - 有「所有檔案存取權」(Android 11+)或儲存權限(Android 10 以下):手機根目錄的 Rhyculator/package,
// 接上電腦(USB)或用任何檔案管理員都看得到,像插上一個隨身碟
// - 沒有權限:app 自己的資料夾 Android/data/<套件名>/files/package(USB 通常也看得到,但檔案管理員看不到)
// 位置的判斷與 RhyculatorActivity.packageDir() 一致,Java 收到的 zip 會直接放進同一個資料夾
public static class PackStorage
{
public const string FolderName = "Rhyculator";
public const string PackageFolder = "package";
// Java 端寫的訊息檔(在 app 自己的資料夾)
public const string ImportErrorFile = "import-error.txt";
public const string PendingDownloadFile = "pending-download.txt";
// 測試用:改放到別的資料夾
public static string rootOverride;
private static string privateRoot, cacheRoot, sharedRoot;
// 在主執行緒呼叫一次(Application.* 只能在主執行緒讀)
public static void Init()
{
privateRoot = Application.persistentDataPath;
cacheRoot = Path.Combine(Application.persistentDataPath, "cache", "packs");
#if UNITY_ANDROID && !UNITY_EDITOR
try
{
using var env = new AndroidJavaClass("android.os.Environment");
using var dir = env.CallStatic<AndroidJavaObject>("getExternalStorageDirectory");
sharedRoot = Path.Combine(dir.Call<string>("getAbsolutePath"), FolderName);
}
catch (Exception e) { Debug.LogWarning("[PackStorage] " + e.Message); }
#endif
}
public static string PrivateRoot => rootOverride ?? privateRoot;
public static string CacheDir => rootOverride != null ? Path.Combine(rootOverride, "cache") : cacheRoot;
public static bool SupportsShared => sharedRoot != null && rootOverride == null;
public static string Root => SupportsShared && HasSharedAccess() ? sharedRoot : PrivateRoot;
public static string PackageDir => Path.Combine(Root, PackageFolder);
public static bool HasSharedAccess()
{
#if UNITY_ANDROID && !UNITY_EDITOR
try { return Activity().CallStatic<bool>("hasStorageAccess", CurrentActivity()); }
catch (Exception e) { Debug.LogWarning("[PackStorage] " + e.Message); }
#endif
return false;
}
// 開啟系統的授權畫面;結果在回到遊戲時(OnApplicationFocus)重新檢查
public static void RequestSharedAccess()
{
#if UNITY_ANDROID && !UNITY_EDITOR
try { Activity().CallStatic("requestStorageAccess", CurrentActivity()); }
catch (Exception e) { Debug.LogWarning("[PackStorage] " + e.Message); }
#endif
}
#if UNITY_ANDROID && !UNITY_EDITOR
static AndroidJavaClass Activity() => new AndroidJavaClass("com.rhyculator.RhyculatorActivity");
static AndroidJavaObject CurrentActivity()
{
using var player = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
return player.GetStatic<AndroidJavaObject>("currentActivity");
}
#endif
// 把舊位置的曲包搬到目前的 package 資料夾(背景執行緒可呼叫):
// - 舊版匯入的 songs/<id>/ 資料夾
// - app 資料夾根目錄的 *.zip(舊版的收件匣、adb push)
// - 取得權限前放在 app 資料夾的 package/
public static void Migrate(string packageDir)
{
Directory.CreateDirectory(packageDir);
string root = PrivateRoot;
string privatePackage = Path.Combine(root, PackageFolder);
// 曲包裡的音樂不要出現在手機的音樂 app
try
{
string nomedia = Path.Combine(Path.GetDirectoryName(packageDir), ".nomedia");
if (!File.Exists(nomedia)) File.WriteAllBytes(nomedia, Array.Empty<byte>());
}
catch { }
string songs = Path.Combine(root, "songs");
if (Directory.Exists(songs))
{
foreach (var dir in Directory.GetDirectories(songs))
MoveInto(dir, packageDir);
TryDelete(songs);
}
foreach (var zip in Directory.GetFiles(root, "*.zip"))
MoveInto(zip, packageDir);
if (!SamePath(privatePackage, packageDir) && Directory.Exists(privatePackage))
{
foreach (var f in Directory.GetFiles(privatePackage)) MoveInto(f, packageDir);
foreach (var d in Directory.GetDirectories(privatePackage)) MoveInto(d, packageDir);
TryDelete(privatePackage);
}
}
static void MoveInto(string path, string dir)
{
try
{
string name = Path.GetFileName(path);
string dest = UniquePath(dir, Path.GetFileNameWithoutExtension(name), Path.GetExtension(name));
if (Directory.Exists(path)) MoveDirectory(path, dest);
else
{
File.Copy(path, dest); // 可能跨儲存區,用複製再刪除
File.Delete(path);
}
}
catch (Exception e) { Debug.LogWarning($"[PackStorage] 無法移動 {path}:{e.Message}"); }
}
static void MoveDirectory(string src, string dest)
{
try { Directory.Move(src, dest); return; }
catch (IOException) { }
Directory.CreateDirectory(dest);
foreach (var f in Directory.GetFiles(src)) File.Copy(f, Path.Combine(dest, Path.GetFileName(f)));
Directory.Delete(src, true);
}
// dir/name.ext,已存在時加上 (2)、(3)…
public static string UniquePath(string dir, string name, string ext)
{
string path = Path.Combine(dir, name + ext);
for (int i = 2; File.Exists(path) || Directory.Exists(path); i++)
path = Path.Combine(dir, $"{name} ({i}){ext}");
return path;
}
static bool SamePath(string a, string b)
=> string.Equals(Path.GetFullPath(a).TrimEnd('/', '\\'), Path.GetFullPath(b).TrimEnd('/', '\\'), StringComparison.OrdinalIgnoreCase);
static void TryDelete(string dir)
{
try { Directory.Delete(dir, true); } catch { }
}
// 刪除一個曲包的來源(zip 或資料夾)
public static bool DeleteSource(SongInfo song)
{
try
{
if (File.Exists(song.source)) File.Delete(song.source);
else if (Directory.Exists(song.source)) Directory.Delete(song.source, true);
return true;
}
catch (Exception e)
{
Debug.LogWarning("[PackStorage] " + e.Message);
return false;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 650f3c7c23c45684c87f71208c439e2f
+12
View File
@@ -0,0 +1,12 @@
// 伺服器網址集中管理
// 本地測試:UseLocal = true,並對模擬器執行
// adb reverse tcp:2010 tcp:2010
// adb reverse tcp:2030 tcp:2030
public static class ServerConfig
{
public const bool UseLocal = true;
// 遊戲 API(POST /)與曲包網站(GET /、/api/packs)是同一個服務
public const string GameServerUrl = UseLocal ? "http://127.0.0.1:2010" : "https://lunchpad.sthkm3.org";
public const string VerifyServerUrl = UseLocal ? "http://127.0.0.1:2030" : "https://verify.sthkm3.org";
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9d6e31a65e930824991bf2a768205f09