aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 683f8c1e7cf6c0b4c9090cbd11e603e3ef4b8339
parent b042ac23b29eecee096862d326de9b01a6384507
Author: anon <anon@example.com>
Date:   Mon, 26 Oct 2026 12:38:49 +0000

Simulate authored flight transitions and native 3D facing

Apply ordered flight effects only after inventory commits, preserving existing
falls and vector motion. Reconstruct flight and ground facing, and anchor newly
loaded owners and idle observers with the native position-correction flag.

Verify delayed effects, failed writes, swimming rejection, pose replay and
orientation cases, plus paired hardware WASM flight and jump/equip checks.
Record remaining input, trajectory and high-altitude initialization work.

Diffstat:
MTODO.md | 30+++++++++++++++++++++++++++---
Mdocs/player-geometry.md | 6++++--
Mdocs/player-movement.md | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mdocs/vehicles.md | 12+++++++++---
Mserver/equipment.go | 8+++-----
Mserver/inventory.go | 18+++++++++---------
Mserver/player_collision.go | 101+++++++++++++++++++++++++++++++++++++++++++++++++------------------------------
Aserver/player_flight.go | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/player_flight_test.go | 329+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/player_follow.go | 2+-
Mserver/player_form_test.go | 8++++++--
Mserver/player_movement.go | 9+++++++--
Mserver/vehicle.go | 3+++
Mserver/world_actions.go | 7+++++++
14 files changed, 662 insertions(+), 69 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -1246,9 +1246,9 @@ disconnect retention and succession policy still need period corroboration. jump/landing behavior, late observers during ascent, midair reconnect and roots/snares during a jump. Ordinary jump/landing is implemented below. Finish internal/nonzero orientation modes, live Chest mass and encumbrance, and Grid - form entry/exit body rebuilding. Vehicle body replacement is implemented below; - flight activation/removal offsets, orientation modes and in-flight gravity - still need shared simulation and native trajectory checks. Add indoor room + form entry/exit body rebuilding. Vehicle body replacement and ordinary flight + transitions/orientation are implemented below. Expand flight checks across + terrain contacts, water boundaries and special modes. Add indoor room transforms, actor colliders and dynamic platforms. See [player geometry](docs/player-geometry.md). - [x] Apply supported vehicles' authored shape/scale effects to collision bodies. @@ -1259,6 +1259,30 @@ disconnect retention and succession policy still need period corroboration. deadlines, rejected completion, failed persistence, signed Pioneer scale, owner/observer reconstruction and actual ground projection. See [vehicle collision bodies](docs/player-geometry.md#vehicle-forms-and-human-restoration). +- [x] Simulate authored flight entry/removal in the shared movement state, retaining + effect order, position-only lifts, existing falling/gravity and cached controls. + Rebuild mode4 facing from full 3D velocity, including reverse, vertical and + half-turn cases. Publish predicted movement and effects only after the item + transaction commits; a failed save must leave pose/body/controls untouched. + Correct owner and idle observer initialization after native OnWear so reconnects + do not accumulate height. Preserve rejected swimming transitions and keep + equipment helper events out of client movement dispatch. See + [flight movement](docs/player-movement.md#flight-transitions-and-facing). +- [ ] Audit high-altitude owner teleport/reinitialization against the remote + actor and server. After a same-playfield control edit to Y900, the sampled + owner was at Y95.14, observer copy Y868.45 and server Y899.94. + Retain the raw teleport/spawn packets and trace their native consumers before + changing height policy; do not assume a flight ceiling. Evidence: + `local/player-flight-movement/runtime/pair-verified-fall-start.json`. +- [ ] Expand flight input and trajectory checks. Distinguish native UI producer + gates from physical helper admission (the UI suppresses Space/action13 in + mode7 although the helper accepts it). Extend the verified jump-to-flight + overlap to longer falls and other effects. Test water rejection followed by + leaving water and late observer initialization, + and curved-flight cadence with synchronized samples. A concurrent race-test + run measured a transient 0.846 m difference with up to 57 ms between native and + server samples; settled forward/reverse errors were below 0.07 m. Keep timing + bounds explicit instead of claiming exact trajectory equivalence. - [x] Simulate ordinary outdoor jumping and physical landing. Movement13 uses raw Strength/Agility, the native upward ceiling probe and mass/impulse float stores. Preserve horizontal controls, reject swimming/sitting and repeated airborne diff --git a/docs/player-geometry.md b/docs/player-geometry.md @@ -328,8 +328,10 @@ removed; database checks and hashes preserve all unrelated rows. The sole HTTPS preview remains on8443. This does not complete Grid replacement, special appearance flags, arbitrary -concurrent forms, flight activation/removal height offsets, orientation changes, -in-flight gravity or indoor vehicle policy. Those remain explicit TODOs. +concurrent forms or indoor vehicle policy. Ordinary flight activation/removal, +mode4 orientation and in-flight gravity now use the shared simulation; see +[flight movement](player-movement.md#flight-transitions-and-facing). Other forms, +nonzero ground orientation modes and the wider lifecycle matrix remain TODOs. ## Ordinary outdoor jumps and landing diff --git a/docs/player-movement.md b/docs/player-movement.md @@ -9,7 +9,8 @@ and basic swimming transitions, plus ordinary outdoor jumping and landing. The shared geometry reads selected 14.9.1 grids, cell surfaces and water directly from the bundled data. [Player geometry](player-geometry.md) records the held-wall and body checks and the remaining lifecycle, indoor, -platform, special jump modes and full flight work. +platform and special jump modes. [Flight](#flight-transitions-and-facing) uses +the same integration and collision paths. ## Ordinary ground motion @@ -51,9 +52,89 @@ The native integrator rejects nonpositive or greater-than-four-second frame intervals, and subdivides admitted intervals at a default maximum of 0.4 seconds. It has no 20-second held-input expiry. Outdoor gravity and contact response run through the shared integrator and its outer-frame alignment. Frame cadence, -flight and nonzero orientation modes remain verification boundaries; the +nonzero ground orientation modes remain verification boundaries; the flat-ground reductions above do not replace those branches. +## Flight transitions and facing + +The shared OnWear iterator consumes authored function 53138 in order with shape +and scale functions. Accepted entry selects helper mode 7, disables new falls, +raises relative Y by float32(0.5) through position-only placement, then stores +orientation mode 4. Removal restores the preferred walking/running helper mode, +enables new falls, raises Y by float32(0.1), clears only vertical control, and +restores the player's stat 197 orientation. In the supported player data, raw 197 +is zero; equipment/nano modifiers supply its effective value. Other nonzero +ground orientation algorithms still need implementation and native checks. + +Position-only placement retains vector velocity and independent vertical +velocity, records the requested Y for fall-height history, and aligns using the +previous orientation mode. Equipment completion predicts old motion first and +publishes the ordered effects only after its inventory transaction succeeds. +The native helper rejects flight entry/removal from inactive 1, swimming 4 and +sitting 8. A worn flight item and an accepted physical flight mode are distinct. +Client movement packets do not invoke these equipment transitions. + +Disabling falling does not cancel an existing jump or fall. Existing independent +vertical velocity still accelerates at -20 and clamps to +/-50 until actual +contact lands the actor. Flight retains world veto, segment/sphere collisions, +upward ground correction and landing. It skips slope restrictions, downward +ground snapping and admission of new falls or deep water. Removal close to the +ground can snap using the resized vehicle body before human restoration; removal +high above ground starts a fall using the requested lifted Y. + +Orientation mode 4 reconstructs facing from full 3D vector velocity when cached +speed is nonzero, otherwise from body forward. It rebuilds up from worldY and +retains negative direction's reverse facing, with the native matrix fallback +near a half-turn. Independent vertical velocity and direct strafe/vertical input +do not enter this orientation. Held turns rotate around worldY after displacement; +mouse pitch/yaw instead redirects vector velocity immediately through the pose +setter. Changing orientation mode alone does not flatten facing or redirect V. + +Worn-state reconstruction restores flight without repeating live displacement. +Native OnWear still lifts each newly loaded owner/observer actor. Ready replay +therefore ends with authoritative position correction action 0x94, pass-on 0. Its +high bit selects the native owner's position-only correction branch; ordinary 20 +is ignored for that actor. A remote actor consumes the same flagged packet as +ordinary full-pose action 20. Late observers also receive an anchor for idle +flying players after their OnWear initialization. Repeated ready acknowledgments +do not replay effects or corrections. + +Maintained-source evidence and independent verifiers are retained under +`local/player-flight-movement/research/transitions/` (75 complete bodies) and +`research/integration/` (65 complete bodies). The ledgers bind helper tables, +flags, setters, quaternion conversion and initialized constants to source hashes. +The companion `research/input-admission/` ledger verifies50 complete bodies for +the UI jump producer, permission bits and ordinary equipment admission. +No guest calls or writes are used. `TestPlayerFlight*` covers committed deadlines, +ordered entry/removal, independent gravity, vector retention, full 3D and reverse +facing, vertical/half-turn cases, held turns, rejected swimming transitions, +forged movement events, failed commits and owner/idle-observer initialization. + +Two headed GPU WASM clients check live activation, owner and observer +reconnects, pitched forward turns, reverse motion and removal from a pitched +hover. Activation agrees at Y16.91. Initialization's compact anchor rounds it +to 16.875 on both clients, without accumulating another lift. Settled curved +forward/reverse position differences are below 0.07 m. After removal at Y60, +both native clients and the server land at Y16.786125 and level their facing. +The removal-facing regression reproduces the mismatch before its repair. +A timed ordinary jump overlaps live equip: both clients retain descending +independent velocity after entering flight, continue gravity and land at +Y16.520000, agreeing with the server within 0.000003 m. Space while already flying +is intentionally suppressed by the native UI producer before helper dispatch. +Curved-motion samples are asynchronous: the largest raw difference was 0.846 m +with up to 57 ms between native and server reads under concurrent race testing. +The captures retain timestamps and explicit timing bounds; they do not establish +bit-identical trajectories. High-altitude owner initialization and broader input, +water and special-mode combinations remain separate TODOs. + +The final code passes all 1,300 top-level server tests (14,271 results), 91 focused +roots (290 results), 213 race roots (808 results), the data checks and `go vet`. +`local/player-flight-movement/` retains exact source coverage, regression failures, +hardware/native packet captures and the independently checked source ledgers. +All six owned test visitors and their fixture item are removed afterward; +cleanup verifies unrelated SQLite rows unchanged, foreign keys and integrity. +The single LAN HTTPS8443 preview remains available for manual play. + ## Cached controls and transitions Forward/reverse start events set signed throttle and refresh speed/force before @@ -234,7 +315,7 @@ The final Go code passes all 1,211 top-level server tests `exact-suite-manifest.json` records complete root coverage and source hashes; `verification.json` links these checks to runtime, preview and cleanup evidence. -Complete scene geometry, slopes, gravity, flight/water, platforms and nonzero -orientation modes remain open. Establish live Chest contents mass and the +The wider scene geometry, slope, water, platform and nonzero ground orientation +matrix remains open. Establish live Chest contents mass and the encumbrance flag before adding policies for them. Expand the combined lifecycle matrix and investigate a lossless late reverse initialization only with evidence. diff --git a/docs/vehicles.md b/docs/vehicles.md @@ -263,21 +263,27 @@ restores the separately saved ground mode, respectively. SwitchToFly mode 4. LeaveFly `100468f0` enables falling, raises Y by 0.1 and restores orientation from stat 197. Removal lets native collision settle the character; the server does not teleport it directly to the ground. +These ordered transitions now run in the shared server simulation. Disabling +falling suppresses new falls while preserving an existing jump/fall and its +gravity. See [flight transitions and facing](player-movement.md#flight-transitions-and-facing). The initial SimpleChar movement snapshot carries current mode 7 and remembers walking 2 or running 3 in the separate DWORD. The reader `10047160` and setter `100496d5` keep these fields distinct. Mode refresh `10046f80` restores flight without raising Y; the subsequent ordinary worn-item initialization applies its one 0.5 m lift. Owner FullCharacter and observer TemplateAction still -apply the authored effects once, with raw base RunSpeed 100. +apply the authored effects once, with raw base RunSpeed 100. A native flagged +position correction after initialization restores authoritative altitude, including +idle actors, instead of accumulating another lift on every reconnect. Mode 7's maximum-speed branch `10047e60` passes base 12 to `10047af0`, adds `0.005 * adjustedRunSpeed`, caps at 15 before encumbrance and floors at 0.1 afterward. Forward and reverse use the same configured maximum, 13.25 m/s for the healthy, unencumbered fixture. Flight's forward vector includes quaternion Y component `2*y*z - 2*x*w`; reverse negates all three components. -The bounded server estimate uses this speed and full direction. Acceleration, -collision and encumbrance remain outside that estimate. +The shared server integrator uses this speed and full direction, including +acceleration, collision and 3D flight orientation. Live encumbrance policy remains +unresolved. The shipped controls use plain RMB mouse movement to pitch the character in first-person or locked third-person. Free third-person and Ctrl+RMB can move diff --git a/server/equipment.go b/server/equipment.go @@ -254,15 +254,13 @@ func (server *server) advanceEquipment(now time.Time) { baseHealth := character.maximumHealth() - uint32(character.directHealthBonus()) baseNano := character.maximumNano() - uint32(character.inventory.equipmentBonus(221)) attackRating := character.attackRating() - if err := server.saveInventory_locked(character, inventory); err != nil { + if err := server.saveInventory_locked(&motion, inventory); err != nil { log.Printf("Equipment: %v", err) updates[client] = append(updates[client], equipmentCorrectionPackets(client.id, move.source)...) continue } - if movementChanged { - // Anchor held movement at the speed before the equipment effect changed. - character.position, character.rotation, character.movement = motion.position, motion.rotation, motion.movement - } + // Commit the old-speed prediction and ordered wear effects together. + *character = motion if move.source < 64 && !item.isWieldableWeapon() { server.queueCombat_locked(updates, character, character, equipmentActionPacket(character.id, item, 7)) } diff --git a/server/inventory.go b/server/inventory.go @@ -120,18 +120,18 @@ func (server *server) saveInventory_locked(character *character, inventory playe previous := *character character.inventory = inventory if character.body.mesh != 0 { - // Existing bodies follow only the committed wear transitions. previous.collisionBody() character.body = previous.body - for _, item := range previous.inventory.Items { - if !slices.ContainsFunc(inventory.Items, func(other ownedItem) bool { return other.ID == item.ID && other.Slot == item.Slot }) { - character.wearCollisionBody(item, true) - } + } + // Apply only committed wear transitions, including their ordered pose changes. + for _, item := range previous.inventory.Items { + if !slices.ContainsFunc(inventory.Items, func(other ownedItem) bool { return other.ID == item.ID && other.Slot == item.Slot }) { + character.wearEffects(item, true) } - for _, item := range inventory.Items { - if !slices.ContainsFunc(previous.inventory.Items, func(other ownedItem) bool { return other.ID == item.ID && other.Slot == item.Slot }) { - character.wearCollisionBody(item, false) - } + } + for _, item := range inventory.Items { + if !slices.ContainsFunc(previous.inventory.Items, func(other ownedItem) bool { return other.ID == item.ID && other.Slot == item.Slot }) { + character.wearEffects(item, false) } } if character.maximumHealth() < healthMaximum { diff --git a/server/player_collision.go b/server/player_collision.go @@ -80,7 +80,7 @@ func (player *character) scaleCollisionBody(minimum int32) { } } -func (player *character) wearCollisionBody(item ownedItem, remove bool) { +func (item ownedItem) wearFunctions(yield func(gamedata.ItemFunction, gamedata.ItemFunction) bool) { if !item.fitsEquipmentSlot(item.Slot) { return } @@ -90,45 +90,69 @@ func (player *character) wearCollisionBody(item ownedItem, remove bool) { if section.Type != 2 || section.Subtype != 14 { continue } - // Shape and scale effects run in authored order on both wear and removal. for index, function := range *section.Functions { - switch function.ID { - case 53012, 53045: - if *function.Arguments[0].Integer == 360 { - value := interpolateItemValue(*function.Arguments[1].Integer, *(*second.Sections[sectionIndex].Functions)[index].Arguments[1].Integer, *first.Quality, *second.Quality, item.Quality) - if remove { - value = -value - } - player.body.bonus += value - player.scaleCollisionBody(1) - } - case 53060: - form := uint32(*function.Arguments[0].Integer) - if remove && player.body.form == form { - player.body.form = 0 - fatness := player.resolvedAppearance().Fatness - if fatness > 2 { - fatness = 1 - } - player.replaceCollisionMesh(player.humanCollisionMesh(fatness)) - player.scaleCollisionBody(1) - } else if !remove && player.body.form == 0 { - player.body.form = form - mesh := gamedata.MonsterTemplates[form].Stats[12] - if player.body.mesh != mesh { - player.replaceCollisionMesh(mesh) - } - player.scaleCollisionBody(20) - } - case 53110: - if *function.Arguments[0].Integer == 360 { - player.body.base = max(int32(20), int32(*function.Arguments[1].Integer)) - if remove { - player.body.base = int32(player.baseScale()) - } - player.scaleCollisionBody(1) - } + if !yield(function, (*second.Sections[sectionIndex].Functions)[index]) { + return + } + } + } +} + +func (player *character) wearCollisionBody(item ownedItem, remove bool) { + for function, upper := range item.wearFunctions { + player.wearCollisionFunction(item, function, upper, remove) + } +} + +func (player *character) wearEffects(item ownedItem, remove bool) { + // Live effects share authored order; reconstructing a body must not move it. + for function, upper := range item.wearFunctions { + if player.body.mesh != 0 { + player.wearCollisionFunction(item, function, upper, remove) + } + if function.ID == 53138 { + player.changeFlight(remove) + } + } +} + +func (player *character) wearCollisionFunction(item ownedItem, function, upper gamedata.ItemFunction, remove bool) { + switch function.ID { + case 53012, 53045: + if *function.Arguments[0].Integer == 360 { + low, high := item.templateIDs() + value := interpolateItemValue(*function.Arguments[1].Integer, *upper.Arguments[1].Integer, *gamedata.ItemTemplates[low].Quality, *gamedata.ItemTemplates[high].Quality, item.Quality) + if remove { + value = -value + } + player.body.bonus += value + player.scaleCollisionBody(1) + } + case 53060: + form := uint32(*function.Arguments[0].Integer) + if remove && player.body.form == form { + player.body.form = 0 + fatness := player.resolvedAppearance().Fatness + if fatness > 2 { + fatness = 1 + } + player.replaceCollisionMesh(player.humanCollisionMesh(fatness)) + player.scaleCollisionBody(1) + } else if !remove && player.body.form == 0 { + player.body.form = form + mesh := gamedata.MonsterTemplates[form].Stats[12] + if player.body.mesh != mesh { + player.replaceCollisionMesh(mesh) + } + player.scaleCollisionBody(20) + } + case 53110: + if *function.Arguments[0].Integer == 360 { + player.body.base = max(int32(20), int32(*function.Arguments[1].Integer)) + if remove { + player.body.base = int32(player.baseScale()) } + player.scaleCollisionBody(1) } } } @@ -417,4 +441,5 @@ func (player *character) alignSurface(previous [3]float32, skipSegment bool) { layout.veto(&position, nil) } player.position = position + player.orientMovement() } diff --git a/server/player_flight.go b/server/player_flight.go @@ -0,0 +1,109 @@ +package main + +import "math" + +func (player *character) changeFlight(remove bool) { + movement := &player.movement + movement.prepare(player, movement.updatedAt) + // KKR PlayerVehicle Submit(27/35) rejects inactive, swimming and sitting modes. + mode := movement.components[0] + if mode == 1 || mode == 4 || mode == 8 { + return + } + movement.components[5] = movement.components[3] + movement.components[0] = 7 + lift := float32(.5) + if remove { + movement.components[0] = 2 + if player.running { + movement.components[0] = 3 + } + lift = .1 + } + + // SetRelPos preserves V and q, aligns with the previous orientation mode, + // and stores the requested position as the fall-height history. + // Sources: kkr.dll 36046770/360468F0; qqr.dll 420108F0/42011D00. + previous := player.position + player.position[1] += lift + movement.previousPosition = player.position + player.alignSurface(previous, true) + if remove { + movement.vertical = 0 + movement.orientation = uint32(player.inventory.equipmentBonus(197) + player.nanoBonus(197)) + } else { + movement.orientation = 4 + } +} + +func (player *character) orientMovement() { + if player.movement.orientation != 0 && player.movement.orientation != 4 { + return + } + // QQR CalcOrientation modes0/4 use vector motion or the stopped body forward. + // Independent q, direct lateral controls and ground normal do not enter this frame. + forward, _ := bodyAxes(player.rotation) + if player.movement.speed != 0 { + forward = player.movement.velocity + if player.movement.orientation == 4 { + length := math.Sqrt(surfaceDot(forward, forward)) + for axis := range forward { + forward[axis] = float32(float64(forward[axis]) / length) + } + } + } + up := [3]float32{0, 1, 0} + if player.movement.orientation == 0 { + forward[1] = 0 + forward = collisionDirection(forward) + if forward == [3]float32{} { + forward = [3]float32{0, 0, 1} + } + } else if forward != [3]float32{} { + for axis := range up { + up[axis] -= forward[axis] * forward[1] + } + up = collisionDirection(up) + if up == [3]float32{} { + up = [3]float32{0, 0, 1} + } + } + if player.movement.direction < 0 && player.movement.speed != 0 { + for axis := range forward { + forward[axis] = -forward[axis] + } + } + right := [3]float32{up[1]*forward[2] - up[2]*forward[1], up[2]*forward[0] - up[0]*forward[2], up[0]*forward[1] - up[1]*forward[0]} + rotation := [4]float32{up[2] - forward[1], forward[0] - right[2], right[1] - up[0], 1 + right[0] + up[1] + forward[2]} + length := float64(rotation[0])*float64(rotation[0]) + float64(rotation[1])*float64(rotation[1]) + float64(rotation[2])*float64(rotation[2]) + float64(rotation[3])*float64(rotation[3]) + if length > .01 { + for axis := range rotation { + rotation[axis] = float32(float64(rotation[axis]) / math.Sqrt(length)) + } + } else { + // FrameQuaternion's near-half-turn fallback uses MR's matrix constructor. + matrix := [3][3]float32{{right[0], up[0], forward[0]}, {right[1], up[1], forward[1]}, {right[2], up[2], forward[2]}} + trace := float64(matrix[0][0]) + float64(matrix[1][1]) + float64(matrix[2][2]) + if trace >= 0 { + scale := math.Sqrt(trace + 1) + rotation[3] = float32(.5 * scale) + rotation[0] = float32(float64(matrix[2][1]-matrix[1][2]) * (.5 / scale)) + rotation[1] = float32(float64(matrix[0][2]-matrix[2][0]) * (.5 / scale)) + rotation[2] = float32(float64(matrix[1][0]-matrix[0][1]) * (.5 / scale)) + } else { + index := 0 + for axis := 1; axis < 3; axis++ { + if matrix[axis][axis] > matrix[index][index] { + index = axis + } + } + next, last := (index+1)%3, (index+2)%3 + scale := math.Sqrt(1 + float64(matrix[index][index]) - float64(matrix[next][next]) - float64(matrix[last][last])) + rotation[index] = float32(.5 * scale) + rotation[next] = float32(float64(matrix[index][next]+matrix[next][index]) * (.5 / scale)) + rotation[last] = float32(float64(matrix[index][last]+matrix[last][index]) * (.5 / scale)) + rotation[3] = float32(float64(matrix[last][next]-matrix[next][last]) * (.5 / scale)) + } + } + player.rotation = rotation +} diff --git a/server/player_flight_test.go b/server/player_flight_test.go @@ -0,0 +1,329 @@ +package main + +import ( + "encoding/binary" + "fmt" + "math" + "testing" + "time" +) + +func TestPlayerFlightWearAndRemovalLiftOnlyAfterTheCommittedDeadline(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + player, client := world.characters[1], world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + finish := client.equipment.readyAt + + world.advanceEquipment(finish.Add(-time.Nanosecond)) + pending := player.position + world.advanceEquipment(finish) + entry, entryHistory := player.position, player.movement.previousPosition + if err := world.handleInventory(client, itemMovePacket(1, 1, 111)[20:]); err != nil || client.equipment == nil { + t.Fatal("removal was not scheduled", err) + } + world.advanceEquipment(client.equipment.readyAt) + + if pending != [3]float32{961.625, 16.41, 510.75} || entry != [3]float32{961.625, 16.91, 510.75} || entryHistory != entry { + t.Fatal("flight entry must lift once through position-only placement", pending, entry, entryHistory) + } + if math.Abs(float64(player.position[1])-16.960006713867188) > .000001 || player.movement.previousPosition != [3]float32{961.625, 17.01, 510.75} || player.movement.falling { + t.Fatal("flight exit must align the lifted position with the resized vehicle before restoring the human body", player.position, player.movement) + } + if player.flying() || player.inventory.Items[0].Slot != 64 || player.height != 150 || player.body.mesh != 17909 { + t.Fatal("flight removal lost the item or saved human form", player.inventory, player.body) + } +} + +func TestPlayerFlightEntryPreservesAnExistingFallAndPositionOnlyVelocity(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + player, client := world.characters[1], world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + finish := client.equipment.readyAt + player.position = [3]float32{961.625, 900, 510.75} + player.movement.updatedAt = finish + player.movement.falling, player.movement.verticalVelocity = true, -12 + player.movement.velocity, player.movement.speed = [3]float32{3, 4, 0}, 5 + player.movement.fallHeight = 1000 + + world.advanceEquipment(finish) + entry, velocity, falling, impulse := player.position, player.movement.velocity, player.movement.falling, player.movement.verticalVelocity + world.advancePlayerMovement(finish.Add(100 * time.Millisecond)) + + if entry != [3]float32{961.625, 900.5, 510.75} || velocity != [3]float32{3, 4, 0} || !falling || impulse != -12 { + t.Fatal("flight entry cancelled falling or redirected the existing vector", entry, velocity, falling, impulse) + } + if !player.movement.falling || player.movement.verticalVelocity != -14 || player.movement.fallHeight != 1000 || player.position[1] >= 900 { + t.Fatal("disabling new falls must preserve gravity during an existing fall", player.position, player.movement) + } +} + +func TestPlayerFlightExitPreservesVectorVelocityAndClearsOnlyVerticalControl(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + player, client := world.characters[1], world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(client.equipment.readyAt) + if err := world.handleInventory(client, itemMovePacket(1, 1, 111)[20:]); err != nil { + t.Fatal(err) + } + finish := client.equipment.readyAt + player.position = [3]float32{961.625, 60, 510.75} + player.movement.updatedAt = finish + player.movement.velocity, player.movement.speed = [3]float32{3, 4, 0}, 5 + player.movement.forward, player.movement.strafe, player.movement.turn, player.movement.vertical = 1, 2, 1.5, 6 + + world.advanceEquipment(finish) + + if player.position != [3]float32{961.625, 60.1, 510.75} || player.movement.velocity != [3]float32{3, 4, 0} || player.movement.speed != 5 { + t.Fatal("exit placement redirected or stopped vector motion", player.position, player.movement) + } + if player.movement.forward != 1 || player.movement.strafe != 2 || player.movement.turn != 1.5 || player.movement.vertical != 0 || !player.movement.falling || player.movement.fallHeight != 60.1 { + t.Fatal("exit cleared unrelated controls or failed to admit a fall", player.movement) + } + forward, _ := bodyAxes(player.rotation) + if math.Abs(float64(forward[0])-.6) > .000001 || math.Abs(float64(forward[1])-.8) > .000001 || math.Abs(float64(forward[2])) > .000001 { + t.Fatal("exit must align in the previous flight orientation mode before restoring mode0", forward, player.rotation) + } +} + +func TestPlayerFlightFailedCommitCannotPublishMovementOrBodyChanges(t *testing.T) { + for _, removal := range []bool{false, true} { + t.Run(fmt.Sprint(removal), func(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + player, client := world.characters[1], world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + if removal { + world.advanceEquipment(client.equipment.readyAt) + if err := world.handleInventory(client, itemMovePacket(1, 1, 111)[20:]); err != nil { + t.Fatal(err) + } + } + before := *player + finish := client.equipment.readyAt + failDatabaseWrites(t, world) + + world.advanceEquipment(finish) + + if player.position != before.position || player.rotation != before.rotation || player.movement != before.movement || player.body != before.body || player.inventory.Items[0] != before.inventory.Items[0] { + t.Fatal("failed equipment commit published flight effects", before.movement, player.movement) + } + }) + } +} + +func TestPlayerFlightRemovalLevelsIdleFacingOnTheNextFallFrame(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + player, client := world.characters[1], world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(client.equipment.readyAt) + player.position[1] = 60 + player.rotation = [4]float32{-.38268343, 0, 0, .9238795} + if err := world.handleInventory(client, itemMovePacket(1, 1, 111)[20:]); err != nil { + t.Fatal(err) + } + finish := client.equipment.readyAt + player.movement.updatedAt = finish + + world.advanceEquipment(finish) + exitForward, _ := bodyAxes(player.rotation) + world.advancePlayerMovement(finish.Add(100 * time.Millisecond)) + + forward, _ := bodyAxes(player.rotation) + if exitForward[1] < .7 || forward != [3]float32{0, 0, 1} || player.rotation != [4]float32{0, 0, 0, 1} || !player.movement.falling { + t.Fatal("exit must preserve pitch until the next ground-mode alignment, then level idle facing", exitForward, forward, player.rotation, player.movement) + } +} + +func TestPlayerFlightReadyAnchorsOwnerAndObserversWithoutAnotherLift(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + player, client := world.characters[1], world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(client.equipment.readyAt) + player.position, player.movement = [3]float32{961.625, 60, 510.75}, playerMovement{} + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 705, health: 100} + world.clients[2] = &worldClient{id: 2, conn: observer, ready: true} + owner := client.conn.(*combatTestConn) + client.target = false + owner.packets = nil + client.loading = true + + if err := world.handleCharacterReady(client); err != nil { + t.Fatal(err) + } + firstOwner, firstObserver := len(owner.packets), len(observer.packets) + if err := world.handleCharacterReady(client); err != nil { + t.Fatal(err) + } + + if player.position != [3]float32{961.625, 60, 510.75} || player.movement.active() || !player.flying() { + t.Fatal("restoring worn flight must not apply another live entry lift", player.position, player.movement) + } + for _, packets := range [][][]byte{owner.packets[:firstOwner], observer.packets[:firstObserver]} { + last := packets[len(packets)-1] + if binary.BigEndian.Uint32(last[20:24]) != 0x54111123 || binary.BigEndian.Uint32(last[36:40]) != 0x94 || math.Float32frombits(binary.BigEndian.Uint32(last[44:48])) != 60 { + t.Fatalf("OnWear initialization must end with native position correction: %x", last) + } + } + if len(owner.packets) != firstOwner+1 || len(observer.packets) != firstObserver+1 { + t.Fatal("repeated ready replays flight effects or corrections", len(owner.packets), len(observer.packets)) + } +} + +func TestPlayerFlightOrientationUsesFullVectorMotionAndRetainedDirection(t *testing.T) { + for _, scenario := range []struct { + velocity [3]float32 + direction int32 + forward [3]float32 + }{ + {[3]float32{0, 3, 4}, 1, [3]float32{0, .6, .8}}, + {[3]float32{0, 3, 4}, -1, [3]float32{0, -.6, -.8}}, + {[3]float32{0, 0, -5}, 1, [3]float32{0, 0, -1}}, + {[3]float32{0, 5, 0}, 1, [3]float32{0, 1, 0}}, + {[3]float32{0, -5, 0}, 1, [3]float32{0, -1, 0}}, + {[3]float32{-3, -4, 0}, -1, [3]float32{.6, .8, 0}}, + } { + t.Run(fmt.Sprint(scenario.velocity, scenario.direction), func(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + player, client := world.characters[1], world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(client.equipment.readyAt) + player.position[1] = 100 + player.movement.velocity, player.movement.speed, player.movement.direction = scenario.velocity, 5, scenario.direction + + world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond)) + + forward, _ := bodyAxes(player.rotation) + for axis, expected := range scenario.forward { + if math.Abs(float64(forward[axis]-expected)) > .000001 || math.IsNaN(float64(forward[axis])) { + t.Fatal("flight orientation flattened 3D motion or lost reverse facing", forward, scenario.forward, player.rotation) + } + } + if player.movement.velocity != scenario.velocity || player.movement.falling { + t.Fatal("orientation refresh must preserve vector motion and suppress new falls", player.movement) + } + }) + } +} + +func TestPlayerFlightHeldTurnRedirectsThreeDimensionalFacing(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + player, client := world.characters[1], world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(client.equipment.readyAt) + player.position[1] = 100 + player.movement.velocity, player.movement.speed, player.movement.turn = [3]float32{0, 3, 4}, 5, 1.5 + + world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond)) + + forward, _ := bodyAxes(player.rotation) + if math.Abs(float64(forward[0])-.11955051) > .000001 || math.Abs(float64(forward[1])-.6) > .000001 || math.Abs(float64(forward[2])-.7910169) > .000001 { + t.Fatal("held flight turn must rotate the 3D vector, then rebuild body facing", forward, player.movement) + } +} + +func TestPlayerFlightSwimmingRejectsTheAuthoredFlightTransition(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + player, client := world.characters[1], world.clients[1] + player.position = [3]float32{100, 6.5, 25} + if err := world.handleMovement(client, playerMovementRequest(player, 9)); err != nil { + t.Fatal(err) + } + world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond)) + if player.movement.components[0] != 4 { + t.Fatal("fixture must enter actual deep water", player.position, player.movement) + } + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil || client.equipment == nil { + t.Fatal("vehicle wear was not scheduled", err) + } + finish := client.equipment.readyAt + player.movement.updatedAt = finish + before := player.position + + world.advanceEquipment(finish) + + if player.position != before || player.flying() || player.movement.components[0] != 4 || !player.movement.deepWater || player.inventory.Items[0].Slot != 1 { + t.Fatal("worn flight gear must not override a rejected swimming transition", before, player.position, player.movement, player.inventory) + } +} + +func TestPlayerFlightMovementPacketsCannotInvokeEquipmentTransitions(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + player, client := world.characters[1], world.clients[1] + + for _, action := range []uint32{27, 35, 27} { + if err := world.handleMovement(client, playerMovementRequest(player, action)); err != nil { + t.Fatal(err) + } + } + + if player.flying() || player.position[1] != 16.41 || player.inventory.Items[0].Slot != 64 || player.movement.components[0] != 2 { + t.Fatal("untrusted movement events activated an unworn vehicle", player.position, player.movement, player.inventory) + } +} + +func TestPlayerFlightOwnerCorrectionKeepsTheNativeCompactFlag(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + player, client := world.characters[1], world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(client.equipment.readyAt) + player.position[1], player.movement = 60, playerMovement{} + client.loading = true + connection := client.conn.(*combatTestConn) + connection.packets = nil + + if err := world.handleCharacterReady(client); err != nil { + t.Fatal(err) + } + + packet := connection.packets[len(connection.packets)-1] + if binary.BigEndian.Uint32(packet[16:20]) != 0x54111123 || packet[28] != 0 || packet[29] != 0x94 || binary.BigEndian.Uint16(packet[32:34]) != 960 { + t.Fatalf("compact owner correction lost its flag, pass-on value or authoritative altitude: %x", packet) + } +} + +func TestPlayerFlightLateObserverReceivesAnIdlePositionAnchor(t *testing.T) { + world := newPlayerFormWorld(t, 117322) + client := world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(client.equipment.readyAt) + world.characters[2] = &character{id: 2, playfield: 705, health: 100} + connection := &combatTestConn{} + world.clients[2] = &worldClient{id: 2, conn: connection, ready: true, loading: true} + + if err := world.handleCharacterReady(world.clients[2]); err != nil { + t.Fatal(err) + } + + var anchors int + for _, packet := range connection.packets { + if binary.BigEndian.Uint32(packet[20:24]) == 0x54111123 && binary.BigEndian.Uint32(packet[28:32]) == 1 { + anchors++ + if binary.BigEndian.Uint32(packet[36:40]) != 20 || math.Float32frombits(binary.BigEndian.Uint32(packet[44:48])) != 16.91 { + t.Fatalf("idle flight replay carried the wrong pose: %x", packet) + } + } + } + if anchors != 1 { + t.Fatal("idle flight initialization lacks its post-OnWear pose", anchors) + } +} diff --git a/server/player_follow.go b/server/player_follow.go @@ -96,7 +96,7 @@ func (server *server) playerMovementReplay_locked(observer *worldClient, now tim var packets [][]byte for id, client := range server.clients { player := server.characters[id] - if id == observer.id || !client.ready || client.loading || !player.movement.active() || player.playfield != server.characters[observer.id].playfield || player.followTarget != 0 && player.movement.direction >= 0 { + if id == observer.id || !client.ready || client.loading || !player.movement.active() && !player.flying() || player.playfield != server.characters[observer.id].playfield || player.followTarget != 0 && player.movement.direction >= 0 { continue } snapshot := player.predictedMovement(now) diff --git a/server/player_form_test.go b/server/player_form_test.go @@ -56,8 +56,12 @@ func TestPlayerFormUsesAuthoredVehicleModelsAfterTheEquipDeadline(t *testing.T) if player.body.mesh != scenario.mesh || player.body.scale != .19999998807907104 || math.Abs(float64(player.body.sphere.radius-scenario.radius)) > .0000001 || math.Abs(float64(player.body.sphere.offset[1]-scenario.offsetY)) > .0000001 { t.Fatal("accepted wear did not apply the authored CAT and scale while idle", player.body) } - if player.height != 150 || player.position[1] != 16.41 { - t.Fatal("body replacement must retain the saved height without snapping position", player.height, player.position) + expectedY := float32(16.41) + if scenario.template == 117322 { + expectedY = 16.91 + } + if player.height != 150 || player.position[1] != expectedY { + t.Fatal("body replacement must retain the saved height and apply the authored flight lift", player.height, player.position) } }) } diff --git a/server/player_movement.go b/server/player_movement.go @@ -25,11 +25,16 @@ type playerMovement struct { fallHeight float32 falling bool deepWater bool + orientation uint32 } func (movement *playerMovement) prepare(player *character, now time.Time) { + flying := player.flying() if movement.components[0] == 0 { movement.components = [10]byte{2, 1, 0, 1, 0, 1, 0, 1, 0, 1} + if flying { + movement.orientation = 4 + } movement.direction = 1 movement.previousPosition = player.position _, movement.carriedMass = player.movementMass() @@ -41,7 +46,7 @@ func (movement *playerMovement) prepare(player *character, now time.Time) { if player.running { movement.components[0] = 3 } - if player.flying() { + if flying { movement.components[0] = 7 } else if movement.deepWater { movement.components[0] = 4 @@ -267,7 +272,7 @@ func (player *character) advanceMovement(now time.Time, target [3]float32) { player.alignSurface(previous, false) movement.previousPosition = previous // Mode0 body orientation follows horizontal velocity, reversed when backing up. - if !player.flying() && (movement.velocity[0] != 0 || movement.velocity[2] != 0) { + if !physical && movement.orientation == 0 && (movement.velocity[0] != 0 || movement.velocity[2] != 0) { sign := float64(1) if movement.direction < 0 { sign = -1 diff --git a/server/vehicle.go b/server/vehicle.go @@ -18,6 +18,9 @@ func (character *character) driving() bool { } func (character *character) flying() bool { + if character.movement.components[0] != 0 { + return character.movement.components[0] == 7 + } for _, item := range character.inventory.Items { if item.Slot == 1 && item.isYalmaha() { return true diff --git a/server/world_actions.go b/server/world_actions.go @@ -51,6 +51,13 @@ func (server *server) handleCharacterReady(client *worldClient) error { replay = playerCombatStatPackets(server.characters[client.id]) replay = append(replay, equippedItemPackets(server.characters[client.id])...) replay = append(replay, activeNanoPackets(server.characters[client.id], time.Now())...) + if player.flying() { + // OnWear lifts newly loaded actors. The native owner correction bit + // restores the authoritative position without another helper transition. + correction := npcMovementPacket(player, 0x94) + replay = append(replay, correction) + motion = append(motion, correction) + } team = server.teamPackets_locked(client.id) server.queueTeamResources_locked(resources, server.characters[client.id]) // Resume the native return request after a disconnect during death.