Files
windroost/p2_godot_sample/scripts/sfx_player.gd
T
wushenghua 2408bda84d fix: audit-driven battle, perf and save correctness batch
Three parallel read-only reviews (save/boundary, perf/lifecycle, battle/economy)
produced verified findings; each was confirmed with a probe before fixing.

Battle logic:
- storm_cooldown was set to 10s on use but never decremented, disabling the
  button for the rest of every battle. Now ticks with speed-scaled delta.
  touch_input_test verifies 9.8s -> 0 after 12s.
- set_p3a_scenario ignored the per-wave seed passed to setup(), so every wave
  of a multi-wave node reused seed 10001. Now accepts an explicit seed from
  GameRoot.

Performance:
- set_roster rebuilt all hero cards every frame (~35 nodes + styleboxes/frame,
  ~2100 nodes/sec at 60fps). Now diffs by hero id and updates labels/energy
  in place; visible_node_test asserts card instance ids are unchanged across
  an identical set_roster call.
- VfxView.configure() called _ready() before add_child() triggered Godot's
  _ready() again, creating two Sprite2Ds per effect (double overdraw). Added
  an _ensure_sprite validity guard like UnitView.
- VFX manifest was reopened + JSON-parsed per effect spawn (~16/sec under held
  taps); now cached in a static.
- SfxPlayer._played (test-only telemetry) grew unbounded; capped at 64.

Save/profile:
- muted and low_power were written by settings but absent from DEFAULT_PROFILE,
  so _normalize() dropped them on every save -> settings never persisted.
  Added to defaults + migration; save_corruption_test verifies.
- An unclaimed offline report was overwritten by the next launch after any
  intervening save, silently losing earned gold. build_offline_report now
  preserves a pending report; p3b test models claim/clear between scenarios.
- hero_levels values are clamped to 1..10000 (negative/huge values gave free
  or overflowing upgrade costs) and unlocked_heroes is deduped (repeat ids
  triple-counted roster DPS).

Robustness:
- hit-stop restore coroutine now uses a generation token so a stale coroutine
  cannot end a newer hit-stop after clear_all.

Full gate P2_CHECKS_PASS. All logs still 0 script/parse errors and 0 lambda-
capture errors. prototype/ untracked.
2026-11-18 04:48:58 +08:00

193 lines
5.5 KiB
GDScript

