feat(client): drag with prediction and rollback (#72)

Drag a controlled token (GM: any token) at <=20 Hz plus a final send on release;
the sprite follows the pointer while authoritative frames are ignored for drawing.
Uniform move nacks roll back with a short tween (on release if still dragging),
rate-limited acks drop quietly, and pending reqIds die with the connection.

- slices/move.ts: pure drag/pending/ack state machine at the reducer seam
- render/modules/drag.ts: canvas pointer input, capture-phase so token drag wins
  over pan/pinch (#69); sends via the new intents bridge
- tokens renderer draws the optimistic/confirmed position and tweens the rollback
- intents.ts + ws.send onReqId: one reqId-keyed sender for render modules
- e2e: drag persists after reload, wall refusal tween, GM move mid-drag,
  reconnect mid-drag dropping the pending map
This commit is contained in:
2026-11-21 09:41:03 +01:00
parent 4534ed6426
commit c7d5e2cc69
10 changed files with 1284 additions and 13 deletions
+148
View File
@@ -0,0 +1,148 @@
// Drag own tokens with prediction and rollback (T9, #72; DESIGN 7.4 input, 7.5, 5.5, 6.4).
//
// Hand-rolled DOM pointer events on the canvas (DESIGN 7.2: Pixi federated events are off). The
// listener sits on `window` in the capture phase and only starts a drag when the press lands on
// the canvas *and* on a token this session may move. When it does, propagation is stopped, so the
// camera's pan/pinch (#69), which listens at the canvas, never sees the gesture: a token drag takes
// precedence over pan exactly when the pointer starts on a token the user controls.
//
// The module owns input only. Prediction lives in `slices/move.ts` (a `reqId`-keyed pending map and
// the rollback state machine); the token renderer draws the optimistic position. Sends are capped
// at 20 Hz (DESIGN 6.4) plus one final position on release, each through the session's protocol
// client (`intents.ts`) so the ack can be matched by `reqId`.
import type { RenderContext, RenderModule } from '../stage.ts'
import type { Vec2 } from '../../protocol.ts'
import { sendIntent } from '../../intents.ts'
import { dragOf, draggableAt } from '../../slices/move.ts'
import { tokensOf } from '../../slices/tokens.ts'
/** 20 Hz while dragging (DESIGN 6.4, FIXED #15); the release always sends. */
export const MOVE_SEND_INTERVAL_MS = 50
interface ActiveDrag {
id: string
pointerId: number
/** `performance.now()` of the last intent; 0 so the first move is sent at once. */
lastSent: number
}
export const renderModule: RenderModule = {
name: 'drag',
mount({ app, layers, store }: RenderContext): () => void {
const canvas = app.canvas
let active: ActiveDrag | null = null
/** Canvas CSS pixels -> the tokens layer's world coordinates (the camera's inverse, #69). */
function worldPointOf(event: PointerEvent): Vec2 {
const rect = canvas.getBoundingClientRect()
const local = layers.tokens.toLocal({ x: event.clientX - rect.left, y: event.clientY - rect.top })
return [local.x, local.y]
}
function send(id: string, pos: Vec2): void {
try {
const pending = sendIntent('token.move', { id, pos: [pos[0], pos[1]] }, reqId => {
// The slice records the intent first; the ack frame that follows finds it by `reqId`.
store.dispatch({ type: 'move-sent', reqId, id, pos })
})
// A refused/unreachable send has no pending entry (onReqId never ran) and nothing to undo.
pending.catch(() => undefined)
} catch {
// `sendIntent` rejects rather than throws, but a drag must never break the render loop.
}
}
function detach(): void {
window.removeEventListener('pointermove', onMove, true)
window.removeEventListener('pointerup', onUp, true)
window.removeEventListener('pointercancel', onCancel, true)
window.removeEventListener('blur', onCancel)
}
function stop(): void {
active = null
detach()
}
function onDown(event: PointerEvent): void {
if (active !== null) return
// Only the primary pointer over the canvas itself; DOM panels keep their clicks.
if (event.button !== 0 || !event.isPrimary || event.target !== canvas) return
const state = store.state
if (state.connection.phase !== 'live') return
const point = worldPointOf(event)
const token = draggableAt(tokensOf(state), state.session.role, point)
if (!token) return
// A token drag wins over pan/pinch (#69): the camera's listener never sees this gesture.
event.preventDefault()
event.stopImmediatePropagation()
active = { id: token.id, pointerId: event.pointerId, lastSent: 0 }
store.dispatch({ type: 'drag-start', id: token.id, pos: token.pos })
window.addEventListener('pointermove', onMove, true)
window.addEventListener('pointerup', onUp, true)
window.addEventListener('pointercancel', onCancel, true)
window.addEventListener('blur', onCancel)
}
function onMove(event: PointerEvent): void {
const drag = active
if (drag === null || event.pointerId !== drag.pointerId) return
// A reconnect (`hello`/`close`) reset the slice under us: stop sending stale intents.
if (dragOf(store.state)?.id !== drag.id) {
stop()
return
}
event.preventDefault()
event.stopImmediatePropagation()
const pos = worldPointOf(event)
store.dispatch({ type: 'drag-move', id: drag.id, pos })
const now = performance.now()
if (now - drag.lastSent >= MOVE_SEND_INTERVAL_MS) {
drag.lastSent = now
send(drag.id, pos)
}
}
function onUp(event: PointerEvent): void {
const drag = active
if (drag === null || event.pointerId !== drag.pointerId) return
event.preventDefault()
event.stopImmediatePropagation()
// A reconnect (or the server dropping the token) already ended this drag: do not send a
// final intent that belongs to the dead connection (6.3).
if (dragOf(store.state)?.id !== drag.id) {
stop()
return
}
const pos = worldPointOf(event)
store.dispatch({ type: 'drag-end', id: drag.id, pos })
stop()
// The final position always goes out (6.4); a dud has its own ack and may rate-limit.
send(drag.id, pos)
}
function onCancel(event: Event): void {
const drag = active
if (drag === null) return
if (event.type === 'pointercancel') {
const pointer = event as PointerEvent
if (pointer.pointerId !== drag.pointerId) return
}
const current = dragOf(store.state)
if (current?.id === drag.id) {
store.dispatch({ type: 'drag-end', id: drag.id, pos: current.pos })
}
stop()
}
// Capture on `window` beats every listener attached to the canvas (#69's pan included).
window.addEventListener('pointerdown', onDown, true)
return () => {
window.removeEventListener('pointerdown', onDown, true)
stop()
}
},
}
+116 -12
View File
@@ -12,8 +12,12 @@
import { BitmapFont, BitmapText, Container, Graphics, GraphicsContext } from 'pixi.js'
import type { RenderContext, RenderModule } from '../stage.ts'
import type { RootState } from '../../reducer.ts'
import type { Vec2 } from '../../protocol.ts'
import { TokenBoard } from '../tokenBoard.ts'
import type { TokenPatch } from '../tokenBoard.ts'
import { drawPositionOf, moveOf, rollbacksOf } from '../../slices/move.ts'
import type { RollbackTween } from '../../slices/move.ts'
import { tokensOf } from '../../slices/tokens.ts'
import type { TokenView } from '../../slices/tokens.ts'
@@ -170,7 +174,14 @@ function applyView(
}
/** Publish the renderer's own counts, so the e2e can observe "only changed entities touched". */
function publish(canvas: HTMLCanvasElement, board: TokenBoard, patch: TokenPatch, labels: number): void {
function publish(
canvas: HTMLCanvasElement,
board: TokenBoard,
patch: TokenPatch,
labels: number,
state: RootState,
nodes: ReadonlyMap<string, TokenNode>,
): void {
const datasets = canvas.dataset
datasets['tokens'] = String(board.size)
datasets['tokenEntered'] = String(patch.entered.length)
@@ -181,8 +192,34 @@ function publish(canvas: HTMLCanvasElement, board: TokenBoard, patch: TokenPatch
datasets['tokenStatuses'] = [...board.views.values()]
.flatMap(view => view.statuses.map(status => `${view.id}:${status}`))
.join(' ')
// The drag renderer's instrumentation (#72): the drawn position (so the e2e reads what the
// browser shows, not what the reducer predicts) plus the move state machine's counters.
datasets['tokenPositions'] = [...nodes.entries()]
.map(([id, node]) => `${id}:${Math.round(node.container.x)},${Math.round(node.container.y)}`)
.join(' ')
const move = moveOf(state)
datasets['dragId'] = move.drag?.id ?? ''
datasets['dragPos'] = move.drag
? `${Math.round(move.drag.pos[0])},${Math.round(move.drag.pos[1])}`
: ''
datasets['dragPhase'] = move.drag !== null ? 'drag' : Object.keys(move.rollbacks).length > 0 ? 'rollback' : ''
datasets['dragPending'] = String(move.pending.length)
datasets['dragRefused'] = String(move.refused)
datasets['dragRateLimited'] = String(move.rateLimited)
datasets['dragRollbacks'] = String(move.rollbackCount)
datasets['dragDropped'] = String(move.dropped)
}
/** Cosmetic rollback tween (DESIGN 7.5: a short slide back, never a teleport). */
const ROLLBACK_MS = 280
interface ActiveTween {
rb: RollbackTween
from: Vec2
started: number
}
export const renderModule: RenderModule = {
name: 'tokens',
mount(context: RenderContext): (() => void) | void {
@@ -193,32 +230,99 @@ export const renderModule: RenderModule = {
const pool: TokenNode[] = []
const nodes = new Map<string, TokenNode>()
const stats = { labels: 0 }
/** At most one cosmetic rollback per token; keyed by token id, replaced on a newer sequence. */
const tweens = new Map<string, ActiveTween>()
function removeNode(id: string): void {
const node = nodes.get(id)
if (!node) return
tweens.delete(id)
layers.tokens.removeChild(node.container)
node.container.visible = false
nodes.delete(id)
pool.push(node)
}
function enterNode(view: TokenView): void {
function atFor(state: RootState, view: TokenView, node: TokenNode): Vec2 {
// A rollback tween owns the sprite position while it runs; a drag/pending prediction owns it
// otherwise (7.5); with neither, the authoritative `token` frame is the truth.
if (tweens.has(view.id)) return [node.container.x, node.container.y]
return drawPositionOf(state, view.id) ?? view.pos
}
function enterNode(view: TokenView, state: RootState): void {
const node = pool.pop() ?? createNode(view.radius)
node.container.visible = true
applyView(node, view, stats)
applyView(node, view, stats, atFor(state, view, node))
layers.tokens.addChild(node.container)
nodes.set(view.id, node)
}
/**
* Apply the reducer's drag/rollback state to the sprites. Touches only a dragged token and the
* tokens with a pending tween, so a pointer move never walks the whole scene (DESIGN 7.2).
*/
function applyMovement(state: RootState, now: number): void {
const move = moveOf(state)
if (move.drag) {
const node = nodes.get(move.drag.id)
if (node) {
tweens.delete(move.drag.id)
node.container.position.set(move.drag.pos[0], move.drag.pos[1])
}
}
const active = rollbacksOf(state)
const current = new Set<string>()
for (const rb of active) {
current.add(rb.id)
const node = nodes.get(rb.id)
if (!node) continue
const existing = tweens.get(rb.id)
if (existing?.rb.seq === rb.seq) continue
tweens.set(rb.id, {
rb,
from: [node.container.x, node.container.y],
started: now,
})
}
// A tween the reducer no longer knows about (a new drag, a reset) is done.
for (const id of [...tweens.keys()]) {
if (!current.has(id) || !nodes.has(id)) tweens.delete(id)
}
}
function tick(): void {
if (tweens.size === 0) return
const now = performance.now()
for (const [id, tween] of tweens) {
const node = nodes.get(id)
if (!node) {
tweens.delete(id)
continue
}
const t = Math.min(1, (now - tween.started) / ROLLBACK_MS)
const eased = 1 - (1 - t) * (1 - t) * (1 - t) // ease-out cubic
node.container.position.set(
tween.from[0] + (tween.rb.to[0] - tween.from[0]) * eased,
tween.from[1] + (tween.rb.to[1] - tween.from[1]) * eased,
)
if (t >= 1) {
tweens.delete(id)
store.dispatch({ type: 'rollback-done', id, seq: tween.rb.seq })
}
}
publish(canvas, board, { reset: false, entered: [], updated: [], left: [] }, stats.labels, store.state, nodes)
}
// The stage is created only once the session is live, but `app.init` is async and the resync
// can beat it: start from whatever the reducer already holds, then follow the event stream.
board.seed(tokensOf(store.state))
let patch = board.drain()
for (const view of patch.entered) enterNode(view)
publish(canvas, board, patch, stats.labels)
for (const view of patch.entered) enterNode(view, store.state)
publish(canvas, board, patch, stats.labels, store.state, nodes)
app.ticker.add(tick)
const unsubscribe = store.subscribe((_state, event) => {
const unsubscribe = store.subscribe((state, event) => {
board.apply(event)
patch = board.drain()
if (patch.reset) {
@@ -227,17 +331,17 @@ export const renderModule: RenderModule = {
for (const id of patch.left) removeNode(id)
for (const view of patch.updated) {
const node = nodes.get(view.id)
if (node) applyView(node, view, stats)
else enterNode(view)
}
for (const view of patch.entered) enterNode(view)
if (patch.reset || patch.entered.length > 0 || patch.updated.length > 0 || patch.left.length > 0) {
publish(canvas, board, patch, stats.labels)
if (node) applyView(node, view, stats, atFor(state, view, node))
else enterNode(view, state)
}
for (const view of patch.entered) enterNode(view, state)
applyMovement(state, performance.now())
publish(canvas, board, patch, stats.labels, state, nodes)
})
return () => {
unsubscribe()
app.ticker.remove(tick)
}
},
}