Archive incari-client (client, 26.3, clean)
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
# platform-desktop
|
||||
|
||||
- Only `platform-api`, LWJGL and the JDK. Never game types (`BoundaryTest`).
|
||||
- Never copy code from `work/client` (Mojang's SDL/OpenAL classes). Implement from LWJGL's API
|
||||
and the `platform-api` Javadoc. `./incari copycheck` must pass.
|
||||
- Test changes here on a machine with a GPU and audio; the game can't run without them.
|
||||
- Test: `./gradlew :platform-desktop:check`.
|
||||
@@ -0,0 +1,34 @@
|
||||
# platform-desktop: the LWJGL platform
|
||||
|
||||
`platform-api` on a normal JVM, over LWJGL (SDL3, OpenAL, STB): the desktop dev runtime, where
|
||||
the game is debugged with a real debugger and profiler.
|
||||
|
||||
## Code map
|
||||
|
||||
`DesktopPlatform` is the whole platform; `app-desktop` installs it.
|
||||
|
||||
- `SdlWindow`, `SdlDisplays`, `SdlEventPump`, `SdlInput`, `SdlShell`, `SdlLogBridge`: SDL3.
|
||||
Windowing policy lives here (borderless-window fullscreen on Windows, exclusive-mode fallback,
|
||||
mouse confinement in exclusive fullscreen).
|
||||
- `audio`: `OpenAlAudio` and its device, sources and buffers. It's also the reference the
|
||||
browser's sound is held to: `openAlReference` (below) measures how it pans and fades.
|
||||
- `net`: `DesktopNetwork`: TCP sockets with a virtual thread per connection, and WebSockets
|
||||
and HTTP GETs (`fetch`) through the JDK's HTTP client (`java.net.http`).
|
||||
|
||||
## Invariants
|
||||
|
||||
- **Depends only on `platform-api` and LWJGL.** No game types (`BoundaryTest`).
|
||||
- **Compiles against the LWJGL version the game ships** (`gradle/libs.versions.toml`); at run
|
||||
time the game's own jars are used.
|
||||
- **Written fresh against LWJGL's API.** It replaces what Mojang's classes did; never copy them.
|
||||
|
||||
## How to test
|
||||
|
||||
```sh
|
||||
./gradlew :platform-desktop:check
|
||||
./gradlew :platform-desktop:openAlReference # the desktop's panning and fading, measured
|
||||
```
|
||||
|
||||
`openAlReference` plays a tone at known positions with OpenAL Soft writing to a WAV file (no sound
|
||||
card needed), and checks the levels `platform-web`'s `Spatializer` copies (ADR 0013). Run it after
|
||||
an LWJGL update.
|
||||
@@ -0,0 +1,73 @@
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
`java-library`
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api(project(":platform-api"))
|
||||
|
||||
// Compile against the same LWJGL version the game ships (libs.versions.toml). At run time
|
||||
// the game's own copies are on the classpath, so these are compile-only.
|
||||
compileOnly(platform(libs.lwjgl.bom))
|
||||
compileOnly(libs.lwjgl)
|
||||
compileOnly(libs.lwjgl.sdl)
|
||||
compileOnly(libs.lwjgl.openal)
|
||||
compileOnly(libs.lwjgl.stb)
|
||||
compileOnly(libs.lwjgl.freetype)
|
||||
|
||||
// A WebSocket server for the WebSocket connection's tests.
|
||||
testImplementation(libs.netty.transport)
|
||||
testImplementation(libs.netty.codec.http)
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testImplementation(libs.archunit)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
|
||||
// `./gradlew :platform-desktop:openAlReference` (ADR 0013): what the desktop's sound sounds
|
||||
// like, measured. OpenAlReferenceTest plays a tone through this platform's OpenAL device at known
|
||||
// positions with OpenAL Soft writing to a WAV file instead of a sound card, and checks each
|
||||
// channel's level against the gains platform-web's Web Audio model reproduces. Needs the game's
|
||||
// LWJGL and this machine's natives (`./incari setup`); no sound card. Not part of `check`: OpenAL
|
||||
// Soft reads the configuration that selects the file only from the environment it starts in.
|
||||
val repoRoot = rootProject.layout.projectDirectory
|
||||
val lwjglRuntime = run {
|
||||
val version = Properties().apply {
|
||||
repoRoot.file("incari.properties").asFile.reader().use { load(it) }
|
||||
}.getProperty("minecraft.version")
|
||||
val root = repoRoot.asFile
|
||||
fun listed(name: String) = providers.fileContents(repoRoot.file("work/cache/versions/$version/$name")).asText
|
||||
.map { text -> text.lines().map { it.trim() }.filter { it.isNotEmpty() } }.orElse(emptyList())
|
||||
listed("classpath.txt").zip(listed("natives.txt")) { jars, natives -> jars + natives }
|
||||
.map { paths ->
|
||||
paths.filter { it.contains("/org/lwjgl/lwjgl/") || it.contains("/org/lwjgl/lwjgl-openal/") }
|
||||
.map { root.resolve(it) }
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register<Test>("openAlReference") {
|
||||
group = "verification"
|
||||
description = "Measures the desktop's OpenAL panning and attenuation through OpenAL Soft's wave backend."
|
||||
testClassesDirs = sourceSets.test.get().output.classesDirs
|
||||
classpath = sourceSets.test.get().runtimeClasspath + files(lwjglRuntime)
|
||||
filter { includeTestsMatching("*OpenAlReferenceTest") }
|
||||
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
|
||||
val directory = layout.buildDirectory.dir("openal-reference").get().asFile
|
||||
val config = directory.resolve("alsoft.conf")
|
||||
val wave = directory.resolve("output.wav")
|
||||
environment("ALSOFT_CONF", config.path)
|
||||
environment("INCARI_OPENAL_WAVE", wave.path)
|
||||
jvmArgs(
|
||||
"--enable-native-access=ALL-UNNAMED",
|
||||
"-Dorg.lwjgl.system.SharedLibraryExtractPath=" + repoRoot.dir("work/natives/lwjgl").asFile.path,
|
||||
)
|
||||
// Stereo 48 kHz, as a desktop's usual output; the device is opened as the game opens it.
|
||||
doFirst {
|
||||
directory.mkdirs()
|
||||
config.writeText("[general]\ndrivers=wave\nchannels=stereo\nfrequency=48000\n[wave]\nfile=${wave.path}\n")
|
||||
}
|
||||
outputs.upToDateWhen { false }
|
||||
testLogging { events("passed", "failed") }
|
||||
}
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
package incari.platform.desktop;
|
||||
|
||||
import incari.platform.api.AppInfo;
|
||||
import incari.platform.api.NativeSurfaceFactory;
|
||||
import incari.platform.api.Platform;
|
||||
import incari.platform.api.PlatformException;
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.PlatformShell;
|
||||
import incari.platform.api.audio.PlatformAudio;
|
||||
import incari.platform.api.fonts.PlatformFonts;
|
||||
import incari.platform.api.input.PlatformInput;
|
||||
import incari.platform.api.net.PlatformNetwork;
|
||||
import incari.platform.api.profile.PlatformProfiling;
|
||||
import incari.platform.api.rtc.PlatformRtc;
|
||||
import incari.platform.api.storage.PlatformStorage;
|
||||
import incari.platform.api.threads.PlatformThreads;
|
||||
import incari.platform.api.window.PlatformDisplays;
|
||||
import incari.platform.api.window.PlatformEventListener;
|
||||
import incari.platform.api.window.PlatformWindow;
|
||||
import incari.platform.api.window.WindowSpec;
|
||||
import incari.platform.desktop.audio.OpenAlAudio;
|
||||
import incari.platform.desktop.net.DesktopNetwork;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.sdl.SDLHints;
|
||||
import org.lwjgl.sdl.SDLInit;
|
||||
import org.lwjgl.sdl.SDLPlatform;
|
||||
import org.lwjgl.sdl.SDLTimer;
|
||||
import org.lwjgl.sdl.SDLVideo;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
/**
|
||||
* The platform on a normal JVM: SDL3 for the window and input, OpenAL for sound, TCP sockets for
|
||||
* servers, the JVM's own threads. This is the desktop dev runtime: the same game code the
|
||||
* browser runs, debuggable with ordinary Java tools.
|
||||
*/
|
||||
public final class DesktopPlatform implements Platform {
|
||||
|
||||
private PlatformRtc rtc = PlatformRtc.UNSUPPORTED;
|
||||
|
||||
private final PlatformFonts fonts = new FreeTypeFonts();
|
||||
private final PlatformStorage storage;
|
||||
private final PlatformLog log;
|
||||
private final SdlDisplays displays;
|
||||
private final SdlInput input = new SdlInput();
|
||||
private final SdlShell shell;
|
||||
private final SdlEventPump events = new SdlEventPump();
|
||||
private final DesktopNetwork network;
|
||||
private final PlatformThreads threads = suggested -> suggested;
|
||||
private final PlatformProfiling profiling = new DesktopProfiling();
|
||||
private final boolean debugLogging;
|
||||
private @Nullable OpenAlAudio audio;
|
||||
private @Nullable SdlWindow window;
|
||||
|
||||
/**
|
||||
* @param debugLogging whether to pass SDL's debug-level messages to the log
|
||||
*/
|
||||
public DesktopPlatform(PlatformStorage storage, PlatformLog log, boolean debugLogging) {
|
||||
this.storage = storage;
|
||||
this.log = log;
|
||||
this.debugLogging = debugLogging;
|
||||
this.displays = new SdlDisplays(log);
|
||||
this.shell = new SdlShell(log);
|
||||
this.network = new DesktopNetwork(log);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
String platform = SDLPlatform.SDL_GetPlatform();
|
||||
String driver = SDLVideo.SDL_GetCurrentVideoDriver();
|
||||
return "SDL on " + (platform == null ? "an unknown system" : platform)
|
||||
+ (driver == null ? "" : " (" + driver + ")");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize(AppInfo app) {
|
||||
new SdlLogBridge(log).install(debugLogging);
|
||||
Map<String, String> metadata = new LinkedHashMap<>();
|
||||
metadata.put("SDL.app.metadata.name", app.name());
|
||||
metadata.put("SDL.app.metadata.version", app.version());
|
||||
metadata.put("SDL.app.metadata.identifier", app.identifier());
|
||||
metadata.put("SDL.app.metadata.creator", app.creator());
|
||||
metadata.put("SDL.app.metadata.url", app.url());
|
||||
metadata.put("SDL.app.metadata.type", "game");
|
||||
metadata.forEach(SDLInit::SDL_SetAppMetadataProperty);
|
||||
|
||||
Map<String, String> hints = new LinkedHashMap<>();
|
||||
// The JVM handles signals itself.
|
||||
hints.put("SDL_NO_SIGNAL_HANDLERS", "1");
|
||||
// Alt-tabbing out of fullscreen must not minimize the game.
|
||||
hints.put("SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS", "0");
|
||||
// The game decides when to quit, after saving.
|
||||
hints.put("SDL_QUIT_ON_LAST_WINDOW_CLOSE", "0");
|
||||
// A click that focuses the window also reaches the game.
|
||||
hints.put("SDL_MOUSE_FOCUS_CLICKTHROUGH", "1");
|
||||
hints.put("SDL_ENABLE_SCREEN_KEYBOARD", "0");
|
||||
// The game draws the composition text itself; the input method draws only its candidates.
|
||||
hints.put("SDL_IME_IMPLEMENTED_UI", "composition");
|
||||
hints.forEach(SDLHints::SDL_SetHint);
|
||||
|
||||
if (!SDLInit.SDL_Init(SDLInit.SDL_INIT_VIDEO)) {
|
||||
throw new PlatformException("Couldn't start SDL: " + SdlWindow.sdlError());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
OpenAlAudio currentAudio = audio;
|
||||
if (currentAudio != null) {
|
||||
currentAudio.close();
|
||||
}
|
||||
events.close();
|
||||
SDLInit.SDL_Quit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long nanoTime() {
|
||||
return SDLTimer.SDL_GetTicksNS();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformDisplays displays() {
|
||||
return displays;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformWindow createWindow(WindowSpec spec, NativeSurfaceFactory surface) {
|
||||
if (window != null) {
|
||||
throw new IllegalStateException("The game has one window, and it already exists");
|
||||
}
|
||||
SdlWindow created = SdlWindow.create(spec, surface, displays, log);
|
||||
window = created;
|
||||
events.setWindow(created);
|
||||
return created;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pollEvents(PlatformEventListener listener) {
|
||||
events.poll(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endFrame() {
|
||||
// The swap chain and the game's own frame limiter pace the loop on the desktop.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flushInputEvents() {
|
||||
events.flushInput();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformInput input() {
|
||||
return input;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformShell shell() {
|
||||
return shell;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformAudio audio() {
|
||||
OpenAlAudio current = audio;
|
||||
if (current == null) {
|
||||
// Created on first use: OpenAL's native library loads only when the game starts sound.
|
||||
current = new OpenAlAudio(log);
|
||||
audio = current;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformNetwork network() {
|
||||
return network;
|
||||
}
|
||||
|
||||
/**
|
||||
* The desktop has no WebRTC (ADR 0019); smoke tests may give it a scripted stand-in, to check
|
||||
* voice chat's signalling against a real server. Call before the game starts.
|
||||
*/
|
||||
public void setRtc(PlatformRtc standIn) {
|
||||
rtc = standIn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformRtc rtc() {
|
||||
return rtc;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void crashNatively() {
|
||||
// A write through a null pointer: the JVM dies with a native crash report, like a driver bug.
|
||||
MemoryUtil.memSet(0L, 0, 1L);
|
||||
throw new IllegalStateException("A write to address 0 didn't crash the JVM");
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformStorage storage() {
|
||||
return storage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformThreads threads() {
|
||||
return threads;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformProfiling profiling() {
|
||||
return profiling;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformFonts fonts() {
|
||||
return fonts;
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package incari.platform.desktop;
|
||||
|
||||
import incari.platform.api.profile.FrameSample;
|
||||
import incari.platform.api.profile.MemoryUsage;
|
||||
import incari.platform.api.profile.PlatformProfiling;
|
||||
import java.lang.management.BufferPoolMXBean;
|
||||
import java.lang.management.GarbageCollectorMXBean;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Profiling on the JVM: the heap and the collections from the JVM's management beans, the
|
||||
* direct buffers as the memory outside the heap. Frames aren't kept anywhere: on the desktop the
|
||||
* profiler overlay and the JVM's own tools read them.
|
||||
*/
|
||||
final class DesktopProfiling implements PlatformProfiling {
|
||||
|
||||
private final List<GarbageCollectorMXBean> collectors = ManagementFactory.getGarbageCollectorMXBeans();
|
||||
private final List<BufferPoolMXBean> bufferPools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
|
||||
|
||||
@Override
|
||||
public MemoryUsage memory() {
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
long collections = 0;
|
||||
for (GarbageCollectorMXBean collector : collectors) {
|
||||
collections += Math.max(0, collector.getCollectionCount());
|
||||
}
|
||||
long direct = 0;
|
||||
for (BufferPoolMXBean pool : bufferPools) {
|
||||
direct += Math.max(0, pool.getMemoryUsed());
|
||||
}
|
||||
return new MemoryUsage(runtime.totalMemory() - runtime.freeMemory(), runtime.maxMemory(), direct, collections);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void frameProfiled(FrameSample sample) {}
|
||||
|
||||
@Override
|
||||
public void mark(String name) {}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package incari.platform.desktop;
|
||||
|
||||
import incari.platform.api.storage.PlatformStorage;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Game directories on the local file system, as the launcher (or {@code app-desktop}) chose them.
|
||||
*
|
||||
* @param gameDirectory where options, saves and packs go
|
||||
* @param assetsDirectory the launcher-layout assets directory ({@code indexes/}, {@code objects/})
|
||||
* @param assetIndex the asset index id, for example "34"
|
||||
*/
|
||||
public record DesktopStorage(
|
||||
String gameDirectory,
|
||||
String assetsDirectory,
|
||||
@Nullable String assetIndex) implements PlatformStorage {}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package incari.platform.desktop;
|
||||
|
||||
import incari.platform.api.fonts.FontFace;
|
||||
import incari.platform.api.fonts.PlatformFonts;
|
||||
import java.nio.ByteBuffer;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.PointerBuffer;
|
||||
import org.lwjgl.system.MemoryStack;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
import org.lwjgl.util.freetype.FT_Bitmap;
|
||||
import org.lwjgl.util.freetype.FT_Face;
|
||||
import org.lwjgl.util.freetype.FT_GlyphSlot;
|
||||
import org.lwjgl.util.freetype.FreeType;
|
||||
|
||||
/**
|
||||
* Smooth fonts through FreeType, the library the game's own TrueType provider uses, with a library
|
||||
* instance of its own. Glyphs are rendered with the font's hinting turned to "light" (vertical
|
||||
* only), as FreeType's default does for anti-aliased text: shapes keep their widths, edges stay
|
||||
* soft.
|
||||
*/
|
||||
final class FreeTypeFonts implements PlatformFonts {
|
||||
|
||||
/** FreeType's library isn't thread-safe; faces made from it share it. */
|
||||
private static final Object LOCK = new Object();
|
||||
|
||||
private long library;
|
||||
|
||||
@Override
|
||||
public @Nullable FontFace open(byte[] data, String name, float pixelsPerEm) {
|
||||
synchronized (LOCK) {
|
||||
if (library == 0) {
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
PointerBuffer pointer = stack.mallocPointer(1);
|
||||
if (FreeType.FT_Init_FreeType(pointer) != 0) {
|
||||
return null;
|
||||
}
|
||||
library = pointer.get(0);
|
||||
}
|
||||
}
|
||||
ByteBuffer memory = MemoryUtil.memAlloc(data.length);
|
||||
memory.put(data).flip();
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
PointerBuffer pointer = stack.mallocPointer(1);
|
||||
if (FreeType.FT_New_Memory_Face(library, memory, 0, pointer) != 0) {
|
||||
MemoryUtil.memFree(memory);
|
||||
return null;
|
||||
}
|
||||
FT_Face face = FT_Face.create(pointer.get(0));
|
||||
FreeType.FT_Select_Charmap(face, FreeType.FT_ENCODING_UNICODE);
|
||||
int size = Math.max(1, Math.round(pixelsPerEm));
|
||||
FreeType.FT_Set_Pixel_Sizes(face, size, size);
|
||||
return new Face(face, memory);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Face implements FontFace {
|
||||
|
||||
private @Nullable FT_Face face;
|
||||
private @Nullable ByteBuffer memory;
|
||||
|
||||
Face(FT_Face face, ByteBuffer memory) {
|
||||
this.face = face;
|
||||
this.memory = memory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FontFace.@Nullable Glyph glyph(int codepoint) {
|
||||
synchronized (LOCK) {
|
||||
FT_Face open = face;
|
||||
if (open == null) {
|
||||
return null;
|
||||
}
|
||||
int index = FreeType.FT_Get_Char_Index(open, codepoint);
|
||||
if (index == 0
|
||||
|| FreeType.FT_Load_Glyph(open, index, FreeType.FT_LOAD_RENDER | FreeType.FT_LOAD_TARGET_LIGHT)
|
||||
!= 0) {
|
||||
return null;
|
||||
}
|
||||
FT_GlyphSlot slot = open.glyph();
|
||||
if (slot == null) {
|
||||
return null;
|
||||
}
|
||||
FT_Bitmap bitmap = slot.bitmap();
|
||||
int width = bitmap.width();
|
||||
int height = bitmap.rows();
|
||||
int pitch = bitmap.pitch();
|
||||
byte[] coverage = new byte[width * height];
|
||||
ByteBuffer buffer = width > 0 && height > 0 ? bitmap.buffer(Math.abs(pitch) * height) : null;
|
||||
if (buffer != null) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
int row = pitch >= 0 ? y * pitch : (height - 1 - y) * -pitch;
|
||||
for (int x = 0; x < width; x++) {
|
||||
coverage[y * width + x] = buffer.get(row + x);
|
||||
}
|
||||
}
|
||||
}
|
||||
float advance = slot.advance().x() / 64.0F;
|
||||
return new FontFace.Glyph(advance, slot.bitmap_left(), slot.bitmap_top(), width, height, coverage);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
synchronized (LOCK) {
|
||||
if (face != null) {
|
||||
FreeType.FT_Done_Face(face);
|
||||
face = null;
|
||||
}
|
||||
if (memory != null) {
|
||||
MemoryUtil.memFree(memory);
|
||||
memory = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
package incari.platform.desktop;
|
||||
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.window.DisplayInfo;
|
||||
import incari.platform.api.window.DisplayMode;
|
||||
import incari.platform.api.window.PlatformDisplays;
|
||||
import java.nio.IntBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.PointerBuffer;
|
||||
import org.lwjgl.sdl.SDLPixels;
|
||||
import org.lwjgl.sdl.SDLStdinc;
|
||||
import org.lwjgl.sdl.SDLVideo;
|
||||
import org.lwjgl.sdl.SDL_DisplayMode;
|
||||
import org.lwjgl.sdl.SDL_PixelFormatDetails;
|
||||
import org.lwjgl.sdl.SDL_Rect;
|
||||
import org.lwjgl.system.MemoryStack;
|
||||
|
||||
/** Monitors as SDL3 reports them, queried fresh on every call. */
|
||||
final class SdlDisplays implements PlatformDisplays {
|
||||
|
||||
private final PlatformLog log;
|
||||
|
||||
SdlDisplays(PlatformLog log) {
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DisplayInfo> all() {
|
||||
IntBuffer ids = SDLVideo.SDL_GetDisplays();
|
||||
if (ids == null) {
|
||||
log.warn("Couldn't list displays: " + SdlWindow.sdlError());
|
||||
return List.of();
|
||||
}
|
||||
List<DisplayInfo> displays = new ArrayList<>();
|
||||
try {
|
||||
int primary = primaryId();
|
||||
for (int i = 0; i < ids.limit(); i++) {
|
||||
DisplayInfo display = get(ids.get(i));
|
||||
if (display != null) {
|
||||
// Primary first, as the interface promises.
|
||||
displays.add(display.id() == primary ? 0 : displays.size(), display);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
SDLStdinc.SDL_free(ids);
|
||||
}
|
||||
return displays;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable DisplayInfo get(int id) {
|
||||
if (id == 0) {
|
||||
return null;
|
||||
}
|
||||
String name = Objects.requireNonNullElse(SDLVideo.SDL_GetDisplayName(id), "unknown display");
|
||||
SDL_DisplayMode desktop = SDLVideo.SDL_GetDesktopDisplayMode(id);
|
||||
if (desktop == null) {
|
||||
log.warn("Couldn't query the desktop mode of display " + name + ": " + SdlWindow.sdlError());
|
||||
return null;
|
||||
}
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
SDL_Rect bounds = SDL_Rect.malloc(stack);
|
||||
if (!SDLVideo.SDL_GetDisplayBounds(id, bounds)) {
|
||||
log.warn("Couldn't query the bounds of display " + name + ": " + SdlWindow.sdlError());
|
||||
return null;
|
||||
}
|
||||
return new DisplayInfo(
|
||||
id,
|
||||
name,
|
||||
bounds.x(),
|
||||
bounds.y(),
|
||||
bounds.w(),
|
||||
bounds.h(),
|
||||
toDisplayMode(desktop),
|
||||
fullscreenModes(id, name));
|
||||
}
|
||||
}
|
||||
|
||||
private List<DisplayMode> fullscreenModes(int id, String name) {
|
||||
PointerBuffer modes = SDLVideo.SDL_GetFullscreenDisplayModes(id);
|
||||
if (modes == null) {
|
||||
log.warn("Couldn't list the video modes of display " + name + ": " + SdlWindow.sdlError());
|
||||
return List.of();
|
||||
}
|
||||
try {
|
||||
List<DisplayMode> result = new ArrayList<>(modes.limit());
|
||||
for (int i = 0; i < modes.limit(); i++) {
|
||||
result.add(toDisplayMode(SDL_DisplayMode.create(modes.get(i))));
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
SDLStdinc.SDL_free(modes);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int primaryId() {
|
||||
return SDLVideo.SDL_GetPrimaryDisplay();
|
||||
}
|
||||
|
||||
static DisplayMode toDisplayMode(SDL_DisplayMode mode) {
|
||||
SDL_PixelFormatDetails format = SDLPixels.SDL_GetPixelFormatDetails(mode.format());
|
||||
// An unknown pixel format is reported as 8 bits per channel: the only kind modern
|
||||
// displays drive, and the kind the game accepts.
|
||||
int red = format == null ? 8 : format.Rbits();
|
||||
int green = format == null ? 8 : format.Gbits();
|
||||
int blue = format == null ? 8 : format.Bbits();
|
||||
return new DisplayMode(mode.w(), mode.h(), red, green, blue, mode.refresh_rate());
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package incari.platform.desktop;
|
||||
|
||||
import static org.lwjgl.sdl.SDLEvents.*;
|
||||
|
||||
import incari.platform.api.input.KeyAction;
|
||||
import incari.platform.api.window.PlatformEventListener;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.sdl.SDLEvents;
|
||||
import org.lwjgl.sdl.SDLKeyboard;
|
||||
import org.lwjgl.sdl.SDL_Event;
|
||||
import org.lwjgl.sdl.SDL_KeyboardEvent;
|
||||
import org.lwjgl.sdl.SDL_MouseMotionEvent;
|
||||
import org.lwjgl.sdl.SDL_MouseWheelEvent;
|
||||
import org.lwjgl.sdl.SDL_TextEditingEvent;
|
||||
|
||||
/** Drains SDL's event queue into a {@link PlatformEventListener}. */
|
||||
final class SdlEventPump implements AutoCloseable {
|
||||
|
||||
/**
|
||||
* The last event type counted as input: everything from key events up to the end of the pen
|
||||
* events (keys, text, mouse, joysticks, touch, drops, sensors, pens).
|
||||
*/
|
||||
private static final int LAST_INPUT_EVENT = 0x13FF;
|
||||
|
||||
/** Reused for every event: polling runs every frame and must not allocate. */
|
||||
private final SDL_Event event = SDL_Event.malloc();
|
||||
|
||||
private final List<String> droppedFiles = new ArrayList<>();
|
||||
private @Nullable SdlWindow window;
|
||||
|
||||
void setWindow(@Nullable SdlWindow window) {
|
||||
this.window = window;
|
||||
}
|
||||
|
||||
void poll(PlatformEventListener listener) {
|
||||
while (SDLEvents.SDL_PollEvent(event)) {
|
||||
dispatch(listener);
|
||||
}
|
||||
}
|
||||
|
||||
void flushInput() {
|
||||
SDLEvents.SDL_PumpEvents();
|
||||
SDLEvents.SDL_FlushEvents(SDL_EVENT_KEY_DOWN, LAST_INPUT_EVENT);
|
||||
}
|
||||
|
||||
private void dispatch(PlatformEventListener listener) {
|
||||
switch (event.type()) {
|
||||
case SDL_EVENT_QUIT, SDL_EVENT_WINDOW_CLOSE_REQUESTED -> listener.closeRequested();
|
||||
case SDL_EVENT_TERMINATING -> listener.terminating();
|
||||
case SDL_EVENT_DISPLAY_ADDED ->
|
||||
listener.displayAdded(event.display().displayID());
|
||||
case SDL_EVENT_DISPLAY_REMOVED ->
|
||||
listener.displayRemoved(event.display().displayID());
|
||||
case SDL_EVENT_DISPLAY_CURRENT_MODE_CHANGED ->
|
||||
listener.displayModeChanged(event.display().displayID());
|
||||
case SDL_EVENT_WINDOW_MOVED ->
|
||||
listener.windowMoved(event.window().data1(), event.window().data2());
|
||||
case SDL_EVENT_WINDOW_RESIZED -> {
|
||||
SdlWindow current = window;
|
||||
if (current != null) {
|
||||
// A resize can move the window between fullscreen states the grab depends on.
|
||||
current.updateMouseGrab();
|
||||
}
|
||||
listener.windowResized(event.window().data1(), event.window().data2());
|
||||
}
|
||||
case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED ->
|
||||
listener.framebufferResized(
|
||||
event.window().data1(), event.window().data2());
|
||||
case SDL_EVENT_WINDOW_MINIMIZED -> listener.minimizedChanged(true);
|
||||
case SDL_EVENT_WINDOW_MAXIMIZED, SDL_EVENT_WINDOW_RESTORED -> listener.minimizedChanged(false);
|
||||
case SDL_EVENT_WINDOW_MOUSE_ENTER, SDL_EVENT_WINDOW_MOUSE_LEAVE -> listener.cursorEnteredOrLeft();
|
||||
case SDL_EVENT_WINDOW_FOCUS_GAINED -> listener.focusChanged(true);
|
||||
case SDL_EVENT_WINDOW_FOCUS_LOST -> listener.focusChanged(false);
|
||||
case SDL_EVENT_WINDOW_DISPLAY_CHANGED -> listener.displayChanged();
|
||||
case SDL_EVENT_WINDOW_ENTER_FULLSCREEN -> listener.fullscreenChanged(true);
|
||||
case SDL_EVENT_WINDOW_LEAVE_FULLSCREEN -> listener.fullscreenChanged(false);
|
||||
case SDL_EVENT_KEY_DOWN, SDL_EVENT_KEY_UP -> key(listener);
|
||||
case SDL_EVENT_TEXT_INPUT -> {
|
||||
String text = event.text().textString();
|
||||
if (text != null) {
|
||||
listener.textInput(text);
|
||||
}
|
||||
}
|
||||
case SDL_EVENT_TEXT_EDITING -> {
|
||||
SDL_TextEditingEvent edit = event.edit();
|
||||
String text = edit.textString();
|
||||
listener.textEditing(text == null ? "" : text, edit.start(), edit.length());
|
||||
}
|
||||
case SDL_EVENT_KEYMAP_CHANGED -> listener.keymapChanged();
|
||||
case SDL_EVENT_MOUSE_MOTION -> {
|
||||
SDL_MouseMotionEvent motion = event.motion();
|
||||
listener.mouseMoved(motion.x(), motion.y(), motion.xrel(), motion.yrel());
|
||||
}
|
||||
case SDL_EVENT_MOUSE_BUTTON_DOWN, SDL_EVENT_MOUSE_BUTTON_UP ->
|
||||
listener.mouseButton(
|
||||
Byte.toUnsignedInt(event.button().button()),
|
||||
event.button().down(),
|
||||
modifiers());
|
||||
case SDL_EVENT_MOUSE_WHEEL -> {
|
||||
SDL_MouseWheelEvent wheel = event.wheel();
|
||||
listener.mouseWheel(wheel.x(), wheel.y(), modifiers());
|
||||
}
|
||||
case SDL_EVENT_DROP_BEGIN -> droppedFiles.clear();
|
||||
case SDL_EVENT_DROP_FILE -> {
|
||||
String path = event.drop().dataString();
|
||||
if (path != null) {
|
||||
droppedFiles.add(path);
|
||||
}
|
||||
}
|
||||
case SDL_EVENT_DROP_COMPLETE -> {
|
||||
if (!droppedFiles.isEmpty()) {
|
||||
listener.filesDropped(List.copyOf(droppedFiles));
|
||||
}
|
||||
droppedFiles.clear();
|
||||
}
|
||||
default -> {
|
||||
// Everything else (gamepads, sensors, pens, clipboard updates) isn't used yet.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void key(PlatformEventListener listener) {
|
||||
SDL_KeyboardEvent key = event.key();
|
||||
KeyAction action = !key.down() ? KeyAction.RELEASE : key.repeat() ? KeyAction.REPEAT : KeyAction.PRESS;
|
||||
listener.key(key.scancode(), key.key(), key.mod() & 0xFFFF, action);
|
||||
}
|
||||
|
||||
private static int modifiers() {
|
||||
return SDLKeyboard.SDL_GetModState() & 0xFFFF;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
event.free();
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package incari.platform.desktop;
|
||||
|
||||
import incari.platform.api.input.PlatformInput;
|
||||
import java.nio.ByteBuffer;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.sdl.SDLKeyboard;
|
||||
|
||||
/**
|
||||
* Keyboard state from SDL3. SDL's scancodes are HID usage ids and its modifier bits are the
|
||||
* platform-api's, so nothing needs translating.
|
||||
*/
|
||||
final class SdlInput implements PlatformInput {
|
||||
|
||||
/** SDL's key state array: owned by SDL, valid for the life of the program, updated on poll. */
|
||||
private @Nullable ByteBuffer keyboardState;
|
||||
|
||||
@Override
|
||||
public boolean isKeyDown(int scancode) {
|
||||
ByteBuffer state = keyboardState;
|
||||
if (state == null) {
|
||||
state = SDLKeyboard.SDL_GetKeyboardState();
|
||||
if (state == null) {
|
||||
return false;
|
||||
}
|
||||
keyboardState = state;
|
||||
}
|
||||
return scancode >= 0 && scancode < state.limit() && state.get(scancode) != 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int modifiers() {
|
||||
// SDL_Keymod is an unsigned 16-bit value in a Java short.
|
||||
return SDLKeyboard.SDL_GetModState() & 0xFFFF;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable String keyName(int scancode) {
|
||||
int keyCode = SDLKeyboard.SDL_GetKeyFromScancode(scancode, (short) 0, false);
|
||||
String name = SDLKeyboard.SDL_GetKeyName(keyCode);
|
||||
return name == null || name.isEmpty() ? null : name;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package incari.platform.desktop;
|
||||
|
||||
import incari.platform.api.PlatformLog;
|
||||
import org.lwjgl.sdl.SDLLog;
|
||||
import org.lwjgl.sdl.SDL_LogOutputFunction;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
/** Sends SDL's own log messages to the platform log, tagged with SDL's category. */
|
||||
final class SdlLogBridge {
|
||||
|
||||
private final PlatformLog log;
|
||||
/** Held so the native callback isn't freed while SDL can still call it. */
|
||||
private final SDL_LogOutputFunction callback;
|
||||
|
||||
SdlLogBridge(PlatformLog log) {
|
||||
this.log = log;
|
||||
this.callback = SDL_LogOutputFunction.create(this::onMessage);
|
||||
}
|
||||
|
||||
void install(boolean debug) {
|
||||
SDLLog.SDL_SetLogOutputFunction(callback, 0L);
|
||||
SDLLog.SDL_SetLogPriorities(debug ? SDLLog.SDL_LOG_PRIORITY_DEBUG : SDLLog.SDL_LOG_PRIORITY_INFO);
|
||||
}
|
||||
|
||||
private void onMessage(long userData, int category, int priority, long message) {
|
||||
String text = message == 0L ? "" : MemoryUtil.memUTF8(message);
|
||||
String line = "SDL [" + categoryName(category) + "]: " + text;
|
||||
if (priority <= SDLLog.SDL_LOG_PRIORITY_DEBUG) {
|
||||
log.debug(line);
|
||||
} else if (priority == SDLLog.SDL_LOG_PRIORITY_INFO) {
|
||||
log.info(line);
|
||||
} else if (priority == SDLLog.SDL_LOG_PRIORITY_WARN) {
|
||||
log.warn(line);
|
||||
} else {
|
||||
log.error(line, null);
|
||||
}
|
||||
}
|
||||
|
||||
/** SDL's built-in log categories (SDL_LogCategory), by their documented order. */
|
||||
private static String categoryName(int category) {
|
||||
String[] names = {"APPLICATION", "ERROR", "ASSERT", "SYSTEM", "AUDIO", "VIDEO", "RENDER", "INPUT", "TEST", "GPU"
|
||||
};
|
||||
return category >= 0 && category < names.length ? names[category] : "category " + category;
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package incari.platform.desktop;
|
||||
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.PlatformShell;
|
||||
import java.net.URI;
|
||||
import java.nio.IntBuffer;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.sdl.SDLClipboard;
|
||||
import org.lwjgl.sdl.SDLMessageBox;
|
||||
import org.lwjgl.sdl.SDLMisc;
|
||||
import org.lwjgl.sdl.SDL_MessageBoxButtonData;
|
||||
import org.lwjgl.sdl.SDL_MessageBoxData;
|
||||
import org.lwjgl.system.MemoryStack;
|
||||
|
||||
/** Clipboard, links and message boxes through SDL3. */
|
||||
final class SdlShell implements PlatformShell {
|
||||
|
||||
private static final int CONTINUE = 1;
|
||||
private static final int QUIT = 2;
|
||||
|
||||
private final PlatformLog log;
|
||||
|
||||
SdlShell(PlatformLog log) {
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable String clipboardText() {
|
||||
String text = SDLClipboard.SDL_GetClipboardText();
|
||||
if (text == null) {
|
||||
log.warn("Couldn't read the clipboard: " + SdlWindow.sdlError());
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setClipboardText(String text) {
|
||||
boolean set = SDLClipboard.SDL_SetClipboardText(text);
|
||||
if (!set) {
|
||||
log.warn("Couldn't set the clipboard: " + SdlWindow.sdlError());
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void open(URI uri) {
|
||||
// Opening a browser or file manager can take a while on some desktops: never on the
|
||||
// render thread.
|
||||
Thread.ofVirtual().name("Incari-open-uri").start(() -> {
|
||||
if (!SDLMisc.SDL_OpenURL(uri.toString())) {
|
||||
log.warn("Couldn't open " + uri + ": " + SdlWindow.sdlError());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean showErrorDialog(String title, String message, boolean askToContinue) {
|
||||
if (!askToContinue) {
|
||||
boolean shown =
|
||||
SDLMessageBox.SDL_ShowSimpleMessageBox(SDLMessageBox.SDL_MESSAGEBOX_ERROR, title, message, 0L);
|
||||
if (!shown) {
|
||||
log.error("Couldn't show the error '" + message + "': " + SdlWindow.sdlError(), null);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
SDL_MessageBoxButtonData.Buffer buttons = SDL_MessageBoxButtonData.calloc(2, stack);
|
||||
buttons.get(0)
|
||||
.buttonID(CONTINUE)
|
||||
.flags(SDLMessageBox.SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT)
|
||||
.text(stack.UTF8("Yes"));
|
||||
buttons.get(1)
|
||||
.buttonID(QUIT)
|
||||
.flags(SDLMessageBox.SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT)
|
||||
.text(stack.UTF8("No"));
|
||||
SDL_MessageBoxData box = SDL_MessageBoxData.calloc(stack)
|
||||
.flags(SDLMessageBox.SDL_MESSAGEBOX_ERROR)
|
||||
.title(stack.UTF8(title))
|
||||
.message(stack.UTF8(message))
|
||||
.buttons(buttons);
|
||||
IntBuffer chosen = stack.callocInt(1);
|
||||
if (!SDLMessageBox.SDL_ShowMessageBox(box, chosen)) {
|
||||
log.error("Couldn't show the error '" + message + "': " + SdlWindow.sdlError(), null);
|
||||
return false;
|
||||
}
|
||||
return chosen.get(0) == CONTINUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
+464
@@ -0,0 +1,464 @@
|
||||
package incari.platform.desktop;
|
||||
|
||||
import static org.lwjgl.sdl.SDLError.SDL_GetError;
|
||||
|
||||
import incari.platform.api.NativeSurfaceFactory;
|
||||
import incari.platform.api.PlatformException;
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.window.DisplayInfo;
|
||||
import incari.platform.api.window.DisplayMode;
|
||||
import incari.platform.api.window.IconImage;
|
||||
import incari.platform.api.window.PlatformWindow;
|
||||
import incari.platform.api.window.SystemBehavior;
|
||||
import incari.platform.api.window.SystemCursor;
|
||||
import incari.platform.api.window.WindowSpec;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.FloatBuffer;
|
||||
import java.nio.IntBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.sdl.SDLHints;
|
||||
import org.lwjgl.sdl.SDLKeyboard;
|
||||
import org.lwjgl.sdl.SDLMouse;
|
||||
import org.lwjgl.sdl.SDLPixels;
|
||||
import org.lwjgl.sdl.SDLSurface;
|
||||
import org.lwjgl.sdl.SDLVideo;
|
||||
import org.lwjgl.sdl.SDL_DisplayMode;
|
||||
import org.lwjgl.sdl.SDL_Rect;
|
||||
import org.lwjgl.sdl.SDL_Surface;
|
||||
import org.lwjgl.system.MemoryStack;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
/** The game's window as an SDL3 window. */
|
||||
final class SdlWindow implements PlatformWindow {
|
||||
|
||||
/** Flags every game window gets, whichever graphics backend creates it. */
|
||||
static final long BASE_FLAGS = SDLVideo.SDL_WINDOW_RESIZABLE | SDLVideo.SDL_WINDOW_HIGH_PIXEL_DENSITY;
|
||||
|
||||
private final long handle;
|
||||
private final SdlDisplays displays;
|
||||
private final PlatformLog log;
|
||||
private final boolean borderlessWindowForFullscreen;
|
||||
private final Map<SystemCursor, Long> cursors = new EnumMap<>(SystemCursor.class);
|
||||
/**
|
||||
* Borderless fullscreen done as a plain window covering the display, one pixel wider so the
|
||||
* driver doesn't treat it as exclusive fullscreen and flip the display mode.
|
||||
*/
|
||||
private boolean inBorderlessWindow;
|
||||
|
||||
private boolean hasTextInputArea;
|
||||
private int textAreaX;
|
||||
private int textAreaY;
|
||||
private int textAreaWidth;
|
||||
private int textAreaHeight;
|
||||
|
||||
private SdlWindow(long handle, SdlDisplays displays, PlatformLog log) {
|
||||
this.handle = handle;
|
||||
this.displays = displays;
|
||||
this.log = log;
|
||||
// Windows' own fullscreen switch is slow and loses the window on alt-tab; a borderless
|
||||
// window covering the display behaves like the desktop expects there.
|
||||
this.borderlessWindowForFullscreen =
|
||||
System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows");
|
||||
}
|
||||
|
||||
static SdlWindow create(WindowSpec spec, NativeSurfaceFactory surface, SdlDisplays displays, PlatformLog log) {
|
||||
long handle = surface.create(spec.title(), spec.width(), spec.height(), BASE_FLAGS);
|
||||
if (handle == 0L) {
|
||||
throw new PlatformException("Couldn't create the window: " + sdlError());
|
||||
}
|
||||
SDLVideo.SDL_SetWindowMinimumSize(handle, WindowSpec.MIN_WIDTH, WindowSpec.MIN_HEIGHT);
|
||||
SdlWindow window = new SdlWindow(handle, displays, log);
|
||||
window.setMaximumSize(spec.maximumSize(), spec.maximumSize());
|
||||
log.info("Created window using SDL video driver: " + SDLVideo.SDL_GetCurrentVideoDriver());
|
||||
return window;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long nativeHandle() {
|
||||
return handle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int x() {
|
||||
return position()[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int y() {
|
||||
return position()[1];
|
||||
}
|
||||
|
||||
private int[] position() {
|
||||
int[] known = knownPosition();
|
||||
return known == null ? new int[] {0, 0} : known;
|
||||
}
|
||||
|
||||
/** The window's position on the desktop, or null where the system doesn't reveal it. */
|
||||
private int @Nullable [] knownPosition() {
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
IntBuffer left = stack.mallocInt(1);
|
||||
IntBuffer top = stack.mallocInt(1);
|
||||
return SDLVideo.SDL_GetWindowPosition(handle, left, top) ? new int[] {left.get(0), top.get(0)} : null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int width() {
|
||||
return size()[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int height() {
|
||||
return size()[1];
|
||||
}
|
||||
|
||||
private int[] size() {
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
IntBuffer w = stack.mallocInt(1);
|
||||
IntBuffer h = stack.mallocInt(1);
|
||||
if (!SDLVideo.SDL_GetWindowSize(handle, w, h)) {
|
||||
throw new PlatformException("Couldn't query the window size: " + sdlError());
|
||||
}
|
||||
return new int[] {w.get(0), h.get(0)};
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int framebufferWidth() {
|
||||
return Math.max(1, pixelSize()[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int framebufferHeight() {
|
||||
return Math.max(1, pixelSize()[1]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int unusedWidth() {
|
||||
return inBorderlessWindow ? 1 : 0;
|
||||
}
|
||||
|
||||
private int[] pixelSize() {
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
IntBuffer w = stack.mallocInt(1);
|
||||
IntBuffer h = stack.mallocInt(1);
|
||||
if (!SDLVideo.SDL_GetWindowSizeInPixels(handle, w, h)) {
|
||||
throw new PlatformException("Couldn't query the window's size in pixels: " + sdlError());
|
||||
}
|
||||
return new int[] {w.get(0), h.get(0)};
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public float pixelDensity() {
|
||||
float density = SDLVideo.SDL_GetWindowPixelDensity(handle);
|
||||
return density > 0.0F ? density : 1.0F;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int displayId() {
|
||||
return SDLVideo.SDL_GetDisplayForWindow(handle);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTitle(String title) {
|
||||
SDLVideo.SDL_SetWindowTitle(handle, title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setIcon(List<IconImage> sizes) {
|
||||
if (sizes.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<ByteBuffer> pixelBuffers = new ArrayList<>();
|
||||
List<SDL_Surface> surfaces = new ArrayList<>();
|
||||
try {
|
||||
for (IconImage icon : sizes) {
|
||||
ByteBuffer pixels = MemoryUtil.memAlloc(icon.rgba().length);
|
||||
pixelBuffers.add(pixels);
|
||||
pixels.put(icon.rgba()).flip();
|
||||
// ABGR8888 is a packed format: on a little-endian machine its bytes are R, G, B, A.
|
||||
SDL_Surface surface = SDLSurface.SDL_CreateSurfaceFrom(
|
||||
icon.width(), icon.height(), SDLPixels.SDL_PIXELFORMAT_ABGR8888, pixels, icon.width() * 4);
|
||||
if (surface == null) {
|
||||
log.warn("Couldn't make a " + icon.width() + "x" + icon.height() + " icon surface: " + sdlError());
|
||||
continue;
|
||||
}
|
||||
surfaces.add(surface);
|
||||
}
|
||||
if (surfaces.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
SDL_Surface primary = surfaces.getFirst();
|
||||
for (SDL_Surface alternate : surfaces.subList(1, surfaces.size())) {
|
||||
if (!SDLSurface.SDL_AddSurfaceAlternateImage(primary, alternate)) {
|
||||
log.warn("Couldn't add an alternate icon size: " + sdlError());
|
||||
}
|
||||
}
|
||||
if (!SDLVideo.SDL_SetWindowIcon(handle, primary)) {
|
||||
log.warn("Couldn't set the window icon: " + sdlError());
|
||||
}
|
||||
} finally {
|
||||
surfaces.forEach(SDLSurface::SDL_DestroySurface);
|
||||
pixelBuffers.forEach(MemoryUtil::memFree);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMaximumSize(int width, int height) {
|
||||
SDLVideo.SDL_SetWindowMaximumSize(handle, width, height);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setWindowed(int x, int y, int width, int height) {
|
||||
leaveBorderlessWindow();
|
||||
if (!SDLVideo.SDL_SetWindowFullscreen(handle, false)) {
|
||||
log.warn("Couldn't leave fullscreen: " + sdlError());
|
||||
return false;
|
||||
}
|
||||
boolean placed = place(x, y, width, height);
|
||||
finishModeChange();
|
||||
return placed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setFullscreen(@Nullable DisplayMode exclusiveMode) {
|
||||
boolean done;
|
||||
if (exclusiveMode != null) {
|
||||
leaveBorderlessWindow();
|
||||
done = enterExclusive(exclusiveMode);
|
||||
} else if (borderlessWindowForFullscreen) {
|
||||
done = enterBorderlessWindow();
|
||||
} else {
|
||||
leaveBorderlessWindow();
|
||||
done = enterDesktopFullscreen();
|
||||
}
|
||||
if (!done) {
|
||||
log.warn("Couldn't enter fullscreen: " + sdlError());
|
||||
}
|
||||
finishModeChange();
|
||||
return done;
|
||||
}
|
||||
|
||||
private boolean enterExclusive(DisplayMode wanted) {
|
||||
int display = displayId();
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
SDL_DisplayMode closest = SDL_DisplayMode.malloc(stack);
|
||||
if (display != 0
|
||||
&& SDLVideo.SDL_GetClosestFullscreenDisplayMode(
|
||||
display, wanted.width(), wanted.height(), wanted.refreshRate(), true, closest)) {
|
||||
return SDLVideo.SDL_SetWindowFullscreenMode(handle, closest)
|
||||
&& SDLVideo.SDL_SetWindowFullscreen(handle, true);
|
||||
}
|
||||
}
|
||||
log.warn("No display mode close to " + wanted.width() + "x" + wanted.height() + "@" + wanted.refreshRate()
|
||||
+ " for exclusive fullscreen; using borderless fullscreen instead");
|
||||
return enterDesktopFullscreen();
|
||||
}
|
||||
|
||||
/** SDL's own borderless fullscreen: fullscreen at the desktop's mode. */
|
||||
private boolean enterDesktopFullscreen() {
|
||||
return SDLVideo.SDL_SetWindowFullscreenMode(handle, null) && SDLVideo.SDL_SetWindowFullscreen(handle, true);
|
||||
}
|
||||
|
||||
private boolean enterBorderlessWindow() {
|
||||
DisplayInfo display = displays.get(displayId());
|
||||
if (display == null) {
|
||||
log.warn("Can't find the window's display for borderless fullscreen; using SDL's fullscreen instead");
|
||||
leaveBorderlessWindow();
|
||||
return enterDesktopFullscreen();
|
||||
}
|
||||
if (!SDLVideo.SDL_SetWindowFullscreenMode(handle, null) || !SDLVideo.SDL_SetWindowFullscreen(handle, false)) {
|
||||
return false;
|
||||
}
|
||||
if (SDLVideo.SDL_RestoreWindow(handle)) {
|
||||
SDLVideo.SDL_SyncWindow(handle);
|
||||
}
|
||||
inBorderlessWindow = true;
|
||||
if (!SDLVideo.SDL_SetWindowBordered(handle, false)) {
|
||||
log.warn("Couldn't remove the window border for borderless fullscreen: " + sdlError());
|
||||
}
|
||||
return place(display.x(), display.y(), display.width() + 1, display.height());
|
||||
}
|
||||
|
||||
private void leaveBorderlessWindow() {
|
||||
if (inBorderlessWindow) {
|
||||
inBorderlessWindow = false;
|
||||
if (!SDLVideo.SDL_SetWindowBordered(handle, true)) {
|
||||
log.warn("Couldn't restore the window border: " + sdlError());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean place(int x, int y, int width, int height) {
|
||||
if (!SDLVideo.SDL_SetWindowSize(handle, width, height)) {
|
||||
return false;
|
||||
}
|
||||
if (!SDLVideo.SDL_SetWindowPosition(handle, x, y)) {
|
||||
// Wayland and some window managers place windows themselves; that's fine.
|
||||
log.debug("The window manager declined to position the window: " + sdlError());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void finishModeChange() {
|
||||
if (!SDLVideo.SDL_SyncWindow(handle)) {
|
||||
log.debug("Window state didn't settle before the timeout: " + sdlError());
|
||||
}
|
||||
updateMouseGrab();
|
||||
}
|
||||
|
||||
/**
|
||||
* Confines the mouse to the window in exclusive fullscreen, where the display belongs to the
|
||||
* game; anywhere else the player must be able to leave the window.
|
||||
*/
|
||||
void updateMouseGrab() {
|
||||
if (!SDLVideo.SDL_SetWindowMouseGrab(handle, isExclusiveFullscreen())) {
|
||||
log.warn("Couldn't update the window's mouse grab: " + sdlError());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSystemBehavior(SystemBehavior behavior, boolean enabled) {
|
||||
// Both are macOS features; SDL ignores these hints elsewhere.
|
||||
String hint =
|
||||
switch (behavior) {
|
||||
case CTRL_CLICK_IS_RIGHT_CLICK -> "SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK";
|
||||
case MENU_BAR_IN_FULLSCREEN -> "SDL_VIDEO_MAC_FULLSCREEN_MENU_VISIBILITY";
|
||||
};
|
||||
SDLHints.SDL_SetHint(hint, enabled ? "1" : "0");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isFullscreen() {
|
||||
return inBorderlessWindow || (SDLVideo.SDL_GetWindowFlags(handle) & SDLVideo.SDL_WINDOW_FULLSCREEN) != 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isExclusiveFullscreen() {
|
||||
return !inBorderlessWindow && isFullscreen() && SDLVideo.SDL_GetWindowFullscreenMode(handle) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable DisplayMode currentDisplayMode() {
|
||||
SDL_DisplayMode mode = SDLVideo.SDL_GetWindowFullscreenMode(handle);
|
||||
if (mode == null) {
|
||||
int display = displayId();
|
||||
mode = display == 0 ? null : SDLVideo.SDL_GetCurrentDisplayMode(display);
|
||||
}
|
||||
return mode == null ? null : SdlDisplays.toDisplayMode(mode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRelativeMouseMode(boolean enabled) {
|
||||
if (!SDLMouse.SDL_SetWindowRelativeMouseMode(handle, enabled)) {
|
||||
log.warn("Couldn't " + (enabled ? "enable" : "disable") + " relative mouse mode: " + sdlError());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warpMouse(double x, double y) {
|
||||
SDLMouse.SDL_WarpMouseInWindow(handle, (float) x, (float) y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CursorPosition cursorPosition() {
|
||||
// Window position plus SDL's desktop-wide cursor position gives an answer even while the
|
||||
// cursor is outside the window. Without a window position (some Wayland compositors),
|
||||
// only the window-relative position is available.
|
||||
int[] origin = knownPosition();
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
FloatBuffer cursorX = stack.mallocFloat(1);
|
||||
FloatBuffer cursorY = stack.mallocFloat(1);
|
||||
if (origin == null) {
|
||||
SDLMouse.SDL_GetMouseState(cursorX, cursorY);
|
||||
return new CursorPosition(cursorX.get(0), cursorY.get(0));
|
||||
}
|
||||
SDLMouse.SDL_GetGlobalMouseState(cursorX, cursorY);
|
||||
return new CursorPosition(cursorX.get(0) - origin[0], cursorY.get(0) - origin[1]);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCursor(SystemCursor cursor) {
|
||||
long sdlCursor = cursors.computeIfAbsent(cursor, SdlWindow::createCursor);
|
||||
SDLMouse.SDL_SetCursor(sdlCursor != 0L ? sdlCursor : SDLMouse.SDL_GetDefaultCursor());
|
||||
}
|
||||
|
||||
private static long createCursor(SystemCursor cursor) {
|
||||
int shape =
|
||||
switch (cursor) {
|
||||
case DEFAULT, ARROW -> SDLMouse.SDL_SYSTEM_CURSOR_DEFAULT;
|
||||
case TEXT -> SDLMouse.SDL_SYSTEM_CURSOR_TEXT;
|
||||
case CROSSHAIR -> SDLMouse.SDL_SYSTEM_CURSOR_CROSSHAIR;
|
||||
case POINTING_HAND -> SDLMouse.SDL_SYSTEM_CURSOR_POINTER;
|
||||
case RESIZE_NS -> SDLMouse.SDL_SYSTEM_CURSOR_NS_RESIZE;
|
||||
case RESIZE_EW -> SDLMouse.SDL_SYSTEM_CURSOR_EW_RESIZE;
|
||||
case RESIZE_ALL -> SDLMouse.SDL_SYSTEM_CURSOR_MOVE;
|
||||
case NOT_ALLOWED -> SDLMouse.SDL_SYSTEM_CURSOR_NOT_ALLOWED;
|
||||
};
|
||||
return cursor == SystemCursor.DEFAULT
|
||||
? SDLMouse.SDL_GetDefaultCursor()
|
||||
: SDLMouse.SDL_CreateSystemCursor(shape);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startTextInput() {
|
||||
if (hasTextInputArea) {
|
||||
applyTextInputArea();
|
||||
}
|
||||
SDLKeyboard.SDL_StartTextInput(handle);
|
||||
SDLKeyboard.SDL_ClearComposition(handle);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopTextInput() {
|
||||
SDLKeyboard.SDL_StopTextInput(handle);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTextInputArea(int x, int y, int width, int height) {
|
||||
hasTextInputArea = true;
|
||||
textAreaX = x;
|
||||
textAreaY = y;
|
||||
textAreaWidth = width;
|
||||
textAreaHeight = height;
|
||||
applyTextInputArea();
|
||||
}
|
||||
|
||||
private void applyTextInputArea() {
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
SDL_Rect.Buffer area = SDL_Rect.malloc(1, stack);
|
||||
area.get(0).x(textAreaX).y(textAreaY).w(textAreaWidth).h(textAreaHeight);
|
||||
// -1: no cursor offset; the input method places its window at the area's edge.
|
||||
SDLKeyboard.SDL_SetTextInputArea(handle, area, -1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setQuitShortcutEnabled(boolean enabled) {
|
||||
SDLHints.SDL_SetHint("SDL_WINDOWS_CLOSE_ON_ALT_F4", enabled ? "1" : "0");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
for (Map.Entry<SystemCursor, Long> cursor : cursors.entrySet()) {
|
||||
// The default cursor belongs to SDL; only the ones created here are freed.
|
||||
if (cursor.getKey() != SystemCursor.DEFAULT && cursor.getValue() != 0L) {
|
||||
SDLMouse.SDL_DestroyCursor(cursor.getValue());
|
||||
}
|
||||
}
|
||||
cursors.clear();
|
||||
SDLVideo.SDL_DestroyWindow(handle);
|
||||
}
|
||||
|
||||
static String sdlError() {
|
||||
String error = SDL_GetError();
|
||||
return error == null || error.isEmpty() ? "no error reported" : error;
|
||||
}
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
package incari.platform.desktop.audio;
|
||||
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.audio.AudioDevice;
|
||||
import incari.platform.api.audio.AudioDeviceList;
|
||||
import incari.platform.api.audio.AudioException;
|
||||
import incari.platform.api.audio.PlatformAudio;
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.openal.ALC;
|
||||
import org.lwjgl.openal.ALC10;
|
||||
import org.lwjgl.openal.ALC11;
|
||||
import org.lwjgl.openal.ALUtil;
|
||||
import org.lwjgl.openal.SOFTSystemEventProc;
|
||||
import org.lwjgl.openal.SOFTSystemEvents;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
/**
|
||||
* {@link PlatformAudio} over OpenAL Soft, through LWJGL.
|
||||
*
|
||||
* <p>Nothing native is touched until the first call, so constructing this is free. LWJGL loads
|
||||
* OpenAL Soft when {@link ALC} is first used. {@link #close} undoes whatever was set up.
|
||||
*/
|
||||
public final class OpenAlAudio implements PlatformAudio, AutoCloseable {
|
||||
|
||||
/** The device events that change what {@link #devices} returns. */
|
||||
private static final int[] DEVICE_EVENTS = {
|
||||
SOFTSystemEvents.ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT,
|
||||
SOFTSystemEvents.ALC_EVENT_TYPE_DEVICE_ADDED_SOFT,
|
||||
SOFTSystemEvents.ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT,
|
||||
};
|
||||
|
||||
private final PlatformLog log;
|
||||
private final Object lock = new Object();
|
||||
|
||||
private @Nullable Boolean eventsSupported;
|
||||
|
||||
/**
|
||||
* Kept for as long as it's installed: OpenAL holds only its native address, so letting it be
|
||||
* collected would leave OpenAL calling freed memory.
|
||||
*/
|
||||
private @Nullable SOFTSystemEventProc eventCallback;
|
||||
|
||||
private volatile @Nullable Runnable deviceChangeListener;
|
||||
|
||||
/** The device opened last, closed with this if the game didn't close it first. */
|
||||
private @Nullable OpenAlDevice lastOpened;
|
||||
|
||||
private boolean closed;
|
||||
|
||||
public OpenAlAudio(PlatformLog log) {
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AudioDeviceList devices() {
|
||||
loadOpenAl();
|
||||
// Without ALC_ENUMERATE_ALL_EXT the only names on offer are the coarse ALC 1.0 ones,
|
||||
// which don't match what an opened device reports; better to list nothing.
|
||||
if (!ALC10.alcIsExtensionPresent(MemoryUtil.NULL, "ALC_ENUMERATE_ALL_EXT")) {
|
||||
return AudioDeviceList.EMPTY;
|
||||
}
|
||||
List<String> all = ALUtil.getStringList(MemoryUtil.NULL, ALC11.ALC_ALL_DEVICES_SPECIFIER);
|
||||
String defaultDevice = ALC10.alcGetString(MemoryUtil.NULL, ALC11.ALC_DEFAULT_ALL_DEVICES_SPECIFIER);
|
||||
return new AudioDeviceList(defaultDevice, all == null ? List.of() : all);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean reportsDeviceChanges() {
|
||||
synchronized (lock) {
|
||||
Boolean supported = eventsSupported;
|
||||
if (supported == null) {
|
||||
supported = querySystemEvents();
|
||||
eventsSupported = supported;
|
||||
}
|
||||
return supported;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDeviceChangeListener(@Nullable Runnable listener) {
|
||||
deviceChangeListener = listener;
|
||||
if (listener == null || !reportsDeviceChanges()) {
|
||||
return;
|
||||
}
|
||||
synchronized (lock) {
|
||||
if (eventCallback != null || closed) {
|
||||
return;
|
||||
}
|
||||
// Installed once and left installed: the callback reads the current listener, so
|
||||
// swapping listeners needs no native calls.
|
||||
SOFTSystemEventProc callback = SOFTSystemEventProc.create(this::onSystemEvent);
|
||||
if (!SOFTSystemEvents.alcEventControlSOFT(DEVICE_EVENTS, true)) {
|
||||
callback.free();
|
||||
log.warn("OpenAL refused to report device changes: "
|
||||
+ OpenAlSupport.alcErrorName(ALC10.alcGetError(MemoryUtil.NULL)));
|
||||
return;
|
||||
}
|
||||
SOFTSystemEvents.alcEventCallbackSOFT(callback, MemoryUtil.NULL);
|
||||
eventCallback = callback;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AudioDevice open(@Nullable String deviceName, boolean spatialize) {
|
||||
synchronized (lock) {
|
||||
if (closed) {
|
||||
throw new AudioException("The audio system was shut down");
|
||||
}
|
||||
}
|
||||
loadOpenAl();
|
||||
OpenAlDevice device = OpenAlDevice.open(log, deviceName, spatialize);
|
||||
synchronized (lock) {
|
||||
lastOpened = device;
|
||||
}
|
||||
return device;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops device-change reports and closes a device the game left open. Safe to call more than
|
||||
* once, and on an instance that never touched OpenAL (then it loads nothing).
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
synchronized (lock) {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
deviceChangeListener = null;
|
||||
SOFTSystemEventProc callback = eventCallback;
|
||||
if (callback != null) {
|
||||
SOFTSystemEvents.alcEventControlSOFT(DEVICE_EVENTS, false);
|
||||
SOFTSystemEvents.alcEventCallbackSOFT(null, MemoryUtil.NULL);
|
||||
callback.free();
|
||||
eventCallback = null;
|
||||
}
|
||||
OpenAlDevice device = lastOpened;
|
||||
if (device != null) {
|
||||
device.close();
|
||||
lastOpened = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether every device event the game needs can be reported for playback devices. */
|
||||
private boolean querySystemEvents() {
|
||||
loadOpenAl();
|
||||
if (!ALC10.alcIsExtensionPresent(MemoryUtil.NULL, "ALC_SOFT_system_events")) {
|
||||
return false;
|
||||
}
|
||||
for (int event : DEVICE_EVENTS) {
|
||||
int support = SOFTSystemEvents.alcEventIsSupportedSOFT(event, SOFTSystemEvents.ALC_PLAYBACK_DEVICE_SOFT);
|
||||
if (support != SOFTSystemEvents.ALC_EVENT_SUPPORTED_SOFT) {
|
||||
if (support == 0) {
|
||||
log.warn("Couldn't ask OpenAL about device event 0x" + Integer.toHexString(event) + ": "
|
||||
+ OpenAlSupport.alcErrorName(ALC10.alcGetError(MemoryUtil.NULL)));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs on OpenAL's own event thread. Must not call back into OpenAL or block: it only logs and
|
||||
* tells the listener, which in the game just raises a flag.
|
||||
*/
|
||||
@SuppressWarnings("UnusedVariable") // The callback's full native signature.
|
||||
private void onSystemEvent(
|
||||
int eventType, int deviceType, long device, int messageLength, long message, long userParam) {
|
||||
if (deviceType != SOFTSystemEvents.ALC_PLAYBACK_DEVICE_SOFT) {
|
||||
return; // Microphones coming and going don't change what the game can play to.
|
||||
}
|
||||
log.debug("Audio device event 0x" + Integer.toHexString(eventType) + ": "
|
||||
+ MemoryUtil.memUTF8(message, messageLength));
|
||||
Runnable listener = deviceChangeListener;
|
||||
if (listener != null) {
|
||||
listener.run();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads OpenAL Soft if nothing has yet. LWJGL does so in {@link ALC}'s static initializer, so
|
||||
* touching the class is enough.
|
||||
*/
|
||||
private static void loadOpenAl() {
|
||||
try {
|
||||
ALC.getFunctionProvider();
|
||||
} catch (RuntimeException | LinkageError e) {
|
||||
throw new AudioException("OpenAL couldn't be loaded", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package incari.platform.desktop.audio;
|
||||
|
||||
import incari.platform.api.audio.AudioBuffer;
|
||||
import incari.platform.api.audio.PcmFormat;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.lwjgl.openal.AL10;
|
||||
|
||||
/** An OpenAL buffer name and what was uploaded into it. */
|
||||
final class OpenAlBuffer implements AudioBuffer {
|
||||
|
||||
private final OpenAlDevice owner;
|
||||
private final int id;
|
||||
private final PcmFormat format;
|
||||
private final int size;
|
||||
private final AtomicBoolean open = new AtomicBoolean(true);
|
||||
|
||||
OpenAlBuffer(OpenAlDevice owner, int id, PcmFormat format, int size) {
|
||||
this.owner = owner;
|
||||
this.id = id;
|
||||
this.format = format;
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
int id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PcmFormat format() {
|
||||
return format;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int sizeInBytes() {
|
||||
return size;
|
||||
}
|
||||
|
||||
/** Safe to call twice, and after the device closed (its buffers went with it). */
|
||||
@Override
|
||||
public void close() {
|
||||
if (!open.compareAndSet(true, false)) {
|
||||
return;
|
||||
}
|
||||
owner.forget(this);
|
||||
if (owner.isReleased()) {
|
||||
return;
|
||||
}
|
||||
AL10.alDeleteBuffers(id);
|
||||
owner.logAlError("Couldn't delete an audio buffer");
|
||||
}
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
package incari.platform.desktop.audio;
|
||||
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.audio.AudioBuffer;
|
||||
import incari.platform.api.audio.AudioDevice;
|
||||
import incari.platform.api.audio.AudioException;
|
||||
import incari.platform.api.audio.AudioListener;
|
||||
import incari.platform.api.audio.AudioSource;
|
||||
import incari.platform.api.audio.PcmFormat;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.openal.AL;
|
||||
import org.lwjgl.openal.AL10;
|
||||
import org.lwjgl.openal.ALC;
|
||||
import org.lwjgl.openal.ALC10;
|
||||
import org.lwjgl.openal.ALC11;
|
||||
import org.lwjgl.openal.ALCCapabilities;
|
||||
import org.lwjgl.openal.ALCapabilities;
|
||||
import org.lwjgl.openal.EXTDisconnect;
|
||||
import org.lwjgl.openal.EXTSourceDistanceModel;
|
||||
import org.lwjgl.openal.SOFTHRTF;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
/**
|
||||
* An OpenAL device with its one context, made current for the whole process. The game keeps a
|
||||
* single device open at a time, so a process-wide context needs no switching.
|
||||
*/
|
||||
final class OpenAlDevice implements AudioDevice {
|
||||
|
||||
private final PlatformLog log;
|
||||
private final long device;
|
||||
private final long context;
|
||||
private final String name;
|
||||
private final boolean reportsDisconnect;
|
||||
private final int maxSources;
|
||||
private final OpenAlListener listener = new OpenAlListener();
|
||||
|
||||
// Buffers are closed from whichever thread drops the game's sound cache, so these are
|
||||
// concurrent sets rather than confined to the sound thread.
|
||||
private final Set<OpenAlSource> sources = ConcurrentHashMap.newKeySet();
|
||||
private final Set<OpenAlBuffer> buffers = ConcurrentHashMap.newKeySet();
|
||||
private volatile boolean closed;
|
||||
/** Set once the native device is gone, after {@link #closed}: nothing may call OpenAL for it then. */
|
||||
private volatile boolean released;
|
||||
|
||||
private OpenAlDevice(
|
||||
PlatformLog log, long device, long context, String name, boolean reportsDisconnect, int maxSources) {
|
||||
this.log = log;
|
||||
this.device = device;
|
||||
this.context = context;
|
||||
this.name = name;
|
||||
this.reportsDisconnect = reportsDisconnect;
|
||||
this.maxSources = maxSources;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens {@code deviceName} (null for the default), creates its context and checks it can do
|
||||
* what the game needs: ALC 1.1, per-source distance models and the linear distance model.
|
||||
*/
|
||||
static OpenAlDevice open(PlatformLog log, @Nullable String deviceName, boolean spatialize) {
|
||||
String shownName = deviceName == null ? "the default audio device" : "audio device '" + deviceName + "'";
|
||||
long device = ALC10.alcOpenDevice(deviceName);
|
||||
if (device == MemoryUtil.NULL) {
|
||||
throw new AudioException("Couldn't open " + shownName + ": "
|
||||
+ OpenAlSupport.alcErrorName(ALC10.alcGetError(MemoryUtil.NULL)));
|
||||
}
|
||||
long context = MemoryUtil.NULL;
|
||||
try {
|
||||
ALCCapabilities alc = ALC.createCapabilities(device);
|
||||
if (!alc.OpenALC11) {
|
||||
throw new AudioException(shownName + " doesn't support OpenAL 1.1");
|
||||
}
|
||||
|
||||
int hrtfCount = alc.ALC_SOFT_HRTF ? ALC10.alcGetInteger(device, SOFTHRTF.ALC_NUM_HRTF_SPECIFIERS_SOFT) : 0;
|
||||
ALC10.alcGetError(device); // A device that can't count its HRTFs has none; don't fail on it.
|
||||
int[] attributes = OpenAlSupport.contextAttributes(hrtfCount, spatialize, alc.ALC_SOFT_output_limiter);
|
||||
context = ALC10.alcCreateContext(device, attributes);
|
||||
int error = ALC10.alcGetError(device);
|
||||
if (context == MemoryUtil.NULL || error != ALC10.ALC_NO_ERROR) {
|
||||
throw new AudioException(
|
||||
"Couldn't create an OpenAL context on " + shownName + ": " + OpenAlSupport.alcErrorName(error));
|
||||
}
|
||||
if (!ALC10.alcMakeContextCurrent(context)) {
|
||||
throw new AudioException("Couldn't make the OpenAL context current on " + shownName);
|
||||
}
|
||||
|
||||
ALCapabilities al = AL.createCapabilities(alc);
|
||||
if (!al.AL_EXT_source_distance_model) {
|
||||
throw new AudioException(shownName + " doesn't support AL_EXT_source_distance_model");
|
||||
}
|
||||
if (!al.AL_EXT_LINEAR_DISTANCE) {
|
||||
throw new AudioException(shownName + " doesn't support AL_EXT_LINEAR_DISTANCE");
|
||||
}
|
||||
// Sources carry their own distance model: some sounds fade with distance, music doesn't.
|
||||
AL10.alEnable(EXTSourceDistanceModel.AL_SOURCE_DISTANCE_MODEL);
|
||||
int alError = AL10.alGetError();
|
||||
if (alError != AL10.AL_NO_ERROR) {
|
||||
throw new AudioException("Couldn't enable per-source distance models on " + shownName + ": "
|
||||
+ OpenAlSupport.alErrorName(alError));
|
||||
}
|
||||
|
||||
String name = queryName(device);
|
||||
int maxSources = OpenAlSupport.monoSourceCount(queryAttributes(device));
|
||||
boolean reportsDisconnect = ALC10.alcIsExtensionPresent(device, "ALC_EXT_disconnect");
|
||||
log.info("Opened audio device " + name + " (" + maxSources + " sources, HRTF "
|
||||
+ hrtfState(alc, device, hrtfCount) + ")");
|
||||
return new OpenAlDevice(log, device, context, name, reportsDisconnect, maxSources);
|
||||
} catch (RuntimeException e) {
|
||||
if (context != MemoryUtil.NULL) {
|
||||
ALC10.alcMakeContextCurrent(MemoryUtil.NULL);
|
||||
ALC10.alcDestroyContext(context);
|
||||
}
|
||||
ALC10.alcCloseDevice(device);
|
||||
throw e instanceof AudioException audio ? audio : new AudioException("Couldn't set up " + shownName, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** The full name, which is what device enumeration lists, falling back to the short one. */
|
||||
private static String queryName(long device) {
|
||||
String name = ALC10.alcGetString(device, ALC11.ALC_ALL_DEVICES_SPECIFIER);
|
||||
if (name == null) {
|
||||
name = ALC10.alcGetString(device, ALC10.ALC_DEVICE_SPECIFIER);
|
||||
}
|
||||
return name != null ? name : "Unknown (0x" + Long.toHexString(device) + ")";
|
||||
}
|
||||
|
||||
/** The attributes the context was actually created with, as key/value pairs. */
|
||||
private static int[] queryAttributes(long device) {
|
||||
int size = ALC10.alcGetInteger(device, ALC10.ALC_ATTRIBUTES_SIZE);
|
||||
if (ALC10.alcGetError(device) != ALC10.ALC_NO_ERROR || size <= 0) {
|
||||
return new int[0];
|
||||
}
|
||||
int[] attributes = new int[size];
|
||||
ALC10.alcGetIntegerv(device, ALC10.ALC_ALL_ATTRIBUTES, attributes);
|
||||
return ALC10.alcGetError(device) == ALC10.ALC_NO_ERROR ? attributes : new int[0];
|
||||
}
|
||||
|
||||
private static String hrtfState(ALCCapabilities alc, long device, int hrtfCount) {
|
||||
if (!alc.ALC_SOFT_HRTF || hrtfCount <= 0) {
|
||||
return "unavailable";
|
||||
}
|
||||
int status = ALC10.alcGetInteger(device, SOFTHRTF.ALC_HRTF_STATUS_SOFT);
|
||||
return switch (status) {
|
||||
case SOFTHRTF.ALC_HRTF_ENABLED_SOFT -> "on";
|
||||
case SOFTHRTF.ALC_HRTF_HEADPHONES_DETECTED_SOFT -> "on (headphones detected)";
|
||||
case SOFTHRTF.ALC_HRTF_REQUIRED_SOFT -> "on (required by the device)";
|
||||
case SOFTHRTF.ALC_HRTF_DENIED_SOFT -> "off (denied by configuration)";
|
||||
case SOFTHRTF.ALC_HRTF_UNSUPPORTED_FORMAT_SOFT -> "off (unsupported output format)";
|
||||
default -> "off";
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDisconnected() {
|
||||
if (closed) {
|
||||
return true;
|
||||
}
|
||||
return reportsDisconnect && ALC10.alcGetInteger(device, EXTDisconnect.ALC_CONNECTED) == ALC10.ALC_FALSE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int maxSources() {
|
||||
return maxSources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AudioListener listener() {
|
||||
return listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable AudioSource createSource() {
|
||||
checkOpen();
|
||||
if (sources.size() >= maxSources) {
|
||||
return null;
|
||||
}
|
||||
AL10.alGetError(); // Clear anything stale so the check below is about this call.
|
||||
int id = AL10.alGenSources();
|
||||
int error = AL10.alGetError();
|
||||
if (error != AL10.AL_NO_ERROR) {
|
||||
log.error("Couldn't create an audio source: " + OpenAlSupport.alErrorName(error), null);
|
||||
return null;
|
||||
}
|
||||
OpenAlSource source = new OpenAlSource(this, id);
|
||||
sources.add(source);
|
||||
return source;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AudioBuffer createBuffer(ByteBuffer samples, PcmFormat format) {
|
||||
checkOpen();
|
||||
int alFormat = OpenAlSupport.alFormat(format);
|
||||
int size = samples.remaining();
|
||||
AL10.alGetError();
|
||||
int id = AL10.alGenBuffers();
|
||||
int error = AL10.alGetError();
|
||||
if (error != AL10.AL_NO_ERROR) {
|
||||
throw new AudioException("Couldn't create an audio buffer: " + OpenAlSupport.alErrorName(error));
|
||||
}
|
||||
// OpenAL copies the samples during the call, so a heap buffer only needs a short-lived
|
||||
// native copy. The game's decoder already produces direct buffers.
|
||||
if (samples.isDirect()) {
|
||||
AL10.alBufferData(id, alFormat, samples, format.sampleRate());
|
||||
} else {
|
||||
ByteBuffer copy = MemoryUtil.memAlloc(size);
|
||||
try {
|
||||
copy.put(samples.duplicate()).flip();
|
||||
AL10.alBufferData(id, alFormat, copy, format.sampleRate());
|
||||
} finally {
|
||||
MemoryUtil.memFree(copy);
|
||||
}
|
||||
}
|
||||
error = AL10.alGetError();
|
||||
if (error != AL10.AL_NO_ERROR) {
|
||||
AL10.alDeleteBuffers(id);
|
||||
throw new AudioException(
|
||||
"Couldn't upload " + size + " bytes of " + format + ": " + OpenAlSupport.alErrorName(error));
|
||||
}
|
||||
OpenAlBuffer buffer = new OpenAlBuffer(this, id, format, size);
|
||||
buffers.add(buffer);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
// Sources first: a buffer can't be deleted while a source still holds it.
|
||||
for (OpenAlSource source : new ArrayList<>(sources)) {
|
||||
source.close();
|
||||
}
|
||||
for (OpenAlBuffer buffer : new ArrayList<>(buffers)) {
|
||||
buffer.close();
|
||||
}
|
||||
if (ALC10.alcGetCurrentContext() == context) {
|
||||
ALC10.alcMakeContextCurrent(MemoryUtil.NULL);
|
||||
}
|
||||
ALC10.alcDestroyContext(context);
|
||||
ALC10.alcCloseDevice(device);
|
||||
released = true;
|
||||
}
|
||||
|
||||
boolean isReleased() {
|
||||
return released;
|
||||
}
|
||||
|
||||
PlatformLog log() {
|
||||
return log;
|
||||
}
|
||||
|
||||
void forget(OpenAlSource source) {
|
||||
sources.remove(source);
|
||||
}
|
||||
|
||||
void forget(OpenAlBuffer buffer) {
|
||||
buffers.remove(buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs an AL error left by the calls just made, if any. For calls whose failure the game
|
||||
* can't act on anyway (it never checks a stop or a delete).
|
||||
*/
|
||||
void logAlError(String what) {
|
||||
int error = AL10.alGetError();
|
||||
if (error != AL10.AL_NO_ERROR) {
|
||||
log.error(what + ": " + OpenAlSupport.alErrorName(error), null);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkOpen() {
|
||||
if (closed) {
|
||||
throw new AudioException("Audio device " + name + " is closed");
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package incari.platform.desktop.audio;
|
||||
|
||||
import incari.platform.api.audio.AudioListener;
|
||||
import org.lwjgl.openal.AL10;
|
||||
|
||||
/** OpenAL's listener, which belongs to the current context: one per device here. */
|
||||
final class OpenAlListener implements AudioListener {
|
||||
|
||||
/** Reused: the listener moves every frame, and this is the sound thread's hot path. */
|
||||
private final float[] orientation = new float[6];
|
||||
|
||||
@Override
|
||||
public void setPosition(double x, double y, double z) {
|
||||
AL10.alListener3f(AL10.AL_POSITION, (float) x, (float) y, (float) z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOrientation(double forwardX, double forwardY, double forwardZ, double upX, double upY, double upZ) {
|
||||
orientation[0] = (float) forwardX;
|
||||
orientation[1] = (float) forwardY;
|
||||
orientation[2] = (float) forwardZ;
|
||||
orientation[3] = (float) upX;
|
||||
orientation[4] = (float) upY;
|
||||
orientation[5] = (float) upZ;
|
||||
AL10.alListenerfv(AL10.AL_ORIENTATION, orientation);
|
||||
}
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
package incari.platform.desktop.audio;
|
||||
|
||||
import incari.platform.api.audio.AudioBuffer;
|
||||
import incari.platform.api.audio.AudioException;
|
||||
import incari.platform.api.audio.AudioSource;
|
||||
import java.util.ArrayDeque;
|
||||
import org.lwjgl.openal.AL10;
|
||||
import org.lwjgl.openal.EXTLinearDistance;
|
||||
|
||||
/**
|
||||
* An OpenAL source. Confined to the game's sound thread, like everything the game does with a
|
||||
* source.
|
||||
*/
|
||||
final class OpenAlSource implements AudioSource {
|
||||
|
||||
private final OpenAlDevice owner;
|
||||
private final int id;
|
||||
|
||||
/**
|
||||
* The buffers queued on the source, oldest first. OpenAL finishes and unqueues them in queue
|
||||
* order, so the head is always the next one {@link #releaseProcessedBuffers} gets back.
|
||||
*/
|
||||
private final ArrayDeque<OpenAlBuffer> queued = new ArrayDeque<>();
|
||||
|
||||
private boolean open = true;
|
||||
|
||||
OpenAlSource(OpenAlDevice owner, int id) {
|
||||
this.owner = owner;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void play() {
|
||||
if (open) {
|
||||
AL10.alSourcePlay(id);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pause() {
|
||||
if (open) {
|
||||
AL10.alSourcePause(id);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
if (open) {
|
||||
AL10.alSourceStop(id);
|
||||
owner.logAlError("Couldn't stop an audio source");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public State state() {
|
||||
if (!open) {
|
||||
return State.STOPPED;
|
||||
}
|
||||
return switch (AL10.alGetSourcei(id, AL10.AL_SOURCE_STATE)) {
|
||||
case AL10.AL_INITIAL -> State.INITIAL;
|
||||
case AL10.AL_PLAYING -> State.PLAYING;
|
||||
case AL10.AL_PAUSED -> State.PAUSED;
|
||||
default -> State.STOPPED;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPosition(double x, double y, double z) {
|
||||
AL10.alSource3f(id, AL10.AL_POSITION, (float) x, (float) y, (float) z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPitch(float pitch) {
|
||||
AL10.alSourcef(id, AL10.AL_PITCH, pitch);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLooping(boolean looping) {
|
||||
AL10.alSourcei(id, AL10.AL_LOOPING, looping ? AL10.AL_TRUE : AL10.AL_FALSE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setGain(float gain) {
|
||||
AL10.alSourcef(id, AL10.AL_GAIN, gain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRelative(boolean relative) {
|
||||
AL10.alSourcei(id, AL10.AL_SOURCE_RELATIVE, relative ? AL10.AL_TRUE : AL10.AL_FALSE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disableAttenuation() {
|
||||
// Per-source model (AL_EXT_source_distance_model, enabled when the device opened).
|
||||
AL10.alSourcei(id, AL10.AL_DISTANCE_MODEL, AL10.AL_NONE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLinearAttenuation(float maxDistance) {
|
||||
// Unclamped linear model with a reference distance of 0 and a rolloff of 1: gain falls in
|
||||
// a straight line from 1 at the source to 0 at maxDistance, and stays 0 beyond it.
|
||||
AL10.alSourcei(id, AL10.AL_DISTANCE_MODEL, EXTLinearDistance.AL_LINEAR_DISTANCE);
|
||||
AL10.alSourcef(id, AL10.AL_MAX_DISTANCE, maxDistance);
|
||||
AL10.alSourcef(id, AL10.AL_ROLLOFF_FACTOR, 1.0F);
|
||||
AL10.alSourcef(id, AL10.AL_REFERENCE_DISTANCE, 0.0F);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBuffer(AudioBuffer buffer) {
|
||||
AL10.alSourcei(id, AL10.AL_BUFFER, ours(buffer).id());
|
||||
owner.logAlError("Couldn't attach an audio buffer");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void queue(AudioBuffer buffer) {
|
||||
OpenAlBuffer alBuffer = ours(buffer);
|
||||
AL10.alSourceQueueBuffers(id, alBuffer.id());
|
||||
int error = AL10.alGetError();
|
||||
if (error != AL10.AL_NO_ERROR) {
|
||||
// Not queued, so nobody else will close it; the stream just skips this chunk.
|
||||
alBuffer.close();
|
||||
owner.log().error("Couldn't queue an audio buffer: " + OpenAlSupport.alErrorName(error), null);
|
||||
return;
|
||||
}
|
||||
queued.addLast(alBuffer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int releaseProcessedBuffers() {
|
||||
if (!open || queued.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
int processed = AL10.alGetSourcei(id, AL10.AL_BUFFERS_PROCESSED);
|
||||
if (processed <= 0) {
|
||||
return 0;
|
||||
}
|
||||
int[] ids = new int[processed];
|
||||
AL10.alSourceUnqueueBuffers(id, ids);
|
||||
int error = AL10.alGetError();
|
||||
if (error != AL10.AL_NO_ERROR) {
|
||||
// Nothing was unqueued. Report none, so the caller doesn't queue more on top.
|
||||
owner.log().error("Couldn't unqueue audio buffers: " + OpenAlSupport.alErrorName(error), null);
|
||||
return 0;
|
||||
}
|
||||
for (int i = 0; i < processed && !queued.isEmpty(); i++) {
|
||||
queued.removeFirst().close();
|
||||
}
|
||||
return processed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!open) {
|
||||
return;
|
||||
}
|
||||
open = false;
|
||||
owner.forget(this);
|
||||
if (owner.isReleased()) {
|
||||
return;
|
||||
}
|
||||
AL10.alSourceStop(id);
|
||||
// Detaching every buffer (static or queued) is allowed once stopped, and lets them be deleted.
|
||||
AL10.alSourcei(id, AL10.AL_BUFFER, 0);
|
||||
AL10.alDeleteSources(id);
|
||||
owner.logAlError("Couldn't delete an audio source");
|
||||
while (!queued.isEmpty()) {
|
||||
queued.removeFirst().close();
|
||||
}
|
||||
}
|
||||
|
||||
private OpenAlBuffer ours(AudioBuffer buffer) {
|
||||
if (buffer instanceof OpenAlBuffer alBuffer) {
|
||||
return alBuffer;
|
||||
}
|
||||
throw new AudioException("Not an OpenAL buffer: " + buffer);
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package incari.platform.desktop.audio;
|
||||
|
||||
import incari.platform.api.audio.AudioException;
|
||||
import incari.platform.api.audio.PcmFormat;
|
||||
import java.util.Arrays;
|
||||
import org.lwjgl.openal.AL10;
|
||||
import org.lwjgl.openal.ALC10;
|
||||
import org.lwjgl.openal.ALC11;
|
||||
import org.lwjgl.openal.SOFTHRTF;
|
||||
import org.lwjgl.openal.SOFTOutputLimiter;
|
||||
|
||||
/**
|
||||
* The decisions around OpenAL calls that don't need a device: which format enum to upload with,
|
||||
* which context attributes to ask for, what the device's attributes say.
|
||||
*
|
||||
* <p>Only LWJGL's {@code static final int} constants appear here, and javac inlines those, so
|
||||
* this class loads without LWJGL on the class path. That keeps it unit-testable (LWJGL is
|
||||
* compile-only in this module).
|
||||
*/
|
||||
final class OpenAlSupport {
|
||||
|
||||
/** How many sources to assume when the device doesn't say (OpenAL's minimum guarantee is lower). */
|
||||
static final int FALLBACK_SOURCE_COUNT = 30;
|
||||
|
||||
private OpenAlSupport() {}
|
||||
|
||||
/** The {@code AL_FORMAT_*} enum for samples in {@code format}. */
|
||||
static int alFormat(PcmFormat format) {
|
||||
boolean mono = format.channels() == 1;
|
||||
return switch (format.bitsPerSample()) {
|
||||
case 8 -> mono ? AL10.AL_FORMAT_MONO8 : AL10.AL_FORMAT_STEREO8;
|
||||
case 16 -> mono ? AL10.AL_FORMAT_MONO16 : AL10.AL_FORMAT_STEREO16;
|
||||
// PcmFormat's constructor already rejects anything else.
|
||||
default -> throw new AudioException("No OpenAL format for " + format);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The attribute list for {@code alcCreateContext}: key/value pairs ending in a 0.
|
||||
*
|
||||
* @param hrtfCount how many HRTF data sets the device offers; HRTF is only requested (either
|
||||
* way) when there is at least one, so a device without HRTF isn't asked about it
|
||||
* @param spatialize whether the player wants HRTF on
|
||||
* @param limiterSupported whether ALC_SOFT_output_limiter is present. The limiter keeps many
|
||||
* loud sources from clipping, which the game relies on: it never mixes gain down itself.
|
||||
*/
|
||||
static int[] contextAttributes(int hrtfCount, boolean spatialize, boolean limiterSupported) {
|
||||
int[] attributes = new int[7];
|
||||
int next = 0;
|
||||
if (hrtfCount > 0) {
|
||||
attributes[next++] = SOFTHRTF.ALC_HRTF_SOFT;
|
||||
attributes[next++] = spatialize ? ALC10.ALC_TRUE : ALC10.ALC_FALSE;
|
||||
// The first HRTF the device lists: OpenAL Soft orders them by preference.
|
||||
attributes[next++] = SOFTHRTF.ALC_HRTF_ID_SOFT;
|
||||
attributes[next++] = 0;
|
||||
}
|
||||
if (limiterSupported) {
|
||||
attributes[next++] = SOFTOutputLimiter.ALC_OUTPUT_LIMITER_SOFT;
|
||||
attributes[next++] = ALC10.ALC_TRUE;
|
||||
}
|
||||
attributes[next++] = 0;
|
||||
return Arrays.copyOf(attributes, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* How many mono sources the context was given, from an {@code ALC_ALL_ATTRIBUTES} list
|
||||
* (key/value pairs, ending at a 0 key or the array's end), or {@link #FALLBACK_SOURCE_COUNT}
|
||||
* if the list doesn't say. Mono sources are the positional ones, which is what the game plays.
|
||||
*/
|
||||
static int monoSourceCount(int[] attributes) {
|
||||
for (int i = 0; i + 1 < attributes.length; i += 2) {
|
||||
int key = attributes[i];
|
||||
if (key == 0) {
|
||||
break;
|
||||
}
|
||||
if (key == ALC11.ALC_MONO_SOURCES && attributes[i + 1] > 0) {
|
||||
return attributes[i + 1];
|
||||
}
|
||||
}
|
||||
return FALLBACK_SOURCE_COUNT;
|
||||
}
|
||||
|
||||
/** A readable name for an ALC error code, for exception messages. */
|
||||
static String alcErrorName(int error) {
|
||||
return switch (error) {
|
||||
case ALC10.ALC_INVALID_DEVICE -> "invalid device";
|
||||
case ALC10.ALC_INVALID_CONTEXT -> "invalid context";
|
||||
case ALC10.ALC_INVALID_ENUM -> "invalid enum";
|
||||
case ALC10.ALC_INVALID_VALUE -> "invalid value";
|
||||
case ALC10.ALC_OUT_OF_MEMORY -> "out of memory";
|
||||
default -> "error 0x" + Integer.toHexString(error);
|
||||
};
|
||||
}
|
||||
|
||||
/** A readable name for an AL error code, for log messages. */
|
||||
static String alErrorName(int error) {
|
||||
return switch (error) {
|
||||
case AL10.AL_INVALID_NAME -> "invalid name";
|
||||
case AL10.AL_INVALID_ENUM -> "invalid enum";
|
||||
case AL10.AL_INVALID_VALUE -> "invalid value";
|
||||
case AL10.AL_INVALID_OPERATION -> "invalid operation";
|
||||
case AL10.AL_OUT_OF_MEMORY -> "out of memory";
|
||||
default -> "error 0x" + Integer.toHexString(error);
|
||||
};
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Sound output over OpenAL (LWJGL's OpenAL Soft build). One process-wide context: OpenAL's
|
||||
* current context is global, and the game only ever has one device open.
|
||||
*/
|
||||
@NullMarked
|
||||
package incari.platform.desktop.audio;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package incari.platform.desktop.net;
|
||||
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.net.NetConnection;
|
||||
import incari.platform.api.net.PlatformNetwork;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/** Server connections as plain TCP sockets, or WebSockets and HTTP GETs through the JDK's HTTP client. */
|
||||
public final class DesktopNetwork implements PlatformNetwork {
|
||||
|
||||
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(30);
|
||||
private static final Duration FETCH_TIMEOUT = Duration.ofSeconds(30);
|
||||
|
||||
private final PlatformLog log;
|
||||
/** Shared by every WebSocket and fetch: it owns the selector thread and a connection pool. */
|
||||
private volatile @Nullable HttpClient http;
|
||||
|
||||
public DesktopNetwork(PlatformLog log) {
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NetConnection connect(String host, int port, NetConnection.Listener listener) {
|
||||
SocketConnection connection = new SocketConnection(host, port, listener, log);
|
||||
connection.start();
|
||||
return connection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NetConnection openWebSocket(String url, NetConnection.Listener listener) {
|
||||
WebSocketConnection connection = new WebSocketConnection(url, listener, log);
|
||||
connection.start(httpClient());
|
||||
return connection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] fetch(String url, int maxBytes) throws IOException {
|
||||
HttpRequest request;
|
||||
try {
|
||||
request = HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(FETCH_TIMEOUT)
|
||||
.GET()
|
||||
.build();
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IOException("Can't fetch " + url + ": " + e.getMessage(), e);
|
||||
}
|
||||
HttpResponse<InputStream> response;
|
||||
try {
|
||||
response = httpClient().send(request, HttpResponse.BodyHandlers.ofInputStream());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted fetching " + url, e);
|
||||
}
|
||||
try (InputStream body = response.body()) {
|
||||
if (response.statusCode() / 100 != 2) {
|
||||
throw new IOException("Couldn't fetch " + url + ": HTTP " + response.statusCode());
|
||||
}
|
||||
long length = response.headers().firstValueAsLong("Content-Length").orElse(-1);
|
||||
if (length > maxBytes) {
|
||||
throw new IOException(
|
||||
"Couldn't fetch " + url + ": the file is " + length + " bytes, over the limit of " + maxBytes);
|
||||
}
|
||||
// One byte past the limit is enough to know the body is too big.
|
||||
byte[] bytes = body.readNBytes(maxBytes + 1);
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new IOException(
|
||||
"Couldn't fetch " + url + ": the file is over the limit of " + maxBytes + " bytes");
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
private HttpClient httpClient() {
|
||||
HttpClient client = http;
|
||||
if (client == null) {
|
||||
synchronized (this) {
|
||||
client = http;
|
||||
if (client == null) {
|
||||
client = HttpClient.newBuilder()
|
||||
.connectTimeout(CONNECT_TIMEOUT)
|
||||
.followRedirects(HttpClient.Redirect.NEVER)
|
||||
.build();
|
||||
http = client;
|
||||
}
|
||||
}
|
||||
}
|
||||
return client;
|
||||
}
|
||||
}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
package incari.platform.desktop.net;
|
||||
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.net.NetConnection;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.StandardSocketOptions;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Queue;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* One TCP connection. A virtual thread connects and then reads; writes happen on the caller's
|
||||
* thread under a lock, so {@link #send} never waits for the network to become readable.
|
||||
*/
|
||||
final class SocketConnection implements NetConnection {
|
||||
|
||||
private static final int CONNECT_TIMEOUT_MS = 30_000;
|
||||
private static final int READ_BUFFER_SIZE = 64 * 1024;
|
||||
|
||||
private final String host;
|
||||
private final int port;
|
||||
private final NetConnection.Listener listener;
|
||||
private final PlatformLog log;
|
||||
private final Object lock = new Object();
|
||||
/** Sends made before the connection opened, written in order once it does. */
|
||||
private final Queue<ByteBuffer> pending = new ArrayDeque<>();
|
||||
|
||||
private @Nullable SocketChannel channel;
|
||||
private boolean open;
|
||||
private boolean closed;
|
||||
/** Set by the connecting thread once resolved; read from any thread. */
|
||||
private volatile String remote;
|
||||
|
||||
SocketConnection(String host, int port, NetConnection.Listener listener, PlatformLog log) {
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.listener = listener;
|
||||
this.log = log;
|
||||
this.remote = host + ":" + port;
|
||||
}
|
||||
|
||||
void start() {
|
||||
Thread.ofVirtual().name("Incari-connection-" + remote).start(this::run);
|
||||
}
|
||||
|
||||
private void run() {
|
||||
SocketChannel socket;
|
||||
try {
|
||||
socket = SocketChannel.open();
|
||||
socket.setOption(StandardSocketOptions.TCP_NODELAY, true);
|
||||
InetSocketAddress address = new InetSocketAddress(host, port);
|
||||
socket.socket().connect(address, CONNECT_TIMEOUT_MS);
|
||||
remote = String.valueOf(socket.getRemoteAddress());
|
||||
} catch (IOException | RuntimeException e) {
|
||||
finish(e);
|
||||
return;
|
||||
}
|
||||
IOException flushFailure = null;
|
||||
synchronized (lock) {
|
||||
if (closed) {
|
||||
closeQuietly(socket);
|
||||
return;
|
||||
}
|
||||
channel = socket;
|
||||
try {
|
||||
while (!pending.isEmpty()) {
|
||||
writeFully(socket, pending.remove());
|
||||
}
|
||||
open = true;
|
||||
} catch (IOException e) {
|
||||
closed = true;
|
||||
closeQuietly(socket);
|
||||
flushFailure = e;
|
||||
}
|
||||
}
|
||||
if (flushFailure != null) {
|
||||
finishOutsideLock(flushFailure);
|
||||
return;
|
||||
}
|
||||
listener.connected();
|
||||
readLoop(socket);
|
||||
}
|
||||
|
||||
private void readLoop(SocketChannel socket) {
|
||||
try {
|
||||
while (true) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(READ_BUFFER_SIZE);
|
||||
int read = socket.read(buffer);
|
||||
if (read < 0) {
|
||||
finish(null);
|
||||
return;
|
||||
}
|
||||
if (read > 0) {
|
||||
buffer.flip();
|
||||
listener.received(buffer);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
finish(isClosed() ? null : e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(ByteBuffer data) {
|
||||
synchronized (lock) {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
SocketChannel socket = channel;
|
||||
if (socket == null) {
|
||||
pending.add(data);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
writeFully(socket, data);
|
||||
} catch (IOException e) {
|
||||
log.debug("Write to " + remote + " failed: " + e);
|
||||
closed = true;
|
||||
open = false;
|
||||
closeQuietly(socket);
|
||||
// The read loop sees the closed socket and reports it to the listener.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeFully(SocketChannel socket, ByteBuffer data) throws IOException {
|
||||
while (data.hasRemaining()) {
|
||||
socket.write(data);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
SocketChannel socket;
|
||||
synchronized (lock) {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
open = false;
|
||||
socket = channel;
|
||||
}
|
||||
if (socket != null) {
|
||||
// Unblocks the read loop, which then reports the orderly close.
|
||||
closeQuietly(socket);
|
||||
} else {
|
||||
finish(null);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isClosed() {
|
||||
synchronized (lock) {
|
||||
return closed;
|
||||
}
|
||||
}
|
||||
|
||||
/** Reports the end once, whichever of connect, read, write or close gets there first. */
|
||||
private final Object finishLock = new Object();
|
||||
|
||||
private boolean finished;
|
||||
|
||||
private void finish(@Nullable Throwable cause) {
|
||||
synchronized (lock) {
|
||||
closed = true;
|
||||
open = false;
|
||||
SocketChannel socket = channel;
|
||||
if (socket != null) {
|
||||
closeQuietly(socket);
|
||||
}
|
||||
}
|
||||
finishOutsideLock(cause);
|
||||
}
|
||||
|
||||
private void finishOutsideLock(@Nullable Throwable cause) {
|
||||
synchronized (finishLock) {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
finished = true;
|
||||
}
|
||||
listener.closed(cause);
|
||||
}
|
||||
|
||||
private void closeQuietly(SocketChannel socket) {
|
||||
try {
|
||||
socket.close();
|
||||
} catch (IOException e) {
|
||||
log.debug("Closing " + remote + " failed: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOpen() {
|
||||
synchronized (lock) {
|
||||
return open;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String remoteDescription() {
|
||||
return remote;
|
||||
}
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
package incari.platform.desktop.net;
|
||||
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.net.NetConnection;
|
||||
import java.io.IOException;
|
||||
import java.net.ProtocolException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.WebSocket;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* One WebSocket through the JDK's HTTP client. Each send is one binary message (or one text
|
||||
* message, for Eagler's queries); the JDK may hand a large incoming message over in pieces, so
|
||||
* they're joined before the listener sees it.
|
||||
*
|
||||
* <p>The JDK allows one outstanding send per socket, so sends are chained: each starts when the one
|
||||
* before it has been written. Listener callbacks come on the HTTP client's threads, one at a time.
|
||||
*/
|
||||
// Each future is finished in its own whenComplete stage, which reports failures to the listener.
|
||||
@SuppressWarnings("FutureReturnValueIgnored")
|
||||
final class WebSocketConnection implements NetConnection {
|
||||
|
||||
/**
|
||||
* Larger than any packet the game accepts (a 21-bit frame length), with room for Eagler's
|
||||
* extras. A server sending more is broken or hostile; the connection fails rather than grow.
|
||||
*/
|
||||
static final int MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
private static final long CLOSE_TIMEOUT_SECONDS = 5;
|
||||
|
||||
private final String url;
|
||||
private final NetConnection.Listener listener;
|
||||
private final PlatformLog log;
|
||||
private final Object lock = new Object();
|
||||
/** Sends made before the socket opened, written in order once it does. */
|
||||
private final Queue<Object> pending = new ArrayDeque<>();
|
||||
|
||||
private @Nullable WebSocket socket;
|
||||
/** Completes when the last send queued so far has been written. */
|
||||
private CompletableFuture<?> lastSend = CompletableFuture.completedFuture(null);
|
||||
|
||||
private boolean open;
|
||||
private boolean closed;
|
||||
private boolean finished;
|
||||
|
||||
WebSocketConnection(String url, NetConnection.Listener listener, PlatformLog log) {
|
||||
this.url = url;
|
||||
this.listener = listener;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
void start(HttpClient client) {
|
||||
URI uri;
|
||||
try {
|
||||
uri = URI.create(url);
|
||||
} catch (IllegalArgumentException e) {
|
||||
finish(new IOException("Not a WebSocket URL: " + url, e));
|
||||
return;
|
||||
}
|
||||
client.newWebSocketBuilder().buildAsync(uri, new Receiver()).whenComplete((opened, failure) -> {
|
||||
if (failure != null) {
|
||||
finish(unwrap(failure));
|
||||
} else {
|
||||
onOpened(opened);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void onOpened(WebSocket opened) {
|
||||
synchronized (lock) {
|
||||
if (closed) {
|
||||
opened.abort();
|
||||
return;
|
||||
}
|
||||
socket = opened;
|
||||
while (!pending.isEmpty()) {
|
||||
sendLocked(opened, pending.remove());
|
||||
}
|
||||
open = true;
|
||||
}
|
||||
listener.connected();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(ByteBuffer data) {
|
||||
enqueue(data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendText(String text) {
|
||||
enqueue(text);
|
||||
}
|
||||
|
||||
/** A {@link ByteBuffer} (binary message) or a {@link String} (text message). */
|
||||
private void enqueue(Object data) {
|
||||
synchronized (lock) {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
WebSocket current = socket;
|
||||
if (current == null) {
|
||||
pending.add(data);
|
||||
} else {
|
||||
sendLocked(current, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void sendLocked(WebSocket target, Object data) {
|
||||
lastSend = lastSend.thenCompose(ignored -> data instanceof String text
|
||||
? target.sendText(text, true)
|
||||
: target.sendBinary((ByteBuffer) data, true))
|
||||
.whenComplete((ignored, failure) -> {
|
||||
if (failure != null) {
|
||||
log.debug("Send to " + url + " failed: " + failure);
|
||||
target.abort();
|
||||
finish(unwrap(failure));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
WebSocket current;
|
||||
CompletableFuture<?> sends;
|
||||
synchronized (lock) {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
open = false;
|
||||
current = socket;
|
||||
sends = lastSend;
|
||||
pending.clear();
|
||||
}
|
||||
if (current != null) {
|
||||
// Let queued packets (a disconnect reason) go out first, then say goodbye; a server that
|
||||
// doesn't answer the close in time is cut off.
|
||||
sends.handle((ignored, failure) -> null)
|
||||
.thenCompose(ignored -> current.sendClose(WebSocket.NORMAL_CLOSURE, ""))
|
||||
.orTimeout(CLOSE_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||
.whenComplete((ignored, failure) -> current.abort());
|
||||
}
|
||||
finish(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOpen() {
|
||||
synchronized (lock) {
|
||||
return open;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String remoteDescription() {
|
||||
return url;
|
||||
}
|
||||
|
||||
// Reports the end once, whichever of open, receive, send or close gets there first.
|
||||
private void finish(@Nullable Throwable cause) {
|
||||
synchronized (lock) {
|
||||
closed = true;
|
||||
open = false;
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
finished = true;
|
||||
}
|
||||
listener.closed(cause);
|
||||
}
|
||||
|
||||
private static Throwable unwrap(Throwable failure) {
|
||||
return failure instanceof CompletionException && failure.getCause() != null ? failure.getCause() : failure;
|
||||
}
|
||||
|
||||
/** The JDK's callbacks: one message at a time, asking for the next only when this one is handled. */
|
||||
private final class Receiver implements WebSocket.Listener {
|
||||
|
||||
/** Pieces of the message being received; empty between messages. */
|
||||
private final List<ByteBuffer> pieces = new ArrayList<>();
|
||||
|
||||
/** The text message being received; empty between messages. */
|
||||
private final StringBuilder text = new StringBuilder();
|
||||
|
||||
private int size;
|
||||
|
||||
@Override
|
||||
public void onOpen(WebSocket webSocket) {
|
||||
webSocket.request(1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable CompletionStage<?> onBinary(WebSocket webSocket, ByteBuffer data, boolean last) {
|
||||
size += data.remaining();
|
||||
if (size > MAX_MESSAGE_BYTES) {
|
||||
webSocket.abort();
|
||||
finish(new ProtocolException("A message from " + url + " is over " + MAX_MESSAGE_BYTES + " bytes"));
|
||||
return null;
|
||||
}
|
||||
// The JDK may reuse the buffer once this returns, so keep a copy.
|
||||
ByteBuffer copy = ByteBuffer.allocate(data.remaining());
|
||||
copy.put(data).flip();
|
||||
pieces.add(copy);
|
||||
if (last) {
|
||||
ByteBuffer message = join();
|
||||
if (!isFinished()) {
|
||||
listener.received(message);
|
||||
}
|
||||
}
|
||||
webSocket.request(1);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
|
||||
// Game packets are binary; Eagler servers answer queries (the MOTD) in text.
|
||||
size += data.length();
|
||||
if (size > MAX_MESSAGE_BYTES) {
|
||||
webSocket.abort();
|
||||
finish(new ProtocolException("A message from " + url + " is over " + MAX_MESSAGE_BYTES + " bytes"));
|
||||
return null;
|
||||
}
|
||||
text.append(data);
|
||||
if (last) {
|
||||
String message = text.toString();
|
||||
text.setLength(0);
|
||||
size = 0;
|
||||
if (!isFinished()) {
|
||||
listener.receivedText(message);
|
||||
}
|
||||
}
|
||||
webSocket.request(1);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
|
||||
if (statusCode == WebSocket.NORMAL_CLOSURE || statusCode == 1001) {
|
||||
finish(null);
|
||||
} else {
|
||||
finish(new IOException("The server closed the connection (" + statusCode
|
||||
+ (reason.isEmpty() ? "" : ": " + reason) + ")"));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(WebSocket webSocket, Throwable error) {
|
||||
finish(error);
|
||||
}
|
||||
|
||||
private ByteBuffer join() {
|
||||
ByteBuffer message;
|
||||
if (pieces.size() == 1) {
|
||||
message = pieces.get(0);
|
||||
} else {
|
||||
message = ByteBuffer.allocate(size);
|
||||
for (ByteBuffer piece : pieces) {
|
||||
message.put(piece);
|
||||
}
|
||||
message.flip();
|
||||
}
|
||||
pieces.clear();
|
||||
size = 0;
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isFinished() {
|
||||
synchronized (lock) {
|
||||
return finished;
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
/** The desktop (LWJGL) implementation of the platform interfaces, for development. */
|
||||
@NullMarked
|
||||
package incari.platform.desktop;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package incari.platform.desktop;
|
||||
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
|
||||
|
||||
import com.tngtech.archunit.core.importer.ImportOption;
|
||||
import com.tngtech.archunit.junit.AnalyzeClasses;
|
||||
import com.tngtech.archunit.junit.ArchTest;
|
||||
import com.tngtech.archunit.lang.ArchRule;
|
||||
|
||||
/**
|
||||
* The desktop platform talks to the machine through LWJGL and to the game only through
|
||||
* platform-api. It never sees game types: those stay behind the interfaces.
|
||||
*/
|
||||
@AnalyzeClasses(packages = "incari.platform.desktop", importOptions = ImportOption.DoNotIncludeTests.class)
|
||||
class BoundaryTest {
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule onlyPlatformApiAndLwjgl = classes()
|
||||
.should()
|
||||
.onlyDependOnClassesThat()
|
||||
.resideInAnyPackage(
|
||||
"java..", "org.jspecify..", "org.lwjgl..", "incari.platform.api..", "incari.platform.desktop..")
|
||||
.allowEmptyShould(true);
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
package incari.platform.desktop.audio;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.audio.AudioBuffer;
|
||||
import incari.platform.api.audio.AudioDevice;
|
||||
import incari.platform.api.audio.AudioSource;
|
||||
import incari.platform.api.audio.PcmFormat;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
/**
|
||||
* What the desktop's sound actually sounds like, for the browser to match (ADR 0013): a tone
|
||||
* played through this platform's OpenAL device at known positions, recorded by OpenAL Soft's
|
||||
* wave-file backend, and the level of each channel measured.
|
||||
*
|
||||
* <p>Only {@code ./gradlew :platform-desktop:openAlReference} runs it: it points OpenAL Soft at
|
||||
* a configuration that writes to a file instead of a sound card ({@code ALSOFT_CONF}), which has
|
||||
* to be set before the JVM starts. The expected gains are the same measurements
|
||||
* {@code platform-web}'s {@code SpatializerTest} holds its model to, so a new OpenAL Soft that
|
||||
* pans differently fails here first.
|
||||
*/
|
||||
@EnabledIfEnvironmentVariable(named = "INCARI_OPENAL_WAVE", matches = ".+")
|
||||
class OpenAlReferenceTest {
|
||||
|
||||
private static final int RATE = 44100;
|
||||
private static final double AMPLITUDE = 8000.0 / 32768;
|
||||
private static final double TOLERANCE = 0.003;
|
||||
|
||||
@ParameterizedTest(name = "({0}, {1}, {2}) {3} relative={4} stereo={5}")
|
||||
@CsvSource({
|
||||
// x, y, z, attenuation, relative, stereo, left, right: listener at the origin facing -z.
|
||||
"0, 0, -4, linear, false, false, 0.4466, 0.4466",
|
||||
"4, 0, 0, linear, false, false, 0.0000, 0.7497",
|
||||
"-4, 0, 0, linear, false, false, 0.7497, 0.0000",
|
||||
"2.828, 0, -2.828, linear, false, false, 0.0560, 0.7486",
|
||||
"2, 0, -3.464, linear, false, false, 0.1605, 0.6906",
|
||||
"2.828, 0, 2.828, linear, false, false, 0.0591, 0.5892",
|
||||
"0, 0, 4, linear, false, false, 0.3031, 0.3031",
|
||||
"0, 4, 0, linear, false, false, 0.3748, 0.3748",
|
||||
"8, 0, 0, linear, false, false, 0.0000, 0.4998",
|
||||
"20, 0, 0, linear, false, false, 0.0000, 0.0000",
|
||||
"0.5, 0, -4, linear, false, false, 0.3748, 0.5135",
|
||||
"4, 0, 0, none, false, false, 0.0000, 0.9996",
|
||||
"0, 0, 0, none, true, false, 0.5954, 0.5954",
|
||||
"4, 0, 0, linear, false, true, 0.9996, 0.9996",
|
||||
})
|
||||
void panningAndAttenuation(
|
||||
double x,
|
||||
double y,
|
||||
double z,
|
||||
String attenuation,
|
||||
boolean relative,
|
||||
boolean stereo,
|
||||
double left,
|
||||
double right)
|
||||
throws Exception {
|
||||
Path wave = Path.of(System.getenv("INCARI_OPENAL_WAVE"));
|
||||
OpenAlAudio audio = new OpenAlAudio(PlatformLog.NONE);
|
||||
try (AudioDevice device = audio.open(null, false)) {
|
||||
device.listener().setPosition(0, 0, 0);
|
||||
device.listener().setOrientation(0, 0, -1, 0, 1, 0);
|
||||
AudioSource source = device.createSource();
|
||||
assertThat(source).isNotNull();
|
||||
AudioBuffer buffer = device.createBuffer(tone(stereo ? 2 : 1), new PcmFormat(RATE, stereo ? 2 : 1, 16));
|
||||
source.setBuffer(buffer);
|
||||
source.setPosition(x, y, z);
|
||||
source.setRelative(relative);
|
||||
if (attenuation.equals("linear")) {
|
||||
source.setLinearAttenuation(16);
|
||||
} else {
|
||||
source.disableAttenuation();
|
||||
}
|
||||
source.play();
|
||||
Thread.sleep(700);
|
||||
source.close();
|
||||
buffer.close();
|
||||
} finally {
|
||||
audio.close();
|
||||
}
|
||||
double[] levels = levels(Files.readAllBytes(wave));
|
||||
assertThat(levels[0]).as("left").isCloseTo(left, within(TOLERANCE));
|
||||
assertThat(levels[1]).as("right").isCloseTo(right, within(TOLERANCE));
|
||||
}
|
||||
|
||||
/** Half a second of a 441 Hz sine, 16-bit, the same in every channel. */
|
||||
private static ByteBuffer tone(int channels) {
|
||||
int frames = RATE / 2;
|
||||
ByteBuffer samples = ByteBuffer.allocateDirect(frames * 2 * channels).order(ByteOrder.LITTLE_ENDIAN);
|
||||
for (int i = 0; i < frames; i++) {
|
||||
short value = (short) Math.round(AMPLITUDE * 32768 * Math.sin(2 * Math.PI * 441 * i / RATE));
|
||||
for (int c = 0; c < channels; c++) {
|
||||
samples.putShort(value);
|
||||
}
|
||||
}
|
||||
return samples.flip();
|
||||
}
|
||||
|
||||
/**
|
||||
* Each channel's RMS over the middle half of the non-silent part of a stereo 32-bit float WAV,
|
||||
* relative to the tone's own RMS.
|
||||
*/
|
||||
private static double[] levels(byte[] wav) throws IOException {
|
||||
ByteBuffer file = ByteBuffer.wrap(wav).order(ByteOrder.LITTLE_ENDIAN);
|
||||
int data = indexOf(wav, "data") + 8;
|
||||
int channels = file.getShort(indexOf(wav, "fmt ") + 10);
|
||||
int bits = file.getShort(indexOf(wav, "fmt ") + 22);
|
||||
if (channels != 2 || bits != 32) {
|
||||
throw new IOException(
|
||||
"Expected stereo 32-bit float output, got " + channels + " channels, " + bits + " bits");
|
||||
}
|
||||
int frames = (wav.length - data) / 8;
|
||||
int first = -1;
|
||||
int last = -1;
|
||||
for (int i = 0; i < frames; i++) {
|
||||
float l = file.getFloat(data + i * 8);
|
||||
float r = file.getFloat(data + i * 8 + 4);
|
||||
if (Math.abs(l) > 1e-4 || Math.abs(r) > 1e-4) {
|
||||
if (first < 0) {
|
||||
first = i;
|
||||
}
|
||||
last = i;
|
||||
}
|
||||
}
|
||||
if (first < 0) {
|
||||
return new double[] {0, 0};
|
||||
}
|
||||
int from = first + (last - first) / 4;
|
||||
int to = first + 3 * (last - first) / 4;
|
||||
double[] sums = new double[2];
|
||||
for (int i = from; i < to; i++) {
|
||||
for (int c = 0; c < 2; c++) {
|
||||
double sample = file.getFloat(data + i * 8 + c * 4);
|
||||
sums[c] += sample * sample;
|
||||
}
|
||||
}
|
||||
double reference = AMPLITUDE / Math.sqrt(2);
|
||||
return new double[] {Math.sqrt(sums[0] / (to - from)) / reference, Math.sqrt(sums[1] / (to - from)) / reference
|
||||
};
|
||||
}
|
||||
|
||||
private static int indexOf(byte[] file, String chunk) throws IOException {
|
||||
byte[] name = chunk.getBytes(java.nio.charset.StandardCharsets.US_ASCII);
|
||||
outer:
|
||||
for (int i = 12; i + name.length <= file.length; i++) {
|
||||
for (int j = 0; j < name.length; j++) {
|
||||
if (file[i + j] != name[j]) {
|
||||
continue outer;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
throw new IOException("No " + chunk + " chunk");
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package incari.platform.desktop.audio;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.platform.api.audio.PcmFormat;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Runs without LWJGL: OpenAlSupport only uses its inlined constants. */
|
||||
class OpenAlSupportTest {
|
||||
|
||||
// OpenAL 1.1 specification values, written out so the test doesn't just repeat the code.
|
||||
private static final int FORMAT_MONO8 = 0x1100;
|
||||
private static final int FORMAT_MONO16 = 0x1101;
|
||||
private static final int FORMAT_STEREO8 = 0x1102;
|
||||
private static final int FORMAT_STEREO16 = 0x1103;
|
||||
private static final int MONO_SOURCES = 0x1010;
|
||||
private static final int FREQUENCY = 0x1007;
|
||||
private static final int HRTF = 0x1992;
|
||||
private static final int HRTF_ID = 0x1996;
|
||||
private static final int OUTPUT_LIMITER = 0x199A;
|
||||
|
||||
@Test
|
||||
void mapsEveryPcmLayoutToItsOpenAlFormat() {
|
||||
assertThat(OpenAlSupport.alFormat(new PcmFormat(44100, 1, 8))).isEqualTo(FORMAT_MONO8);
|
||||
assertThat(OpenAlSupport.alFormat(new PcmFormat(44100, 1, 16))).isEqualTo(FORMAT_MONO16);
|
||||
assertThat(OpenAlSupport.alFormat(new PcmFormat(22050, 2, 8))).isEqualTo(FORMAT_STEREO8);
|
||||
assertThat(OpenAlSupport.alFormat(new PcmFormat(48000, 2, 16))).isEqualTo(FORMAT_STEREO16);
|
||||
}
|
||||
|
||||
@Test
|
||||
void asksForHrtfOnlyWhenTheDeviceHasSome() {
|
||||
assertThat(OpenAlSupport.contextAttributes(0, true, false)).containsExactly(0);
|
||||
assertThat(OpenAlSupport.contextAttributes(2, true, false)).containsExactly(HRTF, 1, HRTF_ID, 0, 0);
|
||||
assertThat(OpenAlSupport.contextAttributes(2, false, false)).containsExactly(HRTF, 0, HRTF_ID, 0, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void turnsTheLimiterOnWhenSupported() {
|
||||
assertThat(OpenAlSupport.contextAttributes(0, false, true)).containsExactly(OUTPUT_LIMITER, 1, 0);
|
||||
assertThat(OpenAlSupport.contextAttributes(1, true, true))
|
||||
.containsExactly(HRTF, 1, HRTF_ID, 0, OUTPUT_LIMITER, 1, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsTheMonoSourceCountFromTheAttributes() {
|
||||
assertThat(OpenAlSupport.monoSourceCount(new int[] {FREQUENCY, 48000, MONO_SOURCES, 255, 0}))
|
||||
.isEqualTo(255);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenTheAttributesDontSay() {
|
||||
assertThat(OpenAlSupport.monoSourceCount(new int[0])).isEqualTo(OpenAlSupport.FALLBACK_SOURCE_COUNT);
|
||||
assertThat(OpenAlSupport.monoSourceCount(new int[] {FREQUENCY, 48000, 0, 0}))
|
||||
.isEqualTo(OpenAlSupport.FALLBACK_SOURCE_COUNT);
|
||||
// Nothing after the terminator counts.
|
||||
assertThat(OpenAlSupport.monoSourceCount(new int[] {0, 0, MONO_SOURCES, 64}))
|
||||
.isEqualTo(OpenAlSupport.FALLBACK_SOURCE_COUNT);
|
||||
// A truncated list (odd length) doesn't read past its end.
|
||||
assertThat(OpenAlSupport.monoSourceCount(new int[] {FREQUENCY, 48000, MONO_SOURCES}))
|
||||
.isEqualTo(OpenAlSupport.FALLBACK_SOURCE_COUNT);
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
package incari.platform.desktop.net;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.net.NetConnection;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DesktopNetworkTest {
|
||||
|
||||
private final DesktopNetwork network = new DesktopNetwork(PlatformLog.NONE);
|
||||
|
||||
@Test
|
||||
void fetchesABodyAndFailsOnAnErrorStatusOrOneTooBig() throws Exception {
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
|
||||
server.createContext("/skin", exchange -> {
|
||||
byte[] body = {(byte) 0x89, 'P', 'N', 'G'};
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
server.createContext("/chunked", exchange -> {
|
||||
// Length 0: chunked, so the size is only known by reading.
|
||||
exchange.sendResponseHeaders(200, 0);
|
||||
exchange.getResponseBody().write(new byte[10]);
|
||||
exchange.close();
|
||||
});
|
||||
server.createContext("/missing", exchange -> {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
try {
|
||||
String base = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
assertThat(network.fetch(base + "/skin", 4)).containsExactly((byte) 0x89, 'P', 'N', 'G');
|
||||
assertThatThrownBy(() -> network.fetch(base + "/skin", 3))
|
||||
.isInstanceOf(IOException.class)
|
||||
.hasMessageContaining("over the limit");
|
||||
assertThat(network.fetch(base + "/chunked", 10)).hasSize(10);
|
||||
assertThatThrownBy(() -> network.fetch(base + "/chunked", 9))
|
||||
.isInstanceOf(IOException.class)
|
||||
.hasMessageContaining("over the limit");
|
||||
assertThatThrownBy(() -> network.fetch(base + "/missing", 4))
|
||||
.isInstanceOf(IOException.class)
|
||||
.hasMessageContaining("404");
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendsQueuedBytesOnceConnectedAndReceivesTheReply() throws Exception {
|
||||
try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
|
||||
CompletableFuture<String> serverSaw = new CompletableFuture<>();
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try (Socket client = server.accept()) {
|
||||
serverSaw.complete(readExactly(client.getInputStream(), 5));
|
||||
OutputStream out = client.getOutputStream();
|
||||
out.write("world".getBytes(StandardCharsets.UTF_8));
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
serverSaw.completeExceptionally(e);
|
||||
}
|
||||
});
|
||||
|
||||
Recorder recorder = new Recorder();
|
||||
NetConnection connection = network.connect("127.0.0.1", server.getLocalPort(), recorder);
|
||||
// Sent before the connection opens: must be queued, then written in order.
|
||||
connection.send(ByteBuffer.wrap("hel".getBytes(StandardCharsets.UTF_8)));
|
||||
connection.send(ByteBuffer.wrap("lo".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
assertThat(serverSaw.get(5, TimeUnit.SECONDS)).isEqualTo("hello");
|
||||
assertThat(recorder.connected.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(recorder.closed.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(recorder.received()).isEqualTo("world");
|
||||
assertThat(recorder.cause).isNull();
|
||||
assertThat(connection.isOpen()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsAFailedConnectOnceWithTheCause() throws Exception {
|
||||
int unusedPort;
|
||||
try (ServerSocket probe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
|
||||
unusedPort = probe.getLocalPort();
|
||||
}
|
||||
Recorder recorder = new Recorder();
|
||||
|
||||
network.connect("127.0.0.1", unusedPort, recorder);
|
||||
|
||||
assertThat(recorder.closed.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(recorder.connected.getCount()).isEqualTo(1);
|
||||
assertThat(recorder.cause).isInstanceOf(IOException.class);
|
||||
assertThat(recorder.closedCalls.get()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingFromOurSideIsAnOrderlyClose() throws Exception {
|
||||
try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
|
||||
CountDownLatch accepted = new CountDownLatch(1);
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try (Socket client = server.accept()) {
|
||||
accepted.countDown();
|
||||
client.getInputStream().read();
|
||||
} catch (IOException e) {
|
||||
// The test only cares about the client side.
|
||||
}
|
||||
});
|
||||
Recorder recorder = new Recorder();
|
||||
NetConnection connection = network.connect("127.0.0.1", server.getLocalPort(), recorder);
|
||||
assertThat(recorder.connected.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(accepted.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
|
||||
connection.close();
|
||||
|
||||
assertThat(recorder.closed.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(recorder.cause).isNull();
|
||||
assertThat(recorder.closedCalls.get()).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static String readExactly(InputStream in, int count) throws IOException {
|
||||
return new String(in.readNBytes(count), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** Records what a connection reports. */
|
||||
private static final class Recorder implements NetConnection.Listener {
|
||||
final CountDownLatch connected = new CountDownLatch(1);
|
||||
final CountDownLatch closed = new CountDownLatch(1);
|
||||
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
volatile @Nullable Throwable cause;
|
||||
final java.util.concurrent.atomic.AtomicInteger closedCalls = new java.util.concurrent.atomic.AtomicInteger();
|
||||
|
||||
@Override
|
||||
public void connected() {
|
||||
connected.countDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void received(ByteBuffer data) {
|
||||
byte[] chunk = new byte[data.remaining()];
|
||||
data.get(chunk);
|
||||
bytes.writeBytes(chunk);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closed(@Nullable Throwable why) {
|
||||
cause = why;
|
||||
closedCalls.incrementAndGet();
|
||||
closed.countDown();
|
||||
}
|
||||
|
||||
synchronized String received() {
|
||||
return bytes.toString(StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
}
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
package incari.platform.desktop.net;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.platform.api.PlatformLog;
|
||||
import incari.platform.api.net.NetConnection;
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
import io.netty.channel.nio.NioIoHandler;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.handler.codec.http.DefaultFullHttpResponse;
|
||||
import io.netty.handler.codec.http.FullHttpRequest;
|
||||
import io.netty.handler.codec.http.HttpObjectAggregator;
|
||||
import io.netty.handler.codec.http.HttpResponseStatus;
|
||||
import io.netty.handler.codec.http.HttpServerCodec;
|
||||
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
|
||||
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
|
||||
import io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame;
|
||||
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@SuppressWarnings("FutureReturnValueIgnored")
|
||||
class WebSocketConnectionTest {
|
||||
|
||||
private final DesktopNetwork network = new DesktopNetwork(PlatformLog.NONE);
|
||||
private final EventLoopGroup group = new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory());
|
||||
/** Every binary message the server received, as text. */
|
||||
private final List<String> serverReceived = new CopyOnWriteArrayList<>();
|
||||
|
||||
private @Nullable Channel server;
|
||||
|
||||
@BeforeEach
|
||||
void startServer() throws InterruptedException {
|
||||
server = new ServerBootstrap()
|
||||
.group(group)
|
||||
.channel(NioServerSocketChannel.class)
|
||||
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||||
@Override
|
||||
protected void initChannel(SocketChannel channel) {
|
||||
channel.pipeline()
|
||||
.addLast(new HttpServerCodec())
|
||||
.addLast(new HttpObjectAggregator(65536))
|
||||
.addLast(new WebSocketServerProtocolHandler("/game"))
|
||||
.addLast(new WebSocketFrameAggregator(1 << 24))
|
||||
.addLast(new ScriptedServer());
|
||||
}
|
||||
})
|
||||
.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0))
|
||||
.sync()
|
||||
.channel();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopServer() {
|
||||
if (server != null) {
|
||||
server.close().syncUninterruptibly();
|
||||
}
|
||||
group.shutdownGracefully(0, 1, TimeUnit.SECONDS).syncUninterruptibly();
|
||||
}
|
||||
|
||||
private String url() {
|
||||
InetSocketAddress address =
|
||||
(InetSocketAddress) java.util.Objects.requireNonNull(server).localAddress();
|
||||
return "ws://127.0.0.1:" + address.getPort() + "/game";
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachSendIsOneMessageAndEachMessageArrivesWhole() throws Exception {
|
||||
Recorder recorder = new Recorder();
|
||||
NetConnection connection = network.openWebSocket(url(), recorder);
|
||||
// Sent before the socket opens: queued, then sent in order.
|
||||
connection.send(text("one"));
|
||||
connection.send(text("two"));
|
||||
|
||||
assertThat(recorder.connected.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(connection.isOpen()).isTrue();
|
||||
connection.send(text("fragmented"));
|
||||
|
||||
// The server echoes each message; "fragmented" comes back split into three frames.
|
||||
assertThat(recorder.next()).isEqualTo("echo:one");
|
||||
assertThat(recorder.next()).isEqualTo("echo:two");
|
||||
assertThat(recorder.next()).isEqualTo("echo:fragmented");
|
||||
assertThat(serverReceived).containsExactly("one", "two", "fragmented");
|
||||
}
|
||||
|
||||
@Test
|
||||
void textMessagesGoBothWaysApartFromBinaryOnes() throws Exception {
|
||||
Recorder recorder = new Recorder();
|
||||
NetConnection connection = network.openWebSocket(url(), recorder);
|
||||
// Queued before the socket opens, in order with the binary message.
|
||||
connection.sendText("Accept: motd");
|
||||
connection.send(text("binary"));
|
||||
|
||||
assertThat(recorder.connected.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
// The server greets with a text message, then echoes each message in its own kind.
|
||||
assertThat(recorder.nextText()).isEqualTo("hello");
|
||||
assertThat(recorder.nextText()).isEqualTo("text-echo:Accept: motd");
|
||||
assertThat(recorder.next()).isEqualTo("echo:binary");
|
||||
assertThat(serverReceived).containsExactly("text:Accept: motd", "binary");
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingIsAnOrderlyCloseReportedOnce() throws Exception {
|
||||
Recorder recorder = new Recorder();
|
||||
NetConnection connection = network.openWebSocket(url(), recorder);
|
||||
assertThat(recorder.connected.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
|
||||
connection.close();
|
||||
connection.close();
|
||||
|
||||
assertThat(recorder.closed.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(recorder.cause).isNull();
|
||||
assertThat(connection.isOpen()).isFalse();
|
||||
Thread.sleep(200);
|
||||
assertThat(recorder.closedCalls.get()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerCloseEndsTheConnection() throws Exception {
|
||||
Recorder recorder = new Recorder();
|
||||
NetConnection connection = network.openWebSocket(url(), recorder);
|
||||
assertThat(recorder.connected.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
|
||||
connection.send(text("bye"));
|
||||
|
||||
assertThat(recorder.closed.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(recorder.cause).isNull();
|
||||
assertThat(recorder.closedCalls.get()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedHandshakeFailsTheConnection() throws Exception {
|
||||
Recorder recorder = new Recorder();
|
||||
|
||||
network.openWebSocket(url().replace("/game", "/nothing-here"), recorder);
|
||||
|
||||
assertThat(recorder.closed.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(recorder.connected.getCount()).isEqualTo(1);
|
||||
assertThat(recorder.cause).isInstanceOf(IOException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedConnectionFailsTheConnection() throws Exception {
|
||||
int port;
|
||||
try (java.net.ServerSocket probe = new java.net.ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
|
||||
port = probe.getLocalPort();
|
||||
}
|
||||
Recorder recorder = new Recorder();
|
||||
|
||||
network.openWebSocket("ws://127.0.0.1:" + port + "/", recorder);
|
||||
|
||||
assertThat(recorder.closed.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(recorder.cause).isNotNull();
|
||||
}
|
||||
|
||||
private static ByteBuffer text(String text) {
|
||||
return ByteBuffer.wrap(text.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* Echoes binary messages as binary and text as text, greets with one text message, and closes
|
||||
* on "bye".
|
||||
* A request for any other path gets a 404.
|
||||
*/
|
||||
private final class ScriptedServer extends SimpleChannelInboundHandler<Object> {
|
||||
|
||||
@Override
|
||||
public void userEventTriggered(ChannelHandlerContext ctx, Object event) {
|
||||
if (event instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
|
||||
ctx.writeAndFlush(new TextWebSocketFrame("hello"));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void channelRead0(ChannelHandlerContext ctx, Object received) {
|
||||
if (received instanceof FullHttpRequest request) {
|
||||
ctx.writeAndFlush(new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.NOT_FOUND))
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
return;
|
||||
}
|
||||
if (received instanceof TextWebSocketFrame textFrame) {
|
||||
serverReceived.add("text:" + textFrame.text());
|
||||
ctx.writeAndFlush(new TextWebSocketFrame("text-echo:" + textFrame.text()));
|
||||
return;
|
||||
}
|
||||
if (!(received instanceof BinaryWebSocketFrame frame)) {
|
||||
return;
|
||||
}
|
||||
String message = frame.content().toString(StandardCharsets.UTF_8);
|
||||
serverReceived.add(message);
|
||||
if (message.equals("bye")) {
|
||||
ctx.writeAndFlush(new CloseWebSocketFrame(WebSocketCloseStatus.NORMAL_CLOSURE))
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
return;
|
||||
}
|
||||
byte[] reply = ("echo:" + message).getBytes(StandardCharsets.UTF_8);
|
||||
if (message.equals("fragmented")) {
|
||||
ctx.write(new BinaryWebSocketFrame(false, 0, Unpooled.wrappedBuffer(reply, 0, 5)));
|
||||
ctx.write(new ContinuationWebSocketFrame(false, 0, Unpooled.wrappedBuffer(reply, 5, 3)));
|
||||
ByteBuf rest = Unpooled.wrappedBuffer(reply, 8, reply.length - 8);
|
||||
ctx.writeAndFlush(new ContinuationWebSocketFrame(true, 0, rest));
|
||||
} else {
|
||||
ctx.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(reply)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Records what a connection reports. */
|
||||
private static final class Recorder implements NetConnection.Listener {
|
||||
final CountDownLatch connected = new CountDownLatch(1);
|
||||
final CountDownLatch closed = new CountDownLatch(1);
|
||||
final BlockingQueue<String> messages = new LinkedBlockingQueue<>();
|
||||
final BlockingQueue<String> texts = new LinkedBlockingQueue<>();
|
||||
final AtomicInteger closedCalls = new AtomicInteger();
|
||||
volatile @Nullable Throwable cause;
|
||||
|
||||
@Override
|
||||
public void connected() {
|
||||
connected.countDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void received(ByteBuffer data) {
|
||||
messages.add(StandardCharsets.UTF_8.decode(data).toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void receivedText(String text) {
|
||||
texts.add(text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closed(@Nullable Throwable why) {
|
||||
cause = why;
|
||||
closedCalls.incrementAndGet();
|
||||
closed.countDown();
|
||||
}
|
||||
|
||||
String next() throws InterruptedException {
|
||||
String message = messages.poll(5, TimeUnit.SECONDS);
|
||||
assertThat(message).as("a message within 5 s").isNotNull();
|
||||
return message;
|
||||
}
|
||||
|
||||
String nextText() throws InterruptedException {
|
||||
String message = texts.poll(5, TimeUnit.SECONDS);
|
||||
assertThat(message).as("a text message within 5 s").isNotNull();
|
||||
return message;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user