-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDialogueTextLabel.gd
More file actions
506 lines (351 loc) · 13 KB
/
DialogueTextLabel.gd
File metadata and controls
506 lines (351 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
extends RichTextLabel
class_name DialogueTextLabel
signal line_finished
signal advance_dialog
const WORDJOINER := "" # Invisible character
var regex := RegEx.new() as RegEx
var text_speed_multiplier := 1.0
var timer := 0.0
var pause_buffer := 0
var realtime_wait := 0.0
var skipping_line := false
var processed_char_commands := 0
var total_char_commands := 0
var play_sound := true
var is_line_finished := false
export var text_speed := 30.0 # per second
export var show_character_name := false
export var voice_player : NodePath
export var expression_base_node : NodePath
onready var audio_stream_player := get_node(voice_player) as AudioStreamPlayer if not voice_player.is_empty() else null
class DialogLine:
extends Reference
var text := ""
var name := ""
var autopunc := false
# Other data you need per line (character names, expressions, etc) goes here
var current_line : DialogLine = null
var current_text := ""
var current_commands := {} # Maps character indices to arrays of commands
static func quick_line(text: String, name := "") -> DialogLine:
var line := DialogLine.new()
line.text = text
line.name = name
return line
func set_new_text(new_line: DialogLine):
skipping_line = false
is_line_finished = false
visible_characters = 0
current_commands = {}
processed_char_commands = 0
total_char_commands = 0
current_line = new_line
if show_character_name:
current_text = current_line.name + ": " + current_line.text
else:
current_text = current_line.text
current_text = parse_escape_sequences(current_text)
# Now for the parsing
# 1. Parse BBCode out of source text
# 2. Feed BBCode output text to command parser
# 3. Remove commands from the original text and put it through
# the BBCode parser *again* to get final output text
bbcode_text = current_text
var parse_result = parse_line_commands(text, current_line.autopunc)
bbcode_text = remove_commands(current_text)
for command in parse_result:
var command_index = command.index
command.erase("index")
if not current_commands.has(command_index):
current_commands[command_index] = []
current_commands[command_index].append(command)
timer = 0.0
if show_character_name:
visible_characters = current_line.name.length() + 2 # To account for the colon and space
func skip_line():
skipping_line = true
func _ready():
# first off. i apologize
regex.compile( "(/{[^!][^/}]*[^!/}]/})".replace("/", "\\").replace("!", WORDJOINER))
# I use replace twice there to make the regex somewhat more readable
# Forward slashes become backslashes, and exclamation marks become WORDJOINER,
# which is the invisible character we use to prevent the label from parsing
# out the BBCode and commands when they're escaped
# (see also: parse_escape_sequences())
func _process(delta):
if not current_line:
return
while realtime_wait > 0.0:
realtime_wait = max(realtime_wait - delta, 0.0)
return
var current_text_speed := text_speed * text_speed_multiplier
# Don't advance more than one character per frame
var capped_delta = min(delta, 1.0 / current_text_speed)
timer += capped_delta
# Get number of commands on the current character
total_char_commands = current_commands.get(visible_characters, []).size()
var char_count : int = text.length()
var char_delay = 1.0 / current_text_speed
var current_char := get_char_at_index(current_line.text, visible_characters)
var skipping_char := is_instant_char(current_char)
# Text advance loop.
# Yes, it has to be like this. I'm sorry.
# Just let it do its magic.
while (timer > char_delay or skipping_line or skipping_char) and realtime_wait == 0.0 and visible_characters <= char_count:
timer = max(timer - char_delay, 0)
if pause_buffer == 0:
# Process commands
if processed_char_commands < total_char_commands:
for i in range(processed_char_commands, total_char_commands):
handle_command(current_commands[visible_characters][i])
processed_char_commands += 1
# Pause buffer or wait timer might have been set by command, in which case we stop processing commands for now
if pause_buffer > 0 or realtime_wait > 0.0:
break
else:
pause_buffer -= 1
# Check if ready to go to next character
if processed_char_commands >= total_char_commands and ((pause_buffer == 0 or skipping_line) and realtime_wait == 0):
if visible_characters == char_count:
break # Done
total_char_commands = current_commands.get(visible_characters + 1, []).size()
processed_char_commands = 0
if not skipping_line and not skipping_char and play_sound and current_char != " ":
if audio_stream_player:
audio_stream_player.play()
visible_characters += 1
# End of text advance loop
# Check if finished with the line
if realtime_wait == 0 and visible_characters >= char_count and processed_char_commands == total_char_commands:
if not is_line_finished:
is_line_finished = true
skipping_line = false
emit_signal("line_finished")
else:
is_line_finished = false
#
# Line parsing
#
static func parse_escape_sequences(var txtline: String):
var escaped_state := false
var result := ""
var is_percent_closing = false
for c in txtline:
if escaped_state:
match c:
"t":
result += "\t"
"n":
result += "\n"
"r":
result += "\r"
"[", "{":
result += c + WORDJOINER
"]", "}":
result += WORDJOINER + c
"%":
if is_percent_closing:
result += WORDJOINER + c
else:
result += c + WORDJOINER
"\\", "\"":
result += c
_:
printerr("Unrecognized escape sequence '\\", c, "'.")
result += "\\" + c
escaped_state = false
else:
match c:
"\\":
escaped_state = true
"%":
is_percent_closing = !is_percent_closing
result += c
_:
result += c
return result
func remove_commands(var txtline: String):
var search_result = regex.search(txtline)
while search_result != null:
var txtline_result = ""
if search_result.get_start() > 0:
txtline_result += txtline.substr(0, search_result.get_start())
if search_result.get_end() < txtline.length():
txtline_result += txtline.substr(search_result.get_end()) # Account for non-WJ match
txtline = txtline_result
search_result = regex.search(txtline)
return txtline
static func get_pause_len(c):
match c:
".", "?", "!", ":":
return 20
",", ";":
return 10
_:
return 0
func parse_line_commands(txtline: String, autopunc: bool):
var commands := []
# Search for command tags
var search_result = regex.search(txtline)
while search_result != null:
var command := {}
var index_offset = txtline.substr(0, search_result.get_start()).count("\n")
# the wonders of weak typing
var substrings = search_result.get_string(1)
substrings = substrings.substr(1, substrings.length() - 2)
substrings = substrings.split(" ")
substrings = Array(substrings)
command["index"] = search_result.get_start() - index_offset
command["name"] = substrings[0]
command["args"] = substrings.slice(1, substrings.size() - 1)
command["raw"] = search_result.get_string(1)
commands.push_back(command)
#Remove command from string
var txtline_result = ""
if search_result.get_start() > 0:
txtline_result += txtline.substr(0, search_result.get_start())
if search_result.get_end() < txtline.length():
txtline_result += txtline.substr(search_result.get_end())
txtline = txtline_result
search_result = regex.search(txtline)
# Autopunc handling
if autopunc:
for i in txtline.length() - 1: # Don't put pause on last character
if txtline[i+1] != ")":
if get_pause_len(txtline[i]) > 0 and (i + 1 == txtline.length() or get_pause_len(txtline[i]) != get_pause_len(txtline[i+1])):
var command := {}
command.name = "p"
command.args = []
command.index = i + 1 - txtline.substr(0, i).count("\n")
command.args.append(str(get_pause_len(txtline[i])))
commands.push_back(command)
return commands
func handle_command(command: Dictionary):
match command.name:
"pause", "p":
pause_buffer = command.args[0].to_int()
"speed", "sp":
text_speed_multiplier = command.args[0].to_float()
"advance", "a":
emit_signal("advance_dialog")
"waitsec", "w":
realtime_wait = command.args[0].to_float()
"event", "e":
process_event(command)
_:
print("WARN: Unrecognized dialog command: ", command.name)
func split_args(param_list: String):
var stack_depth := 0
var args := []
var prev_idx := 0
for i in param_list.length():
match param_list[i]:
",":
if stack_depth == 0:
args.append(param_list.substr(prev_idx, i - prev_idx))
prev_idx = i + 1
"(":
stack_depth += 1
")":
stack_depth -= 1
if stack_depth != 0:
printerr("Unmatched '(' and ')' in parameter list.")
return null
args.append(param_list.substr(prev_idx))
return args
# Events are this system's version of signals.
# Any Node registered to the dia_event group will receive a function call to
# `dia_eventn(name, args)` when an {event} command is reached during dialogue.
# Useful for integration with i.e. a cutscene system
#
# Another useful feature is that these `dia_event` calls can return a float,
# which represents an amount of time in seconds that the dialogue system should
# wait before continuing. This will only happen if the event is prefixed
# with `await`, though.
#
# Also, this part of the parser gets messy. Sorry about that.
#
func process_event(command):
# Get the raw command text so we can parse it ourselves
var event_text = command.raw
var result_array := []
var argstart = event_text.find("(") # Start of parameter list
var qualifstart = event_text.find(" ") + 1 # The character after the first space
var event_name : String
var qualifiers_text : String
var await := false
if argstart != -1:
qualifiers_text = event_text.substr(qualifstart, argstart - qualifstart)
else:
qualifiers_text = event_text.substr(qualifstart)
# Qualifiers (only `await` in this stripped-down version)
var qualifiers = qualifiers_text.split(" ")
if qualifiers.size() > 1:
for i in qualifiers.size() - 1:
match qualifiers[i]:
"await":
await = true
# Get event name, which is the last in the qualifiers array
event_name = qualifiers[qualifiers.size() - 1]
# Parse the parameter list
if argstart != -1:
var args : String = event_text.substr(argstart + 1, event_text.find_last(")") - argstart - 1)
if not args.empty():
# Split the parameter list into individual strings, and evaluate them
var args_array = split_args(args)
for arg in args_array:
result_array.append(parse_expr(arg))
# Call dia_event on listeners
var event_listeners = get_tree().get_nodes_in_group("dia_event")
var wait_time := 0.0
for listener in event_listeners:
if !listener.has_method("dia_event"):
var script_name := listener.get_script().resource_path as String
script_name = script_name.substr(script_name.find_last("/") + 1)
print("WARN: Node ", listener.name, " (", script_name, ") is in group dia_event, but has no method dia_event(); skipping")
continue
# Call dia_event on event listener
var time_result = listener.dia_event(event_name, result_array)
match typeof(time_result):
TYPE_REAL, TYPE_INT, TYPE_NIL:
pass # Numeric or no result
_:
printerr("ERROR: Invalid return type from dia_event() call (", listener.name, ".dia_event())")
return -1
if time_result:
if wait_time != 0.0:
print("WARN: More than one object returned wait time from dia_event() call; using longest time")
wait_time = max(wait_time, time_result)
# If we have a wait time and the `await` qualifier, we apply it here
if await:
realtime_wait = wait_time
func parse_expr(expr_txt: String, flags := {}):
var expr = Expression.new()
var error = expr.parse(expr_txt, PoolStringArray(flags.keys()))
if error != OK:
return
# You could point this to a singleton or other script, to give the
# expression parser extra functions and variables to use.
#
# (https://docs.godotengine.org/en/stable/tutorials/scripting/evaluating_expressions.html)
var result = expr.execute(flags.values(), get_node(expression_base_node), true)
if expr.has_execute_failed():
printerr("Failed to execute expression: ", expr_txt)
return result
# Could be extended if you want certain characters to be skipped.
# Not entirely sure the skipping works properly though
static func is_instant_char(c) -> bool:
match c:
WORDJOINER:
return true
_:
return false
# RichTextLabel doesn't count newlines in visible_characters, so we correct for
# it to get the right character index here.
static func get_corrected_index(txtline: String, idx: int) -> int:
return idx - txtline.substr(0, idx).count("\n")
static func get_char_at_index(txtline: String, idx: int) -> String:
var correct_index := get_corrected_index(txtline, idx)
if correct_index >= txtline.length():
return ""
return txtline[correct_index]