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. # # 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. # # 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 # 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 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 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: 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 # 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. # 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 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 := {} # 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: 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. func start(sprite: Sprite2D, layer: TileMapLayer, entryCell: Vector2i, entryDirection: Vector2i, width: float, entryPose: Dictionary, findPose: Callable, endFrame: int) -> void: top_level = true global_position = Vector2.ZERO z_index = sprite.z_index + 1 _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(): 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]]) # 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) # 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: _pour_out(delta) return if input == Vector2.ZERO: return input = input.normalized() var distanceLeft := SPEED * delta for i in MAX_NODES_PER_FRAME: if distanceLeft <= EPSILON or isFinished or _exitMouth != -1: 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: queue_redraw() # ---- Setup ---- # Maps out the manual tube network from `entryCell`. 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 toVisit: Array[Vector2i] = [entryCell] while not toVisit.is_empty() and cellNodes.size() < MAX_TILES: var cell: Vector2i = toVisit.pop_front() var openings := get_openings(layer, cell) for direction in DIRECTIONS: if openings & side_bit(direction) == 0: 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)) toVisit.append(nextCell) _link(cellNodes[cell], cellNodes[nextCell], direction) 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)) # 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 _link(from: int, to: int, direction: Vector2i) -> void: _nodeLinks[from][direction] = to _nodeLinks[to][-direction] = from # ---- 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 # 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 # 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: 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} 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() func _leave_by(mouth: int) -> void: if mouth == _entryMouth and _trailLength <= EPSILON: _isOutsideEntry = true _outside = 0.0 return # 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] # Once we're leaving, the leader carries on out by itself, pulling the rest of # the pixels 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 # 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 func _edge_length(from: int, to: int) -> float: return _nodePositions[from].distance_to(_nodePositions[to]) func _edge_direction(from: int, to: int) -> Vector2: return (_nodePositions[to] - _nodePositions[from]).normalized() # Indices of `points`, nearest to `target` first (or furthest first). func _sorted_by_distance(points: PackedVector2Array, target: Vector2, furthestFirst: bool) -> 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 order # ---- Drawing ---- func _draw() -> void: if _starts.is_empty(): 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])) 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) 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) # 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 # ---- Tube tiles ---- # Which sides of the tile at `cell` are open (TUBE_OPEN_... bits in player.gd). # 0 if it isn't a tube. static func get_openings(layer: TileMapLayer, cell: Vector2i) -> int: var data := layer.get_cell_tile_data(cell) if data == null: return 0 return data.get_custom_data("tube_openings") # Whether the tile at `cell` is a manual tube (the "tube_manual" custom data). static func is_manual(layer: TileMapLayer, cell: Vector2i) -> bool: var data := layer.get_cell_tile_data(cell) if data == null or not data.has_custom_data("tube_manual"): return false return data.get_custom_data("tube_manual") static func side_bit(direction: Vector2i) -> int: match direction: Vector2i.UP: return 1 Vector2i.RIGHT: return 2 Vector2i.DOWN: return 4 Vector2i.LEFT: return 8 return 0 # 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: var halfTile := Vector2(layer.tile_set.tile_size) / 2.0 return layer.to_global(layer.map_to_local(cell) + Vector2(side) * halfTile)