From 32d82b4bd1fc2ccc6225afdb31c96fa1b40e0fd8 Mon Sep 17 00:00:00 2001 From: SnekInAScarf Date: Tue, 10 Nov 2026 13:36:36 -0800 Subject: [PATCH] Rework manual tubes: steerable goo with a leader indicator Manual tubes (TubeSteer): - The slime is pulled fully into the tube on entry; tubes too short for it squash it to fit, with a few pixels poking out of each mouth. - A leader slides quickly through the goo without moving it, and drags the goo at normal speed once past an end. At covered junctions it can turn into another arm, or pull into an empty branch, draining the goo from all sides. - Only coloured pixels go in; a black outline is drawn around the goo, with rounded ends in the tube. - The leader is a pulsing circle; colour, border colour and radius are set under "Tube Indicator" on the Player. Tiles and level: - Plain tube tiles are now manual, green ones automatic. Test level tubes repainted plain so they stay manual. Also included (earlier work): goo tube prototype (TubeGoo, purple tiles) and a max length for the automatic pixel stream. Co-Authored-By: Claude Opus 5.5 --- Assets/level_tiles.tres | 67 ++- Characters/player.gd | 32 +- Effects/pixel_stream.gd | 12 +- Effects/tube_goo.gd | 525 +++++++++++++++++++++++ Effects/tube_goo.gd.uid | 1 + Effects/tube_steer.gd | 912 +++++++++++++++++++++++++++------------- Levels/test_level.tscn | 2 +- 7 files changed, 1249 insertions(+), 302 deletions(-) create mode 100644 Effects/tube_goo.gd create mode 100644 Effects/tube_goo.gd.uid diff --git a/Assets/level_tiles.tres b/Assets/level_tiles.tres index cb415b2..717a26e 100755 --- a/Assets/level_tiles.tres +++ b/Assets/level_tiles.tres @@ -7,32 +7,48 @@ texture = ExtResource("1_ufwbk") texture_region_size = Vector2i(32, 32) 0:0/0 = 0 0:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, 16, -16, 16) +1:0/next_alternative_id = 3 1:0/0 = 0 1:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -16, -3) 1:0/0/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, 16, 3, 16, 16, -16, 16) 1:0/0/custom_data_0 = 10 +1:0/0/custom_data_1 = true 1:0/1 = 1 1:0/1/modulate = Color(0.6, 1, 0.75, 1) 1:0/1/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -16, -3) 1:0/1/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, 16, 3, 16, 16, -16, 16) 1:0/1/custom_data_0 = 10 -1:0/1/custom_data_1 = true +1:0/2 = 2 +1:0/2/modulate = Color(1, 0.7, 0.95, 1) +1:0/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -16, -3) +1:0/2/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, 16, 3, 16, 16, -16, 16) +1:0/2/custom_data_0 = 10 +1:0/2/custom_data_2 = true +2:0/next_alternative_id = 3 2:0/0 = 0 2:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 16, -16, 16) 2:0/0/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, 16, 3, 16) 2:0/0/custom_data_0 = 5 +2:0/0/custom_data_1 = true 2:0/1 = 1 2:0/1/modulate = Color(0.6, 1, 0.75, 1) 2:0/1/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 16, -16, 16) 2:0/1/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, 16, 3, 16) 2:0/1/custom_data_0 = 5 -2:0/1/custom_data_1 = true +2:0/2 = 2 +2:0/2/modulate = Color(1, 0.7, 0.95, 1) +2:0/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 16, -16, 16) +2:0/2/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, 16, 3, 16) +2:0/2/custom_data_0 = 5 +2:0/2/custom_data_2 = true +3:0/next_alternative_id = 3 3:0/0 = 0 3:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3) 3:0/0/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3) 3:0/0/physics_layer_0/polygon_2/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16) 3:0/0/physics_layer_0/polygon_3/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16) 3:0/0/custom_data_0 = 15 +3:0/0/custom_data_1 = true 3:0/1 = 1 3:0/1/modulate = Color(0.6, 1, 0.75, 1) 3:0/1/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3) @@ -40,47 +56,82 @@ texture_region_size = Vector2i(32, 32) 3:0/1/physics_layer_0/polygon_2/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16) 3:0/1/physics_layer_0/polygon_3/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16) 3:0/1/custom_data_0 = 15 -3:0/1/custom_data_1 = true +3:0/2 = 2 +3:0/2/modulate = Color(1, 0.7, 0.95, 1) +3:0/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3) +3:0/2/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3) +3:0/2/physics_layer_0/polygon_2/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16) +3:0/2/physics_layer_0/polygon_3/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16) +3:0/2/custom_data_0 = 15 +3:0/2/custom_data_2 = true +4:0/next_alternative_id = 3 4:0/0 = 0 4:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 3, 16, 3, 16, 16, -16, 16) 4:0/0/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3) 4:0/0/custom_data_0 = 3 +4:0/0/custom_data_1 = true 4:0/1 = 1 4:0/1/modulate = Color(0.6, 1, 0.75, 1) 4:0/1/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 3, 16, 3, 16, 16, -16, 16) 4:0/1/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3) 4:0/1/custom_data_0 = 3 -4:0/1/custom_data_1 = true +4:0/2 = 2 +4:0/2/modulate = Color(1, 0.7, 0.95, 1) +4:0/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 3, 16, 3, 16, 16, -16, 16) +4:0/2/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3) +4:0/2/custom_data_0 = 3 +4:0/2/custom_data_2 = true +5:0/next_alternative_id = 3 5:0/0 = 0 5:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(3, -16, 16, -16, 16, 16, -16, 16, -16, 3, 3, 3) 5:0/0/physics_layer_0/polygon_1/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3) 5:0/0/custom_data_0 = 9 +5:0/0/custom_data_1 = true 5:0/1 = 1 5:0/1/modulate = Color(0.6, 1, 0.75, 1) 5:0/1/physics_layer_0/polygon_0/points = PackedVector2Array(3, -16, 16, -16, 16, 16, -16, 16, -16, 3, 3, 3) 5:0/1/physics_layer_0/polygon_1/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3) 5:0/1/custom_data_0 = 9 -5:0/1/custom_data_1 = true +5:0/2 = 2 +5:0/2/modulate = Color(1, 0.7, 0.95, 1) +5:0/2/physics_layer_0/polygon_0/points = PackedVector2Array(3, -16, 16, -16, 16, 16, -16, 16, -16, 3, 3, 3) +5:0/2/physics_layer_0/polygon_1/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3) +5:0/2/custom_data_0 = 9 +5:0/2/custom_data_2 = true +0:1/next_alternative_id = 3 0:1/0 = 0 0:1/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, 16, 3, 16, 3, -3, -16, -3) 0:1/0/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16) 0:1/0/custom_data_0 = 12 +0:1/0/custom_data_1 = true 0:1/1 = 1 0:1/1/modulate = Color(0.6, 1, 0.75, 1) 0:1/1/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, 16, 3, 16, 3, -3, -16, -3) 0:1/1/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16) 0:1/1/custom_data_0 = 12 -0:1/1/custom_data_1 = true +0:1/2 = 2 +0:1/2/modulate = Color(1, 0.7, 0.95, 1) +0:1/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, 16, 3, 16, 3, -3, -16, -3) +0:1/2/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16) +0:1/2/custom_data_0 = 12 +0:1/2/custom_data_2 = true +1:1/next_alternative_id = 3 1:1/0 = 0 1:1/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -3, -3, -3, 16, -16, 16) 1:1/0/physics_layer_0/polygon_1/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16) 1:1/0/custom_data_0 = 6 +1:1/0/custom_data_1 = true 1:1/1 = 1 1:1/1/modulate = Color(0.6, 1, 0.75, 1) 1:1/1/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -3, -3, -3, 16, -16, 16) 1:1/1/physics_layer_0/polygon_1/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16) 1:1/1/custom_data_0 = 6 -1:1/1/custom_data_1 = true +1:1/2 = 2 +1:1/2/modulate = Color(1, 0.7, 0.95, 1) +1:1/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -3, -3, -3, 16, -16, 16) +1:1/2/physics_layer_0/polygon_1/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16) +1:1/2/custom_data_0 = 6 +1:1/2/custom_data_2 = true [resource] tile_size = Vector2i(32, 32) @@ -89,4 +140,6 @@ custom_data_layer_0/name = "tube_openings" custom_data_layer_0/type = 2 custom_data_layer_1/name = "tube_manual" custom_data_layer_1/type = 1 +custom_data_layer_2/name = "tube_goo" +custom_data_layer_2/type = 1 sources/0 = SubResource("TileSetAtlasSource_0cw2b") diff --git a/Characters/player.gd b/Characters/player.gd index f0bd49b..7ca3b96 100755 --- a/Characters/player.gd +++ b/Characters/player.gd @@ -48,13 +48,16 @@ const LAND_PITCH_MAX = 1.15 # open (the "tube_openings" custom data). Holding into a tube's mouth squeezes us # in as pixels. An ordinary tube streams us through to the other end # (PixelStream). A manual one ("tube_manual" tiles) lets the player steer us -# through it, round corners and either way at crossings (TubeSteer). +# through it, round corners and either way at crossings (TubeSteer). A goo one +# ("tube_goo" tiles) is the same, but the goo has no head or tail (TubeGoo). const TUBE_DATA_LAYER = "tube_openings" const TUBE_OPEN_UP = 1 const TUBE_OPEN_RIGHT = 2 const TUBE_OPEN_DOWN = 4 const TUBE_OPEN_LEFT = 8 const TUBE_WIDTH = 6.0 # The channel drawn through the tiles in LevelTiles.png. +# The longest our pixels stretch in a tube (two tiles). They bunch up to fit. +const TUBE_MAX_FLOW_LENGTH = 64.0 const TUBE_ENTRY_REACH = 2.0 # How close our side must be to a tube mouth to go in. const TUBE_MAX_TILES = 256 # Give up following a tube this long. const TUBE_REENTRY_DELAY = 0.3 # So we don't dive straight back in. @@ -110,7 +113,9 @@ var isSqueezingIntoTube := false # Holding into a tube's mouth, about to go in. var isInTube := false var tubePixels: PixelStream # Our pixels streaming through an ordinary tube, or null. -var tubeSteer: TubeSteer # Our pixels being steered through a manual tube, or null. +# Our pixels being steered through a manual tube (a TubeSteer) or a goo tube (a +# TubeGoo), or null. Both have start(), steer(), isFinished and exitPose. +var tubeSteer: Variant = null var tubeExitPose := {} # Where the stream comes out (see _tube_exit_pose). var tubeReentryCooldown := 0.0 var timeSpentSqueezingIntoTube := 0.0 @@ -135,6 +140,13 @@ var hasFoundTubeLayers := false # Placeholder sounds, see Assets/Sounds/CREDITS.txt. One plays at random per landing. @export var landSounds: Array[AudioStream] = [] +# The circle that marks where you're steering from in a manual tube (TubeSteer). +@export_group("Tube Indicator") +@export var tubeIndicatorColor := Color(1.0, 0.85, 0.3) +@export var tubeIndicatorBorderColor := Color.WHITE +@export_range(1.0, 12.0, 0.5) var tubeIndicatorRadius := 4.0 +@export_group("") + func _ready() -> void: floor_snap_length = SURFACE_SNAP_DISTANCE @@ -759,7 +771,7 @@ func _find_tube_towards(direction: Vector2) -> Dictionary: if absf(toMouth.dot(across)) > radius or toMouth.dot(direction) > reach: continue var tube := {layer = layer, cell = cell, direction = direction} - if TubeSteer.is_manual(layer, cell): + if TubeSteer.is_manual(layer, cell) or TubeGoo.is_goo(layer, cell): return tube var path := _trace_tube(layer, cell, direction) if not path.is_empty() and not _tube_exit_pose_for(path).is_empty(): @@ -828,16 +840,22 @@ func _enter_tube(tube: Dictionary) -> void: tubeExitPose = _tube_exit_pose_for(tube.path) tubePixels = PixelStream.new() get_parent().add_child(tubePixels) - tubePixels.start(sprite, tube.path, TUBE_WIDTH, tubeExitPose.spriteTransform, REST_FRAME) + tubePixels.start(sprite, tube.path, TUBE_WIDTH, TUBE_MAX_FLOW_LENGTH, tubeExitPose.spriteTransform, REST_FRAME) else: # Backing out of the mouth we went in by reforms us right here. var spriteTransform := sprite.get_global_transform() spriteTransform.origin = spriteTransform.origin.round() # Snapped like the renderer does. var entryPose := {spriteTransform = spriteTransform, normal = _get_surface_normal(), appearAt = global_position} - tubeSteer = TubeSteer.new() + if TubeGoo.is_goo(tube.layer, tube.cell): + tubeSteer = TubeGoo.new() + else: + tubeSteer = TubeSteer.new() + tubeSteer.indicatorColor = tubeIndicatorColor + tubeSteer.indicatorBorderColor = tubeIndicatorBorderColor + tubeSteer.indicatorRadius = tubeIndicatorRadius get_parent().add_child(tubeSteer) - tubeSteer.start(sprite, tube.layer, tube.cell, Vector2i(tube.direction), TUBE_WIDTH, + tubeSteer.start(sprite, tube.layer, tube.cell, Vector2i(tube.direction), TUBE_WIDTH, TUBE_MAX_FLOW_LENGTH, entryPose, _tube_exit_pose, REST_FRAME) isInTube = true @@ -858,7 +876,7 @@ func _update_tube(delta: float, moveInput: Vector2) -> void: if tubeSteer != null: tubeSteer.steer(Vector2(moveInput.x, -moveInput.y), delta) # Up is negative y. if tubeSteer.isFinished: - var pose := tubeSteer.exitPose + var pose: Dictionary = tubeSteer.exitPose tubeSteer.queue_free() tubeSteer = null _exit_tube(pose, delta) diff --git a/Effects/pixel_stream.gd b/Effects/pixel_stream.gd index d643e47..77c7d61 100755 --- a/Effects/pixel_stream.gd +++ b/Effects/pixel_stream.gd @@ -12,7 +12,7 @@ extends Node2D # Watch isFinished to know when every pixel is back in place. const SPEED = 240.0 # How fast pixels flow along the path, in px/s. -const ROW_SPACING = 1.0 # Gap between rows of pixels in the stream. +const ROW_SPACING = 1.0 # Gap between rows of pixels in the stream, unless that would make it too long. const GATHER_TIME = 0.12 # How long the nearest pixels take to reach the entry mouth. const LAND_TIME = 0.15 # How long the last pixels out take to reach their spot. @@ -25,6 +25,7 @@ var _ends := PackedVector2Array() # Where it goes in the sprite we're putting ba var _lanes := PackedFloat32Array() # How far left of the path's middle it flows. var _rows := PackedInt32Array() # Its place in the stream: row 0 goes in first. var _rowCount := 0 +var _rowSpacing := ROW_SPACING # Closer if needed to keep the stream within maxLength. var _path := PackedVector2Array() var _pathDistances := PackedFloat32Array() # How far along the path each point is. @@ -33,9 +34,11 @@ var _time := 0.0 # path: global points from the entry mouth to the exit mouth. # width: how wide the tube is. The stream is this many pixels across. +# maxLength: the longest the stream can be. Rows bunch up (overlapping) to fit. # endTransform: the sprite's global transform once it's back together. # endFrame: the frame it reforms as, so it matches what the sprite shows next. -func start(sprite: Sprite2D, path: PackedVector2Array, width: float, endTransform: Transform2D, endFrame: int) -> void: +func start(sprite: Sprite2D, path: PackedVector2Array, width: float, maxLength: float, + endTransform: Transform2D, endFrame: int) -> void: top_level = true global_position = Vector2.ZERO z_index = sprite.z_index + 1 @@ -54,6 +57,7 @@ func start(sprite: Sprite2D, path: PackedVector2Array, width: float, endTransfor isFinished = true return _pair_pixels(from, to, maxi(int(width), 1)) + _rowSpacing = minf(ROW_SPACING, maxLength / _rowCount) # The frame's opaque pixels (black ones too: they're the eyes) as .positions @@ -140,9 +144,9 @@ func _process(delta: float) -> void: # ---- Timing ---- -# When a row reaches the entry mouth. Each row is ROW_SPACING behind the last. +# When a row reaches the entry mouth. Each row is _rowSpacing behind the last. func _enter_time(row: int) -> float: - return GATHER_TIME + row * ROW_SPACING / SPEED + return GATHER_TIME + row * _rowSpacing / SPEED # When a row leaves the exit mouth. func _exit_time(row: int) -> float: diff --git a/Effects/tube_goo.gd b/Effects/tube_goo.gd new file mode 100644 index 0000000..3da29f2 --- /dev/null +++ b/Effects/tube_goo.gd @@ -0,0 +1,525 @@ +class_name TubeGoo +extends Node2D + +# The slime squeezed into a goo tube as a shapeless amount of goo, with no head +# or tail. The goo fills a connected patch of the tubes (a line, or a T or plus +# shape where it spans a crossing), and moves by growing at one spot while +# shrinking by the same amount at all its other tips at once. +# +# Steering: pressing a direction grows the goo at the growth point nearest the +# one it last grew at (the "active" point) that can grow that way. A growth +# point is any tip, or any spot the goo covers with an empty branch beside it. +# So in a straight tube pressing back grows the far tip (reversing), and with +# the goo spanning a crossing, pressing into a side branch sprouts the middle +# into it while both ends drain towards it. +# Tips also look ahead along straight tube, so pressing towards a turn before +# reaching it carries the tip there. +# Every growth point pulses faintly. The one the input is using pulses brighter. +# +# Past each mouth with room for the slime is a straight "outside line". Goo out +# there gathers into the slime's shape. Once all of it is out far enough, it +# reforms: isFinished goes true and exitPose says where. The goo starts out on +# the entry mouth's line, in the shape of the sprite that went in, so backing +# all the way out reforms us where we went in. +# +# The track is made of vertices one pixel apart, and the goo moves a vertex at a +# time. Each vertex holds one row of pixels across the tube. If the goo would +# be longer than maxLength, the rows hold more pixels (overlapping) instead. + +const SPEED = 150.0 # How fast the goo grows while pressed, in px/s. +const GATHER_DISTANCE = 24 # How far past a mouth goo goes before it's in its place in the slime. +# How much of the input must point along a way for the goo to grow along it +# (0.5 lets diagonals pick either way). +const MIN_PULL = 0.5 +const LOOKAHEAD = 48 # How far along straight tube a tip looks for a turn the input points along. +const MAX_TILES = 1024 # Stop mapping a tube network this big. +const MAX_STEPS_PER_FRAME = 8 +const PULSE_SPEED = 7.0 # Radians per second. +const PULSE_ALPHA = 0.5 # How strongly growth points pulse. +const ACTIVE_PULSE_ALPHA = 0.9 # How strongly the one being grown pulses. +const PULSE_LENGTH = 3 # How many vertices into a branch the pulse shows. +const SHOW_ACTIVE = false # Outline the active point, for debugging. +const NO_GROWTH = Vector2i(-1, -1) + +const DIRECTIONS: Array[Vector2i] = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT] + +var isFinished := false +var exitPose := {} # The pose we came out as (see start()). + +# The track's vertices. +var _positions := PackedVector2Array() +var _neighbors: Array[Array] = [] # Per vertex: the vertices next to it. +var _lines := PackedInt32Array() # Per vertex: the outside line it's on, or -1 in the tubes. +var _depths := PackedInt32Array() # Per vertex on an outside line: how far out it is (1 = just past the mouth). + +# The outside lines. +var _lineMouths := PackedVector2Array() +var _lineOutwards := PackedVector2Array() +var _lineStarts := PackedInt32Array() # The vertex at depth 1. +var _linePoses: Array[Dictionary] = [] # The pose we come out as there. +var _lineShapes: Array[Dictionary] = [] # That pose's pixels nearest the mouth first, worked out when needed. +var _lineLength := 0 +var _entryLine := -1 + +# The goo. +var _rowAt := PackedInt32Array() # Per vertex: the row of pixels there, or -1 if empty. +var _shrunkAt := PackedInt32Array() # Per vertex: when the goo last shrank back to it. +var _clock := 0 +var _active := -1 +var _growth := 0.0 # Growth we're owed but haven't done, in vertices. +var _cue := NO_GROWTH # (vertex, empty vertex it grew into) for the brighter pulse. +var _time := 0.0 + +# The pixels: row r holds pixels r * _pixelsPerRow up to the next row's, going +# across its _laneCount lanes and round again. +var _rowCount := 0 +var _laneCount := 1 +var _pixelsPerRow := 1 +var _colors := PackedColorArray() +var _spots := PackedVector2Array() # Where each pixel goes in the shape it's gathering into outside. +var _spotColors := PackedColorArray() +var _rowLines := PackedInt32Array() # Per row: the outside line its spots are for, or -1. +var _endFrame := {} # The frame we reform as, in the sprite's space. + + +# Squeezes into the tube at `entryCell` heading `entryDirection`. +# Poses are {spriteTransform: Transform2D, ...plus whatever the caller wants +# back in exitPose}. entryPose is the slime as it is now. findPose(mouth: +# Vector2, outward: Vector2) gives the pose for coming out of a mouth, or {} if +# there's no room. endFrame: the frame we reform as. maxLength: the longest the +# goo can be. +func start(sprite: Sprite2D, layer: TileMapLayer, entryCell: Vector2i, entryDirection: Vector2i, + width: float, maxLength: float, entryPose: Dictionary, findPose: Callable, endFrame: int) -> void: + top_level = true + global_position = Vector2.ZERO + z_index = sprite.z_index + 1 + + _laneCount = maxi(int(width), 1) + var from := PixelStream.get_frame_pixels(sprite, sprite.frame, entryPose.spriteTransform) + _endFrame = PixelStream.get_frame_pixels(sprite, endFrame, Transform2D.IDENTITY) + if from.colors.is_empty() or _endFrame.colors.is_empty(): + exitPose = entryPose + isFinished = true + return + # If the frame we reform as has more pixels, or the last row isn't full, + # some are doubled up so none go missing. + var pixelCount := maxi(from.colors.size(), _endFrame.colors.size()) + _rowCount = mini(ceili(float(pixelCount) / _laneCount), maxi(int(maxLength), 1)) + _pixelsPerRow = ceili(float(pixelCount) / _rowCount) + _lineLength = _rowCount + GATHER_DISTANCE + + _build_track(layer, entryCell, entryDirection, entryPose, findPose) + if _entryLine == -1: + exitPose = entryPose + isFinished = true + return + + # The goo starts out on the entry mouth's line, far enough out that every + # pixel is still in its place in the sprite. The pixels nearest the mouth + # are in the rows nearest it, so they go in first. + var count := _rowCount * _pixelsPerRow + var order := _sorted_by_distance(from.positions, _lineMouths[_entryLine]) + for i in count: + var k: int = order[int(float(i) * order.size() / count)] + _colors.append(from.colors[k]) + _spots.append(from.positions[k]) + _spotColors.append(from.colors[k]) + _rowLines.resize(_rowCount) + _rowLines.fill(_entryLine) + for row in _rowCount: + _rowAt[_line_vertex(_entryLine, GATHER_DISTANCE + row)] = row + _active = _line_vertex(_entryLine, GATHER_DISTANCE) + + +# Moves the goo for one physics frame. input: the player's input, with y down. +func steer(input: Vector2, delta: float) -> void: + if isFinished: + return + _cue = NO_GROWTH + if input == Vector2.ZERO: + _growth = 0.0 + return + input = input.normalized() + _growth += SPEED * delta + for i in MAX_STEPS_PER_FRAME: + if _growth < 1.0: + break + var growth := _choose_growth(input) + if growth == NO_GROWTH: + _growth = 0.0 # Nowhere to grow the way the input points. + break + _cue = growth + _grow(growth.x, growth.y) + _growth -= 1.0 + if _check_all_out(): + return + + +func _process(delta: float) -> void: + _time += delta + queue_redraw() + + +# ---- Setup ---- + +# Maps out the goo tube network from `entryCell` as vertices a pixel apart, +# plus an outside line past each mouth we can come out of. +func _build_track(layer: TileMapLayer, entryCell: Vector2i, entryDirection: Vector2i, + entryPose: Dictionary, findPose: Callable) -> void: + var cellVertices := {entryCell: _add_vertex(TubeSteer.cell_point(layer, entryCell, Vector2i.ZERO))} + var toVisit: Array[Vector2i] = [entryCell] + while not toVisit.is_empty() and cellVertices.size() < MAX_TILES: + var cell: Vector2i = toVisit.pop_front() + var openings := TubeSteer.get_openings(layer, cell) + for direction in DIRECTIONS: + if openings & TubeSteer.side_bit(direction) == 0: + continue + var nextCell := cell + direction + if is_goo(layer, nextCell) and TubeSteer.get_openings(layer, nextCell) & TubeSteer.side_bit(-direction): + if not cellVertices.has(nextCell): + cellVertices[nextCell] = _add_vertex(TubeSteer.cell_point(layer, nextCell, Vector2i.ZERO)) + toVisit.append(nextCell) + # Each pair of tiles is joined once, from its left or top tile. + if direction == Vector2i.RIGHT or direction == Vector2i.DOWN: + _join(cellVertices[cell], cellVertices[nextCell]) + elif layer.get_cell_source_id(nextCell) == -1: + # A mouth into open space. + var mouthPosition := TubeSteer.cell_point(layer, cell, direction) + var mouth := _add_vertex(mouthPosition) + _join(cellVertices[cell], mouth) + var isEntry := cell == entryCell and direction == -entryDirection + var pose: Dictionary = entryPose if isEntry else findPose.call(mouthPosition, Vector2(direction)) + if pose.is_empty(): + continue # No room out there: a dead end. + if isEntry: + _entryLine = _lineMouths.size() + _add_outside_line(mouth, Vector2(direction), pose) + # Otherwise it opens into something solid: a dead end. + + +func _add_vertex(at: Vector2, line := -1, depth := 0) -> int: + _positions.append(at) + _neighbors.append([]) + _lines.append(line) + _depths.append(depth) + _rowAt.append(-1) + _shrunkAt.append(0) + return _positions.size() - 1 + + +func _connect(a: int, b: int) -> void: + _neighbors[a].append(b) + _neighbors[b].append(a) + + +# Joins two vertices with a straight run of vertices a pixel apart. +func _join(a: int, b: int) -> void: + var from := _positions[a] + var to := _positions[b] + var steps := maxi(roundi(from.distance_to(to)), 1) + var previous := a + for step in range(1, steps): + var vertex := _add_vertex(from.lerp(to, float(step) / steps)) + _connect(previous, vertex) + previous = vertex + _connect(previous, b) + + +func _add_outside_line(mouth: int, outward: Vector2, pose: Dictionary) -> void: + var line := _lineMouths.size() + _lineMouths.append(_positions[mouth]) + _lineOutwards.append(outward) + _linePoses.append(pose) + _lineShapes.append({}) + _lineStarts.append(_positions.size()) + var previous := mouth + for depth in range(1, _lineLength + 1): + var vertex := _add_vertex(_positions[mouth] + outward * depth, line, depth) + _connect(previous, vertex) + previous = vertex + + +func _line_vertex(line: int, depth: int) -> int: + return _lineStarts[line] + depth - 1 + + +# ---- Growing ---- + +# Where to grow for the input: (a goo vertex, the empty vertex beside it to grow +# into), nearest the active point. NO_GROWTH if there's nowhere. +func _choose_growth(input: Vector2) -> Vector2i: + var distances := _goo_distances_from(_active) + var best := NO_GROWTH + var bestDistance := 0 + var bestPull := 0.0 + for vertex in _rowAt.size(): + if _rowAt[vertex] == -1: + continue + for next: int in _neighbors[vertex]: + if not _can_grow_into(vertex, next): + continue + var pull := input.dot(_direction(vertex, next)) + if pull < MIN_PULL and _is_tip(vertex): + pull = _lookahead_pull(vertex, next, input) + if pull < MIN_PULL: + continue + var distance := distances[vertex] + if best == NO_GROWTH or distance < bestDistance or (distance == bestDistance and pull > bestPull): + best = Vector2i(vertex, next) + bestDistance = distance + bestPull = pull + return best + + +# Whether the goo at `vertex` can grow into `next`: it's empty, and growing +# there wouldn't join up with goo somewhere else (round a loop). +func _can_grow_into(vertex: int, next: int) -> bool: + if _rowAt[next] != -1: + return false + for other: int in _neighbors[next]: + if other != vertex and _rowAt[other] != -1: + return false + return true + + +# From a tip growing into `next`, how well the input points along a way on from +# the turn or junction at the end of the straight run ahead. +func _lookahead_pull(tip: int, next: int, input: Vector2) -> float: + var previous := tip + var current := next + for i in LOOKAHEAD: + var ways := _neighbors[current].filter(func(other: int) -> bool: return other != previous) + var isStraightOn := ways.size() == 1 and _direction(current, ways[0]).is_equal_approx(_direction(previous, current)) + if isStraightOn and _rowAt[ways[0]] == -1: + previous = current + current = ways[0] + continue + var best := -INF + for way: int in ways: + if _rowAt[way] == -1: + best = maxf(best, input.dot(_direction(current, way))) + return best + return -INF + + +# Grows the goo from `vertex` into `next`, and shrinks it at the tip that's gone +# longest without shrinking. Taking turns like this drains all the tips at once. +# The goo between that tip and `next` flows along a vertex. +func _grow(vertex: int, next: int) -> void: + _rowAt[next] = -2 # Goo, but which row is sorted out below. + var tip := _pick_tip_to_shrink(next) + var path := _goo_path(tip, next) + for i in range(path.size() - 1, 0, -1): + _rowAt[path[i]] = _rowAt[path[i - 1]] + _rowAt[tip] = -1 + _clock += 1 + _shrunkAt[path[1]] = _clock + _active = next + for i in range(1, path.size()): + _update_row_line(_rowAt[path[i]], path[i]) + + +func _pick_tip_to_shrink(exclude: int) -> int: + var best := -1 + for vertex in _rowAt.size(): + if _rowAt[vertex] == -1 or vertex == exclude or not _is_tip(vertex): + continue + if best == -1 or _shrunkAt[vertex] < _shrunkAt[best]: + best = vertex + return best + + +func _is_tip(vertex: int) -> bool: + var gooNeighbors := 0 + for other: int in _neighbors[vertex]: + if _rowAt[other] != -1: + gooNeighbors += 1 + return gooNeighbors <= 1 + + +# How far each vertex is from `from` through the goo (-1 if it isn't goo). +func _goo_distances_from(from: int) -> PackedInt32Array: + var distances := PackedInt32Array() + distances.resize(_rowAt.size()) + distances.fill(-1) + distances[from] = 0 + var queue: Array[int] = [from] + while not queue.is_empty(): + var vertex: int = queue.pop_front() + for other: int in _neighbors[vertex]: + if _rowAt[other] != -1 and distances[other] == -1: + distances[other] = distances[vertex] + 1 + queue.append(other) + return distances + + +# The vertices from `from` to `to` through the goo. +func _goo_path(from: int, to: int) -> PackedInt32Array: + var cameFrom := {to: -1} + var queue: Array[int] = [to] + while not queue.is_empty() and not cameFrom.has(from): + var vertex: int = queue.pop_front() + for other: int in _neighbors[vertex]: + if _rowAt[other] != -1 and not cameFrom.has(other): + cameFrom[other] = vertex + queue.append(other) + var path := PackedInt32Array() + var vertex := from + while vertex != -1: + path.append(vertex) + vertex = cameFrom[vertex] + return path + + +# When a row moves onto an outside line, picks the spots its pixels gather +# into there. The first rows out take the spots furthest from the mouth. +func _update_row_line(row: int, vertex: int) -> void: + var line := _lines[vertex] + if line == _rowLines[row]: + return + _rowLines[row] = line + if line == -1: + return + + var alreadyOut := 0 + for depth in range(1, _lineLength + 1): + var other := _rowAt[_line_vertex(line, depth)] + if other >= 0 and other != row: + alreadyOut += 1 + var group := _rowCount - 1 - alreadyOut + + var shape := _get_line_shape(line) + var pointCount: int = shape.positions.size() + for slot in _pixelsPerRow: + var i := row * _pixelsPerRow + slot + var k := int(float(group * _pixelsPerRow + slot) * pointCount / (_rowCount * _pixelsPerRow)) + _spots[i] = shape.positions[k] + _spotColors[i] = shape.colors[k] + + +# The pixels of the frame we reform as, placed as the line's pose, nearest the +# mouth first. +func _get_line_shape(line: int) -> Dictionary: + if not _lineShapes[line].is_empty(): + return _lineShapes[line] + var spriteTransform: Transform2D = _linePoses[line].spriteTransform + var placed := PackedVector2Array() + for local: Vector2 in _endFrame.positions: + placed.append(spriteTransform * local) + var positions := PackedVector2Array() + var colors := PackedColorArray() + for k: int in _sorted_by_distance(placed, _lineMouths[line]): + positions.append(placed[k]) + colors.append(_endFrame.colors[k]) + _lineShapes[line] = {positions = positions, colors = colors} + return _lineShapes[line] + + +# Finishes if all the goo is out on one line, far enough to be back in shape. +func _check_all_out() -> bool: + var line := _lines[_active] + if line == -1: + return false + var outCount := 0 + for depth in range(GATHER_DISTANCE, _lineLength + 1): + if _rowAt[_line_vertex(line, depth)] != -1: + outCount += 1 + if outCount < _rowCount: + return false + exitPose = _linePoses[line] + isFinished = true + return true + + +func _direction(from: int, to: int) -> Vector2: + return (_positions[to] - _positions[from]).normalized() + + +# Indices of `points`, nearest to `target` first. +static func _sorted_by_distance(points: PackedVector2Array, target: Vector2) -> Array: + var order := range(points.size()) + order.sort_custom(func(a: int, b: int) -> bool: + return points[a].distance_squared_to(target) < points[b].distance_squared_to(target)) + return order + + +# ---- Drawing ---- + +func _draw() -> void: + if _colors.is_empty(): + return + for vertex in _rowAt.size(): + var row := _rowAt[vertex] + if row < 0: + continue + var line := _lines[vertex] + var across := _across(vertex) + for slot in _pixelsPerRow: + var i := row * _pixelsPerRow + slot + var laneOffset := across * (slot % _laneCount - (_laneCount - 1) / 2.0) + var spot := _positions[vertex] + laneOffset + var color := _colors[i] + if line != -1: + # Out past a mouth: gathering into its place in the slime. + var gathered := clampf(float(_depths[vertex]) / GATHER_DISTANCE, 0.0, 1.0) + spot = (_lineMouths[line] + laneOffset).lerp(_spots[i], gathered) + color = color.lerp(_spotColors[i], gathered) + draw_rect(Rect2(spot.floor(), Vector2.ONE), color) + _draw_growth_cues() + if SHOW_ACTIVE and _active != -1: + draw_rect(Rect2(_positions[_active].floor() - Vector2.ONE, Vector2.ONE * 3), Color.RED, false) + + +# A faint pulse just into each empty branch the goo could grow into, brighter +# for the one it's growing into now. +func _draw_growth_cues() -> void: + var pulse := 0.5 + 0.5 * sin(_time * PULSE_SPEED) + for vertex in _rowAt.size(): + if _rowAt[vertex] == -1 or _lines[vertex] != -1: + continue + for next: int in _neighbors[vertex]: + if not _can_grow_into(vertex, next): + continue + var isActive := _cue == Vector2i(vertex, next) + var color := Color(1, 1, 1, (ACTIVE_PULSE_ALPHA if isActive else PULSE_ALPHA) * pulse) + var direction := _direction(vertex, next) + var across := _across_for(direction) + # Start past the goo's edge: at a junction, the goo crossing it + # spreads half a tube's width into the branch. + var firstStep := _laneCount / 2 + 1 + for step in range(firstStep, firstStep + PULSE_LENGTH): + for lane in _laneCount: + var spot := _positions[vertex] + direction * step + across * (lane - (_laneCount - 1) / 2.0) + draw_rect(Rect2(spot.floor(), Vector2.ONE), color) + + +# Which way a row's lanes spread at `vertex`: across the tube there. +func _across(vertex: int) -> Vector2: + var line := _lines[vertex] + if line != -1: + return _across_for(_lineOutwards[line]) + # Along the tube to goo next to it if there is some (at a bend or junction + # there's more than one way), otherwise to any neighbour. + var along := Vector2.ZERO + for other: int in _neighbors[vertex]: + if along == Vector2.ZERO or _rowAt[other] != -1: + along = _direction(vertex, other) + if _rowAt[other] != -1: + break + return _across_for(along) + + +# Rows across a tube going `along` always spread the same way (rightwards or +# downwards), so pixels don't swap sides when the goo changes direction. +static func _across_for(along: Vector2) -> Vector2: + return Vector2.DOWN if absf(along.x) > absf(along.y) else Vector2.RIGHT + + +# ---- Tube tiles ---- + +# Whether the tile at `cell` is a goo tube (the "tube_goo" custom data). +static func is_goo(layer: TileMapLayer, cell: Vector2i) -> bool: + var data := layer.get_cell_tile_data(cell) + if data == null or not data.has_custom_data("tube_goo"): + return false + return data.get_custom_data("tube_goo") diff --git a/Effects/tube_goo.gd.uid b/Effects/tube_goo.gd.uid new file mode 100644 index 0000000..b8ba2cd --- /dev/null +++ b/Effects/tube_goo.gd.uid @@ -0,0 +1 @@ +uid://bfwddelrq8ydu diff --git a/Effects/tube_steer.gd b/Effects/tube_steer.gd index 6003bed..43e7e19 100755 --- a/Effects/tube_steer.gd +++ b/Effects/tube_steer.gd @@ -1,77 +1,121 @@ class_name TubeSteer extends Node2D -# The slime squeezed into a manual tube. An invisible "leader" rides the tubes' -# centre lines, steered by the player's arrow keys, and the slime's pixels flow -# along the trail it leaves, a few abreast, like a string of goo. +# The slime squeezed into a manual tube as goo, moved by a "leader" the player +# steers. A circle pulses gently where the leader is (its look is set from the +# Player's inspector: see indicatorColor and friends). # -# Steering: -# - The leader only moves while you press along the tube. Let go and it stops. -# - At a bend or a crossing it takes the way you press. If nothing you press -# leads anywhere, it waits there. -# - Pressing towards a turn before you reach it carries you there to take it. -# - Pressing back the way you came reverses. The pixels back up along the trail. -# Back all the way out of the mouth you came in by and you reform where you were. -# - Pressing out of any other mouth (one with room for the slime) pours the -# pixels out, and they gather back into the slime's shape. Then isFinished -# goes true and exitPose says where we came out. +# - Going in, the goo is pulled all the way into the tubes by itself (pressing +# picks the way at junctions). We're never left half in and half out. +# - If the tubes are too short to hold the goo (a tube a single tile long, say), +# it squashes up to fit, with a little poking out of each mouth. +# - While the leader is inside the goo, it slides through it and the goo stays +# put. At a junction the goo covers, it slides round the corner into whichever +# arm of the goo you press towards. +# - Pressing a way into empty tube drags the goo that way. All the goo's other +# tips drain towards the leader, taking turns. So from the end of a string of +# goo it pulls the string along like a rope, and from a junction in its middle +# it pulls the goo in from both sides into the branch you chose. +# - Pressing towards a turn or junction before you reach it carries you there to +# take it. If nothing you press leads anywhere, the leader waits. +# - Dragging the goo out of a mouth with room for the slime (the one you came in +# by too) pours it out, and it gathers back into the slime's shape. Then +# isFinished goes true and exitPose says where we came out. +# +# Only the slime's coloured pixels go in. Its black outline (and eyes) are drawn +# fresh round whatever goo there is, so the goo in the tube has an outline too, +# and the slime gets its own back once it's gathered. +# +# The track is made of vertices one pixel apart. Each vertex the goo covers holds +# one row of pixels across the tube. If the goo would be longer than maxLength, +# the rows hold more pixels (overlapping) instead. Past each mouth with room for +# the slime is a straight "outside line". Goo out there gathers into the slime's +# shape. The goo starts out on the entry mouth's line, in the shape of the +# sprite that went in. # # Tubes are tiles tagged with which sides are open ("tube_openings") and, # for this kind, "tube_manual". A mouth that opens onto another kind of tile, # or that has no room for the slime outside it, is a dead end. -const SPEED = 150.0 # How fast the leader moves while pressed, in px/s. -const EXIT_SPEED = 200.0 # How fast the pixels pour out once we're leaving. -const ROW_SPACING = 1.0 # Gap between rows of pixels in the trail. -# How far past a mouth a pixel goes before it's back in its place in the slime. -const GATHER_DISTANCE = 24.0 +const SPEED = 150.0 # How fast the leader drags the goo while pressed, in px/s. +# How fast the leader slides through the goo while pressed, in px/s. Fast, so +# turning round to pull the other way is almost immediate. +const SLIDE_SPEED = 640.0 +const EXIT_SPEED = 200.0 # How fast the goo pours out once we're leaving. +const INTAKE_SPEED = 240.0 # How fast the goo is pulled in when we go in, in px/s. +# When the tubes are too short for the goo, how far it pokes out of each mouth. +const STICK_OUT = 3 +const GATHER_DISTANCE = 24 # How far past a mouth goo goes before it's in its place in the slime. # How much of the input must point along a way for us to move along it (0.5 lets # diagonals pick either way). const MIN_PULL = 0.5 +const LOOKAHEAD = 48 # How far along straight tube we look for a turn the input points along. +# Taken off a looked-ahead pull per vertex away, so the nearest turn the input +# points along wins. +const LOOKAHEAD_PENALTY = 0.0001 const MAX_TILES = 1024 # Stop mapping a tube network this big. -const MAX_NODES_PER_FRAME = 8 -const EPSILON = 0.001 -const OUT = -1 # A "way on" from a mouth: out of the tube. -const SHOW_LEADER = false # Draw the invisible leader, for debugging. +const MAX_STEPS_PER_FRAME = 32 +const OUTLINE_DARKNESS = 0.15 # Pixels darker than this are outline (or eyes), and don't go in. +const OUTLINE_COLOR = Color.BLACK +# The leader's circle pulses slowly between these opacities, getting brighter +# as it gets more opaque (from its colour as it is up to INDICATOR_MAX_LIGHTEN +# towards white). +const INDICATOR_PULSE_SPEED = 2.5 # Radians per second (a pulse every 2.5s or so). +const INDICATOR_MIN_OPACITY = 0.4 +const INDICATOR_MAX_OPACITY = 0.6 +const INDICATOR_MAX_LIGHTEN = 0.2 const DIRECTIONS: Array[Vector2i] = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT] +const NEIGHBORS_4: Array[Vector2i] = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT] +const NEIGHBORS_8: Array[Vector2i] = [Vector2i(-1, -1), Vector2i(0, -1), Vector2i(1, -1), + Vector2i(-1, 0), Vector2i(1, 0), Vector2i(-1, 1), Vector2i(0, 1), Vector2i(1, 1)] var isFinished := false var exitPose := {} # The pose we came out as (see start()). -# The track: points (nodes) at the middle of each tube tile and at each mouth. -var _nodePositions := PackedVector2Array() -var _nodeLinks: Array[Dictionary] = [] # Per node: {direction (Vector2i): the node that way}. -var _mouthOutwards := {} # Mouth node -> the way out of it (Vector2). -var _mouthPoses := {} # Mouth node -> the pose we come out as there ({} if there's no room). -var _entryMouth := -1 +# How the circle marking the leader looks. Set these before start(). +var indicatorColor := Color(1.0, 0.85, 0.3) +var indicatorBorderColor := Color.WHITE +var indicatorRadius := 4.0 -# The leader: on the track edge from _from to _to, _offset along it... -var _from := -1 -var _to := -1 -var _offset := 0.0 -# ...or, while _isOutsideEntry, _outside px out past the entry mouth (on the -# way in, or backing out). -var _isOutsideEntry := true -var _outside := 0.0 -var _exitMouth := -1 # Once we're leaving, the mouth we're leaving by. -var _exitStart := 0.0 # How long the trail was when the leader left by it. +# The track's vertices. +var _positions := PackedVector2Array() +var _neighbors: Array[Array] = [] # Per vertex: the vertices next to it. +var _lines := PackedInt32Array() # Per vertex: the outside line it's on, or -1 in the tubes. +var _depths := PackedInt32Array() # Per vertex on an outside line: how far out it is (1 = just past the mouth). -# Where the leader has been: from the entry mouth to where it is now. Backing up -# eats into it. -var _trail := PackedVector2Array() -var _trailLength := 0.0 +# The outside lines. +var _lineMouths := PackedVector2Array() +var _lineOutwards := PackedVector2Array() +var _lineStarts := PackedInt32Array() # The vertex at depth 1. +var _linePoses: Array[Dictionary] = [] # The pose we come out as there. +var _lineShapes: Array[Dictionary] = [] # That pose's pixels nearest the mouth first, worked out when needed. +var _lineLength := 0 +var _entryLine := -1 -# The pixels, in trail order: row 0 is right behind the leader. -var _starts := PackedVector2Array() # Where each pixel was in the sprite we went in as. -var _startColors := PackedColorArray() -var _ends := PackedVector2Array() # Where it goes in the sprite we come out as. -var _endColors := PackedColorArray() -var _rows := PackedInt32Array() -var _lanes := PackedFloat32Array() # How far left of the trail's middle it flows. -var _bodyLength := 0.0 # How far behind the leader the last row is. -# The frame we reform as, in the sprite's space. Placed once we know where. -var _endFrame := {} +# The goo. +var _rowAt := PackedInt32Array() # Per vertex: the row of pixels there, or -1 if empty. +var _shrunkAt := PackedInt32Array() # Per vertex: when the goo last shrank back to it. +var _clock := 0 +var _leader := -1 # The vertex the leader is on. +var _isTakingIn := true # While going in: the goo is pulled in by itself. +var _isPouring := false # Once we're leaving: the leader carries on out by itself. +# How far the goo can poke out of a mouth and still count as in: STICK_OUT if +# the tubes are too short for it, otherwise 0. +var _stickOut := 0 +var _moveOwed := 0.0 # Time we're owed moving but haven't used, in seconds. +var _time := 0.0 + +# The pixels: row r holds pixels r * _pixelsPerRow up to the next row's, going +# across its _laneCount lanes and round again. +var _rowCount := 0 +var _laneCount := 1 +var _pixelsPerRow := 1 +var _colors := PackedColorArray() +var _spots := PackedVector2Array() # Where each pixel goes in the shape it's gathering into outside. +var _spotColors := PackedColorArray() +var _rowLines := PackedInt32Array() # Per row: the outside line its spots are for, or -1. +var _endFrame := {} # The frame we reform as (no outline), in the sprite's space. # Squeezes into the tube at `entryCell` heading `entryDirection`. @@ -79,78 +123,121 @@ var _endFrame := {} # back in exitPose}. entryPose is the slime as it is now: backing out reforms us # there. findPose(mouth: Vector2, outward: Vector2) gives the pose for coming # out of a mouth, or {} if there's no room. endFrame: the frame we reform as. +# width: the tube's channel. The goo is narrower, to leave room for its outline. +# maxLength: the longest the goo can be. func start(sprite: Sprite2D, layer: TileMapLayer, entryCell: Vector2i, entryDirection: Vector2i, - width: float, entryPose: Dictionary, findPose: Callable, endFrame: int) -> void: + width: float, maxLength: float, entryPose: Dictionary, findPose: Callable, endFrame: int) -> void: top_level = true global_position = Vector2.ZERO z_index = sprite.z_index + 1 + _laneCount = maxi(int(width) - 2, 1) + var from := _without_outline(PixelStream.get_frame_pixels(sprite, sprite.frame, entryPose.spriteTransform)) + _endFrame = _without_outline(PixelStream.get_frame_pixels(sprite, endFrame, Transform2D.IDENTITY)) + if from.colors.is_empty() or _endFrame.colors.is_empty(): + exitPose = entryPose + isFinished = true + return + # If the frame we reform as has more pixels, or the last row isn't full, + # some are doubled up so none go missing. + var pixelCount := maxi(from.colors.size(), _endFrame.colors.size()) + _rowCount = mini(ceili(float(pixelCount) / _laneCount), maxi(int(maxLength), 1)) + _pixelsPerRow = ceili(float(pixelCount) / _rowCount) + _lineLength = _rowCount + GATHER_DISTANCE + _build_track(layer, entryCell, entryDirection, entryPose, findPose) - var from := PixelStream.get_frame_pixels(sprite, sprite.frame, entryPose.spriteTransform) - _endFrame = PixelStream.get_frame_pixels(sprite, endFrame, Transform2D.IDENTITY) - if _entryMouth == -1 or from.colors.is_empty() or _endFrame.colors.is_empty(): + if _entryLine == -1: exitPose = entryPose isFinished = true return - # The leader starts out past the entry mouth, far enough that every pixel - # is still in its place in the sprite. - _from = _nodeLinks[_entryMouth].values()[0] - _to = _entryMouth - _offset = _edge_length(_from, _to) - _isOutsideEntry = true - _outside = GATHER_DISTANCE - _trail = PackedVector2Array([_nodePositions[_entryMouth]]) + # Too long for the tubes: squash up to fit, poking out of the mouths a bit. + var tubeLength := _lines.count(-1) + if _rowCount > tubeLength: + _stickOut = STICK_OUT + _rowCount = maxi(mini(_rowCount, tubeLength + STICK_OUT * mini(_lineMouths.size(), 2)), 1) + _pixelsPerRow = ceili(float(pixelCount) / _rowCount) - # The pixels nearest the mouth go in first, a row of laneCount at a time. - # If the frame we reform as has more pixels, some are doubled up so none go - # missing. - var laneCount := maxi(int(width), 1) - var order := _sorted_by_distance(from.positions, _nodePositions[_entryMouth], false) - var count := maxi(order.size(), _endFrame.colors.size()) - for k in count: - var i: int = order[int(float(k) * order.size() / count)] - _starts.append(from.positions[i]) - _startColors.append(from.colors[i]) - _rows.append(floori(float(k) / laneCount)) - _lanes.append((k % laneCount) - (laneCount - 1) / 2.0) - _bodyLength = _rows[count - 1] * ROW_SPACING - _ends.resize(count) - _endColors.resize(count) + # The goo starts out on the entry mouth's line, far enough out that every + # pixel is still in its place in the sprite. The pixels nearest the mouth + # are in the rows nearest it, so they go in first. The leader starts at the + # tip nearest the mouth, ready to pull the goo in. + var count := _rowCount * _pixelsPerRow + var order := _sorted_by_distance(from.positions, _lineMouths[_entryLine]) + for i in count: + var k: int = order[int(float(i) * order.size() / count)] + _colors.append(from.colors[k]) + _spots.append(from.positions[k]) + _spotColors.append(from.colors[k]) + _rowLines.resize(_rowCount) + _rowLines.fill(_entryLine) + for row in _rowCount: + _rowAt[_line_vertex(_entryLine, GATHER_DISTANCE + row)] = row + _leader = _line_vertex(_entryLine, GATHER_DISTANCE) # Moves the leader for one physics frame. input: the player's input, with y down. func steer(input: Vector2, delta: float) -> void: if isFinished: return - if _exitMouth != -1: + if _isPouring: _pour_out(delta) return + if _isTakingIn: + _take_in(input.normalized() if input != Vector2.ZERO else input, delta) + return if input == Vector2.ZERO: + _moveOwed = 0.0 return input = input.normalized() - var distanceLeft := SPEED * delta - for i in MAX_NODES_PER_FRAME: - if distanceLeft <= EPSILON or isFinished or _exitMouth != -1: + + _moveOwed += delta + for i in MAX_STEPS_PER_FRAME: + # Slide through the goo or drag it, whichever the input points along best. + var slide := _best_slide(input) + var drag := _best_drag(input) + if maxf(slide.pull, drag.pull) < MIN_PULL: + _moveOwed = 0.0 # Waiting for the player to press a way that leads somewhere. + break + var isSliding: bool = slide.pull > drag.pull + var stepTime := 1.0 / (SLIDE_SPEED if isSliding else SPEED) + if _moveOwed < stepTime: + break + _moveOwed -= stepTime + if isSliding: + _leader = slide.vertex + else: + _drag_into(drag.vertex) + if isFinished or _isPouring: break - var moved := _step(input, distanceLeft) - if moved < 0.0: - break # Waiting for the player to press a way that leads somewhere. - distanceLeft -= moved -func _process(_delta: float) -> void: +func _process(delta: float) -> void: + _time += delta queue_redraw() # ---- Setup ---- -# Maps out the manual tube network from `entryCell`. +# The frame's pixels without its dark outline and eyes. +static func _without_outline(frame: Dictionary) -> Dictionary: + var positions := PackedVector2Array() + var colors := PackedColorArray() + for i in frame.colors.size(): + var color: Color = frame.colors[i] + if color.get_luminance() >= OUTLINE_DARKNESS: + positions.append(frame.positions[i]) + colors.append(color) + return {positions = positions, colors = colors} + + +# Maps out the manual tube network from `entryCell` as vertices a pixel apart, +# plus an outside line past each mouth we can come out of. func _build_track(layer: TileMapLayer, entryCell: Vector2i, entryDirection: Vector2i, entryPose: Dictionary, findPose: Callable) -> void: - var cellNodes := {entryCell: _add_node(_cell_point(layer, entryCell, Vector2i.ZERO))} + var cellVertices := {entryCell: _add_vertex(cell_point(layer, entryCell, Vector2i.ZERO))} var toVisit: Array[Vector2i] = [entryCell] - while not toVisit.is_empty() and cellNodes.size() < MAX_TILES: + while not toVisit.is_empty() and cellVertices.size() < MAX_TILES: var cell: Vector2i = toVisit.pop_front() var openings := get_openings(layer, cell) for direction in DIRECTIONS: @@ -158,243 +245,502 @@ func _build_track(layer: TileMapLayer, entryCell: Vector2i, entryDirection: Vect continue var nextCell := cell + direction if is_manual(layer, nextCell) and get_openings(layer, nextCell) & side_bit(-direction): - if not cellNodes.has(nextCell): - cellNodes[nextCell] = _add_node(_cell_point(layer, nextCell, Vector2i.ZERO)) + if not cellVertices.has(nextCell): + cellVertices[nextCell] = _add_vertex(cell_point(layer, nextCell, Vector2i.ZERO)) toVisit.append(nextCell) - _link(cellNodes[cell], cellNodes[nextCell], direction) + # Each pair of tiles is joined once, from its left or top tile. + if direction == Vector2i.RIGHT or direction == Vector2i.DOWN: + _join(cellVertices[cell], cellVertices[nextCell]) elif layer.get_cell_source_id(nextCell) == -1: # A mouth into open space. - var mouthPosition := _cell_point(layer, cell, direction) - var mouth := _add_node(mouthPosition) - _link(cellNodes[cell], mouth, direction) - _mouthOutwards[mouth] = Vector2(direction) - if cell == entryCell and direction == -entryDirection: - _entryMouth = mouth - _mouthPoses[mouth] = entryPose - else: - _mouthPoses[mouth] = findPose.call(mouthPosition, Vector2(direction)) + var mouthPosition := cell_point(layer, cell, direction) + var mouth := _add_vertex(mouthPosition) + _join(cellVertices[cell], mouth) + var isEntry := cell == entryCell and direction == -entryDirection + var pose: Dictionary = entryPose if isEntry else findPose.call(mouthPosition, Vector2(direction)) + if pose.is_empty(): + continue # No room out there: a dead end. + if isEntry: + _entryLine = _lineMouths.size() + _add_outside_line(mouth, Vector2(direction), pose) # Otherwise it opens into something solid: a dead end. -func _add_node(at: Vector2) -> int: - _nodePositions.append(at) - _nodeLinks.append({}) - return _nodePositions.size() - 1 +func _add_vertex(at: Vector2, line := -1, depth := 0) -> int: + _positions.append(at) + _neighbors.append([]) + _lines.append(line) + _depths.append(depth) + _rowAt.append(-1) + _shrunkAt.append(0) + return _positions.size() - 1 -func _link(from: int, to: int, direction: Vector2i) -> void: - _nodeLinks[from][direction] = to - _nodeLinks[to][-direction] = from +func _connect(a: int, b: int) -> void: + _neighbors[a].append(b) + _neighbors[b].append(a) -# ---- Steering ---- - -# Moves the leader up to `distance`, but no further than the next node. -# Returns how far it moved, or -1 if it can't move the way the input points. -func _step(input: Vector2, distance: float) -> float: - if _isOutsideEntry: - return _step_outside_entry(input, distance) - - var edgeLength := _edge_length(_from, _to) - var direction := _edge_direction(_from, _to) - if _offset >= edgeLength - EPSILON: - # At a node: take the way on the input points along most (back counts). - var way := _best_way_on(_to, input, -2) - if way.pull < MIN_PULL: - return -1.0 - if way.node == OUT: - _leave_by(_to) - else: - _from = _to - _to = way.node - _offset = 0.0 - return 0.0 - - # Partway along an edge: carry on, or turn back. A way on from the node - # ahead (or behind) counts too, so pressing towards a turn takes us to it. - var aheadPull := maxf(input.dot(direction), _best_way_on(_to, input, _from).pull) - var behindPull := maxf(-input.dot(direction), _best_way_on(_from, input, _to).pull) - if maxf(aheadPull, behindPull) < MIN_PULL: - return -1.0 - if behindPull > aheadPull: - var oldFrom := _from - _from = _to - _to = oldFrom - _offset = edgeLength - _offset - direction = -direction - var step := minf(distance, edgeLength - _offset) - _offset += step - _move_trail(direction, step) - return step +# Joins two vertices with a straight run of vertices a pixel apart. +func _join(a: int, b: int) -> void: + var from := _positions[a] + var to := _positions[b] + var steps := maxi(roundi(from.distance_to(to)), 1) + var previous := a + for step in range(1, steps): + var vertex := _add_vertex(from.lerp(to, float(step) / steps)) + _connect(previous, vertex) + previous = vertex + _connect(previous, b) -# Out past the entry mouth: in towards it, or further out to reform where we -# went in. -func _step_outside_entry(input: Vector2, distance: float) -> float: - var pull := input.dot(-_mouthOutwards[_entryMouth]) - if pull >= MIN_PULL: - var step := minf(distance, _outside) - _outside -= step - if _outside <= EPSILON: - _outside = 0.0 - _isOutsideEntry = false - return step - if -pull >= MIN_PULL: - var step := minf(distance, GATHER_DISTANCE - _outside) - _outside += step - if _outside >= GATHER_DISTANCE - EPSILON: - exitPose = _mouthPoses[_entryMouth] - isFinished = true - return step - return -1.0 +func _add_outside_line(mouth: int, outward: Vector2, pose: Dictionary) -> void: + var line := _lineMouths.size() + _lineMouths.append(_positions[mouth]) + _lineOutwards.append(outward) + _linePoses.append(pose) + _lineShapes.append({}) + _lineStarts.append(_positions.size()) + var previous := mouth + for depth in range(1, _lineLength + 1): + var vertex := _add_vertex(_positions[mouth] + outward * depth, line, depth) + _connect(previous, vertex) + previous = vertex -# The way on from `node` the input points along most: {pull, node}. `node` is OUT -# for leaving the tube there. Never back to `exclude`. -func _best_way_on(node: int, input: Vector2, exclude: int) -> Dictionary: - var best := {pull = -INF, node = -2} - var links: Dictionary = _nodeLinks[node] - for way: Vector2i in links: - if links[way] == exclude: +func _line_vertex(line: int, depth: int) -> int: + return _lineStarts[line] + depth - 1 + + +# ---- Going in ---- + +# Pulls the goo into the tubes from the entry mouth, growing it at the leader +# (the way the input points at junctions, otherwise straight on if it can). +func _take_in(input: Vector2, delta: float) -> void: + _moveOwed += delta + for i in MAX_STEPS_PER_FRAME: + if _moveOwed < 1.0 / INTAKE_SPEED: + return + _moveOwed -= 1.0 / INTAKE_SPEED + var tail := _entry_tail() + var growth := _intake_growth(input) + if tail == -1 or growth.y == -1: + break # All in (or nowhere left to put it). + _grow(growth.x, growth.y, tail) + if growth.x == _leader: + _leader = growth.y + if _entry_tail() == -1 or _intake_growth(input).y == -1: + _isTakingIn = false + _moveOwed = 0.0 + + +# The goo vertex furthest out on the entry line, if it's further than the goo +# can poke out. Otherwise -1: it's all in. +func _entry_tail() -> int: + for depth in range(_lineLength, _stickOut, -1): + var vertex := _line_vertex(_entryLine, depth) + if _rowAt[vertex] != -1: + return vertex + return -1 + + +# Where to grow the goo going in: (a goo vertex, the empty one to grow into). +# At the leader if it can, otherwise anywhere in the tubes. (-1, -1) if nowhere. +func _intake_growth(input: Vector2) -> Vector2i: + var heading := Vector2.ZERO + for other: int in _neighbors[_leader]: + if _rowAt[other] != -1: + heading = _direction(other, _leader) + var best := Vector2i(-1, -1) + var bestScore := -INF + for next: int in _neighbors[_leader]: + if not _can_take_in_to(_leader, next): continue - var pull := input.dot(Vector2(way)) - if pull > best.pull: - best = {pull = pull, node = links[way]} - if _mouthOutwards.has(node) and _can_leave_by(node): - var pull := input.dot(_mouthOutwards[node]) - if pull > best.pull: - best = {pull = pull, node = OUT} + var direction := _direction(_leader, next) + # The input picks; straight on breaks ties. + var score := input.dot(direction) + 0.1 * heading.dot(direction) + if score > bestScore: + bestScore = score + best = Vector2i(_leader, next) + if best.y != -1: + return best + for vertex in _rowAt.size(): + if _rowAt[vertex] == -1 or _lines[vertex] != -1: + continue + for next: int in _neighbors[vertex]: + if _can_take_in_to(vertex, next): + return Vector2i(vertex, next) return best -func _can_leave_by(mouth: int) -> bool: - if mouth == _entryMouth and _trailLength <= EPSILON: - return true # Backing out the way we came. - return not (_mouthPoses[mouth] as Dictionary).is_empty() +# Whether the goo going in can grow from `vertex` into `next`: in towards the +# entry mouth, into the tubes, or just poking out of another mouth if the tubes +# are too short. +func _can_take_in_to(vertex: int, next: int) -> bool: + if not _can_grow_into(vertex, next): + return false + var line := _lines[next] + if line == -1: + return true + if line == _entryLine: + return _lines[vertex] == _entryLine and _depths[next] < _depths[vertex] + return _depths[next] <= _stickOut -func _leave_by(mouth: int) -> void: - if mouth == _entryMouth and _trailLength <= EPSILON: - _isOutsideEntry = true - _outside = 0.0 - return +# ---- Sliding ---- - # On our way out for good. The first rows out go furthest from the mouth, so - # pixels don't cross paths much. - _exitMouth = mouth - _exitStart = _trailLength - var spriteTransform: Transform2D = _mouthPoses[mouth].spriteTransform - var endPositions := PackedVector2Array() - for local: Vector2 in _endFrame.positions: - endPositions.append(spriteTransform * local) - var order := _sorted_by_distance(endPositions, _nodePositions[mouth], true) - var count := _starts.size() - for k in count: - var j: int = order[int(float(k) * order.size() / count)] - _ends[k] = endPositions[j] - _endColors[k] = _endFrame.colors[j] +# The goo vertex next to the leader to slide onto for the input: {pull, vertex}. +func _best_slide(input: Vector2) -> Dictionary: + var best := {pull = -INF, vertex = -1} + for next: int in _neighbors[_leader]: + if _rowAt[next] == -1: + continue + var pull := _slide_pull(_leader, next, input) + if pull > best.pull: + best = {pull = pull, vertex = next} + return best + + +# How well the input points at sliding from `from` onto `first`. Looks along the +# goo for the first turn, junction or tip ahead, so pressing towards a turn (or +# a way on from there) carries us to it. +func _slide_pull(from: int, first: int, input: Vector2) -> float: + var direction := _direction(from, first) + var pull := input.dot(direction) + if pull >= MIN_PULL: + return pull + var previous := from + var current := first + for i in _rowCount: + var penalty := (i + 1) * LOOKAHEAD_PENALTY + if _neighbors[current].size() >= 3 or _is_tip(current): + # A junction or the goo's tip: any way on from there, through the + # goo or into empty tube. + for other: int in _neighbors[current]: + if other == previous: + continue + if _rowAt[other] != -1 or _can_grow_into(current, other): + pull = maxf(pull, input.dot(_direction(current, other)) - penalty) + if _rowAt[other] == -1 and _can_grow_into(current, other): + pull = maxf(pull, _lookahead_pull(current, other, input) - penalty) + return pull + var next := -1 + for other: int in _neighbors[current]: + if other != previous and _rowAt[other] != -1: + next = other + var nextDirection := _direction(current, next) + if not nextDirection.is_equal_approx(direction): + return maxf(pull, input.dot(nextDirection) - penalty) # A bend. + previous = current + current = next + return pull + + +func _is_tip(vertex: int) -> bool: + var gooNeighbors := 0 + for other: int in _neighbors[vertex]: + if _rowAt[other] != -1: + gooNeighbors += 1 + return gooNeighbors <= 1 + + +# ---- Dragging ---- + +# The empty vertex next to the leader to drag the goo into for the input: +# {pull, vertex}. +func _best_drag(input: Vector2) -> Dictionary: + var best := {pull = -INF, vertex = -1} + var isTip := _is_tip(_leader) + for next: int in _neighbors[_leader]: + if not _can_grow_into(_leader, next): + continue + var pull := input.dot(_direction(_leader, next)) + if pull < MIN_PULL and isTip: + pull = maxf(pull, _lookahead_pull(_leader, next, input)) + if pull > best.pull: + best = {pull = pull, vertex = next} + return best + + +# Whether the goo at `vertex` can grow into `next`: it's empty, and growing +# there wouldn't join up with goo somewhere else (round a loop). +func _can_grow_into(vertex: int, next: int) -> bool: + if _rowAt[next] != -1: + return false + for other: int in _neighbors[next]: + if other != vertex and _rowAt[other] != -1: + return false + return true + + +# From the leader's tip going onto `next`, how well the input points along a +# way on from the turn or junction at the end of the straight run ahead. +func _lookahead_pull(tip: int, next: int, input: Vector2) -> float: + var previous := tip + var current := next + for i in LOOKAHEAD: + var ways := _neighbors[current].filter(func(other: int) -> bool: return other != previous) + var isStraightOn := ways.size() == 1 and _direction(current, ways[0]).is_equal_approx(_direction(previous, current)) + if isStraightOn and _rowAt[ways[0]] == -1: + previous = current + current = ways[0] + continue + var best := -INF + for way: int in ways: + if _rowAt[way] == -1: + best = maxf(best, input.dot(_direction(current, way))) + return best - (i + 1) * LOOKAHEAD_PENALTY + return -INF + + +# Drags the goo from the leader into `next`, and the leader with it. +func _drag_into(next: int) -> void: + _grow(_leader, next) + _leader = next + if _lines[next] != -1 and _depths[next] > _stickOut: + _isPouring = true # Out of a mouth: pour the rest out after it. + else: + _check_gathered() + + +# Grows the goo from `vertex` into `next`, and shrinks it at `tip`, or if that's +# -1, at the tip that's gone longest without shrinking. Taking turns like this +# drains all the tips at once. The goo between that tip and `next` flows along a +# vertex. +func _grow(vertex: int, next: int, tip := -1) -> void: + _rowAt[next] = -2 # Goo, but which row is sorted out below. + if tip == -1: + tip = _pick_tip_to_shrink(next) + var path := _goo_path(tip, next) + for i in range(path.size() - 1, 0, -1): + _rowAt[path[i]] = _rowAt[path[i - 1]] + _rowAt[tip] = -1 + _clock += 1 + _shrunkAt[path[1]] = _clock + for i in range(1, path.size()): + _update_row_line(_rowAt[path[i]], path[i]) + + +func _pick_tip_to_shrink(exclude: int) -> int: + var best := -1 + for vertex in _rowAt.size(): + if _rowAt[vertex] == -1 or vertex == exclude or not _is_tip(vertex): + continue + if best == -1 or _shrunkAt[vertex] < _shrunkAt[best]: + best = vertex + return best + + +# The vertices from `from` to `to` through the goo. +func _goo_path(from: int, to: int) -> PackedInt32Array: + var cameFrom := {to: -1} + var queue: Array[int] = [to] + while not queue.is_empty() and not cameFrom.has(from): + var vertex: int = queue.pop_front() + for other: int in _neighbors[vertex]: + if _rowAt[other] != -1 and not cameFrom.has(other): + cameFrom[other] = vertex + queue.append(other) + var path := PackedInt32Array() + var vertex := from + while vertex != -1: + path.append(vertex) + vertex = cameFrom[vertex] + return path # Once we're leaving, the leader carries on out by itself, pulling the rest of -# the pixels after it. +# the goo out after it. func _pour_out(delta: float) -> void: - _move_trail(_mouthOutwards[_exitMouth], EXIT_SPEED * delta) - if _trailLength - _bodyLength >= _exitStart + GATHER_DISTANCE: - exitPose = _mouthPoses[_exitMouth] - isFinished = true + _moveOwed += delta + for i in MAX_STEPS_PER_FRAME: + if _moveOwed < 1.0 / EXIT_SPEED or isFinished: + break + _moveOwed -= 1.0 / EXIT_SPEED + if _depths[_leader] >= _lineLength: + break # Shouldn't happen: we're gathered before the line runs out. + var next := _line_vertex(_lines[_leader], _depths[_leader] + 1) + _grow(_leader, next) + _leader = next + _check_gathered() -# Extends the trail as the leader moves, or eats into it if it's backing up. -func _move_trail(direction: Vector2, distance: float) -> void: - if _trail.size() >= 2: - var last := _trail[_trail.size() - 1] - _trail[_trail.size() - 2] - var lastLength := last.length() - var alignment := last.dot(direction) / lastLength - if alignment < -0.5: - # Backing up. A step never passes a node, so it stays within this piece. - if distance < lastLength - EPSILON: - _trail[_trail.size() - 1] -= last / lastLength * distance - _trailLength -= distance - else: - _trail.remove_at(_trail.size() - 1) - _trailLength = maxf(_trailLength - lastLength, 0.0) - return - if alignment > 0.5: - _trail[_trail.size() - 1] += direction * distance - _trailLength += distance - return - _trail.append(_trail[_trail.size() - 1] + direction * distance) - _trailLength += distance +# The outside line all the goo is out on, far enough to be back in shape, or -1. +func _gathered_line() -> int: + for line in _lineMouths.size(): + var outCount := 0 + for depth in range(GATHER_DISTANCE, _lineLength + 1): + if _rowAt[_line_vertex(line, depth)] != -1: + outCount += 1 + if outCount == _rowCount: + return line + return -1 -func _edge_length(from: int, to: int) -> float: - return _nodePositions[from].distance_to(_nodePositions[to]) +func _check_gathered() -> void: + var line := _gathered_line() + if line != -1: + _finish(line) -func _edge_direction(from: int, to: int) -> Vector2: - return (_nodePositions[to] - _nodePositions[from]).normalized() +func _finish(line: int) -> void: + exitPose = _linePoses[line] + isFinished = true -# Indices of `points`, nearest to `target` first (or furthest first). -func _sorted_by_distance(points: PackedVector2Array, target: Vector2, furthestFirst: bool) -> Array: +# When a row moves onto an outside line, picks the spots its pixels gather +# into there. The first rows out take the spots furthest from the mouth, so +# pixels don't cross paths much. +func _update_row_line(row: int, vertex: int) -> void: + var line := _lines[vertex] + if line == _rowLines[row]: + return + _rowLines[row] = line + if line == -1: + return + + var alreadyOut := 0 + for other in _rowCount: + if other != row and _rowLines[other] == line: + alreadyOut += 1 + var group := _rowCount - 1 - alreadyOut + + var shape := _get_line_shape(line) + var pointCount: int = shape.positions.size() + for slot in _pixelsPerRow: + var i := row * _pixelsPerRow + slot + var k := int(float(group * _pixelsPerRow + slot) * pointCount / (_rowCount * _pixelsPerRow)) + _spots[i] = shape.positions[k] + _spotColors[i] = shape.colors[k] + + +# The pixels of the frame we reform as, placed as the line's pose, nearest the +# mouth first. +func _get_line_shape(line: int) -> Dictionary: + if not _lineShapes[line].is_empty(): + return _lineShapes[line] + var spriteTransform: Transform2D = _linePoses[line].spriteTransform + var placed := PackedVector2Array() + for local: Vector2 in _endFrame.positions: + placed.append(spriteTransform * local) + var positions := PackedVector2Array() + var colors := PackedColorArray() + for k: int in _sorted_by_distance(placed, _lineMouths[line]): + positions.append(placed[k]) + colors.append(_endFrame.colors[k]) + _lineShapes[line] = {positions = positions, colors = colors} + return _lineShapes[line] + + +func _direction(from: int, to: int) -> Vector2: + return (_positions[to] - _positions[from]).normalized() + + +# Indices of `points`, nearest to `target` first. +static func _sorted_by_distance(points: PackedVector2Array, target: Vector2) -> Array: var order := range(points.size()) order.sort_custom(func(a: int, b: int) -> bool: - var aDistance := points[a].distance_squared_to(target) - var bDistance := points[b].distance_squared_to(target) - if furthestFirst: - return aDistance > bDistance - return aDistance < bDistance) + return points[a].distance_squared_to(target) < points[b].distance_squared_to(target)) return order # ---- Drawing ---- func _draw() -> void: - if _starts.is_empty(): + if _leader == -1: return - # How far along the trail the leader is (negative while out past the entry). - var leaderDistance := _trailLength - (_outside if _isOutsideEntry else 0.0) - var trailDistances := PackedFloat32Array([0.0]) - for i in range(1, _trail.size()): - trailDistances.append(trailDistances[i - 1] + _trail[i - 1].distance_to(_trail[i])) + # Work out where every pixel goes first, so the outline can go round them. + # Pixels on their way between the tube and their place in the slime don't + # get an outline: it would speckle them all in black. + var pixels := {} # Vector2i -> Color, for pixels in the tubes or in their place. + var movingPixels := {} # The same, for pixels on their way. + var inTubes := {} # Vector2i -> true, for pixels in the tubes. + var leaderCentre := Vector2.ZERO # Where the leader's row is, on average. + var leaderPixelCount := 0 + for vertex in _rowAt.size(): + var row := _rowAt[vertex] + if row < 0: + continue + var line := _lines[vertex] + var across := _across(vertex) + # The goo's ends in the tubes are rounded: the very end row only fills + # the middle lanes, so the outline curves round it. + var isRoundedEnd := line == -1 and _laneCount > 2 and _is_tip(vertex) + for slot in _pixelsPerRow: + var i := row * _pixelsPerRow + slot + var lane := 1 + slot % (_laneCount - 2) if isRoundedEnd else slot % _laneCount + var laneOffset := across * (lane - (_laneCount - 1) / 2.0) + var spot := _positions[vertex] + laneOffset + var color := _colors[i] + if line != -1: + # Out past a mouth: gathering into its place in the slime. + var gathered := clampf(float(_depths[vertex]) / GATHER_DISTANCE, 0.0, 1.0) + spot = (_lineMouths[line] + laneOffset).lerp(_spots[i], gathered) + color = color.lerp(_spotColors[i], gathered) + var at := Vector2i(spot.floor()) + if vertex == _leader: + leaderCentre += Vector2(at) + Vector2.ONE * 0.5 + leaderPixelCount += 1 + if line != -1 and _depths[vertex] < GATHER_DISTANCE: + movingPixels[at] = color + else: + pixels[at] = color + if line == -1: + inTubes[at] = true - var entryMouth := _nodePositions[_entryMouth] - var entryLeft := (-_mouthOutwards[_entryMouth] as Vector2).orthogonal() # Left of travel going in. - for k in _starts.size(): - var distance := leaderDistance - _rows[k] * ROW_SPACING - var color := _startColors[k] - var spot: Vector2 - if distance < 0.0: - # Not in yet: drawn from its place in the sprite towards the mouth. - var gathered := clampf(-distance / GATHER_DISTANCE, 0.0, 1.0) - spot = (entryMouth + entryLeft * _lanes[k]).lerp(_starts[k], gathered) - elif _exitMouth != -1 and distance > _exitStart: - # Out: gathering into its place in the reformed sprite. - var exitMouth := _nodePositions[_exitMouth] - var exitLeft := (_mouthOutwards[_exitMouth] as Vector2).orthogonal() - var gathered := clampf((distance - _exitStart) / GATHER_DISTANCE, 0.0, 1.0) - spot = (exitMouth + exitLeft * _lanes[k]).lerp(_ends[k], gathered) - color = color.lerp(_endColors[k], gathered) - else: - spot = _point_on_trail(distance, _lanes[k], trailDistances) - draw_rect(Rect2(spot.floor(), Vector2.ONE), color) + # The outline: every empty pixel touching the goo. Out of the tubes, corners + # count, like the slime's own outline. In them they don't, so the goo's + # rounded ends get a rounded outline. + var outlined := {} + for at: Vector2i in pixels: + for offset in (NEIGHBORS_4 if inTubes.has(at) else NEIGHBORS_8): + var spot: Vector2i = at + offset + if pixels.has(spot) or outlined.has(spot): + continue + outlined[spot] = true + draw_rect(Rect2(Vector2(spot), Vector2.ONE), OUTLINE_COLOR) + for at: Vector2i in pixels: + draw_rect(Rect2(Vector2(at), Vector2.ONE), pixels[at]) + for at: Vector2i in movingPixels: + draw_rect(Rect2(Vector2(at), Vector2.ONE), movingPixels[at]) - if SHOW_LEADER: - var leader := _point_on_trail(maxf(leaderDistance, 0.0), 0.0, trailDistances) - draw_rect(Rect2(leader.floor() - Vector2.ONE, Vector2.ONE * 3), Color.RED, false) + if leaderPixelCount > 0: + _draw_indicator(leaderCentre / leaderPixelCount) -# The point `distance` along the trail, moved `lane` to the left of travel. -func _point_on_trail(distance: float, lane: float, trailDistances: PackedFloat32Array) -> Vector2: - if _trail.size() < 2: - return _trail[0] + (-_mouthOutwards[_entryMouth] as Vector2).orthogonal() * lane - var segment := 0 - while segment < _trail.size() - 2 and distance > trailDistances[segment + 1]: - segment += 1 - var from := _trail[segment] - var to := _trail[segment + 1] - var direction := (to - from).normalized() - return from + direction * (distance - trailDistances[segment]) + direction.orthogonal() * lane +# The circle marking the leader, pulsing its opacity and brightness slowly. +func _draw_indicator(centre: Vector2) -> void: + var wave := 0.5 + 0.5 * sin(_time * INDICATOR_PULSE_SPEED) + var opacity := lerpf(INDICATOR_MIN_OPACITY, INDICATOR_MAX_OPACITY, wave) + var lighten := INDICATOR_MAX_LIGHTEN * wave + var fill := indicatorColor.lightened(lighten) + fill.a *= opacity + var border := indicatorBorderColor.lightened(lighten) + border.a *= opacity + draw_circle(centre, indicatorRadius, fill) + draw_circle(centre, indicatorRadius, border, false, 1.0) + + +# Which way a row's lanes spread at `vertex`: across the tube there. +func _across(vertex: int) -> Vector2: + var line := _lines[vertex] + if line != -1: + return _across_for(_lineOutwards[line]) + # Along the tube to goo next to it if there is some (at a bend or junction + # there's more than one way), otherwise to any neighbour. + var along := Vector2.ZERO + for other: int in _neighbors[vertex]: + if along == Vector2.ZERO or _rowAt[other] != -1: + along = _direction(vertex, other) + if _rowAt[other] != -1: + break + return _across_for(along) + + +# Rows across a tube going `along` always spread the same way (rightwards or +# downwards), so pixels don't swap sides when the goo changes direction. +static func _across_for(along: Vector2) -> Vector2: + return Vector2.DOWN if absf(along.x) > absf(along.y) else Vector2.RIGHT # ---- Tube tiles ---- @@ -426,6 +772,6 @@ static func side_bit(direction: Vector2i) -> int: # The global middle of `cell`'s side facing `side`, or its centre for Vector2i.ZERO. -static func _cell_point(layer: TileMapLayer, cell: Vector2i, side: Vector2i) -> Vector2: +static func cell_point(layer: TileMapLayer, cell: Vector2i, side: Vector2i) -> Vector2: var halfTile := Vector2(layer.tile_set.tile_size) / 2.0 return layer.to_global(layer.map_to_local(cell) + Vector2(side) * halfTile) diff --git a/Levels/test_level.tscn b/Levels/test_level.tscn index ba0cf80..b00b1db 100755 --- a/Levels/test_level.tscn +++ b/Levels/test_level.tscn @@ -10,7 +10,7 @@ position = Vector2(329, 266) [node name="TileMapLayer" type="TileMapLayer" parent="." unique_id=459516426] -tile_map_data = PackedByteArray("AAAAAA4AAAAAAAAAAAABAA4AAAAAAAAAAAACAA4AAAAAAAAAAAADAA4AAAAAAAAAAAAEAA4AAAAAAAAAAAAFAA4AAAAAAAAAAAAGAA4AAAAAAAAAAAAHAA4AAAAAAAAAAAAIAA4AAAAAAAAAAAAJAA4AAAAAAAAAAAAKAA4AAAAAAAAAAAALAA4AAAAAAAAAAAAMAA4AAAAAAAAAAAANAA4AAAAAAAAAAAAOAA4AAAAAAAAAAAAPAA4AAAAAAAAAAAAQAA4AAAAAAAAAAAARAA4AAAAAAAAAAAASAA4AAAAAAAAAAAATAA4AAAAAAAAAAAAKAAsAAAAAAAAAAAAJAAsAAAAAAAAAAAAJAAwAAAAAAAAAAAAJAA0AAAABAAAAAAAKAA0AAAABAAAAAAAKAAwAAAAAAAAAAA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IAAAACAAAAAAAOAAIAAAACAAAAAAAQAAIAAAAAAAAAAAAPAAIAAAAAAAAAAAASAAEAAAAAAAAAAAASAAIAAAAAAAAAAAASAAMAAAAAAAAAAAANAAIAAAAAAAAAAAAMAAEAAAAAAAAAAAAKAAMAAAAAAAAAAAAJAAMAAAAAAAAAAAAGAAMAAAAAAAAAAAAFAAMAAAAAAAAAAAAIAAMAAAAAAAAAAAAGAAYAAAAAAAAAAAAHAAYAAAAAAAAAAAAIAAYAAAAAAAAAAAANAAEAAAAAAAAAAAAKAAEAAAAAAAAAAAABAA0AAAAEAAAAAAABAAwAAAACAAAAAAABAAsAAAACAAAAAAABAAoAAAACAAAAAAABAAkAAAABAAEAAAADAAkAAAABAAAAAAAEAAkAAAABAAAAAAADAAwAAAAAAAAAAAADAA0AAAABAAAAAAACAA0AAAABAAAAAAACAAkAAAABAAAAAAADAAsAAAAAAAAAAAAEAA0AAAABAAAAAAAIAAsAAAAAAAAAAAAFAAsAAAAAAAAAAAAGAAsAAAAAAAAAAAAHAAsAAAACAAAAAAAOAAUAAAACAAAAAAAOAAYAAAACAAAAAAAOAAcAAAACAAAAAAAOAAgAAAACAAAAAAAOAAkAAAACAAAAAAA=") tile_set = ExtResource("2_4k50d") [node name="PauseMenu" parent="." unique_id=904032161 instance=ExtResource("3_pause")]