Improve phone ambience and dialogue flow; keep stairwell intact

This commit is contained in:
Codex
2026-10-30 01:03:42 +02:00
parent eaefde2e07
commit 6549ba9308
53 changed files with 1868 additions and 295 deletions
+63 -20
View File
@@ -1,6 +1,7 @@
extends Node3D
## Phone prototype: one physical task at a time; only heard facts persist.
const Profile = preload("res://scripts/profile.gd")
const Soundscape = preload("res://scripts/phone_soundscape.gd")
const SAVE_PATH := "user://profile/phone_memory.cfg"
const BG := Color("10171d")
const CARD := Color("19232c")
@@ -31,10 +32,12 @@ var busy_start := 0.0
var busy_end := 0.0
var reply_at := 0.0
var replied := false
var speech_until := 0.0
var outcome := ""
var heard: Array[String] = []
var archive: Array = []
var voice_cache: Dictionary = {}
var voice_levels: Dictionary = {}
var voice_enabled := true
var master_volume := 0.65
var ui: Control
@@ -54,7 +57,7 @@ var busy_bar: ProgressBar
var cancel_button: Button
var last_caption: Label
var voice: AudioStreamPlayer
var room: AudioStreamPlayer
var soundscape: Node
var siren: AudioStreamPlayer
var effect: AudioStreamPlayer
var hum: AudioStreamPlayer
@@ -71,6 +74,7 @@ var screen_fade: ColorRect
func _ready() -> void:
story = JSON.parse_string(FileAccess.get_file_as_string("res://data/phone_story.json"))
voice_levels = JSON.parse_string(FileAccess.get_file_as_string("res://data/voice_levels.json"))
qa_mode = "--phone-qa" in OS.get_cmdline_user_args()
if not qa_mode:
var saved := Profile.read_profile(SAVE_PATH, story.facts, story.endings)
@@ -371,7 +375,7 @@ func show_menu() -> void:
box.add_child(button("Позвонить маме" if completed == 0 else "Продолжить · звонок %d" % mini(completed + 1, 10), "start", func(): begin_call(mini(completed + 1, 10), false)))
box.add_child(button("Проверка сцен · выбрать любой из 10 звонков", "testing", show_test_menu))
box.add_child(button("Звук и титры", "settings", show_settings))
box.add_child(label("0.2.2 · Катя: Jessica · Мама: Carol · ElevenLabs\nПрогресс сохраняется после находок и законченных звонков.", 16, MUTED))
box.add_child(label("0.2.3 · Катя: Jessica · Мама: Carol · ElevenLabs\nПрогресс сохраняется после находок и законченных звонков.", 16, MUTED))
func show_settings() -> void:
var box := modal()
@@ -393,7 +397,17 @@ func show_settings() -> void:
master_volume = value
AudioServer.set_bus_volume_db(0, linear_to_db(maxf(0.0001, value))))
box.add_child(slider)
box.add_child(label("Все фразы доступны в субтитрах.\nКатя: Jessica — Playful, Bright, Warm / ElevenLabs, 48 реплик.\nМама: Carol — Relatable, Real, Likeable Grandma / ElevenLabs, 54 реплики.\nВзрыв: Synthesized explosion — qubodup / Iwan Gabovitch, CC0.\nОстальные звуки: оригинальный процедурный синтез проекта.\nПолные источники — AUDIO_CREDITS.md рядом с игрой.", 20, MUTED))
box.add_child(label("Фон и звуки окружения", 20))
var background := HSlider.new()
background.name = "BackgroundVolume"
background.min_value = 0
background.max_value = 1
background.step = 0.05
background.value = soundscape.volume
background.value_changed.connect(soundscape.set_volume)
box.add_child(background)
box.add_child(label("Во время речи фон автоматически становится тише.", 16, MUTED))
box.add_child(label("Все фразы доступны в субтитрах.\nКатя: Jessica — Playful, Bright, Warm / ElevenLabs, 52 реплики.\nМама: Carol — Relatable, Real, Likeable Grandma / ElevenLabs, 58 реплик.\nВзрыв: Synthesized explosion — qubodup / Iwan Gabovitch, CC0.\nФон и бытовые звуки: ElevenLabs Sound Effects и синтез проекта.\nПолные источники — AUDIO_CREDITS.md рядом с игрой.", 20, MUTED))
box.add_child(button("Назад", "back_menu", show_menu))
func show_test_menu() -> void:
@@ -441,10 +455,10 @@ func begin_call(number: int, testing: bool, knowledge: int = 1) -> void:
unread = 0
refresh_inbox_button()
siren.stop()
room.play()
room.volume_db = -28
soundscape.begin_call()
screen_fade.color.a = 0
elapsed = 0
speech_until = 0
place = "flat"
items = {}
done = {}
@@ -469,6 +483,7 @@ func begin_call(number: int, testing: bool, knowledge: int = 1) -> void:
refresh()
func _process(_delta: float) -> void:
soundscape.update_mix(_delta, voice_enabled and voice.playing)
if not running and not impacted: return
var second := maxf(0, (Time.get_ticks_msec() - start_tick) / 1000.0)
if running:
@@ -501,6 +516,7 @@ func advance() -> void:
kind = "finish"
if next_time > target: break
elapsed = next_time
soundscape.advance(elapsed, place)
match kind:
"impact":
fired.impact = elapsed
@@ -513,9 +529,10 @@ func advance() -> void:
"power":
fired.power = elapsed
system_caption("Свет в квартире погас. Щелчок — гул холодильника исчезает.")
room.volume_db = -35
soundscape.power_cut(elapsed)
if not busy.is_empty() and busy.get("power", false):
busy = {}
soundscape.cancel_task()
say("late_mail")
elif busy.is_empty(): say("power")
refresh_commands()
@@ -531,6 +548,7 @@ func advance() -> void:
say(busy.response)
"finish": finish_task()
elapsed = target
soundscape.advance(elapsed, place)
refresh_live()
func command_allowed(action: Dictionary) -> bool:
@@ -550,13 +568,15 @@ func command_allowed(action: Dictionary) -> bool:
func action_duration(action: Dictionary) -> float:
var length := maxf(float(action.seconds), voice_length(action.request) + voice_length(action.response) + 0.35)
if action.get("needs_light", false) and elapsed >= float(story.timeline.power) and not items.has("lamp"):
if action.get("needs_light", false) and (elapsed >= float(story.timeline.power) or place in ["landing", "alcove"]) and not items.has("lamp"):
length += 7
return length
func choose_action(id: String) -> void:
# Re-check state, time, and the visible control when a queued click arrives.
if running: elapsed = (Time.get_ticks_msec() - start_tick) / 1000.0
if running: advance()
if not can_respond(): return
if is_instance_valid(overlay): return
var control := action_button(id)
if control == null or control.disabled: return
@@ -573,14 +593,16 @@ func choose_action(id: String) -> void:
busy_end = elapsed + action_duration(selected)
reply_at = maxf(elapsed + voice_length(selected.request) + 0.15, busy_end - voice_length(selected.response))
replied = false
soundscape.schedule_task(id, elapsed + voice_length(selected.request) + 0.12, reply_at)
say(selected.request)
if selected.get("needs_light", false) and elapsed >= float(story.timeline.power) and not items.has("lamp"):
if selected.get("needs_light", false) and (elapsed >= float(story.timeline.power) or place in ["landing", "alcove"]) and not items.has("lamp"):
system_caption("Без фонаря мама будет искать на ощупь. Это займёт дольше.")
refresh_commands()
func finish_task() -> void:
var action := busy.duplicate(true)
busy = {}
soundscape.cancel_task()
done[action.id] = true
for key in action.get("learn", []):
if not facts.has(key):
@@ -596,7 +618,9 @@ func finish_task() -> void:
func cancel_task() -> void:
if not running or busy.is_empty(): return
if not speech_finished(): return
busy = {}
soundscape.cancel_task()
voice.stop()
say("cancel")
system_caption("Мама остановилась. Потраченное время не вернуть.")
@@ -614,7 +638,7 @@ func strike() -> void:
busy = {}
events.clear()
voice.stop()
room.stop()
soundscape.stop()
siren.stop()
hum.stop()
effect.stream = load("res://assets/audio/impact_cc0.wav")
@@ -692,6 +716,7 @@ func refresh_commands() -> void:
if not is_instance_valid(command_list): return
clear_children(command_list)
cancel_button.visible = running and not busy.is_empty()
cancel_button.disabled = not speech_finished()
if not running:
command_list.add_child(label("Линия молчит.", 22, MUTED))
return
@@ -700,7 +725,7 @@ func refresh_commands() -> void:
command_list.add_child(label("Вечер. Знакомый голос. Кажется, на всё ещё есть время.", 20, MUTED))
return
if not busy.is_empty():
command_list.add_child(label("Мама выполняет твою просьбу. Можно дождаться ответа или перебить её.", 22, MUTED))
command_list.add_child(label("Мама выполняет твою просьбу. Отменить её можно в паузе после реплики.", 22, MUTED))
return
var entry: Dictionary = story.chapters[chapter - 1]
if not done.has("question"):
@@ -712,18 +737,31 @@ func refresh_commands() -> void:
command_list.add_child(b)
if place == "flat" and not items.has("keys"):
command_list.add_child(label("Чтобы открыть входную дверь, мама ищет ключи.", 16, MUTED))
update_choice_state()
func speech_finished() -> bool:
return elapsed >= speech_until and (not voice_enabled or not voice.playing)
func can_respond() -> bool:
return running and chapter != 1 and events.is_empty() and speech_finished()
func update_choice_state() -> void:
for child in command_list.get_children():
if child is Button: child.disabled = not can_respond()
cancel_button.disabled = not speech_finished()
func refresh_live() -> void:
clock_label.text = "Разговор" if chapter == 1 else "%02d:%02d" % [mini(int(elapsed), 90) / 60, mini(int(elapsed), 90) % 60]
status_label.text = "Плохая связь" if place == "alcove" and not items.has("connected") else "На линии"
if not running: status_label.text = "Соединение прервано"
var names := {"flat": "В квартире", "inner": "Внутренний коридор", "landing": "Лестничная площадка", "alcove": "Боковой тамбур"}
place_label.text = names[place] + (" · темно" if fired.has("power") else "")
place_label.text = names[place] + (" · темно" if fired.has("power") or place in ["landing", "alcove"] else "")
var held: Array[String] = []
for key in items:
held.append({"keys": "ключи", "lamp": "фонарь", "spare": "запасной ключ", "connected": "телефон на полке"}[key])
objects_label.text = "У мамы: " + (", ".join(held) if not held.is_empty() else "телефон")
task_label.text = str(busy.label) if not busy.is_empty() else "Она слушает тебя"
task_label.text = str(busy.label) if not busy.is_empty() else ("Дождись окончания реплики" if not can_respond() else "Она слушает тебя")
update_choice_state()
busy_bar.visible = not busy.is_empty()
if not busy.is_empty(): busy_bar.value = clampf((elapsed - busy_start) / (busy_end - busy_start) * 100, 0, 100)
for i in range(wave_bars.size()):
@@ -754,12 +792,18 @@ func voice_length(id: String) -> float:
func say(id: String) -> void:
var entry: Dictionary = story.lines[id]
heard.append(id)
speech_until = elapsed + voice_length(id) + 0.08
update_choice_state()
add_caption(entry.speaker, entry.text)
voice.stop()
if id == "intro_04": soundscape.turn_tv_down()
if id == "intro_06": soundscape.world_cue("footsteps", elapsed + voice_length(id) + 0.1)
if voice_enabled:
voice.bus = "Phone" if entry.speaker == "Мама" else "Master"
voice.stream = voice_stream(id)
if voice.stream != null: voice.play()
if voice.stream != null:
soundscape.dialogue_started(float(voice_levels.get(id, -25.0)) - (3.0 if entry.speaker == "Мама" else 0.0))
voice.play()
func system_caption(text: String) -> void:
add_caption("", text)
@@ -782,12 +826,15 @@ func scroll_to_latest() -> void:
func make_audio() -> void:
voice = AudioStreamPlayer.new()
room = AudioStreamPlayer.new()
soundscape = Soundscape.new()
add_child(soundscape)
soundscape.setup()
siren = AudioStreamPlayer.new()
effect = AudioStreamPlayer.new()
hum = AudioStreamPlayer.new()
notification_sound = AudioStreamPlayer.new()
for player in [voice, room, siren, effect, hum, notification_sound]: add_child(player)
for player in [voice, siren, effect, hum, notification_sound]: add_child(player)
for player in [siren, effect, hum]: player.bus = "SceneAudio"
AudioServer.add_bus()
var bus := AudioServer.bus_count - 1
AudioServer.set_bus_name(bus, "Phone")
@@ -798,10 +845,6 @@ func make_audio() -> void:
AudioServer.add_bus_effect(bus, high)
AudioServer.add_bus_effect(bus, low)
voice.volume_db = -2
room.stream = load("res://assets/audio/room.wav")
room.volume_db = -28
room.finished.connect(func():
if running: room.play())
siren.stream = load("res://assets/audio/siren.wav")
siren.volume_db = -23
siren.finished.connect(func():
@@ -810,5 +853,5 @@ func make_audio() -> void:
hum.stream = load("res://assets/audio/approach.wav")
hum.volume_db = -25
notification_sound.stream = load("res://assets/audio/click.wav")
notification_sound.volume_db = -16
notification_sound.volume_db = -22
AudioServer.set_bus_volume_db(0, linear_to_db(master_volume))
+74 -6
View File
@@ -13,6 +13,10 @@ func check(ok: bool, message: String) -> void:
push_error("PHONE QA: " + message)
func click(id: String) -> void:
var gameplay := id in ["question", "cancel"]
for action in game.story.actions:
if action.id == id: gameplay = true
if gameplay: wait_for_speech()
var control: Button = game.action_button(id)
check(control != null, "Visible button: " + id)
if control != null:
@@ -20,8 +24,19 @@ func click(id: String) -> void:
control.pressed.emit()
func at(second: float) -> void:
if second >= game.speech_until: game.voice.stop()
game.start_tick = Time.get_ticks_msec() - int(second * 1000.0)
game._process(0)
if second >= game.speech_until: game.voice.stop()
game.refresh_live()
func wait_for_speech() -> void:
for step in range(12):
if game.speech_finished() and game.events.is_empty(): return
var next: float = maxf(game.elapsed, game.speech_until) + 0.01
if not game.events.is_empty(): next = maxf(next, float(game.events[0].at) + 0.01)
at(next)
check(false, "Dialogue must finish before choosing")
func perform(id: String) -> void:
click(id)
@@ -84,6 +99,11 @@ func realtime_check() -> void:
await game.get_tree().create_timer(5.0).timeout
check(game.chapter == 2 and game.running, "Production redial")
check("greeting" in game.heard and "call_02_k" in game.heard, "Production second opening")
check(game.action_button("keys_search").disabled, "Real audio keeps early answers disabled")
for frame in range(100):
if game.can_respond(): break
await game.get_tree().create_timer(0.2).timeout
check(game.can_respond() and not game.action_button("keys_search").disabled, "Real audio completion unlocks answers")
game.qa_mode = true
start(10, 2)
for id in ["keys_fast", "lamp_fast", "safe", "front", "side_open", "phone_shelf"]: perform(id)
@@ -99,7 +119,7 @@ func run(target: Node) -> void:
game = target
DirAccess.make_dir_recursive_absolute(directory())
check(game.story.chapters.size() == 10, "Ten chapters")
check(game.story.lines.size() == 102, "All 102 spoken lines")
check(game.story.lines.size() == 110, "All 110 spoken lines")
for id in game.story.lines:
check(game.voice_stream(id) != null and game.voice_length(id) > 0.1, "Playable audio " + id)
var voices: Dictionary = JSON.parse_string(FileAccess.get_file_as_string("res://data/voice_manifest.json"))
@@ -112,8 +132,8 @@ func run(target: Node) -> void:
else:
check(voices[id].provider == "ElevenLabs" and voices[id].voice_id == "5u41aNhyCU6hXOcjPPv0", "Carol assigned: " + id)
carol_count += 1
check(jessica_count == 48, "All 48 Katya lines use Jessica")
check(carol_count == 54, "All 54 mother lines use Carol")
check(jessica_count == 52, "All 52 Katya lines use Jessica")
check(carol_count == 58, "All 58 mother lines use Carol")
check(game.voice_length("greeting") <= game.story.intro[0].at, "Greeting fits before prologue")
check(45 + game.voice_length("power") <= 51, "Blackout reaction fits before conversation resumes")
check(85 + game.voice_length("hum") <= 90, "Hum reaction fits before strike")
@@ -126,6 +146,51 @@ func run(target: Node) -> void:
click("settings")
await capture("phone-credits")
click("back_menu")
start(2)
var blocked: Button = game.action_button("keys_search")
check(blocked != null and blocked.disabled, "Choices visible but disabled during greeting")
await capture("phone-locked-answers")
blocked.pressed.emit()
game.choose_action("keys_search")
check(game.busy.is_empty() and game.heard == ["greeting"], "Early clicks cannot cut off a speaker")
at(game.speech_until - 0.02)
check(game.action_button("keys_search").disabled, "Still blocked before audio end")
wait_for_speech()
check(not game.action_button("keys_search").disabled, "Choices enabled after complete opening exchange")
click("keys_search")
check(game.cancel_button.disabled, "Cancellation cannot interrupt the spoken request")
game.cancel_task()
check(not game.busy.is_empty(), "Direct cancel rejected while speaking")
at(game.reply_at + 0.01)
check(game.cancel_button.disabled, "Mother's answer cannot be interrupted")
at(game.busy_end + 0.12)
check(game.can_respond(), "Next choices enabled after response and task completion")
start(1)
check(game.soundscape.streams.size() == 16, "All ambience and foley assets loaded")
check(game.soundscape.beds.fridge.playing and game.soundscape.beds.tv.playing, "Powered room starts alive")
check(game.soundscape.duck_db <= -11.9, "Background ducks under spoken greeting")
game.soundscape.update_mix(0.5, false)
check(game.soundscape.duck_db > -11 and game.soundscape.duck_db < 0, "Background recovers gently after speech")
game.soundscape.dialogue_started(-40)
check(game.soundscape.duck_db <= -23.9, "Very quiet voices receive extra background attenuation")
game.soundscape.set_volume(0)
check(AudioServer.get_bus_volume_db(game.soundscape.scene_bus) <= -79, "Independent background mute")
game.soundscape.set_volume(0.75)
at(36.1)
check(game.soundscape.history.any(func(cue): return cue.id == "kettle"), "Kettle follows the shared call clock")
at(45.01)
check(not game.soundscape.beds.fridge.playing and not game.soundscape.beds.tv.playing, "Power cut silences appliances")
check(game.soundscape.beds.room.playing and game.soundscape.beds.line.playing, "Room and telephone survive power cut")
finish("flat")
check(not game.soundscape.active and game.soundscape.queue.is_empty(), "Strike stops room and all pending sounds")
start(2)
perform("keys_search")
check(game.soundscape.history.any(func(cue): return cue.id == "keys"), "Key sound follows actual search")
click("lamp_search")
wait_for_speech()
click("cancel")
check(not game.soundscape.queue.any(func(cue): return cue.task), "Cancel discards pending action sounds")
# Every redial repeats the same external world, including the first call.
for number in range(1, 11):
start(number)
@@ -166,7 +231,7 @@ func run(target: Node) -> void:
check(game.action_button("keys_search") == null, "Prologue has no commands")
check(game.clock_label.text == "Разговор", "Prologue hides time")
for beat in game.story.intro: at(beat.at + 0.01)
check(game.heard.size() == 11 and "power" in game.heard, "Ordinary conversation and blackout acknowledgement")
check(game.heard.size() == 19 and "power" in game.heard, "Ordinary conversation and blackout acknowledgement")
else:
var entry: Dictionary = game.story.chapters[number - 1]
var opening_at: float = game.events[0].at
@@ -249,7 +314,9 @@ func run(target: Node) -> void:
perform("keys_search")
perform("front")
perform("stairs")
check(game.facts.has("stairs"), "Blocked stairs discovered")
check(game.facts.has("stairs"), "Unlit intact stairs discovered")
check("целая" in game.story.facts.stairs and "завален" not in game.story.facts.stairs, "Stairwell is intact")
await capture("phone-dark-stairwell")
finish("landing")
# Full route with learned facts is feasible at normal production durations,
@@ -358,7 +425,8 @@ func run(target: Node) -> void:
file.close()
print("PHONE_QA ", "PASS" if errors.is_empty() else "FAIL", " checks=", checks, " route=", route_time, " errors=", errors)
await render()
for player in [game.voice, game.room, game.siren, game.effect, game.hum, game.notification_sound]:
game.soundscape.stop()
for player in [game.voice, game.siren, game.effect, game.hum, game.notification_sound]:
player.stop()
player.stream = null
await game.get_tree().create_timer(0.1).timeout
@@ -0,0 +1,162 @@
extends Node
## Separate world, task and speech layers. All scheduling uses the call clock.
const ROOT := "res://assets/audio/call/"
const DUCK_DB := -12.0
var streams: Dictionary = {}
var beds: Dictionary = {}
var players: Array[AudioStreamPlayer] = []
var queue: Array = []
var history: Array = []
var active := false
var powered := true
var tv_quiet := false
var location := "flat"
var volume := 0.75
var duck_db := 0.0
var speech_duck := DUCK_DB
var scene_bus := -1
func setup() -> void:
AudioServer.add_bus()
scene_bus = AudioServer.bus_count - 1
AudioServer.set_bus_name(scene_bus, "SceneAudio")
AudioServer.add_bus()
var phone_bus := AudioServer.bus_count - 1
AudioServer.set_bus_name(phone_bus, "CallBackground")
AudioServer.set_bus_send(phone_bus, "SceneAudio")
var high := AudioEffectHighPassFilter.new()
high.cutoff_hz = 180
var low := AudioEffectLowPassFilter.new()
low.cutoff_hz = 3200
AudioServer.add_bus_effect(phone_bus, high)
AudioServer.add_bus_effect(phone_bus, low)
var manifest: Array = JSON.parse_string(FileAccess.get_file_as_string("res://data/sound_manifest.json"))
for entry in manifest:
var stream := load("res://" + str(entry.file)) as AudioStreamWAV
if entry.loop:
stream = stream.duplicate()
stream.loop_mode = AudioStreamWAV.LOOP_FORWARD
stream.loop_end = int(stream.get_length() * stream.mix_rate)
streams[entry.id] = stream
for id in ["room", "fridge", "tv", "line"]:
var player := AudioStreamPlayer.new()
player.bus = "CallBackground"
player.stream = streams[id]
add_child(player)
beds[id] = player
for i in range(3):
var player := AudioStreamPlayer.new()
player.bus = "CallBackground"
add_child(player)
players.append(player)
apply_volume()
func begin_call() -> void:
stop()
active = true
powered = true
tv_quiet = false
location = "flat"
duck_db = 0
history.clear()
queue = [{"at": 36.0, "id": "kettle", "task": false}]
for player in beds.values(): player.play()
update_location("flat")
apply_volume()
func stop() -> void:
active = false
queue.clear()
for player in beds.values(): player.stop()
for player in players: player.stop()
func update_location(where: String) -> void:
location = where
var distance := 0.0 if where == "flat" else (-8.0 if where == "inner" else -16.0)
beds.room.volume_db = -12 + distance * 0.35
beds.line.volume_db = -24
beds.fridge.volume_db = -12 + distance
beds.tv.volume_db = -18 + distance + (-10.0 if tv_quiet else 0.0)
func turn_tv_down() -> void:
tv_quiet = true
update_location(location)
func world_cue(id: String, at: float) -> void:
queue.append({"at": at, "id": id, "task": false})
queue.sort_custom(func(a, b): return a.at < b.at)
func power_cut(now: float) -> void:
powered = false
beds.fridge.stop()
beds.tv.stop()
for player in players:
if player.get_meta("sound", "") == "kettle": player.stop()
queue = queue.filter(func(cue): return cue.id != "kettle")
play_cue("switch", now, false)
func cancel_task() -> void:
queue = queue.filter(func(cue): return not cue.task)
for player in players:
if player.get_meta("task", false): player.stop()
func schedule_task(id: String, start: float, reply: float) -> void:
cancel_task()
var patterns := {
"look": ["cloth"], "keys_search": ["cloth", "keys"], "keys_fast": ["keys"],
"lamp_search": ["drawer", "cloth", "switch"], "lamp_fast": ["drawer", "switch"],
"read_mail": ["keyboard"], "safe": ["safe", "paper"],
"front": ["keys", "door", "footsteps"], "stairs": ["footsteps"],
"side_try": ["keys", "door"], "side_open": ["door", "footsteps"],
"inner": ["footsteps"], "back": ["footsteps"], "neighbor": ["knock"],
"phone_test": ["phone", "footsteps"], "phone_shelf": ["phone"],
}
var sounds: Array = patterns.get(id, [])
for i in range(sounds.size()):
var at := lerpf(start, maxf(start, reply - 0.5), float(i) / maxf(1, sounds.size() - 1))
queue.append({"at": at, "id": sounds[i], "task": true})
queue.sort_custom(func(a, b): return a.at < b.at)
func advance(now: float, where: String) -> void:
if not active: return
update_location(where)
while not queue.is_empty() and float(queue[0].at) <= now:
var cue: Dictionary = queue.pop_front()
history.append({"id": cue.id, "at": cue.at, "task": cue.task})
# Don't replay stale sounds after a long frame or a QA clock jump.
var offset := now - float(cue.at)
if offset < streams[cue.id].get_length(): play_cue(cue.id, now, cue.task, offset)
func play_cue(id: String, _now: float, task: bool, offset: float = 0.0) -> void:
if not active: return
var player := players[0]
for candidate in players:
if not candidate.playing:
player = candidate
break
player.stop()
player.set_meta("sound", id)
player.set_meta("task", task)
player.stream = streams[id]
player.volume_db = -14 if id != "kettle" else -15
player.play(offset)
func dialogue_started(rms_db: float = -25.0) -> void:
# Keep soft performances soft; make the world quieter instead of boosting voices.
speech_duck = clampf(DUCK_DB + minf(0, rms_db + 28.0), -24.0, DUCK_DB)
duck_db = speech_duck
apply_volume()
func update_mix(delta: float, speaking: bool) -> void:
var goal := speech_duck if speaking else 0.0
var response := 0.035 if speaking else 0.65
duck_db = lerpf(duck_db, goal, 1.0 - exp(-maxf(0, delta) / response))
apply_volume()
func set_volume(value: float) -> void:
volume = clampf(value, 0, 1)
apply_volume()
func apply_volume() -> void:
if scene_bus >= 0:
AudioServer.set_bus_volume_db(scene_bus, -80.0 if volume == 0 else linear_to_db(volume) + duck_db)