core 0.1-beta

This commit is contained in:
Fokinator
2026-05-27 22:02:28 +03:00
parent 38c599c2cf
commit e788a99545
224 changed files with 7812 additions and 3946 deletions
+38 -33
View File
@@ -3,7 +3,7 @@
* <p>This module is always required to use the Sparkle framework. You can optionally connect other Sparkle modules
* for additional functionality.
*/
module ru.fokinatorr.sparkle.core {
module net.fokinatorr.sparkle.core {
requires it.unimi.dsi.fastutil;
requires static lombok;
requires org.slf4j;
@@ -14,40 +14,45 @@ module ru.fokinatorr.sparkle.core {
requires org.lwjgl.opengl;
requires org.lwjgl.nanovg;
requires org.lwjgl.stb;
requires ru.fokinatorr.lwjgl.util.exceptions;
requires net.fokinatorr.lwjgl.util.exceptions;
requires java.compiler;
requires java.management;
requires org.joml;
requires com.google.j2objc.annotations;
requires org.checkerframework.checker.qual;
requires poly2tri;
exports ru.fokinatorr.sparkle.assets;
exports ru.fokinatorr.sparkle.audio;
exports ru.fokinatorr.sparkle.audio.io;
exports ru.fokinatorr.sparkle.context;
exports ru.fokinatorr.sparkle.effect;
exports ru.fokinatorr.sparkle.effect.graphics;
exports ru.fokinatorr.sparkle.effect.sounds;
exports ru.fokinatorr.sparkle.event;
exports ru.fokinatorr.sparkle.event.annotation;
exports ru.fokinatorr.sparkle.event.dispatcher;
exports ru.fokinatorr.sparkle.event.input;
exports ru.fokinatorr.sparkle.event.lifecycle;
exports ru.fokinatorr.sparkle.graphics;
exports ru.fokinatorr.sparkle.graphics.font;
exports ru.fokinatorr.sparkle.graphics.image;
exports ru.fokinatorr.sparkle.graphics.io;
exports ru.fokinatorr.sparkle.graphics.render;
exports ru.fokinatorr.sparkle.graphics.render.framebuffer;
exports ru.fokinatorr.sparkle.graphics.render.surface;
exports ru.fokinatorr.sparkle.graphics.render.renderer;
exports ru.fokinatorr.sparkle.graphics.vector;
exports ru.fokinatorr.sparkle.phys2d;
exports ru.fokinatorr.sparkle.stage;
exports ru.fokinatorr.sparkle.stage.sprite;
exports ru.fokinatorr.sparkle.util;
exports ru.fokinatorr.sparkle.util.stopwatch;
exports ru.fokinatorr.sparkle.util.concurrent;
exports ru.fokinatorr.sparkle.util.concurrent.atomic;
exports ru.fokinatorr.sparkle.variable;
exports net.fokinatorr.sparkle;
exports net.fokinatorr.sparkle.assets;
exports net.fokinatorr.sparkle.audio;
exports net.fokinatorr.sparkle.audio.io;
exports net.fokinatorr.sparkle.context;
exports net.fokinatorr.sparkle.effect;
exports net.fokinatorr.sparkle.effect.graphics;
exports net.fokinatorr.sparkle.effect.sounds;
exports net.fokinatorr.sparkle.event;
exports net.fokinatorr.sparkle.event.annotation;
exports net.fokinatorr.sparkle.event.dispatcher;
exports net.fokinatorr.sparkle.event.input;
exports net.fokinatorr.sparkle.event.lifecycle;
exports net.fokinatorr.sparkle.graphics;
// exports net.fokinatorr.sparkle.graphics.impl.gl to net.fokinatorr.sparkle.ext3d;
// exports net.fokinatorr.sparkle.graphics.impl.gl.element to net.fokinatorr.sparkle.ext3d;
// exports net.fokinatorr.sparkle.graphics.impl.gl.shader to net.fokinatorr.sparkle.ext3d;
exports net.fokinatorr.sparkle.graphics.font;
exports net.fokinatorr.sparkle.graphics.image;
exports net.fokinatorr.sparkle.graphics.io;
exports net.fokinatorr.sparkle.graphics.render;
exports net.fokinatorr.sparkle.graphics.render.framebuffer;
exports net.fokinatorr.sparkle.graphics.render.surface;
exports net.fokinatorr.sparkle.graphics.render.renderer;
exports net.fokinatorr.sparkle.phys;
exports net.fokinatorr.sparkle.phys2d;
exports net.fokinatorr.sparkle.stage;
exports net.fokinatorr.sparkle.stage.sprite;
exports net.fokinatorr.sparkle.util;
exports net.fokinatorr.sparkle.util.stopwatch;
exports net.fokinatorr.sparkle.util.concurrent;
exports net.fokinatorr.sparkle.util.concurrent.atomic;
exports net.fokinatorr.sparkle.variable;
uses net.fokinatorr.sparkle.NativeExtractor;
}
@@ -0,0 +1,321 @@
package net.fokinatorr.sparkle;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import net.fokinatorr.sparkle.audio.AudioManager;
import net.fokinatorr.sparkle.context.AppContext;
import net.fokinatorr.sparkle.context.AppContextHolder;
import net.fokinatorr.sparkle.graphics.GraphicsManager;
import net.fokinatorr.sparkle.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.function.Supplier;
import static net.fokinatorr.sparkle.util.WaitUtils.waitFor;
import static org.lwjgl.system.Configuration.DEBUG;
import static org.lwjgl.system.Configuration.LIBRARY_PATH;
/**
* Manages the full lifecycle of a Sparkle application.
* <p>
* This class handles:
* <ul>
* <li>App instantiation</li>
* <li>Thread management (audio, graphics, terminator)</li>
* <li>Logging setup</li>
* <li>Shutdown hook registration</li>
* <li>Clean termination</li>
* </ul>
* <p>
*/
@Slf4j
@UtilityClass
final class Lifecycle {
/**
* Launches the given app.
*
* @param appClass the app class
* @param init init config
* @param args CLI args
* @param contextFactory creator of an app environment (audio and graphics managers should be registered as lazy if they capture the current
* thread in constructor and consider it the respective audio/graphics thread)
* @param headless whether the context is headless
* @return the launched application
*/
<A extends SparkleApp> A launch(Class<A> appClass, SparkleInit init, String[] args, Supplier<AppContext> contextFactory, boolean headless) {
Objects.requireNonNull(appClass, "app class");
Objects.requireNonNull(init, "init config");
Objects.requireNonNull(args, "args");
Objects.requireNonNull(contextFactory, "context factory");
try {
// First set up logging level (using reflection to avoid compile-time logback dependency)
Logger root = LoggerFactory.getLogger("net.fokinatorr.sparkle");
Class<?> levelClass = Class.forName("ch.qos.logback.classic.Level");
Level logLevel = init.getLogLevel();
Object actualLevel = logLevel == null
? levelClass.getField("OFF").get(null)
: levelClass.getMethod("convertAnSLF4JLevel", Level.class).invoke(null, logLevel);
//noinspection JavaReflectionInvocation
Class.forName("ch.qos.logback.classic.Logger").getMethod("setLevel", levelClass).invoke(root, actualLevel);
} catch (Exception e) {
throw new InternalError("BUG: Could not set log level, did SLF4J implementation change?", e);
}
log.info("Starting Sparkle core version {}", Version.current());
if (headless) {
log.info("Skipping native extraction; platform-specific components (graphics, audio, etc.) will not work");
} else {
log.trace("Extracting JNI libraries");
DEBUG.set(init.isNativeDebug());
Path libDir = init.getNativeExtractPath();
if (libDir == null) {
try {
libDir = Files.createTempDirectory("sparkle-natives");
} catch (IOException e) {
throw report("Could not create temp directory", e);
}
}
if (!Files.isDirectory(libDir)) {
throw report("Library extraction path should be a directory", new NotDirectoryException(libDir.toString()));
}
IOException extractEx = null;
boolean noLibs = true;
for (NativeExtractor extractor : ServiceLoader.load(NativeExtractor.class)) {
log.trace("Found native extractor: {}", extractor.getClass().getName());
try {
extractor.extractTo(libDir);
noLibs = false;
} catch (IOException e) {
if (extractEx == null) {
extractEx = e;
} else {
extractEx.addSuppressed(e);
}
}
}
if (extractEx != null) {
throw report("Some native libraries failed to extract", extractEx);
}
if (noLibs) {
throw report("No native libraries found. Make sure you have at least one natives module", new NullPointerException());
}
String libPath = LIBRARY_PATH.get();
if (libPath == null) {
LIBRARY_PATH.set(libDir.toString());
} else {
if (!libPath.contains(libDir.toString())) {
LIBRARY_PATH.set(libDir + File.pathSeparator + libPath);
}
}
}
A instance;
try {
log.trace("Creating app class instance");
instance = appClass.getConstructor().newInstance();
} catch (InstantiationException e) {
throw report("Could not instantiate app class", e);
} catch (IllegalAccessException e) {
throw report("Could not instantiate app class: No-arg constructor exists, but is inaccessible", e);
} catch (InvocationTargetException e) {
throw report("Could not instantiate app class: Constructor threw exception", e.getTargetException());
} catch (NoSuchMethodException e) {
throw report("Could not instantiate app class: No-arg constructor not found", e);
}
instance.state = SparkleApp.State.NEW;
instance.parameters = List.of(args);
AppContext context = Objects.requireNonNull(contextFactory.get(), "context");
instance.context = context;
if (init.isSetGlobalContext()) {
AppContextHolder.initContext(context);
}
try {
log.trace("Calling init()");
instance.init();
instance.state = SparkleApp.State.INITIALIZED;
} catch (Exception e) {
throw report("init() threw exception", e);
}
if (!headless && context.has(AudioManager.class)) {
instance.audioThread = Thread.ofPlatform()
.name("sparkle-audio")
.start(new AudioLoop(instance, init, context));
}
if (!headless && context.has(GraphicsManager.class)) {
instance.graphicsThread = Thread.ofPlatform()
.name("sparkle-graphics")
.start(new GraphicsLoop(instance, init, context));
} else {
instance.state = SparkleApp.State.RUNNING;
}
instance.terminatorThread = Thread.ofPlatform()
.name("sparkle-terminator")
.unstarted(() -> doTerminate(instance, true));
Runtime.getRuntime().addShutdownHook(instance.terminatorThread);
return instance;
}
/**
* Requests graceful termination of the app, if it's not already terminating/terminated.
* @param app the app
* @throws InterruptedException if interrupted while waiting for termination
*/
void terminate(SparkleApp app) throws InterruptedException {
if (app.state == SparkleApp.State.RUNNING && app.terminatorThread != null) {
Runtime.getRuntime().removeShutdownHook(app.terminatorThread);
if (app.terminatorThread.getState() == Thread.State.NEW) {
// Only terminate if it never started yet
app.terminatorThread = Thread.ofPlatform()
.name("sparkle-terminator")
.start(() -> doTerminate(app, true));
}
app.terminatorThread.join();
}
}
private void doTerminate(SparkleApp app, boolean stopGraphics) {
app.state = SparkleApp.State.TERMINATING;
log.info("Stopping!");
if (app.audioThread != null) {
app.audioThread.interrupt();
try {
app.audioThread.join();
} catch (InterruptedException e) {
log.warn("Terminator thread interrupted", e);
}
}
if (stopGraphics && app.graphicsThread != null) {
app.graphicsThread.interrupt();
try {
app.graphicsThread.join();
} catch (InterruptedException e) {
log.warn("Terminator thread interrupted", e);
}
}
try {
log.trace("Calling stop()");
app.stop();
} catch (Exception e) {
throw report("stop() threw exception", e);
}
try {
log.trace("Terminating context");
app.context.close();
} catch (Exception e) {
throw report("Failed to close context", e);
}
app.state = SparkleApp.State.TERMINATED;
log.info("App terminated. Bye!");
}
/**
* Logs the exception with the message and throws a {@link RuntimeException} that wraps the given exception.
* <p>This method doesn't actually return anything, it always throws. Its "return value"
* must be thrown to avoid compiler errors regarding no return statement and similar problems, like so:
* <pre>{@code throw report(...); // compiler will think it's the final statement}</pre>
*/
private RuntimeException report(String message, Throwable ex) {
log.error(message, ex);
if (ex instanceof RuntimeException rex) {
throw rex;
} else if (ex instanceof Error err) {
throw err;
} else {
throw new RuntimeException(ex);
}
}
@Slf4j
private record AudioLoop(SparkleApp app, SparkleInit init, AppContext context) implements Runnable {
@Override
public synchronized void run() {
log.info("Starting audio loop...");
log.debug("\tApp class: {}", app.getClass().getName());
if (init.isSetGlobalContext()) {
AppContextHolder.initContext(context);
}
AudioManager manager = context.get(AudioManager.class);
try {
while (!Thread.interrupted()) {
manager.tick();
waitFor(1); // we don't need too much precision
}
log.trace("Audio thread interrupted");
} catch (Throwable t) {
log.error("Exception in audio loop", t);
}
log.info("Audio loop terminated.");
}
}
@Slf4j
private record GraphicsLoop(SparkleApp app, SparkleInit init, AppContext context) implements Runnable {
@Override
public synchronized void run() {
log.info("Starting graphics loop...");
log.debug("\tApp class: {}", app.getClass().getName());
if (init.isSetGlobalContext()) {
AppContextHolder.initContext(context);
}
GraphicsManager manager = context.get(GraphicsManager.class);
try {
log.trace("Calling start()");
app.start(manager);
app.state = SparkleApp.State.RUNNING;
} catch (Exception e) {
throw report("start() threw exception", e);
}
try {
while (!Thread.currentThread().isInterrupted() && manager.hasActiveContexts()) {
manager.tick();
}
if (Thread.interrupted()) {
log.trace("Graphics thread interrupted");
} else {
log.trace("No active rendering contexts");
terminateApp();
}
} catch (Throwable t) {
log.error("Exception in graphics loop", t);
terminateApp();
}
log.info("Graphics loop terminated.");
}
private void terminateApp() {
if (app.state == SparkleApp.State.RUNNING && app.terminatorThread != null) {
Runtime.getRuntime().removeShutdownHook(app.terminatorThread);
if (app.terminatorThread.getState() == Thread.State.NEW) {
app.terminatorThread = Thread.ofPlatform()
.name("sparkle-terminator")
.start(() -> doTerminate(app, false));
}
}
}
}
}
@@ -0,0 +1,19 @@
package net.fokinatorr.sparkle;
import java.io.IOException;
import java.nio.file.Path;
/**
* Interface for extracting platform-specific native libraries into the specified directory.
* <p>This framework uses LWJGL for native bindings, so, if you want to implement this interface,
* use <b>strictly only their</b> natives.
* <p>Libraries used by the core module: LWJGL core, GLFW, NanoSVG, OpenAL, OpenGL (core profile), STB.
*/
public interface NativeExtractor {
/**
* Extracts all native libraries into the given directory.
* @param dir the directory
* @throws IOException if an I/O error occurs
*/
void extractTo(Path dir) throws IOException;
}
@@ -0,0 +1,215 @@
package net.fokinatorr.sparkle;
import lombok.Getter;
import net.fokinatorr.sparkle.context.AppContext;
import net.fokinatorr.sparkle.context.DefaultAppContext;
import net.fokinatorr.sparkle.graphics.GraphicsManager;
import net.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.stage.sprite.Sprite;
import java.util.List;
import static java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE;
/**
* Base class for all Sparkle apps.
* <p>
* Subclasses must:
* <ul>
* <li>Have a public no-argument constructor. <i><b>Note</b>: it is recommended to define no constructor at all
* (letting the compiler generate a nullary one) and move initialization to {@link #init()}, since at the moment of object
* construction, all getters return {@code null}.</i></li>
* <li>Override {@link #start(GraphicsManager)}</li>
* </ul>
* <p>
* Example:
* <pre>{@code
* public class MyGame extends SparkleApp {
* private static final Assets STAGE = ...;
* private static final Assets PLAYER = ...;
*
* public static void main(String[] args) {
* SparkleApp.launch(SparkleInit.DEFAULT, args);
* }
*
* private static Stage primaryStage;
*
* protected void start(GraphicsManager gm) {
* RenderingContext renderCtx = gm.createWindowContext("My Game", new StageCreator() {
* @Override
* public Assets getStageAssets() {
* return STAGE;
* }
*
* @Override
* public void customize(Stage stage) {
* stage.setSize(480, 360); // Scratch's stage size
*
* Sprite player = new Sprite(PLAYER);
* player.setX(-100);
* player.setRotationMode(RotationMode.LEFT_RIGHT);
* player.setCostume("blue");
* stage.registerSprite("player", player);
*
* // ...
* Global.registerEventListener(new MyGameLogic());
* }
* });
* primaryStage = renderCtx.getStage();
* renderCtx.getSurface().show();
* }
* }
* }</pre>
*/
public abstract class SparkleApp {
private static final StackWalker STACK_WALKER = StackWalker.getInstance(RETAIN_CLASS_REFERENCE);
/**
* Called once during startup on the same thread that called
* one of the {@code launch} methods, before creating audio/graphics loops.
* Override to configure beans, load assets, register event listeners, etc.
* (Use {@link #getContext()} to access the app context.)
*
* @throws Exception on error
*/
protected void init() throws Exception {
}
/**
* Called after {@link #init()} on the graphics thread. Use to create and initialize rendering contexts
* (e.g. registering {@link Sprite}s or other renderable objects) and register {@link Stage}-dependent event listeners.
* <p>Note: if no rendering contexts are created in this method, the app will immediately terminate.
* <p><i>This method is never called for headless apps!</i>
*
* @param graphics the graphics manager
* @throws Exception on error
*/
protected abstract void start(GraphicsManager graphics) throws Exception;
/**
* Called during shutdown on the terminator thread, when all rendering contexts close or on explicit shutdown request.
* Override to clean up resources.
*
* @throws Exception on error
*/
protected void stop() throws Exception {
}
/**
* Command line arguments (immutable).
*/
@Getter
List<String> parameters; // stable
/**
* The app's context.
*/
@Getter
AppContext context; // stable
/**
* The current app state.
*/
@Getter
State state; // NOT stable
Thread audioThread; // stable
Thread graphicsThread; // stable
Thread terminatorThread; // NOT stable
/**
* Launches a Sparkle app.
*
* @param appClass the app class to launch
* @param init the init configuration
* @param args optional command-line arguments
* @return the launched app instance
*/
public static <A extends SparkleApp> A launch(Class<A> appClass, SparkleInit init, String... args) {
return Lifecycle.launch(appClass, init, args, DefaultAppContext::createWithDefaults, false);
}
/**
* Launches a headless Sparkle app (no audio and graphics).
*
* @param appClass the app class to launch
* @param init the init configuration
* @param args optional command-line arguments
* @return the launched app instance
*/
public static <A extends SparkleApp> A launchHeadless(Class<A> appClass, SparkleInit init, String... args) {
return Lifecycle.launch(appClass, init, args, DefaultAppContext::createHeadless, true);
}
/**
* Launches a Sparkle app, using the directly calling class as the app class.
*
* @param init the init configuration
* @param args optional command-line arguments
* @return the launched app instance
* @throws ClassCastException if caller class is not a {@code SparkleApp}
*/
public static SparkleApp launch(SparkleInit init, String... args) {
return Lifecycle.launch(callerAsAppClass(STACK_WALKER.getCallerClass()), init, args, DefaultAppContext::createWithDefaults, false);
}
/**
* Launches a headless Sparkle app, using the directly calling class as the app class.
*
* @param init the init configuration
* @param args optional command-line arguments
* @return the launched app instance
* @throws ClassCastException if caller class is not a {@code SparkleApp}
*/
public static SparkleApp launchHeadless(SparkleInit init, String... args) {
return Lifecycle.launch(callerAsAppClass(STACK_WALKER.getCallerClass()), init, args, DefaultAppContext::createHeadless, true);
}
/**
* Attempts to gracefully terminate execution of this app.
* @throws InterruptedException if interrupted while waiting
* @throws IllegalStateException if this app hasn't been started yet
* @see State
*/
public final void terminate() throws InterruptedException {
if (state == State.NEW || state == State.INITIALIZED) {
throw new IllegalStateException("App hasn't started yet");
}
if (state == State.RUNNING) {
Lifecycle.terminate(this);
}
}
/**
* The app state.
*/
public enum State {
/**
* The app instance was just created. Calling {@link SparkleApp#terminate()} at this state is illegal.
*/
NEW,
/**
* The app instance has been initialized and is about to start. Calling {@link SparkleApp#terminate()} at this state is illegal.
*/
INITIALIZED,
/**
* The app instance is running. Calling {@link SparkleApp#terminate()} at this state will cause graceful exit.
*/
RUNNING,
/**
* The app instance is being terminated. Calling {@link SparkleApp#terminate()} at this state does nothing.
*/
TERMINATING,
/**
* The app instance is terminated. Calling {@link SparkleApp#terminate()} at this state does nothing.
*/
TERMINATED
}
private static Class<? extends SparkleApp> callerAsAppClass(Class<?> caller) {
// We take caller as argument, because if we do STACK_WALKER.getCallerClass() here, we will always get SparkleApp.class
if (!SparkleApp.class.isAssignableFrom(caller)) {
throw new ClassCastException("Caller class is not an instance of SparkleApp: " + caller);
}
return caller.asSubclass(SparkleApp.class);
}
}
@@ -0,0 +1,49 @@
package net.fokinatorr.sparkle;
import lombok.*;
import org.slf4j.event.Level;
import net.fokinatorr.sparkle.context.AppContextHolder;
import net.fokinatorr.sparkle.util.Global;
import java.nio.file.Path;
/**
* Initialization configuration for Sparkle.
*/
@Builder(toBuilder = true)
@With
@Value
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class SparkleInit {
/**
* Default configuration instance. This is optimal for development and testing environments.
*/
public static final SparkleInit DEFAULT = SparkleInit.builder().build();
/**
* Minimal log level ({@code null} to disable logging). Default is {@link Level#DEBUG}; recommended to increase
* for production.
*/
@Builder.Default
Level logLevel = Level.DEBUG;
/**
* Whether debug mode should be enabled for native libraries. Disabled by default, since this heavily impacts performance.
*/
@Builder.Default
boolean nativeDebug = false;
/**
* Whether to initialize global context in {@link AppContextHolder}. Enabled by default.
* <p>When enabled, the {@link Global} class will properly function.
*/
@Builder.Default
boolean setGlobalContext = true;
/**
* Path to extract native libraries into (must be a directory). Default is {@code null} (extracts into a temporary directory).
* Recommended to change for production.
*/
@Builder.Default
Path nativeExtractPath = null;
}
@@ -1,7 +1,7 @@
package ru.fokinatorr.sparkle.assets;
package net.fokinatorr.sparkle.assets;
import it.unimi.dsi.fastutil.objects.Object2IntFunction;
import ru.fokinatorr.sparkle.util.Constants;
import net.fokinatorr.sparkle.util.Constants;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.assets;
package net.fokinatorr.sparkle.assets;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntMaps;
@@ -7,7 +7,7 @@ import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import java.util.List;
import java.util.Objects;
import static ru.fokinatorr.sparkle.util.Constants.ROOT;
import static net.fokinatorr.sparkle.util.Constants.ROOT;
/**
* Default implementation of {@link Assets}.
@@ -1,9 +1,9 @@
package ru.fokinatorr.sparkle.audio;
package net.fokinatorr.sparkle.audio;
import it.unimi.dsi.fastutil.Pair;
import ru.fokinatorr.sparkle.audio.io.SoundDecoder;
import ru.fokinatorr.sparkle.stage.sprite.Sprite;
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import net.fokinatorr.sparkle.audio.io.SoundDecoder;
import net.fokinatorr.sparkle.stage.sprite.Sprite;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.io.IOException;
import java.nio.file.Path;
@@ -1,7 +1,7 @@
package ru.fokinatorr.sparkle.audio;
package net.fokinatorr.sparkle.audio;
import ru.fokinatorr.sparkle.effect.EffectMap;
import ru.fokinatorr.sparkle.effect.sounds.SoundEffect;
import net.fokinatorr.sparkle.effect.EffectMap;
import net.fokinatorr.sparkle.effect.sounds.SoundEffect;
import java.util.Objects;
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.audio.impl;
package net.fokinatorr.sparkle.audio.impl;
import lombok.AccessLevel;
import lombok.Getter;
@@ -6,18 +6,19 @@ import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
//import lombok.extern.lwjgl.ALCheckError;
import lombok.extern.slf4j.Slf4j;
import ru.fokinatorr.sparkle.audio.SoundInstance;
import ru.fokinatorr.sparkle.effect.EffectMap;
import ru.fokinatorr.sparkle.effect.sounds.SoundEffect;
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import net.fokinatorr.sparkle.audio.SoundInstance;
import net.fokinatorr.sparkle.effect.EffectMap;
import net.fokinatorr.sparkle.effect.sounds.SoundEffect;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.nio.FloatBuffer;
import java.util.Objects;
import static org.lwjgl.openal.ALC10.alcMakeContextCurrent;
import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*;
import static org.lwjgl.system.MemoryUtil.memAllocFloat;
import static org.lwjgl.system.MemoryUtil.memDuplicate;
import static ru.fokinatorr.sparkle.util.BufferUtils.*;
import static net.fokinatorr.sparkle.util.BufferUtils.*;
/**
* Base interface for managing OpenAL sound sources.
@@ -30,13 +31,12 @@ import static ru.fokinatorr.sparkle.util.BufferUtils.*;
public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implements NonThrowingAutoCloseable, SoundInstance<SELF> {
/**
* The OpenAL source ID.
* <p> -- GETTER --
* <p> Returns the OpenAL source ID.
*
* @return the source ID
* The ALC context handle.
*/
protected final long alcContext; // pointer
/**
* The OpenAL source ID.
*/
@SuppressWarnings("JavadocDeclaration") // @return used by getter
protected final int sourceId;
/**
* The attached sound effect map that will be listened. Ignored if {@code null}.
@@ -46,7 +46,9 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
/**
* Constructor for subclasses to call.
*/
protected BaseSoundSource(int sourceId) {
protected BaseSoundSource(long alcContext, int sourceId) {
alcMakeContextCurrent(alcContext);
this.alcContext = alcContext;
this.sourceId = sourceId;
alSourcei(sourceId, AL_SOURCE_RELATIVE, AL_FALSE);
alSource3f(sourceId, AL_POSITION, 0.0f, 0.0f, 0.0f);
@@ -115,6 +117,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
*/
@Override
public void play() {
alcMakeContextCurrent(alcContext);
// alSourcePlay applied to a stopped sound changes the state
// firstly to initial, then to playing, so allow for potential rewind() overrides
if (getALState() == SourceState.STOPPED) {
@@ -133,6 +136,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
*/
@Override
public void pause() {
alcMakeContextCurrent(alcContext);
alSourcePause(sourceId);
}
@@ -142,6 +146,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
*/
@Override
public void stop() {
alcMakeContextCurrent(alcContext);
alSourceStop(sourceId);
}
@@ -152,6 +157,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
*/
@Override
public void rewind() {
alcMakeContextCurrent(alcContext);
// alSourceRewind applied to a playing or paused sound changes the state
// firstly to stopped, then to initial, so allow for potential stop() overrides
SourceState alState = getALState();
@@ -166,6 +172,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
* @return the source state
*/
public SourceState getALState() {
alcMakeContextCurrent(alcContext);
return SourceState.valueOf(alGetSourcei(sourceId, AL_SOURCE_STATE));
}
@@ -185,6 +192,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
* @return this sound source
*/
public SELF alPitch(float newPitch) {
alcMakeContextCurrent(alcContext);
alSourcef(sourceId, AL_PITCH, newPitch);
return self();
}
@@ -196,6 +204,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
* @return this sound source
*/
public SELF alGain(float newGain) {
alcMakeContextCurrent(alcContext);
alSourcef(sourceId, AL_GAIN, newGain);
return self();
}
@@ -209,6 +218,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
* @return this sound source
*/
public SELF alPosition(float x, float y, float z) {
alcMakeContextCurrent(alcContext);
alSource3f(
sourceId, AL_POSITION,
x, y, z
@@ -291,6 +301,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
* {@return the pitch of this sound source}
*/
public float alPitch() {
alcMakeContextCurrent(alcContext);
return alGetSourcef(sourceId, AL_PITCH);
}
@@ -298,6 +309,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
* {@return the gain of this sound source}
*/
public float alGain() {
alcMakeContextCurrent(alcContext);
return alGetSourcef(sourceId, AL_GAIN);
}
@@ -310,6 +322,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
* @return the position of this sound source
*/
public float[] alPosition() {
alcMakeContextCurrent(alcContext);
FloatBuffer pos = memAllocFloat(3);
try (var _ = freeing(pos)) {
alGetSource3f(
@@ -327,6 +340,7 @@ public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implem
* Ticks this source. This method is executed repeatedly for each {@link SourceState#PLAYING playing} sound source in the audio engine loop.
*/
public void tick() {
alcMakeContextCurrent(alcContext);
if (attachedEffects != null) {
//noinspection resource
copyPropertiesFrom(attachedEffects);
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.audio.impl;
package net.fokinatorr.sparkle.audio.impl;
import it.unimi.dsi.fastutil.Pair;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
@@ -11,12 +11,12 @@ import lombok.extern.slf4j.Slf4j;
import org.lwjgl.BufferUtils;
import org.lwjgl.openal.AL;
import org.lwjgl.openal.ALCCapabilities;
import ru.fokinatorr.sparkle.audio.AudioManager;
import ru.fokinatorr.sparkle.audio.impl.bufferprovider.SoundBufferProvider;
import ru.fokinatorr.sparkle.audio.impl.io.ParsedSoundImpl;
import ru.fokinatorr.sparkle.audio.io.SoundDecoder;
import ru.fokinatorr.sparkle.context.AppContext;
import ru.fokinatorr.sparkle.util.GUID;
import net.fokinatorr.sparkle.audio.AudioManager;
import net.fokinatorr.sparkle.audio.impl.bufferprovider.SoundBufferProvider;
import net.fokinatorr.sparkle.audio.impl.io.ParsedSoundImpl;
import net.fokinatorr.sparkle.audio.io.SoundDecoder;
import net.fokinatorr.sparkle.context.AppContext;
import net.fokinatorr.sparkle.util.GUID;
import java.io.IOException;
import java.nio.ByteBuffer;
@@ -31,7 +31,7 @@ import static org.lwjgl.openal.ALC.*;
import static org.lwjgl.openal.ALC10.*;
import static org.lwjgl.system.MemoryUtil.NULL;
import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*;
import static ru.fokinatorr.sparkle.audio.impl.BaseSoundSource.SourceState.PLAYING;
import static net.fokinatorr.sparkle.audio.impl.BaseSoundSource.SourceState.PLAYING;
/**
* The entry point for creating an OpenAL audio engine.
@@ -63,7 +63,7 @@ public class OpenALAudioManager implements AudioManager {
/**
* Creates a new audio engine that opens the default audio device.
* Creates a new audio manager that opens the default audio device.
*
* @param appContext the application context (used to get sound decoders)
* @throws IllegalStateException if initialization fails for any reason
@@ -103,9 +103,10 @@ public class OpenALAudioManager implements AudioManager {
IOException ex = null;
ParsedSoundImpl newSound = null;
if (device != NULL && alcContext != NULL) {
alcMakeContextCurrent(alcContext);
for (SoundDecoder decoder : appContext.getAll(SoundDecoder.class)) {
try {
newSound = ParsedSoundImpl.fromPublicAPI(decoder.parseFile(path));
newSound = ParsedSoundImpl.fromPublicAPI(alcContext, decoder.parseFile(path));
if (decoder.getSupportedExtensions().stream().noneMatch(ext -> path.getFileName().toString().endsWith(ext))) {
logWrongFilenameExt(decoder.getFormatName(), decoder.getSupportedExtensions(), path);
}
@@ -161,7 +162,7 @@ public class OpenALAudioManager implements AudioManager {
@Override
public Pair<String, StaticSoundSource> createStaticSoundInstance(Path path) {
ensureOpen();
ensureContext();
alcMakeContextCurrent(alcContext);
ParsedSoundImpl parsed = getParsedSound(path);
SoundBuffer buffer = parsed.createStandAloneBuffer();
@@ -198,12 +199,12 @@ public class OpenALAudioManager implements AudioManager {
*/
public Pair<String, StreamingSoundSource> createStreamingSoundInstance(Path path, int maxBufferSize, boolean loop) {
ensureOpen();
ensureContext();
alcMakeContextCurrent(alcContext);
ParsedSoundImpl parsed = getParsedSound(path);
SoundBufferProvider provider = parsed.createProvider(maxBufferSize, loop);
String id = GUID.generate();
StreamingSoundSource source = new StreamingSoundSource(provider, 3);
StreamingSoundSource source = new StreamingSoundSource(alcContext, provider, 3);
sources.put(id, source);
return new ObjectObjectImmutablePair<>(id, source);
}
@@ -230,8 +231,8 @@ public class OpenALAudioManager implements AudioManager {
@Override
public void destroySoundInstance(String id) {
ensureOpen();
ensureContext();
if (sources.containsKey(id)) {
alcMakeContextCurrent(alcContext);
BaseSoundSource<?> source = sources.remove(id);
// The source is stopped in close() in all current implementations,
// but maybe a new one will appear, and we'll forget about adding stop() there
@@ -250,7 +251,7 @@ public class OpenALAudioManager implements AudioManager {
@Override
public void tick() {
ensureOpen();
ensureContext();
alcMakeContextCurrent(alcContext);
for (BaseSoundSource<?> source : sources.values()) {
if (source.getALState() == PLAYING) source.tick();
}
@@ -261,6 +262,7 @@ public class OpenALAudioManager implements AudioManager {
*/
@Override
public void close() {
alcMakeContextCurrent(alcContext);
parsedSounds.values().forEach(ParsedSoundImpl::close);
parsedSounds.clear();
sources.values().forEach(BaseSoundSource::close);
@@ -285,12 +287,6 @@ public class OpenALAudioManager implements AudioManager {
}
}
private void ensureContext() {
if (alcContext != NULL && alcGetCurrentContext() == NULL) {
alcMakeContextCurrent(alcContext);
}
}
private ParsedSoundImpl getParsedSound(Path path) {
if (hasLoadedSound(path)) {
return parsedSounds.get(path);
@@ -1,6 +1,7 @@
package ru.fokinatorr.sparkle.audio.impl;
package net.fokinatorr.sparkle.audio.impl;
import lombok.experimental.UtilityClass;
import net.fokinatorr.sparkle.effect.sounds.SoundEffect;
/**
* Sound effect value conversion utils.
@@ -29,7 +30,7 @@ class PitchConversion {
private final double LOG_TO_PITCH_SCALE = Math.log(2) / STEPS_PER_OCTAVE;
/**
* Converts the given {@link ru.fokinatorr.sparkle.effect.sounds.SoundEffect#PITCH pitch sound effect} value to a valid OpenAL pitch.
* Converts the given {@link SoundEffect#PITCH pitch sound effect} value to a valid OpenAL pitch.
* @param pitch the pitch effect value
* @return the corresponding OpenAL pitch value
* @throws IllegalArgumentException if the given argument is infinite or NaN
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.audio.impl;
package net.fokinatorr.sparkle.audio.impl;
import lombok.AccessLevel;
import lombok.Getter;
@@ -7,11 +7,12 @@ import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
//import lombok.extern.lwjgl.ALCheckError;
import lombok.extern.slf4j.Slf4j;
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.nio.ShortBuffer;
import java.util.Objects;
import static org.lwjgl.openal.ALC10.alcMakeContextCurrent;
import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*;
import static org.lwjgl.system.MemoryUtil.*;
@@ -22,6 +23,12 @@ import static org.lwjgl.system.MemoryUtil.*;
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
//@ALCheckError
public class SoundBuffer implements NonThrowingAutoCloseable {
/**
* The OpenAL context handle.
*/
@Getter
long alcContext;
/**
* The OpenAL buffer ID.
*/
@@ -39,7 +46,9 @@ public class SoundBuffer implements NonThrowingAutoCloseable {
* @param frequency the data frequency, in Hz
* @throws NullPointerException if any argument is {@code null}
*/
public SoundBuffer(ShortBuffer pcmData, DataFormat format, int frequency) {
public SoundBuffer(long alcContext, ShortBuffer pcmData, DataFormat format, int frequency) {
alcMakeContextCurrent(alcContext);
this.alcContext = alcContext;
this.bufferId = alGenBuffers();
this.pcm = memDuplicate(Objects.requireNonNull(pcmData, "PCM data"));
alBufferData(
@@ -66,6 +75,7 @@ public class SoundBuffer implements NonThrowingAutoCloseable {
@Override
public void close() {
if (open) {
alcMakeContextCurrent(alcContext);
try {
alDeleteBuffers(bufferId);
} finally {
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.audio.impl;
package net.fokinatorr.sparkle.audio.impl;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
@@ -6,6 +6,7 @@ import lombok.experimental.FieldDefaults;
import java.util.Objects;
import static org.lwjgl.openal.ALC10.alcMakeContextCurrent;
import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*;
/**
@@ -25,7 +26,8 @@ public class StaticSoundSource extends BaseSoundSource<StaticSoundSource> {
* @throws NullPointerException if the buffer is {@code null}
*/
public StaticSoundSource(SoundBuffer buffer) {
super(alGenSources());
alcMakeContextCurrent(buffer.getAlcContext());
super(buffer.getAlcContext(), alGenSources());
this.buffer = Objects.requireNonNull(buffer);
alSourcei(sourceId, AL_BUFFER, buffer.getBufferId());
}
@@ -48,6 +50,7 @@ public class StaticSoundSource extends BaseSoundSource<StaticSoundSource> {
* @return this sound source
*/
public StaticSoundSource looping(boolean newLooping) {
alcMakeContextCurrent(alcContext);
alSourcei(sourceId, AL_LOOPING, newLooping ? AL_TRUE : AL_FALSE);
return this;
}
@@ -59,6 +62,7 @@ public class StaticSoundSource extends BaseSoundSource<StaticSoundSource> {
* @return whether this sound source is looping
*/
public boolean looping() {
alcMakeContextCurrent(alcContext);
return alGetSourcei(sourceId, AL_LOOPING) == AL_TRUE;
}
@@ -68,6 +72,7 @@ public class StaticSoundSource extends BaseSoundSource<StaticSoundSource> {
@Override
public void close() {
if (open) {
alcMakeContextCurrent(alcContext);
stop();
try {
alDeleteSources(sourceId);
@@ -1,20 +1,23 @@
package ru.fokinatorr.sparkle.audio.impl;
package net.fokinatorr.sparkle.audio.impl;
import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
//import lombok.extern.lwjgl.ALCheckError;
import ru.fokinatorr.sparkle.audio.impl.bufferprovider.*;
import net.fokinatorr.sparkle.audio.impl.bufferprovider.IterableSoundBufferProvider;
import net.fokinatorr.sparkle.audio.impl.bufferprovider.SamplesSoundBufferProvider;
import net.fokinatorr.sparkle.audio.impl.bufferprovider.SoundBufferProvider;
import java.nio.IntBuffer;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Stream;
import static org.lwjgl.openal.ALC10.alcMakeContextCurrent;
import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*;
import static org.lwjgl.system.MemoryUtil.memAllocInt;
import static ru.fokinatorr.sparkle.util.BufferUtils.*;
import static net.fokinatorr.sparkle.util.BufferUtils.*;
/**
* Manages a streaming OpenAL sound source. The buffers should be queued.
@@ -49,8 +52,9 @@ public class StreamingSoundSource extends BaseSoundSource<StreamingSoundSource>
* @param provider the provider to use for getting buffers
* @throws NullPointerException if the given buffer array is {@code null}
*/
public StreamingSoundSource(SoundBufferProvider provider, int enqueueStart) {
super(alGenSources());
public StreamingSoundSource(long alcContext, SoundBufferProvider provider, int enqueueStart) {
alcMakeContextCurrent(alcContext);
super(alcContext, alGenSources());
this.provider = provider;
this.bufferItr = provider.iterator();
this.enqueueStart = enqueueStart;
@@ -74,6 +78,7 @@ public class StreamingSoundSource extends BaseSoundSource<StreamingSoundSource>
.filter(Objects::nonNull)
.toArray(SoundBuffer[]::new);
if (queue.length > 0) {
alcMakeContextCurrent(alcContext);
alSourceQueueBuffers(sourceId,
Arrays.stream(queue)
.peek(buf -> bufferQueue.put(buf.getBufferId(), buf))
@@ -94,6 +99,7 @@ public class StreamingSoundSource extends BaseSoundSource<StreamingSoundSource>
private SoundBuffer[] dequeueBuffers(int count) {
IntBuffer bufferIds = memAllocInt(count);
try (var _ = freeing(bufferIds)) {
alcMakeContextCurrent(alcContext);
alSourceUnqueueBuffers(sourceId, bufferIds);
return stream(bufferIds)
.mapToObj(bufferQueue::remove)
@@ -108,6 +114,7 @@ public class StreamingSoundSource extends BaseSoundSource<StreamingSoundSource>
@Override
public void close() {
if (open) {
alcMakeContextCurrent(alcContext);
stop();
try {
dequeueBuffers(alGetSourcei(sourceId, AL_BUFFERS_QUEUED));
@@ -149,6 +156,7 @@ public class StreamingSoundSource extends BaseSoundSource<StreamingSoundSource>
public void tick() {
super.tick();
if (--requeueWaitTicks <= 0) {
alcMakeContextCurrent(alcContext);
requeueWaitTicks = WAIT_BEFORE_UPDATE_TICKS;
dequeueBuffers(alGetSourcei(sourceId, AL_BUFFERS_PROCESSED));
//noinspection resource
@@ -1,10 +1,10 @@
package ru.fokinatorr.sparkle.audio.impl.bufferprovider;
package net.fokinatorr.sparkle.audio.impl.bufferprovider;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
import net.fokinatorr.sparkle.audio.impl.SoundBuffer;
/**
* A {@link SoundBufferProvider} backed by an {@link Iterable}.
@@ -1,11 +1,11 @@
package ru.fokinatorr.sparkle.audio.impl.bufferprovider;
package net.fokinatorr.sparkle.audio.impl.bufferprovider;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import lombok.extern.slf4j.Slf4j;
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
import net.fokinatorr.sparkle.audio.impl.SoundBuffer;
import java.nio.ShortBuffer;
import java.util.LinkedList;
@@ -22,6 +22,10 @@ import static org.lwjgl.system.MemoryUtil.memDuplicate;
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@RequiredArgsConstructor
public final class SamplesSoundBufferProvider implements SoundBufferProvider {
/**
* The ALC context handle.
*/
long alcContext; // pointer
/**
* The parsed PCM samples.
*/
@@ -72,6 +76,7 @@ public final class SamplesSoundBufferProvider implements SoundBufferProvider {
segment.put(samples.get());
}
itr.add(new SoundBuffer(
alcContext,
segment.flip(),
dataFormat,
frequency
@@ -1,8 +1,8 @@
package ru.fokinatorr.sparkle.audio.impl.bufferprovider;
package net.fokinatorr.sparkle.audio.impl.bufferprovider;
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
import ru.fokinatorr.sparkle.audio.impl.StreamingSoundSource;
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import net.fokinatorr.sparkle.audio.impl.SoundBuffer;
import net.fokinatorr.sparkle.audio.impl.StreamingSoundSource;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.util.NoSuchElementException;
@@ -1,9 +1,9 @@
package ru.fokinatorr.sparkle.audio.impl.bufferprovider;
package net.fokinatorr.sparkle.audio.impl.bufferprovider;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
import net.fokinatorr.sparkle.audio.impl.SoundBuffer;
import java.util.Iterator;
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.audio.impl.io;
package net.fokinatorr.sparkle.audio.impl.io;
import lombok.AccessLevel;
import lombok.Getter;
@@ -7,11 +7,11 @@ import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import org.lwjgl.system.MemoryUtil;
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
import ru.fokinatorr.sparkle.audio.impl.bufferprovider.SamplesSoundBufferProvider;
import ru.fokinatorr.sparkle.audio.impl.bufferprovider.SoundBufferProvider;
import ru.fokinatorr.sparkle.audio.io.ParsedSound;
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import net.fokinatorr.sparkle.audio.impl.SoundBuffer;
import net.fokinatorr.sparkle.audio.impl.bufferprovider.SamplesSoundBufferProvider;
import net.fokinatorr.sparkle.audio.impl.bufferprovider.SoundBufferProvider;
import net.fokinatorr.sparkle.audio.io.ParsedSound;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.nio.Buffer;
import java.nio.ShortBuffer;
@@ -36,6 +36,10 @@ import static org.lwjgl.system.MemoryUtil.memFree;
@Getter
public class ParsedSoundImpl implements NonThrowingAutoCloseable {
/**
* The ALC context handle.
*/
long alcContext; // pointer
/**
* The raw sound data samples.
*/
@@ -62,10 +66,11 @@ public class ParsedSoundImpl implements NonThrowingAutoCloseable {
/**
* Converts a {@link ParsedSound} record to a {@code ParsedSoundImpl} instance.
* @param alcContext the ALC context handle
* @param ps the source object
* @return a new {@code ParsedSoundImpl} instance
*/
public static ParsedSoundImpl fromPublicAPI(ParsedSound ps) {
public static ParsedSoundImpl fromPublicAPI(long alcContext, ParsedSound ps) {
Objects.requireNonNull(ps, "source object");
SoundBuffer.DataFormat format = switch (ps.dataFormat()) {
case MONO_8BIT -> SoundBuffer.DataFormat.MONO_8BIT;
@@ -74,6 +79,7 @@ public class ParsedSoundImpl implements NonThrowingAutoCloseable {
case STEREO_16BIT -> SoundBuffer.DataFormat.STEREO_16BIT;
};
return new ParsedSoundImpl(
alcContext,
ps.pcm(),
ps.freePcm(),
format,
@@ -95,7 +101,7 @@ public class ParsedSoundImpl implements NonThrowingAutoCloseable {
ShortBuffer clone = memAllocShort(orig.remaining())
.put(orig)
.flip();
return new SoundBuffer(clone, dataFormat, frequency);
return new SoundBuffer(alcContext, clone, dataFormat, frequency);
}
@@ -162,6 +168,7 @@ public class ParsedSoundImpl implements NonThrowingAutoCloseable {
break;
}
list.add(new SoundBuffer(
alcContext,
buf.flip(),
dataFormat,
frequency
@@ -179,6 +186,7 @@ public class ParsedSoundImpl implements NonThrowingAutoCloseable {
*/
public SoundBufferProvider createProvider(int maxBufferSize, boolean mustLoop) {
return new SamplesSoundBufferProvider(
alcContext,
getPcmData(),
dataFormat,
frequency,
@@ -1,9 +1,8 @@
package ru.fokinatorr.sparkle.audio.impl.io;
package net.fokinatorr.sparkle.audio.impl.io;
import org.lwjgl.stb.STBVorbisInfo;
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
import ru.fokinatorr.sparkle.audio.io.ParsedSound;
import ru.fokinatorr.sparkle.audio.io.SoundDecoder;
import net.fokinatorr.sparkle.audio.io.ParsedSound;
import net.fokinatorr.sparkle.audio.io.SoundDecoder;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.audio.io;
package net.fokinatorr.sparkle.audio.io;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
@@ -1,7 +1,7 @@
package ru.fokinatorr.sparkle.audio.io;
package net.fokinatorr.sparkle.audio.io;
import ru.fokinatorr.sparkle.context.AppContextHolder;
import ru.fokinatorr.sparkle.util.BufferUtils;
import net.fokinatorr.sparkle.context.AppContextHolder;
import net.fokinatorr.sparkle.util.BufferUtils;
import java.io.IOException;
import java.io.InputStream;
@@ -1,9 +1,9 @@
package ru.fokinatorr.sparkle.context;
package net.fokinatorr.sparkle.context;
import java.util.Collection;
import java.util.function.Function;
import java.util.function.Supplier;
import ru.fokinatorr.sparkle.util.Global;
import net.fokinatorr.sparkle.util.Global;
/**
* Represents a lightweight runtime environment for an application.
@@ -15,6 +15,7 @@ import ru.fokinatorr.sparkle.util.Global;
*/
public interface AppContext extends AutoCloseable {
// Not using Spring context; it's too heavy and loads slowly - this is unacceptable for desktop app development, especially games
// TODO add TypeReference support later?
// Accessors
@@ -1,7 +1,7 @@
package ru.fokinatorr.sparkle.context;
package net.fokinatorr.sparkle.context;
import lombok.experimental.UtilityClass;
import ru.fokinatorr.sparkle.util.Global;
import net.fokinatorr.sparkle.util.Global;
import java.util.Objects;
@@ -48,8 +48,7 @@ public class AppContextHolder {
*/
public void initContext(AppContext ctx) {
if (CONTEXT.get() == null) {
Objects.requireNonNull(ctx, "app context");
CONTEXT.set(ctx);
CONTEXT.set(Objects.requireNonNull(ctx, "app context"));
} else {
throw new IllegalStateException("AppContext is already initialized for " + Thread.currentThread());
}
@@ -1,20 +1,20 @@
package ru.fokinatorr.sparkle.context;
package net.fokinatorr.sparkle.context;
import lombok.*;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import ru.fokinatorr.sparkle.audio.AudioManager;
import ru.fokinatorr.sparkle.audio.impl.OpenALAudioManager;
import ru.fokinatorr.sparkle.audio.impl.io.VorbisSoundDecoder;
import ru.fokinatorr.sparkle.audio.io.SoundDecoder;
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import ru.fokinatorr.sparkle.graphics.GraphicsManager;
import ru.fokinatorr.sparkle.graphics.font.FontProvider;
import ru.fokinatorr.sparkle.graphics.impl.OpenGLGraphicsManager;
import ru.fokinatorr.sparkle.graphics.render.renderer.RendererRegistry;
import ru.fokinatorr.sparkle.util.GUID;
import ru.fokinatorr.sparkle.util.concurrent.ContextInheritingThreadFactory;
import ru.fokinatorr.sparkle.util.concurrent.ThreadType;
import net.fokinatorr.sparkle.audio.AudioManager;
import net.fokinatorr.sparkle.audio.impl.OpenALAudioManager;
import net.fokinatorr.sparkle.audio.impl.io.VorbisSoundDecoder;
import net.fokinatorr.sparkle.audio.io.SoundDecoder;
import net.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import net.fokinatorr.sparkle.graphics.GraphicsManager;
import net.fokinatorr.sparkle.graphics.font.FontProvider;
import net.fokinatorr.sparkle.graphics.impl.OpenGLGraphicsManager;
import net.fokinatorr.sparkle.graphics.render.renderer.RendererRegistry;
import net.fokinatorr.sparkle.util.GUID;
import net.fokinatorr.sparkle.util.concurrent.ContextInheritingThreadFactory;
import net.fokinatorr.sparkle.util.concurrent.ThreadType;
import java.lang.ref.Cleaner;
import java.lang.reflect.Modifier;
@@ -66,7 +66,6 @@ public class DefaultAppContext implements AppContext {
T result = entries.stream()
.map(e -> e.get(this))
.findFirst().orElseThrow();
log.trace("[DefaultAppContext id={}] Resolved '{}' -> {}", id, type.getSimpleName(), result);
return result;
}
@@ -81,7 +80,6 @@ public class DefaultAppContext implements AppContext {
List<T> result = entries.stream()
.map(e -> e.get(this))
.collect(Collectors.toList());
log.trace("[DefaultAppContext id={}] Resolved all '{}' -> {}", id, type.getSimpleName(), result);
return result;
}
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.effect;
package net.fokinatorr.sparkle.effect;
import it.unimi.dsi.fastutil.doubles.AbstractDoubleCollection;
import it.unimi.dsi.fastutil.doubles.AbstractDoubleIterator;
@@ -7,7 +7,7 @@ import it.unimi.dsi.fastutil.doubles.DoubleIterator;
import it.unimi.dsi.fastutil.objects.*;
import lombok.Data;
import lombok.NonNull;
import ru.fokinatorr.sparkle.util.concurrent.atomic.AtomicDoubleArray;
import net.fokinatorr.sparkle.util.concurrent.atomic.AtomicDoubleArray;
import java.util.NoSuchElementException;
import java.util.Objects;
@@ -53,7 +53,7 @@ public abstract class EffectMap<K extends NormalizableEffect> extends AbstractOb
values = new AtomicDoubleArray(effects.length);
this.effects = effects;
//noinspection unchecked
kClass = (Class<K>) effects.getClass().componentType();
kClass = (Class<K>) effects.getClass().getComponentType();
clear(); // Set all values to default
}
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.effect;
package net.fokinatorr.sparkle.effect;
/**
* An effect that supports normalizing its values.
@@ -1,11 +1,11 @@
package ru.fokinatorr.sparkle.effect.graphics;
package net.fokinatorr.sparkle.effect.graphics;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import ru.fokinatorr.sparkle.effect.NormalizableEffect;
import ru.fokinatorr.sparkle.util.Mth;
import net.fokinatorr.sparkle.effect.NormalizableEffect;
import net.fokinatorr.sparkle.util.Mth;
/**
* A graphic effect.
@@ -52,10 +52,10 @@ public enum GraphicEffect implements NormalizableEffect {
*/
BRIGHTNESS(-100, 100, false),
/**
* The opacity graphic effect.
* The fade graphic effect. {@code 0} - fully opaque, {@code 100} - fully transparent.
* <p><i>Note for Scratchers: This effect is similar to the "ghost" effect in Scratch.</i>
*/
OPACITY(0, 100, false);
FADE(0, 100, false);
/**
* The minimal value of this effect.
@@ -1,7 +1,7 @@
package ru.fokinatorr.sparkle.effect.graphics;
package net.fokinatorr.sparkle.effect.graphics;
import ru.fokinatorr.sparkle.effect.EffectMap;
import ru.fokinatorr.sparkle.graphics.render.renderer.Renderable;
import net.fokinatorr.sparkle.effect.EffectMap;
import net.fokinatorr.sparkle.graphics.render.renderer.Renderable;
/**
* An effect map that stores a {@link Renderable}'s graphic effects.
@@ -6,7 +6,7 @@ import it.unimi.dsi.fastutil.doubles.DoubleCollection;
import it.unimi.dsi.fastutil.doubles.DoubleIterator;
import it.unimi.dsi.fastutil.objects.*;
import lombok.Data;
import ru.fokinatorr.sparkle.util.concurrent.atomic.AtomicDoubleArray;
import atomic.concurrent.util.net.fokinatorr.sparkle.AtomicDoubleArray;
import java.util.Map;
import java.util.NoSuchElementException;
@@ -1,11 +1,11 @@
package ru.fokinatorr.sparkle.effect.sounds;
package net.fokinatorr.sparkle.effect.sounds;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import ru.fokinatorr.sparkle.effect.NormalizableEffect;
import ru.fokinatorr.sparkle.util.Mth;
import net.fokinatorr.sparkle.effect.NormalizableEffect;
import net.fokinatorr.sparkle.util.Mth;
/**
* A sound effect.
@@ -1,6 +1,6 @@
package ru.fokinatorr.sparkle.effect.sounds;
package net.fokinatorr.sparkle.effect.sounds;
import ru.fokinatorr.sparkle.effect.EffectMap;
import net.fokinatorr.sparkle.effect.EffectMap;
/**
* An effect map that stores sound effects.
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.event;
package net.fokinatorr.sparkle.event;
/**
* This class provides the functionality of a cancellable event.
@@ -1,10 +1,10 @@
package ru.fokinatorr.sparkle.event;
package net.fokinatorr.sparkle.event;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.Value;
import lombok.experimental.NonFinal;
import ru.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.stage.Stage;
import java.util.Objects;
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.event;
package net.fokinatorr.sparkle.event;
/**
* Represents a cancellable event.
@@ -12,8 +12,8 @@ public interface CancellableEvent extends Event {
boolean isCancelled();
/**
* Cancels this event. After that, the {@link #isCancelled()} method should not return {@code false} for this
* event instance ever again.
* Cancels this event. After that, the {@link #isCancelled()} method should never return {@code false} for this
* event instance again.
*/
void cancel();
}
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.event;
package net.fokinatorr.sparkle.event;
/**
* Marker interface for all events, like starting or keyboard/mouse events.
@@ -1,11 +1,11 @@
package ru.fokinatorr.sparkle.event;
package net.fokinatorr.sparkle.event;
import lombok.NonNull;
import java.util.Optional;
/**
* This event is fired when a message is broadcasted.
* This event is fired when a message is broadcasted (from user code).
* <p><i>Note for Scratchers: This event is similar to "when I receive </i>[ v]<i>" event in Scratch.</i>
*
* @param messageId the message's ID. Not necessary to be registered, unlike in Scratch.
@@ -17,8 +17,8 @@ public record MessageEvent(
) implements Event {
/**
* Creates a new {@code MessageEvent}. This is an alternative constructor which constructs an {@link Optional}
* by itself.
* Creates a new {@code MessageEvent}. This is an alternate constructor which constructs an {@link Optional}
* fron the given received data object.
* @param messageId the message's ID
* @param receivedData the received data; may be {@code null}
* @throws NullPointerException if message ID is {@code null}
@@ -35,4 +35,12 @@ public record MessageEvent(
public MessageEvent(String messageId) {
this(messageId, Optional.empty());
}
/**
*
* @return
*/
public boolean hasReceivedData() {
return receivedData.isPresent();
}
}
@@ -1,7 +1,7 @@
package ru.fokinatorr.sparkle.event.annotation;
package net.fokinatorr.sparkle.event.annotation;
import ru.fokinatorr.sparkle.event.Event;
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import net.fokinatorr.sparkle.event.Event;
import net.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import java.lang.annotation.*;
import java.lang.reflect.InaccessibleObjectException;
@@ -1,10 +1,10 @@
package ru.fokinatorr.sparkle.event.dispatcher;
package net.fokinatorr.sparkle.event.dispatcher;
import ru.fokinatorr.sparkle.event.Event;
import ru.fokinatorr.sparkle.event.annotation.EventListener;
import ru.fokinatorr.sparkle.event.dispatcher.impl.DefaultEventDispatcher;
import ru.fokinatorr.sparkle.event.input.MouseEvent;
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import net.fokinatorr.sparkle.event.Event;
import net.fokinatorr.sparkle.event.annotation.EventListener;
import net.fokinatorr.sparkle.event.dispatcher.impl.DefaultEventDispatcher;
import net.fokinatorr.sparkle.event.input.MouseEvent;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.lang.reflect.InaccessibleObjectException;
import java.util.concurrent.CompletableFuture;
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.event.dispatcher;
package net.fokinatorr.sparkle.event.dispatcher;
import java.util.Objects;
@@ -1,15 +1,15 @@
package ru.fokinatorr.sparkle.event.dispatcher.impl;
package net.fokinatorr.sparkle.event.dispatcher.impl;
import it.unimi.dsi.fastutil.bytes.Byte2ObjectRBTreeMap;
import it.unimi.dsi.fastutil.bytes.Byte2ObjectSortedMap;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import ru.fokinatorr.sparkle.event.Event;
import ru.fokinatorr.sparkle.event.annotation.EventListener;
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import ru.fokinatorr.sparkle.event.dispatcher.ListenerRemover;
import ru.fokinatorr.sparkle.util.concurrent.ContextInheritingThreadFactory;
import ru.fokinatorr.sparkle.util.concurrent.ThreadType;
import net.fokinatorr.sparkle.event.Event;
import net.fokinatorr.sparkle.event.annotation.EventListener;
import net.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import net.fokinatorr.sparkle.event.dispatcher.ListenerRemover;
import net.fokinatorr.sparkle.util.concurrent.ContextInheritingThreadFactory;
import net.fokinatorr.sparkle.util.concurrent.ThreadType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@@ -219,10 +219,10 @@ public class DefaultEventDispatcher implements EventDispatcher {
// If there was such a listener, call remove and then add to replace the priority
set.remove(listener);
set.add(listener);
log.info("Registered a listener for event {}: {}", eventClass.getName(), listener);
log.debug("Registered a listener for event {}: {}", eventClass.getName(), listener);
return () -> {
set.remove(listener);
log.info("Unregistered a listener for event {}: {}", eventClass.getName(), listener);
log.debug("Unregistered a listener for event {}: {}", eventClass.getName(), listener);
};
}
@@ -1,7 +1,7 @@
package ru.fokinatorr.sparkle.event.input;
package net.fokinatorr.sparkle.event.input;
import ru.fokinatorr.sparkle.event.Event;
import ru.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.event.Event;
import net.fokinatorr.sparkle.stage.Stage;
/**
* Base interface for events representing a user input (keyboard, mouse, etc.)
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.event.input;
package net.fokinatorr.sparkle.event.input;
import lombok.AccessLevel;
import lombok.Getter;
@@ -1,8 +1,7 @@
package ru.fokinatorr.sparkle.event.input;
package net.fokinatorr.sparkle.event.input;
import lombok.NonNull;
import lombok.experimental.NonFinal;
import ru.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.stage.Stage;
import java.util.Locale;
import java.util.Objects;
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.event.input;
package net.fokinatorr.sparkle.event.input;
/**
* Represents a mouse button.
@@ -1,8 +1,8 @@
package ru.fokinatorr.sparkle.event.input;
package net.fokinatorr.sparkle.event.input;
import lombok.NonNull;
import ru.fokinatorr.sparkle.phys2d.Point2D;
import ru.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.phys2d.Point2D;
import net.fokinatorr.sparkle.stage.Stage;
import java.util.Collections;
import java.util.EnumSet;
@@ -23,13 +23,13 @@ public sealed interface MouseEvent extends InputEvent
Stage stage();
/**
* Returns the X coordinate on the stage where this event was performed.
* Returns the X coordinate on the stage where this event was performed. {@code 0} is leftmost coordinate.
* @return the X coordinate
*/
double x();
/**
* Returns the Y coordinate on the stage where this event was performed.
* Returns the Y coordinate on the stage where this event was performed. {@code 0} is topmost coordinate.
* @return the Y coordinate
*/
double y();
@@ -0,0 +1,32 @@
package net.fokinatorr.sparkle.event.lifecycle;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import net.fokinatorr.sparkle.event.AbstractCancellableEvent;
import net.fokinatorr.sparkle.event.lifecycle.StageStateChangeEvent.StopEvent;
import net.fokinatorr.sparkle.graphics.render.RenderingContext;
import net.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
import static lombok.AccessLevel.NONE;
/**
* This event is fired every when a {@link RenderingContext} has been <b>implicitly</b> requested to close
* (e.g. with the window's 'X' button or Alt+F4). Cancelling an instance of this event results
* in the respective context not being closed.
* <p>This event is fired before a {@link StopEvent}.
* @see RenderingContext#setShouldClose()
* @see RenderingSurface#shouldClose()
*/
@Value
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor(access = NONE)
@RequiredArgsConstructor
public class CloseRequestedEvent extends AbstractCancellableEvent {
/**
* The context for which a close was requested.
*/
RenderingContext context;
}
@@ -1,8 +1,8 @@
package ru.fokinatorr.sparkle.event.lifecycle;
package net.fokinatorr.sparkle.event.lifecycle;
import lombok.Value;
import ru.fokinatorr.sparkle.event.Event;
import ru.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.event.Event;
import net.fokinatorr.sparkle.stage.Stage;
/**
* Base interface for events that are fired when a stage's state is changed.
@@ -65,7 +65,8 @@ public sealed interface StageStateChangeEvent extends Event
// There is no event for pause button; it just calls DebugUtils.debugSuspend()
/**
* This event is fired when the stop button is clicked, or
* This event is fired when the stop button is clicked, or the stage was closed.
* <p>To intercept stage closing, use {@link CloseRequestedEvent}.
*/
@Value
class StopEvent implements StageStateChangeEvent {
@@ -1,10 +1,10 @@
package ru.fokinatorr.sparkle.event.lifecycle;
package net.fokinatorr.sparkle.event.lifecycle;
import lombok.*;
import ru.fokinatorr.sparkle.event.AbstractCancellableEvent;
import ru.fokinatorr.sparkle.internal.access.EventLifecycleAccess;
import ru.fokinatorr.sparkle.internal.access.SharedSecrets;
import ru.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.event.AbstractCancellableEvent;
import net.fokinatorr.sparkle.internal.access.EventLifecycleAccess;
import net.fokinatorr.sparkle.internal.access.SharedSecrets;
import net.fokinatorr.sparkle.stage.Stage;
import static lombok.AccessLevel.NONE;
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.graphics;
package net.fokinatorr.sparkle.graphics;
import lombok.experimental.UtilityClass;
@@ -159,6 +159,17 @@ public class ARGB {
return /* 0x00000000 | */(red & 0xFF) << 16 | (green & 0xFF) << 8 | blue & 0xFF;
}
/**
* Returns a hexadecimal color notation string representation of the given color. That is,
* <pre>{@code #AARRGGBB}</pre>
* where each letter pair represents one component value in hexadecimal notation.
* @param color the color
* @return the color's string representation
*/
public String toString(int color) {
return "#%08X".formatted(color);
}
// Blending
/**
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.graphics;
package net.fokinatorr.sparkle.graphics;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@@ -15,6 +15,10 @@ import static lombok.AccessLevel.PRIVATE;
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = PRIVATE)
public enum BlendMode {
/**
* Standard blending, dependent on the graphics backend used.
*/
NORMAL((_, b)->b, BlendType.ARGB),
/**
* Sums the colors' components.
* Suitable for glow and lighting effects.
@@ -1,15 +1,13 @@
package ru.fokinatorr.sparkle.graphics;
package net.fokinatorr.sparkle.graphics;
import it.unimi.dsi.fastutil.Pair;
import ru.fokinatorr.sparkle.audio.SoundInstance;
import ru.fokinatorr.sparkle.graphics.image.Image;
import ru.fokinatorr.sparkle.graphics.render.RenderingContext;
import ru.fokinatorr.sparkle.graphics.render.surface.EmbeddedSurface;
import ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
import ru.fokinatorr.sparkle.graphics.render.surface.WindowSurface;
import ru.fokinatorr.sparkle.stage.Stage;
import ru.fokinatorr.sparkle.stage.StageCreator;
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import net.fokinatorr.sparkle.graphics.image.Image;
import net.fokinatorr.sparkle.graphics.render.RenderingContext;
import net.fokinatorr.sparkle.graphics.render.surface.EmbeddedSurface;
import net.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
import net.fokinatorr.sparkle.graphics.render.surface.WindowSurface;
import net.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.stage.StageCreator;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.nio.file.Path;
@@ -25,29 +23,33 @@ public interface GraphicsManager extends NonThrowingAutoCloseable {
/**
* Creates a new rendering context with a {@link WindowSurface} and a stage created using the given creator.
* <p>The window will be initially hidden, non-resizable and non-fullscreen in the default implementation, and have the size of the {@link Stage} created
* using the given {@link StageCreator}. The window can be shown with {@link RenderingSurface#show()}.
*
* @param title window title
* @param title initial window title
* @param stageCreator a stage creation strategy
* @return a new rendering context and a stage bound to it
* @return a new rendering context
* @throws IllegalStateException if graphics manager is closed
* @throws NullPointerException if any argument is {@code null}
*/
default Pair<Stage, RenderingContext> createWindowContext(String title, StageCreator stageCreator) {
default RenderingContext createWindowContext(String title, StageCreator stageCreator) {
return createWindowContext(title, stageCreator, false, false);
}
/**
* Creates a new rendering context with a {@link WindowSurface} and a stage created using the given creator.
* <p>The window will be initially hidden and non-resizable in the default implementation, and have the size of the {@link Stage} created
* using the given {@link StageCreator}. The window can be shown with {@link RenderingSurface#show()}.
*
* @param title window title
* @param stageCreator a stage creation strategy
* @param translucent whether the window should be transparent
* @param translucent whether the window should be transparent (not changeable after creation!)
* @param fullscreen whether the window should be fullscreen
* @return a new rendering context and a stage bound to it
* @return a new rendering context
* @throws IllegalStateException if graphics manager is closed
* @throws NullPointerException if any argument is {@code null}
*/
Pair<Stage, RenderingContext> createWindowContext(String title, StageCreator stageCreator, boolean translucent, boolean fullscreen);
RenderingContext createWindowContext(String title, StageCreator stageCreator, boolean translucent, boolean fullscreen);
/**
* Creates a new rendering context with the given embedded rendering surface and a stage created using the given creator.
@@ -55,11 +57,11 @@ public interface GraphicsManager extends NonThrowingAutoCloseable {
*
* @param surface the surface to render on
* @param stageCreator a stage creation strategy
* @return a new rendering context and a stage bound to it
* @return a new rendering context
* @throws IllegalStateException if graphics manager is closed
* @throws NullPointerException if any argument is {@code null}
*/
Pair<Stage, RenderingContext> createEmbeddedContext(EmbeddedSurface surface, StageCreator stageCreator);
RenderingContext createEmbeddedContext(EmbeddedSurface surface, StageCreator stageCreator);
/**
* Returns an existing rendering context bound to the given stage.
@@ -134,4 +136,12 @@ public interface GraphicsManager extends NonThrowingAutoCloseable {
* @throws IllegalStateException if graphics manager is closed
*/
void tick();
/**
* {@inheritDoc}
* After calling this method, the graphics manager must not be used.
* Calling this method more than once does not have any effect.
*/
@Override
void close();
}
@@ -1,14 +1,14 @@
package ru.fokinatorr.sparkle.graphics;
package net.fokinatorr.sparkle.graphics;
import ru.fokinatorr.sparkle.graphics.image.Image;
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
import ru.fokinatorr.sparkle.phys2d.Point2D;
import net.fokinatorr.sparkle.graphics.image.RasterImage;
import net.fokinatorr.sparkle.graphics.render.framebuffer.OffscreenFramebuffer;
import net.fokinatorr.sparkle.phys2d.Point2D;
/**
* Allows reading pixel data from an image/framebuffer in ARGB format.
* @see ARGB
* @see Image#createPixelReader()
* @see Framebuffer#createPixelReader()
* @see RasterImage#createPixelReader()
* @see OffscreenFramebuffer#createPixelReader()
*/
public interface PixelReader {
/**
@@ -1,15 +1,24 @@
package ru.fokinatorr.sparkle.graphics;
package net.fokinatorr.sparkle.graphics;
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
import java.awt.image.BufferedImage;
import net.fokinatorr.sparkle.graphics.render.framebuffer.OffscreenFramebuffer;
/**
* Allows modifying pixel data of an image/framebuffer in ARGB format.
* @see ARGB
* @see Framebuffer#createPixelWriter()
* @see OffscreenFramebuffer#createPixelWriter()
*/
public interface PixelWriter {
/**
* Returns the width of underlying image data.
* @return the width, always positive
*/
int getWidth();
/**
* Returns the height of underlying image data.
* @return the height, always positive
*/
int getHeight();
/**
* Sets a single pixel.
* @param x the X coordinate
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.graphics.font;
package net.fokinatorr.sparkle.graphics.font;
import it.unimi.dsi.fastutil.Pair;
import it.unimi.dsi.fastutil.objects.ObjectReferenceImmutablePair;
@@ -99,7 +99,6 @@ public class FilesystemFontProvider implements FontProvider {
Path ttfPath = baseDir.resolve(actualFamily)
.resolve(actualPosture.name().toLowerCase())
.resolve(actualWeight.name().toLowerCase() + ".ttf");
log.trace("Resolved font: {} -> {}", params, baseDir.relativize(ttfPath));
return ttfPath.toAbsolutePath();
});
}
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.graphics.font;
package net.fokinatorr.sparkle.graphics.font;
import lombok.Builder;
import lombok.NonNull;
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.graphics.font;
package net.fokinatorr.sparkle.graphics.font;
/**
* A font's postural style.
@@ -1,6 +1,6 @@
package ru.fokinatorr.sparkle.graphics.font;
package net.fokinatorr.sparkle.graphics.font;
import ru.fokinatorr.sparkle.util.Constants;
import net.fokinatorr.sparkle.util.Constants;
import java.nio.file.Path;
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.graphics.font;
package net.fokinatorr.sparkle.graphics.font;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
@@ -0,0 +1,133 @@
package net.fokinatorr.sparkle.graphics.image;
import net.fokinatorr.sparkle.graphics.GraphicsManager;
import net.fokinatorr.sparkle.graphics.render.RenderCanvas;
import java.nio.file.Path;
/**
* An immutable image that can be rendered on a canvas.
* <p>
* This interface abstracts over various image formats (raster, vector, procedural)
* and enables uniform handling across rendering pipelines. Implementations may represent:
* <ul>
* <li>Raster images (PNG, JPEG)</li>
* <li>Vector graphics (SVG)</li>
* <li>Dynamic/procedural textures</li>
* </ul>
*
* <h3>Resource Management</h3>
* Images are <b>lazy</b>: they do not load their data until {@link #prepare()} is called.
* This allows efficient handling of large or rarely used assets.
* <p>
* The image itself does <b>not</b> manage GPU resources (like textures) — that is the responsibility
* of the graphics engine.
* Therefore, implementations should not hold native GPU memory.
* <p>
* Some images, however, may hold native non-GPU memory, so they have to be unloaded manually
* once no longer used.
*
* <h3>Lifecycle</h3>
* It's best to load images through {@link GraphicsManager}'s methods for automatic resource management. If there's a need to do
* it manually, though, here's how:
* <ol>
* <li>Create image (e.g., from file or stream)</li>
* <li>Call {@link #prepare()} before drawing</li>
* <li>Draw via {@link RenderCanvas#drawImage}</li>
* <li>Call {@link #unload()} when no longer needed</li>
* </ol>
*
* <h3>Thread Safety</h3>
* Implementations must be safe to pass between threads, but are not required to support
* concurrent drawing from multiple canvases unless explicitly documented.
*
* @see RasterImage
* @see VectorImage
* @see GraphicsManager#loadImage(Path, boolean)
* @see GraphicsManager#getLoadedImage(Path)
* @see GraphicsManager#hasLoadedImage(Path)
* @see GraphicsManager#destroyImage(Path)
*/
public sealed interface Image permits RasterImage, VectorImage {
/**
* Prepares the image for rendering.
* <p>
* This may involve:
* <ul>
* <li>Lazy decoding of compressed data</li>
* <li>Rasterization of vector content</li>
* </ul>
* etc.
* Once the image is done preparing:
* <ul>
* <li>{@link #isReady()} returns {@code true}</li>
* <li>{@link #unload()} may be used to unload the data</li>
* </ul>
* <p>
* Idempotent: calling multiple times has no additional effect.
*/
void prepare();
/**
* Checks whether this image is ready to be drawn.
* <p>
* Returns {@code false} only if:
* <ul>
* <li>The image is still loading asynchronously</li>
* <li>Required resources failed to load</li>
* <li>{@link #prepare()} has never been called or hasn't been called after unloading</li>
* <li>The image has been previously unloaded with {@link #unload()}</li>
* </ul>
*
* @return true if safe to pass to {@link RenderCanvas#drawImage RenderCanvas.drawImage()}
*/
boolean isReady();
/**
* Unloads internal data associated with this image.
* <p>
* After calling this method:
* <ul>
* <li>{@link #isReady()} returns {@code false}</li>
* <li>Subsequent calls to {@link #prepare()} may reload the data</li>
* </ul>
* <p>
* Idempotent: calling multiple times has no effect.
*/
void unload();
/**
* {@return the intrinsic width of this image}
* <a id="intrinsic_size"><h2>Intrinsic Size</h2></a>
* Intrinsic size refers to the source's original dimensions. The actual dimensions are able to change depending
* on scaling and resolution. Examples:
* <ul>
* <li>Raster images have a fixed size and their intrinsic size is equal to that size;</li>
* <li>Vector images have a dynamic resolution due to vector shapes being defined as paths, but the intrinsic size is
* typically set (e.g. {@code <svg>} element has attributes "width" &amp; "height").</li>
* </ul>
* @see #getIntrinsicHeight()
*/
double getIntrinsicWidth();
/**
* {@return the intrinsic height of this image}
* See the definition of {@linkplain Image##intrinsic_size intrinsic size}.
* @see #getIntrinsicWidth()
*/
double getIntrinsicHeight();
/**
* Optional hint about the MIME type of this image.
* <p>
* Examples: {@code "image/png"}, {@code "image/svg+xml"}
* <p>
* May return {@code null} if unknown or irrelevant (e.g. procedural images).
*
* @return the MIME type, or null if unavailable
*/
default String getMimeType() {
return null;
}
}
@@ -0,0 +1,46 @@
package net.fokinatorr.sparkle.graphics.image;
import net.fokinatorr.sparkle.graphics.ARGB;
import net.fokinatorr.sparkle.graphics.PixelReader;
/**
* A raster image is an image with fixed pixel resolution (e.g. PNG, JPEG). The pixels are stored in {@linkplain ARGB}
* format.
*/
public non-sealed interface RasterImage extends Image {
/**
* Returns a pixel reader that can read this image's contents as pixels.
* The image must be {@linkplain #prepare() prepared} before calling this method.
*
* @return an object that reads this image by pixels
* @see #isReady()
* @see #prepare()
* @throws IllegalStateException if the image is not ready
*/
PixelReader createPixelReader();
/**
* Returns the intrinsic width of this image. Raster images have a fixed size,
* so it's retrieved from the image's {@linkplain #createPixelReader pixel reader}.
* <p>Note: Implementations should typically cache this value for performance.
* @return {@inheritDoc}
* @throws IllegalStateException if the image is not ready
*/
@Override
default double getIntrinsicWidth() {
return createPixelReader().getWidth();
}
/**
* Returns the intrinsic height of this image. Raster images have a fixed size,
* so it's retrieved from the image's {@linkplain #createPixelReader pixel reader}.
* <p>Note: Implementations should typically cache this value for performance.
* @return {@inheritDoc}
* @throws IllegalStateException if the image is not ready
*/
@Override
default double getIntrinsicHeight() {
return createPixelReader().getHeight();
}
}
@@ -0,0 +1,101 @@
package net.fokinatorr.sparkle.graphics.image;
import net.fokinatorr.sparkle.graphics.ARGB;
import net.fokinatorr.sparkle.graphics.PixelReader;
import net.fokinatorr.sparkle.phys2d.Point2D;
import java.awt.Shape;
import java.util.List;
import java.util.Objects;
/**
* A vector image is an image defined with vector shapes (shapes with a path), which
* means it has a variable resolution and can return different pixel data depending
* on scaling factors.
*/
public non-sealed interface VectorImage extends Image {
// This comment serves absolutely no informational purpose whatsoever and is only here to distract people for 5 seconds
// and cause minor frustration. You are free to read further now. :)
/**
* Rasterizes the vector content into a pixel grid of the given dimensions and returns a pixel reader over the grid.
* The image must be {@linkplain #prepare() prepared} before calling this method.
*
* @param dimensions the requested dimensions
* @return an object that reads this image by pixels
* @throws IllegalStateException if the image is not ready
* @see #isReady()
* @see #prepare()
*/
PixelReader createPixelReader(Point2D dimensions);
/**
* Returns a list of vectors of this vector image. The image must be {@linkplain #prepare() prepared} before calling this method.
*
* @return this image's vectors
* @throws IllegalStateException if the image is not ready
* @see #isReady()
* @see #prepare()
*/
List<Vector> getVectors();
/**
* A vector of a vector image.
*
* @param vector the path
* @param strokeARGB stroke color in {@linkplain ARGB} format
* @param fillARGB fill color in ARGB
* @param lineWidth stroke line width; if {@code 0}, not outlined
*/
record Vector(
Shape vector,
int strokeARGB,
int fillARGB,
double lineWidth
) {
/**
* @throws NullPointerException if any argument is {@code null}
* @throws IllegalArgumentException if line width is negative
*/
public Vector {
Objects.requireNonNull(vector, "vector");
if (lineWidth < 0) {
throw new IllegalArgumentException("Line width must be non-negative, found: " + lineWidth);
}
}
/**
* Creates a filled-only version of this vector.
*
* @param argb the fill color
* @return a new instance with the given style
*/
public Vector filled(int argb) {
return new Vector(vector, argb, 0, 0);
}
/**
* Creates a stroked-only version of this vector.
*
* @param argb the stroke color
* @param lineWidth the line width
* @return a new instance with the given style
*/
public Vector stroked(int argb, double lineWidth) {
return new Vector(vector, 0, argb, lineWidth);
}
/**
* Creates a stroked and filled version of this vector.
*
* @param strokeARGB the stroke color
* @param fillARGB the fill color
* @param lineWidth the line width
* @return a new instance with the given style
*/
public Vector styled(int strokeARGB, int fillARGB, double lineWidth) {
return new Vector(vector, strokeARGB, fillARGB, lineWidth);
}
}
}
@@ -1,37 +1,38 @@
package ru.fokinatorr.sparkle.graphics.image;
package net.fokinatorr.sparkle.graphics.image.impl;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import ru.fokinatorr.sparkle.graphics.ARGB;
import ru.fokinatorr.sparkle.graphics.PixelReader;
import net.fokinatorr.sparkle.graphics.PixelReader;
import net.fokinatorr.sparkle.graphics.image.RasterImage;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* A raster image is an image consisting of pixels (e.g. PNG, JPEG). The pixels
* are stored in ARGB format.
* @see ARGB
* A universal raster image implementation based on AWT's {@link BufferedImage}
* and {@link ImageIO} API.
*/
@FieldDefaults(level = AccessLevel.PRIVATE)
@RequiredArgsConstructor
public class RasterImage implements Image {
public class AWTRasterImage implements RasterImage {
/**
* Location of the image data.
*/
@NonNull final URL resource;
@NonNull
final Path resource;
volatile BufferedImage decoded;
@Override
public void prepare() {
if (decoded == null) {
try {
decoded = ImageIO.read(resource);
try (var stream = Files.newInputStream(resource)) {
decoded = ImageIO.read(stream);
} catch (IOException e) {
throw new RuntimeException("Failed to decode raster image", e);
}
@@ -45,10 +46,28 @@ public class RasterImage implements Image {
@Override
public PixelReader createPixelReader() {
prepare(); // ensure decoded in case caller forgot to prepare the image
if (decoded == null) {
throw new IllegalStateException("Image has not been prepared yet");
}
return new Reader(decoded);
}
@Override
public double getIntrinsicWidth() {
if (decoded == null) {
throw new IllegalStateException("Image has not been prepared yet");
}
return decoded.getWidth();
}
@Override
public double getIntrinsicHeight() {
if (decoded == null) {
throw new IllegalStateException("Image has not been prepared yet");
}
return decoded.getHeight();
}
@Override
public String getMimeType() {
String guessed = URLConnection.guessContentTypeFromName(resource.toString());
@@ -56,9 +75,7 @@ public class RasterImage implements Image {
}
@Override
public void close() {
// technically this class CAN be used after calling this method since there are no resources to free
// but for code architecture consistency it's not recommended
public void unload() {
decoded = null;
}
@@ -0,0 +1,192 @@
package net.fokinatorr.sparkle.graphics.image.impl;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.lwjgl.nanovg.NSVGImage;
import org.lwjgl.nanovg.NSVGPath;
import org.lwjgl.nanovg.NSVGShape;
import org.lwjgl.system.MemoryUtil;
import net.fokinatorr.sparkle.graphics.PixelReader;
import net.fokinatorr.sparkle.graphics.image.VectorImage;
import net.fokinatorr.sparkle.graphics.impl.IntBufferPixelAccessor;
import net.fokinatorr.sparkle.graphics.impl.sw.Scaling;
import net.fokinatorr.sparkle.phys2d.Point2D;
import java.awt.geom.Path2D;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.lwjgl.system.MemoryStack.stackPush;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.nanovg.NanoSVG.*;
/**
* An SVG image is a vector-based format.
* <p>
* This implementation uses native memory and has to be manually {@linkplain #unload() unloaded} once no longer needed.
*/
@FieldDefaults(level = AccessLevel.PRIVATE)
@RequiredArgsConstructor
public class SVGImage implements VectorImage {
/**
* Location of the image data.
*/
@NonNull
final Path resource;
volatile NSVGImage decoded;
volatile long rasterizer; // pointer
final Map<Point2D, IntBuffer> resolutions = HashMap.newHashMap(1);
volatile List<Vector> vectors;
@Override
public void prepare() {
if (decoded == null) {
try (
var channel = Files.newByteChannel(resource);
var stack = stackPush()
) {
long size = channel.size();
if (size == -1 || (int) ++size != size) { // add 1 to the size to allow null termination
throw new IOException("Resource too large"); // safeguard for 32-bit systems
}
ByteBuffer data = stack.malloc((int) size);
channel.read(data);
data.put((byte) 0).flip(); // null-terminate and prepare for reading
decoded = nsvgParse(data, stack.UTF8("px"), 96f);
} catch (Exception e) {
throw new RuntimeException("Failed to decode SVG image from path: " + resource, e);
}
if (decoded == null) {
throw new RuntimeException("Failed to decode SVG image from path: " + resource);
}
}
}
@Override
public boolean isReady() {
return decoded != null;
}
@Override
public PixelReader createPixelReader(Point2D dimensions) {
if (decoded == null) {
throw new IllegalStateException("Image has not been prepared yet");
}
return new IntBufferPixelAccessor(
(int) dimensions.x(), (int) dimensions.y(),
resolutions.computeIfAbsent(dimensions, this::rasterize),
() -> {
if (decoded == null) {
throw new IllegalStateException("Image has not been prepared yet");
}
}
);
}
@Override
public double getIntrinsicWidth() {
if (decoded == null) {
throw new IllegalStateException("Image has not been prepared yet");
}
return decoded.width();
}
@Override
public double getIntrinsicHeight() {
if (decoded == null) {
throw new IllegalStateException("Image has not been prepared yet");
}
return decoded.height();
}
@Override
public String getMimeType() {
return "image/svg+xml";
}
@Override
public List<Vector> getVectors() {
if (decoded == null) {
throw new IllegalStateException("Image has not been prepared yet");
}
if (vectors == null) {
vectors = new ArrayList<>();
for (NSVGShape svgShape = decoded.shapes(); svgShape != null; svgShape = NSVGShape.createSafe(memGetAddress(svgShape.address() + NSVGShape.NEXT))) {
int strokeColor = svgShape.stroke().color(); // TODO gradient support
int fillColor = svgShape.fill().color();
float lineWidth = svgShape.strokeWidth();
Path2D.Float vec = new Path2D.Float();
for (NSVGPath path = svgShape.paths(); path != null; path = NSVGPath.createSafe(memGetAddress(path.address() + NSVGPath.NEXT))) {
FloatBuffer pts = path.pts().rewind();
vec.moveTo(pts.get(), pts.get());
for (int i = 1; i < path.npts(); i += 3) { // we already read one point, and we read 3 per iteration
vec.curveTo(pts.get(), pts.get(), pts.get(), pts.get(), pts.get(), pts.get());
}
if (path.closed() != 0) vec.closePath();
}
vectors.add(new Vector(vec, strokeColor, fillColor, lineWidth));
}
}
return vectors;
}
@Override
public void unload() {
resolutions.values().forEach(MemoryUtil::memFree);
resolutions.clear();
vectors = null;
if (rasterizer != NULL) nsvgDeleteRasterizer(rasterizer);
if (decoded != null) nsvgDelete(decoded);
decoded = null;
}
// Private implementation
private IntBuffer rasterize(Point2D dim) {
if (rasterizer == NULL) {
rasterizer = nsvgCreateRasterizer();
}
float maxScale = (float) Math.max(
dim.x() / decoded.width(),
dim.y() / decoded.height()
);
int rasterWidth = (int) (decoded.width() * maxScale), rasterHeight = (int) (decoded.height() * maxScale);
ByteBuffer rasterizedBB = memAlloc((int) (rasterWidth * rasterHeight * Integer.BYTES));
try {
nsvgRasterize(
rasterizer,
decoded,
0f, 0f,
maxScale,
rasterizedBB,
rasterWidth, rasterHeight,
rasterWidth * Integer.BYTES
);
} catch (Exception e) {
memFree(rasterizedBB);
throw new RuntimeException("Failed to rasterise SVG image", e);
}
IntBuffer rasterized = rasterizedBB.asIntBuffer();
IntBuffer resized = memAllocInt((int) (dim.x() * dim.y()));
Scaling.bicubicResize(
new IntBufferPixelAccessor(rasterWidth, rasterHeight, rasterized, () -> {}),
new IntBufferPixelAccessor((int) dim.x(), (int) dim.y(), resized, () -> {})
);
memFree(rasterizedBB);
return resized;
}
}
@@ -1,26 +1,21 @@
package ru.fokinatorr.sparkle.graphics.impl;
package net.fokinatorr.sparkle.graphics.impl;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import ru.fokinatorr.sparkle.context.AppContext;
import ru.fokinatorr.sparkle.graphics.GraphicsManager;
import ru.fokinatorr.sparkle.graphics.GraphicsUtils;
import ru.fokinatorr.sparkle.graphics.PixelReader;
import ru.fokinatorr.sparkle.graphics.image.Image;
import ru.fokinatorr.sparkle.graphics.render.RenderingContext;
import ru.fokinatorr.sparkle.graphics.render.renderer.Renderer;
import ru.fokinatorr.sparkle.graphics.render.renderer.RendererRegistry;
import ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
import ru.fokinatorr.sparkle.internal.access.SharedSecrets;
import ru.fokinatorr.sparkle.internal.access.StageAccess;
import ru.fokinatorr.sparkle.phys2d.Point2D;
import ru.fokinatorr.sparkle.stage.RenderableID;
import ru.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.context.AppContext;
import net.fokinatorr.sparkle.graphics.GraphicsManager;
import net.fokinatorr.sparkle.graphics.render.RenderingContext;
import net.fokinatorr.sparkle.graphics.render.renderer.Renderer;
import net.fokinatorr.sparkle.graphics.render.renderer.RendererRegistry;
import net.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
import net.fokinatorr.sparkle.stage.RenderableID;
import net.fokinatorr.sparkle.stage.Stage;
import static lombok.AccessLevel.PROTECTED;
import static ru.fokinatorr.sparkle.graphics.render.RenderCanvas.ORIGINAL_SIZE;
import static ru.fokinatorr.sparkle.util.Constants.NANOS_PER_SECOND;
import static net.fokinatorr.sparkle.util.Constants.NANOS_PER_MILLISECOND;
import static net.fokinatorr.sparkle.util.Constants.NANOS_PER_SECOND;
import static net.fokinatorr.sparkle.util.WaitUtils.*;
/**
* Base class for rendering context implementations.
@@ -33,7 +28,7 @@ public abstract class AbstractRenderingContext implements RenderingContext {
@Getter final Stage stage;
@Getter final GraphicsManager parent;
boolean closed;
@Getter boolean closed;
@Getter double lastFPS;
long totalRenderTimeNs;
int frameCount;
@@ -53,13 +48,14 @@ public abstract class AbstractRenderingContext implements RenderingContext {
ensureOpen();
long startTimeNs = System.nanoTime();
// actual rendering
var fb = surface.acquireBuffer();
var fb = surface.acquireBuffer(stage.getWidth(), stage.getHeight());
RenderCanvasExt canvas = getCanvas();
canvas.attachTarget(fb);
canvas.clear();
renderStage();
renderStage(canvas);
canvas.flush();
surface.present(fb);
waitFor(1000 / stage.getFPSLimit() - (System.nanoTime() - startTimeNs) / NANOS_PER_MILLISECOND);
long renderTimeNs = System.nanoTime() - startTimeNs;
// statistics
@@ -78,30 +74,22 @@ public abstract class AbstractRenderingContext implements RenderingContext {
@Override
public abstract RenderCanvasExt getCanvas();
// Implementation-specific cleanup actions
protected abstract void doClose();
protected abstract boolean renderControlBar();
@SuppressWarnings("unchecked")
protected void renderStage() {
ensureOpen();
RenderCanvasExt canvas = getCanvas();
protected void renderStage(RenderCanvasExt canvas) {
stage.drawBackdrop(canvas);
// render content
RendererRegistry registry = context.get(RendererRegistry.class);
for (RenderableID<?> id : stage.getLayers()) {
Object renderable = id.getFrom(stage);
Renderer<Object> renderer = registry.get((Class<Object>) renderable.getClass());
Renderer<Object> renderer = registry.get(renderable.getClass());
if (renderer.isVisible(renderable)) {
renderer.render(renderable, canvas);
}
}
// render control bar if needed
if (renderControlBar()) {
// TODO render stage's control bar
}
}
protected void ensureOpen() {
@@ -0,0 +1,231 @@
package net.fokinatorr.sparkle.graphics.impl;
import lombok.Data;
import lombok.NonNull;
import lombok.experimental.FieldDefaults;
import net.fokinatorr.sparkle.effect.graphics.GraphicEffectMap;
import net.fokinatorr.sparkle.graphics.BlendMode;
import net.fokinatorr.sparkle.graphics.impl.TransformOp.*;
import net.fokinatorr.sparkle.graphics.render.RenderCanvas;
import java.awt.geom.AffineTransform;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Objects;
import static lombok.AccessLevel.PRIVATE;
/**
* Represents the current graphics state of a {@link RenderCanvas}.
*
* @see RenderCanvas
* @see RenderCanvas#save()
* @see RenderCanvas#restore()
*/
@FieldDefaults(level = PRIVATE)
@Data
public class GraphicsState {
Deque<TransformOp> transformStack = new LinkedList<>();
int fillARGB = 0xFF_00_00_00; // Default black
int strokeARGB = 0xFF_00_00_00; // Default black
double lineWidth = 1.0;
/**
* Unsigned byte representing the opacity multiplier.
* {@code 0} - fully transparent, {@code 255} ({@code -1}) - fully opaque.
*/
byte alpha = -1;
@NonNull
BlendMode blendMode = BlendMode.NORMAL;
@NonNull
GraphicEffectMap effects = new GraphicEffectMap();
double clipX = -1;
double clipY;
double clipW;
double clipH;
/**
* Creates a deep copy of this graphics state.
*
* @return a new {@code GraphicsState} with identical property values
*/
public GraphicsState copy() {
GraphicsState copy = new GraphicsState();
copy.transformStack = new LinkedList<>(this.transformStack);
copy.fillARGB = this.fillARGB;
copy.strokeARGB = this.strokeARGB;
copy.lineWidth = this.lineWidth;
copy.alpha = this.alpha;
copy.blendMode = this.blendMode;
copy.effects = this.effects.copy();
copy.clipX = this.clipX;
copy.clipY = this.clipY;
copy.clipW = this.clipW;
copy.clipH = this.clipH;
return copy;
}
/**
* Translates the transform by the given deltas.
* @param tx the X delta
* @param ty the Y delta
* @throws IllegalArgumentException if any argument is infinite or NaN
*/
public void translate(double tx, double ty) {
if (!Double.isFinite(tx)) {
throw new IllegalArgumentException("Translation must be finite, got: " + tx);
}
if (!Double.isFinite(ty)) {
throw new IllegalArgumentException("Translation must be finite, got: " + ty);
}
if (tx != 0 || ty != 0) {
transformStack.push(new TranslateOp2D((float) tx, (float) ty));
}
}
/**
* Rotates the transform by the given amount of degrees
* @param deg the rotation delta
* @throws IllegalArgumentException if deg is infinite, or NaN
*/
public void rotate(double deg) {
if (!Double.isFinite(deg)) {
throw new IllegalArgumentException("Rotation must be positive and finite, got: " + deg);
}
if (deg % 360 != 0) {
transformStack.push(new RotateOp2D((float) deg));
}
}
/**
* Scales the transform by the given deltas.
* @param sx the X axis scale delta
* @param sy the Y axis scale delta
* @throws IllegalArgumentException if any argument is non-positive, infinite or NaN
*/
public void scale(double sx, double sy) {
if (Math.abs(sx) == 0 || !Double.isFinite(sx)) {
throw new IllegalArgumentException("X scale must be not zero and finite, got: " + sx);
}
if (Math.abs(sy) == 0 || !Double.isFinite(sy)) {
throw new IllegalArgumentException("Y scale must be not zero and finite, got: " + sy);
}
if (sx != 1 || sy != 1) {
transformStack.push(new ScaleOp2D((float) sx, (float) sy));
}
}
/**
* Multiplies the transformation by the given matrix.
* @param at the transform matrix
* @throws NullPointerException if transform matrix is {@code null}
*/
public void mulTransform(AffineTransform at) {
Objects.requireNonNull(at, "transform matrix");
double tx = at.getTranslateX(), ty = at.getTranslateY(),
sx = at.getScaleX(), sy = at.getScaleY();
if (!Double.isFinite(tx)) {
throw new IllegalArgumentException("Translation must be finite, got: " + tx);
}
if (!Double.isFinite(ty)) {
throw new IllegalArgumentException("Translation must be finite, got: " + ty);
}
if (Math.abs(sx) == 0 || !Double.isFinite(sx)) {
throw new IllegalArgumentException("X scale must be not zero and finite, got: " + sx);
}
if (Math.abs(sy) == 0 || !Double.isFinite(sy)) {
throw new IllegalArgumentException("Y scale must be not zero and finite, got: " + sy);
}
if (!at.isIdentity()) {
transformStack.push(new MulOp2D(at));
}
}
/**
* Sets the new line width.
* @param lineWidth the new line width
* @throws IllegalArgumentException if lineWidth is non-positive, infinite, or NaN
*/
public void setLineWidth(double lineWidth) {
if (lineWidth <= 0 || !Double.isFinite(lineWidth)) {
throw new IllegalArgumentException("Line width must be positive and finite, got: " + lineWidth);
}
this.lineWidth = lineWidth;
}
/**
* Sets the X coordinate of the top-left corner of clipping region.
* @param clipX the new value
* @throws IllegalArgumentException if negative, infinite, or NaN
*/
public void setClipX(double clipX) {
if (clipX < 0 || !Double.isFinite(clipX)) {
throw new IllegalArgumentException("Clip X must be non-negative and finite, got: " + clipX);
}
this.clipX = clipX;
}
/**
* Sets the Y coordinate of the top-left corner of clipping region.
* @param clipY the new value
* @throws IllegalArgumentException if negative, infinite, or NaN
*/
public void setClipY(double clipY) {
if (clipY < 0 || !Double.isFinite(clipY)) {
throw new IllegalArgumentException("Clip Y must be non-negative and finite, got: " + clipY);
}
this.clipY = clipY;
}
/**
* Sets the width of clipping region.
* @param clipW the new value
* @throws IllegalArgumentException if non-positive, infinite, or NaN
*/
public void setClipW(double clipW) {
if (clipW <= 0 || !Double.isFinite(clipW)) {
throw new IllegalArgumentException("Clip width must be positive and finite, got: " + clipW);
}
this.clipW = clipW;
}
/**
* Sets the height of clipping region.
* @param clipH the new value
* @throws IllegalArgumentException if non-positive, infinite, or NaN
*/
public void setClipH(double clipH) {
if (clipH <= 0 || !Double.isFinite(clipH)) {
throw new IllegalArgumentException("Clip height must be positive and finite, got: " + clipH);
}
this.clipH = clipH;
}
/**
* Resets the clipping region to none.
*/
public void resetClip() {
clipX = -1;
}
/**
* {@return whether clip must be applied}
*/
public boolean hasClip() {
return clipX >= 0;
}
/**
* Checks whether this state has any non-identity transformations.
* @return true if translation, rotation, or scaling is applied
*/
public boolean hasTransform() {
return !transformStack.isEmpty();
}
}
@@ -1,9 +1,9 @@
package ru.fokinatorr.sparkle.graphics.impl;
package net.fokinatorr.sparkle.graphics.impl;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import ru.fokinatorr.sparkle.graphics.PixelReader;
import ru.fokinatorr.sparkle.graphics.PixelWriter;
import net.fokinatorr.sparkle.graphics.PixelReader;
import net.fokinatorr.sparkle.graphics.PixelWriter;
import java.nio.IntBuffer;
@@ -19,8 +19,7 @@ public class IntBufferPixelAccessor implements PixelReader, PixelWriter {
int width, height;
IntBuffer img;
Runnable ensureOpen;
// <editor-fold desc="-- PixelReader --">
@Override
public int getWidth() {
@@ -34,6 +33,8 @@ public class IntBufferPixelAccessor implements PixelReader, PixelWriter {
return height;
}
// <editor-fold desc="-- PixelReader --">
@Override
public int getARGB(int x, int y) {
ensureOpen();
@@ -1,29 +1,28 @@
package ru.fokinatorr.sparkle.graphics.impl;
package net.fokinatorr.sparkle.graphics.impl;
import it.unimi.dsi.fastutil.Pair;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
import it.unimi.dsi.fastutil.objects.ReferenceReferenceImmutablePair;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import org.lwjgl.glfw.GLFWErrorCallback;
import ru.fokinatorr.sparkle.context.AppContext;
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import ru.fokinatorr.sparkle.graphics.GraphicsManager;
import ru.fokinatorr.sparkle.graphics.image.Image;
import ru.fokinatorr.sparkle.graphics.image.RasterImage;
import ru.fokinatorr.sparkle.graphics.image.SVGImage;
import ru.fokinatorr.sparkle.graphics.impl.gl.OpenGLContext;
import ru.fokinatorr.sparkle.graphics.impl.gl.surface.GL_GLFWWindowSurface;
import ru.fokinatorr.sparkle.graphics.render.RenderingContext;
import ru.fokinatorr.sparkle.graphics.render.surface.EmbeddedSurface;
import ru.fokinatorr.sparkle.internal.access.SharedSecrets;
import ru.fokinatorr.sparkle.internal.access.StageAccess;
import ru.fokinatorr.sparkle.stage.Stage;
import ru.fokinatorr.sparkle.stage.StageCreator;
import net.fokinatorr.sparkle.context.AppContext;
import net.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import net.fokinatorr.sparkle.event.lifecycle.CloseRequestedEvent;
import net.fokinatorr.sparkle.graphics.GraphicsManager;
import net.fokinatorr.sparkle.graphics.image.Image;
import net.fokinatorr.sparkle.graphics.image.impl.AWTRasterImage;
import net.fokinatorr.sparkle.graphics.image.impl.SVGImage;
import net.fokinatorr.sparkle.graphics.impl.gl.OpenGLContext;
import net.fokinatorr.sparkle.graphics.impl.gl.surface.GL_GLFWWindowSurface;
import net.fokinatorr.sparkle.graphics.render.RenderingContext;
import net.fokinatorr.sparkle.graphics.render.surface.EmbeddedSurface;
import net.fokinatorr.sparkle.internal.access.SharedSecrets;
import net.fokinatorr.sparkle.internal.access.StageAccess;
import net.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.stage.StageCreator;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@@ -45,7 +44,8 @@ public class OpenGLGraphicsManager implements GraphicsManager {
private static final StageAccess stageAcc = SharedSecrets.getStageAccess();
@NonNull
final AppContext context;
@Getter
final AppContext appContext;
final Queue<Runnable> workQ = new ConcurrentLinkedQueue<>();
final Map<Stage, AbstractRenderingContext> renderContexts = new Reference2ReferenceOpenHashMap<>();
final Thread graphicsThread = Thread.currentThread();
@@ -60,10 +60,9 @@ public class OpenGLGraphicsManager implements GraphicsManager {
@Override
public void close() {
if (!closed) {
ensureOnCorrectThread();
renderContexts.values().forEach(AbstractRenderingContext::close);
renderContexts.clear();
images.values().forEach(Image::close);
images.values().forEach(Image::unload);
images.clear();
autoLoadImages.clear();
if (glInitialized) {
@@ -76,33 +75,33 @@ public class OpenGLGraphicsManager implements GraphicsManager {
}
@Override
public Pair<Stage, RenderingContext> createWindowContext(String title, StageCreator stageCreator, boolean translucent, boolean fullscreen) {
public RenderingContext createWindowContext(String title, StageCreator stageCreator, boolean translucent, boolean fullscreen) {
ensureOpen();
ensureOnCorrectThread();
ensureGLInitialized();
Stage stage = SharedSecrets.getStageAccess().newStage(stageCreator, context);
Stage stage = stageAcc.newStage(stageCreator, appContext);
// @formatter:off // for readability
GL_GLFWWindowSurface window = fullscreen
? GL_GLFWWindowSurface.createFullscreen(
title, glfwGetPrimaryMonitor(), translucent,
context.get(EventDispatcher.class), stage, graphicsThread
appContext.get(EventDispatcher.class), stage, graphicsThread
)
: GL_GLFWWindowSurface.create(
title, translucent,
context.get(EventDispatcher.class), stage, graphicsThread
appContext.get(EventDispatcher.class), stage, graphicsThread
);
// @formatter:on
OpenGLContext glContext = new OpenGLContext(context, window, stage, autoLoadImages, this);
OpenGLContext glContext = new OpenGLContext(appContext, window, stage, autoLoadImages, this);
renderContexts.put(stage, glContext);
return new ReferenceReferenceImmutablePair<>(stage, glContext);
stageAcc.setRenderContext(stage, glContext);
return glContext;
}
@Override
public Pair<Stage, RenderingContext> createEmbeddedContext(EmbeddedSurface surface, StageCreator stageCreator) {
public RenderingContext createEmbeddedContext(EmbeddedSurface surface, StageCreator stageCreator) {
ensureOpen();
return null;
return null; // TODO implement software rendering context
}
@Override
@@ -120,19 +119,13 @@ public class OpenGLGraphicsManager implements GraphicsManager {
public Image loadImage(Path path, boolean autoLoad) {
ensureOpen();
Image newImg;
try {
newImg = path.getFileName().toString().endsWith(".svg") // TODO more formats later
? new SVGImage(path.toUri().toURL())
: new RasterImage(path.toUri().toURL());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
// TODO more formats later
Image newImg = path.getFileName().toString().endsWith(".svg") ? new SVGImage(path) : new AWTRasterImage(path);
Image oldImg = images.put(path, newImg);
if (oldImg != null) {
autoLoadImages.remove(oldImg);
oldImg.close();
oldImg.unload();
}
if (autoLoad) autoLoadImages.add(newImg);
@@ -154,14 +147,16 @@ public class OpenGLGraphicsManager implements GraphicsManager {
public void destroyImage(Path path) {
ensureOpen();
if (images.containsKey(path)) {
images.remove(path).close();
images.remove(path).unload();
}
}
@Override
public void runLater(Runnable run) {
ensureOpen();
if (!workQ.offer(run)) {
if (Thread.currentThread() == graphicsThread) {
run.run();
} else if (!workQ.offer(run)) {
throw new IllegalStateException("Work queue overflow; cannot add more tasks");
}
}
@@ -174,18 +169,42 @@ public class OpenGLGraphicsManager implements GraphicsManager {
runTasks();
for (var renderCtx : renderContexts.values()) {
renderCtx.pollEvents();
if (!stageAcc.isSuppressRedraw(renderCtx.getStage())) {
// Check close request first to prevent window hang
if (renderCtx.shouldClose()) {
if (renderCtx.getSurface().isExplicitShouldClose()) {
// Explicit request; just close
removeAndClose(renderCtx);
} else {
// Implicit close; fire a CloseRequestedEvent if there are listeners
EventDispatcher dispatcher = appContext.get(EventDispatcher.class);
if (dispatcher.hasListenersFor(CloseRequestedEvent.class)) {
CloseRequestedEvent event = new CloseRequestedEvent(renderCtx);
dispatcher.fireEvent(event).thenRun(() -> {
// If the event wasn't cancelled, close
if (!event.isCancelled()) {
removeAndClose(renderCtx);
}
});
} else {
// Otherwise, just close
removeAndClose(renderCtx);
}
}
}
if (!stageAcc.isSuppressRedraw(renderCtx.getStage()) && renderContexts.containsValue(renderCtx)) {
renderCtx.present();
}
if (renderCtx.shouldClose()) {
renderCtx.getStage().stop().thenRun(() -> runLater(() -> {
renderCtx.close();
renderContexts.remove(renderCtx.getStage());
}));
}
}
}
private void removeAndClose(RenderingContext renderCtx) {
renderCtx.getStage().stop().thenRun(() -> {
renderContexts.remove(renderCtx.getStage());
runLater(renderCtx::close);
});
}
private void ensureOpen() {
if (closed) {
throw new IllegalStateException("This manager is closed");
@@ -204,7 +223,8 @@ public class OpenGLGraphicsManager implements GraphicsManager {
this.errorCallback = GLFWErrorCallback.createPrint(System.err).set();
if (glfwPlatformSupported(GLFW_PLATFORM_WAYLAND) || glfwPlatformSupported(GLFW_PLATFORM_X11)) {
glfwInitHint(GLFW_PLATFORM, GLFW_PLATFORM_X11); // I don't think OpenGL works on Wayland
// EGL/Wayland not supported by NVIDIA drivers; force XWayland mode for Linux Wayland sessions
glfwInitHint(GLFW_PLATFORM, GLFW_PLATFORM_X11);
}
if (!glfwInit()) {
@@ -216,9 +236,13 @@ public class OpenGLGraphicsManager implements GraphicsManager {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
glfwWindowHint(GLFW_CONTEXT_RELEASE_BEHAVIOR, GLFW_RELEASE_BEHAVIOR_NONE); // Don't share resources
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); // For macOS
glfwWindowHint(GLFW_CONTEXT_DEBUG, GLFW_TRUE);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
// GL context not created here, so no GL calls yet
glInitialized = true;
}
}
@@ -1,8 +1,7 @@
package ru.fokinatorr.sparkle.graphics.impl;
package net.fokinatorr.sparkle.graphics.impl;
import ru.fokinatorr.sparkle.graphics.image.Image;
import ru.fokinatorr.sparkle.graphics.render.RenderCanvas;
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
import net.fokinatorr.sparkle.graphics.render.RenderCanvas;
import net.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
/**
* An extensions interface for {@link RenderCanvas} providing additional methods
@@ -26,9 +25,4 @@ public interface RenderCanvasExt extends RenderCanvas {
*/
void flush();
/**
* Uploads an Image object, making it ready for rendering.
* @param image the image
*/
void uploadImage(Image image);
}
@@ -0,0 +1,135 @@
package net.fokinatorr.sparkle.graphics.impl;
import org.joml.Matrix3x2f;
import org.joml.Matrix4f;
import java.awt.geom.AffineTransform;
import java.util.Objects;
/**
* A transform operation to apply to a matrix.
* <p><i>Transform operations are value-based types; treat equal instances as interchangeable
* and don't use them wherever an identity is required (e.g. synchronization, {@link java.lang.ref.Reference} API).</i>
*/
public sealed interface TransformOp
permits TransformOp.MulOp2D, TransformOp.RotateOp2D, TransformOp.ScaleOp2D, TransformOp.TranslateOp2D {
/**
* Applies this transform operation to the given matrix.
*
* @param dest the destination matrix
*/
void apply(Matrix4f dest);
/**
* Applies this transform operation to the given {@link AffineTransform} instance.
*
* @param affine the destination object
* @throws UnsupportedOperationException if this transform is not applicable (e.g. 3D transform (affine transforms are 2D))
*/
default void apply(AffineTransform affine) {
throw new UnsupportedOperationException("Applying a non-2D transform to an AffineTransform instance");
}
/**
* Translate by the specified delta.
*
* @param tx X translation
* @param ty Y translation
*/
record TranslateOp2D(float tx, float ty) implements TransformOp {
public TranslateOp2D {
if (!(Float.isFinite(tx) && Float.isFinite(ty))) {
throw new IllegalArgumentException("Translate deltas must be finite, got: " + tx + ", " + ty);
}
}
@Override
public void apply(Matrix4f dest) {
dest.translate(tx, ty, 0);
}
@Override
public void apply(AffineTransform affine) {
affine.translate(tx, ty);
}
}
/**
* Scale by the specified delta.
*
* @param sx X scaling
* @param sy Y scaling
*/
record ScaleOp2D(float sx, float sy) implements TransformOp {
public ScaleOp2D {
if (!(sx != 0 && sy != 0 && Float.isFinite(sx) && Float.isFinite(sy))) {
throw new IllegalArgumentException("Scale factors must be finite and not 0, got: " + sx + ", " + sy);
}
}
@Override
public void apply(Matrix4f dest) {
dest.scaleXY(sx, sy);
}
@Override
public void apply(AffineTransform affine) {
affine.scale(sx, sy);
}
}
/**
* Rotate by the specified degrees.
*
* @param deg rotation degrees
*/
record RotateOp2D(float deg) implements TransformOp {
public RotateOp2D {
if (!Float.isFinite(deg)) {
throw new IllegalArgumentException("Rotation degrees must be finite, got: " + deg);
}
}
@Override
public void apply(Matrix4f dest) {
dest.rotateZ(org.joml.Math.toRadians(deg));
}
@Override
public void apply(AffineTransform affine) {
affine.rotate(org.joml.Math.toRadians(deg));
}
}
/**
* Multiply by the specified transform matrix.
* @param at the transform matrix
*/
record MulOp2D(AffineTransform at) implements TransformOp {
public MulOp2D {
Objects.requireNonNull(at, "transform matrix");
}
@Override
public void apply(Matrix4f dest) {
Matrix3x2f factor = new Matrix3x2f();
factor.m00 = (float) at.getScaleX();
factor.m10 = (float) at.getShearX();
factor.m20 = (float) at.getTranslateX();
factor.m01 = (float) at.getShearY();
factor.m11 = (float) at.getScaleY();
factor.m21 = (float) at.getTranslateY();
dest.mul(factor);
}
@Override
public void apply(AffineTransform affine) {
affine.concatenate(at);
}
}
}
@@ -0,0 +1,88 @@
package net.fokinatorr.sparkle.graphics.impl.gl;
import net.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
import java.nio.ByteBuffer;
import static org.lwjgl.opengl.GL46.*;
/**
* A wrapper for an OpenGL framebuffer.
* @param fboId the framebuffer object ID
* @param texId the bound color texture ID
* @param width the buffer width
* @param height the buffer height
*/
public record GLFramebuffer(int fboId, int texId, int width, int height) implements Framebuffer {
public GLFramebuffer {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Width and height must be positive");
}
if (fboId > 0 && texId > 0) {
glBindFramebuffer(GL_FRAMEBUFFER, fboId);
// Create texture
glBindTexture(GL_TEXTURE_2D, texId);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA,
width, height,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
(ByteBuffer) null
);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Attach to FBO
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texId, 0);
glDrawBuffers(GL_COLOR_ATTACHMENT0);
int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
String msg = switch (status) {
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT -> "Incomplete attachment";
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT -> "Missing attachment";
case GL_FRAMEBUFFER_UNSUPPORTED -> "Unsupported format";
default -> "Unknown error";
};
throw new RuntimeException("Framebuffer not complete: " + msg + " (0x" + Integer.toHexString(status).toUpperCase() + ")");
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
/**
* Uses the given FBO with the given default dimensions.
* @param fboId the existing FBO ID
* @param width the initial width
* @param height the initial height
*/
public GLFramebuffer(int fboId, int width, int height) {
this(fboId, fboId > 0 ? glGenTextures() : 0, width, height);
}
/**
* Creates a new FBO with the given default dimensions.
* @param width the initial width
* @param height the initial height
*/
public GLFramebuffer(int width, int height) {
this(glGenFramebuffers(), glGenTextures(), width, height);
}
@Override
public void close() {
if (fboId > 0) {
glDeleteFramebuffers(fboId);
glDeleteTextures(texId);
}
}
}
@@ -0,0 +1,671 @@
package net.fokinatorr.sparkle.graphics.impl.gl;
import lombok.experimental.FieldDefaults;
import org.joml.Matrix4f;
import net.fokinatorr.sparkle.effect.graphics.GraphicEffect;
import net.fokinatorr.sparkle.effect.graphics.GraphicEffectMap;
import net.fokinatorr.sparkle.graphics.ARGB;
import net.fokinatorr.sparkle.graphics.BlendMode;
import net.fokinatorr.sparkle.graphics.image.Image;
import net.fokinatorr.sparkle.graphics.image.RasterImage;
import net.fokinatorr.sparkle.graphics.image.VectorImage;
import net.fokinatorr.sparkle.graphics.impl.GraphicsState;
import net.fokinatorr.sparkle.graphics.impl.RenderCanvasExt;
import net.fokinatorr.sparkle.graphics.impl.gl.element.GLTransformedVertexArray;
import net.fokinatorr.sparkle.graphics.impl.gl.shader.GLShaderProgram;
import net.fokinatorr.sparkle.graphics.impl.gl.shader.GLShaderProgramCache;
import net.fokinatorr.sparkle.graphics.impl.gl.shader.ShaderType;
import net.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.util.*;
import static lombok.AccessLevel.PROTECTED;
import static org.lwjgl.opengl.GL46.*;
import static net.fokinatorr.sparkle.graphics.impl.gl.shader.ShaderLoader.loadShader;
import net.fokinatorr.sparkle.phys2d.Point2D;
import net.fokinatorr.sparkle.util.Mth;
/**
* An OpenGL render canvas that accepts {@link GLFramebuffer}s.
*/
@FieldDefaults(level = PROTECTED)
public class GLRenderCanvas implements RenderCanvasExt {
private static final GraphicEffectMap EMPTY = new GraphicEffectMap();
private static final Matrix4f IDENTITY_MATRIX = new Matrix4f();
final OpenGLContext parent;
final Deque<GraphicsState> stateStack = new LinkedList<>();
GraphicsState currentState = new GraphicsState();
final GLShaderProgram strokeShader;
final GLShaderProgram fillShader;
final GLShaderProgram imageShader;
final Matrix4f viewProjection = new Matrix4f();
GLFramebuffer fb;
final boolean clearWhite;
boolean closed;
public GLRenderCanvas(OpenGLContext parent, boolean clearWhite) {
this.parent = parent;
this.clearWhite = clearWhite;
parent.makeCurrent();
GLShaderProgramCache programCache = parent.getProgramCache();
// Compile shaders with error checking
strokeShader = programCache.getOrCreate("stroke", () -> GLShaderProgram.compile(Map.of(
ShaderType.VERTEX, loadShader("stroke.vert.glsl"),
// ShaderType.GEOMETRY, loadShader("stroke.geom.glsl"),
ShaderType.FRAGMENT, loadShader("stroke.frag.glsl")
)));
checkError();
fillShader = programCache.getOrCreate("fill", () -> GLShaderProgram.compile(Map.of(
ShaderType.VERTEX, loadShader("fill.vert.glsl"),
ShaderType.FRAGMENT, loadShader("fill.frag.glsl")
)));
checkError();
imageShader = programCache.getOrCreate("image", () -> GLShaderProgram.compile(Map.of(
ShaderType.VERTEX, loadShader("image.vert.glsl"),
ShaderType.FRAGMENT, loadShader("image.frag.glsl")
)));
checkError();
}
// <editor-fold desc="RenderCanvasExt methods">
@Override
public void attachTarget(Framebuffer target) {
ensureOpen();
if (!(target instanceof GLFramebuffer(int fboId, int _, int width, int height))) {
throw new IllegalArgumentException("Unsupported frame buffer type: " + target.getClass());
}
parent.makeCurrent();
checkError();
if (this.fb != null) this.fb.close();
this.fb = (GLFramebuffer) target;
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId);
checkError();
glViewport(0, 0, width, height);
checkError();
viewProjection.setOrtho2D(0, fb.width(), fb.height(), 0);
if (clearWhite) {
glClearColor(1f, 1f, 1f, 1f);
} else {
glClearColor(0f, 0f, 0f, 0f);
}
checkError();
}
@Override
public void clear() {
ensureOpen();
parent.makeCurrent();
currentState.getTransformStack().clear();
ensureDrawBufferBound();
glClear(GL_COLOR_BUFFER_BIT);
checkError();
}
@Override
public void flush() {
ensureOpen();
parent.makeCurrent();
ensureDrawBufferBound();
glFlush();
checkError();
}
// </editor-fold>
// <editor-fold desc="RenderCanvas methods">
// Drawing methods
/**
* Setup before outline operation(s)
* @return valid line width range
*/
private float[] outlineSetup() {
// Ensure that we're open and parent context is current
ensureOpen();
parent.makeCurrent();
ensureDrawBufferBound();
float[] lineWidthRange = {1, 1};
glGetFloatv(GL_SMOOTH_LINE_WIDTH_RANGE, lineWidthRange);
strokeShader.use();
checkError();
applyBlendFunc();
applyClip();
return lineWidthRange;
}
/**
* {@link #outlineSetup()} must be called before calling this method
*/
private void doOutline(GLTransformedVertexArray outlineVAO, float[] lineWidthRange) {
outlineVAO.bind();
buildTransformMatrix(outlineVAO.getTransform());
outlineVAO.setDirtyTransform();
// Set up vertex attributes & shader uniforms
int strokeARGB = currentState.getStrokeARGB();
float
a = byteToFloat(ARGB.alpha(strokeARGB)) * byteToFloat(currentState.getAlpha()),
r = byteToFloat(ARGB.red(strokeARGB)),
g = byteToFloat(ARGB.green(strokeARGB)),
b = byteToFloat(ARGB.blue(strokeARGB));
GraphicEffectMap effects = currentState.getEffects();
strokeShader
.setUniform("u_Proj", viewProjection)
.setUniform("u_Model", outlineVAO.getTotalTransform())
.setUniform("u_Color", r, g, b, a)
.setUniform("u_HueShift", (float) effects.getDouble(GraphicEffect.HUE_SHIFT))
.setUniform("u_Brightness", (float) effects.getDouble(GraphicEffect.BRIGHTNESS) / 100f)
.setUniform("u_Opacity", 1 - (float) effects.getDouble(GraphicEffect.FADE) / 100f);
checkError();
// Draw
glLineWidth((float) Mth.clamp(currentState.getLineWidth(), lineWidthRange[0], lineWidthRange[1]));
checkError();
glDrawArrays(GL_LINE_STRIP, 0, outlineVAO.getVertexArray().getVertexCount());
checkError();
}
/**
* Cleanup after outline operation(s)
*/
private void outlineTeardown() {
GLTransformedVertexArray.unbind();
strokeShader.unuse(true);
checkError();
}
@Override
public void drawShape(Shape shape) {
float[] lineWidthRange = outlineSetup();
for (GLTransformedVertexArray outlineVAO : parent.getVaoCache().outline(shape)) {
doOutline(outlineVAO, lineWidthRange);
}
outlineTeardown();
}
@Override
public void drawRect(double x, double y, double w, double h) {
float[] lineWidthRange = outlineSetup();
doOutline(parent.getVaoCache().rect((float) x, (float) y, (float) w, (float) h), lineWidthRange);
outlineTeardown();
}
@Override
public void drawOval(double x, double y, double w, double h) {
float[] lineWidthRange = outlineSetup();
doOutline(parent.getVaoCache().oval((float) x, (float) y, (float) w, (float) h), lineWidthRange);
outlineTeardown();
}
@Override
public void drawLine(double x1, double y1, double x2, double y2) {
float[] lineWidthRange = outlineSetup();
doOutline(parent.getVaoCache().line((float) x1, (float) y1, (float) x2, (float) y2), lineWidthRange);
outlineTeardown();
}
// Filling methods
/**
* Setup before fill operation(s)
*/
private void fillSetup() {
// Ensure we're open and parent context is current
ensureOpen();
parent.makeCurrent();
checkError();
ensureDrawBufferBound();
fillShader.use();
checkError();
applyBlendFunc();
applyClip();
}
/**
* {@link #fillSetup()} must be called before calling this method
*/
private void doFill(GLTransformedVertexArray fillVAO, boolean triangleFan) {
fillVAO.bind();
buildTransformMatrix(fillVAO.getTransform());
fillVAO.setDirtyTransform();
int fillARGB = currentState.getFillARGB();
float
a = byteToFloat(ARGB.alpha(fillARGB)) * byteToFloat(currentState.getAlpha()),
r = byteToFloat(ARGB.red(fillARGB)),
g = byteToFloat(ARGB.green(fillARGB)),
b = byteToFloat(ARGB.blue(fillARGB));
GraphicEffectMap effects = currentState.getEffects();
fillShader
.setUniform("u_Proj", viewProjection)
.setUniform("u_Model", fillVAO.getTotalTransform())
.setUniform("u_Color", r, g, b, a)
.setUniform("u_HueShift", (float) effects.getDouble(GraphicEffect.HUE_SHIFT))
.setUniform("u_Brightness", (float) effects.getDouble(GraphicEffect.BRIGHTNESS) / 100f)
.setUniform("u_Opacity", 1 - (float) effects.getDouble(GraphicEffect.FADE) / 100f);
checkError();
if (triangleFan) {
glDrawArrays(GL_TRIANGLE_FAN, 0, fillVAO.getVertexArray().getVertexCount());
} else {
glDrawElements(GL_TRIANGLES, fillVAO.getVertexArray().getIndexCount(), GL_UNSIGNED_INT, 0);
}
checkError();
}
/**
* Cleanup after outline operation(s)
*/
private void fillTeardown() {
GLTransformedVertexArray.unbind();
fillShader.unuse(true);
checkError();
}
@Override
public void fillShape(Shape shape) {
// First fill...
fillSetup();
for (GLTransformedVertexArray fillVAO : parent.getVaoCache().triangulate(shape)) {
doFill(fillVAO, false);
}
fillTeardown();
// ...then outline
float[] lineWidthRange = outlineSetup();
for (GLTransformedVertexArray outlineVAO : parent.getVaoCache().outline(shape)) {
doOutline(outlineVAO, lineWidthRange);
}
outlineTeardown();
}
@Override
public void fillRect(double x, double y, double w, double h) {
fillSetup();
GLTransformedVertexArray rect = parent.getVaoCache().rect((float) x, (float) y, (float) w, (float) h);
doFill(rect, false);
fillTeardown();
float[] lineWidthRange = outlineSetup();
doOutline(rect, lineWidthRange);
outlineTeardown();
}
@Override
public void fillOval(double x, double y, double w, double h) {
fillSetup();
GLTransformedVertexArray oval = parent.getVaoCache().oval((float) x, (float) y, (float) w, (float) h);
doFill(oval, true);
fillTeardown();
float[] lineWidthRange = outlineSetup();
doOutline(oval, lineWidthRange);
outlineTeardown();
}
// Image drawing
@Override
public void drawImage(Image image, double x, double y, double w, double h) {
ensureOpen();
// sanity checks
if (!Double.isFinite(x)) {
throw new IllegalArgumentException("X coordinate must be finite, found: " + x);
}
if (!Double.isFinite(y)) {
throw new IllegalArgumentException("Y coordinate must be finite, found: " + y);
}
if (w == ORIGINAL_SIZE || h == ORIGINAL_SIZE) {
if (!image.isReady()) image.prepare();
if (w == ORIGINAL_SIZE) w = image.getIntrinsicWidth();
if (h == ORIGINAL_SIZE) h = image.getIntrinsicHeight();
}
if (!Double.isFinite(w) || w <= 0) {
throw new IllegalArgumentException("Width must be finite and positive, found: " + w);
}
if (!Double.isFinite(h) || h <= 0) {
throw new IllegalArgumentException("Height must be finite and positive, found: " + h);
}
if (image instanceof RasterImage raster) {
drawUploadedImage(parent.getTextureCache().getOrUploadRaster(raster), x, y, w, h);
} else if (image instanceof VectorImage vector) {
drawUploadedImage(parent.getTextureCache().getOrUploadVector(vector, new Point2D(w, h)), x, y, w, h);
}
}
/**
* Draws a texture that's already uploaded to GPU memory.
* @param textureId the GL texture name
*/
void drawUploadedImage(int textureId, double x, double y, double w, double h) {
parent.makeCurrent();
checkError();
ensureDrawBufferBound();
GLTransformedVertexArray imageVAO = parent.getVaoCache().rectImg((float) x, (float) y, (float) w, (float) h);
imageVAO.bind();
checkError();
buildTransformMatrix(imageVAO.getTransform());
imageVAO.setDirtyTransform();
// === 1. Bind Texture ===
glActiveTexture(GL_TEXTURE0);
checkError();
glBindTexture(GL_TEXTURE_2D, textureId);
checkError();
// === 2. Use Image Shader Program ===
imageShader.use();
checkError();
// === 3. Set Uniforms ===
imageShader
.setUniform("u_Proj", viewProjection)
.setUniform("u_Model", imageVAO.getTotalTransform())
.setUniform("u_Texture", 0) // sampler2D 0 <-> GL_TEXTURE0, current active texture unit
.setUniform("u_Alpha", byteToFloat(currentState.getAlpha()));
checkError();
// Apply blend mode and clip
applyBlendFunc();
applyClip();
// Pass graphic effects
GraphicEffectMap effects = currentState.getEffects();
imageShader
.setUniform("u_HueShift", (float) effects.getDouble(GraphicEffect.HUE_SHIFT))
.setUniform("u_Bulge", (float) effects.getDouble(GraphicEffect.BULGE)) // bulge coefficient
.setUniform("u_Whirl", (float) effects.getDouble(GraphicEffect.WHIRL)) // whirl coefficient: 0 - none, negative - whirl clockwise, positive - counter-clockwise
.setUniform("u_SkewX", (float) effects.getDouble(GraphicEffect.SKEW_X)) // skew angle: 0 - none, negative - left, positive - right
.setUniform("u_SkewY", (float) effects.getDouble(GraphicEffect.SKEW_Y)) // skew angle: 0 - none, negative - left, positive - right
.setUniform("u_Mosaic", (float) effects.getDouble(GraphicEffect.MOSAIC))
.setUniform("u_Brightness", (float) effects.getDouble(GraphicEffect.BRIGHTNESS) / 100f)
.setUniform("u_Opacity", 1 - (float) effects.getDouble(GraphicEffect.FADE) / 100f)
.setUniform("u_Pixelation", (float) effects.getDouble(GraphicEffect.PIXELATION));
checkError();
// === 4. Draw Quad ===
glDrawElements(GL_TRIANGLES, imageVAO.getVertexArray().getIndexCount(), GL_UNSIGNED_INT, 0);
checkError();
// === 5. Cleanup ===
GLTransformedVertexArray.unbind();
imageShader.unuse(true);
checkError();
}
@Override
public GLSubCanvas createSubCanvas(double width, double height) {
ensureOpen();
parent.makeCurrent();
checkError();
Point2D dim = getDimensions();
if (width > dim.x() || height > dim.y()) {
throw new IllegalArgumentException("Width and height of a sub-canvas can't be greater than the original");
}
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Width and height of a sub-canvas most be positive");
}
GLSubCanvas renderCanvas = new GLSubCanvas(this);
renderCanvas.attachTarget(new GLFramebuffer((int) width, (int) height));
renderCanvas.clear();
return renderCanvas;
}
// Current state management
@Override
public void translate(double dx, double dy) {
currentState.translate(dx, dy);
}
@Override
public void rotate(double degrees) {
currentState.rotate(degrees);
}
@Override
public void scale(double sx, double sy) {
currentState.scale(sx, sy);
}
@Override
public void mulTransform(AffineTransform at) {
currentState.mulTransform(at);
}
@Override
public void setFillARGB(int argb) {
currentState.setFillARGB(argb);
}
@Override
public void setStrokeARGB(int argb) {
currentState.setStrokeARGB(argb);
}
@Override
public void setLineWidth(double width) {
currentState.setLineWidth(width);
}
@Override
public void setAlpha(byte alpha) {
currentState.setAlpha(alpha);
}
@Override
public void setBlendMode(BlendMode mode) {
currentState.setBlendMode(mode);
}
@Override
public void setEffects(GraphicEffectMap effects) {
currentState.setEffects(effects);
}
@Override
public void clip(double x, double y, double w, double h) {
if (!Double.isFinite(x)) {
throw new IllegalArgumentException("X coordinate must be finite, found: " + x);
}
if (!Double.isFinite(y)) {
throw new IllegalArgumentException("Y coordinate must be finite, found: " + y);
}
if (!Double.isFinite(w) || w <= 0) {
throw new IllegalArgumentException("Width must be finite and positive, found: " + w);
}
if (!Double.isFinite(h) || h <= 0) {
throw new IllegalArgumentException("Height must be finite and positive, found: " + h);
}
currentState.setClipX(x);
currentState.setClipY(y);
currentState.setClipW(w);
currentState.setClipH(h);
}
@Override
public void resetClip() {
currentState.resetClip();
}
@Override
public void save() {
stateStack.push(currentState.copy());
}
@Override
public void restore() {
if (!stateStack.isEmpty()) {
currentState = stateStack.pop();
}
}
@Override
public void setIdentity() {
currentState.getTransformStack().clear();
currentState.setFillARGB(0xFF_00_00_00);
currentState.setStrokeARGB(0xFF_00_00_00);
currentState.setLineWidth(1);
currentState.setAlpha((byte) 255);
currentState.setBlendMode(BlendMode.NORMAL);
currentState.setEffects(EMPTY);
currentState.resetClip();
}
// Other
@Override
public Point2D getDimensions() {
ensureOpen();
if (fb == null) {
throw new IllegalStateException("No buffer attached");
}
return fb.getDimensions();
}
@Override
public OpenGLContext getContext() {
return parent;
}
@Override
public void close() {
if (!closed) {
if (fb != null) {
fb.close();
fb = null;
}
closed = true;
}
}
// </editor-fold>
// Private implementation
private void applyBlendFunc() {
switch (currentState.getBlendMode()) {
case NORMAL -> {
// Standard alpha compositing
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBlendEquation(GL_FUNC_ADD);
}
case ADD -> {
// Sum all components
glBlendFunc(GL_ONE, GL_ONE);
glBlendEquation(GL_FUNC_ADD);
}
case BLEND_SUBTRACT -> {
// Subtract all components
glBlendFunc(GL_ONE, GL_ONE);
glBlendEquation(GL_FUNC_SUBTRACT);
}
case RGB_SUBTRACT -> {
// Subtract RGB components, sum alpha components
glBlendFunc(GL_ONE, GL_ONE);
glBlendEquationSeparate(GL_FUNC_SUBTRACT, GL_FUNC_ADD);
}
case BLEND_MULTIPLY -> {
// Multiply all components
glBlendFunc(GL_DST_COLOR, GL_ZERO);
glBlendEquation(GL_FUNC_ADD);
}
case RGB_MULTIPLY -> {
// Multiply RGB components, sum alpha components
glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ONE, GL_ONE);
glBlendEquation(GL_FUNC_ADD);
}
}
checkError();
}
private void applyClip() {
if (currentState.hasClip()) {
glScissor(
(int) currentState.getClipX(),
(int) currentState.getClipY(),
(int) currentState.getClipW(),
(int) currentState.getClipH()
);
checkError();
}
}
private void ensureDrawBufferBound() {
ensureBufferBound(true);
}
protected void ensureBufferBound(boolean draw) {
if (fb == null) {
throw new IllegalStateException("No framebuffer attached");
}
glBindFramebuffer(draw ? GL_DRAW_FRAMEBUFFER : GL_READ_FRAMEBUFFER, fb.fboId());
checkError();
glViewport(0, 0, fb.width(), fb.height());
checkError();
}
protected static void checkError() {
int error = glGetError();
if (error != GL_NO_ERROR) {
throw new RuntimeException("OpenGL error: 0x" + Integer.toHexString(error).toUpperCase());
}
}
private Matrix4f buildTransformMatrix() {
if (!currentState.hasTransform()) return IDENTITY_MATRIX;
Matrix4f mat = new Matrix4f();
buildTransformMatrix(mat);
return mat;
}
private void buildTransformMatrix(Matrix4f dest) {
dest.identity();
if (currentState.hasTransform()) {
// Deque.push prepends elements, so we just iterate normally to get reverse transform order
currentState.getTransformStack().forEach(op -> op.apply(dest));
}
}
/**
* Converts a color component from unsigned byte (0 - 255) to float (0.0 - 1.0).
*
* @param b the color component
*/
private static float byteToFloat(byte b) {
return Byte.toUnsignedInt(b) / 255f;
}
protected void ensureOpen() {
if (closed) {
throw new IllegalStateException("This canvas is closed");
}
}
}
@@ -0,0 +1,65 @@
package net.fokinatorr.sparkle.graphics.impl.gl;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import static org.lwjgl.opengl.GL46.*;
import static lombok.AccessLevel.PRIVATE;
/**
* An OpenGL sub-canvas.
*/
@Slf4j
@FieldDefaults(makeFinal = true, level = PRIVATE)
public class GLSubCanvas extends GLRenderCanvas {
public GLSubCanvas(GLRenderCanvas parentCanvas) {
super(parentCanvas.getContext(), false);
this.parentCanvas = parentCanvas;
}
GLRenderCanvas parentCanvas;
@Override
public boolean isSubCanvas() {
return true;
}
@Override
public void submitImage(double x, double y, double w, double h) {
ensureOpen();
if (!Double.isFinite(x)) {
throw new IllegalArgumentException("X coordinate must be finite, found: " + x);
}
if (!Double.isFinite(y)) {
throw new IllegalArgumentException("Y coordinate must be finite, found: " + y);
}
if (w == ORIGINAL_SIZE) w = fb.width();
if (h == ORIGINAL_SIZE) h = fb.height();
if (!Double.isFinite(w) || w <= 0) {
throw new IllegalArgumentException("Width must be finite and positive, found: " + w);
}
if (!Double.isFinite(h) || h <= 0) {
throw new IllegalArgumentException("Height must be finite and positive, found: " + h);
}
if (fb.fboId() == 0) {
// should not happen
throw new IllegalStateException("Can't get texture of default framebuffer");
}
parent.makeCurrent();
flush();
ensureBufferBound(false);
parentCanvas.drawUploadedImage(fb.texId(), x, y, w, h);
}
@Override
protected void ensureBufferBound(boolean draw) {
super.ensureBufferBound(draw);
if (draw) {
glBindTexture(GL_TEXTURE_2D, fb.texId());
}
}
}
@@ -0,0 +1,136 @@
package net.fokinatorr.sparkle.graphics.impl.gl;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GLCapabilities;
import org.slf4j.event.Level;
import net.fokinatorr.sparkle.context.AppContext;
import net.fokinatorr.sparkle.graphics.image.Image;
import net.fokinatorr.sparkle.graphics.image.RasterImage;
import net.fokinatorr.sparkle.graphics.impl.AbstractRenderingContext;
import net.fokinatorr.sparkle.graphics.impl.OpenGLGraphicsManager;
import net.fokinatorr.sparkle.graphics.impl.gl.element.GLTextureCache;
import net.fokinatorr.sparkle.graphics.impl.gl.element.GLVertexArrayCache;
import net.fokinatorr.sparkle.graphics.impl.gl.shader.GLShaderProgramCache;
import net.fokinatorr.sparkle.graphics.impl.gl.surface.GL_GLFWWindowSurface;
import net.fokinatorr.sparkle.stage.Stage;
import java.util.Set;
import static lombok.AccessLevel.PRIVATE;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL46.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* An OpenGL rendering context bound to a GLFW window.
* <p>
* This context uses the GLFW window's OpenGL context for rendering.
*/
@Slf4j
@FieldDefaults(makeFinal = true, level = PRIVATE)
@Getter
public class OpenGLContext extends AbstractRenderingContext {
long glfwWindow; // pointer
Set<Image> autoLoadImages;
GLCapabilities caps;
GLRenderCanvas canvas;
GLVertexArrayCache vaoCache;
GLShaderProgramCache programCache;
GLTextureCache textureCache;
public OpenGLContext(AppContext context,
GL_GLFWWindowSurface surface, Stage stage,
Set<Image> autoLoadImages,
OpenGLGraphicsManager parent) {
super(context, surface, stage, parent);
this.glfwWindow = surface.getGlfwWindow();
this.autoLoadImages = autoLoadImages;
this.vaoCache = new GLVertexArrayCache(context, this);
this.programCache = new GLShaderProgramCache(this);
this.textureCache = new GLTextureCache(context, this);
makeCurrent();
caps = GL.createCapabilities(true);
if (!caps.OpenGL46) {
throw new IllegalStateException("OpenGL 4.6 required but not supported");
}
for (Image img : autoLoadImages) {
if (img instanceof RasterImage raster) textureCache.getOrUploadRaster(raster);
}
String windowPtrString = "0x" + Long.toHexString(glfwWindow).toUpperCase();
glfwSwapInterval(1); // V-sync
glEnable(GL_BLEND);
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback((source, _, _, severity, length, messagePtr, _) -> {
Level logLevel = switch (severity) {
case GL_DEBUG_SEVERITY_HIGH -> Level.ERROR;
case GL_DEBUG_SEVERITY_MEDIUM -> Level.WARN;
default -> Level.DEBUG;
};
String message = memUTF8(messagePtr, length);
String sourceStr = switch (source) {
case GL_DEBUG_SOURCE_API -> "OpenGL API";
case GL_DEBUG_SOURCE_WINDOW_SYSTEM -> "GLFW";
case GL_DEBUG_SOURCE_APPLICATION -> "application";
case GL_DEBUG_SOURCE_SHADER_COMPILER -> "shader compiler";
default -> "<unknown>";
};
log.atLevel(logLevel).log("[{} on context {}] {}", sourceStr, windowPtrString, message);
}, NULL);
glDisable(GL_LINE_SMOOTH);
this.canvas = new GLRenderCanvas(this, !surface.isTranslucent());
glFinish(); // wait for GPU initialization
log.debug("Initialized OpenGL context version {}", glGetString(GL_VERSION));
log.debug("\tGL Renderer: {}", glGetString(GL_RENDERER));
log.debug("\tGL Vendor: {}", glGetString(GL_VENDOR));
log.debug("\tGLFW window: {} ({})", glfwGetWindowTitle(glfwWindow), windowPtrString);
int profile = glGetInteger(GL_CONTEXT_PROFILE_MASK);
log.debug("\tGL Profile: {}", switch (profile) {
case GL_CONTEXT_CORE_PROFILE_BIT -> "Core";
case GL_CONTEXT_COMPATIBILITY_PROFILE_BIT -> "Compatibility";
case 0 -> "None";
default -> "Unknown: " + profile;
});
}
public void makeCurrent() {
ensureOpen();
glfwMakeContextCurrent(glfwWindow);
GL.setCapabilities(caps);
}
@Override
protected void doClose() {
makeCurrent();
glFinish();
vaoCache.close();
programCache.close();
textureCache.close();
canvas.close();
GL.setCapabilities(null);
glfwMakeContextCurrent(0);
// GL context destroyed by the surface
}
@Override
public OpenGLGraphicsManager getParent() {
return (OpenGLGraphicsManager) super.getParent();
}
@Override
public GL_GLFWWindowSurface getSurface() {
return (GL_GLFWWindowSurface) super.getSurface();
}
}
@@ -0,0 +1,170 @@
package net.fokinatorr.sparkle.graphics.impl.gl.element;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import org.lwjgl.opengl.GL46;
import net.fokinatorr.sparkle.context.AppContext;
import net.fokinatorr.sparkle.graphics.ARGB;
import net.fokinatorr.sparkle.graphics.PixelReader;
import net.fokinatorr.sparkle.graphics.image.Image;
import net.fokinatorr.sparkle.graphics.image.RasterImage;
import net.fokinatorr.sparkle.graphics.image.VectorImage;
import net.fokinatorr.sparkle.graphics.impl.gl.OpenGLContext;
import net.fokinatorr.sparkle.phys2d.Point2D;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.lang.ref.Cleaner;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import static org.lwjgl.opengl.GL46.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* A cache for loaded images -> uploaded textures.
*/
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@RequiredArgsConstructor
public class GLTextureCache implements NonThrowingAutoCloseable {
Map<RasterImage, Integer> rasterTextures = new WeakHashMap<>(); // Object2IntMap doesn't have weak implementations sadly
Map<VectorImage, Object2IntMap<Point2D>> vectorTextures = new WeakHashMap<>();
Set<Cleaner.Cleanable> texDeleters = new HashSet<>();
AppContext appContext;
OpenGLContext glContext;
@NonFinal
boolean closed;
/**
* Returns a ready texture ID, or uploads the given raster image to GPU and stores and returns its texture ID.
* @param image the source image
* @return the cached/uploaded texture
*/
public int getOrUploadRaster(RasterImage image) {
ensureOpen();
if (!rasterTextures.containsKey(image)) {
glContext.makeCurrent();
if (!image.isReady()) image.prepare();
int textureId = doUpload(image.createPixelReader());
rasterTextures.put(image, textureId);
return registerCleanupRaster(image, textureId);
}
return rasterTextures.get(image);
}
/**
* Returns a ready texture ID, or uploads the given vector image to GPU with the given dimensions and stores and returns its texture ID.
* @param image the source image
* @param dim the desired image dimensions
* @return the cached/uploaded texture
*/
public int getOrUploadVector(VectorImage image, Point2D dim) {
ensureOpen();
Object2IntMap<Point2D> resolutions = vectorTextures.computeIfAbsent(image, _ -> {
Object2IntMap<Point2D> result = new Object2IntOpenHashMap<>();
registerCleanupVector(image, result);
return result;
});
if (!resolutions.containsKey(dim)) {
glContext.makeCurrent();
if (!image.isReady()) image.prepare();
int textureId = doUpload(image.createPixelReader(dim));
resolutions.put(dim, textureId);
return textureId;
}
return resolutions.getInt(dim);
}
private int doUpload(PixelReader reader) {
int width = reader.getWidth();
int height = reader.getHeight();
int textureId = glGenTextures();
glBindTexture(GL_TEXTURE_2D, textureId);
ByteBuffer pixels = memAlloc(width * height * Integer.BYTES);
int[][] data = reader.getAll();
for (int y = height - 1; y >= 0; y--) { // Flip Y to match OpenGL's coordinate system
for (int x = 0; x < width; x++) {
int argb = data[y][x];
pixels
.put(ARGB.red(argb))
.put(ARGB.green(argb))
.put(ARGB.blue(argb))
.put(ARGB.alpha(argb));
}
}
pixels.flip();
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA,
width, height,
0,
GL_RGBA, GL_UNSIGNED_BYTE,
pixels
);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
memFree(pixels);
return textureId;
}
/**
* {@inheritDoc}
* <p>After calling this method, this texture cache must not be used.
* Idempotent.
*/
@Override
public void close() {
if (!closed) {
glContext.makeCurrent();
rasterTextures.values().forEach(GL46::glDeleteTextures);
rasterTextures.clear();
texDeleters.forEach(Cleaner.Cleanable::clean);
texDeleters.clear();
closed = true;
}
}
private void ensureOpen() {
if (closed) {
throw new IllegalStateException("Texture cache is closed");
}
}
private int registerCleanupRaster(Image img, int tex) {
Cleaner cleaner = appContext.get(Cleaner.class);
texDeleters.add(cleaner.register(img, () -> {
if (!glContext.isClosed()) { // Need to check since cleaning action may run after context closing
glContext.makeCurrent();
glDeleteTextures(tex);
}
}));
return tex;
}
private void registerCleanupVector(Image img, Object2IntMap<Point2D> textures) {
Cleaner cleaner = appContext.get(Cleaner.class);
texDeleters.add(cleaner.register(img, () -> {
if (!glContext.isClosed()) { // Need to check since cleaning action may run after context closing
glContext.makeCurrent();
textures.values().forEach(GL46::glDeleteTextures);
}
}));
}
}
@@ -0,0 +1,71 @@
package net.fokinatorr.sparkle.graphics.impl.gl.element;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import org.joml.*;
/**
* A decorator over {@link GLVertexArray}, adding transformation matrices.
* <p>There are two: one for internal transformations (e.g. transforming unit VAOs),
* and another - for user-supplied transformations.
* <p>The underlying vertex array is not owned by this decorator, you must close it manually when needed!
*/
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@Getter
@RequiredArgsConstructor
public class GLTransformedVertexArray {
/**
* The decorated VAO.
*/
GLVertexArray vertexArray;
/**
* The internal model matrix.
*/
Matrix4f internTransform = new Matrix4f();
/**
* The user-provided model matrix.
*/
Matrix4f transform = new Matrix4f();
Matrix4f totalTransform = new Matrix4f();
@NonFinal boolean transformDirty = true; // lazy (re)calculation on demand
/**
* Returns the combined transformation matrix of this object.
* @return the total transformation matrix
*/
public Matrix4fc getTotalTransform() {
if (transformDirty) {
transform.mul(internTransform, totalTransform);
transformDirty = false;
}
return totalTransform;
}
/**
* Marks that a change in one of transform matrices has occurred
* and the final transform needs to be recalculated.
*/
public void setDirtyTransform() {
transformDirty = true;
}
/**
* Binds this vertex array.
*
* @throws IllegalStateException if the underlying vertex array is closed
*/
public void bind() {
vertexArray.bind();
}
/**
* Unbinds the currently bound vertex array.
*/
public static void unbind() {
GLVertexArray.unbind();
}
}
@@ -0,0 +1,169 @@
package net.fokinatorr.sparkle.graphics.impl.gl.element;
import it.unimi.dsi.fastutil.floats.FloatCollection;
import it.unimi.dsi.fastutil.ints.IntCollection;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.util.Objects;
import static org.lwjgl.opengl.GL46.*;
/**
* An OpenGL vertex array object (VAO).
* May have a vertex buffer (VBO) and an index/element buffer (EBO).
*/
@FieldDefaults(level = AccessLevel.PRIVATE)
public class GLVertexArray implements NonThrowingAutoCloseable {
@Getter(AccessLevel.PACKAGE)
final int vao, vbo, ebo;
/**
* The vertex count, required for array drawing.
*/
@Getter
final int vertexCount;
/**
* The count of indices, required for element drawing.
*/
@Getter
final int indexCount;
boolean closed;
/**
* Creates a new vertex array with the given vertex and index data.
*
* @param vertices the VBO content
* @param indices the EBO content
* @param hasUV whether VBO contains UV coordinates
* @throws NullPointerException if any argument is {@code null}
*/
public GLVertexArray(float[] vertices, int[] indices, boolean hasUV) {
Objects.requireNonNull(vertices, "vertices");
Objects.requireNonNull(indices, "indices");
this.vao = glGenVertexArrays();
this.vbo = glGenBuffers();
this.ebo = glGenBuffers();
this.vertexCount = hasUV ? vertices.length / 5 : vertices.length / 3;
this.indexCount = indices.length;
bind();
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
if (hasUV) {
glVertexAttribPointer(0, 3, GL_FLOAT, false, 5 * Float.BYTES, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, false, 5 * Float.BYTES, 3 * Float.BYTES);
} else {
glVertexAttribPointer(0, 3, GL_FLOAT, false, 3 * Float.BYTES, 0);
}
unbind();
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
/**
* Creates a new vertex array with only vertex data. It will not have an EBO.
*
* @param vertices the VBO content
* @param hasUV whether VBO contains UV coordinates
* @throws NullPointerException if any argument is {@code null}
*/
public GLVertexArray(float[] vertices, boolean hasUV) {
Objects.requireNonNull(vertices, "vertices");
this.vao = glGenVertexArrays();
this.vbo = glGenBuffers();
this.ebo = 0;
this.vertexCount = hasUV ? vertices.length / 5 : vertices.length / 3;
this.indexCount = 0;
bind();
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
if (hasUV) {
glVertexAttribPointer(0, 3, GL_FLOAT, false, 5 * Float.BYTES, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, false, 5 * Float.BYTES, 3 * Float.BYTES);
} else {
glVertexAttribPointer(0, 3, GL_FLOAT, false, 3 * Float.BYTES, 0);
}
unbind();
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
/**
* Creates a new vertex array with the given vertex and index data.
*
* @param vertices the VBO content
* @param indices the EBO content
* @param hasUV whether VBO contains UV coordinates
* @throws NullPointerException if any argument is {@code null}
*/
public GLVertexArray(FloatCollection vertices, IntCollection indices, boolean hasUV) {
Objects.requireNonNull(vertices, "vertices");
Objects.requireNonNull(indices, "indices");
this(vertices.toFloatArray(), indices.toIntArray(), hasUV);
}
/**
* Creates a new vertex array with only vertex data. It will not have an EBO.
*
* @param vertices the VBO content
* @param hasUV whether VBO contains UV coordinates
* @throws NullPointerException if any argument is {@code null}
*/
public GLVertexArray(FloatCollection vertices, boolean hasUV) {
Objects.requireNonNull(vertices, "vertices");
this(vertices.toFloatArray(), hasUV);
}
/**
* Binds this vertex array.
*
* @throws IllegalStateException if this vertex array is closed
*/
public void bind() {
ensureOpen();
glBindVertexArray(vao);
}
/**
* Unbinds the currently bound vertex array.
*/
public static void unbind() {
glBindVertexArray(0);
}
/**
* {@inheritDoc}
* <p>After calling this method, the vertex array should not be used.
* Idempotent.
*/
@Override
public void close() {
if (!closed) {
glDeleteVertexArrays(vao);
glDeleteBuffers(vbo);
if (ebo > 0) glDeleteBuffers(ebo);
closed = true;
}
}
private void ensureOpen() {
if (closed) {
throw new IllegalStateException("Vertex array is closed");
}
}
}
@@ -0,0 +1,473 @@
package net.fokinatorr.sparkle.graphics.impl.gl.element;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import it.unimi.dsi.fastutil.doubles.DoubleList;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import it.unimi.dsi.fastutil.floats.FloatList;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import org.poly2tri.Poly2Tri;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonPoint;
import org.poly2tri.geometry.primitives.Point;
import net.fokinatorr.sparkle.context.AppContext;
import net.fokinatorr.sparkle.graphics.impl.gl.OpenGLContext;
import net.fokinatorr.sparkle.util.Mth;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.awt.*;
import java.awt.geom.PathIterator;
import java.lang.ref.Cleaner;
import java.util.*;
import java.util.List;
import static java.awt.geom.PathIterator.*;
import static java.awt.geom.PathIterator.SEG_CLOSE;
import static java.awt.geom.PathIterator.SEG_QUADTO;
import static org.lwjgl.opengl.GL30.*;
/**
* A storage for commonly used vertex arrays.
*/
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@RequiredArgsConstructor
public class GLVertexArrayCache implements NonThrowingAutoCloseable {
// Note: org.joml.Math has faster and precise enough for rendering trigonometric functions than java.lang.Math, so we're using it here
/**
* render mode: DrawElements(TRIANGLES,..)
*/
@Getter(lazy = true, value = AccessLevel.PRIVATE)
GLVertexArray unitRect = makeUnitRect();
/**
* render mode: DrawElements(TRIANGLES,..)
*/
@Getter(lazy = true, value = AccessLevel.PRIVATE)
GLVertexArray unitImg = makeUnitImg();
/**
* render mode: DrawArrays(TRIANGLE_FAN,..)
*/
@Getter(lazy = true, value = AccessLevel.PRIVATE)
GLVertexArray unitOval = makeUnitOval();
/**
* render mode: DrawArrays(LINE_STRIP,..)
*/
@Getter(lazy = true, value = AccessLevel.PRIVATE)
GLVertexArray unitLine = makeUnitLine();
Map<Shape, List<GLVertexArray>> triangles = new WeakHashMap<>();
Map<Shape, List<GLVertexArray>> outlines = new WeakHashMap<>();
Set<Cleaner.Cleanable> vaDeleters = new HashSet<>();
AppContext appContext;
OpenGLContext glContext;
@NonFinal
boolean closed;
/**
* Returns a rectangle vertex array with the specified position and size.
*
* @param x the origin X coordinate
* @param y the origin Y coordinate
* @param w the width
* @param h the height
* @return a rectangle VAO
*/
public GLTransformedVertexArray rect(float x, float y, float w, float h) {
ensureOpen();
GLTransformedVertexArray result = new GLTransformedVertexArray(getUnitRect());
result.getInternTransform()
.scaleXY(w, h)
.translate(x / w, y / h, 0);
return result;
}
/**
* Returns a rectangle vertex array with the specified position and size for rendering images.
*
* @param x the origin X coordinate
* @param y the origin Y coordinate
* @param w the width
* @param h the height
* @return a rectangle VAO for images
*/
public GLTransformedVertexArray rectImg(float x, float y, float w, float h) {
ensureOpen();
GLTransformedVertexArray result = new GLTransformedVertexArray(getUnitImg());
result.getInternTransform()
.scaleXY(w, h)
.translate(x / w, y / h, 0);
return result;
}
/**
* Returns an ellipse vertex array enclosed by a rectangle with the specified position and size.
*
* @param x the enclosing rectangle's origin X coordinate
* @param y the origin Y coordinate
* @param w the width
* @param h the height
* @return an ellipse VAO
*/
public GLTransformedVertexArray oval(float x, float y, float w, float h) {
ensureOpen();
GLTransformedVertexArray result = new GLTransformedVertexArray(getUnitOval());
result.getInternTransform()
.scaleXY(w, h)
.translate(x / w, y / h, 0);
return result;
}
/**
* Returns a line vertex array between the specified positions.
*
* @param x1 the first position X coordinate
* @param y1 the first position Y coordinate
* @param x2 the second position X coordinate
* @param y2 the second position Y coordinate
* @return a line VAO
*/
public GLTransformedVertexArray line(float x1, float y1, float x2, float y2) {
ensureOpen();
glContext.makeCurrent();
GLTransformedVertexArray result = new GLTransformedVertexArray(getUnitLine());
float dist = x2 - x1;
result.getInternTransform()
.scaleXY(dist, 1)
.rotateZ((float) org.joml.Math.atan2((double) y2 - y1, dist))
.translate(x1 / dist, y1, 0);
return result;
}
/**
* Returns vertex arrays for each subpath of the given {@link Shape} for filling operations.
* <p>For shapes with a united path, the returned list is a singleton.
*
* @param shape the shape
* @return VAOs for the given shape, triangulated
* @throws NullPointerException if any argument is {@code null}
*/
public List<GLTransformedVertexArray> triangulate(Shape shape) {
ensureOpen();
Objects.requireNonNull(shape, "shape");
return triangles.computeIfAbsent(shape, _ -> {
List<GLVertexArray> results = new LinkedList<>();
// Convert Shape to vertices & triangulate
for (DoubleList path : shapeToVertices(shape)) {
// shapeToVertices size is always a multiple of 3
List<PolygonPoint> points = new LinkedList<>();
for (int i = 0; i < path.size(); i += 3) {
points.add(new PolygonPoint(
path.getDouble(i),
path.getDouble(i + 1),
path.getDouble(i + 2)
));
}
Polygon polygon = new Polygon(points);
Poly2Tri.triangulate(polygon);
FloatList vertices = new FloatArrayList();
IntList indices = new IntArrayList();
Object2IntMap<Point> pointIndex = new Object2IntOpenHashMap<>();
for (var triangle : polygon.getTriangles()) {
for (var point : triangle.points) {
indices.add(pointIndex.computeIfAbsent(point, _ -> {
int result = vertices.size() / 3;
vertices.add((float) point.getX());
vertices.add((float) point.getY());
vertices.add((float) point.getZ());
return result;
}));
}
}
if (!vertices.isEmpty()) {
glContext.makeCurrent();
results.add(registerCleanup(new GLVertexArray(vertices, indices, false)));
}
}
return Collections.unmodifiableList(results);
})
.stream()
.map(GLTransformedVertexArray::new)
.toList();
}
/**
* Returns path vertex arrays for each subpath of the given {@link Shape} for stroking operations.
* <p>For shapes with a united path, the returned list is a singleton.
*
* @param shape the shape
* @return VAOs for the given shape, representing outlines
* @throws NullPointerException if any argument is {@code null}
*/
public List<GLTransformedVertexArray> outline(Shape shape) {
ensureOpen();
Objects.requireNonNull(shape, "shape");
return outlines.computeIfAbsent(shape, _ -> {
List<GLVertexArray> results = new LinkedList<>();
// Convert Shape to vertices & triangulate
for (DoubleList path : shapeToVertices(shape)) {
if (!path.isEmpty()) {
FloatList floatPath = new FloatArrayList(path.size());
path.forEach((double v) -> floatPath.add((float) v));
glContext.makeCurrent();
results.add(registerCleanup(new GLVertexArray(floatPath, false)));
}
}
return Collections.unmodifiableList(results);
})
.stream()
.map(GLTransformedVertexArray::new)
.toList();
}
/**
* {@inheritDoc}
* <p>After calling this method, this VAO cache must not be used.
* Idempotent.
*/
@Override
public void close() {
if (!closed) {
glContext.makeCurrent();
getUnitRect().close();
getUnitImg().close();
getUnitOval().close();
getUnitLine().close();
triangles.values().forEach(glVertexArrays -> glVertexArrays.forEach(GLVertexArray::close));
triangles.clear();
outlines.values().forEach(glVertexArrays -> glVertexArrays.forEach(GLVertexArray::close));
outlines.clear();
vaDeleters.forEach(Cleaner.Cleanable::clean); // unregister cleaning actions since VAOs already closed
vaDeleters.clear();
closed = true;
}
}
// Private impl
private void ensureOpen() {
if (closed) {
throw new IllegalStateException("VAO cache is closed");
}
}
private static List<DoubleList> shapeToVertices(Shape shape) {
PathIterator itr = shape.getPathIterator(null);
List<DoubleList> paths = new LinkedList<>();
DoubleList currentVertices = null;
double lastX = 0, lastY = 0;
double[] coords = new double[6];
loop:
while (!itr.isDone()) {
switch (itr.currentSegment(coords)) {
case SEG_MOVETO -> {
if (currentVertices != null) {
paths.add(currentVertices);
}
currentVertices = new DoubleArrayList();
currentVertices.add(lastX = coords[0]);
currentVertices.add(lastY = coords[1]);
currentVertices.add(0);
}
case SEG_LINETO -> {
if (currentVertices == null) {
currentVertices = new DoubleArrayList();
}
currentVertices.add(lastX = coords[0]);
currentVertices.add(lastY = coords[1]);
currentVertices.add(0);
}
case SEG_CUBICTO -> {
if (currentVertices == null) {
currentVertices = new DoubleArrayList();
}
cubicToVertices(
currentVertices,
lastX, lastY,
coords[0], coords[1],
coords[2], coords[3],
coords[4], coords[5]
);
lastX = coords[4];
lastY = coords[5];
}
case SEG_QUADTO -> {
if (currentVertices == null) {
currentVertices = new DoubleArrayList();
}
quadToVertices(
currentVertices,
lastX, lastY,
coords[0], coords[1],
coords[2], coords[3]
);
lastX = coords[2];
lastY = coords[3];
}
case SEG_CLOSE -> {
if (currentVertices == null) {
currentVertices = new DoubleArrayList();
}
break loop;
}
}
itr.next();
}
if (currentVertices != null) {
paths.add(currentVertices);
}
return paths;
}
/**
* Converts a cubic curve into vertices suitable for OpenGL.
*
* @param dest the destination vertex list
* @param x0 the current X
* @param y0 the current Y
* @param x1 the first control X
* @param y1 the first control Y
* @param x2 the second control X
* @param y2 the second control Y
* @param x3 the third control X
* @param y3 the third control Y
*/
private static void cubicToVertices(
DoubleList dest,
double x0, double y0,
double x1, double y1,
double x2, double y2,
double x3, double y3
) {
for (double t = 0; t <= 1; t += 0.05) { // TODO adjust step size?
dest.add(Mth.cubicCurve(t, x0, x1, x2, x3));
dest.add(Mth.cubicCurve(t, y0, y1, y2, y3));
dest.add(0);
}
}
/**
* Converts a quadratic curve into vertices suitable for OpenGL.
*
* @param dest the destination vertex list
* @param x0 the current X
* @param y0 the current Y
* @param x1 the first control X
* @param y1 the first control Y
* @param x2 the second control X
* @param y2 the second control Y
*/
private static void quadToVertices(
DoubleList dest,
double x0, double y0,
double x1, double y1,
double x2, double y2
) {
for (double t = 0; t <= 1; t += 0.05) { // TODO adjust step size?
dest.add((float) Mth.quadCurve(t, x0, x1, x2));
dest.add((float) Mth.quadCurve(t, y0, y1, y2));
dest.add(0);
}
}
private GLVertexArray registerCleanup(GLVertexArray va) {
Cleaner cleaner = appContext.get(Cleaner.class);
int vao = va.getVao();
int vbo = va.getVbo();
int ebo = va.getEbo();
vaDeleters.add(cleaner.register(va, () -> {
if (!glContext.isClosed()) { // Need to check since cleaning action may run after context closing
glContext.makeCurrent();
glDeleteVertexArrays(vao);
glDeleteBuffers(vbo);
if (ebo > 0) glDeleteBuffers(ebo);
}
}));
return va;
}
// Below methods are only for Lombok purposes, do not call them
private GLVertexArray makeUnitRect() {
glContext.makeCurrent();
return new GLVertexArray(
new float[]{
// x y z
0, 0, 0,
0, 1, 0,
1, 1, 0,
1, 0, 0
},
new int[]{
0, 1, 2, // ΔABC
0, 2, 3 // ΔADC
},
false
);
}
private GLVertexArray makeUnitOval() {
glContext.makeCurrent();
int segments = 32;
FloatList vertices = new FloatArrayList(segments * 3);
for (int i = 0; i <= segments; i++) {
double theta = Math.TAU * i / segments;
float x = (float) org.joml.Math.cos(theta) * 0.5f + 0.5f;
float y = (float) org.joml.Math.sin(theta) * 0.5f + 0.5f;
vertices.add(x);
vertices.add(y);
vertices.add(0);
}
return new GLVertexArray(vertices, false);
}
private GLVertexArray makeUnitImg() {
glContext.makeCurrent();
return new GLVertexArray(
new float[]{
// x y z u v
0, 0, 0, 0, 1,
0, 1, 0, 0, 0,
1, 1, 0, 1, 0,
1, 0, 0, 1, 1
},
new int[]{
0, 1, 2, // ΔABC
0, 2, 3 // ΔADC
},
true
);
}
private GLVertexArray makeUnitLine() {
glContext.makeCurrent();
return new GLVertexArray(
new float[]{
// x y z
0, 0, 0,
1, 0, 0
},
false
);
}
}
@@ -1,14 +1,14 @@
package ru.fokinatorr.sparkle.graphics.impl.gl.shader;
package net.fokinatorr.sparkle.graphics.impl.gl.shader;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
import org.lwjgl.opengl.GL20;
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.nio.FloatBuffer;
import java.util.Map;
@@ -26,7 +26,7 @@ import static org.lwjgl.system.MemoryStack.stackPush;
@Getter
public class GLShaderProgram implements NonThrowingAutoCloseable {
final int programId;
final Int2IntMap uniformLocationsCache = new Int2IntOpenHashMap();
final Object2IntMap<String> uniformLocationsCache = new Object2IntOpenHashMap<>();
boolean closed;
@@ -118,12 +118,11 @@ public class GLShaderProgram implements NonThrowingAutoCloseable {
ensureOpen();
int[] currentProgram = {0};
glGetIntegerv(GL_CURRENT_PROGRAM, currentProgram);
if (currentProgram[0] == programId) {
glUseProgram(0);
if (currentProgram[0] != programId) {
return;
}
} else {
glUseProgram(0);
}
glUseProgram(0);
}
/**
@@ -184,7 +183,7 @@ public class GLShaderProgram implements NonThrowingAutoCloseable {
* @param matrix the matrix
* @return this program
*/
public GLShaderProgram setUniform(String name, Matrix4f matrix) {
public GLShaderProgram setUniform(String name, Matrix4fc matrix) {
int loc = getUniformLocation(name);
if (loc != -1) {
try (var stack = stackPush()) {
@@ -217,7 +216,7 @@ public class GLShaderProgram implements NonThrowingAutoCloseable {
}
private int getUniformLocation(String name) {
return uniformLocationsCache.computeIfAbsent(name.hashCode(), _ -> glGetUniformLocation(programId, name));
return uniformLocationsCache.computeIfAbsent(name, _ -> glGetUniformLocation(programId, name));
}
private static void checkCompiled(int shader, String type, String code) {
@@ -0,0 +1,51 @@
package net.fokinatorr.sparkle.graphics.impl.gl.shader;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import net.fokinatorr.sparkle.graphics.impl.gl.OpenGLContext;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Supplier;
/**
* A name-based cache for {@link GLShaderProgram} instances.
*/
@FieldDefaults(level = AccessLevel.PRIVATE)
@RequiredArgsConstructor
public class GLShaderProgramCache implements NonThrowingAutoCloseable {
final ConcurrentMap<String, GLShaderProgram> programs = new ConcurrentHashMap<>();
final OpenGLContext glContext;
boolean closed;
/**
* Gets or creates a shader program with the specified name. The given creation function is only called
* if no program exists with the given name.
*
* @param name the unique identifier of the desired instance
* @param creator a supplier that provides the new program
* @return the existing or newly created and cached shader program instance
* @throws IllegalStateException if this cache is closed
*/
public GLShaderProgram getOrCreate(String name, Supplier<? extends GLShaderProgram> creator) {
if (closed) {
throw new IllegalStateException("Shader program cache is closed");
}
glContext.makeCurrent();
return programs.computeIfAbsent(name, _ -> creator.get());
}
@Override
public void close() {
if (!closed) {
glContext.makeCurrent();
programs.values().forEach(GLShaderProgram::close);
programs.clear();
closed = true;
}
}
}
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.graphics.impl.gl.shader;
package net.fokinatorr.sparkle.graphics.impl.gl.shader;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
@@ -1,7 +1,7 @@
package ru.fokinatorr.sparkle.graphics.impl.gl;
package net.fokinatorr.sparkle.graphics.impl.gl.shader;
import lombok.experimental.UtilityClass;
import ru.fokinatorr.sparkle.util.Constants;
import net.fokinatorr.sparkle.util.Constants;
import java.io.IOException;
import java.nio.file.Files;
@@ -55,7 +55,7 @@ public class ShaderLoader {
if (lastIndexOfDot >= 0) {
name = name.substring(0, lastIndexOfDot);
}
snippetMap.put("{{" + name + "}}", loadSnippet(snippet));
snippetMap.put("// {{" + name + "}}", loadSnippet(snippet));
});
} catch (IOException e) {
throw new ExceptionInInitializerError(e);
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.graphics.impl.gl.shader;
package net.fokinatorr.sparkle.graphics.impl.gl.shader;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.graphics.impl.gl.shader;
package net.fokinatorr.sparkle.graphics.impl.gl.shader;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@@ -1,14 +1,13 @@
package ru.fokinatorr.sparkle.graphics.impl.gl.surface;
package net.fokinatorr.sparkle.graphics.impl.gl.surface;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import ru.fokinatorr.sparkle.graphics.impl.gl.GLFramebuffer;
import ru.fokinatorr.sparkle.graphics.impl.surface.AbstractGLFWWindowSurface;
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
import ru.fokinatorr.sparkle.phys2d.Point2D;
import ru.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import net.fokinatorr.sparkle.graphics.impl.gl.GLFramebuffer;
import net.fokinatorr.sparkle.graphics.impl.surface.AbstractGLFWWindowSurface;
import net.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
import net.fokinatorr.sparkle.stage.Stage;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.system.MemoryUtil.NULL;
@@ -25,8 +24,6 @@ public final class GL_GLFWWindowSurface extends AbstractGLFWWindowSurface {
*/
GL_GLFWWindowSurface(long glfwWindow, EventDispatcher dispatcher, Stage stage, Thread graphicsThread) {
super(glfwWindow, dispatcher, stage, graphicsThread);
glfwMakeContextCurrent(glfwWindow);
glfwSwapInterval(1);
}
@@ -45,16 +42,14 @@ public final class GL_GLFWWindowSurface extends AbstractGLFWWindowSurface {
if (translucent) {
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
}
GL_GLFWWindowSurface result = new GL_GLFWWindowSurface(
glfwCreateWindow(stage.getWidth(), stage.getHeight(), title, NULL, NULL),
dispatcher, stage, graphicsThread
);
if (translucent) {
} else {
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE);
glfwWindowHint(GLFW_DECORATED, GLFW_TRUE);
}
return result;
return new GL_GLFWWindowSurface(
glfwCreateWindow(stage.getWidth(), stage.getHeight(), title, NULL, NULL),
dispatcher, stage, graphicsThread
);
}
/**
@@ -73,22 +68,26 @@ public final class GL_GLFWWindowSurface extends AbstractGLFWWindowSurface {
if (translucent) {
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
}
GL_GLFWWindowSurface result = new GL_GLFWWindowSurface(
glfwCreateWindow(stage.getWidth(), stage.getHeight(), title, monitor, NULL),
dispatcher, stage, graphicsThread
);
if (translucent) {
} else {
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE);
glfwWindowHint(GLFW_DECORATED, GLFW_TRUE);
}
return result;
return new GL_GLFWWindowSurface(
glfwCreateWindow(stage.getWidth(), stage.getHeight(), title, monitor, NULL),
dispatcher, stage, graphicsThread
);
}
@Override
public Framebuffer acquireBuffer() {
Point2D dim = getSize();
return new GLFramebuffer(0, (int) dim.x(), (int) dim.y());
public Framebuffer acquireBuffer(int prefWidth, int prefHeight) {
if (prefWidth < FB_ORIGINAL_SIZE || prefHeight < FB_ORIGINAL_SIZE) {
throw new IllegalArgumentException("Invalid framebuffer size: " + prefWidth + "x" + prefHeight);
}
return new GLFramebuffer(
0, // GL specification: When no framebuffer object is attached (glBindFramebuffer(GL_FRAMEBUFFER, 0)), rendering is done to default framebuffer, which is managed by the windowing system.
prefWidth == FB_ORIGINAL_SIZE ? getWidth() : prefWidth,
prefHeight == FB_ORIGINAL_SIZE ? getHeight() : prefHeight
);
}
@Override
@@ -1,4 +1,4 @@
package ru.fokinatorr.sparkle.graphics.impl.surface;
package net.fokinatorr.sparkle.graphics.impl.surface;
import lombok.AccessLevel;
import lombok.Getter;
@@ -6,19 +6,20 @@ import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.system.Callback;
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import ru.fokinatorr.sparkle.event.input.Key;
import ru.fokinatorr.sparkle.event.input.KeyboardEvent;
import ru.fokinatorr.sparkle.event.input.MouseButton;
import ru.fokinatorr.sparkle.event.input.MouseEvent;
import ru.fokinatorr.sparkle.graphics.render.surface.WindowSurface;
import ru.fokinatorr.sparkle.phys2d.Point2D;
import ru.fokinatorr.sparkle.stage.Stage;
import ru.fokinatorr.sparkle.util.concurrent.atomic.AtomicDouble;
import net.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
import net.fokinatorr.sparkle.event.input.Key;
import net.fokinatorr.sparkle.event.input.KeyboardEvent;
import net.fokinatorr.sparkle.event.input.MouseButton;
import net.fokinatorr.sparkle.event.input.MouseEvent;
import net.fokinatorr.sparkle.graphics.render.surface.WindowSurface;
import net.fokinatorr.sparkle.phys2d.Point2D;
import net.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.util.concurrent.atomic.AtomicDouble;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.system.MemoryUtil.NULL;
@@ -35,11 +36,10 @@ public abstract class AbstractGLFWWindowSurface implements WindowSurface {
@Getter
final long glfwWindow; // pointer
final List<ResizeListener> resizeCallback = new LinkedList<>();
final List<Callback> callbacks = new LinkedList<>();
final Thread graphicsThread;
Callback resizeCB;
int[] oldXYWH = null;
boolean closed;
boolean explicitClose;
/**
@@ -55,7 +55,7 @@ public abstract class AbstractGLFWWindowSurface implements WindowSurface {
this.graphicsThread = Objects.requireNonNull(graphicsThread, "graphics thread");
// <editor-fold desc="-- Set callbacks --" defaultstate="collapsed">
callbacks.add(glfwSetKeyCallback(glfwWindow, (_, keyCode, scancode, action, modifiers) -> {
glfwSetKeyCallback(glfwWindow, (_, keyCode, scancode, action, modifiers) -> {
Key key = GLFWToPublicAPI.KEYS_MAP.get(keyCode);
if (key != null) {
switch (action) {
@@ -87,54 +87,47 @@ public abstract class AbstractGLFWWindowSurface implements WindowSurface {
}
);
}
}));
});
callbacks.add(glfwSetCharCallback(glfwWindow, (_, codePoint) -> {
glfwSetCharCallback(glfwWindow, (_, codePoint) -> {
if (dispatcher.hasListenersFor(KeyboardEvent.CharInputEvent.class)) {
dispatcher.fireEvent(new KeyboardEvent.CharInputEvent(stage, codePoint));
}
}));
});
AtomicLong lastMousePress = new AtomicLong(-1);
callbacks.add(glfwSetMouseButtonCallback(glfwWindow, (_, buttonCode, action, _) -> {
glfwSetMouseButtonCallback(glfwWindow, (_, buttonCode, action, _) -> {
MouseButton button = GLFWToPublicAPI.MOUSE_BUTTONS_MAP.get(buttonCode);
double[] realX = {0}, realY = {0};
glfwGetCursorPos(glfwWindow, realX, realY);
double x = realX[0] - stage.getWidth() / 2d;
double y = realY[0] - stage.getHeight() / 2d;
double[] x = {0}, y = {0};
glfwGetCursorPos(glfwWindow, x, y);
switch (action) {
case GLFW_PRESS -> {
lastMousePress.set(System.nanoTime());
if (dispatcher.hasListenersFor(MouseEvent.MousePressedEvent.class)) {
dispatcher.fireEvent(new MouseEvent.MousePressedEvent(button, stage, x, y));
dispatcher.fireEvent(new MouseEvent.MousePressedEvent(button, stage, x[0], y[0]));
}
}
case GLFW_RELEASE -> {
if (dispatcher.hasListenersFor(MouseEvent.MouseReleasedEvent.class)) {
dispatcher.fireEvent(new MouseEvent.MouseReleasedEvent(button, stage, x, y));
dispatcher.fireEvent(new MouseEvent.MouseReleasedEvent(button, stage, x[0], y[0]));
}
if (lastMousePress.get() > 0) {
long pressDurationNs = System.nanoTime() - lastMousePress.getAndSet(-1);
if (dispatcher.hasListenersFor(MouseEvent.MouseClickedEvent.class)
&& pressDurationNs <= 500_000_000L) { // TODO configurable?
dispatcher.fireEvent(new MouseEvent.MouseClickedEvent(button, stage, x, y));
dispatcher.fireEvent(new MouseEvent.MouseClickedEvent(button, stage, x[0], y[0]));
}
}
}
}
}));
});
AtomicDouble lastMouseX = new AtomicDouble(-1);
AtomicDouble lastMouseY = new AtomicDouble(-1);
callbacks.add(glfwSetCursorPosCallback(glfwWindow, (_, newRealX, newRealY) -> {
double oldRealX = lastMouseX.getAndSet(newRealX);
double oldRealY = lastMouseY.getAndSet(newRealY);
if (dispatcher.hasListenersFor(MouseEvent.MouseCursorMovedEvent.class) && oldRealX >= 0 && oldRealY >= 0) {
double
oldX = oldRealX - stage.getWidth() / 2d,
oldY = oldRealY - stage.getWidth() / 2d,
newX = newRealX - stage.getWidth() / 2d,
newY = newRealY - stage.getWidth() / 2d;
glfwSetCursorPosCallback(glfwWindow, (_, newX, newY) -> {
double oldX = lastMouseX.getAndSet(newX);
double oldY = lastMouseY.getAndSet(newY);
if (dispatcher.hasListenersFor(MouseEvent.MouseCursorMovedEvent.class) && oldX >= 0 && oldY >= 0) {
Set<MouseButton> pressedButtons = EnumSet.noneOf(MouseButton.class);
for (int mb : GLFWToPublicAPI.MOUSE_BUTTONS_MAP.keySet()) {
if (glfwGetMouseButton(glfwWindow, mb) == GLFW_PRESS) {
@@ -144,17 +137,15 @@ public abstract class AbstractGLFWWindowSurface implements WindowSurface {
dispatcher.fireEvent(new MouseEvent.MouseCursorMovedEvent(stage, oldX, oldY, newX, newY, pressedButtons));
}
}));
});
callbacks.add(glfwSetScrollCallback(glfwWindow, (_, dx, dy) -> {
glfwSetScrollCallback(glfwWindow, (_, dx, dy) -> {
if (dispatcher.hasListenersFor(MouseEvent.MouseScrolledEvent.class)) {
double[] realX = {0}, realY = {0};
glfwGetCursorPos(glfwWindow, realX, realY);
double x = realX[0] - stage.getWidth() / 2d;
double y = realY[0] - stage.getHeight() / 2d;
dispatcher.fireEvent(new MouseEvent.MouseScrolledEvent(stage, x, y, dx, dy));
double[] x = {0}, y = {0};
glfwGetCursorPos(glfwWindow, x, y);
dispatcher.fireEvent(new MouseEvent.MouseScrolledEvent(stage, x[0], y[0], dx, dy));
}
}));
});
// </editor-fold>
}
@@ -194,35 +185,50 @@ public abstract class AbstractGLFWWindowSurface implements WindowSurface {
@Override
public boolean shouldClose() {
ensureOpen();
// ensureOnCorrectThread();
return glfwWindowShouldClose(glfwWindow);
if (closed || !glfwWindowShouldClose(glfwWindow)) { // order is important here!
return false;
}
glfwSetWindowShouldClose(glfwWindow, false); // clear flag as required by contract
return true;
}
@Override
public void setShouldClose() {
if (!closed) {
glfwSetWindowShouldClose(glfwWindow, true);
explicitClose = true;
}
}
@Override
public boolean isExplicitShouldClose() {
boolean result = !closed && explicitClose;
explicitClose = false;
return result;
}
@Override
public void setResizable(boolean resizable) {
ensureOnCorrectThread();
glfwSetWindowAttrib(glfwWindow, GLFW_RESIZABLE, resizable ? GLFW_TRUE : GLFW_FALSE);
}
@Override
public boolean isResizable() {
ensureOnCorrectThread();
return glfwGetWindowAttrib(glfwWindow, GLFW_RESIZABLE) == GLFW_TRUE;
}
@Override
public void onResize(ResizeListener callback) {
ensureOpen();
ensureOnCorrectThread();
resizeCallback.add(callback);
Callback newCB = glfwSetWindowSizeCallback(glfwWindow, (_, width, height) -> {
Callback oldCB = glfwSetWindowSizeCallback(glfwWindow, (_, width, height) -> {
for (var cb : resizeCallback) {
cb.resized(this, width, height);
}
});
if (resizeCB != null) resizeCB.free();
resizeCB = newCB;
}
@Override
public Set<Feature> getFeatures() {
return Collections.unmodifiableSet(EnumSet.of(
Feature.RESIZABLE,
Feature.MOVABLE,
Feature.HIDEABLE,
Feature.NAMEABLE,
Feature.FULLSCREENABLE,
Feature.TRANSLUCENT
));
if (oldCB != null) oldCB.free();
}
@Override
@@ -348,16 +354,7 @@ public abstract class AbstractGLFWWindowSurface implements WindowSurface {
@Override
public void close() {
if (!closed) {
if (resizeCB != null) {
resizeCB.free();
resizeCB = null;
}
callbacks.forEach(callback -> {
if (callback != null) {
callback.free();
}
});
callbacks.clear();
glfwFreeCallbacks(glfwWindow);
glfwDestroyWindow(glfwWindow);
closed = true;
}
@@ -1,11 +1,11 @@
package ru.fokinatorr.sparkle.graphics.impl.surface;
package net.fokinatorr.sparkle.graphics.impl.surface;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import lombok.experimental.UtilityClass;
import ru.fokinatorr.sparkle.event.input.Key;
import ru.fokinatorr.sparkle.event.input.MouseButton;
import net.fokinatorr.sparkle.event.input.Key;
import net.fokinatorr.sparkle.event.input.MouseButton;
import static org.lwjgl.glfw.GLFW.*;
@@ -218,8 +218,8 @@ public class GLFWToPublicAPI {
k.put(GLFW_KEY_KP_ENTER, Key.NUMPAD_ENTER); // the tall guy
k.put(GLFW_KEY_KP_EQUAL, Key.NUMPAD_EQUALS); // he is tall bc he ate this key
// Modifier keys. The most controversial keys that have absolutely different meaning on different OSes.
// the key's meaning becomes more and more blurry as we dive deeper...
// Modifier keys. The only ones with absolutely different meaning on different OSes.
// the key's intended meaning becomes more and more blurry as we dive deeper...
// these guys are normal. they have the same name and overall do more or less the same in all OSes
k.put(GLFW_KEY_LEFT_SHIFT, Key.LEFT_SHIFT);
@@ -0,0 +1,121 @@
package net.fokinatorr.sparkle.graphics.impl.sw;
import lombok.experimental.UtilityClass;
import net.fokinatorr.sparkle.graphics.ARGB;
import net.fokinatorr.sparkle.graphics.PixelReader;
import net.fokinatorr.sparkle.graphics.PixelWriter;
import net.fokinatorr.sparkle.util.Mth;
import java.util.Objects;
/**
* High-quality image scaling using bicubic interpolation.
* <p>
* Based on Catmull-Rom kernel: sharp, no oversharpening.
*/
@UtilityClass
public final class Scaling {
/**
* Resizes an image using bicubic interpolation.
*
* @param src the source pixel data
* @param dst the destination pixel data
*/
public void bicubicResize(PixelReader src, PixelWriter dst) {
Objects.requireNonNull(src, "source");
Objects.requireNonNull(dst, "destination");
int
srcWidth = src.getWidth(), srcHeight = src.getHeight(),
targetWidth = dst.getWidth(), targetHeight = dst.getHeight();
double xRatio = (double) srcWidth / targetWidth;
double yRatio = (double) srcHeight / targetHeight;
for (int ty = 0; ty < targetHeight; ty++) {
double sy = ty * yRatio;
int y = (int) Math.floor(sy);
double dy = sy - y;
for (int tx = 0; tx < targetWidth; tx++) {
double sx = tx * xRatio;
int x = (int) Math.floor(sx);
double dx = sx - x;
dst.setARGB(tx, ty, bicubicSample(src, srcWidth, srcHeight, x, y, dx, dy));
}
}
}
/**
* Samples one pixel using bicubic interpolation.
*/
private int bicubicSample(
PixelReader src,
int w,
int h,
int x,
int y,
double dx,
double dy
) {
double[] coeffsY = cubicCoeffs(dy);
double[] coeffsX = cubicCoeffs(dx);
double r = 0, g = 0, b = 0, a = 0;
for (int j = -1; j <= 2; j++) {
double wy = coeffsY[j + 1];
int yj = y + j;
for (int i = -1; i <= 2; i++) {
double wx = coeffsX[i + 1];
int xi = x + i;
int argb = getPixelSafe(src, w, h, xi, yj);
double wgt = wx * wy;
r += (argb & 0xFF) * wgt;
g += ((argb >> 8) & 0xFF) * wgt;
b += ((argb >> 16) & 0xFF) * wgt;
a += ((argb >> 24) & 0xFF) * wgt;
}
}
return ARGB.color(
(byte) clamp(a),
(byte) clamp(r),
(byte) clamp(g),
(byte) clamp(b)
);
}
/**
* Catmull-Rom cubic kernel: B=0, C=0.5
*/
private double[] cubicCoeffs(double x) {
double x2 = x * x;
double x3 = x2 * x;
return new double[] {
-0.5 * x3 + x2 - 0.5 * x,
1.5 * x3 - 2.5 * x2 + 1.0,
-1.5 * x3 + 2.0 * x2 + 0.5 * x,
0.5 * x3 - 0.5 * x2
};
}
/**
* Gets pixel with edge clamping.
*/
private int getPixelSafe(PixelReader src, int w, int h, int x, int y) {
x = Mth.clamp(x, 0, w - 1);
y = Mth.clamp(y, 0, h - 1);
return src.getARGB(x, y);
}
private static int clamp(double v) {
return Mth.clamp(Math.round(v), 0, 255);
}
}
@@ -0,0 +1,4 @@
package net.fokinatorr.sparkle.graphics.io;
public interface ImageDecoder {
}
@@ -1,15 +1,15 @@
package ru.fokinatorr.sparkle.graphics.render;
package net.fokinatorr.sparkle.graphics.render;
import org.w3c.dom.Text;
import ru.fokinatorr.sparkle.effect.graphics.GraphicEffect;
import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap;
import ru.fokinatorr.sparkle.graphics.ARGB;
import ru.fokinatorr.sparkle.graphics.BlendMode;
import ru.fokinatorr.sparkle.graphics.image.Image;
import ru.fokinatorr.sparkle.phys2d.Point2D;
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import net.fokinatorr.sparkle.effect.graphics.GraphicEffect;
import net.fokinatorr.sparkle.effect.graphics.GraphicEffectMap;
import net.fokinatorr.sparkle.graphics.ARGB;
import net.fokinatorr.sparkle.graphics.BlendMode;
import net.fokinatorr.sparkle.graphics.image.Image;
import net.fokinatorr.sparkle.phys2d.Point2D;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
@@ -21,6 +21,9 @@ import java.util.Objects;
* This interface provides methods for drawing shapes and images, applying transformations,
* setting styling properties, and managing clipping regions. It maintains a state
* stack that can be saved and restored using {@link #save()} and {@link #restore()}.
* <p><b>Note: When images and shapes are uploaded into GPU memory, they're typically cached using
* identity semantics (comparing by reference, not value), so custom renderers are expected to cache constantly
* used images/shapes and treat them as immutable objects to prevent data consistency issues.</b>
*
* <h2>Coordinate System</h2>
* The coordinate system uses floating-point coordinates where {@code (0, 0)} is typically the
@@ -87,6 +90,7 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
/**
* Draws an image at the specified position with the given size.
* <p>If either dimension is set to {@link #ORIGINAL_SIZE}, then the image's respective dimension is used.
*
* @param image the image to draw
* @param x the X coordinate of the top-left corner
@@ -94,8 +98,8 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* @param w the preferred width of the image or {@link #ORIGINAL_SIZE}
* @param h the preferred height of the image or {@link #ORIGINAL_SIZE}
* @throws NullPointerException if image is {@code null}
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* ({@link #ORIGINAL_SIZE} doesn't count since it's a special value)
* @throws IllegalArgumentException if dimensions are negative, or if any argument is {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* ({@link #ORIGINAL_SIZE} for coordinates doesn't count since it's a special value)
* @see #drawImage(Image, Point2D, Point2D)
*/
void drawImage(Image image, double x, double y, double w, double h);
@@ -144,7 +148,7 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* @param y the Y coordinate of the top-left corner
* @param w the width of the rectangle
* @param h the height of the rectangle
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @throws IllegalArgumentException if dimensions are negative, or if any argument is {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @see #drawShape(Shape)
* @see #fillShape(Shape)
*/
@@ -156,7 +160,7 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* @param topLeft the top-left corner coordinates
* @param deltaSize the size dimensions of the rectangle
* @throws NullPointerException if any argument is {@code null}
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @throws IllegalArgumentException if dimensions are negative, or if any argument is {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
*/
default void fillRect(Point2D topLeft, Point2D deltaSize) {
fillRect(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y());
@@ -178,7 +182,7 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* @param topLeft the top-left corner coordinates
* @param deltaSize the size dimensions of the rectangle
* @throws NullPointerException if any argument is {@code null}
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @throws IllegalArgumentException if dimensions are negative, or if any argument is {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
*/
default void drawRect(Point2D topLeft, Point2D deltaSize) {
drawRect(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y());
@@ -189,7 +193,7 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* @param y1 the Y coordinate of the first position
* @param x2 the X coordinate of the second position
* @param y2 the Y coordinate of the second position
* @throws IllegalArgumentException if any coordinates are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @throws IllegalArgumentException if any argument is {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @see #drawShape(Shape)
*/
default void drawLine(double x1, double y1, double x2, double y2) {
@@ -200,7 +204,7 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* @param first the first position
* @param second the second position
* @throws NullPointerException if any argument is {@code null}
* @throws IllegalArgumentException if any coordinates are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @throws IllegalArgumentException if any argument is {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
*/
default void drawLine(Point2D first, Point2D second) {
drawLine(first.x(), first.y(), second.x(), second.y());
@@ -212,7 +216,7 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* @param y the Y coordinate of the top-left corner
* @param w the width of the oval
* @param h the height of the oval
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @throws IllegalArgumentException if dimensions are negative, or if any argument is {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @see #drawShape(Shape)
* @see #fillShape(Shape)
*/
@@ -224,7 +228,7 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* @param topLeft the top-left corner coordinates
* @param deltaSize the size dimensions of the oval
* @throws NullPointerException if any argument is {@code null}
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @throws IllegalArgumentException if dimensions are negative, or if any argument is {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
*/
default void fillOval(Point2D topLeft, Point2D deltaSize) {
fillOval(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y());
@@ -235,18 +239,19 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* @param y the Y coordinate of the top-left corner
* @param w the width of the oval
* @param h the height of the oval
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @throws IllegalArgumentException if dimensions are negative, or if any argument is {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @see #drawShape(Shape)
*/
default void drawOval(double x, double y, double w, double h) {
drawShape(new Ellipse2D.Double(x, y, w, h));
}
/**
* Vector version of {@link #drawOval(double, double, double, double)}.
* @param topLeft the top-left corner coordinates
* @param deltaSize the size dimensions of the oval
* @throws NullPointerException if any argument is {@code null}
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @throws IllegalArgumentException if dimensions are negative, or if any argument is {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
*/
default void drawOval(Point2D topLeft, Point2D deltaSize) {
drawOval(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y());
@@ -316,10 +321,28 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
*
* @param sx the scaling factor for the X axis
* @param sy the scaling factor for the Y axis
* @throws IllegalArgumentException if sx or sy is/are non-positive, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
* @throws IllegalArgumentException if sx or sy is/are 0, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
*/
void scale(double sx, double sy);
/**
* Scales the coordinate system by the specified delta vector.
* @param delta the scale factor vector point
* @throws NullPointerException if delta is {@code null}
* @throws IllegalArgumentException if any vector component is 0, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
*/
default void scale(Point2D delta) {
Objects.requireNonNull(delta, "delta");
scale(delta.x(), delta.y());
}
/**
* Multiplies the coordinate system by the specified affine transform matrix.
* @param at the transform matrix
* @throws NullPointerException if transform matrix is {@code null}
*/
void mulTransform(AffineTransform at);
/**
* Sets the fill color for shape filling operations.
* This color will be used by subsequent calls to {@link #fillShape(Shape)} and convenience methods.
@@ -380,33 +403,35 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* Sets the graphic effects map to apply to subsequent drawing operations.
* <p><i>Note: Spatial distortion effects can't be applied to vector content (shapes, text); effects
* that can be applied to them are: {@link GraphicEffect#HUE_SHIFT HUE_SHIFT}, {@link GraphicEffect#BRIGHTNESS BRIGHTNESS}
* and {@link GraphicEffect#OPACITY OPACITY}. Use {@link #createSubCanvas(double, double)} and {@link #getFinalImage()}
* and {@link GraphicEffect#FADE FADE}. Use {@link #createSubCanvas(double, double)} and {@link #submitImage(double, double, double, double)}
* to apply spatial distortion to vector elements.</i>
* @param effects the effect map
*/
void setEffects(GraphicEffectMap effects);
/**
* Intersects the current clipping region with the specified shape.
* All subsequent drawing operations will be clipped to the intersection of
* the current clip and the specified shape. The clip is transformed by the
* current transformation matrix.
*
* @param shape the shape to intersect with the current clip
* @throws NullPointerException if shape is {@code null}
* Sets the current clipping region to the given rectangular path.
*
* @param x X coordinate of top-left corner
* @param y Y coordinate of top-left corner
* @param w width
* @param h height
* @throws IllegalArgumentException if w or h is/are non-positive,
* or if any argument is negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
*
* @see #resetClip()
* @see #translate(double, double)
* @see #rotate(double)
* @see #scale(double, double)
*/
void clip(Shape shape);
void clip(double x, double y, double w, double h);
/**
* Resets the clipping region to the default (typically the entire rendering surface).
* After calling this method, all drawing operations will not be clipped (except by
* the bounds of the rendering surface itself).
*
* @see #clip(Shape)
*
* @see #clip(double, double, double, double)
*/
void resetClip();
@@ -416,8 +441,8 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* Creates a new sub-canvas that renders into an offscreen buffer.
* <p>
* All drawing operations on the returned canvas are isolated and rasterized
* into a procedural image when closed. The result can be retrieved via
* {@link #getFinalImage()} and drawn like any other image.
* into a procedural image when closed. The result can be drawn onto the parent canvas via
* {@link #submitImage(double, double, double, double)}.
* <p>
* This enables:
* <ul>
@@ -432,22 +457,20 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
* layer.setFillArgb(ARGB.RED);
* layer.fillRect(10, 10, 50, 50);
* layer.drawOval(30, 30, 40, 40);
* try (Image img = layer.getFinalImage()) {
* // If "canvas" has graphic effects, they'll be applied to the whole image, not to each component separately!
* canvas.drawImage(img, 100, 100, 200, 200);
* }
* // If "canvas" has graphic effects, they'll be applied to the whole image, not to each component separately!
* layer.submitImage(100, 100, 200, 200);
* }
* }</pre>
*
* @param width the width of the sub-canvas
* @param height the height of the sub-canvas
* @return a new render canvas targeting an offscreen buffer
* @throws IllegalArgumentException if either dimension exceeds this canvas's respective dimension
* @throws IllegalArgumentException if either dimension exceeds this canvas's respective dimension or is non-positive
*/
RenderCanvas createSubCanvas(double width, double height);
/**
* Checks whether this canvas is a sub-canvas. If {@code true}, then {@link #getFinalImage()} can be safely called.
* Checks whether this canvas is a sub-canvas. If {@code true}, then {@link #submitImage(double, double, double, double)} can be safely called.
*
* @return {@code true} for sub-canvases, {@code false} for the main canvas
*/
@@ -456,16 +479,30 @@ public interface RenderCanvas extends NonThrowingAutoCloseable {
}
/**
* Returns the final rendered image, if this canvas is a sub-canvas.
* The image is not cached anywhere and becomes invalid once the canvas is closed.
* Draws the final rendered image on the parent canvas as described in {@link #drawImage drawImage()}, if this canvas is a sub-canvas.
* @param x the X coordinate of the top-left corner
* @param y the Y coordinate of the top-left corner
* @param w the preferred width of the image or {@link #ORIGINAL_SIZE}
* @param h the preferred height of the image or {@link #ORIGINAL_SIZE}
* @throws IllegalStateException if this canvas is not a sub-canvas
* @see #isSubCanvas()
*/
default Image getFinalImage() {
// TODO maybe allow calling on main canvas? For screenshots?
default void submitImage(double x, double y, double w, double h) {
throw new IllegalStateException("This canvas is not a sub-canvas");
}
/**
* Vector version of {@link #submitImage(double, double, double, double)}.
*
* @param topLeft the top-left corner coordinates
* @param deltaSize the preferred dimensions of the image
* @throws IllegalStateException if this canvas is not a sub-canvas
* @see #isSubCanvas()
*/
default void submitImage(Point2D topLeft, Point2D deltaSize) {
submitImage(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y());
}
// Getters
/**
@@ -1,11 +1,10 @@
package ru.fokinatorr.sparkle.graphics.render;
package net.fokinatorr.sparkle.graphics.render;
import ru.fokinatorr.sparkle.assets.Assets;
import ru.fokinatorr.sparkle.graphics.GraphicsManager;
import ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
import ru.fokinatorr.sparkle.stage.Stage;
import ru.fokinatorr.sparkle.stage.StageCreator;
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
import net.fokinatorr.sparkle.graphics.GraphicsManager;
import net.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
import net.fokinatorr.sparkle.stage.Stage;
import net.fokinatorr.sparkle.stage.StageCreator;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
/**
* Represents a graphics environment. Binds together:
@@ -66,7 +65,7 @@ public interface RenderingContext extends NonThrowingAutoCloseable {
void present();
/**
* Checks if the surface should close.
* Checks if the surface should close and clears this flag.
*
* @return whether a close was requested
*/
@@ -74,6 +73,13 @@ public interface RenderingContext extends NonThrowingAutoCloseable {
return getSurface().shouldClose();
}
/**
* Requests the surface to close; in other words, makes {@link #shouldClose()} return {@code true} on the next call.
*/
default void setShouldClose() {
getSurface().setShouldClose();
}
/**
* Adds a resize listener to the surface.
*
@@ -82,4 +88,14 @@ public interface RenderingContext extends NonThrowingAutoCloseable {
default void onResize(RenderingSurface.ResizeListener callback) {
getSurface().onResize(callback);
}
/**
* {@inheritDoc}
* <p><i>Note: contexts must not be closed manually; this is handled by the graphics manager.
* Use {@link #setShouldClose()} instead to signal a close request.</i>
* <p>After calling this method, the context instance should not be used.
* Calling this method more than once does not have any effect.
*/
@Override
void close();
}
@@ -0,0 +1,33 @@
package net.fokinatorr.sparkle.graphics.render.framebuffer;
import net.fokinatorr.sparkle.graphics.render.RenderCanvas;
import net.fokinatorr.sparkle.phys2d.Point2D;
import net.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
/**
* Represents a render target to present on a rendering surface. This is usually a handle to native platform framebuffer.
* <p><i>This interface is not intended to be used directly in user code; it was made public solely to allow custom
* graphics engine implementations.</i> Use {@link RenderCanvas} for drawing operations instead.
*/
public interface Framebuffer extends NonThrowingAutoCloseable {
/**
* Returns the width of underlying framebuffer.
* @return the width, always positive
*/
int width();
/**
* Returns the height of underlying framebuffer.
* @return the height, always positive
*/
int height();
/**
* Returns a vector representing the dimensions of underlying framebuffer's data.
* @return the dimensions, both always positive
*/
default Point2D getDimensions() {
return new Point2D(width(), height());
}
}
@@ -1,11 +1,12 @@
package ru.fokinatorr.sparkle.graphics.render.framebuffer;
package net.fokinatorr.sparkle.graphics.render.framebuffer;
import lombok.experimental.FieldDefaults;
import ru.fokinatorr.sparkle.graphics.PixelReader;
import ru.fokinatorr.sparkle.graphics.PixelWriter;
import net.fokinatorr.sparkle.graphics.ARGB;
import net.fokinatorr.sparkle.graphics.PixelReader;
import net.fokinatorr.sparkle.graphics.PixelWriter;
import org.lwjgl.system.MemoryUtil;
import ru.fokinatorr.sparkle.graphics.impl.IntBufferPixelAccessor;
import net.fokinatorr.sparkle.graphics.impl.IntBufferPixelAccessor;
import java.nio.IntBuffer;
@@ -39,13 +40,21 @@ public final class OffscreenFramebuffer implements Framebuffer {
return height;
}
@Override
/**
* Returns a pixel reader over this buffer, for reading its data as ARGB pixels.
* @return a new {@link PixelReader}
* @see ARGB
*/
public synchronized PixelReader createPixelReader() {
ensureOpen();
return new IntBufferPixelAccessor(width, height, img, this::ensureOpen);
}
@Override
/**
* Returns a pixel writer over this buffer, for writing ARGB pixels into it.
* @return a new {@code PixelWriter}
* @see ARGB
*/
public synchronized PixelWriter createPixelWriter() {
ensureOpen();
return new IntBufferPixelAccessor(width, height, img, this::ensureOpen);
@@ -0,0 +1,65 @@
package net.fokinatorr.sparkle.graphics.render.renderer;
import net.fokinatorr.sparkle.graphics.render.RenderingContext;
import net.fokinatorr.sparkle.phys.RotationMode;
import net.fokinatorr.sparkle.phys2d.Hitbox2D;
import net.fokinatorr.sparkle.phys2d.Physical2D;
import java.awt.geom.AffineTransform;
/**
* A 2D renderable object with physical properties.
*/
public interface PhysicalRenderable2D extends Renderable2D, Physical2D {
@Override
default double getScreenX(RenderingContext ctx) {
return (ctx.getStage().getWidth() - getPreferredCanvasSize(ctx).x()) / 2d + getX();
}
@Override
default double getScreenY(RenderingContext ctx) {
return (ctx.getStage().getHeight() - getPreferredCanvasSize(ctx).y()) / 2d - getY();
}
@Override
default double getAnchorX(RenderingContext ctx) {
return getPreferredCanvasSize(ctx).x() / 2;
}
@Override
default double getAnchorY(RenderingContext ctx) {
return getPreferredCanvasSize(ctx).y() / 2;
}
@Override
default double getRotation(RenderingContext ctx) {
return getRotationMode() == RotationMode.ALL_AROUND || getRotationMode() == RotationMode.LOOK_AT
? (getDirection() - 90) % 360
: 0;
}
@Override
default double getScreenScaleX(RenderingContext ctx) {
double direction = getDirection() % 360;
return getRotationMode() == RotationMode.LEFT_RIGHT && direction > 180
? getStretchX() / -100
: getStretchX() / 100;
}
@Override
default double getScreenScaleY(RenderingContext ctx) {
double direction = getDirection() % 360;
return (getRotationMode() == RotationMode.UP_DOWN && direction > 90 && direction < 270)
|| (getRotationMode() == RotationMode.LOOK_AT && direction > 180)
? getStretchY() / -100
: getStretchY() / 100;
}
@Override
default Hitbox2D getBounds(RenderingContext ctx) {
AffineTransform at = new AffineTransform();
at.translate(ctx.getStage().getWidth() / 2d, ctx.getStage().getHeight() / -2d);
at.scale(1, -1);
return getHitbox().transform(at);
}
}
@@ -0,0 +1,46 @@
package net.fokinatorr.sparkle.graphics.render.renderer;
import net.fokinatorr.sparkle.effect.graphics.GraphicEffectMap;
import net.fokinatorr.sparkle.graphics.render.RenderCanvas;
import net.fokinatorr.sparkle.graphics.render.RenderingContext;
import net.fokinatorr.sparkle.phys2d.Point2D;
/**
* A renderable object is an object that knows how to draw itself. Objects of this type are
* by default drawn into a separate {@link RenderCanvas#createSubCanvas sub-canvas} of the
* {@link #getPreferredCanvasSize preferred size} and the resulting image is drawn in the top-left corner
* with the renderable's properties (e.g. graphic effects, translation, scaling) applied.
* <p>This base interface has these methods: {@link #render(RenderCanvas)} for drawing, {@link #isVisible()}
* for checking visibility, and {@link #getGraphicEffects()} for getting and editing graphic effects.
*/
public interface Renderable {
/**
* Render this object onto the given canvas. The canvas's size will not be more than
* values returned by {@link #getPreferredCanvasSize(RenderingContext)}.
* @param canvas the canvas
*/
void render(RenderCanvas canvas);
/**
* Returns preferred dimensions of the object's render. If a dimension
* exceeds the canvas's dimension, the latter one is used instead.
* <p>Note: This method should not modify the given context in any way to avoid sudden side effects.
* @param ctx the rendering context
* @return the preferred dimensions
*/
Point2D getPreferredCanvasSize(RenderingContext ctx);
/**
* Checks if this object is visible. This method is used as a hint for skipping rendering of this object.
* @return whether this object must be rendered
*/
boolean isVisible();
/**
* Returns the graphic effect map to apply to this object's render. The map
* is mutable and can be also used to edit graphic effects.
* @return the graphic effect map of this object
*/
GraphicEffectMap getGraphicEffects();
}
@@ -0,0 +1,85 @@
package net.fokinatorr.sparkle.graphics.render.renderer;
import net.fokinatorr.sparkle.graphics.render.RenderCanvas;
import net.fokinatorr.sparkle.graphics.render.RenderingContext;
import net.fokinatorr.sparkle.phys2d.Hitbox2D;
import net.fokinatorr.sparkle.phys2d.Physical2D;
import net.fokinatorr.sparkle.stage.sprite.Sprite;
/**
* A 2D {@linkplain Renderable renderable} object is a 2-dimensional object with screen bounds,
* screen translation, rotation, and X/Y axis scaling. These operations are anchored at origin in the
* top-left corner.
* <p>Property methods (getters) must be side-effect-free, i.e. they should not do any modifications
* to the given rendering context or other stateful data structures to avoid unexpected side effects.
*
* @see Sprite Sprite - a general-purpose physical 2D renderable
* @see Physical2D
*/
public interface Renderable2D extends Renderable {
/**
* {@inheritDoc}
* The object must be rendered as if without any transformations applied.
* @param canvas {@inheritDoc}
*/
@Override
void render(RenderCanvas canvas);
/**
* {@return the X axis translation for this object}
* @param ctx the rendering context
*/
double getScreenX(RenderingContext ctx);
/**
* {@return the Y axis translation for this object}
* @param ctx the rendering context
*/
double getScreenY(RenderingContext ctx);
/**
* {@return the X coordinate of the point to rotate and scale around}
* Defaults to zero.
* @param ctx the rendering context
*/
default double getAnchorX(RenderingContext ctx) {
return 0;
}
/**
* {@return the Y coordinate of the point to rotate and scale around}
* Defaults to zero.
* @param ctx the rendering context
*/
default double getAnchorY(RenderingContext ctx) {
return 0;
}
/**
* {@return the rotation in degrees for this object}
* @param ctx the rendering context
*/
double getRotation(RenderingContext ctx);
/**
* {@return the X scale coefficient for this object}
* @param ctx the rendering context
*/
double getScreenScaleX(RenderingContext ctx);
/**
* {@return the Y scale coefficient for this object}
* @param ctx the rendering context
*/
double getScreenScaleY(RenderingContext ctx);
/**
* Returns this object's on-screen bounding hitbox, as if without any transformations applied.
* This can be used to check what object was clicked, what objects intersect, etc.
* <p>Note: This method should not modify the given context in any way to avoid sudden side effects.
* @param ctx the rendering context
* @return the bounding box
*/
Hitbox2D getBounds(RenderingContext ctx);
}
@@ -0,0 +1,230 @@
package net.fokinatorr.sparkle.graphics.render.renderer;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import net.fokinatorr.sparkle.graphics.render.RenderCanvas;
import net.fokinatorr.sparkle.graphics.render.RenderingContext;
import net.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
import net.fokinatorr.sparkle.phys2d.Hitbox2D;
import net.fokinatorr.sparkle.phys2d.Point2D;
import net.fokinatorr.sparkle.phys2d.impl.*;
import net.fokinatorr.sparkle.util.Mth;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import static lombok.AccessLevel.PRIVATE;
import static net.fokinatorr.sparkle.graphics.render.RenderCanvas.ORIGINAL_SIZE;
/**
* A renderer is an object that can render a specific type of objects. The objects don't have to
* implement {@link Renderable}. This interface allows for dynamic rendering implementations.
* @param <T> the type this renderer can draw
* @see ForRenderable
* @see ForRenderable2D
* @see ForRenderable2DWithHitbox
* @see Renderable
*/
public interface Renderer<T> {
/**
* Render the given object onto the given canvas.
* @param obj the object to render
* @param canvas the canvas
*/
void render(T obj, RenderCanvas canvas);
/**
* Checks if the given object is visible. This method is used as a hint for skipping rendering of the object.
* @param obj the object to check
* @return whether the object should be rendered
*/
boolean isVisible(T obj);
/**
* Returns the boundaries of the given object on a 2D surface.
*
* @param obj the object
* @param ctx the rendering context
* @return the object's 2D bounds
* @see RenderingSurface
*/
Hitbox2D getBounds(T obj, RenderingContext ctx);
/**
* A simple implementation of {@link Renderer} which draws {@link Renderable} objects.
* It is possible to extend this class and add custom functionality.
* @param <T> the type this renderer can draw
*/
class ForRenderable<T extends Renderable> implements Renderer<T> {
/**
* {@inheritDoc} The default implementation renders the object into a sub-canvas,
* then submits the image with the object's preferred {@linkplain Renderable#getPreferredCanvasSize size}
* and its {@linkplain Renderable#getGraphicEffects graphic effects}.
* @param obj {@inheritDoc}
* @param canvas {@inheritDoc}
*/
@Override
public void render(T obj, RenderCanvas canvas) {
canvas.save();
canvas.setEffects(obj.getGraphicEffects());
Point2D
dim = canvas.getDimensions(),
prefLayerDim = obj.getPreferredCanvasSize(canvas.getContext());
try (RenderCanvas layer = canvas.createSubCanvas(
Mth.clamp(1, prefLayerDim.x(), dim.x()),
Mth.clamp(1, prefLayerDim.y(), dim.y())
)) {
obj.render(layer);
layer.submitImage(0, 0, ORIGINAL_SIZE, ORIGINAL_SIZE);
}
canvas.restore();
}
/**
* {@inheritDoc} The default implementation calls the object's {@link Renderable#isVisible() isVisible()} method.
* @param obj {@inheritDoc}
* @return {@inheritDoc}
*/
@Override
public boolean isVisible(T obj) {
return obj.isVisible();
}
/**
* {@inheritDoc} The default implementation returns {@link Hitbox2D#never()}.
*
* @param obj {@inheritDoc}
* @param ctx
* @return {@inheritDoc}
*/
@Override
public Hitbox2D getBounds(T obj, RenderingContext ctx) {
return Hitbox2D.never();
}
}
/**
* An implementation of {@link Renderer} which draws {@link Renderable2D} objects,
* applying respective transformations.
* It is possible to extend this class and add custom functionality.
* @param <T> the type this renderer can draw
*/
@Slf4j
class ForRenderable2D<T extends Renderable2D> extends ForRenderable<T> {
@Override
public void render(T obj, RenderCanvas canvas) {
canvas.save();
RenderingContext ctx = canvas.getContext();
double rotation = obj.getRotation(ctx);
double scaleX = obj.getScreenScaleX(ctx), scaleY = obj.getScreenScaleY(ctx);
if (rotation % 360 != 0 || scaleX != 1 || scaleY != 1) {
double anchorX = obj.getAnchorX(ctx), anchorY = obj.getAnchorY(ctx);
canvas.translate(-anchorX, -anchorY);
canvas.rotate(obj.getRotation(ctx));
canvas.scale(obj.getScreenScaleX(ctx), obj.getScreenScaleY(ctx));
canvas.translate(obj.getScreenX(ctx) + anchorX, obj.getScreenY(ctx) + anchorY);
} else {
canvas.translate(obj.getScreenX(ctx), obj.getScreenY(ctx));
}
// Draw
super.render(obj, canvas);
canvas.restore();
}
/**
* {@inheritDoc} The default implementation calls the object's
* {@link Renderable2D#getBounds(RenderingContext) getBounds()} method and transforms it as needed.
*
* @param obj {@inheritDoc}
* @param ctx
* @return {@inheritDoc}
*/
@Override
public Hitbox2D getBounds(T obj, RenderingContext ctx) {
AffineTransform affine = new AffineTransform();
double anchorX = obj.getAnchorX(ctx), anchorY = obj.getAnchorY(ctx);
affine.translate(-anchorX, -anchorY);
affine.rotate(obj.getRotation(ctx));
affine.scale(obj.getScreenScaleX(ctx), obj.getScreenScaleY(ctx));
affine.translate(obj.getScreenX(ctx) + anchorX, obj.getScreenY(ctx) + anchorY);
return obj.getBounds(ctx).transform(affine);
}
}
/**
* An implementation of {@link Renderer} which draws a {@link Renderable2D} and its hitbox on top.
* It is possible to extend this class and add custom functionality.
* @param <T> the type this renderer can draw
*/
@Getter
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = PRIVATE)
class ForRenderable2DWithHitbox<T extends Renderable2D> extends ForRenderable2D<T> {
/**
* The outline color of the hitbox's area, in ARGB format.
*/
int outlineColor;
/**
* The fill color of the hitbox's area, in ARGB format.
*/
int fillColor;
@Override
public void render(T obj, RenderCanvas canvas) {
super.render(obj, canvas);
renderHitbox(getBounds(obj, canvas.getContext()), canvas);
}
private void renderHitbox(Hitbox2D hitbox, RenderCanvas canvas) {
switch (hitbox) {
case ShapeHitbox2D hb -> fillShape(hb.shape(), canvas);
case AlwaysHitbox2D _ -> {
canvas.save();
canvas.setStrokeARGB(fillColor);
canvas.setFillARGB(fillColor);
canvas.fillRect(Point2D.ZERO, canvas.getDimensions());
canvas.restore();
}
case TransformedHitbox2D thb -> {
canvas.save();
canvas.mulTransform(thb.transform());
renderHitbox(thb.delegate(), canvas);
canvas.restore();
}
case NeverHitbox2D _ -> {
}
case NotHitbox2D hb -> hb.createArea().ifPresentOrElse(
area -> fillShape(area, canvas),
() -> hb.delegate().createArea().ifPresent(area -> {
// NotHitbox's delegate is usually finite
Point2D dimensions = canvas.getDimensions();
Area negated = new Area(new Rectangle2D.Double(0, 0, dimensions.x(), dimensions.y()));
negated.subtract(area);
fillShape(negated, canvas);
})
);
default -> hitbox.createArea().ifPresent(area -> fillShape(area, canvas));
}
}
private void fillShape(Shape shape, RenderCanvas canvas) {
canvas.save();
canvas.setStrokeARGB(outlineColor);
canvas.setFillARGB(fillColor);
canvas.fillShape(shape);
canvas.restore();
}
}
}
@@ -1,11 +1,11 @@
package ru.fokinatorr.sparkle.graphics.render.renderer;
package net.fokinatorr.sparkle.graphics.render.renderer;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import lombok.extern.slf4j.Slf4j;
import ru.fokinatorr.sparkle.util.GUID;
import net.fokinatorr.sparkle.util.GUID;
import java.util.HashSet;
import java.util.LinkedList;
@@ -112,7 +112,7 @@ public final class RendererRegistry {
* @throws NullPointerException if no renderers were found for the given type
* @param <T> the type of the object
*/
public <T> Renderer<T> get(Class<T> type) {
public <T> Renderer<T> get(Class<? extends T> type) {
Renderer<T> renderer = null;
if (debugEnabled) {
renderer = find(debugRenderers, type);
@@ -122,7 +122,6 @@ public final class RendererRegistry {
}
if (renderer != null) {
log.trace("[RendererRegistry id={}] Resolved '{}' -> {}", id, type.getSimpleName(), renderer);
return renderer;
} else {
log.error(
@@ -158,7 +157,7 @@ public final class RendererRegistry {
* @return the best matching renderer, or {@code null} if none found
*/
@SuppressWarnings("unchecked")
private static <T> Renderer<T> find(Map<Class<?>, Renderer<?>> m, Class<T> type) {
private static <T> Renderer<T> find(Map<Class<?>, Renderer<?>> m, Class<? extends T> type) {
if (type == null) return null;
// Use a queue or stack to avoid deep recursion
@@ -0,0 +1,50 @@
package net.fokinatorr.sparkle.graphics.render.surface;
import net.fokinatorr.sparkle.graphics.render.framebuffer.OffscreenFramebuffer;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
/**
* An embedded surface (e.g. UI element). In general, more stationary than {@link WindowSurface}.
*/
public non-sealed interface EmbeddedSurface extends RenderingSurface {
@Override
default Set<Feature> getFeatures() {
return Collections.unmodifiableSet(EnumSet.of(
Feature.RESIZABLE,
Feature.NAMEABLE // label or just for debugging
));
}
@Override
void setSize(int newWidth, int newHeight);
@Override
String getName();
@Override
void setName(String name);
/**
* {@inheritDoc}
* <p>Embedded surfaces typically cannot directly use GPU-accelerated rendering APIs due to
* hosting environment restrictions (e.g., Swing, JavaFX). Instead, they render into an off-screen buffer
* using software or indirect GPU rendering, which is then copied to the display surface.
* @param prefWidth {@inheritDoc}
* @param prefHeight {@inheritDoc}
* @return {@inheritDoc}
*/
@Override
default OffscreenFramebuffer acquireBuffer(int prefWidth, int prefHeight) {
if (prefWidth < FB_ORIGINAL_SIZE || prefHeight < FB_ORIGINAL_SIZE) {
throw new IllegalArgumentException("Invalid framebuffer size: " + prefWidth + "x" + prefHeight);
}
return new OffscreenFramebuffer(
prefWidth == FB_ORIGINAL_SIZE ? getWidth() : prefWidth,
prefHeight == FB_ORIGINAL_SIZE ? getHeight() : prefHeight
);
}
}

Some files were not shown because too many files have changed in this diff Show More