aorecomp

Anarchy Online classic in the browser

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


commit 751c16dcb474b8eca53480bc043750eec62f6ea1
parent afb025441e6afe254637dba5fdeb50edad8cc3bc
Author: anon <anon@example.com>
Date:   Mon, 26 Oct 2026 10:14:17 +0000

Integrate native outdoor body response into player movement

Use shipped model spheres, cell surfaces and water in the shared player
simulation, with native contact retries, slope feedback, gravity and basic
swimming transitions. Preserve cached body scaling and horizontal velocity
at walls; install raw Swimming before observer movement refreshes.

Verify 1,264 server tests, 327 focused normal/race results, data packages
and vet. Two GPU WASM clients confirm held-wall stops, body scales,
template heights, swimming limits and idle landing. Record remaining
movement lifecycle and collision coverage in the TODO.

Diffstat:
MTODO.md | 51++++++++++++++++++++++++++++-----------------------
Mdocs/player-geometry.md | 93++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mdocs/player-movement.md | 17+++++++++--------
Mserver/appearance.go | 9+++++++--
Mserver/appearance_test.go | 8++++----
Mserver/browser_creation.go | 1+
Mserver/browser_stream_test.go | 2+-
Mserver/control.go | 1+
Mserver/database.go | 1+
Mserver/dialogue_test.go | 2+-
Mserver/gamedata/player_appearances.go | 1+
Mserver/gamedata/player_appearances.yaml | 7+++++++
Mserver/ip_training.go | 3++-
Mserver/main.go | 1+
Mserver/npc_data_test.go | 2++
Aserver/player_collision.go | 302++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/player_collision_test.go | 294+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/player_movement.go | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Mserver/remote_combat_stats_test.go | 4++--
Mserver/resurrection_reconnect_test.go | 2+-
Mserver/roaming_test.go | 2+-
Mserver/scene_geometry.go | 22+++++++++++++++++++++-
Mserver/state.go | 10++++++++++
Mserver/target_protocol_test.go | 2+-
Mserver/world.go | 2+-
Mserver/world_actions.go | 4++++
Mserver/world_output_test.go | 2+-
Mserver/zoning_test.go | 14++++++++++++--
Mtools/data/extract_player_appearances.py | 1+
29 files changed, 874 insertions(+), 98 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -1222,7 +1222,7 @@ disconnect retention and succession policy still need period corroboration. query kernel retains native sidedness, edge selection, traversal and near-tie rules. Tests bind every decoded outdoor coordinate to an independent parser, exercise malformed records, concurrent initialization and the measured wall. - This foundation is not yet connected to live movement. + The shared outdoor player simulation now consumes these queries. - [x] Implement the outdoor collision query provider. Preserve directed segment intersections, KD traversal and tie rules, native cell/terrain grid traversal, clipping, bounds veto and terrain/static/liquid floor selection. Decode water @@ -1230,24 +1230,23 @@ disconnect retention and succession policy still need period corroboration. volume order and the first matching volume's clip veto. Check all 188 outdoor maps (46,140 water volumes and 788,782 zone entries), five complete independent water geometry/order digests, malformed inputs, boundary cases and concurrent - cache initialization. This provider still needs movement integration; the - held-wall regression below remains open. See [player geometry](docs/player-geometry.md). -- [ ] Integrate shipped outdoor cell collision surfaces with the shared simulation. - Source binds resource 1000013, cell ownership, KD-tree framing, invisible/primary - fallback and model-dependent body spheres. All selected surface records are v4; - parser validation now covers every outdoor cell, including portal tails. - Ordinary wall contact corrects position while retaining cached velocity; do not - replace it with Halt. The 40-second hardware wall fixture currently produces - 28.73 metres of server error before the next pose message. Preserve native segment/contact - ordering, retries, sphere scaling and floor selection. Apply the recovered - intermediate-slope and raised-probe rules. Wire the recovered ordinary-body - cache and MonsterData template selection, directed segment queries and combined - terrain/static/liquid floor selection before claiming full canonical collision. - Hardware now verifies ordinary cached bodies, character scale clamps, explicit - template spheres and adjusted-radius ground heights. Test - owner/observer/server poses, wall sliding, corners, narrow passages, multiple - forms/scales, long holds, large admitted frame steps, release/reversal and - interaction ranges while blocked. See [player geometry](docs/player-geometry.md). + cache initialization. See [player geometry](docs/player-geometry.md). +- [x] Connect shipped outdoor collision to the shared player simulation. Preserve + native five-pass segment/contact/raised-probe ordering, fixed previous pose, + cached normal-body and template spheres, incremental scaling, ground projection, + slope feedback and gravity. Initial placement and accepted pose changes also + align the body. A final-build 40-second hardware wall hold reduces owner/server + error from 28.73 metres to 1.3 cm; the observer is within 0.7 cm. Normal wall + contact retains cached horizontal velocity. Tests cover long holds, large + admitted frames, idle falls, scale clamps, all normal breed/sex/fatness choices, + template heights and in-memory movement without per-tick database writes. +- [ ] Complete the outdoor collision/lifecycle matrix. Test stairs, wall sliding, + corners, narrow passages, release/reversal, followers and blocked interaction + ranges across multiple forms/scales. Finish jump/landing/fall-damage callbacks, + internal/nonzero orientation modes, live Chest mass and encumbrance, and vehicle + and Grid form entry/exit body rebuilding (including current thin/fat mesh on + return). Add indoor room transforms, actor colliders and dynamic platforms. + See [player geometry](docs/player-geometry.md). - [x] Audit compact actor-spawn Run Speed. Send trained stat 156 as an unsigned byte through 255 or a flagged short above it, preserving following materials. Two GPU WASM clients verified training across 255, separate equipment/nano @@ -1267,9 +1266,14 @@ disconnect retention and succession policy still need period corroboration. checkpoint. Captured layouts, validation and evidence: [movement](docs/movement.md). - [ ] Model authoritative swimming transitions. Check: original water boundaries and movement modes agree between the server and native clients, including - movement speed, entering/leaving water and action eligibility. The native - social-command sender refuses gestures in swimming mode 4; current server - movement does not independently establish that mode. + movement speed, entering/leaving water and action eligibility. Outdoor body + projection now establishes mode4, restores preferred walk/run on exit, and uses + effective Swimming138 through the shared skill evaluator. Owner and late + observer receive the raw Swimming base before refreshing movement; both native + limits read 16.004999 for trained3000 plus ability trickle. Finish shoreline, + shallow/deep transitions, encumbrance, cached lateral controls, water smoothing + cadence and action restrictions. The native social sender refuses gestures in + mode4; cover that independently in server eligibility tests. - [x] Enable one verified whom-pah route. Check: its trigger reaches the intended destination and cannot immediately bounce the player back unintentionally. - [x] Enter the Grid through one access point. Check: eligibility is enforced @@ -1610,7 +1614,8 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah target loss, cyclic snapshots, rooted suspension, cast admission/refunds and late replay have regressions. Hardware compares owner/observer/server arrival positions and verifies target-loss stops clear native throttle without changing run mode. - Scene collision and the full lifecycle matrix remain the next item. + Outdoor collision now shares the player simulation; the full following + collision/lifecycle matrix remains the next item. - [ ] Complete canonical player following. Recover native scene collision, surface projection, slopes, falling/flight and platforms instead of relying on the current NPC height-map policy. Use the shared simulation tracked under diff --git a/docs/player-geometry.md b/docs/player-geometry.md @@ -4,8 +4,9 @@ The server's physical height sampler reads all 188 CHGA grids from the selected 14.9.1 resource database. It uses native checkerboard triangle planes and native header bounds, with archive dimensions retained separately for sample storage. This supplies terrain heights to movement, NPC roaming, zoning and controls. -Static building collision, full body projection, gravity and liquid transitions -are still open; the terrain sampler alone does not implement those systems. +Player simulation also uses the shipped outdoor cell surfaces and water for +body projection, wall contact, gravity and basic swimming transitions. Indoor +transforms, dynamic platforms and the full movement lifecycle remain open. ## Selected terrain data @@ -57,14 +58,17 @@ fixture's native 1 cm body-ground separation. The control tool initially places an actor 0.5 above sampled ground; normal movement messages separately quantize pose. Those offsets are not terrain-interpolation errors. -## Static wall fixture and the next collision work +## Static wall fixture An ordinary 40-second reverse walk in PF 705 starts at [961.625,16.41,510.75]. The native character stops against a building at approximately [971.7014,16.41,519.6436], retaining horizontal velocity and reverse throttle. -Before release, the server reaches [991.9849,20.175,539.9869], a 28.73-metre -horizontal error. The next native pose message corrects it. The current terrain -change does not fix this wall case. +The terrain-only server previously reached [991.9849,20.175,539.9869], a +28.73-metre horizontal error before the next native pose message. The integrated +outdoor body response stops at the shipped wall. A final-build 40-second hold +samples owner/server error 0.0126 metres before key release and observer/server +error 0.0061 metres during the hold. Both retain horizontal velocity; ordinary +wall contact does not Halt the movement controller. The wall is present in shipped resource 1000013/46203264. Outdoor playfield 705 has 300x300 tiles, spacing 4, zone size 10 and 900 zones. Its native CellSurface @@ -130,8 +134,8 @@ is not a reliable contact depth: the ordinary KD wrapper leaves it untouched. At the captured PF705 native stop, a sphere with the measured model offset and radius is clear of the building. A small step to [971.72,16.41,519.66] contacts the authored wall, with face normal [-1,0,0] and distance approximately 0.24145. -This verifies the geometry query against the retained runtime fixture; it does -not demonstrate that server movement stops there yet. +The query fixture verifies the authored contact independently of the integrated +movement regression above. ## Model torso metadata @@ -166,8 +170,9 @@ separately clamps effective scale to at least1; form refresh has its own minimum These are different transition rules, so one universal effective-scale clamp would be incorrect. Incremental native scale updates multiply the existing primitive by new/old scale instead of re-decoding metadata. Replacing the CAT -through SetCatMesh rebuilds it. Grid form99902 and special appearance flags still -need separate investigation. +through SetCatMesh rebuilds it. Grid form99902 resolves CAT99894, with radius +0.1000479981 and offsetY0.2507500052. Full Grid entry/exit and special appearance +flag lifecycles remain separate verification work. Six GPU WASM captures corroborate these contracts through normal control edits and read-only probes. Height1 becomes native base20, visual scale @@ -186,8 +191,9 @@ Collision uses center=actorPosition+offset. Ordinary sphere contact corrects position without Halting cached horizontal velocity. Ground projection yields actorY=hitY+0.01-offsetY+radius. Long-displacement segment checks, contact retries, steep slopes, falling and deep water have additional branches. Gravity is -20 -with independent vertical-speed clamp +/-50; these recovered constants have not -yet been substituted for a complete collision implementation. +with independent vertical-speed clamp +/-50. The outdoor simulation now applies +these rules; jump, landing actions and fall damage still need their full +callbacks and combined lifecycle coverage. ## Outdoor collision query provider @@ -229,11 +235,43 @@ Invalid cell queries leave the caller's floor point and normal unchanged. Misses return explicit height sentinels and zero metadata instead of exposing the native scratch metadata left over from earlier calls. -This provider is not yet attached to movement. The five-pass body response, -native falling and slope integration, body cache lifecycle and swimming -transitions remain open. Indoor room transforms and dynamic platforms also -remain separate work. The existing HTTPS preview therefore retains its current -movement behavior, including the measured held-wall failure. +## Outdoor movement integration + +The shared player simulation consumes this provider for manual input, following +and read-only position predictions used by gameplay ranges. Each outer frame +retains one historical position across native force substeps and the five-pass +body response. Segment sweeps prevent large admitted displacements from tunnelling +through walls. Sphere contact, raised probes, slope feedback and floor selection +preserve their native order. Cached horizontal velocity survives ordinary contact. +Gravity is independent of longitudinal velocity; ready placement can start an +idle fall without a key press. Simulation and rotation remain in memory between +normal database checkpoints. + +Ordinary body construction selects the normal breed/sex mesh from the appearance +catalog, independently of later render fatness. Explicit MonsterData uses the +template's mesh. Immutable raw model metadata is shared; each player retains its +scaled primitive and updates it incrementally. Hardware owner and observer checks +cover scale20, scale200, Anvian and Hovertech, with ground-height differences below +0.000003 metres. Explicit player forms retain the breed/sex mass table rather +than copying template stat2; both template fixtures retain Nanomage male mass +0.07500000298. An idle fall from Y80 reaches the same Y16.41 floor in both +native client and server; captures include twelve falling frames and final rest. + +Deep water selects mode4 and effective Swimming138 through the common skill +evaluator, including ability trickle and equipment/nano modifiers. Unlike running, +this speed formula has neither the 15 cap nor the low-health multiplier. Water +entry clears cached vertical input and applicable strafe input; exit restores the +preferred walk/run mode. Raw Swimming reaches observers before the final movement +refresh. With trained3000 and abilities6, both owner and late observer read +16.004999. A two-second high-speed swim sample differs by 0.6754 metres between +owner and server; input delivery and frame cadence remain comparison bounds. +This verifies the formula and replicated limits, not exact swimming trajectories. + +Remaining work includes shoreline/shallow-water and smoothing cadence, stairs, +corners, narrow passages, blocked interactions, jump/landing/fall damage, +internal and nonzero orientation modes, live carried mass/encumbrance and full +vehicle/Grid/body-replacement lifecycles. Indoor room transforms, dynamic +platforms and actor colliders also remain separate work. ## Evidence @@ -263,6 +301,13 @@ failure, selected-archive comparisons and source ledgers: 188 selected resources and five complete geometry/order samples. - `integrator-contact/`: 23 complete bodies; outer-frame alignment, fixed previous pose, slope-normal feedback, steep guards and falling callbacks. +- `water-transition/`: 40 complete bodies; helper transitions, retained controls, + Swimming speed and landing callbacks. +- `grid-body/`: 25 complete bodies; Grid form/model selection and extent clamps. +- `body-lifecycle/`: 42 complete bodies; construction, compact observer clamps + and direct placement through surface alignment. +- `template-mass/`: 16 complete bodies; player form selection versus NPC template + stat application, raw breed/sex mass and the zero-mass fallback. These counts overlap; they are not unique additional procedures. Source checks establish maintained-code contracts and evidence integrity. Runtime probes @@ -279,9 +324,8 @@ The collision-query foundation passes all 1,229 top-level server tests (14,060 results), 62 focused race results, the data packages and `go vet`. `local/player-collision-query/` retains test logs and the manifest binding every Go source and relevant bundled archive to that exact test binary. The independent -coordinate comparison covers every outdoor cell. The sole HTTPS8443 preview -remains on the verified terrain build; this milestone adds no live movement -behavior, database mutations or additional test clients/servers. +coordinate comparison covers every outdoor cell. That foundation milestone +added no live movement behavior or additional test clients/servers. The subsequent six body captures are under `local/player-collision-integration/runtime/body/`. Their verifier records the @@ -294,3 +338,12 @@ results), 163 focused results both normally and under the race detector, the dat packages and `go vet`. `local/player-collision-provider/` retains the exact-source suite manifest, independent water digests, source checks and preview verification. It starts no additional preview, creates no players and changes no live movement. + +The movement integration passes all 1,264 top-level server tests (14,179 results), +327 focused results normally and under the race detector, the data packages and +`go vet`. `local/player-collision-movement/` retains the exact-source manifest, +native owner/observer captures, final binary hashes and verification summary. +Both headed Chromium clients use the GPU and report no WASM page errors. +Owned visitors122/123 are removed after closing the browsers; unrelated SQLite +rows hash unchanged, with foreign-key and integrity checks passing. The single +shared HTTPS8443 preview runs the verified integrated build. diff --git a/docs/player-movement.md b/docs/player-movement.md @@ -4,11 +4,11 @@ The server advances player motion in memory at 60Hz with one force/velocity integrator and distinct longitudinal, arrival, lateral and angular controllers. Ordinary input and [player following](player-follow.md) share this state. Strafing and turning continue without pose packets; held input has no age cap. -The implementation covers ordinary open-ground motion. Native scene collision, -surface projection, falling, swimming and full flight remain separate TODOs. -The shared height sampler now uses selected 14.9.1 grids and native triangle -planes; [player geometry](player-geometry.md) distinguishes that implemented -terrain query from the remaining body/cell collision work. +The implementation includes outdoor scene collision, body projection, gravity +and basic swimming transitions. 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, jump and full flight work. ## Ordinary ground motion @@ -48,9 +48,10 @@ quaternions: the body faces opposite travel. Packets use body heading. 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. Native frame cadence, collision, gravity, -surface projection, flight and nonzero orientation modes remain separate -verification boundaries; these flat-ground reductions do not replace them. +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 +flat-ground reductions above do not replace those branches. ## Cached controls and transitions diff --git a/server/appearance.go b/server/appearance.go @@ -11,10 +11,10 @@ func (character *character) baseScale() uint16 { if character.height == 0 { return 100 } - return character.height + return max(uint16(20), character.height) } -func (character *character) appearanceAssets() (uint32, [5]uint32) { +func (character *character) resolvedAppearance() appearanceFields { // Unspecified player templates use the original Solitus male defaults. appearance := unpackAppearance(character.appearance) if appearance.Breed < 1 || appearance.Breed > 4 { @@ -28,6 +28,11 @@ func (character *character) appearanceAssets() (uint32, [5]uint32) { if appearance.Race == 0 || appearance.Breed != 1 { appearance.Race = 1 } + return appearance +} + +func (character *character) appearanceAssets() (uint32, [5]uint32) { + appearance := character.resolvedAppearance() // Explicit head identity supports all native choices, independently of face bits. head := character.headMesh diff --git a/server/appearance_test.go b/server/appearance_test.go @@ -70,9 +70,9 @@ func TestPlayerAppearanceUsesEachNativeBreedAndSexTemplate(t *testing.T) { } func TestPlayerHeightReachesSpawnStatsAndPhysicalExtent(t *testing.T) { - for _, height := range []uint16{90, 100, 110} { - t.Run(fmt.Sprint(height), func(t *testing.T) { - player := &character{id: 1, name: "Visitor", height: height, level: 1} + for _, scenario := range []struct{ height, native uint16 }{{0, 100}, {1, 20}, {19, 20}, {20, 20}, {90, 90}, {100, 100}, {110, 110}} { + t.Run(fmt.Sprint(scenario.height), func(t *testing.T) { + player := &character{id: 1, name: "Visitor", height: scenario.height, level: 1} spawn, full := characterPacket(player), fullCharacterPacket(player) stats := make(map[uint32]uint32) @@ -82,7 +82,7 @@ func TestPlayerHeightReachesSpawnStatsAndPhysicalExtent(t *testing.T) { } extent := player.physicalExtent() - if binary.BigEndian.Uint16(spawn[111:113]) != height || stats[360] != uint32(height) || extent != float32(height*2)*0.01 { + if binary.BigEndian.Uint16(spawn[111:113]) != scenario.native || stats[360] != uint32(scenario.native) || extent != float32(scenario.native*2)*0.01 { t.Fatalf("height disagrees between observer, local stats and extent: %d %d %f", binary.BigEndian.Uint16(spawn[111:113]), stats[360], extent) } }) diff --git a/server/browser_creation.go b/server/browser_creation.go @@ -149,6 +149,7 @@ func (server *server) insertBrowserPlayer_locked(tx *sql.Tx, player *character, } func (server *server) publishBrowserPlayer_locked(player *character) { + player.geometry = server.geometry server.characters[player.id] = player server.nextCharacter, server.nextItem = player.id, player.inventory.LastID record := player.record() diff --git a/server/browser_stream_test.go b/server/browser_stream_test.go @@ -455,7 +455,7 @@ func TestExpiredBrowserWorldSessionRemovesLivingTargetAndRetargetsNPC(t *testing if err != nil || binary.BigEndian.Uint32(ready[20:24]) != 0x570c2039 { t.Fatalf("observer did not receive browser player readiness: %x %v", ready, err) } - for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 118, 119, 120, 149, 51, 78, 156} { + for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 138, 118, 119, 120, 149, 51, 78, 156} { packet, err := readPacket(observer) if err != nil || binary.BigEndian.Uint32(packet[20:24]) != 0x2b333d6e || binary.BigEndian.Uint32(packet[28:32]) != 2 || binary.BigEndian.Uint32(packet[36:40]) != stat { t.Fatalf("observer did not receive player combat foundations: %x %v", packet, err) diff --git a/server/control.go b/server/control.go @@ -309,6 +309,7 @@ func (server *server) updateUser_locked(destination userData) error { } func (server *server) prepareUser_locked(character, updated *character) { + updated.geometry = server.geometry updated.skillLocks = character.skillLocks updated.activeNanos = character.activeNanos updated.team = character.team diff --git a/server/database.go b/server/database.go @@ -220,6 +220,7 @@ func (server *server) loadPlayers() error { return err } player := record.character() + player.geometry = server.geometry if err := player.userData().validate(); err != nil { return fmt.Errorf("player %d: %w", player.id, err) } diff --git a/server/dialogue_test.go b/server/dialogue_test.go @@ -174,7 +174,7 @@ func TestNPCConversationBelongsToItsWorldConnection(t *testing.T) { readPacket(first) // The second player's spawn is broadcast to the first. second.Write(targetPacket(n3Packet(0x570c2039, 50000, 2, nil))) readPacket(first) - for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 118, 119, 120, 149, 51, 78, 156} { + for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 138, 118, 119, 120, 149, 51, 78, 156} { packet, err := readPacket(first) if err != nil || binary.BigEndian.Uint32(packet[16:20]) != 0x2b333d6e || binary.BigEndian.Uint32(packet[24:28]) != 2 || binary.BigEndian.Uint32(packet[29:33]) != stat { t.Fatalf("observer did not receive player combat foundations: %x %v", packet, err) diff --git a/server/gamedata/player_appearances.go b/server/gamedata/player_appearances.go @@ -10,5 +10,6 @@ type PlayerHead struct { type PlayerBody struct { Breed uint16 `yaml:"breed"` Sex uint16 `yaml:"sex"` + Mesh uint32 `yaml:"mesh"` Textures map[uint16][5]uint32 `yaml:"textures"` } diff --git a/server/gamedata/player_appearances.yaml b/server/gamedata/player_appearances.yaml @@ -258,33 +258,40 @@ heads: bodies: - breed: 1 sex: 2 + mesh: 5907 textures: 1: [8714, 8710, 8773, 8713, 8709] 2: [8714, 8710, 8770, 8713, 8709] 3: [8714, 8710, 8771, 8713, 8709] - breed: 1 sex: 3 + mesh: 5927 textures: 1: [8849, 8850, 8865, 8853, 8848] 2: [8849, 8850, 8863, 8853, 8848] 3: [8849, 8850, 8864, 8853, 8848] - breed: 2 sex: 2 + mesh: 5914 textures: 1: [8964, 8960, 8963, 8965, 8961] - breed: 2 sex: 3 + mesh: 5934 textures: 1: [8885, 8886, 8887, 8884, 8883] - breed: 3 sex: 2 + mesh: 5921 textures: 1: [8986, 8983, 8984, 8985, 8982] - breed: 3 sex: 3 + mesh: 5941 textures: 1: [9028, 9024, 9023, 9027, 9026] - breed: 4 sex: 1 + mesh: 5900 textures: 1: [9233, 9231, 9240, 9234, 9236] diff --git a/server/ip_training.go b/server/ip_training.go @@ -116,7 +116,8 @@ func (server *server) handleSkillTraining(client *worldClient, body []byte) erro baseNano := player.maximumNano() - uint32(player.inventory.equipmentBonus(221)) attackRating := player.attackRating() movementChanged := player.maximumHealth() != updated.maximumHealth() || - player.baseStats().Speed.RunSpeed != updated.stats.Speed.RunSpeed + player.baseStats().Speed.RunSpeed != updated.stats.Speed.RunSpeed || + player.swimmingMovementSpeed() != updated.swimmingMovementSpeed() *player = updated if movementChanged { player.position, player.rotation, player.movement = motion.position, motion.rotation, motion.movement diff --git a/server/main.go b/server/main.go @@ -356,6 +356,7 @@ func (server *server) serveWorldClient(client *worldClient) error { } character.followTarget = 0 character.movement = playerMovement{} + character.body = playerCollisionBody{} server.clients[character.id] = client for index := range character.activeNanos { if character.activeNanos[index].expiresAt.IsZero() { diff --git a/server/npc_data_test.go b/server/npc_data_test.go @@ -31,6 +31,8 @@ func useNPCData(t *testing.T, data gamedata.NPCData) { resources = fstest.MapFS{ "terrain.bin": {Data: append([]byte("AOTERR02"), 0, 0, 0, 0)}, "zone_links.yaml": {Data: []byte("original: {}\ntarget: {}\n")}, + "anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.idx": {Data: make([]byte, 76)}, + "anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.dat": {}, } t.Chdir(t.TempDir()) t.Cleanup(func() { gamedata.NPCs, resources = previousNPCs, previousResources }) diff --git a/server/player_collision.go b/server/player_collision.go @@ -0,0 +1,302 @@ +package main + +import ( + "ao/server/gamedata" + "math" +) + +type playerCollisionBody struct { + mesh uint32 + scale float32 + sphere collisionSphere +} + +func (player *character) collisionBody() collisionSphere { + // Ordinary setup constructs the normal breed/sex CIR before render fatness changes. + appearance := player.resolvedAppearance() + var mesh uint32 + for _, body := range gamedata.PlayerAppearances.Bodies { + if body.Breed == appearance.Breed && body.Sex == appearance.Sex { + mesh = body.Mesh + break + } + } + if template := gamedata.MonsterTemplates[player.monsterData]; template != nil { + mesh = template.Stats[12] + } + base := int32(player.baseScale()) + if player.driving() { + base = 20 + } + effective := base + player.inventory.equipmentBonus(360) + player.nanoBonus(360) + if player.body.mesh != 0 && player.body.mesh != mesh { + effective = max(int32(20), effective) + } else { + effective = max(int32(1), effective) + } + scale := float32(effective) * float32(.01) + if player.body.mesh != mesh { + player.body = playerCollisionBody{mesh: mesh, scale: scale, sphere: player.geometry.model(mesh)} + player.body.sphere.radius *= scale + player.body.sphere.offset[1] *= scale + } else if player.body.scale != scale { + // Scale-only updates multiply the existing primitive instead of decoding it again. + ratio := scale / player.body.scale + player.body.sphere.radius *= ratio + player.body.sphere.offset[1] *= ratio + player.body.scale = scale + } + return player.body.sphere +} + +func collisionDirection(vector [3]float32) [3]float32 { + // QQR's small-vector normalization uses a second pass between its two thresholds. + length := math.Sqrt(surfaceDot(vector, vector)) + if length <= float64(float32(.00000001)) { + return [3]float32{} + } + for axis := range vector { + vector[axis] = float32(float64(vector[axis]) / length) + } + if length <= float64(float32(.0001)) { + length = math.Sqrt(surfaceDot(vector, vector)) + for axis := range vector { + vector[axis] = float32(float64(vector[axis]) / length) + } + } + return vector +} + +func collisionDirectionOrUp(vector [3]float32) [3]float32 { + vector = collisionDirection(vector) + if vector == [3]float32{} { + return [3]float32{0, 1, 0} + } + return vector +} + +func (movement *playerMovement) land(height float32) { + movement.velocity[1], movement.verticalVelocity = 0, 0 + movement.speed = vectorLength(movement.velocity) + movement.fallHeight = height + movement.falling = false +} + +func (movement *playerMovement) startFalling() { + if !movement.falling { + movement.falling = true + movement.fallHeight = movement.previousPosition[1] + } +} + +func collisionResponds(normalY float32) bool { + return normalY < .5 && normalY > -.5 || normalY < float32(-.9) || normalY > float32(.99) +} + +func collisionUphill(normal [3]float32) [3]float32 { + // Keep the native two-stage expression, including its behavior for nonunit normals. + tangent := [3]float32{-normal[0], 1 - normal[1], -normal[2]} + dot := surfaceDot(tangent, normal) + for axis := range tangent { + tangent[axis] -= float32(float64(normal[axis]) * dot) + } + return tangent +} + +func (player *character) guardSteepMovement(previous [3]float32) { + // Source: client/game/qqr.dll/lifted-0006.c, sub_42011D30. + direction := collisionDirection([3]float32{player.movement.velocity[0], 0, player.movement.velocity[2]}) + if direction == [3]float32{} { + forward, _ := bodyAxes(player.rotation) + direction = collisionDirection([3]float32{forward[0], 0, forward[2]}) + if direction == [3]float32{} { + direction = [3]float32{0, 0, 1} + } + } + start, end := player.position, player.position + start[1]++ + end[1]++ + for axis := range start { + start[axis] -= direction[axis] * .5 + end[axis] += direction[axis] + } + contact := player.geometry.line(player.playfield, player.geometry.terrain[player.playfield], start, end, false) + if contact.hit && contact.normal[1] < .5 { + player.alignSurface(previous, false) + player.movement.velocity = [3]float32{} + player.movement.speed = 0 + } +} + +func (player *character) alignSurface(previous [3]float32, skipSegment bool) { + // Source: client/game/qqr.dll/lifted-0006.c, sub_42012A50. + movement := &player.movement + movement.normal = [3]float32{0, 1, 0} + if player.geometry == nil || player.geometry.terrain[player.playfield] == nil { + if movement.falling { + movement.land(player.position[1]) + } + return + } + layout, exists := player.geometry.playfields[player.playfield] + if !exists { + if movement.falling { + movement.land(player.position[1]) + } + return + } + ground := player.geometry.terrain[player.playfield] + body := player.collisionBody() + radius := float32(math.Abs(float64(body.radius))) + if radius > .5 { + for axis := range body.offset { + body.offset[axis] /= 2 * radius + } + radius = .5 + } + position, point := player.position, player.position + corrected := false + for remaining := 5; remaining > 0; remaining-- { + // Veto and all retries keep the same outer-frame historical position. + previousY := position[1] + retry := layout.veto(&position, &previous) + if movement.falling && (position[1] != previousY || retry) { + point = [3]float32{} + probe := position + probe[1] += float32(1.2) * radius + player.geometry.floor(player.playfield, ground, probe, &point, &movement.normal) + movement.verticalVelocity = 0 + position[1] = point[1] + float32(.01) + } + center, oldCenter := position, previous + for axis := range center { + center[axis] += body.offset[axis] + oldCenter[axis] += body.offset[axis] + } + if !skipSegment && surfaceDistanceSquared(previous, position) >= float64(radius*float32(.9))*float64(radius*float32(.9)) { + contact := player.geometry.line(player.playfield, ground, oldCenter, center, true) + if contact.hit { + point, movement.normal = contact.point, contact.normal + direction := collisionDirectionOrUp([3]float32{previous[0] - position[0], previous[1] - position[1], previous[2] - position[2]}) + if movement.normal[1] > .5 { + direction = [3]float32{0, 1, 0} + } + for axis := range center { + center[axis] = point[axis] + (radius+float32(.01))*direction[axis] + position[axis] = center[axis] - body.offset[axis] + } + retry, corrected, skipSegment = true, true, true + if movement.falling && movement.normal[1] > .5 { + movement.land(position[1]) + } + } + } + + // Raised probes reuse the first contact outputs even when the raised query misses. + contact := player.geometry.sphere(player.playfield, center, radius) + if contact.hit { + point, movement.normal = contact.point, contact.normal + } + if movement.normal == [3]float32{} { + movement.normal = collisionDirectionOrUp([3]float32{previous[0] - position[0], previous[1] - position[1], previous[2] - position[2]}) + } + if contact.hit { + raised := false + if !collisionResponds(movement.normal[1]) && movement.normal[1] > .5 && float64(movement.normal[1]) < .8 { + probe := center + probe[1] += .5 + if contact = player.geometry.sphere(player.playfield, probe, radius); contact.hit { + point, movement.normal = contact.point, contact.normal + } + raised = true + } + if collisionResponds(movement.normal[1]) { + if raised { + point[1] -= .5 + } + direction := [3]float32{center[0] - point[0], center[1] - point[1], center[2] - point[2]} + if raised { + direction[1] = 0 + } + if direction != [3]float32{} && surfaceDot(direction, movement.normal) >= 0 { + direction = collisionDirectionOrUp(direction) + } else { + direction = movement.normal + } + for axis := range center { + center[axis] = point[axis] + (radius+float32(.01))*direction[axis] + position[axis] = center[axis] - body.offset[axis] + } + retry, corrected = true, true + } + } + + // Project the body bottom, retaining raw liquid height separately from the floor. + bottom := position + for axis := range bottom { + bottom[axis] += body.offset[axis] + } + bottom[1] -= radius + probe := bottom + probe[1] += float32(1.2) * radius + water := player.geometry.floor(player.playfield, ground, probe, &point, &movement.normal) + clearance := float32(-9999) + if water.height > 0 { + clearance = water.height - point[1] + } + fallingEnabled := !player.flying() + deepWater := fallingEnabled && bottom[1] < water.height && clearance > float32(1.19) + if movement.deepWater != deepWater { + movement.deepWater = deepWater + if deepWater { + if movement.components[3] != 1 { + movement.strafe = 0 + } + movement.vertical = 0 + } + movement.prepare(player, movement.updatedAt) + } + if movement.deepWater { + if movement.falling { + movement.land(point[1]) + } + point[1] += clearance + float32(-.05) + if point[1]-bottom[1] <= 5 && point[1] > bottom[1] { + point[1] = float32(.1)*point[1] + float32(.9)*bottom[1] + } + } + if point[1] > bottom[1] { + bottom[1] = point[1] + float32(.01) + corrected = true + if movement.falling { + movement.land(point[1] + float32(.01)) + } + } else if bottom[1]-radius*float32(.125) > point[1] { + if fallingEnabled { + movement.startFalling() + } + } else if bottom[1]-point[1] <= float32(.011) { + if movement.falling { + movement.land(point[1] + float32(.01)) + } + } else if movement.velocity[1]+movement.verticalVelocity <= 0 && fallingEnabled { + bottom = point + bottom[1] += float32(.01) + corrected = true + if movement.falling { + movement.land(point[1]) + } + } + for axis := range position { + position[axis] = bottom[axis] - body.offset[axis] + } + position[1] += radius + if !retry { + break + } + } + if corrected { + layout.veto(&position, nil) + } + player.position = position +} diff --git a/server/player_collision_test.go b/server/player_collision_test.go @@ -0,0 +1,294 @@ +package main + +import ( + "ao/server/assets" + "encoding/binary" + "math" + "testing" + "time" +) + +func newPlayerCollisionWorld(t *testing.T) *server { + t.Helper() + world, _ := newEquipmentWorld(t) + var err error + world.geometry, err = readSceneGeometry(assets.Files) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { world.geometry.database.file.Close() }) + world.terrain, err = readTerrain() + if err != nil { + t.Fatal(err) + } + world.geometry.terrain = world.terrain + player := world.characters[1] + player.geometry = world.geometry + player.inventory = playerInventory{} + player.playfield, player.position = 705, [3]float32{961.625, 16.41, 510.75} + player.rotation = [4]float32{0, -.9238795, 0, .3826834} + player.appearance = 0x315 + player.running = false + return world +} + +func TestPlayerCollisionStopsHeldReverseAtTheShippedWall(t *testing.T) { + world := newPlayerCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + if err := world.handleMovement(client, playerMovementRequest(player, 3)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + + for frame := 1; frame <= 2400; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * time.Second / 60)) + } + position := player.position + prediction := player.predictedMovement(started.Add(41 * time.Second)) + db, err := world.database() + if err != nil { + t.Fatal(err) + } + var storedX, storedY, storedZ float32 + if err := db.QueryRow("SELECT position_x, position_y, position_z FROM characters WHERE id=1").Scan(&storedX, &storedY, &storedZ); err != nil { + t.Fatal(err) + } + + if math.Abs(float64(position[0])-971.701416) > .15 || math.Abs(float64(position[2])-519.643555) > .15 || math.Abs(float64(position[1])-16.41) > .0001 { + t.Fatal("held reverse escaped the measured native wall", position, player.movement) + } + if player.movement.velocity[0] < 1 || player.movement.velocity[2] < 1 || player.movement.forward != -1 || player.movement.falling { + t.Fatal("ordinary wall contact must retain intended horizontal velocity", player.movement) + } + if surfaceDistanceSquared(position, prediction.position) > .0025 || player.position != position { + t.Fatal("read-only range prediction must share collision without moving the live actor", position, prediction.position, player.position) + } + if storedX != 961.625 || storedY != 16.41 || storedZ != 510.75 { + t.Fatal("simulation ticks must not persist insignificant position changes", storedX, storedY, storedZ) + } + t.Log("held wall pose", position, "velocity", player.movement.velocity) +} + +func TestPlayerCollisionPreventsTunnellingDuringALargeAdmittedFrame(t *testing.T) { + world := newPlayerCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + player.running, player.stats.Speed.RunSpeed = true, 2000 + if err := world.handleMovement(client, playerMovementRequest(player, 3)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + + world.advancePlayerMovement(started.Add(4 * time.Second)) + + if player.position[0] < 970 || player.position[0] >= 972 || player.position[2] < 518 || player.position[2] >= 520 || player.position[1] > 16.5 { + t.Fatal("native long-displacement segment failed to prevent wall tunnelling", player.position) + } + if player.movement.velocity[0] <= 1 || player.movement.velocity[2] <= 1 { + t.Fatal("segment collision must not Halt normal wall movement", player.movement.velocity) + } +} + +func TestPlayerCollisionUsesCachedNormalBodiesAndTemplateSpheres(t *testing.T) { + world := newPlayerCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + for _, scenario := range []struct { + name string + appearance, height uint16 + template, mesh uint32 + radius, offsetY float32 + actorY float32 + }{ + {"normal Solitus", 0x195, 100, 0, 5927, .25075000524520874, .25075000524520874, 16.41}, + {"thin Nanomage retains initial normal body", 0x130, 100, 0, 5921, .25075000524520874, .25075000524520874, 16.41}, + {"base scale setter clamps one to twenty", 0x130, 1, 0, 5921, .05014999955892563, .05014999955892563, 16.41}, + {"double scale", 0x130, 200, 0, 5921, .5015000104904175, .5015000104904175, 16.41}, + {"Anvian template", 0x130, 100, 17651, 15218, .7702500224113464, .7164639830589294, 16.444913864135742}, + {"hovertech radius fallback and negative offset", 0x130, 100, 20614, 20615, .5, -.05000600218772888, 16.960006713867188}, + {"Grid template", 0x130, 100, 99902, 99894, .1000479981303215, .25075000524520874, 16.25929832458496}, + } { + t.Run(scenario.name, func(t *testing.T) { + player.body, player.movement = playerCollisionBody{}, playerMovement{} + player.appearance, player.height, player.monsterData = scenario.appearance, scenario.height, scenario.template + player.position = [3]float32{961.625, 16.1, 510.75} + if err := world.handleMovement(client, playerMovementRequest(player, 9)); err != nil { + t.Fatal(err) + } + + world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond)) + + if player.body.mesh != scenario.mesh || player.body.sphere.radius != scenario.radius || player.body.sphere.offset[1] != scenario.offsetY { + t.Fatal("construction model or raw scaled sphere disagrees with native metadata", player.body) + } + if math.Abs(float64(player.position[1]-scenario.actorY)) > .000003 { + t.Fatal("body-bottom ground projection disagrees with native fixture", player.position, scenario.actorY) + } + }) + } +} + +func TestPlayerCollisionFallsAfterProjectionAndLandsWithoutHorizontalHalt(t *testing.T) { + world := newPlayerCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + player.position[1] = 20 + if err := world.handleMovement(client, playerMovementRequest(player, 3)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + + world.advancePlayerMovement(started.Add(100 * time.Millisecond)) + firstHeight, firstGravity := player.position[1], player.movement.verticalVelocity + world.advancePlayerMovement(started.Add(200 * time.Millisecond)) + secondHeight, secondGravity := player.position[1], player.movement.verticalVelocity + for frame := 3; frame <= 30; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } + + if math.Abs(float64(firstHeight)-19.8) > .00001 || firstGravity != -2 || math.Abs(float64(secondHeight)-19.4) > .00001 || secondGravity != -4 { + t.Fatal("falling must start during projection and apply independent gravity on the next integration", firstHeight, firstGravity, secondHeight, secondGravity) + } + if player.movement.falling || player.movement.verticalVelocity != 0 || math.Abs(float64(player.position[1])-16.41) > .0001 || player.movement.velocity[0] < 1 || player.movement.velocity[2] < 1 { + t.Fatal("landing must clear vertical motion while retaining horizontal movement", player.position, player.movement) + } +} + +func TestPlayerCollisionKeepsTimestepProgressForFractionalFrames(t *testing.T) { + world := newPlayerCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + if err := world.handleMovement(client, playerMovementRequest(player, 3)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + + world.advancePlayerMovement(started.Add(900 * time.Millisecond)) + + if player.position[0] <= 961.625 || player.position[2] <= 510.75 || player.movement.previousPosition != [3]float32{961.625, 16.41, 510.75} { + t.Fatal("fractional substep remainder failed to complete the outer frame", player.position, player.movement) + } +} + +func TestPlayerCollisionScalesTheExistingPrimitiveIncrementally(t *testing.T) { + world := newPlayerCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + if err := world.handleMovement(client, playerMovementRequest(player, 9)); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + for index, scenario := range []struct { + height uint16 + scale, radius float32 + }{ + {100, 1, .25075000524520874}, + {103, 1.0299999713897705, .2582724988460541}, + {97, .9699999690055847, .2432274967432022}, + {110, 1.100000023841858, .27582502365112305}, + {200, 2, .5015000104904175}, + {1, .19999998807907104, .05014999955892563}, + } { + player.height = scenario.height + + world.advancePlayerMovement(started.Add(time.Duration(index+1) * 100 * time.Millisecond)) + + if player.body.scale != scenario.scale || player.body.sphere.radius != scenario.radius || player.body.sphere.offset[1] != scenario.radius || len(world.geometry.models) != 1 { + t.Fatal("scale-only updates must share one decoded model and preserve incremental rounding", scenario.height, player.body) + } + } +} + +func TestPlayerCollisionSelectsAllNormalBreedSexModelsIndependentlyOfFatness(t *testing.T) { + world := newPlayerCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + for _, scenario := range []struct { + breed, sex uint16 + mesh uint32 + }{{1, 2, 5907}, {1, 3, 5927}, {2, 2, 5914}, {2, 3, 5934}, {3, 2, 5921}, {3, 3, 5941}, {4, 1, 5900}} { + for _, fatness := range []uint16{0, 1, 2} { + player.appearance = (appearanceFields{Breed: scenario.breed, Sex: scenario.sex, Fatness: fatness}).packed() + player.body, player.movement = playerCollisionBody{}, playerMovement{} + if err := world.handleMovement(client, playerMovementRequest(player, 9)); err != nil { + t.Fatal(err) + } + + world.advancePlayerMovement(player.movement.updatedAt.Add(100 * time.Millisecond)) + + if player.body.mesh != scenario.mesh || player.body.sphere.radius != .25075000524520874 || player.body.sphere.offset[1] != .25075000524520874 { + t.Fatal("ordinary collision must use its construction-time normal body", scenario.breed, scenario.sex, fatness, player.body) + } + } + } +} + +func TestPlayerCollisionInitialReadyStartsAnIdleFall(t *testing.T) { + world := newPlayerCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + player.position[1] = 20 + client.loading = true + + if err := world.handleCharacterReady(client); err != nil { + t.Fatal(err) + } + started := player.movement.updatedAt + falling := player.movement.falling + world.advancePlayerMovement(started.Add(100 * time.Millisecond)) + + if client.loading || !falling || player.movement.verticalVelocity != -2 || math.Abs(float64(player.position[1])-19.8) > .00001 || player.movement.forward != 0 || player.movement.turn != 0 { + t.Fatal("initial placement must start gravity without requiring a movement key", player.position, player.movement) + } +} + +func TestPlayerCollisionEntersSwimmingAndRestoresThePreferredMode(t *testing.T) { + world := newPlayerCollisionWorld(t) + player, client := world.characters[1], world.clients[1] + player.position, player.rotation = [3]float32{100, 8, 25}, [4]float32{0, 0, 0, 1} + player.stats.Body.Swimming, player.stats.Speed.RunSpeed = 3000, 0 + player.health, player.running = 1, true + if err := world.handleMovement(client, playerMovementRequest(player, 3)); err != nil { + t.Fatal(err) + } + if err := world.handleMovement(client, playerMovementRequest(player, 5)); err != nil { + t.Fatal(err) + } + player.position[1] = 6.5 + started := player.movement.updatedAt + + for frame := 1; frame <= 10; frame++ { + world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) + } + swimming := player.movement.deepWater + swimMode, swimSpeed := player.movement.components[0], player.movement.speed + player.position[1] = 8 + world.advancePlayerMovement(started.Add(1100 * time.Millisecond)) + + if !swimming || swimMode != 4 || math.Abs(float64(swimSpeed)-16.01) > .0001 { + t.Fatal("swimming must use Swimming138 without the run-speed cap or low-health modifier", swimming, swimMode, swimSpeed) + } + if player.movement.deepWater || player.movement.components[0] != 3 || player.movement.strafe != 0 || player.movement.components[3] != 3 { + t.Fatal("leaving deep water must restore the preferred running mode", player.position, player.movement) + } +} + +func TestSwimmingFoundationPrecedesTheObserverMovementRefresh(t *testing.T) { + player := &character{id: 1, stats: testCharacterStats()} + player.stats.Body.Swimming = 3000 + + packets := playerCombatStatPackets(player) + swimming, refresh := -1, -1 + var raw uint32 + for index, packet := range packets { + if binary.BigEndian.Uint32(packet[20:24]) != 0x2b333d6e { + continue + } + switch binary.BigEndian.Uint32(packet[36:40]) { + case 138: + swimming, raw = index, binary.BigEndian.Uint32(packet[40:44]) + case 156: + refresh = index + } + } + + if swimming < 0 || swimming >= refresh || raw != 3000 { + t.Fatal("remote Swimming base must be installed before refreshing native movement parameters", swimming, refresh, raw) + } +} diff --git a/server/player_movement.go b/server/player_movement.go @@ -18,6 +18,12 @@ type playerMovement struct { direction int32 components [10]byte carriedMass int32 + speed float32 + normal [3]float32 + verticalVelocity float32 + fallHeight float32 + falling bool + deepWater bool } func (movement *playerMovement) prepare(player *character, now time.Time) { @@ -36,13 +42,15 @@ func (movement *playerMovement) prepare(player *character, now time.Time) { } if player.flying() { movement.components[0] = 7 + } else if movement.deepWater { + movement.components[0] = 4 } else if player.sitting { movement.components[0] = 8 } } func (movement *playerMovement) active() bool { - return movement.velocity != [3]float32{} || movement.forward != 0 || movement.strafe != 0 || movement.turn != 0 || movement.vertical != 0 + return movement.velocity != [3]float32{} || movement.forward != 0 || movement.strafe != 0 || movement.turn != 0 || movement.vertical != 0 || movement.falling || movement.verticalVelocity != 0 } func (player *character) predictedMovement(now time.Time) character { @@ -55,7 +63,7 @@ func (player *character) predictedMovement(now time.Time) character { func (player *character) anchorMovement_locked(now time.Time) { snapshot := player.predictedMovement(now) - player.position, player.rotation, player.movement = snapshot.position, snapshot.rotation, snapshot.movement + player.position, player.rotation, player.movement, player.body = snapshot.position, snapshot.rotation, snapshot.movement, snapshot.body player.movement.prepare(player, now) player.movement.updatedAt = now } @@ -90,7 +98,8 @@ func (movement *playerMovement) integrateForce(force [3]float32, seconds, bodyMa movement.velocity[axis] *= speed / length } } - return min(length, speed) + movement.speed = min(length, speed) + return movement.speed } func (player *character) advanceMovement(now time.Time, target [3]float32) { @@ -101,26 +110,35 @@ func (player *character) advanceMovement(now time.Time, target [3]float32) { seconds := now.Sub(movement.updatedAt).Seconds() movement.updatedAt = now previous := player.position - defer func() { movement.previousPosition = previous }() if seconds <= 0 || seconds > 4 { return } movement.prepare(player, now) if player.movementRestricted() || player.sitting { movement.velocity = [3]float32{} + movement.speed = 0 return } - speed := float32(1.5) - if player.running || player.flying() { - speed = player.runningMovementSpeed(movement.components[2] != 1) + physical := player.geometry != nil && player.geometry.terrain[player.playfield] != nil + if physical { + _, physical = player.geometry.playfields[player.playfield] } bodyMass, carriedMass := player.movementMass() - forceLimit := min(float32(10000), 2*(bodyMass+float32(carriedMass)*float32(.001))*speed) - for seconds > 0 { - step := float32(math.Min(seconds, .4)) - seconds -= float64(step) + changed := false + duration := float32(seconds) + for elapsed := float32(0); elapsed < duration; { + step := min(duration-elapsed, float32(.4)) + elapsed += step + speed := float32(1.5) + if movement.deepWater { + speed = player.swimmingMovementSpeed() + } else if player.running || player.flying() { + speed = player.runningMovementSpeed(movement.components[2] != 1) + } + forceLimit := min(float32(10000), 2*(bodyMass+float32(carriedMass)*float32(.001))*speed) forward, right := bodyAxes(player.rotation) force := [3]float32{} + steering := false if player.followTarget != 0 { // KKR48430 / QQR15fe0,15e90: four-unit arrival point, damping and Halt. delta := [3]float32{target[0] - player.position[0], target[1] - player.position[1], target[2] - player.position[2]} @@ -134,18 +152,22 @@ func (player *character) advanceMovement(now time.Time, target [3]float32) { delta = [3]float32{arrival[0] - player.position[0], arrival[1] - player.position[1], arrival[2] - player.position[2]} distance = vectorLength(delta) if distance < .2 || delta[0]*(arrival[0]-movement.previousPosition[0])+delta[2]*(arrival[2]-movement.previousPosition[2]) < 0 { + player.alignSurface(previous, false) movement.velocity = [3]float32{} + movement.speed = 0 if movement.direction < 0 { movement.action(player, 4) } else { movement.action(player, 2) } } else { + steering = true for axis := range force { force[axis] = 4 * bodyMass * (delta[axis]/distance*min(speed, 4*distance) - movement.velocity[axis]) } } } else if movement.forward != 0 { + steering = true // QQR159a0/159f0 uses full signed force, independently of arrival damping. sign := float32(1) if movement.forward < 0 { @@ -155,18 +177,50 @@ func (player *character) advanceMovement(now time.Time, target [3]float32) { force[axis] = sign * forceLimit * forward[axis] } } - length := movement.integrateForce(force, step, bodyMass, speed, forceLimit) - for axis := range player.position { - player.position[axis] += step * (right[axis] * movement.strafe) - if axis == 1 { - player.position[axis] += step * movement.vertical + if movement.falling { + movement.verticalVelocity = float32(float64(movement.verticalVelocity) - 20*float64(step)) + } + if steering || movement.falling { + movement.verticalVelocity = max(float32(-50), min(movement.verticalVelocity, float32(50))) + movement.integrateForce(force, step, bodyMass, speed, forceLimit) + } + + // Lateral input is direct displacement, filtered independently of capped velocity. + if movement.strafe != 0 || movement.vertical != 0 { + lateral := [3]float32{right[0] * movement.strafe, right[1]*movement.strafe + movement.vertical, right[2] * movement.strafe} + if physical && !player.flying() && movement.normal[1] < .5 { + tangent := collisionUphill(movement.normal) + if surfaceDot(tangent, lateral) > 0 { + horizontal := collisionDirection([3]float32{tangent[0], 0, tangent[2]}) + dot := surfaceDot(horizontal, lateral) + for axis := range lateral { + lateral[axis] -= float32(float64(horizontal[axis]) * dot) + } + } + } + for axis := range player.position { + player.position[axis] += step * lateral[axis] + } + changed = true + } + if movement.speed > .001 || movement.verticalVelocity != 0 { + if physical && !player.flying() { + if movement.speed > .001 && movement.normal[1] > .001 { + movement.velocity[1] = float32(-(float64(movement.normal[2])*float64(movement.velocity[2]) + float64(movement.normal[0])*float64(movement.velocity[0])) / float64(movement.normal[1])) + } + if movement.normal[1] < .5 && surfaceDot(collisionUphill(movement.normal), movement.velocity) > 0 { + player.guardSteepMovement(previous) + } } - if length > .001 { + for axis := range player.position { player.position[axis] += movement.velocity[axis] * step } + player.position[1] += step * movement.verticalVelocity + changed = true } // Native angular control runs after displacement, separately from lateral motion. if movement.turn != 0 { + changed = true sine, cosine := math.Sincos(float64(movement.turn * step)) if movement.velocity[0] == 0 && movement.velocity[2] == 0 { halfSine, halfCosine := math.Sincos(float64(movement.turn*step) / 2) @@ -179,6 +233,13 @@ func (player *character) advanceMovement(now time.Time, target [3]float32) { } } } + if !changed { + return + } + if physical { + 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) { sign := float64(1) @@ -214,6 +275,7 @@ func (movement *playerMovement) action(player *character, action uint32) bool { if accepted { if movement.direction != direction { movement.velocity = [3]float32{} + movement.speed = 0 } movement.direction = direction movement.forward = float32(direction) @@ -231,6 +293,7 @@ func (movement *playerMovement) action(player *character, action uint32) bool { if accepted { movement.forward = 0 movement.velocity = [3]float32{} + movement.speed = 0 movement.components[1], movement.components[2] = 1, 0 if action == 4 { movement.direction = 1 @@ -293,6 +356,10 @@ func (movement *playerMovement) action(player *character, action uint32) bool { return accepted } +func (player *character) swimmingMovementSpeed() float32 { + return max(float32(.1), 1+float32(.005)*float32(player.effectiveSkill(138, player.baseStats().Body.Swimming, gamedata.IPTraining.Weights[138]))) +} + func (player *character) strafeSpeed() float32 { runSpeed := float32(player.baseStats().Speed.RunSpeed) + float32(player.inventory.equipmentBonus(156)+player.nanoBonus(156)) if float32(player.health) < float32(player.maximumHealth())*float32(.15) { @@ -392,17 +459,6 @@ func (server *server) advancePlayerMovement_locked(now time.Time, updates map[*w server.queueCombat_locked(updates, player, player, playerMovementMassPackets(player)...) } } - if player.position != previous[id] { - if !player.flying() { - if ground := server.terrain[player.playfield]; ground != nil { - oldHeight, oldInside := ground.elevation(previous[id][0], previous[id][2]) - newHeight, newInside := ground.elevation(player.position[0], player.position[2]) - if oldInside && newInside { - player.position[1] = previous[id][1] + (newHeight - oldHeight) - } - } - } - } } // Resource/range effects see all participants at the completed frame. for id, client := range server.clients { diff --git a/server/remote_combat_stats_test.go b/server/remote_combat_stats_test.go @@ -69,7 +69,7 @@ func TestRemotePlayerSpawnCarriesUnmodifiedCombatFoundations(t *testing.T) { } values = append(values, [2]uint32{binary.BigEndian.Uint32(packet[valueOffset:]), binary.BigEndian.Uint32(packet[valueOffset+4:])}) case 0x3b1d2268, 0x35505644, 0x5e477770: - if len(values) != 13 { + if len(values) != 14 { t.Fatal("equipment or nano replay preceded raw combat foundations", values) } case 0x29304349: @@ -78,7 +78,7 @@ func TestRemotePlayerSpawnCarriesUnmodifiedCombatFoundations(t *testing.T) { } expected := [][2]uint32{{16, 7}, {17, 11}, {18, 13}, {19, 17}, {20, 19}, {21, 23}, - {118, 123}, {119, 0}, {120, 567}, {149, 1490}, {51, 0xffffff9c}, {78, 1200}, {156, 0}} + {138, 5}, {118, 123}, {119, 0}, {120, 567}, {149, 1490}, {51, 0xffffff9c}, {78, 1200}, {156, 0}} if err != nil || !spawned || !reflect.DeepEqual(values, expected) || player.equipmentBonus(51) != 5 || player.nanoBonus(16) != 12 { t.Fatal("observer omitted, duplicated or derived a raw combat foundation", err, values) } diff --git a/server/resurrection_reconnect_test.go b/server/resurrection_reconnect_test.go @@ -104,7 +104,7 @@ func TestResurrectionReconnectResumesPendingDeath(t *testing.T) { } } expectedStats := [][2]uint32{{16, 6}, {17, 6}, {18, 6}, {19, 6}, {20, 6}, {21, 6}, - {118, 5}, {119, 5}, {120, 5}, {149, 5}, {51, 0}, {78, 0}, {156, 5}} + {138, 5}, {118, 5}, {119, 5}, {120, 5}, {149, 5}, {51, 0}, {78, 0}, {156, 5}} if !reflect.DeepEqual(observerStats, expectedStats) { t.Fatal("pending reconnect omitted or changed the other player's combat foundations", observerStats) } diff --git a/server/roaming_test.go b/server/roaming_test.go @@ -45,7 +45,7 @@ func TestRoamingIsSharedBoundedAndZoneScoped(t *testing.T) { peer.Add(1) go func() { defer peer.Done() - for range 14 { + for range 15 { if _, err := readPacket(clients[0]); err != nil { t.Error(err) return diff --git a/server/scene_geometry.go b/server/scene_geometry.go @@ -12,6 +12,8 @@ type sceneGeometry struct { mutex sync.Mutex surfaces map[uint32]*sceneSurface waters map[uint32]*sceneWater + models map[uint32]collisionSphere + terrain map[uint32]*terrain } func readSceneGeometry(files fs.FS) (*sceneGeometry, error) { @@ -24,7 +26,25 @@ func readSceneGeometry(files fs.FS) (*sceneGeometry, error) { database.file.Close() return nil, err } - return &sceneGeometry{database: database, playfields: playfields, surfaces: make(map[uint32]*sceneSurface), waters: make(map[uint32]*sceneWater)}, nil + return &sceneGeometry{database: database, playfields: playfields, surfaces: make(map[uint32]*sceneSurface), waters: make(map[uint32]*sceneWater), models: make(map[uint32]collisionSphere)}, nil +} + +func (geometry *sceneGeometry) model(identity uint32) collisionSphere { + geometry.mutex.Lock() + defer geometry.mutex.Unlock() + if sphere, loaded := geometry.models[identity]; loaded { + return sphere + } + payload, _, err := geometry.database.read(1010002, identity) + if err != nil { + panic(err) + } + sphere, err := decodeModelSphere(payload, 1010002, 1) + if err != nil { + panic(fmt.Errorf("collision model %d: %w", identity, err)) + } + geometry.models[identity] = sphere + return sphere } func (geometry *sceneGeometry) water(playfield uint32, ground *terrain) *sceneWater { diff --git a/server/state.go b/server/state.go @@ -43,6 +43,8 @@ type character struct { running bool followTarget uint32 movement playerMovement + geometry *sceneGeometry + body playerCollisionBody returnDoor *doorOrigin npc bool npcDefinitionID string @@ -138,6 +140,7 @@ type server struct { clockStarted time.Time lastNPCUpdate time.Time terrain map[uint32]*terrain + geometry *sceneGeometry zoneLinks map[string]map[uint32]zoneLinks } @@ -157,6 +160,12 @@ func newServer() *server { panic(err) } server.terrain = ground + geometry, err := readSceneGeometry(resources) + if err != nil { + panic(err) + } + geometry.terrain = ground + server.geometry = geometry links, err := readZoneLinks() if err != nil { panic(err) @@ -203,6 +212,7 @@ func (server *server) newCharacter_locked() *character { id: server.nextCharacter, name: fmt.Sprintf("Local Explorer %d", server.nextCharacter), playfield: 950, position: [3]float32{52.625, 14.75, 56.875 + float32((server.nextCharacter-1)%4)*3}, rotation: [4]float32{0, 0, 0, 1}, appearance: 0x315, level: 1, profession: 1, + geometry: server.geometry, } character.stats = defaultCharacterStats(character.appearance >> 4 & 7) character.health = character.maximumHealth() diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go @@ -184,7 +184,7 @@ func TestTargetMovementIsPersistedAndRelayedToReleaseClient(t *testing.T) { if id == 2 { client.Write(targetPacket(n3Packet(0x570c2039, 50000, id, nil))) readPacket(clients[0]) - for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 118, 119, 120, 149, 51, 78, 156} { + for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 138, 118, 119, 120, 149, 51, 78, 156} { packet, err := readPacket(clients[0]) if err != nil || binary.BigEndian.Uint32(packet[20:24]) != 0x2b333d6e || binary.BigEndian.Uint32(packet[28:32]) != 2 || binary.BigEndian.Uint32(packet[36:40]) != stat { t.Fatalf("observer did not receive player combat foundations: %x %v", packet, err) diff --git a/server/world.go b/server/world.go @@ -170,7 +170,7 @@ func playerCombatStatPackets(character *character) [][]byte { // Native getters derive trickle from these bases and separate wear/nano modifiers. for _, stat := range stats { switch stat[0] { - case 16, 17, 18, 19, 20, 21, 51, 118, 119, 120, 149: + case 16, 17, 18, 19, 20, 21, 51, 118, 119, 120, 138, 149: body := binary.BigEndian.AppendUint32(nil, stat[0]) body = binary.BigEndian.AppendUint32(body, stat[1]) packets = append(packets, n3Packet(0x2b333d6e, 50000, character.id, body)) diff --git a/server/world_actions.go b/server/world_actions.go @@ -42,6 +42,9 @@ func (server *server) handleCharacterReady(client *worldClient) error { var motion [][]byte resources := make(map[*worldClient][][]byte) if client.loading { + player := server.characters[client.id] + player.movement.prepare(player, time.Now()) + player.alignSurface([3]float32{}, true) motion = server.playerMovementReplay_locked(client, time.Now()) motion = append(motion, server.playerFollowReplay_locked(client, nil)...) replay = playerCombatStatPackets(server.characters[client.id]) @@ -146,6 +149,7 @@ func (server *server) handleMovement(client *worldClient, body []byte) error { for axis := range forward { character.movement.velocity[axis] = forward[axis] * speed } + character.alignSurface(oldPosition, true) } playfield := character.playfield action := binary.BigEndian.Uint32(body[16:20]) diff --git a/server/world_output_test.go b/server/world_output_test.go @@ -85,7 +85,7 @@ func TestWorldReplacementRemovesRemoteActorBeforeReplayingEquipment(t *testing.T } expected := []uint32{0x271b3a6b, 0x570c2039} - for range 13 { + for range 14 { expected = append(expected, 0x2b333d6e) } expected = append(expected, 0x3b1d2268, 0x35505644, 0x570c2039, 0x36510078) diff --git a/server/zoning_test.go b/server/zoning_test.go @@ -137,10 +137,20 @@ func TestHeldWalkingCrossesDoorWithoutAnotherMovementPacket(t *testing.T) { world.mutex.Unlock() done := make(chan struct{}) - go func() { world.advanceZoneCrossings(started.Add(3 * time.Second)); close(done) }() + go func() { + defer close(done) + for frame := 1; frame <= 180; frame++ { + now := started.Add(time.Duration(frame) * time.Second / 60) + world.advancePlayerMovement(now) + world.advanceZoneCrossings(now) + } + }() teleport, err := readPacket(client) if err != nil { - t.Fatal(err) + world.mutex.Lock() + snapshot := world.characters[1].predictedMovement(started.Add(3 * time.Second)) + world.mutex.Unlock() + t.Fatal(err, "predicted door pose", snapshot.position, snapshot.movement) } redirect, err := readPacket(client) if err != nil { diff --git a/tools/data/extract_player_appearances.py b/tools/data/extract_player_appearances.py @@ -163,6 +163,7 @@ for head in heads: lines.append('bodies:') for body in bodies: lines.extend([f" - breed: {body['breed']}", f" sex: {body['creation_sex']}", + f" mesh: {body['body_meshes'][1]['mesh']}", ' textures:']) for race, materials in body['resolved_default_materials'].items(): lines.append(f' {race}: ' + json.dumps([materials[name]['texture'] for name in ['arms', 'feet', 'hands', 'legs', 'body']]))