322 lines
12 KiB
C#
322 lines
12 KiB
C#
using System.Collections.Generic;
|
||
using System.Globalization;
|
||
using System.Text;
|
||
using UnityEngine;
|
||
|
||
namespace TKS
|
||
{
|
||
/// <summary>
|
||
/// 소리 재생 창구(2026-11-20 사운드 1차 적용 · 개발요청_사운드_2026-11-20 §2-1).
|
||
/// 표 = Resources/Audio/sound_events.csv(s_key · e_bus · s_clips · f_vol · f_pitch_min · f_pitch_max · f_min_gap) — 파일 · 음량 · 높낮이 · 간격은 전부 표에서 읽는다(C45).
|
||
/// 가상 실행(Sim.Active) · Play 가 아닐 때 = 재생하지 않음 · 표에 없는 이름 · 못 찾은 파일 = 경고 1번만(오류 로그 없음).
|
||
/// 재생 장치 = 씬이 바뀌어도 남는 오브젝트 1개(SoundPlayer · 효과음 소스 묶음 + 배경음악 소스 2개 겹쳐 넘기기).
|
||
/// </summary>
|
||
public static class Sound
|
||
{
|
||
public const string Root = "Audio/";
|
||
const string TableFile = "sound_events";
|
||
const string PrefSfx = "tks_sound_sfx", PrefBgm = "tks_sound_bgm", PrefMute = "tks_sound_mute";
|
||
|
||
public class Ev
|
||
{
|
||
public string key, bus;
|
||
public string[] clips;
|
||
public float vol = 1f, pitchMin = 1f, pitchMax = 1f, gap;
|
||
}
|
||
|
||
static Dictionary<string, Ev> table;
|
||
static readonly Dictionary<string, AudioClip> clipCache = new Dictionary<string, AudioClip>();
|
||
static readonly Dictionary<string, float> lastAt = new Dictionary<string, float>();
|
||
static readonly Dictionary<string, bool> rise = new Dictionary<string, bool>();
|
||
static readonly HashSet<string> warned = new HashSet<string>();
|
||
static SoundPlayer player;
|
||
static int uiFrame = -1;
|
||
static bool prefsLoaded;
|
||
static float sfxVol = 1f, bgmVol = 1f;
|
||
static bool mute;
|
||
|
||
/// <summary>켜면 실제로 재생한 소리 이름을 <see cref="Traced"/> 에 쌓는다(자동 시험 · 캡처용).</summary>
|
||
public static bool Trace;
|
||
public static readonly List<string> Traced = new List<string>();
|
||
|
||
/// <summary>Play 진입마다 정적 값 초기화(도메인 리로드를 끈 설정 대비 · BattleEvents.ResetStatics 와 같은 방식).</summary>
|
||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
||
static void ResetStatics()
|
||
{
|
||
table = null;
|
||
clipCache.Clear();
|
||
lastAt.Clear();
|
||
rise.Clear();
|
||
warned.Clear();
|
||
player = null;
|
||
uiFrame = -1;
|
||
prefsLoaded = false;
|
||
Trace = false;
|
||
Traced.Clear();
|
||
}
|
||
|
||
// ---------- 음량(PlayerPrefs 저장) ----------
|
||
|
||
static void LoadPrefs()
|
||
{
|
||
if (prefsLoaded) return;
|
||
prefsLoaded = true;
|
||
sfxVol = PlayerPrefs.GetFloat(PrefSfx, 1f);
|
||
bgmVol = PlayerPrefs.GetFloat(PrefBgm, 1f);
|
||
mute = PlayerPrefs.GetInt(PrefMute, 0) != 0;
|
||
}
|
||
|
||
public static float SfxVolume
|
||
{
|
||
get { LoadPrefs(); return sfxVol; }
|
||
set { LoadPrefs(); sfxVol = Mathf.Clamp01(value); PlayerPrefs.SetFloat(PrefSfx, sfxVol); }
|
||
}
|
||
|
||
public static float BgmVolume
|
||
{
|
||
get { LoadPrefs(); return bgmVol; }
|
||
set { LoadPrefs(); bgmVol = Mathf.Clamp01(value); PlayerPrefs.SetFloat(PrefBgm, bgmVol); }
|
||
}
|
||
|
||
public static bool Mute
|
||
{
|
||
get { LoadPrefs(); return mute; }
|
||
set { LoadPrefs(); mute = value; PlayerPrefs.SetInt(PrefMute, value ? 1 : 0); }
|
||
}
|
||
|
||
// ---------- 표 ----------
|
||
|
||
/// <summary>표를 다음 재생 때 다시 읽는다(전투 시작마다 · 다른 표와 같은 방식 = Play 켠 채 교체 확인).</summary>
|
||
public static void Reload()
|
||
{
|
||
table = null;
|
||
}
|
||
|
||
/// <summary>Resources/Audio/ 아래 표(# 주석 줄 제외) → 줄 목록 · 오류는 경고 1번.</summary>
|
||
public static List<Dictionary<string, string>> ReadTable(string file)
|
||
{
|
||
var text = StageTable.ResourceText(Root + file);
|
||
if (text == null)
|
||
{
|
||
WarnOnce("table:" + file, "Resources/" + Root + file + ".csv 없음");
|
||
return new List<Dictionary<string, string>>();
|
||
}
|
||
if (text.Length > 0 && text[0] == '') text = text.Substring(1);
|
||
var sb = new StringBuilder(text.Length);
|
||
foreach (var line in text.Replace("\r", "").Split('\n'))
|
||
{
|
||
if (line.StartsWith("#")) continue;
|
||
sb.Append(line).Append('\n');
|
||
}
|
||
var errors = new List<string>();
|
||
var rows = StageTable.ReadCsv(sb.ToString(), file + ".csv", errors);
|
||
foreach (var e in errors) WarnOnce("row:" + e, e);
|
||
return rows;
|
||
}
|
||
|
||
static Dictionary<string, Ev> Table
|
||
{
|
||
get
|
||
{
|
||
if (table != null) return table;
|
||
table = new Dictionary<string, Ev>();
|
||
foreach (var r in ReadTable(TableFile))
|
||
{
|
||
string key = Get(r, "s_key");
|
||
if (key.Length == 0) continue;
|
||
var ev = new Ev
|
||
{
|
||
key = key,
|
||
bus = Get(r, "e_bus"),
|
||
clips = Get(r, "s_clips").Split(new[] { ';' }, System.StringSplitOptions.RemoveEmptyEntries),
|
||
vol = Num(r, "f_vol", 1f),
|
||
pitchMin = Num(r, "f_pitch_min", 1f),
|
||
pitchMax = Num(r, "f_pitch_max", 1f),
|
||
gap = Num(r, "f_min_gap", 0f),
|
||
};
|
||
for (int i = 0; i < ev.clips.Length; i++) ev.clips[i] = ev.clips[i].Trim();
|
||
table[key] = ev;
|
||
}
|
||
return table;
|
||
}
|
||
}
|
||
|
||
static string Get(Dictionary<string, string> r, string k)
|
||
{
|
||
string v;
|
||
return r.TryGetValue(k, out v) && v != null ? v.Trim() : "";
|
||
}
|
||
|
||
static float Num(Dictionary<string, string> r, string k, float def)
|
||
{
|
||
float v;
|
||
return float.TryParse(Get(r, k), NumberStyles.Float, CultureInfo.InvariantCulture, out v) ? v : def;
|
||
}
|
||
|
||
/// <summary>표의 모든 소리 이름(시험용).</summary>
|
||
public static List<string> Keys()
|
||
{
|
||
return new List<string>(Table.Keys);
|
||
}
|
||
|
||
public static Ev Find(string key)
|
||
{
|
||
Ev ev;
|
||
return key != null && Table.TryGetValue(key, out ev) ? ev : null;
|
||
}
|
||
|
||
public static bool Has(string key)
|
||
{
|
||
return Find(key) != null;
|
||
}
|
||
|
||
/// <summary>Resources/Audio/ 아래 경로(확장자 없음)의 소리 파일 · 없으면 null.</summary>
|
||
public static AudioClip LoadClip(string path)
|
||
{
|
||
AudioClip c;
|
||
if (clipCache.TryGetValue(path, out c) && c != null) return c;
|
||
c = Resources.Load<AudioClip>(Root + path);
|
||
if (c != null) clipCache[path] = c;
|
||
return c;
|
||
}
|
||
|
||
static void WarnOnce(string id, string msg)
|
||
{
|
||
if (!warned.Add(id)) return;
|
||
Debug.LogWarning("[Sound] " + msg);
|
||
}
|
||
|
||
static bool Blocked
|
||
{
|
||
get { return Sim.Active || !Application.isPlaying; }
|
||
}
|
||
|
||
static Ev Resolve(string key, out AudioClip clip)
|
||
{
|
||
clip = null;
|
||
var ev = Find(key);
|
||
if (ev == null)
|
||
{
|
||
WarnOnce("key:" + key, "표에 없는 소리 이름 「" + key + "」");
|
||
return null;
|
||
}
|
||
if (ev.clips.Length == 0) return null; // 빈 칸 = 소리 없음
|
||
string path = ev.clips[ev.clips.Length == 1 ? 0 : rng.Next(ev.clips.Length)];
|
||
clip = LoadClip(path);
|
||
if (clip == null)
|
||
{
|
||
WarnOnce("clip:" + path, "소리 파일 없음 「" + key + "」 → Resources/" + Root + path);
|
||
return null;
|
||
}
|
||
return ev;
|
||
}
|
||
|
||
/// <summary>소리 전용 난수(게임의 UnityEngine.Random 흐름을 건드리지 않음 = 소리 훅이 전투 결과 · 시험을 바꾸지 않게).</summary>
|
||
static readonly System.Random rng = new System.Random();
|
||
|
||
static float Pitch(Ev ev)
|
||
{
|
||
float lo = Mathf.Min(ev.pitchMin, ev.pitchMax), hi = Mathf.Max(ev.pitchMin, ev.pitchMax);
|
||
return lo + (float)rng.NextDouble() * (hi - lo);
|
||
}
|
||
|
||
static bool GapOk(Ev ev)
|
||
{
|
||
float now = Time.unscaledTime, last;
|
||
if (ev.gap > 0f && lastAt.TryGetValue(ev.key, out last) && now - last < ev.gap) return false;
|
||
lastAt[ev.key] = now;
|
||
return true;
|
||
}
|
||
|
||
static SoundPlayer Player
|
||
{
|
||
get
|
||
{
|
||
if (player == null) player = SoundPlayer.Create();
|
||
return player;
|
||
}
|
||
}
|
||
|
||
static void Record(string key)
|
||
{
|
||
if (Trace) Traced.Add(key);
|
||
}
|
||
|
||
// ---------- 재생 ----------
|
||
|
||
/// <summary>효과음 재생(표 e_bus = jingle 이면 <see cref="Jingle"/> · bgm 이면 <see cref="Bgm"/>). 반환 = 실제로 재생했는가.</summary>
|
||
public static bool Play(string key)
|
||
{
|
||
if (Blocked || string.IsNullOrEmpty(key)) return false;
|
||
var f = Find(key);
|
||
if (f != null && f.bus == "bgm") return Bgm(key);
|
||
if (f != null && f.bus == "jingle") return Jingle(key);
|
||
AudioClip clip;
|
||
var ev = Resolve(key, out clip);
|
||
if (ev == null || !GapOk(ev)) return false;
|
||
if (ev.bus == "ui") uiFrame = Time.frameCount;
|
||
Player.PlaySfx(clip, ev.vol, Pitch(ev), 0f);
|
||
Record(key);
|
||
return true;
|
||
}
|
||
|
||
/// <summary>UI 소리 — 같은 프레임에 이미 UI 소리가 났으면 건너뜀(탭 → 화면 전환처럼 한 번 누름에 소리 하나).</summary>
|
||
public static bool PlayUi(string key)
|
||
{
|
||
if (uiFrame == Time.frameCount) return false;
|
||
return Play(key);
|
||
}
|
||
|
||
/// <summary>UI 소리가 이 프레임에 났는가(공통 버튼 중계가 ui_click 을 낼지 판단).</summary>
|
||
public static bool UiPlayedThisFrame
|
||
{
|
||
get { return uiFrame == Time.frameCount; }
|
||
}
|
||
|
||
/// <summary>배경음악을 잠깐 낮추고 재생(승리 · 패배 · 명장 등용 ★3).</summary>
|
||
public static bool Jingle(string key)
|
||
{
|
||
if (Blocked || string.IsNullOrEmpty(key)) return false;
|
||
AudioClip clip;
|
||
var ev = Resolve(key, out clip);
|
||
if (ev == null || !GapOk(ev)) return false;
|
||
Player.PlaySfx(clip, ev.vol, Pitch(ev), clip.length);
|
||
Record(key);
|
||
return true;
|
||
}
|
||
|
||
/// <summary>배경음악(같은 이름이 이미 나오는 중이면 그대로 · 바뀌면 겹쳐 넘김).</summary>
|
||
public static bool Bgm(string key)
|
||
{
|
||
if (Blocked || string.IsNullOrEmpty(key)) return false;
|
||
if (player != null && player.BgmKey == key) return false;
|
||
AudioClip clip;
|
||
var ev = Resolve(key, out clip);
|
||
if (ev == null) return false;
|
||
Player.PlayBgm(key, clip, ev.vol);
|
||
Record(key);
|
||
return true;
|
||
}
|
||
|
||
public static void StopBgm()
|
||
{
|
||
if (player != null) player.PlayBgm(null, null, 0f);
|
||
}
|
||
|
||
/// <summary>on 이 거짓 → 참으로 바뀌는 순간에만 재생(게이지 치명타 구간 진입 · 명장 등용 문 열림).</summary>
|
||
public static void Rise(string key, bool on)
|
||
{
|
||
bool was;
|
||
rise.TryGetValue(key, out was);
|
||
rise[key] = on;
|
||
if (on && !was) Play(key);
|
||
}
|
||
|
||
/// <summary>지금 나오는 배경음악 이름(없으면 null · 시험용).</summary>
|
||
public static string CurrentBgm
|
||
{
|
||
get { return player != null ? player.BgmKey : null; }
|
||
}
|
||
}
|
||
}
|