class_name SfxPlayer
extends Node
## Audio player for the synthesized slice SFX and the seamless BGM loop.
##
## Implements the mix rules in PRODUCTION/08-audio.md that matter at runtime:
## * BGM / SFX / UI bus levels are read from the generator manifest
## * at most 3-4 simultaneous SFX (four pooled players)
## * the same SFX is rate-limited to 3 plays per second
## * +/-5% pitch jitter so repeated hits don't sound identical
## * low-power mode drops non-critical cues
## * mute is a hard gate: no player starts, BGM stops
## * BGM pauses on NOTIFICATION_APPLICATION_PAUSED and resumes on focus
const AUDIO_DIR := "res://assets/audio/"
const MANIFEST_PATH := AUDIO_DIR + "sfx_manifest.json"
const BGM_NAME := "windplain_loop"
const POOL_SIZE := 4
const RATE_LIMIT_WINDOW := 1.0
const RATE_LIMIT_MAX := 3
var muted := false
var low_power := false
var _bus_db: Dictionary = {}
var _streams: Dictionary = {}
var _bgm_stream: AudioStream
var _players: Array = []
var _bgm_player: AudioStreamPlayer
var _cursor := 0
var _played: Array[String] = []
var _played_times: Dictionary = {}
func _ready() -> void:
_load_manifest()
for i in range(POOL_SIZE):
var player := AudioStreamPlayer.new()
player.name = "Sfx%d" % i
player.bus = "Master"
add_child(player)
_players.append(player)
_bgm_player = AudioStreamPlayer.new()
_bgm_player.name = "Bgm"
_bgm_player.bus = "Master"
if _bgm_stream != null:
if _bgm_stream is AudioStreamWAV:
(_bgm_stream as AudioStreamWAV).loop_mode = AudioStreamWAV.LOOP_FORWARD
_bgm_player.stream = _bgm_stream
_bgm_player.volume_db = float(_bus_db.get("bgm", -12.0))
add_child(_bgm_player)
func _load_manifest() -> void:
var file := FileAccess.open(MANIFEST_PATH, FileAccess.READ)
if file == null:
push_warning("Audio manifest missing: %s" % MANIFEST_PATH)
_load_legacy()
return
var parsed = JSON.parse_string(file.get_as_text())
file.close()
if not parsed is Dictionary:
_load_legacy()
return
_bus_db = parsed.get("bus_db", {})
for name in parsed.get("sfx", {}).keys():
var spec: Dictionary = parsed["sfx"][name]
_streams[name] = load(AUDIO_DIR + str(spec.get("file", ""))) as AudioStream
var bgm_spec: Dictionary = parsed.get("bgm", {}).get(BGM_NAME, {})
if not bgm_spec.is_empty():
_bgm_stream = load(AUDIO_DIR + str(bgm_spec.get("file", ""))) as AudioStream
## Backward compatibility with the old eight-CLI file if manifest is absent.
func _load_legacy() -> void:
_bus_db = {"bgm": -12.0, "sfx": -6.0, "ui": -10.0}
for name in ["click", "hit", "shield_break", "ultimate", "victory", "defeat", "upgrade", "ui"]:
_streams[name] = load(AUDIO_DIR + name + ".wav") as AudioStream
_bgm_stream = load(AUDIO_DIR + "bgm_loop.wav") as AudioStream
func set_muted(value: bool) -> void:
muted = value
if muted:
stop_all()
func stop_all() -> void:
for player in _players:
var p := player as AudioStreamPlayer
p.stop()
p.stream = null
if _bgm_player != null:
_bgm_player.stop()
_bgm_player.stream = null
func set_low_power(value: bool) -> void:
low_power = value
func start_bgm() -> void:
if _bgm_player == null or _bgm_stream == null or muted:
return
if _bgm_player.stream != _bgm_stream:
if _bgm_stream is AudioStreamWAV:
(_bgm_stream as AudioStreamWAV).loop_mode = AudioStreamWAV.LOOP_FORWARD
_bgm_player.stream = _bgm_stream
_bgm_player.volume_db = float(_bus_db.get("bgm", -12.0))
if not _bgm_player.playing:
_bgm_player.play()
func stop_bgm() -> void:
if _bgm_player != null:
_bgm_player.stop()
func play(name: String, bus: String = "sfx") -> void:
if muted or _players.is_empty():
return
if low_power and name in ["click", "ui"]:
return
if not _rate_ok(name):
return
var stream: AudioStream = _streams.get(name)
if stream == null:
push_warning("Missing SFX stream: %s" % name)
return
var player: AudioStreamPlayer = _players[_cursor]
_cursor = (_cursor + 1) % _players.size()
player.stream = stream
player.volume_db = float(_bus_db.get(bus, -6.0))
player.pitch_scale = 1.0 + (randf() * 0.1 - 0.05) # +/-5% anti-fatigue
player.play()
# _played exists only for the test helper played_names(); keep it bounded so
# a long session does not accumulate one string per SFX forever.
if _played.size() >= 64:
_played.pop_front()
_played.append(name)
func _rate_ok(name: String) -> bool:
var now := Time.get_ticks_msec() / 1000.0
var times: Array = _played_times.get(name, [])
times = times.filter(func(t: float) -> bool: return now - t < RATE_LIMIT_WINDOW)
if times.size() >= RATE_LIMIT_MAX:
_played_times[name] = times
return false
times.append(now)
_played_times[name] = times
return true
func _notification(what: int) -> void:
match what:
NOTIFICATION_APPLICATION_PAUSED:
stop_bgm()
NOTIFICATION_APPLICATION_RESUMED, NOTIFICATION_APPLICATION_FOCUS_IN:
if not muted:
start_bgm()
NOTIFICATION_EXIT_TREE, NOTIFICATION_PREDELETE:
# Release loaded streams when the node leaves the tree, so a short
# lived test scene cannot leave AudioStreamWAVs alive at exit.
release_resources()
## Test helpers.
func played_names() -> Array[String]:
return _played.duplicate()
func reset_played() -> void:
_played.clear()
_played_times.clear()
func is_bgm_playing() -> bool:
return _bgm_player != null and _bgm_player.playing
func stream_count() -> int:
return _streams.size()
## Drop resource references before a test process exits. Without this, Godot
## reports the AudioStreamWAVs as "still in use at exit" because this node's
## dictionary outlives the players that loaded them.
func release_resources() -> void:
stop_all()
_streams.clear()
_bgm_stream = null