N5: Replicate building, world damage, tide and loot
Built pieces, props' health, opened chests and the tide's schedule now reach clients as WORLD messages on the reliable channel, and each player is told what they carry as OWN messages. - NetWorld: the WORLD and OWN wire formats, and world_hash(), a digest of everything replicated this way. - WorldSender: one message after each tick in which something changed, the same for everyone, and the whole state for someone joining or a new match. StructureSet and PropSet keep the change lists it reads. - ClientWorld: applies them to the client's world, so pieces and broken props are solid for prediction. A piece's health follows from its building and damage, so building costs nothing on the wire. - Placing ahead of the server: a provisional piece goes up with the command and is replaced by the server's, or taken back once a snapshot shows the server had its chance. Snapshots carry the newest WORLD number for that. - Protocol version 3. A test plays a whole scripted match on a real island with a ClientGame attached and compares the two worlds' hashes throughout. Closes #36 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+48
-8
@@ -8,7 +8,10 @@
|
||||
##
|
||||
## The client generates the match's island itself from the seed in the MATCH notice
|
||||
## (`world`, a Simulation that is never stepped) and plans the same barge route, so it
|
||||
## can run the same movement code as the server on the same ground.
|
||||
## can run the same movement code as the server on the same ground. WORLD messages keep
|
||||
## that world's built pieces, props, chests and tide in line with the server's, and OWN
|
||||
## messages say what the player carries (`replica`, a ClientWorld). Pieces the player
|
||||
## places appear at once and are taken back if the server turns them down.
|
||||
class_name ClientGame
|
||||
extends RefCounted
|
||||
|
||||
@@ -24,6 +27,8 @@ var remote: SnapshotInterpolator = SnapshotInterpolator.new()
|
||||
## The match's island, points of interest and props, generated here. Null until the
|
||||
## first MATCH notice.
|
||||
var world: Simulation = null
|
||||
## Keeps `world` in line with the server, and holds what the player carries.
|
||||
var replica: ClientWorld = ClientWorld.new()
|
||||
var world_seed: int = 0
|
||||
## From the last MATCH notice; the phase is also kept up to date by snapshots.
|
||||
var match_phase: int = Match.LOBBY
|
||||
@@ -63,11 +68,27 @@ func poll(now_msec: int = -1) -> void:
|
||||
## Takes one packet from the server.
|
||||
func receive(channel: int, bytes: PackedByteArray) -> void:
|
||||
if channel == NetProtocol.CHANNEL_CONTROL:
|
||||
var notice: Dictionary = NetSnapshot.decode_match(bytes)
|
||||
if notice.is_empty():
|
||||
bad_packets += 1
|
||||
return
|
||||
_take_notice(notice)
|
||||
var type: int = bytes[0] if not bytes.is_empty() else 0
|
||||
if type == NetWorld.MSG_WORLD:
|
||||
var message: Dictionary = NetWorld.decode_world(bytes)
|
||||
if message.is_empty() or world == null:
|
||||
bad_packets += 1
|
||||
return
|
||||
_take_world(message)
|
||||
elif type == NetWorld.MSG_OWN:
|
||||
var carried: Dictionary = NetWorld.decode_own(bytes)
|
||||
if carried.is_empty():
|
||||
bad_packets += 1
|
||||
return
|
||||
replica.own = carried
|
||||
NetWorld.apply_own(prediction.player, carried)
|
||||
prediction.player.materials = replica.available_materials()
|
||||
else:
|
||||
var notice: Dictionary = NetSnapshot.decode_match(bytes)
|
||||
if notice.is_empty():
|
||||
bad_packets += 1
|
||||
return
|
||||
_take_notice(notice)
|
||||
elif receiver.apply(bytes):
|
||||
_take_snapshot()
|
||||
|
||||
@@ -85,6 +106,8 @@ func advance(delta: float) -> void:
|
||||
while prediction.next_tick <= target:
|
||||
var command: PlayerCommand = _input_for(prediction.next_tick)
|
||||
prediction.predict(command)
|
||||
# A piece placed by this command goes up now, not when the server answers.
|
||||
replica.try_place(prediction.player, command, command.tick)
|
||||
_recent.append(command)
|
||||
while _recent.size() > Tuning.NET_INPUT_REDUNDANCY:
|
||||
_recent.pop_front()
|
||||
@@ -113,14 +136,28 @@ func _take_notice(notice: Dictionary) -> void:
|
||||
var new_match: bool = int(notice["index"]) != match_index
|
||||
match_phase = notice["phase"]
|
||||
match_index = notice["index"]
|
||||
if world == null or int(notice["seed"]) != world_seed:
|
||||
if world == null or int(notice["seed"]) != world_seed or (new_match and replica.dirty):
|
||||
world_seed = notice["seed"]
|
||||
world = make_world.call(world_seed)
|
||||
_make_world()
|
||||
new_match = true
|
||||
if new_match:
|
||||
_reset_match()
|
||||
|
||||
|
||||
func _make_world() -> void:
|
||||
world = make_world.call(world_seed)
|
||||
replica.begin(world)
|
||||
|
||||
|
||||
func _take_world(message: Dictionary) -> void:
|
||||
if message["full"] and replica.dirty:
|
||||
# The whole state has to go on a world nothing was done to.
|
||||
_make_world()
|
||||
_reset_match()
|
||||
replica.take(message)
|
||||
prediction.player.materials = replica.available_materials()
|
||||
|
||||
|
||||
func _reset_match() -> void:
|
||||
prediction.stop()
|
||||
clock.stop()
|
||||
@@ -140,6 +177,9 @@ func _take_snapshot() -> void:
|
||||
remote.reset()
|
||||
else:
|
||||
remote.push(receiver.sim_tick, receiver.entities)
|
||||
replica.sync(receiver.sim_tick)
|
||||
if replica.settle(receiver.sim_tick, receiver.world_seq) > 0:
|
||||
prediction.player.materials = replica.available_materials()
|
||||
if receiver.own.is_empty() or world == null:
|
||||
if prediction.active:
|
||||
prediction.stop()
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
## correction. A correction isn't shown at once: the difference is carried as an offset
|
||||
## on the drawn position and fades out.
|
||||
##
|
||||
## What isn't predicted: built pieces and broken props, which aren't replicated yet,
|
||||
## and the flood beyond the cells around the player. Near those the server corrects.
|
||||
## What isn't predicted: the flood beyond the cells around the player, and a piece or
|
||||
## broken prop whose WORLD message hasn't arrived yet. Near those the server corrects.
|
||||
class_name ClientPrediction
|
||||
extends RefCounted
|
||||
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
## The client's side of WORLD and OWN messages (see NetWorld): keeps the client's copy
|
||||
## of the match's world, a Simulation that is never stepped, in line with the server's,
|
||||
## and places the client's own pieces before the server has answered.
|
||||
##
|
||||
## What is kept in line: built pieces (with their health and building), props' health,
|
||||
## opened chests, unspilled crates and the tide's schedule. NetWorld.world_hash() of
|
||||
## the client's world equals the server's once every message up to a tick has been
|
||||
## applied and sync() has been called for that tick.
|
||||
##
|
||||
## Placing ahead of the server: when the player places a piece and the client's own
|
||||
## check passes, a provisional piece goes into the world at once, under an ID the
|
||||
## server never uses, and its cost is held back from the materials shown. The server's
|
||||
## piece arriving in the same slot replaces it. If a snapshot from after the placing
|
||||
## tick has arrived, the world messages it speaks of have all arrived too, and no
|
||||
## piece came, the server turned it down and the provisional piece is taken away.
|
||||
class_name ClientWorld
|
||||
extends RefCounted
|
||||
|
||||
## Provisional pieces get IDs from here up.
|
||||
const PROVISIONAL_FIRST_ID: int = 1 << 30
|
||||
|
||||
var world: Simulation = null
|
||||
## The newest WORLD applied: its number (-1 before the first full one) and tick.
|
||||
var seq: int = -1
|
||||
var tick: int = 0
|
||||
## True once anything has been applied that a new match would have to undo.
|
||||
var dirty: bool = false
|
||||
## The last OWN (see NetWorld.decode_own), or empty.
|
||||
var own: Dictionary = {}
|
||||
## Counts, for tests and the network graph.
|
||||
var applied: int = 0
|
||||
var gaps: int = 0
|
||||
var confirmed: int = 0
|
||||
var rolled_back: int = 0
|
||||
|
||||
## Piece ID -> damage taken, for every piece the server has sent.
|
||||
var _damage: Dictionary = {}
|
||||
## Piece ID -> the simulation tick its building began, worked back from how far it had
|
||||
## got when the server sent it.
|
||||
var _build_began: Dictionary = {}
|
||||
## Provisional pieces: {"id", "slot", "kind", "material", "tick", "owner"}.
|
||||
var _pending: Array[Dictionary] = []
|
||||
var _next_provisional: int = PROVISIONAL_FIRST_ID
|
||||
var _build_ready_tick: int = 0
|
||||
var _loot_planned: bool = false
|
||||
|
||||
|
||||
## Starts again on a freshly made world.
|
||||
func begin(fresh: Simulation) -> void:
|
||||
world = fresh
|
||||
seq = -1
|
||||
tick = 0
|
||||
dirty = false
|
||||
own = {}
|
||||
_damage.clear()
|
||||
_build_began.clear()
|
||||
_pending.clear()
|
||||
_build_ready_tick = 0
|
||||
_loot_planned = false
|
||||
|
||||
|
||||
## Applies one decoded WORLD. A full one must be given a world nothing has been applied
|
||||
## to: see `dirty`.
|
||||
func take(message: Dictionary) -> void:
|
||||
if world == null:
|
||||
return
|
||||
var structures: StructureSet = world.structures
|
||||
if message["full"]:
|
||||
_damage.clear()
|
||||
_build_began.clear()
|
||||
elif int(message["seq"]) != seq + 1:
|
||||
# The channel is reliable and ordered, so this shouldn't happen. Carry on: the
|
||||
# changes are still true.
|
||||
gaps += 1
|
||||
seq = message["seq"]
|
||||
tick = int(message["tick"]) if message["full"] else maxi(tick, int(message["tick"]))
|
||||
applied += 1
|
||||
if message["loot"] and not _loot_planned:
|
||||
_loot_planned = true
|
||||
if world.island != null:
|
||||
# The same rolls the server made, from the same stream and the same props.
|
||||
world.loot = LootSet.plan(world.rng.stream("loot"), world.pois.loot_markers(), Simulation.crate_spill_points(world.props))
|
||||
dirty = true
|
||||
var tide: Dictionary = message["tide"]
|
||||
if not tide.is_empty():
|
||||
world.tide = Tide.new(tide["started"], tide["levels"])
|
||||
dirty = true
|
||||
for entry: Array in message["pieces"]:
|
||||
var piece_id: int = entry[NetWorld.P_ID]
|
||||
dirty = true
|
||||
if structures.find(piece_id) == null:
|
||||
_replace_provisional(entry)
|
||||
structures.add(entry[NetWorld.P_KIND], entry[NetWorld.P_MATERIAL], entry[NetWorld.P_SLOT], entry[NetWorld.P_FACING], entry[NetWorld.P_OWNER], entry[NetWorld.P_PLACED], world.ground, piece_id)
|
||||
_damage[piece_id] = entry[NetWorld.P_DAMAGE]
|
||||
_build_began[piece_id] = int(message["tick"]) - int(entry[NetWorld.P_ELAPSED])
|
||||
_set_progress(piece_id)
|
||||
var damaged: PackedInt32Array = message["damaged"]
|
||||
for index: int in range(0, damaged.size(), 2):
|
||||
if structures.find(damaged[index]) != null:
|
||||
_damage[damaged[index]] = damaged[index + 1]
|
||||
_set_progress(damaged[index])
|
||||
for piece_id: int in message["removed"]:
|
||||
if structures.remove(piece_id, world.ground):
|
||||
_damage.erase(piece_id)
|
||||
_build_began.erase(piece_id)
|
||||
var props: PackedInt32Array = message["props"]
|
||||
for index: int in range(0, props.size(), 2):
|
||||
var prop: int = props[index]
|
||||
if prop >= world.props.count():
|
||||
continue
|
||||
dirty = true
|
||||
if world.props.damage(prop, world.props.health[prop] - props[index + 1]):
|
||||
# A broken crate has spilled what it held.
|
||||
world.loot.crate_contents.erase(prop)
|
||||
for chest: int in message["chests"]:
|
||||
if chest < world.loot.chest_opened.size():
|
||||
world.loot.chest_opened[chest] = 1
|
||||
dirty = true
|
||||
|
||||
|
||||
## Brings every piece still being built up to simulation tick `sim_tick`.
|
||||
func sync(sim_tick: int) -> void:
|
||||
if world == null:
|
||||
return
|
||||
tick = maxi(tick, sim_tick)
|
||||
for piece_id: int in world.structures.building().duplicate():
|
||||
_set_progress(piece_id)
|
||||
|
||||
|
||||
## The materials the player has to spend: what the server last said, less what the
|
||||
## provisional pieces will cost.
|
||||
func available_materials() -> PackedInt32Array:
|
||||
var materials: PackedInt32Array = PackedInt32Array()
|
||||
materials.resize(Materials.NAMES.size())
|
||||
if not own.is_empty():
|
||||
materials = (own["materials"] as PackedInt32Array).duplicate()
|
||||
for pending: Dictionary in _pending:
|
||||
var material: int = pending["material"]
|
||||
materials[material] = maxi(materials[material] - StructureSet.cost_of(pending["kind"]), 0)
|
||||
return materials
|
||||
|
||||
|
||||
## Provisional pieces waiting for the server's answer.
|
||||
func pending_count() -> int:
|
||||
return _pending.size()
|
||||
|
||||
|
||||
## The player's command for `command_tick` has just been predicted on `player`: if it
|
||||
## places a piece and the checks the server will make pass here, puts a provisional
|
||||
## piece in the world. Returns the Building.Result, or -1 if the command places nothing
|
||||
## or the last piece was too recent.
|
||||
func try_place(player: SimEntity, command: PlayerCommand, command_tick: int) -> int:
|
||||
if world == null or command == null or command_tick < _build_ready_tick:
|
||||
return -1
|
||||
if not command.is_pressed(PlayerCommand.BUTTON_BUILD) or not command.is_pressed(PlayerCommand.BUTTON_FIRE):
|
||||
return -1
|
||||
player.materials = available_materials()
|
||||
var at: Building.Target = Building.target(player, command.selection)
|
||||
var result: Building.Result = Building.check(world, player, at, command.material)
|
||||
if result == Building.Result.OK and Building.would_trap(player, Building.boxes_for_target(at, world.ground)):
|
||||
result = Building.Result.BLOCKED_BY_PLAYER
|
||||
if result != Building.Result.OK:
|
||||
return result
|
||||
var piece: StructureSet.Piece = world.structures.add(at.kind, command.material, at.slot, at.facing, player.id, command_tick, world.ground, _next_provisional)
|
||||
_next_provisional += 1
|
||||
_pending.append({"id": piece.id, "slot": at.slot, "kind": at.kind, "material": command.material, "tick": command_tick, "owner": player.id})
|
||||
dirty = true
|
||||
_build_ready_tick = command_tick + Tuning.BUILD_INTERVAL_TICKS
|
||||
Building.lift(player, piece.boxes)
|
||||
player.materials = available_materials()
|
||||
return result
|
||||
|
||||
|
||||
## Called with each snapshot: `sim_tick` is the snapshot's simulation tick and
|
||||
## `world_seq` the newest WORLD the server had made by then. Takes away every
|
||||
## provisional piece the server has had its chance to place and didn't. Returns how
|
||||
## many went.
|
||||
func settle(sim_tick: int, world_seq: int) -> int:
|
||||
if _pending.is_empty() or seq < world_seq:
|
||||
return 0
|
||||
var waiting: Array[Dictionary] = []
|
||||
var gone: int = 0
|
||||
for pending: Dictionary in _pending:
|
||||
if int(pending["tick"]) >= sim_tick:
|
||||
waiting.append(pending)
|
||||
continue
|
||||
world.structures.remove(pending["id"], world.ground)
|
||||
gone += 1
|
||||
_pending = waiting
|
||||
rolled_back += gone
|
||||
return gone
|
||||
|
||||
|
||||
## The server's piece `entry` is about to be added: a provisional piece in its slot
|
||||
## makes way.
|
||||
func _replace_provisional(entry: Array) -> void:
|
||||
for index: int in _pending.size():
|
||||
var pending: Dictionary = _pending[index]
|
||||
if pending["slot"] != entry[NetWorld.P_SLOT]:
|
||||
continue
|
||||
world.structures.remove(pending["id"], world.ground)
|
||||
_pending.remove_at(index)
|
||||
if pending["kind"] == entry[NetWorld.P_KIND] and pending["owner"] == entry[NetWorld.P_OWNER]:
|
||||
confirmed += 1
|
||||
else:
|
||||
rolled_back += 1
|
||||
return
|
||||
|
||||
|
||||
func _set_progress(piece_id: int) -> void:
|
||||
var piece: StructureSet.Piece = world.structures.find(piece_id)
|
||||
if piece != null:
|
||||
# A provisional piece hasn't begun, as far as the server has said.
|
||||
world.structures.set_progress(piece_id, tick - int(_build_began.get(piece_id, tick)), int(_damage.get(piece_id, 0)))
|
||||
@@ -0,0 +1 @@
|
||||
uid://cyjsoswoc1opy
|
||||
@@ -16,7 +16,7 @@ class_name NetProtocol
|
||||
extends RefCounted
|
||||
|
||||
## Raised whenever the wire format changes in a way old clients can't read.
|
||||
const VERSION: int = 2
|
||||
const VERSION: int = 3
|
||||
const MAGIC: String = "TDWL"
|
||||
const CHANNEL_CONTROL: int = 0
|
||||
## Unreliable game traffic: commands up, snapshots down.
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
## server -> SNAPSHOT (channel 1, unreliable)
|
||||
## u8 type, u32 server tick, u32 baseline tick (0 = none), u32 simulation tick,
|
||||
## u32 newest command tick received from this client plus one (0 = none yet),
|
||||
## u32 the sequence number of the newest WORLD message made (see NetWorld),
|
||||
## varint the entity the client is watching (its own player, or the one it
|
||||
## spectates; 0 = none), u8 match phase, u8 tide phase, s16 sea level in centimetres,
|
||||
## u8 1 if the client's own block follows, then that block (see SELF_BYTES),
|
||||
@@ -31,7 +32,7 @@ const MSG_INPUT: int = 17
|
||||
|
||||
## The server tick counts every tick the server has run and never goes back, so it
|
||||
## orders snapshots across matches. The simulation tick is the one commands name.
|
||||
const HEADER_BYTES: int = 17
|
||||
const HEADER_BYTES: int = 21
|
||||
const MATCH_BYTES: int = 14
|
||||
## The client's own block: what it needs to predict its own player and nobody else is
|
||||
## told. Exact, not quantized, so a prediction made from it matches the server's to the
|
||||
@@ -241,6 +242,7 @@ static func encode_snapshot(header: Dictionary, removed: PackedInt32Array, recor
|
||||
out.put_u32(int(header.get("baseline", 0)) & 0xFFFFFFFF)
|
||||
out.put_u32(int(header.get("sim_tick", 0)) & 0xFFFFFFFF)
|
||||
out.put_u32((int(header.get("command_tick", -1)) + 1) & 0xFFFFFFFF)
|
||||
out.put_u32(int(header.get("world_seq", 0)) & 0xFFFFFFFF)
|
||||
_put_varint(out, int(header.get("own_id", 0)))
|
||||
out.put_u8(int(header.get("match_phase", 0)))
|
||||
out.put_u8(int(header.get("tide_phase", 0)))
|
||||
@@ -285,7 +287,7 @@ static func encode_snapshot(header: Dictionary, removed: PackedInt32Array, recor
|
||||
|
||||
|
||||
## Reads a SNAPSHOT's header and lists, without applying them: {"tick", "baseline",
|
||||
## "sim_tick", "command_tick" (-1 = none yet), "own_id", "match_phase", "tide_phase",
|
||||
## "sim_tick", "command_tick" (-1 = none yet), "world_seq", "own_id", "match_phase", "tide_phase",
|
||||
## "sea_cm", "self": the client's own block as self_of() made it, or empty, "removed":
|
||||
## PackedInt32Array, "records": [[entity ID, archetype, mask, values]]}, where `values`
|
||||
## holds the fields present, in record order. Empty if malformed.
|
||||
@@ -299,7 +301,7 @@ static func decode_snapshot(bytes: PackedByteArray) -> Dictionary:
|
||||
var at: int = cursor[0]
|
||||
var result: Dictionary = {
|
||||
"tick": bytes.decode_u32(1), "baseline": bytes.decode_u32(5), "sim_tick": bytes.decode_u32(9),
|
||||
"command_tick": bytes.decode_u32(13) - 1,
|
||||
"command_tick": bytes.decode_u32(13) - 1, "world_seq": bytes.decode_u32(17),
|
||||
"own_id": own_id, "match_phase": bytes[at], "tide_phase": bytes[at + 1], "sea_cm": bytes.decode_s16(at + 2),
|
||||
}
|
||||
var own: Dictionary = {}
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
## The parts of a match that aren't entities, on the wire: built pieces, damaged and
|
||||
## broken props, opened chests and the tide's schedule (WORLD), and what a client's own
|
||||
## player carries (OWN). Both go on channel 0, reliably and in order, because a wall
|
||||
## the client never heard about is a lie it would keep walking into.
|
||||
##
|
||||
## server -> WORLD
|
||||
## u8 type, u8 flags (FLAG_ bits), u32 sequence number, u32 simulation tick,
|
||||
## if FLAG_TIDE: u32 the tick the tide started, u8 level count, then f32 levels,
|
||||
## varint count, then new pieces: varint ID, u8 (kind | material << 3 | facing << 5),
|
||||
## s16 slot x, s8 slot level, s16 slot z, u8 slot type, varint owner entity,
|
||||
## u32 the tick it was placed, varint ticks of building done, varint damage taken,
|
||||
## varint count, then damaged pieces: varint ID, varint damage taken so far,
|
||||
## varint count, then removed pieces: varint ID,
|
||||
## varint count, then props: varint prop, varint health left,
|
||||
## varint count, then opened chests: varint index
|
||||
## server -> OWN
|
||||
## u8 type, u32 simulation tick, u8 held selection,
|
||||
## u8 count, then u16 of each material,
|
||||
## u8 count, then slots: u8 item code plus one, u16 count, u16 rounds, u8 tier,
|
||||
## u8 count, then u16 of each ammunition
|
||||
##
|
||||
## A WORLD with FLAG_FULL is the whole state: the client forgets what it had first. The
|
||||
## others are changes, numbered one after another from the last full one. A piece's
|
||||
## health isn't sent: it follows from how far its building had got at the message's
|
||||
## tick, the ticks since, and the damage it has taken (StructureSet.set_progress), so a
|
||||
## piece being built costs nothing to keep up to date.
|
||||
##
|
||||
## Decoders return an empty Dictionary for anything malformed and never raise an error.
|
||||
class_name NetWorld
|
||||
extends RefCounted
|
||||
|
||||
const MSG_WORLD: int = 5
|
||||
const MSG_OWN: int = 6
|
||||
|
||||
## The whole state, not changes: forget everything first.
|
||||
const FLAG_FULL: int = 1 << 0
|
||||
## The match's loot has been rolled and placed, so its chests exist.
|
||||
const FLAG_LOOT: int = 1 << 1
|
||||
## The tide's schedule follows.
|
||||
const FLAG_TIDE: int = 1 << 2
|
||||
|
||||
const WORLD_HEADER_BYTES: int = 10
|
||||
## Indices into a decoded piece.
|
||||
const P_ID: int = 0
|
||||
const P_KIND: int = 1
|
||||
const P_MATERIAL: int = 2
|
||||
const P_FACING: int = 3
|
||||
const P_SLOT: int = 4
|
||||
const P_OWNER: int = 5
|
||||
const P_PLACED: int = 6
|
||||
const P_DAMAGE: int = 7
|
||||
## Ticks of building done when the message was made.
|
||||
const P_ELAPSED: int = 8
|
||||
|
||||
|
||||
## A piece as it travels: see the P_ indices.
|
||||
static func piece_entry(piece: StructureSet.Piece) -> Array:
|
||||
return [
|
||||
piece.id, piece.kind, piece.material, piece.facing, piece.slot, piece.owner, piece.placed_tick,
|
||||
StructureSet.damage_taken(piece), piece.build_ticks - piece.build_ticks_left,
|
||||
]
|
||||
|
||||
|
||||
## Builds a WORLD. `message` has "flags", "seq", "tick", and optionally "tide"
|
||||
## ({"started", "levels"}), "pieces" (piece_entry() arrays), "damaged" and "props"
|
||||
## (PackedInt32Arrays of pairs), "removed" and "chests" (PackedInt32Arrays).
|
||||
static func encode_world(message: Dictionary) -> PackedByteArray:
|
||||
var out: StreamPeerBuffer = StreamPeerBuffer.new()
|
||||
out.big_endian = false
|
||||
var tide: Dictionary = message.get("tide", {})
|
||||
var flags: int = int(message.get("flags", 0)) & ~FLAG_TIDE
|
||||
if not tide.is_empty():
|
||||
flags |= FLAG_TIDE
|
||||
out.put_u8(MSG_WORLD)
|
||||
out.put_u8(flags)
|
||||
out.put_u32(int(message.get("seq", 0)) & 0xFFFFFFFF)
|
||||
out.put_u32(int(message.get("tick", 0)) & 0xFFFFFFFF)
|
||||
if not tide.is_empty():
|
||||
var levels: PackedFloat32Array = tide["levels"]
|
||||
out.put_u32(int(tide["started"]) & 0xFFFFFFFF)
|
||||
out.put_u8(levels.size())
|
||||
for level: float in levels:
|
||||
out.put_float(level)
|
||||
var pieces: Array = message.get("pieces", [])
|
||||
_put_varint(out, pieces.size())
|
||||
for entry: Array in pieces:
|
||||
var slot: Vector4i = entry[P_SLOT]
|
||||
_put_varint(out, int(entry[P_ID]))
|
||||
out.put_u8(int(entry[P_KIND]) | int(entry[P_MATERIAL]) << 3 | int(entry[P_FACING]) << 5)
|
||||
out.put_16(slot.x)
|
||||
out.put_8(slot.y)
|
||||
out.put_16(slot.z)
|
||||
out.put_u8(slot.w)
|
||||
_put_varint(out, int(entry[P_OWNER]))
|
||||
out.put_u32(int(entry[P_PLACED]) & 0xFFFFFFFF)
|
||||
_put_varint(out, maxi(int(entry[P_ELAPSED]), 0))
|
||||
_put_varint(out, maxi(int(entry[P_DAMAGE]), 0))
|
||||
for key: String in ["damaged", "removed", "props", "chests"]:
|
||||
var values: PackedInt32Array = message.get(key, PackedInt32Array())
|
||||
var width: int = 2 if key == "damaged" or key == "props" else 1
|
||||
_put_varint(out, values.size() / width)
|
||||
for value: int in values:
|
||||
_put_varint(out, maxi(value, 0))
|
||||
return out.data_array
|
||||
|
||||
|
||||
## {"full": bool, "loot": bool, "seq", "tick", "tide": {} or {"started", "levels"},
|
||||
## "pieces", "damaged", "removed", "props", "chests"} as encode_world() takes them, or
|
||||
## empty if malformed.
|
||||
static func decode_world(bytes: PackedByteArray) -> Dictionary:
|
||||
if bytes.size() < WORLD_HEADER_BYTES + 5 or bytes[0] != MSG_WORLD or bytes[1] > (FLAG_FULL | FLAG_LOOT | FLAG_TIDE):
|
||||
return {}
|
||||
var flags: int = bytes[1]
|
||||
var result: Dictionary = {
|
||||
"full": flags & FLAG_FULL != 0, "loot": flags & FLAG_LOOT != 0,
|
||||
"seq": bytes.decode_u32(2), "tick": bytes.decode_u32(6), "tide": {},
|
||||
}
|
||||
var cursor: Array[int] = [WORLD_HEADER_BYTES]
|
||||
if flags & FLAG_TIDE != 0:
|
||||
if bytes.size() < cursor[0] + 5:
|
||||
return {}
|
||||
var count: int = bytes[cursor[0] + 4]
|
||||
if count != Tide.phase_count() or bytes.size() < cursor[0] + 5 + count * 4:
|
||||
return {}
|
||||
var levels: PackedFloat32Array = PackedFloat32Array()
|
||||
for index: int in count:
|
||||
var level: float = bytes.decode_float(cursor[0] + 5 + index * 4)
|
||||
if not is_finite(level):
|
||||
return {}
|
||||
levels.append(level)
|
||||
result["tide"] = {"started": bytes.decode_u32(cursor[0]), "levels": levels}
|
||||
cursor[0] += 5 + count * 4
|
||||
var piece_count: int = _read_varint(bytes, cursor)
|
||||
if piece_count < 0 or piece_count > bytes.size():
|
||||
return {}
|
||||
var pieces: Array = []
|
||||
for _index: int in piece_count:
|
||||
var piece_id: int = _read_varint(bytes, cursor)
|
||||
var at: int = cursor[0]
|
||||
if piece_id <= 0 or at + 7 > bytes.size():
|
||||
return {}
|
||||
var packed: int = bytes[at]
|
||||
var kind: int = packed & 7
|
||||
var material: int = (packed >> 3) & 3
|
||||
var slot: Vector4i = Vector4i(bytes.decode_s16(at + 1), bytes.decode_s8(at + 3), bytes.decode_s16(at + 4), bytes[at + 6])
|
||||
if packed > 0x7F or kind >= StructureSet.KINDS.size() or not Materials.is_valid(material):
|
||||
return {}
|
||||
var slot_fits: bool = slot.w == StructureSet.slot_type_of(kind)
|
||||
if StructureSet.is_wall_kind(kind):
|
||||
slot_fits = slot.w == StructureSet.SLOT_WALL_X or slot.w == StructureSet.SLOT_WALL_Z
|
||||
if not slot_fits:
|
||||
return {}
|
||||
cursor[0] = at + 7
|
||||
var owner: int = _read_varint(bytes, cursor)
|
||||
if owner < 0 or cursor[0] + 4 > bytes.size():
|
||||
return {}
|
||||
var placed: int = bytes.decode_u32(cursor[0])
|
||||
cursor[0] += 4
|
||||
var elapsed: int = _read_varint(bytes, cursor)
|
||||
var damage: int = _read_varint(bytes, cursor)
|
||||
if elapsed < 0 or damage < 0:
|
||||
return {}
|
||||
pieces.append([piece_id, kind, material, packed >> 5, slot, owner, placed, damage, elapsed])
|
||||
result["pieces"] = pieces
|
||||
for key: String in ["damaged", "removed", "props", "chests"]:
|
||||
var width: int = 2 if key == "damaged" or key == "props" else 1
|
||||
var count: int = _read_varint(bytes, cursor)
|
||||
if count < 0 or count * width > bytes.size():
|
||||
return {}
|
||||
var values: PackedInt32Array = PackedInt32Array()
|
||||
for _index: int in count * width:
|
||||
var value: int = _read_varint(bytes, cursor)
|
||||
if value < 0 or value > 0x7FFFFFFF:
|
||||
return {}
|
||||
values.append(value)
|
||||
result[key] = values
|
||||
if cursor[0] != bytes.size():
|
||||
return {}
|
||||
return result
|
||||
|
||||
|
||||
## What a player carries, as OWN sends it.
|
||||
static func encode_own(player: SimEntity, sim_tick: int) -> PackedByteArray:
|
||||
var out: StreamPeerBuffer = StreamPeerBuffer.new()
|
||||
out.big_endian = false
|
||||
out.put_u8(MSG_OWN)
|
||||
out.put_u32(sim_tick & 0xFFFFFFFF)
|
||||
out.put_u8(clampi(player.selected, 0, 255))
|
||||
out.put_u8(player.materials.size())
|
||||
for amount: int in player.materials:
|
||||
out.put_u16(clampi(amount, 0, 65535))
|
||||
out.put_u8(player.slot_items.size())
|
||||
for slot: int in player.slot_items.size():
|
||||
out.put_u8(clampi(player.slot_items[slot] + 1, 0, 255))
|
||||
out.put_u16(clampi(player.slot_counts[slot], 0, 65535))
|
||||
out.put_u16(clampi(player.slot_rounds[slot], 0, 65535))
|
||||
out.put_u8(clampi(player.slot_tiers[slot], 0, 255))
|
||||
out.put_u8(player.ammo.size())
|
||||
for amount: int in player.ammo:
|
||||
out.put_u16(clampi(amount, 0, 65535))
|
||||
return out.data_array
|
||||
|
||||
|
||||
## {"tick", "selected", "materials", "slot_items", "slot_counts", "slot_rounds",
|
||||
## "slot_tiers", "ammo"}, the lists as PackedInt32Arrays, or empty if malformed or not
|
||||
## the shape this build's players have.
|
||||
static func decode_own(bytes: PackedByteArray) -> Dictionary:
|
||||
var materials: int = Materials.NAMES.size()
|
||||
var slots: int = Inventory.slot_count()
|
||||
var ammo: int = Tuning.AMMO.size()
|
||||
if bytes.size() != 9 + materials * 2 + slots * 6 + ammo * 2 or bytes[0] != MSG_OWN:
|
||||
return {}
|
||||
if bytes[6] != materials or bytes[7 + materials * 2] != slots or bytes[8 + materials * 2 + slots * 6] != ammo:
|
||||
return {}
|
||||
var result: Dictionary = {
|
||||
"tick": bytes.decode_u32(1), "selected": bytes[5],
|
||||
"materials": PackedInt32Array(), "slot_items": PackedInt32Array(), "slot_counts": PackedInt32Array(),
|
||||
"slot_rounds": PackedInt32Array(), "slot_tiers": PackedInt32Array(), "ammo": PackedInt32Array(),
|
||||
}
|
||||
var at: int = 7
|
||||
for _index: int in materials:
|
||||
result["materials"].append(bytes.decode_u16(at))
|
||||
at += 2
|
||||
at += 1
|
||||
for _index: int in slots:
|
||||
var item: int = bytes[at] - 1
|
||||
if item >= ItemCatalog.count():
|
||||
return {}
|
||||
result["slot_items"].append(item)
|
||||
result["slot_counts"].append(bytes.decode_u16(at + 1))
|
||||
result["slot_rounds"].append(bytes.decode_u16(at + 3))
|
||||
result["slot_tiers"].append(bytes[at + 5])
|
||||
at += 6
|
||||
at += 1
|
||||
for _index: int in ammo:
|
||||
result["ammo"].append(bytes.decode_u16(at))
|
||||
at += 2
|
||||
if int(result["selected"]) > slots:
|
||||
return {}
|
||||
return result
|
||||
|
||||
|
||||
## Puts a decoded OWN into `player`.
|
||||
static func apply_own(player: SimEntity, own: Dictionary) -> void:
|
||||
player.selected = own["selected"]
|
||||
player.materials = (own["materials"] as PackedInt32Array).duplicate()
|
||||
player.slot_items = (own["slot_items"] as PackedInt32Array).duplicate()
|
||||
player.slot_counts = (own["slot_counts"] as PackedInt32Array).duplicate()
|
||||
player.slot_rounds = (own["slot_rounds"] as PackedInt32Array).duplicate()
|
||||
player.slot_tiers = (own["slot_tiers"] as PackedInt32Array).duplicate()
|
||||
player.ammo = (own["ammo"] as PackedInt32Array).duplicate()
|
||||
|
||||
|
||||
## SHA-256 hex digest of everything WORLD replicates, as `sim` holds it: the tide's
|
||||
## schedule, every prop's health, every built piece with its health and building, the
|
||||
## opened chests and the crates not yet spilled. A client that has applied every WORLD
|
||||
## up to some tick, and brought its pieces' building up to that tick, agrees with the
|
||||
## server's simulation at that tick.
|
||||
static func world_hash(sim: Simulation) -> String:
|
||||
var buffer: StreamPeerBuffer = StreamPeerBuffer.new()
|
||||
buffer.big_endian = false
|
||||
buffer.put_64(sim.tide.started_tick if sim.tide != null else -1)
|
||||
if sim.tide != null:
|
||||
buffer.put_data(sim.tide.levels.to_byte_array())
|
||||
buffer.put_64(sim.props.count())
|
||||
buffer.put_data(sim.props.health.to_byte_array())
|
||||
var piece_ids: Array = sim.structures.pieces.keys()
|
||||
piece_ids.sort()
|
||||
buffer.put_64(piece_ids.size())
|
||||
for piece_id: int in piece_ids:
|
||||
var piece: StructureSet.Piece = sim.structures.pieces[piece_id]
|
||||
buffer.put_64(piece.id)
|
||||
buffer.put_u8(piece.kind)
|
||||
buffer.put_u8(piece.material)
|
||||
buffer.put_u8(piece.facing)
|
||||
for value: int in [piece.slot.x, piece.slot.y, piece.slot.z, piece.slot.w]:
|
||||
buffer.put_32(value)
|
||||
buffer.put_64(piece.owner)
|
||||
buffer.put_32(piece.health)
|
||||
buffer.put_32(piece.build_ticks_left)
|
||||
buffer.put_u8(1 if piece.grounded else 0)
|
||||
buffer.put_64(piece.placed_tick)
|
||||
sim.loot.write_state(buffer)
|
||||
var hasher: HashingContext = HashingContext.new()
|
||||
hasher.start(HashingContext.HASH_SHA256)
|
||||
hasher.update(buffer.data_array)
|
||||
return hasher.finish().hex_encode()
|
||||
|
||||
|
||||
static func _put_varint(out: StreamPeerBuffer, value: int) -> void:
|
||||
value &= 0xFFFFFFFF
|
||||
while value >= 0x80:
|
||||
out.put_u8(value & 0x7F | 0x80)
|
||||
value >>= 7
|
||||
out.put_u8(value)
|
||||
|
||||
|
||||
## Reads a varint of at most five bytes at cursor[0] and moves the cursor past it.
|
||||
## Returns -1 if the buffer ends first or the number is too long.
|
||||
static func _read_varint(bytes: PackedByteArray, cursor: Array[int]) -> int:
|
||||
var value: int = 0
|
||||
for shift: int in range(0, 35, 7):
|
||||
if cursor[0] >= bytes.size():
|
||||
return -1
|
||||
var byte: int = bytes[cursor[0]]
|
||||
cursor[0] += 1
|
||||
value |= (byte & 0x7F) << shift
|
||||
if byte & 0x80 == 0:
|
||||
return value & 0xFFFFFFFF
|
||||
return -1
|
||||
@@ -0,0 +1 @@
|
||||
uid://ded1axgwbh60m
|
||||
@@ -21,6 +21,8 @@ var sim_tick: int = 0
|
||||
var own_id: int = 0
|
||||
## The newest of this client's command ticks the server had received, or -1.
|
||||
var command_tick: int = -1
|
||||
## The newest WORLD message the server had made when it built that picture.
|
||||
var world_seq: int = 0
|
||||
## This client's own block from that picture (see NetSnapshot.self_of), or empty when
|
||||
## it isn't playing: in the lobby, eliminated or watching someone else.
|
||||
var own: Dictionary = {}
|
||||
@@ -88,6 +90,7 @@ func apply(bytes: PackedByteArray) -> bool:
|
||||
sim_tick = snapshot["sim_tick"]
|
||||
own_id = snapshot["own_id"]
|
||||
command_tick = snapshot["command_tick"]
|
||||
world_seq = snapshot["world_seq"]
|
||||
own = snapshot["self"]
|
||||
match_phase = snapshot["match_phase"]
|
||||
tide_phase = snapshot["tide_phase"]
|
||||
|
||||
@@ -109,7 +109,9 @@ static func interest(sim: Simulation, viewer: SimEntity, among: Array[SimEntity]
|
||||
## outside a match. `tick` is the server's own tick count, which must grow with every
|
||||
## call for the same client. `own_id` is the client's own player, or 0: while that is
|
||||
## who it watches and they are still in the match, the snapshot carries their own block.
|
||||
func build(handle: int, sim: Simulation, viewer_id: int, tick: int, match_phase: int, own_id: int = 0) -> PackedByteArray:
|
||||
## `world_seq` is the newest WORLD message made (see WorldSender), so the client can
|
||||
## tell when it has heard everything this snapshot's world had in it.
|
||||
func build(handle: int, sim: Simulation, viewer_id: int, tick: int, match_phase: int, own_id: int = 0, world_seq: int = 0) -> PackedByteArray:
|
||||
if not _clients.has(handle):
|
||||
return PackedByteArray()
|
||||
var client: Dictionary = _clients[handle]
|
||||
@@ -128,7 +130,7 @@ func build(handle: int, sim: Simulation, viewer_id: int, tick: int, match_phase:
|
||||
"tick": tick, "baseline": baseline_tick, "sim_tick": sim.tick, "command_tick": client["command_tick"],
|
||||
"own_id": viewer.id if viewer != null else 0, "match_phase": match_phase,
|
||||
"tide_phase": sim.tide.phase_at(sim.tick) if sim.tide != null else 0,
|
||||
"sea_cm": roundi(sim.sea_level * 100.0),
|
||||
"sea_cm": roundi(sim.sea_level * 100.0), "world_seq": world_seq,
|
||||
}
|
||||
var own_bytes: int = 0
|
||||
if viewer != null and viewer.id == own_id and not viewer.eliminated:
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
## The server's side of WORLD messages (see NetWorld): works out, after each tick, what
|
||||
## changed in the parts of the match that aren't entities, and makes the whole state
|
||||
## for someone who has just arrived.
|
||||
##
|
||||
## Everyone is sent the same changes, in order and reliably, so one message is made
|
||||
## per tick and nothing is remembered per client. A tick in which nothing changed
|
||||
## makes no message. Changes are numbered from the last begin(); every snapshot says
|
||||
## the newest number, so a client knows when it has heard everything a snapshot's
|
||||
## world had in it.
|
||||
##
|
||||
## The simulation keeps the lists this reads: StructureSet.changed and .removed, and
|
||||
## PropSet.changed. This is the one reader that clears them.
|
||||
class_name WorldSender
|
||||
extends RefCounted
|
||||
|
||||
## The newest change message's number: 0 until the first.
|
||||
var seq: int = 0
|
||||
## Messages and bytes made so far, full ones not counted.
|
||||
var messages: int = 0
|
||||
var bytes_made: int = 0
|
||||
|
||||
var _sim: Simulation = null
|
||||
var _removed_seen: int = 0
|
||||
var _chests: PackedByteArray = PackedByteArray()
|
||||
var _tide_sent: bool = false
|
||||
var _loot_sent: bool = false
|
||||
## Pieces with an ID below this have been sent as new.
|
||||
var _next_new: int = 1
|
||||
|
||||
|
||||
## True if begin() was last called for `sim`.
|
||||
func is_for(sim: Simulation) -> bool:
|
||||
return _sim == sim
|
||||
|
||||
|
||||
## Starts again for a new simulation. Whatever it already holds goes in full(), not
|
||||
## in changes.
|
||||
func begin(sim: Simulation) -> void:
|
||||
_sim = sim
|
||||
seq = 0
|
||||
sim.structures.changed.clear()
|
||||
sim.props.changed.clear()
|
||||
_removed_seen = sim.structures.removed.size()
|
||||
_chests = sim.loot.chest_opened.duplicate()
|
||||
_tide_sent = sim.tide != null
|
||||
_loot_sent = _loot_placed(sim)
|
||||
_next_new = sim.structures.next_id()
|
||||
|
||||
|
||||
## The whole state as it stands, for a client that knows nothing. It carries the
|
||||
## newest change's number, and the changes after it apply on top; one already included
|
||||
## here does no harm applied twice.
|
||||
func full() -> PackedByteArray:
|
||||
var sim: Simulation = _sim
|
||||
var message: Dictionary = {
|
||||
"flags": NetWorld.FLAG_FULL | (NetWorld.FLAG_LOOT if _loot_sent or _loot_placed(sim) else 0),
|
||||
"seq": seq, "tick": sim.tick,
|
||||
}
|
||||
if sim.tide != null:
|
||||
message["tide"] = {"started": sim.tide.started_tick, "levels": sim.tide.levels}
|
||||
var pieces: Array = []
|
||||
var piece_ids: Array = sim.structures.pieces.keys()
|
||||
piece_ids.sort()
|
||||
for piece_id: int in piece_ids:
|
||||
pieces.append(NetWorld.piece_entry(sim.structures.pieces[piece_id]))
|
||||
message["pieces"] = pieces
|
||||
var props: PackedInt32Array = PackedInt32Array()
|
||||
for prop: int in sim.props.count():
|
||||
if sim.props.health[prop] != int(Tuning.PROP_KINDS[sim.props.kind_name(prop)]["health"]):
|
||||
props.append(prop)
|
||||
props.append(sim.props.health[prop])
|
||||
message["props"] = props
|
||||
var chests: PackedInt32Array = PackedInt32Array()
|
||||
for index: int in sim.loot.chest_opened.size():
|
||||
if sim.loot.chest_opened[index] != 0:
|
||||
chests.append(index)
|
||||
message["chests"] = chests
|
||||
return NetWorld.encode_world(message)
|
||||
|
||||
|
||||
## What changed since the last call, as one WORLD message, or nothing if nothing did.
|
||||
## Call after every tick.
|
||||
func changes() -> PackedByteArray:
|
||||
var sim: Simulation = _sim
|
||||
var structures: StructureSet = sim.structures
|
||||
var tide_new: bool = sim.tide != null and not _tide_sent
|
||||
var loot_now: bool = _loot_sent or _loot_placed(sim)
|
||||
var chests_changed: bool = sim.loot.chest_opened != _chests
|
||||
if structures.changed.is_empty() and sim.props.changed.is_empty() and structures.removed.size() == _removed_seen and not tide_new and loot_now == _loot_sent and not chests_changed:
|
||||
return PackedByteArray()
|
||||
var message: Dictionary = {"flags": NetWorld.FLAG_LOOT if loot_now else 0, "tick": sim.tick}
|
||||
if tide_new:
|
||||
message["tide"] = {"started": sim.tide.started_tick, "levels": sim.tide.levels}
|
||||
var pieces: Array = []
|
||||
var damaged: PackedInt32Array = PackedInt32Array()
|
||||
var piece_ids: Array = structures.changed.keys()
|
||||
piece_ids.sort()
|
||||
for piece_id: int in piece_ids:
|
||||
var piece: StructureSet.Piece = structures.find(piece_id)
|
||||
if piece == null:
|
||||
continue
|
||||
if piece_id >= _next_new:
|
||||
pieces.append(NetWorld.piece_entry(piece))
|
||||
else:
|
||||
damaged.append(piece_id)
|
||||
damaged.append(StructureSet.damage_taken(piece))
|
||||
message["pieces"] = pieces
|
||||
message["damaged"] = damaged
|
||||
message["removed"] = structures.removed.slice(_removed_seen)
|
||||
var props: PackedInt32Array = PackedInt32Array()
|
||||
var prop_ids: Array = sim.props.changed.keys()
|
||||
prop_ids.sort()
|
||||
for prop: int in prop_ids:
|
||||
props.append(prop)
|
||||
props.append(sim.props.health[prop])
|
||||
message["props"] = props
|
||||
var chests: PackedInt32Array = PackedInt32Array()
|
||||
if chests_changed:
|
||||
for index: int in sim.loot.chest_opened.size():
|
||||
if sim.loot.chest_opened[index] != 0 and (index >= _chests.size() or _chests[index] == 0):
|
||||
chests.append(index)
|
||||
message["chests"] = chests
|
||||
|
||||
structures.changed.clear()
|
||||
sim.props.changed.clear()
|
||||
_removed_seen = structures.removed.size()
|
||||
_chests = sim.loot.chest_opened.duplicate()
|
||||
_tide_sent = sim.tide != null
|
||||
_loot_sent = loot_now
|
||||
_next_new = structures.next_id()
|
||||
seq += 1
|
||||
message["seq"] = seq
|
||||
var bytes: PackedByteArray = NetWorld.encode_world(message)
|
||||
messages += 1
|
||||
bytes_made += bytes.size()
|
||||
return bytes
|
||||
|
||||
|
||||
static func _loot_placed(sim: Simulation) -> bool:
|
||||
return sim.loot.floor_spots.size() + sim.loot.chest_positions.size() + sim.loot.crate_contents.size() > 0
|
||||
@@ -0,0 +1 @@
|
||||
uid://d27rnyrb1srcn
|
||||
Reference in New Issue
Block a user