commit 1150c34eec22d26dfb8758e9bbb0df3e3b1f6242
parent 7b51ff5df3754921a61c2053fd1ad1686b9eb55a
Author: anon <anon@example.com>
Date: Fri, 16 Oct 2026 20:45:53 +0000
Improve native performance and complete initial WASM scene
Optimize guest memory, x87 stack shifts, graphics lookups and selected terrain arithmetic. Add a threaded browser runtime with asset loading, audio and a WebSocket world connection.
Validated native Bronto at 59.8 FPS and Lush at 20 FPS, native regression tests and rendered pixel equivalence. Verified the optimized browser scene with movement, inventory, map, audio and matching server position. Lush performance work remains ongoing.
Diffstat:
53 files changed, 2552 insertions(+), 465 deletions(-)
diff --git a/README.md b/README.md
@@ -146,7 +146,8 @@ comes before WASM; Linux only needs windowed mode. Read [src/README.md](src/READ
C, SDL2/OpenGL, and Linux adapters. Neither build executes original game code
from external game EXE/DLL files. Keep that standalone property intact.
- Guest addresses are 32-bit identities. Windows uses its fixed address layout;
- Linux translates guest memory through `guest_pages`. Guest pointers, handles
+ 64-bit Linux uses a reserved 4 GiB guest address region, while the browser
+ translates guest memory through `guest_pages`. Guest pointers, handles
and function tokens must never be confused with host pointers. Preserve guest
layouts, calling conventions, stack cleanup, TLS, exception and callback rules.
- Linux file access resolves the game's mixed-case names through
@@ -162,15 +163,11 @@ comes before WASM; Linux only needs windowed mode. Read [src/README.md](src/READ
- Implement platform calls with meaningful behavior. Unknown calls should fail
explicitly, not return blanket fake success. The portable request to restart
the Windows launcher is deliberately a no-op at its call site.
-- Linux has rendered the world and passed movement, inventory and map checks.
- Intermittent missing terrain during turns and roughly 7 FPS versus 60 FPS on
- Windows remain reported issues. They are not established WSL limitations;
- capture consecutive frames and profile before choosing a fix.
-- Future WASM work still needs a browser graphics/input/audio/filesystem host,
- a threading/blocking-call strategy, and a WebSocket adapter. The intended
- networking approach preserves AO packets inside WebSockets, with the server
- unwrapping them before its existing protocol handlers. That adapter is not
- implemented yet. See [browser-porting.md](docs/browser-porting.md).
+- The initial WASM build includes worker-owned WebGL, shared audio mixing,
+ lazy asset loading and a WebSocket byte-stream adapter to the Go server.
+ Bronto Burger renders with movement, inventory/map, audio and a live server
+ connection in the optimized browser build. Performance and broader gameplay
+ validation remain in progress.
- Keep original binaries, assets, downloaded tools, generated reports and saved
users local. Maintained reconstructed sources belong in Git. Do not publish
proprietary game data. Preserve unrelated user edits between turns.
diff --git a/go.mod b/go.mod
@@ -2,4 +2,7 @@ module ao
go 1.24
-require go.yaml.in/yaml/v3 v3.0.5
+require (
+ github.com/coder/websocket v1.8.15
+ go.yaml.in/yaml/v3 v3.0.5
+)
diff --git a/go.sum b/go.sum
@@ -1,2 +1,4 @@
+github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
+github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
diff --git a/server/browser_assets.go b/server/browser_assets.go
@@ -2,12 +2,45 @@ package main
import (
"encoding/json"
+ "io/fs"
"net/http"
"os"
"path/filepath"
"strings"
)
+func browserManifest(w http.ResponseWriter, r *http.Request) {
+ // The browser builds a lazy filesystem from names; file bytes use range requests.
+ var listing strings.Builder
+ for _, entryPath := range []string{"cd_image", "Setupf", "fonts", "Prefs", "version.id"} {
+ err := filepath.WalkDir(filepath.Join("anarchy-assets-14.9.1", entryPath), func(path string, entry fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if entry.Type()&os.ModeSymlink != 0 {
+ return nil
+ }
+ name, err := filepath.Rel("anarchy-assets-14.9.1", path)
+ if err != nil {
+ return err
+ }
+ listing.WriteString(filepath.ToSlash(name))
+ if entry.IsDir() {
+ listing.WriteByte('/')
+ }
+ listing.WriteByte('\n')
+ return nil
+ })
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ }
+ w.Header().Set("Content-Type", "text/plain")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.Write([]byte(listing.String()))
+}
+
func browserAsset(w http.ResponseWriter, r *http.Request) {
// Resolve guest filenames without depending on the host's case sensitivity.
name := strings.ReplaceAll(r.PathValue("path"), "\\", "/")
diff --git a/server/browser_assets_test.go b/server/browser_assets_test.go
@@ -91,3 +91,25 @@ func TestBrowserAssetDirectoryRequestRejectsRegularFile(t *testing.T) {
t.Fatalf("regular file listing response: %d", response.Code)
}
}
+
+func TestBrowserManifestListsLazyAssetTree(t *testing.T) {
+ t.Chdir(t.TempDir())
+ for _, name := range []string{"cd_image", "Setupf", "fonts", "Prefs"} {
+ if err := os.MkdirAll("anarchy-assets-14.9.1/"+name, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile("anarchy-assets-14.9.1/cd_image/asset.dat", []byte("data"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile("anarchy-assets-14.9.1/version.id", []byte("14.9.1"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ response := httptest.NewRecorder()
+
+ browserManifest(response, httptest.NewRequest("GET", "/browser-manifest", nil))
+
+ if response.Code != 200 || response.Body.String() != "cd_image/\ncd_image/asset.dat\nSetupf/\nfonts/\nPrefs/\nversion.id\n" {
+ t.Fatalf("manifest: %d %q", response.Code, response.Body.String())
+ }
+}
diff --git a/server/browser_socket.go b/server/browser_socket.go
@@ -0,0 +1,23 @@
+package main
+
+import (
+ "context"
+ "log"
+ "net/http"
+
+ "github.com/coder/websocket"
+)
+
+func (server *server) browserWorld(w http.ResponseWriter, r *http.Request) {
+ socket, err := websocket.Accept(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer socket.CloseNow()
+
+ // Preserve the TCP byte stream across arbitrary binary WebSocket boundaries.
+ connection := websocket.NetConn(context.Background(), socket, websocket.MessageBinary)
+ if err := server.serveWorldConnection(connection); err != nil {
+ log.Printf("Browser world connection: %v", err)
+ }
+}
diff --git a/server/browser_socket_test.go b/server/browser_socket_test.go
@@ -0,0 +1,76 @@
+package main
+
+import (
+ "context"
+ "encoding/binary"
+ "encoding/hex"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/coder/websocket"
+)
+
+func TestBrowserWorldPreservesPacketStream(t *testing.T) {
+ world := newTestServer(t)
+ world.newCharacter()
+ host := httptest.NewServer(http.HandlerFunc(world.browserWorld))
+ defer host.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ socket, _, err := websocket.Dial(ctx, host.URL, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer socket.CloseNow()
+ cookie, _ := hex.DecodeString("dfdf00010001002000000001000000020000001b000000010000000000000000")
+ connection := websocket.NetConn(ctx, socket, websocket.MessageBinary)
+
+ // Split the AO header and body across messages, just like TCP reads.
+ for _, part := range [][]byte{cookie[:7], cookie[7:21], cookie[21:]} {
+ if err := socket.Write(ctx, websocket.MessageBinary, part); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var keys []uint32
+ for {
+ packet, err := readPacket(connection)
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := binary.BigEndian.Uint32(packet[16:20])
+ keys = append(keys, key)
+ if key == 0x5f52412e {
+ break
+ }
+ }
+
+ if len(keys) < 3 || keys[0] != 0x5f4b1a39 || keys[1] != 0x271b3a6b {
+ t.Fatalf("browser world initialization: %x", keys)
+ }
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ if world.clients[1] == nil || !world.clients[1].target {
+ t.Fatal("browser did not enter the shared 14.9.1 session handler")
+ }
+}
+
+func TestBrowserWorldRejectsUnrelatedOrigin(t *testing.T) {
+ world := newTestServer(t)
+ host := httptest.NewServer(http.HandlerFunc(world.browserWorld))
+ defer host.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ socket, response, err := websocket.Dial(ctx, host.URL, &websocket.DialOptions{
+ HTTPHeader: http.Header{"Origin": {"https://unrelated.example"}},
+ })
+ if socket != nil {
+ socket.CloseNow()
+ }
+
+ if err == nil || response.StatusCode != http.StatusForbidden {
+ t.Fatalf("origin rejection: response=%v error=%v", response, err)
+ }
+}
diff --git a/server/main.go b/server/main.go
@@ -46,6 +46,15 @@ func main() {
})
http.HandleFunc("GET /browser-assets/{path...}", browserAsset)
http.HandleFunc("POST /browser-launch", server.browserLaunch)
+ http.HandleFunc("GET /browser-world", server.browserWorld)
+ http.HandleFunc("GET /browser-manifest", browserManifest)
+ wasmFiles := http.StripPrefix("/wasm/", http.FileServer(http.Dir("src/build/wasm/web")))
+ http.HandleFunc("GET /wasm/", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
+ w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")
+ w.Header().Set("Cache-Control", "no-cache")
+ wasmFiles.ServeHTTP(w, r)
+ })
browserFiles := http.StripPrefix("/browser/", http.FileServer(http.Dir("old_wip/browser")))
http.HandleFunc("GET /browser/", func(w http.ResponseWriter, r *http.Request) {
// Shared WASM memory lets the client worker wait for browser host calls.
diff --git a/src/Makefile.linux b/src/Makefile.linux
@@ -218,6 +218,11 @@ test: build/linux/window build/linux/graphics build/linux/atoi build/linux/stric
./build/linux/qsort
./build/linux/finite
./build/linux/wide-utf8
+ ./build/linux/matrix4
+ ./build/linux/fpu-stack
+ ./build/linux/water-ring
+ ./build/linux/tile-corners
+ ./build/linux/guest-memory
build/linux/surfaces: tests/surfaces.c runtime/linux_graphics.c runtime/linux_window.c runtime/gl_renderer.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_graphics.h runtime/linux_window.h runtime/gl_renderer.h runtime/guest_heap.h runtime/guest_memory.h runtime/recomp_types.h
mkdir -p $(@D)
@@ -396,3 +401,33 @@ test: build/linux/wide-utf8
.PHONY: clean
clean:
rm -rf build/linux
+
+build/linux/matrix4: tests/matrix4.c game/mr.dll/lifted-0001.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h
+ mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@
+
+test: build/linux/matrix4
+
+build/linux/guest-memory: tests/guest_memory.c runtime/guest_memory.c runtime/guest_memory.h
+ @mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -o $@
+
+test: build/linux/guest-memory
+
+build/linux/fpu-stack: tests/fpu_stack.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h
+ @mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -o $@
+
+test: build/linux/fpu-stack
+
+build/linux/water-ring: tests/water_ring.c game/bbr.dll/lifted-0012.c game/bbr.dll/lifted-0079.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h
+ mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -pthread -lm -o $@
+
+test: build/linux/water-ring
+
+build/linux/tile-corners: tests/tile_corners.c game/llr.dll/lifted-0021.c game/llr.dll/lifted-0022.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h
+ mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -pthread -lm -o $@
+
+test: build/linux/tile-corners
diff --git a/src/Makefile.wasm b/src/Makefile.wasm
@@ -0,0 +1,60 @@
+CC := ../toolchains/emsdk/upstream/emscripten/emcc
+CPPFLAGS := -Iruntime -Igame -Idata -DRECOMP_PORTABLE
+# Keep exception landing pads in Wasm so JSPI can yield through guest calls.
+CFLAGS := -O2 -fno-strict-aliasing -pthread -sSUPPORT_LONGJMP=wasm
+PORT_FLAGS := -sUSE_SDL=2 -sUSE_FREETYPE=1
+RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_imports.c runtime/linux_gdi.c runtime/linux_audio.c runtime/browser_audio.c runtime/linux_window.c runtime/linux_graphics.c runtime/gl_renderer.c runtime/linux_platform.c runtime/linux_diagnostics.c runtime/linux_sync.c runtime/linux_file.c runtime/linux_tls.c runtime/linux_thread.c runtime/linux_snapshot.c runtime/browser_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_exception.c runtime/guest_rtti.c runtime/guest_format.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c runtime/linux_path.c runtime/browser_host.c
+GAME_SOURCES := $(wildcard game/*/*.c) game/dispatch.c
+DATA_SOURCES := $(wildcard data/*.c)
+VENDOR_SOURCES := $(wildcard vendor/msvcp60/source/*.c) $(wildcard vendor/ace/source/*.c)
+OBJECTS := $(patsubst %.c,build/wasm/objects/%.o,$(GAME_SOURCES) $(DATA_SOURCES) $(VENDOR_SOURCES) $(RUNTIME_SOURCES))
+
+.DEFAULT_GOAL := all
+.PHONY: all objects
+all: build/wasm/web/game.js build/wasm/web/index.html
+
+build/wasm/web/game.js: $(OBJECTS) runtime/browser_network.js runtime/browser_host.js runtime/browser_audio.js Makefile.wasm
+ @mkdir -p $(@D)
+ $(CC) $(CFLAGS) $(PORT_FLAGS) $(OBJECTS) ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a -sUSE_MPG123=1 -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=8 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sOFFSCREENCANVAS_SUPPORT -sJSPI -sALLOW_MEMORY_GROWTH -sINITIAL_MEMORY=268435456 -sSTACK_SIZE=8388608 --js-library runtime/browser_network.js --js-library runtime/browser_host.js --js-library runtime/browser_audio.js -o $@
+
+build/wasm/web/index.html: browser/index.html
+ @mkdir -p $(@D)
+ cp $< $@
+
+build/wasm/objects/runtime/linux_audio.o: CPPFLAGS += -I../local/wasm/deps/include
+build/wasm/objects/runtime/linux_gdi.o: CFLAGS += $(PORT_FLAGS)
+build/wasm/objects/runtime/linux_graphics.o build/wasm/objects/runtime/linux_window.o build/wasm/objects/runtime/linux_audio.o build/wasm/objects/runtime/browser_audio.o: CFLAGS += -sUSE_SDL=2
+
+objects: $(OBJECTS)
+
+build/wasm/objects/%.o: %.c
+ @mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -MMD -MP -c $< -o $@
+
+-include $(OBJECTS:.o=.d)
+
+build/wasm/web/runtime-test.html: tests/browser_runtime.c runtime/browser_host.c runtime/browser_network.c runtime/linux_sync.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_host.js runtime/browser_network.js
+ @mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_network.js -o $@
+
+build/wasm/web/files-test.html: tests/files.c runtime/linux_file.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_path.c runtime/linux_file.h runtime/guest_memory.h runtime/recomp_types.h runtime/linux_path.h
+ @mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -o $@
+
+build/wasm/web/suspension-test.html: tests/browser_suspension.c Makefile.wasm
+ @mkdir -p $(@D)
+ $(CC) $(CFLAGS) $< -sJSPI -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -o $@
+
+build/wasm/web/audio-output-test.html: tests/browser_audio.html build/wasm/web/audio-output-test.js
+ cp $< $@
+
+build/wasm/web/audio-output-test.js: tests/browser_audio.c runtime/browser_audio.c runtime/browser_audio.h runtime/browser_audio.js Makefile.wasm
+ @mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -sUSE_SDL=2 $(filter %.c,$^) --js-library runtime/browser_audio.js -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -o $@
+
+build/wasm/web/mixer-test.html: tests/browser_mixer.html build/wasm/web/mixer-test.js
+ cp $< $@
+
+build/wasm/web/mixer-test.js: tests/audio.c runtime/linux_audio.c runtime/browser_audio.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_path.c runtime/browser_audio.h runtime/browser_audio.js runtime/linux_audio.h runtime/guest_heap.h runtime/guest_memory.h runtime/recomp_types.h runtime/linux_path.h Makefile.wasm
+ @mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -I../local/wasm/deps/include -sUSE_SDL=2 $(filter %.c,$^) ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a -sUSE_MPG123=1 -sWASMFS --js-library runtime/browser_audio.js -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -Wl,--wrap=audio_output_open -o $@
diff --git a/src/browser/index.html b/src/browser/index.html
@@ -0,0 +1,43 @@
+<!doctype html>
+<html lang="en">
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Anarchy Online 14.9.1</title>
+<style>
+ body { margin: 0; background: #111; color: #ddd; font: 16px sans-serif; }
+ header { padding: 12px; }
+ button { padding: 8px 16px; }
+ canvas { display: block; margin: auto; max-width: 100%; height: auto; }
+ pre { padding: 12px; white-space: pre-wrap; }
+</style>
+<header><button id="start">Enter Rubi-Ka</button> <span id="status">Ready</span></header>
+<canvas id="canvas" width="1024" height="768" tabindex="0"></canvas>
+<pre id="log"></pre>
+<script>
+ const status = document.querySelector('#status');
+ const log = document.querySelector('#log');
+ const canvas = document.querySelector('#canvas');
+ var Module = {
+ canvas,
+ print: message => { log.textContent += message + '\n'; },
+ printErr: message => { log.textContent += message + '\n'; },
+ onAbort: message => { status.textContent = 'Stopped: ' + message; },
+ onRuntimeInitialized: () => { status.textContent = 'Client running'; canvas.focus(); }
+ };
+ document.querySelector('#start').onclick = async event => {
+ event.target.disabled = true;
+ if (!crossOriginIsolated) { status.textContent = 'Shared memory is unavailable'; return; }
+ if (!WebAssembly.Suspending || !canvas.transferControlToOffscreen) { status.textContent = 'This browser lacks required WebAssembly or rendering support'; return; }
+ Module.audioContext = new AudioContext();
+ await Module.audioContext.resume();
+ status.textContent = 'Loading client';
+ const response = await fetch('/browser-launch', {method: 'POST'});
+ if (!response.ok) { status.textContent = await response.text(); event.target.disabled = false; return; }
+ Module.arguments = (await response.text()).trim().split(' ').slice(1);
+ const script = document.createElement('script');
+ script.src = 'game.js';
+ script.onerror = () => { status.textContent = 'Could not load the client'; };
+ document.body.append(script);
+ };
+</script>
+</html>
diff --git a/src/game/bbr.dll/lifted-0012.c b/src/game/bbr.dll/lifted-0012.c
@@ -12314,97 +12314,64 @@ L_2503D0BF:
esi = esi + 8; /* 0x2503D0BF: add esi, 8 */
_flag_k = FK_ADD;
L_2503D0C2:
- eax = MEM32(edi + 0x208); /* 0x2503D0C2: mov eax, dword ptr [edi + 0x208] */
- fp_push(*(float*)&MEM32(eax + ebx * 4)); /* 0x2503D0C8: fld dword ptr [eax + ebx*4] */
- ecx = MEM32(edi + 0x20C); /* 0x2503D0CB: mov ecx, dword ptr [edi + 0x20c] */
- fp_push(*(float*)&MEM32(ecx + ebx * 4)); /* 0x2503D0D1: fld dword ptr [ecx + ebx*4] */
- { float _v = (float)_st[0]; *(float*)ADDR(ebp + 0x10) = _v; } /* 0x2503D0D4: fst dword ptr [ebp + 0x10] */
- _st[0] *= (double)*(float*)ADDR(edi + 0x220); /* 0x2503D0D7: fmul dword ptr [edi + 0x220] */
- fp_push(_st[1]); /* 0x2503D0DD: fld st(1) */
- _st[0] *= (double)*(float*)ADDR(edi + 0x218); /* 0x2503D0DF: fmul dword ptr [edi + 0x218] */
- { double _v = fp_pop(); _st[0] += _v; } /* 0x2503D0E5: faddp st(1) */
- { float _v = (float)fp_pop(); *(float*)ADDR(ebp + (-0x4)) = _v; } /* 0x2503D0E7: fstp dword ptr [ebp - 4] */
- fp_push(_st[0]); /* 0x2503D0EA: fld st(0) */
- _st[0] *= (double)*(float*)ADDR(ebp + 0x8); /* 0x2503D0EC: fmul dword ptr [ebp + 8] */
- { float _v = (float)fp_pop(); *(float*)ADDR(esi + (-0x8)) = _v; } /* 0x2503D0EF: fstp dword ptr [esi - 8] */
- MEM32(esi + (-0x4)) = 0; /* 0x2503D0F2: mov dword ptr [esi - 4], 0 */
- fp_push(*(float*)&MEM32(ebp + 0x10)); /* 0x2503D0F9: fld dword ptr [ebp + 0x10] */
- _st[0] *= (double)*(float*)ADDR(ebp + 0x8); /* 0x2503D0FC: fmul dword ptr [ebp + 8] */
- { float _v = (float)fp_pop(); *(float*)ADDR(esi) = _v; } /* 0x2503D0FF: fstp dword ptr [esi] */
- fp_push(*(float*)&MEM32(ebp + (-0x4))); /* 0x2503D101: fld dword ptr [ebp - 4] */
- _st[0] += (double)*(float*)ADDR(0x251517A4); /* 0x2503D104: fadd dword ptr [0x251517a4] */
- _st[0] *= (double)*(float*)ADDR(0x25153B10); /* 0x2503D10A: fmul dword ptr [0x25153b10] */
- RECOMP_ICALL(0x251380E8u); /* 0x2503D110: call 0x251380e8 */ /* not lifted */
- RECOMP_FLAGS_IN();
- fp_push(_st[1]); /* 0x2503D115: fld st(1) */
- ecx = MEM32(ebp + (-0x8)); /* 0x2503D117: mov ecx, dword ptr [ebp - 8] */
- if (2u) _cf = (((eax) >> 30) & 1u); /* 0x2503D11A: shl eax, 2 */
- if (2u) { _flag_a = recomp_flags_pack((eax << 2u), _cf, 0, 0); _flag_b = 0; _flag_k = FK_EFLAGS; }
- eax = eax << 2u; /* 0x2503D11A: shl eax, 2 */
- edx = 0x251C71F0u; /* 0x2503D11D: mov edx, 0x251c71f0 */
- _flag_a = (uint32_t)(edx); _flag_b = (uint32_t)(eax);
- _cf = (uint32_t)CMP_B(_flag_a, _flag_b);
- edx = edx - eax; /* 0x2503D122: sub edx, eax */
- _flag_k = FK_CMP;
- eax = MEM32(edx); /* 0x2503D124: mov eax, dword ptr [edx] */
- _flag_a = (uint32_t)(eax); _flag_b = (uint32_t)(ecx);
- _cf = (uint32_t)((uint32_t)(_flag_a + _flag_b) < (uint32_t)_flag_a);
- eax = eax + ecx; /* 0x2503D126: add eax, ecx */
- _flag_k = FK_ADD;
- MEM32(esi + 0x4) = eax; /* 0x2503D128: mov dword ptr [esi + 4], eax */
- { float _v = (float)fp_pop(); *(float*)ADDR(esi + 0x8) = _v; } /* 0x2503D12B: fstp dword ptr [esi + 8] */
- _flag_a = (uint32_t)(0); _flag_b = (uint32_t)(0);
- eax = 0; /* 0x2503D12E: xor eax, eax */
- _cf = 0;
- _flag_k = FK_TEST;
- _st[0] *= (double)*(float*)ADDR(ebp + 0xC); /* 0x2503D130: fmul dword ptr [ebp + 0xc] */
- MEM32(esi + 0xC) = eax; /* 0x2503D133: mov dword ptr [esi + 0xc], eax */
- { float _v = (float)fp_pop(); *(float*)ADDR(esi + 0x10) = _v; } /* 0x2503D136: fstp dword ptr [esi + 0x10] */
- MEM32(esi + 0x14) = eax; /* 0x2503D139: mov dword ptr [esi + 0x14], eax */
- fp_push(*(float*)&MEM32(ebp + 0x10)); /* 0x2503D13C: fld dword ptr [ebp + 0x10] */
- _st[0] *= (double)*(float*)ADDR(ebp + 0xC); /* 0x2503D13F: fmul dword ptr [ebp + 0xc] */
- { float _v = (float)fp_pop(); *(float*)ADDR(esi + 0x18) = _v; } /* 0x2503D142: fstp dword ptr [esi + 0x18] */
- fp_push(*(float*)&MEM32(ebp + (-0x4))); /* 0x2503D145: fld dword ptr [ebp - 4] */
- _st[0] *= (double)*(float*)ADDR(0x25153B10); /* 0x2503D148: fmul dword ptr [0x25153b10] */
- _st[0] += (double)*(float*)ADDR(0x25153B0C); /* 0x2503D14E: fadd dword ptr [0x25153b0c] */
- RECOMP_ICALL(0x251380E8u); /* 0x2503D154: call 0x251380e8 */ /* not lifted */
- RECOMP_FLAGS_IN();
- _flag_a = (uint32_t)(0); _flag_b = (uint32_t)(eax);
- _cf = (eax) != 0;
- eax = (uint32_t)(-(int32_t)eax); /* 0x2503D159: neg eax */
- _flag_k = FK_CMP;
- if (2u) _cf = (((eax) >> 30) & 1u); /* 0x2503D15B: shl eax, 2 */
- if (2u) { _flag_a = recomp_flags_pack((eax << 2u), _cf, 0, 0); _flag_b = 0; _flag_k = FK_EFLAGS; }
- eax = eax << 2u; /* 0x2503D15B: shl eax, 2 */
- ecx = 0x251C71F0u; /* 0x2503D15E: mov ecx, 0x251c71f0 */
- _flag_a = (uint32_t)(ecx); _flag_b = (uint32_t)(eax);
- _cf = (uint32_t)CMP_B(_flag_a, _flag_b);
- ecx = ecx - eax; /* 0x2503D163: sub ecx, eax */
- _flag_k = FK_CMP;
- edx = MEM32(ecx); /* 0x2503D165: mov edx, dword ptr [ecx] */
- _flag_a = (uint32_t)(edx); _flag_b = (uint32_t)(MEM32(ebp + (-0x8)));
- _cf = (uint32_t)((uint32_t)(_flag_a + _flag_b) < (uint32_t)_flag_a);
- edx = edx + MEM32(ebp + (-0x8)); /* 0x2503D167: add edx, dword ptr [ebp - 8] */
- _flag_k = FK_ADD;
- MEM32(esi + 0x1C) = edx; /* 0x2503D16A: mov dword ptr [esi + 0x1c], edx */
- { float _v = (float)_st[0]; *(float*)ADDR(esi + 0x20) = _v; } /* 0x2503D16D: fst dword ptr [esi + 0x20] */
- eax = MEM32(edi + 0x204); /* 0x2503D170: mov eax, dword ptr [edi + 0x204] */
- _st[0] += (double)*(float*)ADDR(ebp + (-0xC)); /* 0x2503D176: fadd dword ptr [ebp - 0xc] */
- MEM32(esi + 0x24) = eax; /* 0x2503D179: mov dword ptr [esi + 0x24], eax */
- eax = MEM32(edi + 0x1FC); /* 0x2503D17C: mov eax, dword ptr [edi + 0x1fc] */
- _flag_a = (uint32_t)(ebx); _flag_b = (uint32_t)(1);
- ebx = ebx + 1; /* 0x2503D182: inc ebx */
- _flag_k = FK_INC;
- _flag_a = (uint32_t)(esi); _flag_b = (uint32_t)(0x30u);
- _cf = (uint32_t)((uint32_t)(_flag_a + _flag_b) < (uint32_t)_flag_a);
- esi = esi + 0x30u; /* 0x2503D183: add esi, 0x30 */
- _flag_k = FK_ADD;
- /* cmp ebx, eax */ /* 0x2503D186: cmp ebx, eax */
- _flag_a = (uint32_t)(ebx); _flag_b = (uint32_t)(eax);
- _cf = (uint32_t)CMP_B(_flag_a, _flag_b);
- _flag_k = FK_CMP;
+ /* Load the ring direction and round its lighting projection to float. */
+ eax = MEM32(edi + 0x208);
+ fp_push(*(float *)ADDR(eax + ebx * 4));
+ ecx = MEM32(edi + 0x20C);
+ double z = *(float *)ADDR(ecx + ebx * 4);
+ *(float *)ADDR(ebp + 0x10) = (float)z;
+ double projection = z * *(float *)ADDR(edi + 0x220);
+ projection += _st[0] * *(float *)ADDR(edi + 0x218);
+ *(float *)ADDR(ebp - 4) = (float)projection;
+
+ /* The lifted four-slot peak discards these two inactive stack slots. */
+ _st[6] = _st[7] = 0;
+ g_st_i64[6] = g_st_i64[7] = 0;
+
+ /* First vertex: radius, table color, and the running texture coordinate. */
+ *(float *)ADDR(esi - 8) = (float)(_st[0] * *(float *)ADDR(ebp + 8));
+ MEM32(esi - 4) = 0;
+ *(float *)ADDR(esi) = (float)((double)*(float *)ADDR(ebp + 0x10) * *(float *)ADDR(ebp + 8));
+ double color = (double)*(float *)ADDR(ebp - 4) + *(float *)ADDR(0x251517A4);
+ fp_push(color * *(float *)ADDR(0x25153B10));
+ RECOMP_ICALL(0x251380E8u);
+ RECOMP_FLAGS_IN();
+ ecx = MEM32(ebp - 8);
+ eax <<= 2;
+ edx = 0x251C71F0u - eax;
+ eax = MEM32(edx) + ecx;
+ MEM32(esi + 4) = eax;
+ *(float *)ADDR(esi + 8) = (float)_st[1];
+ eax = 0;
+ _flag_a = 0; _flag_b = 0; _cf = 0; _flag_k = FK_TEST;
+
+ /* Second vertex uses its own radius and the complementary table index. */
+ _st[0] *= *(float *)ADDR(ebp + 0xC);
+ MEM32(esi + 0xC) = 0;
+ *(float *)ADDR(esi + 0x10) = (float)fp_pop();
+ MEM32(esi + 0x14) = 0;
+ *(float *)ADDR(esi + 0x18) = (float)((double)*(float *)ADDR(ebp + 0x10) * *(float *)ADDR(ebp + 0xC));
+ color = (double)*(float *)ADDR(ebp - 4) * *(float *)ADDR(0x25153B10);
+ fp_push(color + *(float *)ADDR(0x25153B0C));
+ RECOMP_ICALL(0x251380E8u);
+ RECOMP_FLAGS_IN();
+ eax = (0u - eax) << 2;
+ ecx = 0x251C71F0u - eax;
+ edx = MEM32(ecx) + MEM32(ebp - 8);
+ MEM32(esi + 0x1C) = edx;
+ *(float *)ADDR(esi + 0x20) = (float)_st[0];
+ eax = MEM32(edi + 0x204);
+ _st[0] += *(float *)ADDR(ebp - 0xC);
+ MEM32(esi + 0x24) = eax;
+
+ /* Retain the guest loop state and its scheduling point. */
+ eax = MEM32(edi + 0x1FC);
+ ebx++;
+ esi += 0x30;
+ _flag_a = ebx; _flag_b = eax;
+ _cf = CMP_B(_flag_a, _flag_b); _flag_k = FK_CMP;
RECOMP_BACKEDGE();
- if (CMP_LE(_flag_a, _flag_b)) goto L_2503D0C2; /* 0x2503D188: jle 0x2503d0c2 */
+ if (CMP_LE(_flag_a, _flag_b)) goto L_2503D0C2;
L_2503D18E:
ecx = MEM32(edi + 0x1FC); /* 0x2503D18E: mov ecx, dword ptr [edi + 0x1fc] */
{ _st[0] = _st[0]; g_st_i64[0] = g_st_i64[0]; fp_pop(); } /* 0x2503D194: fstp st(0) */
diff --git a/src/game/ffr.dll/lifted-0002.c b/src/game/ffr.dll/lifted-0002.c
@@ -8,6 +8,19 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#ifdef __EMSCRIPTEN__
+#include <emscripten.h>
+#endif
+
+static uint64_t timestamp_counter(void)
+{
+#ifdef __EMSCRIPTEN__
+ /* Browser diagnostics use a monotonic nanosecond counter. */
+ return (uint64_t)(emscripten_get_now() * 1000000.0);
+#else
+ return __rdtsc();
+#endif
+}
void sub_2F006FBA(void) {
int _fpu_cmp = 0;
@@ -805,7 +818,7 @@ L_2F0073B1:
RECOMP_FLAGS_IN();
PUSH32(esp, eax); /* 0x2F0073C7: push eax */
PUSH32(esp, edx); /* 0x2F0073C8: push edx */
- { uint64_t _t = __rdtsc(); eax = (uint32_t)_t; edx = (uint32_t)(_t >> 32); } /* 0x2F0073C9: rdtsc */
+ { uint64_t _t = timestamp_counter(); eax = (uint32_t)_t; edx = (uint32_t)(_t >> 32); } /* 0x2F0073C9: rdtsc */
MEM32(ebp + (-0x8)) = eax; /* 0x2F0073CB: mov dword ptr [ebp - 8], eax */
MEM32(ebp + (-0x2C)) = edx; /* 0x2F0073CE: mov dword ptr [ebp - 0x2c], edx */
edx = POP32_VAL(esp); /* 0x2F0073D1: pop edx */
@@ -828,7 +841,7 @@ L_2F0073E6:
RECOMP_FLAGS_IN();
PUSH32(esp, eax); /* 0x2F0073EC: push eax */
PUSH32(esp, edx); /* 0x2F0073ED: push edx */
- { uint64_t _t = __rdtsc(); eax = (uint32_t)_t; edx = (uint32_t)(_t >> 32); } /* 0x2F0073EE: rdtsc */
+ { uint64_t _t = timestamp_counter(); eax = (uint32_t)_t; edx = (uint32_t)(_t >> 32); } /* 0x2F0073EE: rdtsc */
MEM32(ebp + (-0x8)) = eax; /* 0x2F0073F0: mov dword ptr [ebp - 8], eax */
MEM32(ebp + (-0xC)) = edx; /* 0x2F0073F3: mov dword ptr [ebp - 0xc], edx */
edx = POP32_VAL(esp); /* 0x2F0073F6: pop edx */
@@ -1172,7 +1185,7 @@ L_2F0073B1:
RECOMP_FLAGS_IN();
PUSH32(esp, eax); /* 0x2F0073C7: push eax */
PUSH32(esp, edx); /* 0x2F0073C8: push edx */
- { uint64_t _t = __rdtsc(); eax = (uint32_t)_t; edx = (uint32_t)(_t >> 32); } /* 0x2F0073C9: rdtsc */
+ { uint64_t _t = timestamp_counter(); eax = (uint32_t)_t; edx = (uint32_t)(_t >> 32); } /* 0x2F0073C9: rdtsc */
MEM32(ebp + (-0x8)) = eax; /* 0x2F0073CB: mov dword ptr [ebp - 8], eax */
MEM32(ebp + (-0x2C)) = edx; /* 0x2F0073CE: mov dword ptr [ebp - 0x2c], edx */
edx = POP32_VAL(esp); /* 0x2F0073D1: pop edx */
@@ -1195,7 +1208,7 @@ L_2F0073E6:
RECOMP_FLAGS_IN();
PUSH32(esp, eax); /* 0x2F0073EC: push eax */
PUSH32(esp, edx); /* 0x2F0073ED: push edx */
- { uint64_t _t = __rdtsc(); eax = (uint32_t)_t; edx = (uint32_t)(_t >> 32); } /* 0x2F0073EE: rdtsc */
+ { uint64_t _t = timestamp_counter(); eax = (uint32_t)_t; edx = (uint32_t)(_t >> 32); } /* 0x2F0073EE: rdtsc */
MEM32(ebp + (-0x8)) = eax; /* 0x2F0073F0: mov dword ptr [ebp - 8], eax */
MEM32(ebp + (-0xC)) = edx; /* 0x2F0073F3: mov dword ptr [ebp - 0xc], edx */
edx = POP32_VAL(esp); /* 0x2F0073F6: pop edx */
diff --git a/src/game/llr.dll/lifted-0021.c b/src/game/llr.dll/lifted-0021.c
@@ -7714,6 +7714,7 @@ void sub_38038370(void) {
uint32_t _flag_k = FK_NONE;
uint32_t _flag_a = 0, _flag_b = 0;
uint32_t _itail_tgt = 0;
+ double height;
RECOMP_REGS_LOCALS
RECOMP_ENTER(0x38038370u);
@@ -7728,32 +7729,33 @@ L_38038370:
PUSH32(esp, esi); /* 0x38038377: push esi */
esi = ecx; /* 0x38038378: mov esi, ecx */
eax = MEM32(esi + 0xC); /* 0x3803837A: mov eax, dword ptr [esi + 0xc] */
- fp_push(*(float*)&MEM32(eax + 0x8264)); /* 0x3803837D: fld dword ptr [eax + 0x8264] */
- eax = MEM32(ebp + 0x10); /* 0x38038383: mov eax, dword ptr [ebp + 0x10] */
- fp_push((double)(int32_t)MEM32(ebp + 0x8)); /* 0x38038386: fild dword ptr [ebp + 8] */
- PUSH32(esp, edi); /* 0x38038389: push edi */
- _st[0] *= _st[1]; /* 0x3803838A: fmul st(1) */
- { float _v = (float)fp_pop(); *(float*)ADDR(ebp + (-0x4)) = _v; } /* 0x3803838C: fstp dword ptr [ebp - 4] */
- fp_push((double)(int32_t)MEM32(ebp + 0xC)); /* 0x3803838F: fild dword ptr [ebp + 0xc] */
- _st[0] *= _st[1]; /* 0x38038392: fmul st(1) */
- fp_push(*(float*)&MEM32(ebp + (-0x4))); /* 0x38038394: fld dword ptr [ebp - 4] */
- { float _v = (float)fp_pop(); *(float*)ADDR(eax) = _v; } /* 0x38038397: fstp dword ptr [eax] */
- { float _v = (float)_st[0]; *(float*)ADDR(eax + 0x8) = _v; } /* 0x38038399: fst dword ptr [eax + 8] */
- eax = MEM32(ebp + 0x14); /* 0x3803839C: mov eax, dword ptr [ebp + 0x14] */
- fp_push(*(float*)&MEM32(ebp + (-0x4))); /* 0x3803839F: fld dword ptr [ebp - 4] */
- _st[0] += _st[2]; /* 0x380383A2: fadd st(2) */
- fp_push(_st[0]); /* 0x380383A4: fld st(0) */
- { float _v = (float)fp_pop(); *(float*)ADDR(eax) = _v; } /* 0x380383A6: fstp dword ptr [eax] */
- fp_push(_st[1]); /* 0x380383A8: fld st(1) */
- { float _v = (float)fp_pop(); *(float*)ADDR(eax + 0x8) = _v; } /* 0x380383AA: fstp dword ptr [eax + 8] */
- eax = MEM32(ebp + 0x18); /* 0x380383AD: mov eax, dword ptr [ebp + 0x18] */
- { float _v = (float)fp_pop(); *(float*)ADDR(eax) = _v; } /* 0x380383B0: fstp dword ptr [eax] */
- { double _v = fp_pop(); _st[0] += _v; } /* 0x380383B2: faddp st(1) */
- { float _v = (float)_st[0]; *(float*)ADDR(eax + 0x8) = _v; } /* 0x380383B4: fst dword ptr [eax + 8] */
- eax = MEM32(ebp + 0x1C); /* 0x380383B7: mov eax, dword ptr [ebp + 0x1c] */
- fp_push(*(float*)&MEM32(ebp + (-0x4))); /* 0x380383BA: fld dword ptr [ebp - 4] */
- { float _v = (float)fp_pop(); *(float*)ADDR(eax) = _v; } /* 0x380383BD: fstp dword ptr [eax] */
- { float _v = (float)fp_pop(); *(float*)ADDR(eax + 0x8) = _v; } /* 0x380383BF: fstp dword ptr [eax + 8] */
+ /* llr.dll!n3Tilemap_t::GetTileCornerPoints: preserve x87 spill rounding. */
+ {
+ double spacing = *(float *)ADDR(eax + 0x8264);
+ eax = MEM32(ebp + 0x10);
+ float near_x = (float)((double)(int32_t)MEM32(ebp + 8) * spacing);
+ PUSH32(esp, edi);
+ *(float *)ADDR(ebp - 4) = near_x;
+ double near_z = (double)(int32_t)MEM32(ebp + 12) * spacing;
+ *(float *)ADDR(eax) = *(float *)ADDR(ebp - 4);
+ *(float *)ADDR(eax + 8) = (float)near_z;
+
+ eax = MEM32(ebp + 0x14);
+ double far_x = (double)*(float *)ADDR(ebp - 4) + spacing;
+ *(float *)ADDR(eax) = (float)far_x;
+ *(float *)ADDR(eax + 8) = (float)near_z;
+ eax = MEM32(ebp + 0x18);
+ *(float *)ADDR(eax) = (float)far_x;
+ double far_z = spacing + near_z;
+ *(float *)ADDR(eax + 8) = (float)far_z;
+ eax = MEM32(ebp + 0x1c);
+ *(float *)ADDR(eax) = *(float *)ADDR(ebp - 4);
+ *(float *)ADDR(eax + 8) = (float)far_z;
+
+ /* Four temporary stack slots are consumed; live lower slots survive. */
+ memset(_st + 4, 0, 4 * sizeof(*_st));
+ memset(g_st_i64 + 4, 0, 4 * sizeof(*g_st_i64));
+ }
RECOMP_ICALL(0x38039DC0u); /* 0x380383C2: call 0x38039dc0 */ /* not lifted */
RECOMP_FLAGS_IN();
/* test LO8(eax), LO8(eax) */ /* 0x380383C7: test al, al */
@@ -7874,18 +7876,18 @@ L_38038439:
eax = ecx; /* 0x3803845F: mov eax, ecx */
L_38038461:
edx = MEM32(esi + 0xC); /* 0x38038461: mov edx, dword ptr [esi + 0xc] */
- fp_push(*(float*)&MEM32(edx + 0x1C)); /* 0x38038464: fld dword ptr [edx + 0x1c] */
+ height = *(float *)ADDR(edx + 0x1C); /* 0x38038464: fld dword ptr [edx + 0x1c] */
edx = MEM32(ebp + (-0x4)); /* 0x38038467: mov edx, dword ptr [ebp - 4] */
_flag_a = (uint32_t)(eax); _flag_b = (uint32_t)(0xFFFFu);
eax = eax & 0xFFFFu; /* 0x3803846A: and eax, 0xffff */
_cf = 0;
_flag_k = FK_TEST;
MEM32(ebp + (-0x8)) = eax; /* 0x3803846F: mov dword ptr [ebp - 8], eax */
- _st[0] = _st[0] * (double)(int32_t)MEM32(ebp + (-0x8)); /* 0x38038472: fimul dword ptr [ebp - 8] */
+ height *= (double)(int32_t)MEM32(ebp - 8); /* 0x38038472: fimul dword ptr [ebp - 8] */
eax = MEM32(ebp + 0x10); /* 0x38038475: mov eax, dword ptr [ebp + 0x10] */
PUSH32(esp, ebx); /* 0x38038478: push ebx */
PUSH32(esp, edx); /* 0x38038479: push edx */
- { float _v = (float)fp_pop(); *(float*)ADDR(eax + 0x4) = _v; } /* 0x3803847A: fstp dword ptr [eax + 4] */
+ { float _v = (float)height; _st[7] = 0; g_st_i64[7] = 0; *(float*)ADDR(eax + 0x4) = _v; } /* 0x3803847A: fstp dword ptr [eax + 4] */
eax = MEM32(esi + 0xC); /* 0x3803847D: mov eax, dword ptr [esi + 0xc] */
ecx = MEM32(eax + 0x1C); /* 0x38038480: mov ecx, dword ptr [eax + 0x1c] */
MEM32(ebp + (-0x8)) = ecx; /* 0x38038483: mov dword ptr [ebp - 8], ecx */
@@ -7897,10 +7899,10 @@ L_38038461:
_cf = 0;
_flag_k = FK_TEST;
MEM32(ebp + 0x10) = eax; /* 0x38038497: mov dword ptr [ebp + 0x10], eax */
- fp_push((double)(int32_t)MEM32(ebp + 0x10)); /* 0x3803849A: fild dword ptr [ebp + 0x10] */
+ height = (double)(int32_t)MEM32(ebp + 0x10); /* 0x3803849A: fild dword ptr [ebp + 0x10] */
eax = MEM32(ebp + 0x14); /* 0x3803849D: mov eax, dword ptr [ebp + 0x14] */
- _st[0] *= (double)*(float*)ADDR(ebp + (-0x8)); /* 0x380384A0: fmul dword ptr [ebp - 8] */
- { float _v = (float)fp_pop(); *(float*)ADDR(eax + 0x4) = _v; } /* 0x380384A3: fstp dword ptr [eax + 4] */
+ height *= (double)*(float *)ADDR(ebp - 8); /* 0x380384A0: fmul dword ptr [ebp - 8] */
+ { float _v = (float)height; _st[7] = 0; g_st_i64[7] = 0; *(float*)ADDR(eax + 0x4) = _v; } /* 0x380384A3: fstp dword ptr [eax + 4] */
ecx = MEM32(esi + 0xC); /* 0x380384A6: mov ecx, dword ptr [esi + 0xc] */
edi = MEM32(ecx + 0x8258); /* 0x380384A9: mov edi, dword ptr [ecx + 0x8258] */
SET_LO8(eax, MEM8(edi + 0x29)); /* 0x380384AF: mov al, byte ptr [edi + 0x29] */
@@ -7978,17 +7980,17 @@ L_380384E4:
eax = ecx; /* 0x3803850F: mov eax, ecx */
L_38038511:
edx = MEM32(esi + 0xC); /* 0x38038511: mov edx, dword ptr [esi + 0xc] */
- fp_push(*(float*)&MEM32(edx + 0x1C)); /* 0x38038514: fld dword ptr [edx + 0x1c] */
+ height = *(float *)ADDR(edx + 0x1C); /* 0x38038514: fld dword ptr [edx + 0x1c] */
edx = MEM32(ebp + 0xC); /* 0x38038517: mov edx, dword ptr [ebp + 0xc] */
_flag_a = (uint32_t)(eax); _flag_b = (uint32_t)(0xFFFFu);
eax = eax & 0xFFFFu; /* 0x3803851A: and eax, 0xffff */
_cf = 0;
_flag_k = FK_TEST;
MEM32(ebp + 0x10) = eax; /* 0x3803851F: mov dword ptr [ebp + 0x10], eax */
- _st[0] = _st[0] * (double)(int32_t)MEM32(ebp + 0x10); /* 0x38038522: fimul dword ptr [ebp + 0x10] */
+ height *= (double)(int32_t)MEM32(ebp + 0x10); /* 0x38038522: fimul dword ptr [ebp + 0x10] */
eax = MEM32(ebp + 0x18); /* 0x38038525: mov eax, dword ptr [ebp + 0x18] */
PUSH32(esp, edx); /* 0x38038528: push edx */
- { float _v = (float)fp_pop(); *(float*)ADDR(eax + 0x4) = _v; } /* 0x38038529: fstp dword ptr [eax + 4] */
+ { float _v = (float)height; _st[7] = 0; g_st_i64[7] = 0; *(float*)ADDR(eax + 0x4) = _v; } /* 0x38038529: fstp dword ptr [eax + 4] */
esi = MEM32(esi + 0xC); /* 0x3803852C: mov esi, dword ptr [esi + 0xc] */
ecx = MEM32(esi + 0x1C); /* 0x3803852F: mov ecx, dword ptr [esi + 0x1c] */
eax = MEM32(ebp + 0x8); /* 0x38038532: mov eax, dword ptr [ebp + 8] */
@@ -8006,9 +8008,9 @@ L_38038511:
_cf = 0;
_flag_k = FK_TEST;
MEM32(ebp + 0xC) = eax; /* 0x38038551: mov dword ptr [ebp + 0xc], eax */
- fp_push((double)(int32_t)MEM32(ebp + 0xC)); /* 0x38038554: fild dword ptr [ebp + 0xc] */
- _st[0] *= (double)*(float*)ADDR(ebp + 0x10); /* 0x38038557: fmul dword ptr [ebp + 0x10] */
- { float _v = (float)fp_pop(); *(float*)ADDR(ecx + 0x4) = _v; } /* 0x3803855A: fstp dword ptr [ecx + 4] */
+ height = (double)(int32_t)MEM32(ebp + 0xC); /* 0x38038554: fild dword ptr [ebp + 0xc] */
+ height *= (double)*(float *)ADDR(ebp + 0x10); /* 0x38038557: fmul dword ptr [ebp + 0x10] */
+ { float _v = (float)height; _st[7] = 0; g_st_i64[7] = 0; *(float*)ADDR(ecx + 0x4) = _v; } /* 0x3803855A: fstp dword ptr [ecx + 4] */
_flag_a = (uint32_t)((LO8(ebx) ^ MEM8(ebp + 0x8))) << 24; _flag_b = (uint32_t)((LO8(ebx) ^ MEM8(ebp + 0x8))) << 24;
SET_LO8(ebx, LO8(ebx) ^ MEM8(ebp + 0x8)); /* 0x3803855D: xor bl, byte ptr [ebp + 8] */
_cf = 0;
diff --git a/src/game/mr.dll/lifted-0001.c b/src/game/mr.dll/lifted-0001.c
@@ -2504,99 +2504,42 @@ L_3B0043E4:
RECOMP_REGS_OUT();
}
+/* anarchy-vanilla-14.9.1/mr.dll: TMatrix4_t::operator*= (RVA 0x44a0)
+ * and operator* (RVA 0x4580). Preserve the x87 addition order and round only
+ * when storing each float; the temporary also permits either input to alias. */
+static void matrix4_multiply(uint32_t output, uint32_t left, uint32_t right)
+{
+ const float *a = (const float *)ADDR(left), *b = (const float *)ADDR(right);
+ float product[16];
+ for (unsigned row = 0; row < 4; ++row)
+ for (unsigned column = 0; column < 4; ++column) {
+ double value = (double)b[12 + column] * a[row * 4 + 3];
+ value += (double)b[column] * a[row * 4];
+ value += (double)b[4 + column] * a[row * 4 + 1];
+ value += (double)b[8 + column] * a[row * 4 + 2];
+ product[row * 4 + column] = (float)value;
+ }
+ memcpy((void *)ADDR(output), product, sizeof(product));
+
+ /* Two temporary x87 slots are popped; preserve all live caller values. */
+ g_st[6] = g_st[7] = 0;
+ g_st_i64[6] = g_st_i64[7] = 0;
+}
+
void sub_3B0044A0(void) {
- int _fpu_cmp = 0;
- uint32_t _cf = 0;
- int _df = 1;
- uint32_t _flag_k = FK_NONE;
- uint32_t _flag_a = 0, _flag_b = 0;
- uint32_t _itail_tgt = 0;
- RECOMP_REGS_LOCALS
+ uint32_t _flag_k, _flag_a, _flag_b, _cf;
RECOMP_ENTER(0x3B0044A0u);
-
-L_3B0044A0:
- PUSH32(esp, ebp); /* 0x3B0044A0: push ebp */
- ebp = esp; /* 0x3B0044A1: mov ebp, esp */
- _flag_a = (uint32_t)(esp); _flag_b = (uint32_t)(0x44u);
- _cf = (uint32_t)CMP_B(_flag_a, _flag_b);
- esp = esp - 0x44u; /* 0x3B0044A3: sub esp, 0x44 */
- _flag_k = FK_CMP;
- eax = MEM32(ebp + 0x8); /* 0x3B0044A6: mov eax, dword ptr [ebp + 8] */
- PUSH32(esp, ebx); /* 0x3B0044A9: push ebx */
- PUSH32(esp, esi); /* 0x3B0044AA: push esi */
- PUSH32(esp, edi); /* 0x3B0044AB: push edi */
- MEM32(ebp + (-0x4)) = ecx; /* 0x3B0044AC: mov dword ptr [ebp - 4], ecx */
- MEM32(ebp + (-0x44)) = 0x3F800000u; /* 0x3B0044AF: mov dword ptr [ebp - 0x44], 0x3f800000 */
- MEM32(ebp + (-0x40)) = 0; /* 0x3B0044B6: mov dword ptr [ebp - 0x40], 0 */
- MEM32(ebp + (-0x3C)) = 0; /* 0x3B0044BD: mov dword ptr [ebp - 0x3c], 0 */
- MEM32(ebp + (-0x38)) = 0; /* 0x3B0044C4: mov dword ptr [ebp - 0x38], 0 */
- MEM32(ebp + (-0x34)) = 0; /* 0x3B0044CB: mov dword ptr [ebp - 0x34], 0 */
- MEM32(ebp + (-0x30)) = 0x3F800000u; /* 0x3B0044D2: mov dword ptr [ebp - 0x30], 0x3f800000 */
- MEM32(ebp + (-0x2C)) = 0; /* 0x3B0044D9: mov dword ptr [ebp - 0x2c], 0 */
- MEM32(ebp + (-0x28)) = 0; /* 0x3B0044E0: mov dword ptr [ebp - 0x28], 0 */
- MEM32(ebp + (-0x24)) = 0; /* 0x3B0044E7: mov dword ptr [ebp - 0x24], 0 */
- MEM32(ebp + (-0x20)) = 0; /* 0x3B0044EE: mov dword ptr [ebp - 0x20], 0 */
- MEM32(ebp + (-0x1C)) = 0x3F800000u; /* 0x3B0044F5: mov dword ptr [ebp - 0x1c], 0x3f800000 */
- MEM32(ebp + (-0x18)) = 0; /* 0x3B0044FC: mov dword ptr [ebp - 0x18], 0 */
- MEM32(ebp + (-0x14)) = 0; /* 0x3B004503: mov dword ptr [ebp - 0x14], 0 */
- MEM32(ebp + (-0x10)) = 0; /* 0x3B00450A: mov dword ptr [ebp - 0x10], 0 */
- MEM32(ebp + (-0xC)) = 0; /* 0x3B004511: mov dword ptr [ebp - 0xc], 0 */
- MEM32(ebp + (-0x8)) = 0x3F800000u; /* 0x3B004518: mov dword ptr [ebp - 8], 0x3f800000 */
- esi = ebp + (-0x44); /* 0x3B00451F: lea esi, [ebp - 0x44] */
- edx = ecx + 0x8; /* 0x3B004522: lea edx, [ecx + 8] */
- ebx = 4; /* 0x3B004525: mov ebx, 4 */
-L_3B00452A:
- ecx = eax + 0x20; /* 0x3B00452A: lea ecx, [eax + 0x20] */
- edi = 4; /* 0x3B00452D: mov edi, 4 */
-L_3B004532:
- fp_push(*(float*)&MEM32(ecx + 0x10)); /* 0x3B004532: fld dword ptr [ecx + 0x10] */
- _st[0] *= (double)*(float*)ADDR(edx + 0x4); /* 0x3B004535: fmul dword ptr [edx + 4] */
- fp_push(*(float*)&MEM32(ecx + (-0x20))); /* 0x3B004538: fld dword ptr [ecx - 0x20] */
- _st[0] *= (double)*(float*)ADDR(edx + (-0x8)); /* 0x3B00453B: fmul dword ptr [edx - 8] */
- _flag_a = (uint32_t)(ecx); _flag_b = (uint32_t)(4);
- _cf = (uint32_t)((uint32_t)(_flag_a + _flag_b) < (uint32_t)_flag_a);
- ecx = ecx + 4; /* 0x3B00453E: add ecx, 4 */
- _flag_k = FK_ADD;
- _flag_a = (uint32_t)(esi); _flag_b = (uint32_t)(4);
- _cf = (uint32_t)((uint32_t)(_flag_a + _flag_b) < (uint32_t)_flag_a);
- esi = esi + 4; /* 0x3B004541: add esi, 4 */
- _flag_k = FK_ADD;
- _flag_a = (uint32_t)(edi); _flag_b = (uint32_t)(1);
- edi = edi - 1; /* 0x3B004544: dec edi */
- _flag_k = FK_DEC;
- { double _v = fp_pop(); _st[0] += _v; } /* 0x3B004545: faddp st(1) */
- fp_push(*(float*)&MEM32(ecx + (-0x14))); /* 0x3B004547: fld dword ptr [ecx - 0x14] */
- _st[0] *= (double)*(float*)ADDR(edx + (-0x4)); /* 0x3B00454A: fmul dword ptr [edx - 4] */
- { double _v = fp_pop(); _st[0] += _v; } /* 0x3B00454D: faddp st(1) */
- fp_push(*(float*)&MEM32(ecx + (-0x4))); /* 0x3B00454F: fld dword ptr [ecx - 4] */
- _st[0] *= (double)*(float*)ADDR(edx); /* 0x3B004552: fmul dword ptr [edx] */
- { double _v = fp_pop(); _st[0] += _v; } /* 0x3B004554: faddp st(1) */
- { float _v = (float)fp_pop(); *(float*)ADDR(esi + (-0x4)) = _v; } /* 0x3B004556: fstp dword ptr [esi - 4] */
- RECOMP_BACKEDGE();
- if (/* dec result */ CMP_NE(_flag_a, _flag_b)) goto L_3B004532; /* 0x3B004559: jne 0x3b004532 */
-L_3B00455B:
- _flag_a = (uint32_t)(edx); _flag_b = (uint32_t)(0x10u);
- _cf = (uint32_t)((uint32_t)(_flag_a + _flag_b) < (uint32_t)_flag_a);
- edx = edx + 0x10u; /* 0x3B00455B: add edx, 0x10 */
- _flag_k = FK_ADD;
- _flag_a = (uint32_t)(ebx); _flag_b = (uint32_t)(1);
- ebx = ebx - 1; /* 0x3B00455E: dec ebx */
- _flag_k = FK_DEC;
- RECOMP_BACKEDGE();
- if (/* dec result */ CMP_NE(_flag_a, _flag_b)) goto L_3B00452A; /* 0x3B00455F: jne 0x3b00452a */
-L_3B004561:
- eax = MEM32(ebp + (-0x4)); /* 0x3B004561: mov eax, dword ptr [ebp - 4] */
- ecx = 0x10u; /* 0x3B004564: mov ecx, 0x10 */
- esi = ebp + (-0x44); /* 0x3B004569: lea esi, [ebp - 0x44] */
- edi = eax; /* 0x3B00456C: mov edi, eax */
- { uint32_t _n = ecx, _b = _n * 4u; /* 0x3B00456E: rep movsd dword ptr es:[edi], dword ptr [esi] */ if (_df > 0) { memmove((void*)ADDR(edi), (void*)ADDR(esi), _b); esi += _b; edi += _b; } else { memmove((void*)ADDR(edi - _b + 4u), (void*)ADDR(esi - _b + 4u), _b); esi -= _b; edi -= _b; } ecx = 0; }
- edi = POP32_VAL(esp); /* 0x3B004570: pop edi */
- esi = POP32_VAL(esp); /* 0x3B004571: pop esi */
- ebx = POP32_VAL(esp); /* 0x3B004572: pop ebx */
- esp = ebp; /* 0x3B004573: mov esp, ebp */
- ebp = POP32_VAL(esp); /* 0x3B004575: pop ebp */
- RECOMP_FLAGS_OUT(); esp += 8; { RECOMP_REGS_OUT(); return; } /* 0x3B004576: ret 4 */
- RECOMP_REGS_OUT();
+ uint32_t matrix = g_ecx;
+ matrix4_multiply(matrix, matrix, MEM32(g_esp + 4));
+
+ /* Thiscall return state, including the final loop's flags. */
+ g_eax = matrix;
+ g_ecx = 0;
+ g_edx = matrix + 72;
+ g_esp += 8;
+ g_flag_k = FK_DEC;
+ g_flag_a = g_flag_b = 1;
+ g_flag_cf = g_edx < matrix + 56;
}
void sub_3B004503(void) {
@@ -2672,85 +2615,19 @@ L_3B004561:
}
void sub_3B004580(void) {
- int _fpu_cmp = 0;
- uint32_t _cf = 0;
- int _df = 1;
- uint32_t _flag_k = FK_NONE;
- uint32_t _flag_a = 0, _flag_b = 0;
- uint32_t _itail_tgt = 0;
- RECOMP_REGS_LOCALS
+ uint32_t _flag_k, _flag_a, _flag_b, _cf;
RECOMP_ENTER(0x3B004580u);
-
-L_3B004580:
- PUSH32(esp, ebp); /* 0x3B004580: push ebp */
- ebp = esp; /* 0x3B004581: mov ebp, esp */
- _flag_a = (uint32_t)(esp); _flag_b = (uint32_t)(0x44u);
- _cf = (uint32_t)CMP_B(_flag_a, _flag_b);
- esp = esp - 0x44u; /* 0x3B004583: sub esp, 0x44 */
- _flag_k = FK_CMP;
- PUSH32(esp, ebx); /* 0x3B004586: push ebx */
- ebx = MEM32(ebp + 0xC); /* 0x3B004587: mov ebx, dword ptr [ebp + 0xc] */
- PUSH32(esp, esi); /* 0x3B00458A: push esi */
- PUSH32(esp, edi); /* 0x3B00458B: push edi */
- MEM32(ebp + (-0x4)) = 0; /* 0x3B00458C: mov dword ptr [ebp - 4], 0 */
- edx = ebp + (-0x44); /* 0x3B004593: lea edx, [ebp - 0x44] */
- _flag_a = (uint32_t)(ecx); _flag_b = (uint32_t)(8);
- _cf = (uint32_t)((uint32_t)(_flag_a + _flag_b) < (uint32_t)_flag_a);
- ecx = ecx + 8; /* 0x3B004596: add ecx, 8 */
- _flag_k = FK_ADD;
- edi = 4; /* 0x3B004599: mov edi, 4 */
-L_3B00459E:
- eax = ebx + 0x20; /* 0x3B00459E: lea eax, [ebx + 0x20] */
- esi = 4; /* 0x3B0045A1: mov esi, 4 */
-L_3B0045A6:
- fp_push(*(float*)&MEM32(eax + 0x10)); /* 0x3B0045A6: fld dword ptr [eax + 0x10] */
- _st[0] *= (double)*(float*)ADDR(ecx + 0x4); /* 0x3B0045A9: fmul dword ptr [ecx + 4] */
- fp_push(*(float*)&MEM32(eax + (-0x20))); /* 0x3B0045AC: fld dword ptr [eax - 0x20] */
- _st[0] *= (double)*(float*)ADDR(ecx + (-0x8)); /* 0x3B0045AF: fmul dword ptr [ecx - 8] */
- _flag_a = (uint32_t)(eax); _flag_b = (uint32_t)(4);
- _cf = (uint32_t)((uint32_t)(_flag_a + _flag_b) < (uint32_t)_flag_a);
- eax = eax + 4; /* 0x3B0045B2: add eax, 4 */
- _flag_k = FK_ADD;
- _flag_a = (uint32_t)(edx); _flag_b = (uint32_t)(4);
- _cf = (uint32_t)((uint32_t)(_flag_a + _flag_b) < (uint32_t)_flag_a);
- edx = edx + 4; /* 0x3B0045B5: add edx, 4 */
- _flag_k = FK_ADD;
- _flag_a = (uint32_t)(esi); _flag_b = (uint32_t)(1);
- esi = esi - 1; /* 0x3B0045B8: dec esi */
- _flag_k = FK_DEC;
- { double _v = fp_pop(); _st[0] += _v; } /* 0x3B0045B9: faddp st(1) */
- fp_push(*(float*)&MEM32(eax + (-0x14))); /* 0x3B0045BB: fld dword ptr [eax - 0x14] */
- _st[0] *= (double)*(float*)ADDR(ecx + (-0x4)); /* 0x3B0045BE: fmul dword ptr [ecx - 4] */
- { double _v = fp_pop(); _st[0] += _v; } /* 0x3B0045C1: faddp st(1) */
- fp_push(*(float*)&MEM32(eax + (-0x4))); /* 0x3B0045C3: fld dword ptr [eax - 4] */
- _st[0] *= (double)*(float*)ADDR(ecx); /* 0x3B0045C6: fmul dword ptr [ecx] */
- { double _v = fp_pop(); _st[0] += _v; } /* 0x3B0045C8: faddp st(1) */
- { float _v = (float)fp_pop(); *(float*)ADDR(edx + (-0x4)) = _v; } /* 0x3B0045CA: fstp dword ptr [edx - 4] */
- RECOMP_BACKEDGE();
- if (/* dec result */ CMP_NE(_flag_a, _flag_b)) goto L_3B0045A6; /* 0x3B0045CD: jne 0x3b0045a6 */
-L_3B0045CF:
- _flag_a = (uint32_t)(ecx); _flag_b = (uint32_t)(0x10u);
- _cf = (uint32_t)((uint32_t)(_flag_a + _flag_b) < (uint32_t)_flag_a);
- ecx = ecx + 0x10u; /* 0x3B0045CF: add ecx, 0x10 */
- _flag_k = FK_ADD;
- _flag_a = (uint32_t)(edi); _flag_b = (uint32_t)(1);
- edi = edi - 1; /* 0x3B0045D2: dec edi */
- _flag_k = FK_DEC;
- RECOMP_BACKEDGE();
- if (/* dec result */ CMP_NE(_flag_a, _flag_b)) goto L_3B00459E; /* 0x3B0045D3: jne 0x3b00459e */
-L_3B0045D5:
- eax = MEM32(ebp + 0x8); /* 0x3B0045D5: mov eax, dword ptr [ebp + 8] */
- ecx = 0x10u; /* 0x3B0045D8: mov ecx, 0x10 */
- esi = ebp + (-0x44); /* 0x3B0045DD: lea esi, [ebp - 0x44] */
- edi = eax; /* 0x3B0045E0: mov edi, eax */
- { uint32_t _n = ecx, _b = _n * 4u; /* 0x3B0045E2: rep movsd dword ptr es:[edi], dword ptr [esi] */ if (_df > 0) { memmove((void*)ADDR(edi), (void*)ADDR(esi), _b); esi += _b; edi += _b; } else { memmove((void*)ADDR(edi - _b + 4u), (void*)ADDR(esi - _b + 4u), _b); esi -= _b; edi -= _b; } ecx = 0; }
- edi = POP32_VAL(esp); /* 0x3B0045E4: pop edi */
- esi = POP32_VAL(esp); /* 0x3B0045E5: pop esi */
- ebx = POP32_VAL(esp); /* 0x3B0045E6: pop ebx */
- esp = ebp; /* 0x3B0045E7: mov esp, ebp */
- ebp = POP32_VAL(esp); /* 0x3B0045E9: pop ebp */
- RECOMP_FLAGS_OUT(); esp += 12; { RECOMP_REGS_OUT(); return; } /* 0x3B0045EA: ret 8 */
- RECOMP_REGS_OUT();
+ uint32_t matrix = g_ecx, output = MEM32(g_esp + 4);
+ matrix4_multiply(output, matrix, MEM32(g_esp + 8));
+
+ /* The returned value uses the caller's hidden result pointer. */
+ g_eax = output;
+ g_ecx = 0;
+ g_edx = g_esp - 8;
+ g_esp += 12;
+ g_flag_k = FK_DEC;
+ g_flag_a = g_flag_b = 1;
+ g_flag_cf = (uint32_t)(matrix + 72) < (uint32_t)(matrix + 56);
}
void sub_3B0045F0(void) {
diff --git a/src/runtime/browser_audio.c b/src/runtime/browser_audio.c
@@ -0,0 +1,96 @@
+#include "browser_audio.h"
+#include <assert.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+unsigned ao_audio_open(int rate, int channels, int bits);
+int ao_audio_ready(unsigned handle);
+double ao_audio_submit(unsigned handle, const void *buffer, int frames);
+void ao_audio_clear(unsigned handle);
+void ao_audio_close(unsigned handle);
+
+struct audio_output {
+ SDL_AudioSpec format;
+ pthread_t thread;
+ pthread_mutex_t mutex;
+ pthread_cond_t condition;
+ unsigned handle;
+ int paused, closed;
+};
+
+static void *mix_audio(void *argument)
+{
+ struct audio_output *output = argument;
+ unsigned char *buffer = malloc(output->format.size);
+ if (!buffer) abort();
+ for (;;) {
+ /* Only workers take this lock; the browser receives completed PCM blocks. */
+ if (pthread_mutex_lock(&output->mutex)) abort();
+ while (output->paused && !output->closed)
+ if (pthread_cond_wait(&output->condition, &output->mutex)) abort();
+ if (output->closed) {
+ if (pthread_mutex_unlock(&output->mutex)) abort();
+ break;
+ }
+ double delay = 10;
+ if (ao_audio_ready(output->handle)) {
+ output->format.callback(output->format.userdata, buffer, output->format.size);
+ delay = ao_audio_submit(output->handle, buffer, output->format.samples);
+ }
+ if (pthread_mutex_unlock(&output->mutex)) abort();
+ usleep((unsigned)(delay * 1000));
+ }
+ free(buffer);
+ return NULL;
+}
+
+SDL_AudioDeviceID audio_output_open(const SDL_AudioSpec *desired, SDL_AudioSpec *obtained)
+{
+ assert(desired->format == AUDIO_S16LSB || desired->format == AUDIO_U8);
+ assert(desired->channels == 1 || desired->channels == 2);
+ struct audio_output *output = calloc(1, sizeof(*output));
+ if (!output) abort();
+ output->format = *desired;
+ output->format.size = desired->samples * desired->channels * (SDL_AUDIO_BITSIZE(desired->format) / 8);
+ output->format.silence = desired->format == AUDIO_U8 ? 128 : 0;
+ output->paused = 1;
+ if (pthread_mutex_init(&output->mutex, NULL) || pthread_cond_init(&output->condition, NULL)) abort();
+ output->handle = ao_audio_open(desired->freq, desired->channels, SDL_AUDIO_BITSIZE(desired->format));
+ if (pthread_create(&output->thread, NULL, mix_audio, output)) abort();
+ *obtained = output->format;
+ return (uintptr_t)output;
+}
+
+void audio_output_lock(SDL_AudioDeviceID device)
+{
+ if (pthread_mutex_lock(&((struct audio_output *)(uintptr_t)device)->mutex)) abort();
+}
+
+void audio_output_unlock(SDL_AudioDeviceID device)
+{
+ if (pthread_mutex_unlock(&((struct audio_output *)(uintptr_t)device)->mutex)) abort();
+}
+
+void audio_output_pause(SDL_AudioDeviceID device, int paused)
+{
+ struct audio_output *output = (void *)(uintptr_t)device;
+ audio_output_lock(device);
+ output->paused = paused;
+ if (paused) ao_audio_clear(output->handle);
+ if (pthread_cond_signal(&output->condition)) abort();
+ audio_output_unlock(device);
+}
+
+void audio_output_close(SDL_AudioDeviceID device)
+{
+ struct audio_output *output = (void *)(uintptr_t)device;
+ audio_output_lock(device);
+ output->closed = 1;
+ if (pthread_cond_signal(&output->condition)) abort();
+ audio_output_unlock(device);
+ if (pthread_join(output->thread, NULL)) abort();
+ ao_audio_close(output->handle);
+ if (pthread_cond_destroy(&output->condition) || pthread_mutex_destroy(&output->mutex)) abort();
+ free(output);
+}
diff --git a/src/runtime/browser_audio.h b/src/runtime/browser_audio.h
@@ -0,0 +1,12 @@
+#ifndef BROWSER_AUDIO_H
+#define BROWSER_AUDIO_H
+
+#include <SDL2/SDL.h>
+
+SDL_AudioDeviceID audio_output_open(const SDL_AudioSpec *desired, SDL_AudioSpec *obtained);
+void audio_output_close(SDL_AudioDeviceID device);
+void audio_output_lock(SDL_AudioDeviceID device);
+void audio_output_unlock(SDL_AudioDeviceID device);
+void audio_output_pause(SDL_AudioDeviceID device, int paused);
+
+#endif
diff --git a/src/runtime/browser_audio.js b/src/runtime/browser_audio.js
@@ -0,0 +1,52 @@
+addToLibrary({
+ $AOAudio: {next: 1, devices: new Map()},
+ ao_audio_open__deps: ['$AOAudio'],
+ ao_audio_open__proxy: 'sync',
+ ao_audio_open: (rate, channels, bits) => {
+ const context = Module['audioContext'] ||= new AudioContext();
+ const handle = AOAudio.next++;
+ AOAudio.devices.set(handle, {context, rate, channels, bits, nextTime: 0, sources: new Set()});
+ return handle;
+ },
+ ao_audio_ready__deps: ['$AOAudio'],
+ ao_audio_ready__proxy: 'sync',
+ ao_audio_ready: (handle) => AOAudio.devices.get(handle).context.state === 'running',
+ ao_audio_submit__deps: ['$AOAudio'],
+ ao_audio_submit__proxy: 'sync',
+ ao_audio_submit: (handle, data, frames) => {
+ const output = AOAudio.devices.get(handle);
+ const buffer = output.context.createBuffer(output.channels, frames, output.rate);
+ for (let channel = 0; channel < output.channels; ++channel) {
+ const samples = buffer.getChannelData(channel);
+ for (let frame = 0; frame < frames; ++frame) {
+ const index = frame * output.channels + channel;
+ samples[frame] = output.bits === 16 ? HEAP16[(data >> 1) + index] / 32768 :
+ (HEAPU8[data + index] - 128) / 128;
+ }
+ }
+ const source = output.context.createBufferSource();
+ source.buffer = buffer;
+ source.connect(output.context.destination);
+ output.sources.add(source);
+ source.onended = () => { output.sources.delete(source); source.disconnect(); };
+ // Keep a short queue ahead of the playback clock without blocking the UI thread.
+ const start = Math.max(output.nextTime, output.context.currentTime + .01);
+ source.start(start);
+ output.nextTime = start + frames / output.rate;
+ return Math.max(1, (output.nextTime - output.context.currentTime - .03) * 1000);
+ },
+ ao_audio_clear__deps: ['$AOAudio'],
+ ao_audio_clear__proxy: 'sync',
+ ao_audio_clear: (handle) => {
+ const output = AOAudio.devices.get(handle);
+ for (const source of output.sources) { source.stop(); source.disconnect(); }
+ output.sources.clear();
+ output.nextTime = 0;
+ },
+ ao_audio_close__deps: ['$AOAudio', 'ao_audio_clear'],
+ ao_audio_close__proxy: 'sync',
+ ao_audio_close: (handle) => {
+ _ao_audio_clear(handle);
+ AOAudio.devices.delete(handle);
+ }
+});
diff --git a/src/runtime/browser_host.c b/src/runtime/browser_host.c
@@ -0,0 +1,65 @@
+#include <emscripten/wasmfs.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <assert.h>
+
+char *ao_asset_manifest(const char *base);
+char *ao_asset_base_url(void);
+
+void browser_initialize(void)
+{
+ /* FetchFS performs range requests on its own worker while game threads wait. */
+ char *base = ao_asset_base_url();
+ backend_t remote = wasmfs_create_fetch_backend(base, 1024 * 1024);
+ char *manifest = ao_asset_manifest(base);
+ assert(manifest);
+ free(base);
+ assert(wasmfs_create_directory("/remote", 0755, remote) == 0);
+ assert(mkdir("/game", 0755) == 0);
+ assert(chdir("/game") == 0);
+ assert(mkdir("/proc", 0755) == 0);
+ assert(mkdir("/proc/self", 0755) == 0);
+ assert(symlink("/game/game.wasm", "/proc/self/exe") == 0);
+ for (char *name = strtok(manifest, "\n"); name; name = strtok(NULL, "\n")) {
+ char path[4096];
+ snprintf(path, sizeof(path), "/remote/%s", name);
+ size_t length = strlen(name);
+ int directory = name[length - 1] == '/';
+ if (directory) {
+ path[strlen(path) - 1] = 0;
+ assert(mkdir(path, 0755) == 0);
+ } else {
+ int file = open(path, O_CREAT | O_RDONLY, 0644);
+ assert(file >= 0);
+ close(file);
+ }
+ /* Preferences live in writable memory, independent of the native client. */
+ if (!strncmp(name, "Prefs/", 6)) {
+ if (directory) {
+ name[length - 1] = 0;
+ assert(mkdir(name, 0755) == 0);
+ } else {
+ FILE *source = fopen(path, "rb"), *destination = fopen(name, "wb");
+ assert(source && destination);
+ unsigned char buffer[8192];
+ size_t size;
+ while ((size = fread(buffer, 1, sizeof(buffer), source)))
+ assert(fwrite(buffer, 1, size, destination) == size);
+ assert(!ferror(source));
+ fclose(source);
+ fclose(destination);
+ }
+ }
+ }
+ free(manifest);
+ assert(symlink("/remote/cd_image", "cd_image") == 0);
+ assert(symlink("/remote/Setupf", "Setupf") == 0);
+ assert(symlink("/remote/fonts", "fonts") == 0);
+ assert(symlink("/remote/version.id", "version.id") == 0);
+ setenv("ANARCHY_CD", "cd_image", 1);
+ setenv("ANARCHY_SETUP", "Setupf", 1);
+ setenv("ANARCHY", ".", 1);
+}
diff --git a/src/runtime/browser_host.js b/src/runtime/browser_host.js
@@ -0,0 +1,14 @@
+addToLibrary({
+ ao_asset_manifest__deps: ['$stringToNewUTF8', '$UTF8ToString'],
+ ao_asset_manifest: (base) => {
+ // This call runs on the game worker, where synchronous XHR may block safely.
+ const request = new XMLHttpRequest();
+ request.open('GET', new URL('/browser-manifest', UTF8ToString(base)).href, false);
+ request.send();
+ if (request.status !== 200) throw new Error(`Asset manifest: HTTP ${request.status}`);
+ return stringToNewUTF8(request.responseText);
+ },
+ ao_asset_base_url__deps: ['$stringToNewUTF8'],
+ ao_asset_base_url__proxy: 'sync',
+ ao_asset_base_url: () => stringToNewUTF8(new URL('/browser-assets', location.href).href)
+});
diff --git a/src/runtime/browser_network.c b/src/runtime/browser_network.c
@@ -0,0 +1,367 @@
+#include "linux_network.h"
+#include "linux_sync.h"
+#include "guest_heap.h"
+#include <pthread.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#include <emscripten.h>
+
+/* WebSocket callbacks run on the browser UI thread; only game workers wait. */
+int ao_socket_create(void);
+void ao_socket_connect(int handle);
+int ao_socket_status(int handle);
+int ao_socket_available(int handle);
+int ao_socket_send(int handle, const void *data, int size);
+int ao_socket_receive(int handle, void *data, int size, int peek);
+void ao_socket_close(int handle);
+
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+static unsigned startup_count;
+static int watching;
+static struct browser_socket {
+ uint32_t handle, selected, armed, recorded, error;
+ int nonblocking;
+ struct semaphore_handle *event;
+ struct browser_socket *next;
+} *sockets;
+
+static struct browser_socket *find_socket_locked(uint32_t handle)
+{
+ if (!startup_count) { MEM32(g_fs_base + 0x34) = 10093; return NULL; }
+ for (struct browser_socket *socket = sockets; socket; socket = socket->next)
+ if (socket->handle == handle) return socket;
+ MEM32(g_fs_base + 0x34) = 10038;
+ return NULL;
+}
+
+static void *watch_events(void *argument)
+{
+ for (;;) {
+ pthread_mutex_lock(&mutex);
+ for (struct browser_socket *socket = sockets; socket; socket = socket->next) {
+ if (!socket->armed) continue;
+ int status = ao_socket_status(socket->handle);
+ uint32_t ready = (status & 2 ? 1 : 0) | (status & 12 ? 32 : 0);
+ ready &= socket->armed;
+ socket->recorded |= ready;
+ socket->armed &= ~ready;
+ if (status & 8) socket->error = 10054;
+ if (ready && socket->event) linux_sync_event_change(socket->event, 1);
+ }
+ pthread_mutex_unlock(&mutex);
+ usleep(5000);
+ }
+ return NULL;
+}
+
+static void create_socket(void)
+{
+ uint32_t family = MEM32(g_esp + 4), type = MEM32(g_esp + 8), protocol = MEM32(g_esp + 12);
+ g_esp += 16;
+ g_eax = UINT32_MAX;
+ if (family != 2 || type != 1 || (protocol && protocol != 6)) {
+ fprintf(stderr, "Unsupported browser socket: %u %u %u\n", family, type, protocol);
+ abort();
+ }
+ pthread_mutex_lock(&mutex);
+ if (!startup_count) MEM32(g_fs_base + 0x34) = 10093;
+ else {
+ struct browser_socket *socket = calloc(1, sizeof(*socket));
+ if (!socket) abort();
+ socket->handle = ao_socket_create();
+ socket->next = sockets;
+ sockets = socket;
+ g_eax = socket->handle;
+ }
+ pthread_mutex_unlock(&mutex);
+}
+
+static void close_socket(void)
+{
+ pthread_mutex_lock(&mutex);
+ struct browser_socket *socket = find_socket_locked(MEM32(g_esp + 4));
+ g_eax = UINT32_MAX;
+ if (socket) {
+ struct browser_socket **link = &sockets;
+ while (*link != socket) link = &(*link)->next;
+ *link = socket->next;
+ if (socket->event) linux_sync_event_release(socket->event);
+ ao_socket_close(socket->handle);
+ free(socket);
+ g_eax = 0;
+ }
+ pthread_mutex_unlock(&mutex);
+ g_esp += 8;
+}
+
+static void connect_socket(void)
+{
+ uint32_t handle = MEM32(g_esp + 4), address = MEM32(g_esp + 8), size = MEM32(g_esp + 12);
+ g_esp += 16;
+ g_eax = UINT32_MAX;
+ if (!address || size < 16) { MEM32(g_fs_base + 0x34) = 10014; return; }
+ if (MEM16(address) != 2) { MEM32(g_fs_base + 0x34) = 10047; return; }
+ pthread_mutex_lock(&mutex);
+ struct browser_socket *socket = find_socket_locked(handle);
+ int nonblocking = socket ? socket->nonblocking : 0;
+ if (socket) ao_socket_connect(handle);
+ pthread_mutex_unlock(&mutex);
+ if (!socket) return;
+ if (nonblocking) { MEM32(g_fs_base + 0x34) = 10035; return; }
+ int status;
+ while (!((status = ao_socket_status(handle)) & 13)) usleep(1000);
+ if (status & 1) g_eax = 0;
+ else MEM32(g_fs_base + 0x34) = 10061;
+}
+
+static void control_socket(void)
+{
+ uint32_t command = MEM32(g_esp + 8), argument = MEM32(g_esp + 12);
+ pthread_mutex_lock(&mutex);
+ struct browser_socket *socket = find_socket_locked(MEM32(g_esp + 4));
+ g_eax = UINT32_MAX;
+ if (socket && argument) {
+ if (command == 0x8004667e) socket->nonblocking = MEM32(argument) != 0;
+ else if (command == 0x4004667f) MEM32(argument) = ao_socket_available(socket->handle);
+ else { fprintf(stderr, "Unsupported browser ioctlsocket: %08x\n", command); abort(); }
+ g_eax = 0;
+ }
+ pthread_mutex_unlock(&mutex);
+ g_esp += 16;
+}
+
+static void local_socket_address(void)
+{
+ uint32_t output = MEM32(g_esp + 8), length = MEM32(g_esp + 12);
+ pthread_mutex_lock(&mutex);
+ struct browser_socket *socket = find_socket_locked(MEM32(g_esp + 4));
+ g_eax = UINT32_MAX;
+ if (socket) {
+ uint32_t error = 0;
+ if (!output || !length || (int32_t)MEM32(length) < 16) error = 10014;
+ else if (!(ao_socket_status(socket->handle) & 1)) error = 10022;
+ else {
+ /* WebSocket hides the transport endpoint. Report the local virtual
+ * interface, with port zero because no TCP port is exposed. */
+ memset((void *)ADDR(output), 0, 16);
+ MEM16(output) = 2;
+ MEM32(output + 4) = 0x0100007f;
+ MEM32(length) = 16;
+ g_eax = 0;
+ }
+ MEM32(g_fs_base + 0x34) = error;
+ }
+ pthread_mutex_unlock(&mutex);
+ g_esp += 16;
+}
+
+static void transfer_socket(int sending)
+{
+ uint32_t handle = MEM32(g_esp + 4), buffer = MEM32(g_esp + 8), flags = MEM32(g_esp + 16);
+ int32_t size = MEM32(g_esp + 12);
+ g_esp += 20;
+ g_eax = UINT32_MAX;
+ if (!buffer || size < 0) { MEM32(g_fs_base + 0x34) = 10014; return; }
+ if (flags && (sending || flags != 2)) abort();
+ pthread_mutex_lock(&mutex);
+ struct browser_socket *socket = find_socket_locked(handle);
+ int nonblocking = socket ? socket->nonblocking : 0;
+ pthread_mutex_unlock(&mutex);
+ if (!socket) return;
+ int result;
+ do {
+ result = sending ? ao_socket_send(handle, (void *)ADDR(buffer), size) :
+ ao_socket_receive(handle, (void *)ADDR(buffer), size, flags == 2);
+ if (result == -10035 && !nonblocking) usleep(1000);
+ } while (result == -10035 && !nonblocking);
+ if (result < 0) MEM32(g_fs_base + 0x34) = -result;
+ else g_eax = result;
+ if (!sending) {
+ pthread_mutex_lock(&mutex);
+ for (socket = sockets; socket; socket = socket->next)
+ if (socket->handle == handle) { socket->armed |= socket->selected & 1; break; }
+ pthread_mutex_unlock(&mutex);
+ }
+}
+static void send_socket(void) { transfer_socket(1); }
+static void receive_socket(void) { transfer_socket(0); }
+
+static void event_select(void)
+{
+ uint32_t handle = MEM32(g_esp + 4), event = MEM32(g_esp + 8), mask = MEM32(g_esp + 12);
+ if (mask & ~0x21u) abort();
+ pthread_mutex_lock(&mutex);
+ struct browser_socket *socket = find_socket_locked(handle);
+ g_eax = UINT32_MAX;
+ if (socket) {
+ if (socket->event) linux_sync_event_release(socket->event);
+ socket->event = event && mask ? linux_sync_event_acquire(event) : NULL;
+ socket->selected = socket->armed = mask;
+ socket->recorded = socket->error = 0;
+ socket->nonblocking = 1;
+ if (mask && !watching) {
+ pthread_t thread;
+ if (pthread_create(&thread, NULL, watch_events, NULL) || pthread_detach(thread)) abort();
+ watching = 1;
+ }
+ g_eax = 0;
+ }
+ pthread_mutex_unlock(&mutex);
+ g_esp += 16;
+}
+
+static void enum_events(void)
+{
+ uint32_t event = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
+ pthread_mutex_lock(&mutex);
+ struct browser_socket *socket = find_socket_locked(MEM32(g_esp + 4));
+ g_eax = UINT32_MAX;
+ if (socket && output) {
+ memset((void *)ADDR(output), 0, 44);
+ MEM32(output) = socket->recorded;
+ MEM32(output + 24) = socket->error;
+ socket->recorded = 0;
+ if (event) {
+ struct semaphore_handle *signal = linux_sync_event_acquire(event);
+ if (!signal) abort();
+ linux_sync_event_change(signal, 0);
+ linux_sync_event_release(signal);
+ }
+ g_eax = 0;
+ }
+ pthread_mutex_unlock(&mutex);
+ g_esp += 16;
+}
+
+static void select_sockets(void)
+{
+ uint32_t sets[] = {MEM32(g_esp + 8), MEM32(g_esp + 12), MEM32(g_esp + 16)};
+ uint32_t timeout = MEM32(g_esp + 20), counts[3], ready[3][64];
+ double deadline = timeout ? emscripten_get_now() + MEM32(timeout) * 1000.0 + MEM32(timeout + 4) / 1000.0 : INFINITY;
+ for (unsigned i = 0; i < 3; ++i) {
+ counts[i] = sets[i] ? MEM32(sets[i]) : 0;
+ if (counts[i] > 64) abort();
+ }
+ g_esp += 24;
+ for (;;) {
+ uint32_t total = 0, found[3] = {0};
+ for (unsigned i = 0; i < 3; ++i) for (unsigned j = 0; j < counts[i]; ++j) {
+ uint32_t handle = MEM32(sets[i] + 4 + j * 4);
+ int status = ao_socket_status(handle);
+ if (status & (i == 0 ? 14 : i == 1 ? 1 : 8)) {
+ ready[i][found[i]++] = handle;
+ ++total;
+ }
+ }
+ if (total || emscripten_get_now() >= deadline) {
+ for (unsigned i = 0; i < 3; ++i) if (sets[i]) {
+ MEM32(sets[i]) = found[i];
+ memcpy((void *)ADDR(sets[i] + 4), ready[i], found[i] * 4);
+ }
+ g_eax = total;
+ return;
+ }
+ usleep(1000);
+ }
+}
+
+static void socket_in_set(void)
+{
+ uint32_t handle = MEM32(g_esp + 4), set = MEM32(g_esp + 8);
+ g_eax = 0;
+ for (unsigned i = 0; set && i < MEM32(set); ++i)
+ if (MEM32(set + 4 + i * 4) == handle) { g_eax = 1; break; }
+ g_esp += 12;
+}
+
+static void network_long(void) { g_eax = __builtin_bswap32(MEM32(g_esp + 4)); g_esp += 8; }
+static void network_short(void) { g_eax = __builtin_bswap16(MEM16(g_esp + 4)); g_esp += 8; }
+static void address_string(void)
+{
+ struct in_addr address = {MEM32(g_esp + 4)};
+ /* Keep the result in the guest thread's own storage, as on Linux. */
+ g_eax = g_fs_base + 0x2100;
+ if (!inet_ntop(AF_INET, &address, (char *)ADDR(g_eax), 16)) abort();
+ MEM32(g_fs_base + 0x34) = 0;
+ g_esp += 8;
+}
+static void last_error(void) { g_eax = MEM32(g_fs_base + 0x34); g_esp += 4; }
+static void set_error(void) { MEM32(g_fs_base + 0x34) = MEM32(g_esp + 4); g_esp += 8; }
+
+static void startup(void)
+{
+ uint32_t data = MEM32(g_esp + 8);
+ uint16_t requested = MEM16(g_esp + 4);
+ g_eax = 10014;
+ if (data) {
+ MEM16(data) = requested;
+ MEM16(data + 2) = 0x0202;
+ strcpy((char *)ADDR(data + 4), "WinSock 2.0");
+ strcpy((char *)ADDR(data + 261), "Running");
+ MEM16(data + 390) = MEM16(data + 392) = 0;
+ pthread_mutex_lock(&mutex);
+ ++startup_count;
+ pthread_mutex_unlock(&mutex);
+ g_eax = 0;
+ }
+ g_esp += 12;
+}
+
+static void cleanup(void)
+{
+ pthread_mutex_lock(&mutex);
+ g_eax = UINT32_MAX;
+ if (startup_count) {
+ if (!--startup_count) while (sockets) {
+ struct browser_socket *socket = sockets;
+ sockets = socket->next;
+ if (socket->event) linux_sync_event_release(socket->event);
+ ao_socket_close(socket->handle);
+ free(socket);
+ }
+ g_eax = 0;
+ } else MEM32(g_fs_base + 0x34) = 10093;
+ pthread_mutex_unlock(&mutex);
+ g_esp += 4;
+}
+
+static void host_name(void)
+{
+ if (pthread_mutex_lock(&mutex)) abort();
+ uint32_t output = MEM32(g_esp + 4);
+ int32_t size = MEM32(g_esp + 8);
+ char name[256];
+ uint32_t error = 0;
+ if (!startup_count) error = 10093; /* WSANOTINITIALISED */
+ else if (!output || size <= 0) error = 10014; /* WSAEFAULT */
+ else if (gethostname(name, sizeof(name))) error = 10050; /* WSAENETDOWN */
+ else if ((size_t)size <= strlen(name)) error = 10014;
+ else memcpy((void *)ADDR(output), name, strlen(name) + 1);
+
+ MEM32(g_fs_base + 0x34) = error;
+ g_eax = error ? UINT32_MAX : 0;
+ g_esp += 12;
+ if (pthread_mutex_unlock(&mutex)) abort();
+}
+
+recomp_func_t linux_network_lookup(const char *name, uint32_t ordinal)
+{
+ static const struct { const char *name; uint32_t ordinal; recomp_func_t function; } functions[] = {
+ {"gethostname", 57, host_name},
+ {"inet_ntoa", 12, address_string},
+ {"WSAStartup", 115, startup}, {"WSACleanup", 116, cleanup},
+ {"WSAGetLastError", 111, last_error}, {"WSASetLastError", 112, set_error},
+ {"htonl", 8, network_long}, {"htons", 9, network_short},
+ {"ntohl", 14, network_long}, {"ntohs", 15, network_short},
+ {"socket", 23, create_socket}, {"closesocket", 3, close_socket},
+ {"getsockname", 6, local_socket_address},
+ {"ioctlsocket", 10, control_socket}, {"connect", 4, connect_socket},
+ {"send", 19, send_socket}, {"recv", 16, receive_socket},
+ {"select", 18, select_sockets}, {"__WSAFDIsSet", 151, socket_in_set},
+ {"WSAEventSelect", 0, event_select}, {"WSAEnumNetworkEvents", 0, enum_events},
+ };
+ for (unsigned i = 0; i < sizeof(functions) / sizeof(functions[0]); ++i)
+ if (name ? !strcmp(name, functions[i].name) : ordinal && ordinal == functions[i].ordinal)
+ return functions[i].function;
+ return NULL;
+}
diff --git a/src/runtime/browser_network.js b/src/runtime/browser_network.js
@@ -0,0 +1,86 @@
+addToLibrary({
+ $AOSockets: {next: 0x09000000, sockets: new Map()},
+ ao_socket_create__deps: ['$AOSockets'],
+ ao_socket_create__proxy: 'sync',
+ ao_socket_create: () => {
+ const handle = AOSockets.next;
+ AOSockets.next += 4;
+ AOSockets.sockets.set(handle, {socket: null, chunks: [], offset: 0, bytes: 0, error: false});
+ return handle;
+ },
+ ao_socket_connect__deps: ['$AOSockets'],
+ ao_socket_connect__proxy: 'sync',
+ ao_socket_connect: (handle) => {
+ const entry = AOSockets.sockets.get(handle);
+ const url = new URL('/browser-world', location.href);
+ url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
+ entry.socket = new WebSocket(url);
+ entry.socket.binaryType = 'arraybuffer';
+ entry.socket.onmessage = (event) => {
+ if (!(event.data instanceof ArrayBuffer)) {
+ entry.error = true;
+ entry.socket.close(1003, 'AO requires binary messages');
+ return;
+ }
+ if (event.data.byteLength) {
+ entry.chunks.push(new Uint8Array(event.data));
+ entry.bytes += event.data.byteLength;
+ }
+ };
+ entry.socket.onerror = () => { entry.error = true; };
+ },
+ ao_socket_status__deps: ['$AOSockets'],
+ ao_socket_status__proxy: 'sync',
+ ao_socket_status: (handle) => {
+ const entry = AOSockets.sockets.get(handle);
+ if (!entry) return 12;
+ return (entry.socket?.readyState === 1 ? 1 : 0) | (entry.bytes ? 2 : 0) |
+ (entry.socket?.readyState === 3 ? 4 : 0) | (entry.error ? 8 : 0);
+ },
+ ao_socket_available__deps: ['$AOSockets'],
+ ao_socket_available__proxy: 'sync',
+ ao_socket_available: (handle) => AOSockets.sockets.get(handle)?.bytes || 0,
+ ao_socket_send__deps: ['$AOSockets'],
+ ao_socket_send__proxy: 'sync',
+ ao_socket_send: (handle, data, size) => {
+ const entry = AOSockets.sockets.get(handle);
+ if (!entry || entry.socket?.readyState !== 1) return -10057;
+ entry.socket.send(HEAPU8.slice(data, data + size));
+ return size;
+ },
+ ao_socket_receive__deps: ['$AOSockets'],
+ ao_socket_receive__proxy: 'sync',
+ ao_socket_receive: (handle, data, size, peek) => {
+ const entry = AOSockets.sockets.get(handle);
+ if (!entry) return -10038;
+ if (!size) return 0;
+ if (!entry.bytes) {
+ if (entry.error) return -10054;
+ return entry.socket?.readyState === 3 ? 0 : -10035;
+ }
+ let copied = 0, index = 0, offset = entry.offset;
+ while (copied < size && index < entry.chunks.length) {
+ const chunk = entry.chunks[index];
+ const count = Math.min(size - copied, chunk.length - offset);
+ HEAPU8.set(chunk.subarray(offset, offset + count), data + copied);
+ copied += count;
+ offset += count;
+ if (offset === chunk.length) { ++index; offset = 0; }
+ }
+ if (!peek) {
+ entry.chunks.splice(0, index);
+ entry.offset = offset;
+ entry.bytes -= copied;
+ }
+ return copied;
+ },
+ ao_socket_close__deps: ['$AOSockets'],
+ ao_socket_close__proxy: 'sync',
+ ao_socket_close: (handle) => {
+ const entry = AOSockets.sockets.get(handle);
+ if (entry) {
+ entry.socket?.close();
+ AOSockets.sockets.delete(handle);
+ }
+ }
+});
diff --git a/src/runtime/gl_renderer.c b/src/runtime/gl_renderer.c
@@ -1,9 +1,16 @@
#define GL_GLEXT_PROTOTYPES
#include "gl_renderer.h"
+#ifdef __EMSCRIPTEN__
+#include <GLES3/gl3.h>
+#define SHADER_VERSION "#version 300 es\nprecision highp float;\nprecision highp int;\n"
+#else
#include <SDL2/SDL_opengl.h>
+#define SHADER_VERSION "#version 330 core\n"
+#endif
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
#include <assert.h>
static GLuint program, vertex_array, vertex_buffer, index_buffer;
@@ -57,7 +64,7 @@ int gl_renderer_initialize(void)
{
if (program) return 1;
const char *sources[] = {
- "#version 330 core\n"
+ SHADER_VERSION
"layout(location=0) in vec4 position;\n"
"layout(location=1) in vec4 diffuse;\n"
"layout(location=2) in vec2 texcoord;\n"
@@ -66,7 +73,7 @@ int gl_renderer_initialize(void)
"layout(location=5) in vec3 specular; out vec3 highlight;\n"
"out vec4 color; out vec2 uv, uv_second; out float fog_factor;\n"
"void main() { gl_Position=vec4(position.x,-position.y,2.0*position.z-position.w,position.w); color=diffuse; uv=texcoord; uv_second=texcoord_second; fog_factor=fog; highlight=specular; }\n",
- "#version 330 core\n"
+ SHADER_VERSION
"in vec4 color; in vec2 uv, uv_second; in float fog_factor; out vec4 pixel;\n"
"in vec3 highlight;\n"
"uniform bool fog_enabled; uniform vec3 fog_color;\n"
@@ -236,7 +243,6 @@ static int allocate_target(struct gl_target *target)
fprintf(stderr, "Native framebuffer creation failed: %04x\n", status);
return 0;
}
- check_graphics("target creation");
free(target->saved_pixels);
target->saved_pixels = NULL;
return 1;
@@ -247,14 +253,14 @@ static void make_resident(struct gl_target *target)
if (target->saved_pixels && !allocate_target(target)) abort();
}
-struct gl_target *gl_target_create(unsigned width, unsigned height)
+struct gl_target *gl_target_create(unsigned width, unsigned height, int with_depth)
{
struct gl_target *target = calloc(1, sizeof(*target));
if (!target) return NULL;
target->width = width;
target->height = height;
- target->depth = gl_depth_create(width, height, 24);
- if (!target->depth || !allocate_target(target)) { gl_target_destroy(target); return NULL; }
+ if (with_depth) target->depth = gl_depth_create(width, height, 24);
+ if ((with_depth && !target->depth) || !allocate_target(target)) { gl_target_destroy(target); return NULL; }
return target;
}
@@ -272,19 +278,18 @@ void gl_target_destroy(struct gl_target *target)
free(target);
}
-void gl_target_evict(struct gl_target *target)
+void gl_target_evict(struct gl_target *target, const unsigned char *rgba)
{
/* Managed textures retain their contents while releasing GPU allocations. */
assert(!target->depth);
if (target->saved_pixels) return;
unsigned char *pixels = malloc((size_t)target->width * target->height * 4);
if (!pixels) abort();
- gl_target_read(target, pixels);
+ memcpy(pixels, rgba, (size_t)target->width * target->height * 4);
glDeleteFramebuffers(1, &target->framebuffer);
glDeleteTextures(1, &target->color);
target->framebuffer = target->color = 0;
target->saved_pixels = pixels;
- check_graphics("texture eviction");
}
void gl_target_clear(struct gl_target *target, uint32_t argb, float depth)
@@ -308,11 +313,14 @@ void gl_target_clear_rect(struct gl_target *target, uint32_t flags, uint32_t arg
glDepthMask(GL_TRUE);
glClearColor(((argb >> 16) & 255) / 255.0f, ((argb >> 8) & 255) / 255.0f,
(argb & 255) / 255.0f, (argb >> 24) / 255.0f);
+#ifdef __EMSCRIPTEN__
+ glClearDepthf(depth);
+#else
glClearDepth(depth);
+#endif
glClear((flags & 1 ? GL_COLOR_BUFFER_BIT : 0) | (flags & 2 ? GL_DEPTH_BUFFER_BIT : 0));
glDisable(GL_SCISSOR_TEST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
- check_graphics("target clear");
}
void gl_target_draw(struct gl_target *target, unsigned primitive, const struct gl_vertex *vertices,
@@ -351,7 +359,7 @@ void gl_target_draw(struct gl_target *target, unsigned primitive, const struct g
glDisable(GL_SCISSOR_TEST);
glBindVertexArray(0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
- check_graphics("indexed draw");
+ /* Check errors at presentation/readback without synchronizing every draw. */
}
void gl_target_read(struct gl_target *target, unsigned char *rgba)
@@ -360,7 +368,7 @@ void gl_target_read(struct gl_target *target, unsigned char *rgba)
glBindFramebuffer(GL_FRAMEBUFFER, target->framebuffer);
glReadPixels(0, 0, target->width, target->height, GL_RGBA, GL_UNSIGNED_BYTE, rgba);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
- check_graphics("target readback");
+ check_graphics("rendering and target readback");
/* The shader puts the logical top row at GL row zero. This also maps GL's
* bottom-left edge inclusion to Direct3D's top-left rasterization rule. */
@@ -373,7 +381,6 @@ void gl_target_write(struct gl_target *target, const unsigned char *rgba)
glBindTexture(GL_TEXTURE_2D, target->color);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, target->width, target->height,
GL_RGBA, GL_UNSIGNED_BYTE, rgba);
- check_graphics("target upload");
}
void gl_target_blit(struct gl_target *source, struct gl_target *target, const int32_t source_rect[4], const int32_t target_rect[4])
@@ -387,7 +394,6 @@ void gl_target_blit(struct gl_target *source, struct gl_target *target, const in
glBlitFramebuffer(source_rect[0], source_rect[1], source_rect[2], source_rect[3],
target_rect[0], target_rect[1], target_rect[2], target_rect[3], GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
- check_graphics("surface blit");
}
void gl_target_present(struct gl_target *target, const int32_t rectangle[4], int width, int height)
@@ -400,7 +406,7 @@ void gl_target_present(struct gl_target *target, const int32_t rectangle[4], int
glBlitFramebuffer(rectangle[0], rectangle[1], rectangle[2], rectangle[3],
0, height, width, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
- check_graphics("window presentation");
+ check_graphics("frame rendering and presentation");
}
void gl_renderer_set_texture(unsigned stage, const struct gl_texture_state *state)
@@ -446,7 +452,6 @@ void gl_renderer_set_texture(unsigned stage, const struct gl_texture_state *stat
(state->factor >> 24) / 255.0f);
}
glActiveTexture(GL_TEXTURE0);
- check_graphics("texture binding");
}
void gl_renderer_set_depth(int write, uint32_t function, uint32_t bias)
@@ -480,7 +485,6 @@ void gl_renderer_set_fog(int enabled, uint32_t color)
glUniform1i(fog_enabled, enabled);
glUniform3f(fog_color, ((color >> 16) & 255) / 255.0f,
((color >> 8) & 255) / 255.0f, (color & 255) / 255.0f);
- check_graphics("fog state");
}
void gl_renderer_set_blend(int enabled, uint32_t source, uint32_t destination)
@@ -489,7 +493,6 @@ void gl_renderer_set_blend(int enabled, uint32_t source, uint32_t destination)
glEnable(GL_BLEND);
glBlendFunc(blend_factor(source), blend_factor(destination));
} else glDisable(GL_BLEND);
- check_graphics("blend state");
}
void gl_renderer_set_alpha_test(int enabled, uint32_t function, uint32_t reference)
@@ -497,5 +500,4 @@ void gl_renderer_set_alpha_test(int enabled, uint32_t function, uint32_t referen
glUseProgram(program);
glUniform1i(alpha_function, enabled ? function : 8);
glUniform1f(alpha_reference, reference);
- check_graphics("alpha test state");
}
diff --git a/src/runtime/gl_renderer.h b/src/runtime/gl_renderer.h
@@ -23,10 +23,10 @@ struct gl_texture_state {
int gl_renderer_initialize(void);
void gl_renderer_shutdown(void);
-struct gl_target *gl_target_create(unsigned width, unsigned height);
+struct gl_target *gl_target_create(unsigned width, unsigned height, int with_depth);
void gl_target_destroy(struct gl_target *target);
void gl_target_set_mip(struct gl_target *target, struct gl_target *mip);
-void gl_target_evict(struct gl_target *target);
+void gl_target_evict(struct gl_target *target, const unsigned char *rgba);
struct gl_depth *gl_depth_create(unsigned width, unsigned height, unsigned bits);
void gl_depth_destroy(struct gl_depth *depth);
void gl_target_set_depth(struct gl_target *target, struct gl_depth *depth);
diff --git a/src/runtime/guest_memory.c b/src/runtime/guest_memory.c
@@ -1,3 +1,4 @@
+#define _GNU_SOURCE
#include "guest_memory.h"
#include <stdio.h>
#include <stdlib.h>
@@ -6,6 +7,21 @@
unsigned char *guest_pages[65536];
static _Atomic uint64_t mapped_bytes;
+#if defined(__linux__) && UINTPTR_MAX > UINT32_MAX
+#include <pthread.h>
+#include <sys/mman.h>
+
+unsigned char *guest_base;
+static pthread_once_t reservation = PTHREAD_ONCE_INIT;
+
+static void reserve_guest_memory(void)
+{
+ void *memory = mmap(NULL, 0x100000000ull, PROT_NONE,
+ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ if (memory != MAP_FAILED) guest_base = memory;
+}
+#endif
+
/* Kernel32 memory queries report guest mappings, not the host's 64-bit layout. */
uint64_t guest_memory_mapped_bytes(void) { return atomic_load(&mapped_bytes); }
@@ -32,8 +48,15 @@ uint32_t guest_map(const char *name, uint32_t base, uint32_t size)
}
}
+#if defined(__linux__) && UINTPTR_MAX > UINT32_MAX
+ if (pthread_once(&reservation, reserve_guest_memory)) abort();
+ if (!guest_base) return 0;
+ unsigned char *memory = guest_base + base;
+ if (mprotect(memory, (size_t)count * 0x10000u, PROT_READ | PROT_WRITE)) return 0;
+#else
unsigned char *memory = calloc(count, 0x10000u);
if (!memory) return 0;
+#endif
for (uint32_t i = 0; i < count; ++i)
guest_pages[first + i] = memory + (size_t)i * 0x10000u;
atomic_fetch_add(&mapped_bytes, (uint64_t)count * 0x10000u);
diff --git a/src/runtime/guest_memory.h b/src/runtime/guest_memory.h
@@ -10,6 +10,15 @@ uint32_t guest_map(const char *name, uint32_t base, uint32_t size);
extern unsigned char *guest_pages[65536];
void guest_memory_fault(uint32_t address);
+#if defined(__linux__) && UINTPTR_MAX > UINT32_MAX
+extern unsigned char *guest_base;
+
+static inline uintptr_t guest_address(uint32_t address)
+{
+ /* Unmapped pages remain inaccessible in the reserved guest address space. */
+ return address ? (uintptr_t)guest_base + address : 0;
+}
+#else
static inline uintptr_t guest_address(uint32_t address)
{
/* Null pointers also occur in zero-length bulk operations. */
@@ -18,6 +27,7 @@ static inline uintptr_t guest_address(uint32_t address)
if (!page) guest_memory_fault(address);
return (uintptr_t)(page + (address & 0xffffu));
}
+#endif
#else
static inline uintptr_t guest_address(uint32_t address)
{
diff --git a/src/runtime/linux_audio.c b/src/runtime/linux_audio.c
@@ -8,6 +8,15 @@
#include <limits.h>
#include <math.h>
+#ifdef __EMSCRIPTEN__
+#include "browser_audio.h"
+#else
+#define audio_output_close SDL_CloseAudioDevice
+#define audio_output_lock SDL_LockAudioDevice
+#define audio_output_unlock SDL_UnlockAudioDevice
+#define audio_output_pause SDL_PauseAudioDevice
+#endif
+
static pthread_once_t audio_once = PTHREAD_ONCE_INIT;
static int audio_available;
static pthread_mutex_t audio_mutex = PTHREAD_MUTEX_INITIALIZER;
@@ -40,7 +49,7 @@ static struct audio_driver {
struct audio_sample *samples;
} *drivers;
-/* SDL holds its device lock during this callback; it never enters guest code. */
+/* The output worker holds its device lock; this callback never enters guest code. */
static void render_audio(void *userdata, Uint8 *output, int length)
{
struct audio_driver *driver = userdata;
@@ -96,7 +105,7 @@ static void render_audio(void *userdata, Uint8 *output, int length)
static void destroy_driver_locked(struct audio_driver *driver)
{
- SDL_CloseAudioDevice(driver->device);
+ audio_output_close(driver->device);
while (driver->streams) {
struct audio_stream *stream = driver->streams;
driver->streams = stream->next;
@@ -203,8 +212,12 @@ static void wave_out_open(void)
desired.samples = 512;
desired.callback = render_audio;
desired.userdata = driver;
+#ifdef __EMSCRIPTEN__
+ SDL_AudioDeviceID device = audio_output_open(&desired, &driver->format);
+#else
SDL_AudioDeviceID device = SDL_OpenAudioDevice(index == UINT32_MAX ? NULL :
SDL_GetAudioDeviceName(index, 0), 0, &desired, &driver->format, 0);
+#endif
if (device) {
driver->handle = next_driver++;
driver->device = device;
@@ -216,7 +229,12 @@ static void wave_out_open(void)
MEM32(output) = driver->handle;
g_eax = 0;
fprintf(stderr, "[linux-audio] %s: %d Hz, %u channels, %u bits\n",
- SDL_GetCurrentAudioDriver(), desired.freq, channels, bits);
+#ifdef __EMSCRIPTEN__
+ "Web Audio",
+#else
+ SDL_GetCurrentAudioDriver(),
+#endif
+ desired.freq, channels, bits);
} else {
fprintf(stderr, "[linux-audio] open: %s\n", SDL_GetError());
free(driver);
@@ -247,9 +265,9 @@ static void set_digital_master_volume(void)
struct audio_driver *driver = drivers;
while (driver && driver->handle != handle) driver = driver->next;
if (!driver) abort();
- SDL_LockAudioDevice(driver->device);
+ audio_output_lock(driver->device);
driver->volume = (int32_t)MEM32(g_esp + 8);
- SDL_UnlockAudioDevice(driver->device);
+ audio_output_unlock(driver->device);
if (pthread_mutex_unlock(&audio_mutex)) abort();
g_esp += 12;
}
@@ -330,10 +348,10 @@ static void open_stream(void)
stream->frames = size / sizeof(float) / driver->format.channels;
stream->status = 2;
stream->volume = 127;
- SDL_LockAudioDevice(driver->device);
+ audio_output_lock(driver->device);
stream->next = driver->streams;
driver->streams = stream;
- SDL_UnlockAudioDevice(driver->device);
+ audio_output_unlock(driver->device);
g_eax = stream->handle;
fprintf(stderr, "[linux-audio] decoded %s: %u frames\n", path, stream->frames);
} else fprintf(stderr, "[linux-audio] stream %s: %s\n", path, sf_strerror(NULL));
@@ -514,7 +532,7 @@ static void allocate_sample_handle(void)
struct audio_driver *driver = drivers;
while (driver && driver->handle != handle) driver = driver->next;
if (!driver) abort();
- SDL_LockAudioDevice(driver->device);
+ audio_output_lock(driver->device);
unsigned used = 0;
struct audio_sample *available = NULL;
for (struct audio_sample *sample = driver->samples; sample; sample = sample->next) {
@@ -533,7 +551,7 @@ static void allocate_sample_handle(void)
init_sample_locked(available);
g_eax = available->handle;
}
- SDL_UnlockAudioDevice(driver->device);
+ audio_output_unlock(driver->device);
if (pthread_mutex_unlock(&audio_mutex)) abort();
}
@@ -554,7 +572,7 @@ static void sample_control(enum sample_operation operation, unsigned arguments)
if (sample) break;
}
if (!sample) abort();
- SDL_LockAudioDevice(driver->device);
+ audio_output_lock(driver->device);
if (operation == SAMPLE_INIT) init_sample_locked(sample);
else if (operation == SAMPLE_RELEASE) { init_sample_locked(sample); sample->status = 1; }
else if (operation == SAMPLE_STATUS) g_eax = sample->status;
@@ -593,8 +611,8 @@ static void sample_control(enum sample_operation operation, unsigned arguments)
}
}
} else abort();
- SDL_UnlockAudioDevice(driver->device);
- if (operation == SAMPLE_START) SDL_PauseAudioDevice(driver->device, 0);
+ audio_output_unlock(driver->device);
+ if (operation == SAMPLE_START) audio_output_pause(driver->device, 0);
if (pthread_mutex_unlock(&audio_mutex)) abort();
}
@@ -627,7 +645,7 @@ static void stream_control(enum stream_operation operation, unsigned arguments)
if (*link) break;
}
if (!driver) abort();
- SDL_LockAudioDevice(driver->device);
+ audio_output_lock(driver->device);
struct audio_stream *stream = *link;
if (operation == STREAM_STATUS) g_eax = stream->status;
else if (operation == STREAM_POSITION) {
@@ -664,9 +682,9 @@ static void stream_control(enum stream_operation operation, unsigned arguments)
free(stream->samples);
free(stream);
} else abort();
- SDL_UnlockAudioDevice(driver->device);
+ audio_output_unlock(driver->device);
if (operation == STREAM_START || (operation == STREAM_PAUSE && !value))
- SDL_PauseAudioDevice(driver->device, 0);
+ audio_output_pause(driver->device, 0);
if (pthread_mutex_unlock(&audio_mutex)) abort();
}
diff --git a/src/runtime/linux_diagnostics.c b/src/runtime/linux_diagnostics.c
@@ -1,21 +1,31 @@
#include "platform_diagnostics.h"
#include <stdio.h>
#include <stdlib.h>
+#ifdef __EMSCRIPTEN__
+#include <emscripten/heap.h>
+#else
#include <sys/sysinfo.h>
+#endif
#include <sys/utsname.h>
#include <unistd.h>
void platform_describe_system(struct platform_system_description *description)
{
struct utsname system;
+#ifdef __EMSCRIPTEN__
+ if (uname(&system)) { perror("system diagnostics"); abort(); }
+ unsigned long long memory_bytes = emscripten_get_heap_max();
+#else
struct sysinfo memory;
if (uname(&system) || sysinfo(&memory)) { perror("system diagnostics"); abort(); }
+ unsigned long long memory_bytes = (unsigned long long)memory.totalram * memory.mem_unit;
+#endif
snprintf(description->system, sizeof(description->system), "%s", system.sysname);
snprintf(description->version, sizeof(description->version), "%s", system.release);
snprintf(description->processor, sizeof(description->processor), "%s (%ld logical processors)",
system.machine, sysconf(_SC_NPROCESSORS_ONLN));
snprintf(description->memory, sizeof(description->memory), "%llu MB",
- (unsigned long long)memory.totalram * memory.mem_unit / (1024 * 1024));
+ memory_bytes / (1024 * 1024));
}
int platform_write_diagnostics(const char *path)
diff --git a/src/runtime/linux_file.c b/src/runtime/linux_file.c
@@ -12,6 +12,11 @@
struct guest_file {
uint32_t id;
int descriptor, unbuffered;
+#ifdef __EMSCRIPTEN__
+ dev_t device;
+ ino_t inode;
+ int exclusive;
+#endif
struct guest_file *next;
};
static struct guest_file *handles;
@@ -65,7 +70,11 @@ static void create_file_locked(void)
/* OPEN_ALWAYS reports whether it created a file without truncating existing data. */
char *path = linux_path(name);
- int options = O_RDONLY | O_CLOEXEC | O_NONBLOCK | (unbuffered ? O_DIRECT : 0) | (exclusive ? O_SYNC : 0);
+ int options = O_RDONLY | O_CLOEXEC | O_NONBLOCK;
+#ifndef __EMSCRIPTEN__
+ /* WasmFS has no host disk cache; guest alignment and sharing are checked below. */
+ options |= (unbuffered ? O_DIRECT : 0) | (exclusive ? O_SYNC : 0);
+#endif
int descriptor = open(path, options | (unbuffered ? O_CREAT | O_EXCL : 0), 0666);
int created = unbuffered && descriptor >= 0;
if (unbuffered && descriptor < 0 && errno == EEXIST) descriptor = open(path, options);
@@ -79,13 +88,21 @@ static void create_file_locked(void)
}
}
free(path);
+ struct stat info;
if (descriptor >= 0) {
- struct stat info;
if (fstat(descriptor, &info)) error = file_error(errno);
else if (!S_ISREG(info.st_mode)) error = 5;
/* All supported modes are read-only; shared/exclusive locks enforce sharing. */
+#ifdef __EMSCRIPTEN__
+ else for (struct guest_file *other = handles; other; other = other->next)
+ if (other->device == info.st_dev && other->inode == info.st_ino && (exclusive || other->exclusive)) {
+ error = 32;
+ break;
+ }
+#else
else if (flock(descriptor, (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB))
error = errno == EWOULDBLOCK ? 32 : file_error(errno);
+#endif
if (error) close(descriptor);
}
@@ -98,6 +115,11 @@ static void create_file_locked(void)
next_handle += 4;
handle->descriptor = descriptor;
handle->unbuffered = unbuffered;
+#ifdef __EMSCRIPTEN__
+ handle->device = info.st_dev;
+ handle->inode = info.st_ino;
+ handle->exclusive = exclusive;
+#endif
handle->next = handles;
handles = handle;
g_eax = handle->id;
diff --git a/src/runtime/linux_gdi.c b/src/runtime/linux_gdi.c
@@ -1,5 +1,7 @@
#include "linux_gdi.h"
+#ifndef __EMSCRIPTEN__
#include <fontconfig/fontconfig.h>
+#endif
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_TRUETYPE_TABLES_H
@@ -112,6 +114,17 @@ static void create_font(void)
fprintf(stderr, "Unsupported GDI font rotation, decoration, charset or quality\n"); abort();
}
if (!library) check_font(FT_Init_FreeType(&library));
+ struct font *font = calloc(1, sizeof(*font));
+ if (!font) abort();
+#ifdef __EMSCRIPTEN__
+ if (strcasecmp((const char *)ADDR(face), "Verdana")) {
+ fprintf(stderr, "Unsupported browser font: %s\n", (const char *)ADDR(face));
+ abort();
+ }
+ const char *path = weight >= 700 ? (italic ? "fonts/verdanaz.ttf" : "fonts/verdanab.ttf") :
+ (italic ? "fonts/verdanai.ttf" : "fonts/verdana.ttf");
+ check_font(FT_New_Face(library, path, 0, &font->face));
+#else
FcPattern *pattern = FcPatternCreate();
FcPatternAddString(pattern, FC_FAMILY, (const FcChar8 *)ADDR(face));
FcPatternAddInteger(pattern, FC_WEIGHT, weight >= 700 ? FC_WEIGHT_BOLD : FC_WEIGHT_REGULAR);
@@ -125,10 +138,9 @@ static void create_font(void)
int index = 0;
if (!match || FcPatternGetString(match, FC_FILE, 0, &path) != FcResultMatch) abort();
FcPatternGetInteger(match, FC_INDEX, 0, &index);
- struct font *font = calloc(1, sizeof(*font));
- if (!font) abort();
check_font(FT_New_Face(library, (const char *)path, index, &font->face));
FcPatternDestroy(match);
+#endif
font->handle = next_handle++;
font->weight = weight ? weight : 400;
font->italic = italic != 0;
diff --git a/src/runtime/linux_graphics.c b/src/runtime/linux_graphics.c
@@ -3,14 +3,26 @@
#include "guest_heap.h"
#include "gl_renderer.h"
#include <SDL2/SDL.h>
+#ifdef __EMSCRIPTEN__
+#include <GLES3/gl3.h>
+#include <emscripten.h>
+#include <emscripten/html5.h>
+#else
#include <SDL2/SDL_opengl.h>
+#endif
#include <errno.h>
#include <time.h>
#include <math.h>
/* Native graphics resources never appear in guest COM objects or vtables. */
static SDL_Window *window;
+static GLint maximum_texture_size;
+#ifdef __EMSCRIPTEN__
+static EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context;
+static SDL_DisplayMode browser_display;
+#else
static SDL_GLContext context;
+#endif
static struct draw_object {
uint32_t interfaces[3], references[2];
struct draw_object *next;
@@ -45,6 +57,7 @@ static struct surface_object {
struct surface_data *data;
struct surface_object *next;
} *surfaces;
+static struct surface_object *surface_cache[4096];
struct device_light {
uint32_t index, enabled, data[26];
struct device_light *next;
@@ -77,41 +90,75 @@ static struct vertex_buffer {
uint32_t interface, references, caps, fvf, count, size, data;
struct draw_object *owner;
struct vertex_buffer *next;
-} *vertex_buffers;
+} *vertex_buffers[4096];
static uint32_t vtables[9];
static const unsigned interface_slots[] = {23, 30, 8, 49, 36, 9, 49, 9, 7};
static unsigned current_interface, current_slot;
-static void close_graphics(void)
+void linux_graphics_shutdown(void)
{
if (context) gl_renderer_shutdown();
+#ifdef __EMSCRIPTEN__
+ if (context) emscripten_webgl_destroy_context(context);
+#else
SDL_GL_DeleteContext(context);
+#endif
SDL_DestroyWindow(window);
SDL_QuitSubSystem(SDL_INIT_VIDEO);
- context = NULL;
+ context = 0;
window = NULL;
}
static int initialize_graphics(void)
{
if (context) return 1;
- if (SDL_InitSubSystem(SDL_INIT_VIDEO) ||
- SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3) ||
+ if (SDL_InitSubSystem(SDL_INIT_VIDEO)) goto failed;
+#ifdef __EMSCRIPTEN__
+ /* The canvas is the browser's virtual desktop, independent of the monitor. */
+ browser_display.format = SDL_PIXELFORMAT_RGB888;
+ if (emscripten_get_canvas_element_size("#canvas", &browser_display.w,
+ &browser_display.h) != EMSCRIPTEN_RESULT_SUCCESS) goto failed;
+#endif
+#ifndef __EMSCRIPTEN__
+ if (SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3) ||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3) ||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE) ||
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24)) goto failed;
+#endif
window = SDL_CreateWindow("Anarchy Online", SDL_WINDOWPOS_UNDEFINED,
- SDL_WINDOWPOS_UNDEFINED, 32, 32, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
+ SDL_WINDOWPOS_UNDEFINED, 32, 32, SDL_WINDOW_HIDDEN
+#ifndef __EMSCRIPTEN__
+ | SDL_WINDOW_OPENGL
+#endif
+ );
if (!window) goto failed;
+#ifdef __EMSCRIPTEN__
+ /* Own WebGL on the game worker; SDL still handles window/input events. */
+ EmscriptenWebGLContextAttributes attributes;
+ emscripten_webgl_init_context_attributes(&attributes);
+ attributes.majorVersion = 2;
+ attributes.alpha = attributes.antialias = 0;
+ attributes.proxyContextToMainThread = EMSCRIPTEN_WEBGL_CONTEXT_PROXY_DISALLOW;
+ context = emscripten_webgl_create_context("#canvas", &attributes);
+ if (context <= 0) { context = 0; goto failed; }
+ if (emscripten_webgl_make_context_current(context) != EMSCRIPTEN_RESULT_SUCCESS) goto failed;
+#else
context = SDL_GL_CreateContext(window);
if (!context) goto failed;
+ /* The guest's WaitForVerticalBlank already controls frame pacing. */
+ if (SDL_GL_SetSwapInterval(0))
+ fprintf(stderr, "[linux-graphics] Cannot disable implicit swap pacing: %s\n", SDL_GetError());
+#endif
if (!gl_renderer_initialize()) goto failed;
+ glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maximum_texture_size);
fprintf(stderr, "[linux-graphics] %s; OpenGL %s\n", glGetString(GL_RENDERER), glGetString(GL_VERSION));
- atexit(close_graphics);
+#ifndef __EMSCRIPTEN__
+ atexit(linux_graphics_shutdown);
+#endif
return 1;
failed:
fprintf(stderr, "Native graphics initialization failed: %s\n", SDL_GetError());
- close_graphics();
+ linux_graphics_shutdown();
return 0;
}
@@ -120,6 +167,16 @@ SDL_Window *linux_graphics_window(void)
return initialize_graphics() ? window : NULL;
}
+int linux_graphics_display_mode(SDL_DisplayMode *mode)
+{
+#ifdef __EMSCRIPTEN__
+ *mode = browser_display;
+ return 0;
+#else
+ return SDL_GetCurrentDisplayMode(SDL_GetWindowDisplayIndex(window), mode);
+#endif
+}
+
static struct draw_object *find_object(uint32_t address)
{
for (struct draw_object *object = objects; object; object = object->next)
@@ -206,6 +263,14 @@ static void test_cooperative_level(void)
g_esp += 8;
}
+static void restore_display_mode(void)
+{
+ find_object(MEM32(g_esp + 4));
+ /* Windowed rendering never changes the display mode, so nothing needs restoring. */
+ g_eax = 0;
+ g_esp += 8;
+}
+
static void wait_for_vertical_blank(void)
{
find_object(MEM32(g_esp + 4));
@@ -213,14 +278,19 @@ static void wait_for_vertical_blank(void)
g_esp += 16;
g_eax = 0x80070057u;
if (flags != 1 || event) return;
+ /* Browsers and disconnected displays may not report a refresh rate. */
+ unsigned refresh_rate = 60;
+#ifndef __EMSCRIPTEN__
SDL_DisplayMode mode;
- if (SDL_GetCurrentDisplayMode(SDL_GetWindowDisplayIndex(window), &mode) || mode.refresh_rate <= 0) {
+ if (SDL_GetCurrentDisplayMode(SDL_GetWindowDisplayIndex(window), &mode)) {
fprintf(stderr, "Cannot determine native display refresh rate\n"); exit(3);
}
- /* WSL X11 exposes no retrace sync. Pace a virtual refresh clock instead. */
+ if (mode.refresh_rate > 0) refresh_rate = mode.refresh_rate;
+#endif
+ /* Pace a virtual refresh clock where there is no retrace wait API. */
struct timespec now;
if (clock_gettime(CLOCK_MONOTONIC, &now)) abort();
- uint64_t period = 1000000000u / mode.refresh_rate;
+ uint64_t period = 1000000000u / refresh_rate;
uint64_t ticks = (uint64_t)now.tv_sec * 1000000000u + now.tv_nsec;
uint64_t next = ticks + period - ticks % period;
struct timespec deadline = {next / 1000000000u, next % 1000000000u};
@@ -290,7 +360,7 @@ static void get_display_mode(void)
g_eax = 0x80070057u;
if (!output || (MEM32(output) != 108 && MEM32(output) != 124)) return;
SDL_DisplayMode mode;
- if (SDL_GetCurrentDisplayMode(SDL_GetWindowDisplayIndex(window), &mode)) abort();
+ if (linux_graphics_display_mode(&mode)) abort();
int bits;
Uint32 red, green, blue, alpha;
if (!SDL_PixelFormatEnumToMasks(mode.format, &bits, &red, &green, &blue, &alpha)) abort();
@@ -317,7 +387,11 @@ static void enumerate_display_modes(void)
uint32_t data = MEM32(g_esp + 16), callback = MEM32(g_esp + 20);
if (!callback || (flags & ~3u)) { g_eax = 0x80070057u; g_esp += 24; return; }
if (filter) { fprintf(stderr, "Filtered DirectDraw mode enumeration is not implemented\n"); exit(3); }
+#ifdef __EMSCRIPTEN__
+ int count = 1;
+#else
int display = SDL_GetWindowDisplayIndex(window), count = SDL_GetNumDisplayModes(display);
+#endif
if (count < 0) { fprintf(stderr, "SDL mode query failed: %s\n", SDL_GetError()); abort(); }
uint32_t description = guest_malloc(124);
if (!description) abort();
@@ -327,7 +401,11 @@ static void enumerate_display_modes(void)
SDL_DisplayMode previous = {0};
for (int i = 0; i < count; ++i) {
SDL_DisplayMode mode;
+#ifdef __EMSCRIPTEN__
+ if (linux_graphics_display_mode(&mode)) {
+#else
if (SDL_GetDisplayMode(display, i, &mode)) {
+#endif
fprintf(stderr, "SDL mode query failed: %s\n", SDL_GetError()); abort();
}
/* SDL sorts refresh variants together. Without DDEDM_REFRESHRATES,
@@ -415,12 +493,10 @@ static void describe_device(uint32_t record)
MEM32(record + 104) = 0x15; /* Independent U/V, wrap and clamp. */
MEM32(record + 116) = 0x100; /* DDBD_32 color */
MEM32(record + 120) = 0x600; /* DDBD_16 | DDBD_24 depth */
- GLint maximum;
- glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maximum);
MEM32(record + 124) = MEM32(record + 128) = 1;
- MEM32(record + 132) = MEM32(record + 136) = maximum;
+ MEM32(record + 132) = MEM32(record + 136) = maximum_texture_size;
MEM32(record + 140) = UINT32_MAX; /* Float UV range exceeds this DWORD limit. */
- MEM32(record + 144) = maximum; /* A 1-by-maximum texture is supported. */
+ MEM32(record + 144) = maximum_texture_size; /* A 1-by-maximum texture is supported. */
MEM32(record + 148) = 1; /* No anisotropic filtering. */
MEM32(record + 176) = 2; /* Two texture-coordinate sets. */
MEM32(record + 180) = 0x8004b; /* Disable, select argument 1, modulate, add, inverse-alpha add. */
@@ -766,11 +842,26 @@ static void clipper_get_list(void)
g_eax = 0;
}
+/* Mix arena and block offsets so interfaces 64 KiB apart do not share a bucket. */
+static unsigned interface_bucket(uint32_t address)
+{
+ return ((address >> 4) * 2654435761u) >> 20;
+}
+
static struct surface_object *find_surface(uint32_t address)
{
+ /* Cache hot COM identities without putting host pointers in guest memory. */
+ unsigned bucket = interface_bucket(address);
+ struct surface_object *cached = surface_cache[bucket];
+ if (cached)
+ for (unsigned i = 0; i < 2; ++i)
+ if (cached->interfaces[i] == address && cached->references[i]) return cached;
for (struct surface_object *surface = surfaces; surface; surface = surface->next)
for (unsigned i = 0; i < 2; ++i)
- if (surface->interfaces[i] == address && surface->references[i]) return surface;
+ if (surface->interfaces[i] == address && surface->references[i]) {
+ surface_cache[bucket] = surface;
+ return surface;
+ }
fprintf(stderr, "Invalid guest surface interface %08x\n", address);
abort();
}
@@ -821,14 +912,12 @@ static void create_surface(void)
for (struct surface_object *surface = surfaces; surface; surface = surface->next)
if (surface->owner == owner && (surface->caps & 0x200)) { g_eax = 0x88760234u; return; }
SDL_DisplayMode mode;
- if (SDL_GetCurrentDisplayMode(SDL_GetWindowDisplayIndex(window), &mode)) abort();
+ if (linux_graphics_display_mode(&mode)) abort();
width = mode.w;
height = mode.h;
caps |= 0x8000; /* DDSCAPS_VISIBLE */
}
- GLint maximum;
- glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maximum);
- if (!width || !height || width > (uint32_t)maximum || height > (uint32_t)maximum ||
+ if (!width || !height || width > (uint32_t)maximum_texture_size || height > (uint32_t)maximum_texture_size ||
(uint64_t)width * height * 4 > UINT32_MAX) return;
unsigned levels = 1;
if (mip) {
@@ -846,12 +935,11 @@ static void create_surface(void)
surface->depth_bits = MEM32(desc + 84);
surface->depth = gl_depth_create(width, height, surface->depth_bits);
}
- else surface->target = gl_target_create(width, height);
+ else surface->target = gl_target_create(width, height, !texture);
if (!surface->target && !surface->depth) { free(surface); if (first) release_surface(first, 0); g_eax = 0x8007000eu; return; }
if (texture) {
surface->alpha = MEM32(desc + 76) & 1;
surface->caps2 = MEM32(desc + 108);
- gl_target_set_depth(surface->target, NULL);
}
surface->width = width;
surface->height = height;
@@ -888,15 +976,6 @@ static void create_surface(void)
g_eax = 0;
}
-static void evict_managed_textures(void)
-{
- struct draw_object *owner = find_object(MEM32(g_esp + 4));
- for (struct surface_object *surface = surfaces; surface; surface = surface->next)
- if (surface->owner == owner && (surface->caps2 & 0x10)) gl_target_evict(surface->target);
- g_eax = 0;
- g_esp += 8;
-}
-
static void surface_query_interface(void)
{
struct surface_object *surface = find_surface(MEM32(g_esp + 4));
@@ -928,6 +1007,7 @@ static uint32_t release_surface(struct surface_object *surface, unsigned index)
{
uint32_t remaining = --surface->references[index];
if (!remaining) {
+ surface_cache[interface_bucket(surface->interfaces[index])] = NULL;
guest_free(surface->interfaces[index]);
surface->interfaces[index] = 0;
}
@@ -946,6 +1026,7 @@ static uint32_t release_surface(struct surface_object *surface, unsigned index)
/* Implicit mip attachments are destroyed with their parent even if
* callers retain a sublevel interface, as in DirectDraw. */
if (surface->mip_count) {
+ surface_cache[interface_bucket(surface->attached->interfaces[1])] = NULL;
guest_free(surface->attached->interfaces[1]);
surface->attached->interfaces[1] = 0;
surface->attached->references[1] = 0;
@@ -1185,24 +1266,41 @@ static void swap_surface_channels(struct surface_object *surface)
}
}
-static void transfer_surface_pixels(struct surface_object *surface, int upload)
+enum surface_transfer { SURFACE_READ, SURFACE_WRITE, SURFACE_EVICT };
+
+static void transfer_surface_pixels(struct surface_object *surface, enum surface_transfer operation)
{
unsigned char *pixels = (void *)ADDR(surface->pixels), *packed = pixels;
if (surface->pitch != surface->width * 4) {
packed = malloc((size_t)surface->width * surface->height * 4);
if (!packed) abort();
- if (upload) for (unsigned y = 0; y < surface->height; ++y)
+ if (operation != SURFACE_READ) for (unsigned y = 0; y < surface->height; ++y)
memcpy(packed + y * surface->width * 4, pixels + y * surface->pitch, surface->width * 4);
}
- if (upload) gl_target_write(surface->target, packed);
+ if (operation == SURFACE_EVICT) gl_target_evict(surface->target, packed);
+ else if (operation == SURFACE_WRITE) gl_target_write(surface->target, packed);
else gl_target_read(surface->target, packed);
if (packed != pixels) {
- if (!upload) for (unsigned y = 0; y < surface->height; ++y)
+ if (operation == SURFACE_READ) for (unsigned y = 0; y < surface->height; ++y)
memcpy(pixels + y * surface->pitch, packed + y * surface->width * 4, surface->width * 4);
free(packed);
}
}
+static void evict_managed_textures(void)
+{
+ struct draw_object *owner = find_object(MEM32(g_esp + 4));
+ /* Managed surfaces retain authoritative CPU pixels, including blit updates. */
+ for (struct surface_object *surface = surfaces; surface; surface = surface->next) {
+ if (surface->owner != owner || !(surface->caps2 & 0x10)) continue;
+ swap_surface_channels(surface);
+ transfer_surface_pixels(surface, SURFACE_EVICT);
+ swap_surface_channels(surface);
+ }
+ g_eax = 0;
+ g_esp += 8;
+}
+
static void surface_lock(void)
{
struct surface_object *surface = find_surface(MEM32(g_esp + 4));
@@ -1224,7 +1322,7 @@ static void surface_lock(void)
if (!surface->pixels) surface->pixels = guest_malloc(surface->pitch * surface->height);
if (!surface->pixels) { g_eax = 0x8007000eu; return; }
if (!(surface->caps & 0x800)) {
- transfer_surface_pixels(surface, 0);
+ transfer_surface_pixels(surface, SURFACE_READ);
swap_surface_channels(surface);
}
surface->locked = 1;
@@ -1245,7 +1343,7 @@ static void surface_unlock(void)
}
if (!(surface->lock_flags & 0x10)) {
swap_surface_channels(surface);
- transfer_surface_pixels(surface, 1);
+ transfer_surface_pixels(surface, SURFACE_WRITE);
swap_surface_channels(surface);
}
surface->locked = 0;
@@ -1304,14 +1402,23 @@ static void surface_blit(void)
} else if (to[0] < 0 || to[1] < 0 || to[2] > (int32_t)target->width || to[3] > (int32_t)target->height) return;
gl_target_blit(source->target, target->target, from, to);
if (target->caps & 0x800) {
- transfer_surface_pixels(target, 0);
+ transfer_surface_pixels(target, SURFACE_READ);
swap_surface_channels(target);
}
if (primary) {
int width, height;
+#ifdef __EMSCRIPTEN__
+ if (emscripten_get_canvas_element_size("#canvas", &width, &height) != EMSCRIPTEN_RESULT_SUCCESS) abort();
+#else
SDL_GL_GetDrawableSize(native, &width, &height);
+#endif
gl_target_present(target->target, client, width, height);
+#ifdef __EMSCRIPTEN__
+ /* JSPI yields the worker so OffscreenCanvas can present this frame. */
+ emscripten_sleep(0);
+#else
SDL_GL_SwapWindow(native);
+#endif
}
g_eax = 0;
}
@@ -1896,9 +2003,6 @@ static void draw_primitive(struct device_object *device, uint32_t primitive, uin
gl_renderer_set_cull(device->cull);
const int32_t clip[] = {device->viewport[0], device->viewport[1], device->viewport[2], device->viewport[3]};
gl_target_draw(device->target->target, primitive == 2 ? 2 : 4, vertices, count, indices, index_count, clip);
- gl_renderer_set_blend(0, 2, 1);
- gl_renderer_set_fog(0, 0);
- for (unsigned stage = 0; stage < 2; ++stage) gl_renderer_set_texture(stage, NULL);
free(indices);
free(vertices);
g_eax = 0;
@@ -2059,7 +2163,7 @@ static void device_texture_formats(void)
static struct vertex_buffer *find_vertex_buffer(uint32_t address)
{
- for (struct vertex_buffer *buffer = vertex_buffers; buffer; buffer = buffer->next)
+ for (struct vertex_buffer *buffer = vertex_buffers[interface_bucket(address)]; buffer; buffer = buffer->next)
if (buffer->interface == address) return buffer;
fprintf(stderr, "Invalid guest vertex buffer %08x\n", address);
abort();
@@ -2102,8 +2206,9 @@ static void create_vertex_buffer(void)
buffer->caps = caps; buffer->fvf = fvf; buffer->count = count;
buffer->owner = owner;
++owner->references[1];
- buffer->next = vertex_buffers;
- vertex_buffers = buffer;
+ unsigned bucket = interface_bucket(buffer->interface);
+ buffer->next = vertex_buffers[bucket];
+ vertex_buffers[bucket] = buffer;
MEM32(output) = buffer->interface;
g_eax = 0;
}
@@ -2156,7 +2261,7 @@ static void vertex_buffer_release_reference(void)
struct vertex_buffer *buffer = find_vertex_buffer(MEM32(g_esp + 4));
g_eax = --buffer->references;
if (!g_eax) {
- struct vertex_buffer **link = &vertex_buffers;
+ struct vertex_buffer **link = &vertex_buffers[interface_bucket(buffer->interface)];
while (*link != buffer) link = &(*link)->next;
*link = buffer->next;
release_draw(buffer->owner, 1);
@@ -2303,6 +2408,7 @@ recomp_func_t linux_graphics_virtual(uint32_t address)
if (current_interface == 1 && current_slot == 6) return create_surface;
if (current_interface == 1 && current_slot == 8) return enumerate_display_modes;
if (current_interface == 1 && current_slot == 12) return get_display_mode;
+ if (current_interface == 1 && current_slot == 19) return restore_display_mode;
if (current_slot == 11) return get_caps;
if (current_slot == 20) return set_cooperative_level;
if (current_interface == 1 && current_slot == 22) return wait_for_vertical_blank;
diff --git a/src/runtime/linux_graphics.h b/src/runtime/linux_graphics.h
@@ -4,7 +4,11 @@
recomp_func_t linux_graphics_lookup(const char *name);
recomp_func_t linux_graphics_virtual(uint32_t address);
+/* Call on the render thread before the browser proxies process exit to main. */
+void linux_graphics_shutdown(void);
struct SDL_Window;
struct SDL_Window *linux_graphics_window(void);
+struct SDL_DisplayMode;
+int linux_graphics_display_mode(struct SDL_DisplayMode *mode);
#endif
diff --git a/src/runtime/linux_host.c b/src/runtime/linux_host.c
@@ -1,3 +1,4 @@
+#define _GNU_SOURCE
#include "recomp_types.h"
#include "game-data.h"
#include "game-modules.h"
@@ -112,6 +113,11 @@ recomp_func_t recomp_lookup(uint32_t va)
recomp_func_t adapter = guest_exception_virtual(va);
if (!adapter) adapter = linux_graphics_virtual(va);
if (adapter) return adapter;
+ if (va >= 0xf0000000u) return NULL;
+ /* Guest code identities are immutable; virtual adapters retain their dispatch state. */
+ static _Thread_local struct { uint32_t address; recomp_func_t function; } cache[4096];
+ unsigned bucket = (va >> 4) % 4096;
+ if (cache[bucket].function && cache[bucket].address == va) return cache[bucket].function;
const recomp_dispatch_entry_t *table = recomp_dispatch_table;
uint32_t lo = 0, hi = recomp_dispatch_count;
if (va >= 0x46000000u && va < 0x47000000u) {
@@ -123,7 +129,11 @@ recomp_func_t recomp_lookup(uint32_t va)
}
while (lo < hi) {
uint32_t mid = lo + (hi - lo) / 2;
- if (table[mid].address == va) return table[mid].func;
+ if (table[mid].address == va) {
+ cache[bucket].address = va;
+ cache[bucket].function = table[mid].func;
+ return table[mid].func;
+ }
if (table[mid].address < va) lo = mid + 1;
else hi = mid;
}
@@ -226,6 +236,10 @@ static void attach_module(int module)
int main(int argc, char **argv)
{
extern char **environ;
+#ifdef __EMSCRIPTEN__
+ extern void browser_initialize(void);
+ browser_initialize();
+#endif
setvbuf(stderr, NULL, _IONBF, 0);
for (int i = 0; i < game_module_count; ++i) {
modules[i].name = game_modules[i].name;
@@ -256,11 +270,14 @@ int main(int argc, char **argv)
MEM32(g_fs_base + 8) = 0x08000000u;
MEM32(g_fs_base + 0x18) = g_fs_base;
MEM32(g_fs_base + 0x20) = getpid();
- MEM32(g_fs_base + 0x24) = syscall(SYS_gettid);
+ MEM32(g_fs_base + 0x24) = gettid();
int client = module_named("Clientr.exe");
if (pthread_mutex_lock(&loader_mutex)) abort();
attach_module(client);
if (pthread_mutex_unlock(&loader_mutex)) abort();
call_guest(modules[client].entry, NULL, 0);
+#ifdef __EMSCRIPTEN__
+ linux_graphics_shutdown();
+#endif
return 0;
}
diff --git a/src/runtime/linux_imports.c b/src/runtime/linux_imports.c
@@ -22,11 +22,13 @@
#include <strings.h>
/* External calls receive stable guest identifiers rather than host code addresses. */
-static struct { const char *dll, *name; uint32_t ordinal; } imports[4096];
+static struct { const char *dll, *name; uint32_t ordinal; recomp_func_t function; } imports[4096];
static _Atomic unsigned import_count;
static _Thread_local unsigned current_import;
static pthread_mutex_t import_mutex = PTHREAD_MUTEX_INITIALIZER;
+static recomp_func_t resolve_import(unsigned index);
+
static uint32_t import_bind_locked(const char *dll, const char *name, uint32_t ordinal)
{
if (!strcasecmp(dll, "msvcrt.dll") && name) {
@@ -43,6 +45,7 @@ static uint32_t import_bind_locked(const char *dll, const char *name, uint32_t o
imports[import_count].name = name ? strdup(name) : NULL;
if (!imports[import_count].dll || (name && !imports[import_count].name)) abort();
imports[import_count].ordinal = ordinal;
+ imports[import_count].function = resolve_import(import_count);
return 0xf0000000u + 4 * import_count++;
}
@@ -58,6 +61,12 @@ unsigned linux_import_count(void) { return import_count; }
static void external_call(void)
{
+ /* Preserve the game's error text when its fallback dialog is unavailable. */
+ if (!strcasecmp(imports[current_import].dll, "user32.dll") &&
+ imports[current_import].name && !strcmp(imports[current_import].name, "MessageBoxA")) {
+ uint32_t text = MEM32(g_esp + 8);
+ if (text) fprintf(stderr, "Game error: %s\n", (const char *)ADDR(text));
+ }
fprintf(stderr, "Unimplemented platform call: %s!%s ordinal=%u caller=%08x\n",
imports[current_import].dll,
imports[current_import].name ? imports[current_import].name : "",
@@ -121,6 +130,9 @@ static void crt_exit(void)
PUSH32(g_esp, 0);
PUSH32(g_esp, RECOMP_RETADDR);
guest_stdio_lookup("fflush")();
+#ifdef __EMSCRIPTEN__
+ linux_graphics_shutdown();
+#endif
exit(status);
}
@@ -160,58 +172,64 @@ recomp_func_t recomp_lookup_import(uint32_t va)
exit(3);
}
current_import = (va - 0xf0000000u) / 4;
- if (!strcasecmp(imports[current_import].dll, "ddraw.dll") && imports[current_import].name) {
- recomp_func_t function = linux_graphics_lookup(imports[current_import].name);
+ return imports[current_import].function;
+}
+
+/* Resolve immutable bindings once, before publishing their guest tokens. */
+static recomp_func_t resolve_import(unsigned index)
+{
+ if (!strcasecmp(imports[index].dll, "ddraw.dll") && imports[index].name) {
+ recomp_func_t function = linux_graphics_lookup(imports[index].name);
if (function) return function;
}
- if (!strcasecmp(imports[current_import].dll, "ws2_32.dll") ||
- !strcasecmp(imports[current_import].dll, "wsock32.dll")) {
- recomp_func_t function = linux_network_lookup(imports[current_import].name, imports[current_import].ordinal);
+ if (!strcasecmp(imports[index].dll, "ws2_32.dll") ||
+ !strcasecmp(imports[index].dll, "wsock32.dll")) {
+ recomp_func_t function = linux_network_lookup(imports[index].name, imports[index].ordinal);
if (function) return function;
}
- if (imports[current_import].name) {
- recomp_func_t audio = linux_audio_lookup(imports[current_import].dll, imports[current_import].name);
+ if (imports[index].name) {
+ recomp_func_t audio = linux_audio_lookup(imports[index].dll, imports[index].name);
if (audio) return audio;
- if (!strcasecmp(imports[current_import].dll, "gdi32.dll")) {
- recomp_func_t function = linux_gdi_lookup(imports[current_import].name);
+ if (!strcasecmp(imports[index].dll, "gdi32.dll")) {
+ recomp_func_t function = linux_gdi_lookup(imports[index].name);
if (function) return function;
}
- recomp_func_t function = linux_platform_lookup(imports[current_import].dll, imports[current_import].name);
+ recomp_func_t function = linux_platform_lookup(imports[index].dll, imports[index].name);
if (function) return function;
- if (!strcasecmp(imports[current_import].dll, "winmm.dll")) {
- function = linux_thread_lookup(imports[current_import].name);
+ if (!strcasecmp(imports[index].dll, "winmm.dll")) {
+ function = linux_thread_lookup(imports[index].name);
if (function) return function;
}
- function = linux_window_lookup(imports[current_import].dll, imports[current_import].name);
+ function = linux_window_lookup(imports[index].dll, imports[index].name);
if (function) return function;
- if (!strcasecmp(imports[current_import].dll, "kernel32.dll")) {
- function = library_lookup(imports[current_import].name);
- if (!function) function = linux_file_lookup(imports[current_import].name);
- if (!function) function = linux_module_lookup(imports[current_import].name);
- if (!function) function = linux_sync_lookup(imports[current_import].name);
- if (!function) function = linux_tls_lookup(imports[current_import].name);
- if (!function) function = linux_thread_lookup(imports[current_import].name);
- if (!function) function = linux_snapshot_lookup(imports[current_import].name);
+ if (!strcasecmp(imports[index].dll, "kernel32.dll")) {
+ function = library_lookup(imports[index].name);
+ if (!function) function = linux_file_lookup(imports[index].name);
+ if (!function) function = linux_module_lookup(imports[index].name);
+ if (!function) function = linux_sync_lookup(imports[index].name);
+ if (!function) function = linux_tls_lookup(imports[index].name);
+ if (!function) function = linux_thread_lookup(imports[index].name);
+ if (!function) function = linux_snapshot_lookup(imports[index].name);
if (function) return function;
}
}
- if (!strcasecmp(imports[current_import].dll, "msvcrt.dll") && imports[current_import].name) {
- if (!strcmp(imports[current_import].name, "exit")) return crt_exit;
- if (!strcmp(imports[current_import].name, "longjmp")) return guest_longjmp;
- if (!strcmp(imports[current_import].name, "_CxxThrowException")) {
+ if (!strcasecmp(imports[index].dll, "msvcrt.dll") && imports[index].name) {
+ if (!strcmp(imports[index].name, "exit")) return crt_exit;
+ if (!strcmp(imports[index].name, "longjmp")) return guest_longjmp;
+ if (!strcmp(imports[index].name, "_CxxThrowException")) {
extern void native32_shim_CxxThrowException(void);
return native32_shim_CxxThrowException;
}
- recomp_func_t function = linux_thread_lookup(imports[current_import].name);
- if (!function) function = guest_stdio_lookup(imports[current_import].name);
- if (!function) function = guest_crt_lookup(imports[current_import].name);
- if (!function) function = guest_format_lookup(imports[current_import].name);
- if (!function) function = guest_exception_lookup(imports[current_import].name);
- if (!function) function = guest_rtti_lookup(imports[current_import].name);
+ recomp_func_t function = linux_thread_lookup(imports[index].name);
+ if (!function) function = guest_stdio_lookup(imports[index].name);
+ if (!function) function = guest_crt_lookup(imports[index].name);
+ if (!function) function = guest_format_lookup(imports[index].name);
+ if (!function) function = guest_exception_lookup(imports[index].name);
+ if (!function) function = guest_rtti_lookup(imports[index].name);
if (function) return function;
}
- if (!strcasecmp(imports[current_import].dll, "msvcp60.dll") && imports[current_import].name) {
- recomp_func_t function = guest_msvcp_lookup(imports[current_import].name);
+ if (!strcasecmp(imports[index].dll, "msvcp60.dll") && imports[index].name) {
+ recomp_func_t function = guest_msvcp_lookup(imports[index].name);
if (function) return function;
}
return external_call;
diff --git a/src/runtime/linux_platform.c b/src/runtime/linux_platform.c
@@ -7,7 +7,12 @@
#include <sched.h>
#include <strings.h>
#include <sys/stat.h>
+#ifdef __EMSCRIPTEN__
+#include <emscripten/heap.h>
+#include <malloc.h>
+#else
#include <sys/sysinfo.h>
+#endif
#include <time.h>
#include <unistd.h>
@@ -133,7 +138,12 @@ static void tick_count(void)
{
/* Guest DWORD milliseconds wrap at 2^32, including time spent suspended. */
struct timespec now;
+#ifdef __EMSCRIPTEN__
+ /* Browsers expose a monotonic clock but no system boot-time clock. */
+ if (clock_gettime(CLOCK_MONOTONIC, &now)) { perror("clock_gettime"); abort(); }
+#else
if (clock_gettime(CLOCK_BOOTTIME, &now)) { perror("clock_gettime"); abort(); }
+#endif
g_eax = (uint32_t)((uint64_t)now.tv_sec * 1000 + now.tv_nsec / 1000000);
g_esp += 4;
}
@@ -384,12 +394,19 @@ static void set_handle_count(void)
static void global_memory_status(void)
{
+#ifdef __EMSCRIPTEN__
+ /* Report the WASM address-space budget, not unavailable host RAM statistics. */
+ uint64_t total = emscripten_get_heap_max();
+ uint64_t available = total - emscripten_get_heap_size() + mallinfo().fordblks;
+ uint64_t page_total = total, page_available = available;
+#else
struct sysinfo info;
if (sysinfo(&info)) { perror("sysinfo"); abort(); }
uint64_t total = (uint64_t)info.totalram * info.mem_unit;
uint64_t available = ((uint64_t)info.freeram + info.bufferram) * info.mem_unit;
uint64_t page_total = total + (uint64_t)info.totalswap * info.mem_unit;
uint64_t page_available = available + (uint64_t)info.freeswap * info.mem_unit;
+#endif
uint64_t mapped = guest_memory_mapped_bytes();
uint32_t output = MEM32(g_esp + 4);
diff --git a/src/runtime/linux_sync.c b/src/runtime/linux_sync.c
@@ -2,7 +2,11 @@
#include "linux_sync.h"
#include <errno.h>
#include <fcntl.h>
+#ifdef __EMSCRIPTEN__
+#include <emscripten/threading.h>
+#else
#include <linux/futex.h>
+#endif
#include <limits.h>
#include <stdatomic.h>
#include <pthread.h>
@@ -19,6 +23,9 @@ struct semaphore_state {
_Atomic uint32_t count;
uint32_t maximum;
char name[260];
+#ifdef __EMSCRIPTEN__
+ unsigned references;
+#endif
};
_Static_assert(sizeof(_Atomic uint32_t) == 4 && ATOMIC_INT_LOCK_FREE == 2,
"Linux futexes require lock-free 32-bit counters");
@@ -54,8 +61,31 @@ static struct semaphore_handle *find_handle_locked(uint32_t id)
static uint32_t open_semaphore_locked(const char *name, int create, int32_t initial,
int32_t maximum, uint32_t access)
{
- int directory = -1, fd = -1, existing = 0;
- struct semaphore_state *state;
+ int fd = -1, existing = 0;
+ struct semaphore_state *state = NULL;
+#ifdef __EMSCRIPTEN__
+ /* Browser workers share one process and one named-object namespace. */
+ if (name) {
+ for (struct semaphore_handle *other = handles; other; other = other->next)
+ if (!strcmp(other->state->name, name)) { state = other->state; break; }
+ }
+ existing = state != NULL;
+ if (!existing && !create) { MEM32(g_fs_base + 0x34) = 2; return 0; }
+ if (!existing && (maximum <= 0 || initial < 0 || initial > maximum)) {
+ MEM32(g_fs_base + 0x34) = 87;
+ return 0;
+ }
+ if (!existing) {
+ if (name && strlen(name) >= 260) abort();
+ state = calloc(1, sizeof(*state));
+ if (!state) abort();
+ atomic_init(&state->count, initial);
+ state->maximum = maximum;
+ strcpy(state->name, name ? name : "");
+ }
+ ++state->references;
+#else
+ int directory = -1;
if (name) {
if (!*name || strlen(name) >= 260 || strchr(name, '\\')) {
fprintf(stderr, "Unsupported semaphore namespace/name: %s\n", name);
@@ -127,6 +157,7 @@ static uint32_t open_semaphore_locked(const char *name, int create, int32_t init
}
if (fd >= 0 && flock(fd, LOCK_SH)) system_failure("semaphore shared lifetime lock");
if (directory >= 0) close(directory);
+#endif
struct semaphore_handle *handle = malloc(sizeof(*handle));
if (!handle) system_failure("semaphore handle allocation");
@@ -186,8 +217,13 @@ static void change_event_object_locked(struct semaphore_handle *handle, int sign
/* Auto-reset wakes one waiter; manual-reset stays signaled for all waiters. */
atomic_store(&handle->state->count, signaled);
if (signaled && pthread_cond_broadcast(&changed)) abort();
- if (signaled && syscall(SYS_futex, &handle->state->count, FUTEX_WAKE,
- handle->kind == 3 ? INT_MAX : 1, NULL, NULL, 0) < 0)
+ if (signaled &&
+#ifdef __EMSCRIPTEN__
+ emscripten_futex_wake(&handle->state->count, handle->kind == 3 ? INT_MAX : 1) < 0)
+#else
+ syscall(SYS_futex, &handle->state->count, FUTEX_WAKE,
+ handle->kind == 3 ? INT_MAX : 1, NULL, NULL, 0) < 0)
+#endif
system_failure("event wake");
}
@@ -217,7 +253,9 @@ static void create_mutex_locked(void)
pthread_mutexattr_t attributes;
if (pthread_mutexattr_init(&attributes) ||
pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE) ||
+#ifndef __EMSCRIPTEN__
pthread_mutexattr_setrobust(&attributes, PTHREAD_MUTEX_ROBUST) ||
+#endif
pthread_mutex_init(&handles->ownership, &attributes) ||
pthread_mutexattr_destroy(&attributes)) abort();
if (MEM32(g_esp + 8) && pthread_mutex_lock(&handles->ownership)) abort();
@@ -248,7 +286,11 @@ static void release_handle_locked(struct semaphore_handle *handle)
fprintf(stderr, "Closing an owned mutex is not implemented\n");
abort();
}
+#ifdef __EMSCRIPTEN__
+ if (!--handle->state->references) free(handle->state);
+#else
if (munmap(handle->state, sizeof(*handle->state))) system_failure("semaphore unmap");
+#endif
if (handle->fd >= 0 && close(handle->fd)) system_failure("semaphore handle close");
free(handle);
}
@@ -311,7 +353,11 @@ static void release_semaphore_locked(void)
uint32_t previous = MEM32(g_esp + 12);
if (previous) MEM32(previous) = count;
if (pthread_cond_broadcast(&changed)) abort();
+#ifdef __EMSCRIPTEN__
+ if (emscripten_futex_wake(&handle->state->count, increment) < 0)
+#else
if (syscall(SYS_futex, &handle->state->count, FUTEX_WAKE, increment, NULL, NULL, 0) < 0)
+#endif
system_failure("semaphore wake");
g_eax = 1;
break;
@@ -341,7 +387,19 @@ static void wait_for_single_object_locked(void)
if (pthread_mutex_unlock(&mutex)) abort();
int error = !milliseconds ? pthread_mutex_trylock(&handle->ownership) :
milliseconds == UINT32_MAX ? pthread_mutex_lock(&handle->ownership) :
+#ifdef __EMSCRIPTEN__
+ pthread_mutex_trylock(&handle->ownership);
+ while (milliseconds && milliseconds != UINT32_MAX && error == EBUSY) {
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ if (now.tv_sec > deadline.tv_sec ||
+ (now.tv_sec == deadline.tv_sec && now.tv_nsec >= deadline.tv_nsec)) break;
+ usleep(1000);
+ error = pthread_mutex_trylock(&handle->ownership);
+ }
+#else
pthread_mutex_clocklock(&handle->ownership, CLOCK_MONOTONIC, &deadline);
+#endif
if (error == EOWNERDEAD && pthread_mutex_consistent(&handle->ownership)) abort();
if (pthread_mutex_lock(&mutex)) abort();
if (!error || error == EOWNERDEAD) {
@@ -362,9 +420,21 @@ static void wait_for_single_object_locked(void)
}
if (!milliseconds) { g_eax = 258; break; }
if (pthread_mutex_unlock(&mutex)) abort();
+#ifdef __EMSCRIPTEN__
+ double timeout = INFINITY;
+ if (milliseconds != UINT32_MAX) {
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ timeout = (deadline.tv_sec - now.tv_sec) * 1000.0 + (deadline.tv_nsec - now.tv_nsec) / 1000000.0;
+ if (timeout < 0) timeout = 0;
+ }
+ int result = emscripten_futex_wait(&handle->state->count, 0, timeout);
+ int error = -result;
+#else
int result = syscall(SYS_futex, &handle->state->count, FUTEX_WAIT_BITSET, 0,
milliseconds == UINT32_MAX ? NULL : &deadline, NULL, FUTEX_BITSET_MATCH_ANY);
int error = errno;
+#endif
if (pthread_mutex_lock(&mutex)) abort();
if (!result || error == EAGAIN || error == EINTR) continue;
if (error == ETIMEDOUT) { g_eax = 258; break; }
@@ -463,8 +533,21 @@ static void wait_for_multiple_objects_locked(void)
if (milliseconds == UINT32_MAX || now.tv_sec < wake.tv_sec ||
(now.tv_sec == wake.tv_sec && now.tv_nsec < wake.tv_nsec)) wake = now;
}
+#ifdef __EMSCRIPTEN__
+ /* The browser libc exposes timed waits on the condition's realtime clock. */
+ struct timespec realtime;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ clock_gettime(CLOCK_REALTIME, &realtime);
+ realtime.tv_sec += wake.tv_sec - now.tv_sec;
+ realtime.tv_nsec += wake.tv_nsec - now.tv_nsec;
+ if (realtime.tv_nsec < 0) { --realtime.tv_sec; realtime.tv_nsec += 1000000000; }
+ if (realtime.tv_nsec >= 1000000000) { ++realtime.tv_sec; realtime.tv_nsec -= 1000000000; }
+ int error = !has_mutex && milliseconds == UINT32_MAX ? pthread_cond_wait(&changed, &mutex) :
+ pthread_cond_timedwait(&changed, &mutex, &realtime);
+#else
int error = !has_mutex && milliseconds == UINT32_MAX ? pthread_cond_wait(&changed, &mutex) :
pthread_cond_clockwait(&changed, &mutex, CLOCK_MONOTONIC, &wake);
+#endif
if (error && error != ETIMEDOUT) abort();
}
for (unsigned i = 0; i < count; ++i) release_handle_locked(objects[i]);
diff --git a/src/runtime/linux_window.c b/src/runtime/linux_window.c
@@ -15,6 +15,7 @@ static struct {
struct window_class *class;
uint32_t handle, focus, style, capture;
int active, shown;
+ int width, height;
} client;
static uint32_t next_atom = 0xc000, next_handle = 0xf4000000u;
static struct display_context {
@@ -401,7 +402,9 @@ static void create_window(int wide)
SDL_SetWindowTitle(window, title);
free(title);
SDL_SetWindowPosition(window, args[4], args[5]);
- SDL_SetWindowSize(window, args[6] ? args[6] : 1, args[7] ? args[7] : 1);
+ client.width = args[6] ? args[6] : 1;
+ client.height = args[7] ? args[7] : 1;
+ SDL_SetWindowSize(window, client.width, client.height);
client.class = c;
client.handle = next_handle++;
client.style = 0x04c00000u; /* Implicit WS_CAPTION and WS_CLIPSIBLINGS for style zero. */
@@ -490,7 +493,7 @@ static void show_window(void)
/* SDL coordinates describe the client; the compositor owns nonclient paint. */
int x, y, width, height;
SDL_GetWindowPosition(window, &x, &y);
- SDL_GetWindowSize(window, &width, &height);
+ width = client.width; height = client.height;
MEM32(record + 8) = x; MEM32(record + 12) = y;
MEM32(record + 16) = width; MEM32(record + 20) = height;
MEM32(record + 24) |= 0x1804; /* NOZORDER | NOCLIENTMOVE | NOCLIENTSIZE */
@@ -590,10 +593,16 @@ static void system_metrics(void)
uint32_t index = MEM32(g_esp + 4);
if (index > 1) unsupported("system metric", index);
SDL_Rect bounds;
+#ifdef __EMSCRIPTEN__
+ SDL_DisplayMode mode;
+ if (!linux_graphics_window() || linux_graphics_display_mode(&mode)) abort();
+ bounds.w = mode.w; bounds.h = mode.h;
+#else
if (!linux_graphics_window() || SDL_GetDisplayBounds(0, &bounds)) {
fprintf(stderr, "Cannot query native display bounds: %s\n", SDL_GetError());
abort();
}
+#endif
g_eax = index ? bounds.h : bounds.w;
g_esp += 8;
}
@@ -605,7 +614,7 @@ static void client_rect(void)
if (!client.handle || handle != client.handle) MEM32(g_fs_base + 0x34) = 1400;
else {
int width, height;
- SDL_GetWindowSize(linux_graphics_window(), &width, &height);
+ width = client.width; height = client.height;
MEM32(output) = 0; MEM32(output + 4) = 0;
MEM32(output + 8) = width; MEM32(output + 12) = height;
g_eax = 1;
@@ -622,7 +631,7 @@ static void window_rect(void)
/* Match MoveWindow/AdjustWindowRectEx's client-coordinate facade. */
int x, y, width, height;
SDL_GetWindowPosition(linux_graphics_window(), &x, &y);
- SDL_GetWindowSize(linux_graphics_window(), &width, &height);
+ width = client.width; height = client.height;
MEM32(output) = x; MEM32(output + 4) = y;
MEM32(output + 8) = x + width; MEM32(output + 12) = y + height;
g_eax = 1;
@@ -651,7 +660,7 @@ static void set_window_position(void)
SDL_Window *window = linux_graphics_window();
int old_x, old_y, width, height;
SDL_GetWindowPosition(window, &old_x, &old_y);
- SDL_GetWindowSize(window, &width, &height);
+ width = client.width; height = client.height;
SDL_SetWindowPosition(window, x, y);
change_focus(handle);
SDL_GetWindowPosition(window, &x, &y);
@@ -673,7 +682,7 @@ static void move_window(void)
SDL_Window *window = linux_graphics_window();
int x, y, width, height;
SDL_GetWindowPosition(window, &x, &y);
- SDL_GetWindowSize(window, &width, &height);
+ width = client.width; height = client.height;
/* WINDOWPOS followed by NCCALCSIZE_PARAMS, with all pointers in guest space. */
uint32_t record = guest_malloc(80);
@@ -693,7 +702,7 @@ static void move_window(void)
MEM32(record + 36) = x + width; MEM32(record + 40) = y + height;
int old_x, old_y, old_width, old_height;
SDL_GetWindowPosition(window, &old_x, &old_y);
- SDL_GetWindowSize(window, &old_width, &old_height);
+ old_width = client.width; old_height = client.height;
MEM32(record + 44) = old_x; MEM32(record + 48) = old_y;
MEM32(record + 52) = old_x + old_width; MEM32(record + 56) = old_y + old_height;
memcpy((void *)ADDR(record + 60), (const void *)ADDR(record + 44), 16);
@@ -705,6 +714,8 @@ static void move_window(void)
if (memcmp(rectangle, (const void *)ADDR(record + 28), 16)) unsupported("custom client rectangle", record + 28);
}
SDL_SetWindowPosition(window, x, y);
+ /* Win32 geometry updates synchronously even when SDL defers a hidden resize. */
+ client.width = width; client.height = height;
SDL_SetWindowSize(window, width, height);
send_message(0x47, 0, record);
guest_free(record);
@@ -930,7 +941,9 @@ static void process_event(const SDL_Event *event)
}
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
- send_message(5, 0, (event->window.data1 & 0xffffu) | ((uint32_t)event->window.data2 << 16));
+ if (!client.shown) break;
+ /* This fixed-size window retains its requested Win32 client area. */
+ send_message(5, 0, (client.width & 0xffffu) | ((uint32_t)client.height << 16));
break;
case SDL_WINDOWEVENT_MOVED:
send_message(3, 0, (event->window.data1 & 0xffffu) | ((uint32_t)event->window.data2 << 16));
diff --git a/src/runtime/recomp_types.h b/src/runtime/recomp_types.h
@@ -964,6 +964,10 @@ RECOMP_SHARED_DATA RECOMP_THREAD_LOCAL int64_t g_st_i64[8] = {0};
static inline void fp_push_impl(double* st, int* top, double val) {
/* Shift stack down, push new value */
+ /* Keep GCC from lowering these short shifts to out-of-line memmove. */
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC unroll 7
+#endif
for (int i = 7; i > 0; i--) { st[i] = st[i-1]; g_st_i64[i] = g_st_i64[i-1]; }
st[0] = val;
g_st_i64[0] = 0;
@@ -972,6 +976,10 @@ static inline void fp_push_impl(double* st, int* top, double val) {
static inline double fp_pop_impl(double* st, int* top) {
double val = st[0];
+ /* Keep GCC from lowering these short shifts to out-of-line memmove. */
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC unroll 7
+#endif
for (int i = 0; i < 7; i++) { st[i] = st[i+1]; g_st_i64[i] = g_st_i64[i+1]; }
st[7] = 0.0;
g_st_i64[7] = 0;
diff --git a/src/tests/audio.c b/src/tests/audio.c
@@ -20,7 +20,7 @@ static SDL_AudioCallback device_callback;
static void *device_userdata;
static _Atomic int capture, nonzero_samples, bad_samples;
-/* Capture actual output from the public playback path, including SDL scheduling. */
+/* Capture actual output from the public playback path and output worker. */
static void capture_audio(void *userdata, Uint8 *output, int length)
{
device_callback(device_userdata, output, length);
@@ -33,16 +33,25 @@ static void capture_audio(void *userdata, Uint8 *output, int length)
}
}
+#ifdef __EMSCRIPTEN__
+SDL_AudioDeviceID __real_audio_output_open(const SDL_AudioSpec *, SDL_AudioSpec *);
+SDL_AudioDeviceID __wrap_audio_output_open(const SDL_AudioSpec *desired, SDL_AudioSpec *obtained)
+#else
SDL_AudioDeviceID __real_SDL_OpenAudioDevice(const char *, int, const SDL_AudioSpec *, SDL_AudioSpec *, int);
SDL_AudioDeviceID __wrap_SDL_OpenAudioDevice(const char *name, int input, const SDL_AudioSpec *desired,
SDL_AudioSpec *obtained, int changes)
+#endif
{
SDL_AudioSpec spec = *desired;
device_callback = spec.callback;
device_userdata = spec.userdata;
spec.callback = capture_audio;
spec.userdata = NULL;
+#ifdef __EMSCRIPTEN__
+ return __real_audio_output_open(&spec, obtained);
+#else
return __real_SDL_OpenAudioDevice(name, input, &spec, obtained, changes);
+#endif
}
#endif
@@ -562,7 +571,7 @@ static void stream_playback(uint32_t scratch)
call("_AIL_mem_free_lock@4", 1, &wave);
call("_AIL_waveOutClose@4", 1, &driver);
assert(!unlink(path));
- fprintf(stderr, "Linux SDL: 8820 PCM samples verified, pause/resume, restart, mute and stream cleanup passed.\n");
+ fprintf(stderr, "Audio output: 8820 PCM samples verified, pause/resume, restart, mute and stream cleanup passed.\n");
}
#endif
@@ -623,7 +632,7 @@ int main(int argc, char **argv)
adpcm_sample(address);
stream_seek(address);
stream_playback(address);
- fprintf(stderr, "Linux SDL: device enumeration and 4 PCM format open/close/shutdown cases passed.\n");
+ fprintf(stderr, "Audio output: device enumeration and 4 PCM format open/close/shutdown cases passed.\n");
#endif
assert(call("_AIL_set_preference@8", 2, preference) == 64);
call("_AIL_shutdown@0", 0, NULL);
diff --git a/src/tests/browser_audio.c b/src/tests/browser_audio.c
@@ -0,0 +1,64 @@
+#include "browser_audio.h"
+#include <assert.h>
+#include <emscripten.h>
+#include <emscripten/threading.h>
+#include <stdatomic.h>
+#include <stdio.h>
+#include <unistd.h>
+
+static atomic_uint callbacks;
+
+static void render(void *argument, Uint8 *buffer, int length)
+{
+ SDL_AudioSpec *format = argument;
+ assert(!emscripten_is_main_browser_thread());
+ for (int frame = 0; frame < format->samples; ++frame) {
+ int value = frame % 128 < 64 ? 1 : -1;
+ if (format->format == AUDIO_U8) buffer[frame] = 128 + value * 4;
+ else {
+ ((int16_t *)buffer)[frame * 2] = value * 1024;
+ ((int16_t *)buffer)[frame * 2 + 1] = -value * 1024;
+ }
+ }
+ assert(length == format->samples * format->channels * (SDL_AUDIO_BITSIZE(format->format) / 8));
+ atomic_fetch_add(&callbacks, 1);
+}
+
+int main(void)
+{
+ for (unsigned stereo = 0; stereo < 2; ++stereo) {
+ SDL_AudioSpec desired = {0}, obtained;
+ desired.freq = 44100;
+ desired.channels = stereo ? 2 : 1;
+ desired.format = stereo ? AUDIO_S16LSB : AUDIO_U8;
+ desired.samples = 512;
+ desired.callback = render;
+ desired.userdata = &desired;
+ atomic_store(&callbacks, 0);
+ SDL_AudioDeviceID device = audio_output_open(&desired, &obtained);
+ assert(obtained.freq == 44100 && obtained.channels == desired.channels);
+ assert(obtained.format == desired.format && obtained.samples == 512);
+
+ audio_output_pause(device, 0);
+ for (unsigned attempt = 0; attempt < 500 && atomic_load(&callbacks) < 8; ++attempt) usleep(10000);
+ audio_output_lock(device);
+ unsigned locked_count = atomic_load(&callbacks);
+ usleep(50000);
+
+ assert(locked_count >= 8 && atomic_load(&callbacks) == locked_count);
+ audio_output_unlock(device);
+ audio_output_pause(device, 1);
+ unsigned paused_count = atomic_load(&callbacks);
+ usleep(50000);
+ assert(atomic_load(&callbacks) == paused_count);
+ audio_output_pause(device, 0);
+ for (unsigned attempt = 0; attempt < 500 && atomic_load(&callbacks) == paused_count; ++attempt) usleep(10000);
+ assert(atomic_load(&callbacks) > paused_count);
+ audio_output_close(device);
+ unsigned closed_count = atomic_load(&callbacks);
+ usleep(50000);
+ assert(atomic_load(&callbacks) == closed_count);
+ }
+ assert(MAIN_THREAD_EM_ASM_INT({ return Module['checkedBuffers'] >= 18; }));
+ puts("PASS: worker audio mixing, PCM channel conversion, playback scheduling, locking, pause/resume and close");
+}
diff --git a/src/tests/browser_audio.html b/src/tests/browser_audio.html
@@ -0,0 +1,38 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>AO browser audio test</title>
+<button id="start">Run audio test</button>
+<pre id="output"></pre>
+<script>
+ var Module = {
+ checkedBuffers: 0,
+ print: message => { document.querySelector('#output').textContent += message + '\n'; },
+ printErr: message => { document.querySelector('#output').textContent += message + '\n'; }
+ };
+ document.querySelector('#start').onclick = event => {
+ event.target.disabled = true;
+ Module.audioContext = new AudioContext();
+ Module.audioContext.resume();
+ const createSource = Module.audioContext.createBufferSource.bind(Module.audioContext);
+ Module.audioContext.createBufferSource = () => {
+ const source = createSource(), start = source.start.bind(source);
+ source.start = time => {
+ if (Module.audioContext.state !== 'running' || time < Module.audioContext.currentTime)
+ throw new Error('Audio was not scheduled on a running playback clock');
+ for (let channel = 0; channel < source.buffer.numberOfChannels; ++channel) {
+ const samples = source.buffer.getChannelData(channel);
+ for (let frame = 0; frame < samples.length; ++frame) {
+ const expected = (frame % 128 < 64 ? 1 : -1) * (channel ? -1 : 1) / 32;
+ if (samples[frame] !== expected) throw new Error('Incorrect PCM sample or channel');
+ }
+ }
+ ++Module.checkedBuffers;
+ start(time);
+ };
+ return source;
+ };
+ const script = document.createElement('script');
+ script.src = 'audio-output-test.js';
+ document.body.append(script);
+ };
+</script>
diff --git a/src/tests/browser_mixer.html b/src/tests/browser_mixer.html
@@ -0,0 +1,19 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>AO browser mixer test</title>
+<button id="start">Run mixer test</button>
+<pre id="output"></pre>
+<script>
+ var Module = {
+ print: message => { document.querySelector('#output').textContent += message + '\n'; },
+ printErr: message => { document.querySelector('#output').textContent += message + '\n'; }
+ };
+ document.querySelector('#start').onclick = async event => {
+ event.target.disabled = true;
+ Module.audioContext = new AudioContext();
+ await Module.audioContext.resume();
+ const script = document.createElement('script');
+ script.src = 'mixer-test.js';
+ document.body.append(script);
+ };
+</script>
diff --git a/src/tests/browser_runtime.c b/src/tests/browser_runtime.c
@@ -0,0 +1,167 @@
+#include "recomp_types.h"
+#include "guest_memory.h"
+#include "linux_network.h"
+#include "linux_sync.h"
+#include <assert.h>
+#include <emscripten.h>
+#include <emscripten/threading.h>
+#include <stdio.h>
+#include <sys/utsname.h>
+#include <pthread.h>
+
+void browser_initialize(void);
+
+static uint32_t call(recomp_func_t function, unsigned count, const uint32_t *arguments)
+{
+ assert(function);
+ g_esp = 0x10f000;
+ for (unsigned i = 0; i < count; ++i) MEM32(g_esp + 4 + i * 4) = arguments[i];
+ function();
+ assert(g_esp == 0x10f000 + (count + 1) * 4);
+ return g_eax;
+}
+
+static void hostname_queries(int initialized)
+{
+ struct utsname system;
+ assert(uname(&system) == 0);
+ size_t length = strlen(system.nodename);
+ assert(length > 0 && length < 256);
+ assert(linux_network_lookup("gethostname", 0) == linux_network_lookup(NULL, 57));
+ const struct { int size; int null_buffer; } cases[] = {
+ {-1, 0}, {0, 0}, {1, 0}, {length, 0},
+ {length + 1, 0}, {256, 0}, {256, 1}, {0, 1},
+ };
+ for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) {
+ unsigned char expected[264];
+ memset(expected, 0xa5, sizeof(expected));
+ memcpy((void *)ADDR(0x106000), expected, sizeof(expected));
+ uint32_t error = !initialized ? 10093 :
+ cases[i].null_buffer || cases[i].size <= (int)length ? 10014 : 0;
+ if (!error) memcpy(expected + 4, system.nodename, length + 1);
+ MEM32(g_fs_base + 0x34) = 777;
+
+ uint32_t result = call(linux_network_lookup(NULL, 57), 2,
+ (uint32_t[]){cases[i].null_buffer ? 0 : 0x106004, cases[i].size});
+
+ assert(result == (error ? UINT32_MAX : 0));
+ assert(MEM32(g_fs_base + 0x34) == error);
+ assert(!memcmp((void *)ADDR(0x106000), expected, sizeof(expected)));
+ }
+}
+
+static void *format_worker(void *argument)
+{
+ g_fs_base = 0x107000;
+ uint32_t text = call(linux_network_lookup(NULL, 12), 1, (uint32_t[]){0xffffffff});
+ assert(!strcmp((char *)ADDR(text), "255.255.255.255"));
+ return NULL;
+}
+
+static void address_strings(void)
+{
+ assert(linux_network_lookup("inet_ntoa", 0) == linux_network_lookup(NULL, 12));
+ const struct { uint32_t address; const char *text; } cases[] = {
+ {0, "0.0.0.0"}, {0xffffffff, "255.255.255.255"},
+ {0x0100007f, "127.0.0.1"}, {0x2a6433c6, "198.51.100.42"},
+ {0x010200c0, "192.0.2.1"},
+ };
+ uint32_t text = 0;
+ for (unsigned i = 0; i < 5; ++i) {
+ MEM32(g_fs_base + 0x34) = 777;
+
+ uint32_t result = call(linux_network_lookup(NULL, 12), 1, &cases[i].address);
+
+ assert(!strcmp((char *)ADDR(result), cases[i].text));
+ assert(MEM32(g_fs_base + 0x34) == 0);
+ assert(!i || result == text);
+ text = result;
+ }
+ pthread_t thread;
+ assert(!pthread_create(&thread, NULL, format_worker, NULL));
+ assert(!pthread_join(thread, NULL));
+ assert(!strcmp((char *)ADDR(text), "192.0.2.1"));
+}
+
+static void socket_address_queries(uint32_t socket, uint32_t error)
+{
+ assert(linux_network_lookup("getsockname", 0) == linux_network_lookup(NULL, 6));
+ const struct { uint32_t output, length; int size; } cases[] = {
+ {0, 0x106020, 16}, {0x106004, 0, 16}, {0x106004, 0x106020, -1},
+ {0x106004, 0x106020, 15}, {0x106004, 0x106020, 16}, {0x106004, 0x106020, 24},
+ };
+ for (unsigned i = 0; i < 6; ++i) {
+ memset((void *)ADDR(0x106000), 0xa5, 32);
+ MEM32(0x106020) = cases[i].size;
+ MEM32(g_fs_base + 0x34) = 777;
+ uint32_t expected = error == 10093 || error == 10038 ? error : i < 4 ? 10014 : error;
+
+ uint32_t result = call(linux_network_lookup(NULL, 6), 3,
+ (uint32_t[]){socket, cases[i].output, cases[i].length});
+
+ assert(result == (expected ? UINT32_MAX : 0));
+ assert(MEM32(g_fs_base + 0x34) == expected);
+ assert(MEM32(0x106000) == 0xa5a5a5a5 && MEM32(0x106014) == 0xa5a5a5a5);
+ if (expected) {
+ assert(MEM32(0x106020) == (uint32_t)cases[i].size);
+ for (unsigned j = 4; j < 20; ++j) assert(MEM8(0x106000 + j) == 0xa5);
+ } else {
+ assert(MEM32(0x106020) == 16);
+ assert(MEM16(0x106004) == 2 && MEM16(0x106006) == 0);
+ assert(MEM32(0x106008) == 0x0100007f);
+ assert(MEM32(0x10600c) == 0 && MEM32(0x106010) == 0);
+ }
+ }
+}
+
+int main(void)
+{
+ assert(!emscripten_is_main_browser_thread());
+ browser_initialize();
+ assert(guest_map("browser test", 0x100000, 0x10000));
+ g_fs_base = 0x100000;
+ hostname_queries(0);
+ address_strings();
+ socket_address_queries(0, 10093);
+ uint32_t arguments[] = {0x0202, 0x101000};
+ assert(call(linux_network_lookup("WSAStartup", 0), 2, arguments) == 0);
+ hostname_queries(1);
+ socket_address_queries(0, 10038);
+ uint32_t socket = call(linux_network_lookup("socket", 0), 3, (uint32_t[]){2, 1, 0});
+ assert(socket != UINT32_MAX);
+ socket_address_queries(socket, 10022);
+ MEM16(0x102000) = 2;
+ assert(call(linux_network_lookup("connect", 0), 3, (uint32_t[]){socket, 0x102000, 16}) == 0);
+ socket_address_queries(socket, 0);
+ uint32_t event = call(linux_sync_lookup("CreateEventA"), 4, (uint32_t[]){0, 1, 0, 0});
+ assert(event);
+ assert(call(linux_network_lookup("WSAEventSelect", 0), 3, (uint32_t[]){socket, event, 33}) == 0);
+ const unsigned char cookie[] = {
+ 0xdf, 0xdf, 0, 1, 0, 1, 0, 32, 0, 0, 0, 1, 0, 0, 0, 2,
+ 0, 0, 0, 0x1b, 0, 0, 0, 73, 0, 0, 0, 0, 0, 0, 0, 0
+ };
+ memcpy((void *)ADDR(0x103000), cookie, sizeof(cookie));
+
+ assert(call(linux_network_lookup("send", 0), 4, (uint32_t[]){socket, 0x103000, 7, 0}) == 7);
+ assert(call(linux_network_lookup("send", 0), 4, (uint32_t[]){socket, 0x103007, 25, 0}) == 25);
+ assert(call(linux_sync_lookup("WaitForSingleObject"), 2, (uint32_t[]){event, 10000}) == 0);
+ assert(call(linux_network_lookup("WSAEnumNetworkEvents", 0), 3, (uint32_t[]){socket, event, 0x104000}) == 0);
+ uint32_t received = call(linux_network_lookup("recv", 0), 4, (uint32_t[]){socket, 0x105000, 1024, 0});
+ FILE *asset = fopen("cd_image/data/db/ResourceDatabase.dat", "rb");
+ assert(asset);
+ unsigned char bytes[16];
+ size_t read = fread(bytes, 1, sizeof(bytes), asset);
+ fclose(asset);
+
+ assert(MEM32(0x104000) & 1);
+ assert(received >= 20 && received <= 1024);
+ assert(MEM8(0x105010) == 0x5f && MEM8(0x105011) == 0x4b);
+ assert(MEM8(0x105012) == 0x1a && MEM8(0x105013) == 0x39);
+ assert(read == 16);
+ assert(call(linux_network_lookup("closesocket", 0), 1, &socket) == 0);
+ assert(call(linux_network_lookup("WSACleanup", 0), 0, NULL) == 0);
+ hostname_queries(0);
+ address_strings();
+ puts("PASS: worker waits, asset range reads, WebSocket AO initialization and network events");
+ emscripten_exit_with_live_runtime();
+}
diff --git a/src/tests/browser_suspension.c b/src/tests/browser_suspension.c
@@ -0,0 +1,27 @@
+#include <assert.h>
+#include <emscripten.h>
+#include <emscripten/threading.h>
+#include <setjmp.h>
+#include <stdio.h>
+
+static jmp_buf landing;
+static int resumed;
+
+static void yield_and_return(void)
+{
+ emscripten_sleep(0);
+ resumed = 1;
+ longjmp(landing, 7);
+}
+
+int main(void)
+{
+ assert(!emscripten_is_main_browser_thread());
+ resumed = 0;
+
+ int result = setjmp(landing);
+ if (!result) yield_and_return();
+
+ assert(result == 7 && resumed == 1);
+ puts("PASS: JSPI yields through a Wasm longjmp landing pad on the game worker");
+}
diff --git a/src/tests/devices.c b/src/tests/devices.c
@@ -966,6 +966,32 @@ static void material_state_is_copied(uint32_t device)
assert(invoke(device, 17, 2, 0u) == 0x80070057u);
}
+static void vertex_buffer_identities_survive_other_releases(uint32_t d3d)
+{
+ uint32_t buffers[8193];
+ uint32_t desc = workspace() + 128;
+ uint32_t values[] = {16, 0x800, 0x44, 1};
+ memcpy(memory(desc), values, 16);
+ for (unsigned i = 0; i < 8193; ++i) {
+ assert(!invoke(d3d, 5, 4, desc, workspace(), 0u));
+ buffers[i] = *memory(workspace());
+ assert(!invoke(buffers[i], 3, 4, 1u, workspace(), 0u));
+ *memory(*memory(workspace())) = buffers[i];
+ assert(!invoke(buffers[i], 4, 1));
+ }
+
+ for (unsigned i = 0; i < 8193; i += 2)
+ assert(!invoke(buffers[i], 2, 1));
+
+ for (unsigned i = 1; i < 8193; i += 2) {
+ assert(!invoke(buffers[i], 3, 4, 1u, workspace(), workspace() + 4));
+ assert(*memory(workspace() + 4) == 20);
+ assert(*memory(*memory(workspace())) == buffers[i]);
+ assert(!invoke(buffers[i], 4, 1));
+ assert(!invoke(buffers[i], 2, 1));
+ }
+}
+
static void vertex_buffers_preserve_data_and_description(uint32_t d3d)
{
const uint32_t formats[] = {0x112, 0x1c4, 0x44, 0x242, 0x00030112};
@@ -1385,6 +1411,7 @@ static void device_lifetime_and_rendering(const char *pixels_path)
uint32_t draw = *memory(workspace());
assert(!invoke(draw, 20, 3, 0u, 0x808u));
uint32_t d3d = query(draw, d3d_iid), desc = workspace() + 128;
+ vertex_buffer_identities_survive_other_releases(d3d);
vertex_buffers_preserve_data_and_description(d3d);
memset(memory(desc), 0, 124);
*memory(desc) = 124; *memory(desc + 4) = 7;
@@ -1538,6 +1565,9 @@ int main(int argc, char **argv)
g_esp = 0x5000f000;
#endif
device_lifetime_and_rendering(argv[1]);
+#ifdef __EMSCRIPTEN__
+ linux_graphics_shutdown();
+#endif
puts("device: ownership, viewport, scenes, clear, triangles, line lists, depth, textures, filtering and blending passed");
return 0;
}
diff --git a/src/tests/fpu_stack.c b/src/tests/fpu_stack.c
@@ -0,0 +1,49 @@
+#include "recomp_types.h"
+#include <assert.h>
+
+static void push_preserves_register_bits(void)
+{
+ const uint64_t values[] = {0x8000000000000000ull, 0x7ff8000000001234ull,
+ 0x7ff0000000000000ull, 0xfff0000000000000ull, 1, 2, 3, 4};
+ const int64_t exact[] = {INT64_MAX, INT64_MIN, 3, 4, 5, 6, 7, 8};
+ memcpy(g_st, values, sizeof(values));
+ memcpy(g_st_i64, exact, sizeof(exact));
+ g_fp_top = 3;
+
+ fp_push_impl(g_st, &g_fp_top, 1.5);
+
+ const uint64_t expected[] = {0x3ff8000000000000ull, 0x8000000000000000ull,
+ 0x7ff8000000001234ull, 0x7ff0000000000000ull, 0xfff0000000000000ull, 1, 2, 3};
+ const int64_t expected_exact[] = {0, INT64_MAX, INT64_MIN, 3, 4, 5, 6, 7};
+ assert(!memcmp(g_st, expected, sizeof(expected)));
+ assert(!memcmp(g_st_i64, expected_exact, sizeof(expected_exact)));
+ assert(g_fp_top == 4);
+}
+
+static void pop_preserves_register_bits(void)
+{
+ const uint64_t values[] = {0x7ff8000000001234ull, 0x8000000000000000ull,
+ 0x7ff0000000000000ull, 0xfff0000000000000ull, 1, 2, 3, 4};
+ const int64_t exact[] = {INT64_MAX, INT64_MIN, 3, 4, 5, 6, 7, 8};
+ memcpy(g_st, values, sizeof(values));
+ memcpy(g_st_i64, exact, sizeof(exact));
+ g_fp_top = 3;
+
+ double result = fp_pop_impl(g_st, &g_fp_top);
+
+ const uint64_t expected[] = {0x8000000000000000ull, 0x7ff0000000000000ull,
+ 0xfff0000000000000ull, 1, 2, 3, 4, 0};
+ const int64_t expected_exact[] = {INT64_MIN, 3, 4, 5, 6, 7, 8, 0};
+ const uint64_t expected_result = 0x7ff8000000001234ull;
+ assert(!memcmp(&result, &expected_result, sizeof(result)));
+ assert(!memcmp(g_st, expected, sizeof(expected)));
+ assert(!memcmp(g_st_i64, expected_exact, sizeof(expected_exact)));
+ assert(g_fp_top == 2);
+}
+
+int main(void)
+{
+ push_preserves_register_bits();
+ pop_preserves_register_bits();
+ puts("fpu-stack: register bits, exact integer shadows and stack depth passed");
+}
diff --git a/src/tests/graphics.c b/src/tests/graphics.c
@@ -133,6 +133,7 @@ static void direct_draw_seven_creation_and_windowed_mode(void)
uint32_t result = invoke(memory(*memory(object))[20], 3, object, 0, 8);
assert(result == 0);
+ assert(!invoke(memory(*memory(object))[19], 1, object, 0, 0));
assert(!invoke(memory(*memory(object))[26], 1, object, 0, 0));
#ifdef _WIN32
unsigned control = _control87(0, 0);
@@ -173,7 +174,7 @@ static void vertical_blank_wait_preserves_guest_state(void)
#ifndef _WIN32
SDL_DisplayMode mode;
assert(!SDL_GetCurrentDisplayMode(SDL_GetWindowDisplayIndex(SDL_GL_GetCurrentWindow()), &mode));
- assert(mode.refresh_rate > 0);
+ if (!mode.refresh_rate) mode.refresh_rate = 60;
uint64_t start = SDL_GetPerformanceCounter();
#endif
@@ -590,7 +591,7 @@ static void direct3d_enumerates_the_native_renderer(void)
#ifndef _WIN32
static void attached_depth_is_shared_and_retained(void)
{
- struct gl_target *first = gl_target_create(32, 32), *second = gl_target_create(32, 32);
+ struct gl_target *first = gl_target_create(32, 32, 1), *second = gl_target_create(32, 32, 1);
struct gl_depth *depth = gl_depth_create(32, 32, 16);
assert(first && second && depth);
gl_target_set_depth(first, depth);
@@ -624,7 +625,7 @@ static void attached_depth_is_shared_and_retained(void)
static void uploads_preserve_depth_and_top_down_pixels(void)
{
- struct gl_target *target = gl_target_create(2, 2);
+ struct gl_target *target = gl_target_create(2, 2, 1);
assert(target);
gl_target_clear(target, 0, 0.0f);
const unsigned char input[] = {10, 20, 30, 40, 50, 60, 70, 80,
@@ -647,7 +648,7 @@ static void uploads_preserve_depth_and_top_down_pixels(void)
static void indexed_triangles_preserve_depth_and_target_contents(void)
{
- struct gl_target *first = gl_target_create(32, 32), *second = gl_target_create(32, 32);
+ struct gl_target *first = gl_target_create(32, 32, 1), *second = gl_target_create(32, 32, 1);
assert(first && second);
struct gl_vertex vertices[] = {
{{-0.75f, -0.75f, 0.25f, 1}, {0, 1, 0, 1}},
@@ -711,7 +712,7 @@ static void indexed_triangles_preserve_depth_and_target_contents(void)
static void presentation_flips_guest_rows_into_window_coordinates(void)
{
- struct gl_target *target = gl_target_create(4, 4);
+ struct gl_target *target = gl_target_create(4, 4, 1);
unsigned char input[64] = {0}, output[32 * 32 * 4];
const int32_t rectangle[] = {1, 1, 3, 3};
input[(1 * 4 + 1) * 4] = 255;
@@ -735,7 +736,7 @@ static void presentation_flips_guest_rows_into_window_coordinates(void)
static void eviction_releases_gpu_storage_and_restores_pixels(void)
{
- struct gl_target *texture = gl_target_create(2, 2);
+ struct gl_target *texture = gl_target_create(2, 2, 0);
const unsigned char input[] = {1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16};
unsigned char output[16];
gl_target_set_depth(texture, NULL);
@@ -744,15 +745,15 @@ static void eviction_releases_gpu_storage_and_restores_pixels(void)
glGetIntegerv(GL_TEXTURE_BINDING_2D, &name);
assert(glIsTexture(name));
- gl_target_evict(texture);
- gl_target_evict(texture);
+ gl_target_evict(texture, input);
+ gl_target_evict(texture, input);
assert(!glIsTexture(name));
gl_target_read(texture, output);
assert(!memcmp(output, input, 16));
glGetIntegerv(GL_TEXTURE_BINDING_2D, &name);
assert(glIsTexture(name));
- gl_target_evict(texture);
+ gl_target_evict(texture, input);
gl_target_destroy(texture);
assert(!glIsTexture(name) && glGetError() == GL_NO_ERROR);
}
diff --git a/src/tests/guest_memory.c b/src/tests/guest_memory.c
@@ -0,0 +1,32 @@
+#include "guest_memory.h"
+#include <assert.h>
+#include <signal.h>
+#include <stdio.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+int main(void)
+{
+ assert(guest_map("cross-page fixture", 0x50000000, 0x20000));
+ assert(guest_map("high address fixture", 0xffff0000, 0x10000));
+
+ unsigned char *crossing = (void *)guest_address(0x5000ffff);
+ crossing[0] = 12;
+ crossing[1] = 34;
+ *(unsigned char *)guest_address(0xffffffff) = 56;
+
+ assert(guest_address(0) == 0);
+ assert(*(unsigned char *)guest_address(0x50010000) == 34);
+ assert(*(unsigned char *)guest_address(0xffffffff) == 56);
+ assert(*(unsigned char *)guest_address(0x50000000) == 0);
+ pid_t child = fork();
+ assert(child >= 0);
+ if (!child) {
+ *(volatile unsigned char *)guest_address(0x60000000) = 1;
+ _exit(1);
+ }
+ int status;
+ assert(waitpid(child, &status, 0) == child);
+ assert(WIFSIGNALED(status) && WTERMSIG(status) == SIGSEGV);
+ puts("PASS: contiguous guest pages, zero-fill, 32-bit limits and unmapped-page protection");
+}
diff --git a/src/tests/matrix4.c b/src/tests/matrix4.c
@@ -0,0 +1,62 @@
+#include "recomp_types.h"
+#include <assert.h>
+
+void sub_3B0044A0(void);
+void sub_3B004580(void);
+recomp_func_t recomp_lookup(uint32_t address) { abort(); }
+recomp_func_t recomp_lookup_import(uint32_t address) { abort(); }
+
+static void test_product(unsigned mode)
+{
+ const float left[] = {1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16};
+ const float right[] = {16,15,14,13, 12,11,10,9, 8,7,6,5, 4,3,2,1};
+ memcpy((void *)ADDR(0x50000000), left, sizeof(left));
+ memcpy((void *)ADDR(0x50000040), right, sizeof(right));
+ g_esp = 0x5000ff00;
+ g_ecx = 0x50000000;
+ g_ebx = 123; g_esi = 234; g_edi = 345; g_ebp = 456;
+ g_fp_top = 6;
+ for (unsigned i = 0; i < 8; ++i) { g_st[i] = i + .25; g_st_i64[i] = i + 123; }
+ /* In-place, separate output, and output aliasing the right operand. */
+ MEM32(g_esp + 4) = mode == 1 ? 0x50000080 : 0x50000040;
+ MEM32(g_esp + 8) = 0x50000040;
+
+ if (mode == 0) sub_3B0044A0();
+ else sub_3B004580();
+
+ const float expected[] = {80,70,60,50, 240,214,188,162,
+ 400,358,316,274, 560,502,444,386};
+ assert(g_eax == (mode == 0 ? 0x50000000 : mode == 1 ? 0x50000080 : 0x50000040));
+ assert(!memcmp((void *)ADDR(g_eax), expected, sizeof(expected)));
+ assert(g_esp == (mode == 0 ? 0x5000ff08 : 0x5000ff0c));
+ assert(g_ecx == 0 && g_edx == (mode == 0 ? 0x50000048 : 0x5000fef8));
+ assert(g_ebx == 123 && g_esi == 234 && g_edi == 345 && g_ebp == 456);
+ assert(g_fp_top == 6 && g_st[0] == .25 && g_st[5] == 5.25);
+ assert(g_st_i64[0] == 123 && g_st_i64[5] == 128);
+ assert(g_st[6] == 0 && g_st[7] == 0 && g_st_i64[6] == 0 && g_st_i64[7] == 0);
+ assert(g_flag_k == FK_DEC && g_flag_a == 1 && g_flag_b == 1 && g_flag_cf == 0);
+}
+
+static void test_rounding(void)
+{
+ const float left[] = {16777216,1,-16777216,1, 0,0,0,0, 0,0,0,0, 0,0,0,0};
+ const float right[] = {1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1};
+ memcpy((void *)ADDR(0x50000000), left, sizeof(left));
+ memcpy((void *)ADDR(0x50000040), right, sizeof(right));
+ g_esp = 0x5000ff00;
+ g_ecx = 0x50000000;
+ MEM32(g_esp + 4) = 0x50000040;
+
+ sub_3B0044A0();
+
+ const float expected[] = {2,2,2,2, 0,0,0,0, 0,0,0,0, 0,0,0,0};
+ assert(!memcmp((void *)ADDR(0x50000000), expected, sizeof(expected)));
+}
+
+int main(void)
+{
+ assert(guest_map("matrix fixture", 0x50000000, 0x10000));
+ for (unsigned mode = 0; mode < 3; ++mode) test_product(mode);
+ test_rounding();
+ puts("matrix4: multiplication, aliases, rounding and guest ABI passed");
+}
diff --git a/src/tests/tile_corners.c b/src/tests/tile_corners.c
@@ -0,0 +1,197 @@
+#include "recomp_types.h"
+#include <assert.h>
+
+void sub_38038370(void);
+void sub_38039DA0(void);
+void sub_38039DB0(void);
+void sub_38039DC0(void);
+void sub_38039E60(void);
+void sub_38039EC0(void);
+
+static unsigned patch_calls, raw_calls, height_calls;
+static uint32_t patch_coordinates[2][2], raw_coordinates[2][2], height_coordinates[2][2];
+
+/* These three imports supply terrain data; all tilemap functions are real. */
+static void patch_handle(void)
+{
+ assert(g_ecx == 0x5000a000 && patch_calls < 2);
+ patch_coordinates[patch_calls][0] = MEM32(g_esp + 4);
+ patch_coordinates[patch_calls++][1] = MEM32(g_esp + 8);
+ g_eax = 0x5000b000;
+ g_esp += 12;
+}
+
+static void raw_height(void)
+{
+ assert(g_ecx == 0x5000a000 && raw_calls < 2);
+ assert(MEM32(g_esp + 4) == 0x5000b000);
+ raw_coordinates[raw_calls][0] = MEM32(g_esp + 8);
+ raw_coordinates[raw_calls][1] = MEM32(g_esp + 12);
+ g_eax = raw_calls++ == 0 ? 0x0102 : 0x0506;
+ g_esp += 16;
+ g_st[7] = 91.25;
+ g_st_i64[7] = INT64_MAX;
+}
+
+static void height(void)
+{
+ assert(g_ecx == 0x5000a000 && height_calls < 2);
+ height_coordinates[height_calls][0] = MEM32(g_esp + 4);
+ height_coordinates[height_calls][1] = MEM32(g_esp + 8);
+ g_eax = height_calls++ == 0 ? 0x0304 : 0x0708;
+ if (!MEM8(g_ecx + 0x29)) g_eax >>= 8;
+ g_esp += 12;
+ g_st[7] = -42.5;
+ g_st_i64[7] = INT64_MIN;
+}
+
+recomp_func_t recomp_lookup_manual(uint32_t address) { return NULL; }
+recomp_func_t recomp_lookup_import(uint32_t address) { abort(); }
+recomp_func_t recomp_lookup(uint32_t address)
+{
+ switch (address) {
+ case 0x38039dc0: return sub_38039DC0;
+ case 0x38039da0: return sub_38039DA0;
+ case 0x38039db0: return sub_38039DB0;
+ case 0x38039e60: return sub_38039E60;
+ case 0x38039ec0: return sub_38039EC0;
+ case 0x500: return patch_handle;
+ case 0x504: return raw_height;
+ case 0x508: return height;
+ default: abort();
+ }
+}
+
+static void arrange_tilemap(void)
+{
+ /* Place the tilemap, its backing data, outputs, and guest stack separately. */
+ memset((void *)ADDR(0x50000000), 0, 0x20000);
+ patch_calls = raw_calls = height_calls = 0;
+ g_eax = 123; g_ecx = 0x50000000; g_edx = 234;
+ g_esp = 0x5001ff00; g_ebp = 345; g_ebx = 456; g_esi = 567; g_edi = 678;
+ g_flag_k = FK_NONE; g_flag_a = 0; g_flag_b = 0; g_flag_cf = 0;
+ g_fp_top = 3;
+ for (unsigned i = 0; i < 8; ++i) { g_st[i] = i + .25; g_st_i64[i] = INT64_MAX - i; }
+ MEM32(0x5000000c) = 0x50001000;
+ *(float *)ADDR(0x5000101c) = .5f;
+ MEM32(0x50001228) = 0x5000b000;
+ MEM32(0x50009258) = 0x5000a000;
+ MEM32(0x5000925c) = 512;
+ MEM32(0x50009260) = 1024;
+ *(float *)ADDR(0x50009264) = 3.25f;
+ MEM32(0x5000a03c) = 4;
+ MEM32(0x5000a040) = 15;
+
+ /* The guest thiscall receives two indices and four Vector3 references. */
+ MEM32(g_esp) = 0x11223344;
+ MEM32(g_esp + 4) = 2;
+ MEM32(g_esp + 8) = 3;
+ MEM32(g_esp + 12) = 0x5000f000;
+ MEM32(g_esp + 16) = 0x5000f00c;
+ MEM32(g_esp + 20) = 0x5000f018;
+ MEM32(g_esp + 24) = 0x5000f024;
+ MEM32(g_esp + 28) = 0x55667788;
+}
+
+static void assert_preserved_state(void)
+{
+ assert(g_esp == 0x5001ff1c);
+ assert(g_ebp == 345 && g_ebx == 456 && g_esi == 567 && g_edi == 678);
+ assert(MEM32(0x5001ff00) == 0x11223344);
+ assert(MEM32(0x5001ff1c) == 0x55667788);
+ assert(g_fp_top == 3);
+ assert(g_st[0] == .25 && g_st[1] == 1.25 && g_st[2] == 2.25);
+ assert(g_st_i64[0] == INT64_MAX && g_st_i64[1] == INT64_MAX - 1);
+ assert(g_st_i64[2] == INT64_MAX - 2);
+ assert(g_st[4] == 0 && g_st[5] == 0 && g_st[6] == 0 && g_st[7] == 0);
+ assert(g_st_i64[4] == 0 && g_st_i64[5] == 0 && g_st_i64[6] == 0 && g_st_i64[7] == 0);
+}
+
+static void ground_8bit(void)
+{
+ arrange_tilemap();
+ const float expected[] = {6.5f, .5f, 9.75f, 9.75f, 1.5f, 9.75f,
+ 9.75f, 2.5f, 13.f, 6.5f, 3.5f, 13.f};
+
+ sub_38038370();
+
+ assert(memcmp((void *)ADDR(0x5000f000), expected, sizeof(expected)) == 0);
+ assert((g_eax & 255) == 0);
+ assert(patch_calls == 2 && raw_calls == 2 && height_calls == 2);
+ assert(patch_coordinates[0][0] == 0 && patch_coordinates[0][1] == 0);
+ assert(patch_coordinates[1][0] == 0 && patch_coordinates[1][1] == 0);
+ assert(raw_coordinates[0][0] == 2 && raw_coordinates[0][1] == 3);
+ assert(raw_coordinates[1][0] == 3 && raw_coordinates[1][1] == 4);
+ assert(height_coordinates[0][0] == 3 && height_coordinates[0][1] == 3);
+ assert(height_coordinates[1][0] == 2 && height_coordinates[1][1] == 4);
+ assert_preserved_state();
+}
+
+static void ground_16bit(void)
+{
+ arrange_tilemap();
+ MEM8(0x5000a029) = 1;
+ const float expected[] = {6.5f, 129.f, 9.75f, 9.75f, 386.f, 9.75f,
+ 9.75f, 643.f, 13.f, 6.5f, 900.f, 13.f};
+
+ sub_38038370();
+
+ assert(memcmp((void *)ADDR(0x5000f000), expected, sizeof(expected)) == 0);
+ assert((g_eax & 255) == 0);
+ assert(patch_calls == 2 && raw_calls == 2 && height_calls == 2);
+ assert_preserved_state();
+}
+
+static void dungeon_heights(void)
+{
+ arrange_tilemap();
+ MEM32(0x50001018) = 1;
+ MEM8(0x5000b401) = 2;
+ MEM8(0x5000b402) = 4;
+ MEM8(0x5000b602) = 6;
+ MEM8(0x5000b601) = 8;
+ const float expected[] = {6.5f, 1.f, 9.75f, 9.75f, 2.f, 9.75f,
+ 9.75f, 3.f, 13.f, 6.5f, 4.f, 13.f};
+
+ sub_38038370();
+
+ assert(memcmp((void *)ADDR(0x5000f000), expected, sizeof(expected)) == 0);
+ assert((g_eax & 255) == 1);
+ assert(patch_calls == 0 && raw_calls == 0 && height_calls == 0);
+ assert_preserved_state();
+}
+
+static void aliased_corner_rounding(void)
+{
+ arrange_tilemap();
+ MEM8(0x5000a029) = 1;
+ MEM32(0x5000925c) = 16777219;
+ MEM32(0x50009260) = 16777219;
+ *(float *)ADDR(0x50009264) = 1.f;
+ MEM32(g_esp + 4) = 16777217;
+ MEM32(g_esp + 8) = 16777217;
+ MEM32(g_esp + 16) = 0x5000f000;
+ MEM32(g_esp + 20) = 0x5000f000;
+ MEM32(g_esp + 24) = 0x5000f000;
+ const float expected[] = {16777216.f, 900.f, 16777218.f};
+
+ sub_38038370();
+
+ assert(memcmp((void *)ADDR(0x5000f000), expected, sizeof(expected)) == 0);
+ assert((g_eax & 255) == 1);
+ assert_preserved_state();
+}
+
+int main(void)
+{
+ assert(guest_map("tilemap test", 0x50000000, 0x20000));
+ assert(guest_map("tilemap imports", 0x38040000, 0x10000));
+ MEM32(0x3804e24c) = 0x500;
+ MEM32(0x3804e248) = 0x504;
+ MEM32(0x3804e244) = 0x508;
+ ground_8bit();
+ ground_16bit();
+ dungeon_heights();
+ aliased_corner_rounding();
+ puts("tile corner contracts passed");
+}
diff --git a/src/tests/water_ring.c b/src/tests/water_ring.c
@@ -0,0 +1,117 @@
+#include "recomp_types.h"
+#include <assert.h>
+
+void sub_2503D070(void);
+void sub_2503CD60(void);
+void sub_251380E8(void);
+
+/* Match runtime/guest_crt.c:crt_ftol at the water ring's import boundary. */
+static void convert(void)
+{
+ int64_t value = fp_st0_to_i64(g_st[0], g_st_i64[0], 0x0c7f);
+ fp_pop_impl(g_st, &g_fp_top);
+ g_eax = (uint32_t)value;
+ g_edx = (uint32_t)((uint64_t)value >> 32);
+ g_esp += 4;
+}
+
+recomp_func_t recomp_lookup(uint32_t address)
+{
+ if (address == 0x2503CD60) return sub_2503CD60;
+ if (address == 0x251380E8) return sub_251380E8;
+ if (address == 0x70000000) return convert;
+ abort();
+}
+recomp_func_t recomp_lookup_manual(uint32_t address) { return NULL; }
+recomp_func_t recomp_lookup_import(uint32_t address) { abort(); }
+
+static void setup_fixture(void)
+{
+ /* Build the ring object and retain the real color-table initializer. */
+ memset((void *)ADDR(0x50000000), 0, 0x10000);
+ MEM8(0x251C7634) = 0;
+ MEM32(0x25151268) = 0x70000000;
+ MEM32(0x2515177C) = 0;
+ MEM32(0x251517A4) = 0x3f800000;
+ MEM32(0x25151928) = 0x437f0000;
+ MEM32(0x25153B10) = 0xc2fe0000;
+ MEM32(0x25153B0C) = 0x42fe0000;
+ *(float *)ADDR(0x50000200) = 2;
+ *(float *)ADDR(0x50000204) = .75f;
+ MEM32(0x50000208) = 0x50001000;
+ MEM32(0x5000020C) = 0x50002000;
+ MEM32(0x50000210) = 0x50003000;
+ *(float *)ADDR(0x50000218) = .5f;
+ *(float *)ADDR(0x50000220) = .25f;
+
+ /* Supply two radii, alpha, and observable caller register/FPU state. */
+ g_esp = 0x5000ff00;
+ g_ecx = 0x50000000;
+ g_ebx = 123; g_esi = 234; g_edi = 345; g_ebp = 456;
+ *(float *)ADDR(g_esp + 4) = 2;
+ *(float *)ADDR(g_esp + 8) = 4;
+ *(float *)ADDR(g_esp + 12) = .5f;
+ g_fp_top = 6;
+ for (unsigned i = 0; i < 8; ++i) {
+ g_st[i] = i + .25;
+ g_st_i64[i] = 9007199254740993ll + i;
+ }
+}
+
+static void test_vertices(void)
+{
+ setup_fixture();
+ MEM32(0x500001FC) = 1;
+ const float x[] = {1, 0}, z[] = {0, 1};
+ memcpy((void *)ADDR(0x50001000), x, sizeof(x));
+ memcpy((void *)ADDR(0x50002000), z, sizeof(z));
+
+ sub_2503D070();
+
+ /* Each vertex contains x, y, z, packed color, u, and v. */
+ const uint32_t expected[] = {
+ 0x40000000,0,0,0x7fdddddd,0,0,
+ 0x40800000,0,0,0x7f1f1f1f,0,0x3f400000,
+ 0,0,0x40000000,0x7fb4b4b4,0x40000000,0,
+ 0,0,0x40800000,0x7f464646,0x40000000,0x3f400000
+ };
+ assert(!memcmp(expected, (void *)ADDR(0x50003000), sizeof(expected)));
+ assert(MEM32(0x50000214) == 4);
+ assert(g_esp == 0x5000ff10);
+ assert(g_eax == 1 && g_ecx == 1 && g_edx == 4);
+ assert(g_ebx == 123 && g_esi == 234 && g_edi == 345 && g_ebp == 456);
+ assert(g_fp_top == 6 && g_st[0] == .25 && g_st[3] == 3.25);
+ assert(g_st_i64[0] == 9007199254740993ll && g_st_i64[3] == 9007199254740996ll);
+ for (unsigned i = 4; i < 8; ++i) assert(g_st[i] == 0 && g_st_i64[i] == 0);
+ assert(g_flag_k == FK_CMP && g_flag_a == 2 && g_flag_b == 1 && !g_flag_cf);
+}
+
+static void test_negative_segments(void)
+{
+ setup_fixture();
+ MEM32(0x500001FC) = 0xffffffff;
+ MEM32(0x50000214) = 99;
+ memset((void *)ADDR(0x50003000), 0xa5, 96);
+
+ sub_2503D070();
+
+ assert(MEM32(0x50000214) == 0);
+ for (unsigned i = 0; i < 24; ++i) assert(MEM32(0x50003000 + i * 4) == 0xa5a5a5a5);
+ assert(g_esp == 0x5000ff10);
+ assert(g_eax == 0xffffffff && g_ecx == 0xffffffff && g_edx == 0);
+ assert(g_ebx == 123 && g_esi == 234 && g_edi == 345 && g_ebp == 456);
+ assert(g_fp_top == 6 && g_st[0] == .25 && g_st[5] == 5.25);
+ assert(g_st_i64[0] == 9007199254740993ll && g_st_i64[5] == 9007199254740998ll);
+ assert(g_st[6] == 0 && g_st[7] == 0 && g_st_i64[6] == 0 && g_st_i64[7] == 0);
+ assert(g_flag_k == FK_TEST && g_flag_a == 0xffffffff && g_flag_b == 0xffffffff && !g_flag_cf);
+}
+
+int main(void)
+{
+ assert(guest_map("water ring fixture", 0x50000000, 0x10000));
+ assert(guest_map("water ring constants", 0x25150000, 0x4000));
+ assert(guest_map("water ring color table", 0x251C0000, 0x10000));
+ test_vertices();
+ test_negative_segments();
+ puts("water-ring: vertices, colors, UVs, guest ABI and negative segments passed");
+}
diff --git a/src/tests/window.c b/src/tests/window.c
@@ -218,9 +218,9 @@ static void create_and_destroy_dispatch_guest_messages(void)
uint32_t window = call("CreateWindowExA", 12, args);
uint32_t busy = call("UnregisterClassA", 2, unregister_args), busy_error = error();
#ifndef _WIN32
- int width, height;
- SDL_GetWindowSize(linux_graphics_window(), &width, &height);
- assert(width == 320 && height == 240);
+ uint32_t query[] = {window, workspace() + 192};
+ assert(call("GetClientRect", 2, query));
+ assert(memory(query[1])[2] == 320 && memory(query[1])[3] == 240);
assert(!strcmp(SDL_GetWindowTitle(linux_graphics_window()), "AO window test"));
assert(SDL_GetWindowFlags(linux_graphics_window()) & SDL_WINDOW_HIDDEN);
assert(!(SDL_GetWindowFlags(linux_graphics_window()) & SDL_WINDOW_FULLSCREEN));
@@ -411,14 +411,17 @@ static void window_geometry_preserves_requested_client_area(void)
index = 1;
assert(call("GetSystemMetrics", 1, &index) >= 480);
#ifndef _WIN32
- int width, height;
- SDL_GetWindowSize(linux_graphics_window(), &width, &height);
- assert(width == 640 && height == 480);
assert(!(SDL_GetWindowFlags(linux_graphics_window()) & SDL_WINDOW_BORDERLESS));
int x, y;
SDL_GetWindowPosition(linux_graphics_window(), &x, &y);
assert(origin_x == (uint32_t)x && origin_y == (uint32_t)y);
assert(window_x == origin_x && window_y == origin_y);
+ /* SDL may defer a hidden native resize until the window is mapped. */
+ SDL_ShowWindow(linux_graphics_window());
+ SDL_PumpEvents();
+ int width, height;
+ SDL_GetWindowSize(linux_graphics_window(), &width, &height);
+ assert(width == 640 && height == 480);
#endif
capture_geometry = 0;
assert(call("DestroyWindow", 1, &window));
diff --git a/tools/client/build_wasm_dependencies.py b/tools/client/build_wasm_dependencies.py
@@ -0,0 +1,55 @@
+"""Build the audio/font dependencies with the repository's Emscripten SDK."""
+import hashlib
+import pathlib
+import subprocess
+import tarfile
+import urllib.request
+
+
+root = pathlib.Path(__file__).resolve().parents[2]
+work = root / 'local/wasm'
+sdk = root / 'toolchains/emsdk/upstream/emscripten'
+work.mkdir(parents=True, exist_ok=True)
+
+# Pin the same libsndfile release used on Debian and its required MPEG encoder.
+for name, url, digest in [
+ ('libsndfile-1.2.2.tar.xz',
+ 'https://github.com/libsndfile/libsndfile/releases/download/1.2.2/libsndfile-1.2.2.tar.xz',
+ '3799ca9924d3125038880367bf1468e53a1b7e3686a934f098b7e1d286cdb80e'),
+ ('lame-3.100.tar.gz',
+ 'https://downloads.sourceforge.net/project/lame/lame/3.100/lame-3.100.tar.gz',
+ 'ddfe36cab873794038ae2c1210557ad34857a4b6bdc515785d1da9e175b1da1e'),
+]:
+ archive = work / name
+ if not archive.exists():
+ urllib.request.urlretrieve(url, archive)
+ assert hashlib.sha256(archive.read_bytes()).hexdigest() == digest, archive
+ directory = work / name.split('.tar.')[0]
+ if not directory.exists():
+ with tarfile.open(archive) as package:
+ package.extractall(work, filter='data')
+
+# Emscripten supplies its supported FreeType and mpg123 ports.
+probe = work / 'dependency-probe.c'
+probe.write_text('int main(void) { return 0; }\n')
+subprocess.run([str(sdk / 'emcc'), str(probe), '-pthread', '-sUSE_SDL=2',
+ '-sUSE_FREETYPE=1', '-sUSE_MPG123=1', '-o', str(work / 'dependency-probe.js')], check=True)
+prefix = work / 'deps'
+subprocess.run([str(sdk / 'emconfigure'), './configure', '--prefix=' + str(prefix),
+ '--disable-shared', '--disable-frontend', '--disable-decoder', 'CFLAGS=-O2 -pthread'],
+ cwd=work / 'lame-3.100', check=True)
+subprocess.run(['make', '-j4'], cwd=work / 'lame-3.100', check=True)
+subprocess.run(['make', 'install'], cwd=work / 'lame-3.100', check=True)
+
+# Keep decoding in C so Linux and browser audio use the same mixer and formats.
+subprocess.run([str(sdk / 'emcmake'), 'cmake', '-S', str(work / 'libsndfile-1.2.2'),
+ '-B', str(work / 'sndfile-build'), '-DCMAKE_BUILD_TYPE=Release',
+ '-DCMAKE_C_FLAGS=-pthread', '-DCMAKE_INSTALL_PREFIX=' + str(prefix),
+ '-DENABLE_EXTERNAL_LIBS=OFF', '-DBUILD_PROGRAMS=OFF',
+ '-DBUILD_EXAMPLES=OFF', '-DBUILD_TESTING=OFF',
+ '-Dmpg123_INCLUDE_DIR=' + str(sdk / 'cache/sysroot/include'),
+ '-Dmpg123_LIBRARY=' + str(sdk / 'cache/sysroot/lib/wasm32-emscripten/libmpg123.a'),
+ '-DMP3LAME_INCLUDE_DIR=' + str(prefix / 'include'),
+ '-DMP3LAME_LIBRARY=' + str(prefix / 'lib/libmp3lame.a')], check=True)
+subprocess.run(['cmake', '--build', str(work / 'sndfile-build'), '-j4'], check=True)
+subprocess.run(['cmake', '--install', str(work / 'sndfile-build')], check=True)