SlimePlatformer/Levels/Maze/maze_tube_router.gd
tachyonwolf df89fa4ac7 Maze-book labyrinths, sucking one-way entrances, slime movement model
- Regions are now dense labyrinths (recursive backtracker on a coarse grid,
  1-3 tile corridors, braided loops by complexity); tubes run in the rock
  between regions, wall pipes give shortcuts inside a region.
- One-way entrances suck the slime in (player.pull_into_tube); blow zone
  is now 1 tile; blown motes are white. TubeBlower -> TubeAirCurrents.
- Validator: generous "might get to" areas vs strict SlimeMoves model
  (surface slides, corners, wraps, 1-tile gaps, ceiling falls, tubes,
  forced suction/blow tiles as all-outcomes states).
- maze_check: new hand-made blow-zone and suction traps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:15:23 -06:00

300 lines
12 KiB
GDScript

class_name MazeTubeRouter
extends RefCounted
# Lays tubes into a carved maze: long tubes between regions, routed through
# the rock with AStarGrid2D (random weights so they wander), and short "wall
# pipes" through a single wall inside a region. Tubes never share a tile, so
# they can't join by accident, and their openings only face their own tiles.
#
# One-way tubes move the slime by themselves: the tile in front of the
# entrance sucks it in, and the blow zone in front of the exit
# (OneWayTube.blow_zone) blows it away. These "forced" tiles can't be stood on
# or crossed. A one-way tube only goes where MazeValidator's movement model can
# tell what happens, and where forced tiles can't cut a region in two:
# - the exit never blows up (the slime could bounce in place),
# - the zone and the tile past it ("landing") are air,
# - sideways: zone and landing are 1 tile tall, so the slime slides along a floor,
# - down: the slime falls from the landing onto a floor, through no forced tile,
# - the region's air minus all forced tiles is still one connected piece,
# - no other mouth opens onto a forced tile.
const MOUTH_CHOICES = 10 # Of the spots for a mouth nearest the other end, how many we pick from.
const ROUTE_TRIES = 16 # Pairs of mouth spots to try before giving up on a tube.
const WALL_PIPE_TRIES = 30
const MIN_SHORTCUT = 8 # A wall pipe must save at least this many tiles of corridor.
# Extra cost for routing through the walls inside a region rather than the
# rock between regions. In a 1-tile-wall maze the walls form a tree, and a tube
# through it cuts off the rock beyond, so later tubes couldn't get through.
# (Mouths also sit next to that rock, see _touches_channel.)
const INTERIOR_COST = 12.0
var mouthFronts := {} # Air tile in front of a mouth -> true.
var forcedCells := {} # Air tile the air moves the slime off (blow zones, entrance tiles) -> true.
var _keepFree := {} # Air tiles a blown slime lands on or falls through: never forced.
var _layer: TileMapLayer
var _tiles: MazeTiles
var _random: RandomNumberGenerator
var _bounds: Rect2i
var _pathfinder := AStarGrid2D.new()
var _winding := 0.0
var _interiors: Array[Rect2i] = [] # Where the corridors and their walls are.
func _init(layer: TileMapLayer, tiles: MazeTiles, random: RandomNumberGenerator, bounds: Rect2i,
winding: float, interiors: Array[Rect2i]) -> void:
_interiors = interiors
_layer = layer
_tiles = tiles
_random = random
_bounds = bounds
_winding = winding
_pathfinder.region = bounds
_pathfinder.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER
_pathfinder.default_compute_heuristic = AStarGrid2D.HEURISTIC_MANHATTAN
_pathfinder.update()
# Tubes go through rock only, and never through the maze's outer edge.
for y in range(bounds.position.y, bounds.end.y):
for x in range(bounds.position.x, bounds.end.x):
var cell := Vector2i(x, y)
var isEdge := x == bounds.position.x or y == bounds.position.y or x == bounds.end.x - 1 or y == bounds.end.y - 1
_pathfinder.set_point_solid(cell, isEdge or _is_air(cell))
# Routes a tube from region `fromAir` to region `toAir` (their air tiles, as
# sets). A one-way tube with nowhere safe to blow out becomes `fallbackKind`.
func route(fromAir: Dictionary, toAir: Dictionary, kind: StringName, fallbackKind: StringName) -> bool:
_randomize_weights()
var isOneWay := kind == MazeGraph.ONE_WAY
var fromMouths := _mouth_spots(fromAir, _middle(toAir), &"entrance" if isOneWay else &"")
var toMouths := _mouth_spots(toAir, _middle(fromAir), &"exit" if isOneWay else &"")
if isOneWay and (fromMouths.is_empty() or toMouths.is_empty()):
kind = fallbackKind
fromMouths = _mouth_spots(fromAir, _middle(toAir), &"")
toMouths = _mouth_spots(toAir, _middle(fromAir), &"")
for attempt in ROUTE_TRIES:
if fromMouths.is_empty() or toMouths.is_empty():
return false
var fromMouth: Dictionary = fromMouths[_random.randi_range(0, fromMouths.size() - 1)]
var toMouth: Dictionary = toMouths[_random.randi_range(0, toMouths.size() - 1)]
var path := _pathfinder.get_id_path(fromMouth.spot, toMouth.spot)
if path.is_empty():
continue
_put_tube(path, fromMouth.outward, toMouth.outward, kind)
return true
return false
# Adds a short tube through one wall tile inside region `air` (a set of its
# air tiles), joining two corridors that are far apart the long way round.
func add_wall_pipe(air: Dictionary, kind: StringName, fallbackKind: StringName) -> bool:
var tiles: Array = air.keys()
for attempt in WALL_PIPE_TRIES:
var wall: Vector2i = tiles[_random.randi_range(0, tiles.size() - 1)] + MazeCorridors.STEPS[_random.randi_range(0, 3)]
if _pathfinder.is_point_solid(wall) or _is_air(wall):
continue
for step: Vector2i in [Vector2i.RIGHT, Vector2i.DOWN]:
var sideA := wall + step
var sideB := wall - step
if not air.has(sideA) or not air.has(sideB):
continue
if _is_blocked_front(sideA) or _is_blocked_front(sideB):
continue
if _distance(air, sideA, sideB) < MIN_SHORTCUT:
continue
var pipeKind := kind
var outwardIn := step # Mouth into sideA faces `step`.
var outwardOut := -step
if kind == MazeGraph.ONE_WAY:
if _is_one_way_safe(air, wall, step, wall, -step):
outwardIn = step
outwardOut = -step
elif _is_one_way_safe(air, wall, -step, wall, step):
outwardIn = -step
outwardOut = step
else:
pipeKind = fallbackKind
var path: Array[Vector2i] = [wall]
_put_tube(path, outwardIn, outwardOut, pipeKind)
return true
return false
# ---- Mouths ----
# Rock tiles beside the region's air where a mouth can go:
# [{spot, outward}], the MOUTH_CHOICES nearest `towards`. `oneWayEnd`:
# &"entrance" or &"exit" for only spots that end of a one-way tube may use.
func _mouth_spots(air: Dictionary, towards: Vector2, oneWayEnd: StringName) -> Array[Dictionary]:
var spots: Array[Dictionary] = []
for tile: Vector2i in air:
if _is_blocked_front(tile):
continue
for step in MazeCorridors.STEPS:
var spot: Vector2i = tile - step # The mouth faces `step`, onto `tile`.
if not _pathfinder.is_point_solid(spot) and not _is_air(spot) and _touches_channel(spot):
spots.append({spot = spot, outward = step})
spots.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
return Vector2(a.spot).distance_squared_to(towards) < Vector2(b.spot).distance_squared_to(towards))
# The safety check floods the region, so only check spots until we have enough.
var chosen: Array[Dictionary] = []
for spot in spots:
if chosen.size() >= MOUTH_CHOICES:
break
if oneWayEnd == &"entrance" and not _is_one_way_safe(air, spot.spot, spot.outward, Vector2i.ZERO, Vector2i.ZERO):
continue
if oneWayEnd == &"exit" and not _is_one_way_safe(air, Vector2i.ZERO, Vector2i.ZERO, spot.spot, spot.outward):
continue
chosen.append(spot)
return chosen
# Whether `spot` is next to free rock between regions, so its tube can run
# there without going through (and cutting up) the walls inside the region.
func _touches_channel(spot: Vector2i) -> bool:
for step in MazeCorridors.STEPS:
var next := spot + step
if not _is_interior(next) and not _is_air(next) and not _pathfinder.is_point_solid(next):
return true
return false
func _is_blocked_front(tile: Vector2i) -> bool:
return forcedCells.has(tile)
# Whether a one-way tube's entrance (at `entranceSpot`, facing
# `entranceOutward`) and exit (likewise) follow the rules at the top of this
# file in region `air`. An outward of ZERO leaves that end out (it's in
# another region).
func _is_one_way_safe(air: Dictionary, entranceSpot: Vector2i, entranceOutward: Vector2i,
exitSpot: Vector2i, exitOutward: Vector2i) -> bool:
var newForced: Array[Vector2i] = []
var landing := Vector2i.ZERO
if entranceOutward != Vector2i.ZERO:
var front := entranceSpot + entranceOutward
if not air.has(front) or forcedCells.has(front) or mouthFronts.has(front) or _keepFree.has(front):
return false
newForced.append(front)
if exitOutward != Vector2i.ZERO:
if exitOutward == Vector2i.UP:
return false
var zone: Array[Vector2i] = []
for step in range(1, OneWayTube.BLOW_RANGE + 1):
zone.append(exitSpot + exitOutward * step)
landing = exitSpot + exitOutward * (OneWayTube.BLOW_RANGE + 1)
for tile in zone + [landing]:
if not air.has(tile) or forcedCells.has(tile) or newForced.has(tile):
return false
for tile in zone:
if _keepFree.has(tile):
return false
if exitOutward.y == 0 and (_is_air(tile + Vector2i.UP) or _is_air(tile + Vector2i.DOWN)):
return false
for tile in zone:
if mouthFronts.has(tile):
return false
newForced.append_array(zone)
if exitOutward == Vector2i.DOWN:
var fall := landing
while _is_air(fall + Vector2i.DOWN):
fall += Vector2i.DOWN
if forcedCells.has(fall) or newForced.has(fall):
return false
return _stays_connected(air, newForced)
# Whether the region's air, minus every forced tile and `newForced`, is one
# piece.
func _stays_connected(air: Dictionary, newForced: Array[Vector2i]) -> bool:
var open := {}
for tile: Vector2i in air:
if not forcedCells.has(tile) and not newForced.has(tile):
open[tile] = true
if open.is_empty():
return false
var first: Vector2i = open.keys()[0]
var seen := {first: true}
var queue: Array[Vector2i] = [first]
while not queue.is_empty():
var tile: Vector2i = queue.pop_back()
for step in MazeCorridors.STEPS:
var next := tile + step
if open.has(next) and not seen.has(next):
seen[next] = true
queue.append(next)
return seen.size() == open.size()
# Tiles of corridor between two air tiles of a region (a large number if
# they aren't joined).
static func _distance(air: Dictionary, from: Vector2i, to: Vector2i) -> int:
var distances := {from: 0}
var queue: Array[Vector2i] = [from]
while not queue.is_empty():
var tile: Vector2i = queue.pop_front()
if tile == to:
return distances[tile]
for step in MazeCorridors.STEPS:
var next := tile + step
if air.has(next) and not distances.has(next):
distances[next] = distances[tile] + 1
queue.append(next)
return 1 << 30
# ---- Laying tiles ----
func _randomize_weights() -> void:
for y in range(_bounds.position.y, _bounds.end.y):
for x in range(_bounds.position.x, _bounds.end.x):
var weight := 1.0 + _random.randf() * _winding
if _is_interior(Vector2i(x, y)):
weight *= INTERIOR_COST
_pathfinder.set_point_weight_scale(Vector2i(x, y), weight)
# Lays tube tiles along `path`. Its first tile's mouth faces `outwardIn`, its
# last tile's `outwardOut`. A one-way tube goes in at the first mouth.
func _put_tube(path: Array[Vector2i], outwardIn: Vector2i, outwardOut: Vector2i, kind: StringName) -> void:
var last := path.size() - 1
for i in path.size():
var cell := path[i]
var back := outwardIn if i == 0 else path[i - 1] - cell
var ahead := outwardOut if i == last else path[i + 1] - cell
var openings := TubeSteer.side_bit(back) | TubeSteer.side_bit(ahead)
var entrySide := TubeSteer.side_bit(back) if kind == MazeGraph.ONE_WAY and i == 0 else 0
_tiles.set_tile(_layer, cell, openings, kind, entrySide)
_pathfinder.set_point_solid(cell)
mouthFronts[path[0] + outwardIn] = true
mouthFronts[path[last] + outwardOut] = true
if kind == MazeGraph.ONE_WAY:
forcedCells[path[0] + outwardIn] = true
for tile in OneWayTube.blow_zone(_layer, path[last], outwardOut):
forcedCells[tile] = true
# Where the blow drops the slime: the landing tile, the one after (a
# sideways blow can slide it on) and, blowing down, the fall below.
var landing := path[last] + outwardOut * (OneWayTube.BLOW_RANGE + 1)
_keepFree[landing] = true
_keepFree[landing + outwardOut] = true
while outwardOut == Vector2i.DOWN and _is_air(landing + Vector2i.DOWN):
landing += Vector2i.DOWN
_keepFree[landing] = true
func _is_interior(cell: Vector2i) -> bool:
for rect in _interiors:
if rect.has_point(cell):
return true
return false
func _is_air(cell: Vector2i) -> bool:
return _layer.get_cell_source_id(cell) == -1
static func _middle(air: Dictionary) -> Vector2:
var total := Vector2.ZERO
for tile: Vector2i in air:
total += Vector2(tile)
return total / maxf(air.size(), 1.0)