harvest/game/scripts/dialogue_box.gd
Forrest 49e94874a6 #39: tappable HUD
On phones (MobilePort.active()) the HUD's widgets take taps through small
STOP hit targets (ScarecrowHud.HitTarget, at least minimum_target()), and
everything beside them is still the thumbsticks':
- hotbar: a tap on a main slot picks it through the number keys' path
  (weapon_k, applied only when combat may switch); no number keys on phones
  (Prompts.hotbar_key)
- backpack: a tap toggles the pouch panel, a finger elsewhere (not on the
  panel) closes it; the panel stays inside safe_rect
- tip box: an × hides tips as Backspace does (Tutorial.hide_tips)
- dialogue: a Skip button on pausing conversations; a tap elsewhere advances
Desktop has no targets and draws as before. Test: mobile/hud_taps_test.gd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:10:56 -04:00

509 lines
18 KiB
GDScript

class_name DialogueBox
extends Control
## The talking-head box: a conversation (Conversation) one line at a time on a sheet of paper like
## the morning sign's (Sketch.paper, nailed at its top corners) above the hotbar, the speaker's
## name over their words on their side of it, and their picture (the talking head) standing behind
## the paper's top edge on that side. A new speaker's head rises from behind the paper (the last
## one's sinks back); while the words are written, letter by letter (a beat longer after a comma
## or a full stop), the head bobs, flaps its mouth (DialogueSpeaker.talk_frames), and blips
## (voice); then it breathes, and a pen arrow bobs in the corner. A line without a speaker is
## narration: words only.
## Click, [Enter / Space / E] or (A) writes the rest of the line, then goes on to the next;
## [Backspace / Back] skips the rest of the conversation. One that doesn't pause the game takes no
## input and goes on by itself (Conversation.line_hold). Works while the game is paused
## (DialogueDirector pauses it for a conversation); waits while blocked (a menu is up over it).
## On a phone (MobilePort.active()) a tap is the click, and a conversation that pauses the game
## has a Skip button on the paper (a ScarecrowHud.HitTarget) that skips it, as Backspace does.
signal finished(conversation: Conversation)
## The paper's size and its gap above the screen's bottom (the hotbar is under it).
const WIDTH := 1360.0
const HEIGHT := 350.0
const BOTTOM := 118.0
const SIDE_GAP := 40.0
## The name's and words' inset from the paper's edges.
const MARGIN := Vector2(64.0, 30.0)
## A head stands this far in from the paper's side, its bottom TUCK behind the paper.
const HEAD_INSET := 30.0
const TUCK := 44.0
const RISE_TIME := 0.25
const OPEN_TIME := 0.18
## A beat after these letters, when a space or the end follows.
const PAUSES := {".": 0.32, "!": 0.32, "?": 0.32, "…": 0.32, ",": 0.14, ";": 0.14, ":": 0.14}
const TALK_FPS := 9.0
const SEED := 701.0
## Phones: the Skip button drawn on the paper (its hit target may be bigger), its right edge and
## bottom this far in from the paper's bottom-right corner (left of the pen arrow).
const SKIP_SIZE := Vector2(118.0, 50.0)
const SKIP_INSET := Vector2(104.0, 26.0)
const SKIP_FONT := 30
## Optional: whether a menu is up over the box (it waits: no input, no writing).
var blocked: Callable
## The conversation up (null when none), and its line on the paper.
var conversation: Conversation
var index: int = -1
## Phones: the Skip button (null on desktop), shown while a conversation pauses the game.
var skip_target: ScarecrowHud.HitTarget
static var _narrator := DialogueSpeaker.new()
static var _variants := {} # "font id/slant/bold" -> FontVariation
var _stage: Control
var _sheet: Control
var _name: Label
var _text: RichTextLabel
var _more: Control
var _voice: AudioStreamPlayer
var _heads: Array[Head] = []
var _speaker: DialogueSpeaker
var _plain := ""
var _shown: int = 0
var _speed := 0.0
var _budget := 0.0
var _wait := 0.0
var _hold := 0.0
var _letters: int = 0
var _open := 0.0
var _closing := false
var _time := 0.0
var _focus_before: Control
## A speaker's head on the stage: rising in (risen 0 -> 1) or sinking away (leaving).
class Head:
var speaker: DialogueSpeaker
var face: Texture2D
var risen := 0.0
var leaving := false
var talking := false
func _ready() -> void:
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
process_mode = Node.PROCESS_MODE_ALWAYS
mouse_filter = Control.MOUSE_FILTER_IGNORE
_stage = Control.new()
_stage.clip_contents = true # a sunk head is out of sight below the paper's top
_stage.mouse_filter = Control.MOUSE_FILTER_IGNORE
_stage.draw.connect(_draw_heads)
add_child(_stage)
_sheet = Control.new()
_sheet.mouse_filter = Control.MOUSE_FILTER_IGNORE
_sheet.draw.connect(_draw_sheet)
add_child(_sheet)
_name = Label.new()
_name.mouse_filter = Control.MOUSE_FILTER_IGNORE
_sheet.add_child(_name)
_text = RichTextLabel.new()
_text.bbcode_enabled = true
_text.scroll_active = false
_text.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_text.visible_characters_behavior = TextServer.VC_CHARS_AFTER_SHAPING # words don't jump lines as they're written
_text.mouse_filter = Control.MOUSE_FILTER_IGNORE
_sheet.add_child(_text)
_more = Control.new()
_more.mouse_filter = Control.MOUSE_FILTER_IGNORE
_more.size = Vector2(40.0, 40.0)
_more.draw.connect(_draw_more)
_sheet.add_child(_more)
if MobilePort.active():
skip_target = ScarecrowHud.HitTarget.new()
skip_target.name = "Skip"
skip_target.visible = false
skip_target.tapped.connect(_on_skip_tapped)
skip_target.draw.connect(_draw_skip)
_sheet.add_child(skip_target)
_voice = AudioStreamPlayer.new()
_voice.bus = &"SFX"
add_child(_voice)
visible = false
## Shows conversation c from its first line, over whatever was up. Returns false (and shows
## nothing) when it has no lines.
func play(c: Conversation) -> bool:
if c == null or c.lines.is_empty():
return false
conversation = c
_closing = false
visible = true
_take_input(c.pause_game)
_show_line(0)
_place()
return true
func is_playing() -> bool:
return conversation != null
func is_blocked() -> bool:
return blocked.is_valid() and bool(blocked.call())
## Whether the line on the paper is all written.
func is_written() -> bool:
return _shown >= _plain.length()
## The words on the paper as written so far (no BBCode), for tests.
func written_text() -> String:
return _plain.substr(0, _shown)
func speaker_name() -> String:
return _name.text
## Writes the rest of the line, or goes on to the next one (after the last: closes).
func advance() -> void:
if conversation == null:
return
if not is_written():
_shown = _plain.length()
_wait = 0.0
_text.visible_characters = -1
return
if index + 1 < conversation.lines.size():
_show_line(index + 1)
else:
_finish()
## Skips the rest of the conversation.
func skip() -> void:
if conversation != null:
_finish()
## Takes the box away at once, without finished.
func stop() -> void:
if conversation != null:
_take_input(false)
conversation = null
_closing = false
_heads.clear()
_open = 0.0
visible = false
func _finish() -> void:
var c := conversation
conversation = null
_closing = true # the paper fades and the head sinks, unless the next conversation starts now
_take_input(false)
finished.emit(c)
func _show_line(i: int) -> void:
index = i
var line := conversation.lines[i]
_speaker = line.speaker if line.speaker != null else _narrator
_style(line, _speaker)
_text.text = _bbcode(line, _speaker)
_text.visible_characters = 0
_plain = _text.get_parsed_text()
_shown = 0
_budget = 0.0
_wait = 0.0
_letters = 0
_hold = conversation.line_hold()
_speed = line.letters_per_second if line.letters_per_second > 0.0 else _speaker.letters_per_second
if _speed <= 0.0:
advance() # all at once
_set_head(_speaker, line.portrait if line.portrait != null else _speaker.portrait)
func _style(line: DialogueLine, sp: DialogueSpeaker) -> void:
var font: Font = sp.font if sp.font != null else Sketch.font()
_name.text = sp.display_name
_name.visible = sp.display_name != ""
_name.add_theme_font_override("font", font)
_name.add_theme_font_size_override("font_size", sp.name_size)
_name.add_theme_color_override("font_color", sp.name_color)
_name.add_theme_constant_override("outline_size", 0)
_name.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT if sp.side == DialogueSpeaker.HeadSide.RIGHT else HORIZONTAL_ALIGNMENT_LEFT
_text.add_theme_font_override("normal_font", font)
_text.add_theme_font_override("italics_font", _variant(font, true, false))
_text.add_theme_font_override("bold_font", _variant(font, false, true))
_text.add_theme_font_override("bold_italics_font", _variant(font, true, true))
var font_size := line.font_size if line.font_size > 0 else sp.font_size
for key: String in ["normal_font_size", "italics_font_size", "bold_font_size", "bold_italics_font_size"]:
_text.add_theme_font_size_override(key, font_size)
_text.add_theme_color_override("default_color", line.text_color if line.text_color.a > 0.0 else sp.text_color)
_text.add_theme_constant_override("line_separation", 2)
match sp.align:
DialogueSpeaker.Align.LEFT:
_text.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT
DialogueSpeaker.Align.CENTER:
_text.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
DialogueSpeaker.Align.RIGHT:
_text.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
_:
_text.horizontal_alignment = _name.horizontal_alignment
static func _bbcode(line: DialogueLine, sp: DialogueSpeaker) -> String:
var t := line.text
if line.italic or sp.italic:
t = "[i]%s[/i]" % t
if line.bold or sp.bold:
t = "[b]%s[/b]" % t
return t
## The font slanted (italics) and / or heavier (bold), for fonts without those faces (the
## handwritten one has neither).
static func _variant(base: Font, slant: bool, bold: bool) -> Font:
var key := "%d/%s/%s" % [base.get_instance_id(), slant, bold]
if not _variants.has(key):
var v := FontVariation.new()
v.base_font = base
if slant:
v.variation_transform = Transform2D(Vector2(1.0, 0.25), Vector2(0.0, 1.0), Vector2.ZERO)
if bold:
v.variation_embolden = 0.8
_variants[key] = v
return _variants[key]
## The speaker's head takes the stage (a new speaker's rises, the last one's sinks), unless
## they're already on it; a line can change their face.
func _set_head(sp: DialogueSpeaker, face: Texture2D) -> void:
var current := _current_head()
if current != null and current.speaker == sp:
current.face = face
return
if current != null:
current.leaving = true
if face == null and sp.icon == "":
return # narration, or nobody to show
var h := Head.new()
h.speaker = sp
h.face = face
_heads.append(h)
func _current_head() -> Head:
for i in range(_heads.size() - 1, -1, -1):
if not _heads[i].leaving:
return _heads[i]
return null
func _take_input(on: bool) -> void:
mouse_filter = Control.MOUSE_FILTER_STOP if on else Control.MOUSE_FILTER_IGNORE
focus_mode = Control.FOCUS_ALL if on else Control.FOCUS_NONE # (NONE lets the focus go)
if on:
var had := get_viewport().gui_get_focus_owner()
if had != self:
_focus_before = had
grab_focus() # keys come here first: Enter doesn't press the morning sign's button under it
elif is_instance_valid(_focus_before) and _focus_before.is_visible_in_tree() and _focus_before.focus_mode != Control.FOCUS_NONE:
_focus_before.grab_focus()
_focus_before = null
func _process(delta: float) -> void:
if not visible or is_blocked():
return
_time += delta
_open = move_toward(_open, 0.0 if _closing else 1.0, delta / OPEN_TIME)
var staying: Array[Head] = []
for h in _heads:
var going := h.leaving or _closing
h.risen = move_toward(h.risen, 0.0 if going else 1.0, delta / RISE_TIME)
if h.risen > 0.0 or not going:
staying.append(h)
_heads = staying
if _closing:
if _open <= 0.0 and _heads.is_empty():
visible = false
else:
if conversation.pause_game and not has_focus():
grab_focus() # back from a menu over it
_write(delta)
_place()
## Writes letters at the speaker's speed (with a beat after a comma or a full stop), and goes
## on by itself once the line's been up long enough (Conversation.line_hold).
func _write(delta: float) -> void:
var head := _current_head()
var total := _plain.length()
if _shown >= total:
if head != null:
head.talking = false
_hold -= delta
if _hold <= 0.0:
advance()
return
if head != null:
head.talking = _wait <= 0.0
if _wait > 0.0:
_wait -= delta
return
_budget += delta * _speed
while _budget >= 1.0 and _shown < total:
_budget -= 1.0
_shown += 1
var ch := _plain[_shown - 1]
if ch != " " and ch != "\n":
_letters += 1
if _speaker.voice != null and (_letters - 1) % _speaker.voice_every == 0:
_voice.stream = _speaker.voice
_voice.pitch_scale = _speaker.voice_pitch * randf_range(0.92, 1.08)
_voice.volume_db = _speaker.voice_volume_db
_voice.play()
var beat: float = PAUSES.get(ch, 0.0)
if beat > 0.0 and (_shown == total or _plain[_shown] == " " or _plain[_shown] == "\n"):
_wait = beat
_budget = 0.0
break
_text.visible_characters = _shown if _shown < total else -1
## Lays the paper out over the hotbar (sliding up and fading in as it opens) and the stage above
## it, down to TUCK under the paper's top edge.
func _place() -> void:
var r := _sheet_rect()
var k := _ease(_open)
_sheet.position = r.position + Vector2(0.0, (1.0 - k) * 30.0)
_sheet.size = r.size
_sheet.modulate.a = k
_stage.position = Vector2.ZERO
_stage.size = Vector2(size.x, r.position.y + TUCK)
var name_h := _name.get_minimum_size().y if _name.visible else 0.0
var inner := r.size.x - 2.0 * MARGIN.x
_name.position = MARGIN
_name.size = Vector2(inner, name_h)
var top := MARGIN.y + name_h + (8.0 if _name.visible else 0.0)
_text.position = Vector2(MARGIN.x, top)
_text.size = Vector2(inner, r.size.y - top - 36.0)
_more.position = Vector2(r.size.x - 50.0 - _more.size.x, r.size.y - 30.0 - _more.size.y)
_more.visible = conversation != null and conversation.pause_game and is_written()
if skip_target != null:
skip_target.visible = conversation != null and conversation.pause_game
skip_target.cover(skip_rect())
skip_target.queue_redraw()
_stage.queue_redraw()
_more.queue_redraw()
## Phones: where the Skip button is drawn on the paper (the sheet's coordinates).
func skip_rect() -> Rect2:
var r := _sheet_rect()
return Rect2(r.size - SKIP_INSET - SKIP_SIZE, SKIP_SIZE)
func _on_skip_tapped() -> void:
if conversation != null and conversation.pause_game and not is_blocked():
skip()
func _sheet_rect() -> Rect2:
var w := minf(WIDTH, size.x - 2.0 * SIDE_GAP)
return Rect2((size.x - w) * 0.5, size.y - BOTTOM - HEIGHT, w, HEIGHT)
static func _ease(t: float) -> float:
return 1.0 - pow(1.0 - clampf(t, 0.0, 1.0), 3.0)
func _gui_input(event: InputEvent) -> void:
if _press(event):
accept_event()
func _unhandled_input(event: InputEvent) -> void:
if _press(event):
get_viewport().set_input_as_handled()
## A press that goes on (or skips), while the box takes input. Returns whether it was used.
func _press(event: InputEvent) -> bool:
if conversation == null or not conversation.pause_game or event.is_echo() or is_blocked():
return false
if event.is_action_pressed("hide_tips"):
skip()
return true
var mb := event as InputEventMouseButton
if (mb != null and mb.pressed and mb.button_index == MOUSE_BUTTON_LEFT) or event.is_action_pressed("ui_accept") \
or event.is_action_pressed("interact"):
advance()
return true
return false
## The sheet of paper, nailed at its top corners as on the morning sign.
func _draw_sheet() -> void:
var r := Rect2(Vector2.ZERO, _sheet.size)
Sketch.paper(_sheet, r, SEED)
for x: float in [30.0, r.size.x - 30.0]:
Sketch.nail(_sheet, Vector2(x, 26.0))
## The heads, their feet TUCK under the paper's top edge: rising or sinking, bobbing while they
## talk (their mouth flapping when they have talk frames), breathing when they're done.
func _draw_heads() -> void:
var r := _sheet_rect()
for h in _heads:
var sp := h.speaker
var face := _frame(h)
var tall := sp.portrait_height
var wide := tall * face.get_size().aspect() if face != null else tall
var x := r.position.x + HEAD_INSET if sp.side == DialogueSpeaker.HeadSide.LEFT else r.end.x - HEAD_INSET - wide
var lift := 0.0
var tilt := 0.0
var stretch := 1.0
if h.talking:
lift = absf(sin(_time * 10.0)) * 8.0
tilt = sin(_time * 5.0) * 0.03
else:
stretch = 1.0 + sin(_time * 2.2) * 0.008
var foot := Vector2(x + wide * 0.5, _stage.size.y + (1.0 - _ease(h.risen)) * (tall + 20.0) - lift) + sp.portrait_offset
if face != null:
_stage.draw_set_transform(foot, tilt, Vector2(-1.0 if sp.flip else 1.0, stretch))
_stage.draw_texture_rect(face, Rect2(-wide * 0.5, -tall, wide, tall), false)
_stage.draw_set_transform_matrix(Transform2D.IDENTITY)
else:
Sketch.icon(_stage, sp.icon, Rect2(foot - Vector2(wide * 0.5, tall * stretch), Vector2(wide, tall * stretch)))
## The head's picture now: its face, or while it talks (with its usual face) its mouth flaps.
func _frame(h: Head) -> Texture2D:
var sp := h.speaker
if not h.talking or sp.talk_frames.is_empty() or h.face != sp.portrait:
return h.face
var k := int(_time * TALK_FPS) % (sp.talk_frames.size() + 1)
return h.face if k == 0 else sp.talk_frames[k - 1]
## Phones: the Skip button, a pen-drawn box on the paper with the word and a double arrow.
func _draw_skip() -> void:
var ink := Sketch.PAPER_INK
var r := Rect2((skip_target.size - SKIP_SIZE) * 0.5, SKIP_SIZE)
Sketch.box(skip_target, r, Color(Sketch.PAPER.darkened(0.1), 0.9), Color(ink, 0.85), 2.0, SEED + 21.0)
var word := Sketch.text_width("Skip", SKIP_FONT)
var arrows := 26.0
var x := r.get_center().x - (word + 8.0 + arrows) * 0.5
var f := Sketch.font()
var top := r.get_center().y - (f.get_ascent(SKIP_FONT) + f.get_descent(SKIP_FONT)) * 0.5
Sketch.text(skip_target, Vector2(x, top), "Skip", SKIP_FONT, ink, HORIZONTAL_ALIGNMENT_LEFT, 0)
var c := Vector2(x + word + 8.0, r.get_center().y)
for k in 2:
var a := c + Vector2(k * 12.0, 0.0)
var tip := PackedVector2Array([a + Vector2(0.0, -9.0), a + Vector2(13.0, 0.0), a + Vector2(0.0, 9.0)])
skip_target.draw_colored_polygon(tip, Color(ink, 0.85))
Sketch.outline(skip_target, tip, ink, 1.5, SEED + 30.0 + k, 0.6, 1)
## The pen arrow in the corner when the line is written and the player goes on.
func _draw_more() -> void:
var ink: Color = _text.get_theme_color("default_color")
var c := _more.size * 0.5 + Vector2(0.0, sin(_time * 5.0) * 4.0)
var tip := PackedVector2Array([c + Vector2(-13.0, -8.0), c + Vector2(13.0, -8.0), c + Vector2(0.0, 11.0)])
_more.draw_colored_polygon(tip, Color(ink, 0.85))
Sketch.outline(_more, tip, ink, 2.0, SEED + 9.0, 0.8, 1)