aorecomp

Anarchy Online classic in the browser

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


commit 9cbfef5b96e43b0415a8628b58fccb33941f7edb
parent 14d1907e12db140daefb39fe216623ffbcf86efb
Author: anon <anon@example.com>
Date:   Tue, 27 Oct 2026 18:14:38 +0000

Build placed mission-room collision and floor queries

Diffstat:
MTODO.md | 9+++++++--
Mdocs/mission-interiors.md | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/dungeon_rooms.go | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/mission_geometry.go | 13++++++++++---
Aserver/mission_scene.go | 254+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/mission_scene_test.go | 432+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 903 insertions(+), 5 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -1535,8 +1535,13 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). The Go server now decodes the original dungeon tile, floor and ceiling grids and archived tileset heights from all four libraries. Independent decoding verifies every grid byte; a published-WASM fixture also matches all three - library330 grids byte for byte. Connect transformed room collision, floor - sampling and walkable/ceiling admission before enabling private entry. + library330 grids byte for byte. The placed-room physics backend now reads all + 298 original room records, shares immutable meshes, and implements rotated + sphere/segment queries, fixed-diagonal floor sampling and tile/ceiling lookup. + Four connected-layout rotations match native room anchors, source poses, + reciprocal links and standing floor height. Route this backend through live + movement and enforce room transitions before enabling private entry; this + verification does not establish native equivalence for every query or slope. Resolve why library330 tileset types0/1 load as zero in WASM despite archived height words65535; preserve raw data until the producer is established. This is not usable entry, recovered style selection or a private-world boundary. diff --git a/docs/mission-interiors.md b/docs/mission-interiors.md @@ -309,3 +309,75 @@ reader. Native room queries select one containing room and transform queries into its template coordinates (`0x100364c0`/`0x10036780`), rather than combining all room meshes indiscriminately. These static observations still require a server integration and native comparison of placed query results. + +## Placed-room physics backend + +`dungeon_rooms.go` reads all298 original room records directly from the bundled +archive. Tests compare every retained atlas bound, source pose, orientation, +door binding, liquid-presence flag and floor baseline with independent Python +room parsing and PNG decoding. Room parsing rejects malformed headers, counts, +lightmaps, water/camera framing, bounds and nonfinite positions. The suffix +beyond the base room list remains outside this physics reader. + +`mission_scene.go` builds immutable placed rooms over the existing shared +surface cache. The generator and physics builder share field validation. +Placement follows `KKR:0x100f5540`/`0x100f5e10`: reverse building Z, rotate the +room anchor, swap quarter-turned dimensions, and normalize signed floors against +the lowest assigned floor. Building dimensions and room-template references +must be valid; rooms with liquids are rejected until liquid physics is connected. +This builder does not yet validate complete topology or choose authored portals. + +Room membership follows `LLR:0x100326e0`/`0x10031910`: rotate into the placed +tile grid, reject empty cells, and compare Y with the local floor and ceiling. +Mesh queries instead rotate by the difference between placed and original +orientations. Keeping these transformations distinct supports both the grid +and original template-world collision coordinates. Sphere queries use the +containing room; segment queries use the start room or fall back to the end +room, query that mesh, then use the start point's floor plane after a mesh miss. + +Floor projection combines the tile grid's fixed diagonal with the original +KD-tree's one-unit downward probe. The native KD-tree wrapper `0x100460f0` +takes this bound from the initialized upward normal, rather than the query's +height above zero. The room wrapper transforms the mesh contact point while +retaining its returned normal; grid normals rotate with the placed room. +The resulting floor height is clamped to0.001..1999.9. Go tests cover both +nonplanar tile triangles, rotated grid normals, near/distant/empty mesh floors, +mesh walls, segment fallback, stacked rooms and concurrent instances sharing +meshes while keeping separate placements. This is source-derived behavior; +the native comparisons below do not establish every sloped-contact result. + +Published-WASM fixtures290..293 load the connected room0/room37 layout at all +four rotations. Read-only capture matches the Go anchors within0.00005 units, +original source poses, reciprocal links and exactly one exterior portal. +All four characters settle at Y0.011, consistent with the sampled floor0.001 +plus the native standing offset. Screenshots were visually reviewed, and the +owned browser contexts close before builds. No page exceptions or adapter +errors occur; these runs retain two browser console404s each without identifying +their resource URLs. No WASM source or published client artifact changes. + +These are owned client-only fixtures. The sole shared HTTPS preview continues +to run; the backend is not yet routed through live character movement. Private +assignment, immediate entry/return persistence, key admission, instance isolation, +room-transition vetoes and retirement remain open. The raw-versus-runtime +heights of library330 types0/1 also remain unresolved before live admission. + +New evidence/reproductions in `local/mission-interior/` are +`llr-room-admission-evidence.json`, `llr-room-floor-evidence.json`, +`tmp_room_physics_goldens.py`, `tmp_rotated_scenes_test.go`, +`runtime-rotation-0/` through `runtime-rotation-3/`, and +`native-rotation-verification.json`. Original room-membership evidence is +`ev_c10492347dc4e670a2642c1cb0f309840ea4cbd7bc4ade90a4bc041ebaeb0058`; +floor-baseline recovery is +`ev_668fda0e007490eea9953148c839e836e507060a7406660eaa864f46d9ebc402`; +the static-floor wrapper is +`ev_670b516889b145cb6bae76e2b8ffdf48e2249769bf7256a0e79d1a5bc3c22e77`. +All owned REA sessions are closed. + +Room physics/library/generator tests pass19 roots/396 results under the race +detector, including shared-mesh concurrent placements and the empty-primary-tree +floor fallback. The final focused suite adds a stacked-room case and passes20 +roots/397 results. The broader scene/terrain/surface/generator regression run +passes56 roots/525 results under race; that binary predates the final empty-tree +fallback, which is covered by the final focused race run. Final build and vet pass. +Logs are `final-mission-scene-race-tests.json`, `final-room-physics-race-tests.json` +and `final-mission-scene-tests.json` in the investigation directory. diff --git a/server/dungeon_rooms.go b/server/dungeon_rooms.go @@ -0,0 +1,128 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "math" +) + +type dungeonLibrary struct { + ground *dungeonTilemap + rooms []dungeonRoom +} + +type dungeonRoom struct { + bounds [4]uint16 + position [3]float32 + rotation byte + minHeight float32 + doors [][2]int16 + water bool +} + +func (geometry *sceneGeometry) dungeonLibrary(identity uint32) (*dungeonLibrary, error) { + data, _, err := geometry.database.read(1000001, identity) + if err != nil { + return nil, err + } + reader := &surfaceReader{Reader: bytes.NewReader(data)} + var header [13]uint32 + reader.read(&header) + if reader.err != nil || header[0] != 8 || header[1] != identity || header[10] == identity || header[12] == 0 || uint64(header[12])*34 > uint64(reader.Len()) { + return nil, fmt.Errorf("invalid dungeon room library %d", identity) + } + data, _, err = geometry.database.read(1000009, header[10]) + if err != nil { + return nil, err + } + ground, err := decodeDungeonTilemap(data) + if err != nil { + return nil, err + } + library := &dungeonLibrary{ground: ground, rooms: make([]dungeonRoom, header[12])} + skip := func(size uint64) { + if reader.err != nil { + return + } + if size > uint64(reader.Len()) { + reader.err = io.ErrUnexpectedEOF + return + } + reader.Seek(int64(size), io.SeekCurrent) + } + for index := range library.rooms { + // LLR n3Room_t::ReadBlob 0x10033d50: atlas bounds and template-world pose. + room := &library.rooms[index] + var flags, unused byte + var doors uint16 + reader.read(&flags) + reader.read(&unused) + reader.read(&room.bounds) + reader.read(&room.position) + reader.read(&doors) + if reader.err != nil || int(doors)*4 > reader.Len() { + return nil, fmt.Errorf("truncated dungeon room %d", index) + } + room.rotation = flags & 3 + room.doors = make([][2]int16, doors) + reader.read(room.doors) + if flags&128 != 0 { + skip(32) + } + var length, vertices uint32 + reader.read(&length) + reader.read(&vertices) + if length < 4 { + return nil, fmt.Errorf("invalid dungeon room lightmap %d", index) + } + if vertices != 0 { + skip(uint64(length - 4)) + } + + // Water polygons and camera attractors follow the optional lightmap. + var water, cameras uint32 + reader.read(&water) + if reader.err != nil || water < 1009 || water%1009 != 0 || uint64(water/1009-1)*12 > uint64(reader.Len()) { + return nil, fmt.Errorf("invalid dungeon room water %d", index) + } + room.water = water != 1009 + for count := water/1009 - 1; count > 0; count-- { + var flags, points, faces uint32 + reader.read(&flags) + reader.read(&points) + skip(uint64(points) * 12) + reader.read(&faces) + skip(uint64(faces) * 6) + } + reader.read(&cameras) + skip(uint64(cameras) * 44) + if reader.err != nil { + return nil, fmt.Errorf("dungeon room %d: %w", index, reader.err) + } + if room.bounds[0] >= room.bounds[2] || room.bounds[1] >= room.bounds[3] || int(room.bounds[2]) > ground.width || int(room.bounds[3]) > ground.depth { + return nil, fmt.Errorf("invalid dungeon room bounds %d", index) + } + for _, value := range room.position { + if math.IsNaN(float64(value)) || math.IsInf(float64(value), 0) { + return nil, fmt.Errorf("nonfinite dungeon room position %d", index) + } + } + + // LLR RDBPlayfield_t::CalculateRoomHeights 0x100416a0 ignores empty tiles. + room.minHeight = 65536 + for z := int(room.bounds[1]); z < int(room.bounds[3]); z++ { + for x := int(room.bounds[0]); x < int(room.bounds[2]); x++ { + cell := z*ground.width + x + kind := ground.tiles[cell] & 127 + if kind == 0 { + continue + } + height := float32(ground.floors[cell]) * ground.scale + room.minHeight = min(room.minHeight, height) + } + } + } + // Resource extensions after the base room list are not part of room physics. + return library, nil +} diff --git a/server/mission_geometry.go b/server/mission_geometry.go @@ -20,17 +20,24 @@ type missionLayout struct { rooms []missionRoom } -func missionPlayfieldPacket(player *character, layout missionLayout) ([]byte, error) { +func (layout missionLayout) validate() error { // KKR 14.9.1 0x100f1850 / 0x100f5e80: serialized generator and room fields. if layout.template == 0 || layout.width == 0 || layout.depth == 0 || layout.floorHeight == 0 || layout.floorHeight > 1000 || len(layout.rooms) == 0 || len(layout.rooms) > 10000 { - return nil, fmt.Errorf("invalid mission building dimensions or room count") + return fmt.Errorf("invalid mission building dimensions or room count") } for _, room := range layout.rooms { if room.template > 10000 || room.floor < -16 || room.floor > 16 || room.x > 32 || room.z > 32 || room.rotation > 3 { - return nil, fmt.Errorf("invalid mission building room") + return fmt.Errorf("invalid mission building room") } } + return nil +} + +func missionPlayfieldPacket(player *character, layout missionLayout) ([]byte, error) { + if err := layout.validate(); err != nil { + return nil, err + } // Model 51105 selects the generated-building factory; running identity is separate. body := binary.BigEndian.AppendUint32(nil, 4) diff --git a/server/mission_scene.go b/server/mission_scene.go @@ -0,0 +1,254 @@ +package main + +import ( + "fmt" + "math" +) + +type missionScene struct { + ground *dungeonTilemap + rooms []placedRoom +} + +type placedRoom struct { + template *dungeonRoom + position [3]float32 + rotation byte + surface *sceneSurface +} + +func roomRotate(point [3]float32, turns byte) [3]float32 { + switch turns & 3 { + case 1: + return [3]float32{point[2], point[1], -point[0]} + case 2: + return [3]float32{-point[0], point[1], -point[2]} + case 3: + return [3]float32{-point[2], point[1], point[0]} + } + return point +} + +func (geometry *sceneGeometry) missionScene(layout missionLayout) (*missionScene, error) { + if err := layout.validate(); err != nil { + return nil, err + } + if layout.template > math.MaxUint16 { + return nil, fmt.Errorf("dungeon library identity exceeds surface namespace") + } + library, err := geometry.dungeonLibrary(layout.template) + if err != nil { + return nil, err + } + scene := &missionScene{ground: library.ground, rooms: make([]placedRoom, len(layout.rooms))} + minimum := layout.rooms[0].floor + for _, room := range layout.rooms { + minimum = min(minimum, room.floor) + } + for index, placement := range layout.rooms { + if int(placement.template) >= len(library.rooms) { + return nil, fmt.Errorf("unknown dungeon room %d", placement.template) + } + room := &scene.rooms[index] + room.template, room.rotation = &library.rooms[placement.template], placement.rotation + if room.template.water { + return nil, fmt.Errorf("dungeon room %d requires liquid physics", placement.template) + } + width := int(room.template.bounds[2] - room.template.bounds[0]) + depth := int(room.template.bounds[3] - room.template.bounds[1]) + if width%5 != 0 || depth%5 != 0 { + return nil, fmt.Errorf("dungeon room dimensions are not multiples of five") + } + spacing := library.ground.spacing + rotatedWidth, rotatedDepth := width, depth + if room.rotation&1 != 0 { + rotatedWidth, rotatedDepth = depth, width + } + x := float32(placement.x) * 10 + z := float32(layout.depth)*10 - float32(placement.z)*10 - float32(rotatedDepth)*spacing + if z < 0 || x+float32(rotatedWidth)*spacing > float32(layout.width)*10 { + return nil, fmt.Errorf("dungeon room %d lies outside building", index) + } + + // KKR CreateDungeonRoom 0x100f5540/0x100f5e10: rotate the room anchor. + anchor := [3]float32{float32(((width-1)&^1)+1)*.5*spacing + 1, 0, float32(((depth-1)&^1)+1)*.5*spacing + 1} + anchor = roomRotate(anchor, room.rotation) + switch room.rotation { + case 1: + anchor[2] += float32(width) * spacing + case 2: + anchor[0] += float32(width) * spacing + anchor[2] += float32(depth) * spacing + case 3: + anchor[0] += float32(depth) * spacing + } + room.position = [3]float32{x + anchor[0], float32(int(placement.floor)-int(minimum))*float32(layout.floorHeight) + room.template.position[1], z + anchor[2]} + room.surface = geometry.surface(layout.template<<16 | uint32(placement.template)) + if room.surface == nil { + return nil, fmt.Errorf("missing dungeon room surface %d", placement.template) + } + } + return scene, nil +} + +func (room *placedRoom) templatePoint(point [3]float32) [3]float32 { + // LLR n3Room_t::CalcTemplatePosFromGlobalPos 0x10033320. + for axis := range point { + point[axis] -= room.position[axis] + } + point = roomRotate(point, room.template.rotation-room.rotation) + for axis := range point { + point[axis] += room.template.position[axis] + } + return point +} + +func (room *placedRoom) globalPoint(point [3]float32) [3]float32 { + // LLR n3Room_t::CalcGlobalFromTemplatePos 0x100333f0. + for axis := range point { + point[axis] -= room.template.position[axis] + } + point = roomRotate(point, room.rotation-room.template.rotation) + for axis := range point { + point[axis] += room.position[axis] + } + return point +} + +func (scene *missionScene) roomAt(point [3]float32) *placedRoom { + // LLR GetTilemapIndexFromPos 0x100326e0 / IsPosInside 0x10031910. + for index := range scene.rooms { + room := &scene.rooms[index] + local := room.tilePoint(point, scene.ground.spacing) + width := int(room.template.bounds[2] - room.template.bounds[0]) + depth := int(room.template.bounds[3] - room.template.bounds[1]) + x := int(math.Floor(float64(local[0] / scene.ground.spacing))) + z := int(math.Floor(float64(local[2] / scene.ground.spacing))) + if x < 0 || x >= width || z < 0 || z >= depth { + continue + } + x, z = x+int(room.template.bounds[0]), z+int(room.template.bounds[1]) + cell := z*scene.ground.width + x + kind := scene.ground.tiles[cell] & 127 + if kind == 0 { + continue + } + floor := min(scene.ground.floors[cell], scene.ground.floors[z*scene.ground.width+max(x-1, 0)], + scene.ground.floors[max(z-1, 0)*scene.ground.width+x], scene.ground.floors[max(z-1, 0)*scene.ground.width+max(x-1, 0)]) + height := float32(floor)*scene.ground.scale - room.template.minHeight + room.position[1] + ceiling := (float32(int(scene.ground.ceilings[cell])-32)*scene.ground.scale*.25+1)*scene.ground.tilesetHeights[kind] + height + if point[1] >= height-.5 && point[1] <= ceiling+.5 { + return room + } + } + return nil +} + +func (room *placedRoom) tilePoint(point [3]float32, spacing float32) [3]float32 { + // Grid lookup rotates by the placed orientation, independently of mesh orientation. + for axis := range point { + point[axis] -= room.position[axis] + } + point = roomRotate(point, -room.rotation) + width := int(room.template.bounds[2] - room.template.bounds[0]) + depth := int(room.template.bounds[3] - room.template.bounds[1]) + point[0] += float32(((width-1)&^1)+1)*.5*spacing + 1 + point[2] += float32(((depth-1)&^1)+1)*.5*spacing + 1 + return point +} + +func (scene *missionScene) sphere(center [3]float32, radius float32) surfaceContact { + // LLR n3RoomSurface_t::GetSphereIntersection 0x10036780. + room := scene.roomAt(center) + if room == nil { + return surfaceContact{} + } + contact := room.surface.sphere(room.templatePoint(center), radius) + if contact.hit { + contact.point = room.globalPoint(contact.point) + contact.normal = roomRotate(contact.normal, room.rotation-room.template.rotation) + } + return contact +} + +func (scene *missionScene) floor(origin [3]float32, point, normal *[3]float32) { + // LLR n3RoomSurface_t::CalculateClosestPoint 0x10035a90. + room := scene.roomAt(origin) + if room == nil { + *point = [3]float32{origin[0], 0, origin[2]} + return + } + template := room.templatePoint(origin) + // The KD-tree probe uses the initialized upward normal as its one-unit bound. + static := surfaceIntersection{point: [3]float32{template[0], 0, template[2]}, normal: [3]float32{0, 1, 0}} + if room.surface.primary != nil { + static = room.surface.primary.floor(template, 1) + } + // The native room wrapper transforms the mesh point and retains its returned normal. + *point, *normal = room.globalPoint(static.point), static.normal + + // Dungeon floor vertices straddle the selected tile; every cell uses the same diagonal. + spacing := scene.ground.spacing + local := room.tilePoint(origin, spacing) + x, z := int(math.Floor(float64(local[0]/spacing))), int(math.Floor(float64(local[2]/spacing))) + u, v := local[0]/spacing-float32(x), local[2]/spacing-float32(z) + x, z = x+int(room.template.bounds[0]), z+int(room.template.bounds[1]) + var corners [4][3]float32 + for index, offset := range [4][2]int{{-1, -1}, {0, -1}, {0, 0}, {-1, 0}} { + cell := max(z+offset[1], 0)*scene.ground.width + max(x+offset[0], 0) + corners[index] = [3]float32{float32(offset[0]+1) * spacing, + float32(scene.ground.floors[cell])*scene.ground.scale - room.template.minHeight, + float32(offset[1]+1) * spacing} + } + indices := [3]int{0, 1, 2} + height := corners[0][1] + u*(corners[1][1]-corners[0][1]) + v*(corners[2][1]-corners[1][1]) + if u <= v { + indices = [3]int{0, 2, 3} + height = corners[0][1] + u*(corners[2][1]-corners[3][1]) + v*(corners[3][1]-corners[0][1]) + } + height += room.position[1] + if height > point[1] { + 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] + } + *point = [3]float32{origin[0], height, origin[2]} + *normal = roomRotate(surfaceNormal(second, first), room.rotation) + } + point[1] = max(float32(.001), min(point[1], float32(1999.9))) +} + +func (scene *missionScene) line(origin, end [3]float32) surfaceIntersection { + // LLR n3RoomSurface_t::GetLineIntersection 0x100364c0 selects one endpoint room. + room := scene.roomAt(origin) + if room == nil { + room = scene.roomAt(end) + } + if room == nil { + return surfaceIntersection{} + } + contact := room.surface.line(room.templatePoint(origin), room.templatePoint(end)) + if contact.hit { + contact.point = room.globalPoint(contact.point) + contact.normal = roomRotate(contact.normal, room.rotation-room.template.rotation) + return contact + } + + // A mesh miss falls back to the floor plane sampled at the original start point. + var point, normal [3]float32 + scene.floor(origin, &point, &normal) + delta := [3]float32{end[0] - origin[0], end[1] - origin[1], end[2] - origin[2]} + denominator := surfaceDot(delta, normal) + if denominator == 0 { + return surfaceIntersection{} + } + fraction := float32(surfaceDot([3]float32{point[0] - origin[0], point[1] - origin[1], point[2] - origin[2]}, normal) / denominator) + if !(fraction >= 0 && fraction < 1) { + return surfaceIntersection{} + } + for axis := range point { + point[axis] = origin[axis] + delta[axis]*fraction + } + return surfaceIntersection{point: point, normal: normal, fraction: fraction, hit: true} +} diff --git a/server/mission_scene_test.go b/server/mission_scene_test.go @@ -0,0 +1,432 @@ +package main + +import ( + "ao/server/assets" + "bytes" + "crypto/sha256" + "encoding/binary" + "fmt" + "math" + "os" + "sync" + "testing" +) + +func missionGeometryFixture(t *testing.T) *sceneGeometry { + t.Helper() + database, err := readGameDatabase(assets.Files) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { database.file.Close() }) + return &sceneGeometry{database: database, surfaces: make(map[uint32]*sceneSurface)} +} + +func TestMissionSceneSamplesDungeonTrianglesAndRotatesGridNormals(t *testing.T) { + geometry := missionGeometryFixture(t) + ground := &dungeonTilemap{width: 4, depth: 4, spacing: 2, scale: 1, + tiles: bytes.Repeat([]byte{1}, 16), floors: make([]byte, 16), ceilings: bytes.Repeat([]byte{32}, 16), tilesetHeights: []float32{0, 20}} + ground.floors[0], ground.floors[1], ground.floors[4], ground.floors[5] = 1, 3, 2, 7 + surface := geometry.surface(331 << 16) + for _, scenario := range []struct { + name string + rotation byte + origin [3]float32 + height float32 + normal [3]float32 + }{ + {"lower triangle", 0, [3]float32{2.5, 10, 3.5}, 3, [3]float32{-.9128709, .36514837, -.18257418}}, + {"upper triangle", 0, [3]float32{3.5, 10, 2.5}, 3.5, [3]float32{-.4082483, .4082483, -.8164966}}, + {"rotated lower triangle", 1, [3]float32{3.5, 10, 5.5}, 3, [3]float32{-.18257418, .36514837, .9128709}}, + } { + t.Run(scenario.name, func(t *testing.T) { + scene := &missionScene{ground: ground, rooms: []placedRoom{{position: [3]float32{4, 0, 4}, rotation: scenario.rotation, surface: surface, + template: &dungeonRoom{bounds: [4]uint16{0, 0, 4, 4}, position: [3]float32{10000, 0, 10000}, rotation: 1}}}} + var point, normal [3]float32 + + scene.floor(scenario.origin, &point, &normal) + + if point != [3]float32{scenario.origin[0], scenario.height, scenario.origin[2]} { + t.Fatal("dungeon fixed-diagonal floor height", point) + } + for axis := range normal { + if math.Abs(float64(normal[axis]-scenario.normal[axis])) > .000001 { + t.Fatal("placed grid slope normal", normal) + } + } + }) + } +} + +func TestMissionSceneKeepsNativeStaticFloorBoundAndUnknownRoomOutputs(t *testing.T) { + scene := &missionScene{ground: &dungeonTilemap{width: 4, depth: 4, spacing: 2, scale: 1, + tiles: bytes.Repeat([]byte{1}, 16), floors: make([]byte, 16), ceilings: bytes.Repeat([]byte{32}, 16), tilesetHeights: []float32{0, 20}}, + rooms: []placedRoom{{position: [3]float32{4, 0, 4}, template: &dungeonRoom{bounds: [4]uint16{0, 0, 4, 4}, position: [3]float32{4, 0, 4}}, surface: sceneSlopeFixture(0)}}} + var point, normal [3]float32 + + scene.floor([3]float32{2, 2.75, 2}, &point, &normal) + if point != [3]float32{2, 2, 2} || math.Abs(float64(normal[2]+.70710677)) > .000001 || math.Abs(float64(normal[1]-.70710677)) > .000001 { + t.Fatal("nearby mesh floor must beat the base tile floor", point, normal) + } + scene.floor([3]float32{2, 3.01, 2}, &point, &normal) + if point != [3]float32{2, .001, 2} || normal != [3]float32{0, 1, 0} { + t.Fatal("mesh floor beyond the native one-unit probe must miss", point, normal) + } + scene.rooms[0].surface = &sceneSurface{} + scene.floor([3]float32{2, 2.75, 2}, &point, &normal) + if point != [3]float32{2, .001, 2} || normal != [3]float32{0, 1, 0} { + t.Fatal("empty mesh must retain the tile floor", point, normal) + } + normal = [3]float32{7, 8, 9} + scene.floor([3]float32{50, 1, 50}, &point, &normal) + if point != [3]float32{50, 0, 50} || normal != [3]float32{7, 8, 9} { + t.Fatal("missing room resets only point height", point, normal) + } +} + +func TestMissionSceneQueriesOriginalWallsAndFloor(t *testing.T) { + geometry := missionGeometryFixture(t) + scene, err := geometry.missionScene(missionLayout{template: 331, width: 4, depth: 6, floorHeight: 10, + rooms: []missionRoom{{template: 0, x: 1, z: 3, rotation: 2}, {template: 37, x: 1, z: 1}}}) + if err != nil { + t.Fatal(err) + } + + wall := scene.line([3]float32{15, 1, 16}, [3]float32{20, 1, 16}) + floor := scene.line([3]float32{15, 1, 35}, [3]float32{15, -1, 35}) + outside := scene.line([3]float32{0, 1, 0}, [3]float32{5, 1, 0}) + sphere := scene.sphere([3]float32{17.1, .8, 16}, .25) + + if !wall.hit || math.Abs(float64(wall.point[0]-17.601997)) > .00001 || wall.normal != [3]float32{-1, 0, 0} { + t.Fatal("placed original entrance wall", wall) + } + if !floor.hit || math.Abs(float64(floor.point[1]-.001)) > .000001 || floor.normal != [3]float32{0, 1, 0} || outside.hit { + t.Fatal("native dungeon floor fallback or outside endpoints", floor, outside) + } + if !sphere.hit || math.Abs(float64(sphere.point[0]-17.255186)) > .00001 || math.Abs(float64(sphere.normal[0]+.7071066)) > .000001 || math.Abs(float64(sphere.normal[1]-.707107)) > .000001 { + t.Fatal("original mesh sphere contact must rotate its point and normal", sphere) + } +} + +func TestDungeonLibrariesMatchIndependentOriginalRoomDecoding(t *testing.T) { + geometry := missionGeometryFixture(t) + for _, scenario := range []struct { + identity uint32 + rooms int + hash string + }{ + {331, 42, "915a805373ab7e9c0eef6b498c329f1d342b2f549cbe08d6259f439b329b6c9c"}, + {341, 103, "ffe8298c354033050e29a4291b670faa2543cdfba3533770ca11b6fe84645ec2"}, + {346, 72, "2b543b43607515188b1d3f7c96c8375885e4f7af11d3c156430d423aaeb43500"}, + {351, 81, "5cf78291e89470ac6d50a2b650195741967e0c16f01a85b37c55ace020872311"}, + } { + t.Run(fmt.Sprint(scenario.identity), func(t *testing.T) { + library, err := geometry.dungeonLibrary(scenario.identity) + + if err != nil { + t.Fatal(err) + } + if len(library.rooms) != scenario.rooms { + t.Fatal("original room count", len(library.rooms)) + } + var fields bytes.Buffer + for _, room := range library.rooms { + binary.Write(&fields, binary.LittleEndian, room.bounds) + binary.Write(&fields, binary.LittleEndian, room.position) + fields.WriteByte(room.rotation) + binary.Write(&fields, binary.LittleEndian, room.minHeight) + binary.Write(&fields, binary.LittleEndian, room.water) + binary.Write(&fields, binary.LittleEndian, uint16(len(room.doors))) + binary.Write(&fields, binary.LittleEndian, room.doors) + } + if fmt.Sprintf("%x", sha256.Sum256(fields.Bytes())) != scenario.hash { + t.Fatal("room bounds, template pose, floor baseline, water or door bindings differ") + } + }) + } +} + +func TestMissionScenesLoadEveryDryOriginalRoomMesh(t *testing.T) { + geometry := missionGeometryFixture(t) + for _, identity := range []uint32{331, 341, 346, 351} { + library, err := geometry.dungeonLibrary(identity) + if err != nil { + t.Fatal(err) + } + for index, room := range library.rooms { + if room.water { + continue + } + t.Run(fmt.Sprintf("%d/%d", identity, index), func(t *testing.T) { + layout := missionLayout{template: identity, width: 32, depth: 32, floorHeight: 10, + rooms: []missionRoom{{template: uint16(index), x: 1, z: 1}}} + + scene, err := geometry.missionScene(layout) + + if err != nil { + t.Fatal(err) + } + if scene.rooms[0].surface.primary == nil || scene.rooms[0].position[1] != room.position[1] { + t.Fatal("original mesh or authored room elevation was lost") + } + }) + } + } +} + +func TestMissionScenePlacesTheNativeTwoRoomLayout(t *testing.T) { + geometry := missionGeometryFixture(t) + layout := missionLayout{template: 331, width: 4, depth: 6, floorHeight: 10, + rooms: []missionRoom{{template: 0, x: 1, z: 3, rotation: 2}, {template: 37, x: 1, z: 1}}} + + scene, err := geometry.missionScene(layout) + + if err != nil { + t.Fatal(err) + } + if scene.rooms[0].position != [3]float32{14, 0, 20} || scene.rooms[1].position != [3]float32{20, 0, 40} { + t.Fatal("native generated-room anchors", scene.rooms[0].position, scene.rooms[1].position) + } + if scene.rooms[0].template.position != [3]float32{24, 0, 368} || scene.rooms[1].template.position != [3]float32{212, 0, 178} { + t.Fatal("template-world surface origins must survive placement") + } + if scene.rooms[0].surface != geometry.surfaces[331<<16] || scene.rooms[1].surface != geometry.surfaces[331<<16|37] { + t.Fatal("generated rooms must share original immutable surface trees") + } +} + +func TestMissionScenePlacesEveryQuarterTurnAndNormalizesFloors(t *testing.T) { + geometry := missionGeometryFixture(t) + for _, scenario := range []struct { + rotation byte + position [3]float32 + point [3]float32 + }{ + {0, [3]float32{16, 0, 20}, [3]float32{17, 2, 23}}, + {1, [3]float32{20, 0, 24}, [3]float32{23, 2, 23}}, + {2, [3]float32{14, 0, 20}, [3]float32{13, 2, 17}}, + {3, [3]float32{20, 0, 26}, [3]float32{17, 2, 27}}, + } { + t.Run(fmt.Sprint(scenario.rotation), func(t *testing.T) { + layout := missionLayout{template: 331, width: 4, depth: 6, floorHeight: 10, + rooms: []missionRoom{{template: 0, x: 1, z: 3, rotation: scenario.rotation, floor: -2}, {template: 37, x: 1, z: 1, floor: 1}}} + + scene, err := geometry.missionScene(layout) + + if err != nil { + t.Fatal(err) + } + if scene.rooms[0].position != scenario.position || scene.rooms[1].position != [3]float32{20, 30, 40} { + t.Fatal("quarter-turn extent or normalized signed floor", scene.rooms[0].position, scene.rooms[1].position) + } + if point := scene.rooms[0].globalPoint([3]float32{25, 2, 371}); point != scenario.point { + t.Fatal("template to global point", point) + } + if point := scene.rooms[0].templatePoint(scenario.point); point != [3]float32{25, 2, 371} { + t.Fatal("global to template point", point) + } + }) + } +} + +func TestMissionSceneFindsWalkableCellsAndVerticalBounds(t *testing.T) { + geometry := missionGeometryFixture(t) + scene, err := geometry.missionScene(missionLayout{template: 331, width: 4, depth: 6, floorHeight: 10, + rooms: []missionRoom{{template: 0, x: 1, z: 3, rotation: 2}, {template: 37, x: 1, z: 1}}}) + if err != nil { + t.Fatal(err) + } + for _, scenario := range []struct { + name string + point [3]float32 + room int + }{ + {"entrance", [3]float32{15, 1, 16}, 0}, + {"chamber", [3]float32{15, 1, 35}, 1}, + {"empty corner", [3]float32{10.5, 1, 10.5}, -1}, + {"outside building", [3]float32{0, 1, 0}, -1}, + {"below floor", [3]float32{15, -.501, 35}, -1}, + {"lower vertical boundary", [3]float32{15, -.5, 35}, 1}, + {"above chamber ceiling", [3]float32{15, 5, 35}, -1}, + {"upper vertical boundary", [3]float32{15, 4.5, 35}, 1}, + } { + t.Run(scenario.name, func(t *testing.T) { + room := scene.roomAt(scenario.point) + + if scenario.room == -1 { + if room != nil { + t.Fatal("nonwalkable or vertically excluded point admitted", scenario.point) + } + } else if room != &scene.rooms[scenario.room] { + t.Fatal("wrong containing room", scenario.point) + } + }) + } +} + +func TestMissionSceneRejectsUnavailableOrIncompleteRoomAssignments(t *testing.T) { + for _, scenario := range []struct { + name string + change func(*missionLayout, *sceneGeometry) + }{ + {"missing library", func(layout *missionLayout, geometry *sceneGeometry) { layout.template = 65535 }}, + {"public map", func(layout *missionLayout, geometry *sceneGeometry) { layout.template = 705 }}, + {"surface namespace overflow", func(layout *missionLayout, geometry *sceneGeometry) { layout.template = 65536 }}, + {"unknown room", func(layout *missionLayout, geometry *sceneGeometry) { layout.rooms[0].template = 42 }}, + {"outside width", func(layout *missionLayout, geometry *sceneGeometry) { layout.width = 1 }}, + {"outside depth", func(layout *missionLayout, geometry *sceneGeometry) { layout.depth = 3 }}, + {"unsupported water", func(layout *missionLayout, geometry *sceneGeometry) { + layout.template = 341 + layout.rooms[0].template = 21 + }}, + {"missing surface", func(layout *missionLayout, geometry *sceneGeometry) { geometry.surfaces[331<<16] = nil }}, + } { + t.Run(scenario.name, func(t *testing.T) { + geometry := missionGeometryFixture(t) + layout := missionLayout{template: 331, width: 4, depth: 6, floorHeight: 10, rooms: []missionRoom{{x: 1, z: 3}}} + scenario.change(&layout, geometry) + + scene, err := geometry.missionScene(layout) + + if err == nil || scene != nil { + t.Fatal("invalid assignment produced a usable private scene", err) + } + }) + } +} + +func TestMissionSceneUsesBothTemplateAndPlacedOrientation(t *testing.T) { + room := placedRoom{position: [3]float32{14, 30, 20}, rotation: 3, + template: &dungeonRoom{position: [3]float32{100, 2, 200}, rotation: 1}} + + global := room.globalPoint([3]float32{103, 4, 205}) + template := room.templatePoint([3]float32{11, 32, 15}) + + if global != [3]float32{11, 32, 15} || template != [3]float32{103, 4, 205} { + t.Fatal("relative template rotation or vertical translation", global, template) + } +} + +func TestDungeonLibraryRejectsMalformedRoomRecords(t *testing.T) { + geometry := missionGeometryFixture(t) + original, _, err := geometry.database.read(1000001, 331) + if err != nil { + t.Fatal(err) + } + ground, _, err := geometry.database.read(1000009, 330) + if err != nil { + t.Fatal(err) + } + for _, scenario := range []struct { + name string + change func([]byte) []byte + }{ + {"short header", func(data []byte) []byte { return data[:51] }}, + {"version", func(data []byte) []byte { data[0] = 9; return data }}, + {"identity", func(data []byte) []byte { data[4]++; return data }}, + {"public map", func(data []byte) []byte { binary.LittleEndian.PutUint32(data[40:44], 331); return data }}, + {"room count", func(data []byte) []byte { binary.LittleEndian.PutUint32(data[48:52], math.MaxUint32); return data }}, + {"door count", func(data []byte) []byte { binary.LittleEndian.PutUint16(data[74:76], math.MaxUint16); return data }}, + {"lightmap length", func(data []byte) []byte { binary.LittleEndian.PutUint32(data[116:120], 3); return data }}, + {"truncated lightmap", func(data []byte) []byte { binary.LittleEndian.PutUint32(data[116:120], math.MaxUint32); return data }}, + {"water list", func(data []byte) []byte { binary.LittleEndian.PutUint32(data[653:657], 1008); return data }}, + {"camera list", func(data []byte) []byte { binary.LittleEndian.PutUint32(data[657:661], math.MaxUint32); return data }}, + {"bounds", func(data []byte) []byte { clear(data[58:60]); return data }}, + {"position", func(data []byte) []byte { + binary.LittleEndian.PutUint32(data[62:66], math.Float32bits(float32(math.NaN()))) + return data + }}, + } { + t.Run(scenario.name, func(t *testing.T) { + file, err := os.CreateTemp(t.TempDir(), "rooms") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { file.Close() }) + database := &gameDatabase{file: file, positions: make(map[[2]uint32]uint32)} + for _, record := range []struct { + identity [2]uint32 + data []byte + }{{[2]uint32{1000001, 331}, scenario.change(bytes.Clone(original))}, {[2]uint32{1000009, 330}, ground}} { + var header [34]byte + binary.LittleEndian.PutUint32(header[10:14], record.identity[0]) + binary.LittleEndian.PutUint32(header[14:18], record.identity[1]) + binary.LittleEndian.PutUint32(header[18:22], uint32(len(record.data)+12)) + database.positions[record.identity] = uint32(database.size) + if _, err := file.Write(header[:]); err != nil { + t.Fatal(err) + } + if _, err := file.Write(record.data); err != nil { + t.Fatal(err) + } + database.size += int64(34 + len(record.data)) + } + broken := &sceneGeometry{database: database} + + library, err := broken.dungeonLibrary(331) + + if err == nil || library != nil { + t.Fatal("malformed archive produced usable room geometry", err) + } + }) + } +} + +func TestMissionScenesShareMeshesWithoutSharingPlacement(t *testing.T) { + geometry := missionGeometryFixture(t) + var workers sync.WaitGroup + results := make(chan bool, 8) + + for level := range int8(8) { + workers.Add(1) + go func() { + defer workers.Done() + scene, err := geometry.missionScene(missionLayout{template: 331, width: 4, depth: 6, floorHeight: 10, + rooms: []missionRoom{{x: 1, z: 3, rotation: 2}, {template: 37, x: 1, z: 1, floor: level}}}) + if err != nil { + results <- false + return + } + var point, normal [3]float32 + scene.floor([3]float32{15, float32(level)*10 + 1, 35}, &point, &normal) + wall := scene.line([3]float32{15, 1, 16}, [3]float32{20, 1, 16}) + results <- point == [3]float32{15, max(.001, float32(level)*10), 35} && normal == [3]float32{0, 1, 0} && wall.hit && scene.rooms[1].position[1] == float32(level)*10 + }() + } + workers.Wait() + close(results) + + for passed := range results { + if !passed { + t.Fatal("concurrent scene changed another scene's floor placement") + } + } + if len(geometry.surfaces) != 2 { + t.Fatal("instances must reuse the same two immutable room meshes", len(geometry.surfaces)) + } +} + +func TestMissionSceneSelectsStackedRoomsByHeight(t *testing.T) { + geometry := missionGeometryFixture(t) + scene, err := geometry.missionScene(missionLayout{template: 331, width: 4, depth: 6, floorHeight: 10, + rooms: []missionRoom{{template: 37, x: 1, z: 1}, {template: 37, x: 1, z: 1, floor: 1}}}) + if err != nil { + t.Fatal(err) + } + var point, normal [3]float32 + + lower := scene.roomAt([3]float32{15, 1, 35}) + upper := scene.roomAt([3]float32{15, 11, 35}) + between := scene.roomAt([3]float32{15, 6, 35}) + scene.floor([3]float32{15, 11, 35}, &point, &normal) + + if lower != &scene.rooms[0] || upper != &scene.rooms[1] || between != nil { + t.Fatal("overlapping footprints must use the cell's vertical room bounds") + } + if point != [3]float32{15, 10, 35} || normal != [3]float32{0, 1, 0} { + t.Fatal("upper room floor must preserve its placed elevation", point, normal) + } + if scene.rooms[0].surface != scene.rooms[1].surface { + t.Fatal("stacked copies must share the original mesh") + } +}