diff --git a/ui/main_cli.gd b/ui/main_cli.gd index c294987..1e4dc82 100644 --- a/ui/main_cli.gd +++ b/ui/main_cli.gd @@ -4,10 +4,16 @@ extends RefCounted ## docs/DESIGN.md §5). Only automation needs this file. var m: Main +## The group, template and inspector flags (MainCliBuild). +var _build: MainCliBuild +## The --perf timings (MainCliPerf). +var _perf: MainCliPerf func _init(p_main: Main) -> void: m = p_main + _build = MainCliBuild.new(p_main) + _perf = MainCliPerf.new(p_main) # ---------- Command line (used for screenshots and checks) ---------- @@ -35,7 +41,7 @@ func _run_cli(args: PackedStringArray) -> void: m.set_all_collapsed(true) _run_shell_cli(args) _run_logic_cli(args) - await _run_group_cli(args) + await _build.run_group_cli(args) var roll := _arg_value(args, "--roll") if roll != "": m.start_roll(roll, args.has("--fast")) @@ -154,94 +160,9 @@ func _run_logic_cli(args: PackedStringArray) -> void: m.tray._vars.confirm_reset_all() -# ----- Group and template screenshot flags ----- -# --select=,… select cards (Build) -# --group-selected[=] group the selection -# --collapse-groups / --expand-groups every group -# --toggle-group= collapse or expand one group -# --templates[=] open the template list -# --insert-template= insert a template (builtin: or a user id) -# [--template-values==|…] -# --insert-form= open a template's parameter form -# --save-template= open the save dialog for one card -# --save-group-template= -# --group-menu open the first group's ⋯ menu (Build) -# --drag-demo hold a card over the first group's frame (Build) # --clear-result empty the tray (the board stays lit) # --view=,[,] centre the view on a world point (after Fit) -func _run_group_cli(args: PackedStringArray) -> void: - var sel := _arg_value(args, "--select") - if sel != "": - m.editing.set_selection(Array(sel.split(","))) - for a in args: - if a == "--group-selected" or a.begins_with("--group-selected="): - var g := m.grouping.group_selection() - if g and a.contains("="): - g.name = a.get_slice("=", 1) - m.grouping._groups_changed() - if args.has("--collapse-groups") or args.has("--expand-groups"): - for g in m.data.groups: - g.collapsed = args.has("--collapse-groups") - m.grouping._groups_changed() - var tg := _arg_value(args, "--toggle-group") - if tg != "": - for gid in tg.split(","): - m.toggle_group(gid) - var ins := _arg_value(args, "--insert-template") - if ins != "": - var tpl := m.templating.templates().get_template(ins) - var values := {} - for pair in _arg_value(args, "--template-values").split("|", false): - values[pair.get_slice("=", 0)] = pair.substr(pair.find("=") + 1) - if tpl.is_empty(): - push_warning("No template %s" % ins) - else: - m.templating.insert_template(tpl, values) - var form := _arg_value(args, "--insert-form") - if form != "" and not m.templating.templates().get_template(form).is_empty(): - m.begin_template_insert(m.templating.templates().get_template(form)) - var st := _arg_value(args, "--save-template") - if st != "": - m.save_template_from([Roller.resolve(m.data, st)], "card") - var sg := _arg_value(args, "--save-group-template") - if sg != "" and not m.data.groups.is_empty(): - var gid: String = sg - if sg == "first": - gid = m.data.groups[0].id - elif sg == "last": - gid = m.data.groups[m.data.groups.size() - 1].id - m.save_template_from([], "group", [gid]) - for a in args: - if a == "--templates" or a.begins_with("--templates="): - var p := m.templating.open_template_picker() - if a.contains("="): - p._search.text = a.get_slice("=", 1) - p.refresh() - var shown := p.shown_ids() - if not shown.is_empty(): - p.select(str(shown[0])) - if args.has("--group-selected") or sel != "" or ins != "": - # Let new cards and frames lay out. - await m.get_tree().process_frame - await m.get_tree().process_frame - if args.has("--group-menu") and not m.data.groups.is_empty(): - await m.get_tree().process_frame - var gn := m.group_node(m.data.groups[0].id) - if gn and gn.menu_button: - gn.menu_button.show_popup() - if args.has("--drag-demo") and not m.data.groups.is_empty(): - # A card held over the first group's frame, to show the drop highlight. - var g := m.data.groups[0] - for t in m.data.tables: - if not g.has(t.id) and m.card_for(t.id) and m.card_for(t.id).visible: - var c := m.card_for(t.id) - c.get_parent().move_child(c, -1) - m.begin_card_drag(c) - m.drag_card(c, g.position + Vector2(g.size.x * 0.5, TableGroup.TITLE_H + 40)) - break - - func _apply_view_flag(args: PackedStringArray) -> void: var v := _arg_value(args, "--view") if v == "": @@ -273,7 +194,7 @@ func _load_board_file(path: String) -> void: func _run_cli_extras(args: PackedStringArray) -> void: if args.has("--perf"): - _run_perf() + _perf.run_perf() await _run_undo_cli(args) _run_nav_cli(args) if args.has("--clear-result"): @@ -285,7 +206,7 @@ func _run_cli_extras(args: PackedStringArray) -> void: var pipe := _arg_value(args, "--pipe") if pipe != "": m.open_pipe_options(pipe, Vector2(m.size.x * 0.45, m.size.y * 0.3)) - await _run_inspector_cli(args) + await _build.run_inspector_cli(args) var hover := _arg_value(args, "--hover") if hover.contains(","): # Synthetic mouse move, to check hover pop-ups in screenshots. @@ -316,67 +237,6 @@ func _run_test_board_cli(args: PackedStringArray) -> void: d.runs = n.to_int() d.run_test() -## --perf: times a reload of the current board and the frame cost while idle -## and while panning (vsync off), then prints the numbers and quits. -func _run_perf() -> void: - DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED) - Engine.max_fps = 0 - var text := m.data.to_json() - for i in 10: - await m.get_tree().process_frame - var t0 := Time.get_ticks_usec() - m.data.load_json(text) - var tj := Time.get_ticks_usec() - m._rebuild_cards() - var t1 := Time.get_ticks_usec() - m.rolling._seed_session() - var t2 := Time.get_ticks_usec() - await m.get_tree().process_frame - await m.get_tree().process_frame - var t3 := Time.get_ticks_usec() - m.board.fit() - print("PERF load: parse %.1f ms, rebuild_cards %.1f ms, seed %.1f ms, first two frames %.1f ms, total %.1f ms" % [ - (tj - t0) / 1000.0, (t1 - tj) / 1000.0, (t2 - t1) / 1000.0, (t3 - t2) / 1000.0, (t3 - t0) / 1000.0]) - print("PERF nodes: %d, table cards built: %d of %d" % [Performance.get_monitor(Performance.OBJECT_NODE_COUNT), m.cards.size(), m.data.tables.size()]) - for i in 30: - await m.get_tree().process_frame - print("PERF idle (fit view): %s" % await _perf_frames(240, Vector2.ZERO)) - m.board.set_zoom(0.6) - print("PERF pan (zoom 0.6): %s" % await _perf_frames(240, Vector2(-6, -2))) - m.board.set_zoom(1.0) - print("PERF idle (zoom 1): %s" % await _perf_frames(240, Vector2.ZERO)) - print("PERF pan (zoom 1): %s" % await _perf_frames(240, Vector2(-6, -2))) - if OS.get_cmdline_user_args().has("--perf-layers"): - m.board.fit() - print("PERF idle (fit view again): %s" % await _perf_frames(120, Vector2.ZERO)) - m.board.pipes.visible = false - print("PERF idle, no pipes: %s" % await _perf_frames(120, Vector2.ZERO)) - m.board.ports.visible = false - print("PERF idle, no pipes or ports: %s" % await _perf_frames(120, Vector2.ZERO)) - m.board.cards.visible = false - print("PERF idle, no cards either: %s" % await _perf_frames(120, Vector2.ZERO)) - m.board.set_process(false) - m.board.groups.set_process(false) - print("PERF idle, board and group processing off: %s" % await _perf_frames(120, Vector2.ZERO)) - m.get_tree().quit() - - -func _perf_frames(n: int, pan: Vector2) -> String: - var times: Array[float] = [] - var last := Time.get_ticks_usec() - for i in n: - if pan != Vector2.ZERO: - m.board.world.position += pan - await m.get_tree().process_frame - var now := Time.get_ticks_usec() - times.append((now - last) / 1000.0) - last = now - times.sort() - var total := 0.0 - for t in times: - total += t - return "mean %.2f ms, median %.2f ms, p95 %.2f ms" % [total / n, times[n / 2], times[int(n * 0.95)]] - # ----- Navigation screenshot flags ----- # --search= open the search panel with that query @@ -441,65 +301,3 @@ func _run_undo_cli(args: PackedStringArray) -> void: ev.global_position = ev.position m.get_viewport().push_input(ev) await m.get_tree().process_frame - - -# --inspect=
[:][>] select that card, result or pipe -# --rules=text show rules as text -# --pick-open open the inspector's first value picker -# --vars=name=value,… set board values (e.g. collection members) -# --light=,… light pipes and their results, as if rolled -# --window=x resize the window first (screenshots) -# --inspect-scroll= scroll the inspector down -func _run_inspector_cli(args: PackedStringArray) -> void: - var win := _arg_value(args, "--window") - if win.contains("x"): - m.get_window().size = Vector2i(win.get_slice("x", 0).to_int(), win.get_slice("x", 1).to_int()) - for i in 3: - await m.get_tree().process_frame - var rv := _arg_value(args, "--rules") - if rv != "": - m.set_rules_view(rv) - var vars := _arg_value(args, "--vars") - if vars != "": - for pair in vars.split(",", false): - var v := pair.get_slice("=", 1) - m.persistent_vars[pair.get_slice("=", 0)] = {"value": Expr.to_value(v) if Expr.is_number(v) else v, "source": ""} - m.local_state._variables_changed() - var light := _arg_value(args, "--light") - if light != "": - for k in light.split(",", false): - m.lit_pipes[k] = true - m.lit_entries[k.get_slice(">", 0)] = true - m._refresh_lit() - var sel := _arg_value(args, "--inspect") - if sel == "": - return - if m.mode != Main.Mode.BUILD: - m.set_mode(Main.Mode.BUILD) - if sel.contains(">"): - m.inspecting.select_pipe(sel) - elif sel.contains(":"): - m.select_result(sel.get_slice(":", 0), sel.get_slice(":", 1)) - else: - m.select_card(sel) - var scroll := _arg_value(args, "--inspect-scroll") - if scroll != "": - for i in 3: - await m.get_tree().process_frame - m.inspector._scroll.scroll_vertical = scroll.to_int() - if args.has("--pick-open"): - for i in 3: - await m.get_tree().process_frame - var p := _first_picker(m.inspector) - if p: - p.open_menu() - - -func _first_picker(n: Node) -> ValuePicker: - for c in n.get_children(): - if c is ValuePicker and (c as ValuePicker).is_visible_in_tree(): - return c - var r := _first_picker(c) - if r: - return r - return null diff --git a/ui/main_cli_build.gd b/ui/main_cli_build.gd new file mode 100644 index 0000000..f7afa07 --- /dev/null +++ b/ui/main_cli_build.gd @@ -0,0 +1,160 @@ +class_name MainCliBuild +extends RefCounted +## The Build-mode command-line flags: groups, templates and the inspector. +## They set up the board for a screenshot (see docs/DESIGN.md §5). MainCli +## uses it; only automation needs this file. + +var m: Main + + +func _init(p_main: Main) -> void: + m = p_main + + +# ----- Group and template screenshot flags ----- +# --select=,… select cards (Build) +# --group-selected[=] group the selection +# --collapse-groups / --expand-groups every group +# --toggle-group= collapse or expand one group +# --templates[=] open the template list +# --insert-template= insert a template (builtin: or a user id) +# [--template-values==|…] +# --insert-form= open a template's parameter form +# --save-template=
open the save dialog for one card +# --save-group-template= +# --group-menu open the first group's ⋯ menu (Build) +# --drag-demo hold a card over the first group's frame (Build) + +func run_group_cli(args: PackedStringArray) -> void: + var selection := MainCli._arg_value(args, "--select") + if selection != "": + m.editing.set_selection(Array(selection.split(","))) + for arg in args: + if arg == "--group-selected" or arg.begins_with("--group-selected="): + var group := m.grouping.group_selection() + if group and arg.contains("="): + group.name = arg.get_slice("=", 1) + m.grouping._groups_changed() + if args.has("--collapse-groups") or args.has("--expand-groups"): + for group in m.data.groups: + group.collapsed = args.has("--collapse-groups") + m.grouping._groups_changed() + var toggle_ids := MainCli._arg_value(args, "--toggle-group") + if toggle_ids != "": + for gid in toggle_ids.split(","): + m.toggle_group(gid) + var insert_id := MainCli._arg_value(args, "--insert-template") + if insert_id != "": + var template := m.templating.templates().get_template(insert_id) + var values := {} + for pair in MainCli._arg_value(args, "--template-values").split("|", false): + values[pair.get_slice("=", 0)] = pair.substr(pair.find("=") + 1) + if template.is_empty(): + push_warning("No template %s" % insert_id) + else: + m.templating.insert_template(template, values) + var form := MainCli._arg_value(args, "--insert-form") + if form != "" and not m.templating.templates().get_template(form).is_empty(): + m.begin_template_insert(m.templating.templates().get_template(form)) + var save_card := MainCli._arg_value(args, "--save-template") + if save_card != "": + m.save_template_from([Roller.resolve(m.data, save_card)], "card") + var save_group := MainCli._arg_value(args, "--save-group-template") + if save_group != "" and not m.data.groups.is_empty(): + var gid: String = save_group + if save_group == "first": + gid = m.data.groups[0].id + elif save_group == "last": + gid = m.data.groups[m.data.groups.size() - 1].id + m.save_template_from([], "group", [gid]) + for arg in args: + if arg == "--templates" or arg.begins_with("--templates="): + var picker := m.templating.open_template_picker() + if arg.contains("="): + picker._search.text = arg.get_slice("=", 1) + picker.refresh() + var shown := picker.shown_ids() + if not shown.is_empty(): + picker.select(str(shown[0])) + if args.has("--group-selected") or selection != "" or insert_id != "": + # Let new cards and frames lay out. + await m.get_tree().process_frame + await m.get_tree().process_frame + if args.has("--group-menu") and not m.data.groups.is_empty(): + await m.get_tree().process_frame + var group_node := m.group_node(m.data.groups[0].id) + if group_node and group_node.menu_button: + group_node.menu_button.show_popup() + if args.has("--drag-demo") and not m.data.groups.is_empty(): + # A card held over the first group's frame, to show the drop highlight. + var group := m.data.groups[0] + for table in m.data.tables: + if not group.has(table.id) and m.card_for(table.id) and m.card_for(table.id).visible: + var card := m.card_for(table.id) + card.get_parent().move_child(card, -1) + m.begin_card_drag(card) + m.drag_card(card, group.position + Vector2(group.size.x * 0.5, TableGroup.TITLE_H + 40)) + break + + +# --inspect=
[:][>] select that card, result or pipe +# --rules=text show rules as text +# --pick-open open the inspector's first value picker +# --vars=name=value,… set board values (e.g. collection members) +# --light=,… light pipes and their results, as if rolled +# --window=x resize the window first (screenshots) +# --inspect-scroll= scroll the inspector down +func run_inspector_cli(args: PackedStringArray) -> void: + var window_size := MainCli._arg_value(args, "--window") + if window_size.contains("x"): + m.get_window().size = Vector2i(window_size.get_slice("x", 0).to_int(), window_size.get_slice("x", 1).to_int()) + for i in 3: + await m.get_tree().process_frame + var rules_view := MainCli._arg_value(args, "--rules") + if rules_view != "": + m.set_rules_view(rules_view) + var vars := MainCli._arg_value(args, "--vars") + if vars != "": + for pair in vars.split(",", false): + var value := pair.get_slice("=", 1) + m.persistent_vars[pair.get_slice("=", 0)] = {"value": Expr.to_value(value) if Expr.is_number(value) else value, "source": ""} + m.local_state._variables_changed() + var light := MainCli._arg_value(args, "--light") + if light != "": + for key in light.split(",", false): + m.lit_pipes[key] = true + m.lit_entries[key.get_slice(">", 0)] = true + m._refresh_lit() + var inspect := MainCli._arg_value(args, "--inspect") + if inspect == "": + return + if m.mode != Main.Mode.BUILD: + m.set_mode(Main.Mode.BUILD) + if inspect.contains(">"): + m.inspecting.select_pipe(inspect) + elif inspect.contains(":"): + m.select_result(inspect.get_slice(":", 0), inspect.get_slice(":", 1)) + else: + m.select_card(inspect) + var scroll := MainCli._arg_value(args, "--inspect-scroll") + if scroll != "": + for i in 3: + await m.get_tree().process_frame + m.inspector._scroll.scroll_vertical = scroll.to_int() + if args.has("--pick-open"): + for i in 3: + await m.get_tree().process_frame + var picker := _first_picker(m.inspector) + if picker: + picker.open_menu() + + +## The first visible ValuePicker inside `node` (searching depth first), or null. +func _first_picker(node: Node) -> ValuePicker: + for child in node.get_children(): + if child is ValuePicker and (child as ValuePicker).is_visible_in_tree(): + return child + var found := _first_picker(child) + if found: + return found + return null diff --git a/ui/main_cli_build.gd.uid b/ui/main_cli_build.gd.uid new file mode 100644 index 0000000..b712dea --- /dev/null +++ b/ui/main_cli_build.gd.uid @@ -0,0 +1 @@ +uid://bem3m1inyi4bs diff --git a/ui/main_cli_perf.gd b/ui/main_cli_perf.gd new file mode 100644 index 0000000..2f4acb1 --- /dev/null +++ b/ui/main_cli_perf.gd @@ -0,0 +1,76 @@ +class_name MainCliPerf +extends RefCounted +## The --perf command-line flag: it times how long the board takes to load and +## how long each frame takes (idle and while panning), prints the numbers and +## quits. MainCli uses it; only automation needs this file. + +var m: Main + + +func _init(p_main: Main) -> void: + m = p_main + + +## --perf: times a reload of the current board and the frame cost while idle +## and while panning (vsync off), then prints the numbers and quits. +func run_perf() -> void: + DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED) + Engine.max_fps = 0 + var text := m.data.to_json() + for i in 10: + await m.get_tree().process_frame + var start_usec := Time.get_ticks_usec() + m.data.load_json(text) + var parsed_usec := Time.get_ticks_usec() + m._rebuild_cards() + var rebuilt_usec := Time.get_ticks_usec() + m.rolling._seed_session() + var seeded_usec := Time.get_ticks_usec() + await m.get_tree().process_frame + await m.get_tree().process_frame + var drawn_usec := Time.get_ticks_usec() + m.board.fit() + print("PERF load: parse %.1f ms, rebuild_cards %.1f ms, seed %.1f ms, first two frames %.1f ms, total %.1f ms" % [ + (parsed_usec - start_usec) / 1000.0, (rebuilt_usec - parsed_usec) / 1000.0, (seeded_usec - rebuilt_usec) / 1000.0, + (drawn_usec - seeded_usec) / 1000.0, (drawn_usec - start_usec) / 1000.0]) + print("PERF nodes: %d, table cards built: %d of %d" % [Performance.get_monitor(Performance.OBJECT_NODE_COUNT), m.cards.size(), m.data.tables.size()]) + for i in 30: + await m.get_tree().process_frame + print("PERF idle (fit view): %s" % await _perf_frames(240, Vector2.ZERO)) + m.board.set_zoom(0.6) + print("PERF pan (zoom 0.6): %s" % await _perf_frames(240, Vector2(-6, -2))) + m.board.set_zoom(1.0) + print("PERF idle (zoom 1): %s" % await _perf_frames(240, Vector2.ZERO)) + print("PERF pan (zoom 1): %s" % await _perf_frames(240, Vector2(-6, -2))) + if OS.get_cmdline_user_args().has("--perf-layers"): + m.board.fit() + print("PERF idle (fit view again): %s" % await _perf_frames(120, Vector2.ZERO)) + m.board.pipes.visible = false + print("PERF idle, no pipes: %s" % await _perf_frames(120, Vector2.ZERO)) + m.board.ports.visible = false + print("PERF idle, no pipes or ports: %s" % await _perf_frames(120, Vector2.ZERO)) + m.board.cards.visible = false + print("PERF idle, no cards either: %s" % await _perf_frames(120, Vector2.ZERO)) + m.board.set_process(false) + m.board.groups.set_process(false) + print("PERF idle, board and group processing off: %s" % await _perf_frames(120, Vector2.ZERO)) + m.get_tree().quit() + + +## Waits `frame_count` frames (moving the view by `pan` each frame) and returns +## the mean, median and 95th-percentile frame times as text. +func _perf_frames(frame_count: int, pan: Vector2) -> String: + var times: Array[float] = [] + var last := Time.get_ticks_usec() + for i in frame_count: + if pan != Vector2.ZERO: + m.board.world.position += pan + await m.get_tree().process_frame + var now := Time.get_ticks_usec() + times.append((now - last) / 1000.0) + last = now + times.sort() + var total := 0.0 + for frame_ms in times: + total += frame_ms + return "mean %.2f ms, median %.2f ms, p95 %.2f ms" % [total / frame_count, times[frame_count / 2], times[int(frame_count * 0.95)]] diff --git a/ui/main_cli_perf.gd.uid b/ui/main_cli_perf.gd.uid new file mode 100644 index 0000000..edd546c --- /dev/null +++ b/ui/main_cli_perf.gd.uid @@ -0,0 +1 @@ +uid://d3q8cvryn2ocv diff --git a/ui/main_rolling.gd b/ui/main_rolling.gd index 43af0e3..a219f35 100644 --- a/ui/main_rolling.gd +++ b/ui/main_rolling.gd @@ -5,8 +5,6 @@ extends RefCounted ## Chains longer than this show at once instead of animating. const LONG_CHAIN := 40 -## Copy-as-text indents by depth up to this many levels. -const MAX_INDENT := 8 var m: Main @@ -17,12 +15,16 @@ var _choice: ChoiceDialog var pauses: RollPauses ## Deck-mode draws not shown yet in an animated roll. var deck_reveal: DeckReveal +var _seed: MainRollingSeed +var _copy: MainRollingCopy func _init(p_main: Main) -> void: m = p_main pauses = RollPauses.new(p_main) deck_reveal = DeckReveal.new(self) + _seed = MainRollingSeed.new(p_main) + _copy = MainRollingCopy.new(p_main) ## Rolls a table and plays the result down its pipes. A fast roll (Shift held @@ -312,68 +314,9 @@ func _archive_current() -> void: m.history.resize(Main.HISTORY_SIZE) -## Opens the session: the collection's saved history, decks and variables. With -## no saved history (a fresh start, or --sample / --screenshot), it seeds a game -## already under way: a couple of earlier rolls, saved variables for the -## Variables tab, and a current roll that runs through the d100 travel table -## into the collapsed trinket table. +## Opens the session (MainRollingSeed.seed_session). func _seed_session() -> void: - m.local_state.load_local_state() - if not m.current.is_empty(): - _light_steps(m.current.get("all", [])) - m._refresh_lit() - m.refresh_live() - m.tray.render() - return - var now := Time.get_unix_time_from_system() - # Seeded rolls draw from scratch decks so they don't use up real cards. - var scratch := {} - for seed_roll in [["monsters", 9], ["loot", 4]]: - if m.data.get_table(seed_roll[0]): - var tree := Roller.roll(m.data, seed_roll[0], m.rng, 0, scratch) - var steps := Roller.flatten(tree, []) - m.history.push_front({"collection": m.data.id, "root": seed_roll[0], "root_name": m.data.get_table(seed_roll[0]).name, - "time": now - seed_roll[1] * 60, "steps": steps, "all": steps, "archived": true}) - # A quest-style chain earlier in the session saved who guides the party and - # the day's weather, so {@guide} and {@weather} have values. - if m.persistent_vars.is_empty(): - var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, scratch) - for pair in [["@guide", "names"], ["@weather", "weather"]]: - if m.data.get_table(pair[1]): - var n := Roller.roll(m.data, pair[1], m.rng, 0, scratch, ctx) - if not n.is_empty() and not n.has("stop"): - ctx.save(pair[0], Formatter.to_export_bbcode(str(n["summary"])), pair[1]) - var start := "wilderness" if m.data.get_table("wilderness") else _first_rollable() - if start == "": - m.refresh_live() - m.tray.render() - return - var best: Dictionary - if m.data.get_table("trinkets"): - best = Roller.roll(m.data, start, m.rng, 0, scratch) - for i in 400: - if Roller.reaches(best, "trinkets"): - break - best = Roller.roll(m.data, start, m.rng, 0, scratch) - else: - # Any other board: one roll with the headless answers, through the real - # variables, so variable and sheet cards have values to show. - best = Roller.roll(m.data, start, m.rng, 0, scratch, Roller.new_context(m.data, m.rng, m.persistent_vars, scratch)) - var all := Roller.flatten(best, []) - m.current = {"collection": m.data.id, "root": start, "root_name": m.data.get_table(start).name, "time": now - 60, - "steps": all, "all": all, "done": true, "chain_vars": {}} - Roller.collect_lit(best, m.lit_entries, m.lit_pipes, m.lit_texts) - m._refresh_lit() - m.refresh_live() - m.tray.render() - - -## The first table that can start a roll (not a variable card), or "". -func _first_rollable() -> String: - for t in m.data.tables: - if t.kind != RollTable.KIND_VARIABLE: - return t.id - return "" + _seed.seed_session() ## Lights the entries and pipes of a roll from its saved steps. @@ -401,32 +344,9 @@ func _light_steps(steps: Array) -> void: ## Copies the current result: ResultTray.COPY_TEXT, COPY_BBCODE or COPY_DETAILS. func copy_current(kind: int) -> void: - if m.current.is_empty(): - return - var text := result_text(m.current.get("all", []), kind) - DisplayServer.clipboard_set(text) - m.toast(["Copied as text", "Copied as BBCode", "Copied with details"][clampi(kind, 0, 2)]) + _copy.copy_current(kind) -## One line per table rolled, indented by depth. Inline rolls are already part -## of their parent's text, so they don't get lines of their own. +## The steps of a roll as text, one line per table (MainRollingCopy.result_text). func result_text(steps: Array, kind: int) -> String: - var lines := PackedStringArray() - for s: Dictionary in steps: - if s.get("inline", false): - continue - # Long pipe chains nest thousands deep; cap the indent so the text stays usable. - var indent := " ".repeat(mini(int(s.get("depth", 0)), MAX_INDENT)) - var tname := str(s.get("table", "")) - var text := str(s.get("text", "")) - if kind == ResultTray.COPY_BBCODE: - lines.append(indent + "[b]%s:[/b] %s" % [Formatter.to_export_bbcode(tname), Formatter.to_export_bbcode(text)]) - else: - lines.append(indent + "%s: %s" % [Formatter.strip_tags(tname), Formatter.strip_tags(text)]) - if kind == ResultTray.COPY_DETAILS: - var t := m.data.get_table(str(s.get("table_id", ""))) - var e := t.find_entry(str(s.get("entry_id", ""))) if t else null - if e and e.details.strip_edges() != "": - var pad := indent + " " - lines.append(pad + Formatter.strip_tags(e.details).strip_edges().replace("\n", "\n" + pad)) - return "\n".join(lines) + return _copy.result_text(steps, kind) diff --git a/ui/main_rolling_copy.gd b/ui/main_rolling_copy.gd new file mode 100644 index 0000000..a9b35df --- /dev/null +++ b/ui/main_rolling_copy.gd @@ -0,0 +1,46 @@ +class_name MainRollingCopy +extends RefCounted +## Turns a roll's result into text for the clipboard: plain text, BBCode, or +## text with each result's details. MainRolling uses it. + +## Copy-as-text indents by depth up to this many levels. +const MAX_INDENT := 8 + +var m: Main + + +func _init(p_main: Main) -> void: + m = p_main + + +## Copies the current result: ResultTray.COPY_TEXT, COPY_BBCODE or COPY_DETAILS. +func copy_current(kind: int) -> void: + if m.current.is_empty(): + return + var text := result_text(m.current.get("all", []), kind) + DisplayServer.clipboard_set(text) + m.toast(["Copied as text", "Copied as BBCode", "Copied with details"][clampi(kind, 0, 2)]) + + +## One line per table rolled, indented by depth. Inline rolls are already part +## of their parent's text, so they don't get lines of their own. +func result_text(steps: Array, kind: int) -> String: + var lines := PackedStringArray() + for step: Dictionary in steps: + if step.get("inline", false): + continue + # Long pipe chains nest thousands deep; cap the indent so the text stays usable. + var indent := " ".repeat(mini(int(step.get("depth", 0)), MAX_INDENT)) + var table_name := str(step.get("table", "")) + var text := str(step.get("text", "")) + if kind == ResultTray.COPY_BBCODE: + lines.append(indent + "[b]%s:[/b] %s" % [Formatter.to_export_bbcode(table_name), Formatter.to_export_bbcode(text)]) + else: + lines.append(indent + "%s: %s" % [Formatter.strip_tags(table_name), Formatter.strip_tags(text)]) + if kind == ResultTray.COPY_DETAILS: + var table := m.data.get_table(str(step.get("table_id", ""))) + var entry := table.find_entry(str(step.get("entry_id", ""))) if table else null + if entry and entry.details.strip_edges() != "": + var pad := indent + " " + lines.append(pad + Formatter.strip_tags(entry.details).strip_edges().replace("\n", "\n" + pad)) + return "\n".join(lines) diff --git a/ui/main_rolling_copy.gd.uid b/ui/main_rolling_copy.gd.uid new file mode 100644 index 0000000..418a1cf --- /dev/null +++ b/ui/main_rolling_copy.gd.uid @@ -0,0 +1 @@ +uid://wryf8vxg8vuk diff --git a/ui/main_rolling_seed.gd b/ui/main_rolling_seed.gd new file mode 100644 index 0000000..61a876a --- /dev/null +++ b/ui/main_rolling_seed.gd @@ -0,0 +1,75 @@ +class_name MainRollingSeed +extends RefCounted +## Opens the roll session when a board loads. It brings back the saved history, +## or, on a fresh start, makes up a game already under way (a few earlier rolls +## and some saved variables) so the board doesn't look empty. MainRolling uses it. + +var m: Main + + +func _init(p_main: Main) -> void: + m = p_main + + +## Opens the session: the collection's saved history, decks and variables. With +## no saved history (a fresh start, or --sample / --screenshot), it seeds a game +## already under way: a couple of earlier rolls, saved variables for the +## Variables tab, and a current roll that runs through the d100 travel table +## into the collapsed trinket table. +func seed_session() -> void: + m.local_state.load_local_state() + if not m.current.is_empty(): + m.rolling._light_steps(m.current.get("all", [])) + m._refresh_lit() + m.refresh_live() + m.tray.render() + return + var now := Time.get_unix_time_from_system() + # Seeded rolls draw from scratch decks so they don't use up real cards. + var scratch := {} + for seed_roll in [["monsters", 9], ["loot", 4]]: + if m.data.get_table(seed_roll[0]): + var tree := Roller.roll(m.data, seed_roll[0], m.rng, 0, scratch) + var steps := Roller.flatten(tree, []) + m.history.push_front({"collection": m.data.id, "root": seed_roll[0], "root_name": m.data.get_table(seed_roll[0]).name, + "time": now - seed_roll[1] * 60, "steps": steps, "all": steps, "archived": true}) + # A quest-style chain earlier in the session saved who guides the party and + # the day's weather, so {@guide} and {@weather} have values. + if m.persistent_vars.is_empty(): + var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, scratch) + for pair in [["@guide", "names"], ["@weather", "weather"]]: + if m.data.get_table(pair[1]): + var node := Roller.roll(m.data, pair[1], m.rng, 0, scratch, ctx) + if not node.is_empty() and not node.has("stop"): + ctx.save(pair[0], Formatter.to_export_bbcode(str(node["summary"])), pair[1]) + var start := "wilderness" if m.data.get_table("wilderness") else _first_rollable() + if start == "": + m.refresh_live() + m.tray.render() + return + var best: Dictionary + if m.data.get_table("trinkets"): + best = Roller.roll(m.data, start, m.rng, 0, scratch) + for i in 400: + if Roller.reaches(best, "trinkets"): + break + best = Roller.roll(m.data, start, m.rng, 0, scratch) + else: + # Any other board: one roll with the headless answers, through the real + # variables, so variable and sheet cards have values to show. + best = Roller.roll(m.data, start, m.rng, 0, scratch, Roller.new_context(m.data, m.rng, m.persistent_vars, scratch)) + var all := Roller.flatten(best, []) + m.current = {"collection": m.data.id, "root": start, "root_name": m.data.get_table(start).name, "time": now - 60, + "steps": all, "all": all, "done": true, "chain_vars": {}} + Roller.collect_lit(best, m.lit_entries, m.lit_pipes, m.lit_texts) + m._refresh_lit() + m.refresh_live() + m.tray.render() + + +## The first table that can start a roll (not a variable card), or "". +func _first_rollable() -> String: + for table in m.data.tables: + if table.kind != RollTable.KIND_VARIABLE: + return table.id + return "" diff --git a/ui/main_rolling_seed.gd.uid b/ui/main_rolling_seed.gd.uid new file mode 100644 index 0000000..0f81cb6 --- /dev/null +++ b/ui/main_rolling_seed.gd.uid @@ -0,0 +1 @@ +uid://batuwy2avqxfu diff --git a/ui/pipe_batch.gd b/ui/pipe_batch.gd new file mode 100644 index 0000000..c5c8019 --- /dev/null +++ b/ui/pipe_batch.gd @@ -0,0 +1,104 @@ +class_name PipeBatch +extends RefCounted +## Draws the unlit threads (pipes) for PipeLayer, fast. Each thread goes in a +## canvas item of its own, so the renderer skips the ones out of view. Lit +## threads, labels and the bead are drawn by PipeLayer._draw on top. The canvas +## items are kept in a pool and reused between redraws. + +## The PipeLayer these canvas items belong to (they draw behind it). +var layer: CanvasItem +## Zoomed far out (BoardView.FAR_ZOOM): unlit threads draw as one coarse line. +var far := false +var _items: Array[RID] = [] +var _items_used := 0 + + +func _init(p_layer: CanvasItem) -> void: + layer = p_layer + + +## Starts a redraw: empties every canvas item used last time. +func begin(is_far: bool) -> void: + far = is_far + for i in _items_used: + RenderingServer.canvas_item_clear(_items[i]) + _items_used = 0 + + +## The next free canvas item for one thread: a child of the layer's item drawn +## behind it, so lit threads and labels stay on top. Its bounds come from what's +## drawn in it, so the renderer culls it when the thread is out of view. +func item() -> RID: + if _items_used == _items.size(): + var rid := RenderingServer.canvas_item_create() + RenderingServer.canvas_item_set_parent(rid, layer.get_canvas_item()) + RenderingServer.canvas_item_set_draw_behind_parent(rid, true) + _items.append(rid) + _items_used += 1 + # A theme's thread strip sets a material on its item; reused items start clean. + RenderingServer.canvas_item_set_material(_items[_items_used - 1], RID()) + return _items[_items_used - 1] + + +## Frees every canvas item (call when the layer is deleted). +func free_items() -> void: + for rid in _items: + RenderingServer.free_rid(rid) + _items.clear() + + +static func line(rid: RID, pts: PackedVector2Array, color: Color, width: float) -> void: + RenderingServer.canvas_item_add_polyline(rid, pts, PackedColorArray([color]), width, true) + + +## Far out: one plain line through every fourth point. +static func coarse(rid: RID, pts: PackedVector2Array, color: Color, width: float) -> void: + var points := PackedVector2Array() + for i in range(0, pts.size(), 4): + points.append(pts[i]) + if (pts.size() - 1) % 4 != 0: + points.append(pts[pts.size() - 1]) + RenderingServer.canvas_item_add_polyline(rid, points, PackedColorArray([color]), width, false) + + +## An unlit thread (as PipeLayer._draw_pipe draws it), in its own canvas item. +## `own` is the thread's own colour ("" = the theme's THREAD). +func add_pipe(pts: PackedVector2Array, hovered: bool, own: String = "") -> void: + var rid := item() + var color := Color.from_string(own, Style.THREAD) if own != "" else Style.THREAD + var dark := color.darkened(0.6) if own != "" else Style.THREAD_DARK + if far: + coarse(rid, pts, color, 10.0) + return + if ThreadStrip.active: + ThreadStrip.active.add_to(rid, pts, color.lightened(0.35) if hovered else color, dark) + ThreadStrip.active.add_pins(item(), pts) + return + line(rid, pts, dark, 11.0) + line(rid, pts, color.lightened(0.35) if hovered else color, 6.0) + RenderingServer.canvas_item_add_set_transform(rid, Transform2D(0.0, Vector2(0, -1.5))) + line(rid, pts, Color(1.0, 0.886, 0.745, 0.4), 1.5) + RenderingServer.canvas_item_add_set_transform(rid, Transform2D.IDENTITY) + + +## An unlit thread to or from a collapsed group (as PipeLayer._draw_bundle draws it). +func add_bundle(pts: PackedVector2Array) -> void: + var rid := item() + if far: + coarse(rid, pts, Color(Style.THREAD, 0.6), 6.0) + return + line(rid, pts, Color(Style.THREAD_DARK, 0.55), 6.0) + line(rid, pts, Color(Style.THREAD, 0.6), 3.0) + + +## An unlit reference thread (as PipeLayer._draw_ref draws it). +func add_ref(pts: PackedVector2Array) -> void: + var rid := item() + if far: + coarse(rid, pts, Color(Style.THREAD, 0.7), 4.0) + return + var dashes := PipeGeometry.dashes(pts, 12.0, 7.0) + for dash in dashes: + line(rid, dash, Style.THREAD_DARK, 6.0) + for dash in dashes: + line(rid, dash, Style.THREAD, 3.0) diff --git a/ui/pipe_batch.gd.uid b/ui/pipe_batch.gd.uid new file mode 100644 index 0000000..1b7ea6f --- /dev/null +++ b/ui/pipe_batch.gd.uid @@ -0,0 +1 @@ +uid://bl43d8i7gkax7 diff --git a/ui/pipe_geometry.gd b/ui/pipe_geometry.gd new file mode 100644 index 0000000..0357700 --- /dev/null +++ b/ui/pipe_geometry.gd @@ -0,0 +1,72 @@ +class_name PipeGeometry +extends RefCounted +## The shape of a thread (pipe): the curve between two cards, a point part way +## along it, its length, and how to cut it into dashes. Only maths; it draws +## nothing. PipeLayer and PipeBatch use it. + +## How many straight pieces make up one curve. +const SAMPLES := 40 + + +## A smooth S-curve from `start` to `end`, as SAMPLES + 1 points. +static func curve(start: Vector2, end: Vector2) -> PackedVector2Array: + var dx := maxf(70.0, absf(end.x - start.x) / 2.0) + var control1 := start + Vector2(dx, 0) + var control2 := end - Vector2(dx, 0) + var pts := PackedVector2Array() + for i in SAMPLES + 1: + pts.append(start.bezier_interpolate(control1, control2, end, float(i) / SAMPLES)) + return pts + + +## The length of a polyline. +static func length(pts: PackedVector2Array) -> float: + var total := 0.0 + for i in range(1, pts.size()): + total += pts[i - 1].distance_to(pts[i]) + return total + + +## The point a fraction `fraction` (0 to 1) of the way along a polyline. +static func point_along(pts: PackedVector2Array, fraction: float) -> Vector2: + if pts.size() < 2: + return pts[0] if pts.size() == 1 else Vector2.ZERO + var want := clampf(fraction, 0.0, 1.0) * length(pts) + for i in range(1, pts.size()): + var seg := pts[i - 1].distance_to(pts[i]) + if want <= seg and seg > 0.0: + return pts[i - 1].lerp(pts[i], want / seg) + want -= seg + return pts[pts.size() - 1] + + +## Splits a polyline into dashes `on` long with gaps `off` long. +static func dashes(pts: PackedVector2Array, on: float, off: float) -> Array[PackedVector2Array]: + var out: Array[PackedVector2Array] = [] + var current := PackedVector2Array() + var drawing := true + var left := on + for i in range(1, pts.size()): + var from := pts[i - 1] + var to := pts[i] + var seg := from.distance_to(to) + var pos := 0.0 + if drawing and current.is_empty(): + current.append(from) + while seg - pos > left: + pos += left + var cut := from.lerp(to, pos / seg) + if drawing: + current.append(cut) + out.append(current) + current = PackedVector2Array() + else: + current = PackedVector2Array([cut]) + drawing = not drawing + left = on if drawing else off + left -= seg - pos + if drawing: + current.append(to) + if drawing and current.size() > 1: + out.append(current) + return out diff --git a/ui/pipe_geometry.gd.uid b/ui/pipe_geometry.gd.uid new file mode 100644 index 0000000..5c8e5a1 --- /dev/null +++ b/ui/pipe_geometry.gd.uid @@ -0,0 +1 @@ +uid://c2phcwqa4n3ge diff --git a/ui/pipe_layer.gd b/ui/pipe_layer.gd index 1ce7318..e1997b1 100644 --- a/ui/pipe_layer.gd +++ b/ui/pipe_layer.gd @@ -17,8 +17,6 @@ extends Control ## they still light up and carry the bead; pipes inside one collapsed group ## aren't drawn. -const SAMPLES := 40 - var main: Main var hover_key: String = "" ## The pipe whose options are open in Build mode. @@ -38,13 +36,10 @@ var _label_box: StyleBoxFlat var _lit_label_box: StyleBoxFlat ## What the last redraw was drawn from (see _process). var _drawn_state: Array = [] -## Unlit pipes each go in a canvas item of their own (see _batch_item), so the +## Draws the unlit pipes, each in a canvas item of its own (PipeBatch), so the ## renderer skips the ones out of view; lit pipes, labels and the bead are -## drawn by _draw on top. A pool reused between redraws. -var _items: Array[RID] = [] -var _items_used := 0 -## Zoomed far out (BoardView.FAR_ZOOM): unlit pipes draw as one coarse line. -var _far := false +## drawn by _draw on top. +var _batch := PipeBatch.new(self) func _init() -> void: @@ -82,106 +77,18 @@ func _move_trail() -> void: _trail.emitting = on -# ---------- Batched unlit pipes (performance) ---------- - -func _begin_batch() -> void: - _far = main.board.cards.far - for i in _items_used: - RenderingServer.canvas_item_clear(_items[i]) - _items_used = 0 - - -## The next free canvas item for one pipe: a child of this layer's item drawn -## behind it, so lit pipes and labels stay on top. Its bounds come from what's -## drawn in it, so the renderer culls it when the pipe is out of view. -func _batch_item() -> RID: - if _items_used == _items.size(): - var rid := RenderingServer.canvas_item_create() - RenderingServer.canvas_item_set_parent(rid, get_canvas_item()) - RenderingServer.canvas_item_set_draw_behind_parent(rid, true) - _items.append(rid) - _items_used += 1 - # A theme's thread strip sets a material on its item; reused items start clean. - RenderingServer.canvas_item_set_material(_items[_items_used - 1], RID()) - return _items[_items_used - 1] - - -func _line(rid: RID, pts: PackedVector2Array, color: Color, width: float) -> void: - RenderingServer.canvas_item_add_polyline(rid, pts, PackedColorArray([color]), width, true) - - -## Far out: one plain line through every fourth point. -func _coarse(rid: RID, pts: PackedVector2Array, color: Color, width: float) -> void: - var c := PackedVector2Array() - for i in range(0, pts.size(), 4): - c.append(pts[i]) - if (pts.size() - 1) % 4 != 0: - c.append(pts[pts.size() - 1]) - RenderingServer.canvas_item_add_polyline(rid, c, PackedColorArray([color]), width, false) - - -## An unlit pipe (as _draw_pipe draws it), in its own canvas item. -## `own` is the thread's own colour ("" = the theme's THREAD). -func _batch_pipe(pts: PackedVector2Array, hovered: bool, own: String = "") -> void: - var rid := _batch_item() - var col := Color.from_string(own, Style.THREAD) if own != "" else Style.THREAD - var dark := col.darkened(0.6) if own != "" else Style.THREAD_DARK - if _far: - _coarse(rid, pts, col, 10.0) - return - if ThreadStrip.active: - ThreadStrip.active.add_to(rid, pts, col.lightened(0.35) if hovered else col, dark) - ThreadStrip.active.add_pins(_batch_item(), pts) - return - _line(rid, pts, dark, 11.0) - _line(rid, pts, col.lightened(0.35) if hovered else col, 6.0) - RenderingServer.canvas_item_add_set_transform(rid, Transform2D(0.0, Vector2(0, -1.5))) - _line(rid, pts, Color(1.0, 0.886, 0.745, 0.4), 1.5) - RenderingServer.canvas_item_add_set_transform(rid, Transform2D.IDENTITY) - - -## An unlit pipe to or from a collapsed group (as _draw_bundle draws it). -func _batch_bundle(pts: PackedVector2Array) -> void: - var rid := _batch_item() - if _far: - _coarse(rid, pts, Color(Style.THREAD, 0.6), 6.0) - return - _line(rid, pts, Color(Style.THREAD_DARK, 0.55), 6.0) - _line(rid, pts, Color(Style.THREAD, 0.6), 3.0) - - -## An unlit reference pipe (as _draw_ref draws it). -func _batch_ref(pts: PackedVector2Array) -> void: - var rid := _batch_item() - if _far: - _coarse(rid, pts, Color(Style.THREAD, 0.7), 4.0) - return - var dashes := _dashes(pts, 12.0, 7.0) - for d in dashes: - _line(rid, d, Style.THREAD_DARK, 6.0) - for d in dashes: - _line(rid, d, Style.THREAD, 3.0) - - func _notification(what: int) -> void: if what == NOTIFICATION_PREDELETE: - for rid in _items: - RenderingServer.free_rid(rid) - _items.clear() + _batch.free_items() -static func curve(a: Vector2, b: Vector2) -> PackedVector2Array: - var dx := maxf(70.0, absf(b.x - a.x) / 2.0) - var c1 := a + Vector2(dx, 0) - var c2 := b - Vector2(dx, 0) - var pts := PackedVector2Array() - for i in SAMPLES + 1: - pts.append(a.bezier_interpolate(c1, c2, b, float(i) / SAMPLES)) - return pts +## A smooth curve between two points (PipeGeometry.curve). +static func curve(start: Vector2, end: Vector2) -> PackedVector2Array: + return PipeGeometry.curve(start, end) func _draw() -> void: - _begin_batch() + _batch.begin(main.board.cards.far) _paths.clear() _rerouted.clear() group_ports.clear() @@ -248,11 +155,11 @@ func _draw() -> void: continue drawn[dk] = true if is_ref: - _batch_ref(pts) + _batch.add_ref(pts) elif rerouted: - _batch_bundle(pts) + _batch.add_bundle(pts) else: - _batch_pipe(pts, build and (key == hover_key or key == select_key), str(e.pipe_color.get(to, ""))) + _batch.add_pipe(pts, build and (key == hover_key or key == select_key), str(e.pipe_color.get(to, ""))) if not is_ref and not rerouted: var tag := RulesView.pipe_label(e, to, main.data, plain) if tag != "": @@ -343,7 +250,7 @@ func _draw_diamond(pts: PackedVector2Array, lit: bool, otherwise: bool) -> void: func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void: - if ThreadStrip.active and not _far: + if ThreadStrip.active and not _batch.far: _strip_pipe(pts, lit, hovered) return if lit: @@ -362,10 +269,10 @@ func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void: ## (made after the unlit ones, so drawn over them) keep the material off labels. func _strip_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void: if lit: - _line(_batch_item(), pts, Color(Style.ACCENT, 0.18), ThreadStrip.active.width * 2.0) + PipeBatch.line(_batch.item(), pts, Color(Style.ACCENT, 0.18), ThreadStrip.active.width * 2.0) var trim := Style.ACCENT if lit else (Style.THREAD.lightened(0.35) if hovered else Style.THREAD) - ThreadStrip.active.add_to(_batch_item(), pts, trim, Style.ACCENT_DARK if lit else Style.THREAD_DARK) - ThreadStrip.active.add_pins(_batch_item(), pts) + ThreadStrip.active.add_to(_batch.item(), pts, trim, Style.ACCENT_DARK if lit else Style.THREAD_DARK) + ThreadStrip.active.add_pins(_batch.item(), pts) ## An unlit pipe to or from a collapsed group: thinner and quieter, so the @@ -379,68 +286,22 @@ func _draw_bundle(pts: PackedVector2Array) -> void: func _draw_ref(pts: PackedVector2Array, lit: bool) -> void: if lit: draw_polyline(pts, Color(Style.ACCENT, 0.14), 12.0, true) - var dashes := _dashes(pts, 12.0, 7.0) + var dashes := PipeGeometry.dashes(pts, 12.0, 7.0) for d in dashes: draw_polyline(d, Style.ACCENT_DARK if lit else Style.THREAD_DARK, 6.0, true) for d in dashes: draw_polyline(d, Style.ACCENT if lit else Style.THREAD, 3.0, true) -## Splits a polyline into dashes `on` long with gaps `off` long. -static func _dashes(pts: PackedVector2Array, on: float, off: float) -> Array[PackedVector2Array]: - var out: Array[PackedVector2Array] = [] - var cur := PackedVector2Array() - var drawing := true - var left := on - for i in range(1, pts.size()): - var a := pts[i - 1] - var b := pts[i] - var seg := a.distance_to(b) - var pos := 0.0 - if drawing and cur.is_empty(): - cur.append(a) - while seg - pos > left: - pos += left - var p := a.lerp(b, pos / seg) - if drawing: - cur.append(p) - out.append(cur) - cur = PackedVector2Array() - else: - cur = PackedVector2Array([p]) - drawing = not drawing - left = on if drawing else off - left -= seg - pos - if drawing: - cur.append(b) - if drawing and cur.size() > 1: - out.append(cur) - return out - - func path_length(key: String) -> float: if not _paths.has(key): return 0.0 - var pts: PackedVector2Array = _paths[key] - var total := 0.0 - for i in range(1, pts.size()): - total += pts[i - 1].distance_to(pts[i]) - return total + return PipeGeometry.length(_paths[key]) -static func point_along(pts: PackedVector2Array, t: float) -> Vector2: - if pts.size() < 2: - return pts[0] if pts.size() == 1 else Vector2.ZERO - var total := 0.0 - for i in range(1, pts.size()): - total += pts[i - 1].distance_to(pts[i]) - var want := clampf(t, 0.0, 1.0) * total - for i in range(1, pts.size()): - var seg := pts[i - 1].distance_to(pts[i]) - if want <= seg and seg > 0.0: - return pts[i - 1].lerp(pts[i], want / seg) - want -= seg - return pts[pts.size() - 1] +## The point a fraction `fraction` of the way along a polyline (PipeGeometry.point_along). +static func point_along(pts: PackedVector2Array, fraction: float) -> Vector2: + return PipeGeometry.point_along(pts, fraction) ## The pipe under a world-space point, or "" if none is within `tolerance`.