commit 38c599c2cf630d0ebc8f14d07f6c90925d3c19f1 Author: Fokinator Date: Sat Apr 11 14:27:11 2026 +0300 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5ff6309 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..cfa8e6c --- /dev/null +++ b/pom.xml @@ -0,0 +1,236 @@ + + + 4.0.0 + + ru.fokinatorr.sparkle + sparkle-core + 1.0-SNAPSHOT + Sparkle Framework core module + + The core module of SFNS (code name Sparkle). + + Sparkle is a framework for creating graphical applications, with an API similar to the functionality MIT Scratch + offers. The primary difference + from Scratch is writing Java code instead of code blocks; there is also a lot more features and customization + support. + + To run Sparkle, you only need this module; if you want additional functionality, see other modules with group ID + "${project.groupId}". + + + + 25 + 25 + UTF-8 + 3.4.1 + 1.18.44 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + 25 + + + org.projectlombok + lombok + ${lombok.version} + + + + + + + + + + + lwjgl-natives-linux-amd64 + + + unix + linux + amd64 + + + + natives-linux + + + + lwjgl-natives-macos-x86_64 + + + mac + x86_64 + + + + natives-macos + + + + lwjgl-natives-macos-aarch64 + + + mac + aarch64 + + + + natives-macos-arm64 + + + + lwjgl-natives-windows-amd64 + + + windows + amd64 + + + + natives-windows + + + + + + + + + org.lwjgl + lwjgl-bom + ${lwjgl.version} + import + pom + + + + + + + + org.lwjgl + lwjgl + + + org.lwjgl + lwjgl-glfw + + + org.lwjgl + lwjgl-nanovg + + + org.lwjgl + lwjgl-openal + + + org.lwjgl + lwjgl-opengl + + + org.lwjgl + lwjgl-shaderc + + + org.lwjgl + lwjgl-stb + + + org.lwjgl + lwjgl + ${lwjgl.natives} + + + org.lwjgl + lwjgl-glfw + ${lwjgl.natives} + + + org.lwjgl + lwjgl-nanovg + ${lwjgl.natives} + + + org.lwjgl + lwjgl-openal + ${lwjgl.natives} + + + org.lwjgl + lwjgl-opengl + ${lwjgl.natives} + + + org.lwjgl + lwjgl-shaderc + ${lwjgl.natives} + + + org.lwjgl + lwjgl-stb + ${lwjgl.natives} + + + + org.projectlombok + lombok + ${lombok.version} + provided + + + it.unimi.dsi + fastutil + 8.5.15 + + + org.slf4j + slf4j-api + 2.0.16 + + + + ch.qos.logback + logback-classic + 1.5.18 + runtime + + + org.jspecify + jspecify + 1.0.0 + provided + + + org.joml + joml + 1.10.8 + + + ru.fokinatorr + lwjgl-exceptions + 1.0-SNAPSHOT + + + + io.github.hakky54 + logcaptor + 2.12.6 + test + + + org.junit.jupiter + junit-jupiter + 5.11.4 + test + + + \ No newline at end of file diff --git a/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/surface/vulkan/VKSurfaceFramebuffer.java b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/surface/vulkan/VKSurfaceFramebuffer.java new file mode 100644 index 0000000..97f7591 --- /dev/null +++ b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/surface/vulkan/VKSurfaceFramebuffer.java @@ -0,0 +1,44 @@ +package ru.fokinatorr.sparkle.graphics.impl.surface; + +import lombok.experimental.FieldDefaults; +import ru.fokinatorr.sparkle.graphics.PixelReader; +import ru.fokinatorr.sparkle.graphics.PixelWriter; +import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer; + +import static lombok.AccessLevel.PRIVATE; + +/** + * A {@code VKSurfaceKHR} frame buffer. + */ +@FieldDefaults(level = PRIVATE) +public class VKSurfaceFramebuffer implements Framebuffer { + + final int width, height; + final long vkSurface; // pointer + + + @Override + public int getWidth() { + return width; + } + + @Override + public int getHeight() { + return height; + } + + @Override + public PixelReader createPixelReader() { + return null; + } + + @Override + public PixelWriter createPixelWriter() { + return null; + } + + @Override + public void close() { + + } +} diff --git a/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/surface/vulkan/VK_GLFWWindowSurface.java b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/surface/vulkan/VK_GLFWWindowSurface.java new file mode 100644 index 0000000..90e6324 --- /dev/null +++ b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/surface/vulkan/VK_GLFWWindowSurface.java @@ -0,0 +1,397 @@ +package ru.fokinatorr.sparkle.graphics.impl.surface; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.experimental.FieldDefaults; +import lombok.extern.slf4j.Slf4j; +import org.lwjgl.glfw.GLFWVidMode; +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.framebuffer.Framebuffer; +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 java.util.*; +import java.util.concurrent.atomic.AtomicLong; + +import static org.lwjgl.glfw.GLFW.*; +import static org.lwjgl.system.MemoryUtil.NULL; + +/** + * A GLFW window rendering surface, providing Vulkan framebuffers. + */ +@Slf4j +@FieldDefaults(level = AccessLevel.PRIVATE) +public final class VK_GLFWWindowSurface implements WindowSurface { + /** + * The GLFW window pointer. + */ + @Getter + final long glfwWindow; // pointer + final List resizeCallback = new LinkedList<>(); + int[] oldXYWH = null; + boolean closed; + + + /** + * @throws NullPointerException if any argument is {@code null} + */ + @SuppressWarnings("resource") + VK_GLFWWindowSurface(long glfwWindow, EventDispatcher dispatcher, Stage stage) { + if (glfwWindow == NULL) { + throw new NullPointerException("glfwWindow"); + } + this.glfwWindow = glfwWindow; + Objects.requireNonNull(dispatcher, "dispatcher"); + Objects.requireNonNull(stage, "stage"); + + glfwSetKeyCallback(glfwWindow, (_, keyCode, scancode, action, modifiers) -> { + Key key = GLFWToPublicAPI.KEYS_MAP.get(keyCode); + if (key != null) { + switch (action) { + case GLFW_PRESS -> { + if (dispatcher.hasListenersFor(KeyboardEvent.KeyPressedEvent.class)) { + dispatcher.fireEvent(new KeyboardEvent.KeyPressedEvent(stage, key, modifiers)); + } + } + case GLFW_RELEASE -> { + if (dispatcher.hasListenersFor(KeyboardEvent.KeyReleasedEvent.class)) { + dispatcher.fireEvent(new KeyboardEvent.KeyReleasedEvent(stage, key, modifiers)); + } + } + case GLFW_REPEAT -> { + if (dispatcher.hasListenersFor(KeyboardEvent.KeyRepeatedEvent.class)) { + dispatcher.fireEvent(new KeyboardEvent.KeyRepeatedEvent(stage, key, modifiers)); + } + } + } + } else { + log.warn( + "Unknown key with scancode {} {}", + scancode, + switch (action) { + case GLFW_PRESS -> "pressed"; + case GLFW_RELEASE -> "released"; + case GLFW_REPEAT -> "repeated"; + default -> ""; + } + ); + } + }); + + glfwSetCharCallback(glfwWindow, (_, codePoint) -> { + if (dispatcher.hasListenersFor(KeyboardEvent.CharInputEvent.class)) { + dispatcher.fireEvent(new KeyboardEvent.CharInputEvent(stage, codePoint)); + } + }); + + AtomicLong lastMousePress = new AtomicLong(-1); + 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; + switch (action) { + case GLFW_PRESS -> { + lastMousePress.set(System.nanoTime()); + if (dispatcher.hasListenersFor(MouseEvent.MousePressedEvent.class)) { + dispatcher.fireEvent(new MouseEvent.MousePressedEvent(button, stage, x, y)); + } + } + case GLFW_RELEASE -> { + if (dispatcher.hasListenersFor(MouseEvent.MouseReleasedEvent.class)) { + dispatcher.fireEvent(new MouseEvent.MouseReleasedEvent(button, stage, x, y)); + } + 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)); + } + } + } + } + }); + + AtomicDouble lastMouseX = new AtomicDouble(-1); + AtomicDouble lastMouseY = new AtomicDouble(-1); + 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; + Set pressedButtons = EnumSet.noneOf(MouseButton.class); + for (int mb : GLFWToPublicAPI.MOUSE_BUTTONS_MAP.keySet()) { + if (glfwGetMouseButton(glfwWindow, mb) == GLFW_PRESS) { + pressedButtons.add(GLFWToPublicAPI.MOUSE_BUTTONS_MAP.get(mb)); + } + } + + dispatcher.fireEvent(new MouseEvent.MouseCursorMovedEvent(stage, oldX, oldY, newX, newY, pressedButtons)); + } + }); + + 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)); + } + }); + } + + + /** + * Creates a new non-fullscreen window. + * + * @param title the window title + * @param dispatcher the event dispatcher to use for sending window events + * @param stage the stage to use for sending window events + * @return a new window surface + */ + public static VK_GLFWWindowSurface create(String title, EventDispatcher dispatcher, Stage stage, boolean translucent) { + if (translucent) { + glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE); + glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); + } + VK_GLFWWindowSurface result = new VK_GLFWWindowSurface( + glfwCreateWindow(stage.getWidth(), stage.getHeight(), title, NULL, NULL), + dispatcher, stage + ); + if (translucent) { + glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE); + glfwWindowHint(GLFW_DECORATED, GLFW_TRUE); + } + return result; + } + + /** + * Creates a new fullscreen window. + * + * @param title the window title + * @param monitor the GLFW monitor on which the window should be fullscreen + * @param dispatcher the event dispatcher to use for sending window events + * @param stage the stage to use for sending window events + * @return a new window surface + */ + public static VK_GLFWWindowSurface createFullscreen(String title, long monitor /*pointer*/, + EventDispatcher dispatcher, Stage stage, + boolean translucent) { + if (translucent) { + glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE); + glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); + } + VK_GLFWWindowSurface result = new VK_GLFWWindowSurface( + glfwCreateWindow(stage.getWidth(), stage.getHeight(), title, monitor, NULL), + dispatcher, stage + ); + if (translucent) { + glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE); + glfwWindowHint(GLFW_DECORATED, GLFW_TRUE); + } + return result; + } + + + @Override + public int getWidth() { + ensureOpen(); + int[] w = {0}; + glfwGetWindowSize(glfwWindow, w, null); + return w[0]; + } + + @Override + public int getHeight() { + ensureOpen(); + int[] h = {0}; + glfwGetWindowSize(glfwWindow, null, h); + return h[0]; + } + + @Override + public Point2D getSize() { + ensureOpen(); + int[] w = {0}, h = {0}; + glfwGetWindowSize(glfwWindow, w, h); + return new Point2D(w[0], h[0]); + } + + @Override + public void pollEvents() { + ensureOpen(); + glfwPollEvents(); + } + + @Override + public Framebuffer acquireBuffer() { + // TODO + } + + @Override + public void present(Framebuffer frameBuffer) { + // TODO + } + + @Override + public boolean shouldClose() { + ensureOpen(); + return glfwWindowShouldClose(glfwWindow); + } + + @Override + public void onResize(ResizeListener callback) { + ensureOpen(); + resizeCallback.add(callback); + glfwSetWindowSizeCallback(glfwWindow, (_, width, height) -> { + for (var cb : resizeCallback) { + cb.resized(this, width, height); + } + }); + } + + @Override + public Set getFeatures() { + return Collections.unmodifiableSet(EnumSet.of( + Feature.RESIZABLE, + Feature.MOVABLE, + Feature.HIDEABLE, + Feature.NAMEABLE, + Feature.FULLSCREENABLE, + Feature.TRANSLUCENT + )); + } + + @Override + public void setSize(int newWidth, int newHeight) { + ensureOpen(); + glfwSetWindowSize(glfwWindow, newWidth, newHeight); + } + + @Override + public int getX() { + ensureOpen(); + int[] x = {0}; + glfwGetWindowPos(glfwWindow, x, null); + return x[0]; + } + + @Override + public int getY() { + ensureOpen(); + int[] y = {0}; + glfwGetWindowPos(glfwWindow, null, y); + return y[0]; + } + + @Override + public Point2D getPos() { + ensureOpen(); + int[] x = {0}, y = {0}; + glfwGetWindowPos(glfwWindow, x, y); + return new Point2D(x[0], y[0]); + } + + @Override + public void setPos(int newX, int newY) { + ensureOpen(); + glfwSetWindowPos(glfwWindow, newX, newY); + } + + @Override + public boolean isHidden() { + ensureOpen(); + return glfwGetWindowAttrib(glfwWindow, GLFW_VISIBLE) == GLFW_TRUE; + } + + @Override + public void show() { + ensureOpen(); + glfwShowWindow(glfwWindow); + } + + @Override + public void hide() { + ensureOpen(); + glfwHideWindow(glfwWindow); + } + + @Override + public String getName() { + ensureOpen(); + return glfwGetWindowTitle(glfwWindow); + } + + @Override + public void setName(String name) { + ensureOpen(); + glfwSetWindowTitle(glfwWindow, name); + } + + @Override + public boolean isFullscreen() { + ensureOpen(); + return glfwGetWindowMonitor(glfwWindow) != NULL; + } + + @Override + public void setFullscreen(boolean fullscreen) { + ensureOpen(); + GLFWVidMode vidMode = glfwGetVideoMode(glfwGetPrimaryMonitor()); + if (vidMode == null) { + throw new IllegalStateException("GLFW error"); + } + if (fullscreen) { + Point2D pos = getPos(), dimensions = getSize(); + oldXYWH = new int[] {(int) pos.x(), (int) pos.y(), (int) dimensions.x(), (int) dimensions.y()}; + glfwSetWindowMonitor( + glfwWindow, + glfwGetPrimaryMonitor(), + 0, 0, + vidMode.width(), vidMode.height(), + vidMode.refreshRate() + ); + } else { + glfwSetWindowMonitor( + glfwWindow, + NULL, + oldXYWH[0], oldXYWH[1], + oldXYWH[2], oldXYWH[3], + vidMode.refreshRate() + ); + oldXYWH = null; + } + } + + @Override + public boolean isTranslucent() { + ensureOpen(); + return glfwGetWindowAttrib(glfwWindow, GLFW_TRANSPARENT_FRAMEBUFFER) == GLFW_TRUE; + } + + @Override + public void close() { + if (!closed) { + glfwDestroyWindow(glfwWindow); + closed = true; + } + } + + private void ensureOpen() { + if (closed) { + throw new IllegalStateException("Window closed"); + } + } +} \ No newline at end of file diff --git a/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/AbstractVKContext.java b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/AbstractVKContext.java new file mode 100644 index 0000000..4010580 --- /dev/null +++ b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/AbstractVKContext.java @@ -0,0 +1,89 @@ +package ru.fokinatorr.sparkle.graphics.impl; + +import it.unimi.dsi.fastutil.objects.ObjectIntPair; +import lombok.Getter; +import lombok.experimental.FieldDefaults; +import lombok.experimental.NonFinal; +import org.lwjgl.PointerBuffer; +import org.lwjgl.vulkan.*; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.graphics.render.RenderingContext; +import ru.fokinatorr.sparkle.graphics.render.renderer.RendererRegistry; +import ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface; +import ru.fokinatorr.sparkle.stage.Stage; + +import java.util.List; +import java.util.Objects; + +import static lombok.AccessLevel.*; +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.vulkan.VK14.*; + +/** + * A Vulkan rendering context. + */ +@FieldDefaults(makeFinal = true, level = PROTECTED) +@Getter +public abstract class AbstractVKContext implements RenderingContext { + AppContext context; + RenderingSurface surface; + Stage stage; + VKRenderCanvas canvas; + @NonFinal + @Getter(NONE) + boolean closed; + + // Vulkan handles + VkDevice vkDevice; + VkQueue vkQ; + + protected AbstractVKContext( + AppContext context, + RenderingSurface surface, + Stage stage, + VkDevice vkDevice, int qFamilyIndex + ) { + this.context = Objects.requireNonNull(context, "context"); + this.surface = Objects.requireNonNull(surface, "surface"); + this.stage = Objects.requireNonNull(stage, "stage"); + this.vkDevice = Objects.requireNonNull(vkDevice, "VkDevice"); + + try (var stack = stackPush()) { + // + PointerBuffer qPtrBuf = stack.callocPointer(1); // NULL by default + vkGetDeviceQueue(vkDevice, qFamilyIndex, 0, qPtrBuf); + this.vkQ = new VkQueue(qPtrBuf.get(0), vkDevice); + // + this.canvas = createCanvas(); + } + } + + protected abstract VKRenderCanvas createCanvas(); + + @Override + public void close() { + if (!closed) { + canvas.close(); + surface.close(); + closed = true; + } + } + + protected void ensureOpen() { + if (closed) { + throw new IllegalStateException("This context is closed"); + } + } + + @SuppressWarnings("unchecked") + protected void renderStage(boolean renderControlBar) { + RendererRegistry registry = context.get(RendererRegistry.class); + for (ObjectIntPair spriteId : stage.getSpriteLayers()) { + Object renderable = stage.getSprite(spriteId.left(), spriteId.rightInt()); // TODO allow Stage to store not only sprites + registry.get((Class) renderable.getClass()).render(renderable, canvas); + } + if (renderControlBar) { + // TODO render stage's control bar + } + } +} diff --git a/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/VKEmbeddedContext.java b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/VKEmbeddedContext.java new file mode 100644 index 0000000..db40ae2 --- /dev/null +++ b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/VKEmbeddedContext.java @@ -0,0 +1,38 @@ +package ru.fokinatorr.sparkle.graphics.impl; + +import org.lwjgl.vulkan.VkDevice; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.graphics.render.surface.EmbeddedSurface; +import ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface; +import ru.fokinatorr.sparkle.stage.Stage; + +/** + * A VK context for embedded surfaces. + */ +public class VKEmbeddedContext extends AbstractVKContext { + protected VKEmbeddedContext(AppContext context, EmbeddedSurface surface, Stage stage, VkDevice vkDevice, int qFamilyIndex) { + super(context, surface, stage, vkDevice, qFamilyIndex); + } + + @Override + protected VKRenderCanvas createCanvas() { + // TODO + } + + @Override + public void present() { + ensureOpen(); + + EmbeddedSurface s = getSurface(); + var fb = s.acquireBuffer(); + canvas.attachTarget(fb); + renderStage(true); + canvas.flush(); + s.present(fb); + } + + @Override + public EmbeddedSurface getSurface() { + return (EmbeddedSurface) surface; + } +} diff --git a/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/VKRenderCanvas.java b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/VKRenderCanvas.java new file mode 100644 index 0000000..3db84c5 --- /dev/null +++ b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/VKRenderCanvas.java @@ -0,0 +1,19 @@ +package ru.fokinatorr.sparkle.graphics.impl; + +import ru.fokinatorr.sparkle.graphics.render.RenderCanvas; +import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer; + +public class VKRenderCanvas implements RenderCanvas { + // TODO everything + // TODO below methods are stubs + + public void attachTarget(Framebuffer frameBuffer) { + + } + + public void flush() { + + } + + +} diff --git a/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/VK_GLFWGraphicsManager.java b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/VK_GLFWGraphicsManager.java new file mode 100644 index 0000000..66bf735 --- /dev/null +++ b/src/main/java-unused/ru/fokinatorr/sparkle/graphics/impl/vulkan/VK_GLFWGraphicsManager.java @@ -0,0 +1,285 @@ +package ru.fokinatorr.sparkle.graphics.impl; + +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.objects.ObjectIntImmutablePair; +import it.unimi.dsi.fastutil.objects.ObjectIntPair; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; +import it.unimi.dsi.fastutil.objects.ReferenceReferenceImmutablePair; +import lombok.experimental.FieldDefaults; +import lombok.experimental.NonFinal; +import lombok.extern.slf4j.Slf4j; +import org.lwjgl.PointerBuffer; +import org.lwjgl.glfw.GLFW; +import org.lwjgl.glfw.GLFWErrorCallback; +import org.lwjgl.glfw.GLFWVulkan; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.vulkan.*; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher; +import ru.fokinatorr.sparkle.graphics.GraphicsManager; +import ru.fokinatorr.sparkle.graphics.impl.surface.VK_GLFWWindowSurface; +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.internal.access.SharedSecrets; +import ru.fokinatorr.sparkle.stage.Stage; +import ru.fokinatorr.sparkle.stage.StageCreator; +import ru.fokinatorr.sparkle.util.Version; + +import java.nio.IntBuffer; +import java.util.Map; +import java.util.Objects; +import java.util.OptionalInt; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.stream.IntStream; + +import static lombok.AccessLevel.PRIVATE; +import static org.lwjgl.glfw.GLFW.*; +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.vulkan.VK14.*; + +/** + * A Vulkan + GLFW graphics manager. + */ +@Slf4j +@FieldDefaults(makeFinal = true, level = PRIVATE) +public class VK_GLFWGraphicsManager implements GraphicsManager { + + Map vkContexts = new Reference2ReferenceOpenHashMap<>(); + AppContext context; + Queue workQueue = new ConcurrentLinkedQueue<>(); + @NonFinal boolean closed; + + // Vulkan global handles + VkInstance vk; + VkPhysicalDevice vkPhysDev; + VkDevice vkLogDev; + int qFamilyIndex; + + /** + * Important note: call the constructor and {@link #tick()} methods from the same thread, + * because GLFW's main thread is the one that called {@link GLFW#glfwInit() glfwInit()}! + */ + public VK_GLFWGraphicsManager(AppContext context) { + this.context = context; + + // Initialize GLFW + GLFWErrorCallback.createPrint(System.err).set(); + if (!glfwInit()) { + throw new IllegalStateException("Failed to initialize GLFW"); + } + if (!GLFWVulkan.glfwVulkanSupported()) { + throw new IllegalStateException("Vulkan not supported by GLFW"); + } + glfwDefaultWindowHints(); + // Critical: no OpenGL context — Vulkan manages rendering + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + + // Init global VK handles + try (var stack = stackPush()) { + this.vk = createVkInstance(stack); + var physDevAndQFamilyIdx = pickVkPhysicalDevice(stack); + this.vkPhysDev = physDevAndQFamilyIdx.left(); + this.qFamilyIndex = physDevAndQFamilyIdx.rightInt(); + this.vkLogDev = createVkLogicalDevice(stack); + } + // Most VK initialization done in VKContexts + } + + @Override + public void tick() { + ensureOpen(); + runTasks(); + for (AbstractVKContext vkContext : vkContexts.values()) { + vkContext.pollEvents(); + vkContext.present(); + if (vkContext.shouldClose()) { + vkContext.getStage().stop().thenRun(() -> { + // close and remove the context + vkContext.close(); + vkContexts.remove(vkContext.getStage()); + }); + } + // TODO + } + } + + @Override + public void close() { + if (!closed) { + vkContexts.values().forEach(AbstractVKContext::close); + vkContexts.clear(); + vkDestroyDevice(vkLogDev, null); + vkDestroyInstance(vk, null); + glfwTerminate(); + closed = true; + } + } + + @Override + public Pair createWindowContext(String title, StageCreator stageCreator, + boolean translucent, boolean fullscreen) { + ensureOpen(); + Stage stage = SharedSecrets.getStageAccess().newStage(stageCreator, context); + VK_GLFWWindowSurface window = fullscreen + ? VK_GLFWWindowSurface.createFullscreen(title, glfwGetPrimaryMonitor(), context.get(EventDispatcher.class), stage, translucent) + : VK_GLFWWindowSurface.create(title, context.get(EventDispatcher.class), stage, translucent); + return createAndPutWindowContext(window, stage); + } + + @Override + public Pair createContext(RenderingSurface surface, StageCreator stageCreator) { + ensureOpen(); + if (surface instanceof WindowSurface) { + if (surface instanceof VK_GLFWWindowSurface glfw) { + return createAndPutWindowContext(glfw, SharedSecrets.getStageAccess().newStage(stageCreator, context)); + } else { + throw new UnsupportedOperationException("Unsupported window surface: " + surface.getClass()); + } + } else if (!(surface instanceof EmbeddedSurface embedded)) { + throw new UnsupportedOperationException("Unsupported rendering surface: " + surface.getClass()); + } else { + return createAndPutEmbeddedContext(embedded, SharedSecrets.getStageAccess().newStage(stageCreator, context)); + } + } + + @Override + public AbstractVKContext getContext(Stage boundStage) { + ensureOpen(); + return vkContexts.get(Objects.requireNonNull(boundStage, "bound stage")); + } + + @Override + public boolean hasActiveContexts() { + return !(closed || vkContexts.isEmpty()); + } + + @Override + public void runLater(Runnable run) { + Objects.requireNonNull(run, "run"); + if (!workQueue.offer(run)) { + throw new IllegalStateException("Work queue overflow"); + } + } + + // Private implementation + + private void runTasks() { + Runnable task; + while ((task = workQueue.poll()) != null) { + try { + task.run(); + } catch (Exception e) { + log.error("Exception in graphics task", e); + } + } + } + + private void ensureOpen() { + if (closed) { + throw new IllegalStateException("Graphics manager already closed"); + } + } + + private synchronized Pair createAndPutEmbeddedContext(EmbeddedSurface surface, Stage stage) { + AbstractVKContext vkContext = new VKEmbeddedContext(context, surface, stage, vkLogDev, qFamilyIndex); + vkContexts.put(stage, vkContext); + return new ReferenceReferenceImmutablePair<>(stage, vkContext); + } + + private synchronized Pair createAndPutWindowContext(VK_GLFWWindowSurface surface, Stage stage) { + AbstractVKContext vkContext = null; // TODO + vkContexts.put(stage, vkContext); + return new ReferenceReferenceImmutablePair<>(stage, vkContext); + } + + + private static int getVkVersion(Version version) { + return VK_MAKE_VERSION(version.getMajor(), version.getMinor(), version.getPatch()); + } + + private VkInstance createVkInstance(MemoryStack stack) { + VkApplicationInfo appInfo = VkApplicationInfo.calloc(stack) + .sType(VK_STRUCTURE_TYPE_APPLICATION_INFO) + .pApplicationName(stack.ASCII("SparkleApp")) + .applicationVersion(getVkVersion(Version.current())) + .apiVersion(VK_API_VERSION_1_4); + + VkInstanceCreateInfo createInfo = VkInstanceCreateInfo.calloc(stack) + .sType(VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO) + .pApplicationInfo(appInfo) + .flags(0) + .ppEnabledExtensionNames(GLFWVulkan.glfwGetRequiredInstanceExtensions()); + + PointerBuffer instancePtrBuf = stack.mallocPointer(1); + int resultCode = vkCreateInstance(createInfo, null, instancePtrBuf); + + if (resultCode != VK_SUCCESS) { + throw new IllegalStateException("Failed to initialize Vulkan (error code " + resultCode + ")"); + } + + return new VkInstance(instancePtrBuf.get(), createInfo); + } + + private ObjectIntPair pickVkPhysicalDevice(MemoryStack stack) { + IntBuffer deviceCount = stack.mallocInt(1); + vkEnumeratePhysicalDevices(vk, deviceCount, null); + if (deviceCount.get(0) <= 0) { + throw new IllegalStateException("VK error: No suitable GPUs found"); + } + + PointerBuffer physDevices = stack.mallocPointer(deviceCount.get(0)); + vkEnumeratePhysicalDevices(vk, deviceCount, physDevices); + physDevices.rewind(); + VkPhysicalDevice physDevice = null; + int qFamilyIndex = -1; + while (physDevices.hasRemaining()) { + // Basically, we're looking for a physical device whose queues support graphics. + // Shouldn't all GPUs have it? Their second name is "graphics card" after all :P + VkPhysicalDevice pdHandle = new VkPhysicalDevice(physDevices.get(), vk); + + IntBuffer qFamilyPropsCount = stack.callocInt(1); + vkGetPhysicalDeviceQueueFamilyProperties(pdHandle, qFamilyPropsCount, null); + VkQueueFamilyProperties.Buffer qFamilyPropsBuff = VkQueueFamilyProperties.malloc(qFamilyPropsCount.get(0), stack); + vkGetPhysicalDeviceQueueFamilyProperties(pdHandle, qFamilyPropsCount, qFamilyPropsBuff); + + OptionalInt qFamilyIndexOpt = IntStream.range(0, qFamilyPropsBuff.capacity()) + .filter(idx -> (qFamilyPropsBuff.get(idx).queueFlags() & VK_QUEUE_GRAPHICS_BIT) != 0) + .findFirst(); + + if (qFamilyIndexOpt.isPresent()) { + physDevice = pdHandle; + qFamilyIndex = qFamilyIndexOpt.getAsInt(); + break; + } + } + if (physDevice == null) { + throw new IllegalStateException("VK error: Couldn't find GPU with graphics queue support"); + } + return new ObjectIntImmutablePair<>(physDevice, qFamilyIndex); + } + + private VkDevice createVkLogicalDevice(MemoryStack stack) { + VkDeviceQueueCreateInfo.Buffer qCreateInfos = VkDeviceQueueCreateInfo.calloc(1, stack) + .sType(VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO) + .queueFamilyIndex(qFamilyIndex) + .pQueuePriorities(stack.callocFloat(1).put(0, 1f)); + + VkPhysicalDeviceFeatures physDeviceFeatures = VkPhysicalDeviceFeatures.calloc(stack); + vkGetPhysicalDeviceFeatures(vkPhysDev, physDeviceFeatures); + + VkDeviceCreateInfo logDeviceCreateInfo = VkDeviceCreateInfo.calloc(stack) + .sType(VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO) + .pQueueCreateInfos(qCreateInfos) + .pEnabledFeatures(physDeviceFeatures); + + PointerBuffer logDevicePtrBuf = stack.callocPointer(1); // NULL by default because using calloc + int resultCode = vkCreateDevice(vkPhysDev, logDeviceCreateInfo, null, logDevicePtrBuf); + if (resultCode != VK_SUCCESS) { + throw new IllegalStateException("VK error: Failed to create logical device (error code " + resultCode + ")"); + } + return new VkDevice(logDevicePtrBuf.get(0), vkPhysDev, logDeviceCreateInfo); + } +} diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java new file mode 100644 index 0000000..1b79ffb --- /dev/null +++ b/src/main/java/module-info.java @@ -0,0 +1,53 @@ +/** + * The core module of Project Sparkle, where base API and implementation resides. + *

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 { + requires it.unimi.dsi.fastutil; + requires static lombok; + requires org.slf4j; + requires java.desktop; + requires org.lwjgl; + requires org.lwjgl.glfw; + requires org.lwjgl.openal; + requires org.lwjgl.opengl; + requires org.lwjgl.nanovg; + requires org.lwjgl.stb; + requires ru.fokinatorr.lwjgl.util.exceptions; + requires java.compiler; + requires java.management; + requires org.joml; + requires com.google.j2objc.annotations; + requires org.checkerframework.checker.qual; + + 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; +} \ No newline at end of file diff --git a/src/main/java/ru/fokinatorr/sparkle/assets/Assets.java b/src/main/java/ru/fokinatorr/sparkle/assets/Assets.java new file mode 100644 index 0000000..8ad6c42 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/assets/Assets.java @@ -0,0 +1,127 @@ +package ru.fokinatorr.sparkle.assets; + +import it.unimi.dsi.fastutil.objects.Object2IntFunction; +import ru.fokinatorr.sparkle.util.Constants; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import java.util.stream.Stream; + +import static java.util.function.Predicate.not; + +/** + * A set of assets (textures and sounds) with names. Can be queried by name and index. + *

Note for Scratchers: The indexes, unlike in Scratch, are starting from {@code 0} and NOT {@code 1}. + * Also, this interface is used both by stages and sprites, so the respective asset names (costumes + * for sprites, backdrops for stages) are unified under the term "textures". + * @see Constants#ROOT + */ +public interface Assets { + + /** + * Returns an immutable list of textures. + * + * @return textures to query by index + */ + List texturesByIndex(); + + /** + * Returns a function that maps texture names to texture indexes, + * and returns value less than {@code 0} for absent names. + * @return indexes to query by name + */ + Object2IntFunction texturesIndexesByName(); + + /** + * Returns an immutable list of sounds. + * + * @return sounds to query by index + */ + List soundsByIndex(); + + /** + * Returns a function that maps sound names to sound indexes, + * and returns value less than {@code 0} for absent names. + * @return sound indexes to query by name + */ + Object2IntFunction soundsIndexesByName(); + + /** + * An asset pointer with a name. + * + * @param name the asset name + * @param location the location of the asset + */ + record NamedAsset(String name, Path location) {} + + /** + * Creates and returns a {@code Assets} instance with contents of the given lists. + * + * @param textures the texture list + * @param sounds the sound list + * @return a new {@code Assets} + * @throws NullPointerException if one of the elements is {@code null} + * @throws IllegalArgumentException if there was a duplicate texture/sound name + */ + static Assets fromLoaded(List textures, List sounds) { + return new DefaultAssets(textures, sounds); + } + + /** + * Creates and returns a {@code Assets} instance with resolved assets from the given textures and sounds directories. + * The name of each asset will be the same as the file name, but without the last filename extension. + *

Note: files will only be read directly from the given directories, not recursively. The order of assets will be undefined. + *

Special handling for empty textures' directory: there will be only one empty SVG texture. + * + * @param texturesDir path to the textures directory + * @param soundsDir path to the sounds directory + * @return a new resolved {@code Assets} + * @throws IllegalArgumentException if one of the given paths does not locate a directory + * @throws NullPointerException if one of the paths is {@code null} + * @throws UncheckedIOException if one of the directories could not be opened + */ + static Assets resolve(Path texturesDir, Path soundsDir) { + checkIfDirectory(Objects.requireNonNull(texturesDir, "textures path")); + checkIfDirectory(Objects.requireNonNull(soundsDir, "sounds path")); + List texturesList, soundsList; + try (Stream textures = Files.list(texturesDir); + Stream sounds = Files.list(soundsDir)) { + texturesList = createAssets(textures); + soundsList = createAssets(sounds); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return fromLoaded(texturesList, soundsList); + } + + /** + * Returns an empty assets instance (one empty texture named {@code default} and no sounds). + * @return empty assets + */ + static Assets empty() { + return DefaultAssets.EMPTY_ASSETS; + } + + private static void checkIfDirectory(Path path) { + if (!Files.isDirectory(path)) { + throw new IllegalArgumentException("Not a directory: " + path.normalize()); + } + } + + private static List createAssets(Stream fromPaths) { + return fromPaths.filter(not(Files::isDirectory)) + .map(path -> { + String fileName = path.getFileName().toString(); + int lastDotIndex = fileName.lastIndexOf('.'); + String name = lastDotIndex > 0 + ? fileName.substring(0, lastDotIndex) + : fileName; // no extension + return new NamedAsset(name, path); + }) + .toList(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/assets/DefaultAssets.java b/src/main/java/ru/fokinatorr/sparkle/assets/DefaultAssets.java new file mode 100644 index 0000000..426ab8a --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/assets/DefaultAssets.java @@ -0,0 +1,57 @@ +package ru.fokinatorr.sparkle.assets; + +import it.unimi.dsi.fastutil.objects.Object2IntMap; +import it.unimi.dsi.fastutil.objects.Object2IntMaps; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; + +import java.util.List; +import java.util.Objects; + +import static ru.fokinatorr.sparkle.util.Constants.ROOT; + +/** + * Default implementation of {@link Assets}. + */ +record DefaultAssets( + List texturesByIndex, + Object2IntMap texturesIndexesByName, + List soundsByIndex, + Object2IntMap soundsIndexesByName +) implements Assets { + + DefaultAssets { + if (texturesByIndex.isEmpty()) { + texturesByIndex = List.of(EMPTY_TEXTURE); + texturesIndexesByName = Object2IntMaps.singleton(EMPTY_NAME, 0); + } + } + + static final String EMPTY_NAME = "default"; + static final NamedAsset EMPTY_TEXTURE = new NamedAsset(EMPTY_NAME, ROOT.resolve("assets/textures/empty.svg")); + static final DefaultAssets EMPTY_ASSETS = new DefaultAssets( + List.of(EMPTY_TEXTURE), + Object2IntMaps.singleton(EMPTY_NAME, 0), + List.of(), + Object2IntMaps.emptyMap() + ); + + DefaultAssets(List costumes, List sounds) { + Objects.requireNonNull(costumes, "Costumes list cannot be null"); + Objects.requireNonNull(sounds, "Sounds list cannot be null"); + this(costumes.isEmpty() ? List.of() : List.copyOf(costumes), mapNamesToIndexes(costumes), + List.copyOf(sounds), mapNamesToIndexes(sounds)); + } + + private static Object2IntMap mapNamesToIndexes(List assets) { + Object2IntMap map = new Object2IntOpenHashMap<>(assets.size()); + map.defaultReturnValue(-1); + for (int i = 0; i < assets.size(); i++) { + NamedAsset asset = assets.get(i); + if (map.put(asset.name(), i) >= 0) { + throw new IllegalArgumentException("Duplicate asset name: " + asset.name()); + } + } + // Return immutable map + return Object2IntMaps.unmodifiable(map); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/AudioManager.java b/src/main/java/ru/fokinatorr/sparkle/audio/AudioManager.java new file mode 100644 index 0000000..5110d1d --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/AudioManager.java @@ -0,0 +1,171 @@ +package ru.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 java.io.IOException; +import java.nio.file.Path; + +/** + * An audio manager is responsible for sound loading and managing {@link SoundInstance sound instances}. + *

Note: Do not manually close sound instance objects returned by an audio manager. Instead, use + * the {@link #destroySoundInstance(String)} method for proper cleanup. + */ +public interface AudioManager extends NonThrowingAutoCloseable { + + /** + * Loads a sound from file at the given path. If a sound is already loaded at the given path, it is closed, removed and replaced with a new one. + * The sprite/stage assets are loaded automatically, so there's usually no need to call this method manually. + *

See {@link SoundDecoder} for supported formats list. + * + * @param path the path to the sound file + * @throws IOException if something goes wrong during loading, or if the file format isn't recognized + * @see #loadSounds(Path...) + * @see #loadSounds(Iterable) + * @see SoundDecoder + */ + void loadSound(Path path) throws IOException; + + /** + * Array bulk version of {@link #loadSound(Path)}. + * The sprite/stage assets are loaded automatically, so there's usually no need to call this method manually. + * + * @param paths the paths to sound files + * @throws IOException if something goes wrong during loading, or if the file format isn't recognized + * @implNote By default, if loading of a sound file fails, this method will continue loading other files + * and then throw the exception. If multiple sound files fail to load, their exceptions will get suppressed into one. + * @see #loadSound(Path) + */ + default void loadSounds(Path... paths) throws IOException { + IOException ex = null; + for (Path path : paths) { + try { + loadSound(path); + } catch (IOException e) { + if (ex == null) { + ex = e; + } else { + ex.addSuppressed(e); + } + } + } + if (ex != null) { + throw ex; + } + } + + /** + * {@link Iterable} bulk version of {@link #loadSound(Path)}. + * The sprite/stage assets are loaded automatically, so there's usually no need to call this method manually. + * + * @param paths the paths to sound files + * @throws IOException if something goes wrong during loading, or if the file format isn't recognized + * @implNote By default, if loading of a sound file fails, this method will continue loading other files + * and then throw the exception. If multiple sound files fail to load, their exceptions will get suppressed into one. + * @see #loadSound(Path) + */ + default void loadSounds(Iterable paths) throws IOException { + IOException ex = null; + for (Path path : paths) { + try { + loadSound(path); + } catch (IOException e) { + if (ex == null) { + ex = e; + } else { + ex.addSuppressed(e); + } + } + } + if (ex != null) { + throw ex; + } + } + + /** + * Determines whether a sound is already loaded from file at the given path. This can be useful + * to prevent unnecessary sound reloading. + * This is always true for sprite/stage assets since they're loaded automatically. + * @param path the file path + * @return {@code true} if a sound from file at the given path is already loaded by this manager, {@code false} + * otherwise. + */ + boolean hasLoadedSound(Path path); + + /** + * Creates a new sound instance from the loaded sound at the given path. + *

This is ideal for short sounds like sound effects or UI feedback that should load quickly and play immediately. + *

A sound must be loaded at the given path using {@link #loadSound(Path)} before calling this method. (For sprite/stage assets, + * this is done automatically.) + *

Note for Scratchers: "Static" sound instances are similar to how all sounds work in Scratch. + * The sound is fully loaded into memory, so it starts playing instantly and can be played multiple times efficiently. + *

To play a sound just like it's done in Scratch (from a sprite's assets, one-shot), it's better + * to use the {@code startSound(...)} methods of {@link Sprite}. They handle the sound instance's lifecycle automatically. + * + * @param filePath the path to the (already loaded!) sound file + * @return a {@link Pair} containing: + *

    + *
  • Key: The unique ID of the new sound instance
  • + *
  • Value: The sound instance itself, ready to play
  • + *
+ * @throws IllegalArgumentException if no sound is loaded at the given path + * @throws IllegalStateException if this audio manager is closed + */ + Pair> createStaticSoundInstance(Path filePath); + + /** + * Creates a new "streaming" sound instance from the loaded sound at the given path. + *

Streaming sound instances are dynamic; they don't store their data all at once but instead request chunks on demand. + * This works well with long ambient music tracks, since they don't get loaded entirely immediately, which would cause lags. + *

A sound must be loaded at the given path using {@link #loadSound(Path)} before calling this method. (For sprite/stage assets, + * this is done automatically.) + *

Note for Scratchers: This is different from how sounds work in Scratch. In Scratch, all sounds are loaded fully before playing. + * Here, streaming allows very long sounds (like background music) to play without delay and with low memory usage. + * Use this for tracks longer than ~30 seconds. + * + * @param filePath the path to the (already loaded!) sound file + * @param loop whether the sound instance must loop + * @return a {@link Pair} containing: + *

    + *
  • Key: The unique ID of the new sound instance
  • + *
  • Value: The sound instance itself, ready to play
  • + *
+ * @throws IllegalArgumentException if no sound is loaded at the given path + * @throws IllegalStateException if this audio manager is closed + */ + Pair> createStreamingSoundInstance(Path filePath, boolean loop); + + /** + * Returns a sound source by the given ID, if any, otherwise returns {@code null}. + * + * @param id the ID + * @return the respective sound source or {@code null} + * @throws IllegalStateException if the audio manager is closed + */ + SoundInstance getSoundInstance(String id); + + /** + * If a sound source with the given ID exists, stops, closes and removes it, otherwise does nothing. + * + * @param id the ID + * @throws IllegalStateException if the audio manager is closed + */ + void destroySoundInstance(String id); + + /** + * Advances the audio manager by one tick. This method is called regularly from the audio loop, no + * need to call in manually in your code. + * + * @throws IllegalStateException if the audio manager is closed + */ + void tick(); + + /** + * Destroys this audio manager. The manager can not be used after call to this method. + * Calling this method more than once does not have any effect. + */ + @Override + void close(); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/SoundInstance.java b/src/main/java/ru/fokinatorr/sparkle/audio/SoundInstance.java new file mode 100644 index 0000000..255e71f --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/SoundInstance.java @@ -0,0 +1,191 @@ +package ru.fokinatorr.sparkle.audio; + +import ru.fokinatorr.sparkle.effect.EffectMap; +import ru.fokinatorr.sparkle.effect.sounds.SoundEffect; + +import java.util.Objects; + +/** + * A playable sound instance. It has a {@link State state} and may have {@link SoundEffect sound effects}. + *

This interface is implemented by the internal APIs, which expect a concrete implementation, + * and thus this interface must not be implemented directly or indirectly by other classes. + * @param the type of this sound instance + */ +public interface SoundInstance> { + + // Sound state + + /** + * A state of a sound instance. + */ + enum State { + /** + * The initial state. The sound position is at the beginning, and the sound is not playing. + * This state does not guarantee that the sound was never played yet. + */ + INITIAL, + /** + * The playing state. The sound is currently playing. + */ + PLAYING, + /** + * The paused state. The sound position is at where the sound was paused, and the sound is not playing. + * Changing from this state to playing state will resume the sound. + */ + PAUSED, + /** + * The stopped state. The sound position is at the beginning, and the sound is not playing. + * This state guarantees that the sound has already been played at least once. + */ + STOPPED + } + + /** + * If this sound is stopped, firstly {@link #rewind() rewinds} it, then plays. + * Otherwise, if it is already playing, does nothing, otherwise plays it. + */ + void play(); + + /** + * If this sound is playing, pauses it, otherwise does nothing. + */ + void pause(); + + /** + * If this sound is in initial state or stopped, does nothing, otherwise + * stops this sound. + */ + void stop(); + + /** + * If the state of this sound is already initial, does nothing. If this sound + * is playing or paused, firstly {@link #stop() stops} it, then rewinds it and sets the state to initial. + * If this sound is stopped, just sets the state to initial. + */ + void rewind(); + + /** + * Calls one of the state changing methods depending on the given state enum. + *

    + *
  • If the given state is {@link State#PLAYING}, calls {@link #play()} on this sound;
  • + *
  • For {@link State#PAUSED}, calls {@link #pause()};
  • + *
  • For {@link State#STOPPED}, calls {@link #stop()};
  • + *
  • For {@link State#INITIAL}, calls {@link #rewind()}.
  • + *
+ * @param newState the new state + * @return the actual current state after calling the corresponding method + * @throws NullPointerException if the state is {@code null} + */ + default State setState(State newState) { + switch (Objects.requireNonNull(newState)) { + case PLAYING -> play(); + case PAUSED -> pause(); + case STOPPED -> stop(); + case INITIAL -> rewind(); + } + return getState(); + } + + /** + * Returns the current state of this sound. + * @return the current state + */ + State getState(); + + + // Properties + + /** + * Sets the given effect to the given value, which is normalized according to the given effect's rules. + * @param effect the effect + * @param value the new value + * @throws NullPointerException if the given sound effect is {@code null} + * @return this sound instance + */ + SELF effect(SoundEffect effect, double value); + + /** + * Sets the volume for this sound. The given new volume value is normalized according to the rules of the volume effect. + * @param newVolume the new volume + * @return this sound instance + */ + default SELF volume(double newVolume) { + return effect(SoundEffect.VOLUME, newVolume); + } + + /** + * Sets the pitch for this sound. The given new pitch value is normalized according to the rules of the pitch effect. + * @param newPitch the new pitch + * @return this sound instance + */ + default SELF pitch(double newPitch) { + return effect(SoundEffect.PITCH, newPitch); + } + + /** + * Sets the pan for this sound. The given new pan value is normalized according to the rules of the pan effect. + * @param newPan the new pan + * @return this sound instance + */ + default SELF pan(double newPan) { + return effect(SoundEffect.PAN, newPan); + } + + /** + * Returns the given effect's value for this sound. + * @param effect the effect + * @return the effect's value + * @throws NullPointerException if the effect is {@code null} + */ + double effect(SoundEffect effect); + + /** + * Returns the volume of this sound. + * @return the volume + */ + default double volume() { + return effect(SoundEffect.VOLUME); + } + + /** + * Returns the pitch of this sound. + * @return the pitch + */ + default double pitch() { + return effect(SoundEffect.PITCH); + } + + /** + * Returns the pan of this sound. + * @return the pan + */ + default double pan() { + return effect(SoundEffect.PAN); + } + + /** + * Copies the sound effects to this sound. + * + * @param soundEffects the sound effects to copy + * @return this sound instance + * @throws NullPointerException if the given sound effect map is {@code null} + */ + SELF copyPropertiesFrom(EffectMap soundEffects); + + /** + * Attaches the sound effects to this sound. The values from this map will be copied + * to this sound constantly. + * @param soundEffects the sound effect map to listen to + * @return this sound instance + * @throws NullPointerException if the given sound effect map is {@code null} + */ + SELF attachProperties(EffectMap soundEffects); + + /** + * Detaches the sound effects from this sound. The properties of this sound will no longer + * be constantly changing after calling this method. + * + * @return this sound instance + */ + SELF detachProperties(); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/BaseSoundSource.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/BaseSoundSource.java new file mode 100644 index 0000000..475c756 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/BaseSoundSource.java @@ -0,0 +1,343 @@ +package ru.fokinatorr.sparkle.audio.impl; + +import lombok.AccessLevel; +import lombok.Getter; +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 java.nio.FloatBuffer; +import java.util.Objects; + +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.*; + +/** + * Base interface for managing OpenAL sound sources. + * + * @param the type of this sound buffer + */ +@Slf4j +@Getter +//@ALCheckError +public abstract class BaseSoundSource> implements NonThrowingAutoCloseable, SoundInstance { + + /** + * The OpenAL source ID. + *

-- GETTER -- + *

Returns the OpenAL source ID. + * + * @return the 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}. + */ + protected EffectMap attachedEffects; + + /** + * Constructor for subclasses to call. + */ + protected BaseSoundSource(int sourceId) { + this.sourceId = sourceId; + alSourcei(sourceId, AL_SOURCE_RELATIVE, AL_FALSE); + alSource3f(sourceId, AL_POSITION, 0.0f, 0.0f, 0.0f); + } + + /** + * Enum class representing an OpenAL sound source state. + */ + @Getter + @RequiredArgsConstructor + @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) + public enum SourceState { + INITIAL(AL_INITIAL), + PLAYING(AL_PLAYING), + PAUSED(AL_PAUSED), + STOPPED(AL_STOPPED); + + /** + * The corresponding OpenAL source state. + */ + int openALSourceState; + + /** + * Returns a source state corresponding to the given OpenAL source state. + * + * @param openALSourceState the OpenAL source state + * @return the corresponding source state instance + * @throws IllegalArgumentException if there is no such source state + */ + public static SourceState valueOf(int openALSourceState) { + return switch (openALSourceState) { + case AL_INITIAL -> INITIAL; + case AL_PLAYING -> PLAYING; + case AL_PAUSED -> PAUSED; + case AL_STOPPED -> STOPPED; + default -> throw new IllegalArgumentException("Unexpected source state: " + openALSourceState); + }; + } + + /** + * Converts this OpenAL source state to a {@link SoundInstance.State}. + * @return the corresponding {@link SoundInstance.State} to this source state + */ + public SoundInstance.State toPublicAPIState() { + return switch (this) { + case INITIAL -> SoundInstance.State.INITIAL; + case PLAYING -> SoundInstance.State.PLAYING; + case PAUSED -> SoundInstance.State.PAUSED; + case STOPPED -> SoundInstance.State.STOPPED; + }; + } + } + + /** + * This method must return this sound source. + * + * @return this sound source + */ + protected abstract SELF self(); + + /** + * If the state of this source is stopped, firstly sets it to initial, then to playing. + * Otherwise, if the state is not already playing, sets it to playing. + *

If the state was paused, the source is resumed, i.e. starts playing from the + * current sampling offset. Otherwise, the source starts playing from the beginning. + */ + @Override + public void play() { + // 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) { + rewind(); + } + // alSourcePlay applied to an already playing source will reset + // the source's sampling offset, i.e. start playing it from the beginning. + // We change that to a NOP to avoid confusion and encourage explicit stopping for that purpose + if (getALState() != SourceState.PLAYING) { + alSourcePlay(sourceId); + } + } + + /** + * If the state of this source is playing, sets it to paused, otherwise does nothing. + */ + @Override + public void pause() { + alSourcePause(sourceId); + } + + /** + * If the state of this source is initial or stopped, does nothing, otherwise + * sets the state of this source to stopped. + */ + @Override + public void stop() { + alSourceStop(sourceId); + } + + /** + * If the state of this source is already initial, does nothing. If the state + * is playing or paused, firstly {@link #stop() stops} this source, then sets the state + * to initial. If the state is stopped, just sets the state to initial. + */ + @Override + public void rewind() { + // 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(); + if (alState == SourceState.PAUSED || alState == SourceState.PLAYING) { + stop(); + } + alSourceRewind(sourceId); + } + + /** + * Returns the OpenAL source state of this source. + * @return the source state + */ + public SourceState getALState() { + return SourceState.valueOf(alGetSourcei(sourceId, AL_SOURCE_STATE)); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public SoundInstance.State getState() { + return getALState().toPublicAPIState(); + } + + /** + * Sets the pitch for this sound source. + * + * @param newPitch the new pitch + * @return this sound source + */ + public SELF alPitch(float newPitch) { + alSourcef(sourceId, AL_PITCH, newPitch); + return self(); + } + + /** + * Sets the gain for this sound source. + * + * @param newGain the new gain + * @return this sound source + */ + public SELF alGain(float newGain) { + alSourcef(sourceId, AL_GAIN, newGain); + return self(); + } + + /** + * Sets the position for this sound source (relative to the listener's position). + * + * @param x the X coordinate + * @param y the Y coordinate + * @param z the Z coordinate + * @return this sound source + */ + public SELF alPosition(float x, float y, float z) { + alSource3f( + sourceId, AL_POSITION, + x, y, z + ); + return self(); + } + + /** + * {@inheritDoc} + * @param effect {@inheritDoc} + * @param value {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public SELF effect(SoundEffect effect, double value) { + Objects.requireNonNull(effect, "sound effect"); + value = effect.normalize(value); + return switch (effect) { + case VOLUME -> alGain((float) (value / 100d)); + case PITCH -> alPitch((float) PitchConversion.toALPitch(value)); + case PAN -> alPosition((float) (value / 100d), 0f, 0f); + }; + } + + /** + * {@inheritDoc} + * @param effect {@inheritDoc} + * @return {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + */ + @Override + public double effect(SoundEffect effect) { + return switch (Objects.requireNonNull(effect, "sound effect")) { + case VOLUME -> alGain() * 100d; + case PITCH -> PitchConversion.fromALPitch(alPitch()); + case PAN -> alPosition()[0] * 100d; + }; + } + + /** + * {@inheritDoc} + * @param soundEffects {@inheritDoc} + * @return {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + */ + @Override + public SELF copyPropertiesFrom(EffectMap soundEffects) { + Objects.requireNonNull(soundEffects, "sound effects"); + return alPitch((float) PitchConversion.toALPitch(soundEffects.getDouble(SoundEffect.PITCH))) + .alGain((float) (soundEffects.getDouble(SoundEffect.VOLUME) / 100d)) + .alPosition((float) (soundEffects.getDouble(SoundEffect.PAN) / 100d), 0f, 0f); + } + + /** + * {@inheritDoc} + * @param soundEffects {@inheritDoc} + * @return {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + */ + @Override + public SELF attachProperties(EffectMap soundEffects) { + this.attachedEffects = Objects.requireNonNull( + soundEffects, + "Sound effects map cannot be null" + ); + return self(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public SELF detachProperties() { + this.attachedEffects = null; + return self(); + } + + /** + * {@return the pitch of this sound source} + */ + public float alPitch() { + return alGetSourcef(sourceId, AL_PITCH); + } + + /** + * {@return the gain of this sound source} + */ + public float alGain() { + return alGetSourcef(sourceId, AL_GAIN); + } + + /** + * Returns a {@code float} array with length {@code 3}, where the 0th element represents the X position + * of this sound source, the 1st element represents the Y position of this sound source and + * the 2nd element represents the Z position of this sound source. Changing the contents of the array + * will not affect this sound source. + * + * @return the position of this sound source + */ + public float[] alPosition() { + FloatBuffer pos = memAllocFloat(3); + try (var _ = freeing(pos)) { + alGetSource3f( + sourceId, AL_POSITION, + pos, + memDuplicate(pos).position(1), + memDuplicate(pos).position(2) + ); + pos.clear(); + return new float[]{pos.get(), pos.get(), pos.get()}; + } + } + + /** + * Ticks this source. This method is executed repeatedly for each {@link SourceState#PLAYING playing} sound source in the audio engine loop. + */ + public void tick() { + if (attachedEffects != null) { + //noinspection resource + copyPropertiesFrom(attachedEffects); + } + } + + /** + * Destroys this sound source and releases all associated resources. + * The sound source should not be able to be used after calling this method. + * Calling this method more than once should not have any effect. + */ + @Override + public abstract void close(); // Overrides JavaDoc +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/OpenALAudioManager.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/OpenALAudioManager.java new file mode 100644 index 0000000..c4b12be --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/OpenALAudioManager.java @@ -0,0 +1,332 @@ +package ru.fokinatorr.sparkle.audio.impl; + +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.Int2IntMap; +import it.unimi.dsi.fastutil.objects.ObjectObjectImmutablePair; +import lombok.AccessLevel; +import lombok.experimental.ExtensionMethod; +import lombok.experimental.FieldDefaults; +//import lombok.extern.lwjgl.ALCheckError; +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 java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.nio.file.Path; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +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; + +/** + * The entry point for creating an OpenAL audio engine. + *

+ * The audio manager is not thread-safe. All methods except {@link #close()} + * should be called from the same thread that calls {@link #tick()} (usually the main/game loop). + *

Note: Do not manually close sound source objects returned by an instance of this class. Instead, use + * the {@link #destroySoundInstance(String)} method for proper cleanup. + */ +@Slf4j +@ExtensionMethod(OpenALAudioManager.class) +@FieldDefaults(level = AccessLevel.PRIVATE) +//@ALCheckError +public class OpenALAudioManager implements AudioManager { + + private static final int DEFAULT_STREAMING_BUFFER_SIZE = 8192; + // Look along negative Z (standard right-handed coordinate system) + private static final float[] DEFAULT_ORIENTATION = + {0.0f, 0.0f, -1.0f, // look direction + 0.0f, 1.0f, 0.0f}; // up vector + + private static final AtomicBoolean CREATE_LOCK = new AtomicBoolean(); + + long device; // pointer + long alcContext; // pointer + final Map parsedSounds = new HashMap<>(); + final Map> sources = new HashMap<>(); + final AppContext appContext; + + + /** + * Creates a new audio engine that opens the default audio device. + * + * @param appContext the application context (used to get sound decoders) + * @throws IllegalStateException if initialization fails for any reason + */ + public OpenALAudioManager(AppContext appContext) { + if (!CREATE_LOCK.compareAndSet(false,true)) { + throw new IllegalStateException("OpenALAudioManager is a singleton, only one instance allowed"); + } + + this.appContext = appContext; + + device = alcOpenDevice((ByteBuffer) null); // null = default device + if (device == NULL) { + throw new IllegalStateException("Could not open an audio device"); + } + ALCCapabilities deviceCaps = createCapabilities(device); + alcContext = alcCreateContext(device, createContextAttributes(null)); + if (alcContext == NULL) { + throw new IllegalStateException("Could not create OpenAL device context"); + } + alcMakeContextCurrent(alcContext); + AL.createCapabilities(deviceCaps); + alListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f); + alListenerfv(AL_ORIENTATION, DEFAULT_ORIENTATION); + } + + // Loading sound data (only OGG support so far) + + /** + * {@inheritDoc} + * + * @param path {@inheritDoc} + * @throws IOException {@inheritDoc} + */ + @Override + public void loadSound(Path path) throws IOException { + IOException ex = null; + ParsedSoundImpl newSound = null; + if (device != NULL && alcContext != NULL) { + for (SoundDecoder decoder : appContext.getAll(SoundDecoder.class)) { + try { + newSound = ParsedSoundImpl.fromPublicAPI(decoder.parseFile(path)); + if (decoder.getSupportedExtensions().stream().noneMatch(ext -> path.getFileName().toString().endsWith(ext))) { + logWrongFilenameExt(decoder.getFormatName(), decoder.getSupportedExtensions(), path); + } + break; + } catch (IOException e) { + log.debug("Could not read '{}' as {}", path.getFileName(), decoder.getFormatName(), e); + if (ex == null) { + ex = e; + } else { + ex.addSuppressed(e); + } + } + } + } + if (newSound == null) { + if (ex != null) { + log.error("Could not load '{}' as audio; either not an audio file or the format is unsupported", path.getFileName(), ex); + throw ex; + } else { + log.error("Could not load '{}' as audio; no sound decoders available", path.getFileName()); + throw new IOException("No supported formats found"); + } + } else { + ParsedSoundImpl oldSound = parsedSounds.put(path, newSound); + if (oldSound != null) { + oldSound.close(); + } + } + } + + /** + * {@inheritDoc} + * + * @param path {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean hasLoadedSound(Path path) { + return parsedSounds.containsKey(path); + } + + // Creating/managing sound sources + + /** + * Creates a new {@link StaticSoundSource} from the loaded sound at the given path. A sound must be + * loaded with {@link #loadSound(Path)} before calling this method. + * + * @param path the path to the loaded sound + * @return a pair containing the ID of the new sound source and the sound source itself + * @throws IllegalArgumentException if no sound is loaded at the given path + * @throws IllegalStateException if the audio manager is closed + */ + @Override + public Pair createStaticSoundInstance(Path path) { + ensureOpen(); + ensureContext(); + ParsedSoundImpl parsed = getParsedSound(path); + SoundBuffer buffer = parsed.createStandAloneBuffer(); + + String id = GUID.generate(); + StaticSoundSource source = new StaticSoundSource(buffer); + sources.put(id, source); + return new ObjectObjectImmutablePair<>(id, source); + } + + /** + * {@inheritDoc} + * + * @param path {@inheritDoc} + * @param loop {@inheritDoc} + * @return {@inheritDoc} + * @throws IllegalArgumentException {@inheritDoc} + * @throws IllegalStateException {@inheritDoc} + */ + @Override + public Pair createStreamingSoundInstance(Path path, boolean loop) { + return createStreamingSoundInstance(path, DEFAULT_STREAMING_BUFFER_SIZE, loop); + } + + /** + * Creates a new streaming sound source from the loaded sound at the given path. A sound must be + * loaded with {@link #loadSound(Path)} before calling this method. + * + * @param path the path to the loaded sound + * @param maxBufferSize the maximum size (in samples per channel) for each streamed buffer + * @param loop whether the source should loop + * @return a pair containing the ID of the new sound source and the sound source itself + * @throws IllegalArgumentException if no sound is loaded at the given path + * @throws IllegalStateException if the audio manager is closed + */ + public Pair createStreamingSoundInstance(Path path, int maxBufferSize, boolean loop) { + ensureOpen(); + ensureContext(); + ParsedSoundImpl parsed = getParsedSound(path); + SoundBufferProvider provider = parsed.createProvider(maxBufferSize, loop); + + String id = GUID.generate(); + StreamingSoundSource source = new StreamingSoundSource(provider, 3); + sources.put(id, source); + return new ObjectObjectImmutablePair<>(id, source); + } + + /** + * Returns a sound source by the given ID, if any, otherwise returns {@code null}. + * + * @param id the ID + * @return the respective sound source or {@code null} + * @throws IllegalStateException if the audio manager is closed + */ + @Override + public BaseSoundSource getSoundInstance(String id) { + ensureOpen(); + return sources.get(id); + } + + /** + * If a sound source with the given ID exists, stops, closes and removes it, otherwise does nothing. + * + * @param id the ID + * @throws IllegalStateException if the audio manager is closed + */ + @Override + public void destroySoundInstance(String id) { + ensureOpen(); + ensureContext(); + if (sources.containsKey(id)) { + 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 + source.stop(); + source.close(); + } + } + + // Engine state management + + /** + * Advances the audio manager by one tick. Should be called regularly from the main/game loop. + * + * @throws IllegalStateException if the audio manager is closed + */ + @Override + public void tick() { + ensureOpen(); + ensureContext(); + for (BaseSoundSource source : sources.values()) { + if (source.getALState() == PLAYING) source.tick(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void close() { + parsedSounds.values().forEach(ParsedSoundImpl::close); + parsedSounds.clear(); + sources.values().forEach(BaseSoundSource::close); + sources.clear(); + if (alcContext != NULL) { + alcMakeContextCurrent(NULL); + alcDestroyContext(alcContext); + alcContext = NULL; + } + if (device != NULL) { + alcCloseDevice(device); + device = NULL; + } + CREATE_LOCK.set(false); + } + + // Private methods + + private void ensureOpen() { + if (device == NULL || alcContext == NULL) { + throw new IllegalStateException("AudioManager is closed"); + } + } + + private void ensureContext() { + if (alcContext != NULL && alcGetCurrentContext() == NULL) { + alcMakeContextCurrent(alcContext); + } + } + + private ParsedSoundImpl getParsedSound(Path path) { + if (hasLoadedSound(path)) { + return parsedSounds.get(path); + } + throw new IllegalArgumentException("No sound loaded at path: " + path); + } + + /** + * @throws OutOfMemoryError if there is not enough space for the buffer + */ + @SuppressWarnings("SameParameterValue") + private static IntBuffer createContextAttributes(Int2IntMap source) { + if (source == null || source.isEmpty()) return null; + + IntBuffer result = BufferUtils.createIntBuffer(source.size() * 2 + 1); + for (Int2IntMap.Entry entry : source.int2IntEntrySet()) { + result.put(entry.getIntKey()) + .put(entry.getIntValue()); + } + return result.put(0) // null-terminate the buffer + .flip(); + } + + + /** + * Logs a warning about an incorrect filename extension. + */ + private static void logWrongFilenameExt(String formatName, Collection correctExt, Path filePath) { + log.warn( + "Loaded {} audio from '{}', but file has non-standard extension.", + formatName, filePath.getFileName() + ); + log.warn( + "This is not a fatal error, but the filename may cause confusion. Consider giving it one of these extensions: {} for clarity.", + correctExt + ); + log.warn("Full file path: {}", filePath); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/PitchConversion.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/PitchConversion.java new file mode 100644 index 0000000..4b29782 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/PitchConversion.java @@ -0,0 +1,58 @@ +package ru.fokinatorr.sparkle.audio.impl; + +import lombok.experimental.UtilityClass; + +/** + * Sound effect value conversion utils. + */ +@UtilityClass +class PitchConversion { + // OpenAL pitch formula is 2^octaves + // Pitch effect value formula is 10*semitones + + /** + * Number of 0.1-semitone units per octave (12 semitones * 10). (The pitch effect unit + * is {@code 0.1} semitones, and OpenAL requires octaves) + */ + private final double STEPS_PER_OCTAVE = 120.0; + /** + * Precomputed scale factor: {@code ln(2) / }{@link #STEPS_PER_OCTAVE}. + *

+ * Used to convert {@code ln(alPitch)} to {@code log₂(alPitch) * STEPS_PER_OCTAVE} via division: + *


+     * log₂(alPitch) * STEPS_PER_OCTAVE =
+     * = ln(alPitch) / ln(2) * STEPS_PER_OCTAVE =
+     * = ln(alPitch) / (ln(2) / STEPS_PER_OCTAVE) =
+     * = ln(alPitch) / LOG_TO_PITCH_SCALE
+     * 
+ */ + 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. + * @param pitch the pitch effect value + * @return the corresponding OpenAL pitch value + * @throws IllegalArgumentException if the given argument is infinite or NaN + */ + double toALPitch(double pitch) { + if (Double.isNaN(pitch) || Double.isInfinite(pitch)) { + throw new IllegalArgumentException("Invalid pitch: " + pitch); + } + // OpenAL's pitch value formula is 2^octaves + return Math.pow(2.0, pitch / STEPS_PER_OCTAVE); + } + + /** + * Converts the given OpenAL pitch value to a sound effect pitch value (not normalized). + * @param alPitch the AL pitch value + * @return the corresponding sound effect pitch value + * @throws IllegalArgumentException if the given argument is infinite, NaN or non-positive + */ + double fromALPitch(double alPitch) { + if (alPitch <= 0.0 || Double.isNaN(alPitch) || Double.isInfinite(alPitch)) { + throw new IllegalArgumentException("Invalid AL pitch: " + alPitch); + } + // The below expression is effectively equal to log₂(alPitch) * STEPS_PER_OCTAVE + return Math.log(alPitch) / LOG_TO_PITCH_SCALE; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/SoundBuffer.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/SoundBuffer.java new file mode 100644 index 0000000..8be96b2 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/SoundBuffer.java @@ -0,0 +1,111 @@ +package ru.fokinatorr.sparkle.audio.impl; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +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 java.nio.ShortBuffer; +import java.util.Objects; + +import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*; +import static org.lwjgl.system.MemoryUtil.*; + +/** + * Manages an OpenAL sound buffer. + */ +@Slf4j +@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) +//@ALCheckError +public class SoundBuffer implements NonThrowingAutoCloseable { + /** + * The OpenAL buffer ID. + */ + @Getter + int bufferId; + ShortBuffer pcm; + + @NonFinal + volatile boolean open; + + /** + * Creates a new {@code SoundBuffer}. + * @param pcmData the raw PCM data + * @param format the buffer data format + * @param frequency the data frequency, in Hz + * @throws NullPointerException if any argument is {@code null} + */ + public SoundBuffer(ShortBuffer pcmData, DataFormat format, int frequency) { + this.bufferId = alGenBuffers(); + this.pcm = memDuplicate(Objects.requireNonNull(pcmData, "PCM data")); + alBufferData( + bufferId, + Objects.requireNonNull(format, "format").getOpenALFormat(), + this.pcm, + frequency + ); + open = true; + } + + /** + * Returns the raw PCM data associated with this sound buffer. The returned buffer is read-only. + * @return the raw PCM data + */ + public ShortBuffer getPCMData() { + return pcm.asReadOnlyBuffer().rewind(); + } + + /** + * Destroys this sound buffer and releases all associated resources. The sound buffer can + * not be used after calling this method. Calling this method more than once does not have any effect. + */ + @Override + public void close() { + if (open) { + try { + alDeleteBuffers(bufferId); + } finally { + memFree(pcm); + open = false; + } + } + } + + /** + * The data format of a sound buffer. + */ + @Getter + @RequiredArgsConstructor + @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) + public enum DataFormat { + MONO_8BIT(AL_FORMAT_MONO8), + MONO_16BIT(AL_FORMAT_MONO16), + STEREO_8BIT(AL_FORMAT_STEREO8), + STEREO_16BIT(AL_FORMAT_STEREO16); + + /** + * The corresponding OpenAL format value. + */ + int openALFormat; + + /** + * Returns a {@code DataFormat} with the given OpenAL format. + * @param openALFormat the OpenAL format value + * @return the corresponding {@code DataFormat} + * @throws IllegalArgumentException if there is no such OpenAL format + */ + public static DataFormat valueOf(int openALFormat) { + return switch (openALFormat) { + case AL_FORMAT_MONO8 -> MONO_8BIT; + case AL_FORMAT_STEREO8 -> STEREO_8BIT; + case AL_FORMAT_MONO16 -> MONO_16BIT; + case AL_FORMAT_STEREO16 -> STEREO_16BIT; + default -> throw new IllegalArgumentException("Unknown OpenAL data format: " + openALFormat); + }; + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/StaticSoundSource.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/StaticSoundSource.java new file mode 100644 index 0000000..7697fcb --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/StaticSoundSource.java @@ -0,0 +1,84 @@ +package ru.fokinatorr.sparkle.audio.impl; + +import lombok.AccessLevel; +import lombok.experimental.FieldDefaults; +//import lombok.extern.lwjgl.ALCheckError; + +import java.util.Objects; + +import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*; + +/** + * Manages a static OpenAL sound source, a sound source with only one static buffer. + */ +//@ALCheckError +@FieldDefaults(level = AccessLevel.PRIVATE) +public class StaticSoundSource extends BaseSoundSource { + + SoundBuffer buffer; + boolean open = true; + + /** + * Creates a new {@code SoundSource} with the given buffer attached. + * + * @param buffer the buffer + * @throws NullPointerException if the buffer is {@code null} + */ + public StaticSoundSource(SoundBuffer buffer) { + super(alGenSources()); + this.buffer = Objects.requireNonNull(buffer); + alSourcei(sourceId, AL_BUFFER, buffer.getBufferId()); + } + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + protected StaticSoundSource self() { + return this; + } + + /** + * Sets this sound source to be looping if the given value is {@code true}, or sets + * this sound source not to be looping if the given value is {@code false}. + * + * @param newLooping the new looping value + * @return this sound source + */ + public StaticSoundSource looping(boolean newLooping) { + alSourcei(sourceId, AL_LOOPING, newLooping ? AL_TRUE : AL_FALSE); + return this; + } + + /** + * Determines whether this sound source is looping when played. Returns {@code true} + * if so, or {@code false} otherwise. + * + * @return whether this sound source is looping + */ + public boolean looping() { + return alGetSourcei(sourceId, AL_LOOPING) == AL_TRUE; + } + + /** + * {@inheritDoc} + */ + @Override + public void close() { + if (open) { + stop(); + try { + alDeleteSources(sourceId); + } finally { + try { + buffer.close(); + } finally { + buffer = null; + open = false; + } + } + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/StreamingSoundSource.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/StreamingSoundSource.java new file mode 100644 index 0000000..e8e594e --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/StreamingSoundSource.java @@ -0,0 +1,185 @@ +package ru.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 java.nio.IntBuffer; +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.Stream; + +import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*; +import static org.lwjgl.system.MemoryUtil.memAllocInt; +import static ru.fokinatorr.sparkle.util.BufferUtils.*; + +/** + * Manages a streaming OpenAL sound source. The buffers should be queued. + *

Buffers are taken from a {@link SoundBufferProvider} instance supplied in constructor. There are ready-to-use implementations, + * see below reference links; to create your own implementation, refer to {@code SoundBufferProvider}'s Javadoc.

+ * + * @see SoundBufferProvider + * @see IterableSoundBufferProvider + * @see SamplesSoundBufferProvider + */ +@SuppressWarnings("UnusedReturnValue") +@FieldDefaults(level = AccessLevel.PRIVATE) +//@ALCheckError +public class StreamingSoundSource extends BaseSoundSource { + + /** + * How much ticks to wait before updating the queue. + */ + private static final int WAIT_BEFORE_UPDATE_TICKS = 25; + private static final int UPDATE_BUFFER_COUNT = 3; + + final Int2ObjectMap bufferQueue = new Int2ObjectLinkedOpenHashMap<>(); + final SoundBufferProvider provider; + final SoundBufferProvider.Iterator bufferItr; + final int enqueueStart; + int requeueWaitTicks = WAIT_BEFORE_UPDATE_TICKS; + boolean open = true; + + /** + * Creates a new {@code SoundSource} with the given sound buffers enqueued. + * + * @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()); + this.provider = provider; + this.bufferItr = provider.iterator(); + this.enqueueStart = enqueueStart; + //noinspection resource + enqueueBuffers( + Stream.generate(this::nextBuffer) + .limit(enqueueStart) + .toArray(SoundBuffer[]::new) + ); + } + + /** + * Enqueues the given sound buffers to this sound source. + * + * @param queue the buffers to enqueue; {@code null} elements are ignored + * @return this sound source + * @throws NullPointerException if the given buffer array is {@code null} + */ + private StreamingSoundSource enqueueBuffers(SoundBuffer... queue) { + queue = Arrays.stream(queue) + .filter(Objects::nonNull) + .toArray(SoundBuffer[]::new); + if (queue.length > 0) { + alSourceQueueBuffers(sourceId, + Arrays.stream(queue) + .peek(buf -> bufferQueue.put(buf.getBufferId(), buf)) + .mapToInt(SoundBuffer::getBufferId) + .toArray() + ); + } + return this; + } + + /** + * Dequeues the given count of buffers from this sound source. + * + * @param count the count of buffers to dequeue + * @return an array of dequeued buffers of the specified size + * @throws NegativeArraySizeException if the count is negative + */ + private SoundBuffer[] dequeueBuffers(int count) { + IntBuffer bufferIds = memAllocInt(count); + try (var _ = freeing(bufferIds)) { + alSourceUnqueueBuffers(sourceId, bufferIds); + return stream(bufferIds) + .mapToObj(bufferQueue::remove) + .toArray(SoundBuffer[]::new); + } + } + + /** + * Destroys this sound source, i.e. releases all associated resources. The sound source can + * not be used after calling this method. Calling this method more than once does not have any effect. + */ + @Override + public void close() { + if (open) { + stop(); + try { + dequeueBuffers(alGetSourcei(sourceId, AL_BUFFERS_QUEUED)); + provider.close(); + alDeleteSources(sourceId); + } finally { + try { + bufferQueue.values().forEach(SoundBuffer::close); + bufferQueue.clear(); + } finally { + open = false; + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void rewind() { + super.rewind(); + // clear the queue + dequeueBuffers(alGetSourcei(sourceId, AL_BUFFERS_QUEUED)); + requeueWaitTicks = WAIT_BEFORE_UPDATE_TICKS; + bufferItr.startOver(); + //noinspection resource + enqueueBuffers( + Stream.generate(() -> bufferItr.hasNext() ? bufferItr.next() : null) + .limit(enqueueStart) + .toArray(SoundBuffer[]::new) + ); + } + + /** + * {@inheritDoc} + */ + @Override + public void tick() { + super.tick(); + if (--requeueWaitTicks <= 0) { + requeueWaitTicks = WAIT_BEFORE_UPDATE_TICKS; + dequeueBuffers(alGetSourcei(sourceId, AL_BUFFERS_PROCESSED)); + //noinspection resource + enqueueBuffers(Stream.generate(this::nextBuffer) + .limit(UPDATE_BUFFER_COUNT) + .toArray(SoundBuffer[]::new) + ); + } + } + + // null indicates no more buffers must be queued + private SoundBuffer nextBuffer() { + if (bufferItr.hasNext()) { + return bufferItr.next(); + } + if (provider.mustLoop()) { + bufferItr.startOver(); + if (bufferItr.hasNext()) { + return bufferItr.next(); + } + } + return null; + } + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + protected StreamingSoundSource self() { + return this; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/IterableSoundBufferProvider.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/IterableSoundBufferProvider.java new file mode 100644 index 0000000..93f608e --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/IterableSoundBufferProvider.java @@ -0,0 +1,62 @@ +package ru.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; + +/** + * A {@link SoundBufferProvider} backed by an {@link Iterable}. + */ +@FieldDefaults(level = AccessLevel.PRIVATE) +@RequiredArgsConstructor +public final class IterableSoundBufferProvider implements SoundBufferProvider { + @NonNull Iterable iterable; + final boolean mustLoop; + boolean closed = false; + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public Iterator iterator() { + if (closed) { + throw new IllegalStateException("The provider is closed"); + } + return new StandardJavaProviderIterator(iterable); + } + + /** + * {@inheritDoc} + */ + @Override + public void close() { + if (!closed) { + iterable.forEach(SoundBuffer::close); + closed = true; + } + } + + /** + * Returns the backing iterable. + * @return the iterable + */ + public Iterable getIterable() { + if (closed) { + throw new IllegalStateException("The provider is closed"); + } + return iterable; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean mustLoop() { + return mustLoop; + } + +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/SamplesSoundBufferProvider.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/SamplesSoundBufferProvider.java new file mode 100644 index 0000000..46f5c77 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/SamplesSoundBufferProvider.java @@ -0,0 +1,107 @@ +package ru.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 java.nio.ShortBuffer; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; + +import static org.lwjgl.system.MemoryUtil.memAllocShort; +import static org.lwjgl.system.MemoryUtil.memDuplicate; + +/** + * A {@link SoundBufferProvider} that uses a PCM sample buffer as a sound buffer source. + */ +@Slf4j +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +@RequiredArgsConstructor +public final class SamplesSoundBufferProvider implements SoundBufferProvider { + /** + * The parsed PCM samples. + */ + ShortBuffer samples; + /** + * The data format to use for creating sound buffers. + */ + SoundBuffer.DataFormat dataFormat; + /** + * The frequency of the PCm data, in Hz, to use for creating sound buffers. + */ + int frequency; + /** + * The maximal buffer size. + */ + int bufferSize; + /** + * Whether a sound source that uses this provider must loop. + */ + boolean mustLoop; + /** + * The sound buffer cache. + */ + List cache = new LinkedList<>(); + @NonFinal boolean closed = false; + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + public Iterator iterator() { + if (closed) { + throw new IllegalStateException("Provider is closed"); + } + fillCacheIfNeeded(); + return new StandardJavaProviderIterator(cache); + } + + private void fillCacheIfNeeded() { + if (cache.isEmpty()) { + ShortBuffer samples = memDuplicate(this.samples).rewind(); + ListIterator itr = cache.listIterator(); + while (samples.hasRemaining()) { + ShortBuffer segment = memAllocShort(bufferSize); + while (segment.hasRemaining() && samples.hasRemaining()) { + segment.put(samples.get()); + } + itr.add(new SoundBuffer( + segment.flip(), + dataFormat, + frequency + )); + } + } + log.debug("Buffer count: {}", cache.size()); + } + + /** + * {@inheritDoc} + */ + @Override + public void close() { + if (!closed) { + if (!cache.isEmpty()) { + cache.forEach(SoundBuffer::close); + cache.clear(); + } + closed = true; + } + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean mustLoop() { + return mustLoop; + } + +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/SoundBufferProvider.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/SoundBufferProvider.java new file mode 100644 index 0000000..1ed1abf --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/SoundBufferProvider.java @@ -0,0 +1,66 @@ +package ru.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 java.util.NoSuchElementException; + +/** + * Provides sound buffers for a streaming sound source. + *

Providers are expected to hold references to all buffers they ever create and close all of them in their + * {@link #close()} method. Otherwise, memory leaks are likely to occur, since {@link StreamingSoundSource} + * only does a best-effort attempt at closing the buffers. + * @see StreamingSoundSource + */ +public interface SoundBufferProvider extends NonThrowingAutoCloseable { + + /** + * Determines whether a sound source that uses this provider must loop. Returns {@code true} if so, + * and {@code false} otherwise. + * @return {@code true} if a sound source that uses this provider must loop, and {@code false} otherwise + */ + boolean mustLoop(); + + /** + * Returns an iterator over this provider. + * @return a new iterator instance + */ + Iterator iterator(); + + /** + * Closes this provider, and any remaining sound buffers. The provider should not be usable after call to + * this method. Calling this method more than once must not have any effect. + */ + @Override + void close(); + + /** + * An iterator over a {@link SoundBufferProvider}. It differs from {@link java.util.Iterator} + * since it supports starting over and doesn't have a {@code remove()} operation. + */ + interface Iterator { + + /** + * Determines whether there are more buffers left in this iterator. Returns {@code true} if so, + * and {@code false} otherwise. (In other words, returns {@code true} if the method + * {@link #next()} would return normally, and {@code false} if that method + * would throw an exception.) + * @return {@code true} if has more buffers, and {@code false} otherwise + */ + boolean hasNext(); + + /** + * Returns the next sound buffer, if any, otherwise throws a {@link NoSuchElementException}. + * @return the next sound buffer + * @throws NoSuchElementException if there are no more buffers left + */ + SoundBuffer next(); + + /** + * Starts iterating from the beginning. More formally, sets the iterator's position + * to the starting position. + */ + void startOver(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/StandardJavaProviderIterator.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/StandardJavaProviderIterator.java new file mode 100644 index 0000000..e3ae10e --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/bufferprovider/StandardJavaProviderIterator.java @@ -0,0 +1,57 @@ +package ru.fokinatorr.sparkle.audio.impl.bufferprovider; + +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import ru.fokinatorr.sparkle.audio.impl.SoundBuffer; + +import java.util.Iterator; + +/** + * A {@link SoundBufferProvider.Iterator} that uses the standard Java {@link Iterable} + * and {@link java.util.Iterator Iterator} API. + */ +@RequiredArgsConstructor +@FieldDefaults(level = AccessLevel.PRIVATE) +public final class StandardJavaProviderIterator implements SoundBufferProvider.Iterator { + + final Iterable iterable; + Iterator iterator; + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean hasNext() { + return getIterator().hasNext(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public SoundBuffer next() { + return getIterator().next(); + } + + /** + * {@inheritDoc} + */ + @Override + public void startOver() { + iterator = null; // Will be lazily recomputed when needed + } + + /** + * Returns the iterator, creating it if necessary. + * @return the backing iterator + */ + private synchronized Iterator getIterator() { + if (iterator == null) { + iterator = iterable.iterator(); + } + return iterator; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/io/ParsedSoundImpl.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/io/ParsedSoundImpl.java new file mode 100644 index 0000000..e473a17 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/io/ParsedSoundImpl.java @@ -0,0 +1,238 @@ +package ru.fokinatorr.sparkle.audio.impl.io; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NonNull; +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 java.nio.Buffer; +import java.nio.ShortBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +import static org.lwjgl.system.MemoryUtil.memAllocShort; +import static org.lwjgl.system.MemoryUtil.memFree; + +/** + * An intermediate representation of a loaded sound (in PCM) which is ready to be converted into any of: + *

    + *
  • a stand-alone {@link SoundBuffer};
  • + *
  • a list of {@link SoundBuffer}s;
  • + *
  • a {@link SoundBufferProvider} that generates buffers from the loaded data.
  • + *
+ */ +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) // private final +@RequiredArgsConstructor(access = AccessLevel.PACKAGE) +@Getter +public class ParsedSoundImpl implements NonThrowingAutoCloseable { + + /** + * The raw sound data samples. + */ + @NonNull + ShortBuffer pcmData; + /** + * Whether to explicitly free the {@link #pcmData} buffer. Must be {@code true} + * for buffers allocated using {@link MemoryUtil}, and {@code false} for buffers + * allocated with standard Java API (static allocator methods in the {@link Buffer} classes). + */ + @Getter(AccessLevel.NONE) + boolean freePcmData; + /** + * The data format to use for creating sound buffers. + */ + @NonNull + SoundBuffer.DataFormat dataFormat; + /** + * The frequency (in Hz) to use for creating sound buffers. + */ + int frequency; + @NonFinal + boolean closed = false; + + /** + * Converts a {@link ParsedSound} record to a {@code ParsedSoundImpl} instance. + * @param ps the source object + * @return a new {@code ParsedSoundImpl} instance + */ + public static ParsedSoundImpl fromPublicAPI(ParsedSound ps) { + Objects.requireNonNull(ps, "source object"); + SoundBuffer.DataFormat format = switch (ps.dataFormat()) { + case MONO_8BIT -> SoundBuffer.DataFormat.MONO_8BIT; + case MONO_16BIT -> SoundBuffer.DataFormat.MONO_16BIT; + case STEREO_8BIT -> SoundBuffer.DataFormat.STEREO_8BIT; + case STEREO_16BIT -> SoundBuffer.DataFormat.STEREO_16BIT; + }; + return new ParsedSoundImpl( + ps.pcm(), + ps.freePcm(), + format, + ps.frequency() + ); + } + + + // Sound buffer creation + + /** + * Creates and returns a stand-alone {@link SoundBuffer} from this instance. + * The data buffer is cloned, so the created buffer will be independent of this instance. + * + * @return a stand-alone {@link SoundBuffer} from this parsed sound + */ + public SoundBuffer createStandAloneBuffer() { + ShortBuffer orig = getPcmData(); + ShortBuffer clone = memAllocShort(orig.remaining()) + .put(orig) + .flip(); + return new SoundBuffer(clone, dataFormat, frequency); + } + + + /** + * Creates and returns a list of {@link SoundBuffer}s from this instance, given + * the maximal buffer count. The returned list will have at most the given count of sound buffers. + * The data buffer is cloned, so the created buffers will be independent of this instance. + * + * @param maxBufferCount the maximal buffer count, must be positive + * @return a list of sound buffers from this parsed sound + */ + public List createBuffersByCount(int maxBufferCount) { + ShortBuffer pcm = getPcmData(); + if (maxBufferCount <= 0) { + throw new IllegalArgumentException("Buffer count must be positive, found:" + maxBufferCount); + } + List result = new ArrayList<>(maxBufferCount); + fillList( + result, pcm, + maxBufferCount, + (int) Math.ceil((double) pcm.remaining() / maxBufferCount) * channels() + ); + return Collections.unmodifiableList(result); + } + + /** + * Creates and returns a list of {@link SoundBuffer}s from this instance, given + * the maximal buffer size. Every sound buffer in the returned list will have at most the given count of samples multiplied + * by the {@link #channels() channel count}. + * The data buffer is cloned, so the created buffers will be independent of this instance. + * + * @param maxBufferSize the maximal buffer size for each buffer (will be multiplied by the channel count), + * must be positive + * @return a list of sound buffers from this parsed sound + */ + public List createBuffersBySize(int maxBufferSize) { + ShortBuffer pcm = getPcmData(); + if (maxBufferSize <= 0) { + throw new IllegalArgumentException("Buffer size must be positive, found:" + maxBufferSize); + } + int maxBufferCount = (int) Math.ceil((double) pcm.remaining() / maxBufferSize / channels()); + List result = new ArrayList<>(maxBufferCount); + fillList( + result, pcm, + maxBufferCount, + maxBufferSize * channels() + ); + return Collections.unmodifiableList(result); + } + + /** + * Shared logic for {@link #createBuffersByCount} and {@link #createBuffersBySize}. + * + * @param list the list to fill + * @param pcmData the copied PCM data buffer + */ + private void fillList(List list, ShortBuffer pcmData, int bufferCount, int bufferSize) { + for (int i = 0; i < bufferCount; i++) { + ShortBuffer buf = memAllocShort(bufferSize); + while (buf.hasRemaining() && pcmData.hasRemaining()) { + buf.put(pcmData.get()); + } + if (!pcmData.hasRemaining()) { + break; + } + list.add(new SoundBuffer( + buf.flip(), + dataFormat, + frequency + )); + } + } + + /** + * Creates and returns a {@link SoundBufferProvider} from this instance, given the maximal buffer size, + * and whether the provider should loop. Each buffer emitted by the provider will have at most the given + * count of samples multiplied by the {@link #channels() channel count}. + * @param maxBufferSize the maximal buffer size + * @param mustLoop whether the provider must loop + * @return a new {@link SoundBufferProvider} from this parsed sound + */ + public SoundBufferProvider createProvider(int maxBufferSize, boolean mustLoop) { + return new SamplesSoundBufferProvider( + getPcmData(), + dataFormat, + frequency, + maxBufferSize * channels(), + mustLoop + ); + } + + // Info + + /** + * Returns the underlying PCM data buffer. + * + * @return the PCM data + */ + public ShortBuffer getPcmData() { + return pcmData.asReadOnlyBuffer().rewind(); + } + + /** + * Returns the total sound length, in samples. + * + * @return the sound length + */ + public int length() { + return pcmData.remaining() / channels(); + } + + /** + * Returns the channel count of this sound. + * + * @return the channel count + */ + public int channels() { + return switch (dataFormat) { + case MONO_8BIT, MONO_16BIT -> 1; + case STEREO_8BIT, STEREO_16BIT -> 2; + }; + } + + // AutoCloseable + + /** + * Releases all associated resources of this instance. The instance cannot be used + * to create buffers after call to this method. Calling this method more than once has + * no effect. + */ + @Override + public void close() { + if (!closed) { + if (freePcmData) { + memFree(pcmData); + } + closed = true; + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/impl/io/VorbisSoundDecoder.java b/src/main/java/ru/fokinatorr/sparkle/audio/impl/io/VorbisSoundDecoder.java new file mode 100644 index 0000000..5fa8ddf --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/impl/io/VorbisSoundDecoder.java @@ -0,0 +1,133 @@ +package ru.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 java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ShortBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.Set; + +import static org.lwjgl.stb.STBVorbis.*; +import static org.lwjgl.system.MemoryUtil.*; + +/** + * A sound decoder that reads and parses Ogg Vorbis sounds into {@link ParsedSoundImpl ParsedSounds}. Uses + * libstb for decoding. + * + * @see SoundDecoder + * @see org.lwjgl.stb.STBVorbis + */ +public enum VorbisSoundDecoder implements SoundDecoder { + INSTANCE; + + /** + * Attempts to read an Ogg Vorbis sound from file represented by the given path into a {@link ParsedSoundImpl}. + * + * @param path {@inheritDoc} + * @return {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + * @throws IOException {@inheritDoc} + */ + @Override + public ParsedSound parseFile(Path path) throws IOException { + pathCheck(path); + try (STBVorbisInfo info = STBVorbisInfo.malloc()) { + return doParse(info, createVorbisDecoder(path) /*pointer*/); + } + } + + /** + * Attempts to read an Ogg Vorbis sound from memory represented by the given path into a {@link ParsedSoundImpl}. + * The caller must ensure that the buffer is properly prepared for reading. + * + * @param bb {@inheritDoc} + * @return {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + * @throws IOException {@inheritDoc} + */ + @Override + public ParsedSound parseBytes(ByteBuffer bb) throws IOException { + Objects.requireNonNull(bb, "byte buffer"); + try (STBVorbisInfo info = STBVorbisInfo.malloc()) { + return doParse(info, createVorbisDecoder(bb) /*pointer*/); + } + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public Set getSupportedExtensions() { + return Set.of(".ogg"); + } + + private static ParsedSound doParse(STBVorbisInfo info, long decoder /*pointer*/) { + stb_vorbis_get_info(decoder, info); + int channels = info.channels(); + ShortBuffer pcm = memAllocShort(stb_vorbis_stream_length_in_samples(decoder) * channels); + pcm.limit(stb_vorbis_get_samples_short_interleaved(decoder, channels, pcm) * channels); + ParsedSound sound = new ParsedSound( + pcm.rewind().asReadOnlyBuffer(), + true, + channels == 1 ? ParsedSound.DataFormat.MONO_16BIT : ParsedSound.DataFormat.STEREO_16BIT, + info.sample_rate() + ); + stb_vorbis_close(decoder); + return sound; + } + + + private static void pathCheck(Path path) throws IOException { + Objects.requireNonNull(path, "path"); + if (!Files.exists(path)) { + throw new FileNotFoundException(path.toString()); + } + if (Files.isDirectory(path)) { + throw new IOException("Is a directory: " + path); + } + } + + // pointer + private static long createVorbisDecoder(Path path) throws IOException { + int[] error = new int[1]; + long decoder = stb_vorbis_open_filename(path.toString(), error, null); // pointer + throwIfDecoderNull(decoder, "Cannot open path " + path, error[0]); + return decoder; + } + + // pointer + private static long createVorbisDecoder(ByteBuffer bb) throws IOException { + int[] error = new int[1]; + long decoder = stb_vorbis_open_memory(bb, error, null); // pointer + throwIfDecoderNull( + decoder, + "Cannot open memory at 0x" + Long.toHexString(memAddress(bb)).toUpperCase() + " (buffer state: " + bb + ")", + error[0] + ); + return decoder; + } + + private static void throwIfDecoderNull(long decoder /*pointer*/, String prefix, int errorCode) throws IOException { + if (decoder == NULL) { + String message = prefix + ": " + switch (errorCode) { + case VORBIS_invalid_first_page -> "Invalid first Ogg page"; + case VORBIS_too_many_channels -> "Too many channels in the sound"; + case VORBIS_outofmem -> "Not enough memory"; + case VORBIS_unexpected_eof -> "Unexpected end of Ogg stream"; + case VORBIS_invalid_setup -> "Invalid libstb setup"; // TODO add a more descriptive string + case VORBIS_feature_not_supported -> "Feature not supported"; + case VORBIS_file_open_failure -> "Unknown file open failure"; + default -> "[STB Vorbis error code " + errorCode + "]"; + }; + throw new IOException(message); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/io/ParsedSound.java b/src/main/java/ru/fokinatorr/sparkle/audio/io/ParsedSound.java new file mode 100644 index 0000000..1a168ff --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/io/ParsedSound.java @@ -0,0 +1,89 @@ +package ru.fokinatorr.sparkle.audio.io; + +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ShortBuffer; +import java.util.Objects; + +import static lombok.AccessLevel.PRIVATE; + +/** + * A sound parsed to PCM. + * @param pcm the PCM data samples + * @param freePcm whether {@code pcm} was allocated using {@link MemoryUtil}'s methods and must be explicitly freed + * (handling of this flag is implemented internally) + * @param dataFormat the audio's data format (channel count and sample size) + * @param frequency the frequency (samples per second) of the sound + * @see SoundDecoder + */ +public record ParsedSound(ShortBuffer pcm, boolean freePcm, DataFormat dataFormat, int frequency) { + /** + * Creates a new {@code ParsedSound}. + * @throws NullPointerException if any argument is {@code null} + * @see ParsedSound Parameters' descriptions + */ + public ParsedSound { + pcm = Objects.requireNonNull(pcm, "PCM data").asReadOnlyBuffer().rewind(); + Objects.requireNonNull(dataFormat, "data format"); + } + + /** + * Supported data formats of a PCM sound. + */ + @Getter + @RequiredArgsConstructor + @FieldDefaults(makeFinal = true, level = PRIVATE) + public enum DataFormat { + MONO_8BIT(1, 1), + MONO_16BIT(1, 2), + STEREO_8BIT(2, 1), + STEREO_16BIT(2, 2); + + /** + * The channel count. + */ + int channels; + + /** + * The sample size in bytes. + */ + int sampleSize; + /** + * Attempts to find an appropriate instance for given parameters. + * @param channels the channel count + * @param sampleSize the sample size in bytes + * @return a data format with the given characteristics, if any + * @throws IllegalArgumentException if there is no respective instance found + */ + public static DataFormat valueOf(int channels, int sampleSize) { + Int2ObjectMap bySampleSize = ValueOfMapHolder.MAP.get(channels); + if (bySampleSize == null) { + throw new IllegalArgumentException("Unexpected channel count: " + channels); + } + DataFormat result = bySampleSize.get(sampleSize); + if (result == null) { + throw new IllegalArgumentException("Unexpected sample size: " + sampleSize); + } + return result; + } + + } + + /** + * Holds the properties-to-instance map. Declared in a separate class for lazy initialization. + */ + private static final class ValueOfMapHolder { + static final Int2ObjectMap> MAP = new Int2ObjectOpenHashMap<>(); + + static { + for (DataFormat format : DataFormat.values()) { + MAP.computeIfAbsent(format.channels, _ -> new Int2ObjectOpenHashMap<>()).putIfAbsent(format.sampleSize, format); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/fokinatorr/sparkle/audio/io/SoundDecoder.java b/src/main/java/ru/fokinatorr/sparkle/audio/io/SoundDecoder.java new file mode 100644 index 0000000..a141728 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/audio/io/SoundDecoder.java @@ -0,0 +1,92 @@ +package ru.fokinatorr.sparkle.audio.io; + +import ru.fokinatorr.sparkle.context.AppContextHolder; +import ru.fokinatorr.sparkle.util.BufferUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.file.Path; +import java.util.Objects; +import java.util.Set; + +/** + * A sound decoder can decode a {@link Path file}, a {@link InputStream stream of bytes}, or a {@link ByteBuffer byte buffer} + * into a {@link ParsedSound} (PCM data). + *

Currently supported formats: + *

    + *
  • OGG Vorbis (.ogg)
  • + *
+ *

Note for Scratchers: Unlike Scratch, which supports many formats (including MP3 and WAV), + * we currently only support OGG Vorbis. This keeps the core lightweight and focused on free, open formats. + * If you have sounds in other formats that you want to use: + *

    + *
  1. + * Easy way (recommended): convert them to one of the supported formats + * using tools like Audacity, and they're ready to use! + *
  2. + *
  3. + * Advanced way: implement this interface yourself and register your custom implementation in an + * application context like this: + *
    
    + *             context.register(SoundDecoder.class, new MySoundDecoder());
    + *         
    + * You can get the context using {@link AppContextHolder} utilities. + *
  4. + *
+ * @see ParsedSound + */ +public interface SoundDecoder { + + /** + * Parses the data from file at the given path into PCM. + * @param path the file path + * @return a new parsed sound + * @throws IOException if an I/O or parse error occurs + * @throws NullPointerException if path is {@code null} + */ + ParsedSound parseFile(Path path) throws IOException; + + /** + * Parses the data from memory into PCM. The caller must ensure that the buffer is properly prepared for reading. + * @param bb the loaded unparsed sound bytes + * @return a new parsed sound + * @throws IOException if a parse error occurs + * @throws NullPointerException if byte buffer is {@code null} + */ + ParsedSound parseBytes(ByteBuffer bb) throws IOException; + + /** + * Parses the bytes emitted by the given input stream into PCM. + * @param in the input stream + * @return a new parsed sound + * @throws IOException if an I/O or parse error occurs + * @throws NullPointerException if input stream is {@code null} + * @implNote The default implementation reads all remaining bytes of the + * input stream into an off-heap buffer, parses them and then frees the buffer. + */ + default ParsedSound parseStream(InputStream in) throws IOException { + Objects.requireNonNull(in, "input stream"); + ByteBuffer bb = BufferUtils.readFully(in); + try (var _ = BufferUtils.freeing(bb)) { + return parseBytes(bb); + } + } + + /** + * Returns all file extensions of audio formats supported by this decoder, if available, otherwise returns an empty set. + * @return file extensions supported by this decoder (immutable) + */ + default Set getSupportedExtensions() { + return Set.of(); + } + + /** + * Returns the name of the format this decoder is used to handle, if available, + * otherwise a string telling the format is unknown, e.g. {@code ""}. + * @return the name of the format this decoder can handle, if any + */ + default String getFormatName() { + return ""; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/context/AppContext.java b/src/main/java/ru/fokinatorr/sparkle/context/AppContext.java new file mode 100644 index 0000000..c11b99c --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/context/AppContext.java @@ -0,0 +1,142 @@ +package ru.fokinatorr.sparkle.context; + +import java.util.Collection; +import java.util.function.Function; +import java.util.function.Supplier; +import ru.fokinatorr.sparkle.util.Global; + +/** + * Represents a lightweight runtime environment for an application. + * Contains services such as graphics, audio, input, and asset management. + *

Registered services are also called "components" or "beans" in documentation of this interface's methods. + * + * @see AppContextHolder + * @see 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 + + // Accessors + + /** + * Gets a bean instance by its type (usually an interface type). There's no guarantee to which bean will be returned + * if multiple beans were registered under that type. + * + * @param type the type that was used to register the bean + * @param the type of the bean + * @return the bean instance + * @throws IllegalArgumentException if no beans were registered under the given type + * @throws NullPointerException if type is {@code null}, or if there's a lazy bean registered under that type + * and its factory function returns {@code null} + * @see #getAll(Class) + */ + T get(Class type); + + /** + * Gets all registered beans by the given type. + * + * @param type the type + * @param the common supertype of the beans + * @return all beans registered under that type + * @throws IllegalArgumentException if no beans were registered under the given type + * @throws NullPointerException if type is {@code null}, or if there's a lazy bean registered under that type + * and its factory function returns {@code null} + * @see #get(Class) + */ + Collection getAll(Class type); + + /** + * Returns the count of beans registered under the given type. + *

This method doesn't initialize lazy beans, so it can be used instead of {@code getAll(type).size()} + * to avoid initialization when only the count of them is needed. + * @param type the type + * @return the count of beans registered under the given type + * @throws NullPointerException if type is {@code null} + */ + int count(Class type); + + /** + * Determines whether there is at least one bean registered under the given type. + * Returns {@code true} if so and {@code false} otherwise. + *

This method doesn't initialize lazy beans, so it can be used instead of {@code !getAll(type).isEmpty()} + * to avoid initialization when only needed to check presence. + *

Implementations may choose to return {@code false} instead of throwing a {@link NullPointerException} + * when the given type is {@code null}. + * @param type the type + * @return whether any beans are registered under the given type + * @throws NullPointerException (optional) if type is {@code null} + */ + default boolean has(Class type) { + return count(type) > 0; + } + + // Mutators + + /** + * Registers a new component under the given type. Multiple components can + * be registered under the same type. + * + * @param type the type (usually an interface type implemented by the component) + * @param instance the component instance to register + * @param the type of the component + * @return this context, for chaining calls + * @throws NullPointerException if any argument is {@code null} + * @see #registerLazy(Class, Function) + * @see #registerOverride(Class, Object) + */ + AppContext register(Class type, T instance); + + /** + * Registers a new component under the given type, guaranteeing that {@link #get(Class)} returns + * that component instance after call to this method. + * + * @param type the type (usually an interface type implemented by the component) + * @param instance the component instance to register, overriding other instances with the same type + * @param the type of the component + * @return this context, for chaining calls + * @throws NullPointerException if any argument is {@code null} + * @see #registerLazy(Class, Function) + */ + AppContext registerOverride(Class type, T instance); + + /** + * Registers a lazy-initialized component under the given type. + * Lazy components are not initialized until they're requested with {@link #get(Class)} or similar methods. + *

This is useful for registering heavy beans that might never be used, or beans that do some irreversible changes once created. + * + * @param type the type (usually an interface type implemented by the component) + * @param factory a factory function that accepts this context and produces a new component instance + * @param the type of the component + * @return this context, for chaining calls + * @throws NullPointerException if any argument is {@code null} (does not check for the factory's return value) + * @see #registerLazy(Class, Supplier) + */ + AppContext registerLazy(Class type, Function factory); + + /** + * Registers a lazy-initialized component under the given type. + * Lazy components are not initialized until they're requested with {@link #get(Class)} or similar methods. + *

This is useful for registering heavy beans that might never be used, or beans that do some irreversible changes once created. + *

This method is a version of {@link #registerLazy(Class, Function)} where the factory + * function does not accept arguments. + * + * @param type the type (usually an interface type implemented by the component) + * @param factory a factory function that produces a new component instance + * @param the type of the component + * @return this context, for chaining calls + * @throws NullPointerException if any argument is {@code null} (does not check for the factory's return value) + * @see #registerLazy(Class, Function) + */ + default AppContext registerLazy(Class type, Supplier factory) { + return registerLazy(type, _ -> factory.get()); + } + + /** + * Closes this context and releases beans that implement {@link AutoCloseable}. + * The context cannot be used after calling this method. + * Calling this method more than once does not have any effect. + * @throws Exception {@inheritDoc} + */ + @Override + void close() throws Exception; +} diff --git a/src/main/java/ru/fokinatorr/sparkle/context/AppContextHolder.java b/src/main/java/ru/fokinatorr/sparkle/context/AppContextHolder.java new file mode 100644 index 0000000..416d982 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/context/AppContextHolder.java @@ -0,0 +1,57 @@ +package ru.fokinatorr.sparkle.context; + +import lombok.experimental.UtilityClass; +import ru.fokinatorr.sparkle.util.Global; + +import java.util.Objects; + +/** + * A thread-local holder for the {@link AppContext application context}. + *

For each thread, it can only be initialized once. + * @see AppContext + * @see ThreadLocal + * @see Global + */ +@UtilityClass +public class AppContextHolder { + + private static final ThreadLocal CONTEXT = new ThreadLocal<>(); + // not using InheritableThreadLocal so that other potential inheritable thread locals are not inherited if not needed + + /** + * Returns the application context of the current thread, or {@code null} if none. + * @return the application context, if any, otherwise {@code null} + */ + public AppContext getContext() { + return CONTEXT.get(); + } + + /** + * Returns this application context of the current thread, requiring it to be present. + * That means, returns the context if it's not {@code null} and throws an exception otherwise. + * @return the application context, if any + * @throws IllegalStateException if there is no context for the current thread + */ + public AppContext getContextOrThrow() { + AppContext context = CONTEXT.get(); + if (context == null) { + throw new IllegalStateException("AppContext is not initialized for " + Thread.currentThread()); + } + return context; + } + + /** + * Sets the application context for the current thread, if not yet done. + * @param ctx the application context to initialize with + * @throws IllegalStateException if context was already initialized for the current thread + * @throws NullPointerException if context is not initialized for the current thread and the given one is {@code null} + */ + public void initContext(AppContext ctx) { + if (CONTEXT.get() == null) { + Objects.requireNonNull(ctx, "app context"); + CONTEXT.set(ctx); + } else { + throw new IllegalStateException("AppContext is already initialized for " + Thread.currentThread()); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/context/DefaultAppContext.java b/src/main/java/ru/fokinatorr/sparkle/context/DefaultAppContext.java new file mode 100644 index 0000000..5a68571 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/context/DefaultAppContext.java @@ -0,0 +1,342 @@ +package ru.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 java.lang.ref.Cleaner; +import java.lang.reflect.Modifier; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import static java.util.Objects.requireNonNull; + +/** + * Default implementation of {@link AppContext}. + * Uses insertion order with override-by-prepend semantics: + *

    + *
  • {@link #register(Class, Object)} → appends
  • + *
  • {@link #registerOverride(Class, Object)} → prepends
  • + *
  • {@link #get(Class)} → returns first match
  • + *
+ */ +@FieldDefaults(level = AccessLevel.PRIVATE) +@Slf4j +public class DefaultAppContext implements AppContext { + + /** + * The ID of this context. Useful for debugging purposes. + */ + @Getter + @Setter(AccessLevel.PACKAGE) + String id = GUID.generate(); + + final Map, List>> components = new ConcurrentHashMap<>(); + final Set disposables = ConcurrentHashMap.newKeySet(); + + // Context implementation + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public T get(@NonNull Class type) { + requireNonNull(type, "type"); + List> entries = (List) components.get(type); + if (entries == null || entries.isEmpty()) { + throw new NullPointerException("No components registered for " + type.getName()); + } + T result = entries.stream() + .map(e -> e.get(this)) + .findFirst().orElseThrow(); + log.trace("[DefaultAppContext id={}] Resolved '{}' -> {}", id, type.getSimpleName(), result); + return result; + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public Collection getAll(@NonNull Class type) { + requireNonNull(type, "type"); + List> entries = (List) components.get(type); + if (entries == null || entries.isEmpty()) { + throw new IllegalArgumentException("No components registered for " + type.getName()); + } + List result = entries.stream() + .map(e -> e.get(this)) + .collect(Collectors.toList()); + log.trace("[DefaultAppContext id={}] Resolved all '{}' -> {}", id, type.getSimpleName(), result); + return result; + } + + @Override + public int count(@NonNull Class type) { + requireNonNull(type, "type"); + List> entries = components.get(type); + return entries != null ? entries.size() : 0; + } + + @Override + public boolean has(Class type) { + if (type == null) { + return false; + } + List> entries = components.get(type); + return entries != null && !entries.isEmpty(); + } + + @Override + public DefaultAppContext register(Class type, T instance) { + return doRegister(type, new Entry<>(instance), false); + } + + @Override + public DefaultAppContext registerOverride(Class type, T instance) { + return doRegister(type, new Entry<>(instance), true); + } + + @Override + public DefaultAppContext registerLazy(Class type, Function factory) { + return doRegister(type, new Entry<>(() -> factory.apply(this)), false); + } + + @Override + public DefaultAppContext registerLazy(Class type, Supplier factory) { + return doRegister(type, new Entry<>(factory), false); + } + + @Override + public void close() throws Exception { + log.info("[DefaultAppContext id={}] Shutting down context...", id); + List exceptions = new ArrayList<>(); + for (AutoCloseable disposable : disposables) { + try { + log.trace("[DefaultAppContext id={}] Closing component {}", id, disposable); + disposable.close(); + } catch (Exception e) { + log.error("[DefaultAppContext id={}] Failed to close {}", id, disposable, e); + exceptions.add(e); + } + } + if (!exceptions.isEmpty()) { + throw multipleExceptions(exceptions); + } + log.info("[DefaultAppContext id={}] Context terminated.", id); + } + + + // Factory methods + + /** + * Creates a new application context with default services pre-registered. + * + * @return a new context + */ + public static DefaultAppContext createWithDefaults() { + DefaultAppContext result = new DefaultAppContext() + .registerLazy(ScheduledExecutorService.class, DefaultAppContext::createDefaultExecutor) + .register(EventDispatcher.class, EventDispatcher.newDefault()) + .registerLazy(Cleaner.class, () -> Cleaner.create(new ContextInheritingThreadFactory("cleaner-worker", ThreadType.VIRTUAL))) + .registerLazy(AudioManager.class, OpenALAudioManager::new) + .register(SoundDecoder.class, VorbisSoundDecoder.INSTANCE) + .registerLazy(GraphicsManager.class, OpenGLGraphicsManager::new) + .register(RendererRegistry.class, RendererRegistry.withDefaults()) + .register(FontProvider.class, FontProvider.defaultProvider()); + log.info("Created headful DefaultAppContext, id={}", result.id); + return result; + } + + /** + * Creates a new headless application context (without audio or graphics services). + * + * @return a new context + */ + public static DefaultAppContext createHeadless() { + DefaultAppContext result = new DefaultAppContext() + .registerLazy(ScheduledExecutorService.class, DefaultAppContext::createDefaultExecutor) + .register(EventDispatcher.class, EventDispatcher.newDefault()) + .registerLazy(Cleaner.class, () -> Cleaner.create(new ContextInheritingThreadFactory("cleaner-worker", ThreadType.VIRTUAL))); + log.info("Created headless DefaultAppContext (no graphics/audio components), id={}", result.id); + return result; + } + + + // Private implementation + + /** + * Creates an executor service to use in the default services. + * + * @return the default executor service + */ + private static ScheduledExecutorService createDefaultExecutor() { + ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor( + Runtime.getRuntime().availableProcessors(), + new ContextInheritingThreadFactory("scheduler-worker", ThreadType.VIRTUAL) + ); + executor.setRemoveOnCancelPolicy(true); + return executor; + } + + /** + * Registers the given component under the given type. + * + * @param type the type + * @param entry the component entry (initialized value or lazy supplier) + * @param prepend if {@code true} then add to the beginning of the bean list rather than end + * @param the type of the bean + * @return this context + */ + private DefaultAppContext doRegister(Class type, Entry entry, boolean prepend) { + requireNonNull(type, "type"); + // If the type is not an interface or abstract class and has an abstract supertype (interface or an abstract class) in the hierarchy, consider it a concrete type + if (!type.isInterface() && (type.getModifiers() & Modifier.ABSTRACT) == 0 && hasAbstractSupertype(type)) { + log.warn( + "[DefaultAppContext id={}] Registering bean under concrete type '{}'. " + + "Prefer registering under interfaces or abstract types where possible.", + id, type.getSimpleName() + ); + } + + List> entries = components.computeIfAbsent(type, _ -> new CopyOnWriteArrayList<>()); + if (prepend) { + entries.addFirst(entry); + log.debug("[DefaultAppContext id={}] Registered override entry {} under type {}", id, entry, type); + } else { + entries.addLast(entry); + log.debug("[DefaultAppContext id={}] Registered entry {} under type {}", id, entry, type); + } + + return this; + } + + private static boolean hasAbstractSupertype(Class type) { + while (type.isArray()) { + type = type.getComponentType(); + } + if (type.getInterfaces().length == 0) { + type = type.getSuperclass(); + while (type != null) { + if (type.getInterfaces().length > 0 || (type.getModifiers() & Modifier.ABSTRACT) != 0) { + return true; + } + type = type.getSuperclass(); + } + return false; + } else { + return true; + } + } + + /** + * Combines the given exceptions into a single one by suppressing. + * + * @param exceptions the exceptions + * @return a combined exception + */ + private static Exception multipleExceptions(List exceptions) { + Exception first = exceptions.getFirst(); + for (int i = 1; i < exceptions.size(); i++) { + first.addSuppressed(exceptions.get(i)); + } + return first; + } + + /** + * An internal component holder that can be used to store either initialized values + * or lazily-supplied ones. + * + * @param the type of the value + */ + @FieldDefaults(makeFinal = true) + private static final class Entry { + + Supplier supplier; + AtomicReference val; + + /** + * Creates an uninitialized lazy entry. + * + * @param supplier the initialization function + */ + @SuppressWarnings("unchecked") + Entry(Supplier supplier) { + this.supplier = (Supplier) Objects.requireNonNull(supplier, "supplier"); + this.val = new AtomicReference<>(); + } + + /** + * Creates an initialized entry. + * + * @param val the value + */ + Entry(T val) { + this.val = new AtomicReference<>(Objects.requireNonNull(val, "instance")); + this.supplier = () -> val; + } + + /** + * Returns the stored component, initializing it and updating + * the context's disposable list as necessary. + * + * @param ctx the context to maybe update + * @return the stored object + */ + T get(DefaultAppContext ctx) { + T result = val.get(); + if (result == null) { + T init = supplier.get(); + if (init == null) { + log.error("[DefaultAppContext id={}] Factory function {} returned null", ctx.id, supplier); + throw new NullPointerException("Factory function returned null"); + } + if (val.compareAndSet(null, init)) { + // won race + result = init; + log.debug( + "[DefaultAppContext id={}] Initialized lazy component {} (factory function: {})", + ctx.id, result, supplier + ); + if (result instanceof AutoCloseable disposable && !(result instanceof AppContext)) { + ctx.disposables.add(disposable); + } + } else { + // lost race + // double object creation occurred; the instance that won might be invalid now + // still, attempt to close the leaked instance + result = val.get(); + if (init instanceof AutoCloseable) { + try { + ((AutoCloseable) init).close(); + } catch (Exception e) { + log.error("[DefaultAppContext id={}] Failed to close leaked component: {}", ctx.id, init, e); + } + } + } + } + return result; + } + + @Override + public String toString() { + return val.get() == null + ? "Entry[]" + : "Entry[]"; + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/fokinatorr/sparkle/effect/EffectMap.java b/src/main/java/ru/fokinatorr/sparkle/effect/EffectMap.java new file mode 100644 index 0000000..40acabf --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/effect/EffectMap.java @@ -0,0 +1,494 @@ +package ru.fokinatorr.sparkle.effect; + +import it.unimi.dsi.fastutil.doubles.AbstractDoubleCollection; +import it.unimi.dsi.fastutil.doubles.AbstractDoubleIterator; +import it.unimi.dsi.fastutil.doubles.DoubleCollection; +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 java.util.NoSuchElementException; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +import static java.lang.reflect.Array.newInstance; + +/** + * An object mapping effects to their values. + *

Null keys are not supported. + * The map contains all the possible keys, so removing a key effectively sets the associated value to + * {@link K#getDefaultValue() its default value}. + *

The default return value of an effect map is {@code 0.0} and it can't be changed. + * @param the effect type + */ +public abstract class EffectMap extends AbstractObject2DoubleMap { + + /** + * The values array. Similarly to {@link java.util.EnumMap}, maps enum ordinal to value. + */ + protected final AtomicDoubleArray values; + /** + * The effect class, stored because of type erasure + */ + protected final Class kClass; + /** + * All the possible effect values. + */ + protected final K[] effects; + + /** + * Creates a new empty {@code EffectMap} with the given possible effect values. + * @param effects the possible effect values + * @throws IllegalArgumentException if the effect array size is {@code 0} + * @throws NullPointerException if the effects array is {@code null} + */ + protected EffectMap(K[] effects) { + defRetValue = 0.0d; + Objects.requireNonNull(effects, "effect array"); + if (effects.length == 0) { + throw new IllegalArgumentException("No effects provided"); + } + values = new AtomicDoubleArray(effects.length); + this.effects = effects; + //noinspection unchecked + kClass = (Class) effects.getClass().componentType(); + clear(); // Set all values to default + } + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + public int size() { + return values.length(); + } + + /** + * An effect map is never empty. + * + * @return {@code false} + */ + @Override + public boolean isEmpty() { + return false; + } + + /** + * Associates the given effect with the given value. + * + * @param key the effect (must not be {@code null}) + * @param value the new value + * @return the old value of the effect + * @throws NullPointerException if the key is {@code null} + */ + @Override + public double put(K key, double value) { + Objects.requireNonNull(key, "effect"); + return values.getAndSet(key.ordinal(), key.normalize(value)); + } + + /** + * Increments the given effect's value by the given delta. + * @param key the effect + * @param delta the delta + * @return the old effect value + */ + public double increment(K key, double delta) { + Objects.requireNonNull(key, "effect"); + return values.getAndUpdate(key.ordinal(), oldVal -> key.normalize(oldVal + delta)); + } + + /** + * Decrements the given effect's value by the given delta. + * @param key the effect + * @param delta the delta + * @return the old effect value + */ + public double decrement(K key, double delta) { + Objects.requireNonNull(key, "effect"); + return values.getAndUpdate(key.ordinal(), oldVal -> key.normalize(oldVal - delta)); + } + + /** + * Returns the value of the given effect. + * + * @param key the key + * @return {@inheritDoc} + */ + @Override + public double getDouble(Object key) { + return kClass.isInstance(key) ? values.get(kClass.cast(key).ordinal()) : defRetValue; + } + + /** + * Sets the value of the given effect to its default value. + * + * @param key the effect + * @return {@inheritDoc} + */ + @Override + public double removeDouble(Object key) { + return kClass.isInstance(key) + ? values.getAndSet(kClass.cast(key).ordinal(), kClass.cast(key).getDefaultValue()) + : defRetValue; + } + + /** + * Effectively sets all effect values to their respective default values. + */ + @Override + public void clear() { + for (int i = 0; i < values.length(); i++) { + values.set(i, effects[i].getDefaultValue()); + } + } + + /** + * Creates and returns a deep copy of this effect map. The copied map's contents are independent of this map's contents. + * @return a deep copy of this map + */ + public abstract EffectMap copy(); + + /** + * All keys of type {@link K} are present in the map. + * + * @param k {@inheritDoc} + * @return {@code true} if the given value is not {@code null} and is an instance of {@link K}. + */ + @Override + public boolean containsKey(Object k) { + return kClass.isInstance(k); + } + + /** + * {@inheritDoc} + * + * @param v the value + */ + @Override + public boolean containsValue(double v) { + final AtomicBoolean result = new AtomicBoolean(false); + values.forEach(value_ -> { + if (value_ == v) { + result.set(true); + } + }); + return result.get(); + } + + // keySet + + private transient ObjectSet keySet; + + @Override + public @NonNull ObjectSet keySet() { + var ks = keySet; + return ks == null ? (keySet = new KeySet()) : ks; + } + + private class KeySet extends AbstractObjectSet { + // Generally, something similar to set from values array but with "remove" options + + private class KeyItr extends AbstractObjectIterator { + // Iterator over an array with "removing" capability + int cursor = 0; + + @Override + public boolean hasNext() { + return cursor < effects.length; + } + + @Override + public K next() { + if (cursor >= effects.length) { + throw new NoSuchElementException(); + } + return effects[cursor++]; + } + + @Override + public void remove() { + int cursor = this.cursor; + if (cursor == 0) { + throw new IllegalStateException("next() has not been yet called"); + } + values.set(cursor - 1, effects[cursor - 1].getDefaultValue()); + } + } + + @Override + public @NonNull ObjectIterator iterator() { + return new KeyItr(); + } + + @Override + public int size() { + return EffectMap.this.size(); + } + + @Override + public void clear() { + EffectMap.this.clear(); + } + + @Override + public K @NonNull [] toArray() { + return effects.clone(); + } + + @Override + public T @NonNull [] toArray(T @NonNull [] a) { + int size = size(); + if (a.length < size) + //noinspection unchecked + a = (T[]) newInstance(a.getClass().componentType(), size); + if (a.length > size) + a[size] = null; + //noinspection ReassignedVariable, SuspiciousSystemArraycopy + System.arraycopy(effects, 0, a, 0, effects.length); + return a; + } + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + boolean result = containsKey(o); + EffectMap.this.removeDouble(o); + return result; + } + } + + // values + + private transient DoubleCollection valuesCollection; + + @Override + public @NonNull DoubleCollection values() { + var vals = valuesCollection; + return vals == null ? (valuesCollection = new Values()) : vals; + } + + private class Values extends AbstractDoubleCollection { + + @Override + public @NonNull DoubleIterator iterator() { + return new ValueItr(); + } + + private class ValueItr extends AbstractDoubleIterator { + int cursor; + + @Override + public boolean hasNext() { + return cursor < values.length(); + } + + @Override + public double nextDouble() { + if (cursor >= values.length()) { + throw new NoSuchElementException(); + } + return values.get(cursor++); + } + + @Override + public void remove() { + int cursor = this.cursor; + if (cursor == 0) { + throw new IllegalStateException("next() has not been yet called"); + } + values.set(cursor - 1, effects[cursor - 1].getDefaultValue()); + } + } + + @Override + public int size() { + return EffectMap.this.size(); + } + + @Override + public void clear() { + EffectMap.this.clear(); + } + + @Override + public double[] toDoubleArray() { + double[] result = new double[values.length()]; + for (int i = 0; i < result.length; i++) { + result[i] = values.get(i); + } + return result; + } + + @Override + public boolean contains(double k) { + return containsValue(k); + } + } + + // entrySet + + private transient ObjectSet> entrySet; + + @Override + public ObjectSet> object2DoubleEntrySet() { + var es = entrySet; + return es == null ? (entrySet = new EntrySet()) : es; + } + + private class EntrySet extends AbstractObjectSet> { + + final Object[] entries = new Object[values.length()]; + + EntrySet() { + for (int i = 0; i < entries.length; i++) { + entries[i] = new Entry(i); + } + } + + @Override + public @NonNull ObjectIterator> iterator() { + return new EntryItr(); + } + + class EntryItr extends AbstractObjectIterator> { + int cursor = 0; + + @Override + public boolean hasNext() { + return cursor < entries.length; + } + + @Override + public Object2DoubleMap.Entry next() { + if (cursor >= entries.length) { + throw new NoSuchElementException(); + } + //noinspection unchecked + return (Entry) entries[cursor++]; + } + + @Override + public void remove() { + int cursor = this.cursor; + if (cursor == 0) { + throw new IllegalStateException("next() has not been yet called"); + } + values.set(cursor - 1, effects[cursor - 1].getDefaultValue()); + } + } + + @Override + public int size() { + return EffectMap.this.size(); + } + + @Override + public void clear() { + EffectMap.this.clear(); + } + + @Override + public Object @NonNull [] toArray() { + return entries.clone(); + } + + @Override + public T @NonNull [] toArray(T @NonNull [] a) { + int size = size(); + if (a.length < size) + //noinspection unchecked + a = (T[]) newInstance(a.getClass().componentType(), size); + if (a.length > size) + a[size] = null; + //noinspection ReassignedVariable, SuspiciousSystemArraycopy + System.arraycopy(entries, 0, a, 0, entries.length); + return a; + } + + @Override + public boolean contains(Object o) { + return o instanceof Object2DoubleMap.Entry entry + && kClass.isInstance(entry.getKey()) + && EffectMap.this.getDouble(entry.getKey()) == entry.getDoubleValue(); + } + + @Override + public boolean remove(Object o) { + if (o != null) { + for (Object object : entries) { + //noinspection unchecked + Entry entry = (Entry) object; + if (entry.equals(o)) { + entry.setValue(entry.getKey().getDefaultValue()); + return true; + } + } + } + return false; + } + } + + + @Data + private class Entry implements Object2DoubleMap.Entry { + final int index; + + @Override + public K getKey() { + return effects[index]; + } + + @Override + public double getDoubleValue() { + return values.get(index); + } + + @Override + public double setValue(double value) { + return EffectMap.this.put(effects[index], value); + } + + @Override + public boolean equals(Object o) { + if (o instanceof Object2DoubleMap.Entry object2DoubleEntry) { + // No instanceof because of compile error + //noinspection RedundantClassCall + if (Entry.class.isInstance(object2DoubleEntry)) { + @SuppressWarnings("unchecked") + Entry entry = (Entry) object2DoubleEntry; + return entry.index == this.index + && entry.getDoubleValue() == this.getDoubleValue(); + } + return object2DoubleEntry.getKey() instanceof NormalizableEffect effect + && effect.ordinal() == index + && object2DoubleEntry.getDoubleValue() == this.getDoubleValue(); + } + return false; + } + + @Override + public int hashCode() { + return getKey().hashCode() ^ Double.hashCode(getDoubleValue()); + } + } + + /** + * Throws {@link UnsupportedOperationException}. + * + * @param rv ignored + * @throws UnsupportedOperationException always + */ + @Override + public final void defaultReturnValue(double rv) { + throw new UnsupportedOperationException("defaultReturnValue() is not supported for EffectMap. This map always contains all " + kClass.getSimpleName() + " keys each with its own default value."); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/effect/NormalizableEffect.java b/src/main/java/ru/fokinatorr/sparkle/effect/NormalizableEffect.java new file mode 100644 index 0000000..f3f1445 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/effect/NormalizableEffect.java @@ -0,0 +1,28 @@ +package ru.fokinatorr.sparkle.effect; + +/** + * An effect that supports normalizing its values. + */ +public interface NormalizableEffect { + + /** + * Normalizes the given value to be suitable for this effect. + * @param value the value to normalize + * @return the normalized value + */ + double normalize(double value); + + /** + * Returns the ordinal of this effect instance (in case it's an enum, its position + * in its enum declaration, where the initial constant is assigned + * an ordinal of zero). + * @return the ordinal of this effect instance + */ + int ordinal(); + + /** + * Returns the default value of this effect instance. + * @return the default effect value + */ + double getDefaultValue(); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/effect/graphics/GraphicEffect.java b/src/main/java/ru/fokinatorr/sparkle/effect/graphics/GraphicEffect.java new file mode 100644 index 0000000..1a18bc4 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/effect/graphics/GraphicEffect.java @@ -0,0 +1,99 @@ +package ru.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; + +/** + * A graphic effect. + *

Some graphic effects can only be applied to rasterized content (images) + */ +@Getter +@RequiredArgsConstructor +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +public enum GraphicEffect implements NormalizableEffect { + /** + * The hue-shift graphic effect. + *

Note for Scratchers: This effect is similar to the "color" effect in Scratch. + * Unlike in Scratch, the max meaningful value of this effect is {@code 360} and not {@code 200}. + */ + HUE_SHIFT(0, 360, true), + /** + * The bulge graphic effect. + *

Note for Scratchers: This effect is similar to the "fisheye" effect in Scratch. + */ + BULGE, + /** + * The whirl graphic effect. + */ + WHIRL, + /** + * The skew graphic effect. Skew is performed along the X axis. + */ + SKEW_X, + /** + * The skew graphic effect. Skew is performed along the Y axis. + */ + SKEW_Y, + /** + * The pixelation graphic effect. + *

Note for Scratchers: This effect is similar to the "pixelate" effect in Scratch. + */ + PIXELATION(0, Double.POSITIVE_INFINITY, false), + /** + * The mosaic graphic effect. + */ + MOSAIC(0, Double.POSITIVE_INFINITY, false), + /** + * The brightness graphic effect. + */ + BRIGHTNESS(-100, 100, false), + /** + * The opacity graphic effect. + *

Note for Scratchers: This effect is similar to the "ghost" effect in Scratch. + */ + OPACITY(0, 100, false); + + /** + * The minimal value of this effect. + */ + double min; + /** + * The maximal value of this effect. + */ + double max; + /** + * If {@code true} then uses wrap-around clamping in normalization, otherwise normal clamping. + */ + boolean useWrapClamp; + + /** + * Constructor for effects without range + */ + GraphicEffect() { + this(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, false); + } + + /** + * {@inheritDoc} + * + * @param value {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public double normalize(double value) { + return useWrapClamp ? Mth.wrapClamp(value, min, max) : Mth.clamp(value, min, max); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public double getDefaultValue() { + return 0; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/effect/graphics/GraphicEffectMap.java b/src/main/java/ru/fokinatorr/sparkle/effect/graphics/GraphicEffectMap.java new file mode 100644 index 0000000..6a5d86d --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/effect/graphics/GraphicEffectMap.java @@ -0,0 +1,29 @@ +package ru.fokinatorr.sparkle.effect.graphics; + +import ru.fokinatorr.sparkle.effect.EffectMap; +import ru.fokinatorr.sparkle.graphics.render.renderer.Renderable; + +/** + * An effect map that stores a {@link Renderable}'s graphic effects. + */ +public class GraphicEffectMap extends EffectMap { + /** + * Creates a new empty {@code GraphicEffectMap} with all effect values set to respective default ones. + */ + public GraphicEffectMap() { + super(GraphicEffect.values()); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public GraphicEffectMap copy() { + GraphicEffectMap copy = new GraphicEffectMap(); + for (int i = 0; i < values.length(); i++) { + copy.values.set(i, values.get(i)); + } + return copy; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/effect/graphics/GraphicEffectMap.java.bak b/src/main/java/ru/fokinatorr/sparkle/effect/graphics/GraphicEffectMap.java.bak new file mode 100644 index 0000000..3b02dc6 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/effect/graphics/GraphicEffectMap.java.bak @@ -0,0 +1,466 @@ +package ru.fokinatorr.sparkle.effect.graphics; + +import it.unimi.dsi.fastutil.doubles.AbstractDoubleCollection; +import it.unimi.dsi.fastutil.doubles.AbstractDoubleIterator; +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 java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +import static java.lang.reflect.Array.newInstance; + +/** + * An object mapping graphic effects to their values. + *

Null keys are not supported. + * The map contains all the possible keys, so removing a key effectively sets the associated value to {@code 0.0}. + */ +public class GraphicEffectMap extends AbstractObject2DoubleMap { + + /** + * The values array. Similarly to {@link java.util.EnumMap}, maps enum ordinal to value. + */ + private final AtomicDoubleArray values = new AtomicDoubleArray(GRAPHIC_EFFECTS.length); + /** + * All the graphic effect values, cached for performance. + */ + private static final GraphicEffect[] GRAPHIC_EFFECTS = GraphicEffect.values(); + + /** + * Creates a new empty {@code GraphicEffectMap}. + */ + public GraphicEffectMap() { + defRetValue = 0.0; + clear(); + } + + /** + * Creates a new {@code GraphicEffectMap} with the given map's contents. + */ + public GraphicEffectMap(Map m) { + this(); + putAll(m); + } + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + public int size() { + return values.length(); + } + + /** + * A graphic effect map is never empty. + * + * @return {@code false} + */ + @Override + public boolean isEmpty() { + return false; + } + + /** + * Associates the given graphic effect with the given value. + * + * @param key the graphic effect (must not be {@code null}) + * @param value the new value + * @return the old value of the effect + * @throws NullPointerException if the key is {@code null} + */ + @Override + public double put(GraphicEffect key, double value) { + Objects.requireNonNull(key, "graphic effect"); + return values.getAndSet(key.ordinal(), key.normalize(value)); + } + + /** + * Increments the given graphic effect's value by the given delta. + * @param key the graphic effect + * @param delta the delta + * @return the old effect value + */ + public double increment(GraphicEffect key, double delta) { + Objects.requireNonNull(key, "graphic effect"); + return values.getAndUpdate(key.ordinal(), oldVal -> key.normalize(oldVal + delta)); + } + + /** + * Decrements the given graphic effect's value by the given delta. + * @param key the graphic effect + * @param delta the delta + * @return the old effect value + */ + public double decrement(GraphicEffect key, double delta) { + Objects.requireNonNull(key, "graphic effect"); + return values.getAndUpdate(key.ordinal(), oldVal -> key.normalize(oldVal - delta)); + } + + /** + * Returns the value of the given graphic effect. + * + * @param key the key + * @return {@inheritDoc} + */ + @Override + public double getDouble(Object key) { + return key instanceof GraphicEffect graphicEffect ? values.get(graphicEffect.ordinal()) : defRetValue; + } + + /** + * Sets the value of the given graphic effect to {@code 0.0}. + * + * @param key the graphic effect + * @return {@inheritDoc} + */ + @Override + public double removeDouble(Object key) { + return key instanceof GraphicEffect graphicEffect + ? values.getAndSet(graphicEffect.ordinal(), 0.0) + : defRetValue; + } + + /** + * Effectively sets all effect values to {@code 0.0}. + */ + @Override + public void clear() { + for (int i = 0; i < values.length(); i++) { + values.set(i, defRetValue); + } + } + + /** + * All keys of type {@link GraphicEffect} are present in the map. + * + * @param k {@inheritDoc} + * @return {@code true} if the given value is not {@code null} and is an instance of {@link GraphicEffect}. + */ + @Override + public boolean containsKey(Object k) { + return k instanceof GraphicEffect; + } + + /** + * {@inheritDoc} + * + * @param v the value + */ + @Override + public boolean containsValue(double v) { + final AtomicBoolean result = new AtomicBoolean(false); + values.forEach(value -> { + if (value == v) { + result.set(true); + } + }); + return result.get(); + } + + // keySet + + private transient ObjectSet keySet; + + @Override + public ObjectSet keySet() { + var ks = keySet; + return ks == null ? (keySet = new KeySet()) : ks; + } + + private class KeySet extends AbstractObjectSet { + // Generally, something similar to set from values array but with "remove" options + + private class KeyItr extends AbstractObjectIterator { + // Iterator over an array with "removing" capability + int cursor = 0; + + @Override + public boolean hasNext() { + return cursor < GRAPHIC_EFFECTS.length; + } + + @Override + public GraphicEffect next() { + if (cursor >= GRAPHIC_EFFECTS.length) { + throw new NoSuchElementException(); + } + return GRAPHIC_EFFECTS[cursor++]; + } + + @Override + public void remove() { + int cursor = this.cursor; + if (cursor == 0) { + throw new IllegalStateException("next() has not been yet called"); + } + values.set(cursor - 1, defRetValue); + } + } + + @Override + public ObjectIterator iterator() { + return new KeyItr(); + } + + @Override + public int size() { + return GraphicEffectMap.this.size(); + } + + @Override + public void clear() { + GraphicEffectMap.this.clear(); + } + + @Override + public GraphicEffect[] toArray() { + return GRAPHIC_EFFECTS.clone(); + } + + @Override + public T[] toArray(T[] a) { + int size = size(); + if (a.length < size) + //noinspection unchecked + a = (T[]) newInstance(a.getClass().componentType(), size); + if (a.length > size) + a[size] = null; + //noinspection ReassignedVariable + System.arraycopy(GRAPHIC_EFFECTS, 0, a, 0, GRAPHIC_EFFECTS.length); + return a; + } + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + boolean result = containsKey(o); + GraphicEffectMap.this.removeDouble(o); + return result; + } + } + + // values + + private transient DoubleCollection valuesCollection; + + @Override + public DoubleCollection values() { + var vals = valuesCollection; + return vals == null ? (valuesCollection = new Values()) : vals; + } + + private class Values extends AbstractDoubleCollection { + + @Override + public DoubleIterator iterator() { + return new ValueItr(); + } + + private class ValueItr extends AbstractDoubleIterator { + int cursor; + + @Override + public boolean hasNext() { + return cursor < values.length(); + } + + @Override + public double nextDouble() { + if (cursor >= values.length()) { + throw new NoSuchElementException(); + } + return values.get(cursor++); + } + + @Override + public void remove() { + int cursor = this.cursor; + if (cursor == 0) { + throw new IllegalStateException("next() has not been yet called"); + } + values.set(cursor - 1, defRetValue); + } + } + + @Override + public int size() { + return GraphicEffectMap.this.size(); + } + + @Override + public void clear() { + GraphicEffectMap.this.clear(); + } + + @Override + public double[] toDoubleArray() { + double[] result = new double[values.length()]; + for (int i = 0; i < result.length; i++) { + result[i] = values.get(i); + } + return result; + } + + @Override + public boolean contains(double k) { + return containsValue(k); + } + } + + // entrySet + + private transient ObjectSet> entrySet; + + @Override + public ObjectSet> object2DoubleEntrySet() { + var es = entrySet; + return es == null ? (entrySet = new EntrySet()) : es; + } + + private class EntrySet extends AbstractObjectSet> { + + final Entry[] entries = new Entry[values.length()]; + + EntrySet() { + for (int i = 0; i < entries.length; i++) { + entries[i] = new Entry(i); + } + } + + @Override + public ObjectIterator> iterator() { + return new EntryItr(); + } + + class EntryItr extends AbstractObjectIterator> { + int cursor = 0; + + @Override + public boolean hasNext() { + return cursor < entries.length; + } + + @Override + public Object2DoubleMap.Entry next() { + if (cursor >= entries.length) { + throw new NoSuchElementException(); + } + return entries[cursor++]; + } + + @Override + public void remove() { + int cursor = this.cursor; + if (cursor == 0) { + throw new IllegalStateException("next() has not been yet called"); + } + values.set(cursor - 1, defRetValue); + } + } + + @Override + public int size() { + return GraphicEffectMap.this.size(); + } + + @Override + public void clear() { + GraphicEffectMap.this.clear(); + } + + @Override + public Entry[] toArray() { + return entries.clone(); + } + + @Override + public T[] toArray(T[] a) { + int size = size(); + if (a.length < size) + //noinspection unchecked + a = (T[]) newInstance(a.getClass().componentType(), size); + if (a.length > size) + a[size] = null; + //noinspection ReassignedVariable + System.arraycopy(entries, 0, a, 0, entries.length); + return a; + } + + @Override + public boolean contains(Object o) { + return o instanceof Object2DoubleMap.Entry entry + && entry.getKey() instanceof GraphicEffect graphicEffect + && GraphicEffectMap.this.getDouble(graphicEffect) == entry.getDoubleValue(); + } + + @Override + public boolean remove(Object o) { + if (o != null) { + for (Entry entry : entries) { + if (entry.equals(o)) { + entry.setValue(defRetValue); + return true; + } + } + } + return false; + } + } + + + @Data + private class Entry implements Object2DoubleMap.Entry { + final int index; + + @Override + public GraphicEffect getKey() { + return GRAPHIC_EFFECTS[index]; + } + + @Override + public double getDoubleValue() { + return values.get(index); + } + + @Override + public double setValue(double value) { + return GraphicEffectMap.this.put(GRAPHIC_EFFECTS[index], value); + } + + @Override + public boolean equals(Object o) { + if (o instanceof Object2DoubleMap.Entry object2DoubleEntry) { + if (o instanceof Entry entry) { + return entry.index == this.index + && entry.getDoubleValue() == this.getDoubleValue(); + } + return object2DoubleEntry.getKey() instanceof GraphicEffect graphicEffect + && graphicEffect.ordinal() == index + && object2DoubleEntry.getDoubleValue() == this.getDoubleValue(); + } + return false; + } + } + + /** + * Throws {@link UnsupportedOperationException}. + * + * @param rv ignored + * @throws UnsupportedOperationException always + */ + @Override + public void defaultReturnValue(double rv) { + throw new UnsupportedOperationException("defaultReturnValue() is not supported for GraphicEffectMap. This map always contains all GraphicEffect keys with a default value of 0.0."); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/effect/sounds/SoundEffect.java b/src/main/java/ru/fokinatorr/sparkle/effect/sounds/SoundEffect.java new file mode 100644 index 0000000..89ecfba --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/effect/sounds/SoundEffect.java @@ -0,0 +1,47 @@ +package ru.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; + +/** + * A sound effect. + */ +@Getter +@RequiredArgsConstructor +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +public enum SoundEffect implements NormalizableEffect { + /** + * The volume sound effect. + *

Note for Scratchers: Unlike in Scratch, the volume is a sound effect rather than a separate property. + */ + VOLUME(0, 100, 100), + /** + * The pitch sound effect. + *

Note for Scratchers: The effect is similar to the "pitch" sound effect in Scratch. The only thing different + * from Scratch's "pitch" effect is the value range, being as in TurboWarp when "Remove Miscellaneous Limits" is enabled. + */ + PITCH(-1000, 1000, 0), + /** + * The left-right pan sound effect. This is only guaranteed to work with mono sounds. + *

Note for Scratchers: The effect is similar to the "pan left/right" sound effect in Scratch. + */ + PAN(-100, 100, 0); + + double min; + double max; + double defaultValue; + + /** + * {@inheritDoc} + * @param value {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public double normalize(double value) { + return Mth.clamp(value, min, max); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/effect/sounds/SoundEffectMap.java b/src/main/java/ru/fokinatorr/sparkle/effect/sounds/SoundEffectMap.java new file mode 100644 index 0000000..4e2cf77 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/effect/sounds/SoundEffectMap.java @@ -0,0 +1,28 @@ +package ru.fokinatorr.sparkle.effect.sounds; + +import ru.fokinatorr.sparkle.effect.EffectMap; + +/** + * An effect map that stores sound effects. + */ +public class SoundEffectMap extends EffectMap { + /** + * Creates a new {@code SoundEffectMap} with all effect values set to respective default ones. + */ + public SoundEffectMap() { + super(SoundEffect.values()); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public SoundEffectMap copy() { + SoundEffectMap copy = new SoundEffectMap(); + for (int i = 0; i < values.length(); i++) { + copy.values.set(i, values.get(i)); + } + return copy; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/AbstractCancellableEvent.java b/src/main/java/ru/fokinatorr/sparkle/event/AbstractCancellableEvent.java new file mode 100644 index 0000000..f5416d2 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/AbstractCancellableEvent.java @@ -0,0 +1,37 @@ +package ru.fokinatorr.sparkle.event; + +/** + * This class provides the functionality of a cancellable event. + */ +public abstract class AbstractCancellableEvent implements CancellableEvent { + + /** + * The "cancelled" flag. Declared {@code private} to prevent unauthorized changes; should only be modified with + * {@link CancellableEvent}'s API. + */ + private boolean cancelled; + + /** + * Constructor for subclasses to call. + */ + protected AbstractCancellableEvent() { + cancelled = false; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean isCancelled() { + return cancelled; + } + + /** + * {@inheritDoc} + */ + @Override + public void cancel() { + cancelled = true; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/BackdropChangeEvent.java b/src/main/java/ru/fokinatorr/sparkle/event/BackdropChangeEvent.java new file mode 100644 index 0000000..6b4d6cf --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/BackdropChangeEvent.java @@ -0,0 +1,124 @@ +package ru.fokinatorr.sparkle.event; + +import lombok.EqualsAndHashCode; +import lombok.NonNull; +import lombok.Value; +import lombok.experimental.NonFinal; +import ru.fokinatorr.sparkle.stage.Stage; + +import java.util.Objects; + +/** + * Interface for events that indicate a stage's backdrop change. + *

Note for Scratchers: This event is similar to "when backdrop switches to [ v]" event in Scratch. + */ +public sealed interface BackdropChangeEvent extends Event + permits BackdropChangeEvent.Before, + BackdropChangeEvent.After { + + /** + * {@return the stage whose backdrop is changed} + */ + Stage stage(); + + /** + * {@return the old backdrop ID} + */ + int oldBackdropId(); + + /** + * {@return the new backdrop ID} + */ + int newBackdropId(); + + /** + * This event is fired before a backdrop is changed. + */ + @Value + @EqualsAndHashCode(callSuper = false) + class Before extends AbstractCancellableEvent implements BackdropChangeEvent { + @NonNull + Stage stage; + int oldBackdropId; + @NonFinal + int newBackdropId; + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public Stage stage() { + return stage; + } + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + public int oldBackdropId() { + return oldBackdropId; + } + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + public int newBackdropId() { + return newBackdropId; + } + + /** + * Sets the new backdrop ID. + * + * @param newBackdropId the new backdrop ID + * @throws IndexOutOfBoundsException if there is no such backdrop ID + */ + public void setNewBackdropId(int newBackdropId) { + Objects.checkIndex(newBackdropId, stage.getAssets().texturesByIndex().size()); + this.newBackdropId = newBackdropId; + } + + /** + * {@return a string representation of this event} + */ + @Override + public String toString() { + return "BackdropChangeEvent.Before{" + + "stage=" + stage + ", " + + "oldCostumeId=" + oldBackdropId + ", " + + "newCostumeId=" + newBackdropId + '}'; + } + + } + + /** + * This event is fired after a backdrop was changed. + * + * @param stage the stage whose backdrop was changed + * @param oldBackdropId the old backdrop ID + * @param newBackdropId the new backdrop ID + */ + record After( + @NonNull Stage stage, + int oldBackdropId, + int newBackdropId + ) implements BackdropChangeEvent { + /** + * {@return a string representation of this event} + */ + @Override + @NonNull + public String toString() { + return "BackdropChangeEvent.After{" + + "stage=" + stage + + ", oldCostumeId=" + oldBackdropId + + ", newCostumeId=" + newBackdropId + + '}'; + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/CancellableEvent.java b/src/main/java/ru/fokinatorr/sparkle/event/CancellableEvent.java new file mode 100644 index 0000000..9e962ae --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/CancellableEvent.java @@ -0,0 +1,19 @@ +package ru.fokinatorr.sparkle.event; + +/** + * Represents a cancellable event. + */ +public interface CancellableEvent extends Event { + + /** + * {@return whether this event is cancelled} {@code false} means {@link #cancel()} haven't ever been called + * on this event instance yet. + */ + boolean isCancelled(); + + /** + * Cancels this event. After that, the {@link #isCancelled()} method should not return {@code false} for this + * event instance ever again. + */ + void cancel(); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/Event.java b/src/main/java/ru/fokinatorr/sparkle/event/Event.java new file mode 100644 index 0000000..ec6fc8a --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/Event.java @@ -0,0 +1,9 @@ +package ru.fokinatorr.sparkle.event; + +/** + * Marker interface for all events, like starting or keyboard/mouse events. + *

Events can also carry some useful info and are generally immutable. One + * of the exceptions is the cancelled flag in {@link CancellableEvent}, which can be changed once. + */ +public interface Event { +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/MessageEvent.java b/src/main/java/ru/fokinatorr/sparkle/event/MessageEvent.java new file mode 100644 index 0000000..02cb5bf --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/MessageEvent.java @@ -0,0 +1,38 @@ +package ru.fokinatorr.sparkle.event; + +import lombok.NonNull; + +import java.util.Optional; + +/** + * This event is fired when a message is broadcasted. + *

Note for Scratchers: This event is similar to "when I receive [ v]" event in Scratch. + * + * @param messageId the message's ID. Not necessary to be registered, unlike in Scratch. + * @param receivedData an optional data of the message + */ +public record MessageEvent( + @NonNull String messageId, + @NonNull Optional receivedData +) implements Event { + + /** + * Creates a new {@code MessageEvent}. This is an alternative constructor which constructs an {@link Optional} + * by itself. + * @param messageId the message's ID + * @param receivedData the received data; may be {@code null} + * @throws NullPointerException if message ID is {@code null} + */ + public MessageEvent(String messageId, Object receivedData) { + this(messageId, Optional.ofNullable(receivedData)); + } + + /** + * Creates a new {@code MessageEvent} without received data. + * @param messageId the message ID + * @throws NullPointerException if message ID is {@code null} + */ + public MessageEvent(String messageId) { + this(messageId, Optional.empty()); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/annotation/EventListener.java b/src/main/java/ru/fokinatorr/sparkle/event/annotation/EventListener.java new file mode 100644 index 0000000..77347ed --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/annotation/EventListener.java @@ -0,0 +1,43 @@ +package ru.fokinatorr.sparkle.event.annotation; + +import ru.fokinatorr.sparkle.event.Event; +import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher; + +import java.lang.annotation.*; +import java.lang.reflect.InaccessibleObjectException; + +/** + * Annotation used by {@link EventDispatcher#register(Object)} that indicates the annotated method should be registered as a listener in the event dispatcher. + *

Valid Method Signature

+ *
    + *
  • + * The method should only accept a single argument of type {@link Event} or subinterface/implementing class, + * otherwise an {@link IllegalArgumentException} will be thrown; + *
  • + *
  • + * The return value is ignored and can be of any type. + *
  • + *
+ *

Note: If you use named modules and a class containing a method annotated with this annotation is not + * exported outside the module, or the method and/or class are not public, you should export/open the + * containing package (respectively) to module {@code ru.fokinatorr.sparkle.core}, otherwise an {@link InaccessibleObjectException} + * will likely be thrown by a dispatcher. + * + * @see EventDispatcher#register(Object) + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface EventListener { + + /** + * Specifies the priority of the listener. Default value is equal to {@link EventDispatcher#DEFAULT_PRIORITY}. + * Higher priority listeners (the ones with less priority value) are executed first. + * + * @return the listener's priority + * @see EventDispatcher#MAX_PRIORITY + * @see EventDispatcher#MIN_PRIORITY + * @see EventDispatcher#DEFAULT_PRIORITY + */ + byte priority() default EventDispatcher.DEFAULT_PRIORITY; +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/dispatcher/EventDispatcher.java b/src/main/java/ru/fokinatorr/sparkle/event/dispatcher/EventDispatcher.java new file mode 100644 index 0000000..68e8ad6 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/dispatcher/EventDispatcher.java @@ -0,0 +1,128 @@ +package ru.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 java.lang.reflect.InaccessibleObjectException; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; + +/** + * An event dispatcher that can be used to fire/listen to events. + *

Implementations are not required to throw a {@link NullPointerException} if a {@code null} reference was passed to any + * method; they are allowed to silently ignore it and/or just log that a {@code null} reference was passed. + *

Some implementations might need to perform cleanup when they're no longer needed, so this interface extends {@link NonThrowingAutoCloseable}. + *

Warning: event listeners should not fire the same event they received, or events that cause + * the same event to be re-fired. This can (and will in most cases) lead to infinite loops and unpredictable + * behaviour. Implementations may try to prevent re-firing the same event, but are NOT required to. + */ +public interface EventDispatcher extends NonThrowingAutoCloseable { + /** + * The maximal listener priority. + */ + byte MAX_PRIORITY = Byte.MIN_VALUE; + /** + * The minimal listener priority. + */ + byte MIN_PRIORITY = Byte.MAX_VALUE; + /** + * The default listener priority. + */ + byte DEFAULT_PRIORITY = 0; + + /** + * Adds a listener for event of the given type or any of its subclasses. + *

+ * If the given event listener was already present, then its priority is set to {@link #DEFAULT_PRIORITY default value}. + * + * @param eventClass the type of the event + * @param listener the listener to add + * @return an object that can be used to remove the listener + * @throws NullPointerException if any argument is {@code null} (optional) + */ + ListenerRemover addListener(Class eventClass, Consumer listener); + + /** + * Adds a listener for event of the given type or any of its subclasses. + *

+ * If the given event listener was already present, then its priority is set to the given one. + * + * @param eventClass the type of the event + * @param priority the priority of the listener + * @param listener the listener to add + * @return an object that can be used to remove the listener + * @throws NullPointerException if any argument is {@code null} (optional) + * @see #MAX_PRIORITY + * @see #MIN_PRIORITY + */ + ListenerRemover addListener(Class eventClass, byte priority, Consumer listener); + + /** + * Registers all instance methods annotated with {@link EventListener @EventListener} of the given object's class as event listeners. + * Or, if the given object is a {@link Class}, all its static methods annotated with {@link EventListener @EventListener} + * are registered as listeners. + * + * @param o the object + * @return an object that can be used to remove the listeners + * @throws IllegalArgumentException if a method annotated with {@link EventListener @EventListener} has invalid arguments + * @throws InaccessibleObjectException if a method could not be reflectively accessed for any reason + * @throws NullPointerException if the object is {@code null} (optional) + * @see EventListener + */ + ListenerRemover register(Object o); + + /** + * Determines whether there are registered event listeners that listen for the given event class or superclass. + * This method can be used to determine whether firing an event has any effect. Useful to avoid firing an event + * that is fired a lot of times (like {@link MouseEvent.MouseCursorMovedEvent MouseCursorMovedEvent}), + * thus optimizing the CPU usage. + * @param eventClass the event class to check for + * @throws NullPointerException if the given class object is {@code null} (optional) + * @return {@code true} if there are any registered listeners that listen for the given event class (or superclass), + * {@code false} otherwise + */ + boolean hasListenersFor(Class eventClass); + + /** + * Fires the given event, i.e. activates all listeners that listen to events of the given event's type or supertypes, + * returning immediately. + *

Be aware that listeners may change the mutable state of the given event. + * + * @param event the event to fire + * @return a {@link CompletableFuture} that completes when all event handlers are done + * @throws NullPointerException if the given event is {@code null} (optional) + */ + CompletableFuture fireEvent(Event event); + + /** + * Fires the given event, i.e. activates all listeners that listen to events of the given event's type or supertypes, + * and waits until all event listeners are executed. + *

Be aware that listeners may change the mutable state of the given event. + * + * @param event the event to fire + * @throws NullPointerException if the given event is {@code null} (optional) + */ + default void fireEventAndWait(Event event) { + fireEvent(event).join(); + } + + /** + * Returns a new default implementation of {@code EventDispatcher}. + * + * @return a new {@code EventDispatcher} + */ + static EventDispatcher newDefault() { + return new DefaultEventDispatcher(); + } + + /** + * {@inheritDoc} + * @implNote By default, this method does nothing. An event dispatcher doesn't usually have closeable resources. + */ + @Override + default void close() { + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/dispatcher/ListenerRemover.java b/src/main/java/ru/fokinatorr/sparkle/event/dispatcher/ListenerRemover.java new file mode 100644 index 0000000..dddabbe --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/dispatcher/ListenerRemover.java @@ -0,0 +1,42 @@ +package ru.fokinatorr.sparkle.event.dispatcher; + +import java.util.Objects; + +/** + * An object that knows how to remove a listener from a dispatcher. Extends {@link Runnable} for + * convenience. + */ +@FunctionalInterface +public interface ListenerRemover extends Runnable { + + /** + * Removes the listener from the dispatcher. If the listener is already removed, will not have any effect. + */ + void remove(); + + /** + * {@inheritDoc} Equivalent to {@link #remove()}. + */ + @Override + default void run() { + remove(); + } + + /** + * Returns a new {@code ListenerRemover} that firstly calls the {@link #remove()} method + * of this {@code ListenerRemover}, then the {@link #remove()} method of the given one. + * @param other the {@code ListenerRemover} to call after this one + * @throws NullPointerException if the given {@code ListenerRemover} is {@code null} + * @return a new composed {@code ListenerRemover} + */ + default ListenerRemover andThen(ListenerRemover other) { + Objects.requireNonNull(other, "other"); + return () -> { + try { + remove(); + } finally { + other.remove(); + } + }; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/dispatcher/impl/DefaultEventDispatcher.java b/src/main/java/ru/fokinatorr/sparkle/event/dispatcher/impl/DefaultEventDispatcher.java new file mode 100644 index 0000000..ebc0feb --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/dispatcher/impl/DefaultEventDispatcher.java @@ -0,0 +1,264 @@ +package ru.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 java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Parameter; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; +import java.util.function.Predicate; + +/** + * Default implementation of {@link EventDispatcher}. + */ +// Not public API +@Slf4j +public class DefaultEventDispatcher implements EventDispatcher { + + private record PrioritizedEventListener( + byte priority, + @NonNull Consumer listener + ) implements Consumer, Comparable> { + @Override + public void accept(E e) { + listener.accept(e); + } + + @Override + public int compareTo(@NonNull PrioritizedEventListener that) { + return Byte.compare(that.priority, this.priority); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof PrioritizedEventListener(_, Consumer listener1))) return false; + return listener == listener1; + } + + @Override + public int hashCode() { + return listener.hashCode(); + } + } + + private final EventListeners eventListeners = new EventListeners(); + // Use dedicated ExecutorService instead of common to prevent thread starvation + private final ExecutorService dispatchEventExecutor = Executors.newCachedThreadPool(new ContextInheritingThreadFactory( + "event-dispatcher-" + hashCode() + "-worker", + ThreadType.VIRTUAL // virtual threads to avoid system overloading + )); + private final Lock listenersLock = new ReentrantLock(); + + private static class EventListeners { + + private final Map, NavigableSet>> + map = new HashMap<>(); + + NavigableSet> getOrCreate(Class eventClass) { + //noinspection unchecked, RedundantCast + return (NavigableSet>) (Object) + map.computeIfAbsent(eventClass, _ -> new ConcurrentSkipListSet<>()); + } + + NavigableSet> getOrEmpty(Class eventClass) { + return map.containsKey(eventClass) ? getOrCreate(eventClass) : Collections.emptyNavigableSet(); + } + } + + @Override + public ListenerRemover addListener(Class eventClass, Consumer listener) { + Objects.requireNonNull(eventClass, "event class"); + Objects.requireNonNull(listener, "listener"); + listenersLock.lock(); + try { + return implAddListener(eventClass, listener, DEFAULT_PRIORITY); + } finally { + listenersLock.unlock(); + } + } + + @Override + public ListenerRemover addListener(Class eventClass, byte priority, Consumer listener) { + Objects.requireNonNull(eventClass, "event class"); + Objects.requireNonNull(listener, "listener"); + listenersLock.lock(); + try { + return implAddListener(eventClass, listener, priority); + } finally { + listenersLock.unlock(); + } + } + + @Override + public ListenerRemover register(Object o) { + Objects.requireNonNull(o, "the object"); + Class clazz; + Object target; + Predicate methodPredicate; + ListenerRemover listenerRemover = null; + if (o instanceof Class cls) { // Register only static methods + clazz = cls; + target = null; // Static methods do not have an instance target + methodPredicate = method -> Modifier.isStatic(method.getModifiers()); + } else { // Register instance methods + clazz = o.getClass(); + target = o; + methodPredicate = method -> !Modifier.isStatic(method.getModifiers()); + } + listenersLock.lock(); + try { + for (Method method : clazz.getDeclaredMethods()) { + if (methodPredicate.test(method)) { + EventListener eventListener = method.getAnnotation(EventListener.class); + if (eventListener != null) { + Class eventClass = getListenedEvent(method); + // if we're here the signature is valid + method.setAccessible(true); + ListenerRemover addend = implAddListener( + eventClass, + asEventListener(method, target), + eventListener.priority() + ); + if (listenerRemover == null) { + listenerRemover = addend; + } else { + listenerRemover = listenerRemover.andThen(addend); + } + } + } + } + if (listenerRemover == null) { + listenerRemover = () -> { + }; + log.warn("No @EventListener methods were found in {}", clazz); + } + return listenerRemover; + } finally { + listenersLock.unlock(); + } + } + + @Override + public boolean hasListenersFor(Class eventClass) { + Objects.requireNonNull(eventClass, "event class"); + return eventListeners.map.keySet().stream().anyMatch(cls -> cls.isAssignableFrom(eventClass)); + } + + @Override + public CompletableFuture fireEvent(Event event) { + Objects.requireNonNull(event, "event"); + + listenersLock.lock(); + try { + // Recollect listeners by priority, in order from highest to lowest + Byte2ObjectSortedMap>> listenersByPriority = new Byte2ObjectRBTreeMap<>(); + Set> handledTypes = new HashSet<>(); + + for (var entry : eventListeners.map.entrySet()) { + Class eventClass = entry.getKey(); + NavigableSet> listeners = entry.getValue(); + + if (handledTypes.add(eventClass) && !listeners.isEmpty() && eventClass.isAssignableFrom(event.getClass())) { + for (PrioritizedEventListener listener : listeners) { + @SuppressWarnings("unchecked") + Consumer typedListener = (Consumer) listener.listener(); + listenersByPriority + .computeIfAbsent(listener.priority(), _ -> new ArrayList<>()) + .add(typedListener); + } + } + } + + CompletableFuture chain = CompletableFuture.completedFuture(null); + if (!listenersByPriority.isEmpty()) { + for (var groupListeners : listenersByPriority.values()) { + // Different priority listeners get executed sequentially, from highest to lowest + chain = chain.thenCompose(_ -> { + List> futures = groupListeners.stream() + .map(listener -> CompletableFuture.runAsync( + () -> listener.accept(event), + dispatchEventExecutor + )) + .toList(); + + // Same priority listeners get executed concurrently + return CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)); + }); + } + } // else silently ignore the event and return an empty future + return chain; + } finally { + listenersLock.unlock(); + } + } + + @Override + public void close() { + // We need cleanup + dispatchEventExecutor.close(); + } + + // Assumes null checks were done + private ListenerRemover implAddListener(Class eventClass, Consumer cons, byte priority) { + NavigableSet> set = eventListeners.getOrCreate(eventClass); + PrioritizedEventListener listener = new PrioritizedEventListener<>(priority, cons); + // 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); + return () -> { + set.remove(listener); + log.info("Unregistered a listener for event {}: {}", eventClass.getName(), listener); + }; + } + + /** + * @throws IllegalArgumentException if the signature of the method is invalid + */ + private static Class getListenedEvent(Method method) { + Parameter[] parameters = method.getParameters(); + if (parameters.length != 1) { + throw new IllegalArgumentException( + "Illegal @EventListener method parameter count; expected 1, found " + parameters.length + + " (in method " + method + ")" + ); + } + Class cls = parameters[0].getType(); + if (!Event.class.isAssignableFrom(cls)) { + throw new IllegalArgumentException( + "Illegal @EventListener method parameter type: expected " + Event.class.getName() + + " or subinterface/implementation, found " + cls.getName() + " (in method " + method + ")" + ); + } + return cls.asSubclass(Event.class); + } + + private static Consumer asEventListener(Method method, Object target) { + return e -> { + try { + method.invoke(target, e); + } catch (InvocationTargetException ex) { + log.error("Listener threw exception", ex.getCause()); + } catch (IllegalAccessException ex) { + throw new AssertionError( + "Unexpected IllegalAccessException thrown, method should have been setAccessible(true)", + ex + ); + } + }; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/input/InputEvent.java b/src/main/java/ru/fokinatorr/sparkle/event/input/InputEvent.java new file mode 100644 index 0000000..1fcbe2c --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/input/InputEvent.java @@ -0,0 +1,16 @@ +package ru.fokinatorr.sparkle.event.input; + +import ru.fokinatorr.sparkle.event.Event; +import ru.fokinatorr.sparkle.stage.Stage; + +/** + * Base interface for events representing a user input (keyboard, mouse, etc.) + */ +public interface InputEvent extends Event { + + /** + * Returns the stage on which the input was performed. + * @return the target stage + */ + Stage stage(); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/input/Key.java b/src/main/java/ru/fokinatorr/sparkle/event/input/Key.java new file mode 100644 index 0000000..5cf8f77 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/input/Key.java @@ -0,0 +1,224 @@ +package ru.fokinatorr.sparkle.event.input; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; + +/** + * Represents a key on the keyboard. This enum class should generally not be used to determine + * the actual typed character. + *

Note that there are different names and/or typical behaviour for several modifier keys and the + * {@link #MENU Menu} key, as listed below: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Key named as it is in this classWindowsLinuxmacOSNotes
{@link #LEFT_SHIFT Shift}ShiftShiftShiftSame function across all OSes.
{@link #LEFT_CONTROL Control}ControlControlControlLess common for app shortcuts on macOS.
{@link #LEFT_ALT Alt}AltAltOptionGenerally the same function.
{@link #LEFT_META Meta}WindowsSuper (typically)CommandKey used for OS-level functions, the main shortcut key on macOS.
{@link #MENU Menu}Context menu/Application keyMenuN/AThis key is typically not present on macOS, where the context menu functionality is accessed differently. + * Pressing this key still can be detected on macOS, though.
+ */ +@RequiredArgsConstructor +@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) +public enum Key { + + // printable keys + + // spec. symbol keys + SPACE(' '), + APOSTROPHE('\''), + COMMA(','), + MINUS('-'), + PERIOD('.'), + SLASH('/'), + SEMICOLON(';'), + EQUALS('='), + LEFT_SQUARE_BRACKET('['), + RIGHT_SQUARE_BRACKET(']'), + BACKSLASH('\\'), + GRAVE_ACCENT('`'), + /** + * This key does not have a US mapping, and has different meanings on different layouts. + */ + WORLD_1('\0'), // non-US #1 + /** + * This key does not have a US mapping, and has different meanings on different layouts. + */ + WORLD_2('\0'), // non-US #2 + + // digit keys + KEY_0('0'), + KEY_1('1'), + KEY_2('2'), + KEY_3('3'), + KEY_4('4'), + KEY_5('5'), + KEY_6('6'), + KEY_7('7'), + KEY_8('8'), + KEY_9('9'), + + // letter keys + A('A'), + B('B'), + C('C'), + D('D'), + E('E'), + F('F'), + G('G'), + H('H'), + I('I'), + J('J'), + K('K'), + L('L'), + M('M'), + N('N'), + O('O'), + P('P'), + Q('Q'), + R('R'), + S('S'), + T('T'), + U('U'), + V('V'), + W('W'), + X('X'), + Y('Y'), + Z('Z'), + + // function keys + + ESCAPE, + ENTER, + TAB('\t', true), + BACKSPACE, + INSERT, + DELETE, + // arrow keys + RIGHT, LEFT, UP, DOWN, + // navigation keys + PAGE_UP, PAGE_DOWN, HOME, END, + // ... Lock keys + CAPS_LOCK, SCROLL_LOCK, NUM_LOCK, + PRINT_SCREEN, + PAUSE, + // F... keys + F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, F25, + // Numpad keys, these are function keys according to GLFW + NUMPAD_0('0', true), + NUMPAD_1('1', true), + NUMPAD_2('2', true), + NUMPAD_3('3', true), + NUMPAD_4('4', true), + NUMPAD_5('5', true), + NUMPAD_6('6', true), + NUMPAD_7('7', true), + NUMPAD_8('8', true), + NUMPAD_9('9', true), + NUMPAD_DECIMAL_POINT('.', true), + NUMPAD_DIVIDE('/', true), + NUMPAD_MULTIPLY('*', true), + NUMPAD_SUBTRACT('-', true), + NUMPAD_ADD('+', true), + NUMPAD_ENTER, + NUMPAD_EQUALS('=', true), + + // modifier keys + LEFT_SHIFT, RIGHT_SHIFT, + LEFT_CONTROL, RIGHT_CONTROL, + // AKA Option key on Mac + LEFT_ALT, RIGHT_ALT, + // AKA Windows key on Windows, Super key on Linux, Command key on Mac + LEFT_META, RIGHT_META, + + /** + * The menu (AKA Context menu or Application (on Windows)) key. Typically not present on Mac. + */ + MENU; + + /** + * Constructor for non-function keys with US mapping. + * @param character the character + */ + Key(char character) { + this(character, false); + } + + /** + * Constructor for function keys without US mapping. + */ + Key() { + this('\0', true); + } + + /** + * The character, is equal to {@code 0} if this key does not have a US mapping + */ + char character; + /** + * {@code true} if this key is a function key, {@code false} if this key is a printable key. + */ + @Getter + boolean functionKey; + + /** + * Returns the US mapping for this key, if any, else throws an exception. Most printable keys + * have a US mapping, but not all of them; most function keys do not have a US mapping, but not all of them. + * @return the US mapping for this key, if any + * @throws IllegalStateException if there is no US mapping for the given key + */ + public char getUSMapping() { + if (character == 0) { + throw new IllegalStateException("Key " + name() + " does not have a US mapping."); + } + return character; + } + + /** + * Returns whether this key has a US mapping character. In other words, {@code true} + * if {@link #getUSMapping()} would return a value, or {@code false} if it would throw an + * exception. + * @return {@code true} if this key has a US mapping, {@code false} otherwise + */ + public boolean hasUSMapping() { + return character != 0; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/input/KeyboardEvent.java b/src/main/java/ru/fokinatorr/sparkle/event/input/KeyboardEvent.java new file mode 100644 index 0000000..0905233 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/input/KeyboardEvent.java @@ -0,0 +1,223 @@ +package ru.fokinatorr.sparkle.event.input; + +import lombok.NonNull; +import lombok.experimental.NonFinal; +import ru.fokinatorr.sparkle.stage.Stage; + +import java.util.Locale; +import java.util.Objects; + +/** + * Base interface for events representing a keyboard event. + *

Note for Scratchers: This event is similar to the "when [ v] key pressed" in Scratch. Unfortunately, + * there is no universal event type for every single key. See the JavaDoc of the subinterfaces & implementations + * to see which event type you need. + */ +public sealed interface KeyboardEvent extends InputEvent + permits KeyboardEvent.KeyEvent, + KeyboardEvent.CharInputEvent { + + /** + * Returns the stage on which the event was done. + * @return {@inheritDoc} + */ + @Override + Stage stage(); + + /** + * Base interface for events representing a physical key input. This event can be used + * to detect function keys. + *

Important note: This interface should NOT be used to input a character since physical + * keys can not be mapped 1:1 to characters. The character value depends on the keyboard layout, + * modifier keys held, etc. Most function keys do not even have a character representation. Use + * {@link KeyboardEvent.CharInputEvent CharInputEvent} for that purpose. + */ + non-sealed interface KeyEvent extends KeyboardEvent { + // Modifier bits + /** + * If this bit is set in modifiers, one or more Shift keys were held down. + */ + int MOD_SHIFT = 0x1; + /** + * If this bit is set in modifiers, one or more Control keys were held down. + */ + int MOD_CONTROL = 0x2; + /** + * If this bit is set in modifiers, one or more Alt (AKA Option on Mac) keys were held down. + */ + int MOD_ALT = 0x4; + /** + * If this bit is set in modifiers, one or more Meta (AKA Windows on Windows, Super on Linux, Command on Mac) + * keys were held down. + */ + int MOD_META = 0x8; + /** + * If this bit is set in modifiers, the Caps Lock key is enabled. + */ + int MOD_CAPS_LOCK = 0x10; + /** + * If this bit is set in modifiers, the Num Lock key is enabled. + */ + int MOD_NUM_LOCK = 0x20; + + /** + * Returns the physical key this event is associated with. + * @return the key + */ + Key key(); + + /** + * Returns the bitfield describing which modifier keys were held down. + *

Example of checking if a modifier was present: + *

+         *     // ...
+         *     int mod = event.modifiers();
+         *     if ((mod & KeyEvent.MOD_SHIFT) != 0) {
+         *         // do something if the Shift key was down
+         *     }
+         *     if ((mod & KeyEvent.MOD_NUM_LOCK) != 0) {
+         *         // do something if Num Lock was enabled
+         *     }
+         *     if ((mod & KeyEvent.MOD_ALT) == KeyEvent.MOD_ALT) {
+         *         // do something if ONLY the Alt/Option key was down
+         *     }
+         *     // ...
+         * 
+ * @return the modifier keys that were held/enabled + * @see #MOD_SHIFT + * @see #MOD_CONTROL + * @see #MOD_ALT + * @see #MOD_META + * @see #MOD_CAPS_LOCK + * @see #MOD_NUM_LOCK + */ + int modifiers(); + + /** + * Returns whether one of the Shift keys was held down. + * @return whether Shift was held down + * @see Key + * @see Key#LEFT_SHIFT + * @see Key#RIGHT_SHIFT + */ + default boolean isShiftDown() { + return (modifiers() & MOD_SHIFT) != 0; + } + + /** + * Returns whether one of the Control keys was held down. + * @return whether Control was held down + * @see Key + * @see Key#LEFT_CONTROL + * @see Key#RIGHT_CONTROL + */ + default boolean isControlDown() { + return (modifiers() & MOD_CONTROL) != 0; + } + + /** + * Returns whether one of the Alt keys was held down. + * @return whether Alt was held down + * @see Key + * @see Key#LEFT_ALT + * @see Key#RIGHT_ALT + */ + default boolean isAltDown() { + return (modifiers() & MOD_ALT) != 0; + } + + /** + * Returns whether one of the Meta keys was held down. + * @return whether Meta was held down + * @see Key + * @see Key#LEFT_META + * @see Key#RIGHT_META + */ + default boolean isMetaDown() { + return (modifiers() & MOD_META) != 0; + } + + /** + * {@return whether Caps Lock was enabled} + * @see Key#CAPS_LOCK + */ + default boolean isCapsLockOn() { + return (modifiers() & MOD_CAPS_LOCK) != 0; + } + + /** + * {@return whether Num Lock was enabled} + * @see Key#NUM_LOCK + */ + default boolean isNumLockOn() { + return (modifiers() & MOD_NUM_LOCK) != 0; + } + } + + /** + * This event is fired when a key is pressed. + * @param stage the stage on which the key was pressed + * @param key the physical key that was pressed + * @param modifiers the modifier key bitfield + */ + record KeyPressedEvent(@NonNull Stage stage, @NonNull Key key, int modifiers) implements KeyEvent { + } + + /** + * This event is fired when a key is released. + * @param stage the stage on which the key was released + * @param key the physical key that was released + * @param modifiers the modifier key bitfield + */ + record KeyReleasedEvent(@NonNull Stage stage, @NonNull Key key, int modifiers) implements KeyEvent { + } + + /** + * This event is fired when a key was held long enough to be repeated. This event indicates that the + * key is still held down. + * @param stage the stage on which the key was repeated + * @param key the physical key that was repeated + * @param modifiers the modifier key bitfield + */ + record KeyRepeatedEvent(@NonNull Stage stage, @NonNull Key key, int modifiers) implements KeyEvent { + } + + /** + * This event is fired when a character is emitted because a key was pressed or some key combination was used. + * @param stage the stage on which the character was emitted + * @param codePoint the character Unicode code point, always in range between {@link Character#MIN_CODE_POINT} + * and {@link Character#MAX_CODE_POINT} (both inclusive) + */ + record CharInputEvent(@NonNull Stage stage, int codePoint) implements KeyboardEvent { + + /** + * Constructs a new {@code CharInputEvent}. + * @throws NullPointerException if the target stage is {@code null} + * @param codePoint the character Unicode code point; must be between {@link Character#MIN_CODE_POINT} + * and {@link Character#MAX_CODE_POINT} (both inclusive) + * @throws IllegalArgumentException if the provided code point is not in the valid range + */ + public CharInputEvent { + Objects.requireNonNull(stage, "target stage"); + // Character.isValidCodePoint(int) is an optimized version of: + // codePoint >= MIN_CODE_POINT && codePoint <= MAX_CODE_POINT + if (!Character.isValidCodePoint(codePoint)) { + throw new IllegalArgumentException( + "Invalid Unicode code point: U+" + Integer.toHexString(codePoint).toUpperCase(Locale.ENGLISH) + ); + } + } + + /** + * Returns the character representation of the stored {@link #codePoint() Unicode code point}. + * For code points within the Basic Multilingual Plane (BMP), i.e. characters within the range + * {@code [U+0000; U+FFFF]}, there will be a single character in the returned string's char array. + * For code points outside the BMP, there will be a surrogate character pair in the returned string's char array. + * @return the {@link String} representation of the stored code point + */ + @SuppressWarnings("SpellCheckingInspection") + public String character() { + return Character.toString(codePoint); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/input/MouseButton.java b/src/main/java/ru/fokinatorr/sparkle/event/input/MouseButton.java new file mode 100644 index 0000000..8fc5673 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/input/MouseButton.java @@ -0,0 +1,25 @@ +package ru.fokinatorr.sparkle.event.input; + +/** + * Represents a mouse button. + */ +public enum MouseButton { + /** + * The left (button 1) mouse button. + */ + LEFT, + /** + * The middle (button 3, usually the wheel) mouse button. + */ + MIDDLE, + /** + * The right (button 2) mouse button. + */ + RIGHT, + + BUTTON_4, + BUTTON_5, + BUTTON_6, + BUTTON_7, + BUTTON_8 +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/input/MouseEvent.java b/src/main/java/ru/fokinatorr/sparkle/event/input/MouseEvent.java new file mode 100644 index 0000000..56c09f0 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/input/MouseEvent.java @@ -0,0 +1,256 @@ +package ru.fokinatorr.sparkle.event.input; + +import lombok.NonNull; +import ru.fokinatorr.sparkle.phys2d.Point2D; +import ru.fokinatorr.sparkle.stage.Stage; + +import java.util.Collections; +import java.util.EnumSet; +import java.util.Objects; +import java.util.Set; + +/** + * Base interface for events representing a mouse/cursor user input. + */ +public sealed interface MouseEvent extends InputEvent + permits MouseEvent.MouseButtonEvent, MouseEvent.MouseCursorMovedEvent, MouseEvent.MouseScrolledEvent { + + /** + * Returns the stage on which the event was done. + * @return {@inheritDoc} + */ + @Override + Stage stage(); + + /** + * Returns the X coordinate on the stage where this event was performed. + * @return the X coordinate + */ + double x(); + + /** + * Returns the Y coordinate on the stage where this event was performed. + * @return the Y coordinate + */ + double y(); + + /** + * Returns the position on the stage where this event was performed. + * @return the position + */ + default Point2D position() { + return new Point2D(x(), y()); + } + + /** + * Base interface for events representing a mouse button state (pressed/released) change. + */ + non-sealed interface MouseButtonEvent extends MouseEvent { + /** + * Returns the mouse button which this event is related to. + * @return the mouse button + */ + MouseButton button(); + + /** + * Determines whether the mouse button was pressed at the moment when this event was fired. + * @return {@code true} if the button is pressed, {@code false} otherwise + */ + boolean isPressed(); + } + + // Generic events + + /** + * This event is fired when a mouse button was pressed on a stage. + * @param button the mouse button that was pressed + * @param stage the stage on which the mouse button was pressed + * @param x the X coordinate of the cursor when the mouse button was pressed + * @param y the Y coordinate of the cursor when the mouse button was pressed + */ + record MousePressedEvent(@NonNull MouseButton button, @NonNull Stage stage, double x, double y) implements MouseButtonEvent { + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean isPressed() { + return true; + } + } + + /** + * This event is fired when a mouse button was released on a stage. + * @param button the mouse button that was released + * @param stage the stage on which the mouse button was released + * @param x the X coordinate of the cursor when the mouse button was released + * @param y the Y coordinate of the cursor when the mouse button was released + */ + record MouseReleasedEvent(@NonNull MouseButton button, @NonNull Stage stage, double x, double y) implements MouseButtonEvent { + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean isPressed() { + return false; + } + } + + /** + * This event is fired when mouse cursor was moved on a stage. + * @param stage the stage on which the cursor was moved + * @param oldX the old X coordinate of the cursor + * @param oldY the old Y coordinate of the cursor + * @param newX the new X coordinate of the cursor + * @param newY the new Y coordinate of the cursor + * @param pressedButtons the buttons that were pressed when the cursor was moved (immutable) + */ + record MouseCursorMovedEvent( + Stage stage, + double oldX, double oldY, + double newX, double newY, + Set pressedButtons + ) implements MouseEvent { + + /** + * Constructs a new {@code MouseCursorMovedEvent}. + * @throws NullPointerException if any argument is {@code null}, or if {@code pressedButtons} contains {@code null}s + */ + public MouseCursorMovedEvent { + Objects.requireNonNull(stage, "stage"); + Objects.requireNonNull(pressedButtons, "pressed buttons"); + // null elements not allowed in an EnumSet + pressedButtons = Collections.unmodifiableSet(EnumSet.copyOf(pressedButtons)); + } + + /** + * Constructs a new {@code MouseCursorMovedEvent}. + * @param stage the stage on which the mouse was moved + * @param oldX the old X coordinate of the mouse + * @param oldY the old Y coordinate of the mouse + * @param newX the new X coordinate of the mouse + * @param newY the new Y coordinate of the mouse + * @param pressedButtons the buttons that were pressed when the mouse was moved + * @throws NullPointerException if any argument is {@code null}, or if {@code pressedButtons} contains {@code null}s + */ + public MouseCursorMovedEvent(Stage stage, double oldX, double oldY, double newX, double newY, MouseButton... pressedButtons) { + this(stage, oldX, oldY, newX, newY, + // implicit null element check + Objects.requireNonNull(pressedButtons, "pressed buttons").length == 0 + ? EnumSet.noneOf(MouseButton.class) + : EnumSet.of(pressedButtons[0], pressedButtons) + ); + } + + /** + * {@inheritDoc} For this event, it's equal to the new X coordinate. + * @return {@inheritDoc} + */ + @Override + public double x() { + return newX; + } + + /** + * {@inheritDoc} For this event, it's equal to the new Y coordinate. + * @return {@inheritDoc} + */ + @Override + public double y() { + return newY; + } + + /** + * Returns the difference between the new and the old X coordinate of the mouse. + * @return delta movement along the X axis + */ + public double deltaX() { + return newX - oldX; + } + + /** + * Returns the difference between the new and the old Y coordinate of the mouse. + * @return delta movement along the Y axis + */ + public double deltaY() { + return newY - oldY; + } + + /** + * Returns the old position of the mouse. + * @return the old position + */ + public Point2D oldPosition() { + return new Point2D(oldX, oldY); + } + + /** + * Returns the new position of the mouse. + * @return the new position + */ + public Point2D newPosition() { + return new Point2D(newX, newY); + } + + @Override + public Point2D position() { + return newPosition(); + } + + /** + * Returns the delta movement vector from the old position to the new one. + * @return the delta movement vector + * @see #deltaX() + * @see #deltaY() + */ + public Point2D deltaMovement() { + return new Point2D(deltaX(), deltaY()); + } + } + + /** + * This event a fired when one of the mouse wheels were scrolled on a stage. + *

Typically older mice have only a vertical scroll wheel; some modern mice have an additional horizontal one. + * @param stage the stage on which the mouse was scrolled + * @param x the X coordinate of the mouse cursor + * @param y the Y coordinate of the mouse cursor + * @param dx the horizontal scroll delta + * @param dy the vertical scroll delta + */ + record MouseScrolledEvent( + @NonNull Stage stage, + double x, double y, + double dx, double dy + ) implements MouseEvent { + + /** + * Returns a vector representing total scroll delta. + * @return the delta scroll in each direction + */ + public Point2D deltaScroll() { + return new Point2D(dx, dy); + } + } + + // Composite events + + /** + * This event is fired when a mouse button was clicked on a stage, i.e. pressed and quickly released. + * @param button the mouse button that was clicked + * @param stage the stage on which the mouse button was clicked + * @param x the X coordinate on which the mouse button was clicked + * @param y the Y coordinate on which the mouse button was clicked + */ + record MouseClickedEvent(@NonNull MouseButton button, @NonNull Stage stage, double x, double y) implements MouseButtonEvent { + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean isPressed() { + return false; + } + + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/lifecycle/StageStateChangeEvent.java b/src/main/java/ru/fokinatorr/sparkle/event/lifecycle/StageStateChangeEvent.java new file mode 100644 index 0000000..ff1d64c --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/lifecycle/StageStateChangeEvent.java @@ -0,0 +1,100 @@ +package ru.fokinatorr.sparkle.event.lifecycle; + +import lombok.Value; +import ru.fokinatorr.sparkle.event.Event; +import ru.fokinatorr.sparkle.stage.Stage; + +/** + * Base interface for events that are fired when a stage's state is changed. + */ +public sealed interface StageStateChangeEvent extends Event + permits StageStateChangeEvent.StartEvent, + StageStateChangeEvent.StopEvent { + + /** + * Returns the state which is set within a stage before this event is fired. + * + * @return the state + */ + Stage.State getState(); + + /** + * Returns the stage whose state was changed. + * + * @return the stage + */ + Stage getStage(); + + /** + * This event is fired when the start button is clicked. + *

Note for Scratchers: This event is similar to "when green flag clicked" event in Scratch. + */ + @Value + class StartEvent implements StageStateChangeEvent { + Stage stage; + + /** + * @param stage the stage on which the start button was clicked + */ + StartEvent(Stage stage) { + this.stage = stage; + } + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + public Stage.State getState() { + return Stage.State.RUNNING; + } + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + public Stage getStage() { + return stage; + } + + } + + // There is no event for pause button; it just calls DebugUtils.debugSuspend() + + /** + * This event is fired when the stop button is clicked, or + */ + @Value + class StopEvent implements StageStateChangeEvent { + Stage stage; + + /** + * @param stage the stage on which the stop button is clicked + */ + StopEvent(Stage stage) { + this.stage = stage; + } + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + public Stage.State getState() { + return Stage.State.STOPPING; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public Stage getStage() { + return stage; + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/event/lifecycle/TickEvent.java b/src/main/java/ru/fokinatorr/sparkle/event/lifecycle/TickEvent.java new file mode 100644 index 0000000..7813d5f --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/event/lifecycle/TickEvent.java @@ -0,0 +1,45 @@ +package ru.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 static lombok.AccessLevel.NONE; + +/** + * This event is fired every stage loop tick, up to {@link Stage#getFPSLimit()} times per second. + *

If one of this event instances gets cancelled, the loop will be stopped and a {@link StageStateChangeEvent.StopEvent} will be fired. + *

Note for Scratchers: This event is similar to the "forever" block in Scratch, and you should use it instead of + * {@code while (true) {...}} loops without {@code break} statements for code that must run every cycle. + */ +@Value +@EqualsAndHashCode(callSuper = true) +@AllArgsConstructor(access = NONE) +@RequiredArgsConstructor +public class TickEvent extends AbstractCancellableEvent { + + static { + SharedSecrets.setEventLifecycleAccess(new EventLifecycleAccess() { + @Override + public StageStateChangeEvent.StartEvent newStartEvent(Stage stage) { + return new StageStateChangeEvent.StartEvent(stage); + } + + @Override + public StageStateChangeEvent.StopEvent newStopEvent(Stage stage) { + return new StageStateChangeEvent.StopEvent(stage); + } + }); + } + + /** + * The stage being ticked. + */ + Stage stage; + /** + * The time between the current and the previous tick in milliseconds. + */ + double deltaTime; +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/ARGB.java b/src/main/java/ru/fokinatorr/sparkle/graphics/ARGB.java new file mode 100644 index 0000000..9340c82 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/ARGB.java @@ -0,0 +1,296 @@ +package ru.fokinatorr.sparkle.graphics; + +import lombok.experimental.UtilityClass; + +/** + * Utility methods that help treating an {@code int} value as a ARGB-format color. + *

+ * ARGB stands for Alpha (opacity), + * Red, + * Green, + * Blue. + * Each of these properties are called color components + * or channels. Each component takes up 8 bits of the number, which means they range between 0 and 255 inclusive, and the + * resulting component values in blending methods are clamped between that range. + *

+ * The bits of an {@code int} value are treated as follows, assuming bit {@code 0} is + * the most significant bit, and bit {@code 31} is the least significant bit: + *

    + *
  • bits from {@code 0} to {@code 7} representing alpha value,
  • + *
  • bits from {@code 8} to {@code 15} representing red value,
  • + *
  • bits from {@code 16} to {@code 23} representing green value,
  • + *
  • bits from {@code 24} to {@code 31} representing blue value.
  • + *
+ * + *

Note for Scratchers: Subtractive and multiplicative blendings have 2 different variations: layered ({@code rgbXxx()}) + * and true ({@code blendXxx()}). Layered variants always use additive blending for alpha channels - similarly to what Scratch does when + * half-transparent sprites overlap. True variants use the same blending for all channels, which is what most modern software (including image + * editors) do. Be careful with true blendings; for example, using {@link #blendSubtract(int, int) true subtractive blending} on two opaque colors will + * result in a fully transparent color! + */ +@UtilityClass +public class ARGB { + + // Getting the color values + + /** + * Returns the alpha value of the given color (unsigned). + * + * @param color the color + * @return the alpha value + */ + public byte alpha(int color) { + return (byte) (color >>> 24); + } + + /** + * Returns the red value of the given color (unsigned). + * + * @param color the color + * @return the red value + */ + public byte red(int color) { + return (byte) (color >>> 16 & 0xFF); + } + + /** + * Returns the green value of the given color (unsigned). + * + * @param color the color + * @return the green value + */ + public byte green(int color) { + return (byte) (color >>> 8 & 0xFF); + } + + /** + * Returns the blue value of the given color (unsigned). + * + * @param color the color + * @return the blue value + */ + public byte blue(int color) { + return (byte) (color & 0xFF); + } + + // Setting color values + + /** + * Sets the alpha value for the given color. + * + * @param color the color + * @param alpha the new alpha value + * @return the new color + */ + public int alpha(int color, byte alpha) { + return color & 0x00FFFFFF | (alpha & 0xFF) << 24; + } + + /** + * Sets the red value for the given color. + * + * @param color the color + * @param red the new red value + * @return the new color + */ + public int red(int color, byte red) { + return color & 0xFF00FFFF | (red & 0xFF) << 16; + } + + /** + * Sets the green value for the given color. + * + * @param color the color + * @param green the new green value + * @return the new color + */ + public int green(int color, byte green) { + return color & 0xFFFF00FF | (green & 0xFF) << 8; + } + + /** + * Sets the blue value for the given color. + * + * @param color the color + * @param blue the new blue value + * @return the new color + */ + public int blue(int color, byte blue) { + return color & 0xFFFFFF00 | blue & 0xFF; + } + + // Construction + + /** + * Creates a new color with the given values. + * + * @param alpha the alpha value + * @param red the red value + * @param green the green value + * @param blue the blue value + * @return a new color + */ + public int color(byte alpha, byte red, byte green, byte blue) { + return (alpha & 0xFF) << 24 | (red & 0xFF) << 16 | (green & 0xFF) << 8 | blue & 0xFF; + } + + /** + * Creates a new, fully opaque color with the given values. + * + * @param red the red value + * @param green the green value + * @param blue the blue value + * @return a new color + */ + public int opaqueColor(byte red, byte green, byte blue) { + return 0xFF000000 | (red & 0xFF) << 16 | (green & 0xFF) << 8 | blue & 0xFF; + } + + /** + * Creates a new, fully transparent color with the given values. No matter which values were passed, + * the color will not be visible until its alpha value becomes greater than {@code 0}. + * + * @param red the red value + * @param green the green value + * @param blue the blue value + * @return a new color + */ + public int transparentColor(byte red, byte green, byte blue) { + return /* 0x00000000 | */(red & 0xFF) << 16 | (green & 0xFF) << 8 | blue & 0xFF; + } + + // Blending + + /** + * Sums the given two colors' components. The layered additive blending and true additive blending + * do the same thing, so this method is responsible for both of these blending variants. + * + * @param color1 the first color + * @param color2 the second color + * @return the additive blending of the given colors + */ + public int add(int color1, int color2) { + // @formatter:off + byte alpha1 = alpha(color1), alpha2 = alpha(color2), + red1 = red(color1), red2 = red(color2), + green1 = green(color1), green2 = green(color2), + blue1 = blue(color1), blue2 = blue(color2); + + return Math.min(255, Byte.toUnsignedInt(alpha1) + Byte.toUnsignedInt(alpha2)) << 24 + | Math.min(255, Byte.toUnsignedInt(red1) + Byte.toUnsignedInt(red2)) << 16 + | Math.min(255, Byte.toUnsignedInt(green1) + Byte.toUnsignedInt(green2)) << 8 + | Math.min(255, Byte.toUnsignedInt(blue1) + Byte.toUnsignedInt(blue2)); + // @formatter:on + } + + /** + * Subtracts the second color's RGB components from the first color's RGB components. The alpha channels get summed instead, + * resulting in a layered blending. + * + * @param color1 the first color + * @param color2 the second color + * @return the layered subtractive blending of the given colors + */ + public int rgbSubtract(int color1, int color2) { + // @formatter:off + byte alpha1 = alpha(color1), alpha2 = alpha(color2), + red1 = red(color1), red2 = red(color2), + green1 = green(color1), green2 = green(color2), + blue1 = blue(color1), blue2 = blue(color2); + + return Math.min(255, Byte.toUnsignedInt(alpha1) + Byte.toUnsignedInt(alpha2)) << 24 + | Math.max(0, Byte.toUnsignedInt(red1) - Byte.toUnsignedInt(red2)) << 16 + | Math.max(0, Byte.toUnsignedInt(green1) - Byte.toUnsignedInt(green2)) << 8 + | Math.max(0, Byte.toUnsignedInt(blue1) - Byte.toUnsignedInt(blue2)); + // @formatter:on + } + + /** + * Subtracts the second color's components from the first color's components. The alpha channels also get subtracted, + * resulting in a true blending. + * + * @param color1 the first color + * @param color2 the second color + * @return the true subtractive blending of the given colors + */ + public int blendSubtract(int color1, int color2) { + // @formatter:off + byte alpha1 = alpha(color1), alpha2 = alpha(color2), + red1 = red(color1), red2 = red(color2), + green1 = green(color1), green2 = green(color2), + blue1 = blue(color1), blue2 = blue(color2); + + return Math.min(255, Byte.toUnsignedInt(alpha1) - Byte.toUnsignedInt(alpha2)) << 24 + | Math.max(0, Byte.toUnsignedInt(red1) - Byte.toUnsignedInt(red2)) << 16 + | Math.max(0, Byte.toUnsignedInt(green1) - Byte.toUnsignedInt(green2)) << 8 + | Math.max(0, Byte.toUnsignedInt(blue1) - Byte.toUnsignedInt(blue2)); + // @formatter:on + } + + /** + * Multiplies the given two colors' RGB components. The alpha channels get summed instead, + * resulting in a layered blending. + * + * @param color1 the first color + * @param color2 the second color + * @return the layered multiplicative blending of the given colors + */ + public int rgbMultiply(int color1, int color2) { + // @formatter:off + byte alpha1 = alpha(color1), alpha2 = alpha(color2), + red1 = red(color1), red2 = red(color2), + green1 = green(color1), green2 = green(color2), + blue1 = blue(color1), blue2 = blue(color2); + + return Math.min(255, Byte.toUnsignedInt(alpha1) + Byte.toUnsignedInt(alpha2) ) << 24 + | ( Byte.toUnsignedInt(red1) * Byte.toUnsignedInt(red2) + 127) / 255 << 16 + | ( Byte.toUnsignedInt(green1) * Byte.toUnsignedInt(green2) + 127) / 255 << 8 + | ( Byte.toUnsignedInt(blue1) * Byte.toUnsignedInt(blue2) + 127) / 255; + // @formatter:on + } + + /** + * Multiplies the given two colors' components. The alpha channels also get multiplied, + * resulting in a true blending. + * + * @param color1 the first color + * @param color2 the second color + * @return the true multiplicative blending of the given colors + */ + public int blendMultiply(int color1, int color2) { + // @formatter:off + byte alpha1 = alpha(color1), alpha2 = alpha(color2), + red1 = red(color1), red2 = red(color2), + green1 = green(color1), green2 = green(color2), + blue1 = blue(color1), blue2 = blue(color2); + + return (Byte.toUnsignedInt(alpha1) * Byte.toUnsignedInt(alpha2) + 127) / 255 << 24 + | (Byte.toUnsignedInt(red1) * Byte.toUnsignedInt(red2) + 127) / 255 << 16 + | (Byte.toUnsignedInt(green1) * Byte.toUnsignedInt(green2) + 127) / 255 << 8 + | (Byte.toUnsignedInt(blue1) * Byte.toUnsignedInt(blue2) + 127) / 255; + // @formatter:on + } + + // Misc + + /** + * Turns the given color into its fully opaque version. + * + * @param color the color + * @return the new, fully opaque color + */ + public int opaque(int color) { + return color | 0xFF000000; + } + + /** + * Turns the given color into its fully transparent version. The color will not be visible until its alpha + * value becomes more than {@code 0}. + * + * @param color the color + * @return the new, fully transparent color + */ + public int transparent(int color) { + return color & 0x00FFFFFF; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/BlendMode.java b/src/main/java/ru/fokinatorr/sparkle/graphics/BlendMode.java new file mode 100644 index 0000000..2b03692 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/BlendMode.java @@ -0,0 +1,83 @@ +package ru.fokinatorr.sparkle.graphics; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; + +import java.util.function.IntBinaryOperator; + +import static lombok.AccessLevel.PRIVATE; + +/** + * Enum representing different blending strategies for combining source and destination pixels. + * Each blend mode uses a specific mathematical operation to compute the resulting color. + */ +@RequiredArgsConstructor +@FieldDefaults(makeFinal = true, level = PRIVATE) +public enum BlendMode { + /** + * Sums the colors' components. + * Suitable for glow and lighting effects. + * @see ARGB#add(int, int) + */ + ADD(ARGB::add, BlendType.ARGB), + /** + * Subtracts the colors' components. + * Produces inverted, transparent results. + * @see ARGB#blendSubtract(int, int) + */ + BLEND_SUBTRACT(ARGB::blendSubtract, BlendType.ARGB), + /** + * Subtracts RGB color channels, summing alpha instead. + * Produces more opaque results than {@link #BLEND_SUBTRACT}. + * @see ARGB#rgbSubtract(int, int) + */ + RGB_SUBTRACT(ARGB::rgbSubtract, BlendType.RGB), + /** + * Multiplies the colors' components. + * Produces darker results, useful for shadows and darkening effects. + * @see ARGB#blendMultiply(int, int) + */ + BLEND_MULTIPLY(ARGB::blendMultiply, BlendType.ARGB), + /** + * Multiplies RGB color channels, summing alpha instead. + * Produces more opaque results than {@link #BLEND_MULTIPLY}. + * @see ARGB#rgbMultiply(int, int) + */ + RGB_MULTIPLY(ARGB::rgbMultiply, BlendType.RGB); + + IntBinaryOperator op; + /** + * -- GETTER -- + *

+ * The blend type that determines how alpha channel is handled during blending. + * @return the blend type (ARGB or RGB) + * @see BlendType + */ + @Getter BlendType type; + + /** + * Applies this blend mode to two colors. + * + * @param color1 the source color + * @param color2 the destination color + * @return the blended color result + */ + public int apply(int color1, int color2) { + return op.applyAsInt(color1, color2); + } + + /** + * Enum representing how blending operations handle the alpha channel. + */ + public enum BlendType { + /** + * Applies the same blending operation to all channels including alpha. + */ + ARGB, + /** + * Applies blending only to RGB color channels while using additive blending for the alpha channel. + */ + RGB + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/GraphicsManager.java b/src/main/java/ru/fokinatorr/sparkle/graphics/GraphicsManager.java new file mode 100644 index 0000000..baa51db --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/GraphicsManager.java @@ -0,0 +1,137 @@ +package ru.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 java.nio.file.Path; + +/** + * Manages rendering contexts and their lifecycle. + *

Note: Do not manually close image instances returned by a graphics manager. Instead, use + * the {@link #destroyImage(Path)} method for proper cleanup. + * @see RenderingContext + */ +public interface GraphicsManager extends NonThrowingAutoCloseable { + + // Context creation & management + + /** + * Creates a new rendering context with a {@link WindowSurface} and a stage created using the given creator. + * + * @param title window title + * @param stageCreator a stage creation strategy + * @return a new rendering context and a stage bound to it + * @throws IllegalStateException if graphics manager is closed + * @throws NullPointerException if any argument is {@code null} + */ + default Pair 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. + * + * @param title window title + * @param stageCreator a stage creation strategy + * @param translucent whether the window should be transparent + * @param fullscreen whether the window should be fullscreen + * @return a new rendering context and a stage bound to it + * @throws IllegalStateException if graphics manager is closed + * @throws NullPointerException if any argument is {@code null} + */ + Pair 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. + *

To create a context with a window surface, use {@link #createWindowContext createWindowContext(...)}. + * + * @param surface the surface to render on + * @param stageCreator a stage creation strategy + * @return a new rendering context and a stage bound to it + * @throws IllegalStateException if graphics manager is closed + * @throws NullPointerException if any argument is {@code null} + */ + Pair createEmbeddedContext(EmbeddedSurface surface, StageCreator stageCreator); + + /** + * Returns an existing rendering context bound to the given stage. + * @param boundStage the bound stage + * @return the corresponding rendering context + * @throws NullPointerException if stage is {@code null} + */ + RenderingContext getContext(Stage boundStage); + + /** + * Checks whether this manager currently has any active contexts. + * @return whether there are active contexts + */ + boolean hasActiveContexts(); + + // Image loading + + /** + * Loads an image at the specified path. The image will automatically be closed with this manager. + * If an image is already loaded at the given path, it is closed, removed and replaced with a new one. + * The sprite/stage assets are loaded automatically, so there's usually no need to call this method manually. + * @param path the file path + * @param autoLoad whether to preload the image to all existing & future rendering contexts + * @return the image + * @throws IllegalStateException if graphics manager is closed + */ + Image loadImage(Path path, boolean autoLoad); + + /** + * Determines whether an image is already loaded at the given path. This can be useful + * to prevent unnecessary image reloading. + * This is always true for sprite/stage assets since they're loaded automatically. + * @param path the file path + * @return {@code true} if an image at the given path is already loaded by this manager, {@code false} + * otherwise + */ + boolean hasLoadedImage(Path path); + + /** + * Returns an image previously loaded from the given path, if any, otherwise returns {@code null}. + * + * @param path the file path + * @return the respective image or {@code null} + * @throws IllegalStateException if graphics manager is closed + */ + Image getLoadedImage(Path path); + + /** + * If an image is loaded at the given path, closes and removes it, otherwise does nothing. + * + * @param path the file path + * @throws IllegalStateException if graphics manager is closed + */ + void destroyImage(Path path); + + + // Lifecycle + + /** + * Schedules the given task to run in the graphics loop. + *

This is required for calling most {@link RenderingSurface} methods, since they can only change properties + * & render within a single thread. + * @param run the action + * @throws NullPointerException if {@code run == null} + * @throws IllegalStateException if the work queue cannot accept more tasks (optional) + */ + void runLater(Runnable run); + + /** + * Advances the graphics manager by one tick. + * This method is called regularly from the graphics loop, no need to call in manually. + * @throws IllegalStateException if graphics manager is closed + */ + void tick(); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/GraphicsUtils.java b/src/main/java/ru/fokinatorr/sparkle/graphics/GraphicsUtils.java new file mode 100644 index 0000000..9906bd4 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/GraphicsUtils.java @@ -0,0 +1,91 @@ +package ru.fokinatorr.sparkle.graphics; + +import lombok.experimental.UtilityClass; +import ru.fokinatorr.sparkle.graphics.image.Image; +import ru.fokinatorr.sparkle.graphics.render.RenderCanvas; +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.Stage; + +import javax.imageio.ImageIO; +import java.util.Objects; +import java.util.function.Supplier; + +import static ru.fokinatorr.sparkle.graphics.render.RenderCanvas.ORIGINAL_SIZE; + +/** + * Graphics-related utilities. + */ +@UtilityClass +public class GraphicsUtils { + private static final StageAccess stageAcc = SharedSecrets.getStageAccess(); + + /** + * Draws an image on the given canvas as if the origin is in the center, not in the top-left corner. + * + * @param canvas the canvas to draw on + * @param image the image to draw + * @param x the X coordinate of center + * @param y the Y coordinate of center + * @param w the preferred width + * @param h the preferred height + * @see RenderCanvas#drawImage(Image, double, double, double, double) + */ + public void drawImageOriginCenter(RenderCanvas canvas, Image image, + double x, double y, + double w, double h) { + Objects.requireNonNull(canvas, "canvas"); + Objects.requireNonNull(image, "image"); + + if (w == ORIGINAL_SIZE || h == ORIGINAL_SIZE) { + if (!image.isReady()) image.prepare(); // perform lazy loading + var reader = image.createPixelReader(); + if (w == ORIGINAL_SIZE) w = reader.getWidth(); + if (h == ORIGINAL_SIZE) h = reader.getHeight(); + } + + Point2D dim = canvas.getDimensions(); + canvas.drawImage( + image, + (dim.x() - w) / 2 + x, (dim.y() - h) / 2 - y, + w, h + ); + } + + /** + * Runs the given code, disabling redraws on the given stage. + *

Note for Scratchers: This method's functionality is similar to "run without screen refresh" in + * custom blocks, except you can use it with any code. + * + * @param stage the stage to suppress redraws for + * @param run what should be executed + */ + public void runWithoutStageRedraw(Stage stage, Runnable run) { + stageAcc.setSuppressRedraw(stage, true); + try { + run.run(); + } finally { + stageAcc.setSuppressRedraw(stage, false); + } + } + + /** + * Runs the given code, disabling redraws on the given stage, and returns the code's result. + *

Note for Scratchers: This method's functionality is similar to "run without screen refresh" in + * custom blocks, except you can use it with any code. + * + * @param stage the stage to suppress redraws for + * @param run what should be executed + * @param the type of return value + * @return the value returned by {@code run} + */ + public T getWithoutStageRedraw(Stage stage, Supplier run) { + stageAcc.setSuppressRedraw(stage, true); + try { + return run.get(); + } finally { + stageAcc.setSuppressRedraw(stage, false); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/PixelReader.java b/src/main/java/ru/fokinatorr/sparkle/graphics/PixelReader.java new file mode 100644 index 0000000..32fa810 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/PixelReader.java @@ -0,0 +1,80 @@ +package ru.fokinatorr.sparkle.graphics; + +import ru.fokinatorr.sparkle.graphics.image.Image; +import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer; +import ru.fokinatorr.sparkle.phys2d.Point2D; + +/** + * Allows reading pixel data from an image/framebuffer in ARGB format. + * @see ARGB + * @see Image#createPixelReader() + * @see Framebuffer#createPixelReader() + */ +public interface PixelReader { + /** + * Returns the color of the given point in ARGB format. + * @param x the X coordinate of the point + * @param y the Y coordinate of the point + * @return the color of the point + */ + int getARGB(int x, int y); + + /** + * 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(); + + /** + * Returns a vector representing the dimensions of underlying image data. + * @return the dimensions, both always positive + */ + default Point2D getDimensions() { + return new Point2D(getWidth(), getHeight()); + } + + /** + * Returns a horizontal line of pixels at the specified Y coordinate. + * @param y the Y coordinate + * @return all pixels at the given Y coordinate + */ + default int[] getRow(int y) { + int[] row = new int[getWidth()]; + for (int x = 0; x < getWidth(); x++) { + row[x] = getARGB(x, y); + } + return row; + } + + /** + * Returns a vertical line of pixels at the specified X coordinate. + * @param x the X coordinate + * @return all pixels at the given X coordinate + */ + default int[] getColumn(int x) { + int[] col = new int[getHeight()]; + for (int y = 0; y < getHeight(); y++) { + col[y] = getARGB(x, y); + } + return col; + } + + /** + * Returns the entire image as a 2D array using row-major order. + * @return the entire image data + */ + default int[][] getAll() { + int[][] grid = new int[getHeight()][getWidth()]; + for (int y = 0; y < getHeight(); y++) { + for (int x = 0; x < getWidth(); x++) { + grid[y][x] = getARGB(x, y); + } + } + return grid; + } +} \ No newline at end of file diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/PixelWriter.java b/src/main/java/ru/fokinatorr/sparkle/graphics/PixelWriter.java new file mode 100644 index 0000000..f4682b3 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/PixelWriter.java @@ -0,0 +1,61 @@ +package ru.fokinatorr.sparkle.graphics; + +import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer; + +import java.awt.image.BufferedImage; + +/** + * Allows modifying pixel data of an image/framebuffer in ARGB format. + * @see ARGB + * @see Framebuffer#createPixelWriter() + */ +public interface PixelWriter { + /** + * Sets a single pixel. + * @param x the X coordinate + * @param y the Y coordinate + * @param argb the ARGB color + * @throws IllegalArgumentException if x or y are out of bounds + */ + void setARGB(int x, int y, int argb); + + /** + * Fills a rectangular region with the given color. + * @param x the X of top-left corner + * @param y the Y of top-left corner + * @param w rectangle width + * @param h rectangle height + * @param argb the ARGB color + * @throws IllegalArgumentException if part of the region is out of bounds + */ + default void fillARGB(int x, int y, int w, int h, int argb) { + for (int posX = x; posX < x + h; posX++) { + for (int posY = y; posY < y + w; posY++) { + setARGB(posX, posY, argb); + } + } + } + + /** + * Copies pixel data from an array. + *

A pixel at (x, y) is read from the given source array as: + *

{@code src[off + (y - startY) * scanSize + (x - startX)]}
+ * (row-major order). + * @param src the source array (ARGB) + * @param off data offset in the source array + * @param scanSize number of pixels per row + * @param startX the starting X coordinate + * @param startY the starting Y coordinate + * @param w width of region to copy + * @param h height of region to copy + * @throws IllegalArgumentException if part of the region is out of bounds + */ + default void writePixels(int[] src, int off, int scanSize, + int startX, int startY, int w, int h) { + for (int x = startX; x < startX + h; x++) { + for (int y = startY; y < startY + w; y++) { + setARGB(x, y, src[off + (x - startX) * scanSize + (y - startY)]); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/font/FilesystemFontProvider.java b/src/main/java/ru/fokinatorr/sparkle/graphics/font/FilesystemFontProvider.java new file mode 100644 index 0000000..4710569 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/font/FilesystemFontProvider.java @@ -0,0 +1,172 @@ +package ru.fokinatorr.sparkle.graphics.font; + +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.objects.ObjectReferenceImmutablePair; +import lombok.NonNull; +import lombok.experimental.FieldDefaults; +import lombok.extern.slf4j.Slf4j; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.util.function.Predicate.not; +import static lombok.AccessLevel.PRIVATE; + +/** + * A font provider that loads fonts from a base directory, using this format for locating TTF files: + *
{@code ///.ttf}
+ * where: + *
    + *
  • + * <base_dir> is the base directory path provided in the constructor; + *
  • + *
  • + * <family> is the font family name as-is (without replacing spaces or changing case); + *
  • + *
  • + * <posture> is the font's desired posture in lowercase; + *
  • + *
  • + * <weight> is the font's desired weight in lowercase. + *
  • + *
+ */ +@Slf4j +@FieldDefaults(level = PRIVATE) +public class FilesystemFontProvider implements FontProvider { + @NonNull + final Path baseDir; + @NonNull + final String fallbackFamily; + final Map cache = new HashMap<>(); + + Set availableFamilies; + final Map> availablePostures = new HashMap<>(); + final Map, Set> availableWeights = new HashMap<>(); + + /** + * Creates a new filesystem font provider. + * @param baseDir the base directory to locate fonts in + * @param fallbackFamily the fallback font family, if one cannot be found (must exist in available families) + * @throws NullPointerException if any argument is {@code null} + * @throws IllegalArgumentException if the base path does not exist or does not represent a directory + */ + public FilesystemFontProvider(@NonNull Path baseDir, @NonNull String fallbackFamily) { + this.baseDir = Objects.requireNonNull(baseDir, "base directory"); + this.fallbackFamily = Objects.requireNonNull(fallbackFamily, "fallback family"); + if (!Files.exists(baseDir)) { + throw new IllegalArgumentException("Path does not exist: " + baseDir); + } + if (!Files.isDirectory(baseDir)) { + throw new IllegalArgumentException("Not a directory: " + baseDir); + } + } + + @Override + public Path getTTF(String family, FontWeight weight, FontPosture posture) { + return cache.computeIfAbsent(new FontParams(family, weight, posture), params -> { + Set families = availableFamilies(); + if (families.isEmpty()) { + throw new IllegalArgumentException("No font families found in " + baseDir); + } + + String actualFamily = family; + if (!families.contains(actualFamily)) actualFamily = fallbackFamily; + if (!families.contains(actualFamily)) { + throw new IllegalArgumentException("Fallback family doesn't exist: '" + fallbackFamily + "' in " + baseDir); + } + + Set postures = availablePostures(actualFamily); + if (postures.isEmpty()) { + throw new IllegalArgumentException("No font postures available for family: '" + actualFamily + "' in " + baseDir); + } + FontPosture actualPosture = posture; + if (!postures.contains(actualPosture)) actualPosture = postures.iterator().next(); // If more postures appear later, choose a closer one + + Set weights = availableWeights(actualFamily, actualPosture); + if (weights.isEmpty()) { + throw new IllegalArgumentException("No font weights available for family: '" + actualFamily + "' in " + baseDir); + } + + FontWeight actualWeight = weight; + if (!weights.contains(actualWeight)) actualWeight = actualWeight.closestOf(weights); + + 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(); + }); + } + + private Set availableFamilies() { + if (availableFamilies == null) { + try (Stream list = Files.list(baseDir)) { + availableFamilies = list.filter(Files::isDirectory) + .map(Path::getFileName) + .map(Path::toString) + .collect(Collectors.toUnmodifiableSet()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + return availableFamilies; + } + + private Set availablePostures(String family) { + return availablePostures.computeIfAbsent(family, _ -> { + try (Stream list = Files.list(baseDir.resolve(family))) { + return list.filter(Files::isDirectory) + .map(Path::getFileName) + .map(Path::toString) + .map(String::toUpperCase) + .map(name -> { + try { + return FontPosture.valueOf(name); + } catch (IllegalArgumentException _) { // no such enum constant + return null; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toUnmodifiableSet()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + } + + private Set availableWeights(String family, FontPosture posture) { + return availableWeights.computeIfAbsent(new ObjectReferenceImmutablePair<>(family, posture), _ -> { + try (Stream list = Files.list(baseDir.resolve(family).resolve(posture.name().toLowerCase()))) { + return list.filter(not(Files::isDirectory)) + .map(Path::getFileName) + .map(Path::toString) + .filter(fileName -> fileName.endsWith(".ttf")) + .map(fileName -> fileName.substring(0, fileName.lastIndexOf("."))) + .map(String::toUpperCase) + .map(name -> { + try { + return FontWeight.valueOf(name); + } catch (IllegalArgumentException _) { // no such enum constant + return null; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toUnmodifiableSet()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + } + + private record FontParams( + @NonNull String family, + @NonNull FontWeight weight, + @NonNull FontPosture posture + ) {} +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/font/Font.java b/src/main/java/ru/fokinatorr/sparkle/graphics/font/Font.java new file mode 100644 index 0000000..34f83e2 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/font/Font.java @@ -0,0 +1,187 @@ +package ru.fokinatorr.sparkle.graphics.font; + +import lombok.Builder; +import lombok.NonNull; +import lombok.Value; +import lombok.experimental.Tolerate; + +import java.util.Objects; + +/** + * Represents a font and its properties. + *

This class has a builder, see {@link FontBuilder} and {@link #builder()}. + *

Only standard fonts are supported by default; use {@link FontProvider} to associate custom + * font families to font files on disk or other locations. + *

Note for Scratchers: Default fonts are the ones used in Scratch! The fonts for Chinese, Japanese and Korean + * are not present yet, since there are actually multiple font variations for these. + * + * @see FontWeight + * @see FontPosture + * @see FontProvider + */ +@Builder(toBuilder = true) +@Value +public class Font { + @NonNull + String family; + @Builder.Default + double size = 20.0; + @NonNull + @Builder.Default + FontWeight weight = FontWeight.NORMAL; + @Builder.Default + FontPosture posture = FontPosture.NORMAL; + boolean underline; + boolean strikethrough; + + + /** + * Creates a new font. + * @param family the font's family + * @param size the font's size, in points (1 pt = ~3/4 px) + * @param weight the font's {@linkplain FontWeight weight} + * @param posture the font's {@linkplain FontPosture posture} + * @param underline whether to apply underlining to text + * @param strikethrough whether to apply strikethrough to text + * @throws NullPointerException if any argument is {@code null} + * @throws IllegalArgumentException if size is non-positive, infinite or NaN + */ + public Font(@NonNull String family, double size, + @NonNull FontWeight weight, @NonNull FontPosture posture, + boolean underline, boolean strikethrough) { + this.family = Objects.requireNonNull(family, "family"); + checkSize(size); + this.size = size; + this.weight = Objects.requireNonNull(weight, "weight"); + this.posture = Objects.requireNonNull(posture, "posture"); + this.underline = underline; + this.strikethrough = strikethrough; + } + + // Standard Scratch fonts; + // copying Scratch's font names to method names for Scratchers' convenience, but listing the actual font family in Javadoc + + /** + * Creates a font builder with "Noto Sans" family and the given size. + * + * @param size the font size + * @return a new builder + */ + public static FontBuilder sansSerif(double size) { + return new FontBuilder() + .family("Noto Sans") + .size(size); + } + + /** + * Creates a font builder with the default family and the given size. + * + * @param size the font size + * @return a new builder + */ + public static FontBuilder serif(double size) { + return new FontBuilder() + .family("") + .size(size); + } + + /** + * Creates a font builder with "Handlee" family and the given size. + * + * @param size the font size + * @return a new builder + */ + public static FontBuilder handwriting(double size) { + return new FontBuilder() + .family("Handlee") + .size(size); + } + + /** + * Creates a font builder with "Knewave" family and the given size. + * + * @param size the font size + * @return a new builder + */ + public static FontBuilder marker(double size) { + return new FontBuilder() + .family("Knewave") + .size(size); + } + + /** + * Creates a font builder with "Griffy" family and the given size. + * + * @param size the font size + * @return a new builder + */ + public static FontBuilder curly(double size) { + return new FontBuilder() + .family("Griffy") + .size(size); + } + + /** + * Creates a font builder with "Grand9K Pixel" family and the given size. + * + * @param size the font size + * @return a new builder + */ + public static FontBuilder pixel(double size) { + return new FontBuilder() + .family("Grand9K Pixel") + .size(size); + } + + /** + * A builder for conveniently creating {@link Font}s. + */ + public static class FontBuilder { + + /** + * Makes the font builder underlined. + *

This is a shortcut for {@code .underline(true)}. + * + * @return this builder + */ + @Tolerate + public FontBuilder underline() { + this.underline = true; + return this; + } + + /** + * Makes the font builder struck through. + *

This is a shortcut for {@code .strikethrough(true)}. + * + * @return this builder + */ + @Tolerate + public FontBuilder strikethrough() { + this.strikethrough = true; + return this; + } + + /** + * Sets the desired size for the resulting font. + * + * @param size the size + * @return this builder + * @throws IllegalArgumentException if size is non-positive, infinite or NaN + */ + public FontBuilder size(double size) { + checkSize(size); + size$set = true; + size$value = size; + return this; + } + + // the rest generated by Lombok + } + + private static void checkSize(double size) { + if (!(Double.isFinite(size) && size > 0)) { + throw new IllegalArgumentException("Size must be finite and positive, found: " + size); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/font/FontPosture.java b/src/main/java/ru/fokinatorr/sparkle/graphics/font/FontPosture.java new file mode 100644 index 0000000..da629fc --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/font/FontPosture.java @@ -0,0 +1,9 @@ +package ru.fokinatorr.sparkle.graphics.font; + +/** + * A font's postural style. + */ +public enum FontPosture { + NORMAL, + ITALIC +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/font/FontProvider.java b/src/main/java/ru/fokinatorr/sparkle/graphics/font/FontProvider.java new file mode 100644 index 0000000..b562b63 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/font/FontProvider.java @@ -0,0 +1,36 @@ +package ru.fokinatorr.sparkle.graphics.font; + +import ru.fokinatorr.sparkle.util.Constants; + +import java.nio.file.Path; + +/** + * Provides TrueType fonts for family, weight and posture. + */ +@FunctionalInterface +public interface FontProvider { + + /** + * Attempts to find a path to a TrueType font matching the given characteristics. + *

Implementations are free to return a fallback font if no match is found (e.g. family doesn't exist, + * no such weight or posture). + * @param family the font's preferred family + * @param weight the font's preferred weight + * @param posture the font's preferred posture + * @return the respective TTF file path + * @throws NullPointerException if any argument is {@code null} (optional) + */ + Path getTTF(String family, FontWeight weight, FontPosture posture); + + /** + * Returns a {@code FontProvider} that loads default fonts from this framework's /assets/fonts + * directory. + * @return a new default font provider + */ + static FontProvider defaultProvider() { + return new FilesystemFontProvider( + Constants.ROOT.resolve("assets/fonts"), + "Noto Sans" + ); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/font/FontWeight.java b/src/main/java/ru/fokinatorr/sparkle/graphics/font/FontWeight.java new file mode 100644 index 0000000..496abce --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/font/FontWeight.java @@ -0,0 +1,113 @@ +package ru.fokinatorr.sparkle.graphics.font; + +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; + +import java.util.Collection; + +import static lombok.AccessLevel.PRIVATE; + +/** + * A font's weight (thickness). + *

Note: most fonts don't support all weights; most widely supported weight values are {@link #NORMAL} and {@link #BOLD}. + */ +@FieldDefaults(makeFinal = true, level = PRIVATE) +@Getter +@RequiredArgsConstructor +public enum FontWeight { + THIN(1), + EXTRA_LIGHT(2), + LIGHT(3), + NORMAL(4), + MEDIUM(5), + SEMI_BOLD(6), + BOLD(7), + EXTRA_BOLD(8), + BLACK(9); + + /** + * The lightest font weight. + */ + public static final FontWeight MIN_VALUE = THIN; + /** + * The boldest font weight. + */ + public static final FontWeight MAX_VALUE = BLACK; + + /** + * The weight's scalar value. + *

This is used to choose the closest supported weight. + */ + int value; + + /** + * Returns a font weight that is bolder than this weight by one. + * @return a bolder font weight + */ + public FontWeight bolder() { + return this == MAX_VALUE ? this : ValueOfMapHolder.MAP.get(value + 1); + } + + /** + * Returns a font weight that is lighter than this weight by one. + * @return a lighter font weight + */ + public FontWeight lighter() { + return this == MIN_VALUE ? this : ValueOfMapHolder.MAP.get(value - 1); + } + + /** + * Returns the closest weight to this one from the specified collection. + *

If two weights are found at the same distance from this one, the lighter one is returned. + * @param weights the possible candidates + * @return the closest of them to this one + * @throws IllegalArgumentException if the collection is empty + */ + public FontWeight closestOf(Collection weights) { + if (weights.contains(this)) { + return this; + } + for ( + FontWeight lighter = this, bolder = this; + !(lighter == MIN_VALUE || bolder == MAX_VALUE); + lighter = lighter.lighter(), bolder = bolder.bolder() + ) { + if (weights.contains(lighter)) return lighter; + if (weights.contains(bolder)) return bolder; + } + throw new IllegalArgumentException("No available weights"); + } + + /** + * Returns a font weight with the given scalar value. + * @param value the weight value + * @return the respective font weight + * @throws IllegalArgumentException if no such font weight exists + */ + public static FontWeight valueOf(int value) { + Int2ObjectMap m = ValueOfMapHolder.MAP; + if (!m.containsKey(value)) { + throw new IllegalArgumentException("No weight with value " + value); + } + return m.get(value); + } + + /** + * Lazy holder for the scalar value to instance map. + */ + private static class ValueOfMapHolder { + static final Int2ObjectMap MAP; + + static { + Int2ObjectMap m = new Int2ObjectOpenHashMap<>(); + for (FontWeight wt : values()) { + m.put(wt.value, wt); + } + MAP = Int2ObjectMaps.unmodifiable(m); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/image/Image.java b/src/main/java/ru/fokinatorr/sparkle/graphics/image/Image.java new file mode 100644 index 0000000..039f2ea --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/image/Image.java @@ -0,0 +1,96 @@ +package ru.fokinatorr.sparkle.graphics.image; + +import ru.fokinatorr.sparkle.graphics.PixelReader; +import ru.fokinatorr.sparkle.graphics.render.RenderCanvas; +import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable; + +/** + * An image that can be rendered on a canvas. + *

+ * This interface abstracts over various image formats (raster, vector, procedural) + * and enables uniform handling across rendering pipelines. Implementations may represent: + *

    + *
  • Raster images (PNG, JPEG)
  • + *
  • Vector graphics (SVG)
  • + *
  • Dynamic/procedural textures
  • + *
  • Animation frames
  • + *
+ * + *

Resource Management

+ * Images may hold native resources (e.g. GPU textures). Callers should ensure + * {@link #prepare()} is called before drawing, and consider disposal + * if the image supports it. + *

To potentially release these resources, {@link #close()} must be called when the image + * is no longer in use. + * + *

Thread Safety

+ * 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 SVGImage + * @see AnimatedImage + */ +public interface Image extends NonThrowingAutoCloseable { + + /** + * Prepares the image for rendering. + *

+ * This may involve: + *

    + *
  • Lazy decoding of compressed data
  • + *
  • Rasterization of vector content
  • + *
  • Creating internal rendering structures
  • + *
+ *

+ * Idempotent: calling multiple times has no additional effect. + * + * @throws NullPointerException if context is {@code null} + */ + void prepare(); + + /** + * Checks whether this image is ready to be drawn. + *

+ * Returns {@code false} only if: + *

    + *
  • The image is still loading asynchronously
  • + *
  • Required resources failed to load
  • + *
  • {@link #prepare()} hasn't been called yet
  • + *
+ * + * @return true if safe to pass to {@link RenderCanvas#drawImage RenderCanvas.drawImage()} + */ + boolean isReady(); + + /** + * Returns a pixel reader that can read this image's contents as pixels. + * The image must be {@link #prepare() prepared} before calling this method. + * + * @return an object that reads this image by pixels + * @see #isReady() + * @see #prepare() + */ + PixelReader createPixelReader(); + + /** + * Optional hint about the MIME type of this image. + *

+ * Examples: {@code "image/png"}, {@code "image/svg+xml"} + *

+ * 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; + } + + /** + * {@inheritDoc} + * The image can not be used after calling this method. + * Calling this method more than once does not have any effect. + */ + @Override + void close(); +} \ No newline at end of file diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/image/RasterImage.java b/src/main/java/ru/fokinatorr/sparkle/graphics/image/RasterImage.java new file mode 100644 index 0000000..9e45ba0 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/image/RasterImage.java @@ -0,0 +1,111 @@ +package ru.fokinatorr.sparkle.graphics.image; + +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 javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; + +/** + * A raster image is an image consisting of pixels (e.g. PNG, JPEG). The pixels + * are stored in ARGB format. + * @see ARGB + */ +@FieldDefaults(level = AccessLevel.PRIVATE) +@RequiredArgsConstructor +public class RasterImage implements Image { + /** + * Location of the image data. + */ + @NonNull final URL resource; + volatile BufferedImage decoded; + + @Override + public void prepare() { + if (decoded == null) { + try { + decoded = ImageIO.read(resource); + } catch (IOException e) { + throw new RuntimeException("Failed to decode raster image", e); + } + } + } + + @Override + public boolean isReady() { + return decoded != null; + } + + @Override + public PixelReader createPixelReader() { + prepare(); // ensure decoded in case caller forgot to prepare the image + return new Reader(decoded); + } + + @Override + public String getMimeType() { + String guessed = URLConnection.guessContentTypeFromName(resource.toString()); + return guessed == null ? "image/unknown" : guessed; + } + + @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 + decoded = null; + } + + /** + * Pixel accessor for a {@link BufferedImage}. + */ + @RequiredArgsConstructor + @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) + public static class Reader implements PixelReader { + /** + * The image to read from. + */ + BufferedImage img; + + @Override + public int getARGB(int x, int y) { + return img.getRGB(x, y); + } + + @Override + public int getWidth() { + return img.getWidth(); + } + + @Override + public int getHeight() { + return img.getHeight(); + } + + @Override + public int[] getRow(int y) { + return img.getRGB(0, y, img.getWidth(), 1, null, 0, img.getWidth()); + } + + @Override + public int[] getColumn(int x) { + return img.getRGB(x, 0, 1, img.getHeight(), null, 0, img.getWidth()); + } + + @Override + public int[][] getAll() { + int[][] result = new int[img.getHeight()][img.getWidth()]; + for (int y = 0; y < result.length; y++) { + int[] row = result[y]; + img.getRGB(0, y, img.getWidth(), 1, row, 0, img.getWidth()); + } + return result; + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/image/SVGImage.java b/src/main/java/ru/fokinatorr/sparkle/graphics/image/SVGImage.java new file mode 100644 index 0000000..9b1277d --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/image/SVGImage.java @@ -0,0 +1,120 @@ +package ru.fokinatorr.sparkle.graphics.image; + +import lombok.AccessLevel; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import org.lwjgl.nanovg.NSVGImage; +import ru.fokinatorr.sparkle.graphics.ARGB; +import ru.fokinatorr.sparkle.graphics.PixelReader; +import ru.fokinatorr.sparkle.graphics.impl.IntBufferPixelAccessor; +import ru.fokinatorr.sparkle.graphics.vector.SVGVector; + +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.ArrayList; +import java.util.List; + +import static org.lwjgl.system.MemoryUtil.*; +import static org.lwjgl.nanovg.NanoSVG.*; + +/** + * An SVG image is a vector-based format. + */ +@FieldDefaults(level = AccessLevel.PRIVATE) +@RequiredArgsConstructor +public class SVGImage implements Image { + /** + * Location of the image data. + */ + @NonNull + final URL resource; + volatile NSVGImage decoded; + volatile IntBuffer rasterized; + + @Override + public void prepare() { + if (decoded == null) { + try { + decoded = nsvgParseFromFile(resource.getPath(), "px", 96f); + rasterize(); + } 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 rasterized != null; + } + + @Override + public PixelReader createPixelReader() { + prepare(); + return new IntBufferPixelAccessor((int) decoded.width(), (int) decoded.height(), rasterized, () -> { + if (rasterized == null) { + throw new IllegalStateException("Image has not been prepared yet"); + } + }); + } + + @Override + public String getMimeType() { + return "image/svg+xml"; + } + + public List getVectors() { + prepare(); + + List vectors = new ArrayList<>(); + return vectors;//TODO + } + + @Override + public void close() { + memFree(rasterized); + rasterized = null; + nsvgDelete(decoded); + decoded = null; + } + + // Private implementation + + private void rasterize() { + long rasterizer /*pointer*/ = nsvgCreateRasterizer(); + ByteBuffer rasterizedBB = memAlloc((int) (decoded.width() * decoded.height() * Integer.BYTES)); + try { + nsvgRasterize( + rasterizer, + decoded, + 0f, 0f, + 1f, + rasterizedBB, + (int) decoded.width(), (int) decoded.height(), + (int) (decoded.width() * Integer.BYTES) + ); + } catch (Exception e) { + memFree(rasterizedBB); + throw new RuntimeException("Failed to rasterise SVG image", e); + } finally { + nnsvgDeleteRasterizer(rasterizer); + } + rasterized = rasterizedBB.asIntBuffer(); + // convert from RGBA to ARGB + for (int i = 0; i < rasterized.capacity(); i++) { + int rgba = rasterized.get(i); + int argb = ARGB.color( + (byte) (rgba & 0xFF), + (byte) (rgba >>> 24 & 0xFF), + (byte) (rgba >>> 16 & 0xFF), + (byte) (rgba >>> 8 & 0xFF) + ); + rasterized.put(i, argb); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/AbstractRenderingContext.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/AbstractRenderingContext.java new file mode 100644 index 0000000..b8d5916 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/AbstractRenderingContext.java @@ -0,0 +1,112 @@ +package ru.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 static lombok.AccessLevel.PROTECTED; +import static ru.fokinatorr.sparkle.graphics.render.RenderCanvas.ORIGINAL_SIZE; +import static ru.fokinatorr.sparkle.util.Constants.NANOS_PER_SECOND; + +/** + * Base class for rendering context implementations. + */ +@FieldDefaults(level = PROTECTED) +@RequiredArgsConstructor +public abstract class AbstractRenderingContext implements RenderingContext { + final AppContext context; + @Getter final RenderingSurface surface; + @Getter final Stage stage; + @Getter final GraphicsManager parent; + + boolean closed; + @Getter double lastFPS; + long totalRenderTimeNs; + int frameCount; + @Getter double avgFPS; + + @Override + public void close() { + if (!closed) { + doClose(); + surface.close(); + closed = true; + } + } + + @Override + public void present() { + ensureOpen(); + long startTimeNs = System.nanoTime(); + // actual rendering + var fb = surface.acquireBuffer(); + RenderCanvasExt canvas = getCanvas(); + canvas.attachTarget(fb); + canvas.clear(); + renderStage(); + canvas.flush(); + surface.present(fb); + long renderTimeNs = System.nanoTime() - startTimeNs; + + // statistics + totalRenderTimeNs += renderTimeNs; + frameCount++; + double fps = (double) NANOS_PER_SECOND / renderTimeNs; + if (Double.isFinite(fps)) { // ignore NaNs and infinities from division by zero etc. + this.lastFPS = fps; + } + double avgFPS = 1d / totalRenderTimeNs * NANOS_PER_SECOND * frameCount; + if (Double.isFinite(avgFPS)) { + this.avgFPS = avgFPS; + } + } + + @Override + public abstract RenderCanvasExt getCanvas(); + + protected abstract void doClose(); + + protected abstract boolean renderControlBar(); + + @SuppressWarnings("unchecked") + protected void renderStage() { + ensureOpen(); + RenderCanvasExt canvas = getCanvas(); + stage.drawBackdrop(canvas); + + // render content + RendererRegistry registry = context.get(RendererRegistry.class); + for (RenderableID id : stage.getLayers()) { + Object renderable = id.getFrom(stage); + Renderer renderer = registry.get((Class) 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() { + if (closed) { + throw new IllegalStateException("This context is closed"); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/GraphicsState.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/GraphicsState.java new file mode 100644 index 0000000..90c464e --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/GraphicsState.java @@ -0,0 +1,205 @@ +package ru.fokinatorr.sparkle.graphics.impl; + +import lombok.Data; +import lombok.NonNull; +import lombok.experimental.FieldDefaults; +import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap; +import ru.fokinatorr.sparkle.graphics.BlendMode; +import ru.fokinatorr.sparkle.graphics.render.RenderCanvas; +import ru.fokinatorr.sparkle.phys2d.Point2D; +import ru.fokinatorr.sparkle.util.Mth; + +import java.awt.*; + +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 { + + double translateX; + double translateY; + double rotationDegrees; + double scaleX = 1.0; + double scaleY = 1.0; + + 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 = (byte) 255; + + @NonNull + BlendMode blendMode = BlendMode.ADD; + @NonNull + GraphicEffectMap effects = new GraphicEffectMap(); + + Shape clip; + + + /** + * 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.translateX = this.translateX; + copy.translateY = this.translateY; + copy.rotationDegrees = this.rotationDegrees; + copy.scaleX = this.scaleX; + copy.scaleY = this.scaleY; + 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.clip = this.clip; + return copy; + } + + /** + * Sets the new X coordinate translation. + * @param translateX the new translation + * @throws IllegalArgumentException if translateX is infinite or NaN + */ + public void setTranslateX(double translateX) { + if (Double.isInfinite(translateX) || Double.isNaN(translateX)) { + throw new IllegalArgumentException("Translation must be finite, got: " + translateX); + } + this.translateX = translateX; + } + + /** + * Sets the new Y coordinate translation. + * @param translateY the new translation + * @throws IllegalArgumentException if translateY is infinite or NaN + */ + public void setTranslateY(double translateY) { + if (Double.isInfinite(translateY) || Double.isNaN(translateY)) { + throw new IllegalArgumentException("Translation must be finite, got: " + translateY); + } + this.translateY = translateY; + } + + /** + * Translates the state by the given deltas. + * @param dx the X delta + * @param dy the Y delta + * @throws IllegalArgumentException if any argument is infinite or NaN + */ + public void translate(double dx, double dy) { + setTranslateX(translateX + dx); + setTranslateY(translateY + dy); + } + + /** + * Sets the new rotation, in degrees. + * @param rotationDegrees the new rotation + * @throws IllegalArgumentException if rotationDegrees is infinite, or NaN + */ + public void setRotationDegrees(double rotationDegrees) { + if (Double.isInfinite(rotationDegrees) || Double.isNaN(rotationDegrees)) { + throw new IllegalArgumentException("Rotation must be positive and finite, got: " + rotationDegrees); + } + this.rotationDegrees = Mth.wrapClamp(rotationDegrees, -360d, 360d); + } + + /** + * Adds the given delta (in degrees) to the current rotation. + * @param dr the rotation delta + * @throws IllegalArgumentException if dr is infinite, or NaN + */ + public void rotate(double dr) { + setRotationDegrees(rotationDegrees + dr); + } + + /** + * Sets the new X axis scale. + * @param scaleX the new X axis scale + * @throws IllegalArgumentException if scaleX is non-positive, infinite, or NaN + */ + public void setScaleX(double scaleX) { + if (scaleX <= 0 || Double.isInfinite(scaleX) || Double.isNaN(scaleX)) { + throw new IllegalArgumentException("Scale must be positive and finite, got: " + scaleX); + } + this.scaleX = scaleX; + } + + /** + * Sets the new Y axis scale. + * @param scaleY the new Y axis scale + * @throws IllegalArgumentException if scaleY is non-positive, infinite, or NaN + */ + public void setScaleY(double scaleY) { + if (scaleY <= 0 || Double.isInfinite(scaleY) || Double.isNaN(scaleY)) { + throw new IllegalArgumentException("Scale must be positive and finite, got: " + scaleY); + } + this.scaleY = scaleY; + } + + /** + * Scales the state 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) { + setScaleX(scaleX * sx); + setScaleY(scaleY * sy); + } + + /** + * 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.isInfinite(lineWidth) || Double.isNaN(lineWidth)) { + throw new IllegalArgumentException("Line width must be positive and finite, got: " + lineWidth); + } + this.lineWidth = lineWidth; + } + + /** + * Transforms the given point by this state's transformation matrix. + * @param x the X coordinate + * @param y the Y coordinate + * @return a new {@link Point2D} with transformed coordinates + */ + public Point2D transformPoint(double x, double y) { + // Apply scale + double tx = x * scaleX; + double ty = y * scaleY; + + // Apply rotation (clockwise) + double cos = Math.cos(Math.toRadians(rotationDegrees)); + double sin = Math.sin(Math.toRadians(rotationDegrees)); + double rx = tx * cos + ty * sin; + double ry = -tx * sin + ty * cos; + + // Apply translation + return new Point2D(rx + translateX, ry + translateY); + } + + /** + * Checks whether this state has any non-identity transformations. + * @return true if translation, rotation, or scaling is applied + */ + public boolean hasTransform() { + return translateX != 0 || translateY != 0 || + rotationDegrees != 0 || + scaleX != 1.0 || scaleY != 1.0; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/IntBufferPixelAccessor.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/IntBufferPixelAccessor.java new file mode 100644 index 0000000..ac766f9 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/IntBufferPixelAccessor.java @@ -0,0 +1,131 @@ +package ru.fokinatorr.sparkle.graphics.impl; + +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import ru.fokinatorr.sparkle.graphics.PixelReader; +import ru.fokinatorr.sparkle.graphics.PixelWriter; + +import java.nio.IntBuffer; + +import static lombok.AccessLevel.PRIVATE; + +/** + * IntBuffer as image accessor, row-major order. + */ +@FieldDefaults(makeFinal = true, level = PRIVATE) +@RequiredArgsConstructor +public class IntBufferPixelAccessor implements PixelReader, PixelWriter { + + int width, height; + IntBuffer img; + Runnable ensureOpen; + + // + + @Override + public int getWidth() { + ensureOpen(); + return width; + } + + @Override + public int getHeight() { + ensureOpen(); + return height; + } + + @Override + public int getARGB(int x, int y) { + ensureOpen(); + checkBounds(x, y); + return img.get(y * width + x); + } + + @Override + public int[] getRow(int y) { + ensureOpen(); + checkBoundsY(y); + int[] row = new int[width]; + img.get(y * width, row); + return row; + } + + @Override + public int[] getColumn(int x) { + ensureOpen(); + checkBoundsX(x); + int[] column = new int[height]; + for (int y = 0; y < height; y++) { + column[y] = img.get(y * width + x); + } + return column; + } + + @Override + public int[][] getAll() { + int[][] data = new int[height][width]; + for (int y = 0; y < height; y++) { + img.get(y * width, data[y]); + } + return data; + } + + // + + // + + @Override + public void setARGB(int x, int y, int argb) { + ensureOpen(); + checkBounds(x, y); + img.put(y * width + x, argb); + } + + @Override + public void fillARGB(int startX, int startY, int w, int h, int argb) { + ensureOpen(); + checkBounds(startX, startY); + checkBounds(startX + w - 1, startY + h - 1); + + for (int y = startY; y < startY + h; y++) { + int base = y * width; + for (int x = startX; x < startX + w; x++) { + img.put(base + x, argb); + } + } + } + + @Override + public void writePixels(int[] src, int off, int scanSize, int startX, int startY, int w, int h) { + ensureOpen(); + checkBounds(startX, startY); + checkBounds(startX + w - 1, startY + h - 1); + + for (int y = startY; y < startY + w; y++) { + img.put(y * width + startX, src, off + scanSize * (y - startX), h); + } + } + + // + + private void ensureOpen() { + ensureOpen.run(); + } + + private void checkBoundsX(int x) { + if (x >= width) { + throw new IllegalArgumentException("X coordinate out of bounds for " + width + "x" + height + " image: " + x); + } + } + + private void checkBoundsY(int y) { + if (y >= height) { + throw new IllegalArgumentException("Y coordinate out of bounds for " + width + "x" + height + " image: " + y); + } + } + + private void checkBounds(int x, int y) { + checkBoundsX(x); + checkBoundsY(y); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/OpenGLGraphicsManager.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/OpenGLGraphicsManager.java new file mode 100644 index 0000000..319cff6 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/OpenGLGraphicsManager.java @@ -0,0 +1,235 @@ +package ru.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.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 java.net.MalformedURLException; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; + +import static lombok.AccessLevel.PRIVATE; +import static org.lwjgl.glfw.GLFW.*; + +/** + * A graphics manager using OpenGL + GLFW as a GPU-based backend. + *

NOTE: Make sure to call the constructor from the graphics loop thread! + */ +@Slf4j +@FieldDefaults(level = PRIVATE) +@RequiredArgsConstructor +public class OpenGLGraphicsManager implements GraphicsManager { + // NOTE: Using OpenGL for beta releases. If performance gets unbearably horrible, switch to Vulkan + + private static final StageAccess stageAcc = SharedSecrets.getStageAccess(); + + @NonNull + final AppContext context; + final Queue workQ = new ConcurrentLinkedQueue<>(); + final Map renderContexts = new Reference2ReferenceOpenHashMap<>(); + final Thread graphicsThread = Thread.currentThread(); + final Map images = new ConcurrentHashMap<>(); + final Set autoLoadImages = Collections.newSetFromMap(new ConcurrentHashMap<>()); + + boolean glInitialized; + GLFWErrorCallback errorCallback; + + boolean closed; + + @Override + public void close() { + if (!closed) { + ensureOnCorrectThread(); + renderContexts.values().forEach(AbstractRenderingContext::close); + renderContexts.clear(); + images.values().forEach(Image::close); + images.clear(); + autoLoadImages.clear(); + if (glInitialized) { + glfwTerminate(); + errorCallback.free(); + glInitialized = false; + } + closed = true; + } + } + + @Override + public Pair createWindowContext(String title, StageCreator stageCreator, boolean translucent, boolean fullscreen) { + ensureOpen(); + ensureOnCorrectThread(); + ensureGLInitialized(); + + + Stage stage = SharedSecrets.getStageAccess().newStage(stageCreator, context); + // @formatter:off // for readability + GL_GLFWWindowSurface window = fullscreen + ? GL_GLFWWindowSurface.createFullscreen( + title, glfwGetPrimaryMonitor(), translucent, + context.get(EventDispatcher.class), stage, graphicsThread + ) + : GL_GLFWWindowSurface.create( + title, translucent, + context.get(EventDispatcher.class), stage, graphicsThread + ); + // @formatter:on + OpenGLContext glContext = new OpenGLContext(context, window, stage, autoLoadImages, this); + renderContexts.put(stage, glContext); + return new ReferenceReferenceImmutablePair<>(stage, glContext); + } + + @Override + public Pair createEmbeddedContext(EmbeddedSurface surface, StageCreator stageCreator) { + ensureOpen(); + return null; + } + + @Override + public AbstractRenderingContext getContext(Stage boundStage) { + ensureOpen(); + return renderContexts.get(Objects.requireNonNull(boundStage, "bound stage")); + } + + @Override + public boolean hasActiveContexts() { + return !(closed || renderContexts.isEmpty()); + } + + @Override + 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); + } + + Image oldImg = images.put(path, newImg); + if (oldImg != null) { + autoLoadImages.remove(oldImg); + oldImg.close(); + } + + if (autoLoad) autoLoadImages.add(newImg); + return newImg; + } + + @Override + public boolean hasLoadedImage(Path path) { + return !closed && images.containsKey(path); + } + + @Override + public Image getLoadedImage(Path path) { + ensureOpen(); + return images.get(path); + } + + @Override + public void destroyImage(Path path) { + ensureOpen(); + if (images.containsKey(path)) { + images.remove(path).close(); + } + } + + @Override + public void runLater(Runnable run) { + ensureOpen(); + if (!workQ.offer(run)) { + throw new IllegalStateException("Work queue overflow; cannot add more tasks"); + } + } + + @Override + public void tick() { + ensureOpen(); + ensureOnCorrectThread(); + + runTasks(); + for (var renderCtx : renderContexts.values()) { + renderCtx.pollEvents(); + if (!stageAcc.isSuppressRedraw(renderCtx.getStage())) { + renderCtx.present(); + } + if (renderCtx.shouldClose()) { + renderCtx.getStage().stop().thenRun(() -> runLater(() -> { + renderCtx.close(); + renderContexts.remove(renderCtx.getStage()); + })); + } + } + } + + private void ensureOpen() { + if (closed) { + throw new IllegalStateException("This manager is closed"); + } + } + + private void ensureOnCorrectThread() { + if (Thread.currentThread() != graphicsThread) { + throw new IllegalCallerException("Called from incorrect thread; must call from " + graphicsThread); + } + } + + private void ensureGLInitialized() { + if (!glInitialized) { + // GLFW + 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 + } + + if (!glfwInit()) { + throw new IllegalStateException("Unable to initialize GLFW"); + } + glfwDefaultWindowHints(); + glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API); + glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); + 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); + + // GL context not created here, so no GL calls yet + } + } + + private void runTasks() { + Runnable task; + while ((task = workQ.poll()) != null) { + try { + task.run(); + } catch (Exception e) { + log.error("Exception in task", e); + } + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/RenderCanvasExt.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/RenderCanvasExt.java new file mode 100644 index 0000000..73ea5ef --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/RenderCanvasExt.java @@ -0,0 +1,34 @@ +package ru.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; + +/** + * An extensions interface for {@link RenderCanvas} providing additional methods + * for attaching framebuffers, flushing, etc. + */ +public interface RenderCanvasExt extends RenderCanvas { + + /** + * Attaches a new framebuffer for the canvas to draw on. + * @param target the framebuffer + */ + void attachTarget(Framebuffer target); + + /** + * Clears the entire surface. + */ + void clear(); + + /** + * Flushes all pending operations, if any. + */ + void flush(); + + /** + * Uploads an Image object, making it ready for rendering. + * @param image the image + */ + void uploadImage(Image image); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/GLFramebuffer.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/GLFramebuffer.java new file mode 100644 index 0000000..8c9ec07 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/GLFramebuffer.java @@ -0,0 +1,203 @@ +package ru.fokinatorr.sparkle.graphics.impl.gl; + +import ru.fokinatorr.sparkle.graphics.ARGB; +import ru.fokinatorr.sparkle.graphics.PixelReader; +import ru.fokinatorr.sparkle.graphics.PixelWriter; +import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer; + +import java.nio.ByteBuffer; + +import static org.lwjgl.opengl.GL46.*; + +/** + * A wrapper for an OpenGL framebuffer. + */ +public record GLFramebuffer(int fboId, int width, int height) implements Framebuffer { + + public GLFramebuffer { + if (width <= 0 || height <= 0) { + throw new IllegalArgumentException("Width and height must be positive"); + } + } + + /** + * 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(), width, height); + } + + @Override + public PixelReader createPixelReader() { + ensureOpen(); + if (fboId == 0) { + return new Accessor(); + } + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + * @deprecated By-pixel writing to a GL buffer is much slower than using GL operations + * directly and may not work. Prefer GL operations instead of this method. + */ + @Override + @Deprecated(since = "0.1-beta") + public PixelWriter createPixelWriter() { + ensureOpen(); + if (fboId == 0) { + return new Accessor(); + } + throw new UnsupportedOperationException(); + } + + @Override + public void close() { + if (fboId != 0) { + glDeleteFramebuffers(fboId); + } + } + + private void ensureOpen() { + if (!glIsFramebuffer(fboId)) { + throw new IllegalStateException("The framebuffer is closed"); + } + } + + private void checkBoundsX(int x) { + if (x >= width) { + throw new IllegalArgumentException("X coordinate out of bounds for " + width + "x" + height + " image: " + x); + } + } + + private void checkBoundsY(int y) { + if (y >= height) { + throw new IllegalArgumentException("Y coordinate out of bounds for " + width + "x" + height + " image: " + y); + } + } + + private void checkBounds(int x, int y) { + checkBoundsX(x); + checkBoundsY(y); + } + + + // not thread-safe! + private class Accessor implements PixelReader, PixelWriter { + + private final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(Math.max(width, height) * Integer.BYTES); + // can't use MemoryUtil.memAlloc since no chance to clean up (PixelReader/Writer are not closeable) + + private static void rgbaToArgb(ByteBuffer src, int[] dest) { + for (int i = 0; i < dest.length; i++) { + byte + r = src.get(), + g = src.get(), + b = src.get(), + a = src.get(); + dest[i] = ARGB.color(a, r, g, b); + } + } + + private static void argbToRgba(int argb, ByteBuffer dest) { + dest + .put(ARGB.red (argb)) + .put(ARGB.green(argb)) + .put(ARGB.blue (argb)) + .put(ARGB.alpha(argb)) + .flip(); + } + + // + + @Override + public int getARGB(int x, int y) { + ensureOpen(); + checkBounds(x, y); + byteBuffer.limit(Integer.BYTES).rewind(); + glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer); + return ARGB.color( + byteBuffer.get(3), + byteBuffer.get(0), + byteBuffer.get(1), + byteBuffer.get(2) + ); + } + + @Override + public int[] getRow(int y) { + ensureOpen(); + checkBoundsY(y); + int[] row = new int[width]; + byteBuffer.limit(width * Integer.BYTES).rewind(); + glReadPixels(0, y, width, 1, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer); + rgbaToArgb(byteBuffer, row); + return row; + } + + @Override + public int[] getColumn(int x) { + ensureOpen(); + checkBoundsX(x); + int[] column = new int[height]; + byteBuffer.limit(height * Integer.BYTES).rewind(); + glReadPixels(x, 0, 1, height, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer); + rgbaToArgb(byteBuffer, column); + return column; + } + + @Override + public int[][] getAll() { + int[][] data = new int[height][width]; + byteBuffer.limit(width * Integer.BYTES).rewind(); + for (int y = 0; y < height; y++) { + glReadPixels(0, y, width, 1, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer); + rgbaToArgb(byteBuffer, data[y]); + byteBuffer.rewind(); + } + return data; + } + + @Override + public int getWidth() { + return width; + } + + @Override + public int getHeight() { + return height; + } + + // + + // + + + @Override + @Deprecated(since = "0.1-beta") + public void setARGB(int x, int y, int argb) { + ensureOpen(); + checkBounds(x, y); + argbToRgba(argb, byteBuffer.rewind()); + glRasterPos2i(x, height - 1 - y); + glDrawPixels(1, 1, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer); + } + + @Override + @Deprecated(since = "0.1-beta") + public void fillARGB(int x, int y, int w, int h, int argb) { + ensureOpen(); + checkBounds(x, y); + checkBounds(x + w - 1, y + h - 1); + argbToRgba(argb, byteBuffer.rewind()); + glRasterPos2i(x, height - 1 - y); + glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer); + } + + // + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/GLRenderCanvas.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/GLRenderCanvas.java new file mode 100644 index 0000000..60c621f --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/GLRenderCanvas.java @@ -0,0 +1,697 @@ +package ru.fokinatorr.sparkle.graphics.impl.gl; + +import it.unimi.dsi.fastutil.floats.*; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import org.joml.Matrix4f; +import org.lwjgl.opengl.GL46; +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.PixelReader; +import ru.fokinatorr.sparkle.graphics.image.Image; +import ru.fokinatorr.sparkle.graphics.impl.GraphicsState; +import ru.fokinatorr.sparkle.graphics.impl.RenderCanvasExt; +import ru.fokinatorr.sparkle.graphics.impl.gl.shader.GLShaderProgram; +import ru.fokinatorr.sparkle.graphics.impl.gl.shader.ShaderType; +import ru.fokinatorr.sparkle.graphics.render.RenderCanvas; +import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer; + +import java.awt.*; +import java.awt.geom.Area; +import java.awt.geom.PathIterator; +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.util.*; + +import static lombok.AccessLevel.PROTECTED; +import static org.lwjgl.opengl.GL46.*; +import static org.lwjgl.system.MemoryUtil.*; +import static ru.fokinatorr.sparkle.graphics.impl.gl.ShaderLoader.loadShader; + +import ru.fokinatorr.sparkle.phys2d.Point2D; + +/** + * An OpenGL render canvas that accepts {@link GLFramebuffer}s. + */ +@FieldDefaults(level = PROTECTED) +public class GLRenderCanvas implements RenderCanvasExt { + + final OpenGLContext parent; + final Set autoLoadImages; + + final Deque stateStack = new LinkedList<>(); // Funny how Stack was effectively replaced with Deque + GraphicsState currentState = new GraphicsState(); + + final GLShaderProgram strokeShader; + final GLShaderProgram fillShader; + final GLShaderProgram imageShader; + + final Map textures = new WeakHashMap<>(); + GLFramebuffer fb; + + boolean closed; + + + public GLRenderCanvas(OpenGLContext parent, Set autoLoadImages) { + this.parent = parent; + this.autoLoadImages = autoLoadImages; + + parent.makeCurrent(); + strokeShader = GLShaderProgram.compile(Map.of( + ShaderType.VERTEX, loadShader("stroke.vert.glsl"), + ShaderType.FRAGMENT, loadShader("stroke.frag.glsl") + )); + fillShader = GLShaderProgram.compile(Map.of( + ShaderType.VERTEX, loadShader("fill.vert.glsl"), + ShaderType.FRAGMENT, loadShader("fill.frag.glsl") + )); + imageShader = GLShaderProgram.compile(Map.of( + ShaderType.VERTEX, loadShader("image.vert.glsl"), + ShaderType.FRAGMENT, loadShader("image.frag.glsl") + )); + } + + // + + @Override + public void attachTarget(Framebuffer target) { + ensureOpen(); + if (!(target instanceof GLFramebuffer(int fboId, int width, int height))) { + throw new IllegalArgumentException("Unsupported frame buffer type: " + target.getClass()); + } + parent.makeCurrent(); + if (this.fb != null) this.fb.close(); + this.fb = (GLFramebuffer) target; + + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + glViewport(0, 0, width, height); + glClearColor(1f, 1f, 1f, 0f); // transparent/white by default + + for (Image img : autoLoadImages) uploadImage(img); + } + + @Override + public void clear() { + ensureOpen(); + parent.makeCurrent(); + ensureCurrentBufferBound(); + glClear(GL_COLOR_BUFFER_BIT); + } + + @Override + public void flush() { + ensureOpen(); + parent.makeCurrent(); + ensureCurrentBufferBound(); + glFlush(); + } + + @Override + public void uploadImage(Image image) { + ensureOpen(); + parent.makeCurrent(); + ensureCurrentBufferBound(); + if (!textures.containsKey(image)) { + image.prepare(); + + PixelReader reader = image.createPixelReader(); + int width = reader.getWidth(); + int height = reader.getHeight(); + + int textureId = glGenTextures(); + textures.put(image, textureId); + glBindTexture(GL_TEXTURE_2D, textureId); + + ByteBuffer pixels = memAlloc(width * height * Integer.BYTES); + int[][] data = reader.getAll(); + for (int y = 0; y < height; y++) { + 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_RGBA8, + 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); + } + + } + + // + + // + + // Drawing methods + + @Override + public void drawShape(Shape shape) { + // Ensure openness and current context + ensureOpen(); + parent.makeCurrent(); + ensureCurrentBufferBound(); + + // Convert Shape to VBO + FloatList vertices = shapeToVertices(shape); + + if (vertices.isEmpty()) return; + int vbo = uploadAndBindVertices(vertices); + + // Set up vertex attributes & shader uniforms + strokeShader.use(); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, NULL); + + Matrix4f modelViewProj = buildOrthoMatrix().mul(buildTransformMatrix()); + 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_ModelViewProj", modelViewProj) + .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", (float) effects.getDouble(GraphicEffect.OPACITY) / 100f); + + // Apply blend function & draw + glEnable(GL_BLEND); + applyBlendFunc(); + + glLineWidth((float) currentState.getLineWidth()); + glDrawArrays(GL_LINE_STRIP, 0, vertices.size() / 2); + + // Cleanup + glDisable(GL_BLEND); + glDisableVertexAttribArray(0); + glDeleteBuffers(vbo); + strokeShader.unuse(true); + } + + @Override + public void fillShape(Shape shape) { + ensureOpen(); + parent.makeCurrent(); + ensureCurrentBufferBound(); + + // Init common objects + glEnable(GL_BLEND); + applyBlendFunc(); + Matrix4f modelViewProj = buildOrthoMatrix().mul(buildTransformMatrix()); + + // First fill... + FloatList fillVertices = shapeToFillVertices(shape); + if (!fillVertices.isEmpty()) { + int vbo = uploadAndBindVertices(fillVertices); + + // Set up vertex attributes & shader uniforms + fillShader.use(); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, NULL); + + 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_ModelViewProj", modelViewProj) + .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", (float) effects.getDouble(GraphicEffect.OPACITY) / 100f); + + // Draws as triangle fan (assumes convex or simple shape). TODO replace with tessellation + glDrawArrays(GL_TRIANGLE_FAN, 0, fillVertices.size() / 2); + + // Cleanup + glDisableVertexAttribArray(0); + glDeleteBuffers(vbo); + fillShader.unuse(true); + } + + // ...then outline + FloatList outlineVertices = shapeToVertices(shape); + if (!outlineVertices.isEmpty()) { + int vbo = uploadAndBindVertices(outlineVertices); + + strokeShader.use(); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, NULL); + + 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_ModelViewProj", modelViewProj) + .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", (float) effects.getDouble(GraphicEffect.OPACITY) / 100f); + + // Draw + glLineWidth((float) currentState.getLineWidth()); + glDrawArrays(GL_LINE_STRIP, 0, outlineVertices.size() / 2); + + // Cleanup + glDisableVertexAttribArray(0); + glDeleteBuffers(vbo); + strokeShader.unuse(true); + } + + // Common cleanup + glDisable(GL_BLEND); + } + + @Override + public void drawImage(Image image, double x, double y, double w, double h) { + ensureOpen(); + + // sanity checks + if (!Double.isFinite(x) || x < 0) { + throw new IllegalArgumentException("X coordinate must be finite and non-negative, found: " + x); + } + if (!Double.isFinite(y) || y < 0) { + throw new IllegalArgumentException("Y coordinate must be finite and non-negative, found: " + y); + } + if (w == ORIGINAL_SIZE || h == ORIGINAL_SIZE) { + PixelReader reader = image.createPixelReader(); + if (w == ORIGINAL_SIZE) w = reader.getWidth(); + if (h == ORIGINAL_SIZE) h = reader.getHeight(); + } + 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); + } + + parent.makeCurrent(); + ensureCurrentBufferBound(); + glEnable(GL_BLEND); + + if (!textures.containsKey(image)) { + uploadImage(image); + } + int textureId = textures.get(image); + + // === 1. Upload Quad Geometry to GPU === + FloatBuffer quadVertices = memAllocFloat(16); // 4 vertices × 4 values (x,y,u,v) + // Vertex format: x, y, u, v + + quadVertices + .put((float) x).put((float) y).put(0f).put(0f) // TL + .put((float) x).put((float) (y + h)).put(0f).put(1f) // BL + .put((float) (x + w)).put((float) (y + h)).put(1f).put(1f) // BR + .put((float) (x + w)).put((float) y).put(1f).put(0f) // TR + .flip(); + + int vbo = glGenBuffers(); + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glBufferData(GL_ARRAY_BUFFER, quadVertices, GL_DYNAMIC_DRAW); + + // === 2. Bind Texture === + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, textureId); + + // === 3. Use Image Shader Program === + imageShader.use(); + + // === 4. Set Up Vertex Attributes === + glEnableVertexAttribArray(0); // Position (x,y) + glEnableVertexAttribArray(1); // TexCoord (u,v) + glVertexAttribPointer(0, 2, GL_FLOAT, false, 4 * Float.BYTES, 0); + glVertexAttribPointer(1, 2, GL_FLOAT, false, 4 * Float.BYTES, 2 * Float.BYTES); + + // === 5. Set Uniforms === + Matrix4f modelViewProj = buildOrthoMatrix().mul(buildTransformMatrix()); + imageShader + .setUniform("u_ModelViewProj", modelViewProj) + .setUniform("u_Texture", 0); // sampler2D bound to unit 0 + + // Apply alpha and blend mode + float alphaMult = byteToFloat(currentState.getAlpha()); + imageShader.setUniform("u_Alpha", alphaMult); + applyBlendFunc(); + + // 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", (float) effects.getDouble(GraphicEffect.OPACITY) / 100f) + .setUniform("u_Pixelate", (float) effects.getDouble(GraphicEffect.PIXELATION)); + + // === 6. Draw Quad === + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + + // === 7. Cleanup === + glDisable(GL_BLEND); + glDisableVertexAttribArray(0); + glDisableVertexAttribArray(1); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glDeleteBuffers(vbo); + imageShader.unuse(true); + } + + @Override + public RenderCanvas createSubCanvas(double width, double height) { + 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"); + } + GLSubCanvas renderCanvas = new GLSubCanvas(parent, autoLoadImages); + 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 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(Shape shape) { + currentState.setClip(shape); + } + + @Override + public void resetClip() { + currentState.setClip(null); + } + + @Override + public void save() { + stateStack.push(currentState.copy()); + } + + @Override + public void restore() { + if (!stateStack.isEmpty()) { + currentState = stateStack.pop(); + } + } + + private static final GraphicEffectMap EMPTY = new GraphicEffectMap(); + + @Override + public void setIdentity() { + currentState.setTranslateX(0); + currentState.setTranslateY(0); + currentState.setRotationDegrees(0); + currentState.setScaleX(1); + currentState.setScaleY(1); + currentState.setFillARGB(0xFF_00_00_00); + currentState.setStrokeARGB(0xFF_00_00_00); + currentState.setLineWidth(1); + currentState.setAlpha((byte) 255); + currentState.setBlendMode(BlendMode.ADD); + currentState.setEffects(EMPTY); + currentState.setClip(null); + } + + // 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) { + textures.values().forEach(GL46::glDeleteTextures); + textures.clear(); + strokeShader.close(); + fillShader.close(); + if (fb != null) { + fb.close(); + fb = null; + } + closed = true; + } + } + + // + + // Private implementation + + private void applyBlendFunc() { + switch (currentState.getBlendMode()) { + 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_REVERSE_SUBTRACT); // reversed addition - subtraction + } + case RGB_SUBTRACT -> { + // Subtract RGB components, sum alpha components + glBlendFunc(GL_ONE, GL_ONE); + glBlendEquationSeparate(GL_FUNC_REVERSE_SUBTRACT, GL_FUNC_ADD); // reverse only RGB components + } + 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); + } + } + } + + private FloatList shapeToVertices(Shape shape) { + Area area = shape instanceof Area a ? a : new Area(shape); + PathIterator itr = area.getPathIterator(null); + double[] coords = new double[6]; + FloatList vertices = new FloatArrayList(); + + double startX = 0, startY = 0; + boolean isMoveTo = true; + + while (!itr.isDone()) { + int type = itr.currentSegment(coords); + switch (type) { + case PathIterator.SEG_MOVETO: + if (!isMoveTo) { + // Close previous subpath by connecting to start point + vertices.add((float) startX); + vertices.add((float) startY); + } + startX = coords[0]; + startY = coords[1]; + isMoveTo = false; + break; + + case PathIterator.SEG_LINETO: + if (isMoveTo) break; // Skip degenerate segments + vertices.add((float) coords[0]); + vertices.add((float) coords[1]); + break; + + case PathIterator.SEG_CLOSE: + if (!isMoveTo) { + vertices.add((float) startX); + vertices.add((float) startY); + } + isMoveTo = true; // Triggers new MOVETO on next SEG_MOVETO + break; + } + itr.next(); + } + + return vertices; + } + + /** + * Like {@link #shapeToVertices(Shape)}, but, at the end, closes the path if unclosed. This ensures + * a closed fill area. + */ + private FloatList shapeToFillVertices(Shape shape) { + Area area = shape instanceof Area a ? a : new Area(shape); + PathIterator itr = area.getPathIterator(null, 0.2); // Flatness controls curve accuracy + double[] coords = new double[6]; + FloatList vertices = new FloatArrayList(); + + double startX = 0, startY = 0; + boolean isMoveTo = true; + + while (!itr.isDone()) { + int type = itr.currentSegment(coords); + switch (type) { + case PathIterator.SEG_MOVETO: + if (!isMoveTo) { + // Close previous contour + vertices.add((float) startX); + vertices.add((float) startY); + } + startX = coords[0]; + startY = coords[1]; + isMoveTo = false; + break; + + case PathIterator.SEG_LINETO: + if (isMoveTo) break; + vertices.add((float) coords[0]); + vertices.add((float) coords[1]); + break; + + case PathIterator.SEG_CLOSE: + if (!isMoveTo) { + vertices.add((float) startX); + vertices.add((float) startY); + } + isMoveTo = true; + break; + } + itr.next(); + } + + // Close final contour if open + if (!isMoveTo) { + vertices.add((float) startX); + vertices.add((float) startY); + } + + return vertices; + } + + private int uploadAndBindVertices(FloatCollection vertices) { + FloatBuffer vertexData = memAllocFloat(vertices.size()); + vertices.forEach(vertexData::put); + vertexData.flip(); + + int vbo = glGenBuffers(); + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glBufferData(GL_ARRAY_BUFFER, vertexData, GL_DYNAMIC_DRAW); + + return vbo; + } + + private Matrix4f buildOrthoMatrix() { + int w = fb.width(), h = fb.height(); + return new Matrix4f().setOrtho(0, w, h, 0, -1, 1); // Y-down to match Java2D + } + + protected void ensureCurrentBufferBound() { + glBindFramebuffer(GL_FRAMEBUFFER, fb.fboId()); + } + + // Helper: Build transform from GraphicsState + private Matrix4f buildTransformMatrix() { + Matrix4f translate = new Matrix4f().translation((float) currentState.getTranslateX(), (float) currentState.getTranslateY(), 0); + Matrix4f rotate = new Matrix4f().rotationZ((float) Math.toRadians(-currentState.getRotationDegrees())); // Clockwise → negative angle + Matrix4f scale = new Matrix4f().scaling((float) currentState.getScaleX(), (float) currentState.getScaleY(), 1); + return new Matrix4f().mul(translate).mul(rotate).mul(scale); + } + + /** + * 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"); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/GLSubCanvas.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/GLSubCanvas.java new file mode 100644 index 0000000..8c3a80c --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/GLSubCanvas.java @@ -0,0 +1,155 @@ +package ru.fokinatorr.sparkle.graphics.impl.gl; + +import lombok.experimental.FieldDefaults; +import lombok.extern.slf4j.Slf4j; +import ru.fokinatorr.sparkle.graphics.PixelReader; +import ru.fokinatorr.sparkle.graphics.image.Image; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.Set; + +import org.lwjgl.system.MemoryUtil; +import ru.fokinatorr.sparkle.graphics.impl.IntBufferPixelAccessor; +import ru.fokinatorr.sparkle.util.BufferUtils; + +import static lombok.AccessLevel.PRIVATE; +import static org.lwjgl.opengl.GL46.*; + +/** + * An OpenGL sub-canvas. + */ +@Slf4j +public class GLSubCanvas extends GLRenderCanvas { + public GLSubCanvas(OpenGLContext parent, Set autoLoadImages) { + super(parent, autoLoadImages); + } + + private LoadedImage finalImage; + + @Override + public Image getFinalImage() { + ensureOpen(); + if (finalImage == null) { + flush(); + + int width = fb.width(); + int height = fb.height(); + + ByteBuffer pixels = MemoryUtil.memAlloc(width * height * Integer.BYTES); + parent.makeCurrent(); + + glBindFramebuffer(GL_READ_FRAMEBUFFER, fb.fboId()); + glReadBuffer(GL_COLOR_ATTACHMENT0); + + glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + pixels.rewind(); + + flipVertically(pixels, width, height); + while (pixels.hasRemaining()) { + int pos = pixels.position(); + byte + r = pixels.get(), + g = pixels.get(), + b = pixels.get(), + a = pixels.get(); + pixels.position(pos) + .put(a) + .put(r) + .put(g) + .put(b); + } + finalImage = new LoadedImage(pixels, width, height); + } + return finalImage; + } + + /** + * Flips the image vertically, so that the origin is in the top-left corner for images + * retrieved from GL. + * + * @param buffer the pixel data + * @param width row width + * @param height row count + */ + private static void flipVertically(ByteBuffer buffer, int width, int height) { + int rowSize = width * Integer.BYTES; + ByteBuffer tempRow = MemoryUtil.memAlloc(rowSize); + + try (var _ = BufferUtils.freeing(tempRow)) { + for (int y = 0; y < height / 2; y++) { + int topRowStart = y * rowSize; + int bottomRowStart = (height - y - 1) * rowSize; + + buffer.position(topRowStart); + tempRow.clear(); + tempRow.put(buffer.slice().limit(rowSize)); + + buffer.position(topRowStart); + buffer.limit(bottomRowStart + rowSize); + buffer.put(buffer.slice()); + + buffer.position(bottomRowStart); + tempRow.flip(); + buffer.put(tempRow); + } + } + } + + @Override + public void close() { + if (!closed) { + finalImage.close(); + finalImage = null; + super.close(); + } + } + + /** + * A loaded and always prepared image. + */ + @FieldDefaults(level = PRIVATE) + static class LoadedImage implements Image { + final ByteBuffer pixels; + final IntBuffer img; + final int width; + final int height; + boolean closed; + + public LoadedImage(ByteBuffer pixels, int width, int height) { + this.width = width; + this.height = height; + this.pixels = pixels; + img = MemoryUtil.memIntBuffer(MemoryUtil.memAddress(pixels.rewind()), pixels.capacity() / 4); + } + + @Override + public void prepare() { + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public PixelReader createPixelReader() { + ensureOpen(); + return new IntBufferPixelAccessor(width, height, img, this::ensureOpen); + } + + private void ensureOpen() { + if (closed) { + throw new IllegalStateException("This image is closed"); + } + } + + @Override + public void close() { + if (!closed) { + MemoryUtil.memFree(pixels); + closed = true; + } + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/OpenGLContext.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/OpenGLContext.java new file mode 100644 index 0000000..5cb124e --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/OpenGLContext.java @@ -0,0 +1,73 @@ +package ru.fokinatorr.sparkle.graphics.impl.gl; + +import lombok.Getter; +import lombok.experimental.FieldDefaults; +import lombok.extern.slf4j.Slf4j; +import org.lwjgl.opengl.GL; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.graphics.GraphicsManager; +import ru.fokinatorr.sparkle.graphics.image.Image; +import ru.fokinatorr.sparkle.graphics.impl.AbstractRenderingContext; +import ru.fokinatorr.sparkle.graphics.impl.gl.surface.GL_GLFWWindowSurface; +import ru.fokinatorr.sparkle.stage.Stage; + +import java.util.Set; + +import static lombok.AccessLevel.PRIVATE; +import static org.lwjgl.glfw.GLFW.*; +import static org.lwjgl.opengl.GL11.*; + +/** + * An OpenGL rendering context bound to a GLFW window. + *

+ * This context uses the GLFW window's OpenGL context for rendering. + */ +@Slf4j +@FieldDefaults(makeFinal = true, level = PRIVATE) +public class OpenGLContext extends AbstractRenderingContext { + @Getter + final long glfwWindow; // pointer + @Getter + final GLRenderCanvas canvas; // TODO implement & create! + + public OpenGLContext(AppContext context, GL_GLFWWindowSurface surface, Stage stage, Set autoLoadImages, GraphicsManager parent) { + super(context, surface, stage, parent); + this.glfwWindow = surface.getGlfwWindow(); + makeCurrent(); + if (!GL.getCapabilities().OpenGL46) { + throw new IllegalStateException("OpenGL 4.6 required but not supported"); + } + log.info("Initialized OpenGL context version {}", glGetString(GL_VERSION)); + log.info("\tGL Renderer: {}", glGetString(GL_RENDERER)); + log.info("\tGL Vendor: {}", glGetString(GL_VENDOR)); + + this.canvas = new GLRenderCanvas(this, autoLoadImages); + } + + public void makeCurrent() { + glfwMakeContextCurrent(glfwWindow); + try { + if (GL.getCapabilities() == null) { + GL.createCapabilities(); + } + } catch (IllegalStateException _) { // thrown when no capabilities were created yet + GL.createCapabilities(); // sets automatically + } + } + + @Override + protected void doClose() { + canvas.close(); + // GL context destroyed by the surface + } + + @Override + protected boolean renderControlBar() { + return !getSurface().isTranslucent(); + } + + @Override + public GL_GLFWWindowSurface getSurface() { + return (GL_GLFWWindowSurface) super.getSurface(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/ShaderLoader.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/ShaderLoader.java new file mode 100644 index 0000000..8c934f0 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/ShaderLoader.java @@ -0,0 +1,74 @@ +package ru.fokinatorr.sparkle.graphics.impl.gl; + +import lombok.experimental.UtilityClass; +import ru.fokinatorr.sparkle.util.Constants; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Stream; + +/** + * Loads shader files, replacing snippet placeholders with actual snippets. + */ +@UtilityClass +public class ShaderLoader { + + private static final Map SNIPPETS; + private static final Map SHADERS = new HashMap<>(); + + private static final Path SHADERS_DIR; + private static final Path SNIPPETS_DIR; + + /** + * Loads a GLSL file at the given location. + * @param loc the location of the shader file in /resources/shaders + * @return the shader's code + * @throws RuntimeException if loading fails + */ + public static String loadShader(String loc) { + return SHADERS.computeIfAbsent(SHADERS_DIR.resolve(loc), shaderFile -> { + try { + String sourceCode = Files.readString(shaderFile); + for (var entry : SNIPPETS.entrySet()) { + sourceCode = sourceCode.replace(entry.getKey(), entry.getValue()); + } + return sourceCode; + } catch (IOException e) { + throw new RuntimeException("Failed to read shader '" + loc + "'", e); + } + }); + } + + static { + SHADERS_DIR = Constants.ROOT.resolve("shaders"); + SNIPPETS_DIR = SHADERS_DIR.resolve("snippets"); + + Map snippetMap = new HashMap<>(); + try (Stream snippets = Files.list(SNIPPETS_DIR)) { + snippets.forEach(snippet -> { + String name = snippet.getFileName().toString(); + int lastIndexOfDot = name.lastIndexOf("."); + if (lastIndexOfDot >= 0) { + name = name.substring(0, lastIndexOfDot); + } + snippetMap.put("{{" + name + "}}", loadSnippet(snippet)); + }); + } catch (IOException e) { + throw new ExceptionInInitializerError(e); + } + + SNIPPETS = Collections.unmodifiableMap(snippetMap); + } + + private static String loadSnippet(Path path) { + try { + return Files.readString(path); + } catch (IOException e) { + throw new RuntimeException("Failed to read snippet '" + path.getFileName() + "'", e); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/GLShaderProgram.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/GLShaderProgram.java new file mode 100644 index 0000000..647e036 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/GLShaderProgram.java @@ -0,0 +1,246 @@ +package ru.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 lombok.Getter; +import lombok.experimental.FieldDefaults; +import org.joml.Matrix4f; +import org.lwjgl.opengl.GL20; +import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable; + +import java.nio.FloatBuffer; +import java.util.Map; +import java.util.Objects; + +import static lombok.AccessLevel.PRIVATE; +import static org.lwjgl.opengl.GL46.*; +import static org.lwjgl.system.MemoryStack.stackPush; + +/** + * An OpenGL shader program wrapper. Not thread-safe. + */ +@SuppressWarnings("UnusedReturnValue") +@FieldDefaults(level = PRIVATE) +@Getter +public class GLShaderProgram implements NonThrowingAutoCloseable { + final int programId; + final Int2IntMap uniformLocationsCache = new Int2IntOpenHashMap(); + + boolean closed; + + // Factory methods + + /** + * Creates a {@code GLShaderProgram} from an initialized shader program. + * + * @param programId the program ID + * @throws IllegalArgumentException if program ID is invalid + */ + public GLShaderProgram(int programId) { + if (!glIsProgram(programId)) { + throw new IllegalArgumentException("Invalid program ID: 0x" + Integer.toHexString(programId).toUpperCase()); + } + this.programId = programId; + } + + /** + * Compiles the given GLSL sources into a new shader program. + * + * @param shadersGLSL the shader sources + * @return a new {@code GLShaderProgram} of compiled shaders + * @throws ShaderCompileException if compilation of any source fails + * @throws ShaderProgramLinkException if program linkage fails + * @throws NullPointerException if any key or value in map is {@code null} + */ + public static GLShaderProgram compile(Map shadersGLSL) { + IntList shaders = new IntArrayList(shadersGLSL.size()); + for (var entry : shadersGLSL.entrySet()) { + ShaderType type = Objects.requireNonNull(entry.getKey(), "One of keys in map is null"); + String code = Objects.requireNonNull(entry.getValue(), "One of values in map is null").toString(); + int shader = glCreateShader(type.getGlEnum()); + glShaderSource(shader, code); + glCompileShader(shader); + checkCompiled(shader, type.getName(), code); + shaders.add(shader); + } + GLShaderProgram result = ofCompiled(shaders); + shaders.forEach(GL20::glDeleteShader); + shaders.clear(); + return result; + } + + /** + * Creates a shader program from already-compiled shaders. + *

This method does not delete the shaders after linking; do so manually if they won't be used again. + * + * @param shaderIDs the shader IDs + * @throws IllegalArgumentException if any shader ID is invalid + * @throws ShaderProgramLinkException if program linkage fails + */ + public static GLShaderProgram ofCompiled(IntList shaderIDs) { + int program = glCreateProgram(); + shaderIDs.forEach((int shader) -> { + if (!glIsShader(shader)) { + glDeleteProgram(program); + throw new IllegalArgumentException("Invalid shader ID: 0x" + Integer.toHexString(shader).toUpperCase()); + } + glAttachShader(program, shader); + }); + glLinkProgram(program); + checkLinked(program); + shaderIDs.forEach((int shader) -> glDetachShader(program, shader)); + + return new GLShaderProgram(program); + } + + // Public API + + /** + * Starts using this program in current context. + * + * @throws IllegalStateException if this program is closed + */ + public void use() { + ensureOpen(); + glUseProgram(programId); + } + + /** + * Stops using this program in current context. + * + * @param onlyIfCurrent if {@code true}, will only stop usage when this program is currently active + * @throws IllegalStateException if {@code onlyIfCurrent == true} and this program is closed + */ + public void unuse(boolean onlyIfCurrent) { + if (onlyIfCurrent) { + ensureOpen(); + int[] currentProgram = {0}; + glGetIntegerv(GL_CURRENT_PROGRAM, currentProgram); + if (currentProgram[0] == programId) { + glUseProgram(0); + } + } else { + glUseProgram(0); + } + } + + /** + * Updates uniform variable for this program with the specified integer value. + * @param name the variable name + * @param value the value + * @return this program + */ + public GLShaderProgram setUniform(String name, int value) { + int loc = getUniformLocation(name); + if (loc != -1) glUniform1i(loc, value); + return this; + } + + /** + * Updates uniform variable for this program with the specified floating-point value. + * @param name the variable name + * @param value the value + * @return this program + */ + public GLShaderProgram setUniform(String name, float value) { + int loc = getUniformLocation(name); + if (loc != -1) glUniform1f(loc, value); + return this; + } + + /** + * Updates uniform variable for this program with the specified floating-point 2D vector components. + * @param name the variable name + * @param x the first component + * @param y the second component + * @return this program + */ + public GLShaderProgram setUniform(String name, float x, float y) { + int loc = getUniformLocation(name); + if (loc != -1) glUniform2f(loc, x, y); + return this; + } + + /** + * Updates uniform variable for this program with the specified floating-point 4D vector components. + * @param name the variable name + * @param x the first component + * @param y the second component + * @param z the third component + * @param w the fourth component + * @return this program + */ + public GLShaderProgram setUniform(String name, float x, float y, float z, float w) { + int loc = getUniformLocation(name); + if (loc != -1) glUniform4f(loc, x, y, z, w); + return this; + } + + /** + * Updates uniform variable for this program with the specified 4x4 floating-point matrix. + * @param name the variable name + * @param matrix the matrix + * @return this program + */ + public GLShaderProgram setUniform(String name, Matrix4f matrix) { + int loc = getUniformLocation(name); + if (loc != -1) { + try (var stack = stackPush()) { + FloatBuffer buf = stack.mallocFloat(16); + matrix.get(buf); + glUniformMatrix4fv(loc, false, buf); + } + } + return this; + } + + /** + * {@inheritDoc} After calling this method, the instance should no longer be used. + * Idempotent: calling this method more than once has no effect. + */ + @Override + public void close() { + if (!closed) { + glDeleteProgram(programId); + closed = true; + } + } + + // Private implementation + + private void ensureOpen() { + if (closed) { + throw new IllegalStateException("This program is closed"); + } + } + + private int getUniformLocation(String name) { + return uniformLocationsCache.computeIfAbsent(name.hashCode(), _ -> glGetUniformLocation(programId, name)); + } + + private static void checkCompiled(int shader, String type, String code) { + if (glGetShaderi(shader, GL_COMPILE_STATUS) == GL_FALSE) { + throw new ShaderCompileException( + type + " shader 0x" + Integer.toHexString(shader).toUpperCase() + " failed to compile", + code, + glGetShaderInfoLog(shader) + ); + } + } + + private static void checkLinked(int program) { + if (glGetProgrami(program, GL_LINK_STATUS) == GL_FALSE) { + int error = glGetError(); + if (error != GL_NO_ERROR) { + throw new RuntimeException("OpenGL Error after link: 0x" + Integer.toHexString(error).toUpperCase()); + } + + throw new ShaderProgramLinkException( + "Program 0x" + Integer.toHexString(program).toUpperCase() + " failed to link", + glGetProgramInfoLog(program) + ); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/ShaderCompileException.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/ShaderCompileException.java new file mode 100644 index 0000000..59b2c85 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/ShaderCompileException.java @@ -0,0 +1,35 @@ +package ru.fokinatorr.sparkle.graphics.impl.gl.shader; + +import lombok.Getter; +import lombok.experimental.FieldDefaults; + +import static lombok.AccessLevel.PRIVATE; + +/** + * Thrown by {@link GLShaderProgram}'s factory methods when shader compilation fails. + *

Includes the shader's code and error log. + */ +@FieldDefaults(makeFinal = true, level = PRIVATE) +@Getter +public class ShaderCompileException extends RuntimeException { + String shaderCode; + String errorLog; + + /** + * @param message the detail message + * @param shaderCode the shader's source code, or {@code null} if unavailable + * @param errorLog the compiler output, or {@code null} if unavailable + */ + public ShaderCompileException(String message, String shaderCode, String errorLog) { + super(message); + this.errorLog = errorLog; + this.shaderCode = shaderCode; + } + + @Override + public String getMessage() { + return super.getMessage() + + "\nError Log: " + (errorLog == null ? "" : "\n" + errorLog) + + "\nShader Code: " + (shaderCode == null ? "" : "\n" + shaderCode); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/ShaderProgramLinkException.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/ShaderProgramLinkException.java new file mode 100644 index 0000000..2bfdf55 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/ShaderProgramLinkException.java @@ -0,0 +1,31 @@ +package ru.fokinatorr.sparkle.graphics.impl.gl.shader; + +import lombok.Getter; +import lombok.experimental.FieldDefaults; + +import static lombok.AccessLevel.PRIVATE; + +/** + * Thrown by {@link GLShaderProgram}'s factory methods when shader program linking fails. + *

Includes the error log. + */ +@FieldDefaults(makeFinal = true, level = PRIVATE) +@Getter +public class ShaderProgramLinkException extends RuntimeException { + String errorLog; + + /** + * @param message the detail message + * @param errorLog the linker output, or {@code null} if unavailable + */ + public ShaderProgramLinkException(String message, String errorLog) { + super(message); + this.errorLog = errorLog; + } + + @Override + public String getMessage() { + return super.getMessage() + + "\nError Log: " + (errorLog == null ? "" : "\n" + errorLog); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/ShaderType.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/ShaderType.java new file mode 100644 index 0000000..498f599 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/shader/ShaderType.java @@ -0,0 +1,32 @@ +package ru.fokinatorr.sparkle.graphics.impl.gl.shader; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; + +import static lombok.AccessLevel.PRIVATE; +import static org.lwjgl.opengl.GL46.*; + +/** + * Represents a GL shader type. + */ +@Getter +@RequiredArgsConstructor +@FieldDefaults(makeFinal = true, level = PRIVATE) +public enum ShaderType { + VERTEX(GL_VERTEX_SHADER, "Vertex"), + FRAGMENT(GL_FRAGMENT_SHADER, "Fragment"), + TESS_CTRL(GL_TESS_CONTROL_SHADER, "Tessellation control"), + TESS_EVAL(GL_TESS_EVALUATION_SHADER, "Tessellation evaluation"), + GEOMETRY(GL_GEOMETRY_SHADER, "Geometry"), + COMPUTE(GL_COMPUTE_SHADER, "Compute"); + + /** + * The OpenGL constant for this shader type. + */ + int glEnum; + /** + * User-friendly name of this shader type. + */ + String name; +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/surface/GL_GLFWWindowSurface.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/surface/GL_GLFWWindowSurface.java new file mode 100644 index 0000000..2a7d869 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/gl/surface/GL_GLFWWindowSurface.java @@ -0,0 +1,104 @@ +package ru.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 static org.lwjgl.glfw.GLFW.*; +import static org.lwjgl.system.MemoryUtil.NULL; + +/** + * A GLFW window rendering surface, providing GL framebuffers. + */ +@Slf4j +@FieldDefaults(level = AccessLevel.PRIVATE) +public final class GL_GLFWWindowSurface extends AbstractGLFWWindowSurface { + + /** + * @throws NullPointerException if any argument is {@code null} + */ + GL_GLFWWindowSurface(long glfwWindow, EventDispatcher dispatcher, Stage stage, Thread graphicsThread) { + super(glfwWindow, dispatcher, stage, graphicsThread); + glfwMakeContextCurrent(glfwWindow); + glfwSwapInterval(1); + } + + + /** + * Creates a new non-fullscreen window. + * + * @param title the window title + * @param translucent whether the window must be translucent + * @param dispatcher the event dispatcher to use for sending window events + * @param stage the stage to use for sending window events + * @param graphicsThread the thread on which all calls must be made + * @return a new window surface + */ + public static GL_GLFWWindowSurface create(String title, boolean translucent, + EventDispatcher dispatcher, Stage stage, Thread graphicsThread) { + 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) { + glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE); + glfwWindowHint(GLFW_DECORATED, GLFW_TRUE); + } + return result; + } + + /** + * Creates a new fullscreen window. + * + * @param title the window title + * @param translucent whether the window must be translucent + * @param monitor the GLFW monitor on which the window should be fullscreen + * @param dispatcher the event dispatcher to use for sending window events + * @param stage the stage to use for sending window events + * @param graphicsThread the thread on which all calls must be made + * @return a new window surface + */ + public static GL_GLFWWindowSurface createFullscreen(String title, long monitor /*pointer*/, boolean translucent, + EventDispatcher dispatcher, Stage stage, Thread graphicsThread) { + 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) { + glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE); + glfwWindowHint(GLFW_DECORATED, GLFW_TRUE); + } + return result; + } + + @Override + public Framebuffer acquireBuffer() { + Point2D dim = getSize(); + return new GLFramebuffer(0, (int) dim.x(), (int) dim.y()); + } + + @Override + public void present(Framebuffer frameBuffer) { + if (!(frameBuffer instanceof GLFramebuffer fb)) { + throw new IllegalArgumentException("Unsupported frame buffer type: " + frameBuffer.getClass()); + } + if (fb.fboId() != 0) { + throw new IllegalArgumentException("Can only render from the default framebuffer"); + } + glfwSwapBuffers(glfwWindow); + } +} \ No newline at end of file diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/surface/AbstractGLFWWindowSurface.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/surface/AbstractGLFWWindowSurface.java new file mode 100644 index 0000000..e3bdee8 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/surface/AbstractGLFWWindowSurface.java @@ -0,0 +1,377 @@ +package ru.fokinatorr.sparkle.graphics.impl.surface; + +import lombok.AccessLevel; +import lombok.Getter; +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 java.util.*; +import java.util.concurrent.atomic.AtomicLong; + +import static org.lwjgl.glfw.GLFW.*; +import static org.lwjgl.system.MemoryUtil.NULL; + +/** + * A GLFW window rendering surface, providing base GLFW functionality, + * except framebuffer-related methods. + */ +@Slf4j +@FieldDefaults(level = AccessLevel.PROTECTED) +public abstract class AbstractGLFWWindowSurface implements WindowSurface { + /** + * The GLFW window pointer. + */ + @Getter + final long glfwWindow; // pointer + final List resizeCallback = new LinkedList<>(); + final List callbacks = new LinkedList<>(); + final Thread graphicsThread; + Callback resizeCB; + int[] oldXYWH = null; + boolean closed; + + + /** + * @throws NullPointerException if any argument is {@code null} + */ + protected AbstractGLFWWindowSurface(long glfwWindow, EventDispatcher dispatcher, Stage stage, Thread graphicsThread) { + if (glfwWindow == NULL) { + throw new NullPointerException("glfwWindow"); + } + this.glfwWindow = glfwWindow; + Objects.requireNonNull(dispatcher, "dispatcher"); + Objects.requireNonNull(stage, "stage"); + this.graphicsThread = Objects.requireNonNull(graphicsThread, "graphics thread"); + + // + callbacks.add(glfwSetKeyCallback(glfwWindow, (_, keyCode, scancode, action, modifiers) -> { + Key key = GLFWToPublicAPI.KEYS_MAP.get(keyCode); + if (key != null) { + switch (action) { + case GLFW_PRESS -> { + if (dispatcher.hasListenersFor(KeyboardEvent.KeyPressedEvent.class)) { + dispatcher.fireEvent(new KeyboardEvent.KeyPressedEvent(stage, key, modifiers)); + } + } + case GLFW_RELEASE -> { + if (dispatcher.hasListenersFor(KeyboardEvent.KeyReleasedEvent.class)) { + dispatcher.fireEvent(new KeyboardEvent.KeyReleasedEvent(stage, key, modifiers)); + } + } + case GLFW_REPEAT -> { + if (dispatcher.hasListenersFor(KeyboardEvent.KeyRepeatedEvent.class)) { + dispatcher.fireEvent(new KeyboardEvent.KeyRepeatedEvent(stage, key, modifiers)); + } + } + } + } else { + log.warn( + "Unknown key with scancode {} {}", + scancode, + switch (action) { + case GLFW_PRESS -> "pressed"; + case GLFW_RELEASE -> "released"; + case GLFW_REPEAT -> "repeated"; + default -> ""; + } + ); + } + })); + + callbacks.add(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, _) -> { + 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; + switch (action) { + case GLFW_PRESS -> { + lastMousePress.set(System.nanoTime()); + if (dispatcher.hasListenersFor(MouseEvent.MousePressedEvent.class)) { + dispatcher.fireEvent(new MouseEvent.MousePressedEvent(button, stage, x, y)); + } + } + case GLFW_RELEASE -> { + if (dispatcher.hasListenersFor(MouseEvent.MouseReleasedEvent.class)) { + dispatcher.fireEvent(new MouseEvent.MouseReleasedEvent(button, stage, x, y)); + } + 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)); + } + } + } + } + })); + + 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; + Set pressedButtons = EnumSet.noneOf(MouseButton.class); + for (int mb : GLFWToPublicAPI.MOUSE_BUTTONS_MAP.keySet()) { + if (glfwGetMouseButton(glfwWindow, mb) == GLFW_PRESS) { + pressedButtons.add(GLFWToPublicAPI.MOUSE_BUTTONS_MAP.get(mb)); + } + } + + dispatcher.fireEvent(new MouseEvent.MouseCursorMovedEvent(stage, oldX, oldY, newX, newY, pressedButtons)); + } + })); + + callbacks.add(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)); + } + })); + // + } + + @Override + public int getWidth() { + ensureOpen(); + ensureOnCorrectThread(); + int[] w = {0}; + glfwGetWindowSize(glfwWindow, w, null); + return w[0]; + } + + @Override + public int getHeight() { + ensureOpen(); + ensureOnCorrectThread(); + int[] h = {0}; + glfwGetWindowSize(glfwWindow, null, h); + return h[0]; + } + + @Override + public Point2D getSize() { + ensureOpen(); + ensureOnCorrectThread(); + int[] w = {0}, h = {0}; + glfwGetWindowSize(glfwWindow, w, h); + return new Point2D(w[0], h[0]); + } + + @Override + public void pollEvents() { + ensureOpen(); + ensureOnCorrectThread(); + glfwPollEvents(); + } + + @Override + public boolean shouldClose() { + ensureOpen(); +// ensureOnCorrectThread(); + return glfwWindowShouldClose(glfwWindow); + } + + @Override + public void onResize(ResizeListener callback) { + ensureOpen(); + ensureOnCorrectThread(); + resizeCallback.add(callback); + Callback newCB = glfwSetWindowSizeCallback(glfwWindow, (_, width, height) -> { + for (var cb : resizeCallback) { + cb.resized(this, width, height); + } + }); + if (resizeCB != null) resizeCB.free(); + resizeCB = newCB; + } + + @Override + public Set getFeatures() { + return Collections.unmodifiableSet(EnumSet.of( + Feature.RESIZABLE, + Feature.MOVABLE, + Feature.HIDEABLE, + Feature.NAMEABLE, + Feature.FULLSCREENABLE, + Feature.TRANSLUCENT + )); + } + + @Override + public void setSize(int newWidth, int newHeight) { + ensureOpen(); + ensureOnCorrectThread(); + glfwSetWindowSize(glfwWindow, newWidth, newHeight); + } + + @Override + public int getX() { + ensureOpen(); + ensureOnCorrectThread(); + int[] x = {0}; + glfwGetWindowPos(glfwWindow, x, null); + return x[0]; + } + + @Override + public int getY() { + ensureOpen(); + ensureOnCorrectThread(); + int[] y = {0}; + glfwGetWindowPos(glfwWindow, null, y); + return y[0]; + } + + @Override + public Point2D getPos() { + ensureOpen(); + ensureOnCorrectThread(); + int[] x = {0}, y = {0}; + glfwGetWindowPos(glfwWindow, x, y); + return new Point2D(x[0], y[0]); + } + + @Override + public void setPos(int newX, int newY) { + ensureOpen(); + ensureOnCorrectThread(); + glfwSetWindowPos(glfwWindow, newX, newY); + } + + @Override + public boolean isHidden() { + ensureOpen(); + ensureOnCorrectThread(); + return glfwGetWindowAttrib(glfwWindow, GLFW_VISIBLE) == GLFW_TRUE; + } + + @Override + public void show() { + ensureOpen(); + ensureOnCorrectThread(); + glfwShowWindow(glfwWindow); + } + + @Override + public void hide() { + ensureOpen(); + ensureOnCorrectThread(); + glfwHideWindow(glfwWindow); + } + + @Override + public String getName() { + ensureOpen(); + ensureOnCorrectThread(); + return glfwGetWindowTitle(glfwWindow); + } + + @Override + public void setName(String name) { + ensureOpen(); + ensureOnCorrectThread(); + glfwSetWindowTitle(glfwWindow, name); + } + + @Override + public boolean isFullscreen() { + ensureOpen(); + ensureOnCorrectThread(); + return glfwGetWindowMonitor(glfwWindow) != NULL; + } + + @Override + public void setFullscreen(boolean fullscreen) { + ensureOpen(); + ensureOnCorrectThread(); + GLFWVidMode vidMode = glfwGetVideoMode(glfwGetPrimaryMonitor()); + if (vidMode == null) { + throw new IllegalStateException("GLFW error"); + } + if (fullscreen) { + Point2D pos = getPos(), dimensions = getSize(); + oldXYWH = new int[]{(int) pos.x(), (int) pos.y(), (int) dimensions.x(), (int) dimensions.y()}; + glfwSetWindowMonitor( + glfwWindow, + glfwGetPrimaryMonitor(), + 0, 0, + vidMode.width(), vidMode.height(), + vidMode.refreshRate() + ); + } else { + glfwSetWindowMonitor( + glfwWindow, + NULL, + oldXYWH[0], oldXYWH[1], + oldXYWH[2], oldXYWH[3], + vidMode.refreshRate() + ); + oldXYWH = null; + } + } + + @Override + public boolean isTranslucent() { + ensureOpen(); + ensureOnCorrectThread(); + return glfwGetWindowAttrib(glfwWindow, GLFW_TRANSPARENT_FRAMEBUFFER) == GLFW_TRUE; + } + + @Override + public void close() { + if (!closed) { + if (resizeCB != null) { + resizeCB.free(); + resizeCB = null; + } + callbacks.forEach(callback -> { + if (callback != null) { + callback.free(); + } + }); + callbacks.clear(); + glfwDestroyWindow(glfwWindow); + closed = true; + } + } + + protected void ensureOpen() { + if (closed) { + throw new IllegalStateException("Window closed"); + } + } + + protected void ensureOnCorrectThread() { + if (Thread.currentThread() != graphicsThread) { + throw new IllegalCallerException("Called from incorrect thread; must call from " + graphicsThread); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/impl/surface/GLFWToPublicAPI.java b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/surface/GLFWToPublicAPI.java new file mode 100644 index 0000000..8f92116 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/impl/surface/GLFWToPublicAPI.java @@ -0,0 +1,266 @@ +package ru.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 static org.lwjgl.glfw.GLFW.*; + +/** + * Maps GLFW key & mouse button codes to public API enums. + * + * @see Key + * @see MouseButton + */ +@UtilityClass +public class GLFWToPublicAPI { + + /** + * GLFW key code -> {@link Key} instance + */ + public static final Int2ObjectMap KEYS_MAP; + /** + * GLFW mouse button code -> {@link MouseButton} instance + */ + public static final Int2ObjectMap MOUSE_BUTTONS_MAP; + + static { + Int2ObjectMap k = new Int2ObjectOpenHashMap<>(Key.values().length); + // Here goes hell. Wish there was a faster way of doing that... + k.put(GLFW_KEY_SPACE, Key.SPACE); // %20 in URL + k.put(GLFW_KEY_APOSTROPHE, Key.APOSTROPHE); // ' (" when shift down) + k.put(GLFW_KEY_COMMA, Key.COMMA); // , (< with shift) + k.put(GLFW_KEY_MINUS, Key.MINUS); // - (_ with shift) + k.put(GLFW_KEY_PERIOD, Key.PERIOD); // . (>) + k.put(GLFW_KEY_SLASH, Key.SLASH); // / (?) + // digits + k.put(GLFW_KEY_0, Key.KEY_0); // 0 or ) + k.put(GLFW_KEY_1, Key.KEY_1); // 1 or ! + k.put(GLFW_KEY_2, Key.KEY_2); // 2 or @ + k.put(GLFW_KEY_3, Key.KEY_3); // 3 or # + k.put(GLFW_KEY_4, Key.KEY_4); // 4 or $ + k.put(GLFW_KEY_5, Key.KEY_5); // 5 or % + k.put(GLFW_KEY_6, Key.KEY_6); // 6 or ^ + k.put(GLFW_KEY_7, Key.KEY_7); // 7 or & + k.put(GLFW_KEY_8, Key.KEY_8); // 8 or * + k.put(GLFW_KEY_9, Key.KEY_9); // 9 or ( + + k.put(GLFW_KEY_SEMICOLON, Key.SEMICOLON); // ; or : + k.put(GLFW_KEY_EQUAL, Key.EQUALS); // = or + + // alphabet lore + k.put(GLFW_KEY_A, Key.A); + k.put(GLFW_KEY_B, Key.B); + k.put(GLFW_KEY_C, Key.C); + k.put(GLFW_KEY_D, Key.D); + k.put(GLFW_KEY_F, Key.F); // F, the villain, comes and kidnaps D + k.put(GLFW_KEY_E, Key.E); // and also F kidnaps E + k.put(GLFW_KEY_G, Key.G); // G is frustrated! He calls A, B and C to form a CAB and follow F + k.put(GLFW_KEY_H, Key.H); // F hides behind H, G doesn't notice. F escapes + k.put(GLFW_KEY_I, Key.I); // F stomps on I and uses it as a gun + k.put(GLFW_KEY_J, Key.J); // "J" famous last words + // G is looking for F... hears a sudden blast + k.put(GLFW_KEY_K, Key.K); // K appears and laughs at J's sudden death. F uses K as wings + // G arrives with his CAB. F points his gun at them. Who's going to save them?.. + // ... + k.put(GLFW_KEY_L, Key.L); // L He saved G and CAB from getting obliterated by F! + k.put(GLFW_KEY_M, Key.M); // M also transforms and detaches K from F + k.put(GLFW_KEY_N, Key.N); // N also transforms, tries to save I from F. F blows onto N's hair and N awkwardly runs away + k.put(GLFW_KEY_O, Key.O); // Wheel! Oh no wait, it's O. He says "OOOOOOOOOOO" and transforms :P + // F seems tired from these transformations + k.put(GLFW_KEY_P, Key.P); // P transforms! L M N O P are all here! but wait F escaped :\ + k.put(GLFW_KEY_Q, Key.Q); // KYOOOOOOOOOOO + // Hold up! Someone stole N's gem! He transforms back into his normal form. L and O look angrily at him + // Meanwhile F, in his cave, where D, E, and I are chained to the walls, evilly smiles, looking at N's gem... + k.put(GLFW_KEY_R, Key.R); // "A-a-ar?!" - says R before immediately getting kidnapped by F + // L and O kick N because he lost his gem, then fly away. N lies on the ground, depressed. P cheers him up. + // the CAB deforms back to letters; then M, A and P form a MAP. G takes it and sees F running towards S. They all + // sit into the CAB and start chasing F. Meanwhile Q, being a slow snail, tries his best to catch-up... + k.put(GLFW_KEY_S, Key.S); // "Essss-" says S before getting sucked by F like spaghetti ._. + // L and O approach F faster than others, freeze F into place. But F uses N's gem to neutralize L and O by gluing them together >:) + // For good measure F also steals L and O's gems... + k.put(GLFW_KEY_T, Key.T); // T appears and says "Tea!". F smashes T into the ground like a nail + // G, P, N and M arrive on a CAB. M, A and P create a MAP again. G takes it, sees that F conjoined B and C with O's gem. + // G was too late to realize F is right in front of him... then F froze G with L's gem... + + // N, scared of F, hides behind G + // M tried to defeat F using his powers... He transforms, jumps and... gets his gem unfairly stolen! F uses it to conjoin T, M and A. + // P joins! She transforms and starts quickly knocking F onto the ground! But F uses M's gem to freeze her! + // F starts looking for N. N is horrified. C notices that, starts crawling towards F. When he finally reaches him, he bites him. + // F screams in pain, turns around and... literally rips C into pieces with his teeth. Everybody watches that in terror, unable to move, + // everyone except N... who didn't move just because he was a coward... + // ... + // F finally flies away, leaving the letters with pain of C getting brutally murdered... G and N decided to take revenge. + k.put(GLFW_KEY_U, Key.U); // They started looking for U to form a GUN and hunt F down. + k.put(GLFW_KEY_V, Key.V); // V-v-v-vee! - says V. Suddenly, F appears; V starts shaking in fear... + // G with a GUN notices F approaching V. He charges up the GUN and says "GG", then shoots F... + // G, U and N come closer, then they notice that it wasn't F... it was P, bitten by F so that she looked like F... + // G screams... "P, P, NO!!! DON'T LEAVE US! F, YOU WILL REGRET THIS!!" while F is watching them from above, evilly smiling, + // then runs towards his cave... + k.put(GLFW_KEY_W, Key.W); // N thinks how much of a coward he was... because of him, C and P were murdered by F, and he... + // he was just hiding behind G the whole time, not even helping... coward... coward... + // Suddenly, G wakes N up from his thoughts, pointing to F's cave. N decided to take revenge for P and C and drives towards the cave. + k.put(GLFW_KEY_X, Key.X); // Meanwhile, F, running towards his cave, is stopped by X. X, with his power gem, starts replicating + // and surrounded F with his clones. F, noticing that, drops all his stolen gems, knowing that X prefers fair fights. X also dropped + // his gem, and the clones disappeared. X thought they're going to fight fairly, but F cheated... he bit X and stole his gem too... + k.put(GLFW_KEY_Y, Key.Y); // Y sees X deceased, falls on her knees are screams "WHYYYYYYYYYY!!??" + // Meanwhile, V, A, G, N, U and M entered F's cave, where his clones were everywhere, waiting for them to enter. + // While everybody was walking, F's clones absorbed everyone except N. F only needed him now... + // N noticed F dropped the gems and started picking them up. Then, he notices sawblades running towards him... he picks up + // P's gem and started running away. Suddenly, the sawblades stopped. N couldn't go back anymore. + // F used X's gem to point to some place. But N, blinded by a thirst for revenge, didn't understand F's sign... N used + // all of his gems to create a powerful beam and shoot F with it. F, clearly shocked, was smashed against the wall, and died in agony... + // N thought the villain is defeated, came to pick up X's gem, but then he noticed... Him, F and all the kidnapped letters formed + // the word... FRIENDS. Something was clearly off, nobody understood what that meant... until Q finally came into the cave, very slowly. + + // -- FLASHBACK... -- + // n, e, d, i, s, r and f, when they were children, were friends. once upon a time they peacefully played around. then o and l came, + // clearly wanting to bully them. l used o to shoot into one of the letters... Everyone ran away except f and n, so l shoot o into n... + // n fell onto the ground, while l and o were laughing. then f came to cheer n up. They used to be best friends... + // f, wanting to avenge n, took a, r, and t to form a fart and make it look like l is farting. Everyone saw that and started laughing... + // f and n were lying on the ground and laughing harder than anyone else. l and o became furious, they kicked f so hard he cried... + // then l pushed f to other letters to form the word "frick"... o came and said "Look everybody, f is slurring!" Everybody's rage + // turned against f. c bit him; j shot at his teeth and broke them; i, m, x, t, e and d also punched f, then f tripped against n + // and fell over... n tried to help, but the letters stood behind him. n, seeing this, stood back and hid behind the letters... + // f, seeing that even his best friend betrayed him, started intensely crying: "I hate every one of you!!!", running towards a cave, + // planning to live there alone, isolated... + // g and p weren't there. they never bullied f... + // That's how F became a villain and L M N O P got superpowers. Villains are not born, they're made by people, by bullies... + k.put(GLFW_KEY_Z, Key.Z); // And what about Z? Z always was with us. He is the planet. Watching everybody fight, unable to stop them... + // end of alphabet lore...? + // credits to Mike Salcedo (https://www.youtube.com/channel/UCZESvFbPmlmF9rnT4Ke1uKQ) for such an amazing and enlightening story. + + k.put(GLFW_KEY_LEFT_BRACKET, Key.LEFT_SQUARE_BRACKET); // [ ({) + k.put(GLFW_KEY_BACKSLASH, Key.BACKSLASH); // \ (|) + k.put(GLFW_KEY_RIGHT_BRACKET, Key.RIGHT_SQUARE_BRACKET); // ] (}) + k.put(GLFW_KEY_GRAVE_ACCENT, Key.GRAVE_ACCENT); // ` (~) + k.put(GLFW_KEY_ESCAPE, Key.ESCAPE); + + // These two keys don't have a US keyboard mapping, and are rarely used + k.put(GLFW_KEY_WORLD_1, Key.WORLD_1); + k.put(GLFW_KEY_WORLD_2, Key.WORLD_2); + + // purely functionality keys, no character representation + k.put(GLFW_KEY_ENTER, Key.ENTER); // CR+LF on Windows/macOS, LF on Linux, CR on old macOS + k.put(GLFW_KEY_TAB, Key.TAB); // exception: often inserts a tabulation character + k.put(GLFW_KEY_BACKSPACE, Key.BACKSPACE); // erase left + k.put(GLFW_KEY_INSERT, Key.INSERT); // switch between insert/overwrite character mode + k.put(GLFW_KEY_DELETE, Key.DELETE); // erase right + + // arrow keys + k.put(GLFW_KEY_RIGHT, Key.RIGHT); + k.put(GLFW_KEY_LEFT, Key.LEFT); + k.put(GLFW_KEY_DOWN, Key.DOWN); + k.put(GLFW_KEY_UP, Key.UP); + + // navigation keys (similar to arrow keys, but go farther) + k.put(GLFW_KEY_PAGE_UP, Key.PAGE_UP); // one segment up + k.put(GLFW_KEY_PAGE_DOWN, Key.PAGE_DOWN); // one segment down + k.put(GLFW_KEY_HOME, Key.HOME); // all the way left + k.put(GLFW_KEY_END, Key.END); // all the way right + + // lock keys + k.put(GLFW_KEY_CAPS_LOCK, Key.CAPS_LOCK); // If enabled, capitalization of letters is reversed + k.put(GLFW_KEY_SCROLL_LOCK, Key.SCROLL_LOCK); // Used to make arrow keys scroll the page instead of moving cursor; mostly not used nowadays + k.put(GLFW_KEY_NUM_LOCK, Key.NUM_LOCK); // See numpad keys below + + // miscellaneous + k.put(GLFW_KEY_PRINT_SCREEN, Key.PRINT_SCREEN); // AKA SysRq when you hold Shift + k.put(GLFW_KEY_PAUSE, Key.PAUSE); // AKA Break + + // function keys ^u^ + k.put(GLFW_KEY_F1, Key.F1); // help + k.put(GLFW_KEY_F2, Key.F2); // rename file + k.put(GLFW_KEY_F3, Key.F3); // Opens up Minecraft cheat menu + k.put(GLFW_KEY_F4, Key.F4); // This key is very important because Alt+F4 + k.put(GLFW_KEY_F5, Key.F5); // reload + k.put(GLFW_KEY_F6, Key.F6); + k.put(GLFW_KEY_F7, Key.F7); + k.put(GLFW_KEY_F8, Key.F8); + k.put(GLFW_KEY_F9, Key.F9); + k.put(GLFW_KEY_F10, Key.F10); + k.put(GLFW_KEY_F11, Key.F11); // fullscreen mode + k.put(GLFW_KEY_F12, Key.F12); // the last one?... + k.put(GLFW_KEY_F13, Key.F13); // ABSOLUTELY NOT! + k.put(GLFW_KEY_F14, Key.F14); // nobody EVER uses this + k.put(GLFW_KEY_F15, Key.F15); // because these keys + k.put(GLFW_KEY_F16, Key.F16); // do not exist + k.put(GLFW_KEY_F17, Key.F17); // on most modern keyboards + k.put(GLFW_KEY_F18, Key.F18); // But GLFW is kind enough + k.put(GLFW_KEY_F19, Key.F19); // to provide bindings + k.put(GLFW_KEY_F20, Key.F20); // for every single + k.put(GLFW_KEY_F21, Key.F21); // historically existed function key + k.put(GLFW_KEY_F22, Key.F22); + k.put(GLFW_KEY_F23, Key.F23); + k.put(GLFW_KEY_F24, Key.F24); + k.put(GLFW_KEY_F25, Key.F25); // the ACTUAL last function key + + // Numpad keys! Without Num Lock, they're function keys; with Num Lock, they're printable keys :D + k.put(GLFW_KEY_KP_0, Key.NUMPAD_0); // AKA Insert without Num Lock + k.put(GLFW_KEY_KP_1, Key.NUMPAD_1); // AKA End without Num Lock + k.put(GLFW_KEY_KP_2, Key.NUMPAD_2); // AKA Down arrow without Num Lock + k.put(GLFW_KEY_KP_3, Key.NUMPAD_3); // Page down + k.put(GLFW_KEY_KP_4, Key.NUMPAD_4); // Left arrow + k.put(GLFW_KEY_KP_5, Key.NUMPAD_5); // Doesn't do anything without Num Lock... or, Does It?? + k.put(GLFW_KEY_KP_6, Key.NUMPAD_6); // Right Arrow + k.put(GLFW_KEY_KP_7, Key.NUMPAD_7); // Home + k.put(GLFW_KEY_KP_8, Key.NUMPAD_8); // Up Arrow + k.put(GLFW_KEY_KP_9, Key.NUMPAD_9); // Page up + k.put(GLFW_KEY_KP_DECIMAL, Key.NUMPAD_DECIMAL_POINT); // Delete key + + // these are technically function keys, but they usually insert characters + k.put(GLFW_KEY_KP_DIVIDE, Key.NUMPAD_DIVIDE); + k.put(GLFW_KEY_KP_MULTIPLY, Key.NUMPAD_MULTIPLY); + k.put(GLFW_KEY_KP_SUBTRACT, Key.NUMPAD_SUBTRACT); + k.put(GLFW_KEY_KP_ADD, Key.NUMPAD_ADD); + + 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... + + // 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); + k.put(GLFW_KEY_RIGHT_SHIFT, Key.RIGHT_SHIFT); + + // normal guys again. Apple just decided to stand out and named it "Option"... + k.put(GLFW_KEY_LEFT_ALT, Key.LEFT_ALT); + k.put(GLFW_KEY_RIGHT_ALT, Key.RIGHT_ALT); + + // These would be NORMAL until Apple decided to stand out AGAIN and say "We're swapping the meaning of Control and Command" >:( + k.put(GLFW_KEY_LEFT_CONTROL, Key.LEFT_CONTROL); + k.put(GLFW_KEY_RIGHT_CONTROL, Key.RIGHT_CONTROL); + + // This key has so many names we could barely decide on which one to use... anyway, we chose "Meta" cos it's the first ever name for this key. + // Every single OS has its own interpretation of Meta. + // macOS uses it for shortcuts and calls it "Command" + // Microsoft was lazy and literally called it "Windows" key; there it's used for OS-level functions + // Most Linux distros call it "Super"; some call it "Meta" + // In conclusion... only ever use this key if the current platform is macOS. Otherwise, avoid using it altogether + k.put(GLFW_KEY_LEFT_SUPER, Key.LEFT_META); + k.put(GLFW_KEY_RIGHT_SUPER, Key.RIGHT_META); + + // This key doesn't even exist on Macs! It exists only on Windows and Linux. There, it brings up the context menu + // So it's basically an alternative to the right mouse button + k.put(GLFW_KEY_MENU, Key.MENU); + + + KEYS_MAP = Int2ObjectMaps.unmodifiable(k); + + + Int2ObjectMap mb = new Int2ObjectOpenHashMap<>(MouseButton.values().length); + // standard buttons + mb.put(GLFW_MOUSE_BUTTON_LEFT, MouseButton.LEFT); + mb.put(GLFW_MOUSE_BUTTON_MIDDLE, MouseButton.MIDDLE); // usually the wheel + mb.put(GLFW_MOUSE_BUTTON_RIGHT, MouseButton.RIGHT); + // extra buttons; their name and purpose varies, and they don't appear on older mice + mb.put(GLFW_MOUSE_BUTTON_4, MouseButton.BUTTON_4); + mb.put(GLFW_MOUSE_BUTTON_5, MouseButton.BUTTON_5); + mb.put(GLFW_MOUSE_BUTTON_6, MouseButton.BUTTON_6); + mb.put(GLFW_MOUSE_BUTTON_7, MouseButton.BUTTON_7); + mb.put(GLFW_MOUSE_BUTTON_8, MouseButton.BUTTON_8); + MOUSE_BUTTONS_MAP = Int2ObjectMaps.unmodifiable(mb); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/io/ImageDecoder.java b/src/main/java/ru/fokinatorr/sparkle/graphics/io/ImageDecoder.java new file mode 100644 index 0000000..80f9c44 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/io/ImageDecoder.java @@ -0,0 +1,4 @@ +package ru.fokinatorr.sparkle.graphics.io; + +public interface ImageDecoder { +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/render/RenderCanvas.java b/src/main/java/ru/fokinatorr/sparkle/graphics/render/RenderCanvas.java new file mode 100644 index 0000000..9608348 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/render/RenderCanvas.java @@ -0,0 +1,491 @@ +package ru.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 java.awt.Shape; +import java.awt.geom.Ellipse2D; +import java.awt.geom.Line2D; +import java.awt.geom.Rectangle2D; +import java.util.Objects; + +/** + * A canvas for 2D rendering operations. + *

+ * 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()}. + * + *

Coordinate System

+ * The coordinate system uses floating-point coordinates where {@code (0, 0)} is typically the + * top-left corner of the rendering surface. Positive X extends right and positive Y extends down. + *

Note for Scratchers: This is different from Scratch's coordinate system. In Scratch, {@code (0, 0)} + * is the center of the stage, positive X values extend right and positive Y values extend up. To get + * the center coordinates, use {@link #getDimensions()} to get the width & height of the canvas + * and divide these values by 2. Vanilla renderers handle conversion between these systems automatically; + * custom renderers must do this manually. + * + *

Graphics State

+ * The render canvas maintains a state that includes: + *
    + *
  • Current transformation matrix ({@link #translate translation}, {@link #rotate rotation}, {@link #scale scaling})
  • + *
  • Current {@link #setFillARGB fill} and {@link #setStrokeARGB stroke} colors
  • + *
  • {@link #setLineWidth Line width}
  • + *
  • {@link #setAlpha Alpha} (transparency) value
  • + *
  • {@link #setBlendMode Blend mode}
  • + *
  • {@link #setEffects Graphic effects}
  • + *
  • Current {@link #clip clipping region}
  • + *
+ * This state can be pushed onto the stack with {@link #save()} and popped & restored with {@link #restore()}. + * + *

Color Representation

+ * Colors are represented as ARGB integers where: + *
    + *
  • Bits 0-7: Alpha (opacity) + * component (0 = fully transparent, 255 = fully opaque)
  • + *
  • Bits 8-15: Red component
  • + *
  • Bits 16-23: Green component
  • + *
  • Bits 24-31: Blue component
  • + *
+ * + *

Blend Modes

+ * Blend modes control how new pixels are combined with existing pixels in the framebuffer. + * Available modes include: + *
    + *
  • {@link BlendMode#ADD}: Adds color components together
  • + *
  • {@link BlendMode#BLEND_SUBTRACT}: Subtracts color components (true subtractive)
  • + *
  • {@link BlendMode#RGB_SUBTRACT}: Subtracts RGB components, adds alpha (layered subtractive)
  • + *
  • {@link BlendMode#BLEND_MULTIPLY}: Multiplies all components (true multiplicative)
  • + *
  • {@link BlendMode#RGB_MULTIPLY}: Multiplies RGB components, adds alpha (layered multiplicative)
  • + *
+ * + *

See {@link ARGB} for utility methods to work with ARGB colors, an explanation of layered/true blending types, + * and more info about ARGB format.

+ * + *

Resource Management

+ * The render canvas may hold native resources that should be released by calling {@link #close()}. + * + * @see ARGB + * @see BlendMode + * @see NonThrowingAutoCloseable + */ +public interface RenderCanvas extends NonThrowingAutoCloseable { + + /** + * Pass this constant to width / height arguments of {@link #drawImage(Image, double, double, double, double)} + * to prefer the original width / height of the image. + */ + double ORIGINAL_SIZE = -1; + + // Drawing + + /** + * Draws an image at the specified position with the given size. + * + * @param image the image to draw + * @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 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) + * @see #drawImage(Image, Point2D, Point2D) + */ + void drawImage(Image image, double x, double y, double w, double h); + + /** + * Draws an outline of the specified shape as specified in {@link #drawShape(Shape)} and fills it using the current + * {@link #setFillARGB fill color} and {@link #setBlendMode blend mode}. + * + * @param shape the shape to fill + * @throws NullPointerException if shape is {@code null} + * @see #drawShape(Shape) + * @see #setFillARGB(int) + * @see #setBlendMode(BlendMode) + */ + void fillShape(Shape shape); + + /** + * Draws the outline of the specified shape using the current {@link #setStrokeARGB stroke color}, + * {@link #setLineWidth line width} and {@link #setBlendMode blend mode}. + * + * @param shape the shape to draw + * @throws NullPointerException if shape is {@code null} + * @see #setStrokeARGB(int) + * @see #setLineWidth(double) + * @see #setBlendMode(BlendMode) + */ + void drawShape(Shape shape); + + // + + /** + * Vector version of {@link #drawImage(Image, double, double, double, double)}. + * @param image the image to draw + * @param topLeft the top-left corner coordinates + * @param deltaSize the preferred dimensions of the image + * @throws NullPointerException if any argument is {@code null} + */ + default void drawImage(Image image, Point2D topLeft, Point2D deltaSize) { + drawImage(image, topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y()); + } + + /** + * Draws an outline of a rectangle with the given position and dimensions as specified in {@link #drawShape(Shape)} and fills it + * as specified in {@link #fillShape(Shape)}. + * @param x the X coordinate of the top-left corner + * @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} + * @see #drawShape(Shape) + * @see #fillShape(Shape) + */ + default void fillRect(double x, double y, double w, double h) { + fillShape(new Rectangle2D.Double(x, y, w, h)); + } + /** + * Vector version of {@link #fillRect(double, double, double, double)}. + * @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} + */ + default void fillRect(Point2D topLeft, Point2D deltaSize) { + fillRect(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y()); + } + /** + * Draws an outline of a rectangle with the given position and dimensions as specified in {@link #drawShape(Shape)}. + * @param x the X coordinate of the top-left corner + * @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} + * @see #drawShape(Shape) + */ + default void drawRect(double x, double y, double w, double h) { + drawShape(new Rectangle2D.Double(x, y, w, h)); + } + /** + * Vector version of {@link #drawRect(double, double, double, double)}. + * @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} + */ + default void drawRect(Point2D topLeft, Point2D deltaSize) { + drawRect(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y()); + } + /** + * Draws a line from one position to another as specified in {@link #drawShape(Shape)}. + * @param x1 the X coordinate of the first position + * @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} + * @see #drawShape(Shape) + */ + default void drawLine(double x1, double y1, double x2, double y2) { + drawShape(new Line2D.Double(x1, y1, x2, y2)); + } + /** + * Vector version of {@link #drawLine(double, double, double, double)}. + * @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} + */ + default void drawLine(Point2D first, Point2D second) { + drawLine(first.x(), first.y(), second.x(), second.y()); + } + /** + * Draws an outline of an oval with the given position and dimensions as specified in {@link #drawShape(Shape)} and fills it + * as specified in {@link #fillShape(Shape)}. + * @param x the X coordinate of the top-left corner + * @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} + * @see #drawShape(Shape) + * @see #fillShape(Shape) + */ + default void fillOval(double x, double y, double w, double h) { + fillShape(new Ellipse2D.Double(x, y, w, h)); + } + /** + * Vector version of {@link #fillOval(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} + */ + default void fillOval(Point2D topLeft, Point2D deltaSize) { + fillOval(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y()); + } + /** + * Draws an outline of an oval with the given position and dimensions as specified in {@link #drawShape(Shape)}. + * @param x the X coordinate of the top-left corner + * @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} + * @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} + */ + default void drawOval(Point2D topLeft, Point2D deltaSize) { + drawOval(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y()); + } + // + + // State management + + /** + * Saves the current graphics state (transformations, styling, clipping) onto a stack. + * The state can be restored later using {@link #restore()}. + * + * @see #restore() + * @see #translate(double, double) + * @see #rotate(double) + * @see #scale(double, double) + */ + void save(); + + /** + * Restores the most recently saved graphics state from the stack. + * This reverts all transformations, styling, and clipping to their values when + * {@link #save()} was last called. + * + * @throws IllegalStateException if the state stack is empty + * @see #save() + */ + void restore(); + + /** + * Resets the current graphics state to default values. Useful for finer control over texture/primitive position, + * rotation, scale, etc. + */ + void setIdentity(); + + /** + * Translates the coordinate system by the specified amounts (subsequent drawing operations will be offset by {@code (dx, dy)}). + * @param dx the distance to translate along X axis + * @param dy the distance to translate along Y axis + */ + void translate(double dx, double dy); + + /** + * Translates the coordinate system by the specified delta vector. + * @param delta the translation amount vector point + * @throws NullPointerException if delta is {@code null} + */ + default void translate(Point2D delta) { + Objects.requireNonNull(delta, "delta"); + translate(delta.x(), delta.y()); + } + + /** + * Rotates the coordinate system around the origin by the specified angle (subsequent drawing operations will be rotated). + *

Note for Scratchers: In Scratch, the rotation angle is relative to the upper part of the vertical axis (0 degrees is + * facing up, 90 degrees is no rotation, etc.). In the context of graphics, for convenience’s sake (and because + * there's usually no front face like with Scratch's built-in costumes), a different system is used: + * 0 degrees means no rotation, positive values rotate clockwise and negative values - counterclockwise. + * Conversion between these systems happens automatically in vanilla classes, but custom renderers need to do this manually. + * @param degrees the angle of rotation in degrees (0 or multiples of 360 mean no rotation) + */ + void rotate(double degrees); + + /** + * Scales the coordinate system by the specified factors. + * Subsequent drawing operations will have their coordinates multiplied by (sx, sy). + * + * @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} + */ + void scale(double sx, double sy); + + /** + * Sets the fill color for shape filling operations. + * This color will be used by subsequent calls to {@link #fillShape(Shape)} and convenience methods. + * + * @param argb the ARGB color value (see {@link ARGB}) + * @see #fillShape(Shape) + * @see #setBlendMode(BlendMode) + * @see ARGB + */ + void setFillARGB(int argb); + + /** + * Sets the stroke color for shape outline drawing operations. + * This color will be used by subsequent calls to {@link #drawShape(Shape)} and convenience methods. + * + * @param argb the ARGB color value (see {@link ARGB}) + * @see #drawShape(Shape) + * @see #setBlendMode(BlendMode) + * @see ARGB + */ + void setStrokeARGB(int argb); + + /** + * Sets the line width for stroke operations. + * This width will be used by subsequent calls to {@link #drawShape(Shape)} and convenience methods. + * + * @param width the line width in coordinate units (must be positive) + * @throws IllegalArgumentException if width is non-positive, {@link Double#isInfinite infinite} or {@link Double#NaN NaN} + */ + void setLineWidth(double width); + + /** + * Sets the alpha (transparency) value for all drawing operations. + * This value is combined with the alpha components of fill/stroke colors. + * A value of 0 means fully transparent, 255 (-1) means fully opaque. + * + * @param alpha the alpha value (0-255 unsigned) + * @see #setFillARGB(int) + * @see #setStrokeARGB(int) + */ + // ARGB.alpha(int) returns byte, so we respect that here + void setAlpha(byte alpha); + + /** + * Sets the blend mode for combining source pixels with destination pixels. + * The blend mode affects all drawing operations including shape filling/drawing and image drawing. + * + * @param mode the blend mode to use + * @throws NullPointerException if mode is {@code null} + * @see BlendMode + * @see #drawImage(Image, double, double, double, double) + * @see #fillShape(Shape) + * @see #drawShape(Shape) + */ + void setBlendMode(BlendMode mode); + + /** + * Sets the graphic effects map to apply to subsequent drawing operations. + *

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()} + * to apply spatial distortion to vector elements. + * @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} + * @see #resetClip() + * @see #translate(double, double) + * @see #rotate(double) + * @see #scale(double, double) + */ + void clip(Shape shape); + + /** + * 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) + */ + void resetClip(); + + // Sub-canvases + + /** + * Creates a new sub-canvas that renders into an offscreen buffer. + *

+ * 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. + *

+ * This enables: + *

    + *
  • Coherent application of graphic effects
  • + *
  • Layered rendering
  • + *
  • Reusable render passes
  • + *
+ * + * Example: + *
{@code
+     * try (RenderCanvas layer = canvas.createSubCanvas(200, 200)) {
+     *     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);
+     *     }
+     * }
+     * }
+ * + * @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 + */ + RenderCanvas createSubCanvas(double width, double height); + + /** + * Checks whether this canvas is a sub-canvas. If {@code true}, then {@link #getFinalImage()} can be safely called. + * + * @return {@code true} for sub-canvases, {@code false} for the main canvas + */ + default boolean isSubCanvas() { + return false; + } + + /** + * 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. + * @throws IllegalStateException if this canvas is not a sub-canvas + * @see #isSubCanvas() + */ + default Image getFinalImage() { + // TODO maybe allow calling on main canvas? For screenshots? + throw new IllegalStateException("This canvas is not a sub-canvas"); + } + + // Getters + + /** + * Returns a vector representing the width and height of the canvas area. + * @return the dimensions of this canvas + */ + Point2D getDimensions(); + + /** + * {@return the parent context of this canvas} + */ + RenderingContext getContext(); + + // Lifecycle + + /** + * Releases any resources associated with this render canvas. + * After calling this method, the canvas should not be used. + * Calling this method more than once does not have any effect. + */ + @Override + void close(); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/render/RenderingContext.java b/src/main/java/ru/fokinatorr/sparkle/graphics/render/RenderingContext.java new file mode 100644 index 0000000..c6672a0 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/render/RenderingContext.java @@ -0,0 +1,85 @@ +package ru.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; + +/** + * Represents a graphics environment. Binds together: + *
    + *
  • + * a {@link RenderingSurface} (where to draw) + *
  • + *
  • + * a {@link Stage} (what to draw) + *
  • + *
  • + * a {@link RenderCanvas} (how to draw) + *
  • + *
+ * Multiple can coexist in one {@link GraphicsManager}. + *

Note: do not manually close instances of this interface retrieved + * from a {@link GraphicsManager}; it does so automatically when needed. + * @see GraphicsManager#createWindowContext(String, StageCreator) + */ +public interface RenderingContext extends NonThrowingAutoCloseable { + + /** + * {@return the underlying rendering surface} + * @throws IllegalStateException if this context is closed (optional) + */ + RenderingSurface getSurface(); + + /** + * {@return the stage associated with this context} + * @throws IllegalStateException if this context is closed (optional) + */ + Stage getStage(); + + /** + * Returns the canvas used for drawing operations. + * @return the canvas + * @throws IllegalStateException if this context is closed (optional) + */ + RenderCanvas getCanvas(); + + /** + * Polls input and system events (e.g., window close, resize, key press) and + * fires them on the underlying stage's local event dispatcher. + *

This method is called regularly from the graphics loop, no need + * to call it manually. + * @throws IllegalStateException if this context is closed + */ + default void pollEvents() { + getSurface().pollEvents(); + } + + /** + * Presents the rendered frame. + *

This method is called regularly from the graphics loop, no need + * to call it manually. + * @throws IllegalStateException if this context is closed + */ + void present(); + + /** + * Checks if the surface should close. + * + * @return whether a close was requested + */ + default boolean shouldClose() { + return getSurface().shouldClose(); + } + + /** + * Adds a resize listener to the surface. + * + * @param callback the listener to call every time the surface gets resized + */ + default void onResize(RenderingSurface.ResizeListener callback) { + getSurface().onResize(callback); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/render/framebuffer/Framebuffer.java b/src/main/java/ru/fokinatorr/sparkle/graphics/render/framebuffer/Framebuffer.java new file mode 100644 index 0000000..4a1cbe8 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/render/framebuffer/Framebuffer.java @@ -0,0 +1,50 @@ +package ru.fokinatorr.sparkle.graphics.render.framebuffer; + +import ru.fokinatorr.sparkle.graphics.ARGB; +import ru.fokinatorr.sparkle.graphics.PixelReader; +import ru.fokinatorr.sparkle.graphics.PixelWriter; +import ru.fokinatorr.sparkle.phys2d.Point2D; +import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable; + +/** + * Represents a render target to present on a rendering surface. + *

This is usually a handle to native platform framebuffer; do not use directly from your code + * unless you're integrating with low-level rendering APIs. + */ +public interface Framebuffer extends NonThrowingAutoCloseable { + + /** + * Returns the width of underlying frame buffer. + * @return the width, always positive + */ + int width(); + + /** + * Returns the height of underlying frame buffer. + * @return the height, always positive + */ + int height(); + + /** + * Returns a vector representing the dimensions of underlying frame buffer's data. + * @return the dimensions, both always positive + */ + default Point2D getDimensions() { + return new Point2D(width(), height()); + } + + /** + * Returns a pixel reader over this buffer, for reading its data as ARGB pixels. + * @return a new {@link PixelReader} + * @see ARGB + */ + PixelReader createPixelReader(); + + /** + * Returns a pixel writer over this buffer, for writing ARGB pixels into it. + * @return a new {@code PixelWriter} + * @see ARGB + */ + PixelWriter createPixelWriter(); + +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/render/framebuffer/OffscreenFramebuffer.java b/src/main/java/ru/fokinatorr/sparkle/graphics/render/framebuffer/OffscreenFramebuffer.java new file mode 100644 index 0000000..a3529e6 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/render/framebuffer/OffscreenFramebuffer.java @@ -0,0 +1,68 @@ +package ru.fokinatorr.sparkle.graphics.render.framebuffer; + +import lombok.experimental.FieldDefaults; +import ru.fokinatorr.sparkle.graphics.PixelReader; +import ru.fokinatorr.sparkle.graphics.PixelWriter; + +import org.lwjgl.system.MemoryUtil; +import ru.fokinatorr.sparkle.graphics.impl.IntBufferPixelAccessor; + +import java.nio.IntBuffer; + +import static lombok.AccessLevel.PRIVATE; + +/** + * An off-screen frame buffer (never displayed directly; use {@link #createPixelReader()} to use its content). + *

When created, its contents are by default fully transparent (or black if transparency is disabled). + */ +@FieldDefaults(level = PRIVATE) +public final class OffscreenFramebuffer implements Framebuffer { + final IntBuffer img; // pixel[x][y] = pixel[y * width + x] + final int width, height; + boolean closed; + + public OffscreenFramebuffer(int width, int height) { + this.width = width; + this.height = height; + this.img = MemoryUtil.memCallocInt(width * height); + } + + @Override + public int width() { + ensureOpen(); + return width; + } + + @Override + public int height() { + ensureOpen(); + return height; + } + + @Override + public synchronized PixelReader createPixelReader() { + ensureOpen(); + return new IntBufferPixelAccessor(width, height, img, this::ensureOpen); + } + + @Override + public synchronized PixelWriter createPixelWriter() { + ensureOpen(); + return new IntBufferPixelAccessor(width, height, img, this::ensureOpen); + } + + @Override + public void close() { + if (!closed) { + MemoryUtil.memFree(img); + closed = true; + } + } + + private void ensureOpen() { + if (closed) { + throw new IllegalStateException("The buffer is closed"); + } + } + +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/Renderable.java b/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/Renderable.java new file mode 100644 index 0000000..f35cca8 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/Renderable.java @@ -0,0 +1,31 @@ +package ru.fokinatorr.sparkle.graphics.render.renderer; + +import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap; +import ru.fokinatorr.sparkle.graphics.render.RenderCanvas; + +/** + * A renderable object is an object that knows how to draw itself. + *

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. + * @param canvas the canvas + */ + void render(RenderCanvas canvas); + + /** + * 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(); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/Renderable2D.java b/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/Renderable2D.java new file mode 100644 index 0000000..f9c4088 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/Renderable2D.java @@ -0,0 +1,46 @@ +package ru.fokinatorr.sparkle.graphics.render.renderer; + +import ru.fokinatorr.sparkle.phys2d.Hitbox2D; +import ru.fokinatorr.sparkle.stage.sprite.Sprite; + +/** + * A 2-dimensional {@link Renderable renderable} object is a physical 2-dimensional object with a hitbox, position, direction, and size (X and Y axis stretches). + * + * @see Sprite Sprite - a general-purpose 2D renderable + */ +public interface Renderable2D extends Renderable { + + /** + * {@return the current X coordinate} + */ + double getX(); + + /** + * {@return the current Y coordinate} + */ + double getY(); + + /** + * {@return the current direction in angles} The direction is relative to the upper vertical axis: {@code 0} + * means facing up, {@code 90} means no rotation. The minimal value is {@code -180} and the maximal value is + * {@code 180} (both of these mean facing down). + */ + double getDirection(); + + /** + * {@return the X axis stretch in percents} If you don't want to apply stretch, return {@code 100} (100% stretch - no change). + */ + double getStretchX(); + + /** + * {@return the Y axis stretch in percents} If you don't want to apply stretch, return {@code 100} (100% stretch - no change). + */ + double getStretchY(); + + /** + * Returns this object's collision box. This can be used to check what object was clicked, what objects intersect, etc. + * The hitbox's center is relative to current coordinates. + * @return the collision box + */ + Hitbox2D getHitbox(); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/Renderer.java b/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/Renderer.java new file mode 100644 index 0000000..9a0d590 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/Renderer.java @@ -0,0 +1,151 @@ +package ru.fokinatorr.sparkle.graphics.render.renderer; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import ru.fokinatorr.sparkle.graphics.image.Image; +import ru.fokinatorr.sparkle.graphics.render.RenderCanvas; +import ru.fokinatorr.sparkle.phys2d.Hitbox2D; +import ru.fokinatorr.sparkle.phys2d.Point2D; + +import java.util.Map; +import java.util.WeakHashMap; + +import static lombok.AccessLevel.PRIVATE; + +/** + * 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 the type this renderer can draw + * @see ForRenderable + * @see ForRenderable2D + * @see ForRenderable2DWithHitbox + * @see Renderable + */ +public interface Renderer { + + /** + * 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 + * @return the object's 2D bounds + * @see ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface + */ + Hitbox2D getBounds(T obj); + + /** + * A simple implementation of {@link Renderer} which draws {@link Renderable} objects. + * It is possible to extend this class and add custom functionality. + * @param the type this renderer can draw + */ + class ForRenderable implements Renderer { + + /** + * {@inheritDoc} The default implementation calls the object's {@link Renderable#render(RenderCanvas) render()} method. + * @param obj {@inheritDoc} + * @param canvas {@inheritDoc} + */ + @Override + public void render(T obj, RenderCanvas canvas) { + canvas.save(); + canvas.setEffects(obj.getGraphicEffects()); + Point2D dim = canvas.getDimensions(); + try (RenderCanvas layer = canvas.createSubCanvas(dim.x(), dim.y())) { + obj.render(layer); + canvas.drawImage(layer.getFinalImage(), 0, 0, dim.x(), dim.y()); + } + 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} + * @return {@inheritDoc} + */ + @Override + public Hitbox2D getBounds(T obj) { + 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 the type this renderer can draw + */ + class ForRenderable2D extends ForRenderable { + + @Override + public void render(T obj, RenderCanvas canvas) { + canvas.save(); + canvas.translate(obj.getX(), obj.getY()); + canvas.rotate(obj.getDirection() - 90); // Convert from face direction to relative rotation + canvas.scale(obj.getStretchX() / 100, obj.getStretchY() / 100); // Convert from percentage to coefficients + super.render(obj, canvas); + canvas.restore(); + } + + /** + * {@inheritDoc} The default implementation call the object's {@link Renderable2D#getHitbox() getHitbox()} method. + * @param obj {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public Hitbox2D getBounds(T obj) { + return obj.getHitbox(); + } + } + + /** + * 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 the type this renderer can draw + */ + @Getter + @RequiredArgsConstructor + @FieldDefaults(makeFinal = true, level = PRIVATE) + class ForRenderable2DWithHitbox extends ForRenderable2D { + + /** + * 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; + Map hitboxRenderers = new WeakHashMap<>(); // avoid constant recreation of hitbox renderers + + + @Override + public void render(T obj, RenderCanvas context) { + super.render(obj, context); + Renderable2D hitboxRenderer = hitboxRenderers.computeIfAbsent(obj.getHitbox(), hitbox -> hitbox.asRenderable(outlineColor, fillColor)); + hitboxRenderer.render(context); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/RendererRegistry.java b/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/RendererRegistry.java new file mode 100644 index 0000000..665a3f8 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/render/renderer/RendererRegistry.java @@ -0,0 +1,196 @@ +package ru.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 java.util.HashSet; +import java.util.LinkedList; +import java.util.Map; +import java.util.Queue; +import java.util.Set; + +import static lombok.AccessLevel.PRIVATE; + +/** + * A registry that maps type -> renderer for that type or supertype. + *

Also contains a separate class of renderers: debug renderers. They are disabled be default and can not be registered; + * to enable them, use {@link #enableDebug()}. + *

If both a regular and a debug renderer were found for the same type, the latter is used instead. + * + * @see Renderer + */ +@Slf4j +@FieldDefaults(makeFinal = true, level = PRIVATE) +public final class RendererRegistry { + + /** + * The ID of this registry. Useful for debugging purposes to differentiate between registries. + */ + @Getter + String id = GUID.generate(); + Map, Renderer> renderers = new Reference2ObjectOpenHashMap<>(); + Map, Renderer> debugRenderers = new Reference2ObjectOpenHashMap<>(); + /** + * Whether debug renderers are enabled and can be registered. + */ + @NonFinal + @Getter + volatile boolean debugEnabled; + + + // Registration methods + + /** + * Registers a renderer for the given type. + * + * @param type the type + * @param renderer the renderer for that type or its subtypes + * @param the type of the object + * @return this registry, for chaining calls + */ + public RendererRegistry register(Class type, Renderer renderer) { + if (renderers.containsKey(type)) { + log.warn( + "[RendererRegistry id={}] Replacing existing entry '{}' -> {} with {}", + id, type.getSimpleName(), renderers.get(type), renderer + ); + } + renderers.put(type, renderer); + log.debug("[RendererRegistry id={}] Registered a renderer '{}' -> {}", id, type.getSimpleName(), renderer); + return this; + } + + /** + * Registers a debug renderer for the given type. + *

If debug renderers are disabled, calling this method does not have any effect. + * + * @param type the type + * @param renderer the debug renderer for that type or its subtypes + * @param the type of the object + * @return this registry, for chaining calls + */ + public RendererRegistry registerDebug(Class type, Renderer renderer) { + if (debugRenderers.containsKey(type)) { + log.warn( + "[RendererRegistry id={}] Replacing existing debug entry '{}' -> {} with {}", + id, type.getSimpleName(), renderers.get(type), renderer + ); + } + if (debugEnabled) { + debugRenderers.put(type, renderer); + log.debug("[RendererRegistry id={}] Registered a debug renderer '{}' -> {}", id, type.getSimpleName(), renderer); + } else { + log.warn( + "[RendererRegistry id={}] Ignoring debug renderer registration '{}' -> {}; debug renderers are disabled", + id, type.getSimpleName(), renderer + ); + } + return this; + } + + /** + * Enables registering and using debug renderers in addition to regular ones. This can't be reversed. + * @return this registry, for chaining calls + */ + public RendererRegistry enableDebug() { + debugEnabled = true; + log.debug("[RendererRegistry id={}] Debug renderers enabled", id); + return this; + } + + // Retrieval methods + + /** + * Returns a renderer suitable for rendering instances of the given type or its supertype. + *

If debug renderers are enabled and both a regular and a debug one were found for the given type, the latter is used instead. + * @param type the type + * @return the appropriate renderer, if any + * @throws NullPointerException if no renderers were found for the given type + * @param the type of the object + */ + public Renderer get(Class type) { + Renderer renderer = null; + if (debugEnabled) { + renderer = find(debugRenderers, type); + } + if (renderer == null) { + renderer = find(renderers, type); + } + + if (renderer != null) { + log.trace("[RendererRegistry id={}] Resolved '{}' -> {}", id, type.getSimpleName(), renderer); + return renderer; + } else { + log.error( + "[RendererRegistry id={}] No renderers found for type '{}'. Debug renderers are {}", + id, type.getSimpleName(), debugEnabled ? "enabled" : "disabled" + ); + throw new NullPointerException("No renderers found for type " + type); + } + } + + // Factory methods + + /** + * Creates a renderer registry with default renderers pre-registered. This registry + * has debug renderers disabled. + * @return a new defaulted registry + */ + public static RendererRegistry withDefaults() { + return new RendererRegistry() + .register(Renderable.class, new Renderer.ForRenderable<>()) + .register(Renderable2D.class, new Renderer.ForRenderable2D<>()); + } + + // Private implementation + + /** + * Finds the first renderer registered for any supertype or implemented interface of {@code type}. + * Performs breadth-first search through the type hierarchy to ensure the closest matches win. + * + * @param m the map of type -> renderer + * @param type the queried type + * @param the object type + * @return the best matching renderer, or {@code null} if none found + */ + @SuppressWarnings("unchecked") + private static Renderer find(Map, Renderer> m, Class type) { + if (type == null) return null; + + // Use a queue or stack to avoid deep recursion + Queue> queue = new LinkedList<>(); + Set> visited = new HashSet<>(); + + visited.add(type); + queue.offer(type); + + while (!queue.isEmpty()) { + Class current = queue.poll(); + + // Check direct match + Renderer renderer = m.get(current); + if (renderer != null) { + return (Renderer) renderer; + } + + // Add interfaces + for (Class iface : current.getInterfaces()) { + if (visited.add(iface)) { + queue.offer(iface); + } + } + + // Add superclass + Class superClass = current.getSuperclass(); + if (superClass != null && visited.add(superClass)) { + queue.offer(superClass); + } + } + + return null; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/render/surface/EmbeddedSurface.java b/src/main/java/ru/fokinatorr/sparkle/graphics/render/surface/EmbeddedSurface.java new file mode 100644 index 0000000..3aa45a1 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/render/surface/EmbeddedSurface.java @@ -0,0 +1,62 @@ +package ru.fokinatorr.sparkle.graphics.render.surface; + +import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer; +import ru.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 interface EmbeddedSurface extends RenderingSurface { + + @Override + default Set 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} + * Embedded surfaces usually don't interact directly with rendering API, so they have to render to an off-screen buffer, then copy + * it onto the actual surface. + * @return {@inheritDoc} + */ + @Override + default Framebuffer acquireBuffer() { + return new OffscreenFramebuffer(getWidth(), getHeight()); + } + + /** + * Presents the given frame buffer onto this surface and releases it. + *

Internal use only, do not call directly!

+ * @param frameBuffer the frame buffer + */ + void present(OffscreenFramebuffer frameBuffer); + + /** + * {@inheritDoc} + * Embedded surfaces usually don't interact directly with rendering API, so they have to render to an off-screen buffer, then copy + * it onto the actual surface. + */ + @Override + default void present(Framebuffer frameBuffer) { + if (!(frameBuffer instanceof OffscreenFramebuffer offscreen)) { + throw new UnsupportedOperationException("Unsupported frame buffer type: " + frameBuffer.getClass()); + } + present(offscreen); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/render/surface/RenderingSurface.java b/src/main/java/ru/fokinatorr/sparkle/graphics/render/surface/RenderingSurface.java new file mode 100644 index 0000000..f40ae37 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/render/surface/RenderingSurface.java @@ -0,0 +1,241 @@ +package ru.fokinatorr.sparkle.graphics.render.surface; + +import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer; +import ru.fokinatorr.sparkle.phys2d.Point2D; +import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable; + +import java.util.Set; + +/** + * Represents a surface where rendering occurs (e.g. window, embedded UI element). + *

Different implementations provide different capabilities. + */ +public interface RenderingSurface extends NonThrowingAutoCloseable { + + // Common features + + /** + * Returns the width of this surface, in pixels. + * @return the width of this surface + */ + int getWidth(); + + /** + * Returns the height of this surface, in pixels. + * @return the height of this surface + */ + int getHeight(); + + /** + * Returns a vector representing dimensions of this surface, in pixels. + * @return dimensions of this surface + */ + default Point2D getSize() { + return new Point2D(getWidth(), getHeight()); + } + + /** + * Checks whether this surface is translucent (only the rendered content is visible). + * This is, in general, determined at creation time and may not change later. + * @return whether this surface is translucent + * @implNote The default implementation returns {@code false}. + */ + default boolean isTranslucent() { + return false; + } + + /** + * Polls input and system events. + */ + void pollEvents(); + + /** + * Acquires the next available framebuffer for rendering, if any. + *

Internal use only, do not call directly!

+ * @return an available render target or {@code null} if not available + */ + Framebuffer acquireBuffer(); + + /** + * Presents the given frame buffer onto this surface and releases it. + *

Internal use only, do not call directly!

+ * @param frameBuffer the frame buffer + */ + void present(Framebuffer frameBuffer); + + /** + * Check if this surface should close. + * @return whether a close was requested + */ + boolean shouldClose(); + + /** + * Adds a resize listener to this surface. + * + * @param callback the listener to call every time this surface gets resized + */ + void onResize(ResizeListener callback); + + + // Conditional features + + /** + * {@return supported features of this surface} This can be used to check + * whether some method will throw {@link UnsupportedOperationException}. + */ + Set getFeatures(); + + /** + * Sets the new size for this surface, if {@link Feature#RESIZABLE} + * is supported. + * @param newWidth the new width + * @param newHeight the new height + * @throws UnsupportedOperationException if not resizable + * @see #getFeatures() + */ + default void setSize(int newWidth, int newHeight) { + throw new UnsupportedOperationException("Feature.RESIZABLE not supported"); + } + + /** + * Returns X coordinate of the top-left corner of this surface, if {@link Feature#MOVABLE} + * is supported. + * @return X coordinate of the top-left corner, if supported + * @throws UnsupportedOperationException if not movable + * @see #getFeatures() + */ + default int getX() { + throw new UnsupportedOperationException("Feature.MOVABLE not supported"); // retrieving position doesn't usually make sense if not movable + } + + /** + * Returns Y coordinate of the top-left corner of this surface, if {@link Feature#MOVABLE} + * is supported. + * @return Y coordinate of the top-left corner, if supported + * @throws UnsupportedOperationException if not movable + * @see #getFeatures() + */ + default int getY() { + throw new UnsupportedOperationException("Feature.MOVABLE not supported"); + } + + /** + * Returns position of the top-left corner of this surface, if {@link Feature#MOVABLE} + * is supported. + * @return position of the top-left corner, if supported + * @throws UnsupportedOperationException if not movable + * @see #getFeatures() + */ + default Point2D getPos() { + return new Point2D(getX(), getY()); + } + + /** + * Sets the position of the top-left corner of this surface, if {@link Feature#MOVABLE} + * is supported. + * @param newX the X coordinate of the position + * @param newY the Y coordinate of the position + * @throws UnsupportedOperationException if not movable + * @see #getFeatures() + */ + default void setPos(int newX, int newY) { + throw new UnsupportedOperationException("Feature.MOVABLE not supported"); + } + + /** + * Checks whether this surface is hidden, if {@link Feature#HIDEABLE} + * is supported. + * @return whether this surface is hidden, is supported + * @throws UnsupportedOperationException if not hideable + */ + default boolean isHidden() { + throw new UnsupportedOperationException("Feature.HIDEABLE not supported"); + } + + /** + * Shows this surface, if {@link Feature#HIDEABLE} is supported. + * @throws UnsupportedOperationException if not hideable + */ + default void show() { + throw new UnsupportedOperationException("Feature.HIDEABLE not supported"); + } + + /** + * Hides this surface, if {@link Feature#HIDEABLE} is supported. + * @throws UnsupportedOperationException if not hideable + */ + default void hide() { + throw new UnsupportedOperationException("Feature.HIDEABLE not supported"); + } + + /** + * Returns the name of this surface, if {@link Feature#NAMEABLE} is supported. + * @return the name of this surface, if supported + * @throws UnsupportedOperationException if not nameable + */ + default String getName() { + throw new UnsupportedOperationException("Feature.NAMEABLE not supported"); + } + + /** + * Sets the name for this surface, if {@link Feature#NAMEABLE} is supported. + * @param name the new name + * @throws UnsupportedOperationException if not nameable + */ + default void setName(String name) { + throw new UnsupportedOperationException("Feature.NAMEABLE not supported"); + } + + /** + * Checks whether this surface is in fullscreen mode, if {@link Feature#FULLSCREENABLE} is supported. + * @return whether this surface is fullscreen, if supported + * @throws UnsupportedOperationException if not fullscreenable + */ + default boolean isFullscreen() { + throw new UnsupportedOperationException("Feature.NAMEABLE not supported"); + } + + /** + * Changes the fullscreen state of this surface, if {@link Feature#FULLSCREENABLE} is supported. + * @param fullscreen whether this surface must be in fullscreen mode + * @throws UnsupportedOperationException if not fullscreenable + */ + default void setFullscreen(boolean fullscreen) { + throw new UnsupportedOperationException("Feature.NAMEABLE not supported"); + } + + /** + * {@inheritDoc} After calling this method, the surface instance should not be used. + * Calling this method more than once does not have any effect. + */ + @Override + void close(); + + // Inner classes + + /** + * Feature flags describing capabilities of this surface. + */ + enum Feature { + RESIZABLE, + MOVABLE, + HIDEABLE, + NAMEABLE, + FULLSCREENABLE, + TRANSLUCENT + } + + /** + * Represents a callback listening to resize events. + */ + @FunctionalInterface + interface ResizeListener { + /** + * Executed when a surface was resized. + * @param surface the surface + * @param newWidth new width of the surface + * @param newHeight new height of the surface + */ + void resized(RenderingSurface surface, int newWidth, int newHeight); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/render/surface/WindowSurface.java b/src/main/java/ru/fokinatorr/sparkle/graphics/render/surface/WindowSurface.java new file mode 100644 index 0000000..656c74d --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/render/surface/WindowSurface.java @@ -0,0 +1,60 @@ +package ru.fokinatorr.sparkle.graphics.render.surface; + +import ru.fokinatorr.sparkle.graphics.GraphicsManager; + +import java.util.Collections; +import java.util.EnumSet; +import java.util.Set; + +/** + * A window rendering surface. + *

Custom implementations of ths interface are not supported by {@link GraphicsManager}; use its + * {@link GraphicsManager#createWindowContext createWindowContext(...)} methods to create & obtain an instance of this interface. + * If you want to insert a stage into a UI framework's window (JavaFX, Swing, etc.) - implement {@link EmbeddedSurface} instead. + */ +public interface WindowSurface extends RenderingSurface { + + @Override + default Set getFeatures() { + return Collections.unmodifiableSet(EnumSet.of( + Feature.RESIZABLE, + Feature.MOVABLE, + Feature.HIDEABLE, + Feature.NAMEABLE, + Feature.FULLSCREENABLE + )); + } + + @Override + void setSize(int newWidth, int newHeight); + + @Override + int getX(); + + @Override + int getY(); + + @Override + void setPos(int newX, int newY); + + @Override + boolean isHidden(); + + @Override + void show(); + + @Override + void hide(); + + @Override + String getName(); + + @Override + void setName(String name); + + @Override + boolean isFullscreen(); + + @Override + void setFullscreen(boolean fullscreen); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/graphics/vector/SVGVector.java b/src/main/java/ru/fokinatorr/sparkle/graphics/vector/SVGVector.java new file mode 100644 index 0000000..19962d6 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/graphics/vector/SVGVector.java @@ -0,0 +1,62 @@ +package ru.fokinatorr.sparkle.graphics.vector; + +import ru.fokinatorr.sparkle.graphics.ARGB; + +import java.awt.Shape; +import java.util.Objects; + +/** + * A vector with SVG style properties. + * @param vector the path + * @param strokeARGB stroke color in {@link ARGB} format + * @param fillARGB fill color in ARGB + * @param lineWidth stroke line width; if {@code 0}, not outlined + */ +public record SVGVector( + Shape vector, + int strokeARGB, + int fillARGB, + double lineWidth +) { + + /** + * @throws NullPointerException if any argument is {@code null} + * @throws IllegalArgumentException if line width is negative + */ + public SVGVector { + 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 SVGVector filled(int argb) { + return new SVGVector(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 SVGVector stroked(int argb, double lineWidth) { + return new SVGVector(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 SVGVector styled(int strokeARGB, int fillARGB, double lineWidth) { + return new SVGVector(vector, strokeARGB, fillARGB, lineWidth); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/internal/access/EventLifecycleAccess.java b/src/main/java/ru/fokinatorr/sparkle/internal/access/EventLifecycleAccess.java new file mode 100644 index 0000000..2c21b91 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/internal/access/EventLifecycleAccess.java @@ -0,0 +1,16 @@ +package ru.fokinatorr.sparkle.internal.access; + +import ru.fokinatorr.sparkle.event.AbstractCancellableEvent; +import ru.fokinatorr.sparkle.event.lifecycle.StageStateChangeEvent; +import ru.fokinatorr.sparkle.event.lifecycle.TickEvent; +import ru.fokinatorr.sparkle.stage.Stage; + +public interface EventLifecycleAccess { + + /// The class in which this interface is implemented. + Class INIT = TickEvent.class; + + StageStateChangeEvent.StartEvent newStartEvent(Stage stage); + + StageStateChangeEvent.StopEvent newStopEvent(Stage stage); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/internal/access/SharedSecrets.java b/src/main/java/ru/fokinatorr/sparkle/internal/access/SharedSecrets.java new file mode 100644 index 0000000..7575ed5 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/internal/access/SharedSecrets.java @@ -0,0 +1,75 @@ +package ru.fokinatorr.sparkle.internal.access; + +import lombok.SneakyThrows; +import lombok.experimental.UtilityClass; + +import java.lang.invoke.MethodHandles; + +/** + * Similarly to Java's {@code jdk.internal.access.SharedSecrets}, this class is a repository of "shared secrets" + * used to avoid reflection when calling package-private methods in bounds of this module. + */ +@UtilityClass +public class SharedSecrets { + + private final MethodHandles.Lookup lookup = MethodHandles.lookup(); + + /** + * Accesses package-private methods of {@link ru.fokinatorr.sparkle.stage.sprite} package. + */ + private SpriteAccess spriteAccess; + /** + * Accesses package-private methods of {@link ru.fokinatorr.sparkle.stage} package. + */ + private StageAccess stageAccess; + /** + * Accesses package-private methods of {@link ru.fokinatorr.sparkle.event.lifecycle} package. + */ + private EventLifecycleAccess eventLifecycleAccess; + + + @SneakyThrows(IllegalAccessException.class) + public SpriteAccess getSpriteAccess() { + if (spriteAccess == null) { + lookup.ensureInitialized(SpriteAccess.INIT); + } + return spriteAccess; + } + + public void setSpriteAccess(SpriteAccess spriteAccess) { + if (SharedSecrets.spriteAccess != null) { + throw new IllegalStateException("spriteAccess already initialized"); + } + SharedSecrets.spriteAccess = spriteAccess; + } + + @SneakyThrows(IllegalAccessException.class) + public StageAccess getStageAccess() { + if (stageAccess == null) { + lookup.ensureInitialized(StageAccess.INIT); + } + return stageAccess; + } + + public void setStageAccess(StageAccess stageAccess) { + if (SharedSecrets.stageAccess != null) { + throw new IllegalStateException("stageAccess already initialized"); + } + SharedSecrets.stageAccess = stageAccess; + } + + @SneakyThrows(IllegalAccessException.class) + public EventLifecycleAccess getEventLifecycleAccess() { + if (eventLifecycleAccess == null) { + lookup.ensureInitialized(EventLifecycleAccess.INIT); + } + return eventLifecycleAccess; + } + + public void setEventLifecycleAccess(EventLifecycleAccess eventLifecycleAccess) { + if (SharedSecrets.eventLifecycleAccess != null) { + throw new IllegalStateException("eventLifecycleAccess already initialized"); + } + SharedSecrets.eventLifecycleAccess = eventLifecycleAccess; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/internal/access/SpriteAccess.java b/src/main/java/ru/fokinatorr/sparkle/internal/access/SpriteAccess.java new file mode 100644 index 0000000..d44c117 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/internal/access/SpriteAccess.java @@ -0,0 +1,23 @@ +package ru.fokinatorr.sparkle.internal.access; + +import it.unimi.dsi.fastutil.Pair; +import ru.fokinatorr.sparkle.assets.Assets; +import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap; +import ru.fokinatorr.sparkle.effect.sounds.SoundEffectMap; +import ru.fokinatorr.sparkle.stage.RenderableID; +import ru.fokinatorr.sparkle.stage.Stage; +import ru.fokinatorr.sparkle.stage.sprite.Sprite; + +public interface SpriteAccess { + + /// The class in which this interface is implemented. + Class INIT = Sprite.class; + + Pair getParent(Sprite sprite); + + void attach(Sprite sprite, Stage toStage, String spriteId, int cloneId); + + void detach(Sprite sprite); + + Sprite newSprite(Assets assets, GraphicEffectMap graphicEffects, SoundEffectMap soundEffects); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/internal/access/StageAccess.java b/src/main/java/ru/fokinatorr/sparkle/internal/access/StageAccess.java new file mode 100644 index 0000000..28959e1 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/internal/access/StageAccess.java @@ -0,0 +1,28 @@ +package ru.fokinatorr.sparkle.internal.access; + +import org.checkerframework.checker.units.qual.Current; +import ru.fokinatorr.sparkle.assets.Assets; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.graphics.image.Image; +import ru.fokinatorr.sparkle.stage.Stage; +import ru.fokinatorr.sparkle.stage.StageCreator; + +public interface StageAccess { + + /// The class in which this interface is implemented. + Class INIT = Stage.class; + + void setSuppressRedraw(Stage s, boolean suppress); + + boolean isSuppressRedraw(Stage s); + + Stage newStage(Assets assets, AppContext context); + + AppContext getContext(Stage stage); + + default Stage newStage(StageCreator creator, AppContext context) { + Stage stage = newStage(creator.getStageAssets(), context); + creator.customize(stage); + return stage; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/phys2d/Hitbox2D.java b/src/main/java/ru/fokinatorr/sparkle/phys2d/Hitbox2D.java new file mode 100644 index 0000000..bbec3c9 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/phys2d/Hitbox2D.java @@ -0,0 +1,211 @@ +package ru.fokinatorr.sparkle.phys2d; + +import ru.fokinatorr.sparkle.graphics.ARGB; +import ru.fokinatorr.sparkle.graphics.render.renderer.Renderable2D; +import ru.fokinatorr.sparkle.phys2d.impl.*; + +import java.awt.Shape; +import java.awt.geom.Area; +import java.util.Optional; + +/** + * Represents a 2D hitbox used for collision and interaction detection. + *

+ * A hitbox defines a region in 2D space that can: + *

    + *
  • Check if a point is inside ({@link #contains(Point2D)})
  • + *
  • Detect overlap with another hitbox ({@link #intersects(Hitbox2D)})
  • + *
+ * + *

Design Notes

+ *
    + *
  • Hitboxes may be infinite (e.g. {@link Hitbox2D#always()}) — always check {@link #isFinite()} when needed
  • + *
  • Center may not exist (e.g. infinite or complex shapes) — {@link #getCenter()} returns {@code Optional}
  • + *
  • Implementations should be immutable and thread-safe where possible
  • + *
+ * + * @see #shape(Shape) + * @see #or(Hitbox2D...) + * @see #and(Hitbox2D...) + * @see #not() + * @see #never() + * @see #always() + */ +public interface Hitbox2D { + + /** + * Checks whether the given point lies within this hitbox. + * + * @param point the point to test + * @return whether the point is contained by this hitbox + */ + boolean contains(Point2D point); + + /** + * Checks whether this hitbox intersects with the given one. + *

+ * Intersection is symmetric: {@code a.intersects(b) == b.intersects(a)} + * + * @param other the other hitbox, must not be null + * @return whether the hitboxes overlap + */ + boolean intersects(Hitbox2D other); + + /** + * Checks whether this hitbox fully contains the given one. + *

+ * Containment is not always symmetric, unlike {@link #intersects intersection}. It's symmetric + * only for equal hitboxes; otherwise, it's asymmetric. + *

+ * A finite hitbox can never contain an infinite one. If this hitbox and the given one are infinite, + * this method checks for equality instead. + * + * @param other the other hitbox, must not be null + * @return whether this hitbox fully contains the given one + */ + boolean contains(Hitbox2D other); + + /** + * Returns whether this hitbox and the given one cover exactly the same points. + * @param other the other hitbox + * @return whether the two hitboxes are equivalent + */ + default boolean equals(Hitbox2D other) { + return this == other || (other != null && this.contains(other) && other.contains(this)); + } + + /** + * Determines whether this hitbox represents a finite region. + *

+ * Example: {@link Hitbox2D#always()} returns {@code false}, while a rectangle returns {@code true}. + * + * @return whether the hitbox is finite + */ + boolean isFinite(); + + /** + * Creates an {@link Area} representing all points covered by this hitbox, if it's {@link #isFinite finite}, + * otherwise returns an empty optional. + * @return a new area of this hitbox, if applicable + */ + Optional createArea(); + + /** + * Gets the center point of this hitbox, if any. + *

+ * May return empty for non-symmetric or infinite hitboxes. + * + * @return the center, or empty if undefined + */ + Optional getCenter(); + + + // Factory methods + + /** + * Creates a 2D hitbox matching the given shape without rotating the shape. + * @param shape the shape + * @return a new 2D hitbox + * @see #shape(Shape, double) + */ + static Hitbox2D shape(Shape shape) { + return new ShapeHitbox2D(shape); + } + + /** + * Creates a 2D hitbox matching the given shape. + * + * @param shape the shape + * @param direction the rotation angle of the shape in degrees, relative to upper vertical axis (0 is facing upwards, 90 is no rotation). + * It will be {@link ru.fokinatorr.sparkle.util.Mth#wrapClamp(double, double, double) wrap-around clamped} + * between {@code -180} and {@code 180}, so any finite value can be passed. + * @return a new 2D hitbox + */ + static Hitbox2D shape(Shape shape, double direction) { + return new ShapeHitbox2D(shape, direction); + } + + /** + * Creates a 2D hitbox that is a union of the given hitboxes. The hitbox list is optimized + * (all hitboxes that are fully contained by other hitboxes in the list are removed). + * @param hitboxes the hitboxes + * @return a new 2D hitbox + * @see #or(boolean, Hitbox2D...) + */ + static Hitbox2D or(Hitbox2D... hitboxes) { + return or(true, hitboxes); + } + + /** + * Creates a 2D hitbox that is a union of the given hitboxes. + * @param hitboxes the hitboxes + * @param optimize whether to optimize the hitbox list (removes all hitboxes that are fully contained by other hitboxes in the list) + * @return a new 2D hitbox + */ + static Hitbox2D or(boolean optimize, Hitbox2D... hitboxes) { + OrHitbox2D or = new OrHitbox2D(hitboxes); + return optimize ? or.optimize() : or; + } + + /** + * Creates a 2D hitbox that is an intersection of the given hitboxes. The hitbox list is optimized + * (all hitboxes that fully contain any other hitbox in the list are removed). + * @param hitboxes the hitboxes + * @return a new 2D hitbox + * @see #and(boolean, Hitbox2D...) + */ + static Hitbox2D and(Hitbox2D... hitboxes) { + return and(true, hitboxes); + } + + /** + * Creates a 2D hitbox that is an intersection of the given hitboxes. + * @param hitboxes the hitboxes + * @param optimize whether to optimize the hitbox list (removes all hitboxes that fully contain any other hitbox in the list) + * @return a new 2D hitbox + */ + static Hitbox2D and(boolean optimize, Hitbox2D... hitboxes) { + AndHitbox2D and = new AndHitbox2D(hitboxes); + return optimize ? and.optimize() : and; + } + + /** + * Creates a 2D hitbox that covers every point except those covered by this hitbox. In other words, + * returns a negation of this hitbox. + * @return a new 2D hitbox + */ + default Hitbox2D not() { + return new NotHitbox2D(this); + } + + /** + * Returns a 2D hitbox that doesn't cover any points. Useful for purely visual objects, like particles, etc. + *

It doesn't have a {@link #getCenter center point} and {@link #createArea creates} empty {@link Area Areas}. + * @return an empty 2D hitbox + */ + static Hitbox2D never() { + return NeverHitbox2D.INSTANCE; + } + + /** + * Returns a 2D hitbox that covers all points. + *

It doesn't have a {@link #getCenter center point} or an {@link Area}. + * @return an "all-points" 2D hitbox + */ + static Hitbox2D always() { + return AlwaysHitbox2D.INSTANCE; + } + + /** + * Creates a renderable object from this hitbox. Useful for debugging/cheat menu mods. + * @param outlineColor the outline color of the hitbox's area in ARGB format (usually opaque) + * @param fillColor the fill color of the hitbox's area in ARGB format (usually ~50% transparent) + * @return this hitbox as a renderable object + * @see ARGB + */ + default Renderable2D asRenderable(int outlineColor, int fillColor) { + return new RenderableHitbox2D(this, outlineColor, fillColor); + } + + +} \ No newline at end of file diff --git a/src/main/java/ru/fokinatorr/sparkle/phys2d/Point2D.java b/src/main/java/ru/fokinatorr/sparkle/phys2d/Point2D.java new file mode 100644 index 0000000..a93b418 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/phys2d/Point2D.java @@ -0,0 +1,91 @@ +package ru.fokinatorr.sparkle.phys2d; + +/** + * Represents a point in 2D space. + * Can also represent a 2D vector or 2D dimensions (width & height respectively). + *

This class has convenience methods for movement. They all can throw an exception as specified + * in the {@link #Point2D(double, double) constructor}. + * + * @param x the X coordinate + * @param y the Y coordinate + */ +public record Point2D(double x, double y) { + + /** + * A 2D point with both coordinates set to {@code 0}. + */ + public static final Point2D ZERO = new Point2D(0, 0); + + /** + * Creates a new 2D point. + * + * @param x the X coordinate + * @param y the Y coordinate + * @throws IllegalArgumentException if either {@code x} or {@code y} is {@link Double#isInfinite(double) infinite} or {@link Double#isNaN(double) NaN}. + */ + public Point2D { + if (Double.isInfinite(x)) throw new IllegalArgumentException("x must be finite"); + if (Double.isNaN(x)) throw new IllegalArgumentException("x must not be NaN"); + if (Double.isInfinite(y)) throw new IllegalArgumentException("y must be finite"); + if (Double.isNaN(y)) throw new IllegalArgumentException("y must not be NaN"); + } + + // Movement methods + + /** + * Returns a new 2D point with the specified X coordinate and this one's Y coordinate. + * + * @param newX the new X coordinate + * @return a new 2D point + */ + public Point2D x(double newX) { + return new Point2D(newX, y); + } + + /** + * Returns a new 2D point with this one's X coordinate and the specified Y coordinate. + * + * @param newY the new Y coordinate + * @return a new 2D point + */ + public Point2D y(double newY) { + return new Point2D(x, newY); + } + + /** + * Returns a new 2D point moved by given amount of units along the X axis and unchanged Y coordinate. + * @param dx the distance to move along the X axis + * @return a new 2D point + */ + public Point2D dx(double dx) { + return new Point2D(x + dx, y); + } + + /** + * Returns a new 2D point moved by given amount of units along the Y axis and unchanged X coordinate. + * @param dy the distance to move along the Y axis + * @return a new 2D point + */ + public Point2D dy(double dy) { + return new Point2D(x, y + dy); + } + + /** + * Returns a new 2D point moved by {@code dx} units along the X axis and {@code dy} units along the Y axis. + * @param dx the distance to move along the X axis + * @param dy the distance to move along the Y axis + * @return a new 2D point + */ + public Point2D translate(double dx, double dy) { + return new Point2D(x + dx, y + dy); + } + + /** + * Returns a new 2D point with both coordinates translated by the given point's coordinates respectively. + * @param delta the translation delta vector + * @return a new 2D point + */ + public Point2D translate(Point2D delta) { + return new Point2D(x + delta.x, y + delta.y); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/AlwaysHitbox2D.java b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/AlwaysHitbox2D.java new file mode 100644 index 0000000..40f2a31 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/AlwaysHitbox2D.java @@ -0,0 +1,57 @@ +package ru.fokinatorr.sparkle.phys2d.impl; + +import ru.fokinatorr.sparkle.phys2d.Hitbox2D; +import ru.fokinatorr.sparkle.phys2d.Point2D; + +import java.awt.geom.Area; +import java.util.Optional; + +/** + * A 2D hitbox that covers all points. + *

IDK why anyone would use this, but it's here as an opposite to {@link NeverHitbox2D}. + */ +public enum AlwaysHitbox2D implements Hitbox2D { + INSTANCE; + + @Override + public boolean contains(Point2D point) { + return true; + } + + @Override + public boolean intersects(Hitbox2D other) { + return true; + } + + @Override + public boolean contains(Hitbox2D other) { + return true; + } + + @Override + public boolean isFinite() { + return false; + } + + @Override + public Optional createArea() { + return Optional.empty(); + } + + @Override + public Optional getCenter() { + return Optional.empty(); + } + + @Override + public Hitbox2D not() { + return NeverHitbox2D.INSTANCE; + } + + @Override + public boolean equals(Hitbox2D other) { + return other instanceof AlwaysHitbox2D + || other instanceof AndHitbox2D and && and.optimize() instanceof AlwaysHitbox2D + || other instanceof OrHitbox2D or && or.optimize() instanceof AlwaysHitbox2D; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/AndHitbox2D.java b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/AndHitbox2D.java new file mode 100644 index 0000000..5704c65 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/AndHitbox2D.java @@ -0,0 +1,195 @@ +package ru.fokinatorr.sparkle.phys2d.impl; + +import ru.fokinatorr.sparkle.phys2d.Hitbox2D; +import ru.fokinatorr.sparkle.phys2d.Point2D; + +import java.awt.geom.Area; +import java.util.*; +import java.util.function.Predicate; + +import static ru.fokinatorr.sparkle.phys2d.impl.OrHitbox2D.areaSize; + +/** + * An intersection of 2D hitboxes. This hitbox is finite only if at least one child hitbox is finite. + * + * @param children the child hitboxes + */ +public record AndHitbox2D(Collection children) implements Hitbox2D { + + private static final Predicate IS_ALWAYS_HITBOX = child -> child instanceof AlwaysHitbox2D; + private static final Set ALWAYS_HITBOX_SET = Set.of(AlwaysHitbox2D.INSTANCE); + + /** + * @throws NullPointerException if children is {@code null} + */ + public AndHitbox2D { + Objects.requireNonNull(children, "children"); + } + + /** + * Array version of {@link #AndHitbox2D(Collection)}. + * + * @throws NullPointerException if children is {@code null} + */ + public AndHitbox2D(Hitbox2D... children) { + this(Arrays.asList(Objects.requireNonNull(children, "children"))); + } + + /** + * Returns an {@code AndHitbox2D} with same children as this one, but without those + * that fully contain any other child (they're effectively redundant); if + * there are no children, returns {@link NeverHitbox2D#INSTANCE}. + * + * @return an optimized version of this hitbox + */ + public Hitbox2D optimize() { + if (children.isEmpty() || children.contains(NeverHitbox2D.INSTANCE)) { + return NeverHitbox2D.INSTANCE; + } else if (children.stream().allMatch(IS_ALWAYS_HITBOX)) { + return AlwaysHitbox2D.INSTANCE; + } + Collection optChildren = optimizeChildren(children); + if (optChildren.isEmpty() || optChildren.contains(NeverHitbox2D.INSTANCE)) { + return NeverHitbox2D.INSTANCE; + } else if (ALWAYS_HITBOX_SET.equals(optChildren)) { + return AlwaysHitbox2D.INSTANCE; + } + return new AndHitbox2D(optChildren); + } + + @Override + public boolean intersects(Hitbox2D other) { + return reduceChildrenAnd(children, child -> child.intersects(other), false); + } + + @Override + public boolean contains(Hitbox2D other) { + return reduceChildrenAnd(children, child -> child.contains(other), false); + } + + @Override + public boolean contains(Point2D point) { + return reduceChildrenAnd(children, child -> child.contains(point), false); + } + + @Override + public Optional createArea() { + Area area = new Area(); + for (Hitbox2D child : children) { + child.createArea().ifPresent(area::add); + } + return Optional.of(area); + } + + @Override + public Optional getCenter() { + if (children.isEmpty()) return Optional.empty(); + double xSum = 0, ySum = 0; + int childCount = children.size(); + for (Hitbox2D child : children) { + Point2D childCenter = child.getCenter().orElse(null); + if (childCenter != null) { + xSum += childCenter.x(); + ySum += childCenter.y(); + } + } + return Optional.of(new Point2D(xSum / childCount, ySum / childCount)); + } + + @Override + public boolean isFinite() { + return OrHitbox2D.reduceChildrenOr(children, Hitbox2D::isFinite, true); + } + + + @Override + public Hitbox2D not() { + // !c1 && !c2 && ... && !cn + // can be replaced with + // !(c1 || c2 || ... || cn) + List newChildren = new ArrayList<>(children.size()); + for (Hitbox2D child : children) { + if (child instanceof NotHitbox2D(Hitbox2D delegate)) { + newChildren.add(delegate); + } else { + return Hitbox2D.super.not(); + } + } + return new NotHitbox2D(new OrHitbox2D(newChildren)); + } + + + @Override + public boolean equals(Hitbox2D other) { + if (other instanceof AndHitbox2D(Collection thatChildren)) { + Collection optChildren = optimizeChildren(children); + Collection thatOptChildren = optimizeChildren(thatChildren); + return optChildren.containsAll(thatOptChildren) && thatOptChildren.containsAll(optChildren); + } + return Hitbox2D.super.equals(other); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof Hitbox2D hitbox && equals(hitbox); + } + + /** + * Applies the reduction operator to all children and returns {@code c1 && c2 && ... && cn}, where + * {@code ci} is the result of the reduction operator applied on the {@code i}th child. If there are no children, + * returns the given default value. + * + * @param children the children + * @param reduceOp the reduction operator + * @param defaultValue the value returned when {@code children} is empty + * @return boolean values from applying the reduction operator to children merged with AND operation, or the default value if + * {@code children} is empty + */ + static boolean reduceChildrenAnd(Collection children, Predicate reduceOp, boolean defaultValue) { + if (children.isEmpty()) return defaultValue; + boolean result = true; + for (Hitbox2D child : children) { + result = reduceOp.test(child); + if (!result) break; + } + return result; + } + + /** + * Remove children that fully contain any other child. If there's a child that doesn't intersect any other child, return an empty collection. + */ + private static Collection optimizeChildren(Collection children) { + if (children.stream().allMatch(IS_ALWAYS_HITBOX)) return ALWAYS_HITBOX_SET; + + List list = new ArrayList<>(children); + Set toRemove = new HashSet<>(ALWAYS_HITBOX_SET); + + // Sort by approximate area size (larger first) to improve pruning + list.sort((a, b) -> Double.compare(areaSize(b), areaSize(a))); + + for (int i = 0; i < list.size(); i++) { + Hitbox2D outer = list.get(i); + if (!toRemove.contains(outer)) { + boolean intersectsWithAny = false; + for (int j = i + 1; j < list.size(); j++) { + Hitbox2D inner = list.get(j); + if (!toRemove.contains(inner)) { + intersectsWithAny |= outer.intersects(inner); + if (outer.contains(inner)) { + toRemove.add(outer); + break; + } else if (inner.contains(outer)) { + toRemove.add(inner); + } + } + } + if (!intersectsWithAny) { + return List.of(); + } + } + } + + list.removeAll(toRemove); + return Collections.unmodifiableList(list); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/NeverHitbox2D.java b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/NeverHitbox2D.java new file mode 100644 index 0000000..29caa79 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/NeverHitbox2D.java @@ -0,0 +1,57 @@ +package ru.fokinatorr.sparkle.phys2d.impl; + +import ru.fokinatorr.sparkle.phys2d.Hitbox2D; +import ru.fokinatorr.sparkle.phys2d.Point2D; + +import java.awt.geom.Area; +import java.util.Collection; +import java.util.Optional; + +/** + * A 2D hitbox that covers no points. Useful for objects that are purely a visual (e.g. particles). + */ +public enum NeverHitbox2D implements Hitbox2D { + INSTANCE; + + @Override + public boolean contains(Point2D point) { + return false; + } + + @Override + public boolean intersects(Hitbox2D other) { + return false; + } + + @Override + public boolean contains(Hitbox2D other) { + return false; + } + + @Override + public boolean isFinite() { + return true; + } + + @Override + public Optional createArea() { + return Optional.of(new Area()); + } + + @Override + public Optional getCenter() { + return Optional.empty(); + } + + @Override + public Hitbox2D not() { + return AlwaysHitbox2D.INSTANCE; + } + + @Override + public boolean equals(Hitbox2D other) { + return other instanceof NeverHitbox2D + || other instanceof AndHitbox2D and && and.optimize() instanceof NeverHitbox2D + || other instanceof OrHitbox2D or && or.optimize() instanceof NeverHitbox2D; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/NotHitbox2D.java b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/NotHitbox2D.java new file mode 100644 index 0000000..4fbdf59 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/NotHitbox2D.java @@ -0,0 +1,84 @@ +package ru.fokinatorr.sparkle.phys2d.impl; + +import ru.fokinatorr.sparkle.phys2d.Hitbox2D; +import ru.fokinatorr.sparkle.phys2d.Point2D; + +import java.awt.*; +import java.awt.geom.Area; +import java.util.Objects; +import java.util.Optional; + +/** + * A negation of a 2D hitbox. Usually infinite; can be finite if the backing hitbox is a negation of a finite one. + * @param delegate the hitbox to negate + */ +public record NotHitbox2D(Hitbox2D delegate) implements Hitbox2D { + + /** + * @throws NullPointerException if delegate is {@code null} + */ + public NotHitbox2D { + Objects.requireNonNull(delegate, "delegate"); + } + + /** + * Creates an optimized negation of the given hitbox. This method + * is preferred to the {@link #NotHitbox2D constructor} if you don't need the hitbox + * to be an instance of this class. + * @param hitbox the hitbox to negate + * @return a negated hitbox + */ + public static Hitbox2D of(Hitbox2D hitbox) { + return hitbox.not(); // Some classes override this method to potentially optimize negation + } + + @Override + public boolean contains(Point2D point) { + return !delegate.contains(point); + } + + @Override + public boolean intersects(Hitbox2D other) { + return !delegate.contains(other); + } + + @Override + public boolean contains(Hitbox2D other) { + return !delegate.intersects(other); + } + + @Override + public boolean isFinite() { + return delegate instanceof NotHitbox2D(Hitbox2D thatDelegate) && thatDelegate.isFinite(); + } + + @Override + public Optional createArea() { + return delegate instanceof NotHitbox2D(Hitbox2D thatDelegate) + ? thatDelegate.createArea() + : Optional.empty(); + } + + @Override + public Optional getCenter() { + return delegate.getCenter(); + } + + @Override + public Hitbox2D not() { + return delegate; + } + + @Override + public boolean equals(Hitbox2D other) { + if (other instanceof NotHitbox2D(Hitbox2D thatDelegate)) { + return delegate.equals(thatDelegate); + } + return Hitbox2D.super.equals(other); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof Hitbox2D hitbox && equals(hitbox); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/OrHitbox2D.java b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/OrHitbox2D.java new file mode 100644 index 0000000..642cf14 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/OrHitbox2D.java @@ -0,0 +1,198 @@ +package ru.fokinatorr.sparkle.phys2d.impl; + +import ru.fokinatorr.sparkle.phys2d.Hitbox2D; +import ru.fokinatorr.sparkle.phys2d.Point2D; + +import java.awt.geom.Area; +import java.util.*; +import java.util.List; +import java.util.function.Predicate; + +/** + * A union of 2D hitboxes. This hitbox is finite only if all child hitboxes are finite. + * + * @param children the child hitboxes + */ +public record OrHitbox2D(Collection children) implements Hitbox2D { + + private static final Predicate IS_NEVER_HITBOX = child -> child instanceof NeverHitbox2D; + private static final Set NEVER_HITBOX_SET = Set.of(NeverHitbox2D.INSTANCE); + + /** + * @throws NullPointerException if children is {@code null} + */ + public OrHitbox2D { + Objects.requireNonNull(children, "children"); + } + + /** + * Array version of {@link #OrHitbox2D(Collection)}. + * @throws NullPointerException if children is {@code null} + */ + public OrHitbox2D(Hitbox2D... children) { + this(Arrays.asList(Objects.requireNonNull(children, "children"))); + } + + /** + * Returns an {@code OrHitbox2D} with same children as this one, but without those + * that are fully contained by other children (they're effectively redundant); if + * there are no children, returns {@link NeverHitbox2D#INSTANCE}. + * @return an optimized version of this hitbox + */ + public Hitbox2D optimize() { + if (children.isEmpty() || children.stream().allMatch(IS_NEVER_HITBOX)) { + return NeverHitbox2D.INSTANCE; + } else if (children.contains(AlwaysHitbox2D.INSTANCE)) { + return AlwaysHitbox2D.INSTANCE; + } + Collection optChildren = optimizeChildren(children); + if (optChildren.isEmpty() || NEVER_HITBOX_SET.equals(optChildren)) { + return NeverHitbox2D.INSTANCE; + } else if (optChildren.contains(AlwaysHitbox2D.INSTANCE)) { + return AlwaysHitbox2D.INSTANCE; + } + return new OrHitbox2D(optChildren); + } + + @Override + public boolean intersects(Hitbox2D other) { + return reduceChildrenOr(children, child -> child.intersects(other), false); + } + + @Override + public boolean contains(Hitbox2D other) { + return reduceChildrenOr(children, child -> child.contains(other), false); + } + + @Override + public boolean contains(Point2D point) { + return reduceChildrenOr(children, child -> child.contains(point), false); + } + + @Override + public Optional createArea() { + Area area = new Area(); + for (Hitbox2D child : children) { + Area addend = child.createArea().orElse(null); + if (addend == null) return Optional.empty(); + area.add(addend); + } + return Optional.of(area); + } + + @Override + public Optional getCenter() { + if (children.isEmpty()) return Optional.empty(); + double xSum = 0, ySum = 0; + int childCount = children.size(); + for (Hitbox2D child : children) { + Point2D childCenter = child.getCenter().orElse(null); + if (childCenter == null) return Optional.empty(); + xSum += childCenter.x(); + ySum += childCenter.y(); + } + return Optional.of(new Point2D(xSum / childCount, ySum / childCount)); + } + + @Override + public boolean isFinite() { + return AndHitbox2D.reduceChildrenAnd(children, Hitbox2D::isFinite, true); + } + + @Override + public Hitbox2D not() { + // !c1 || !c2 || ... || !cn + // can be replaced with + // !(c1 && c2 && ... && cn) + List newChildren = new ArrayList<>(children.size()); + for (Hitbox2D child : children) { + if (child instanceof NotHitbox2D(Hitbox2D delegate)) { + newChildren.add(delegate); + } else { + return Hitbox2D.super.not(); + } + } + return new NotHitbox2D(new AndHitbox2D(newChildren)); + } + + + @Override + public boolean equals(Hitbox2D other) { + if (other instanceof OrHitbox2D(Collection thatChildren)) { + Collection optChildren = optimizeChildren(children); + Collection thatOptChildren = optimizeChildren(thatChildren); + return optChildren.containsAll(thatOptChildren) && thatOptChildren.containsAll(optChildren); + } + return Hitbox2D.super.equals(other); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof Hitbox2D hitbox && equals(hitbox); + } + + /** + * Applies the reduction operator to all children and returns {@code c1 || c2 || ... || cn}, where + * {@code ci} is the result of the reduction operator applied on the {@code i}th child. If there are no children, + * returns the given default value. + * @param children the children + * @param reduceOp the reduction operator + * @param defaultValue the value returned when {@code children} is empty + * @return boolean values from applying the reduction operator to children merged with OR operation, or the default value if + * {@code children} is empty + */ + static boolean reduceChildrenOr(Collection children, Predicate reduceOp, boolean defaultValue) { + if (children.isEmpty()) return defaultValue; + boolean result = false; + for (Hitbox2D child : children) { + result = reduceOp.test(child); + if (result) break; + } + return result; + } + + /** + * Remove children that are fully contained by other children. + *

Would be even better if this was invoked for each {@code OrHitbox2D} at compile time ^u^ + * sadly Collections are not compile-time constants :\ + */ + private static Collection optimizeChildren(Collection children) { + if (children.stream().allMatch(IS_NEVER_HITBOX)) return NEVER_HITBOX_SET; + + List list = new ArrayList<>(children); + Set toRemove = new HashSet<>(NEVER_HITBOX_SET); + + // Sort by approximate area size (larger first) to improve pruning + list.sort((a, b) -> Double.compare(areaSize(b), areaSize(a))); + + for (int i = 0; i < list.size(); i++) { + Hitbox2D outer = list.get(i); + if (!toRemove.contains(outer)) { + for (int j = i + 1; j < list.size(); j++) { + Hitbox2D inner = list.get(j); + if (!toRemove.contains(inner)) { + if (outer.contains(inner)) { + toRemove.add(inner); + } else if (inner.contains(outer)) { + toRemove.add(outer); + break; + } + } + } + } + } + + list.removeAll(toRemove); + return Collections.unmodifiableList(list); + } + + /** + * Returns the area size of the given hitbox. Returns {@link Double#POSITIVE_INFINITY} + * for infinite hitboxes. + */ + static double areaSize(Hitbox2D hitbox) { + return hitbox.createArea() + .map(area -> area.getBounds2D().getWidth() * area.getBounds2D().getHeight()) + .orElse(Double.POSITIVE_INFINITY); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/RenderableHitbox2D.java b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/RenderableHitbox2D.java new file mode 100644 index 0000000..d422656 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/RenderableHitbox2D.java @@ -0,0 +1,115 @@ +package ru.fokinatorr.sparkle.phys2d.impl; + +import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap; +import ru.fokinatorr.sparkle.graphics.ARGB; +import ru.fokinatorr.sparkle.graphics.render.RenderCanvas; +import ru.fokinatorr.sparkle.graphics.render.renderer.Renderable2D; +import ru.fokinatorr.sparkle.phys2d.Hitbox2D; +import ru.fokinatorr.sparkle.phys2d.Point2D; + +import java.awt.*; +import java.awt.geom.Area; +import java.awt.geom.Rectangle2D; +import java.util.Optional; + +/** + * A decorator 2D hitbox that is also renderable. Useful for debugging/cheat menu mods. + * + * @param delegate the hitbox to render + * @param outlineColor the outline color of the hitbox's area in ARGB format + * @param fillColor the fill color of the hitbox's area in ARGB format + * @see ARGB + */ +public record RenderableHitbox2D( + Hitbox2D delegate, + int outlineColor, + int fillColor +) implements Renderable2D, Hitbox2D { + // @formatter:off + // Renderable properties + // Most of them are stored in the hitbox itself, so don't apply external movement, rotation, or stretching. + @Override public double getX() { return 0; } + @Override public double getY() { return 0; } + @Override public double getDirection() { return 90; } + @Override public double getStretchX() { return 100; } + @Override public double getStretchY() { return 100; } + @Override public Hitbox2D getHitbox() { return delegate; } // return the delegate instead of this for smaller stack size + // maybe add customization for these two? + @Override public boolean isVisible() { return true; } + @Override public GraphicEffectMap getGraphicEffects() { return new GraphicEffectMap(); } + // @formatter:on + + + @Override + public void render(RenderCanvas canvas) { + switch (delegate) { + 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 NeverHitbox2D _ -> { + } + case RenderableHitbox2D hb -> hb.render(canvas); + 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 -> delegate.createArea().ifPresent(area -> fillShape(area, canvas)); + } + } + + // @formatter:off + // Hitbox API + @Override public boolean contains(Point2D point) { return delegate.contains(point); } + @Override public boolean intersects(Hitbox2D other) { return delegate.intersects(other); } + @Override public boolean contains(Hitbox2D other) { return delegate.contains(other); } + @Override public boolean equals(Hitbox2D other) { return delegate.equals(other); } + @Override public boolean isFinite() { return delegate.isFinite(); } + @Override public Optional createArea() { return delegate.createArea(); } + @Override public Optional getCenter() { return delegate.getCenter(); } + // @formatter:on + + @Override + public Hitbox2D not() { + // Special handling here to allow chained calls + return new RenderableHitbox2D( + delegate.not(), + outlineColor, + fillColor + ); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof RenderableHitbox2D(Hitbox2D thatDelegate, int thatOutline, int thatFill) + && delegate.equals(thatDelegate) && outlineColor == thatOutline && fillColor == thatFill; + } + + @Override + public Renderable2D asRenderable(int outlineColor, int fillColor) { + // Don't do double decoration, but allow changing colors + return new RenderableHitbox2D( + delegate, + outlineColor, + fillColor + ); + } + + private void fillShape(Shape shape, RenderCanvas canvas) { + canvas.save(); + canvas.setStrokeARGB(outlineColor); + canvas.setFillARGB(fillColor); + canvas.fillShape(shape); + canvas.restore(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/ShapeHitbox2D.java b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/ShapeHitbox2D.java new file mode 100644 index 0000000..6408975 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/phys2d/impl/ShapeHitbox2D.java @@ -0,0 +1,117 @@ +package ru.fokinatorr.sparkle.phys2d.impl; + +import ru.fokinatorr.sparkle.phys2d.Hitbox2D; +import ru.fokinatorr.sparkle.phys2d.Point2D; +import ru.fokinatorr.sparkle.util.Mth; + +import java.awt.Shape; +import java.awt.geom.AffineTransform; +import java.awt.geom.Area; +import java.awt.geom.Rectangle2D; +import java.util.Objects; +import java.util.Optional; + +/** + * A 2D hitbox matching the given shape's position and bounds. This hitbox is always finite, i.e. + * {@link #isFinite()} called on an instance of this class always returns {@code true}. + * @param shape the shape + */ +public record ShapeHitbox2D(Shape shape) implements Hitbox2D { + + /** + * @throws NullPointerException if the shape is {@code null} + */ + public ShapeHitbox2D { + Objects.requireNonNull(shape, "shape"); + } + + /** + * Creates a {@code ShapeHitbox2D} with the given shape rotated by the given amount of degrees + * @param shape the shape + * @param directionInDegrees the rotation angle in degrees, relative to upper vertical axis (0 is facing upwards, 90 is no rotation). It will + * be {@link Mth#wrapClamp(double, double, double) wrap-around clamped} between {@code -180} and {@code 180}. + * @throws NullPointerException if the shape is {@code null} + */ + public ShapeHitbox2D(Shape shape, double directionInDegrees) { + Objects.requireNonNull(shape, "shape"); + directionInDegrees = Mth.wrapClamp(directionInDegrees, -180.0, 180.0); + if (directionInDegrees != 90) { + Point2D center = getShapeCenter(shape); + shape = AffineTransform.getRotateInstance( + Math.toRadians(directionInDegrees), // angle + center.x(), // anchor x + center.y() // anchor y + ).createTransformedShape(shape); + } + this(shape); + } + + @Override + public boolean contains(Point2D point) { + return shape.contains(point.x(), point.y()); + } + + @Override + public Optional getCenter() { + return Optional.of(getShapeCenter(shape)); + } + + @Override + public Optional createArea() { + return Optional.of(new Area(shape)); + } + + @Override + public boolean isFinite() { + return true; + } + + @Override + public boolean intersects(Hitbox2D other) { + Optional thatAreaOpt = other.createArea(); + if (thatAreaOpt.isPresent()) { + Area thisArea = new Area(this.shape); + Area thatArea = thatAreaOpt.get(); + thisArea.intersect(thatArea); + return !thisArea.isEmpty(); + } else { + // fall back to conservative check + return other.intersects(this); + } + } + + @Override + public boolean contains(Hitbox2D other) { + Optional thatAreaOpt = other.createArea(); + if (thatAreaOpt.isPresent()) { + Area thisArea = new Area(this.shape); + Area thatArea = thatAreaOpt.get(); + thatArea.subtract(thisArea); + return thatArea.isEmpty(); // Nothing left outside + } else { + return false; // finite hitboxes can't contain infinite ones + } + } + + @Override + public boolean equals(Hitbox2D other) { + if (other instanceof ShapeHitbox2D(Shape thatShape)) { + return shape.equals(thatShape); + } + return Hitbox2D.super.equals(other); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof Hitbox2D hitbox && equals(hitbox); + } + + /** + * {@return the center point of the given shape} + * @param shape the shape + */ + private static Point2D getShapeCenter(Shape shape) { + Rectangle2D bounds = shape.getBounds2D(); + return new Point2D(bounds.getCenterX(), bounds.getCenterY()); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/stage/RenderableID.java b/src/main/java/ru/fokinatorr/sparkle/stage/RenderableID.java new file mode 100644 index 0000000..b77f4a9 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/stage/RenderableID.java @@ -0,0 +1,48 @@ +package ru.fokinatorr.sparkle.stage; + +import ru.fokinatorr.sparkle.stage.sprite.Sprite; + +/** + * Represents an ID of a renderable object on a stage. + * + * @param the type of the object + */ +public sealed interface RenderableID permits + RenderableID.SpriteID, + RenderableID.OtherID { + + /** + * Gets a renderable object from the given {@link Stage} by this ID. + * + * @param stage the stage to retrieve from + * @return the object + */ + T getFrom(Stage stage); + + /** + * A sprite ID. + * + * @param spriteId the ID (usually the name) + * @param cloneId the clone ID (0 for main sprite) + */ + record SpriteID(String spriteId, int cloneId) implements RenderableID { + + @Override + public Sprite getFrom(Stage stage) { + return stage.getSprite(spriteId, cloneId); + } + } + + /** + * An arbitrary object ID. + * + * @param id the ID + */ + record OtherID(String id) implements RenderableID { + + @Override + public Object getFrom(Stage stage) { + return stage.getRenderable(id); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/stage/Stage.java b/src/main/java/ru/fokinatorr/sparkle/stage/Stage.java new file mode 100644 index 0000000..6160144 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/stage/Stage.java @@ -0,0 +1,973 @@ +package ru.fokinatorr.sparkle.stage; + +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import lombok.experimental.NonFinal; +import lombok.extern.slf4j.Slf4j; +import ru.fokinatorr.sparkle.assets.Assets; +import ru.fokinatorr.sparkle.audio.SoundInstance; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.context.AppContextHolder; +import ru.fokinatorr.sparkle.event.BackdropChangeEvent; +import ru.fokinatorr.sparkle.event.lifecycle.StageStateChangeEvent; +import ru.fokinatorr.sparkle.event.lifecycle.StageStateChangeEvent.StartEvent; +import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher; +import ru.fokinatorr.sparkle.event.lifecycle.TickEvent; +import ru.fokinatorr.sparkle.graphics.GraphicsManager; +import ru.fokinatorr.sparkle.graphics.GraphicsUtils; +import ru.fokinatorr.sparkle.graphics.image.Image; +import ru.fokinatorr.sparkle.graphics.render.RenderCanvas; +import ru.fokinatorr.sparkle.graphics.render.renderer.RendererRegistry; +import ru.fokinatorr.sparkle.internal.access.*; +import ru.fokinatorr.sparkle.stage.RenderableID.OtherID; +import ru.fokinatorr.sparkle.stage.RenderableID.SpriteID; +import ru.fokinatorr.sparkle.stage.sprite.Sprite; +import ru.fokinatorr.sparkle.util.*; +import ru.fokinatorr.sparkle.variable.AbstractVariableStorage; +import ru.fokinatorr.sparkle.variable.Variable; + +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import static ru.fokinatorr.sparkle.graphics.render.RenderCanvas.ORIGINAL_SIZE; +import static ru.fokinatorr.sparkle.util.Constants.MILLIS_PER_SECOND; +import static ru.fokinatorr.sparkle.util.Constants.NANOS_PER_MILLISECOND; + +/** + * A stage, containing {@link Sprite sprites}, arbitrary renderable objects and background. + *

Note for Scratchers: The default stage size, unlike in Scratch, is 640x360 (16:9 ratio) + * and not 480x360 (4:3 ratio). The default framerate limit is also different, being {@code 60} instead of {@code 30}. + */ +@Slf4j +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +@RequiredArgsConstructor(access = AccessLevel.PACKAGE) +public class Stage extends AbstractVariableStorage { + + static { + SharedSecrets.setStageAccess(new StageAccess() { + @Override + public void setSuppressRedraw(Stage s, boolean suppress) { + s.setSuppressRedraw(suppress); + } + + @Override + public boolean isSuppressRedraw(Stage s) { + return s.isSuppressRedraw(); + } + + @Override + public Stage newStage(Assets assets, AppContext context) { + return new Stage(assets, context); + } + + @Override + public AppContext getContext(Stage stage) { + return stage.context; + } + }); + } + + private static final SpriteAccess spriteAcc = SharedSecrets.getSpriteAccess(); + private static final EventLifecycleAccess eventAcc = SharedSecrets.getEventLifecycleAccess(); + + /** + * This stage's assets (backdrops & sounds). + */ + @Getter + Assets assets; + /** + * The application context. + */ + AppContext context; + /** + * A unique ID of this stage, for debug & exception messages. + */ + @Getter + String id = GUID.generate(); + // Maps sprite IDs to the main sprite and its clones. + // element with key 0 always represents the main sprite + ConcurrentMap> sprites = new ConcurrentHashMap<>(); + // Arbitrary renderable objects + ConcurrentMap renderables = new ConcurrentHashMap<>(); + // first element = back layer + List> layers = new CopyOnWriteArrayList<>(); + List> layersView = Collections.unmodifiableList(layers); + // default backdrop 0 + AtomicInteger backdropIndex = new AtomicInteger(); + + AtomicReference state = new AtomicReference<>(State.NEW); + EnumSet visibleButtons = DebugUtils.isDebuggerAttached() + ? EnumSet.allOf(ControlButton.class) + : EnumSet.of(ControlButton.START, ControlButton.STOP); + + AtomicInteger width = new AtomicInteger(640); + AtomicInteger height = new AtomicInteger(360); + + AtomicBoolean suppressRedraw = new AtomicBoolean(); + AtomicInteger fpsLim = new AtomicInteger(60); + AtomicInteger tpsLim = new AtomicInteger(240); + + Lock renderablesLock = new ReentrantLock(); + + Int2ObjectMap loadedBackdrops = Int2ObjectMaps.synchronize(new Int2ObjectOpenHashMap<>()); + Int2ObjectMap> loadedSounds = Int2ObjectMaps.synchronize(new Int2ObjectOpenHashMap<>()); + + /* ********************* + * * + * Renderables general * + * * + ***********************/ + + /** + * Registers a new {@link Sprite} with the given ID. + * + * @param spriteId the sprite's ID + * @param sprite the main sprite + * @return this {@code Stage}, for chaining {@code registerXxx(...)} calls + * @throws NullPointerException if any argument is {@code null} + * @throws IllegalStateException if there already is a sprite with the given ID + * @throws IllegalArgumentException if the given sprite is already registered in a different stage + */ + public Stage registerSprite(String spriteId, Sprite sprite) { + Objects.requireNonNull(spriteId, "sprite id"); + Objects.requireNonNull(sprite, "sprite"); + var parent = spriteAcc.getParent(sprite); + if (parent != null) { + throw new IllegalArgumentException( + "The given sprite already has an ID '" + parent.right().spriteId() + + "' in stage with ID '" + parent.left().id + "'" + ); + } + renderablesLock.lock(); + try { + if (sprites.containsKey(spriteId)) { + throw new IllegalStateException("A sprite with ID '" + spriteId + "' is already registered"); + } + Int2ObjectMap map = new Int2ObjectOpenHashMap<>(); + map.put(0, sprite); + sprites.put(spriteId, map); + addSpriteToLayers(spriteId, 0); + spriteAcc.attach(sprite, this, spriteId, 0); + log.debug("[Stage id={}] Registered new sprite with ID '{}'", id, spriteId); + return this; + } finally { + renderablesLock.unlock(); + } + } + + + /** + * {@return the main sprite with the given ID} + * + * @param spriteId the sprite ID + * @throws NullPointerException if the given ID is {@code null} + * @throws IllegalArgumentException if there is no sprite with the given ID + */ + public Sprite getMainSprite(String spriteId) { + return getSprite(spriteId, 0); + } + + /** + * Returns the sprite with the given sprite ID and clone ID. Note that the main sprite + * always has the clone ID {@code 0}. + * + * @param spriteId the sprite ID + * @param cloneId the clone ID + * @return the sprite identified by the given IDs + * @throws NullPointerException if the given ID is {@code null} + * @throws IllegalArgumentException if there is no sprite with the given sprite ID or clone ID + */ + public Sprite getSprite(String spriteId, int cloneId) { + Objects.requireNonNull(spriteId, "sprite id"); + renderablesLock.lock(); + try { + checkSpriteId(spriteId); + Sprite result = sprites.get(spriteId).get(cloneId); + if (result == null) { + throw new IllegalArgumentException("No clone of sprite " + spriteId + " with clone ID " + cloneId); + } + return result; + } finally { + renderablesLock.unlock(); + } + } + + /** + * Unregisters the sprite with the given ID, i.e. removes it and its clones from the stage. + * + * @param spriteId the sprite ID + * @return an immutable view of the removed sprites by clone ID; {@code 0} clone ID represents the + * main sprite + * @throws NullPointerException if the sprite ID is {@code null} + * @throws IllegalArgumentException if there is no such sprite with the given ID + */ + public Int2ObjectMap unregisterSprite(String spriteId) { + Objects.requireNonNull(spriteId, "sprite id"); + renderablesLock.lock(); + try { + checkSpriteId(spriteId); + Int2ObjectMap result = Int2ObjectMaps.unmodifiable(sprites.remove(spriteId)); + layers.removeIf(id -> id instanceof SpriteID(String thatSpriteId, int _) && thatSpriteId.equals(spriteId)); + result.keySet().forEach((int cloneId) -> spriteAcc.detach(result.get(cloneId))); + log.debug("[Stage id={}] Unregistered sprite with ID {}", id, spriteId); + return result; + } finally { + renderablesLock.unlock(); + } + } + + /** + * Registers an arbitrary renderable object with the given ID. There must be a renderer available for + * the object's type to register successfully. + *

To register sprites, use {@link #registerSprite(String, Sprite)} instead; they're a special case of renderable objects. + * + * @param id the object's ID + * @param obj the object + * @return this {@code Stage}, for chaining {@code registerXxx(...)} calls + * @throws NullPointerException if any argument is {@code null}, or if the object is not renderable + * @throws IllegalStateException if there already is an object with the given ID + * @throws IllegalArgumentException if the given object is a sprite + */ + public Stage registerRenderable(String id, Object obj) { + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(obj, "object"); + + if (obj instanceof Sprite) { + throw new IllegalArgumentException("Cannot register a sprite as a generic renderable object"); + } + context.get(RendererRegistry.class).get(obj.getClass()); // throws if no renderer for the object + + renderablesLock.lock(); + try { + if (renderables.containsKey(id)) { + throw new IllegalStateException("An object with ID '" + id + "' is already registered"); + } + renderables.put(id, obj); + addObjToLayers(id); + log.debug("[Stage id={}] Registered new renderable object with ID '{}'", this.id, id); + return this; + } finally { + renderablesLock.unlock(); + } + } + + /** + * {@return the renderable object with the given ID} This method does not check for sprites. + * + * @param id the object ID + * @throws NullPointerException if the given ID is {@code null} + * @throws IllegalArgumentException if there is no object with the given ID + * @throws ClassCastException if the object cannot be case to requested type + * @param the requested type of the object + */ + @SuppressWarnings("unchecked") + public T getRenderable(String id) { + Objects.requireNonNull(id, "id"); + renderablesLock.lock(); + try { + checkObjId(id); + return (T) renderables.get(id); + } finally { + renderablesLock.unlock(); + } + } + + /** + * Unregisters the renderable object with the given ID, i.e. removes it from the stage. + * + * @param id the object ID + * @return the unregistered object + * @throws NullPointerException if the object ID is {@code null} + * @throws IllegalArgumentException if there is no such object with the given ID + * @throws ClassCastException if the object cannot be case to requested type + * @param the requested type of the object + */ + @SuppressWarnings("unchecked") + public T unregisterRenderable(String id) { + Objects.requireNonNull(id, "id"); + renderablesLock.lock(); + try { + checkObjId(id); + Object result = renderables.remove(id); + log.debug("[Stage id={}] Unregistered renderable object with ID {}", this.id, id); + return (T) result; + } finally { + renderablesLock.unlock(); + } + } + + /* ********************* + * * + * Sprites cloning * + * * + ***********************/ + + /** + * Creates a clone of the sprite with the given ID. The clone is immediately added to this stage. + *

Note for Scratchers: Unlike in Scratch, the clone's initial layer will be front instead of back. + * + * @param spriteId the sprite ID + * @return the clone ID of the new clone + * @throws IllegalArgumentException if there is no sprite with the given ID + * @throws NullPointerException if the given ID is {@code null} + */ + public int createClone(String spriteId) { + Objects.requireNonNull(spriteId, "sprite id"); + renderablesLock.lock(); + try { + checkSpriteId(spriteId); + Int2ObjectMap map = sprites.get(spriteId); + Sprite mainSprite = map.get(0); + int newCloneId = generateCloneId(map); + Sprite cloneSprite = mainSprite.copy(); + map.put(newCloneId, cloneSprite); + addSpriteToLayers(spriteId, newCloneId); + spriteAcc.attach(cloneSprite, this, spriteId, newCloneId); + log.debug("[Stage id={}] Cloned sprite with ID '{}', new clone ID: {}", id, spriteId, newCloneId); + return newCloneId; + } finally { + renderablesLock.unlock(); + } + } + + /** + * Deletes a clone with the given clone ID of the sprite with the given ID. If there is no clone with the given + * clone ID, this method does nothing. + * + * @param spriteId the main sprite ID + * @param cloneId the clone ID + * @throws NullPointerException if the sprite ID is {@code null} + * @throws IllegalArgumentException if there is no sprite with the given ID, or the clone ID is {@code 0}, which represents + * the main sprite (use {@link #unregisterSprite(String)} to remove the main sprite with clones) + */ + public void deleteClone(String spriteId, int cloneId) { + Objects.requireNonNull(spriteId, "sprite id"); + if (cloneId == 0) { + throw new IllegalArgumentException("Cannot delete main sprite"); + } + renderablesLock.lock(); + try { + checkSpriteId(spriteId); + Int2ObjectMap map = sprites.get(spriteId); + layers.remove(new SpriteID(spriteId, cloneId)); + spriteAcc.detach(map.remove(cloneId)); + log.debug("[Stage id={}] Deleted clone with ID {} of sprite with ID '{}'", id, cloneId, spriteId); + } finally { + renderablesLock.unlock(); + } + } + + /** + * Deletes all clones of the sprite with the given ID. If the sprite has no clones, this method + * does nothing. + * + * @param spriteId the main sprite ID + * @throws NullPointerException if the sprite ID is {@code null} + * @throws IllegalArgumentException if there is no sprite with the given ID + */ + public void deleteAllClones(String spriteId) { + Objects.requireNonNull(spriteId, "sprite id"); + renderablesLock.lock(); + try { + checkSpriteId(spriteId); + Int2ObjectMap map = sprites.get(spriteId); + map.keySet().intStream() + .filter(cloneId -> cloneId != 0) // 0 represents the main sprite + .forEach(cloneId -> { + layers.remove(new SpriteID(spriteId, cloneId)); + spriteAcc.detach(map.remove(cloneId)); + }); + log.debug("[Stage id={}] Deleted all clones of sprite with ID '{}'", id, spriteId); + } finally { + renderablesLock.unlock(); + } + } + + /* ******************** + * * + * Render order * + * * + **********************/ + + /** + * Moves the object with the given ID to the given layer. + * + * @param id the renderable's ID + * @param newLayer the new layer of the desired object, will be clamped to be in range {@code [0; renderable count)} + * @throws NullPointerException if ID is {@code null} + * @throws IllegalArgumentException if no object/sprite with the given ID was found + * @see RenderableID + */ + public void moveToLayer(RenderableID id, int newLayer) { + Objects.requireNonNull(id, "id"); + renderablesLock.lock(); + try { + checkId(id); + doMoveToLayer(layers.indexOf(id), newLayer); + } finally { + renderablesLock.unlock(); + } + } + + /** + * Moves the object with the given ID to the front layer. + *

Equivalent to {@code moveToLayer(id, getLayers().size() - 1)}. + * + * @param id the renderable's ID + * @throws NullPointerException if ID is {@code null} + * @throws IllegalArgumentException if no object/sprite with the given ID was found + * @see RenderableID + */ + public void moveToFrontLayer(RenderableID id) { + moveToLayer(id, layers.size() - 1); + } + + /** + * Moves the object with the given ID to the front layer. + *

Equivalent to {@code moveToLayer(id, 0)}. + * + * @param id the renderable's ID + * @throws NullPointerException if ID is {@code null} + * @throws IllegalArgumentException if no object/sprite with the given ID was found + * @see RenderableID + */ + public void moveToBackLayer(RenderableID id) { + moveToLayer(id, 0); + } + + /** + * Moves the object with the given ID {@code delta} count of layers. Negative {@code delta} + * stands for moving backward, positive {@code delta} stands for moving forward. + * + * @param id the renderable's ID + * @param delta how much layers to move the object; moves forward if positive, or moves backward if negative, + * {@code Math.abs(delta)} layers. If {@code 0}, does nothing + * @throws NullPointerException if {@code delta != 0 && id == null} + * @throws IllegalArgumentException if {@code delta != 0} and no object/sprite with the given ID was found + * @see RenderableID + */ + public void moveByLayers(RenderableID id, int delta) { + if (delta == 0) return; + Objects.requireNonNull(id, "id"); + renderablesLock.lock(); + try { + checkId(id); + int currentLayer = layers.indexOf(id); + doMoveToLayer(currentLayer, currentLayer + delta); + } finally { + renderablesLock.unlock(); + } + } + + /** + * Returns an immutable {@link List} view which represents in which order to render the objects (in other words, + * the objects' layers). Whenever an object's layer is updated, it is reflected in the view returned by this method. + * + * @return a view over this stage's objects' layers + * @see #getSprite(String, int) + * @see #getRenderable(String) + * @see RenderableID + */ + public List> getLayers() { + return layersView; + } + + + /* **************************** + * * + * Miscellaneous properties * + * * + ******************************/ + + /** + * {@return the current width of this stage} + */ + public int getWidth() { + return width.get(); + } + + /** + * {@return the current height of this stage} + */ + public int getHeight() { + return height.get(); + } + + /** + * Sets the width for this stage to the given value. + * + * @param newWidth the new width + * @throws IllegalArgumentException if the new width is non-positive + */ + public void setWidth(int newWidth) { + setSize(newWidth, getHeight()); + } + + /** + * Sets the new height for this stage to the given value. + * + * @param newHeight the new height + * @throws IllegalArgumentException if the new height are non-positive + */ + public void setHeight(int newHeight) { + setSize(getWidth(), newHeight); + } + + /** + * Sets the width and height for this stage to the given values. + * + * @param newWidth the new width + * @param newHeight the new height + * @throws IllegalArgumentException if either width or height are non-positive + */ + public void setSize(int newWidth, int newHeight) { + if (newWidth <= 0) { + throw new IllegalArgumentException("width is non-positive: " + newWidth); + } + if (newHeight <= 0) { + throw new IllegalArgumentException("height is non-positive: " + newHeight); + } + width.set(newHeight); + height.set(newHeight); + } + + // not public API + void setSuppressRedraw(boolean newValue) { + suppressRedraw.set(newValue); + } + + // not public API + boolean isSuppressRedraw() { + return suppressRedraw.get(); + } + + /** + * {@return the current framerate limit} It is not guaranteed that the actual framerate would be equal to this value; + * this is just the upper bound. + */ + public int getFPSLimit() { + return fpsLim.get(); + } + + /** + * Sets the current framerate limit to the given value. + * It is not guaranteed that the actual framerate would be equal to this value; this is just the upper bound. + * + * @param fpsLimit the new framerate limit + * @return the old framerate limit + */ + public int setFPSLimit(int fpsLimit) { + return fpsLim.getAndSet(fpsLimit); + } + + /** + * {@return the current tick rate limit} It is not guaranteed that the actual tick rate would be equal to this value; + * this is just the upper bound. + */ + public int getTPSLimit() { + return tpsLim.get(); + } + + /** + * Sets the current tick rate limit to the given value. + * It is not guaranteed that the actual tick rate would be equal to this value; this is just the upper bound. + * + * @param tpsLimit the new tick rate limit + * @return the old tick rate limit + */ + public int setTPSLimit(int tpsLimit) { + return tpsLim.getAndSet(tpsLimit); + } + + /* ******************* + * * + * Stage state * + * * + *********************/ + + + /** + * Represents the state of a stage. + */ + public enum State { + /** + * The stage has never been started yet. + */ + NEW, + /** + * The stage has been started and is preparing to run. + */ + PREPARING, + /** + * The stage has been started and is running. + */ + RUNNING, + /** + * The stage has been started before, and it's stopping. + */ + STOPPING, + /** + * The stage has been started before, but it's now stopped. Can be restarted at this point. + */ + STOPPED + } + + /** + * Returns the current state of this stage. + * + * @return this stage's state, never {@code null} + * @see State + */ + public State getState() { + return state.get(); + } + + /** + * Fires the start event on this stage. Doesn't do anything if the stage is already running or stopping. Returns immediately. + * + * @return a {@link CompletableFuture} that completes when the {@link StartEvent} was dispatched by every listener and the + * stage stopped afterward. + */ + public CompletableFuture start() { + State current = state.get(); + if ((current == State.NEW || current == State.STOPPED) && state.compareAndSet(current, State.PREPARING)) { + log.trace("[Stage id={}] Preparing to run...", id); + return context.get(EventDispatcher.class).fireEvent(eventAcc.newStartEvent(this)) + .thenRun(() -> { + loopThread = createLoopThread(); + loopThread.start(); + // state set to RUNNING in the thread + }); + } + return CompletableFuture.completedFuture(null); + } + + @NonFinal + Thread loopThread; + + /** + * Fires the stop event on this stage. Returns immediately. + * + * @return a {@link CompletableFuture} that completes when the {@link StageStateChangeEvent.StopEvent} was dispatched by every listener. + */ + public CompletableFuture stop() { + State current = state.get(); + if (current == State.RUNNING && state.compareAndSet(current, State.STOPPING)) { + log.trace("[Stage id={}] Stopping...", id); + return context.get(EventDispatcher.class).fireEvent(eventAcc.newStopEvent(this)) + .thenRun(() -> { + try { + if (loopThread != Thread.currentThread()) { // prevent deadlock + loopThread.interrupt(); + loopThread.join(); + } + } catch (InterruptedException _) { + } finally { + loopThread = null; + state.set(State.STOPPED); + log.debug("[Stage id={}] Stopped.", id); + } + }); + } + return CompletableFuture.completedFuture(null); + } + + /* ********************* + * * + * Visible buttons * + * * + ***********************/ + + /** + * Represents a button controlling state of a stage. + */ + public enum ControlButton { + /** + * Starts the stage with {@link #start()}. + */ + START, + /** + * Suspends execution using {@link DebugUtils#debugSuspend()}, if a debugger is attached. + */ + PAUSE, + /** + * Stops the stage with {@link #stop()}. + */ + STOP + } + + /** + * Returns a mutable set containing currently enabled control buttons. The set does not permit {@code null} values. + * @return the visible control buttons set + */ + public Set getVisibleButtons() { + return visibleButtons; + } + + /* ********************* + * * + * Backdrops, sounds * + * * + ***********************/ + + /** + * Sets the backdrop index to the given one. This action is not guaranteed to be done since event listeners + * can cancel the event. This method does not wait for the event to be processed by listeners. + *

Note for Scratchers: Unlike in Scratch, the first backdrop index value is {@code 0}. + * + * @param index the backdrop index + * @throws IndexOutOfBoundsException if no backdrop with the given index was found + */ + public void setBackdrop(int index) { + setBackdrop(index, false); + } + + /** + * Sets the backdrop index to the given one. This action is not guaranteed to be done since event listeners + * can cancel the event. + *

Note for Scratchers: Unlike in Scratch, the first backdrop index value is {@code 0}. + * + * @param index the backdrop index + * @param waitForListeners whether to wait until the event was processed by listeners + * @throws IndexOutOfBoundsException if no backdrop with the given index was found + */ + public void setBackdrop(int index, boolean waitForListeners) { + Objects.checkIndex(index, getAssets().texturesByIndex().size()); + int oldIndex = backdropIndex.get(); + BackdropChangeEvent.Before event = new BackdropChangeEvent.Before(this, oldIndex, index); + try { + context.get(EventDispatcher.class).fireEventAndWait(event); + } finally { + index = event.newBackdropId(); // newBackdropId is mutable + if (event.isCancelled()) { + log.info("{}: setBackdrop({}) was cancelled", this, index); + } else { + backdropIndex.set(index); + var future = context.get(EventDispatcher.class).fireEvent(new BackdropChangeEvent.After(this, oldIndex, index)); + if (waitForListeners) future.join(); + } + } + } + + /** + * Sets the backdrop name to the given one. This action is not guaranteed to be done since event listeners + * can cancel the event. This method does not wait for the event to be processed by listeners. + * + * @param name the backdrop name + * @throws IndexOutOfBoundsException if no backdrop with the given name was found + * @throws NullPointerException if backdrop name is {@code null} + */ + public void setBackdrop(String name) { + setBackdrop(name, false); + } + + /** + * Sets the backdrop name to the given one. This action is not guaranteed to be done since event listeners + * can cancel the event. + * + * @param name the backdrop name + * @param waitForListeners whether to wait until the event was processed by listeners + * @throws IndexOutOfBoundsException if no backdrop with the given name was found + * @throws NullPointerException if backdrop name is {@code null} + */ + public void setBackdrop(String name, boolean waitForListeners) { + Objects.requireNonNull(name, "backdrop name"); + setBackdrop(assets.texturesIndexesByName().getInt(name), waitForListeners); + } + + /** + * {@return the current backdrop index} + *

Note for Scratchers: This method matches the functionality of "backdrop number" block. + */ + public int getBackdropIndex() { + return backdropIndex.get(); + } + + /** + * {@return the current backdrop name} + */ + public String getBackdropName() { + return getAssets().texturesByIndex().get(backdropIndex.get()).name(); + } + + /** + * Draws the current backdrop onto the given canvas. + * @param canvas the canvas + * @throws NullPointerException if canvas is {@code null} + */ + public void drawBackdrop(RenderCanvas canvas) { + canvas.save(); + canvas.setIdentity(); + GraphicsUtils.drawImageOriginCenter(canvas, getCurrentBackdropImage(), 0, 0, ORIGINAL_SIZE, ORIGINAL_SIZE); + canvas.restore(); + } + + // TODO sounds + + /* ******************** + * * + * Private API * + * * + **********************/ + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + protected Map> createVariables() { + return new ConcurrentHashMap<>(); + } + + /** + * Moves whatever sprite at layer {@code currentLayer} to {@code newLayer}. Assume that the {@link #renderablesLock} + * is acquired. + * + * @param currentLayer the current (old) layer + * @param newLayer the new layer, will be clamped to be in the bounds + */ + private void doMoveToLayer(int currentLayer, int newLayer) { + layers.add(Mth.clamp(newLayer, 0, layers.size() - 1), layers.remove(currentLayer)); + } + + /** + * Adds the sprite with the given ID and clone ID to the front layer. Assume that the {@link #renderablesLock} + * is acquired. + */ + private void addSpriteToLayers(String spriteId, int cloneId) { + layers.addLast(new SpriteID(spriteId, cloneId)); + } + + /** + * Adds the object with the given ID to the front layer. Assume that the {@link #renderablesLock} + * is acquired. + */ + private void addObjToLayers(String id) { + layers.addLast(new OtherID(id)); + } + + /** + * Throws IllegalArgumentException if the ID is absent + */ + private void checkSpriteId(String spriteId) { + if (!sprites.containsKey(spriteId)) { + throw new IllegalArgumentException("No sprite with ID " + spriteId); + } + } + + /** + * Throws IllegalArgumentException if the ID is absent + */ + private void checkId(RenderableID id) { + if (id instanceof SpriteID(String spriteId, int cloneId)){ + checkSpriteId(spriteId, cloneId); + } else if (id instanceof OtherID(String objId)) { + checkObjId(objId); + } + } + + /** + * Throws IllegalArgumentException if the sprite ID or clone ID is absent + */ + private void checkSpriteId(String spriteId, int cloneId) { + checkSpriteId(spriteId); + if (!sprites.get(spriteId).containsKey(cloneId)) { + throw new IllegalArgumentException("No clone of sprite " + spriteId + " with clone ID " + cloneId); + } + } + + /** + * Throws IllegalArgumentException if the ID is absent + */ + private void checkObjId(String id) { + if (!renderables.containsKey(id)) { + throw new IllegalArgumentException("No object with ID " + id); + } + } + + /** + * Creates a loop thread for this stage that continuously fires {@link TickEvent TickEvents} until one of them is cancelled + * or {@link #stop()} is called. + * + * @return a new virtual thread + */ + private Thread createLoopThread() { + return Thread.ofVirtual() + .name("stage#" + id + "-loop") + .unstarted(() -> { + state.set(State.RUNNING); + log.trace("[Stage id={}] Running...", id); + try { + AppContextHolder.initContext(context); // init global context for this thread + } catch (IllegalStateException _) { + } // already initialized; ignore + EventDispatcher dispatcher = context.get(EventDispatcher.class); + long prevTickTime = System.nanoTime(); + long lastTickTime = prevTickTime; + long tpsLimit = tpsLim.get(); + + log.trace("[Stage id={}] Entering loop...", id); + while (!Thread.interrupted()) { + if (dispatcher.hasListenersFor(TickEvent.class)) { + TickEvent event = new TickEvent(this, (double) (lastTickTime - prevTickTime) / NANOS_PER_MILLISECOND); + try { + dispatcher.fireEventAndWait(event); + } finally { + prevTickTime = lastTickTime; + lastTickTime = System.nanoTime(); + } + if (event.isCancelled()) { + break; + } + WaitUtils.waitFor(MILLIS_PER_SECOND / tpsLimit - (lastTickTime - prevTickTime) / NANOS_PER_MILLISECOND); + tpsLimit = tpsLim.get(); + } else { + WaitUtils.waitFor(MILLIS_PER_SECOND / tpsLimit); + if (tpsLimit > 5) { + tpsLimit /= 2; + } + } + } + stop(); // only joins the loop thread if the loop thread is NOT the current thread, so no deadlocks + }); + } + + /** + * Clone ID generator that avoids collisions. + */ + private static int generateCloneId(Int2ObjectMap map) { + int newCloneId; + do { + newCloneId = Constants.RANDOM.nextInt(); + } while (map.containsKey(newCloneId)); // avoid collisions + return newCloneId; + } + + /** + * Returns an image respective to the current backdrop. + */ + Image getCurrentBackdropImage() { + return loadedBackdrops.computeIfAbsent( + getBackdropIndex(), + idx -> { + GraphicsManager graphicsManager = context.get(GraphicsManager.class); + Path imgPath = assets.texturesByIndex().get(idx).location(); + return graphicsManager.hasLoadedImage(imgPath) + ? graphicsManager.getLoadedImage(imgPath) + : graphicsManager.loadImage(imgPath, true); + } + ); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/stage/StageCreator.java b/src/main/java/ru/fokinatorr/sparkle/stage/StageCreator.java new file mode 100644 index 0000000..438fe14 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/stage/StageCreator.java @@ -0,0 +1,97 @@ +package ru.fokinatorr.sparkle.stage; + +import ru.fokinatorr.sparkle.assets.Assets; +import ru.fokinatorr.sparkle.event.input.Key; +import ru.fokinatorr.sparkle.graphics.render.RenderingContext; +import ru.fokinatorr.sparkle.stage.sprite.Sprite; + +import ru.fokinatorr.sparkle.event.input.KeyboardEvent; + +/** + * A factory interface for controlled creation and customization of {@link Stage} instances. + *

+ * Direct instantiation of {@link Stage} via constructor is restricted because: + *

    + *
  • Stages are tightly bound to a {@link RenderingContext} and must be managed by the graphics system
  • + *
  • Uncontrolled creation could lead to resource leaks or inconsistent state
  • + *
+ *

+ * Implementations of this interface provide: + *

    + *
  1. The {@link Assets} bundle required for loading images, sounds, and other media during stage setup
  2. + *
  3. Custom configuration logic applied after the stage is constructed
  4. + *
+ *

+ * This pattern ensures that stages are: + *

    + *
  • Created with proper dependencies
  • + *
  • Configured in a consistent, testable way
  • + *
  • Integrated safely into the rendering lifecycle
  • + *
+ *

Example usage

+ *
{@code
+ * public class MyGameStage implements StageCreator {
+ *     private final Assets assets;
+ *
+ *     public MyGameStage(Assets assets) {
+ *         this.assets = assets;
+ *     }
+ *
+ *     @Override
+ *     public Assets getStageAssets() {
+ *         return assets;
+ *     }
+ *
+ *     private static final Assets PLAYER_ASSETS = ...;
+ *
+ *     @Override
+ *     public void customize(Stage stage) {
+ *         Sprite player = new Sprite(PLAYER_ASSETS);
+ *         player.setCostume("idle");
+ *         stage.registerSprite("player", player);
+ *
+ *         stage.setBackdrop("sky_blue");
+ *         Global.when(KeyboardEvent.KeyPressedEvent.class, e -> {
+ *             if (e.stage() == stage && e.key() == Key.SPACE) {
+ *                 player.jump();
+ *             }
+ *         });
+ *         // ...
+ *     }
+ * }
+ * }
+ * + * @see RenderingContext#getStage() + * @see KeyboardEvent.KeyPressedEvent + * @see Stage + * @see Sprite + * @see Key + */ +public interface StageCreator { + + /** + * Returns the assets bundle used by this stage (backdrops and sounds). + * + * @return the non-{@code null} assets bundle for this stage + */ + Assets getStageAssets(); + + /** + * Customizes the given stage after construction. + *

+ * This method is called immediately after the stage is instantiated, + * allowing implementors to: + *

    + *
  • Add sprites and UI elements
  • + *
  • Set backdrop
  • + *
  • Register event listeners
  • + *
  • Configure physics or camera settings
  • + *
+ *

Note: The stage is already fully constructed and safe to use, + * but has not yet been rendered. This is the ideal time to set up initial state. + * + * @param stage the stage to customize, never {@code null} + * @throws NullPointerException if {@code stage} is {@code null} + */ + void customize(Stage stage); +} \ No newline at end of file diff --git a/src/main/java/ru/fokinatorr/sparkle/stage/sprite/BubbleState.java b/src/main/java/ru/fokinatorr/sparkle/stage/sprite/BubbleState.java new file mode 100644 index 0000000..09c9c78 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/stage/sprite/BubbleState.java @@ -0,0 +1,54 @@ +package ru.fokinatorr.sparkle.stage.sprite; + +import lombok.*; +import lombok.experimental.FieldDefaults; + +/** + * Holds data about a sprite's text bubble state. + */ +@Data +@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) +@Builder(toBuilder = true) +@With +public class BubbleState { + /** + * The text + */ + @NonNull + String text; + /** + * The type of the bubble + * + * @see BubbleType + */ + @NonNull + BubbleType type; + /** + * ID indicating the most recent usage of the bubble. + * Used for comparison when determining whether to clear a bubble. + * Can be {@code null}. + */ + String usageId; + + /** + * The limit of characters in text. + */ + public static final int BUBBLE_TEXT_LIMIT = 330; + + /** + * The default (empty) {@code BubbleState}, which represents no bubble at all. + */ + public static BubbleState EMPTY = new BubbleState( + "", + BubbleType.SAY, + null + ); + + /** + * The type of text bubble. + */ + public enum BubbleType { + SAY, + THINK + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/stage/sprite/RotationStyle.java b/src/main/java/ru/fokinatorr/sparkle/stage/sprite/RotationStyle.java new file mode 100644 index 0000000..83607f2 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/stage/sprite/RotationStyle.java @@ -0,0 +1,27 @@ +package ru.fokinatorr.sparkle.stage.sprite; + +/** + * Adds sprite rendering rules depending on its direction value. + */ +public enum RotationStyle { + /** + * Render direction as is + */ + ALL_AROUND, + /** + * Render the sprite as if direction is {@code 90} and also mirror it if the direction is negative + */ + LEFT_RIGHT, + /** + * Always render the sprite as if direction is {@code 90} + */ + DO_NOT_ROTATE, + /** + * Same as {@link #ALL_AROUND}, but also mirror the sprite if the direction is negative + */ + LOOK_AT, + /** + * Render the sprite as if direction is {@code 0} and also mirror it if the direction is negative + */ + UP_DOWN +} diff --git a/src/main/java/ru/fokinatorr/sparkle/stage/sprite/Sprite.java b/src/main/java/ru/fokinatorr/sparkle/stage/sprite/Sprite.java new file mode 100644 index 0000000..2278c4f --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/stage/sprite/Sprite.java @@ -0,0 +1,893 @@ +package ru.fokinatorr.sparkle.stage.sprite; + +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ReferenceObjectImmutablePair; +import lombok.AccessLevel; +import lombok.NonNull; +import lombok.experimental.FieldDefaults; +import lombok.experimental.PackagePrivate; +import ru.fokinatorr.sparkle.assets.Assets; +import ru.fokinatorr.sparkle.audio.AudioManager; +import ru.fokinatorr.sparkle.audio.SoundInstance; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap; +import ru.fokinatorr.sparkle.effect.sounds.SoundEffectMap; +import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher; +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.image.RasterImage; +import ru.fokinatorr.sparkle.graphics.image.SVGImage; +import ru.fokinatorr.sparkle.graphics.render.RenderCanvas; +import ru.fokinatorr.sparkle.graphics.render.renderer.Renderable2D; +import ru.fokinatorr.sparkle.graphics.vector.SVGVector; +import ru.fokinatorr.sparkle.internal.access.SharedSecrets; +import ru.fokinatorr.sparkle.internal.access.SpriteAccess; +import ru.fokinatorr.sparkle.internal.access.StageAccess; +import ru.fokinatorr.sparkle.phys2d.Hitbox2D; +import ru.fokinatorr.sparkle.phys2d.Point2D; +import ru.fokinatorr.sparkle.stage.RenderableID; +import ru.fokinatorr.sparkle.stage.Stage; +import ru.fokinatorr.sparkle.util.WaitUtils; +import ru.fokinatorr.sparkle.util.GUID; +import ru.fokinatorr.sparkle.util.Mth; +import ru.fokinatorr.sparkle.util.concurrent.atomic.AtomicDouble; +import ru.fokinatorr.sparkle.util.stopwatch.InstantStopwatch; +import ru.fokinatorr.sparkle.util.stopwatch.Stopwatch; +import ru.fokinatorr.sparkle.variable.AbstractVariableStorage; +import ru.fokinatorr.sparkle.variable.Variable; + +import java.awt.*; +import java.awt.geom.Rectangle2D; +import java.io.Serial; +import java.io.Serializable; +import java.nio.file.Path; +import java.util.*; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static ru.fokinatorr.sparkle.graphics.render.RenderCanvas.ORIGINAL_SIZE; +import static ru.fokinatorr.sparkle.util.WaitUtils.*; + +/** + * A general-purpose {@link Renderable2D 2D renderable} with Scratch-like API. + * Holds info like position, rotation, etc. Also has several basic operations. + *

On a {@link Stage}, this is a special case of a 2D renderable, since {@code Stage} supports cloning sprites, + * and thus sprites need special handling from {@code Stage}. + *

Note for Scratchers: This class's functionality is similar to Scratch's sprites. There are some differences, for example:
+ * in Scratch, sprites can access the current backdrop. + * In this implementation, the backdrop is a property of a {@code Stage}, not a {@code Sprite}. + * So, to access the current backdrop, you should use {@link Stage#getBackdropIndex()} or {@link Stage#getBackdropName()} + * on a {@code Stage} instance.
+ */ +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +public class Sprite extends AbstractVariableStorage implements Serializable, Renderable2D { + + static { + SharedSecrets.setSpriteAccess(new SpriteAccess() { + + @Override + public Pair getParent(Sprite sprite) { + return sprite.parentStage.get(); + } + + @Override + public void attach(Sprite sprite, Stage toStage, String spriteId, int cloneId) { + sprite.parentStage.set(new ReferenceObjectImmutablePair<>(toStage, new RenderableID.SpriteID(spriteId, cloneId))); + } + + @Override + public void detach(Sprite sprite) { + sprite.parentStage.set(null); + } + + @Override + public Sprite newSprite(Assets assets, GraphicEffectMap graphicEffects, SoundEffectMap soundEffects) { + return new Sprite(assets, graphicEffects, soundEffects); + } + }); + } + + @Serial + private static final long serialVersionUID = -7283596994843063991L; + private static final StageAccess stageAcc = SharedSecrets.getStageAccess(); + + AtomicDouble x = new AtomicDouble(); + AtomicDouble y = new AtomicDouble(); + AtomicDouble direction = new AtomicDouble(90); + AtomicReference rotationStyle = new AtomicReference<>(RotationStyle.ALL_AROUND); + AtomicDouble stretchX = new AtomicDouble(100); + AtomicDouble stretchY = new AtomicDouble(100); + AtomicReference bubbleState = new AtomicReference<>(BubbleState.EMPTY); + Assets assets; + AtomicInteger costumeIndex = new AtomicInteger(); // 0 by default + GraphicEffectMap graphicEffectMap; + AtomicBoolean visible = new AtomicBoolean(true); + SoundEffectMap soundEffectMap; + + @PackagePrivate + final AtomicReference> parentStage = new AtomicReference<>(); + + final Int2ObjectMap loadedCostumes = Int2ObjectMaps.synchronize(new Int2ObjectOpenHashMap<>()); + final Int2ObjectMap loadedSounds = Int2ObjectMaps.synchronize(new Int2ObjectOpenHashMap<>()); + + + /** + * Creates a new {@code Sprite} instance. + * + * @param assets the assets (costumes and sounds) + * @see Assets#fromLoaded(List, List) + * @see Assets#resolve(Path, Path) + */ + public Sprite(Assets assets) { + this(assets, new GraphicEffectMap(), new SoundEffectMap()); + } + + /** + * Internal constructor which is also used in {@link #copy()} method. + */ + Sprite(Assets assets, GraphicEffectMap graphicEffectMap, SoundEffectMap soundEffectMap) { + this.assets = assets; + this.graphicEffectMap = graphicEffectMap; + this.soundEffectMap = soundEffectMap; + } + + /** + * Creates and returns a deep copy of this sprite. + * + * @return a copy of this sprite + */ + public Sprite copy() { + Sprite copy = new Sprite(assets, graphicEffectMap.copy(), soundEffectMap.copy()); + copy.x.set(x.get()); + copy.y.set(y.get()); + copy.direction.set(direction.get()); + copy.rotationStyle.set(rotationStyle.get()); + copy.stretchX.set(stretchX.get()); + copy.stretchY.set(stretchY.get()); + copy.bubbleState.set(bubbleState.get()); + copy.costumeIndex.set(costumeIndex.get()); + copy.visible.set(visible.get()); + for (String varId : getVariables().keySet()) { + copy.registerVariable(varId, getVariable(varId).copy()); + } + return copy; + } + + // motion + + /** + * Move {@code steps} steps towards the current direction. + * + * @param steps steps to move + */ + public void moveSteps(double steps) { + double direction = Math.toRadians(this.direction.get()); + x.getAndAdd(Math.sin(direction) * steps); + y.getAndAdd(Math.cos(direction) * steps); + } + + /** + * Rotates right the given count of degrees. + * + * @param degrees degrees to rotate right + */ + public void rotateRight(double degrees) { + while (true) { + double currentDir = direction.get(); + double newDir = Mth.wrapClamp(currentDir + degrees, -180, 180); + if (direction.compareAndSet(currentDir, newDir)) { + break; + } + } + } + + /** + * Rotates left the given count of degrees. + * + * @param degrees degrees to rotate left + */ + public void rotateLeft(double degrees) { + rotateRight(-degrees); + } + + /** + * Moves to the given sprite's position. + * + * @param another the sprite to move to + * @throws NullPointerException if the given sprite is {@code null} + */ + public void copyPos(Sprite another) { + Objects.requireNonNull(another, "The given sprite is null"); + x.set(another.getX()); + y.set(another.getY()); + } + + /** + * Moves to the given coordinates. + * + * @param x the new x + * @param y the new y + */ + public void goTo(double x, double y) { + this.x.set(x); + this.y.set(y); + } + + /** + * Glides to the given sprite position for the given count of milliseconds. + * + * @param another the sprite to glide towards. The target position is not changed + * if this sprite moves while this one is gliding. + * @param millis how long to glide in milliseconds + * @throws NullPointerException if the given sprite is {@code null} + */ + public void glideTo(Sprite another, long millis) { + Objects.requireNonNull(another, "The given sprite is null"); + glide(another.getX(), another.getY(), millis); + } + + /** + * Glides at the given position for the given count of milliseconds. + * + * @param targetX x position to glide towards + * @param targetY y position to glide towards + * @param millis how long to glide in milliseconds + */ + public void glide(double targetX, double targetY, long millis) { + if (millis <= 0) { + // Duration too short to glide. + goTo(targetX, targetY); + } else { + double startX = x.get(); + double startY = y.get(); + Stopwatch stopwatch = new InstantStopwatch(); + stopwatch.start(); + while (true) { + long timeElapsed = stopwatch.timeElapsed(); + if (timeElapsed < millis) { + // Move to intermediate position. + double frac = (double) timeElapsed / millis; + double dx = frac * (targetX - startX); + double dy = frac * (targetY - startY); + goTo(startX + dx, startY + dy); + } else { + // Finished: move to final position. + goTo(targetX, targetY); + stopwatch.stop(); // Potentially free some memory + break; + } + } + } + } + + /** + * Sets the current direction to the given value. + * + * @param dir the new direction + */ + public void setDirection(double dir) { + direction.set(Mth.wrapClamp(dir, -180, 180)); + } + + /** + * Points towards the given sprite's position. + * + * @param another the sprite to point towards + * @throws NullPointerException if the given sprite is {@code null} + */ + public void pointTowards(Sprite another) { + Objects.requireNonNull(another, "The given sprite is null"); + pointTowards(another.getX(), another.getY()); + } + + /** + * Points towards the given position. + * + * @param targetX the X coordinate of the position + * @param targetY the Y coordinate of the position + */ + public void pointTowards(double targetX, double targetY) { + double dx = targetX - x.get(); + double dy = targetY - y.get(); + setDirection(90 - Math.toDegrees(Math.atan2(dy, dx))); + } + + /** + * Adds the given value to the x coordinate. + * + * @param dx the delta x + */ + public void changeX(double dx) { + x.getAndAdd(dx); + } + + /** + * Sets the x coordinate to the given value. + * + * @param x the new x + */ + public void setX(double x) { + this.x.set(x); + } + + /** + * Adds the given value to the y coordinate. + * + * @param dy the delta y + */ + public void changeY(double dy) { + y.getAndAdd(dy); + } + + /** + * Sets the y coordinate to the given value. + * + * @param y the new y + */ + public void setY(double y) { + this.y.set(y); + } + + /** + * Rotates away from the nearest edge. + * + * @throws IllegalStateException if not registered to a stage + * @see Stage#registerSprite(String, Sprite) + */ + public void bounce() { + var parentProps = parentStage.get(); + if (parentProps == null) { + throw new IllegalStateException("No registered in a stage"); + } + + Stage parent = parentProps.left(); + int width = parent.getWidth(), height = parent.getHeight(); + double dir = Math.toRadians(90 - getDirection()); + double dx = Math.cos(dir), dy = -Math.sin(dir); // negative dy to point away + // Measure distance to edges. + // Values are positive when the sprite is far away, 0 when right on the edge, negative when the sprite is beyond. + double + distLeft = width / 2d + getX(), + distTop = height / 2d - getY(), + distRight = width / 2d - getX(), + distBottom = height / 2d + getY(); + + // Point away from the nearest edge. + double minDist = Double.POSITIVE_INFINITY; + if (distLeft < minDist) { + minDist = distLeft; + } + if (distTop < minDist) { + minDist = distTop; + } + if (distRight < minDist) { + minDist = distRight; + } + if (distBottom < minDist) { + minDist = distBottom; + } + + if (minDist == distLeft) { + dx = Math.max(0.2, Math.abs(dx)); + } else if (minDist == distTop) { + dy = Math.max(0.2, Math.abs(dy)); + } else if (minDist == distRight) { + dx = -Math.max(0.2, Math.abs(dx)); + } else { + dy = -Math.max(0.2, Math.abs(dy)); + } + setDirection(Math.toDegrees(Math.atan2(dy, dx)) + 90); + } + + /** + * Updates the rotation style to the given value. + * + * @param newStyle the new rotation style + * @throws NullPointerException if the given value is {@code null} + */ + public void setRotationStyle(RotationStyle newStyle) { + Objects.requireNonNull(newStyle, "The given rotation style is null"); + rotationStyle.set(newStyle); + } + + /** + * {@return the current rotation style} + */ + public RotationStyle getRotationStyle() { + return rotationStyle.get(); + } + + /** + * {@return the current X coordinate} + */ + public double getX() { + return x.get(); + } + + /** + * {@return the current Y coordinate} + */ + public double getY() { + return y.get(); + } + + /** + * {@return the current direction} The minimal value is {@code -180} and the maximal value is + * {@code 180}. + */ + public double getDirection() { + return direction.get(); + } + + // looks + + /** + * Creates a text bubble near this sprite with the given text that lasts for the given count of milliseconds. + * Note: If any other thread executes say/think operation, the previous text bubble is discarded. + * + * @param text the text to appear in the bubble + * @param millis how long the text should last + */ + public void sayFor(String text, long millis) { + say(text); + removeTextBubbleAfter(millis); + } + + /** + * Creates a text bubble near this sprite with the given text that lasts until the next text bubble. + * Note: If any other thread executes say/think operation, the previous text bubble is discarded. + * + * @param text the text to appear in the bubble + */ + public void say(String text) { + bubbleState.set(new BubbleState(text, + BubbleState.BubbleType.SAY, + GUID.generate() + )); + } + + /** + * Creates a think cloud near this sprite with the given text that lasts for the given count of milliseconds. + * Note: If any other thread executes say/think operation, the previous text bubble is discarded. + * + * @param text the text to appear in the bubble + * @param millis how long the text should last + */ + public void thinkFor(String text, long millis) { + think(text); + removeTextBubbleAfter(millis); + } + + /** + * Creates a think cloud near this sprite with the given text that lasts until the next text bubble. + * Note: If any other thread executes say/think operation, the previous text bubble is discarded. + * + * @param text the text to appear in the bubble + */ + public void think(String text) { + bubbleState.set(new BubbleState(text, + BubbleState.BubbleType.THINK, + GUID.generate() + )); + } + + private void removeTextBubbleAfter(long millis) { + String usageId = bubbleState.get().getUsageId(); + assert usageId != null; + waitFor(millis); + // Only clear the bubble if it hasn't been changed before + if (bubbleState.get().getUsageId().equals(usageId)) { + bubbleState.set(BubbleState.EMPTY); + } + } + + /** + * {@return the current text bubble state} + */ + public BubbleState getBubbleState() { + return bubbleState.get(); + } + + /** + * Returns this sprite's assets (costumes and sounds). + * + * @return this sprite's assets + */ + @NonNull + public Assets getAssets() { + return assets; + } + + /** + * Sets the costume index to the given one. + *

Note for Scratchers: Unlike in Scratch, the first costume index value is {@code 0}. + * + * @param index the costume index + * @throws IndexOutOfBoundsException if no costume with the given index was found + */ + public void setCostume(int index) { + Objects.checkIndex(index, getAssets().texturesByIndex().size()); + costumeIndex.set(index); + } + + /** + * Sets the costume name to the given one. + * + * @param name the costume name + * @throws NullPointerException if the name is {@code null} + * @throws IndexOutOfBoundsException if no costume with the given name was found + */ + public void setCostume(String name) { + Objects.requireNonNull(name, "costume name"); + // IndexOutOfBoundsException is thrown if the map returns value less than 0 + setCostume(getAssets().texturesIndexesByName().getInt(name)); + } + + /** + * Increments the costume index, wrapping around if necessary. + */ + public void incrementCostume() { + int size = getAssets().texturesByIndex().size(); + costumeIndex.getAndUpdate(index -> (index + 1) % size); + } + + /** + * Decrements the costume index, wrapping around if necessary. + */ + public void decrementCostume() { + int size = getAssets().texturesByIndex().size(); + costumeIndex.getAndUpdate(index -> (index - 1 + size) % size); + } + + /** + * Changes the X axis stretch by the given count of percents. + * + * @param percents how much to change the X axis stretch + */ + public void changeStretchX(double percents) { + stretchX.getAndUpdate(stretch -> Math.max(0, stretch + percents)); + } + + /** + * Changes the Y axis stretch by the given count of percents. + * + * @param percents how much to change the Y axis stretch + */ + public void changeStretchY(double percents) { + stretchY.getAndUpdate(stretch -> Math.max(0, stretch + percents)); + } + + /** + * Changes both X and Y axis stretches by the given count of percents. + * + * @param percents how much to change the size + */ + public void changeSize(double percents) { + changeStretchX(percents); + changeStretchY(percents); + } + + /** + * Sets the X axis stretch to the given value. + * + * @param newStretch the new X axis stretch + */ + public void setStretchX(double newStretch) { + stretchX.set(Math.max(0, newStretch)); + } + + /** + * Sets the Y axis stretch to the given value. + * + * @param newStretch the new Y axis stretch + */ + public void setStretchY(double newStretch) { + stretchY.set(Math.max(0, newStretch)); + } + + /** + * Sets both X and Y stretches to the given value. + * + *

Note for Scratchers: In this sprite implementation, there is no {@code getSize()}, + * since size is stored as two separate properties: {@link #getStretchX() X stretch} and + * {@link #getStretchY() Y stretch}. If you're sure they're always equal, you can use either + * of these properties to determine the size. + * + * @param newSize the new size + */ + public void setSize(double newSize) { + setStretchX(newSize); + setStretchY(newSize); + } + + /** + * Returns this sprite's graphic effect map, i.e. an object storing values of graphic effects. + * It is mutable, i.e. can be changed. + *

Note for Scratchers: This method can be used for both changing effect values, setting them, and clearing, + * either all effects, or the preferred one. Example usages: + *


+     * sprite.getGraphicEffects().put(GraphicEffect.OPACITY, 100.0); // Equivalent to "set ghost effect to 100" block
+     * // To convert Scratch's "color" effect value to hue degrees, multiply it by 1.8
+     * sprite.getGraphicEffects().increment(GraphicEffect.HUE_SHIFT, 45.0); // Equivalent to "change color effect by 25" block
+     * sprite.getGraphicEffects().clear(); // Equivalent to "clear graphic effects" block
+     * double pixelationValue = sprite.getGraphicEffects().getDouble(GraphicEffect.PIXELATION); // retrieve the current value without changing
+     * double oldWhirlValue = sprite.getGraphicEffects().removeDouble(GraphicEffect.WHIRL); // sets the value to 0.0, returning the old value
+     * 
+ * + * @return the graphic effect map + */ + public GraphicEffectMap getGraphicEffects() { + return graphicEffectMap; + } + + /** + * Shows this sprite if the given value is {@code true}, or hides this sprite otherwise. + *

When a sprite is visible, it is rendered on the stage. When it is hidden, it is not rendered, + * but it still exists and can continue to execute code. + *

Note for Scratchers: This method matches the functionality of "show" and "hide" blocks. + * + * @param visible {@code true} to show this sprite, {@code false} to hide it. + */ + public void setVisible(boolean visible) { + this.visible.set(visible); + } + + @Override + public void render(RenderCanvas canvas) { + var parentProps = parentStage.get(); + if (parentProps == null) { + throw new IllegalStateException("Not registered in a stage"); + } + + canvas.save(); + canvas.setEffects(graphicEffectMap); + Stage parent = parentProps.left(); + Image costumeAsImage = getCurrentCostumeImage(stageAcc.getContext(parent)); + GraphicsUtils.drawImageOriginCenter(canvas, costumeAsImage, 0, 0, ORIGINAL_SIZE, ORIGINAL_SIZE); + canvas.restore(); + } + + @Override + public Hitbox2D getHitbox() { + var parentProps = parentStage.get(); + if (parentProps == null) { + throw new IllegalStateException("Not registered in a stage"); + } + + Stage parent = parentProps.left(); + AppContext context = stageAcc.getContext(parent); + Image costumeAsImage = getCurrentCostumeImage(stageAcc.getContext(parent)); + + if (costumeAsImage instanceof SVGImage svg) { + List vectors = svg.getVectors(); + return Hitbox2D.or( + vectors.stream() + .map(SVGVector::vector) + .map(Hitbox2D::shape) + .toArray(Hitbox2D[]::new) + ); + } else if (costumeAsImage instanceof RasterImage raster) { + PixelReader reader = costumeAsImage.createPixelReader(); + // TODO outline + return null; + } else { + // Fallback: bounding box + PixelReader reader = costumeAsImage.createPixelReader(); + return Hitbox2D.shape(new Rectangle2D.Double( + getX() - reader.getWidth() / 2d, + getY() - reader.getHeight() / 2d, + reader.getWidth(), + reader.getHeight() + )); + } + } + + /** + * Returns whether this sprite is visible. + *

A visible sprite is rendered on the stage, while a hidden sprite is not. However, a hidden sprite + * still exists and can continue to execute code. + * + * @return {@code true} if this sprite is visible, {@code false} otherwise. + */ + public boolean isVisible() { + return visible.get(); + } + + /** + * {@return the current costume index} + *

Note for Scratchers: This method matches the functionality of "costume number" block. + */ + public int getCostumeIndex() { + return costumeIndex.get(); + } + + /** + * {@return the current costume name} + */ + public String getCostumeName() { + return getAssets().texturesByIndex().get(costumeIndex.get()).name(); + } + + /** + * Returns the current X axis stretch. + * + * @return the X axis stretch + */ + public double getStretchX() { + return stretchX.get(); + } + + /** + * Returns the current Y axis stretch. + * + * @return the Y axis stretch + */ + public double getStretchY() { + return stretchY.get(); + } + + // sound + + /** + * Starts playing a sound with the given name. This sprite's sound effects will be applied. + * + * @param soundName the sound name + * @return the control ID of the sound. Can be used to stop the sound or change its effects. + * @throws IndexOutOfBoundsException if there is no sound with the given name in assets. + */ + public String startSound(String soundName) { + return startSound(soundName, false, false); + } + + /** + * Starts playing a sound with the given name. This sprite's sound effects will be applied. + * + * @param soundName the sound name + * @param waitForDone whether to wait until the sound finished playing. If set to {@code true}, the return value + * is essentially useless. + * @return the control ID of the sound. Can be used to stop the sound or change its effects. + * @throws IndexOutOfBoundsException if there is no sound with the given name in assets. + */ + public String startSound(String soundName, boolean waitForDone) { + return startSound(soundName, waitForDone, false); + } + + /** + * Starts playing a sound with the given name. + * + * @param soundName the sound name + * @param soundEffects the sound effect map to use. The changes made to the given map are reflected on the + * playing sound. + * @return the control ID of the sound. Can be used to stop the sound or change its effects. + * @throws IndexOutOfBoundsException if there is no sound with the given name in assets. + */ + public String startSound(String soundName, SoundEffectMap soundEffects) { + return startSound(soundName, false, soundEffects); + } + + /** + * Starts playing a sound with the given name. This sprite's sound effects will be applied. + * + * @param soundName the sound name + * @param copySoundEffects whether to copy the sound effect map. + * Set this to {@code true} if you do not want this sprite's sound effect map changes + * to affect the sound. + * @param waitForDone whether to wait until the sound finished playing. If set to {@code true}, the return value + * is essentially useless. + * @return the control ID of the sound. Can be used to stop the sound or change its effects. + * @throws IndexOutOfBoundsException if there is no sound with the given name in assets. + */ + public String startSound(String soundName, boolean waitForDone, boolean copySoundEffects) { + return startSound( + soundName, + waitForDone, + copySoundEffects ? soundEffectMap.copy() : soundEffectMap + ); + } + + /** + * Starts playing a sound with the given name. + * + * @param soundName the sound name + * @param soundEffects the sound effect map to use. The changes made to the given map are reflected on the + * playing sound. + * @param waitForDone whether to wait until the sound finished playing. If set to {@code true}, the return value + * is essentially useless. + * @return the control ID of the sound. Can be used to stop the sound or change its effects. + * @throws IndexOutOfBoundsException if there is no sound with the given name in assets. + */ + public String startSound(String soundName, boolean waitForDone, SoundEffectMap soundEffects) { + var parentProps = parentStage.get(); + if (parentProps == null) { + throw new IllegalStateException("Not registered in a stage"); + } + + Stage parent = parentProps.left(); + AudioManager audioManager = stageAcc.getContext(parent).get(AudioManager.class); + + String soundId = loadedSounds.computeIfAbsent( + getAssets().texturesIndexesByName().getInt(soundName), + index -> audioManager.createStaticSoundInstance(getAssets().soundsByIndex().get(index).location()).left() + ); + SoundInstance sound = audioManager.getSoundInstance(soundId); + sound.attachProperties(soundEffects); + sound.play(); + if (waitForDone) { + waitUntil(() -> sound.getState() == SoundInstance.State.STOPPED); + } + return soundId; + } + + /** + * Returns this sprite's sound effect map, i.e. an object storing values of sound effects. + * It is mutable, i.e. can be changed. This is also the default sound effect map for playing sounds. + *

Note for Scratchers: This method can be used for both changing effect values, setting them, and clearing, + * either all effects, or the preferred one. Example usages: + *


+     *       sprite.getSoundEffects().put(SoundEffect.VOLUME, 80.0); // Equivalent to "set volume to 80" block
+     *       sprite.getSoundEffects().increment(SoundEffect.PITCH, 45.0); // Equivalent to "change pitch effect by 25" block
+     *       sprite.getSoundEffects().clear(); // Equivalent to "clear sound effects" block
+     *       double panValue = sprite.getSoundEffects().getDouble(SoundEffect.PAN); // retrieve the current value
+     * 
+ * + * @return the sound effect map + */ + public SoundEffectMap getSoundEffects() { + return soundEffectMap; + } + + /** + * Events: Methods related to event handling are not present in the Sprite class + * because Sprites are passive targets, and not the entities that execute code. + * Instead, event processing is the responsibility of the {@link EventDispatcher}. + *

+ * Controls: Methods related to control flow, such as loops and conditional statements, + * are largely handled by standard Java features. Specific Scratch control blocks are + * addressed as follows: + *

    + *
  1. + * Many of the Scratch control blocks have direct equivalents in standard Java + * (e.g., {@code if}, {@code for}, {@code while}). + *
  2. + *
  3. + * Cloning and clone management are handled by the {@link Stage} class. + * See the {@link Stage#createClone(String)} and {@link Stage#deleteClone(String, int)} + * methods. + *
  4. + *
  5. + * The "wait for" and "wait until" blocks can be found in the {@link WaitUtils} + * class (also not a responsibility of the Sprite). + *
  6. + *
+ */ + @SuppressWarnings("unused") + private void WhyEventsAndControlsAreAbsent() { + } + + @Override + protected Map> createVariables() { + return new ConcurrentHashMap<>(); + } + + + private Image getCurrentCostumeImage(AppContext ctx) { + return loadedCostumes.computeIfAbsent( + getCostumeIndex(), + idx -> { + GraphicsManager graphicsManager = ctx.get(GraphicsManager.class); + Path imgPath = assets.texturesByIndex().get(idx).location(); + return graphicsManager.hasLoadedImage(imgPath) + ? graphicsManager.loadImage(imgPath, true) + : graphicsManager.getLoadedImage(imgPath); + } + ); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/BufferUtils.java b/src/main/java/ru/fokinatorr/sparkle/util/BufferUtils.java new file mode 100644 index 0000000..c2eb1b6 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/BufferUtils.java @@ -0,0 +1,163 @@ +package ru.fokinatorr.sparkle.util; + +import lombok.experimental.UtilityClass; +import org.lwjgl.system.MemoryUtil; + +import java.io.*; +import java.nio.*; +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; + +import static org.lwjgl.system.MemoryUtil.*; + +/** + * Several utilities for {@link java.nio} {@link Buffer} API. + */ +@UtilityClass +public class BufferUtils { + + // Stream utilities + + /** + * Creates a stream over the given {@link ByteBuffer} without copying its data into the heap. + * @param buffer the buffer + * @throws NullPointerException if the buffer is {@code null} + * @return a new stream with the given buffer as a source + */ + public IntStream stream(ByteBuffer buffer) { + ByteBuffer copy = memDuplicate(Objects.requireNonNull(buffer, "buffer")); + return IntStream.generate(copy::get).limit(copy.remaining()); + } + + /** + * Creates a stream over the given {@link ShortBuffer} without copying its data into the heap. + * @param buffer the buffer + * @throws NullPointerException if the buffer is {@code null} + * @return a new stream with the given buffer as a source + */ + public IntStream stream(ShortBuffer buffer) { + ShortBuffer copy = memDuplicate(Objects.requireNonNull(buffer, "buffer")); + return IntStream.generate(copy::get).limit(copy.remaining()); + } + + /** + * Creates a stream over the given {@link CharBuffer} without copying its data into the heap. + * @param buffer the buffer + * @throws NullPointerException if the buffer is {@code null} + * @return a new stream with the given buffer as a source + */ + public IntStream stream(CharBuffer buffer) { + CharBuffer copy = memDuplicate(Objects.requireNonNull(buffer, "buffer")); + return IntStream.generate(copy::get).limit(copy.remaining()); + } + + /** + * Creates a stream over the given {@link IntBuffer} without copying its data into the heap. + * @param buffer the buffer + * @throws NullPointerException if the buffer is {@code null} + * @return a new stream with the given buffer as a source + */ + public IntStream stream(IntBuffer buffer) { + IntBuffer copy = memDuplicate(Objects.requireNonNull(buffer, "buffer")); + return IntStream.generate(copy::get).limit(copy.remaining()); + } + + /** + * Creates a stream over the given {@link LongBuffer} without copying its data into the heap. + * @param buffer the buffer + * @throws NullPointerException if the buffer is {@code null} + * @return a new stream with the given buffer as a source + */ + public LongStream stream(LongBuffer buffer) { + LongBuffer copy = memDuplicate(Objects.requireNonNull(buffer, "buffer")); + return LongStream.generate(copy::get).limit(copy.remaining()); + } + + /** + * Creates a stream over the given {@link FloatBuffer} without copying its data into the heap. + * @param buffer the buffer + * @throws NullPointerException if the buffer is {@code null} + * @return a new stream with the given buffer as a source + */ + public DoubleStream stream(FloatBuffer buffer) { + FloatBuffer copy = memDuplicate(Objects.requireNonNull(buffer, "buffer")); + return DoubleStream.generate(copy::get).limit(copy.remaining()); + } + + /** + * Creates a stream over the given {@link DoubleBuffer} without copying its data into the heap. + * @param buffer the buffer + * @throws NullPointerException if the buffer is {@code null} + * @return a new stream with the given buffer as a source + */ + public DoubleStream stream(DoubleBuffer buffer) { + DoubleBuffer copy = memDuplicate(Objects.requireNonNull(buffer, "buffer")); + return DoubleStream.generate(copy::get).limit(copy.remaining()); + } + + private static final int READ_FULLY_CHUNK_SIZE = 8192; + + /** + * Reads all bytes from the input stream into a direct {@link ByteBuffer}. + * The input stream must be finite, otherwise reading may block forever! + *

The buffer must be explicitly freed with {@link MemoryUtil#memFree(Buffer)}; + * you can also use {@link #freeing(Buffer)} to represent the buffer as an {@link AutoCloseable}. + * @param in the input stream + * @return a new direct buffer + * @throws IOException if an I/O error occurs + * @throws NullPointerException if the input stream is {@code null} + */ + public ByteBuffer readFully(InputStream in) throws IOException { + Objects.requireNonNull(in, "input stream"); + + long sizeHint = 0; + if (in instanceof FileInputStream fis) { + sizeHint = fis.getChannel().size(); + } + + ByteArrayOutputStream buf = new ByteArrayOutputStream( + (int) Math.min(sizeHint > 0 ? sizeHint : READ_FULLY_CHUNK_SIZE, Integer.MAX_VALUE) + ); + + byte[] chunk = new byte[READ_FULLY_CHUNK_SIZE]; + int n; + while ((n = in.read(chunk)) != -1) { + buf.write(chunk, 0, n); + } + + byte[] data = buf.toByteArray(); + ByteBuffer result = memAlloc(data.length) // malloc for uninitialized contents + .put(data) + .flip(); + // clear potentially sensitive data; maybe also a hint for GC? + Arrays.fill(chunk, (byte) -1); + Arrays.fill(data, (byte) -1); + return result; + } + + // Auto freeing + + /** + * Returns an {@link AutoCloseable} that will free the given buffer's memory address + * in its {@link AutoCloseable#close() close()} method. This method should only be used when the buffer + * was allocated using {@link MemoryUtil}'s {@code (n)memAllocXxx()}, {@code (n)memCallocXxx()} or + * {@code (n)memReallocXxx()} methods. + *

A typical usage would be creating an unnamed variable in the {@code try}-with-resources + * statement like this: + * {@snippet : + * ByteBuffer bb = MemoryUtil.memAlloc(1024); + * try (var _ = freeing(bb)) { + * // do some stuff with the buffer + * } + * } + * @param ptr the buffer to free + * @return an {@link AutoCloseable} that frees the given buffer + */ + @SuppressWarnings("EmptyTryBlock") + public NonThrowingAutoCloseable freeing(Buffer ptr) { + return () -> memFree(ptr); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/Constants.java b/src/main/java/ru/fokinatorr/sparkle/util/Constants.java new file mode 100644 index 0000000..b2e3d34 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/Constants.java @@ -0,0 +1,55 @@ +package ru.fokinatorr.sparkle.util; + +import lombok.experimental.UtilityClass; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.context.AppContextHolder; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.util.Map; +import java.util.Random; + +/** + * Utility class holding public constants. + *

Note: Heavy/stateful objects should not be stored here; use the application context for that matter. + * @see AppContext + * @see AppContextHolder + * @see Global + */ +@UtilityClass +public class Constants { + + /** + * The common random generator. + */ + public static final Random RANDOM = new Random(); + /** + * The resources root path (useful for loading). + */ + public static final Path ROOT; + /** + * The number of nanoseconds in a millisecond. + */ + public static final long NANOS_PER_MILLISECOND = 1_000_000L; + /** + * The number of milliseconds in a second. + */ + public static final long MILLIS_PER_SECOND = 1_000L; + /** + * The number of nanoseconds in a second. + */ + public static final long NANOS_PER_SECOND = NANOS_PER_MILLISECOND * MILLIS_PER_SECOND; + + static { + try { + //noinspection DataFlowIssue + ROOT = Path.of(Constants.class.getResource("/").toURI()); + } catch (Exception e) { + throw new ExceptionInInitializerError(e); + } + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/DebugUtils.java b/src/main/java/ru/fokinatorr/sparkle/util/DebugUtils.java new file mode 100644 index 0000000..d024423 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/DebugUtils.java @@ -0,0 +1,53 @@ +package ru.fokinatorr.sparkle.util; + +import lombok.experimental.UtilityClass; +import lombok.extern.slf4j.Slf4j; + +import static java.lang.management.ManagementFactory.getRuntimeMXBean; + +/** + * Debugging utilities. + *

This class provides methods that integrate with IDE debuggers, + * such as triggering a breakpoint programmatically via user action + * (e.g., clicking a "Pause" button in the UI). + *

This is useful for headless or embedded environments where traditional + * breakpoints are hard to trigger deterministically. + *

Note: This is not a JVM standard feature and relies on your IDE. + * Breakpoints exist in most modern IDEs (IntelliJ IDEA, Eclipse, VS Code, etc.). + * See {@link #debugSuspend()} for usage details. + */ +@Slf4j +@UtilityClass +public class DebugUtils { + + /** + * Suspends the program execution. + *

To use: + *

    + *
  1. + * See the source file and place a breakpoint at the correct line (marked by a comment) + *
  2. + *
  3. + * Ensure a debugger is attached + *
  4. + *
  5. + * Call this method (e.g. using the stage's pause button) + *
  6. + *
+ */ + public void debugSuspend() { + log.info("[DebugUtils] Suspending execution..."); + log.info("[DebugUtils] Resuming execution..."); // PLACE A BREAKPOINT HERE! + } + + /** + * Checks whether a debugger is currently attached. + *

+ * Useful to avoid unnecessary logging or actions when not in debug mode. + * + * @return {@code true} if debugger is likely attached + */ + public boolean isDebuggerAttached() { + return getRuntimeMXBean().getInputArguments().toString().contains("jdwp"); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/GUID.java b/src/main/java/ru/fokinatorr/sparkle/util/GUID.java new file mode 100644 index 0000000..c55c380 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/GUID.java @@ -0,0 +1,52 @@ +package ru.fokinatorr.sparkle.util; + +import lombok.experimental.UtilityClass; + +import java.security.SecureRandom; +import java.util.random.RandomGenerator; + +/** + * UID generator, from Blockly. Taken from Scratch's source code and changed it to use a secure RNG. + *

+ * GUID stands for "Globally Unique Identifier", and produces short, safe strings + * ideal for block IDs, sprite names, etc. + */ +@UtilityClass +public class GUID { + + /** + * Legal characters for the unique ID. + * Should be all on a US keyboard. No XML special characters or control codes. + */ + private static final char[] SOUP + = "!#%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray(); + + /** + * The length of a UID. + */ + private static final int LENGTH = 20; + + /** + * The length of the legal characters array. Cached because UIDs are created constantly. + */ + private static final int SOUP_LENGTH = SOUP.length; + + /** + * A cryptographically strong RNG, like in UUID. + */ + private static final RandomGenerator RNG = new SecureRandom(); + + /** + * Generates a new UID. This should be globally unique. + *

87 characters ^ 20 length > 128 bits (better than a UUID). + * + * @return A globally unique ID string. + */ + public String generate() { + StringBuilder id = new StringBuilder(); + for (int i = 0; i < LENGTH; i++) { + id.append(SOUP[RNG.nextInt(SOUP_LENGTH)]); + } + return id.toString(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/Global.java b/src/main/java/ru/fokinatorr/sparkle/util/Global.java new file mode 100644 index 0000000..4cbb446 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/Global.java @@ -0,0 +1,192 @@ +package ru.fokinatorr.sparkle.util; + +import lombok.experimental.UtilityClass; +import ru.fokinatorr.sparkle.audio.AudioManager; +import ru.fokinatorr.sparkle.audio.io.SoundDecoder; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.context.AppContextHolder; +import ru.fokinatorr.sparkle.context.DefaultAppContext; +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.graphics.GraphicsManager; +import ru.fokinatorr.sparkle.graphics.font.FontProvider; +import ru.fokinatorr.sparkle.graphics.render.renderer.RendererRegistry; + +import java.lang.ref.Cleaner; +import java.lang.reflect.InaccessibleObjectException; +import java.util.Collection; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.function.Consumer; + +/** + * Global access to services via the current application context. + *

+ * This is a convenience utility for deep-framework code or user scripts + * that don't want to pass {@link AppContext} explicitly. + *

+ * The application context created using {@link DefaultAppContext#createWithDefaults()} contains the following default components: + *

    + *
  • + * {@link ScheduledExecutorService} (lazy): creates threads that inherit the {@code AppContext} + * of the creator thread so you can use it instead of creating threads manually; + *
  • + *
  • + * {@link EventDispatcher}: the global event dispatcher; + *
  • + *
  • + * {@link Cleaner} (lazy): can be used to clean up resources once an object is no longer used; + *
  • + *
  • + * {@link AudioManager} (lazy, not in {@link DefaultAppContext#createHeadless() headless}): loads & plays sounds; + *
  • + *
  • + * {@link SoundDecoder} (not in headless): decodes sound files (mostly used by the audio manager); + *
  • + *
  • + * {@link GraphicsManager} (lazy, not in headless): manages rendering contexts; + *
  • + *
  • + * {@link RendererRegistry} (not in headless): provides renderers for objects (mostly used by the graphics manager); + *
  • + *
  • + * {@link FontProvider} (not in headless): provides TTF fonts (mostly used by the graphics manager). + *
  • + *
+ *

+ * Example: + *


+ *    AudioManager audioManager = Global.get(AudioManager.class);
+ *    audioManager.loadSound(Path.of("ambient.ogg"));
+ *    // ...
+ * 
+ * Another example: + *

+ *     Global.when(StartEvent.class, e -> {
+ *         System.out.println("Green flag clicked!");
+ *         Stage stage = e.getStage();
+ *         // prepare for execution (only preparation code must be here!)
+ *     });
+ * 
+ * + * @see AppContext + * @see AppContextHolder + */ +@UtilityClass +public class Global { + + // + + /** + * Gets a component instance from the global context by the given type. + *

This is a shortcut for {@code AppContextHolder.getContextOrThrow().get(type)}. + * + * @param type the type that was used to register the component (usually an interface type) + * @param the type of the component + * @return the component instance + * @throws IllegalStateException if there is no context for the current thread + * @throws IllegalArgumentException if no components were registered under the given type + * @throws NullPointerException if type is {@code null}, or if there's a lazy component registered under that type + * in the global context and its factory function returns {@code null} + */ + public T get(Class type) { + return AppContextHolder.getContextOrThrow().get(type); + } + + /** + * Gets all component instances from the global context by the given type. + *

This is a shortcut for {@code AppContextHolder.getContextOrThrow().getAll(type)}. + * + * @param type the type (usually an interface type) + * @param the common supertype of the components + * @return all components registered under that type + * @throws IllegalStateException if there is no context for the current thread + * @throws IllegalArgumentException if no components were registered under the given type + * @throws NullPointerException if type is {@code null}, or if there's a lazy component registered under that type + * in the global context and its factory function returns {@code null} + */ + public Collection getAll(Class type) { + return AppContextHolder.getContextOrThrow().getAll(type); + } + + // + // + + /** + * Adds a listener to the global event dispatcher (the event dispatcher registered in the global context). + *

This is a shortcut for: + *
{@code AppContextHolder.getContextOrThrow().get(EventDispatcher.class).addListener(...)}. + * + * @param eventClass the type of the event + * @param listener the listener to add + * @return an object that can be used to remove the listener + * @throws IllegalStateException if there is no context for the current thread + * @see EventDispatcher#addListener(Class, Consumer) + */ + public ListenerRemover when(Class eventClass, Consumer listener) { + return AppContextHolder.getContextOrThrow().get(EventDispatcher.class).addListener(eventClass, listener); + } + + /** + * The behaviour of this method depends on the type of the given object: + *

    + *
  1. + * if the given object is a {@link Class} object: registers all static methods annotated with {@link EventListener @EventListener} + * in the class represented by the object as event listeners in the global event dispatcher + * (the event dispatcher registered in the global context); + *
  2. + *
  3. + * if the given object is not a {@link Class} object: registers all instance methods annotated with {@link EventListener @EventListener} + * in the class of the object as event listeners in the global event dispatcher. + *
  4. + *
+ *

This is a shortcut for: + *
{@code AppContextHolder.getContextOrThrow().get(EventDispatcher.class).register(...)}. + * @param o the object + * @return an object that can be used to remove the listeners + * @throws IllegalStateException if there is no context for the current thread + * @throws IllegalArgumentException if a method annotated with {@link EventListener @EventListener} has invalid arguments + * @throws InaccessibleObjectException if a method could not be reflectively accessed for any reason + * @throws NullPointerException if the object is {@code null} (implementation-dependent) + * @see EventDispatcher#register(Object) + * @see EventListener + */ + public ListenerRemover registerEventListener(Object o) { + return AppContextHolder.getContextOrThrow().get(EventDispatcher.class).register(o); + } + + /** + * Fires the given event on the global event dispatcher (the event dispatcher registered in the global context), + * returning immediately. + *

This is a shortcut for: + *
{@code AppContextHolder.getContextOrThrow().get(EventDispatcher.class).fireEvent(...);} + * + * @param event the event to fire + * @return a {@link CompletableFuture} that completes when all event handlers are done + * @throws IllegalStateException if there is no context for the current thread + * @throws NullPointerException if the given event is {@code null} (implementation-dependent) + * @see EventDispatcher#fireEvent(Event) + */ + public CompletableFuture fire(Event event) { + return AppContextHolder.getContextOrThrow().get(EventDispatcher.class).fireEvent(event); + } + + /** + * Fires the given event on the global event dispatcher (the event dispatcher registered in the global context), + * and waits until all event listeners finish executing. + *

This is a shortcut for: + *
{@code AppContextHolder.getContextOrThrow().get(EventDispatcher.class).fireEventAndWait(...);} + * + * @param event the event to fire + * @throws IllegalStateException if there is no context for the current thread + * @throws NullPointerException if the given event is {@code null} (implementation-dependent) + * @see EventDispatcher#fireEventAndWait(Event) + */ + public void fireAndWait(Event event) { + AppContextHolder.getContextOrThrow().get(EventDispatcher.class).fireEventAndWait(event); + } + + // +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/Mth.java b/src/main/java/ru/fokinatorr/sparkle/util/Mth.java new file mode 100644 index 0000000..0599298 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/Mth.java @@ -0,0 +1,75 @@ +package ru.fokinatorr.sparkle.util; + +import lombok.experimental.UtilityClass; + +import java.util.random.RandomGenerator; + +/** + * Several other math utilities. + */ +@UtilityClass +public class Mth { + + /** + * Returns {@code value} clamped between {@code min} and {@code max}. + * @param value the value to clamp + * @param min the min value + * @param max the max value + */ + public double clamp(double value, double min, double max) { + return Math.clamp(value, min, max); + } + + /** + * Returns {@code value} clamped between {@code min} and {@code max}. + * @param value the value to clamp + * @param min the min value + * @param max the max value + */ + public int clamp(long value, int min, int max) { + return Math.clamp(value, min, max); + } + + /** + * Returns {@code value} wrap-around clamped between {@code min} and {@code max} + * (the result is clamped to the range {@code [min, max)}). + * @param value the value to clamp + * @param min the min value + * @param max the max value + * @throws IllegalArgumentException if {@code min} is more than or equal to {@code max} + */ + public double wrapClamp(double value, double min, double max) { + if (min >= max) { + throw new IllegalArgumentException("min should be less than max"); + } + // I honestly don't know how this even works + double range = max - min; + double diff = value - min; + double wrapped = diff % range; + if (wrapped < 0) { + wrapped += range; + } + return min + wrapped; + } + + /** + * Returns {@code value} wrap-around clamped between {@code min} and {@code max} + * (the result is clamped to the range {@code [min, max)}). + * @param value the value to clamp + * @param min the min value + * @param max the max value + * @throws IllegalArgumentException if {@code min} is more than or equal to {@code max} + */ + public int wrapClamp(int value, int min, int max) { + if (min >= max) { + throw new IllegalArgumentException("min should be less than max"); + } + int range = max - min; + int diff = value - min; + int wrapped = diff % range; + if (wrapped < 0) { + wrapped += range; + } + return min + wrapped; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/NonThrowingAutoCloseable.java b/src/main/java/ru/fokinatorr/sparkle/util/NonThrowingAutoCloseable.java new file mode 100644 index 0000000..a840074 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/NonThrowingAutoCloseable.java @@ -0,0 +1,21 @@ +package ru.fokinatorr.sparkle.util; + +/** + * An {@link AutoCloseable} that doesn't throw checked exceptions in its {@link #close()} method. + * This interface can be also converted into {@link Runnable} for convenience. + */ +public interface NonThrowingAutoCloseable extends AutoCloseable { + + /** + * {@inheritDoc} This method is not expected to throw any checked exceptions. + */ + @Override + void close(); + + /** + * Creates and returns a {@link Runnable} which closes this object when run. + */ + default Runnable asRunnable() { + return this::close; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/TypeReference.java b/src/main/java/ru/fokinatorr/sparkle/util/TypeReference.java new file mode 100644 index 0000000..135acb6 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/TypeReference.java @@ -0,0 +1,35 @@ +package ru.fokinatorr.sparkle.util; + +import lombok.Getter; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +/** + * A class used for reifying generic types. Used by creating an anonymous subclass, like this: + * {@snippet : + * TypeReference typeRef = new TypeReference<>() {}; + * Type type = typeRef.getType(); // In this example, returns String.class + * // do something with the type... + * } + * @implNote The class only works when creating a direct subclass. Otherwise, the constructor may throw + * a {@link ClassCastException}. + * @param the type to reify + */ +@Getter +@SuppressWarnings("unused") +public abstract class TypeReference { + + /** + * Returns the reified type. It may be a class if it was explicitly specified, or a wildcard type, or a + * type parameter. + */ + private final Type type; + + /** + * Creates a new {@code TypeReference}. + */ + protected TypeReference() { + this.type = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/Version.java b/src/main/java/ru/fokinatorr/sparkle/util/Version.java new file mode 100644 index 0000000..e323e83 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/Version.java @@ -0,0 +1,57 @@ +package ru.fokinatorr.sparkle.util; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; + +import static lombok.AccessLevel.PRIVATE; + +/** + * Framework version info. + *

Used mostly for logging/debugging purposes. + */ +@Getter +@RequiredArgsConstructor +@FieldDefaults(makeFinal = true, level = PRIVATE) +public enum Version { + V0_1_BETA(0, 1, 0, "0.1-beta"); + + // Prepend new versions to the top + + /** + * Major version (0 for betas). + *

Incremented for breaking changes. + */ + int major; + /** + * Minor release number. + *

Incremented for new features, backward-compatible. + */ + int minor; + /** + * Patch version. + *

Incremented for purely bugfix updates. + */ + int patch; + /** + * Name of the version. + */ + String name; + + Version(int major, int minor, int patch) { + this(major, minor, patch, major + "." + minor + "." + patch); + } + + @Override + public String toString() { + return name; + } + + /** + * Returns the current version of the framework. + * @return the current version + */ + public static Version current() { + return values()[0]; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/WaitUtils.java b/src/main/java/ru/fokinatorr/sparkle/util/WaitUtils.java new file mode 100644 index 0000000..b7f01df --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/WaitUtils.java @@ -0,0 +1,68 @@ +package ru.fokinatorr.sparkle.util; + +import lombok.experimental.UtilityClass; + +import java.util.concurrent.locks.LockSupport; +import java.util.function.BooleanSupplier; + +import static ru.fokinatorr.sparkle.util.Constants.NANOS_PER_MILLISECOND; + +/** + * This class has methods for accurate waiting. + *

Note for Scratchers: This class matches the functionality of Scratch's + * [wait () seconds] and [wait until <>] blocks, and also the functionality of + * PenguinMod's [wait () seconds or until <>] block. + */ +@UtilityClass +public class WaitUtils { + + /** + * Waits for the given count of milliseconds and returns. + * @param millis the milliseconds count; if non-positive, returns immediately + */ + public void waitFor(long millis) { + if (millis > 0) { + LockSupport.parkNanos(millis * NANOS_PER_MILLISECOND); + } + } + + /** + * Waits until the given condition supplier evaluates to {@code true}. Note that + * using this method instead of {@link #waitForOrUntil(BooleanSupplier, long)} can lead to + * an indefinite stall if the given supplier never evaluates to {@code true}. + * @param condition the condition supplier, must not be {@code null} + */ + public void waitUntil(BooleanSupplier condition) { + if (condition.getAsBoolean()) return; + while (!condition.getAsBoolean()) { + LockSupport.parkNanos(NANOS_PER_MILLISECOND); // 1ms + } + } + + /** + * Waits until the given condition supplier evaluates to {@code true} or until the given timeout is reached, + * then returns. + * @param condition the condition supplier; must not be {@code null} + * @param timeoutMillis how much to wait for the condition supplier evaluating to {@code true}; if non-positive, + * this method returns {@code !condition.getAsBoolean()} immediately + * @return whether the timeout was reached before the condition evaluated to {@code true} + */ + public boolean waitForOrUntil(BooleanSupplier condition, long timeoutMillis) { + if (condition.getAsBoolean()) { + return false; + } else if (timeoutMillis <= 0) { + return true; + } + + long timeoutNanos = timeoutMillis * NANOS_PER_MILLISECOND; + long startTime = System.nanoTime(); + while (!condition.getAsBoolean()) { + long remainingNanos = -(System.nanoTime() - startTime - timeoutNanos); + if (remainingNanos <= 0) { + return true; + } + LockSupport.parkNanos(Math.min(remainingNanos, NANOS_PER_MILLISECOND)); + } + return false; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/concurrent/ContextInheritingThreadFactory.java b/src/main/java/ru/fokinatorr/sparkle/util/concurrent/ContextInheritingThreadFactory.java new file mode 100644 index 0000000..1e1dc9b --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/concurrent/ContextInheritingThreadFactory.java @@ -0,0 +1,55 @@ +package ru.fokinatorr.sparkle.util.concurrent; + +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.context.AppContextHolder; +import ru.fokinatorr.sparkle.internal.access.SharedSecrets; + +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicLong; + +import static lombok.AccessLevel.PRIVATE; + +/** + * A {@link ThreadFactory} that inherits the {@link AppContext} of the creator thread, if any exists. + *

Gives every thread a name with the given prefix plus a number, starting from {@code 0L} + * and increasing per each created thread. Also supports various thread types. + * @see ThreadType ThreadType + */ +@RequiredArgsConstructor +@FieldDefaults(makeFinal = true, level = PRIVATE) +public class ContextInheritingThreadFactory implements ThreadFactory { + + /** + * The name prefix for each created thread. + */ + @NonNull + String namePrefix; + /** + * The thread type to use for creating threads. + */ + @NonNull + ThreadType threadType; + AtomicLong counter = new AtomicLong(); + + /** + * {@inheritDoc} + * @param r {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public Thread newThread(@NonNull Runnable r) { + AppContext ctx = AppContextHolder.getContext(); + return threadType.toBuilder(Thread.currentThread().getThreadGroup()) + .name(namePrefix + "-" + counter.getAndIncrement()) + .unstarted(() -> { + if (ctx != null) { + AppContextHolder.initContext(ctx); + } + r.run(); + }); + } + +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/concurrent/ThreadType.java b/src/main/java/ru/fokinatorr/sparkle/util/concurrent/ThreadType.java new file mode 100644 index 0000000..a76258a --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/concurrent/ThreadType.java @@ -0,0 +1,54 @@ +package ru.fokinatorr.sparkle.util.concurrent; + +/** + * Different kinds of threads. Can be represented as a {@link Thread.Builder}. + * @see Thread#isDaemon() + * @see Thread#isVirtual() + * @see Thread.Builder + */ +public enum ThreadType { + /** + * Platform non-daemon thread. Can have a thread group. + */ + NON_DAEMON { + @Override + public Thread.Builder toBuilder(ThreadGroup threadGroup) { + var result = Thread.ofPlatform(); + if (threadGroup != null) { + result.group(threadGroup); + } + return result; + } + }, + /** + * Platform daemon thread. Can have a thread group. + */ + DAEMON { + @Override + public Thread.Builder toBuilder(ThreadGroup threadGroup) { + var result = Thread.ofPlatform().daemon(); + if (threadGroup != null) { + result.group(threadGroup); + } + return result; + } + }, + /** + * Virtual thread. Such thread are always daemon. and can NOT have a thread group. + */ + VIRTUAL { + @Override + public Thread.Builder toBuilder(ThreadGroup threadGroup) { + return Thread.ofVirtual(); + } + }; + + /** + * Creates a builder matching the characteristics of this thread type. + * + * @param threadGroup the thread group to set for the builder (ignored if {@code null} or not applicable to + * this thread type) + * @return a new {@link Thread.Builder} + */ + public abstract Thread.Builder toBuilder(ThreadGroup threadGroup); +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/concurrent/atomic/AtomicDouble.java b/src/main/java/ru/fokinatorr/sparkle/util/concurrent/atomic/AtomicDouble.java new file mode 100644 index 0000000..a2d9e28 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/concurrent/atomic/AtomicDouble.java @@ -0,0 +1,229 @@ +package ru.fokinatorr.sparkle.util.concurrent.atomic; + +import java.io.Serializable; +import java.lang.invoke.VarHandle; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.DoubleUnaryOperator; +import java.util.function.LongUnaryOperator; + +/** + * A {@code double} value that can be updated atomically. Internally stores a {@code long}. + */ +public class AtomicDouble extends Number implements Serializable { + + private final AtomicLong value; + + /** + * Creates a new {@code AtomicDouble} with initial value {@code 0.0}. + */ + public AtomicDouble() { + this.value = new AtomicLong(); + } + + /** + * Creates a new {@code AtomicDouble} with the given initial value. + * + * @param initialValue the initial value + */ + public AtomicDouble(double initialValue) { + this.value = new AtomicLong(Double.doubleToLongBits(initialValue)); + } + + // Delegate everything to "value" but converting double values to/from long bits + + /** + * Returns the current value, with memory effects as specified by {@link VarHandle#getVolatile}. + * + * @return the current value + */ + public final double get() { + return Double.longBitsToDouble(value.get()); + } + + /** + * Sets the value to the given value, with memory effects as specified by {@link VarHandle#setVolatile}. + * + * @param newValue the new value + */ + public final void set(double newValue) { + value.set(Double.doubleToLongBits(newValue)); + } + + /** + * Sets the value to the given value, with memory effects as specified by {@link VarHandle#setRelease}. + * + * @param newValue the new value + */ + public final void lazySet(double newValue) { + value.lazySet(Double.doubleToLongBits(newValue)); + } + + /** + * Atomically sets the value to the given value and returns the old value, + * with memory effects as specified by {@link VarHandle#getAndSet}. + * + * @param newValue the new value + * @return the previous value + */ + public final double getAndSet(double newValue) { + return Double.longBitsToDouble(value.getAndSet(Double.doubleToLongBits(newValue))); + } + + /** + * Atomically sets the value to {@code newValue} + * if the current value {@code == expectedValue}, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + * @param expectedValue the expected value + * @param newValue the new value + * @return {@code true} if successful. False return indicates that + * the actual value was not equal to the expected value. + */ + public final boolean compareAndSet(double expectedValue, double newValue) { + return value.compareAndSet(Double.doubleToLongBits(expectedValue), Double.doubleToLongBits(newValue)); + } + + /** + * Possibly atomically sets the value to {@code newValue} + * if the current value {@code == expectedValue}, + * with memory effects as specified by {@link VarHandle#weakCompareAndSetPlain}. + * + * @param expectedValue the expected value + * @param newValue the new value + * @return {@code true} if successful + */ + public final boolean weakCompareAndSetPlain(double expectedValue, double newValue) { + return value.weakCompareAndSetPlain(Double.doubleToLongBits(expectedValue), Double.doubleToLongBits(newValue)); + } + + /** + * Atomically increments the current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + *

Equivalent to {@code getAndAdd(1.0)}. + * + * @return the previous value + */ + public final double getAndIncrement() { + return getAndAdd(1.0d); + } + + /** + * Atomically decrements the current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + *

Equivalent to {@code getAndAdd(-1.0)}. + * + * @return the previous value + */ + public final double getAndDecrement() { + return getAndAdd(-1.0d); + } + + /** + * Atomically adds the given value to current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + * @param delta the value to add + * @return the previous value + */ + public final double getAndAdd(double delta) { + while (true) { + long currentBits = value.get(); + double currentValue = Double.longBitsToDouble(currentBits); + long nextBits = Double.doubleToLongBits(currentValue + delta); + if (value.compareAndSet(currentBits, nextBits)) { + return currentValue; + } + } + } + + /** + * Atomically increments the current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + *

Equivalent to {@code addAndGet(1.0)}. + * + * @return the updated value + */ + public final double incrementAndGet() { + return getAndAdd(1.0d) + 1.0d; + } + + /** + * Atomically decrements the current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + *

Equivalent to {@code addAndGet(-1.0)}. + * + * @return the updated value + */ + public final double decrementAndGet() { + return getAndAdd(-1.0d) - 1.0d; + } + + /** + * Atomically adds the given value to current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + * @param delta the value to add + * @return the updated value + */ + public final double addAndGet(double delta) { + return getAndAdd(delta) + delta; + } + + /** + * Atomically updates (with memory effects as specified by {@link + * VarHandle#compareAndSet}) the current value with the results of + * applying the given function, returning the updated value. The + * function should be side-effect-free, since it may be re-applied + * when attempted updates fail due to contention among threads. + * + * @param updateFunction a side-effect-free function + * @return the previous value + */ + public final double getAndUpdate(DoubleUnaryOperator updateFunction) { + return value.getAndUpdate(toLongUnaryOperator(updateFunction)); + } + + /** + * Atomically updates (with memory effects as specified by {@link + * VarHandle#compareAndSet}) the current value with the results of + * applying the given function, returning the updated value. The + * function should be side-effect-free, since it may be re-applied + * when attempted updates fail due to contention among threads. + * + * @param updateFunction a side-effect-free function + * @return the updated value + */ + public final double updateAndGet(DoubleUnaryOperator updateFunction) { + return value.updateAndGet(toLongUnaryOperator(updateFunction)); + } + + @Override + public String toString() { + return Double.toString(get()); + } + + @Override + public int intValue() { + return (int) get(); + } + + @Override + public long longValue() { + return (long) get(); + } + + @Override + public double doubleValue() { + return get(); + } + + @Override + public float floatValue() { + return (float) get(); + } + + + static LongUnaryOperator toLongUnaryOperator(DoubleUnaryOperator func) { + return l -> Double.doubleToLongBits(func.applyAsDouble(Double.longBitsToDouble(l))); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/concurrent/atomic/AtomicDoubleArray.java b/src/main/java/ru/fokinatorr/sparkle/util/concurrent/atomic/AtomicDoubleArray.java new file mode 100644 index 0000000..9b85ad9 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/concurrent/atomic/AtomicDoubleArray.java @@ -0,0 +1,245 @@ +package ru.fokinatorr.sparkle.util.concurrent.atomic; + +import it.unimi.dsi.fastutil.doubles.AbstractDoubleIterator; +import it.unimi.dsi.fastutil.doubles.DoubleIterable; +import it.unimi.dsi.fastutil.doubles.DoubleIterator; + +import java.io.Serializable; +import java.lang.invoke.VarHandle; +import java.util.Arrays; +import java.util.NoSuchElementException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLongArray; +import java.util.function.DoubleConsumer; +import java.util.function.DoubleUnaryOperator; + +import static ru.fokinatorr.sparkle.util.concurrent.atomic.AtomicDouble.toLongUnaryOperator; + +/** + * A {@code double} array in which elements can be updated atomically. Internally stores a {@code long[]}. + * Can also be used in enhanced {@code for} (for-each) loops, + * but it's recommended to use {@link #forEach(DoubleConsumer)} to avoid (un)boxing. + */ +public class AtomicDoubleArray implements DoubleIterable, Serializable { + private final AtomicLongArray values; + + /** + * Creates a new {@code AtomicDoubleArray} of the given length, with all + * elements initially zero. + * + * @param length the length of the array + */ + public AtomicDoubleArray(int length) { + this.values = new AtomicLongArray(length); + } + + /** + * Creates a new {@code AtomicDoubleArray} with the same length as, and + * all elements copied from, the given array. + * + * @param array the array to copy elements from + * @throws NullPointerException if array is null + */ + public AtomicDoubleArray(double[] array) { + this.values = new AtomicLongArray(Arrays.stream(array).mapToLong(Double::doubleToLongBits).toArray()); + } + + /** + * {@return the length of the array} + */ + public final int length() { + return values.length(); + } + + /** + * Returns the current value of the element at index {@code i}, + * with memory effects as specified by {@link VarHandle#getVolatile}. + * + * @param i the index + * @return the current value + */ + public final double get(int i) { + return Double.longBitsToDouble(values.get(i)); + } + + /** + * Sets the element at index {@code i} to {@code newValue}, + * with memory effects as specified by {@link VarHandle#setVolatile}. + * + * @param i the index + * @param newValue the new value + */ + public final void set(int i, double newValue) { + values.set(i, Double.doubleToLongBits(newValue)); + } + + /** + * Atomically sets the element at index {@code i} to {@code + * newValue} and returns the old value, + * with memory effects as specified by {@link VarHandle#getAndSet}. + * + * @param i the index + * @param newValue the new value + * @return the previous value + */ + public final double getAndSet(int i, double newValue) { + return Double.longBitsToDouble(values.getAndSet(i, Double.doubleToLongBits(newValue))); + } + + /** + * Atomically sets the element at index {@code i} to {@code newValue} + * if the element's current value {@code == expectedValue}, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + * @param i the index + * @param expectedValue the expected value + * @param newValue the new value + * @return {@code true} if successful. False return indicates that + * the actual value was not equal to the expected value. + */ + public final boolean compareAndSet(int i, double expectedValue, double newValue) { + return values.compareAndSet(i, Double.doubleToLongBits(expectedValue), Double.doubleToLongBits(newValue)); + } + + /** + * Atomically increments the value of the element at index {@code i}, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + *

Equivalent to {@code getAndAdd(i, 1.0)}. + * + * @param i the index + * @return the previous value + */ + public final double getAndIncrement(int i) { + return getAndAdd(i, 1.0); + } + + /** + * Atomically decrements the value of the element at index {@code i}, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + *

Equivalent to {@code getAndAdd(i, -1.0)}. + * + * @param i the index + * @return the previous value + */ + public final double getAndDecrement(int i) { + return getAndAdd(i, -1.0); + } + + /** + * Atomically adds the given value to the element at index {@code i}, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + * @param i the index + * @param delta the value to add + * @return the previous value + */ + public final double getAndAdd(int i, double delta) { + while (true) { + long currentBits = values.get(i); + double currentValue = Double.longBitsToDouble(currentBits); + long nextBits = Double.doubleToLongBits(currentValue + delta); + if (values.compareAndSet(i, currentBits, nextBits)) { + return currentValue; + } + } + } + + /** + * Atomically increments the value of the element at index {@code i}, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + *

Equivalent to {@code getAndAdd(i, 1.0)}. + * + * @param i the index + * @return the updated value + */ + public final double incrementAndGet(int i) { + return getAndAdd(i, 1.0) + 1.0; + } + + /** + * Atomically decrements the value of the element at index {@code i}, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + *

Equivalent to {@code getAndAdd(i, -1.0)}. + * + * @param i the index + * @return the updated value + */ + public final double decrementAndGet(int i) { + return getAndAdd(i, -1.0) - 1.0; + } + + /** + * Atomically adds the given value to the element at index {@code i}, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + * @param i the index + * @param delta the value to add + * @return the updated value + */ + public final double addAndGet(int i, double delta) { + return getAndAdd(i, delta) + delta; + } + + /** + * Atomically updates (with memory effects as specified by {@link + * VarHandle#compareAndSet}) the element at index {@code i} with + * the results of applying the given function, returning the + * previous value. The function should be side-effect-free, since + * it may be re-applied when attempted updates fail due to + * contention among threads. + * + * @param i the index + * @param updateFunction a side-effect-free function + * @return the previous value + */ + public final long getAndUpdate(int i, DoubleUnaryOperator updateFunction) { + return values.getAndUpdate(i, toLongUnaryOperator(updateFunction)); + } + + /** + * Atomically updates (with memory effects as specified by {@link + * VarHandle#compareAndSet}) the element at index {@code i} with + * the results of applying the given function, returning the + * updated value. The function should be side-effect-free, since it + * may be re-applied when attempted updates fail due to contention + * among threads. + * + * @param i the index + * @param updateFunction a side-effect-free function + * @return the updated value + */ + public final long updateAndGet(int i, DoubleUnaryOperator updateFunction) { + return values.updateAndGet(i, toLongUnaryOperator(updateFunction)); + } + + // Atomic iterator over this double array + private class Itr extends AbstractDoubleIterator { + final AtomicInteger cursor = new AtomicInteger(); + + @Override + public boolean hasNext() { + return cursor.get() < length(); + } + + @Override + public double nextDouble() { + if (cursor.get() > length()) { + throw new NoSuchElementException(); + } + return get(cursor.getAndIncrement()); + } + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public DoubleIterator iterator() { + return new Itr(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/concurrent/atomic/AtomicFloat.java b/src/main/java/ru/fokinatorr/sparkle/util/concurrent/atomic/AtomicFloat.java new file mode 100644 index 0000000..30835f0 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/concurrent/atomic/AtomicFloat.java @@ -0,0 +1,230 @@ +package ru.fokinatorr.sparkle.util.concurrent.atomic; + +import it.unimi.dsi.fastutil.floats.FloatUnaryOperator; + +import java.io.Serializable; +import java.lang.invoke.VarHandle; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.IntUnaryOperator; + +/** + * A {@code float} value that can be updated atomically. Internally stores an {@code int}. + */ +public class AtomicFloat extends Number implements Serializable { + + private final AtomicInteger value; + + /** + * Creates a new {@code AtomicFloat} with initial value {@code 0.0}. + */ + public AtomicFloat() { + this.value = new AtomicInteger(); + } + + /** + * Creates a new {@code AtomicFloat} with the given initial value. + * + * @param initialValue the initial value + */ + public AtomicFloat(float initialValue) { + this.value = new AtomicInteger(Float.floatToIntBits(initialValue)); + } + + // Delegate everything to "value" but converting float values to/from int bits + + /** + * Returns the current value, with memory effects as specified by {@link VarHandle#getVolatile}. + * + * @return the current value + */ + public final float get() { + return Float.intBitsToFloat(value.get()); + } + + /** + * Sets the value to the given value, with memory effects as specified by {@link VarHandle#setVolatile}. + * + * @param newValue the new value + */ + public final void set(float newValue) { + value.set(Float.floatToIntBits(newValue)); + } + + /** + * Sets the value to the given value, with memory effects as specified by {@link VarHandle#setRelease}. + * + * @param newValue the new value + */ + public final void lazySet(float newValue) { + value.lazySet(Float.floatToIntBits(newValue)); + } + + /** + * Atomically sets the value to the given value and returns the old value, + * with memory effects as specified by {@link VarHandle#getAndSet}. + * + * @param newValue the new value + * @return the previous value + */ + public final float getAndSet(float newValue) { + return Float.intBitsToFloat(value.getAndSet(Float.floatToIntBits(newValue))); + } + + /** + * Atomically sets the value to {@code newValue} + * if the current value {@code == expectedValue}, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + * @param expectedValue the expected value + * @param newValue the new value + * @return {@code true} if successful. False return indicates that + * the actual value was not equal to the expected value. + */ + public final boolean compareAndSet(float expectedValue, float newValue) { + return value.compareAndSet(Float.floatToIntBits(expectedValue), Float.floatToIntBits(newValue)); + } + + /** + * Possibly atomically sets the value to {@code newValue} + * if the current value {@code == expectedValue}, + * with memory effects as specified by {@link VarHandle#weakCompareAndSetPlain}. + * + * @param expectedValue the expected value + * @param newValue the new value + * @return {@code true} if successful + */ + public final boolean weakCompareAndSetPlain(float expectedValue, float newValue) { + return value.weakCompareAndSetPlain(Float.floatToIntBits(expectedValue), Float.floatToIntBits(newValue)); + } + + /** + * Atomically increments the current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + *

Equivalent to {@code getAndAdd(1.0)}. + * + * @return the previous value + */ + public final float getAndIncrement() { + return getAndAdd(1.0f); + } + + /** + * Atomically decrements the current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + *

Equivalent to {@code getAndAdd(-1.0)}. + * + * @return the previous value + */ + public final float getAndDecrement() { + return getAndAdd(-1.0f); + } + + /** + * Atomically adds the given value to current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + * @param delta the value to add + * @return the previous value + */ + public final float getAndAdd(float delta) { + while (true) { + int currentBits = value.get(); + float currentValue = Float.intBitsToFloat(currentBits); + int nextBits = Float.floatToIntBits(currentValue + delta); + if (value.compareAndSet(currentBits, nextBits)) { + return currentValue; + } + } + } + + /** + * Atomically increments the current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + *

Equivalent to {@code addAndGet(1.0)}. + * + * @return the updated value + */ + public final float incrementAndGet() { + return getAndAdd(1.0f) + 1.0f; + } + + /** + * Atomically decrements the current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + *

Equivalent to {@code addAndGet(-1.0)}. + * + * @return the updated value + */ + public final float decrementAndGet() { + return getAndAdd(-1.0f) - 1.0f; + } + + /** + * Atomically adds the given value to current value, + * with memory effects as specified by {@link VarHandle#compareAndSet}. + * + * @param delta the value to add + * @return the updated value + */ + public final float addAndGet(float delta) { + return getAndAdd(delta) + delta; + } + + /** + * Atomically updates (with memory effects as specified by {@link + * VarHandle#compareAndSet}) the current value with the results of + * applying the given function, returning the updated value. The + * function should be side-effect-free, since it may be re-applied + * when attempted updates fail due to contention among threads. + * + * @param updateFunction a side-effect-free function + * @return the previous value + */ + public final float getAndUpdate(FloatUnaryOperator updateFunction) { + return value.getAndUpdate(toIntUnaryOperator(updateFunction)); + } + + /** + * Atomically updates (with memory effects as specified by {@link + * VarHandle#compareAndSet}) the current value with the results of + * applying the given function, returning the updated value. The + * function should be side-effect-free, since it may be re-applied + * when attempted updates fail due to contention among threads. + * + * @param updateFunction a side-effect-free function + * @return the updated value + */ + public final float updateAndGet(FloatUnaryOperator updateFunction) { + return value.updateAndGet(toIntUnaryOperator(updateFunction)); + } + + @Override + public String toString() { + return Float.toString(get()); + } + + @Override + public int intValue() { + return (int) get(); + } + + @Override + public long longValue() { + return (long) get(); + } + + @Override + public double doubleValue() { + return get(); + } + + @Override + public float floatValue() { + return get(); + } + + + static IntUnaryOperator toIntUnaryOperator(FloatUnaryOperator func) { + return i -> Float.floatToIntBits(func.apply(Float.intBitsToFloat(i))); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/AbstractStopwatch.java b/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/AbstractStopwatch.java new file mode 100644 index 0000000..1cc8fee --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/AbstractStopwatch.java @@ -0,0 +1,80 @@ +package ru.fokinatorr.sparkle.util.stopwatch; + +/** + * Base implementation of {@link Stopwatch} interface. + */ +public abstract class AbstractStopwatch implements Stopwatch { + + /** + * State of this stopwatch + */ + protected State state; + + /** + * Constructor for subclasses to call. + */ + protected AbstractStopwatch() { + state = State.NEW; + } + + /** + * {@inheritDoc} + * @throws IllegalStopwatchStateException {@inheritDoc} + * @implSpec This is just a base implementation. Always override this method and call superclass method. + */ + @Override + public void start() { + if (state == State.RUNNING) + throw new IllegalStopwatchStateException("Stopwatch is already running", State.RUNNING, null); + state = State.RUNNING; + } + + /** + * {@inheritDoc} + * @throws IllegalStopwatchStateException {@inheritDoc} + * @implSpec This is just a base implementation. Always override this method and call superclass method. + */ + @Override + public void pause() { + if (state != State.RUNNING) + throw new IllegalStopwatchStateException("Stopwatch is not running", state, State.PAUSED); + state = State.PAUSED; + } + + /** + * {@inheritDoc} + * @throws IllegalStopwatchStateException {@inheritDoc} + * @implSpec This is just a base implementation. Always override this method and call superclass method. + */ + @Override + public void stop() { + if (state == State.STOPPED) + throw new IllegalStopwatchStateException("Stopwatch is already stopped", State.STOPPED, null); + state = State.STOPPED; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + * @see State + */ + @Override + public State getState() { + return state; + } + + + /** + * Returns a string representation of this {@code Stopwatch}. + * @return a string representation of this {@code Stopwatch}. + * @implSpec By default, this method returns: + *

{@code getState() + " " + String.format("%02d:%02d:%02d.%03d", timeElapsed() / 3600000, timeElapsed() / 60000 % 60, timeElapsed() / 1000 % 3600, timeElapsed() % 1000)}
+ */ + public String toString() { + long timeElapsed = timeElapsed(); + long timeElapsedSeconds = timeElapsed / 1000; + return getState() + " " + + String.format("%02d:%02d:%02d.%03d", timeElapsedSeconds / 3600, timeElapsedSeconds / 60 % 60, + timeElapsedSeconds % 60, timeElapsed % 1000); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/IllegalStopwatchStateException.java b/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/IllegalStopwatchStateException.java new file mode 100644 index 0000000..e4cb313 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/IllegalStopwatchStateException.java @@ -0,0 +1,56 @@ +package ru.fokinatorr.sparkle.util.stopwatch; + +/** + * Thrown when an operation cannot be performed because of the current stopwatch state + */ +public class IllegalStopwatchStateException extends IllegalStateException { + + @java.io.Serial + private static final long serialVersionUID = -2522016967152973998L; + + + private final Stopwatch.State current; + private final Stopwatch.State required; + + /** + * Creates a new {@code IllegalStopwatchStateException} with no reason and no required and current state specified. + */ + public IllegalStopwatchStateException() { + this("", null, null); + } + + /** + * Creates an {@code IllegalStopwatchStateException}. + * @param reason the reason, or {@code null} if none + * @param current the current stopwatch state, or {@code null} if unknown + * @param required the required stopwatch state, or {@code null} if unknown or multiple + */ + public IllegalStopwatchStateException(String reason, Stopwatch.State current, Stopwatch.State required) { + super(reason); + this.current = current; + this.required = required; + } + + @Override + public String getMessage() { + StringBuilder sb = new StringBuilder(); + if (required != null) { + sb.append("Required state: State.").append(required).append(", "); + } + if (current != null) { + //noinspection SpellCheckingInspection + sb.append(sb.isEmpty() ? 'C' : 'c') + .append("urrent state: State.") + .append(required); + } + String reason = super.getMessage(); + if (reason != null && !reason.isBlank()) { + if (!sb.isEmpty()) { + sb.append("; detail reason: "); + } + sb.append(reason); + } + + return new String(sb); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/InstantStopwatch.java b/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/InstantStopwatch.java new file mode 100644 index 0000000..f8ee1ef --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/InstantStopwatch.java @@ -0,0 +1,87 @@ +package ru.fokinatorr.sparkle.util.stopwatch; + +import java.time.Instant; + +/** + * A {@link Stopwatch} that uses {@link Instant} timestamp calculations + */ +public class InstantStopwatch extends AbstractStopwatch implements Stopwatch { + + // some private fields + private Instant startTime = null; + private Instant startTimeOfBeingPaused = null; + + private long offsetMillis = 0L; + + /** + * Constructs a new {@code InstantStopwatch}. + */ + public InstantStopwatch() { + super(); + } + + /** + * {@inheritDoc} + * @throws IllegalStopwatchStateException {@inheritDoc} + */ + @Override + public void start() { + super.start(); + if (startTime == null) { // it's started + startTime = Instant.now(); + } else { // it's resumed + offsetMillis = Instant.now().toEpochMilli() - startTimeOfBeingPaused.toEpochMilli(); + startTimeOfBeingPaused = null; + } + } + + /** + * {@inheritDoc} + * @throws IllegalStopwatchStateException {@inheritDoc} + */ + @Override + public void pause() { + super.pause(); + startTimeOfBeingPaused = Instant.now(); + } + + /** + * {@inheritDoc} + * @throws IllegalStopwatchStateException {@inheritDoc} + */ + @Override + public void stop() { + super.stop(); + startTime = null; + startTimeOfBeingPaused = null; + } + + /** + * {@inheritDoc} + * @throws IllegalStopwatchStateException {@inheritDoc} + */ + @Override + public Instant startTime() { + throwExceptionIfNotStarted(); + return startTime; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public long timeElapsed() { + if (!wasStarted()) return 0L; + long currentEpochMilli = Instant.now().toEpochMilli(); + if (state == State.PAUSED) + offsetMillis = currentEpochMilli - startTimeOfBeingPaused.toEpochMilli(); + return currentEpochMilli - startTime.toEpochMilli() - offsetMillis; + } + + // Throw an exception if wasStarted() returns false + private void throwExceptionIfNotStarted() { + if (!wasStarted()) + throw new IllegalStopwatchStateException("Stopwatch was not started", state, null); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/Stopwatch.java b/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/Stopwatch.java new file mode 100644 index 0000000..dbb8177 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/util/stopwatch/Stopwatch.java @@ -0,0 +1,101 @@ +package ru.fokinatorr.sparkle.util.stopwatch; + +import java.time.Instant; + +/** + * A stopwatch + */ +public interface Stopwatch extends Runnable { + + /** + * Returns a timestamp representing the time this stopwatch was started, never null. + * @return when this stopwatch was started + * @throws IllegalStopwatchStateException if {@link #wasStarted()} returns {@code false}. + */ + Instant startTime(); + + /** + * Returns how much time elapsed since the stopwatch started (in milliseconds). + * If {@link #wasStarted()} returns {@code false}, returns {@code 0L}. + * @return how much time elapsed since the stopwatch started + */ + long timeElapsed(); + + /** + * Starts or resumes the stopwatch. + * @throws IllegalStopwatchStateException if the stopwatch is already running. + */ + @Override + default void run() { + start(); + } + + /** + * Starts or resumes the stopwatch. + * @throws IllegalStopwatchStateException if the stopwatch is already running. + */ + void start(); + + /** + * Pauses the stopwatch. This method doesn't clear the stopwatch stats, unlike the {@link #stop()} method. + * @throws IllegalStopwatchStateException if the stopwatch is not running. + * @see State#RUNNING + */ + void pause(); + + /** + * Stops the stopwatch and clear its stats. + * @throws IllegalStopwatchStateException if the stopwatch is already stopped. + */ + void stop(); + + /** + * Returns the state of this {@code Stopwatch}. + * @return the state of this {@code Stopwatch} + * @see State + */ + State getState(); + + /** + * Stopwatch state + * @see #getState() + */ + enum State { + + /** + * Stopwatch was just created and wasn't yet started. Needed for stopwatches that can be only run once. + */ + NEW, + + /** + * Stopwatch is running + * @see #start() + */ + RUNNING, + + /** + * Stopwatch is paused (not running, but was started). + * @see #pause() + */ + PAUSED, + + /** + * Stopwatch was stopped and is not running + * @see #stop() + */ + STOPPED + } + + /** + * Determines whether this stopwatch was started. + * @return whether this stopwatch was started + * @implSpec This method returns true if + *
{@code getState() == State.RUNNING || getState() == State.PAUSED}
+ * @see State#RUNNING + * @see State#PAUSED + */ + default boolean wasStarted() { + State state = getState(); + return state == State.RUNNING || state == State.PAUSED; + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/AbstractVariableStorage.java b/src/main/java/ru/fokinatorr/sparkle/variable/AbstractVariableStorage.java new file mode 100644 index 0000000..846ed69 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/AbstractVariableStorage.java @@ -0,0 +1,56 @@ +package ru.fokinatorr.sparkle.variable; + +import java.util.Collections; +import java.util.Map; + +/** + * Provides an implementation of {@link VariableStorage}. + * @param the type of variable ID + */ +public abstract class AbstractVariableStorage implements VariableStorage { + + protected final Map> variables = createVariables(); + protected final Map> variablesView = Collections.unmodifiableMap(variables); + + /** + * Constructor for subclasses to call. + */ + protected AbstractVariableStorage() { + } + + /** + * Creates a new {@link Map} to store variables in. + * @return a new variable map + */ + protected abstract Map> createVariables(); + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public Map> getVariables() { + return variablesView; + } + + /** + * {@inheritDoc} + * @param id {@inheritDoc} + * @param variable {@inheritDoc} + * @throws UnsupportedOperationException if {@code put} operation is not supported by the backing map + */ + @Override + public void registerVariable(ID id, Variable variable) { + variables.put(id, variable); + } + + /** + * {@inheritDoc} + * @param id {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public Variable getVariable(ID id) { + return variables.get(id); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/BooleanVariable.java b/src/main/java/ru/fokinatorr/sparkle/variable/BooleanVariable.java new file mode 100644 index 0000000..df2c4ad --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/BooleanVariable.java @@ -0,0 +1,116 @@ +package ru.fokinatorr.sparkle.variable; + +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.experimental.FieldDefaults; + +import java.util.concurrent.atomic.AtomicBoolean; + +import static ru.fokinatorr.sparkle.variable.ObjectVariable.PRIMITIVE_TO_WRAPPER; + +/** + * A variable storing a {@code boolean} value. + */ +@SuppressWarnings({"UnnecessaryBoxing", "UnnecessaryUnboxing"}) +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +@EqualsAndHashCode +public class BooleanVariable implements Variable { + + AtomicBoolean value; + + /** + * Constructs a new {@code BooleanVariable} with initial value {@code false}. + */ + public BooleanVariable() { + value = new AtomicBoolean(); + } + + /** + * Constructs a new {@code BooleanVariable} with the given initial value. + * @param initialValue the initial value + */ + public BooleanVariable(boolean initialValue) { + value = new AtomicBoolean(initialValue); + } + + /** + * Returns the current value of this variable. + * @return the value + */ + @Override + public boolean getValueAsBoolean() { + return value.get(); + } + + /** + * Sets the value of this variable to the given one. + * @param newValue {@inheritDoc} + */ + @Override + public void setBooleanValue(boolean newValue) { + value.set(newValue); + } + + /** + * Negates the current value, returning the old value. + * @return the previous value + */ + public boolean getAndNegate() { + while (true) { + boolean currentVal = value.get(); + boolean nextVal = !currentVal; + if (value.compareAndSet(currentVal, nextVal)) { + return currentVal; + } + } + } + + /** + * Negates the current value, returning the new value. + * @return the updated value + */ + public boolean negateAndGet() { + return !getAndNegate(); + } + + /** + * {@inheritDoc} + * @param cls {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean is(Class cls) { + return PRIMITIVE_TO_WRAPPER.getOrDefault(cls, cls) == Boolean.class; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public BooleanVariable copy() { + return new BooleanVariable(value.get()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #getValueAsBoolean()} instead. + * @return {@inheritDoc} + */ + @Override + @Deprecated + public Boolean getValue() { + return Boolean.valueOf(getValueAsBoolean()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #setBooleanValue(boolean)} instead. + * @param newValue the new value + */ + @Override + @Deprecated + public void setValue(Boolean newValue) { + setBooleanValue(newValue.booleanValue()); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/ByteVariable.java b/src/main/java/ru/fokinatorr/sparkle/variable/ByteVariable.java new file mode 100644 index 0000000..41f1222 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/ByteVariable.java @@ -0,0 +1,255 @@ +package ru.fokinatorr.sparkle.variable; + +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.experimental.FieldDefaults; + +import static ru.fokinatorr.sparkle.variable.ObjectVariable.PRIMITIVE_TO_WRAPPER; + +/** + * A variable storing a {@code byte} value. + */ +@SuppressWarnings({"UnnecessaryUnboxing", "UnnecessaryBoxing"}) +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +@EqualsAndHashCode(callSuper = false) +public class ByteVariable extends Number implements Variable { + + IntVariable delegate; + + /** + * Creates a new {@code ByteVariable} with initial value {@code 0}. + */ + public ByteVariable() { + delegate = new IntVariable(); + } + + /** + * Creates a new {@code ByteVariable} with the given initial value. + */ + public ByteVariable(byte initialValue) { + delegate = new IntVariable(initialValue); + } + + /** + * Returns the current value of this variable. + * @return the value + */ + @Override + public byte getValueAsByte() { + return delegate.getValueAsByte(); + } + + /** + * Returns the current value of this variable as {@code short}. + * @return the value as {@code short} + */ + @Override + public short getValueAsShort() { + return getValueAsByte(); + } + + /** + * Returns the current value of this variable as {@code int}. + * @return the value as {@code int} + */ + @Override + public int getValueAsInt() { + return getValueAsByte(); + } + + /** + * Returns the current value of this variable as {@code long}. + * @return the value as {@code long} + */ + @Override + public long getValueAsLong() { + return getValueAsByte(); + } + + /** + * Returns the current value of this variable as {@code float}. + * @return the value as {@code float} + */ + @Override + public float getValueAsFloat() { + return getValueAsByte(); + } + + /** + * Returns the current value of this variable as {@code double}. + * @return the value as {@code double} + */ + @Override + public double getValueAsDouble() { + return getValueAsByte(); + } + + /** + * Sets the value of this variable to the given one. + * @param newValue {@inheritDoc} + */ + @Override + public void setByteValue(byte newValue) { + delegate.setByteValue(newValue); + } + + + /** + * Increments the current value. + * @return the previous value + */ + public byte getAndIncrement() { + return getAndAdd((byte) 1); + } + + /** + * Decrements the current value. + * @return the previous value + */ + public byte getAndDecrement() { + return getAndAdd((byte) -1); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the previous value + */ + public byte getAndAdd(byte delta) { + while (true) { + byte currentValue = getValueAsByte(); + byte nextValue = (byte) (currentValue + delta & 0xFFFF); + if (delegate.value.compareAndSet(currentValue, nextValue)) { + return currentValue; + } + } + } + + /** + * Increments the current value. + * @return the updated value + */ + public byte incrementAndGet() { + return (byte) (getAndAdd((byte) 1) + 1); + } + + /** + * Decrements the current value. + * @return the updated value + */ + public byte decrementAndGet() { + return (byte) (getAndAdd((byte) -1) - 1); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the updated value + */ + public byte addAndGet(byte delta) { + return (byte) (getAndAdd(delta) + delta); + } + + /** + * {@inheritDoc} + * @param cls {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean is(Class cls) { + return PRIMITIVE_TO_WRAPPER.getOrDefault(cls, cls) == Byte.class; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public ByteVariable copy() { + return new ByteVariable(getValueAsByte()); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public byte byteValue() { + return getValueAsByte(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public short shortValue() { + return getValueAsByte(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public int intValue() { + return getValueAsByte(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public long longValue() { + return getValueAsByte(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public float floatValue() { + return getValueAsByte(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public double doubleValue() { + return getValueAsByte(); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #getValueAsByte()} instead. + * @return {@inheritDoc} + */ + @Override + @Deprecated + public Byte getValue() { + return Byte.valueOf(getValueAsByte()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #setByteValue(byte)} instead. + * @param newValue {@inheritDoc} + */ + @Override + @Deprecated + public void setValue(Byte newValue) { + setByteValue(newValue.byteValue()); + } + + /** + * {@return a string representation of the current value} + */ + @Override + public String toString() { + return delegate.value.toString(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/CharVariable.java b/src/main/java/ru/fokinatorr/sparkle/variable/CharVariable.java new file mode 100644 index 0000000..c5a7132 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/CharVariable.java @@ -0,0 +1,95 @@ +package ru.fokinatorr.sparkle.variable; + +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.experimental.FieldDefaults; + +import java.util.concurrent.atomic.AtomicInteger; + +import static ru.fokinatorr.sparkle.variable.ObjectVariable.PRIMITIVE_TO_WRAPPER; + +/** + * A variable storing a {@code char} value. + */ +@SuppressWarnings({"UnnecessaryUnboxing", "UnnecessaryBoxing"}) +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +@EqualsAndHashCode +public class CharVariable implements Variable { + + AtomicInteger value; + + /** + * Constructs a {@code CharVariable} with the given initial value. + * @param initialValue the initial value + */ + public CharVariable(char initialValue) { + value = new AtomicInteger(initialValue); + } + + /** + * Returns the current value of this variable. + * @return the value + */ + @Override + public char getValueAsChar() { + return (char) value.get(); + } + + /** + * Sets the current value of this variable. + * @param newValue {@inheritDoc} + */ + @Override + public void setCharValue(char newValue) { + value.set(newValue); + } + + /** + * {@inheritDoc} + * @param cls {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean is(Class cls) { + return PRIMITIVE_TO_WRAPPER.getOrDefault(cls, cls) == Character.class; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public CharVariable copy() { + return new CharVariable(getValueAsChar()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #getValueAsChar()} instead. + * @return {@inheritDoc} + */ + @Override + @Deprecated + public Character getValue() { + return Character.valueOf(getValueAsChar()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #setCharValue(char)} instead. + * @param newValue {@inheritDoc} + */ + @Override + @Deprecated + public void setValue(Character newValue) { + setCharValue(newValue.charValue()); + } + + /** + * {@return a string representation of the current value} + */ + @Override + public String toString() { + return Character.toString(getValueAsChar()); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/DoubleVariable.java b/src/main/java/ru/fokinatorr/sparkle/variable/DoubleVariable.java new file mode 100644 index 0000000..f113630 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/DoubleVariable.java @@ -0,0 +1,276 @@ +package ru.fokinatorr.sparkle.variable; + +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.experimental.FieldDefaults; +import ru.fokinatorr.sparkle.util.concurrent.atomic.AtomicDouble; + +import static ru.fokinatorr.sparkle.variable.ObjectVariable.PRIMITIVE_TO_WRAPPER; + +/** + * A variable storing a {@code double} value. + */ +@SuppressWarnings({"UnnecessaryUnboxing", "UnnecessaryBoxing"}) +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +@EqualsAndHashCode(callSuper = false) +public class DoubleVariable extends Number implements Variable { + + AtomicDouble value; + + /** + * Creates a new {@code DoubleVariable} with initial value {@code 0.0}. + */ + public DoubleVariable() { + value = new AtomicDouble(); + } + + /** + * Creates a new {@code DoubleVariable} with the given initial value. + */ + public DoubleVariable(double initialValue) { + value = new AtomicDouble(initialValue); + } + + /** + * Returns the current value of this variable as {@code byte}. + * @return the value as {@code byte} + */ + @Override + public byte getValueAsByte() { + return (byte) getValueAsInt(); + } + + /** + * Returns the current value of this variable as {@code short}. + * @return the value as {@code short} + */ + @Override + public short getValueAsShort() { + return (short) getValueAsInt(); + } + + /** + * Returns the current value of this variable as {@code int}. + * @return the value as {@code int} + */ + @Override + public int getValueAsInt() { + return (int) getValueAsDouble(); + } + + /** + * Returns the current value of this variable as {@code long}. + * @return the value as {@code long} + */ + @Override + public long getValueAsLong() { + return (long) getValueAsDouble(); + } + + /** + * Returns the current value of this variable as {@code float}. + * @return the value as {@code float} + */ + @Override + public float getValueAsFloat() { + return (float) getValueAsDouble(); + } + + /** + * Returns the current value of this variable. + * @return the value + */ + @Override + public double getValueAsDouble() { + return value.get(); + } + + /** + * Sets the current value as {@code byte}. + * @param newValue {@inheritDoc} + */ + @Override + public void setByteValue(byte newValue) { + setDoubleValue(newValue); + } + + /** + * Sets the current value as {@code short}. + * @param newValue {@inheritDoc} + */ + @Override + public void setShortValue(short newValue) { + setDoubleValue(newValue); + } + + /** + * Sets the current value as {@code int}. + * @param newValue {@inheritDoc} + */ + @Override + public void setIntValue(int newValue) { + setDoubleValue(newValue); + } + + /** + * Sets the current value as {@code long}. + * @param newValue {@inheritDoc} + */ + @Override + public void setLongValue(long newValue) { + setDoubleValue(newValue); + } + + /** + * Sets the current value as {@code float}. + * @param newValue {@inheritDoc} + */ + @Override + public void setFloatValue(float newValue) { + setDoubleValue(newValue); + } + + /** + * Sets the value of this variable to the given one. + * @param newValue {@inheritDoc} + */ + @Override + public void setDoubleValue(double newValue) { + value.set(newValue); + } + + /** + * Increments the current value. + * @return the previous value + */ + public double getAndIncrement() { + return value.getAndIncrement(); + } + + /** + * Decrements the current value. + * @return the previous value + */ + public double getAndDecrement() { + return value.getAndDecrement(); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the previous value + */ + public double getAndAdd(double delta) { + return value.getAndAdd(delta); + } + + /** + * Increments the current value. + * @return the updated value + */ + public double incrementAndGet() { + return value.incrementAndGet(); + } + + /** + * Decrements the current value. + * @return the updated value + */ + public double decrementAndGet() { + return value.decrementAndGet(); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the updated value + */ + public double addAndGet(double delta) { + return value.addAndGet(delta); + } + + /** + * {@inheritDoc} + * @param cls {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean is(Class cls) { + return PRIMITIVE_TO_WRAPPER.getOrDefault(cls, cls) == Double.class; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public DoubleVariable copy() { + return new DoubleVariable(value.get()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #getValueAsDouble()} instead. + * @return {@inheritDoc} + */ + @Override + @Deprecated + public Double getValue() { + return Double.valueOf(getValueAsDouble()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #setDoubleValue(double)} instead. + * @param newValue {@inheritDoc} + */ + @Override + @Deprecated + public void setValue(Double newValue) { + setDoubleValue(newValue.doubleValue()); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public int intValue() { + return (int) getValueAsDouble(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public long longValue() { + return (long) getValueAsDouble(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public float floatValue() { + return (float) getValueAsDouble(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public double doubleValue() { + return getValueAsDouble(); + } + + /** + * {@return a string representation of the current value} + */ + @Override + public String toString() { + return value.toString(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/FloatVariable.java b/src/main/java/ru/fokinatorr/sparkle/variable/FloatVariable.java new file mode 100644 index 0000000..629a49a --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/FloatVariable.java @@ -0,0 +1,276 @@ +package ru.fokinatorr.sparkle.variable; + +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.experimental.FieldDefaults; +import ru.fokinatorr.sparkle.util.concurrent.atomic.AtomicFloat; + +import static ru.fokinatorr.sparkle.variable.ObjectVariable.PRIMITIVE_TO_WRAPPER; + +/** + * A variable storing a {@code double} value. + */ +@SuppressWarnings({"UnnecessaryUnboxing", "UnnecessaryBoxing"}) +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +@EqualsAndHashCode(callSuper = false) +public class FloatVariable extends Number implements Variable { + + AtomicFloat value; + + /** + * Creates a new {@code FloatVariable} with initial value {@code 0.0}. + */ + public FloatVariable() { + value = new AtomicFloat(); + } + + /** + * Creates a new {@code FloatVariable} with the given initial value. + */ + public FloatVariable(float initialValue) { + value = new AtomicFloat(initialValue); + } + + /** + * Returns the current value of this variable as {@code byte}. + * @return the value as {@code byte} + */ + @Override + public byte getValueAsByte() { + return (byte) getValueAsInt(); + } + + /** + * Returns the current value of this variable as {@code short}. + * @return the value as {@code short} + */ + @Override + public short getValueAsShort() { + return (short) getValueAsInt(); + } + + /** + * Returns the current value of this variable as {@code int}. + * @return the value as {@code int} + */ + @Override + public int getValueAsInt() { + return (int) getValueAsFloat(); + } + + /** + * Returns the current value of this variable as {@code long}. + * @return the value as {@code long} + */ + @Override + public long getValueAsLong() { + return (long) getValueAsFloat(); + } + + /** + * Returns the current value of this variable. + * @return the value + */ + @Override + public float getValueAsFloat() { + return value.get(); + } + + /** + * Returns the current value of this variable as {@code double}. + * @return the value as {@code double} + */ + @Override + public double getValueAsDouble() { + return getValueAsFloat(); + } + + /** + * Sets the current value as {@code byte}. + * @param newValue {@inheritDoc} + */ + @Override + public void setByteValue(byte newValue) { + setFloatValue(newValue); + } + + /** + * Sets the current value as {@code short}. + * @param newValue {@inheritDoc} + */ + @Override + public void setShortValue(short newValue) { + setFloatValue(newValue); + } + + /** + * Sets the current value as {@code int}. + * @param newValue {@inheritDoc} + */ + @Override + public void setIntValue(int newValue) { + setFloatValue(newValue); + } + + /** + * Sets the current value as {@code long}. + * @param newValue {@inheritDoc} + */ + @Override + public void setLongValue(long newValue) { + setFloatValue(newValue); + } + + /** + * Sets the value of this variable to the given one. + * @param newValue {@inheritDoc} + */ + @Override + public void setFloatValue(float newValue) { + value.set(newValue); + } + + /** + * Sets the current value as {@code double}. + * @param newValue {@inheritDoc} + */ + @Override + public void setDoubleValue(double newValue) { + setFloatValue((float) newValue); + } + + /** + * Increments the current value. + * @return the previous value + */ + public float getAndIncrement() { + return value.getAndIncrement(); + } + + /** + * Decrements the current value. + * @return the previous value + */ + public float getAndDecrement() { + return value.getAndDecrement(); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the previous value + */ + public float getAndAdd(float delta) { + return value.getAndAdd(delta); + } + + /** + * Increments the current value. + * @return the updated value + */ + public float incrementAndGet() { + return value.incrementAndGet(); + } + + /** + * Decrements the current value. + * @return the updated value + */ + public float decrementAndGet() { + return value.decrementAndGet(); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the updated value + */ + public float addAndGet(float delta) { + return value.addAndGet(delta); + } + + /** + * {@inheritDoc} + * @param cls {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean is(Class cls) { + return PRIMITIVE_TO_WRAPPER.getOrDefault(cls, cls) == Float.class; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public FloatVariable copy() { + return new FloatVariable(value.get()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #getValueAsFloat()} instead. + * @return {@inheritDoc} + */ + @Override + @Deprecated + public Float getValue() { + return Float.valueOf(getValueAsFloat()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #setFloatValue(float)} instead. + * @param newValue {@inheritDoc} + */ + @Override + @Deprecated + public void setValue(Float newValue) { + setFloatValue(newValue.floatValue()); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public int intValue() { + return (int) getValueAsFloat(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public long longValue() { + return (long) getValueAsFloat(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public float floatValue() { + return getValueAsFloat(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public double doubleValue() { + return getValueAsFloat(); + } + + /** + * {@return a string representation of the current value} + */ + @Override + public String toString() { + return value.toString(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/IntVariable.java b/src/main/java/ru/fokinatorr/sparkle/variable/IntVariable.java new file mode 100644 index 0000000..a461db9 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/IntVariable.java @@ -0,0 +1,249 @@ +package ru.fokinatorr.sparkle.variable; + +import lombok.EqualsAndHashCode; +import lombok.experimental.FieldDefaults; + +import java.util.concurrent.atomic.AtomicInteger; + +import static ru.fokinatorr.sparkle.variable.ObjectVariable.PRIMITIVE_TO_WRAPPER; + +/** + * A variable storing an {@code int} value. + */ +@SuppressWarnings({"UnnecessaryUnboxing", "UnnecessaryBoxing"}) +@FieldDefaults(makeFinal = true) +@EqualsAndHashCode(callSuper = false) +public class IntVariable extends Number implements Variable { + + AtomicInteger value; + + /** + * Creates a new {@code IntVariable} with initial value {@code 0}. + */ + public IntVariable() { + value = new AtomicInteger(); + } + + /** + * Creates a new {@code IntVariable} with the given initial value. + */ + public IntVariable(int initialValue) { + value = new AtomicInteger(initialValue); + } + + /** + * Returns the current value of this variable as {@code byte}. + * @return the value as {@code byte} + */ + @Override + public byte getValueAsByte() { + return (byte) getValueAsInt(); + } + + /** + * Returns the current value of this variable as {@code short}. + * @return the value as {@code short} + */ + @Override + public short getValueAsShort() { + return (short) getValueAsInt(); + } + + /** + * Returns the current value of this variable. + * @return the value + */ + @Override + public int getValueAsInt() { + return value.get(); + } + + /** + * Returns the current value of this variable as {@code long}. + * @return the value as {@code long} + */ + @Override + public long getValueAsLong() { + return getValueAsInt(); + } + + /** + * Returns the current value of this variable as {@code float}. + * @return the value as {@code float} + */ + @Override + public float getValueAsFloat() { + return getValueAsInt(); + } + + /** + * Returns the current value of this variable as {@code double}. + * @return the value as {@code double} + */ + @Override + public double getValueAsDouble() { + return getValueAsInt(); + } + + /** + * Sets the current value as {@code byte}. + * @param newValue {@inheritDoc} + */ + @Override + public void setByteValue(byte newValue) { + setIntValue(newValue); + } + + /** + * Sets the current value as {@code short}. + * @param newValue {@inheritDoc} + */ + @Override + public void setShortValue(short newValue) { + setIntValue(newValue); + } + + /** + * Sets the value of this variable to the given one. + * @param newValue {@inheritDoc} + */ + @Override + public void setIntValue(int newValue) { + value.set(newValue); + } + + /** + * Increments the current value. + * @return the previous value + */ + public int getAndIncrement() { + return value.getAndIncrement(); + } + + /** + * Decrements the current value. + * @return the previous value + */ + public int getAndDecrement() { + return value.getAndDecrement(); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the previous value + */ + public int getAndAdd(int delta) { + return value.getAndAdd(delta); + } + + /** + * Increments the current value. + * @return the updated value + */ + public int incrementAndGet() { + return value.incrementAndGet(); + } + + /** + * Decrements the current value. + * @return the updated value + */ + public int decrementAndGet() { + return value.decrementAndGet(); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the updated value + */ + public int addAndGet(int delta) { + return value.addAndGet(delta); + } + + /** + * {@inheritDoc} + * @param cls {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean is(Class cls) { + return PRIMITIVE_TO_WRAPPER.getOrDefault(cls, cls) == Integer.class; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public IntVariable copy() { + return new IntVariable(value.get()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #getValueAsInt()} instead. + * @return {@inheritDoc} + */ + @Override + @Deprecated + public Integer getValue() { + return Integer.valueOf(getValueAsInt()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #setIntValue(int)} instead. + * @param newValue {@inheritDoc} + */ + @Override + @Deprecated + public void setValue(Integer newValue) { + setIntValue(newValue.intValue()); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public int intValue() { + return getValueAsInt(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public long longValue() { + return getValueAsLong(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public float floatValue() { + return getValueAsFloat(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public double doubleValue() { + return getValueAsDouble(); + } + + /** + * {@return a string representation of the current value} + */ + @Override + public String toString() { + return value.toString(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/LongVariable.java b/src/main/java/ru/fokinatorr/sparkle/variable/LongVariable.java new file mode 100644 index 0000000..b643f3e --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/LongVariable.java @@ -0,0 +1,259 @@ +package ru.fokinatorr.sparkle.variable; + +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.experimental.FieldDefaults; + +import java.util.concurrent.atomic.AtomicLong; + +import static ru.fokinatorr.sparkle.variable.ObjectVariable.PRIMITIVE_TO_WRAPPER; + +/** + * A variable storing a {@code long} value. + */ +@SuppressWarnings({"UnnecessaryUnboxing", "UnnecessaryBoxing"}) +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +@EqualsAndHashCode(callSuper = false) +public class LongVariable extends Number implements Variable { + + AtomicLong value; + + /** + * Creates a new {@code LongVariable} with initial value {@code 0}. + */ + public LongVariable() { + value = new AtomicLong(); + } + + /** + * Creates a new {@code LongVariable} with the given initial value. + */ + public LongVariable(long initialValue) { + value = new AtomicLong(initialValue); + } + + /** + * Returns the current value of this variable as {@code byte}. + * @return the value as {@code byte} + */ + @Override + public byte getValueAsByte() { + return (byte) getValueAsInt(); + } + + /** + * Returns the current value of this variable as {@code short}. + * @return the value as {@code short} + */ + @Override + public short getValueAsShort() { + return (short) getValueAsInt(); + } + + /** + * Returns the current value of this variable as {@code int}. + * @return the value as {@code int} + */ + @Override + public int getValueAsInt() { + return (int) getValueAsLong(); + } + + /** + * Returns the current value of this variable. + * @return the value + */ + @Override + public long getValueAsLong() { + return value.get(); + } + + /** + * Returns the current value of this variable as {@code float}. + * @return the value as {@code float} + */ + @Override + public float getValueAsFloat() { + return getValueAsLong(); + } + + /** + * Returns the current value of this variable as {@code double}. + * @return the value as {@code double} + */ + @Override + public double getValueAsDouble() { + return getValueAsLong(); + } + + /** + * Sets the current value as {@code byte}. + * @param newValue {@inheritDoc} + */ + @Override + public void setByteValue(byte newValue) { + setLongValue(newValue); + } + + /** + * Sets the current value as {@code short}. + * @param newValue {@inheritDoc} + */ + @Override + public void setShortValue(short newValue) { + setLongValue(newValue); + } + + /** + * Sets the current value as {@code int}. + * @param newValue {@inheritDoc} + */ + @Override + public void setIntValue(int newValue) { + setLongValue(newValue); + } + + /** + * Sets the value of this variable to the given one. + * @param newValue {@inheritDoc} + */ + @Override + public void setLongValue(long newValue) { + value.set(newValue); + } + + /** + * Increments the current value. + * @return the previous value + */ + public long getAndIncrement() { + return value.getAndIncrement(); + } + + /** + * Decrements the current value. + * @return the previous value + */ + public long getAndDecrement() { + return value.getAndDecrement(); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the previous value + */ + public long getAndAdd(long delta) { + return value.getAndAdd(delta); + } + + /** + * Increments the current value. + * @return the updated value + */ + public long incrementAndGet() { + return value.incrementAndGet(); + } + + /** + * Decrements the current value. + * @return the updated value + */ + public long decrementAndGet() { + return value.decrementAndGet(); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the updated value + */ + public long addAndGet(long delta) { + return value.addAndGet(delta); + } + + /** + * {@inheritDoc} + * @param cls {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean is(Class cls) { + return PRIMITIVE_TO_WRAPPER.getOrDefault(cls, cls) == Long.class; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public LongVariable copy() { + return new LongVariable(value.get()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #getValueAsLong()} instead. + * @return {@inheritDoc} + */ + @Override + @Deprecated + public Long getValue() { + return Long.valueOf(getValueAsLong()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #setLongValue(long)} instead. + * @param newValue {@inheritDoc} + */ + @Override + @Deprecated + public void setValue(Long newValue) { + setLongValue(newValue.longValue()); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public int intValue() { + return getValueAsInt(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public long longValue() { + return getValueAsLong(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public float floatValue() { + return getValueAsFloat(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public double doubleValue() { + return getValueAsDouble(); + } + + /** + * {@return a string representation of the current value} + */ + @Override + public String toString() { + return value.toString(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/ObjectVariable.java b/src/main/java/ru/fokinatorr/sparkle/variable/ObjectVariable.java new file mode 100644 index 0000000..0658b64 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/ObjectVariable.java @@ -0,0 +1,115 @@ +package ru.fokinatorr.sparkle.variable; + +import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.experimental.FieldDefaults; + +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; + +/** + * A variable storing an object. This can be also used to create a list variable, e.g.:
+ * import java.util.ArrayList;
+ * import java.util.List;
+ *
+ * Variable> listVar = new ObjectVariable<>(new ArrayList<>());
+ * // do something with the list
+ * listVar.getValue().add("Example value");
+ * // ...
+ * 
+ *

Note: It is discouraged to use this class as a primitive variable because of the (un)boxing overhead. See other + * implementations of {@link Variable} for that purpose. + * @param the type of the object + */ +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +@EqualsAndHashCode +public class ObjectVariable implements Variable { + + /** + * Maps primitive classes to their respective wrapper classes. + */ + static final Reference2ReferenceMap, Class> PRIMITIVE_TO_WRAPPER = + new Reference2ReferenceOpenHashMap<>(Map.ofEntries( + Map.entry(boolean.class, Boolean.class), + Map.entry(byte.class, Byte.class), + Map.entry(short.class, Short.class), + Map.entry(int.class, Integer.class), + Map.entry(long.class, Long.class), + Map.entry(char.class, Character.class), + Map.entry(float.class, Float.class), + Map.entry(double.class, Double.class), + Map.entry(void.class, Void.class) + )); + + AtomicReference value; + + /** + * Constructs a new {@code ObjectVariable} with the initial value {@code null}. + */ + public ObjectVariable() { + value = new AtomicReference<>(); + } + + /** + * Constructs a new {@code ObjectVariable} with the given initial value. + * @param initialValue the initial value (nullable) + */ + public ObjectVariable(T initialValue) { + value = new AtomicReference<>(initialValue); + } + + /** + * {@inheritDoc} + * + * @return {@inheritDoc} + */ + @Override + public T getValue() { + return value.get(); + } + + /** + * {@inheritDoc} + * + * @param newValue {@inheritDoc} + */ + @Override + public void setValue(T newValue) { + value.set(newValue); + } + + /** + * {@inheritDoc} + * + * @param cls {@inheritDoc} + * @return {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + */ + @Override + public boolean is(Class cls) { + Objects.requireNonNull(cls, "class"); + T value = this.value.get(); + cls = PRIMITIVE_TO_WRAPPER.getOrDefault(cls, cls); + return value == null ? !cls.isPrimitive() : cls.isInstance(value); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public ObjectVariable copy() { + return new ObjectVariable<>(value.get()); + } + + /** + * {@return a string representation of the current value} + */ + @Override + public String toString() { + return value.toString(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/ShortVariable.java b/src/main/java/ru/fokinatorr/sparkle/variable/ShortVariable.java new file mode 100644 index 0000000..e82bd0d --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/ShortVariable.java @@ -0,0 +1,263 @@ +package ru.fokinatorr.sparkle.variable; + +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.experimental.FieldDefaults; + +import static ru.fokinatorr.sparkle.variable.ObjectVariable.PRIMITIVE_TO_WRAPPER; + +/** + * A variable storing a {@code short} value. + */ +@SuppressWarnings({"UnnecessaryUnboxing", "UnnecessaryBoxing"}) +@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) +@EqualsAndHashCode(callSuper = false) +public class ShortVariable extends Number implements Variable { + + IntVariable delegate; + + /** + * Creates a new {@code ShortVariable} with initial value {@code 0}. + */ + public ShortVariable() { + delegate = new IntVariable(); + } + + /** + * Creates a new {@code ShortVariable} with the given initial value. + */ + public ShortVariable(short initialValue) { + delegate = new IntVariable(initialValue); + } + + /** + * Returns the current value of this variable as {@code byte}. + * @return the value as {@code byte} + */ + @Override + public byte getValueAsByte() { + return delegate.getValueAsByte(); + } + + /** + * Returns the current value of this variable. + * @return the value + */ + @Override + public short getValueAsShort() { + return delegate.getValueAsShort(); + } + + /** + * Returns the current value of this variable as {@code int}. + * @return the value as {@code int} + */ + @Override + public int getValueAsInt() { + return getValueAsShort(); + } + + /** + * Returns the current value of this variable as {@code long}. + * @return the value as {@code long} + */ + @Override + public long getValueAsLong() { + return getValueAsShort(); + } + + /** + * Returns the current value of this variable as {@code float}. + * @return the value as {@code float} + */ + @Override + public float getValueAsFloat() { + return getValueAsShort(); + } + + /** + * Returns the current value of this variable as {@code double}. + * @return the value as {@code double} + */ + @Override + public double getValueAsDouble() { + return getValueAsShort(); + } + + /** + * Sets the current value as {@code byte}. + * @param newValue {@inheritDoc} + */ + @Override + public void setByteValue(byte newValue) { + delegate.setByteValue(newValue); + } + + /** + * Sets the value of this variable to the given one. + * @param newValue {@inheritDoc} + */ + @Override + public void setShortValue(short newValue) { + delegate.setShortValue(newValue); + } + + /** + * Increments the current value. + * @return the previous value + */ + public short getAndIncrement() { + return getAndAdd((short) 1); + } + + /** + * Decrements the current value. + * @return the previous value + */ + public short getAndDecrement() { + return getAndAdd((short) -1); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the previous value + */ + public short getAndAdd(short delta) { + while (true) { + short currentValue = getValueAsShort(); + short nextValue = (short) (currentValue + delta & 0xFFFF); + if (delegate.value.compareAndSet(currentValue, nextValue)) { + return currentValue; + } + } + } + + /** + * Increments the current value. + * @return the updated value + */ + public short incrementAndGet() { + return (short) (getAndAdd((short) 1) + 1); + } + + /** + * Decrements the current value. + * @return the updated value + */ + public short decrementAndGet() { + return (short) (getAndAdd((short) -1) - 1); + } + + /** + * Adds the given value to current value. + * @param delta the value to add + * @return the updated value + */ + public short addAndGet(short delta) { + return (short) (getAndAdd(delta) + delta); + } + + /** + * {@inheritDoc} + * @param cls {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public boolean is(Class cls) { + return PRIMITIVE_TO_WRAPPER.getOrDefault(cls, cls) == Short.class; + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public ShortVariable copy() { + return new ShortVariable(getValueAsShort()); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public byte byteValue() { + return (byte) getValueAsShort(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public short shortValue() { + return getValueAsShort(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public int intValue() { + return getValueAsShort(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public long longValue() { + return getValueAsShort(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public float floatValue() { + return getValueAsShort(); + } + + /** + * {@inheritDoc} + * @return {@inheritDoc} + */ + @Override + public double doubleValue() { + return getValueAsShort(); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #getValueAsShort()} instead. + * @return {@inheritDoc} + */ + @Override + @Deprecated + public Short getValue() { + return Short.valueOf(getValueAsShort()); + } + + /** + * {@inheritDoc} + * @deprecated Please use {@link #setShortValue(short)} instead. + * @param newValue {@inheritDoc} + */ + @Override + @Deprecated + public void setValue(Short newValue) { + setShortValue(newValue.shortValue()); + } + + /** + * {@return a string representation of the current value} + */ + @Override + public String toString() { + return delegate.value.toString(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/Variable.java b/src/main/java/ru/fokinatorr/sparkle/variable/Variable.java new file mode 100644 index 0000000..e231a25 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/Variable.java @@ -0,0 +1,280 @@ +package ru.fokinatorr.sparkle.variable; + +/** + * Base interface for all variables stored within a sprite or a stage. + *

Note for Scratchers: This interface and its implementations match the functionality of the "Variables" + * block section in Scratch. + * @param the type of the variable + */ +@SuppressWarnings("UnnecessaryUnboxing") +public interface Variable { + + /** + * Returns the current value of this variable. + * @return the value + */ + T getValue(); + + /** + * Sets the value of this variable to the given one. + * @param newValue the new value + */ + void setValue(T newValue); + + /** + * Returns whether the current value of this variable can be exactly represented + * as the class represented by the given {@link Class} object. Primitive classes should also be accepted. + * @param cls the class + * @return {@code true} if the current value is an instance of the given class, {@code false} otherwise + * @throws NullPointerException if the given class object is {@code null} (optional) + */ + boolean is(Class cls); + + /** + * Creates and returns a copy of this variable. The copy should not be a view over the source {@code Variable}. + * @return a copy of this variable + */ + Variable copy(); + + /** + * Returns the current value as {@code boolean}, if possible, else + * throws an exception. + * @return the current value as {@code boolean} if applicable + * @throws ClassCastException if current value can not be represented as {@code boolean} + */ + default boolean getValueAsBoolean() { + T value = getValue(); + if (value instanceof Boolean b) { + return b.booleanValue(); + } else if (value instanceof String s) { + if ("true".equalsIgnoreCase(s)) { + return true; + } else if ("false".equalsIgnoreCase(s)) { + return false; + } + } + throw new ClassCastException("Cannot convert " + getClassNameOrNull(value) + " to boolean"); + } + + /** + * Returns the current value as {@code byte}, if possible, else + * throws an exception. + * @return the current value as {@code byte} if applicable + * @throws ClassCastException if current value can not be represented as {@code byte} + */ + default byte getValueAsByte() { + T value = getValue(); + if (value instanceof Number n) { + return n.byteValue(); + } else if (value instanceof String s) { + try { + return Byte.parseByte(s); + } catch (NumberFormatException _) { + // pass through + } + } + throw new ClassCastException("Cannot convert " + getClassNameOrNull(value) + " to byte"); + } + + /** + * Returns the current value as {@code short}, if possible, else + * throws an exception. + * @return the current value as {@code short} if applicable + * @throws ClassCastException if current value can not be represented as {@code short} + */ + default short getValueAsShort() { + T value = getValue(); + if (value instanceof Number n) { + return n.shortValue(); + } else if (value instanceof String s) { + try { + return Short.parseShort(s); + } catch (NumberFormatException _) { + // pass through + } + } + throw new ClassCastException("Cannot convert " + getClassNameOrNull(value) + " to short"); + } + + /** + * Returns the current value as {@code int}, if possible, else + * throws an exception. + * @return the current value as {@code int} if applicable + * @throws ClassCastException if current value can not be represented as {@code int} + */ + default int getValueAsInt() { + T value = getValue(); + if (value instanceof Number n) { + return n.intValue(); + } else if (value instanceof String s) { + try { + return Integer.parseInt(s); + } catch (NumberFormatException _) { + // pass through + } + } + throw new ClassCastException("Cannot convert " + getClassNameOrNull(value) + " to int"); + } + + /** + * Returns the current value as {@code long}, if possible, else + * throws an exception. + * @return the current value as {@code long} if applicable + * @throws ClassCastException if current value can not be represented as {@code long} + */ + default long getValueAsLong() { + T value = getValue(); + if (value instanceof Number n) { + return n.longValue(); + } else if (value instanceof String s) { + try { + return Long.parseLong(s); + } catch (NumberFormatException _) { + // pass through + } + } + throw new ClassCastException("Cannot convert " + getClassNameOrNull(value) + " to long"); + } + + /** + * Returns the current value as {@code float}, if possible, else + * throws an exception. + * @return the current value as {@code float} if applicable + * @throws ClassCastException if current value can not be represented as {@code float} + */ + default float getValueAsFloat() { + T value = getValue(); + if (value instanceof Number n) { + return n.floatValue(); + } else if (value instanceof String s) { + try { + return Float.parseFloat(s); + } catch (NumberFormatException _) { + // pass through + } + } + throw new ClassCastException("Cannot convert " + getClassNameOrNull(value) + " to float"); + } + + /** + * Returns the current value as {@code double}, if possible, else + * throws an exception. + * @return the current value as {@code double} if applicable + * @throws ClassCastException if current value can not be represented as {@code double} + */ + default double getValueAsDouble() { + T value = getValue(); + if (value instanceof Number n) { + return n.doubleValue(); + } else if (value instanceof String s) { + try { + return Double.parseDouble(s); + } catch (NumberFormatException _) { + // pass through + } + } + throw new ClassCastException("Cannot convert " + getClassNameOrNull(value) + " to double"); + } + + /** + * Returns the current value as {@code char}, if possible, else + * throws an exception. + * @return the current value as {@code char} if applicable + * @throws ClassCastException if current value can not be represented as {@code char} + */ + default char getValueAsChar() { + T value = getValue(); + if (value instanceof Character c) { + return c.charValue(); + } else if (value instanceof String s) { + if (s.length() == 1) { + return s.charAt(0); + } + } + throw new ClassCastException("Cannot convert " + getClassNameOrNull(value) + " to char"); + } + + /** + * Sets the current value as {@code boolean} (optional operation). + * @param newValue the new {@code boolean} value + * @throws UnsupportedOperationException if setting the value as {@code boolean} is not supported + * @implNote The default implementation just throws an {@link UnsupportedOperationException}. + */ + default void setBooleanValue(boolean newValue) { + throw new UnsupportedOperationException(); + } + + /** + * Sets the current value as {@code byte} (optional operation). + * @param newValue the new {@code byte} value + * @throws UnsupportedOperationException if setting the value as {@code byte} is not supported + * @implNote The default implementation just throws an {@link UnsupportedOperationException}. + */ + default void setByteValue(byte newValue) { + throw new UnsupportedOperationException(); + } + + /** + * Sets the current value as {@code short} (optional operation). + * @param newValue the new {@code short} value + * @throws UnsupportedOperationException if setting the value as {@code short} is not supported + * @implNote The default implementation just throws an {@link UnsupportedOperationException}. + */ + default void setShortValue(short newValue) { + throw new UnsupportedOperationException(); + } + + /** + * Sets the current value as {@code int} (optional operation). + * @param newValue the new {@code int} value + * @throws UnsupportedOperationException if setting the value as {@code int} is not supported + * @implNote The default implementation just throws an {@link UnsupportedOperationException}. + */ + default void setIntValue(int newValue) { + throw new UnsupportedOperationException(); + } + + /** + * Sets the current value as {@code long} (optional operation). + * @param newValue the new {@code long} value + * @throws UnsupportedOperationException if setting the value as {@code long} is not supported + * @implNote The default implementation just throws an {@link UnsupportedOperationException}. + */ + default void setLongValue(long newValue) { + throw new UnsupportedOperationException(); + } + + /** + * Sets the current value as {@code float} (optional operation). + * @param newValue the new {@code float} value + * @throws UnsupportedOperationException if setting the value as {@code float} is not supported + * @implNote The default implementation just throws an {@link UnsupportedOperationException}. + */ + default void setFloatValue(float newValue) { + throw new UnsupportedOperationException(); + } + + /** + * Sets the current value as {@code double} (optional operation). + * @param newValue the new {@code double} value + * @throws UnsupportedOperationException if setting the value as {@code double} is not supported + * @implNote The default implementation just throws an {@link UnsupportedOperationException}. + */ + default void setDoubleValue(double newValue) { + throw new UnsupportedOperationException(); + } + + /** + * Sets the current value as {@code char} (optional operation). + * @param newValue the new {@code char} value + * @throws UnsupportedOperationException if setting the value as {@code char} is not supported + * @implNote The default implementation just throws an {@link UnsupportedOperationException}. + */ + default void setCharValue(char newValue) { + throw new UnsupportedOperationException(); + } + + private static String getClassNameOrNull(Object value) { + return value == null ? "null" : value.getClass().getName(); + } +} diff --git a/src/main/java/ru/fokinatorr/sparkle/variable/VariableStorage.java b/src/main/java/ru/fokinatorr/sparkle/variable/VariableStorage.java new file mode 100644 index 0000000..104dce3 --- /dev/null +++ b/src/main/java/ru/fokinatorr/sparkle/variable/VariableStorage.java @@ -0,0 +1,31 @@ +package ru.fokinatorr.sparkle.variable; + +import java.util.Map; + +/** + * An object that stores variables mapped to IDs. + * @param the type of variable ID + */ +public interface VariableStorage { + /** + * Returns an unmodifiable view over this storage's variables. + * @return an immutable view over registered variables + */ + Map> getVariables(); + + /** + * Registers a variable under the given ID. + * @param id the ID of the variable + * @param variable the variable + * @throws IllegalArgumentException if a variable with the given ID is already present + */ + void registerVariable(ID id, Variable variable); + + /** + * Returns a variable with the given ID. + *

Equivalent to {@code getVariables().get(id)}. + * @param id the ID + * @return the respective variable + */ + Variable getVariable(ID id); +} diff --git a/src/main/resources/LICENSE b/src/main/resources/LICENSE new file mode 100644 index 0000000..9890b48 --- /dev/null +++ b/src/main/resources/LICENSE @@ -0,0 +1,7 @@ +Copyright © 2026 Fokinatorr_ + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/src/main/resources/README.md b/src/main/resources/README.md new file mode 100644 index 0000000..70f8cbf --- /dev/null +++ b/src/main/resources/README.md @@ -0,0 +1,91 @@ +Project Sparkle (SFNS) +========== + +SFNS *(code name Sparkle; later Sparkle)* +is a Java-based framework for creating graphical applications with an API inspired by MIT Scratch. +It provides a modern, object-oriented approach to building interactive applications and +many customization options, while maintaining the simplicity and accessibility that Scratch is known for. + +## Project Goals + +These goals are what this project aims at achieving, in chronological order. Below each goal is a brief description of why +it matters, and when it was created (approximately). +1. *Provide a Scratch-like API with Java code instead of code blocks, but offer more flexibility without making things harder overall.* + - Some, like me, find code blocks and many restrictions very inconvenient for project creation. Sparkle fixes those issues + by removing these two altogether. APIs are more flexible, and Java code is used instead of code blocks. + - This goal was the primary fuel for working on Sparkle ever since the very beginning (June 2025). +2. *Create a bridge between Scratch and Java worlds, allowing to advance step-by-step and allowing Scratchers to learn Java +and get a taste of real-world programming.* + - Schools nowadays (in profile IT classes!) often teach students only procedural programming paradigm (which first appeared in good old **C**) + and basics of programming, focusing mostly on working with existing software, which is usually *not even remotely* related to programming. + - As a result, students that want to learn programming don't get any idea about real-world programming. Especially the OOP paradigm, + the one that skyrocketed in popularity and is very practical today. + - Sparkle solves that by providing a well-structured OOP-based interface and layers of simplification for newbies. Maybe it's even + school-friendly? We'll find out some day... + - This goal was placed in March 2026, and was already fulfilled upon its placement :] +3. *Prove that Java is not "old and slow", but rather a good choice for graphical apps.* + - Many people think Java is a very slow platform for an unexplainable reason... Maybe because it was like that in its early days. + Nowadays, it's completely different. JIT compilers can optimize JVM bytecode at runtime so good, it can compete against GCC-compiled + C/C++ binaries, and sometimes even exceed their performance! + - Moreover, performance isn't everything. Take a look at *Minecraft*, a very popular and beloved game. Original Minecraft is written + in Java (with LWJGL for C++ bindings, and Sparkle uses LWJGL!). You might say it's not optimal, but that's because of the game's code itself, + not the platform. Many optimization mods exist (like OptiFine, Sodium, etc.) and with them, the game runs *much* faster. + - Sparkle has a potential to prove the world Java is evolving like any other platform, including C++ and Python. Maybe it will even + revive Java gaming? Or it's just me `(._.);` + - This goal was placed in April 2026. + +## Overview + +While Sparkle shares conceptual similarities with Scratch, it's a completely different framework, with some aspects of its own design. +The framework allows developers to write Java code instead of using code blocks, providing greater flexibility and access to Java's extensive ecosystem. + +### This project is for you if: +- You want more power and flexibility than what can be achieved through block scripts; +- You know about Scratch and want something closer to its syntax; +- You know basic OOP and Java and want to advance your Java skills without being constrained or limited. + +### This project is *not* for you if: +- You prefer code blocks instead of writing code, or if Java structures scare you; +- You prefer simplicity to flexibility; +- You want an exact copy of Scratch's model in Java. + +*Don't take it too personally if any of these statements are true for you! You still can try out Sparkle; this paragraph acts +as a warning that you **might** not enjoy coding with it, **not** as a restriction layer. `(^u^)`* + +--- + +## Core Features + +- **Sprite-based programming**: Create and manipulate sprites with properties like position, rotation, costumes, and sounds +- **Stage management**: Control the application stage with backdrops, custom drawing, and layer management +- **Event-driven architecture**: Comprehensive event system for handling user input, stage state changes, and custom events +- **Graphics rendering**: 2D rendering capabilities with support for transformations, effects, and custom drawing +- **Audio support**: Play and manipulate sounds with various effects +- **Physics**: 2D hitbox system for collision detection + +## Key Components + +TODO: This is a draft, reformat when done +1. sprites, stages, event dispatcher - basic Scratch-like components +2. variables, lists (via `.variable` subpackage), custom "blocks" (in Java these are just methods!) - advanced Scratch-like features +3. application context, vanilla components (audio manager, graphics manager, etc.), custom user-made components - advanced-level features + +## Getting Started + +TODO: make a template project when done and tell about "Sparkle" IDE plugin here + +Enjoy! :D + +--- + +## Development Status + +The framework is currently under active development with most core features implemented. + +_Note: The project is **still in beta**_; feel free to contribute via pull requests, apply for the beta testing programme, +suggest features and improvements, and report bugs/issues. Make sure to be constructive in your posts, _nobody_ likes +whiners/spammers ;) + +## License + +MIT License - see [the license](LICENSE) file for details. \ No newline at end of file diff --git a/src/main/resources/assets/fonts/Grand9K Pixel/COPYRIGHT.txt b/src/main/resources/assets/fonts/Grand9K Pixel/COPYRIGHT.txt new file mode 100644 index 0000000..8ae5db6 --- /dev/null +++ b/src/main/resources/assets/fonts/Grand9K Pixel/COPYRIGHT.txt @@ -0,0 +1 @@ +© 2009, 2010, 2011, 2012, 2013 Grand Chaos Productions. Some Rights Reserved. \ No newline at end of file diff --git a/src/main/resources/assets/fonts/Grand9K Pixel/normal/normal.ttf b/src/main/resources/assets/fonts/Grand9K Pixel/normal/normal.ttf new file mode 100755 index 0000000..cf6fdf4 Binary files /dev/null and b/src/main/resources/assets/fonts/Grand9K Pixel/normal/normal.ttf differ diff --git a/src/main/resources/assets/fonts/Griffy/OFL.txt b/src/main/resources/assets/fonts/Griffy/OFL.txt new file mode 100644 index 0000000..084ee14 --- /dev/null +++ b/src/main/resources/assets/fonts/Griffy/OFL.txt @@ -0,0 +1,94 @@ +Copyright (c) 2012, Font Diner (www.fontdiner.com), +with Reserved Font Name "Griffy". + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/main/resources/assets/fonts/Griffy/normal/normal.ttf b/src/main/resources/assets/fonts/Griffy/normal/normal.ttf new file mode 100644 index 0000000..5c13523 Binary files /dev/null and b/src/main/resources/assets/fonts/Griffy/normal/normal.ttf differ diff --git a/src/main/resources/assets/fonts/Handlee/OFL.txt b/src/main/resources/assets/fonts/Handlee/OFL.txt new file mode 100644 index 0000000..aa19fc2 --- /dev/null +++ b/src/main/resources/assets/fonts/Handlee/OFL.txt @@ -0,0 +1,94 @@ +Copyright (c) 2011, Joe Prince, Vissol Ltd. (http://www.vissol.co.uk/mavenpro/) +with Reserved Font Name "Handlee". + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/main/resources/assets/fonts/Handlee/normal/normal.ttf b/src/main/resources/assets/fonts/Handlee/normal/normal.ttf new file mode 100644 index 0000000..7984255 Binary files /dev/null and b/src/main/resources/assets/fonts/Handlee/normal/normal.ttf differ diff --git a/src/main/resources/assets/fonts/Knewave/OFL.txt b/src/main/resources/assets/fonts/Knewave/OFL.txt new file mode 100644 index 0000000..34f48fe --- /dev/null +++ b/src/main/resources/assets/fonts/Knewave/OFL.txt @@ -0,0 +1,93 @@ +Copyright (c) 2010, Tyler Finck , with Reserved Font Name: "Knewave". + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/main/resources/assets/fonts/Knewave/normal/normal.ttf b/src/main/resources/assets/fonts/Knewave/normal/normal.ttf new file mode 100644 index 0000000..a98f750 Binary files /dev/null and b/src/main/resources/assets/fonts/Knewave/normal/normal.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/OFL.txt b/src/main/resources/assets/fonts/Noto Sans/OFL.txt new file mode 100644 index 0000000..0373e14 --- /dev/null +++ b/src/main/resources/assets/fonts/Noto Sans/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/main/resources/assets/fonts/Noto Sans/italic/black.ttf b/src/main/resources/assets/fonts/Noto Sans/italic/black.ttf new file mode 100644 index 0000000..dfc640c Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/italic/black.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/italic/bold.ttf b/src/main/resources/assets/fonts/Noto Sans/italic/bold.ttf new file mode 100644 index 0000000..e538eae Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/italic/bold.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/italic/extra_bold.ttf b/src/main/resources/assets/fonts/Noto Sans/italic/extra_bold.ttf new file mode 100644 index 0000000..68abd4c Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/italic/extra_bold.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/italic/extra_light.ttf b/src/main/resources/assets/fonts/Noto Sans/italic/extra_light.ttf new file mode 100644 index 0000000..acaa466 Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/italic/extra_light.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/italic/light.ttf b/src/main/resources/assets/fonts/Noto Sans/italic/light.ttf new file mode 100644 index 0000000..0ab65c0 Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/italic/light.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/italic/medium.ttf b/src/main/resources/assets/fonts/Noto Sans/italic/medium.ttf new file mode 100644 index 0000000..467af1b Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/italic/medium.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/italic/normal.ttf b/src/main/resources/assets/fonts/Noto Sans/italic/normal.ttf new file mode 100644 index 0000000..d9b9e14 Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/italic/normal.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/italic/semi_bold.ttf b/src/main/resources/assets/fonts/Noto Sans/italic/semi_bold.ttf new file mode 100644 index 0000000..cacc7ec Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/italic/semi_bold.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/italic/thin.ttf b/src/main/resources/assets/fonts/Noto Sans/italic/thin.ttf new file mode 100644 index 0000000..910dfc7 Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/italic/thin.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/normal/black.ttf b/src/main/resources/assets/fonts/Noto Sans/normal/black.ttf new file mode 100644 index 0000000..d5a6e0d Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/normal/black.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/normal/bold.ttf b/src/main/resources/assets/fonts/Noto Sans/normal/bold.ttf new file mode 100644 index 0000000..07f0d25 Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/normal/bold.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/normal/extra_bold.ttf b/src/main/resources/assets/fonts/Noto Sans/normal/extra_bold.ttf new file mode 100644 index 0000000..5868446 Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/normal/extra_bold.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/normal/extra_light.ttf b/src/main/resources/assets/fonts/Noto Sans/normal/extra_light.ttf new file mode 100644 index 0000000..078f8dc Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/normal/extra_light.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/normal/light.ttf b/src/main/resources/assets/fonts/Noto Sans/normal/light.ttf new file mode 100644 index 0000000..8d8a678 Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/normal/light.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/normal/medium.ttf b/src/main/resources/assets/fonts/Noto Sans/normal/medium.ttf new file mode 100644 index 0000000..a44124b Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/normal/medium.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/normal/normal.ttf b/src/main/resources/assets/fonts/Noto Sans/normal/normal.ttf new file mode 100644 index 0000000..4bac02f Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/normal/normal.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/normal/semi_bold.ttf b/src/main/resources/assets/fonts/Noto Sans/normal/semi_bold.ttf new file mode 100644 index 0000000..e846749 Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/normal/semi_bold.ttf differ diff --git a/src/main/resources/assets/fonts/Noto Sans/normal/thin.ttf b/src/main/resources/assets/fonts/Noto Sans/normal/thin.ttf new file mode 100644 index 0000000..04335a5 Binary files /dev/null and b/src/main/resources/assets/fonts/Noto Sans/normal/thin.ttf differ diff --git a/src/main/resources/assets/textures/control_buttons/desktop.ini b/src/main/resources/assets/textures/control_buttons/desktop.ini new file mode 100644 index 0000000..f242a79 --- /dev/null +++ b/src/main/resources/assets/textures/control_buttons/desktop.ini @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/main/resources/assets/textures/control_buttons/pause.svg b/src/main/resources/assets/textures/control_buttons/pause.svg new file mode 100644 index 0000000..5255ed3 --- /dev/null +++ b/src/main/resources/assets/textures/control_buttons/pause.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/main/resources/assets/textures/control_buttons/start.svg b/src/main/resources/assets/textures/control_buttons/start.svg new file mode 100644 index 0000000..890f4a2 --- /dev/null +++ b/src/main/resources/assets/textures/control_buttons/start.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/main/resources/assets/textures/control_buttons/stop.svg b/src/main/resources/assets/textures/control_buttons/stop.svg new file mode 100644 index 0000000..2fe81ab --- /dev/null +++ b/src/main/resources/assets/textures/control_buttons/stop.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/main/resources/assets/textures/empty.svg b/src/main/resources/assets/textures/empty.svg new file mode 100644 index 0000000..8cb020c --- /dev/null +++ b/src/main/resources/assets/textures/empty.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/main/resources/shaders/fill.frag.glsl b/src/main/resources/shaders/fill.frag.glsl new file mode 100644 index 0000000..741c539 --- /dev/null +++ b/src/main/resources/shaders/fill.frag.glsl @@ -0,0 +1,24 @@ +#version 330 core + +in vec4 v_Color; +out vec4 FragColor; + +uniform float u_HueShift; +uniform float u_Brightness; +uniform float u_Opacity; + +{{rgb2hsv}} +{{hsv2rgb}} +{{apply_hue_shift}} +{{apply_brightness}} +{{apply_opacity}} + +void main() { + vec4 color = v_Color; + + color = applyOpacity(color, u_Opacity); + color = applyHueShift(color, u_HueShift); + color = applyBrightness(color, u_Brightness); + + FragColor = color; +} \ No newline at end of file diff --git a/src/main/resources/shaders/fill.vert.glsl b/src/main/resources/shaders/fill.vert.glsl new file mode 100644 index 0000000..0d43634 --- /dev/null +++ b/src/main/resources/shaders/fill.vert.glsl @@ -0,0 +1,13 @@ +#version 330 core + +layout (location = 0) in vec2 a_Position; + +uniform mat4 u_ModelViewProj; +uniform vec4 u_Color; + +out vec4 v_Color; + +void main() { + v_Color = u_Color; + gl_Position = u_ModelViewProj * vec4(a_Position, 0.0, 1.0); +} \ No newline at end of file diff --git a/src/main/resources/shaders/image.frag.glsl b/src/main/resources/shaders/image.frag.glsl new file mode 100644 index 0000000..52b04d6 --- /dev/null +++ b/src/main/resources/shaders/image.frag.glsl @@ -0,0 +1,49 @@ +#version 330 core + +in vec2 v_TexCoord; +out vec4 FragColor; + +uniform sampler2D u_Texture; +uniform float u_Alpha; +uniform float u_HueShift; +uniform float u_Bulge; // Radial distortion strength +uniform float u_Whirl; // Rotation angle based on distance from center +uniform float u_Pixelation; +uniform float u_Mosaic; +uniform float u_Brightness; +uniform float u_Opacity; + +{{rgb2hsv}} +{{hsv2rgb}} +{{apply_hue_shift}} +{{apply_bulge}} +{{apply_whirl}} +{{apply_pixelation}} +{{apply_mosaic}} +{{apply_brightness}} +{{apply_opacity}} + +void main() { + vec2 uv = v_TexCoord; + + // Apply geometric distortions in order + uv = applyBulge(uv, u_Bulge); + uv = applyWhirl(uv, u_Whirl); + // skew done in vertex shader + uv = applyMosaic(uv, u_Mosaic); + if (u_Pixelation > 0.0) { + uv = applyPixelation(uv, u_Pixelation); + } + + vec4 color = texture(u_Texture, uv); + + // Apply color effects + color = applyHueShift(color, u_HueShift); + color = applyBrightness(color, u_Brightness); + color = applyOpacity(color, u_Opacity); + + // Final alpha + color.a *= u_Alpha; + + FragColor = color; +} \ No newline at end of file diff --git a/src/main/resources/shaders/image.vert.glsl b/src/main/resources/shaders/image.vert.glsl new file mode 100644 index 0000000..9328601 --- /dev/null +++ b/src/main/resources/shaders/image.vert.glsl @@ -0,0 +1,20 @@ +#version 330 core + +layout (location = 0) in vec2 a_Position; +layout (location = 1) in vec2 a_TexCoord; + +out vec2 v_TexCoord; + +uniform mat4 u_ModelViewProj; +uniform float u_SkewX; +uniform float u_SkewY; + +void main() { + // Apply skew + vec2 skewedPos = a_Position; + skewedPos.x += a_Position.y * u_SkewX * 0.01; // Shear X based on Y + skewedPos.y += a_Position.x * u_SkewY * 0.01; // Shear Y based on X + + gl_Position = u_ModelViewProj * vec4(skewedPos, 0.0, 1.0); + v_TexCoord = a_TexCoord; +} \ No newline at end of file diff --git a/src/main/resources/shaders/snippets/apply_brightness.glsl b/src/main/resources/shaders/snippets/apply_brightness.glsl new file mode 100644 index 0000000..d3104f6 --- /dev/null +++ b/src/main/resources/shaders/snippets/apply_brightness.glsl @@ -0,0 +1,3 @@ +vec4 applyBrightness(vec4 color, float factor) { + return vec4(mix(vec3(0.5), color.rgb, 1.0 + factor), color.a); +} \ No newline at end of file diff --git a/src/main/resources/shaders/snippets/apply_bulge.glsl b/src/main/resources/shaders/snippets/apply_bulge.glsl new file mode 100644 index 0000000..e6a40dc --- /dev/null +++ b/src/main/resources/shaders/snippets/apply_bulge.glsl @@ -0,0 +1,8 @@ +vec2 applyBulge(vec2 uv, float strength) { + if (strength == 0.0) return uv; + vec2 center = vec2(0.5, 0.5); + vec2 dir = uv - center; + float dist = length(dir); + float factor = pow(dist, 1.0 + strength * 0.5); + return center + dir * (factor / dist); +} \ No newline at end of file diff --git a/src/main/resources/shaders/snippets/apply_hue_shift.glsl b/src/main/resources/shaders/snippets/apply_hue_shift.glsl new file mode 100644 index 0000000..e7acd56 --- /dev/null +++ b/src/main/resources/shaders/snippets/apply_hue_shift.glsl @@ -0,0 +1,7 @@ +// Requires rgb2hsv and hsv2rgb +vec4 applyHueShift(vec4 color, float degrees) { + if (degrees == 0.0) return color; + vec3 hsv = rgb2hsv(color.rgb); + hsv.x = fract(hsv.x + degrees / 360.0); + return vec4(hsv2rgb(hsv), color.a); +} \ No newline at end of file diff --git a/src/main/resources/shaders/snippets/apply_mosaic.glsl b/src/main/resources/shaders/snippets/apply_mosaic.glsl new file mode 100644 index 0000000..0fa6884 --- /dev/null +++ b/src/main/resources/shaders/snippets/apply_mosaic.glsl @@ -0,0 +1,16 @@ +vec2 applyMosaic(vec2 uv, float strength) { + float absStrength = abs(strength); + if (absStrength < 5.0) return uv; + + // Map strength to grid size: 5-14 → 2, 15-24 → 3, etc. + int level = int((absStrength - 5.0) / 10.0) + 2; // Start at 2×2 + int scale = clamp(level, 2, 32); // Safety cap + + // Compute which cell we're in + vec2 cellCoord = floor(uv * scale); + + // Sample from center of that cell in low-res space + vec2 samplePoint = (cellCoord + 0.5) / scale; + + return samplePoint; +} \ No newline at end of file diff --git a/src/main/resources/shaders/snippets/apply_opacity.glsl b/src/main/resources/shaders/snippets/apply_opacity.glsl new file mode 100644 index 0000000..3c402ea --- /dev/null +++ b/src/main/resources/shaders/snippets/apply_opacity.glsl @@ -0,0 +1,4 @@ +vec4 applyOpacity(vec4 color, float opacity) { + color.a *= opacity; + return color; +} \ No newline at end of file diff --git a/src/main/resources/shaders/snippets/apply_pixelation.glsl b/src/main/resources/shaders/snippets/apply_pixelation.glsl new file mode 100644 index 0000000..b5721b9 --- /dev/null +++ b/src/main/resources/shaders/snippets/apply_pixelation.glsl @@ -0,0 +1,7 @@ +vec2 applyPixelation(vec2 uv, float strength) { + if (strength <= 0.0) return uv; + ivec2 size = textureSize(u_Texture, 0); + vec2 invRes = 1.0 / vec2(size); + vec2 cell = floor(uv / invRes / (strength + 1.0)); + return cell * invRes * (strength + 1.0) + invRes * 0.5; +} \ No newline at end of file diff --git a/src/main/resources/shaders/snippets/apply_whirl.glsl b/src/main/resources/shaders/snippets/apply_whirl.glsl new file mode 100644 index 0000000..7b1b249 --- /dev/null +++ b/src/main/resources/shaders/snippets/apply_whirl.glsl @@ -0,0 +1,10 @@ +vec2 applyWhirl(vec2 uv, float strength) { + if (strength == 0.0) return uv; + vec2 center = vec2(0.5, 0.5); + vec2 dir = uv - center; + float dist = length(dir); + float maxDist = length(vec2(0.5)); + float angle = strength * (dist / maxDist) * 3.14159265; + mat2 rot = mat2(cos(angle), -sin(angle), sin(angle), cos(angle)); + return center + rot * dir; +} \ No newline at end of file diff --git a/src/main/resources/shaders/snippets/hsv2rgb.glsl b/src/main/resources/shaders/snippets/hsv2rgb.glsl new file mode 100644 index 0000000..770068f --- /dev/null +++ b/src/main/resources/shaders/snippets/hsv2rgb.glsl @@ -0,0 +1,5 @@ +vec3 hsv2rgb(vec3 c) { + vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); + return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); +} \ No newline at end of file diff --git a/src/main/resources/shaders/snippets/rgb2hsv.glsl b/src/main/resources/shaders/snippets/rgb2hsv.glsl new file mode 100644 index 0000000..56e5a57 --- /dev/null +++ b/src/main/resources/shaders/snippets/rgb2hsv.glsl @@ -0,0 +1,7 @@ +vec3 rgb2hsv(vec3 c) { + vec4 K = vec4(0.0, -1.0 / 3.0, 1.0 / 3.0, -1.0); + vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); + vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); + float d = q.x - min(q.w, q.y); + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + 1e-10)), d / (q.x + 1e-10), q.x); +} \ No newline at end of file diff --git a/src/main/resources/shaders/stroke.frag.glsl b/src/main/resources/shaders/stroke.frag.glsl new file mode 100644 index 0000000..741c539 --- /dev/null +++ b/src/main/resources/shaders/stroke.frag.glsl @@ -0,0 +1,24 @@ +#version 330 core + +in vec4 v_Color; +out vec4 FragColor; + +uniform float u_HueShift; +uniform float u_Brightness; +uniform float u_Opacity; + +{{rgb2hsv}} +{{hsv2rgb}} +{{apply_hue_shift}} +{{apply_brightness}} +{{apply_opacity}} + +void main() { + vec4 color = v_Color; + + color = applyOpacity(color, u_Opacity); + color = applyHueShift(color, u_HueShift); + color = applyBrightness(color, u_Brightness); + + FragColor = color; +} \ No newline at end of file diff --git a/src/main/resources/shaders/stroke.vert.glsl b/src/main/resources/shaders/stroke.vert.glsl new file mode 100644 index 0000000..0d43634 --- /dev/null +++ b/src/main/resources/shaders/stroke.vert.glsl @@ -0,0 +1,13 @@ +#version 330 core + +layout (location = 0) in vec2 a_Position; + +uniform mat4 u_ModelViewProj; +uniform vec4 u_Color; + +out vec4 v_Color; + +void main() { + v_Color = u_Color; + gl_Position = u_ModelViewProj * vec4(a_Position, 0.0, 1.0); +} \ No newline at end of file diff --git a/src/test/java/ARGBTest.java b/src/test/java/ARGBTest.java new file mode 100644 index 0000000..a2362b9 --- /dev/null +++ b/src/test/java/ARGBTest.java @@ -0,0 +1,33 @@ +import lombok.experimental.ExtensionMethod; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import ru.fokinatorr.sparkle.graphics.ARGB; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Slf4j +@ExtensionMethod(ARGB.class) +public class ARGBTest { + + // Ignore the errors; IDEA for some reason can not find the extension methods from ARGB + // The error calls are actually calls to method in ARGB class with the int value as a parameter; this is done by Lombok + // Also the calls directly on the int colors just look pretty and OOP-ish, so I made it like that ^u^ + @Test + void test() { + int red = ARGB.color((byte) 255, (byte) 255, (byte) 0, (byte) 0); + int green = ARGB.color((byte) 255, (byte) 0, (byte) 255, (byte) 0); + int yellow = ARGB.color((byte) 255, (byte) 255, (byte) 255, (byte) 0); + int black = ARGB.color((byte) 255, (byte) 0, (byte) 0, (byte) 0); + assertEquals((byte) 255, red.red()); + assertEquals((byte) 255, green.green()); + assertEquals(yellow, red.add(green)); + assertEquals(red, yellow.rgbSubtract(green)); + assertEquals(green, yellow.rgbSubtract(red)); + assertEquals(black, red.rgbSubtract(yellow)); + assertEquals(black, red.rgbMultiply(green)); + assertEquals(green, yellow.rgbMultiply(green)); + assertEquals(red, yellow.rgbMultiply(red)); + } +} diff --git a/src/test/java/AudioManagerTest.java b/src/test/java/AudioManagerTest.java new file mode 100644 index 0000000..5eba5b4 --- /dev/null +++ b/src/test/java/AudioManagerTest.java @@ -0,0 +1,190 @@ +import it.unimi.dsi.fastutil.Pair; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.*; +import ru.fokinatorr.sparkle.audio.AudioManager; +import ru.fokinatorr.sparkle.audio.SoundInstance; +import ru.fokinatorr.sparkle.audio.impl.OpenALAudioManager; +import ru.fokinatorr.sparkle.audio.impl.StaticSoundSource; +import ru.fokinatorr.sparkle.audio.impl.StreamingSoundSource; +import ru.fokinatorr.sparkle.audio.impl.io.VorbisSoundDecoder; +import ru.fokinatorr.sparkle.audio.io.SoundDecoder; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.context.DefaultAppContext; + +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.*; +import static ru.fokinatorr.sparkle.util.WaitUtils.*; + +@SuppressWarnings("resource") +@Slf4j +@Disabled("Temporary") +public class AudioManagerTest { + + + static final Path + BEEP = resource("beep.ogg"), // ~1 second, mostly silence + BOOM = resource("boom.ogg"), // ~1 second + NOCK_EM = resource("nock_em.ogg"); // 3:31 + + static AppContext context; + static OpenALAudioManager audioManager; + static Thread audioThread; + + @Test + void testState() { + Pair beepInstance = audioManager.createStaticSoundInstance(BEEP); + assertEquals(beepInstance.value(), audioManager.getSoundInstance(beepInstance.key())); + assertEquals(SoundInstance.State.INITIAL, beepInstance.value().getState()); + + beepInstance.value().play(); + assertEquals(SoundInstance.State.PLAYING, beepInstance.value().getState()); + log.warn("You must hear two beep sounds"); + + waitUntil(() -> beepInstance.value().getState() == SoundInstance.State.STOPPED); + log.warn("The sound must have ended now"); + waitFor(750); // enough to react to log + + audioManager.destroySoundInstance(beepInstance.key()); + assertNull(audioManager.getSoundInstance(beepInstance.key())); + } + + @Test + void testPauseResumeRewind() { + Pair boomInstance = audioManager.createStaticSoundInstance(BOOM); // a bit longer than beep + assertEquals(SoundInstance.State.INITIAL, boomInstance.value().getState()); + log.warn("You must hear the boom sound start, then a pause for about 1 second and the rest of the sound"); + waitFor(750); + + boomInstance.value().play(); + log.warn("The sound must have started playing"); + assertEquals(SoundInstance.State.PLAYING, boomInstance.value().getState()); + + waitFor(500); + boomInstance.value().pause(); + log.warn("The sound must have been paused"); + assertEquals(SoundInstance.State.PAUSED, boomInstance.value().getState()); + + waitFor(1000); + boomInstance.value().play(); + log.warn("The sound must have been resumed"); + assertEquals(SoundInstance.State.PLAYING, boomInstance.value().getState()); + + waitUntil(() -> boomInstance.value().getState() == SoundInstance.State.STOPPED); + log.warn("The sound must have ended"); + log.warn("The sound must now play again without pauses"); + waitFor(750); + + boomInstance.value().rewind(); + assertEquals(SoundInstance.State.INITIAL, boomInstance.value().getState()); + boomInstance.value().play(); + assertEquals(SoundInstance.State.PLAYING, boomInstance.value().getState()); + waitUntil(() -> boomInstance.value().getState() == SoundInstance.State.STOPPED); + + audioManager.destroySoundInstance(boomInstance.key()); + assertNull(audioManager.getSoundInstance(boomInstance.key())); + } + + @Test + void testStreamingAndEffectsAndStop() { + Pair musicInstance = audioManager.createStreamingSoundInstance(NOCK_EM, true); + + musicInstance.value().play(); + log.warn("Music must have started playing"); + + waitFor(2000); + musicInstance.value() + .volume(50) // 50% + .pitch(40); // 2 tones up + log.warn("The music must have become quieter and faster"); + + waitFor(2000); + musicInstance.value() + .volume(100) + .pitch(-40) + .pan(-100); + log.warn("The music must have become normal volume, slower, and panned fully to left"); + + waitFor(2000); + musicInstance.value().pan(100); + log.warn("The music must have become panned fully to right"); + + waitFor(2000); + musicInstance.value() + .volume(0) + .pitch(0) + .pan(0); + log.warn("The music must have stopped playing because of 0% volume"); + + waitFor(2000); + musicInstance.value().volume(100); + log.warn("The music must have continued playing normally"); + + waitFor(2000); + musicInstance.value().stop(); + assertEquals(SoundInstance.State.STOPPED, musicInstance.value().getState()); + log.warn("The music must have stopped playing again"); + waitFor(750); + + audioManager.destroySoundInstance(musicInstance.key()); + } + + + @BeforeAll + static void init() { + log.warn("------------ AUDIO TESTS ------------"); + log.warn("Please watch out for warn warn logs and make sure the tests pass"); + waitFor(750); + + context = new DefaultAppContext().register(SoundDecoder.class, VorbisSoundDecoder.INSTANCE); + AtomicBoolean initDone = new AtomicBoolean(); + audioThread = Thread.ofPlatform() // not virtual to avoid context switch, which may cause invalid engine state + .daemon() + .name("sparkle-audio") + .start(() -> { + log.info("Initializing the audio manager..."); + try (var _ = audioManager = new OpenALAudioManager(context)) { + context.register(AudioManager.class, audioManager); + log.info("Loading sounds..."); + assertDoesNotThrow(() -> audioManager.loadSounds(BEEP, BOOM, NOCK_EM), "Audio manager failed to load sounds"); + initDone.set(true); + log.info("Done. Entering main loop..."); + while (!Thread.interrupted()) { + audioManager.tick(); + waitFor(1); + } + log.info("Requested interrupt; cleaning up..."); + } catch (Throwable t) { + log.error("Exception in audio loop", t); + log.info("Cleaning up..."); + } // implicit "finally"; try-with-resources closes the audio manager + log.info("Stopping..."); + }); + waitUntil(initDone::get); + } + + @AfterAll + static void destroy() throws Exception { + audioThread.interrupt(); + audioThread.join(); + context.close(); + log.warn("------------- END AUDIO TESTS --------------"); + } + + /** + * Get a file (relative to the test resources directory) as a {@link Path}. + * @param path the relative location of the resource + */ + private static Path resource(String path) { + try { + return Path.of(Objects.requireNonNull(AudioManagerTest.class.getResource("/" + path)).toURI()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } catch (NullPointerException _) { + throw new RuntimeException("Resource not found: " + path); + } + } +} diff --git a/src/test/java/EventDispatcherTest.java b/src/test/java/EventDispatcherTest.java new file mode 100644 index 0000000..be20f10 --- /dev/null +++ b/src/test/java/EventDispatcherTest.java @@ -0,0 +1,121 @@ +import lombok.EqualsAndHashCode; +import lombok.Value; +import lombok.experimental.ExtensionMethod; +import lombok.extern.slf4j.Slf4j; +import nl.altindag.log.LogCaptor; +import org.junit.jupiter.api.Test; +import ru.fokinatorr.sparkle.event.AbstractCancellableEvent; +import ru.fokinatorr.sparkle.event.CancellableEvent; +import ru.fokinatorr.sparkle.event.Event; +import ru.fokinatorr.sparkle.event.MessageEvent; +import ru.fokinatorr.sparkle.event.annotation.EventListener; +import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher; +import ru.fokinatorr.sparkle.graphics.ARGB; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static ru.fokinatorr.sparkle.util.WaitUtils.waitFor; + +@Slf4j +@ExtensionMethod(ARGB.class) +public class EventDispatcherTest { + + @Test + void test() throws Throwable { + EventDispatcher eventDispatcher = EventDispatcher.newDefault(); + eventDispatcher.register(EventDispatcherTest.class); + String[] strings = new String[] {"Hello", "World", "!"}; + try (LogCaptor logCaptor = LogCaptor.forClass(EventDispatcherTest.class)) { + MessageEvent message1 = new MessageEvent("message1"); // no data + MessageEvent message2 = new MessageEvent("message2", "Hello World!"); // has data + MessageEvent message3 = new MessageEvent("message3", Arrays.toString(strings)); // string array data + ExplodeUniverseEvent customEvent = new ExplodeUniverseEvent(120); + eventDispatcher.fireEventAndWait(message1); + eventDispatcher.fireEventAndWait(message2); + eventDispatcher.fireEventAndWait(message3); + eventDispatcher.fireEventAndWait(customEvent); + // Handler priority order from highest to lowest: + // -128 handleMessage2(MessageEvent) + // 0 handleMessage(MessageEvent) + // 0 handleEnd(ExplodeUniverseEvent) + // 126 handleCancellableEvent(CancellableEvent) + // 127 handleAnyEvent(Event) + List expectedLogs = List.of( + // message1 + // #handleMessage: + "Message with ID message1 received", + "No data received", + // #handleAnyEvent: + "Event received: " + message1, + // message2 + // #handleMessage2: + "Received message2! This should be before \"Message with ID message2 received\"", + // #handleMessage: + "Message with ID message2 received", + "Received data: Hello World!", + // #handleAnyEvent: + "Event received: " + message2, + // message3 + // #handleMessage: + "Message with ID message3 received", + "Received data: " + Arrays.toString(strings), + // #handleAnyEvent: + "Event received: " + message3, + // customEvent + // #handleEnd: + "Universe exploding in 120 seconds", + "JK I cancelled it", + // #handleCancellableEvent: + "Cancellable event received: " + customEvent + "; cancelled = true", + // #handleAnyEvent: + "Event received: " + customEvent + ); + List actualLogs = logCaptor.getLogs(); + log.info("Expected logs: {}\nActual logs: {}", expectedLogs, actualLogs); + assertEquals(expectedLogs, actualLogs); + } + } + + @Value + @EqualsAndHashCode(callSuper = false) + private static class ExplodeUniverseEvent extends AbstractCancellableEvent { + long inSeconds; + } + + @EventListener + private static void handleEnd(ExplodeUniverseEvent event) { + log.info("Universe exploding in {} seconds", event.getInSeconds()); + waitFor(1000); + event.cancel(); + log.info("JK I cancelled it"); + } + + @EventListener + private static void handleMessage(MessageEvent e) { + log.info("Message with ID {} received", e.messageId()); + e.receivedData().ifPresentOrElse( + data -> log.info("Received data: {}", data), + () -> log.info("No data received") + ); + } + + @EventListener(priority = EventDispatcher.MAX_PRIORITY) + private static void handleMessage2(MessageEvent e) { + if (e.messageId().equals("message2")) { + log.info("Received message2! This should be before \"Message with ID message2 received\""); + } + } + + @EventListener(priority = EventDispatcher.MIN_PRIORITY) + private static Object handleAnyEvent(Event event) { + log.info("Event received: {}", event); + return "This value should be ignored"; + } + + @EventListener(priority = 126) + private static void handleCancellableEvent(CancellableEvent event) { + log.info("Cancellable event received: {}; cancelled = {}", event, event.isCancelled()); + } +} \ No newline at end of file diff --git a/src/test/java/GraphicsManagerTest.java b/src/test/java/GraphicsManagerTest.java new file mode 100644 index 0000000..f7ba0e4 --- /dev/null +++ b/src/test/java/GraphicsManagerTest.java @@ -0,0 +1,163 @@ +import it.unimi.dsi.fastutil.Pair; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import ru.fokinatorr.sparkle.assets.Assets; +import ru.fokinatorr.sparkle.context.AppContext; +import ru.fokinatorr.sparkle.context.DefaultAppContext; +import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap; +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.RenderCanvas; +import ru.fokinatorr.sparkle.graphics.render.RenderingContext; +import ru.fokinatorr.sparkle.graphics.render.renderer.Renderable2D; +import ru.fokinatorr.sparkle.graphics.render.renderer.RendererRegistry; +import ru.fokinatorr.sparkle.phys2d.Hitbox2D; +import ru.fokinatorr.sparkle.stage.Stage; +import ru.fokinatorr.sparkle.stage.StageCreator; + +import java.awt.*; +import java.awt.geom.Ellipse2D; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.*; +import static ru.fokinatorr.sparkle.util.WaitUtils.*; + +@Slf4j +public class GraphicsManagerTest { + + static AppContext context; + static OpenGLGraphicsManager graphicsManager; + static Thread graphicsThread; + + @Test + void testSimpleShape() { + AtomicReference simpleShape = new AtomicReference<>(); + AtomicReference> ctxPair = new AtomicReference<>(); + graphicsManager.runLater(() -> ctxPair.set(graphicsManager.createWindowContext("Simple Shape", new StageCreator() { + @Override + public Assets getStageAssets() { + return Assets.empty(); + } + + @Override + public void customize(Stage stage) { + simpleShape.set(new SimpleShape(stage)); + stage.registerRenderable("theShape", simpleShape.get()); + } + }))); + waitUntil(() -> ctxPair.get() != null); + Stage stage = ctxPair.get().left(); + RenderingContext ctx = ctxPair.get().right(); + + assertEquals(simpleShape.get(), stage.getRenderable("theShape")); + + waitUntil(ctx::shouldClose); + } + + @BeforeAll + static void init() { + log.info("------------ GRAPHICS TESTS ------------"); + log.info("Make sure a window appears for each test"); + waitFor(750); + + context = new DefaultAppContext() + .register(EventDispatcher.class, EventDispatcher.newDefault()) + .register(RendererRegistry.class, RendererRegistry.withDefaults()) + .register(FontProvider.class, FontProvider.defaultProvider()); + AtomicBoolean initDone = new AtomicBoolean(); + graphicsThread = Thread.ofPlatform() + .name("sparkle-graphics") + .start(() -> { + log.info("Initializing the graphics manager..."); + try (var _ = graphicsManager = new OpenGLGraphicsManager(context)) { + context.register(GraphicsManager.class, graphicsManager); + initDone.set(true); + log.info("Done. Entering main loop..."); + while (!Thread.interrupted()) { + graphicsManager.tick(); + waitFor(1); + } + log.info("Requested interrupt; cleaning up..."); + } catch (Throwable t) { + log.error("Exception in graphics loop", t); + log.info("Cleaning up..."); + } + log.info("Stopping..."); + }); + waitUntil(initDone::get); + } + + @AfterAll + static void destroy() throws Exception { + graphicsThread.interrupt(); + graphicsThread.join(); + context.close(); + log.warn("------------- END GRAPHICS TESTS --------------"); + } + + static class SimpleShape implements Renderable2D { + static final GraphicEffectMap EMPTY = new GraphicEffectMap(); + + final Shape shape; + + public SimpleShape(Stage stage) { + double s = 50; + shape = new Ellipse2D.Double((stage.getWidth() - s) / 2, (stage.getHeight() - s) / 2, s, s); + } + + @Override + public double getX() { + return 0; + } + + @Override + public double getY() { + return 0; + } + + @Override + public double getDirection() { + return 90; + } + + @Override + public double getStretchX() { + return 100; + } + + @Override + public double getStretchY() { + return 100; + } + + @Override + public Hitbox2D getHitbox() { + return Hitbox2D.shape(shape); + } + + @Override + public void render(RenderCanvas canvas) { + canvas.save(); + canvas.setStrokeARGB(0xFF_FF_00_00); + canvas.setFillARGB(0xFF_FF_00_00); + canvas.setLineWidth(1); + canvas.fillShape(shape); + canvas.restore(); + } + + @Override + public boolean isVisible() { + return true; + } + + @Override + public GraphicEffectMap getGraphicEffects() { + return EMPTY; + } + } +} diff --git a/src/test/java/TestUtils.java b/src/test/java/TestUtils.java new file mode 100644 index 0000000..e162393 --- /dev/null +++ b/src/test/java/TestUtils.java @@ -0,0 +1,4 @@ +package PACKAGE_NAME; + +public class TestUtils { +} diff --git a/src/test/java/WaitUtilsTest.java b/src/test/java/WaitUtilsTest.java new file mode 100644 index 0000000..bbf94c1 --- /dev/null +++ b/src/test/java/WaitUtilsTest.java @@ -0,0 +1,181 @@ +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.*; +import static ru.fokinatorr.sparkle.util.WaitUtils.*; // star import because static imports are processed before Lombok kicks in + +@Slf4j +@Disabled("Temporary") +public class WaitUtilsTest { + + private static final long EPSILON_NANOS = + System.getProperty("os.name").toLowerCase().contains("win") + ? 10_000_000L // 10ms for Windows + : 5_000_000L; // 5ms for *nix since they're stricter + private static final long EPSILON_NANOS_IMMEDIATE = 100_000L; // 100μs + private static final double MIN_SUCCESS_RATE = 0.7; + private static final long[] FIXED_TRIALS = {10, 20, 50, 100, 250, 500, 1000}; + private static final long[] FIXED_FLAG_TRIALS = {20, 10, 100, 50, 120, 1000, 2000}; // for timed conditional sleep + + private boolean trialNoCond(long millis) { + log.info("======= SLEEP TRIAL ======="); + log.info("Testing delay: {} ms", millis); + long startTime = System.nanoTime(); + waitFor(millis); + long endTime = System.nanoTime(); + long diff = Math.abs(endTime - startTime - millis * 1_000_000L); + log.info("Expected: {}, actual: {}, diff: {}", millis * 1_000_000L, endTime - startTime, diff); + log.info("======= END SLEEP TRIAL ======="); + return diff <= EPSILON_NANOS; + } + + private boolean trialCond(long millis) { + log.info("======= CONDITIONAL SLEEP TRIAL ======="); + log.info("Switching the flag after: {} ms", millis); + AtomicBoolean flag = new AtomicBoolean(false); + Thread switcher = Thread.ofVirtual() + .name("switcher-thread") + .unstarted(() -> { + waitFor(millis); // simulate work + flag.set(true); + }); + long startTime = System.nanoTime(); + switcher.start(); + waitUntil(flag::get); + long endTime = System.nanoTime(); + long diff = Math.abs(endTime - startTime - millis * 1_000_000L); + log.info("Expected: {}, actual: {}, diff: {}", millis * 1_000_000L, endTime - startTime, diff); + log.info("======= END CONDITIONAL SLEEP TRIAL ======="); + return diff <= EPSILON_NANOS; + } + + private boolean trialCondTimed(long flagTimeout, long waitTimeout) { + log.info("======= CONDITIONAL TIMED SLEEP TRIAL ======="); + log.info("Switching the flag after: {} ms; waiting for: {} ms", flagTimeout, waitTimeout); + long minTimeout = Math.min(flagTimeout, waitTimeout); + AtomicBoolean flag = new AtomicBoolean(false); + Thread switcher = Thread.ofVirtual() + .name("switcher-thread") + .unstarted(() -> { + waitFor(flagTimeout); // simulate work + flag.set(true); + }); + long startTime = System.nanoTime(); + switcher.start(); + assertEquals(flagTimeout > waitTimeout, waitForOrUntil(flag::get, waitTimeout), "waitForOrUntil() returned incorrect result"); + long endTime = System.nanoTime(); + long diff = Math.abs(endTime - startTime - minTimeout * 1_000_000L); + log.info("Expected: {}, actual: {}, diff: {}", minTimeout * 1_000_000L, endTime - startTime, diff); + log.info("======= END CONDITIONAL TIMED SLEEP TRIAL ======="); + return diff <= EPSILON_NANOS; + } + + @Test + void fixedTrialsNoCondition() { + log.info("============= Unconditional timed sleep, fixed delays ============="); + int successCount = 0; + for (long t : FIXED_TRIALS) { + if (trialNoCond(t)) successCount++; + } + double successRate = (double) successCount / FIXED_TRIALS.length; + log.info("Fixed trials success rate: {}% ({}/{})", (int) (successRate * 100), successCount, FIXED_TRIALS.length); + assertTrue(successRate >= MIN_SUCCESS_RATE, "Expected minimal success rate: " + MIN_SUCCESS_RATE + ", actual: " + successRate); + } + + @Test + void randomTrialsNoCondition() { + log.info("============= Unconditional timed sleep, randomized delays ============="); + int trialCount = 10; + int successCount = 0; + for (int i = 0; i < trialCount; i++) { + long t = (long) (Math.random() * 1000); + if (trialNoCond(t)) successCount++; + } + double successRate = (double) successCount / trialCount; + log.info("Random trials success rate: {}% ({}/{})", (int) (successRate * 100), successCount, trialCount); + assertTrue(successRate >= MIN_SUCCESS_RATE, "Expected minimal success rate: " + MIN_SUCCESS_RATE + ", actual: " + successRate); + } + + @Test + void fixedTrialsCondition() { + log.info("============= Conditional indefinite sleep, fixed delays ============="); + int successCount = 0; + for (long t : FIXED_TRIALS) { + if (trialCond(t)) successCount++; + } + double successRate = (double) successCount / FIXED_TRIALS.length; + log.info("Fixed conditional trials success rate: {}% ({}/{})", (int) (successRate * 100), successCount, FIXED_TRIALS.length); + assertTrue(successRate >= MIN_SUCCESS_RATE, "Expected minimal success rate: " + MIN_SUCCESS_RATE + ", actual: " + successRate); + } + + @Test + void randomTrialsCondition() { + log.info("============= Conditional indefinite sleep, randomized delays ============="); + int trialCount = 10; + int successCount = 0; + for (int i = 0; i < trialCount; i++) { + long t = (long) (Math.random() * 1000); + if (trialCond(t)) successCount++; + } + double successRate = (double) successCount / trialCount; + log.info("Random conditional trials success rate: {}% ({}/{})", (int) (successRate * 100), successCount, trialCount); + assertTrue(successRate >= MIN_SUCCESS_RATE, "Expected minimal success rate: " + MIN_SUCCESS_RATE + ", actual: " + successRate); + } + + @Test + void conditionAlwaysTrue() { + log.info("============= Conditional indefinite sleep, condition is always true ============="); + waitUntil(() -> true); // warmup + + long startTime = System.nanoTime(); + waitUntil(() -> true); + long endTime = System.nanoTime(); + log.info("Wait time: {}ns", endTime - startTime); + assertTrue(endTime - startTime <= EPSILON_NANOS_IMMEDIATE, "waitUntil(() -> true) didn't return immediately"); + } + + @Test + void fixedTrialsConditionTimed() { + log.info("============= Conditional timed sleep, fixed delays ============="); + int successCount = 0; + for (int i = 0; i < FIXED_TRIALS.length; i++) { + long tWait = FIXED_TRIALS[i]; + long tFlag = FIXED_FLAG_TRIALS[i]; + if (trialCondTimed(tFlag, tWait)) successCount++; + } + double successRate = (double) successCount / FIXED_TRIALS.length; + log.info("Fixed conditional timed trials success rate: {}% ({}/{})", (int) (successRate * 100), successCount, FIXED_TRIALS.length); + assertTrue(successRate >= MIN_SUCCESS_RATE, "Expected minimal success rate: " + MIN_SUCCESS_RATE + ", actual: " + successRate); + } + + @Test + void randomTrialsConditionTimed() { + log.info("============= Conditional timed sleep, randomized delays ============="); + int trialCount = 10; + int successCount = 0; + for (int i = 0; i < trialCount; i++) { + long tWait = (long) (Math.random() * 2000); + long tFlag = (long) (Math.random() * 1000); + if (trialCondTimed(tWait, tFlag)) successCount++; + } + double successRate = (double) successCount / trialCount; + log.info("Random conditional timed trials success rate: {}% ({}/{})", (int) (successRate * 100), successCount, trialCount); + assertTrue(successRate >= MIN_SUCCESS_RATE, "Expected minimal success rate: " + MIN_SUCCESS_RATE + ", actual: " + successRate); + } + + @Test + void conditionTimedAlwaysTrue() { + log.info("============= Conditional timed sleep, condition is always true ============="); + waitForOrUntil(() -> true, 0); // warmup + + long startTime = System.nanoTime(); + boolean result = waitForOrUntil(() -> true, 10000); + long endTime = System.nanoTime(); + log.info("Wait time: {}ns", endTime - startTime); + assertFalse(result, "Condition was satisfied immediately but waitForOrUntil returned true (should be false)"); + assertTrue(endTime - startTime <= EPSILON_NANOS_IMMEDIATE, "waitUntil(() -> true) didn't return immediately"); + } +} diff --git a/src/test/resources/assets/fonts b/src/test/resources/assets/fonts new file mode 120000 index 0000000..a27596d --- /dev/null +++ b/src/test/resources/assets/fonts @@ -0,0 +1 @@ +/home/michael/IdeaProjects/project-sparkle/sparkle-core/src/main/resources/assets/fonts \ No newline at end of file diff --git a/src/test/resources/assets/textures b/src/test/resources/assets/textures new file mode 120000 index 0000000..8de6ebd --- /dev/null +++ b/src/test/resources/assets/textures @@ -0,0 +1 @@ +/home/michael/IdeaProjects/project-sparkle/sparkle-core/src/main/resources/assets/textures \ No newline at end of file diff --git a/src/test/resources/beep.ogg b/src/test/resources/beep.ogg new file mode 100644 index 0000000..cf1868c Binary files /dev/null and b/src/test/resources/beep.ogg differ diff --git a/src/test/resources/boom.ogg b/src/test/resources/boom.ogg new file mode 100644 index 0000000..caa1d3e Binary files /dev/null and b/src/test/resources/boom.ogg differ diff --git a/src/test/resources/nock_em.ogg b/src/test/resources/nock_em.ogg new file mode 100644 index 0000000..f081dcf Binary files /dev/null and b/src/test/resources/nock_em.ogg differ diff --git a/src/test/resources/shaders b/src/test/resources/shaders new file mode 120000 index 0000000..94437f1 --- /dev/null +++ b/src/test/resources/shaders @@ -0,0 +1 @@ +/home/michael/IdeaProjects/project-sparkle/sparkle-core/src/main/resources/shaders \ No newline at end of file diff --git a/todo-list.md b/todo-list.md new file mode 100644 index 0000000..012954a --- /dev/null +++ b/todo-list.md @@ -0,0 +1,40 @@ +TODO List +=== +## Core goals (Almost there!) + +1. Create `Image` implementations (~~`RasterImage`~~, ~~`SVGImage`~~, `AnimatedImage`) +2. ~~Create a `ru.fokinatorr.sparkle.graphics.GraphicsManager` interface and an implementation based on a native +graphics engine. Make it a default headful bean. +Also create an interface `ru.fokinatorr.sparkle.graphics.render.RenderingContext` based on the graphics manager interface.~~ **DONE**: +implemented with OpenGL: `OpenGLGraphicsManager`, `OpenGLContext`. To do: `SoftwareContext` +3. ~~Implement `RenderingContext` and `RenderCanvas`~~ **DONE**: `OpenGLContext` and `GLRenderCanvas`. To do: `SoftwareContext` and `OffscreenRenderCanvas`. +4. Improve `RenderCanvas` to unify 2D and 3D +5. ~~Add support for `Renderable` and `Renderer` interfaces in `Stage`~~ **DONE**: Created an arbitrary renderable object map +6. Create a bootstrap class `ru.fokinatorr.sparkle.SparkleApp` +7. ~~Add support for `GraphicEffectMap` in `RenderCanvas`~~ **DONE** +8. ~~Maybe rename `GraphicsContext` to `CanvasAccessor` or something canvas-related? To avoid confusion with bgfx/glfw context, if there is one~~ +**DONE: Renamed to `RenderCanvas`** +9. ~~Implement `Renderable2D`'s methods in `Sprite`~~ **DONE** +10. ~~Create a `RendererRegistry` bean that maps type -> `Renderer`s for that type or supertype~~ **DONE** +11. ~~Create class `Renderer.ForRenderable2D` that applies transformations according to `Renderable2D`'s properties +(`Renderable`s don't do that, they just draw)~~ **DONE** +12. ~~Make some kind of `Stage` registry? A `Stage` instance will probably be tied to a `GraphicsManager` instance~~ **DONE: `Stage`s are attached to `RenderingContext`s** +13. Find all TODO comments and apply them +14. ~~Add LICENSE to resources (MIT)~~ **DONE: [created file](/src/main/resources/LICENSE)** +15. Update version to `0.1-beta` in `pom.xml` +16. Create a Git repository and commit everything +--- +## Future goals + +1. Create a demo app `sparkle-demo-app` +2. Create extensions `sparkle-ext-3d`, `sparkle-ext-ui`, `sparkle-ext-box2d`, `sparkle-ext-cloud-variables`, +`sparkle-ext-midi`, `sparkle-ext-tts`, `sparkle-ext-asset-library`,... +3. Maybe create a converter app `sparkle-scratch2sparkle`? +4. Create website (potential base URLs: https://fokinatorr.net/sparkle, https://sfns.fokinatorr.net.ru/, any combo of those) +5. Attract Scratchers that know basics of Java and hope they'll find Sparkle usable +--- +## Notes + +- SFNS - **Sparkle Framework is Not Scratch** (API similar to Scratch, but it's a different thing) +- If you like the GNU trend, you can call it **SFNS Framework is Not Scratch** :) +- Code name: Project Sparkle or just Sparkle \ No newline at end of file