aorecomp

Anarchy Online classic in the browser

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


commit afb025441e6afe254637dba5fdeb50edad8cc3bc
parent d531d828a3e954c844662b89f3454142dd365769
Author: anon <anon@example.com>
Date:   Mon, 26 Oct 2026 09:12:00 +0000

Implement native outdoor segment, floor and water queries

Read ordered water collision volumes from bundled playfields and share lazy
cell geometry across sphere, directed line and floor queries. Preserve native
KD traversal, grid traversal, clipping, bounds veto and terrain/static/liquid
selection. Movement integration remains a separate milestone.

Verified all 188 outdoor water maps, five independent geometry/order digests,
1254 server tests (14158 results), 163 focused normal/race results, data tests
and go vet. The single HTTPS preview remains available unchanged.

Diffstat:
MTODO.md | 9+++++++++
Mdocs/player-geometry.md | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/scene_geometry.go | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/scene_geometry_test.go | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/scene_playfield.go | 11+++++++++--
Aserver/scene_queries.go | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/scene_queries_test.go | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/scene_surface_test.go | 2+-
Aserver/scene_water.go | 312+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/scene_water_test.go | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/surface_line.go | 244+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/surface_line_test.go | 195+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/surface_sphere.go | 36+++++++++++++++++++++++++++++++++---
Mserver/terrain.go | 38++++++++++++++++++++++++++++++++++++++
Aserver/terrain_line.go | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/terrain_line_test.go | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16 files changed, 1816 insertions(+), 6 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -1223,6 +1223,15 @@ disconnect retention and succession policy still need period corroboration. 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. +- [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 + from the bundled playfield resources, retaining curved strips, subdivision, + 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; diff --git a/docs/player-geometry.md b/docs/player-geometry.md @@ -189,6 +189,52 @@ 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. +## Outdoor collision query provider + +The provider lazily shares immutable decoded cells and water geometry from the +already bundled database. Directed line and sphere queries include the extra +invisible tree; it wins exact distance ties. Floor queries use the embedded +primary tree. Segment triangles require the front-facing direction, admit the +origin and exclude the exact endpoint. Equal triangle hits retain the first +triangle within a group, while later groups can replace equal hits. Vertical +KD traversal preserves the native mixed displacement/fraction scalar rather +than substituting a generic nearest downward ray. + +Cell and terrain traversal share a grid walker with caller-specific float stores, +truncation and Z-first crossing ties. Cells query the whole segment but accept a +point only within the visited cell's closed bounds. Terrain queries preserve +alternating triangle order, directed faces and the unsigned distance gate. +Terrain wins exact distance ties against static geometry. World clipping keeps +native boundary interpolation and the high-edge 0.1 margin; terrain retains the +pre-clipping displacement. Position veto reverts the entire invalid pose before +clamping when supplied with a previous position. + +Water comes from the type1000001 outdoor playfield extension. The reader keeps +authored face or centroid-fan order, odd-kind cubic strips, even-kind recursive +subdivision, winding correction, the visual-bucket admission gate and zone-list +insertion order, including duplicates. All 188 selected outdoor maps decode to +46,140 volumes and 788,782 zone entries. Five complete geometry and ordered-list +digests match an independent Python asset parser. These host reductions preserve +explicit float stores but do not claim exact x87 intermediate rounding. + +Floor selection first samples terrain and its triangle normal, then queries the +current cell's static floor when the origin is at or above terrain. Static must +be strictly higher to replace terrain. Water uses that selected floor as its +query origin and the original origin height as its clip limit. Strict water +bounds and edge tests reject polygon boundaries. The first positive volume +either succeeds or vetoes the query; it does not search later volumes after a +clip rejection. Water replaces the floor only when its height minus1.2 is +strictly higher, while the returned medium retains the raw liquid height. +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. + ## Evidence `local/player-geometry-research/` retains runtime captures, the 28.73-metre wall @@ -212,6 +258,11 @@ failure, selected-archive comparisons and source ledgers: vertical KD traversal, normals, miss outputs and outdoor position veto. - `segment-query/`: 33 complete bodies; cell/terrain DDA, directed triangle intersections, KD ordering and the normally enabled invisible-surface switch. +- `water-data/`: 39 complete bodies; outdoor polygon framing, curved strips, + subdivision, collision volumes and exact zone-list construction, with all + 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. These counts overlap; they are not unique additional procedures. Source checks establish maintained-code contracts and evidence integrity. Runtime probes @@ -237,3 +288,9 @@ The subsequent six body captures are under cached-body, scale, template and ground-formula checks. Owned visitor121 was removed after closing the browser; unrelated rows hash unchanged, foreign-key and integrity checks pass, and the same single preview build was restarted. + +The outdoor provider milestone passes all 1,254 top-level server tests (14,158 +results), 163 focused results both normally and under the race detector, the data +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. diff --git a/server/scene_geometry.go b/server/scene_geometry.go @@ -0,0 +1,112 @@ +package main + +import ( + "fmt" + "io/fs" + "sync" +) + +type sceneGeometry struct { + database *gameDatabase + playfields map[uint32]scenePlayfield + mutex sync.Mutex + surfaces map[uint32]*sceneSurface + waters map[uint32]*sceneWater +} + +func readSceneGeometry(files fs.FS) (*sceneGeometry, error) { + database, err := readGameDatabase(files) + if err != nil { + return nil, err + } + playfields, err := database.outdoorPlayfields() + if err != nil { + database.file.Close() + return nil, err + } + return &sceneGeometry{database: database, playfields: playfields, surfaces: make(map[uint32]*sceneSurface), waters: make(map[uint32]*sceneWater)}, nil +} + +func (geometry *sceneGeometry) water(playfield uint32, ground *terrain) *sceneWater { + geometry.mutex.Lock() + defer geometry.mutex.Unlock() + if water, loaded := geometry.waters[playfield]; loaded { + return water + } + payload, version, err := geometry.database.read(1000001, playfield) + if err != nil { + panic(err) + } + if version != 1 { + panic(fmt.Errorf("outdoor water resource %d: unsupported version %d", playfield, version)) + } + water, err := readSceneWater(payload, geometry.playfields[playfield], ground) + if err != nil { + panic(fmt.Errorf("outdoor water resource %d: %w", playfield, err)) + } + geometry.waters[playfield] = water + return water +} + +func (geometry *sceneGeometry) surface(identity uint32) *sceneSurface { + geometry.mutex.Lock() + defer geometry.mutex.Unlock() + if surface, loaded := geometry.surfaces[identity]; loaded { + return surface + } + if _, exists := geometry.database.positions[[2]uint32{1000013, identity}]; !exists { + geometry.surfaces[identity] = nil + return nil + } + // Missing cells are ordinary; corruption of immutable bundled assets is an error. + payload, version, err := geometry.database.read(1000013, identity) + if err != nil { + panic(err) + } + surface, err := decodeSceneSurface(payload, version) + if err != nil { + panic(fmt.Errorf("scene resource %d: %w", identity, err)) + } + geometry.surfaces[identity] = surface + return surface +} + +func (geometry *sceneGeometry) sphere(playfield uint32, center [3]float32, radius float32) surfaceContact { + layout, exists := geometry.playfields[playfield] + if !exists { + return surfaceContact{} + } + surface := geometry.surface(playfield<<16 | layout.cellID(center)) + if surface == nil { + return surfaceContact{} + } + return surface.sphere(center, radius) +} + +func (geometry *sceneGeometry) cellLine(playfield uint32, origin, end [3]float32) surfaceIntersection { + // Sources: client/game/qqr.dll/lifted-0005.c, sub_4200F990; + // client/game/ggr.dll/lifted-0000.c, sub_30003730/300037C0. + layout, exists := geometry.playfields[playfield] + if !exists { + return surfaceIntersection{} + } + width := float64(layout.sizeX) / float64(layout.cellsX) + start := [2]float64{float64(float32(float64(origin[0]) / width)), float64(float32(float64(origin[2]) / width))} + endX, endZ := float32(float64(end[0])/width), float64(end[2])/width + travel := [2]float64{float64(float32(endX - float32(start[0]))), float64(float32(endZ - start[1]))} + for line := newGridLine(start, travel, [2]int{int(endX), int(endZ)}); line.remaining > 0; line.advance() { + x, z := line.cell[0], line.cell[1] + if x < 0 || x >= layout.cellsX || z < 0 || z >= layout.cellsZ { + break + } + surface := geometry.surface(playfield<<16 | uint32(z*layout.cellsX+x)) + if surface == nil { + continue + } + contact := surface.line(origin, end) + if contact.hit && float64(contact.point[0]) >= float64(x)*width && float64(contact.point[0]) <= float64(x+1)*width && float64(contact.point[2]) >= float64(z)*width && float64(contact.point[2]) <= float64(z+1)*width { + return contact + } + } + return surfaceIntersection{} +} diff --git a/server/scene_geometry_test.go b/server/scene_geometry_test.go @@ -0,0 +1,94 @@ +package main + +import ( + "ao/server/assets" + "math" + "sync" + "testing" +) + +func TestSceneCellLineRejectsHitsOutsideTheVisitedCell(t *testing.T) { + wall := func(x float32) *sceneSurface { + return &sceneSurface{primary: &surfaceTree{ + vertices: [][3]float32{{x, 0, 0}, {x, 0, 2}, {x, 2, 0}}, + groups: []surfaceGroup{{bounds: [6]float32{x, 0, 0, x, 2, 2}, triangles: [][3]uint32{{0, 1, 2}}}}, + nodes: []surfaceNode{{groups: []uint32{0}}}, + }} + } + geometry := &sceneGeometry{ + playfields: map[uint32]scenePlayfield{705: {cellsX: 3, cellsZ: 1, cellWidth: 1, cellDepth: 1, sizeX: 3, sizeZ: 1}}, + surfaces: map[uint32]*sceneSurface{705 << 16: wall(1.5), 705<<16 | 1: wall(1.75), 705<<16 | 2: nil}, + } + + contact := geometry.cellLine(705, [3]float32{.5, .5, .5}, [3]float32{2.5, .5, .5}) + outside := geometry.cellLine(705, [3]float32{-1.5, .5, .5}, [3]float32{2.5, .5, .5}) + unknown := geometry.cellLine(9999, [3]float32{.5, .5, .5}, [3]float32{2.5, .5, .5}) + + if !contact.hit || contact.point != [3]float32{1.75, .5, .5} { + t.Fatal("out-of-cell hit must not prevent the next cell query", contact) + } + if outside.hit || unknown.hit { + t.Fatal("unclipped cell traversal must stop outside the grid", outside, unknown) + } +} + +func TestSceneSphereUsesOnlyItsCenterCell(t *testing.T) { + geometry := &sceneGeometry{ + playfields: map[uint32]scenePlayfield{705: {cellsX: 2, cellsZ: 1, cellWidth: 1, cellDepth: 1, sizeX: 2, sizeZ: 1}}, + surfaces: map[uint32]*sceneSurface{ + 705 << 16: nil, + 705<<16 | 1: {primary: &surfaceTree{ + vertices: [][3]float32{{1.1, 0, 0}, {1.1, 0, 2}, {1.1, 2, 0}}, + groups: []surfaceGroup{{bounds: [6]float32{1.1, 0, 0, 1.1, 2, 2}, triangles: [][3]uint32{{0, 1, 2}}}}, + nodes: []surfaceNode{{groups: []uint32{0}}}, + }}, + }, + } + + neighbor := geometry.sphere(705, [3]float32{.99, .5, .5}, .5) + center := geometry.sphere(705, [3]float32{1.01, .5, .5}, .5) + + if neighbor.hit || !center.hit || center.normal != [3]float32{-1, 0, 0} { + t.Fatal("native sphere lookup must not expand into neighboring cells", neighbor, center) + } +} + +func TestSceneGeometrySharesShippedCellAcrossConcurrentQueries(t *testing.T) { + geometry, err := readSceneGeometry(assets.Files) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { geometry.database.file.Close() }) + grounds, err := readTerrain() + if err != nil { + t.Fatal(err) + } + var workers sync.WaitGroup + results := make(chan bool, 16) + + for range 16 { + workers.Add(1) + go func() { + defer workers.Done() + sphere := geometry.sphere(705, [3]float32{971.72, 16.66075, 519.66}, .25075) + line := geometry.cellLine(705, [3]float32{970, 17.5, 519.8}, [3]float32{975, 17.5, 519.8}) + var point, normal [3]float32 + geometry.floor(705, grounds[705], [3]float32{971.72, 17, 519.66}, &point, &normal) + results <- sphere.hit && line.hit && math.Abs(float64(line.point[0]-971.9442138671875)) < .0001 && math.Abs(float64(point[1]-16.4)) < .0001 && normal == [3]float32{0, 1, 0} + }() + } + workers.Wait() + close(results) + + for passed := range results { + if !passed { + t.Fatal("concurrent archive-backed wall query") + } + } + if len(geometry.surfaces) != 1 || geometry.surfaces[46203264] == nil { + t.Fatal("queries must share the decoded immutable cell", len(geometry.surfaces)) + } + if len(geometry.waters) != 1 || geometry.waters[705] == nil { + t.Fatal("queries must share the decoded immutable water geometry", len(geometry.waters)) + } +} diff --git a/server/scene_playfield.go b/server/scene_playfield.go @@ -9,6 +9,7 @@ import ( type scenePlayfield struct { cellsX, cellsZ int cellWidth, cellDepth float32 + sizeX, sizeZ float32 } func (database *gameDatabase) outdoorPlayfields() (map[uint32]scenePlayfield, error) { @@ -49,6 +50,7 @@ func (database *gameDatabase) outdoorPlayfields() (map[uint32]scenePlayfield, er cellsX: int(cellsX), cellsZ: int(cellsZ), cellWidth: float32(width*uint32(spacing)) / float32(cellsX), cellDepth: float32(depth*uint32(spacing)) / float32(cellsZ), + sizeX: float32(width * uint32(spacing)), sizeZ: float32(depth * uint32(spacing)), } } return playfields, nil @@ -57,9 +59,14 @@ func (database *gameDatabase) outdoorPlayfields() (map[uint32]scenePlayfield, er func (playfield scenePlayfield) cellID(position [3]float32) uint32 { // Source: client/game/ggr.dll/lifted-0000.c, sub_30003930/30003990. // CellSurface uses truncation and falls back to cell zero outside the grid. + id, _ := playfield.cellIndex(position) + return id +} + +func (playfield scenePlayfield) cellIndex(position [3]float32) (uint32, bool) { x, z := int(position[0]/playfield.cellWidth), int(position[2]/playfield.cellDepth) if x < 0 || x >= playfield.cellsX || z < 0 || z >= playfield.cellsZ { - return 0 + return 0, false } - return uint32(z*playfield.cellsX + x) + return uint32(z*playfield.cellsX + x), true } diff --git a/server/scene_queries.go b/server/scene_queries.go @@ -0,0 +1,122 @@ +package main + +func (layout scenePlayfield) clip(origin, end *[3]float32) bool { + // Source: client/game/llr.dll/lifted-0023.c, sub_3803B970. + code := func(point [3]float32) int { + result := 0 + if point[2] >= layout.sizeZ { + result |= 8 + } + if point[2] < 0 { + result |= 4 + } + if point[0] >= layout.sizeX { + result |= 2 + } + if point[0] < 0 { + result |= 1 + } + return result + } + for { + first, last := code(*origin), code(*end) + if first|last == 0 { + return true + } + if first&last != 0 { + return false + } + outside := first + if outside == 0 { + outside = last + } + axis, boundary, target := 2, float32(0), float32(0) + if outside&8 != 0 { + boundary, target = layout.sizeZ, layout.sizeZ-.1 + } else if outside&4 == 0 { + axis = 0 + if outside&2 != 0 { + boundary, target = layout.sizeX, layout.sizeX-.1 + } + } + fraction := (float64(boundary) - float64(origin[axis])) / (float64(end[axis]) - float64(origin[axis])) + var point [3]float32 + for other := range 3 { + point[other] = float32((float64(end[other])-float64(origin[other]))*fraction + float64(origin[other])) + } + point[axis] = target + if first != 0 { + *origin = point + } else { + *end = point + } + } +} + +func (layout scenePlayfield) veto(position, previous *[3]float32) bool { + // Source: client/game/llr.dll/lifted-0023.c, sub_3803CB70. + if position[0] >= 0 && position[0] < layout.sizeX && position[2] >= 0 && position[2] < layout.sizeZ && position[1] >= 0 && position[1] < 2000 { + return false + } + if previous != nil { + *position = *previous + } + position[0] = max(float32(.1), min(position[0], layout.sizeX-.1)) + position[2] = max(float32(.1), min(position[2], layout.sizeZ-.1)) + position[1] = max(float32(.01), min(position[1], float32(1999.9))) + return true +} + +func (geometry *sceneGeometry) line(playfield uint32, ground *terrain, origin, end [3]float32, clip bool) surfaceIntersection { + layout, exists := geometry.playfields[playfield] + if !exists { + return surfaceIntersection{} + } + // Native terrain keeps the pre-clipping displacement while cells use clipped endpoints. + delta := [3]float32{end[0] - origin[0], end[1] - origin[1], end[2] - origin[2]} + if clip && !layout.clip(&origin, &end) { + return surfaceIntersection{} + } + static := geometry.cellLine(playfield, origin, end) + terrain := ground.line(origin, end, delta) + if terrain.hit && (!static.hit || !(surfaceDistanceSquared(origin, static.point) < surfaceDistanceSquared(origin, terrain.point))) { + return terrain + } + return static +} + +func (geometry *sceneGeometry) floor(playfield uint32, ground *terrain, origin [3]float32, point, normal *[3]float32) waterContact { + // Source: client/game/llr.dll/lifted-0023.c, sub_3803B690. + // Invalid cells leave the caller's point and normal unchanged. + layout, exists := geometry.playfields[playfield] + if !exists || ground == nil { + return waterContact{} + } + cell, inside := layout.cellIndex(origin) + if !inside { + return waterContact{} + } + height, slope, sampled := ground.sample(origin[0], origin[2]) + if sampled { + *normal = slope + } + *point = [3]float32{origin[0], height, origin[2]} + if above := origin[1] - height; above >= 0 { + surface := geometry.surface(playfield<<16 | cell) + if surface != nil { + static := surfaceIntersection{point: [3]float32{origin[0], 0, origin[2]}, normal: [3]float32{0, 1, 0}} + if surface.primary != nil { + static = surface.primary.floor(origin, above+.3) + } + if static.point[1] > height { + *point, *normal = static.point, static.normal + } + } + } + water := geometry.water(playfield, ground).surface(cell, *point, origin[1]) + if water.height-float32(1.2) > point[1] { + point[1] = water.height - float32(1.2) + *normal = water.normal + } + return water +} diff --git a/server/scene_queries_test.go b/server/scene_queries_test.go @@ -0,0 +1,172 @@ +package main + +import ( + "math" + "testing" +) + +func TestSceneClippingUsesBoundaryInterpolationAndHighMargin(t *testing.T) { + layout := scenePlayfield{sizeX: 10, sizeZ: 10} + + for _, scenario := range []struct { + name string + origin, end [3]float32 + first, last [3]float32 + accepted bool + }{ + {"inside", [3]float32{0, 3, 0}, [3]float32{9, 4, 9}, [3]float32{0, 3, 0}, [3]float32{9, 4, 9}, true}, + {"high X", [3]float32{5, 0, 5}, [3]float32{15, 10, 5}, [3]float32{5, 0, 5}, [3]float32{9.9, 5, 5}, true}, + {"low Z", [3]float32{5, 0, -5}, [3]float32{5, 10, 5}, [3]float32{5, 5, 0}, [3]float32{5, 10, 5}, true}, + {"both sides", [3]float32{-5, 0, 5}, [3]float32{15, 20, 5}, [3]float32{0, 5, 5}, [3]float32{9.9, 15, 5}, true}, + {"shared outside side", [3]float32{11, 0, 3}, [3]float32{12, 5, 9}, [3]float32{11, 0, 3}, [3]float32{12, 5, 9}, false}, + } { + t.Run(scenario.name, func(t *testing.T) { + origin, end := scenario.origin, scenario.end + accepted := layout.clip(&origin, &end) + if accepted != scenario.accepted || origin != scenario.first || end != scenario.last { + t.Fatal("native clipped segment", origin, end, accepted) + } + }) + } +} + +func TestSceneVetoRevertsBeforeClampingAndKeepsValidZero(t *testing.T) { + layout := scenePlayfield{sizeX: 10, sizeZ: 20} + + for _, scenario := range []struct { + name string + position [3]float32 + previous *[3]float32 + veto bool + result [3]float32 + }{ + {"valid zero", [3]float32{}, nil, false, [3]float32{}}, + {"revert whole pose", [3]float32{11, 10, 15}, &[3]float32{4, 5, 6}, true, [3]float32{4, 5, 6}}, + {"clamp reverted zero edges", [3]float32{11, 10, 15}, &[3]float32{0, 5, 0}, true, [3]float32{.1, 5, .1}}, + {"final clamp", [3]float32{-1, 2000, 21}, nil, true, [3]float32{.1, 1999.9, 19.9}}, + {"lower height", [3]float32{5, -1, 5}, nil, true, [3]float32{5, .01, 5}}, + } { + t.Run(scenario.name, func(t *testing.T) { + position := scenario.position + veto := layout.veto(&position, scenario.previous) + if veto != scenario.veto || position != scenario.result { + t.Fatal("native outdoor bounds veto", position, veto) + } + }) + } +} + +func sceneSlopeFixture(offset float32) *sceneSurface { + return &sceneSurface{primary: &surfaceTree{ + vertices: [][3]float32{{0, offset, 0}, {0, offset + 8, 8}, {8, offset, 0}}, + groups: []surfaceGroup{{bounds: [6]float32{0, offset, 0, 8, offset + 8, 8}, triangles: [][3]uint32{{0, 1, 2}}}}, + nodes: []surfaceNode{{groups: []uint32{0}}}, + }} +} + +func TestSceneLineChoosesNearestSurfaceAndTerrainOnEqualHits(t *testing.T) { + ground := &terrain{width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 5, scale: 1, heights: make([]byte, 9)} + for _, scenario := range []struct { + name string + offset, height float32 + normal [3]float32 + }{ + {"static nearer", -1, 1, [3]float32{0, .70710677, -.70710677}}, + {"terrain wins tie", -2, 0, [3]float32{0, 1, 0}}, + {"terrain nearer", -3, 0, [3]float32{0, 1, 0}}, + } { + t.Run(scenario.name, func(t *testing.T) { + geometry := &sceneGeometry{ + playfields: map[uint32]scenePlayfield{705: {cellsX: 1, cellsZ: 1, cellWidth: 10, cellDepth: 10, sizeX: 10, sizeZ: 10}}, + surfaces: map[uint32]*sceneSurface{705 << 16: sceneSlopeFixture(scenario.offset)}, + } + + contact := geometry.line(705, ground, [3]float32{1, 5, 2}, [3]float32{1, -5, 2}, true) + + if !contact.hit || math.Abs(float64(contact.point[1]-scenario.height)) > .000001 || contact.normal != scenario.normal { + t.Fatal("combined terrain/static segment selection", contact) + } + }) + } +} + +func TestSceneLineRetainsTerrainDisplacementAfterClipping(t *testing.T) { + geometry := &sceneGeometry{ + playfields: map[uint32]scenePlayfield{705: {cellsX: 1, cellsZ: 1, cellWidth: 10, cellDepth: 10, sizeX: 10, sizeZ: 10}}, + surfaces: map[uint32]*sceneSurface{705 << 16: nil}, + } + ground := &terrain{width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 5, scale: 1, + heights: []byte{2, 2, 2, 2, 2, 2, 2, 2, 2}} + + clipped := geometry.line(705, ground, [3]float32{-5, 10, 2}, [3]float32{5, 0, 2}, true) + unclipped := geometry.line(705, ground, [3]float32{-5, 10, 2}, [3]float32{5, 0, 2}, false) + outside := geometry.line(705, ground, [3]float32{-5, 10, 2}, [3]float32{-1, 0, 2}, true) + + if !clipped.hit || clipped.point != [3]float32{3, 2, 2} || clipped.fraction != .3 || !unclipped.hit || unclipped.fraction != .8 || outside.hit { + t.Fatal("clipped terrain must keep the original displacement and distance gate", clipped, unclipped, outside) + } +} + +func TestSceneFloorSelectsTerrainStaticAndLiquidInNativeOrder(t *testing.T) { + ground := &terrain{width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 5, scale: 1, + heights: []byte{2, 2, 2, 2, 2, 2, 2, 2, 2}} + for _, scenario := range []struct { + name string + originY, offset, waterY float32 + height float32 + normal [3]float32 + }{ + {"static above terrain", 5, 1, 0, 3, [3]float32{0, .70710677, -.70710677}}, + {"terrain wins tie", 5, 0, 0, 2, [3]float32{0, 1, 0}}, + {"below terrain skips static", 1, 1, 0, 2, [3]float32{0, 1, 0}}, + {"below static keeps terrain", 2.5, 1, 0, 2, [3]float32{0, 1, 0}}, + {"liquid lifts selected floor", 5, 1, 5, 3.8, [3]float32{0, 1, 0}}, + {"liquid clearance keeps static normal", 5, 1, 4, 3, [3]float32{0, .70710677, -.70710677}}, + } { + t.Run(scenario.name, func(t *testing.T) { + water := &sceneWater{zones: []waterZone{{maxHeight: -1}}} + if scenario.waterY > 0 { + water.create([3][3]float32{{0, scenario.waterY, 0}, {8, scenario.waterY, 0}, {0, scenario.waterY, 8}}, 2) + water.zones[0] = waterZone{volumes: []int{0}, maxHeight: scenario.waterY} + water.maxHeight = scenario.waterY + } + geometry := &sceneGeometry{ + playfields: map[uint32]scenePlayfield{705: {cellsX: 1, cellsZ: 1, cellWidth: 10, cellDepth: 10, sizeX: 10, sizeZ: 10}}, + surfaces: map[uint32]*sceneSurface{705 << 16: sceneSlopeFixture(scenario.offset)}, + waters: map[uint32]*sceneWater{705: water}, + } + point, normal := [3]float32{99, 99, 99}, [3]float32{99, 99, 99} + + medium := geometry.floor(705, ground, [3]float32{1, scenario.originY, 2}, &point, &normal) + + if point[0] != 1 || point[2] != 2 || math.Abs(float64(point[1]-scenario.height)) > .000001 || normal != scenario.normal { + t.Fatal("combined terrain/static/liquid floor", point, normal) + } + if scenario.waterY > 0 && medium != (waterContact{height: scenario.waterY, normal: [3]float32{0, 1, 0}, kind: 2}) { + t.Fatal("liquid medium must retain raw water height even without floor replacement", medium) + } + }) + } +} + +func TestSceneFloorPreservesOutputsOutsideCellsAndTerrainNormalOnInvalidSamples(t *testing.T) { + geometry := &sceneGeometry{ + playfields: map[uint32]scenePlayfield{705: {cellsX: 1, cellsZ: 1, cellWidth: 10, cellDepth: 10, sizeX: 10, sizeZ: 10}}, + surfaces: map[uint32]*sceneSurface{705 << 16: nil}, + waters: map[uint32]*sceneWater{705: {zones: []waterZone{{maxHeight: -1}}}}, + } + ground := &terrain{width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 5, scale: 1, heights: make([]byte, 9)} + point, normal := [3]float32{1, 2, 3}, [3]float32{4, 5, 6} + + missing := geometry.floor(999, ground, [3]float32{}, &point, &normal) + outside := geometry.floor(705, ground, [3]float32{10, 2, 2}, &point, &normal) + unchangedPoint, unchangedNormal := point, normal + boundary := geometry.floor(705, ground, [3]float32{-.1, 2, 2}, &point, &normal) + + if missing != (waterContact{}) || outside != (waterContact{}) || unchangedPoint != [3]float32{1, 2, 3} || unchangedNormal != [3]float32{4, 5, 6} { + t.Fatal("invalid cell queries must retain caller outputs", unchangedPoint, unchangedNormal) + } + if point != [3]float32{-.1, 0, 2} || normal != [3]float32{4, 5, 6} || boundary.height != -100000 { + t.Fatal("cell truncation can admit a point outside terrain; numeric height zero leaves normal", point, normal, boundary) + } +} diff --git a/server/scene_surface_test.go b/server/scene_surface_test.go @@ -219,7 +219,7 @@ func TestScenePlayfieldUsesNativeCellSelection(t *testing.T) { t.Fatal(err) } - if playfields[705] != (scenePlayfield{30, 30, 40, 40}) || playfields[950] != (scenePlayfield{6, 6, 40, 40}) { + if playfields[705] != (scenePlayfield{30, 30, 40, 40, 1200, 1200}) || playfields[950] != (scenePlayfield{6, 6, 40, 40, 240, 240}) { t.Fatal("outdoor collision dimensions differ from native", playfields[705], playfields[950]) } for _, scenario := range []struct { diff --git a/server/scene_water.go b/server/scene_water.go @@ -0,0 +1,312 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "math" +) + +type waterVolume struct { + vertices [3][3]float32 + normal [3]float32 + plane float32 + bounds [6]float32 + kind uint32 + clipOffset float32 +} + +type waterZone struct { + volumes []int + maxHeight float32 +} + +type sceneWater struct { + volumes []waterVolume + zones []waterZone + maxHeight float32 +} + +type waterContact struct { + height float32 + normal [3]float32 + kind uint32 +} + +func readSceneWater(data []byte, layout scenePlayfield, ground *terrain) (*sceneWater, error) { + // Source: client/game/kkr.dll/lifted-0096.c, sub_3614FEA0. + reader := &surfaceReader{Reader: bytes.NewReader(data)} + var header [13]uint32 + reader.read(&header) + if reader.err != nil || header[0] != 8 || header[1] != header[10] || header[11] == 0 || uint64(header[12]) != uint64(layout.cellsX)*uint64(layout.cellsZ) { + return nil, fmt.Errorf("invalid outdoor water header") + } + if uint64(header[11]) > uint64(ground.boundsWidth) || uint64(header[11]) > uint64(ground.boundsHeight) || ground.boundsWidth/int(header[11]) != layout.cellsX || ground.boundsHeight/int(header[11]) != layout.cellsZ { + return nil, fmt.Errorf("outdoor water zones do not match terrain") + } + for range header[12] { + var count uint32 + reader.read(&count) + if reader.err != nil || uint64(count)*44 > uint64(reader.Len()) { + return nil, fmt.Errorf("truncated outdoor zone objects") + } + _, reader.err = reader.Seek(int64(count)*44, io.SeekCurrent) + } + var count uint32 + reader.read(&count) + if reader.err != nil || uint64(count)*12 > uint64(reader.Len()) { + return nil, fmt.Errorf("invalid outdoor water polygon count") + } + water := &sceneWater{zones: make([]waterZone, header[12])} + for index := range water.zones { + water.zones[index].maxHeight = -1 + } + for range count { + var flags, verticesCount, facesCount uint32 + reader.read(&flags) + reader.read(&verticesCount) + if reader.err != nil || uint64(verticesCount)*12 > uint64(reader.Len()) { + return nil, fmt.Errorf("truncated outdoor water vertices") + } + vertices := make([][3]float32, verticesCount) + reader.read(vertices) + for _, vertex := range vertices { + for _, value := range vertex { + if math.IsNaN(float64(value)) || math.IsInf(float64(value), 0) { + return nil, fmt.Errorf("nonfinite outdoor water vertex") + } + } + } + reader.read(&facesCount) + if reader.err != nil || uint64(facesCount)*6 > uint64(reader.Len()) { + return nil, fmt.Errorf("truncated outdoor water faces") + } + faces := make([][3]uint16, facesCount) + reader.read(faces) + for _, face := range faces { + for _, index := range face { + if uint32(index) >= verticesCount { + return nil, fmt.Errorf("invalid outdoor water face index") + } + } + } + if flags&1 != 0 || verticesCount == 3 { + for _, face := range faces { + water.create([3][3]float32{vertices[face[0]], vertices[face[1]], vertices[face[2]]}, flags) + } + } else if verticesCount != 0 { + var center [3]float32 + for _, vertex := range vertices { + for axis := range 3 { + center[axis] += vertex[axis] + } + } + for axis := range 3 { + center[axis] /= float32(verticesCount) + } + for index, vertex := range vertices { + water.create([3][3]float32{center, vertices[(index+len(vertices)-1)%len(vertices)], vertex}, flags) + } + } + } + if reader.err != nil { + return nil, reader.err + } + // Later playfield fields follow the water extension; they are not part of this reader. + water.assignZones(ground, header[11]) + return water, nil +} + +func waterMidpoint(first, second [3]float32) [3]float32 { + var midpoint [3]float32 + for axis := range 3 { + delta := float32(first[axis] - second[axis]) + midpoint[axis] = delta/2 + second[axis] + } + return midpoint +} + +func (water *sceneWater) create(vertices [3][3]float32, flags uint32) { + // Sources: client/game/bbr.dll/lifted-0017.c, sub_25052D20/25053210/25053A90. + if vertices[0] == vertices[1] || vertices[0] == vertices[2] || vertices[1] == vertices[2] { + return + } + kind := flags & 31 + clipOffset := float32(int32(flags)>>5) * float32(.1) + if clipOffset == 0 { + clipOffset = 100000 + } + minimum := min(vertices[0][1], vertices[1][1], vertices[2][1]) + height := max(vertices[0][1], vertices[1][1], vertices[2][1]) - minimum + if kind&1 == 0 || height < .1 { + water.subdivide(vertices, kind, clipOffset) + return + } + for index := range vertices { + if (vertices[index][1]-minimum)/height > .5 { + vertices[index][1] = 1 + } else { + vertices[index][1] = -.01 + } + } + if vertices[0][1] == vertices[2][1] { + vertices[1], vertices[2] = vertices[2], vertices[1] + } else if vertices[0][1] != vertices[1][1] { + vertices = [3][3]float32{vertices[1], vertices[2], vertices[0]} + } + bend := func(vertex [3]float32) [3]float32 { + t := 1 - float64(vertex[1]) + vertex[1] = float32((1-t*t*t)*float64(height) + float64(minimum)) + return vertex + } + first, second := vertices[0], vertices[1] + tipHigh := vertices[2][1] > .5 + if tipHigh { + first, second = vertices[2], vertices[2] + } + var stepFirst, stepSecond [3]float32 + for axis := range 3 { + if tipHigh { + stepFirst[axis] = (vertices[0][axis] - vertices[2][axis]) * float32(.1) + stepSecond[axis] = (vertices[1][axis] - vertices[2][axis]) * float32(.1) + } else { + stepFirst[axis] = (vertices[2][axis] - vertices[0][axis]) * float32(.1) + stepSecond[axis] = (vertices[2][axis] - vertices[1][axis]) * float32(.1) + } + } + for strip := range 10 { + previousFirst, previousSecond := first, second + for axis := range 3 { + first[axis] += stepFirst[axis] + second[axis] += stepSecond[axis] + } + if tipHigh || strip != 9 { + water.addVolume([3][3]float32{bend(previousFirst), bend(first), bend(second)}, kind, clipOffset) + } + if !tipHigh || strip != 0 { + water.addVolume([3][3]float32{bend(previousFirst), bend(previousSecond), bend(second)}, kind, clipOffset) + } + } +} + +func (water *sceneWater) subdivide(vertices [3][3]float32, kind uint32, clipOffset float32) { + var first, second [3]float32 + for axis := range 3 { + first[axis] = vertices[1][axis] - vertices[0][axis] + second[axis] = vertices[2][axis] - vertices[0][axis] + } + normal := surfaceCross(first, second) + if kind&1 == 0 && math.Sqrt(surfaceDot(normal, normal)) > 10000 { + ab, ac, bc := waterMidpoint(vertices[1], vertices[0]), waterMidpoint(vertices[2], vertices[0]), waterMidpoint(vertices[2], vertices[1]) + for _, child := range [4][3][3]float32{{vertices[0], ab, ac}, {vertices[1], bc, ab}, {vertices[2], bc, ac}, {ab, bc, ac}} { + water.subdivide(child, kind, clipOffset) + } + return + } + water.addVolume(vertices, kind, clipOffset) +} + +func (water *sceneWater) addVolume(vertices [3][3]float32, kind uint32, clipOffset float32) { + // Source: client/game/bbr.dll/lifted-0017.c, sub_25054050/250527E0. + if vertices[0] == vertices[1] || vertices[0] == vertices[2] || vertices[1] == vertices[2] { + return + } + sumX := float64(vertices[0][0]) + float64(vertices[1][0]) + float64(vertices[2][0]) + sumZ := float64(vertices[0][2]) + float64(vertices[1][2]) + float64(vertices[2][2]) + bucket := int(sumX*float64(float32(1.0/3))*float64(float32(.01))) - 60*int(sumZ*float64(float32(1.0/3))*float64(float32(-.01))) + if bucket < 0 || bucket >= 3600 { + return + } + var first, second [3]float32 + for axis := range 3 { + first[axis] = vertices[1][axis] - vertices[0][axis] + second[axis] = vertices[2][axis] - vertices[0][axis] + } + normal := surfaceCross(first, second) + if normal[1] < 0 { + vertices[1], vertices[2] = vertices[2], vertices[1] + normal = surfaceCross(second, first) + } + if math.Abs(float64(normal[0])) < float64(float32(.00001)) && math.Abs(float64(normal[1])) < float64(float32(.00001)) && math.Abs(float64(normal[2])) < float64(float32(.00001)) { + return + } + length := math.Sqrt(surfaceDot(normal, normal)) + for axis := range normal { + normal[axis] = float32(float64(normal[axis]) / length) + } + volume := waterVolume{vertices: vertices, normal: normal, kind: kind - kind&1, clipOffset: clipOffset} + volume.plane = float32(-(float64(normal[2])*float64(vertices[0][2]) + float64(normal[1])*float64(vertices[0][1]) + float64(normal[0])*float64(vertices[0][0]))) + for axis := range 3 { + volume.bounds[axis] = min(vertices[0][axis], vertices[1][axis], vertices[2][axis]) + volume.bounds[axis+3] = max(vertices[0][axis], vertices[1][axis], vertices[2][axis]) + } + water.volumes = append(water.volumes, volume) +} + +func (water *sceneWater) assignZones(ground *terrain, zoneSize uint32) { + // Source: client/game/kkr.dll/lifted-0061.c, sub_360D0040. + step := float32(zoneSize) * ground.spacing + upperX, upperZ := float32(ground.boundsWidth)*ground.spacing-.1, float32(ground.boundsHeight)*ground.spacing-.1 + for index := range water.volumes { + volume := &water.volumes[index] + var x, z [3]float32 + for vertex := range 3 { + x[vertex] = max(float32(.1), min(volume.vertices[vertex][0], upperX)) + z[vertex] = max(float32(.1), min(volume.vertices[vertex][2], upperZ)) + } + firstX, lastX := max(float32(.1), min(min(x[0], x[1], x[2])-step, upperX)), max(float32(.1), min(max(x[0], x[1], x[2])+step, upperX)) + firstZ, lastZ := max(float32(.1), min(min(z[0], z[1], z[2])-step, upperZ)), max(float32(.1), min(max(z[0], z[1], z[2])+step, upperZ)) + for x := firstX; x < lastX; x += step { + for z := firstZ; z < lastZ; z += step { + cell := int(float32(int(z/ground.spacing))/float32(zoneSize))*(ground.boundsWidth/int(zoneSize)) + int(x/ground.spacing/float32(zoneSize)) + water.zones[cell].volumes = append(water.zones[cell].volumes, index) + water.zones[cell].maxHeight = max(water.zones[cell].maxHeight, volume.bounds[4]) + } + } + } + for _, zone := range water.zones { + water.maxHeight = max(water.maxHeight, zone.maxHeight) + } +} + +func (volume *waterVolume) height(origin [3]float32) float64 { + // Source: client/game/bbr.dll/lifted-0017.c, sub_250529B0. + if !(origin[1] < volume.bounds[4] && origin[0] > volume.bounds[0] && origin[0] < volume.bounds[3] && origin[2] > volume.bounds[2] && origin[2] < volume.bounds[5]) { + return 0 + } + for edge, vertex := range volume.vertices { + next := volume.vertices[(edge+1)%3] + dx, dz := next[0]-vertex[0], next[2]-vertex[2] + side := (float64(origin[2])-float64(vertex[2]))*float64(dx) - (float64(origin[0])-float64(vertex[0]))*float64(dz) + if !(side < 0) { + return 0 + } + } + height := (-float64(origin[0])*float64(volume.normal[0]) - float64(origin[2])*float64(volume.normal[2]) - float64(volume.plane)) / float64(volume.normal[1]) + if !(height > 0) { + return 0 + } + return height +} + +func (water *sceneWater) surface(cell uint32, origin [3]float32, heightLimit float32) waterContact { + // Sources: client/game/llr.dll/lifted-0017.c, sub_3802D2B0; + // client/game/llr.dll/lifted-0024.c, sub_3803F0E0. + if origin[1] > water.maxHeight { + return waterContact{height: -9999} + } + zone := &water.zones[cell] + if origin[1] < zone.maxHeight { + for _, index := range zone.volumes { + volume := &water.volumes[index] + height := volume.height(origin) + if height > 0 { + if height-float64(volume.clipOffset) <= float64(heightLimit) { + return waterContact{height: float32(height), normal: volume.normal, kind: volume.kind} + } + break + } + } + } + return waterContact{height: -100000} +} diff --git a/server/scene_water_test.go b/server/scene_water_test.go @@ -0,0 +1,205 @@ +package main + +import ( + "ao/server/assets" + "bytes" + "crypto/sha256" + "encoding/binary" + "fmt" + "math" + "sort" + "testing" +) + +func TestSceneWaterDecodesEverySelectedOutdoorPlayfield(t *testing.T) { + geometry, err := readSceneGeometry(assets.Files) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { geometry.database.file.Close() }) + grounds, err := readTerrain() + if err != nil { + t.Fatal(err) + } + identities := make([]int, 0, len(geometry.playfields)) + for identity := range geometry.playfields { + identities = append(identities, int(identity)) + } + sort.Ints(identities) + golden := map[uint32]string{ + 540: "8b29477b8001893b0f9deac41fb56d1542f9ab5577049de8b4325f4f793a3e36", + 600: "406dbbe1cf1dc18bb46efa74f586e471f165c15022646fb4253819a4fbd86661", + 705: "7793e806c51b5aaecedb1729907f85434bd0ace715889e42fb95447dc1569bb4", + 800: "2c11d7822547016cdd2f6f063317246d5b90ce5ffb9ee2dd3c4ef6482c0465c7", + 950: "ea56822b3a15f9b95c4d33b07f44d913d70a281005bf426af700e7541cd12130", + } + volumes, entries, wetPlayfields := 0, 0, 0 + + for _, identity := range identities { + water := geometry.water(uint32(identity), grounds[uint32(identity)]) + volumes += len(water.volumes) + if len(water.volumes) != 0 { + wetPlayfields++ + } + digest := sha256.New() + write := func(value any) { + if err := binary.Write(digest, binary.LittleEndian, value); err != nil { + t.Fatal(err) + } + } + for _, volume := range water.volumes { + write(volume.vertices) + write(volume.normal) + write(volume.plane) + write(volume.kind) + write(volume.clipOffset) + write(volume.bounds) + } + for _, zone := range water.zones { + entries += len(zone.volumes) + write(uint32(len(zone.volumes))) + for _, index := range zone.volumes { + write(uint32(index)) + } + } + + if expected, sample := golden[uint32(identity)]; sample && fmt.Sprintf("%x", digest.Sum(nil)) != expected { + t.Fatalf("playfield %d differs from independent water parser: %x", identity, digest.Sum(nil)) + } + } + if len(identities) != 188 || volumes != 46140 || entries != 788782 || wetPlayfields != 158 { + t.Fatal("selected water census changed", len(identities), volumes, entries, wetPlayfields) + } + t.Log("188 playfields, 46140 volumes, 788782 ordered zone entries; five complete geometry/list digests") +} + +func sceneWaterFixture() []byte { + var data bytes.Buffer + header := [13]uint32{0: 8, 1: 705, 10: 705, 11: 2, 12: 1} + for _, value := range []any{header, uint32(0), uint32(1), uint32(960), uint32(3), [3][3]float32{{2, 5, 2}, {8, 5, 2}, {2, 5, 8}}, uint32(1), [3]uint16{0, 1, 2}} { + binary.Write(&data, binary.LittleEndian, value) + } + return data.Bytes() +} + +func TestSceneWaterReadsFlagsAndAllowsTheFollowingPlayfieldTail(t *testing.T) { + ground := &terrain{boundsWidth: 2, boundsHeight: 2, spacing: 10} + layout := scenePlayfield{cellsX: 1, cellsZ: 1} + + water, err := readSceneWater(append(sceneWaterFixture(), 1, 2, 3), layout, ground) + + if err != nil { + t.Fatal(err) + } + if len(water.volumes) != 1 || len(water.zones[0].volumes) != 1 || water.maxHeight != 5 || water.zones[0].maxHeight != 5 { + t.Fatal("water framing or zone maxima", water) + } + if water.volumes[0].kind != 0 || water.volumes[0].clipOffset != 3 || water.volumes[0].normal != [3]float32{0, 1, 0} { + t.Fatal("authored flags or winding correction", water.volumes[0]) + } +} + +func TestSceneWaterRejectsTruncationAndMalformedPolygons(t *testing.T) { + ground := &terrain{boundsWidth: 2, boundsHeight: 2, spacing: 10} + layout := scenePlayfield{cellsX: 1, cellsZ: 1} + data := sceneWaterFixture() + + for length := range len(data) { + if _, err := readSceneWater(data[:length], layout, ground); err == nil { + t.Fatal("accepted truncated water prefix", length) + } + } + for _, scenario := range []struct { + name string + offset int + value uint32 + }{ + {"inner version", 0, 7}, + {"indoor template", 40, 999}, + {"zero zone size", 44, 0}, + {"zone terrain mismatch", 44, 1}, + {"zone count", 48, 2}, + {"objects exceed payload", 52, math.MaxUint32}, + {"polygons exceed payload", 56, math.MaxUint32}, + {"vertices exceed payload", 64, math.MaxUint32}, + {"nonfinite vertex", 68, 0x7f800000}, + {"faces exceed payload", 104, math.MaxUint32}, + {"face vertex out of range", 108, 3}, + } { + t.Run(scenario.name, func(t *testing.T) { + changed := bytes.Clone(data) + binary.LittleEndian.PutUint32(changed[scenario.offset:], scenario.value) + if _, err := readSceneWater(changed, layout, ground); err == nil { + t.Fatal("accepted malformed water data") + } + }) + } +} + +func TestSceneWaterRequiresStrictInteriorAndPositivePlaneHeight(t *testing.T) { + water := &sceneWater{} + water.create([3][3]float32{{2, 5, 2}, {8, 5, 2}, {2, 5, 8}}, 0) + water.create([3][3]float32{{2, 0, 2}, {8, 0, 2}, {2, 0, 8}}, 0) + + for _, scenario := range []struct { + name string + origin [3]float32 + height float64 + }{ + {"inside below plane", [3]float32{3, 4, 3}, 5}, + {"at plane", [3]float32{3, 5, 3}, 0}, + {"above plane", [3]float32{3, 6, 3}, 0}, + {"minimum X", [3]float32{2, 4, 3}, 0}, + {"maximum X", [3]float32{8, 4, 3}, 0}, + {"minimum Z", [3]float32{3, 4, 2}, 0}, + {"maximum Z", [3]float32{3, 4, 8}, 0}, + {"diagonal edge", [3]float32{5, 4, 5}, 0}, + {"outside triangle inside bounds", [3]float32{7, 4, 7}, 0}, + } { + t.Run(scenario.name, func(t *testing.T) { + if height := water.volumes[0].height(scenario.origin); height != scenario.height { + t.Fatal("strict water volume admission", height) + } + }) + } + if height := water.volumes[1].height([3]float32{3, -1, 3}); height != 0 { + t.Fatal("nonpositive water plane must be rejected", height) + } +} + +func TestSceneWaterUsesFirstMatchAndStopsAtItsClipVeto(t *testing.T) { + water := &sceneWater{zones: []waterZone{{volumes: []int{0, 1}, maxHeight: 7}}, maxHeight: 7} + water.create([3][3]float32{{2, 5, 2}, {8, 5, 2}, {2, 5, 8}}, 32) + water.create([3][3]float32{{2, 7, 2}, {8, 7, 2}, {2, 7, 8}}, 2) + + accepted := water.surface(0, [3]float32{3, 1, 3}, 5) + vetoed := water.surface(0, [3]float32{3, 1, 3}, 3) + next := water.surface(0, [3]float32{3, 5, 3}, 7) + zoneMiss := water.surface(0, [3]float32{3, 7, 3}, 7) + playfieldMiss := water.surface(0, [3]float32{3, 8, 3}, 8) + + if accepted != (waterContact{height: 5, normal: [3]float32{0, 1, 0}}) || next != (waterContact{height: 7, normal: [3]float32{0, 1, 0}, kind: 2}) { + t.Fatal("water selection must retain creation order", accepted, next) + } + if vetoed != (waterContact{height: -100000}) || zoneMiss != (waterContact{height: -100000}) || playfieldMiss != (waterContact{height: -9999}) { + t.Fatal("water clip veto or miss sentinels", vetoed, zoneMiss, playfieldMiss) + } +} + +func TestSceneWaterCurvesOddKindsAndRejectsDegenerateVolumes(t *testing.T) { + water := &sceneWater{} + + water.create([3][3]float32{{2, 2, 2}, {8, 2, 2}, {2, 6, 8}}, 3) + water.create([3][3]float32{{2, 2, 2}, {2, 2, 2}, {2, 6, 8}}, 3) + water.create([3][3]float32{{2, 2, 2}, {3, 2, 3}, {4, 2, 4}}, 0) + water.create([3][3]float32{{10000, 2, 10000}, {10010, 2, 10000}, {10000, 2, 10010}}, 0) + + if len(water.volumes) != 19 { + t.Fatal("ten cubic strips must emit nineteen admitted triangles", len(water.volumes)) + } + for _, volume := range water.volumes { + if volume.kind != 2 || volume.clipOffset != 100000 || volume.normal[1] < 0 { + t.Fatal("odd-kind normalization or default clip offset", volume) + } + } +} diff --git a/server/surface_line.go b/server/surface_line.go @@ -0,0 +1,244 @@ +package main + +type surfaceIntersection struct { + point, normal [3]float32 + fraction float32 + hit bool +} + +func (group *surfaceGroup) line(origin, delta [3]float32) surfaceIntersection { + // Source: client/game/llr.dll/lifted-0028.c, sub_380475F0/38047800. + best := surfaceIntersection{fraction: 1} + for index := range group.geometry { + triangle := &group.geometry[index] + denominator := float64(delta[2])*float64(triangle.normal[2]) + float64(delta[0])*float64(triangle.normal[0]) + float64(delta[1])*float64(triangle.normal[1]) + if !(denominator < 0) { + continue + } + dot := float64(origin[1])*float64(triangle.normal[1]) + float64(origin[2])*float64(triangle.normal[2]) + float64(origin[0])*float64(triangle.normal[0]) + fraction := float32((-float64(triangle.plane) - dot) / denominator) + if float64(fraction)+float64(float32(.0000011920928955078125)) < 0 || float64(best.fraction)+float64(float32(.0000011920928955078125)) < float64(fraction) { + continue + } + var point [3]float32 + for axis := range 3 { + product := float32(delta[axis] * fraction) + point[axis] = origin[axis] + product + } + inside := true + for edge := range 3 { + if surfaceDot(point, triangle.sides[edge])+float64(triangle.side[edge]) > 0 { + inside = false + break + } + } + if inside && fraction < best.fraction { + best = surfaceIntersection{point: point, normal: triangle.normal, fraction: fraction, hit: true} + } + } + return best +} + +func surfaceLineExcluded(bounds [6]float32, origin, end [3]float32) bool { + // Source: client/game/llr.dll/lifted-0028.c, sub_380457B0. + for _, point := range [2][3]float32{origin, end} { + inside := true + for axis := range 3 { + if point[axis] < bounds[axis] || point[axis] > bounds[axis+3] { + inside = false + } + } + if inside { + return false + } + } + for _, axis := range [3]int{1, 0, 2} { + if origin[axis] == end[axis] { + continue + } + for _, plane := range [2]float32{bounds[axis], bounds[axis+3]} { + if origin[axis] < plane && end[axis] < plane || origin[axis] > plane && end[axis] > plane { + continue + } + fraction := float32((float64(plane) - float64(origin[axis])) / (float64(end[axis]) - float64(origin[axis]))) + inside := true + for other := range 3 { + if other == axis { + continue + } + coordinate := (float64(end[other])-float64(origin[other]))*float64(fraction) + float64(origin[other]) + if coordinate < float64(bounds[other]) || coordinate > float64(bounds[other+3]) { + inside = false + } + } + if inside { + return false + } + } + } + return true +} + +func surfaceSegmentOutside(bounds [6]float32, origin, end [3]float32) bool { + for axis := range 3 { + if origin[axis] < bounds[axis] && end[axis] < bounds[axis] || origin[axis] > bounds[axis+3] && end[axis] > bounds[axis+3] { + return true + } + } + return false +} + +func (surface *sceneSurface) line(origin, end [3]float32) surfaceIntersection { + // Source: client/game/llr.dll/lifted-0021.c, sub_38037B50. + if surface.primary == nil { + return surfaceIntersection{} + } + invisible := surfaceIntersection{} + if surface.invisible != nil { + invisible = surface.invisible.line(origin, end) + } + primary := surface.primary.line(origin, end) + if !invisible.hit || primary.hit && surfaceDistanceSquared(origin, primary.point) < surfaceDistanceSquared(origin, invisible.point) { + return primary + } + return invisible +} + +func (tree *surfaceTree) line(origin, end [3]float32) surfaceIntersection { + tree.initialize() + return tree.nodeLine(0, origin, end, 1) +} + +func (tree *surfaceTree) nodeLine(index int, origin, end [3]float32, bound float32) surfaceIntersection { + // Source: client/game/llr.dll/lifted-0027.c, sub_38044C90. + delta := [3]float32{end[0] - origin[0], end[1] - origin[1], end[2] - origin[2]} + var clipped [3]float32 + for axis := range 3 { + product := float32(delta[axis] * bound) + clipped[axis] = origin[axis] + product + } + clipped[0] = float32(float64(origin[0]) + float64(delta[0])*float64(bound)) + found := surfaceIntersection{} + node := &tree.nodes[index] + for len(node.groups) == 0 { + if float32(surfaceDistanceSquared(clipped, origin)) > 3 { + if surfaceLineExcluded(node.bounds, origin, clipped) { + return found + } + } else if surfaceSegmentOutside(node.bounds, origin, clipped) { + return found + } + low := origin[node.axis] < node.split || clipped[node.axis] < node.split + high := origin[node.axis] >= node.split || clipped[node.axis] >= node.split + if !low { + node = &tree.nodes[node.children[1]] + continue + } + if !high { + node = &tree.nodes[node.children[0]] + continue + } + first, next := node.children[0], node.children[1] + upper := origin[node.axis] >= node.split + if upper { + first, next = next, first + } + candidate := tree.nodeLine(first, origin, end, bound) + if candidate.hit && candidate.fraction <= bound { + for axis := range 3 { + product := float32(delta[axis] * candidate.fraction) + clipped[axis] = origin[axis] + product + } + if upper && clipped[node.axis] >= node.split || !upper && clipped[node.axis] < node.split { + return candidate + } + found, bound = candidate, candidate.fraction + } + node = &tree.nodes[next] + } + if len(node.groups) != 1 && surfaceLineExcluded(node.bounds, origin, end) { + return found + } + for _, index := range node.groups { + group := &tree.groups[index] + if surfaceLineExcluded(group.bounds, origin, clipped) { + continue + } + candidate := group.line(origin, delta) + if candidate.hit && candidate.fraction <= bound { + found, bound = candidate, candidate.fraction + } + } + return found +} + +func surfaceFloorOverlap(bounds [6]float32, origin [3]float32, displacement float32) bool { + if origin[0] < bounds[0] || origin[0] > bounds[3] || origin[2] < bounds[2] || origin[2] > bounds[5] { + return false + } + end := float64(origin[1]) + float64(displacement) + return !(float64(origin[1]) < float64(bounds[1]) && end < float64(bounds[1]) || float64(origin[1]) > float64(bounds[4]) && end > float64(bounds[4])) +} + +func (tree *surfaceTree) floor(origin [3]float32, bound float32) surfaceIntersection { + // Source: client/game/llr.dll/lifted-0028.c, sub_380460F0. + tree.initialize() + result := tree.nodeFloor(0, origin, bound) + if !result.hit { + result.point = [3]float32{origin[0], 0, origin[2]} + result.normal = [3]float32{0, 1, 0} + } + return result +} + +func (tree *surfaceTree) nodeFloor(index int, origin [3]float32, bound float32) surfaceIntersection { + // Source: client/game/llr.dll/lifted-0028.c, sub_38045BC0. + // The native recursion carries a mixed displacement/fraction scalar; retain it literally. + displacement := -bound + found := surfaceIntersection{} + node := &tree.nodes[index] + for len(node.groups) == 0 { + if !surfaceFloorOverlap(node.bounds, origin, displacement) { + return found + } + low, high := origin[node.axis] < node.split, origin[node.axis] >= node.split + if node.axis == 1 { + low = low || float64(origin[1])+float64(displacement) < float64(node.split) + high = high || float64(origin[1])+float64(displacement) >= float64(node.split) + } + if low && high { + first, next := node.children[0], node.children[1] + upper := origin[node.axis] >= node.split + if upper { + first, next = next, first + } + candidate := tree.nodeFloor(first, origin, bound) + if candidate.hit && candidate.fraction <= bound { + end := float64(origin[1]) + float64(displacement) + if upper && end >= float64(node.split) || !upper && end < float64(node.split) { + return candidate + } + found, bound = candidate, candidate.fraction + } + node = &tree.nodes[next] + } else if low { + node = &tree.nodes[node.children[0]] + } else { + node = &tree.nodes[node.children[1]] + } + } + if len(node.groups) != 1 && !surfaceFloorOverlap(node.bounds, origin, displacement) { + return found + } + for _, index := range node.groups { + group := &tree.groups[index] + if !surfaceFloorOverlap(group.bounds, origin, displacement) { + continue + } + candidate := group.line(origin, [3]float32{0, displacement, 0}) + if candidate.hit && candidate.fraction <= bound { + found, bound = candidate, candidate.fraction + } + } + return found +} diff --git a/server/surface_line_test.go b/server/surface_line_test.go @@ -0,0 +1,195 @@ +package main + +import ( + "ao/server/assets" + "math" + "sync" + "testing" +) + +func TestSurfaceLineUsesDirectedFacesAndStrictEndpoint(t *testing.T) { + tree := &surfaceTree{ + vertices: [][3]float32{{0, 0, 0}, {0, 0, 2}, {0, 2, 0}}, + groups: []surfaceGroup{{bounds: [6]float32{-.01, 0, 0, .01, 2, 2}, triangles: [][3]uint32{{0, 1, 2}}}}, + nodes: []surfaceNode{{groups: []uint32{0}}}, + } + + for _, scenario := range []struct { + name string + origin, end [3]float32 + hit bool + point [3]float32 + fraction float32 + }{ + {"face", [3]float32{-1, .5, .5}, [3]float32{1, .5, .5}, true, [3]float32{0, .5, .5}, .5}, + {"edge", [3]float32{-1, 0, .5}, [3]float32{1, 0, .5}, true, [3]float32{0, 0, .5}, .5}, + {"vertex", [3]float32{-1, 0, 0}, [3]float32{1, 0, 0}, true, [3]float32{}, .5}, + {"origin included", [3]float32{0, .5, .5}, [3]float32{1, .5, .5}, true, [3]float32{0, .5, .5}, 0}, + {"tiny negative fraction", [3]float32{.0000001, .5, .5}, [3]float32{1, .5, .5}, true, [3]float32{0, .5, .5}, -.00000010000001}, + {"endpoint excluded", [3]float32{-1, .5, .5}, [3]float32{0, .5, .5}, false, [3]float32{}, 0}, + {"back face", [3]float32{1, .5, .5}, [3]float32{-1, .5, .5}, false, [3]float32{}, 0}, + {"parallel", [3]float32{-1, .5, .5}, [3]float32{-1, 1, .5}, false, [3]float32{}, 0}, + {"outside triangle", [3]float32{-1, 1.5, 1.5}, [3]float32{1, 1.5, 1.5}, false, [3]float32{}, 0}, + } { + t.Run(scenario.name, func(t *testing.T) { + contact := tree.line(scenario.origin, scenario.end) + if contact.hit != scenario.hit { + t.Fatal("directed segment eligibility", contact) + } + if contact.hit && (contact.normal != [3]float32{-1, 0, 0} || contact.point != scenario.point || math.Abs(float64(contact.fraction-scenario.fraction)) > .00000001) { + t.Fatal("directed segment point/normal/fraction", contact) + } + }) + } +} + +func TestSurfaceLineLetsLaterGroupsReplaceEqualHits(t *testing.T) { + vertices := [][3]float32{{0, -2, -2}, {0, -2, 2}, {0, 2, -2}, {-2, -2, 0}, {-2, 2, 0}, {2, -2, 0}} + groups := []surfaceGroup{ + {bounds: [6]float32{0, -2, -2, 0, 2, 2}, triangles: [][3]uint32{{0, 1, 2}}}, + {bounds: [6]float32{-2, -2, 0, 2, 2, 0}, triangles: [][3]uint32{{3, 4, 5}}}, + } + oneGroup := &surfaceTree{vertices: vertices, + groups: []surfaceGroup{{bounds: [6]float32{-2, -2, -2, 2, 2, 2}, triangles: [][3]uint32{{0, 1, 2}, {3, 4, 5}}}}, + nodes: []surfaceNode{{groups: []uint32{0}}}} + + firstTriangle := oneGroup.line([3]float32{-1, 0, -1}, [3]float32{1, 0, 1}) + if !firstTriangle.hit || firstTriangle.normal != [3]float32{-1, 0, 0} { + t.Fatal("equal triangles inside one group must retain the first", firstTriangle) + } + for _, scenario := range []struct { + name string + nodes []surfaceNode + normal [3]float32 + }{ + {"stored order", []surfaceNode{{groups: []uint32{0, 1}}}, [3]float32{0, 0, -1}}, + {"reversed order", []surfaceNode{{groups: []uint32{1, 0}}}, [3]float32{-1, 0, 0}}, + {"KD split equality", []surfaceNode{{axis: 0, children: [2]int{1, 2}}, {groups: []uint32{0}}, {groups: []uint32{1}}}, [3]float32{0, 0, -1}}, + } { + t.Run(scenario.name, func(t *testing.T) { + tree := &surfaceTree{vertices: vertices, groups: append([]surfaceGroup(nil), groups...), nodes: scenario.nodes} + contact := tree.line([3]float32{-1, 0, -1}, [3]float32{1, 0, 1}) + if !contact.hit || contact.fraction != .5 || contact.normal != scenario.normal || contact.point != [3]float32{} { + t.Fatal("native cross-group tie replacement", contact) + } + }) + } +} + +func TestSceneQueriesIncludeInvisibleGeometryAndItsEqualHits(t *testing.T) { + surface := &sceneSurface{ + primary: &surfaceTree{ + vertices: [][3]float32{{0, -2, -2}, {0, -2, 2}, {0, 2, -2}}, + groups: []surfaceGroup{{bounds: [6]float32{0, -2, -2, 0, 2, 2}, triangles: [][3]uint32{{0, 1, 2}}}}, + nodes: []surfaceNode{{groups: []uint32{0}}}, + }, + invisible: &surfaceTree{ + vertices: [][3]float32{{-2, -2, 0}, {-2, 2, 0}, {2, -2, 0}}, + groups: []surfaceGroup{{bounds: [6]float32{-2, -2, 0, 2, 2, 0}, triangles: [][3]uint32{{0, 1, 2}}}}, + nodes: []surfaceNode{{groups: []uint32{0}}}, + }, + } + + equalSphere := surface.sphere([3]float32{-.25, 0, -.25}, .5) + nearSphere := surface.sphere([3]float32{-.1, 0, -.25}, .5) + equalLine := surface.line([3]float32{-1, 0, -1}, [3]float32{1, 0, 1}) + nearLine := surface.line([3]float32{-.25, -.75, -1}, [3]float32{1, -.75, 1}) + + if !equalSphere.hit || equalSphere.normal != [3]float32{0, 0, -1} || !equalLine.hit || equalLine.normal != [3]float32{0, 0, -1} { + t.Fatal("extra invisible geometry must win exact distance ties", equalSphere, equalLine) + } + if !nearSphere.hit || nearSphere.normal != [3]float32{-1, 0, 0} || !nearLine.hit || nearLine.normal != [3]float32{-1, 0, 0} { + t.Fatal("strictly nearer primary geometry must replace invisible geometry", nearSphere, nearLine) + } +} + +func TestSurfaceLineFloorAndSphereShareLazyCoefficients(t *testing.T) { + tree := &surfaceTree{ + vertices: [][3]float32{{0, 0, 0}, {0, 0, 2}, {0, 2, 0}, {-2, 0, -2}, {-2, 0, 2}, {2, 0, -2}}, + groups: []surfaceGroup{ + {bounds: [6]float32{0, 0, 0, 0, 2, 2}, triangles: [][3]uint32{{0, 1, 2}}}, + {bounds: [6]float32{-2, 0, -2, 2, 0, 2}, triangles: [][3]uint32{{3, 4, 5}}}, + }, + nodes: []surfaceNode{{groups: []uint32{0, 1}}}, + } + var workers sync.WaitGroup + results := make(chan [3]bool, 16) + + for range 16 { + workers.Add(1) + go func() { + defer workers.Done() + sphere := tree.sphere([3]float32{-.25, .5, .5}, .5) + line := tree.line([3]float32{-1, .5, .5}, [3]float32{1, .5, .5}) + floor := tree.floor([3]float32{-.5, 1, -.5}, 2) + results <- [3]bool{sphere.hit && sphere.distance == .25, line.hit && line.fraction == .5, floor.hit && floor.point[1] == 0} + }() + } + workers.Wait() + close(results) + + for result := range results { + if result != [3]bool{true, true, true} { + t.Fatal("concurrent shared geometry queries", result) + } + } +} + +func TestSurfaceFloorKeepsNativeBoundAndMissSemantics(t *testing.T) { + tree := &surfaceTree{ + vertices: [][3]float32{{-2, 1.8, -2}, {-2, 1.8, 2}, {2, 1.8, -2}}, + groups: []surfaceGroup{{bounds: [6]float32{-2, 1.8, -2, 2, 1.8, 2}, triangles: [][3]uint32{{0, 1, 2}}}}, + nodes: []surfaceNode{{groups: []uint32{0}}}, + } + + for _, scenario := range []struct { + name string + origin [3]float32 + bound float32 + hit bool + y float32 + fraction float32 + }{ + {"ordinary floor", [3]float32{0, 2, -.5}, 2, true, 1.8, .100000024}, + {"mixed scalar gate", [3]float32{0, 2, -.5}, .25, false, 0, 0}, + {"endpoint excluded", [3]float32{0, 2.8, -.5}, 1, false, 0, 0}, + {"outside group", [3]float32{4, 2, -.5}, 2, false, 0, 0}, + {"below floor", [3]float32{0, 1, -.5}, 2, false, 0, 0}, + } { + t.Run(scenario.name, func(t *testing.T) { + contact := tree.floor(scenario.origin, scenario.bound) + if contact.hit != scenario.hit || contact.point != [3]float32{scenario.origin[0], scenario.y, scenario.origin[2]} || contact.normal != [3]float32{0, 1, 0} { + t.Fatal("native floor result or zero-height miss", contact) + } + if contact.hit && math.Abs(float64(contact.fraction-scenario.fraction)) > .0000001 { + t.Fatal("native floor scalar", contact.fraction) + } + }) + } +} + +func TestSurfaceLineAndFloorFindShippedWallAndRoof(t *testing.T) { + database, err := readGameDatabase(assets.Files) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { database.file.Close() }) + payload, version, err := database.read(1000013, 46203264) + if err != nil { + t.Fatal(err) + } + surface, err := decodeSceneSurface(payload, version) + if err != nil { + t.Fatal(err) + } + + wall := surface.line([3]float32{970, 17.5, 520.2}, [3]float32{975, 17.5, 520.2}) + roof := surface.primary.floor([3]float32{972.2, 22, 520.2}, 6) + + if !wall.hit || wall.normal != [3]float32{-1, 0, 0} || math.Abs(float64(wall.point[0]-971.9442138671875)) > .0001 { + t.Fatal("shipped building directed wall", wall) + } + if !roof.hit || math.Abs(float64(roof.normal[1]-.98302039306738)) > .000001 || math.Abs(float64(roof.normal[2]+.18349634005520044)) > .000001 || math.Abs(float64(roof.point[1]-21.192259481797624)) > .0001 { + t.Fatal("shipped building roof floor selection", roof) + } +} diff --git a/server/surface_sphere.go b/server/surface_sphere.go @@ -20,12 +20,16 @@ func surfaceDot(first, second [3]float32) float64 { return float64(first[0])*float64(second[0]) + float64(first[1])*float64(second[1]) + float64(first[2])*float64(second[2]) } -func surfaceNormal(first, second [3]float32) [3]float32 { - normal := [3]float32{ +func surfaceCross(first, second [3]float32) [3]float32 { + return [3]float32{ float32(float64(first[1])*float64(second[2]) - float64(first[2])*float64(second[1])), float32(float64(first[2])*float64(second[0]) - float64(first[0])*float64(second[2])), float32(float64(first[0])*float64(second[1]) - float64(first[1])*float64(second[0])), } +} + +func surfaceNormal(first, second [3]float32) [3]float32 { + normal := surfaceCross(first, second) length := math.Sqrt(surfaceDot(normal, normal)) if length == 0 { return [3]float32{0, 1, 0} @@ -151,7 +155,7 @@ func surfaceOverlap(bounds [6]float32, center [3]float32, radius float32) bool { return true } -func (tree *surfaceTree) sphere(center [3]float32, radius float32) surfaceContact { +func (tree *surfaceTree) initialize() { // Lazy coefficients are immutable after construction, including authored bounds. tree.prepare.Do(func() { for index := range tree.groups { @@ -181,6 +185,32 @@ func (tree *surfaceTree) sphere(center [3]float32, radius float32) surfaceContac } } }) +} + +func (surface *sceneSurface) sphere(center [3]float32, radius float32) surfaceContact { + if surface.primary == nil { + return surfaceContact{} + } + // Resource sphere checks include invisible geometry; the camera-only scope is separate. + // Source: client/game/llr.dll/lifted-0021.c, sub_38037D20. + invisible := surfaceContact{} + if surface.invisible != nil { + invisible = surface.invisible.sphere(center, radius) + } + primary := surface.primary.sphere(center, radius) + if !invisible.hit || primary.hit && surfaceDistanceSquared(center, primary.point) < surfaceDistanceSquared(center, invisible.point) { + return primary + } + return invisible +} + +func surfaceDistanceSquared(first, second [3]float32) float64 { + difference := [3]float32{first[0] - second[0], first[1] - second[1], first[2] - second[2]} + return surfaceDot(difference, difference) +} + +func (tree *surfaceTree) sphere(center [3]float32, radius float32) surfaceContact { + tree.initialize() return tree.nodeSphere(0, center, radius, radius) } diff --git a/server/terrain.go b/server/terrain.go @@ -78,3 +78,41 @@ func (ground *terrain) elevation(x, z float32) (float32, bool) { } return bottomRight + (1-x)*(bottomLeft-bottomRight) + (1-z)*(topRight-bottomRight), true } + +func (ground *terrain) corners(column, row int) [4][3]float32 { + // Source: client/game/llr.dll/lifted-0021.c, sub_38038370. + nextColumn, nextRow := min(column+1, ground.boundsWidth-1), min(row+1, ground.boundsHeight-1) + x, z := float32(column)*ground.spacing, float32(row)*ground.spacing + return [4][3]float32{ + {x, float32(ground.heights[row*(ground.width+1)+column]) * ground.scale, z}, + {x + ground.spacing, float32(ground.heights[row*(ground.width+1)+nextColumn]) * ground.scale, z}, + {x + ground.spacing, float32(ground.heights[nextRow*(ground.width+1)+nextColumn]) * ground.scale, z + ground.spacing}, + {x, float32(ground.heights[nextRow*(ground.width+1)+column]) * ground.scale, z + ground.spacing}, + } +} + +func (ground *terrain) sample(x, z float32) (float32, [3]float32, bool) { + height, inside := ground.elevation(x, z) + if !inside { + return 0, [3]float32{}, false + } + column, row := int(x/ground.spacing), int(z/ground.spacing) + u, v := x/ground.spacing-float32(column), z/ground.spacing-float32(row) + indices := [3]int{0, 2, 3} + if (column+row)&1 == 0 { + if u > v { + indices = [3]int{0, 1, 2} + } + } else if u+v <= 1 { + indices = [3]int{0, 1, 3} + } else { + indices = [3]int{1, 2, 3} + } + corners := ground.corners(column, row) + var first, second [3]float32 + for axis := range 3 { + first[axis] = corners[indices[1]][axis] - corners[indices[0]][axis] + second[axis] = corners[indices[2]][axis] - corners[indices[0]][axis] + } + return height, surfaceNormal(second, first), true +} diff --git a/server/terrain_line.go b/server/terrain_line.go @@ -0,0 +1,110 @@ +package main + +import "math" + +type gridLine struct { + cell, step [2]int + next, interval [2]float32 + remaining int +} + +func newGridLine(start, delta [2]float64, end [2]int) gridLine { + // Sources: client/game/qqr.dll/lifted-0005.c, sub_4200F990; + // client/game/llr.dll/lifted-0023.c, sub_3803B970. Callers preserve their own spills. + line := gridLine{cell: [2]int{int(start[0]), int(start[1])}, remaining: 1} + for axis := range 2 { + distance := end[axis] - line.cell[axis] + if distance < 0 { + distance = -distance + } + line.remaining += distance + line.step[axis] = 1 + fraction := math.Floor(start[axis]) + 1 - start[axis] + if delta[axis] < 0 { + line.step[axis] = -1 + fraction = start[axis] - math.Floor(start[axis]) + } + line.interval[axis] = float32(float64(line.step[axis]*100) / delta[axis]) + line.next[axis] = float32(fraction * float64(line.interval[axis])) + } + return line +} + +func (line *gridLine) advance() { + line.remaining-- + if line.remaining == 0 { + return + } + axis := 0 + if line.next[0] >= line.next[1] { + axis = 1 + } + line.cell[axis] += line.step[axis] + line.next[axis] += line.interval[axis] +} + +func (ground *terrain) line(origin, end, delta [3]float32) surfaceIntersection { + // Source: client/game/llr.dll/lifted-0023.c, sub_3803B970. + start := [2]float64{float64(origin[0] / ground.spacing), float64(origin[2] / ground.spacing)} + endX, endZ := float64(end[0])/float64(ground.spacing), end[2]/ground.spacing + travel := [2]float64{endX - start[0], float64(float32(endZ - float32(start[1])))} + for cells := newGridLine(start, travel, [2]int{int(endX), int(endZ)}); cells.remaining > 0; cells.advance() { + column, row := cells.cell[0], cells.cell[1] + if column < 0 || column >= ground.boundsWidth || row < 0 || row >= ground.boundsHeight { + continue + } + contact := ground.tileLine(column, row, origin, end, delta) + if contact.hit && surfaceDistanceSquared(contact.point, origin) < surfaceDistanceSquared(end, origin) { + return contact + } + } + return surfaceIntersection{} +} + +func (ground *terrain) tileLine(column, row int, origin, end, delta [3]float32) surfaceIntersection { + // Source: client/game/llr.dll/lifted-0023.c, sub_3803C220/3803C6B0. + corners := ground.corners(column, row) + maximum := max(corners[0][1], corners[1][1], corners[2][1], corners[3][1]) + if origin[1] > maximum && end[1] > maximum { + return surfaceIntersection{} + } + triangles := [2][3]int{{0, 1, 2}, {2, 3, 0}} + if (column+row)&1 != 0 { + triangles = [2][3]int{{0, 1, 3}, {1, 2, 3}} + } + for index, vertices := range triangles { + var first, second, toOrigin [3]float32 + for axis := range 3 { + first[axis] = corners[vertices[1]][axis] - corners[vertices[0]][axis] + second[axis] = corners[vertices[2]][axis] - corners[vertices[0]][axis] + toOrigin[axis] = corners[vertices[0]][axis] - origin[axis] + } + normal := surfaceCross(first, second) + denominator := surfaceDot(delta, normal) + if !(denominator > 0) { + continue + } + fraction := surfaceDot(toOrigin, normal) / float64(float32(denominator)) + if (column+row)&1 == 0 && index == 0 { + fraction = float64(float32(fraction)) + } + var point [3]float32 + for axis := range 3 { + product := float32(float64(delta[axis]) * fraction) + point[axis] = origin[axis] + product + } + var fromFirst, fromSecond, fromThird, lastEdge [3]float32 + for axis := range 3 { + fromFirst[axis] = point[axis] - corners[vertices[0]][axis] + fromSecond[axis] = point[axis] - corners[vertices[1]][axis] + fromThird[axis] = point[axis] - corners[vertices[2]][axis] + lastEdge[axis] = corners[vertices[2]][axis] - corners[vertices[1]][axis] + } + cross := surfaceCross(first, fromFirst) + if surfaceDot(cross, surfaceCross(lastEdge, fromSecond)) < float64(float32(-.0005)) || surfaceDot(cross, surfaceCross(fromThird, second)) < float64(float32(-.0005)) { + continue + } + return surfaceIntersection{point: point, normal: surfaceNormal(second, first), fraction: float32(fraction), hit: true} + } + return surfaceIntersection{} +} diff --git a/server/terrain_line_test.go b/server/terrain_line_test.go @@ -0,0 +1,103 @@ +package main + +import ( + "math" + "slices" + "testing" +) + +func TestGridLinePreservesNativeCellVisitation(t *testing.T) { + for _, scenario := range []struct { + name string + start, delta [2]float64 + end [2]int + cells [][2]int + }{ + {"diagonal", [2]float64{.5, .5}, [2]float64{2, 2}, [2]int{2, 2}, [][2]int{{0, 0}, {0, 1}, {1, 1}, {1, 2}, {2, 2}}}, + {"reverse", [2]float64{2.5, 2.5}, [2]float64{-2, -2}, [2]int{0, 0}, [][2]int{{2, 2}, {2, 1}, {1, 1}, {1, 0}, {0, 0}}}, + {"one axis", [2]float64{.5, .5}, [2]float64{0, 2}, [2]int{0, 2}, [][2]int{{0, 0}, {0, 1}, {0, 2}}}, + {"stationary", [2]float64{.5, .5}, [2]float64{}, [2]int{0, 0}, [][2]int{{0, 0}}}, + {"negative fractional start", [2]float64{-.5, .5}, [2]float64{2, 0}, [2]int{1, 0}, [][2]int{{0, 0}, {1, 0}}}, + } { + t.Run(scenario.name, func(t *testing.T) { + var visited [][2]int + for line := newGridLine(scenario.start, scenario.delta, scenario.end); line.remaining > 0; line.advance() { + visited = append(visited, line.cell) + } + + if !slices.Equal(visited, scenario.cells) { + t.Fatal("native Z-first crossing ties or truncation", visited) + } + }) + } +} + +func TestTerrainLineUsesNativeTriangleOrderAndNormals(t *testing.T) { + ground := &terrain{width: 3, height: 3, boundsWidth: 3, boundsHeight: 3, spacing: 4, scale: 1, + heights: []byte{0, 0, 0, 99, 0, 4, 0, 99, 0, 0, 0, 99, 99, 99, 99, 99}} + + for _, scenario := range []struct { + name string + x, z, height float32 + normal [3]float32 + }{ + {"AC first half", 3, .5, .5, [3]float32{0, .70710677, -.70710677}}, + {"AC second half", .5, 3, .5, [3]float32{-.70710677, .70710677, 0}}, + {"AC ray tie uses first half", 2, 2, 2, [3]float32{0, .70710677, -.70710677}}, + {"BD first half", 4.5, .5, .5, [3]float32{0, .70710677, -.70710677}}, + {"BD second half", 7.5, 3.5, .5, [3]float32{.70710677, .70710677, 0}}, + {"repeated far samples", 11.75, 11.75, 0, [3]float32{0, 1, 0}}, + } { + t.Run(scenario.name, func(t *testing.T) { + origin, end := [3]float32{scenario.x, 10, scenario.z}, [3]float32{scenario.x, -10, scenario.z} + contact := ground.line(origin, end, [3]float32{0, -20, 0}) + if !contact.hit || math.Abs(float64(contact.point[1]-scenario.height)) > .000001 { + t.Fatal("native terrain plane intersection", contact) + } + for axis := range 3 { + if math.Abs(float64(contact.normal[axis]-scenario.normal[axis])) > .000001 { + t.Fatal("native terrain triangle normal", contact.normal) + } + } + }) + } +} + +func TestTerrainLinePreservesDistanceAndDirectionGates(t *testing.T) { + ground := &terrain{width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 4, scale: 1, heights: make([]byte, 9)} + + for _, scenario := range []struct { + name string + start, end float32 + hit bool + }{ + {"downward", 1, -1, true}, + {"endpoint excluded", 1, 0, false}, + {"upward excluded", -1, 1, false}, + {"both above tile", 2, 1, false}, + {"short behind-origin hit", -.5, -2, true}, + {"distant behind-origin miss", -2, -2.5, false}, + } { + t.Run(scenario.name, func(t *testing.T) { + contact := ground.line([3]float32{2, scenario.start, 2}, [3]float32{2, scenario.end, 2}, [3]float32{0, scenario.end - scenario.start, 0}) + if contact.hit != scenario.hit || contact.hit && contact.point != [3]float32{2, 0, 2} { + t.Fatal("terrain direction or strict unsigned distance gate", contact) + } + }) + } +} + +func TestTerrainSampleKeepsPhysicalNormalAtDiagonalTie(t *testing.T) { + ground := &terrain{width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 4, scale: 1, + heights: []byte{0, 0, 99, 0, 4, 99, 99, 99, 99}} + + height, normal, inside := ground.sample(2, 2) + _, outsideNormal, outside := ground.sample(8, 2) + + if !inside || height != 2 || math.Abs(float64(normal[0]+.70710677)) > .000001 || math.Abs(float64(normal[1]-.70710677)) > .000001 || normal[2] != 0 { + t.Fatal("height query uses its own second-half tie normal", height, normal, inside) + } + if outside || outsideNormal != [3]float32{} { + t.Fatal("outside terrain must not invent a valid normal", outsideNormal, outside) + } +}