SlimePlatformer/Effects/pixel_stream.gd

286 lines
12 KiB
GDScript3
Raw Normal View History

2026-11-08 21:19:46 -06:00
class_name PixelStream
extends Node2D
# Takes a sprite's current frame apart into its pixels and pours them along a
# path as a stream, then puts them back together as a chosen frame somewhere
# else. Used for the slime squeezing through tubes.
# Every pixel sets off at once: they're drawn into the entry mouth nearest-first,
# flow along the path a few abreast, and fly out of the exit mouth so that they
# all land at the same moment.
# Pixels keep their colours on the way, and blend into the colour of the spot
# they land on, so the sprite reforms exactly.
# Watch isFinished to know when every pixel is back in place.
# Like TubeSteer, only the coloured pixels go in. A black outline is drawn fresh
# round the stream in the tube, and round pixels still (or back) at their spot
# in the sprite. Pixels flying between the two don't get one: it would speckle
# them all in black.
2026-11-08 21:19:46 -06:00
# Where the slime's pixels draw while in a tube (this and TubeSteer and TubeGoo):
# behind the tiles (z 0), which only show them through the tube's see-through
# channel. Goo going in or out of a mouth is hidden where it overlaps the tile.
# A background must go lower than this, or on its own CanvasLayer.
const GOO_Z_INDEX = -1
2026-11-08 21:19:46 -06:00
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, unless that would make it too long.
2026-11-08 21:19:46 -06:00
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.
const MAX_TRACE_TILES = 256 # Give up following a tube this long.
const SETTLED_DISTANCE = 1.0 # Pixels within this of their spot in the sprite get an outline.
2026-11-08 21:19:46 -06:00
var isFinished := false
var _startColors := PackedColorArray()
var _endColors := PackedColorArray()
var _starts := PackedVector2Array() # Where each pixel was in the sprite we took apart.
var _ends := PackedVector2Array() # Where it goes in the sprite we're putting back together.
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 _footprint := {} # Vector2i -> true, for every spot in the sprite we took apart or put back.
2026-11-08 21:19:46 -06:00
var _path := PackedVector2Array()
var _pathDistances := PackedFloat32Array() # How far along the path each point is.
var _time := 0.0
# path: global points from the entry mouth to the exit mouth.
# width: how wide the tube is. The stream is 2 pixels narrower, to leave room for its outline.
# maxLength: the longest the stream can be. Rows bunch up (overlapping) to fit.
2026-11-08 21:19:46 -06:00
# 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, maxLength: float,
endTransform: Transform2D, endFrame: int) -> void:
2026-11-08 21:19:46 -06:00
top_level = true
global_position = Vector2.ZERO
z_index = GOO_Z_INDEX
2026-11-08 21:19:46 -06:00
_path = path
_pathDistances.append(0.0)
for i in range(1, path.size()):
_pathDistances.append(_pathDistances[i - 1] + path[i - 1].distance_to(path[i]))
# Where the sprite is drawn now: snapped to whole pixels like the renderer does.
var startTransform := sprite.get_global_transform()
startTransform.origin = startTransform.origin.round()
var from := TubeSteer.without_outline(get_frame_pixels(sprite, sprite.frame, startTransform))
var to := TubeSteer.without_outline(get_frame_pixels(sprite, endFrame, endTransform))
2026-11-08 21:19:46 -06:00
if from.colors.is_empty() or to.colors.is_empty():
isFinished = true
return
_pair_pixels(from, to, maxi(int(width) - 2, 1))
for spot in from.positions + to.positions:
_footprint[Vector2i(spot.floor())] = true
_rowSpacing = minf(ROW_SPACING, maxLength / _rowCount)
2026-11-08 21:19:46 -06:00
# The path through an ordinary tube from the mouth of `cell` we go in heading
# `direction`, round each bend, to the mouth it comes out of into an empty tile.
# Empty if it's blocked or a dead end. The Player and MazeValidator use this.
static func trace_tube(layer: TileMapLayer, cell: Vector2i, direction: Vector2i) -> PackedVector2Array:
var path := PackedVector2Array([TubeSteer.cell_point(layer, cell, -direction)])
for step in MAX_TRACE_TILES:
var openings := TubeSteer.get_openings(layer, cell)
if openings & TubeSteer.side_bit(-direction) == 0:
return PackedVector2Array() # This tile doesn't connect to the last one.
# Straight on if we can (through crossings), otherwise round the bend.
if openings & TubeSteer.side_bit(direction) == 0:
var turn := Vector2i(-direction.y, direction.x)
if openings & TubeSteer.side_bit(turn) == 0:
turn = -turn
if openings & TubeSteer.side_bit(turn) == 0:
return PackedVector2Array() # Dead end.
path.append(TubeSteer.cell_point(layer, cell, Vector2i.ZERO))
direction = turn
var nextCell := cell + direction
if layer.get_cell_source_id(nextCell) == -1:
path.append(TubeSteer.cell_point(layer, cell, direction))
return path
cell = nextCell
return PackedVector2Array()
2026-11-08 21:19:46 -06:00
# The frame's opaque pixels (black ones too: they're the eyes) as .positions
# (global, through `spriteTransform`) and .colors. TubeSteer uses this too.
static func get_frame_pixels(sprite: Sprite2D, frame: int, spriteTransform: Transform2D) -> Dictionary:
2026-11-08 21:19:46 -06:00
var positions := PackedVector2Array()
var colors := PackedColorArray()
var image := _get_frame_image(sprite, frame)
if image != null:
image.convert(Image.FORMAT_RGBA8)
var size := image.get_size()
for y in size.y:
for x in size.x:
var color := image.get_pixel(x, y)
if color.a < 0.5:
continue
# Pixel centre in the sprite's local space (it's centered).
var local := Vector2(x, y) + Vector2.ONE * 0.5 - Vector2(size) / 2.0
if sprite.flip_h:
local.x = -local.x
if sprite.flip_v:
local.y = -local.y
positions.append(spriteTransform * (local + sprite.offset))
colors.append(color)
return {positions = positions, colors = colors}
# The pixels of one cell of the sprite's hframes x vframes sheet.
static func _get_frame_image(sprite: Sprite2D, frame: int) -> Image:
var image := sprite.texture.get_image()
if image == null:
return null
if image.is_compressed():
image.decompress()
var frameSize := image.get_size() / Vector2i(sprite.hframes, sprite.vframes)
var frameCoords := Vector2i(frame % sprite.hframes, floori(float(frame) / sprite.hframes))
return image.get_region(Rect2i(frameCoords * frameSize, frameSize))
# Gives each pixel a place in the stream and a spot in the reformed sprite. The
# pixels nearest the entry go in first, and the first ones out land furthest
# from the exit, so pixels don't cross paths much.
# If one frame has more pixels, some of the other's are doubled up so none go
# missing from either.
func _pair_pixels(from: Dictionary, to: Dictionary, laneCount: int) -> void:
var fromOrder := _sorted_by_distance(from.positions, _path[0], false)
var toOrder := _sorted_by_distance(to.positions, _path[_path.size() - 1], true)
var fromCount := fromOrder.size()
var toCount := toOrder.size()
var count := maxi(fromCount, toCount)
for k in count:
var i: int = fromOrder[int(float(k) * fromCount / count)]
var j: int = toOrder[int(float(k) * toCount / count)]
_starts.append(from.positions[i])
_startColors.append(from.colors[i])
_ends.append(to.positions[j])
_endColors.append(to.colors[j])
_lanes.append((k % laneCount) - (laneCount - 1) / 2.0)
_rows.append(floori(float(k) / laneCount))
_rowCount = _rows[count - 1] + 1
# 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
func _process(delta: float) -> void:
if isFinished:
return
_time += delta
if _time >= _duration():
isFinished = true
queue_redraw()
# ---- Timing ----
# When a row reaches the entry mouth. Each row is _rowSpacing behind the last.
2026-11-08 21:19:46 -06:00
func _enter_time(row: int) -> float:
return GATHER_TIME + row * _rowSpacing / SPEED
2026-11-08 21:19:46 -06:00
# When a row leaves the exit mouth.
func _exit_time(row: int) -> float:
return _enter_time(row) + _tube_length() / SPEED
# When every pixel is back in place.
func _duration() -> float:
return _exit_time(_rowCount - 1) + LAND_TIME
func _draw() -> void:
var tubeLength := _tube_length()
var duration := _duration()
# Work out where every pixel goes first, so the outline can go round them.
var pixels := {} # Vector2i -> Color, for pixels in the tube or at their spot.
var movingPixels := {} # The same, for pixels on their way.
var inTube := {} # Vector2i -> true, for pixels in the tube.
2026-11-08 21:19:46 -06:00
for i in _starts.size():
var row := _rows[i]
var enterTime := _enter_time(row)
var exitTime := _exit_time(row)
var spot: Vector2
var color := _startColors[i]
var settled := false
2026-11-08 21:19:46 -06:00
if _time < enterTime:
# Drawn in, speeding up towards the mouth.
var progress := _time / enterTime
spot = _starts[i].lerp(_point_on_path(0.0, _lanes[i]), progress * progress)
if spot.distance_to(_starts[i]) <= SETTLED_DISTANCE:
settled = true
spot = _starts[i] # Held in place, so the sprite's shape stays crisp.
2026-11-08 21:19:46 -06:00
elif _time < exitTime:
spot = _point_on_path((_time - enterTime) * SPEED, _lanes[i])
else:
# Out to its spot, slowing down to land with everyone else.
var progress := minf((_time - exitTime) / (duration - exitTime), 1.0)
var eased := 1.0 - (1.0 - progress) * (1.0 - progress)
spot = _point_on_path(tubeLength, _lanes[i]).lerp(_ends[i], eased)
color = _startColors[i].lerp(_endColors[i], eased)
if spot.distance_to(_ends[i]) <= SETTLED_DISTANCE:
settled = true
spot = _ends[i]
var at := Vector2i(spot.floor())
if _time >= enterTime and _time < exitTime:
pixels[at] = color
inTube[at] = true
elif settled:
pixels[at] = color
else:
movingPixels[at] = color
# The outline: every empty pixel touching the settled pixels. At their spot,
# corners count, like the slime's own outline. In the tube they don't, so
# the stream's outline hugs it. Spots inside the sprite's shape that pixels
# have left (or not reached yet) don't get one: they'd speckle it in black.
var outlined := {}
for at: Vector2i in pixels:
for offset in (TubeSteer.NEIGHBORS_4 if inTube.has(at) else TubeSteer.NEIGHBORS_8):
var spot: Vector2i = at + offset
if pixels.has(spot) or outlined.has(spot) or _footprint.has(spot):
continue
outlined[spot] = true
draw_rect(Rect2(Vector2(spot), Vector2.ONE), TubeSteer.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])
2026-11-08 21:19:46 -06:00
# The point `distance` along the path, moved `lane` to the left of travel.
func _point_on_path(distance: float, lane: float) -> Vector2:
var segment := 0
while segment < _path.size() - 2 and distance > _pathDistances[segment + 1]:
segment += 1
var from := _path[segment]
var to := _path[segment + 1]
var segmentLength := _pathDistances[segment + 1] - _pathDistances[segment]
var progress := 0.0
if segmentLength > 0.0:
progress = clampf((distance - _pathDistances[segment]) / segmentLength, 0.0, 1.0)
var left := (to - from).normalized().orthogonal() # Left of travel, with y down.
return from.lerp(to, progress) + left * lane
# Where the front of the stream is, in global coordinates (for the camera).
func get_focus() -> Vector2:
if _path.is_empty():
return global_position
var distance := clampf((_time - _enter_time(0)) * SPEED, 0.0, _tube_length())
return _point_on_path(distance, 0.0)
2026-11-08 21:19:46 -06:00
func _tube_length() -> float:
return _pathDistances[_pathDistances.size() - 1]