Files
sor/Client/origin-client/autoloads/Music.gd
T
3810742fe6 Feature: leaderboard hide, ability animations, card sounds, BGM, in-game settings
Server:
- Account.IsHiddenFromLeaderboard: filter bots/devs from leaderboard
- AbilityAnimationDefinition: type, effect, dimensions, asset/sound URLs per ability
- CardAnimationBinding: CastSoundCdnUrl + ImpactSoundCdnUrl per card action
- GameAudioConfig entity: admin-configurable BGM tracks per context
- GetGameAudioConfigHandler (content.get_audio_config) + ServiceRegistration
- Admin pages: AccountDetail toggle, AudioConfig CRUD, CardEditor + AbilityBuilder UI
- Migrations: AddLeaderboardHide, AddCardActionSounds, AddGameAudioConfig

Client:
- Music.gd autoload: fetches BGM config, crossfades between context tracks
- InGameSettings overlay: audio sliders, camera follow toggle, concede with confirm
- GameScreen: gear button opens settings; ConcedeBtn moved into settings panel
- project.godot: Music autoload registered

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
2026-03-13 23:31:10 -04:00

154 lines
5.4 KiB
GDScript

extends Node
## Music autoload — fetches BGM config from the server and plays context-appropriate tracks.
##
## Usage:
## Music.play_context("Game") # start/crossfade to the Game context track
## Music.play_context("Lobby") # switch to Lobby context
## Music.stop() # fade out and stop
##
## Volume and mute are controlled via Settings.music_volume / Settings.music_muted.
## This node streams audio via an AudioStreamPlayer on the "Music" bus.
const CROSSFADE_DURATION := 1.2 # seconds
const CONTEXT_AUDIO_MSG := "content.get_audio_config"
## _tracks[context] = Array of { "name": String, "url": String }
var _tracks : Dictionary = {}
var _current_context: String = ""
var _player_a : AudioStreamPlayer
var _player_b : AudioStreamPlayer
var _active_player : AudioStreamPlayer # the one currently audible
# ── Lifecycle ─────────────────────────────────────────────────────────────────
func _ready() -> void:
_player_a = _make_player()
_player_b = _make_player()
_active_player = _player_a
# Fetch BGM config once at startup (connection must be established by then).
# Scenes that start music will typically call play_context after login.
func _make_player() -> AudioStreamPlayer:
var p := AudioStreamPlayer.new()
p.bus = Settings.BUS_MUSIC
p.volume_db = linear_to_db(Settings.music_volume) if not Settings.music_muted else -80.0
add_child(p)
return p
# ── Public API ─────────────────────────────────────────────────────────────────
## Fetch the BGM track list from the server.
## Call this once after the player is authenticated and connected.
func fetch_config() -> void:
Network.request(CONTEXT_AUDIO_MSG, {},
func(_type: String, resp: Variant) -> void:
var d := resp as Dictionary
if not d.has("tracks"):
return
_tracks.clear()
for t: Dictionary in d.get("tracks", []):
var ctx : String = str(t.get("context", ""))
if ctx.is_empty():
continue
if not _tracks.has(ctx):
_tracks[ctx] = []
_tracks[ctx].append({
"name": str(t.get("trackName", "")),
"url": str(t.get("trackCdnUrl", "")),
}),
func(code: String, msg: String) -> void:
push_warning("Music: fetch_config failed — %s: %s" % [code, msg]))
## Start playing a track for the given context.
## Crossfades from the currently playing track. No-ops if already on this context.
func play_context(ctx: String) -> void:
if ctx == _current_context:
return
_current_context = ctx
var list : Array = _tracks.get(ctx, [])
if list.is_empty():
stop()
return
var entry : Dictionary = list[randi() % list.size()]
var url : String = str(entry.get("url", ""))
if url.is_empty():
return
_crossfade_to(url)
## Stop music with a short fade-out.
func stop() -> void:
_current_context = ""
_fade_out(_active_player)
# ── Internal ──────────────────────────────────────────────────────────────────
func _crossfade_to(url: String) -> void:
var next : AudioStreamPlayer = _player_b if _active_player == _player_a else _player_a
# Load stream from URL (Godot's ResourceLoader supports http URLs if configured,
# otherwise fall back to local path for bundled tracks).
var stream := await _load_stream(url)
if stream == null:
return
next.stream = stream
next.volume_db = -80.0
next.play()
var tween := create_tween().set_parallel(true)
tween.tween_property(next, "volume_db",
linear_to_db(Settings.music_volume) if not Settings.music_muted else -80.0,
CROSSFADE_DURATION)
tween.tween_property(_active_player, "volume_db", -80.0, CROSSFADE_DURATION)
await tween.finished
_active_player.stop()
_active_player = next
func _fade_out(player: AudioStreamPlayer) -> void:
if not player.playing:
return
var tween := create_tween()
tween.tween_property(player, "volume_db", -80.0, CROSSFADE_DURATION)
await tween.finished
player.stop()
func _load_stream(url: String) -> AudioStream:
# If it looks like a local resource path, load directly.
if url.begins_with("res://") or url.begins_with("user://"):
return load(url) as AudioStream
# For CDN URLs: use HTTPRequest to download and create stream from bytes.
# This is an async download approach compatible with Godot 4.
var http := HTTPRequest.new()
add_child(http)
http.request(url)
var result : Array = await http.request_completed
http.queue_free()
var response_code : int = result[1]
var body : PackedByteArray = result[3]
if response_code != 200 or body.is_empty():
push_warning("Music: failed to download %s (HTTP %d)" % [url, response_code])
return null
# Determine format from URL extension and create appropriate stream.
var ext := url.get_extension().to_lower()
if ext == "ogg":
return AudioStreamOggVorbis.load_from_buffer(body)
elif ext in ["mp3"]:
var stream := AudioStreamMP3.new()
stream.data = body
return stream
elif ext == "wav":
# WAV loading from bytes is not directly supported; warn and return null.
push_warning("Music: WAV from URL not supported. Use OGG or MP3.")
return null
push_warning("Music: unknown audio format '%s'" % ext)
return null