feat(engine): import the seven-module engine and the demo app
authorSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Thu, 26 Nov 2026 20:43:53 +0000 (22:43 +0200)
committerSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Thu, 26 Nov 2026 20:43:53 +0000 (22:43 +0200)
The engine written in the aukio-v3 repository moves here, where the
project's name and history live: Modules/{world,renderer,swing,
scheduler,gi,hid,navigation} as JPMS modules plus Applications/demos
with MinimalExample. Packages and module names carry no version segment
any more (eu.svjatoslav.aukio.world, .render, .sched, .gi, .hid,
.navigation, .swing), so the jars are named aukio-<module>.

The build is Gradle 9.6.0 through the committed wrapper, compiling and
testing on a Java 21 toolchain whatever JDK launched the daemon, with
toolchain auto-download disabled so the build stays offline; the gate is
./gradlew --offline build -Ptla.

The v3 module map becomes Documentation/index.org and the previous
workspace vision page is kept beside it as Documentation/vision.org.
pom.xml and verify.sh go: this repository no longer builds with Maven,
and the old gate pointed at the removed workspace-v2 module and its
scenario tables. .gitignore keeps the old rules and gains the Gradle,
.openidea and TLC scratch ones.

The source arrived from aukio-v3 by copy, so the file history lives in
that repository; this commit is the entry point in aukio.

82 files changed:
.gitignore
AGENTS.org [new file with mode: 0644]
Applications/demos/build.gradle [new file with mode: 0644]
Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/ApplicationListPanel.java [new file with mode: 0644]
Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/Main.java [new file with mode: 0644]
Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/minimal/MinimalExample.java [new file with mode: 0644]
Documentation/index.org
Documentation/vision.org [new file with mode: 0644]
Modules/gi/Documentation/index.org [new file with mode: 0644]
Modules/gi/build.gradle [new file with mode: 0644]
Modules/gi/src/main/java/eu/svjatoslav/aukio/gi/package-info.java [new file with mode: 0644]
Modules/gi/src/main/java/module-info.java [new file with mode: 0644]
Modules/gi/src/test/java/eu/svjatoslav/aukio/gi/ModuleShapeTest.java [new file with mode: 0644]
Modules/hid/Documentation/index.org [new file with mode: 0644]
Modules/hid/build.gradle [new file with mode: 0644]
Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/Motion.java [new file with mode: 0644]
Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/SpaceNavigator.java [new file with mode: 0644]
Modules/hid/src/main/java/module-info.java [new file with mode: 0644]
Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/ModuleShapeTest.java [new file with mode: 0644]
Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/SpaceNavigatorTest.java [new file with mode: 0644]
Modules/navigation/Documentation/index.org [new file with mode: 0644]
Modules/navigation/build.gradle [new file with mode: 0644]
Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/CameraDriver.java [new file with mode: 0644]
Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/FlyCamera.java [new file with mode: 0644]
Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/InputRecorder.java [new file with mode: 0644]
Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/ViewInput.java [new file with mode: 0644]
Modules/navigation/src/main/java/module-info.java [new file with mode: 0644]
Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/FlyCameraTest.java [new file with mode: 0644]
Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/InputRecorderTest.java [new file with mode: 0644]
Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/ModuleShapeTest.java [new file with mode: 0644]
Modules/renderer/Documentation/index.org [new file with mode: 0644]
Modules/renderer/build.gradle [new file with mode: 0644]
Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Cull.java [new file with mode: 0644]
Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/FrameBuffer.java [new file with mode: 0644]
Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Projection.java [new file with mode: 0644]
Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Raster.java [new file with mode: 0644]
Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Renderer.java [new file with mode: 0644]
Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/package-info.java [new file with mode: 0644]
Modules/renderer/src/main/java/module-info.java [new file with mode: 0644]
Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/ModuleShapeTest.java [new file with mode: 0644]
Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/RendererTest.java [new file with mode: 0644]
Modules/scheduler/Documentation/index.org [new file with mode: 0644]
Modules/scheduler/Model/FrameGate.tla [new file with mode: 0644]
Modules/scheduler/Model/FrameGate_buggy_bgfirst.cfg [new file with mode: 0644]
Modules/scheduler/Model/FrameGate_buggy_countbg.cfg [new file with mode: 0644]
Modules/scheduler/Model/FrameGate_gate.cfg [new file with mode: 0644]
Modules/scheduler/Model/check-models.sh [new file with mode: 0755]
Modules/scheduler/build.gradle [new file with mode: 0644]
Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/Scheduler.java [new file with mode: 0644]
Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/package-info.java [new file with mode: 0644]
Modules/scheduler/src/main/java/module-info.java [new file with mode: 0644]
Modules/scheduler/src/test/java/eu/svjatoslav/aukio/sched/SchedulerTest.java [new file with mode: 0644]
Modules/swing/Documentation/index.org [new file with mode: 0644]
Modules/swing/build.gradle [new file with mode: 0644]
Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/AukioView.java [new file with mode: 0644]
Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/package-info.java [new file with mode: 0644]
Modules/swing/src/main/java/module-info.java [new file with mode: 0644]
Modules/swing/src/test/java/eu/svjatoslav/aukio/swing/ModuleShapeTest.java [new file with mode: 0644]
Modules/world/Documentation/index.org [new file with mode: 0644]
Modules/world/build.gradle [new file with mode: 0644]
Modules/world/src/main/java/eu/svjatoslav/aukio/world/Boxes.java [new file with mode: 0644]
Modules/world/src/main/java/eu/svjatoslav/aukio/world/Camera.java [new file with mode: 0644]
Modules/world/src/main/java/eu/svjatoslav/aukio/world/Mesh.java [new file with mode: 0644]
Modules/world/src/main/java/eu/svjatoslav/aukio/world/Node.java [new file with mode: 0644]
Modules/world/src/main/java/eu/svjatoslav/aukio/world/Scene.java [new file with mode: 0644]
Modules/world/src/main/java/eu/svjatoslav/aukio/world/Transform.java [new file with mode: 0644]
Modules/world/src/main/java/eu/svjatoslav/aukio/world/Vec3.java [new file with mode: 0644]
Modules/world/src/main/java/eu/svjatoslav/aukio/world/package-info.java [new file with mode: 0644]
Modules/world/src/main/java/module-info.java [new file with mode: 0644]
Modules/world/src/test/java/eu/svjatoslav/aukio/world/BoxesTest.java [new file with mode: 0644]
Modules/world/src/test/java/eu/svjatoslav/aukio/world/ModuleShapeTest.java [new file with mode: 0644]
Modules/world/src/test/java/eu/svjatoslav/aukio/world/TransformTest.java [new file with mode: 0644]
README.org [new file with mode: 0644]
build.gradle [new file with mode: 0644]
gradle.properties [new file with mode: 0644]
gradle/wrapper/gradle-wrapper.jar [new file with mode: 0644]
gradle/wrapper/gradle-wrapper.properties [new file with mode: 0644]
gradlew [new file with mode: 0755]
gradlew.bat [new file with mode: 0644]
pom.xml [deleted file]
settings.gradle [new file with mode: 0644]
verify.sh [deleted file]

index 31e209b..0aae896 100644 (file)
@@ -12,3 +12,14 @@ target/
 *.html
 # jcstress result dumps (parallel agent)
 jcstress-results-*.bin.gz
+
+# Gradle
+.gradle/
+build/
+*.class
+.vscode/
+.openidea/
+
+# TLC scratch
+Modules/scheduler/Model/states/
+Modules/scheduler/Model/*_TTrace_*
diff --git a/AGENTS.org b/AGENTS.org
new file mode 100644 (file)
index 0000000..a3fbf4b
--- /dev/null
@@ -0,0 +1,103 @@
+#+TITLE: AGENTS - aukio
+
+* What this is
+
+Read =Documentation/index.org= first; it is the map, this file is the
+recipe.
+
+* Hard rules
+
+- The user owns judgment. Propose, wait for an explicit go, land ONE readable
+  change, stop. Never batch several pieces into one turn.
+- NEVER git commit and NEVER push. The user commits himself.
+- A module's tests must run with the other modules absent from the
+  classpath.  That is the proof of isolation, not a diagram.
+- One public package per module; everything else is package-private or under
+  =.internal.=.
+- Every module declares =module-info.java= in =src/main/java/=, named after its
+  package, exporting that one package and requiring only what its build file
+  depends on. A =requires= on another engine module that is not a dependency is
+  a compile error, which is the whole point.
+- Java 21 =--release=; the build is Gradle 9.6.0 through =./gradlew=, run
+  offline (every dependency is already in =~/.m2=, reached through
+  =mavenLocal()=). Compiling and testing happen on a Java 21 toolchain even
+  when a newer JDK launched Gradle, and a missing toolchain fails the build
+  instead of being downloaded.
+- Every heading under =Documentation/= carries a =CUSTOM_ID=;
+  sub-pages open with a back-link to their anchor in the map.
+
+* Working rules for the agent
+
+- Report the command and what it printed. "It works" is the user's
+  word, not yours; never claim a behaviour without the check that
+  demonstrates it.
+- A behaviour is accepted only when a check fails before and passes
+  after, and that check stays in the build.
+- Anything with interleaving or ordering goes spec-first: a model in
+  the module's =Model/= directory, a gate config wired into
+  =./gradlew -Ptla check=, and a buggy config that must violate the
+  invariant the gate asserts.
+- A comment states what the code relies on. No benchmark folklore, no
+  dates, no "we tried this once" — provenance belongs in the docs, not
+  in a constant's Javadoc.
+- Documentation describes the current state. Do not record the edit
+  history in it.
+
+* Layout
+
+- =Modules/scheduler/= :: CPU budget, work queues, frame gate. =Model/= holds
+  its TLA+ model and =check-models.sh=.
+- =Modules/world/= :: the scene as data - geometry, object tree, mesh,
+  primitives, camera pose. Its descriptor requires no other engine module, and
+  =ModuleShapeTest= fails the build if that changes or if a file passes 800
+  lines.
+- =Modules/gi/= :: direct and indirect light, lightmaps, and the bake order. It
+  requires the world and the scheduler and may require nothing else: a
+  =requires= on the renderer, or on =java.desktop=, is a build failure.
+- =Modules/renderer/= :: projection, culling and rasterisation. It requires the
+  world and nothing else; =ModuleShapeTest= holds that requirement list, the one
+  package, and the 800-line limit.
+- =Modules/navigation/= :: one frame of input as a record, and the camera policy
+  that answers it (=FlyCamera=). Requires the world and nothing else - the input
+  record is data, so a policy is testable without a window.
+- =Modules/swing/= :: the embeddable view component and its render loop. The
+  only engine module that requires =java.desktop=; it depends on the renderer
+  and the renderer never depends on it.
+- =Modules/hid/= :: 3D input devices read off =/dev/hidraw= - the toolkit cannot
+  deliver them, so they are not the swing adapter's business. Requires nothing;
+  its reader thread is blocked I/O and deliberately outside the scheduler's CPU
+  budget.
+- =Documentation/= :: the map. Each module keeps its own page in its own
+  =Documentation/= directory, next to the code it describes.
+- =README.org= :: layout and build, one screen.
+
+* Build and checks
+
+#+begin_src sh
+export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
+./gradlew --offline build                              # compile and unit tests
+./gradlew --offline -Ptla :scheduler:check             # TLA+ gate (green configs only)
+Modules/scheduler/Model/check-models.sh                 # gate must pass, every probe must fail
+#+end_src
+
+The buggy model configs are excluded from the Gradle gate on
+purpose: they fail by design, and a probe that passes proves the
+invariant is vacuous.
+
+* Known traps
+
+- Never trust an exit code that travelled through a pipe. Gradle prints
+  =BUILD SUCCESSFUL= only when every task passed, and the counts live in
+  each module's =build/test-results/test/*.xml=; read one of the two
+  before reporting a build or a test run as green.
+- TLC writes =states/= and =*_TTrace_*= into the invocation directory. Run it from
+  the module's =Model/= directory (both are gitignored) or the repo root gains
+  scratch.
+- The thread budget is a policy default (75% of logical cores), not an
+  enforcement: nothing yet bounds the process with it, so a module
+  that sizes its own pool is a defect to report rather than a
+  convenience.
+- A bare =Xvfb= has no window manager, so no window is ever activated and
+  keyboard events never reach the application, however the window is focused.
+  Run a WM (=xfwm4=) on the display, or drive the component's listeners
+  directly in a probe, before concluding that input handling is broken.
diff --git a/Applications/demos/build.gradle b/Applications/demos/build.gradle
new file mode 100644 (file)
index 0000000..5723b18
--- /dev/null
@@ -0,0 +1,10 @@
+// The demo applications. They embed the engine's view component in ordinary Swing
+// windows, so they depend on the adapter and on nothing else from the engine.
+
+dependencies {
+    implementation project(':swing')
+    implementation project(':hid')
+    // The demo picks the engine's camera policy; an application that wants its
+    // own implements CameraDriver instead and does not need this.
+    implementation project(':navigation')
+}
diff --git a/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/ApplicationListPanel.java b/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/ApplicationListPanel.java
new file mode 100644 (file)
index 0000000..5e292df
--- /dev/null
@@ -0,0 +1,64 @@
+package eu.svjatoslav.aukio.demos.launcher;
+
+import eu.svjatoslav.aukio.demos.minimal.MinimalExample;
+
+import javax.swing.JButton;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.border.EmptyBorder;
+import java.awt.Dimension;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.Insets;
+
+/**
+ * The list of demos this application can open.
+ *
+ * <p>One entry per demo, added in reading order. A demo is an independent
+ * program with its own {@code main}, so an entry does nothing more than start
+ * that program; the launcher never learns what a demo draws.</p>
+ */
+final class ApplicationListPanel extends JPanel {
+
+    private static final long serialVersionUID = 1L;
+
+    ApplicationListPanel() {
+        super(new GridBagLayout());
+        setBorder(new EmptyBorder(32, 48, 32, 48));
+        setPreferredSize(new Dimension(480, 320));
+        add(entry("Minimal example", MinimalExample::main), row(0));
+    }
+
+    private static JButton entry(final String name, final DemoEntry demo) {
+        final JButton button = new JButton(name);
+        button.addActionListener(event -> launch(name, demo));
+        return button;
+    }
+
+    /** A demo that cannot start is reported here rather than swallowed by the event thread. */
+    private static void launch(final String name, final DemoEntry demo) {
+        try {
+            demo.run(new String[0]);
+        } catch (final Exception failure) {
+            failure.printStackTrace();
+            JOptionPane.showMessageDialog(null, name + " could not start: " + failure,
+                    Main.WINDOW_TITLE, JOptionPane.ERROR_MESSAGE);
+        }
+    }
+
+    private static GridBagConstraints row(final int row) {
+        final GridBagConstraints constraints = new GridBagConstraints();
+        constraints.gridx = 0;
+        constraints.gridy = row;
+        constraints.weightx = 1;
+        constraints.fill = GridBagConstraints.HORIZONTAL;
+        constraints.insets = new Insets(4, 4, 4, 4);
+        return constraints;
+    }
+
+    /** A demo's entry point, as the launcher sees it. */
+    @FunctionalInterface
+    private interface DemoEntry {
+        void run(String[] args) throws Exception;
+    }
+}
diff --git a/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/Main.java b/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/Main.java
new file mode 100644 (file)
index 0000000..0ba479b
--- /dev/null
@@ -0,0 +1,37 @@
+package eu.svjatoslav.aukio.demos.launcher;
+
+import javax.swing.JFrame;
+import javax.swing.SwingUtilities;
+import java.awt.BorderLayout;
+
+import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
+
+/**
+ * Entry point for the Aukio V3 demos launcher.
+ *
+ * <p>The window lists the demos that can be opened. There are none yet, so it
+ * says so; adding a demo is a change inside {@link ApplicationListPanel}, not
+ * here.
+ */
+public final class Main {
+
+    static final String WINDOW_TITLE = "Aukio V3 demos";
+
+    private Main() {
+    }
+
+    public static void main(final String[] args) {
+        SwingUtilities.invokeLater(Main::buildAndShowGuiWindow);
+    }
+
+    private static void buildAndShowGuiWindow() {
+        final JFrame frame = new JFrame(WINDOW_TITLE);
+        frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+        frame.getContentPane().setLayout(new BorderLayout());
+        frame.getContentPane().add(new ApplicationListPanel(), BorderLayout.CENTER);
+        frame.pack();
+        frame.setMinimumSize(frame.getSize());
+        frame.setLocationRelativeTo(null);
+        frame.setVisible(true);
+    }
+}
diff --git a/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/minimal/MinimalExample.java b/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/minimal/MinimalExample.java
new file mode 100644 (file)
index 0000000..c4dcb06
--- /dev/null
@@ -0,0 +1,113 @@
+package eu.svjatoslav.aukio.demos.minimal;
+
+import eu.svjatoslav.aukio.hid.SpaceNavigator;
+import eu.svjatoslav.aukio.navigation.FlyCamera;
+import eu.svjatoslav.aukio.render.FrameBuffer;
+import eu.svjatoslav.aukio.render.Renderer;
+import eu.svjatoslav.aukio.swing.AukioView;
+import eu.svjatoslav.aukio.world.Boxes;
+import eu.svjatoslav.aukio.world.Camera;
+import eu.svjatoslav.aukio.world.Node;
+import eu.svjatoslav.aukio.world.Scene;
+import eu.svjatoslav.aukio.world.Vec3;
+
+import javax.imageio.ImageIO;
+import javax.swing.JFrame;
+import javax.swing.SwingUtilities;
+import java.awt.BorderLayout;
+import java.awt.image.BufferedImage;
+import java.io.File;
+
+import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
+
+/**
+ * One red box, a camera pulled back, and a view you can fly around it - the
+ * scene every Aukio engine ships as its first demo.
+ *
+ * <p>The scene is carried over unchanged from the first engine, so a render here
+ * can be put side by side with that engine's golden image: a 100-unit box
+ * centred on the origin, and a level camera a hundred units above it and three
+ * hundred back, which is why the box sits below the middle of the picture and
+ * its top face is just visible.</p>
+ *
+ * <p>The window mode wires three things a demo needs and the engine must not
+ * decide: a camera policy, the input the view records, and the 3D mouse. Moving
+ * the pointer with a button held looks around, the keyboard flies, and a
+ * SpaceNavigator or SpaceMouse pushes the camera exactly as far as the cap is
+ * pushed. If no 3D mouse is attached the other two still work and the demo says
+ * nothing about it.</p>
+ *
+ * <p>Run with no arguments for the window; run with {@code shot} for one
+ * headless frame written to {@code target/minimal-example.png}, which is what a
+ * pixel comparison against another engine needs.</p>
+ */
+public final class MinimalExample {
+
+    static final int SHOT_WIDTH = 1920;
+    static final int SHOT_HEIGHT = 1080;
+    static final int BACKGROUND = 0xFF000000;
+    static final int RED = 0xFFFF0000;
+
+    private static final double HALF_EDGE = 50;
+    private static final double CAMERA_HEIGHT = 100;
+    private static final double CAMERA_DISTANCE = 300;
+
+    private MinimalExample() {
+    }
+
+    /** The demo scene: one box, centred, no lights and no animation. */
+    public static Scene buildScene() {
+        final Vec3 corner = new Vec3(-HALF_EDGE, -HALF_EDGE, -HALF_EDGE);
+        final Vec3 opposite = new Vec3(HALF_EDGE, HALF_EDGE, HALF_EDGE);
+        return new Scene(Node.mesh(Boxes.box(corner, opposite, RED)));
+    }
+
+    /** Level camera, no yaw and no pitch, above the box and back along -Z. */
+    public static Camera buildCamera() {
+        return Camera.of(new Vec3(0, CAMERA_HEIGHT, -CAMERA_DISTANCE), 0, 0);
+    }
+
+    public static void main(final String[] args) throws Exception {
+        if (args.length > 0 && "shot".equals(args[0])) {
+            writeShot();
+            return;
+        }
+        openWindow();
+    }
+
+    private static void writeShot() throws Exception {
+        final FrameBuffer frame = new FrameBuffer(SHOT_WIDTH, SHOT_HEIGHT);
+        frame.clear(BACKGROUND);
+        Renderer.render(buildScene(), buildCamera(), frame);
+        final BufferedImage image =
+                new BufferedImage(SHOT_WIDTH, SHOT_HEIGHT, BufferedImage.TYPE_INT_RGB);
+        image.setRGB(0, 0, SHOT_WIDTH, SHOT_HEIGHT, frame.pixels(), 0, SHOT_WIDTH);
+        final File out = shotFile();
+        out.getParentFile().mkdirs();
+        ImageIO.write(image, "png", out);
+        System.out.println("wrote " + out.getAbsolutePath());
+    }
+
+    static File shotFile() {
+        return new File("target/minimal-example.png");
+    }
+
+    private static void openWindow() {
+        SwingUtilities.invokeLater(() -> {
+            final FlyCamera fly = new FlyCamera(buildCamera());
+            final JFrame window = new JFrame("Minimal example (Aukio V3) - WASD and drag, or 3D mouse");
+            window.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+            window.getContentPane().setLayout(new BorderLayout());
+            final AukioView view = new AukioView(buildScene(), fly.camera());
+            view.setDriver(fly);
+            window.getContentPane().add(view, BorderLayout.CENTER);
+            window.setSize(960, 600);
+            window.setLocationRelativeTo(null);
+            window.setVisible(true);
+            view.requestFocusInWindow();
+            view.start();
+            new SpaceNavigator(motion -> view.setDeviceMotion(motion.x(), motion.y(), motion.z(),
+                    motion.yaw(), motion.pitch(), motion.roll())).start();
+        });
+    }
+}
index 89b0a3c..bc79af1 100644 (file)
 #+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme
-#+TITLE: Aukio — System for Data Storage, Computation, Exploration and Interaction
+#+TITLE: Aukio V3 - documentation
 #+LANGUAGE: en
-#+LATEX_HEADER: \usepackage[margin=1.0in]{geometry}
-#+LATEX_HEADER: \usepackage{parskip}
-#+LATEX_HEADER: \usepackage[none]{hyphenat}
-
-#+OPTIONS: H:20 num:20
-#+OPTIONS: author:nil
-
-* Vision
-  :PROPERTIES:
-  :CUSTOM_ID: vision
-  :ID:       1f4e1c17-d25f-4d92-aa9b-5785f1d86f4f
-  :END:
-
-: A tool to amplify human ability
-
-The goal is a /bicycle for the mind/ — a powerful, extensible, hackable,
-general-purpose computing environment for working with knowledge.
-
-The system is built around the following priorities:
-
-+ *Knowledge-first.* Data and insights should be easy to discover,
-  understand, manipulate, transform and visualize.
-
-+ *Intuitive, visual, real-time, 3D-first interface.*
-
-  #+BEGIN_QUOTE
-  "Virtual reality holds the key to the evolution of the human mind."
-  — Dr. Lawrence Angelo, /The Lawnmower Man/ (1992)
-  #+END_QUOTE
-
-
-
-** Extensible, Programmable Computing Environment — An Example
-   :PROPERTIES:
-   :CUSTOM_ID: extensible-programmable-computing-environment
-   :ID:       c19c5a3b-dfb0-4f7f-961c-a387b925669f
-   :END:
-
-[[https://www.johndcook.com/blog/2008/04/27/one-program-to-rule-them-all/][GNU Emacs]] is perhaps the best existing example of this philosophy. At
-its core, Emacs is a text editor built on top of a Lisp runtime. Data
-storage and computation can be expressed in [[https://www.defmacro.org/ramblings/lisp.html][Lisp]], which is itself a
-programmable programming language — new paradigms and domain-specific
-languages can be added dynamically. Text buffers serve as building
-blocks for arbitrary user interfaces. The result is an environment
-that can be adapted and extended to fit virtually any problem domain.
-
-** Architecture and Components
-   :PROPERTIES:
-   :CUSTOM_ID: architecture-and-components
-   :ID:       52dbbf4c-2ef4-42a6-8331-ad006b6a52ae
-   :END:
-
-+ [[https://www3.svjatoslav.eu/projects/aukio/][Aukio]] — Parent project and the product: a spatial computing
-  environment (3D virtual workspace).
-  + [[https://www3.svjatoslav.eu/projects/aukio-data/][Aukio Data]] — Data storage and computation engine. (Very early
-    stage, nothing to see yet)
-  + [[https://www3.svjatoslav.eu/projects/aukio-3d/][Aukio 3D]] — Real-time 3D engine for user interface and data
-    visualization. The workspace runs on its 2.0 rewrite
-    (~aukio-3d-2~); Aukio 3D v1 is no longer used by Aukio. (Working
-    and usable, fast evolving)
-    + [[https://www3.svjatoslav.eu/projects/aukio-3d-demos/][Aukio 3D Demos]] — Demonstration scenes showcasing the
-      capabilities of the Aukio 3D engine. (Many demos, in good shape)
-
-The system is far from complete — the scope is large and available
-time is limited.
-
-** Roles and boundaries
-
-+ *Aukio 3D* is a reusable library. Anyone can take it to build games
-  or visualizations. It keeps only generic mechanisms: the renderer,
-  the pass kernel and substrate, the camera, input stores, and the
-  widget layer (text grids with an SDF atlas, 3D-anchored labels) that
-  games can also use (in-game consoles, interactive screens).
-+ *Aukio* is the concrete product built on that library: the virtual
-  workspace you actually work in (~workspace-v2~). Application-
-  integration bridges (PTY/terminal, window capture of X11 apps over
-  Xvfb, future VNC client) live here.
-  Exception to the "no native code in the engine" rule: XR glasses
-  head tracking (RayNeo IMU over hidraw, ~eu.svjatoslav.aukio.e3d.gui.headtrack~)
-  lives in the ENGINE, so every app and demo gets look-around head
-  tracking automatically when glasses are plugged in — including
-  hot-plug at runtime.
-+ *Aukio 3D Demos* remains the capability gallery and regression
-  harness. Workspace features are prototyped as demos, but the real
-  thing lives in Aukio.
-
-** Virtual workspace
-
-Aukio is a spatial computing environment: a persistent 3D world where
-every program you use — text editor, terminal, browser, virtual
-machine, data view — is a virtual object you place, walk to, and work
-at. It replaces window-switching with spatial memory: related tools
-live near each other, and your body remembers where things are.
-
-Roadmap for external applications, from cheapest to most general:
-
-+ *Virtual machines* — talk VNC/SPICE to the guest display instead of
-  scraping a window; the protocol provides both framebuffer updates
-  and input injection.
-+ *Arbitrary Linux applications* (browser, etc.) — run the app on a
-  dedicated ~Xvfb~ display, capture pixels via ~XShmGetImage~, inject
-  input via XTEST; the app lives only inside the 3D world.
-
-* Ideas
+
+:PROPERTIES:
+:CUSTOM_ID: aukio
+:END:
+
+#+OPTIONS: H:20 num:nil author:nil
+
+* What this documentation is
+:PROPERTIES:
+:CUSTOM_ID: what-this-documentation-is
+:END:
+
+The map of the engine. One page per module; each page states what that module
+owns, what it guarantees, and what it deliberately does not do yet.
+
+The repository README is the one-screen entry point (layout and build), and
+=AGENTS.org= at the root is the operating recipe for an AI agent working in the
+tree. This directory is what a human reads.
+
+* Modules
+:PROPERTIES:
+:CUSTOM_ID: modules
+:END:
+
+- Scheduler :: decides how many threads exist and which work runs on them.
+- World :: the scene as data: geometry, transforms, object tree, primitives.
+- Global illumination :: the light a surface receives, and the baking of it.
+- Renderer :: the algorithms that turn a world into pixels.
+- Navigation :: one frame of input, and the camera policy that answers it.
+- Swing adapter :: the component a host application embeds, and its render loop.
+- HID devices :: 3D mice, read off a character device that no toolkit delivers.
+- Demos :: the demonstration applications, and the launcher that lists them.
+
+** Scheduler
 :PROPERTIES:
-:CUSTOM_ID: ideas
+:CUSTOM_ID: scheduler
 :END:
 
-** Molecular dynamics integration
+The single owner of the CPU budget. It is the one place that knows how
+many worker threads the process may use, and the only place that
+decides whether a render task or a background task runs next.
+
+Today it holds the budget and nothing else; the queues, the priority
+rule and the frame gate are named on its page as planned work, not as
+behaviour.
+
+See [[file:../Modules/scheduler/Documentation/index.org][the scheduler page]].
+
+** World
 :PROPERTIES:
-:CUSTOM_ID: molecular-dynamics-integration
+:CUSTOM_ID: world
 :END:
 
-Integrate with [[https://www.gromacs.org/][GROMACS]] or a similar molecular dynamics simulator.
+The scene as data: geometry, transforms, the object tree, triangle storage in
+object space, the primitives, and the camera pose. It carries the object model
+deliberately - a node owns a transform and children inherit it, so a chain of
+parts is posed by writing transforms rather than by rewriting vertices.
 
-Users could place atoms in molecular dynamics models and manipulate
-them directly with hand gestures (in VR) or mouse drag-and-drop
-(desktop), seeing immediate force-based reactions. in 3D, the
-simulation becomes a tangible object you "hold" and adjust.
+It is the bottom of the engine and requires nothing: not the renderer, not the
+toolkit, not the scheduler, which the build enforces rather than promises.
 
-Teams in VR could jointly manipulate a protein model while viewing
-real-time simulation data, with each member's avatar contributing to
-the workspace.
+See [[file:../Modules/world/Documentation/index.org][the world page]].
 
-** Emacs client integration
+** Global illumination
 :PROPERTIES:
-:CUSTOM_ID: emacs-client-integration
+:CUSTOM_ID: gi
 :END:
 
-Allow Aukio to act as an Emacs client, connecting to a running Emacs
-instance. Text editors could then be spawned as objects in 3D space,
-each backed by the live Emacs process. This would make all existing
-Emacs plugins and functionality available inside the Aukio environment.
+The light a surface actually receives: direct light with visibility, indirect
+light, lightmaps, and the policy for what to bake next.
 
-** Document represented as geometry
+It writes light into world storage and the renderer samples it, so the two never
+meet: the raster carries no bake logic, and the baker carries no pixels. It
+requires the world and the scheduler, and it cannot require the renderer or the
+toolkit - the build refuses both.
 
-Text editors would be replaced by floating 3D "cubes" where code
-structure is visualized spatially - functions as connected nodes,
-dependencies as glowing wires. Moving a function node would
-automatically rewire related components, making refactoring a spatial
-act. In 2D, this requires mental mapping; in 3D, the structure is
-visible and manipulable.
+Three rules, each of which cost a bug in the previous engine: light is published
+complete or not at all, displayed quality never drops, and light positions and
+normals are always in world space.
 
-Ideas in Obsidian-like systems could be arranged in 3D mind maps where
-proximity indicates relevance - clicking a node pulls connected
-documents into view, creating a navigable "knowledge landscape".
+See [[file:../Modules/gi/Documentation/index.org][the global illumination page]].
 
-** Electronics circuit simulation integration
+** Renderer
 :PROPERTIES:
-:CUSTOM_ID: electronics-circuit-simulation-integration
+:CUSTOM_ID: renderer
 :END:
 
-Integrate with [[https://ngspice.sourceforge.io/][ngspice]], [[http://www.bwsst.com/][SPICE]], or a similar electronics circuit
-simulator, enabling interactive circuit design and simulation in 3D.
+The algorithms that turn a world into pixels: the frame buffer, the projection
+from a camera pose and a viewport to screen coordinates, culling and
+rasterisation.
+
+A pose is world data, a projection is not. The camera's position and rotation
+belong to the world; the =scale = width / 3= that turns them into screen
+coordinates belongs here, because only the renderer knows how wide the picture
+is.
+
+See [[file:../Modules/renderer/Documentation/index.org][the renderer page]].
+
+** Navigation
+:PROPERTIES:
+:CUSTOM_ID: navigation
+:END
+
+One frame of user intent as a record, and the camera that answers it. Keys,
+pointer movement, wheel notches and the six axes of a 3D device go in; the pose
+the next frame is drawn from comes out.
 
-A circuit designer using ngspice could place resistors/capacitors in
-3D space, connect them with virtual wires, and simultaneously
-visualize current flow as animated particles while overlaying
-Pandas-generated performance metrics. This eliminates
-context-switching between tools - data, simulation, and visualization
-coexist in one spatial workflow.
+The record lives here rather than in the toolkit adapter because a policy that
+cannot be tested without a window stops being tested: =FlyCameraTest= flies with
+no toolkit on its classpath at all. Keys and device deflection are levels and
+survive into every frame; pointer deltas and wheel notches are spent by exactly
+one frame. The module requires the world - a pose is world data - and nothing
+else.
 
-This would provide contextual continuity. Related tools (e.g., a
-simulation and its data analysis) can be spatially adjacent in space,
-avoiding the "window-switching" friction of 2D desktops.
+See [[file:../Modules/navigation/Documentation/index.org][the navigation page]].
 
-** 3D visualization of statistical data
+** Swing adapter
+:PROPERTIES:
+:CUSTOM_ID: swing
+:END:
 
-Dataframes from Pandas would render as 3D grids where rows/columns
-occupy spatial axes. Dragging a region of the grid would instantly
-filter related data. Unlike 2D tables where multidimensional
-relationships are flattened, 3D preserves natural spatial
-relationships- e.g., high-value data points "tower" above low-value
-ones, creating intuitive topographical insights.
+The component a host application embeds, plus the render loop that feeds it. A
+host with its own frame, tab or split pane takes only this; nothing here owns a
+window, and nothing here knows what the scene contains.
 
-A 3D scatter plot shows all variables simultaneously; rotating it
-reveals patterns invisible in 2D projections.
+It is the only engine module that may require =java.desktop=, and it depends on
+the renderer rather than the other way round, so the engine itself stays
+headless.
 
-Students could "walk through" a dataset experiencing trends as spatial
-terrain rather than abstract graphs.
+See [[file:../Modules/swing/Documentation/index.org][the swing adapter page]].
 
-* Source code
+** HID devices
 :PROPERTIES:
-:CUSTOM_ID: source-code
+:CUSTOM_ID: hid
 :END:
 
-*This program is free software: released under Creative Commons Zero
-(CC0) license*
+Input devices no toolkit can hand over: a 3Dconnexion cap arrives as bytes on
+=/dev/hidraw=, so a host with no window still has it. The module reads the
+device and reports six normalised axes; what those axes mean is the host's
+decision.
+
+It requires nothing at all, which is what lets a test, a server or a terminal
+read the same device as a windowed application. The reader thread is a blocked
+I/O thread - not CPU budget, so the scheduler has no business with it - and it
+never waits for a frame: a cap that lags the picture it steers is useless.
 
-*Program author:*
-- Svjatoslav Agejenko
-- Homepage: https://svjatoslav.eu
-- Email: mailto://svjatoslav@svjatoslav.eu
-- See also: [[https://www.svjatoslav.eu/projects/][Other software projects hosted at svjatoslav.eu]]
+See [[file:../Modules/hid/Documentation/index.org][the HID page]].
+
+** Demos
+:PROPERTIES:
+:CUSTOM_ID: demos
+:END:
 
-*Getting the source code:*
-- [[https://www2.svjatoslav.eu/gitweb/?p=aukio.git;a=snapshot;h=HEAD;sf=tgz][Download latest snapshot in TAR GZ format]]
-- [[https://www2.svjatoslav.eu/gitweb/?p=aukio.git;a=summary][Browse Git repository online]]
-- Clone Git repository using command:
-  : git clone https://www2.svjatoslav.eu/git/aukio.git
+The applications a person runs. Each is a small program of its own that embeds
+the view component in an ordinary window, and the launcher is a list of them
+rather than a framework that knows what they draw.
+
+The first one is =MinimalExample=: one red box, a camera pulled back - the scene
+every Aukio engine has shipped as its first demo, carried over unchanged so a
+render here can be put beside the previous engine's golden image. It writes one
+1920x1080 frame to =target/minimal-example.png= when started with =shot=, which
+is what a pixel comparison needs.
+
+In the window it is flown, by three means at once:
+
+| Input                  | Effect                                                    |
+|------------------------+-----------------------------------------------------------|
+| drag with a button     | look around; the pointer delta is pixels, the rate is 0.02 rad per pixel |
+| =W A S D=, arrows, =Q R= | fly and strafe level, rise and sink; Dvorak =, O E ' .= follow the physical WASD keys |
+| wheel                  | height only: turning it away from you descends, towards you rises; one notch is a hundred units per second of thrust |
+| 3D mouse cap           | proportional drive: push to fly along the view, twist to turn, tilt to look, press for down |
+
+The rates are the previous engine's, not new ones - they were tuned against this
+device and this hand - except that the cap's sensitivity is a single constant at
+the top of =FlyCamera=, and the previous engine's value was tuned for a
+kilometre-scale world rather than a hundred-unit box.
+
+The 3D mouse is read straight from =/dev/hidraw= in plain Java, so there is no
+native library and no device daemon to install; the udev rule that makes the node
+readable lives with the older engines in their repositories. A device that is
+unplugged and plugged back in is found again within two seconds.
+
+#+begin_src sh
+export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
+./gradlew --offline :demos:build
+CP=$(ls -d Applications/demos/build/classes/java/main Modules/*/build/classes/java/main | paste -sd:)
+java -cp "$CP" eu.svjatoslav.aukio.demos.minimal.MinimalExample shot
+#+end_src
diff --git a/Documentation/vision.org b/Documentation/vision.org
new file mode 100644 (file)
index 0000000..89b0a3c
--- /dev/null
@@ -0,0 +1,203 @@
+#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme
+#+TITLE: Aukio — System for Data Storage, Computation, Exploration and Interaction
+#+LANGUAGE: en
+#+LATEX_HEADER: \usepackage[margin=1.0in]{geometry}
+#+LATEX_HEADER: \usepackage{parskip}
+#+LATEX_HEADER: \usepackage[none]{hyphenat}
+
+#+OPTIONS: H:20 num:20
+#+OPTIONS: author:nil
+
+* Vision
+  :PROPERTIES:
+  :CUSTOM_ID: vision
+  :ID:       1f4e1c17-d25f-4d92-aa9b-5785f1d86f4f
+  :END:
+
+: A tool to amplify human ability
+
+The goal is a /bicycle for the mind/ — a powerful, extensible, hackable,
+general-purpose computing environment for working with knowledge.
+
+The system is built around the following priorities:
+
++ *Knowledge-first.* Data and insights should be easy to discover,
+  understand, manipulate, transform and visualize.
+
++ *Intuitive, visual, real-time, 3D-first interface.*
+
+  #+BEGIN_QUOTE
+  "Virtual reality holds the key to the evolution of the human mind."
+  — Dr. Lawrence Angelo, /The Lawnmower Man/ (1992)
+  #+END_QUOTE
+
+
+
+** Extensible, Programmable Computing Environment — An Example
+   :PROPERTIES:
+   :CUSTOM_ID: extensible-programmable-computing-environment
+   :ID:       c19c5a3b-dfb0-4f7f-961c-a387b925669f
+   :END:
+
+[[https://www.johndcook.com/blog/2008/04/27/one-program-to-rule-them-all/][GNU Emacs]] is perhaps the best existing example of this philosophy. At
+its core, Emacs is a text editor built on top of a Lisp runtime. Data
+storage and computation can be expressed in [[https://www.defmacro.org/ramblings/lisp.html][Lisp]], which is itself a
+programmable programming language — new paradigms and domain-specific
+languages can be added dynamically. Text buffers serve as building
+blocks for arbitrary user interfaces. The result is an environment
+that can be adapted and extended to fit virtually any problem domain.
+
+** Architecture and Components
+   :PROPERTIES:
+   :CUSTOM_ID: architecture-and-components
+   :ID:       52dbbf4c-2ef4-42a6-8331-ad006b6a52ae
+   :END:
+
++ [[https://www3.svjatoslav.eu/projects/aukio/][Aukio]] — Parent project and the product: a spatial computing
+  environment (3D virtual workspace).
+  + [[https://www3.svjatoslav.eu/projects/aukio-data/][Aukio Data]] — Data storage and computation engine. (Very early
+    stage, nothing to see yet)
+  + [[https://www3.svjatoslav.eu/projects/aukio-3d/][Aukio 3D]] — Real-time 3D engine for user interface and data
+    visualization. The workspace runs on its 2.0 rewrite
+    (~aukio-3d-2~); Aukio 3D v1 is no longer used by Aukio. (Working
+    and usable, fast evolving)
+    + [[https://www3.svjatoslav.eu/projects/aukio-3d-demos/][Aukio 3D Demos]] — Demonstration scenes showcasing the
+      capabilities of the Aukio 3D engine. (Many demos, in good shape)
+
+The system is far from complete — the scope is large and available
+time is limited.
+
+** Roles and boundaries
+
++ *Aukio 3D* is a reusable library. Anyone can take it to build games
+  or visualizations. It keeps only generic mechanisms: the renderer,
+  the pass kernel and substrate, the camera, input stores, and the
+  widget layer (text grids with an SDF atlas, 3D-anchored labels) that
+  games can also use (in-game consoles, interactive screens).
++ *Aukio* is the concrete product built on that library: the virtual
+  workspace you actually work in (~workspace-v2~). Application-
+  integration bridges (PTY/terminal, window capture of X11 apps over
+  Xvfb, future VNC client) live here.
+  Exception to the "no native code in the engine" rule: XR glasses
+  head tracking (RayNeo IMU over hidraw, ~eu.svjatoslav.aukio.e3d.gui.headtrack~)
+  lives in the ENGINE, so every app and demo gets look-around head
+  tracking automatically when glasses are plugged in — including
+  hot-plug at runtime.
++ *Aukio 3D Demos* remains the capability gallery and regression
+  harness. Workspace features are prototyped as demos, but the real
+  thing lives in Aukio.
+
+** Virtual workspace
+
+Aukio is a spatial computing environment: a persistent 3D world where
+every program you use — text editor, terminal, browser, virtual
+machine, data view — is a virtual object you place, walk to, and work
+at. It replaces window-switching with spatial memory: related tools
+live near each other, and your body remembers where things are.
+
+Roadmap for external applications, from cheapest to most general:
+
++ *Virtual machines* — talk VNC/SPICE to the guest display instead of
+  scraping a window; the protocol provides both framebuffer updates
+  and input injection.
++ *Arbitrary Linux applications* (browser, etc.) — run the app on a
+  dedicated ~Xvfb~ display, capture pixels via ~XShmGetImage~, inject
+  input via XTEST; the app lives only inside the 3D world.
+
+* Ideas
+:PROPERTIES:
+:CUSTOM_ID: ideas
+:END:
+
+** Molecular dynamics integration
+:PROPERTIES:
+:CUSTOM_ID: molecular-dynamics-integration
+:END:
+
+Integrate with [[https://www.gromacs.org/][GROMACS]] or a similar molecular dynamics simulator.
+
+Users could place atoms in molecular dynamics models and manipulate
+them directly with hand gestures (in VR) or mouse drag-and-drop
+(desktop), seeing immediate force-based reactions. in 3D, the
+simulation becomes a tangible object you "hold" and adjust.
+
+Teams in VR could jointly manipulate a protein model while viewing
+real-time simulation data, with each member's avatar contributing to
+the workspace.
+
+** Emacs client integration
+:PROPERTIES:
+:CUSTOM_ID: emacs-client-integration
+:END:
+
+Allow Aukio to act as an Emacs client, connecting to a running Emacs
+instance. Text editors could then be spawned as objects in 3D space,
+each backed by the live Emacs process. This would make all existing
+Emacs plugins and functionality available inside the Aukio environment.
+
+** Document represented as geometry
+
+Text editors would be replaced by floating 3D "cubes" where code
+structure is visualized spatially - functions as connected nodes,
+dependencies as glowing wires. Moving a function node would
+automatically rewire related components, making refactoring a spatial
+act. In 2D, this requires mental mapping; in 3D, the structure is
+visible and manipulable.
+
+Ideas in Obsidian-like systems could be arranged in 3D mind maps where
+proximity indicates relevance - clicking a node pulls connected
+documents into view, creating a navigable "knowledge landscape".
+
+** Electronics circuit simulation integration
+:PROPERTIES:
+:CUSTOM_ID: electronics-circuit-simulation-integration
+:END:
+
+Integrate with [[https://ngspice.sourceforge.io/][ngspice]], [[http://www.bwsst.com/][SPICE]], or a similar electronics circuit
+simulator, enabling interactive circuit design and simulation in 3D.
+
+A circuit designer using ngspice could place resistors/capacitors in
+3D space, connect them with virtual wires, and simultaneously
+visualize current flow as animated particles while overlaying
+Pandas-generated performance metrics. This eliminates
+context-switching between tools - data, simulation, and visualization
+coexist in one spatial workflow.
+
+This would provide contextual continuity. Related tools (e.g., a
+simulation and its data analysis) can be spatially adjacent in space,
+avoiding the "window-switching" friction of 2D desktops.
+
+** 3D visualization of statistical data
+
+Dataframes from Pandas would render as 3D grids where rows/columns
+occupy spatial axes. Dragging a region of the grid would instantly
+filter related data. Unlike 2D tables where multidimensional
+relationships are flattened, 3D preserves natural spatial
+relationships- e.g., high-value data points "tower" above low-value
+ones, creating intuitive topographical insights.
+
+A 3D scatter plot shows all variables simultaneously; rotating it
+reveals patterns invisible in 2D projections.
+
+Students could "walk through" a dataset experiencing trends as spatial
+terrain rather than abstract graphs.
+
+* Source code
+:PROPERTIES:
+:CUSTOM_ID: source-code
+:END:
+
+*This program is free software: released under Creative Commons Zero
+(CC0) license*
+
+*Program author:*
+- Svjatoslav Agejenko
+- Homepage: https://svjatoslav.eu
+- Email: mailto://svjatoslav@svjatoslav.eu
+- See also: [[https://www.svjatoslav.eu/projects/][Other software projects hosted at svjatoslav.eu]]
+
+*Getting the source code:*
+- [[https://www2.svjatoslav.eu/gitweb/?p=aukio.git;a=snapshot;h=HEAD;sf=tgz][Download latest snapshot in TAR GZ format]]
+- [[https://www2.svjatoslav.eu/gitweb/?p=aukio.git;a=summary][Browse Git repository online]]
+- Clone Git repository using command:
+  : git clone https://www2.svjatoslav.eu/git/aukio.git
diff --git a/Modules/gi/Documentation/index.org b/Modules/gi/Documentation/index.org
new file mode 100644 (file)
index 0000000..5877aef
--- /dev/null
@@ -0,0 +1,82 @@
+#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme
+#+TITLE: Global illumination
+#+LANGUAGE: en
+
+:PROPERTIES:
+:CUSTOM_ID: gi-page
+:END:
+
+#+OPTIONS: H:20 num:nil author:nil
+
+[[file:../../../Documentation/index.html#outline-container-gi][<- Back to index]]
+
+* What it owns
+:PROPERTIES:
+:CUSTOM_ID: gi-owns
+:END:
+
+The light a surface actually receives: direct light with visibility, indirect
+light, the lightmaps that hold per-texel results, and the policy that decides
+what to bake next and in which order.
+
+It is the Java module =eu.svjatoslav.aukio.gi=. It requires the world and the
+scheduler, and it cannot require the renderer or =java.desktop= - both are
+build failures, because a baker that draws has stopped being a baker.
+
+* Where the light goes
+:PROPERTIES:
+:CUSTOM_ID: gi-where
+:END:
+
+This module writes light into world storage; the renderer samples it. Neither
+knows the other exists. That is what keeps the raster free of bake logic and the
+baker free of pixels: swap the raster and the bakes still hold; turn GI off and
+the raster draws with whatever direct light the app supplies.
+
+* The three rules it exists to keep
+:PROPERTIES:
+:CUSTOM_ID: gi-rules
+:END:
+
+1. Light is published complete or not at all. A store that is allocated but not
+   yet baked reads as zeros, and zeros times albedo is a black frame. Until a
+   bake completes, the previous light stays on screen.
+2. Displayed quality never drops. A re-pin, a streamed append or leaving a ring
+   may add unbaked surfaces, but it must never replace fine light with coarse
+   light or with none.
+3. Coordinates are world coordinates. A light position and a normal in different
+   spaces produce light that appears displaced - the previous engine's phantom
+   lights were exactly that.
+
+* What it does not own
+:PROPERTIES:
+:CUSTOM_ID: gi-not-owns
+:END:
+
+- No pixels and no frame buffer. That is the renderer's.
+- No threads. The scheduler owns the process budget; this module submits work
+  and never sizes a pool of its own.
+- No scene. Geometry, poses and lights belong to the world.
+
+* What the build checks
+:PROPERTIES:
+:CUSTOM_ID: gi-checks
+:END:
+
+=ModuleShapeTest= holds the requirement list itself - world and scheduler, no
+renderer, no toolkit - plus one package, files under 800 lines, and imports that
+stay inside those two modules.
+
+#+begin_src sh
+export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
+./gradlew --offline :gi:test    # the baker alone, other modules absent
+#+end_src
+
+* Implemented today
+:PROPERTIES:
+:CUSTOM_ID: gi-implemented
+:END:
+
+The module, its descriptor and its shape check. Nothing is baked yet; the first
+piece will be direct light with visibility, because everything else is measured
+against it.
diff --git a/Modules/gi/build.gradle b/Modules/gi/build.gradle
new file mode 100644 (file)
index 0000000..8dc11af
--- /dev/null
@@ -0,0 +1,11 @@
+// Global illumination: the producer of light. It reads the world, spends the
+// scheduler's budget, and writes light where the renderer can find it - it
+// never draws and never owns a thread.
+
+dependencies {
+    // api: this module's own surface is expressed in world types (meshes, poses).
+    api project(':world')
+    // implementation: the scheduler is how the work gets run, not part of the
+    // API. The app that assembles modules decides which budget it gets.
+    implementation project(':scheduler')
+}
diff --git a/Modules/gi/src/main/java/eu/svjatoslav/aukio/gi/package-info.java b/Modules/gi/src/main/java/eu/svjatoslav/aukio/gi/package-info.java
new file mode 100644 (file)
index 0000000..abb349b
--- /dev/null
@@ -0,0 +1,27 @@
+/**
+ * Global illumination: turning geometry and lights into the light each surface
+ * actually receives.
+ *
+ * <p>What belongs here: direct light with visibility, indirect light, the
+ * lightmaps that hold per-texel results, and the policy that decides what gets
+ * baked next and in which order. What does not, and never will: pixels, the
+ * window, the scene itself, or a thread of its own - the scheduler owns the
+ * budget, and this module asks it for work.</p>
+ *
+ * <p>Three rules carry over from the previous engine, each of which cost a bug
+ * that took days to find:</p>
+ *
+ * <ul>
+ *   <li><b>Light is published complete or not at all.</b> A store that is
+ *       allocated but not yet baked reads as zeros, and zeros multiplied by
+ *       albedo is a black frame. Until a bake is complete, the previous light
+ *       stays on screen.</li>
+ *   <li><b>Displayed quality never drops.</b> Leaving a ring, a re-pin or a
+ *       streamed append may add unbaked surfaces, but it must never replace
+ *       fine light with coarse light or with none.</li>
+ *   <li><b>Coordinates are world coordinates.</b> A light position and a
+ *       normal must be in the same space, or the light appears displaced - the
+ *       previous engine's phantom lights were exactly that mistake.</li>
+ * </ul>
+ */
+package eu.svjatoslav.aukio.gi;
diff --git a/Modules/gi/src/main/java/module-info.java b/Modules/gi/src/main/java/module-info.java
new file mode 100644 (file)
index 0000000..e550a00
--- /dev/null
@@ -0,0 +1,16 @@
+/**
+ * The global illumination module: the producer of light.
+ *
+ * <p>It reads the world, spends the scheduler's thread budget, and writes the
+ * light it computes where the renderer can sample it. It never writes a pixel
+ * and never owns a thread - that is why its descriptor requires the world and
+ * the scheduler and cannot require the renderer.</p>
+ *
+ * <p>The export arrives with the first type. A package that holds only
+ * =package-info= cannot be exported, so the descriptor declares the module and
+ * its requirements now.</p>
+ */
+module eu.svjatoslav.aukio.gi {
+    requires transitive eu.svjatoslav.aukio.world;
+    requires eu.svjatoslav.aukio.sched;
+}
diff --git a/Modules/gi/src/test/java/eu/svjatoslav/aukio/gi/ModuleShapeTest.java b/Modules/gi/src/test/java/eu/svjatoslav/aukio/gi/ModuleShapeTest.java
new file mode 100644 (file)
index 0000000..c535fff
--- /dev/null
@@ -0,0 +1,178 @@
+package eu.svjatoslav.aukio.gi;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * The module's shape, checked rather than promised.
+ *
+ * <p>The requirement list is the load-bearing check here: global illumination
+ * produces light, so it may see the world and the scheduler and nothing else.
+ * A =requires= on the renderer would mean the baker has started drawing; a
+ * =requires= on =java.desktop= would mean it has started owning a window.</p>
+ */
+class ModuleShapeTest {
+
+    private static final int MAX_FILE_LINES = 800;
+
+    private static final Path SOURCE_ROOT = Path.of("src", "main", "java");
+
+    private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.gi";
+
+    private static final String WORLD_PACKAGE = "eu.svjatoslav.aukio.world";
+
+    private static final String SCHED_PACKAGE = "eu.svjatoslav.aukio.sched";
+
+    private static final Set<String> ALLOWED_ENGINE_MODULES = Set.of(WORLD_PACKAGE, SCHED_PACKAGE);
+
+    private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE);
+
+    private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    @Test
+    void sourcesLiveInExactlyOnePackage() throws IOException {
+        final List<String> problems = new ArrayList<>();
+        for (final Path file : sources()) {
+            final String declared = declaredPackage(file);
+            if (!MODULE_PACKAGE.equals(declared)) {
+                problems.add(relativize(file) + " declares package " + declared);
+            }
+        }
+        assertTrue(problems.isEmpty(), "one public package per module, found: " + problems);
+    }
+
+    @Test
+    void theDescriptorAsksForTheWorldAndTheSchedulerOnly() throws IOException {
+        final String descriptor = descriptor();
+        assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor),
+                "the module name is derived from its package");
+        final List<String> required = allMatches(REQUIRES, descriptor);
+        assertTrue(required.contains(WORLD_PACKAGE), "the baker reads the world: " + required);
+        assertTrue(required.contains(SCHED_PACKAGE), "the baker spends the scheduler's budget: " + required);
+        for (final String module : required) {
+            final boolean ours = module.startsWith("eu.svjatoslav.aukio.");
+            if (ours && !ALLOWED_ENGINE_MODULES.contains(module)) {
+                fail("global illumination is not allowed to require " + module);
+            }
+        }
+        final List<String> exports = allMatches(EXPORT, descriptor);
+        assertTrue(exports.size() <= 1, "one public package at most, found: " + exports);
+        for (final String exported : exports) {
+            assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported");
+        }
+    }
+
+    @Test
+    void noFileExceedsTheLineLimit() throws IOException {
+        final List<String> tooLong = new ArrayList<>();
+        for (final Path file : sources()) {
+            final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size();
+            if (lines > MAX_FILE_LINES) {
+                tooLong.add(relativize(file) + " " + lines + " lines");
+            }
+        }
+        assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong);
+    }
+
+    @Test
+    void importsStayInsideTheAllowedModules() throws IOException {
+        final List<String> foreign = new ArrayList<>();
+        for (final Path file : sources()) {
+            for (final String imported : imports(file)) {
+                if (!imported.startsWith("eu.svjatoslav.aukio.")) {
+                    continue;
+                }
+                final boolean allowed = imported.startsWith(MODULE_PACKAGE)
+                        || imported.startsWith(WORLD_PACKAGE)
+                        || imported.startsWith(SCHED_PACKAGE);
+                if (!allowed) {
+                    foreign.add(relativize(file) + " imports " + imported);
+                }
+            }
+        }
+        assertTrue(foreign.isEmpty(), "the baker sees the world and the scheduler, nothing else: " + foreign);
+    }
+
+    @Test
+    void theModuleItselfHasSources() throws IOException {
+        assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous");
+    }
+
+    private static List<Path> sources() throws IOException {
+        if (!Files.isDirectory(SOURCE_ROOT)) {
+            fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist");
+        }
+        try (Stream<Path> walk = Files.walk(SOURCE_ROOT)) {
+            return walk.filter(Files::isRegularFile)
+                    .filter(path -> path.toString().endsWith(".java"))
+                    .filter(path -> !path.getFileName().toString().equals("module-info.java"))
+                    .sorted()
+                    .toList();
+        }
+    }
+
+    private static String descriptor() throws IOException {
+        final Path file = SOURCE_ROOT.resolve("module-info.java");
+        if (!Files.isRegularFile(file)) {
+            fail("the module declares no descriptor: " + relativize(file) + " is missing");
+        }
+        return Files.readString(file, StandardCharsets.UTF_8);
+    }
+
+    private static String declaredPackage(final Path file) throws IOException {
+        final String text = Files.readString(file, StandardCharsets.UTF_8);
+        final Matcher matcher = PACKAGE.matcher(text);
+        if (!matcher.find()) {
+            return "<none>";
+        }
+        assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file));
+        return matcher.group(1);
+    }
+
+    private static List<String> imports(final Path file) throws IOException {
+        return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8));
+    }
+
+    private static String firstMatch(final Pattern pattern, final String text) {
+        final List<String> found = allMatches(pattern, text);
+        return found.isEmpty() ? "<none>" : found.get(0);
+    }
+
+    private static List<String> allMatches(final Pattern pattern, final String text) {
+        final List<String> found = new ArrayList<>();
+        final Matcher matcher = pattern.matcher(text);
+        while (matcher.find()) {
+            found.add(matcher.group(1));
+        }
+        return found;
+    }
+
+    private static int countMatches(final Pattern pattern, final String text) {
+        return allMatches(pattern, text).size();
+    }
+
+    private static String relativize(final Path path) {
+        return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString();
+    }
+}
diff --git a/Modules/hid/Documentation/index.org b/Modules/hid/Documentation/index.org
new file mode 100644 (file)
index 0000000..44c2aa1
--- /dev/null
@@ -0,0 +1,116 @@
+#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme
+#+TITLE: HID devices
+#+LANGUAGE: en
+
+:PROPERTIES:
+:CUSTOM_ID: hid-page
+:END:
+
+#+OPTIONS: H:20 num:nil author:nil
+
+[[file:../../../Documentation/index.html#outline-container-hid][<- Back to index]]
+
+* What it owns
+:PROPERTIES:
+:CUSTOM_ID: hid-owns
+:END
+
+Input devices the toolkit cannot deliver, read directly from =/dev/hidraw=: a
+3Dconnexion 6DOF mouse today, whatever else arrives as bytes from a character
+device later.
+
+It is the Java module =eu.svjatoslav.aukio.hid= and it requires nothing at
+all - not the world, not the renderer, not the toolkit. A device is a level in
+six axes and a listener call; nothing else is needed to report one, and a host
+with no window can read a cap exactly like a windowed one.
+
+* Why it is its own module
+:PROPERTIES:
+:CUSTOM_ID: hid-why
+:END
+
+A key press arrives through a toolkit, so =Modules/swing= records it. A cap
+deflection does not: it is a report on a character device, and a host that has no
+window - a test, a server, a terminal - still has a USB port. Putting the reader
+inside the Swing adapter would tie the engine's device support to
+=java.desktop=; putting it in the world would give the data model a file
+descriptor and a thread, which that module's page forbids.
+
+=Modules/hid= is therefore the sixth kind of thing in the engine, and the only one
+that owns a file descriptor.
+
+* The thread, and why the scheduler does not own it
+:PROPERTIES:
+:CUSTOM_ID: hid-thread
+:END
+
+The reader runs one daemon thread per device, and that lifetime is spent blocked
+in =read()= waiting for a hand to move. It is cheap and it is not CPU budget: the
+scheduler decides how much compute this process may use, and a blocked I/O
+thread uses none of it. Scheduling it would also mean a navigation source could
+be starved by a frame - the cap would lag the picture it steers, which is the one
+thing a 3D mouse must never do.
+
+* What it does not own
+:PROPERTIES:
+:CUSTOM_ID: hid-not-owns
+:END
+
+- No camera policy. A deflection is reported as =Motion=, six axes in -1..1; how
+  that becomes a pose - or an object position, or a light - is the host's
+  decision, and the demo's =FlyCamera= is one such decision.
+- No toolkit, no window, no scene.
+- No discovery UI. A device that is not attached is not an error; the reader
+  looks again every two seconds, so a replug needs no restart.
+
+* The protocol
+:PROPERTIES:
+:CUSTOM_ID: hid-protocol
+:END
+
+Two models are recognised, and both speak the same signs and the same
+full-deflection range:
+
+- SpaceNavigator over USB: 7-byte reports, sent only while the cap is deflected
+  or a button changes, so silence is normal rather than a fault. Report 1 carries
+  translation, report 2 rotation, report 3 buttons, each axis a little-endian
+  signed 16-bit pair.
+- SpaceMouse Wireless over Bluetooth: one 13-byte report carries all six axes.
+
+Raw signs, measured on the hardware: x to the right, y towards the user, z
+pressed down, yaw twisted clockwise seen from above, pitch tilted away from the
+user, roll tilted right. Axes are shaped before they leave the module - a
+deadband of one count, then a quadratic response - so a small push gives fine
+control and the rim gives full speed.
+
+The udev rule that makes the node readable lives in the older engines'
+repositories (=aukio-3d/udev/99-spacenavigator.rules=); nothing here depends on
+it existing at build time.
+
+* What the build checks
+:PROPERTIES:
+:CUSTOM_ID: hid-checks
+:END
+
+=ModuleShapeTest= holds the shape: one package, a descriptor that requires no
+other engine module, files under 800 lines, and imports that never leave the
+module.
+
+=SpaceNavigatorTest= pins the protocol rather than a device: the endianness, the
+report ids and the axis-to-role mapping are exactly what fails silently on real
+hardware, where a wrong offset reads as a tiny movement instead of an error.
+
+#+begin_src sh
+export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
+./gradlew --offline :hid:test    # the module alone, other modules absent
+#+end_src
+
+* Implemented today
+:PROPERTIES:
+:CUSTOM_ID: hid-implemented
+:END
+
+=SpaceNavigator= for the USB SpaceNavigator and the Bluetooth SpaceMouse
+Wireless, and =Motion= as the six-axis reading. The button reports are recognised
+and ignored: the cap button is a brake in the older engines, and a brake is a
+navigation decision that belongs to whichever policy wants it.
diff --git a/Modules/hid/build.gradle b/Modules/hid/build.gradle
new file mode 100644 (file)
index 0000000..8ee30a1
--- /dev/null
@@ -0,0 +1,7 @@
+// Input devices no toolkit delivers: 3D mice first, and whatever else arrives as
+// bytes from a character device later. It requires nothing at all, so a host
+// with no window can use it exactly like a windowed one.
+
+dependencies {
+    // none
+}
diff --git a/Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/Motion.java b/Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/Motion.java
new file mode 100644 (file)
index 0000000..5f434a9
--- /dev/null
@@ -0,0 +1,26 @@
+package eu.svjatoslav.aukio.hid;
+
+/**
+ * What a 3D device is being asked to do right now, as six normalised axes.
+ *
+ * <p>Every value is -1..1: the transport applies a deadband and a quadratic
+ * response before this record exists, so a small push gives fine control and the
+ * rim gives full speed. The axes are levels, not deltas - a cap that is held
+ * keeps reporting until it is released - because that is what the hardware
+ * sends.</p>
+ *
+ * <p>Signs are the hardware's, not the camera's: x to the right, y towards the
+ * user, z pressed down, yaw twisted to the right, pitch tilted away from the
+ * user, roll tilted right. A navigation policy flips them into whatever its own
+ * conventions are; this module only reports what the device did.</p>
+ */
+public record Motion(double x, double y, double z, double yaw, double pitch, double roll) {
+
+    /** Nothing touched: a hand off the cap. */
+    public static final Motion REST = new Motion(0, 0, 0, 0, 0, 0);
+
+    /** Whether any axis is currently deflected. */
+    public boolean moving() {
+        return x != 0 || y != 0 || z != 0 || yaw != 0 || pitch != 0 || roll != 0;
+    }
+}
diff --git a/Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/SpaceNavigator.java b/Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/SpaceNavigator.java
new file mode 100644 (file)
index 0000000..df30a8f
--- /dev/null
@@ -0,0 +1,217 @@
+package eu.svjatoslav.aukio.hid;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+
+/**
+ * A 3Dconnexion 6DOF mouse, read from /dev/hidraw in plain Java.
+ *
+ * <p>No native library and no device daemon: the kernel already presents the
+ * device as a character device, a udev rule makes it readable by the user, and
+ * the reports are a dozen bytes. Two models are recognised - the USB
+ * SpaceNavigator and the Bluetooth SpaceMouse Wireless - because both speak the
+ * same axis signs and the same full-deflection range.</p>
+ *
+ * <p>Protocol, SpaceNavigator over USB: 7-byte reports, sent only while the cap
+ * is deflected or a button changes, so silence is normal rather than a fault.</p>
+ *
+ * <pre>
+ *   report[0] = 1   translation, int16 little endian at 1, 3, 5
+ *   report[0] = 2   rotation,    int16 little endian at 1, 3, 5
+ *   report[0] = 3   buttons,     report[1] bit 0 = left, bit 1 = right
+ * </pre>
+ *
+ * <p>Protocol, SpaceMouse Wireless: one 13-byte report carries all six axes,
+ * translation then rotation, with the same little-endian int16 pairs.</p>
+ *
+ * <p>Raw signs, measured on the hardware: x to the right, y towards the user,
+ * z pressed down, yaw twisted clockwise seen from above, pitch tilted away from
+ * the user, roll tilted right. Axes are shaped before they leave this class - a
+ * deadband of one count, then a quadratic response - so the driver receives
+ * -1..1 with fine control near the centre and full speed at the rim.</p>
+ *
+ * <p>The hidraw node number changes on every replug, so the device is found by
+ * scanning /sys/class/hidraw for a known HID id and is re-scanned after a read
+ * failure: unplugging and plugging back in needs no restart.</p>
+ */
+public final class SpaceNavigator {
+
+    /** Where each decoded report goes. Called on the reader thread. */
+    @FunctionalInterface
+    public interface MotionListener {
+        void motion(Motion motion);
+    }
+
+    private static final String[] HID_IDS = {
+            "0003:0000046D:0000C626",   // SpaceNavigator, USB
+            "0005:0000256F:0000C63A"    // SpaceMouse Wireless, Bluetooth
+    };
+
+    /** How long to wait before looking for the device again. */
+    private static final long RESCAN_MILLIS = 2000;
+
+    /** Raw counts below this are a hand resting on the cap, not a push. */
+    private static final int DEADBAND = 1;
+
+    /** Full deflection, per the HID descriptor. */
+    private static final double FULL_DEFLECTION = 350.0;
+
+    private final MotionListener listener;
+    private final Thread thread;
+
+    private volatile boolean running = true;
+    private volatile FileChannel open;
+
+    public SpaceNavigator(final MotionListener listener) {
+        this.listener = listener;
+        this.thread = new Thread(this::loop, "space-navigator");
+        this.thread.setDaemon(true);
+    }
+
+    public void start() {
+        thread.start();
+    }
+
+    public void stop() {
+        running = false;
+        final FileChannel channel = open;
+        if (channel != null) {
+            try {
+                channel.close();
+            } catch (final IOException ignored) {
+                // stopping is not a failure
+            }
+        }
+        thread.interrupt();
+    }
+
+    private void loop() {
+        final double[] axes = new double[6];
+        while (running) {
+            final Path node = findDevice();
+            if (node == null) {
+                if (!pause()) {
+                    return;
+                }
+                continue;
+            }
+            System.out.println("space navigator: " + node);
+            try (FileChannel channel = FileChannel.open(node, StandardOpenOption.READ)) {
+                open = channel;
+                final ByteBuffer report = ByteBuffer.allocate(32);
+                while (running) {
+                    report.clear();
+                    final int length = channel.read(report);
+                    if (length > 0 && decode(report.array(), length, axes)) {
+                        listener.motion(new Motion(axes[0], axes[1], axes[2],
+                                axes[3], axes[4], axes[5]));
+                    }
+                }
+            } catch (final IOException failure) {
+                if (running) {
+                    System.out.println("space navigator: " + node + " stopped reading ("
+                            + failure.getMessage() + "), looking for it again");
+                }
+            } finally {
+                open = null;
+            }
+            if (!pause()) {
+                return;
+            }
+        }
+    }
+
+    /** @return false when the thread was interrupted and must stop */
+    private boolean pause() {
+        try {
+            Thread.sleep(RESCAN_MILLIS);
+            return true;
+        } catch (final InterruptedException interrupted) {
+            Thread.currentThread().interrupt();
+            return false;
+        }
+    }
+
+    /** @return the hidraw node of a supported device, or null when none is attached */
+    static Path findDevice() {
+        final Path hidraw = Path.of("/sys/class/hidraw");
+        if (!Files.isDirectory(hidraw)) {
+            return null;
+        }
+        try (DirectoryStream<Path> nodes = Files.newDirectoryStream(hidraw, "hidraw*")) {
+            for (final Path node : nodes) {
+                final Path uevent = node.resolve("device").resolve("uevent");
+                if (!Files.isRegularFile(uevent)) {
+                    continue;
+                }
+                final String content = Files.readString(uevent, StandardCharsets.UTF_8);
+                for (final String hidId : HID_IDS) {
+                    if (content.contains(hidId)) {
+                        return Path.of("/dev", node.getFileName().toString());
+                    }
+                }
+            }
+        } catch (final IOException unreadable) {
+            return null;
+        }
+        return null;
+    }
+
+    /**
+     * Decodes one report into the six axes.
+     *
+     * @param report the bytes read
+     * @param length how many of them are valid
+     * @param axes   receives x, y, z, yaw, pitch, roll; untouched when this is not a motion report
+     * @return whether the report carried motion
+     */
+    static boolean decode(final byte[] report, final int length, final double[] axes) {
+        if (length < 4) {
+            return false;
+        }
+        final int id = report[0] & 0xFF;
+        if (id == 1 && length >= 13) {
+            axes[0] = shaped(axis(report, 1));
+            axes[1] = shaped(axis(report, 3));
+            axes[2] = shaped(axis(report, 5));
+            axes[4] = shaped(axis(report, 7));    // RX, pitch
+            axes[5] = shaped(axis(report, 9));    // RY, roll
+            axes[3] = shaped(axis(report, 11));   // RZ, yaw
+            return true;
+        }
+        if (id == 1 && length >= 7) {
+            axes[0] = shaped(axis(report, 1));
+            axes[1] = shaped(axis(report, 3));
+            axes[2] = shaped(axis(report, 5));
+            return true;
+        }
+        if (id == 2 && length >= 7) {
+            axes[4] = shaped(axis(report, 1));   // pitch, tilt away from the user
+            axes[5] = shaped(axis(report, 3));   // roll, tilt to the right
+            axes[3] = shaped(axis(report, 5));   // yaw, twist to the right
+            return true;
+        }
+        return false;
+    }
+
+    /** Little-endian signed 16-bit at an offset. */
+    private static int axis(final byte[] report, final int offset) {
+        return (short) ((report[offset] & 0xFF) | (report[offset + 1] << 8));
+    }
+
+    /** Deadband, then a quadratic response: fine control near the centre, full speed at the rim. */
+    static double shaped(final int raw) {
+        final int magnitude = Math.abs(raw);
+        if (magnitude <= DEADBAND) {
+            return 0;
+        }
+        final double normalised = (magnitude - DEADBAND) / (FULL_DEFLECTION - DEADBAND);
+        return Math.copySign(normalised * normalised, raw);
+    }
+}
diff --git a/Modules/hid/src/main/java/module-info.java b/Modules/hid/src/main/java/module-info.java
new file mode 100644 (file)
index 0000000..dc47abd
--- /dev/null
@@ -0,0 +1,15 @@
+/**
+ * The HID module: 3D input devices the toolkit knows nothing about.
+ *
+ * <p>A 6DOF mouse arrives as bytes from a character device, not as an event from
+ * a window, so no toolkit can deliver it and no window has to exist for it to
+ * work. This module reads such devices and reports their deflection as data -
+ * six normalised axes - and the host decides what that means.</p>
+ *
+ * <p>It requires nothing: not the world, not the renderer, not the toolkit. A
+ * device is a level in six axes and a listener call, and no other module is
+ * needed to say that.</p>
+ */
+module eu.svjatoslav.aukio.hid {
+    exports eu.svjatoslav.aukio.hid;
+}
diff --git a/Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/ModuleShapeTest.java b/Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/ModuleShapeTest.java
new file mode 100644 (file)
index 0000000..de655cb
--- /dev/null
@@ -0,0 +1,162 @@
+package eu.svjatoslav.aukio.hid;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * The module's shape, checked rather than promised: one public package, one
+ * descriptor, no requirement on any other engine module, and no file longer
+ * than the agreed limit.
+ *
+ * <p>The requirement list is the important one here. A device reader needs a
+ * byte stream and nothing else; if it ever requires the world or the renderer,
+ * then flying a camera has leaked into the module that should only be reporting
+ * what the hardware said.</p>
+ */
+class ModuleShapeTest {
+
+    private static final int MAX_FILE_LINES = 800;
+
+    private static final Path SOURCE_ROOT = Path.of("src", "main", "java");
+
+    private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.hid";
+
+    private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE);
+
+    private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    @Test
+    void sourcesLiveInExactlyOnePackage() throws IOException {
+        final List<String> problems = new ArrayList<>();
+        for (final Path file : sources()) {
+            final String declared = declaredPackage(file);
+            if (!MODULE_PACKAGE.equals(declared)) {
+                problems.add(relativize(file) + " declares package " + declared);
+            }
+        }
+        assertTrue(problems.isEmpty(), "one public package per module, found: " + problems);
+    }
+
+    @Test
+    void theDescriptorRequiresNoEngineModule() throws IOException {
+        final String descriptor = descriptor();
+        assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor),
+                "the module name is derived from its package");
+        for (final String required : allMatches(REQUIRES, descriptor)) {
+            assertFalse(required.startsWith("eu.svjatoslav.aukio."),
+                    "a device reader requires no engine module, found: " + required);
+        }
+        final List<String> exports = allMatches(EXPORT, descriptor);
+        assertTrue(exports.size() <= 1, "one public package at most, found: " + exports);
+        for (final String exported : exports) {
+            assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported");
+        }
+    }
+
+    @Test
+    void noFileExceedsTheLineLimit() throws IOException {
+        final List<String> tooLong = new ArrayList<>();
+        for (final Path file : sources()) {
+            final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size();
+            if (lines > MAX_FILE_LINES) {
+                tooLong.add(relativize(file) + " " + lines + " lines");
+            }
+        }
+        assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong);
+    }
+
+    @Test
+    void importsStayInsideThisModule() throws IOException {
+        final List<String> foreign = new ArrayList<>();
+        for (final Path file : sources()) {
+            for (final String imported : imports(file)) {
+                if (imported.startsWith("eu.svjatoslav.aukio.") && !imported.startsWith(MODULE_PACKAGE)) {
+                    foreign.add(relativize(file) + " imports " + imported);
+                }
+            }
+        }
+        assertTrue(foreign.isEmpty(), "this module imports no other engine module: " + foreign);
+    }
+
+    @Test
+    void theModuleItselfHasSources() throws IOException {
+        assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous");
+    }
+
+    private static List<Path> sources() throws IOException {
+        if (!Files.isDirectory(SOURCE_ROOT)) {
+            fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist");
+        }
+        try (Stream<Path> walk = Files.walk(SOURCE_ROOT)) {
+            return walk.filter(Files::isRegularFile)
+                    .filter(path -> path.toString().endsWith(".java"))
+                    .filter(path -> !path.getFileName().toString().equals("module-info.java"))
+                    .sorted()
+                    .toList();
+        }
+    }
+
+    private static String descriptor() throws IOException {
+        final Path file = SOURCE_ROOT.resolve("module-info.java");
+        if (!Files.isRegularFile(file)) {
+            fail("the module declares no descriptor: " + relativize(file) + " is missing");
+        }
+        return Files.readString(file, StandardCharsets.UTF_8);
+    }
+
+    private static String declaredPackage(final Path file) throws IOException {
+        final String text = Files.readString(file, StandardCharsets.UTF_8);
+        final Matcher matcher = PACKAGE.matcher(text);
+        if (!matcher.find()) {
+            return "<none>";
+        }
+        assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file));
+        return matcher.group(1);
+    }
+
+    private static List<String> imports(final Path file) throws IOException {
+        return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8));
+    }
+
+    private static String firstMatch(final Pattern pattern, final String text) {
+        final List<String> found = allMatches(pattern, text);
+        return found.isEmpty() ? "<none>" : found.get(0);
+    }
+
+    private static List<String> allMatches(final Pattern pattern, final String text) {
+        final List<String> found = new ArrayList<>();
+        final Matcher matcher = pattern.matcher(text);
+        while (matcher.find()) {
+            found.add(matcher.group(1));
+        }
+        return found;
+    }
+
+    private static int countMatches(final Pattern pattern, final String text) {
+        return allMatches(pattern, text).size();
+    }
+
+    private static String relativize(final Path path) {
+        return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString();
+    }
+}
diff --git a/Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/SpaceNavigatorTest.java b/Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/SpaceNavigatorTest.java
new file mode 100644 (file)
index 0000000..b62b7e6
--- /dev/null
@@ -0,0 +1,99 @@
+package eu.svjatoslav.aukio.hid;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The HID protocol and the response curve, checked against recorded report
+ * shapes rather than against a device.
+ *
+ * <p>The endianness, the report ids and the sign mapping are exactly the things
+ * that fail silently on real hardware - a wrong offset reads as a tiny movement
+ * rather than as an error - so they are pinned here, and the live check only has
+ * to confirm that the pipe opens.</p>
+ */
+class SpaceNavigatorTest {
+
+    private static final double EXACT = 1e-12;
+
+    @Test
+    void aTranslationReportFillsTheFirstThreeAxes() {
+        final double[] axes = new double[6];
+        assertTrue(SpaceNavigator.decode(report(1, 350, -350, 0), 7, axes));
+        assertEquals(1.0, axes[0], EXACT, "push right is full x");
+        assertEquals(-1.0, axes[1], EXACT, "pull towards the user is full -y");
+        assertEquals(0, axes[2], EXACT);
+        assertEquals(0, axes[3], EXACT);
+    }
+
+    @Test
+    void aRotationReportFillsYawPitchAndRoll() {
+        final double[] axes = new double[6];
+        assertTrue(SpaceNavigator.decode(report(2, 350, 350, 350), 7, axes));
+        assertEquals(1.0, axes[4], EXACT, "the first rotation axis is pitch, tilt away");
+        assertEquals(1.0, axes[5], EXACT, "the second is roll, tilt right");
+        assertEquals(1.0, axes[3], EXACT, "the third is yaw, twist right");
+    }
+
+    @Test
+    void aCombinedReportCarriesAllSixAxes() {
+        final byte[] report = new byte[13];
+        report[0] = 1;
+        put(report, 1, 350);
+        put(report, 3, 175);
+        put(report, 5, -350);
+        put(report, 7, 350);    // RX, pitch
+        put(report, 9, -350);   // RY, roll
+        put(report, 11, 175);   // RZ, yaw
+        final double[] axes = new double[6];
+        assertTrue(SpaceNavigator.decode(report, 13, axes));
+        assertEquals(1.0, axes[0], EXACT);
+        assertEquals(0.2486, axes[1], 1e-4, "half deflection is a quarter of the speed, by the curve");
+        assertEquals(-1.0, axes[2], EXACT);
+        assertEquals(1.0, axes[4], EXACT, "pitch comes from the RX axis at offset 7");
+        assertEquals(-1.0, axes[5], EXACT, "roll from RY at offset 9");
+        assertEquals(0.2486, axes[3], 1e-4, "yaw from RZ at offset 11");
+    }
+
+    @Test
+    void aButtonReportIsNotMotion() {
+        final byte[] report = new byte[7];
+        report[0] = 3;
+        report[1] = 1;
+        final double[] axes = new double[]{0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
+        assertFalse(SpaceNavigator.decode(report, 7, axes));
+        assertEquals(0.5, axes[0], EXACT, "a button report must not disturb the axes");
+    }
+
+    @Test
+    void theDeadbandIsSilent() {
+        assertEquals(0, SpaceNavigator.shaped(0), EXACT);
+        assertEquals(0, SpaceNavigator.shaped(1), EXACT);
+        assertEquals(0, SpaceNavigator.shaped(-1), EXACT);
+    }
+
+    @Test
+    void theCurveIsQuadraticAndReachesOneAtTheRim() {
+        assertEquals(-1.0, SpaceNavigator.shaped(-350), EXACT);
+        final double quarter = SpaceNavigator.shaped(88);
+        assertTrue(quarter > 0.05 && quarter < 0.07, "a quarter push is a fraction of the speed: " + quarter);
+    }
+
+    /** A 7-byte report: id, then three little-endian 16-bit axes. */
+    private static byte[] report(final int id, final int first, final int second, final int third) {
+        final byte[] report = new byte[7];
+        report[0] = (byte) id;
+        put(report, 1, first);
+        put(report, 3, second);
+        put(report, 5, third);
+        return report;
+    }
+
+    private static void put(final byte[] report, final int offset, final int value) {
+        report[offset] = (byte) (value & 0xFF);
+        report[offset + 1] = (byte) ((value >> 8) & 0xFF);
+    }
+}
diff --git a/Modules/navigation/Documentation/index.org b/Modules/navigation/Documentation/index.org
new file mode 100644 (file)
index 0000000..4f009fb
--- /dev/null
@@ -0,0 +1,108 @@
+#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme
+#+TITLE: Navigation
+#+LANGUAGE: en
+
+:PROPERTIES:
+:CUSTOM_ID: navigation-page
+:END:
+
+#+OPTIONS: H:20 num:nil author:nil
+
+[[file:../../../Documentation/index.html#outline-container-navigation][<- Back to index]]
+
+* What it owns
+:PROPERTIES:
+:CUSTOM_ID: navigation-owns
+:END
+
+What the user asked for during one frame, and the camera policy that answers it.
+
+It is the Java module =eu.svjatoslav.aukio.navigation=: it requires the world,
+because a pose is world data, and it deliberately requires nothing else - in
+particular not the toolkit. Whoever fills the input record - a Swing component, a
+test, a device with no window at all - the same policy flies the same way.
+
+* The seam: a record in, a pose out
+:PROPERTIES:
+:CUSTOM_ID: navigation-seam
+:END
+
+| Type            | Role                                                          |
+|-----------------+---------------------------------------------------------------|
+| =ViewInput=     | one frame's worth of user intent, immutable                   |
+| =InputRecorder= | where a host writes events; one snapshot is drained per frame |
+| =CameraDriver=  | the contract: record and elapsed seconds in, a pose out       |
+| =FlyCamera=     | the engine's driver, with the rates every Aukio engine used   |
+
+Two kinds of value live in a record, and the difference is the rule the previous
+engine learned the hard way. Keys and 3D-device deflection are *levels*: true
+until something changes them, copied into every frame. Pointer movement and wheel
+notches are *accumulations*: drained by exactly one frame, so a drag is applied
+once and never replayed. A value that is read and consumed in the same place is a
+value applied twice, and that is why the recorder and the driver are separate
+objects rather than one method.
+
+Keys travel as AWT key codes. The toolkit is where keys come from, so its
+numbering is the dialect a record speaks; that keeps every policy from growing a
+table of its own.
+
+* FlyCamera
+:PROPERTIES:
+:CUSTOM_ID: navigation-fly
+:END
+
+The engine's camera: the pointer looks, the keyboard moves, the wheel changes
+height, a 3D mouse does all three proportionally. The rates are the previous
+engine's - a fiftieth of a radian per pixel, 2000 units per second squared of
+acceleration growing with speed and damped at 5 per second up to 600 units per
+second, a cap that drives five times the keyboard top speed, a wheel notch worth
+a hundred units per second of thrust.
+
+Two behaviours are easy to get wrong and are deliberate. Keyboard movement is
+level: forward and strafe come from yaw only, so pitching up to look at a roof
+does not fly you into it. The cap, by contrast, flies along the view direction
+with pitch included, because pushing it away means "go where I am looking".
+
+* What it does not own
+:PROPERTIES:
+:CUSTOM_ID: navigation-not-owns
+:END
+
+- The scene, the frame, and everything the renderer does with them.
+- Reading devices: a 3D mouse arrives through =Modules/hid= as =Motion=, and a host
+  hands it to the record it is filling.
+- Toolkits. A host with no window drives the same record, and a host that wants
+  to orbit, walk or follow a path implements =CameraDriver= instead of using
+  =FlyCamera=.
+
+* What the build checks
+:PROPERTIES:
+:CUSTOM_ID: navigation-checks
+:END
+
+=ModuleShapeTest= holds the shape: one package, a descriptor that requires the
+world and no other engine module, files under 800 lines, and imports that stay
+inside the module and the world. Proving the descriptor is not vacuous is one
+line: adding =requires eu.svjatoslav.aukio.render= to it fails to compile with
+"module not found".
+
+=FlyCameraTest= and =InputRecorderTest= drive the policy headlessly - keys, drags,
+wheel notches and cap deflection in, poses out - which is the reason the input
+record does not live in the toolkit module: a policy that needs a window to be
+tested is a policy that stops being tested.
+
+#+begin_src sh
+export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
+./gradlew --offline :navigation:test    # the module alone, other modules absent
+#+end_src
+
+* Implemented today
+:PROPERTIES:
+:CUSTOM_ID: navigation-implemented
+:END
+
+=ViewInput= with keys, pointer delta, wheel notches and six device axes;
+=InputRecorder= as the host's write seam; =CameraDriver=; =FlyCamera= with the
+previous engine's rates. Not here yet: orbiting and walking policies, a key map
+for a host that is not a toolkit, and anything that moves the scene rather than
+the camera.
diff --git a/Modules/navigation/build.gradle b/Modules/navigation/build.gradle
new file mode 100644 (file)
index 0000000..1851bff
--- /dev/null
@@ -0,0 +1,8 @@
+// What a frame of input is, and the camera policy that answers it. It knows the
+// world (a pose is world data) and deliberately not the toolkit, so the same
+// flying works in a test, a server, or a host with no window.
+
+dependencies {
+    // api: a driver hands back world types, so callers of this module name them.
+    api project(':world')
+}
diff --git a/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/CameraDriver.java b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/CameraDriver.java
new file mode 100644 (file)
index 0000000..bbf5da1
--- /dev/null
@@ -0,0 +1,26 @@
+package eu.svjatoslav.aukio.navigation;
+
+import eu.svjatoslav.aukio.world.Camera;
+
+/**
+ * The host's answer to one frame of input: the pose the next frame is drawn
+ * from.
+ *
+ * <p>A view knows nothing about flying, walking or orbiting, and this is where
+ * that stays true: each frame the host hands over what the user did and how long
+ * the frame took, and takes back a pose. {@link FlyCamera} is the engine's
+ * answer, and an application that wants another one implements this instead.</p>
+ *
+ * <p>Called on the render thread, once per rendered frame, never on an event
+ * dispatch thread.</p>
+ */
+@FunctionalInterface
+public interface CameraDriver {
+
+    /**
+     * @param input   what the user did during this frame
+     * @param seconds time since the previous rendered frame, 0 on the first
+     * @return the pose for this frame, or null to keep the current one
+     */
+    Camera frame(ViewInput input, double seconds);
+}
diff --git a/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/FlyCamera.java b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/FlyCamera.java
new file mode 100644 (file)
index 0000000..0cc0b25
--- /dev/null
@@ -0,0 +1,199 @@
+package eu.svjatoslav.aukio.navigation;
+
+import eu.svjatoslav.aukio.world.Camera;
+import eu.svjatoslav.aukio.world.Vec3;
+
+/**
+ * Flying, the way every Aukio engine has flown: the pointer looks, the keyboard
+ * moves, the 3D mouse does both proportionally.
+ *
+ * <p>The rates are the previous engine's, not new numbers: pointer at a fiftieth
+ * of a radian per pixel, keyboard acceleration of 2000 units per second squared
+ * growing with speed and damped at 5 per second up to 600 units per second, and
+ * a 3D cap that drives five times the keyboard top speed at full deflection and
+ * twists twice as fast as it tilts. They were tuned against the real device and
+ * the same hand, so keeping them is what makes this feel like the engine that
+ * came before rather than a new one.</p>
+ *
+ * <p>Two behaviours are easy to get wrong and are copied deliberately. Keyboard
+ * movement is level - forward and strafe come from yaw only, pitch only steers
+ * the view - while the cap flies along the view direction with pitch included,
+ * because pushing the cap away means "go where I am looking". And the cap is a
+ * level, not an impulse: it moves the camera for as long as it is deflected and
+ * stops the same frame it is released.</p>
+ */
+public final class FlyCamera implements CameraDriver {
+
+    /**
+     * Key codes in the input record's dialect, which is AWT's: the toolkit is
+     * where keys come from, so its numbering is what travels. The Dvorak cluster
+     * mirrors the physical WASD positions, so the same fingers fly in both
+     * layouts.
+     */
+    static final int KEY_W = 87;
+    static final int KEY_A = 65;
+    static final int KEY_S = 83;
+    static final int KEY_D = 68;
+    static final int KEY_Q = 81;
+    static final int KEY_R = 82;
+    static final int KEY_E = 69;
+    static final int KEY_O = 79;
+    static final int KEY_COMMA = 44;
+    static final int KEY_PERIOD = 46;
+    static final int KEY_QUOTE = 222;
+    static final int KEY_UP = 38;
+    static final int KEY_DOWN = 40;
+    static final int KEY_LEFT = 37;
+    static final int KEY_RIGHT = 39;
+
+    static final double MOUSE_SENSITIVITY = 0.02;
+    static final double PITCH_LIMIT = 1.5;
+    /** One wheel notch, in units per second of thrust: the legacy camera gave a
+     *  notch fifty times its acceleration factor, which is this number here. */
+    static final double WHEEL_THRUST = 100.0;
+    static final double ACCELERATION = 2000.0;
+    static final double ACCELERATION_SPEED_REFERENCE = 200.0;
+    static final double DAMPING = 5.0;
+    static final double MAX_SPEED = 600.0;
+    static final double CAP_SPEED_FACTOR = 5.0;
+    static final double CAP_SENSITIVITY = 5.0;
+    static final double CAP_YAW_RATE = Math.toRadians(180);
+    static final double CAP_PITCH_RATE = Math.toRadians(90);
+    static final double MAX_FRAME_SECONDS = 0.25;
+
+    private double x;
+    private double y;
+    private double z;
+    private double yaw;
+    private double pitch;
+    private double velocityX;
+    private double velocityY;
+    private double velocityZ;
+
+    public FlyCamera(final Camera start) {
+        this.x = start.position().x();
+        this.y = start.position().y();
+        this.z = start.position().z();
+        this.yaw = start.yaw();
+        this.pitch = start.pitch();
+    }
+
+    /** The pose as it stands, for a view that has not asked for a frame yet. */
+    public Camera camera() {
+        return Camera.of(new Vec3(x, y, z), yaw, pitch);
+    }
+
+    @Override
+    public Camera frame(final ViewInput input, final double seconds) {
+        final double dt = Math.min(Math.max(seconds, 0), MAX_FRAME_SECONDS);
+        if (dt > 0) {
+            look(input, dt);
+            fly(input, dt);
+            drive(input, dt);
+        }
+        return camera();
+    }
+
+    /** Pointer drag and cap tilt/twist: once per frame, because both are angles, not distances. */
+    private void look(final ViewInput input, final double dt) {
+        yaw += input.dragX() * MOUSE_SENSITIVITY;
+        pitch = clamp(pitch - input.dragY() * MOUSE_SENSITIVITY);
+        yaw += input.deviceYaw() * CAP_YAW_RATE * CAP_SENSITIVITY * dt;
+        pitch = clamp(pitch + input.devicePitch() * CAP_PITCH_RATE * CAP_SENSITIVITY * dt);
+    }
+
+    /** Keyboard and wheel: accelerate along the level view basis, damp, cap, move. */
+    private void fly(final ViewInput input, final double dt) {
+        final double sinYaw = Math.sin(yaw);
+        final double cosYaw = Math.cos(yaw);
+        double dirX = 0;
+        double dirY = 0;
+        double dirZ = 0;
+        if (down(input, KEY_W, KEY_UP, KEY_COMMA)) {
+            dirX += sinYaw;
+            dirZ += cosYaw;
+        }
+        if (down(input, KEY_S, KEY_DOWN, KEY_O)) {
+            dirX -= sinYaw;
+            dirZ -= cosYaw;
+        }
+        if (down(input, KEY_D, KEY_RIGHT, KEY_E)) {
+            dirX += cosYaw;
+            dirZ -= sinYaw;
+        }
+        if (down(input, KEY_A, KEY_LEFT)) {
+            dirX -= cosYaw;
+            dirZ += sinYaw;
+        }
+        if (down(input, KEY_R, KEY_PERIOD)) {
+            dirY += 1;
+        }
+        if (down(input, KEY_Q, KEY_QUOTE)) {
+            dirY -= 1;
+        }
+        final double length = Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ);
+        if (length > 0) {
+            final double speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY
+                    + velocityZ * velocityZ);
+            final double acceleration = ACCELERATION * (1 + speed / ACCELERATION_SPEED_REFERENCE);
+            velocityX += dirX / length * acceleration * dt;
+            velocityY += dirY / length * acceleration * dt;
+            velocityZ += dirZ / length * acceleration * dt;
+        }
+        // The wheel pushes vertically and nothing else, which is what both
+        // earlier engines did and what makes it a height control rather than a
+        // zoom: turning the wheel away from the user descends, towards the user
+        // rises. A notch is a push, so it is spent by the frame that reads it.
+        if (input.wheel() != 0) {
+            final double speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY
+                    + velocityZ * velocityZ);
+            velocityY -= input.wheel() * WHEEL_THRUST * (1 + speed / ACCELERATION_SPEED_REFERENCE);
+        }
+        final double damp = Math.exp(-DAMPING * dt);
+        velocityX *= damp;
+        velocityY *= damp;
+        velocityZ *= damp;
+        final double speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY
+                + velocityZ * velocityZ);
+        if (speed > MAX_SPEED) {
+            final double limit = MAX_SPEED / speed;
+            velocityX *= limit;
+            velocityY *= limit;
+            velocityZ *= limit;
+        }
+        x += velocityX * dt;
+        y += velocityY * dt;
+        z += velocityZ * dt;
+    }
+
+    /** 3D mouse: deflection is velocity along the view basis, released means stopped. */
+    private void drive(final ViewInput input, final double dt) {
+        final double strafe = input.deviceX();
+        final double forward = -input.deviceY();
+        final double vertical = -input.deviceZ();
+        if (strafe == 0 && forward == 0 && vertical == 0) {
+            return;
+        }
+        final double sinYaw = Math.sin(yaw);
+        final double cosYaw = Math.cos(yaw);
+        final double sinPitch = Math.sin(pitch);
+        final double cosPitch = Math.cos(pitch);
+        final double step = CAP_SPEED_FACTOR * MAX_SPEED * CAP_SENSITIVITY * dt;
+        x += (sinYaw * cosPitch * forward + cosYaw * strafe) * step;
+        y += (sinPitch * forward + vertical) * step;
+        z += (cosYaw * cosPitch * forward - sinYaw * strafe) * step;
+    }
+
+    private static boolean down(final ViewInput input, final int... keyCodes) {
+        for (final int keyCode : keyCodes) {
+            if (input.isDown(keyCode)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static double clamp(final double value) {
+        return value < -PITCH_LIMIT ? -PITCH_LIMIT : Math.min(value, PITCH_LIMIT);
+    }
+}
diff --git a/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/InputRecorder.java b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/InputRecorder.java
new file mode 100644 (file)
index 0000000..c8ed0b1
--- /dev/null
@@ -0,0 +1,109 @@
+package eu.svjatoslav.aukio.navigation;
+
+import java.util.TreeSet;
+
+/**
+ * Where the component writes what its listeners saw, and where the render thread
+ * takes it from.
+ *
+ * <p>Two kinds of value live here, and the difference is the whole point. Keys
+ * and device deflection are levels: they are true until something changes them,
+ * so they are copied into every frame's snapshot. Pointer movement and wheel
+ * notches are accumulations: they are drained exactly once per frame, so a drag
+ * is applied once and never replayed.</p>
+ *
+ * <p>The writers are whatever collects events - the toolkit listeners, a device
+ * thread, a test - and the single reader is the frame that renders next. That is
+ * why this type is public: it is the seam a host uses to feed the engine, and a
+ * host that is not Swing uses exactly the same one.</p>
+ */
+public final class InputRecorder {
+
+    private final Object lock = new Object();
+
+    private final TreeSet<Integer> keys = new TreeSet<>();
+
+    private double dragX;
+    private double dragY;
+    private int wheel;
+
+    private final double[] device = new double[6];
+
+    public void keyDown(final int keyCode) {
+        synchronized (lock) {
+            keys.add(keyCode);
+        }
+    }
+
+    public void keyUp(final int keyCode) {
+        synchronized (lock) {
+            keys.remove(keyCode);
+        }
+    }
+
+    /** A window that loses focus never sees the key releases, so they are dropped here. */
+    public void clearKeys() {
+        synchronized (lock) {
+            keys.clear();
+        }
+    }
+
+    public void addPointerDelta(final double dx, final double dy) {
+        synchronized (lock) {
+            dragX += dx;
+            dragY += dy;
+        }
+    }
+
+    /** Wheel notches accumulate like the pointer: they are spent by one frame. */
+    public void addWheel(final int rotation) {
+        synchronized (lock) {
+            wheel += rotation;
+        }
+    }
+
+    /** Device deflection is a level, written by the device thread and read every frame. */
+    public void setDeviceMotion(final double x, final double y, final double z,
+                         final double yaw, final double pitch, final double roll) {
+        synchronized (lock) {
+            device[0] = x;
+            device[1] = y;
+            device[2] = z;
+            device[3] = yaw;
+            device[4] = pitch;
+            device[5] = roll;
+        }
+    }
+
+    /** One snapshot per frame; the pointer delta is consumed here and nowhere else. */
+    public ViewInput drain() {
+        synchronized (lock) {
+            final int[] held = new int[keys.size()];
+            int slot = 0;
+            for (final int key : keys) {
+                held[slot++] = key;
+            }
+            final ViewInput input = ViewInput.of(held, dragX, dragY, wheel,
+                    device[0], device[1], device[2], device[3], device[4], device[5]);
+            dragX = 0;
+            dragY = 0;
+            wheel = 0;
+            return input;
+        }
+    }
+
+    /** Whether a frame is worth rendering at all. */
+    public boolean isActive() {
+        synchronized (lock) {
+            if (!keys.isEmpty() || dragX != 0 || dragY != 0 || wheel != 0) {
+                return true;
+            }
+            for (final double axis : device) {
+                if (axis != 0) {
+                    return true;
+                }
+            }
+            return false;
+        }
+    }
+}
diff --git a/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/ViewInput.java b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/ViewInput.java
new file mode 100644 (file)
index 0000000..5bbf360
--- /dev/null
@@ -0,0 +1,128 @@
+package eu.svjatoslav.aukio.navigation;
+
+import java.util.Arrays;
+
+/**
+ * What the user asked for during one frame: the keys still held, the pointer
+ * movement since the previous frame, and the current deflection of a 3D device.
+ *
+ * <p>This is a record, not a channel. A host adapter - the toolkit component, or
+ * anything else that collects events - builds one per frame and hands it to a
+ * {@link CameraDriver}; nothing else may read those pointer deltas, or they
+ * would be applied twice. Key state and device deflection are levels, so reading
+ * them twice is harmless - the pointer delta and the wheel notches are the
+ * values that are spent.</p>
+ *
+ * <p>Keys arrive as AWT key codes because that is the dialect the toolkit speaks
+ * and the one the toolkits before this engine used; a different host would have
+ * to translate its own codes into them, which is cheaper than every policy
+ * growing a table.</p>
+ *
+ * <p>Device axes are normalised to -1..1 through a deadband and a quadratic
+ * response, so a small push gives fine control and the rim gives full speed.
+ * Signs are the hardware's: x to the right, y towards the user, z pressed down,
+ * yaw twisted to the right, pitch tilted away from the user, roll tilted right.
+ * The driver flips them into the camera's own conventions; keeping the raw sense
+ * here is what lets one snapshot serve any controller.</p>
+ */
+public final class ViewInput {
+
+    /** Nothing held, nothing moved: an idle frame. */
+    public static final ViewInput NOTHING = new ViewInput(new int[0], 0, 0, 0,
+            new double[]{0, 0, 0, 0, 0, 0});
+
+    private final int[] keys;
+
+    private final double dragX;
+    private final double dragY;
+    private final int wheel;
+    private final double[] device;
+
+    private ViewInput(final int[] keys, final double dragX, final double dragY, final int wheel,
+                      final double[] device) {
+        this.keys = keys;
+        this.dragX = dragX;
+        this.dragY = dragY;
+        this.wheel = wheel;
+        this.device = device;
+    }
+
+    /**
+     * @param keys   key codes held at the start of the frame, in any order
+     * @param dragX  pointer movement to the right since the previous frame, in pixels
+     * @param dragY  pointer movement downwards since the previous frame, in pixels
+     * @param wheel  wheel notches since the previous frame, positive scrolling away from the user
+     */
+    public static ViewInput of(final int[] keys, final double dragX, final double dragY, final int wheel,
+                               final double deviceX, final double deviceY, final double deviceZ,
+                               final double deviceYaw, final double devicePitch, final double deviceRoll) {
+        final int[] sorted = keys.clone();
+        Arrays.sort(sorted);
+        return new ViewInput(sorted, dragX, dragY, wheel,
+                new double[]{deviceX, deviceY, deviceZ, deviceYaw, devicePitch, deviceRoll});
+    }
+
+    /** @param keyCode an AWT key code, the toolkit's own dialect */
+    public boolean isDown(final int keyCode) {
+        return Arrays.binarySearch(keys, keyCode) >= 0;
+    }
+
+    /** The key codes held, ascending. */
+    public int[] keys() {
+        return keys.clone();
+    }
+
+    public double dragX() {
+        return dragX;
+    }
+
+    public double dragY() {
+        return dragY;
+    }
+
+    /**
+     * Wheel notches since the previous frame, positive when the wheel was turned
+     * away from the user. A notch is an accumulation like the pointer delta: the
+     * frame that reads it spends it.
+     */
+    public int wheel() {
+        return wheel;
+    }
+
+    public double deviceX() {
+        return device[0];
+    }
+
+    public double deviceY() {
+        return device[1];
+    }
+
+    public double deviceZ() {
+        return device[2];
+    }
+
+    public double deviceYaw() {
+        return device[3];
+    }
+
+    public double devicePitch() {
+        return device[4];
+    }
+
+    public double deviceRoll() {
+        return device[5];
+    }
+
+    /** Whether anything is still being asked for, which decides if another frame is needed. */
+    public boolean anyActivity() {
+        if (keys.length > 0 || dragX != 0 || dragY != 0 || wheel != 0) {
+            return true;
+        }
+        for (final double axis : device) {
+            if (axis != 0) {
+                return true;
+            }
+        }
+        return false;
+    }
+}
diff --git a/Modules/navigation/src/main/java/module-info.java b/Modules/navigation/src/main/java/module-info.java
new file mode 100644 (file)
index 0000000..badb0aa
--- /dev/null
@@ -0,0 +1,22 @@
+/**
+ * The navigation module: the input a frame receives, and the camera policy that
+ * answers it.
+ *
+ * <p>A frame's worth of input is a record - keys held, pointer movement, wheel
+ * notches, the six axes of a 3D device - and a driver turns it into the pose the
+ * next frame is drawn from. The engine ships one driver, {@code FlyCamera}, with
+ * the rates every Aukio engine has used; a host that wants to orbit, walk or be
+ * driven by a path writes its own and the modules below never learn about it.</p>
+ *
+ * <p>It requires the world, because a pose is world data and a driver produces
+ * one. It deliberately does not require the toolkit: input arrives here as a
+ * record, whoever filled it, so the same policy flies a windowed application, a
+ * test, or a device with no window at all.</p>
+ */
+module eu.svjatoslav.aukio.navigation {
+    // transitive: this module's own API is expressed in world types (a pose in,
+    // a pose out), so anything that requires navigation needs the world to name
+    // them.
+    requires transitive eu.svjatoslav.aukio.world;
+    exports eu.svjatoslav.aukio.navigation;
+}
diff --git a/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/FlyCameraTest.java b/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/FlyCameraTest.java
new file mode 100644 (file)
index 0000000..07c2835
--- /dev/null
@@ -0,0 +1,177 @@
+package eu.svjatoslav.aukio.navigation;
+
+import eu.svjatoslav.aukio.world.Camera;
+import eu.svjatoslav.aukio.world.Vec3;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The camera controls, driven without a window: keys fly, a drag looks, the cap
+ * pushes proportionally.
+ *
+ * <p>Each test feeds input frames to the driver and reads the pose back, which is
+ * the whole point of the driver seam - the behaviour that a person feels can be
+ * asserted headlessly, and the arithmetic cannot rot unnoticed behind a panel.</p>
+ */
+class FlyCameraTest {
+
+    private static final double HALF_A_SECOND = 0.05;
+    private static final int TEN_FRAMES = 10;
+    private static final int TWENTY_FRAMES = 20;
+
+    private static final ViewInput NOTHING = ViewInput.NOTHING;
+
+    @Test
+    void noInputLeavesThePoseAlone() {
+        final FlyCamera fly = new FlyCamera(Camera.of(new Vec3(1, 2, 3), 0.4, -0.2));
+        fly.frame(NOTHING, HALF_A_SECOND);
+        assertEquals(1, fly.camera().position().x(), 1e-12);
+        assertEquals(2, fly.camera().position().y(), 1e-12);
+        assertEquals(3, fly.camera().position().z(), 1e-12);
+        assertEquals(0.4, fly.camera().yaw(), 1e-12);
+        assertEquals(-0.2, fly.camera().pitch(), 1e-12);
+    }
+
+    @Test
+    void wFliesForwardAlongTheViewDirection() {
+        final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0)));
+        hold(fly, new int[]{FlyCamera.KEY_W}, TWENTY_FRAMES);
+        assertEquals(0, fly.camera().position().x(), 1e-9, "level flight has no sideways drift");
+        assertEquals(0, fly.camera().position().y(), 1e-9, "level flight has no vertical drift");
+        assertTrue(fly.camera().position().z() > 200,
+                "a second at full speed covers hundreds of units, not " + fly.camera().position().z());
+    }
+
+    @Test
+    void dStrafesRight() {
+        final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0)));
+        hold(fly, new int[]{FlyCamera.KEY_D}, TWENTY_FRAMES);
+        assertTrue(fly.camera().position().x() > 200, "strafe right goes to +X, got "
+                + fly.camera().position().x());
+        assertEquals(0, fly.camera().position().z(), 1e-9);
+    }
+
+    @Test
+    void rRisesAndQSinks() {
+        final FlyCamera up = new FlyCamera(Camera.at(new Vec3(0, 0, 0)));
+        hold(up, new int[]{FlyCamera.KEY_R}, TEN_FRAMES);
+        assertTrue(up.camera().position().y() > 0, "R rises, got " + up.camera().position().y());
+
+        final FlyCamera down = new FlyCamera(Camera.at(new Vec3(0, 0, 0)));
+        hold(down, new int[]{FlyCamera.KEY_Q}, TEN_FRAMES);
+        assertTrue(down.camera().position().y() < 0, "Q sinks, got " + down.camera().position().y());
+    }
+
+    @Test
+    void theWheelChangesHeightAndNothingElse() {
+        final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 100, 0)));
+        // a notch away from the user is the legacy gesture for going down
+        fly.frame(wheel(1), HALF_A_SECOND);
+        hold(fly, new int[0], TEN_FRAMES);
+        final double descent = 100 - fly.camera().position().y();
+        // a notch is a hundred units per second of thrust, damped at five per
+        // second, so one notch carries the camera about twenty units
+        assertTrue(descent > 15 && descent < 30,
+                "one notch descends about twenty units, got " + descent);
+        assertEquals(0, fly.camera().position().x(), 1e-9, "the wheel is a height control, not a strafe");
+        assertEquals(0, fly.camera().position().z(), 1e-9, "the wheel is a height control, not a thrust");
+    }
+
+    @Test
+    void theWheelTowardsTheUserRises() {
+        final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 100, 0)));
+        fly.frame(wheel(-1), HALF_A_SECOND);
+        hold(fly, new int[0], TEN_FRAMES);
+        assertTrue(fly.camera().position().y() > 100, "wheel towards the user rises, got "
+                + fly.camera().position().y());
+    }
+
+    @Test
+    void aNotchIsSpentByTheFrameThatReadsIt() {
+        final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 100, 0)));
+        fly.frame(wheel(1), HALF_A_SECOND);
+        // the push is a thrust: the camera keeps its velocity, but a frame that
+        // carries no notch must not add another one
+        final double afterFirst = fly.camera().position().y();
+        final double firstStepDrop = 100 - afterFirst;
+        fly.frame(NOTHING, HALF_A_SECOND);
+        final double nextStepDrop = afterFirst - fly.camera().position().y();
+        assertTrue(nextStepDrop < firstStepDrop, "a spent notch must not push again: " + nextStepDrop
+                + " in the next frame against " + firstStepDrop + " in the notch frame");
+    }
+
+    @Test
+    void draggingRightTurnsRight() {
+        final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0)));
+        fly.frame(input(new int[0], 100, 0), HALF_A_SECOND);
+        assertEquals(2.0, fly.camera().yaw(), 1e-9, "a hundred pixels at 0.02 radians each");
+    }
+
+    @Test
+    void draggingUpLooksUpAndStopsAtTheLimit() {
+        final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0)));
+        fly.frame(input(new int[0], 0, -10000), HALF_A_SECOND);
+        assertEquals(FlyCamera.PITCH_LIMIT, fly.camera().pitch(), 1e-9, "pitch is clamped upright");
+    }
+
+    @Test
+    void theCapFliesForward() {
+        final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0)));
+        for (int frame = 0; frame < TEN_FRAMES; frame++) {
+            // pushing the cap away from the user reads negative on the y axis
+            fly.frame(input(new int[0], 0, 0, 0, -1, 0, 0, 0, 0), HALF_A_SECOND);
+        }
+        assertTrue(fly.camera().position().z() > 100, "the cap flies along the view, got "
+                + fly.camera().position().z());
+        assertEquals(0, fly.camera().position().x(), 1e-9);
+    }
+
+    @Test
+    void theCapStopsTheFrameItIsReleased() {
+        final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0)));
+        fly.frame(input(new int[0], 0, 0, 0, -1, 0, 0, 0, 0), HALF_A_SECOND);
+        final double moved = fly.camera().position().z();
+        fly.frame(NOTHING, HALF_A_SECOND);
+        assertEquals(moved, fly.camera().position().z(), 1e-12, "a released cap does not coast");
+    }
+
+    @Test
+    void theCapTwistsTheCamera() {
+        final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0)));
+        fly.frame(input(new int[0], 0, 0, 0, 0, 0, 1, 0, 0), HALF_A_SECOND);
+        assertTrue(fly.camera().yaw() > 0, "twisting clockwise turns right, got " + fly.camera().yaw());
+    }
+
+    @Test
+    void aFrameOfZeroSecondsChangesNothing() {
+        final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0)));
+        fly.frame(input(new int[]{FlyCamera.KEY_W}, 50, 50, 1, 1, 1, 1, 1, 1), 0);
+        assertEquals(0, fly.camera().position().z(), 1e-12);
+        assertEquals(0, fly.camera().yaw(), 1e-12);
+    }
+
+    private static void hold(final FlyCamera fly, final int[] keys, final int frames) {
+        for (int frame = 0; frame < frames; frame++) {
+            fly.frame(input(keys, 0, 0), HALF_A_SECOND);
+        }
+    }
+
+    private static ViewInput input(final int[] keys, final double dragX, final double dragY) {
+        return ViewInput.of(keys, dragX, dragY, 0, 0, 0, 0, 0, 0, 0);
+    }
+
+    /** @param wheel notches, positive away from the user */
+    private static ViewInput wheel(final int notches) {
+        return ViewInput.of(new int[0], 0, 0, notches, 0, 0, 0, 0, 0, 0);
+    }
+
+    private static ViewInput input(final int[] keys, final double dragX, final double dragY,
+                                   final double deviceX, final double deviceY, final double deviceZ,
+                                   final double deviceYaw, final double devicePitch,
+                                   final double deviceRoll) {
+        return ViewInput.of(keys, dragX, dragY, 0, deviceX, deviceY, deviceZ,
+                deviceYaw, devicePitch, deviceRoll);
+    }
+}
diff --git a/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/InputRecorderTest.java b/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/InputRecorderTest.java
new file mode 100644 (file)
index 0000000..7054745
--- /dev/null
@@ -0,0 +1,79 @@
+package eu.svjatoslav.aukio.navigation;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * What survives a frame and what does not: keys and device deflection are
+ * levels, the pointer delta is spent by the frame that reads it.
+ *
+ * <p>This is the rule the previous engine broke with a signature built from
+ * live mouse deltas, so it is asserted rather than trusted.</p>
+ */
+class InputRecorderTest {
+
+    @Test
+    void keysAreStillHeldOnTheNextFrame() {
+        final InputRecorder recorder = new InputRecorder();
+        recorder.keyDown(87);
+        assertTrue(recorder.drain().isDown(87));
+        assertTrue(recorder.drain().isDown(87), "a key is a level until it is released");
+        recorder.keyUp(87);
+        assertFalse(recorder.drain().isDown(87));
+    }
+
+    @Test
+    void pointerMovementIsSpentByTheFrameThatReadsIt() {
+        final InputRecorder recorder = new InputRecorder();
+        recorder.addPointerDelta(10, -4);
+        final ViewInput first = recorder.drain();
+        assertTrue(first.dragX() == 10 && first.dragY() == -4);
+        final ViewInput second = recorder.drain();
+        assertTrue(second.dragX() == 0 && second.dragY() == 0, "a drag must not be applied twice");
+    }
+
+    @Test
+    void pointerMovementAccumulatesUntilTheFrameReadsIt() {
+        final InputRecorder recorder = new InputRecorder();
+        recorder.addPointerDelta(3, 0);
+        recorder.addPointerDelta(4, 0);
+        assertTrue(recorder.drain().dragX() == 7);
+    }
+
+    @Test
+    void deviceDeflectionPersistsUntilItChanges() {
+        final InputRecorder recorder = new InputRecorder();
+        recorder.setDeviceMotion(0.5, 0, 0, 0, 0, 0);
+        assertTrue(recorder.drain().deviceX() == 0.5);
+        assertTrue(recorder.drain().deviceX() == 0.5, "a held cap keeps reporting, frame after frame");
+        recorder.setDeviceMotion(0, 0, 0, 0, 0, 0);
+        assertFalse(recorder.drain().anyActivity());
+    }
+
+    @Test
+    void wheelNotchesAreSpentByTheFrameThatReadsThem() {
+        final InputRecorder recorder = new InputRecorder();
+        recorder.addWheel(1);
+        recorder.addWheel(1);
+        assertTrue(recorder.drain().wheel() == 2, "two notches in one frame are one push of two");
+        assertTrue(recorder.drain().wheel() == 0, "a notch must not be applied twice");
+    }
+
+    @Test
+    void losingFocusDropsHeldKeys() {
+        final InputRecorder recorder = new InputRecorder();
+        recorder.keyDown(65);
+        recorder.clearKeys();
+        assertFalse(recorder.drain().isDown(65), "a key released while unfocused would otherwise stick");
+    }
+
+    @Test
+    void anIdleRecorderAsksForNoFrames() {
+        final InputRecorder recorder = new InputRecorder();
+        assertFalse(recorder.isActive());
+        recorder.keyDown(87);
+        assertTrue(recorder.isActive());
+    }
+}
diff --git a/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/ModuleShapeTest.java b/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/ModuleShapeTest.java
new file mode 100644 (file)
index 0000000..9c462cb
--- /dev/null
@@ -0,0 +1,177 @@
+package eu.svjatoslav.aukio.navigation;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * The module's shape, checked rather than promised: one public package, one
+ * export, no file longer than the agreed limit, and no import of another module
+ * in this tree but the world.
+ *
+ * <p>The rule that matters here is the one that is absent: no requirement on the
+ * toolkit. A policy that could not fly without a window would be a policy that
+ * cannot be tested, and the whole point of keeping input as a record is that it
+ * can be driven by a test as easily as by a mouse.</p>
+ */
+class ModuleShapeTest {
+
+    private static final int MAX_FILE_LINES = 800;
+
+    private static final Path SOURCE_ROOT = Path.of("src", "main", "java");
+
+    private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.navigation";
+
+    private static final String WORLD_PACKAGE = "eu.svjatoslav.aukio.world";
+
+    private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE);
+
+    private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    @Test
+    void sourcesLiveInExactlyOnePackage() throws IOException {
+        final List<String> problems = new ArrayList<>();
+        for (final Path file : sources()) {
+            final String declared = declaredPackage(file);
+            if (!MODULE_PACKAGE.equals(declared)) {
+                problems.add(relativize(file) + " declares package " + declared);
+                continue;
+            }
+            final Path directory = file.getParent();
+            if (!directory.endsWith(Path.of("", MODULE_PACKAGE.split("\\.")))) {
+                problems.add(relativize(file) + " sits in " + relativize(directory)
+                        + " but declares " + MODULE_PACKAGE);
+            }
+        }
+        assertTrue(problems.isEmpty(), "one public package per module, found: " + problems);
+    }
+
+    @Test
+    void theDescriptorExportsThatOnePackageAndRequiresTheWorldOnly() throws IOException {
+        final String descriptor = descriptor();
+        assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor),
+                "the module name is derived from its package, so a requires clause reads naturally");
+        final List<String> exports = allMatches(EXPORT, descriptor);
+        assertTrue(exports.size() <= 1, "the module exports at most its one public package, found: " + exports);
+        for (final String exported : exports) {
+            assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported");
+        }
+        final List<String> required = allMatches(REQUIRES, descriptor);
+        assertTrue(required.contains(WORLD_PACKAGE),
+                "a driver produces a world pose, so its descriptor says so: " + required);
+        for (final String module : required) {
+            final boolean ours = module.startsWith("eu.svjatoslav.aukio.");
+            if (ours && !module.equals(WORLD_PACKAGE)) {
+                fail("navigation requires no engine module but the world, found: " + module);
+            }
+        }
+    }
+
+    @Test
+    void noFileExceedsTheLineLimit() throws IOException {
+        final List<String> tooLong = new ArrayList<>();
+        for (final Path file : sources()) {
+            final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size();
+            if (lines > MAX_FILE_LINES) {
+                tooLong.add(relativize(file) + " " + lines + " lines");
+            }
+        }
+        assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong);
+    }
+
+    @Test
+    void importsReachIntoTheWorldAndNoFurther() throws IOException {
+        final List<String> foreign = new ArrayList<>();
+        for (final Path file : sources()) {
+            for (final String imported : imports(file)) {
+                if (imported.startsWith("eu.svjatoslav.aukio.")
+                        && !imported.startsWith(MODULE_PACKAGE)
+                        && !imported.startsWith(WORLD_PACKAGE)) {
+                    foreign.add(relativize(file) + " imports " + imported);
+                }
+            }
+        }
+        assertTrue(foreign.isEmpty(), "navigation may see the world and nothing else: " + foreign);
+    }
+
+    @Test
+    void theModuleItselfHasSources() throws IOException {
+        assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous");
+    }
+
+    private static List<Path> sources() throws IOException {
+        if (!Files.isDirectory(SOURCE_ROOT)) {
+            fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist");
+        }
+        try (Stream<Path> walk = Files.walk(SOURCE_ROOT)) {
+            return walk.filter(Files::isRegularFile)
+                    .filter(path -> path.toString().endsWith(".java"))
+                    .filter(path -> !path.getFileName().toString().equals("module-info.java"))
+                    .sorted()
+                    .toList();
+        }
+    }
+
+    private static String descriptor() throws IOException {
+        final Path file = SOURCE_ROOT.resolve("module-info.java");
+        if (!Files.isRegularFile(file)) {
+            fail("the module declares no descriptor: " + relativize(file) + " is missing");
+        }
+        return Files.readString(file, StandardCharsets.UTF_8);
+    }
+
+    private static String declaredPackage(final Path file) throws IOException {
+        final String text = Files.readString(file, StandardCharsets.UTF_8);
+        final Matcher matcher = PACKAGE.matcher(text);
+        if (!matcher.find()) {
+            return "<none>";
+        }
+        assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file));
+        return matcher.group(1);
+    }
+
+    private static List<String> imports(final Path file) throws IOException {
+        return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8));
+    }
+
+    private static String firstMatch(final Pattern pattern, final String text) {
+        final List<String> found = allMatches(pattern, text);
+        return found.isEmpty() ? "<none>" : found.get(0);
+    }
+
+    private static List<String> allMatches(final Pattern pattern, final String text) {
+        final List<String> found = new ArrayList<>();
+        final Matcher matcher = pattern.matcher(text);
+        while (matcher.find()) {
+            found.add(matcher.group(1));
+        }
+        return found;
+    }
+
+    private static int countMatches(final Pattern pattern, final String text) {
+        return allMatches(pattern, text).size();
+    }
+
+    private static String relativize(final Path path) {
+        return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString();
+    }
+}
diff --git a/Modules/renderer/Documentation/index.org b/Modules/renderer/Documentation/index.org
new file mode 100644 (file)
index 0000000..6921b7f
--- /dev/null
@@ -0,0 +1,120 @@
+#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme
+#+TITLE: Renderer
+#+LANGUAGE: en
+
+:PROPERTIES:
+:CUSTOM_ID: renderer-page
+:END:
+
+#+OPTIONS: H:20 num:nil author:nil
+
+[[file:../../../Documentation/index.html#outline-container-renderer][<- Back to index]]
+
+* What it owns
+:PROPERTIES:
+:CUSTOM_ID: renderer-owns
+:END:
+
+The algorithms that turn a world into pixels: the frame buffer, the projection
+from a camera pose and a viewport to screen coordinates, culling, and
+rasterisation.
+
+It owns no scene data. Geometry, the object tree, triangle storage, the
+primitives and the camera pose all live in =Modules/world=; the renderer reads
+them and produces an image.
+
+| Seam          | Owns                                                     |
+|---------------+----------------------------------------------------------|
+| frame buffer  | the pixels and the depth buffer being written             |
+| transform     | camera pose + viewport in, screen coordinates out         |
+| cull          | backface verdict, viewport rejection, per-node bounds     |
+| raster        | tile fill, depth test, flat colour                        |
+
+* A pose is data, a projection is not
+:PROPERTIES:
+:CUSTOM_ID: renderer-pose
+:END:
+
+The camera's position and rotation are world data. The =scale = width / 3=
+convention that turns them into screen coordinates is here, because only the
+renderer knows how wide the picture is. If that constant moved into the world,
+the world would need a viewport and the two modules would collapse into one.
+
+* Invariants
+:PROPERTIES:
+:CUSTOM_ID: renderer-invariants
+:END:
+
+- Local coordinates arrive already composed. By the time a triangle reaches the
+  transform stage it is in world space; anything else is a bug in the world, not
+  a convention to accommodate here.
+- A frame is produced whole. Nothing half-written is visible to another thread,
+  so a reader either sees the previous frame or the next one.
+- The same world and the same pose produce the same pixels. A rendering feature
+  that is not deterministic cannot be verified.
+
+* What the build checks
+:PROPERTIES:
+:CUSTOM_ID: renderer-checks
+:END:
+
+The descriptor is =module eu.svjatoslav.aukio.render= with exactly one
+requirement, =eu.svjatoslav.aukio.world=; naming any other engine module is a
+compile error.
+
+=ModuleShapeTest= adds what the compiler cannot: one package, files under 800
+lines, imports that reach into the world and no further, an export that is the
+module's own package, and the requirement list itself.
+
+=RendererTest= pins the picture rather than the code: it renders the first
+engine's minimal scene - one 100-unit red box, a level camera a hundred units up
+and three hundred back - at 1920x1080 and asserts the silhouette the first
+engine actually drew, the covered area to within two percent, one flat colour,
+and byte-identical pixels across two runs. It also checks that a nearer surface
+wins, and that a triangle crossing the near plane keeps the part in front of it.
+A projection convention, a field of view or a depth-test change moves the box and
+fails the test.
+
+#+begin_src sh
+export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
+./gradlew --offline :renderer:test    # module alone, other modules absent
+#+end_src
+
+* Implemented today
+:PROPERTIES:
+:CUSTOM_ID: renderer-implemented
+:END:
+
+The frame buffer and the three stages, enough to draw a flat-shaded scene:
+
+| Type          | What it does                                                  |
+|---------------+---------------------------------------------------------------|
+| =FrameBuffer= | pixels plus reciprocal depth; zero depth means uncovered       |
+| =Projection=  | camera pose and picture size in, screen coordinates out        |
+| =Cull=        | drops a projected polygon whose bounds miss the picture        |
+| =Raster=      | flat-colour fill with a depth test, triangle or clipped quad   |
+| =Renderer=    | one frame: clip to the near plane, project, cull, rasterise     |
+
+The near plane is inside =Renderer= rather than in =Cull= because a clip
+produces new vertices and a cull produces a verdict. Clipping is
+Sutherland-Hodgman in camera space: a triangle crossing the plane becomes a quad
+rather than a hole.
+
+There is no backface verdict yet, and that is deliberate. The first engine did
+not cull backfaces either - it let the depth buffer resolve a closed solid - and
+no mesh in the world module carries a winding contract that a verdict could be
+judged against. The condition on adding one is the contract, not the algorithm.
+
+The renderer is single threaded. A frame that is a few hundred triangles wide
+buys more from reproducible ordering than from a pool, and a renderer that owns
+a pool would be a second place deciding how much CPU this process may use - the
+scheduler's job.
+
+* Deliberately not here
+:PROPERTIES:
+:CUSTOM_ID: renderer-not-here
+:END:
+
+Global illumination, CSG, OBJ loading, SDF text, the octree raytracer, stereo and
+the developer tools. Each is a separate module built on top of the world and the
+renderer, so both keep compiling and testing with them absent.
diff --git a/Modules/renderer/build.gradle b/Modules/renderer/build.gradle
new file mode 100644 (file)
index 0000000..7ef62ea
--- /dev/null
@@ -0,0 +1,9 @@
+// The algorithms that turn a world into pixels: projection, culling and
+// rasterisation. It knows the world, the world does not know it.
+
+dependencies {
+    // api, not implementation: a caller of the renderer passes world types
+    // (scene, camera pose) straight through, so those types are part of this
+    // module's own surface.
+    api project(':world')
+}
diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Cull.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Cull.java
new file mode 100644 (file)
index 0000000..47fa765
--- /dev/null
@@ -0,0 +1,43 @@
+package eu.svjatoslav.aukio.render;
+
+/**
+ * What must not reach the raster stage.
+ *
+ * <p>Today that is one verdict: a projected polygon whose bounding box misses
+ * the picture entirely. The near plane is handled earlier, by the clip in
+ * {@link Renderer}, because a clip produces new vertices and a cull does
+ * not.</p>
+ *
+ * <p>There is deliberately no backface verdict here yet. The first engine never
+ * culled backfaces either - it let the depth buffer resolve a closed solid - and
+ * no mesh in the world module carries a winding contract to judge against.
+ * Adding one without that contract would be a rule the data cannot keep.</p>
+ */
+public final class Cull {
+
+    private Cull() {
+    }
+
+    /**
+     * @param xs    screen-space x of the polygon's vertices
+     * @param ys    screen-space y of the polygon's vertices
+     * @param count how many vertices the polygon has, 3 or 4
+     * @return whether any part of it can land on a pixel
+     */
+    public static boolean onScreen(final double[] xs, final double[] ys, final int count,
+                                   final int width, final int height) {
+        double minX = xs[0];
+        double maxX = xs[0];
+        double minY = ys[0];
+        double maxY = ys[0];
+        for (int i = 1; i < count; i++) {
+            minX = Math.min(minX, xs[i]);
+            maxX = Math.max(maxX, xs[i]);
+            minY = Math.min(minY, ys[i]);
+            maxY = Math.max(maxY, ys[i]);
+        }
+        // pixel centres live at x + 0.5, so the boxes overlap the picture when
+        // the vertex range crosses it by more than one pixel on either side
+        return maxX > 0 && minX < width && maxY > 0 && minY < height;
+    }
+}
diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/FrameBuffer.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/FrameBuffer.java
new file mode 100644 (file)
index 0000000..0e6c59d
--- /dev/null
@@ -0,0 +1,90 @@
+package eu.svjatoslav.aukio.render;
+
+import java.util.Arrays;
+
+/**
+ * The pixels and the depth buffer one frame is painted into.
+ *
+ * <p>Depth is stored as a reciprocal, one over the camera-space z: it grows
+ * towards the viewer, so a nearer fragment has the larger value and the test is
+ * a plain "greater than". Zero means nothing has been written, which is why
+ * clearing a buffer is a fill and a zeroing rather than a pass over the depth
+ * array with a far-plane value.</p>
+ *
+ * <p>A buffer is not thread safe by design: one renderer owns one buffer for
+ * the duration of a frame, and only the finished pixels are ever handed on.</p>
+ *
+ * <p>The pixel array may be supplied by the caller, which is what lets a host
+ * render straight into the raster of an image it will blit: no copy per frame
+ * and no allocation per frame. The depth array is always the buffer's own,
+ * because nothing outside wants to see it.</p>
+ */
+public final class FrameBuffer {
+
+    private final int width;
+    private final int height;
+    private final int[] pixels;
+    private final double[] reciprocalDepth;
+
+    public FrameBuffer(final int width, final int height) {
+        this(width, height, new int[requireSaneSize(width, height)]);
+    }
+
+    /**
+     * @param pixels the array the renderer writes into; a host that renders into
+     *               an image's own raster passes it here and then blits it with
+     *               no copy at all
+     */
+    public FrameBuffer(final int width, final int height, final int[] pixels) {
+        requireSaneSize(width, height);
+        if (pixels.length != width * height) {
+            throw new IllegalArgumentException(
+                    "the pixel array must hold exactly " + (width * height) + " pixels: " + pixels.length);
+        }
+        this.width = width;
+        this.height = height;
+        this.pixels = pixels;
+        this.reciprocalDepth = new double[width * height];
+    }
+
+    private static int requireSaneSize(final int width, final int height) {
+        if (width <= 0 || height <= 0) {
+            throw new IllegalArgumentException("an empty buffer cannot be rendered into: " + width + "x" + height);
+        }
+        return width * height;
+    }
+
+    public int width() {
+        return width;
+    }
+
+    public int height() {
+        return height;
+    }
+
+    /** The pixels, row-major, in ARGB. Writing to this array is the caller's risk. */
+    public int[] pixels() {
+        return pixels;
+    }
+
+    public int pixelAt(final int x, final int y) {
+        return pixels[y * width + x];
+    }
+
+    /** Reciprocal depth at a pixel; 0 means the pixel was never covered. */
+    public double depthAt(final int x, final int y) {
+        return reciprocalDepth[y * width + x];
+    }
+
+    public void clear(final int argb) {
+        Arrays.fill(pixels, argb);
+        Arrays.fill(reciprocalDepth, 0);
+    }
+
+    /** Writes a fragment without a depth test; the raster decides what to keep. */
+    void write(final int x, final int y, final int argb, final double depth) {
+        final int index = y * width + x;
+        pixels[index] = argb;
+        reciprocalDepth[index] = depth;
+    }
+}
diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Projection.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Projection.java
new file mode 100644 (file)
index 0000000..65386f8
--- /dev/null
@@ -0,0 +1,96 @@
+package eu.svjatoslav.aukio.render;
+
+import eu.svjatoslav.aukio.world.Camera;
+
+/**
+ * Camera pose plus picture size in, screen coordinates out.
+ *
+ * <p>The pose arrives from the world; the width arrives from the frame, and so
+ * does the one constant this module owns: the camera's scale is a third of the
+ * picture width. If that constant lived in the world, the world would need a
+ * viewport and the two modules would be one.</p>
+ *
+ * <p>The transform is the one the previous engines used, kept because renders
+ * across engines are compared to the pixel: subtract the eye, turn the world by
+ * the inverse yaw about +Y, then by the pitch about +X so that the camera's
+ * forward direction ends up on +Z. Screen y grows downwards, hence the
+ * subtraction in {@code sy}.</p>
+ */
+public final class Projection {
+
+    private static final double SCALE_PER_WIDTH = 1.0 / 3.0;
+
+    private final double eyeX;
+    private final double eyeY;
+    private final double eyeZ;
+    private final double cosYaw;
+    private final double sinYaw;
+    private final double cosPitch;
+    private final double sinPitch;
+    private final double scale;
+    private final double centerX;
+    private final double centerY;
+    private final int width;
+    private final int height;
+
+    public Projection(final Camera camera, final int width, final int height) {
+        if (width <= 0 || height <= 0) {
+            throw new IllegalArgumentException("a projection needs a picture: " + width + "x" + height);
+        }
+        this.width = width;
+        this.height = height;
+        this.eyeX = camera.position().x();
+        this.eyeY = camera.position().y();
+        this.eyeZ = camera.position().z();
+        this.cosYaw = Math.cos(camera.yaw());
+        this.sinYaw = Math.sin(camera.yaw());
+        this.cosPitch = Math.cos(camera.pitch());
+        this.sinPitch = Math.sin(camera.pitch());
+        this.scale = width * SCALE_PER_WIDTH;
+        this.centerX = width / 2.0;
+        this.centerY = height / 2.0;
+    }
+
+    /** Stored as written, because it is the engine's field of view, not a tuning knob. */
+    public double scale() {
+        return scale;
+    }
+
+    public int width() {
+        return width;
+    }
+
+    public int height() {
+        return height;
+    }
+
+    /**
+     * World space to camera space: x right, y up, z forward.
+     *
+     * @param out receives x, y, z
+     */
+    public void toCameraSpace(final double worldX, final double worldY, final double worldZ,
+                              final double[] out) {
+        final double dx = worldX - eyeX;
+        final double dy = worldY - eyeY;
+        final double dz = worldZ - eyeZ;
+        final double x = dx * cosYaw - dz * sinYaw;
+        final double z = dx * sinYaw + dz * cosYaw;
+        out[0] = x;
+        out[1] = dy * cosPitch - z * sinPitch;
+        out[2] = dy * sinPitch + z * cosPitch;
+    }
+
+    /**
+     * Camera space to screen space.
+     *
+     * @param camera a vertex in front of the camera; z must be positive
+     * @param out    receives screen x, screen y and reciprocal depth
+     */
+    public void toScreenSpace(final double[] camera, final double[] out) {
+        final double reciprocal = 1.0 / camera[2];
+        out[0] = centerX + camera[0] * reciprocal * scale;
+        out[1] = centerY - camera[1] * reciprocal * scale;
+        out[2] = reciprocal;
+    }
+}
diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Raster.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Raster.java
new file mode 100644 (file)
index 0000000..64d3c5d
--- /dev/null
@@ -0,0 +1,89 @@
+package eu.svjatoslav.aukio.render;
+
+/**
+ * Flat-coloured triangle and quad fill with a depth test.
+ *
+ * <p>A polygon is filled by testing every pixel centre inside its bounding box
+ * against the polygon's edges, interpolating reciprocal depth from the same
+ * barycentric weights, and writing the pixel when it is nearer than whatever is
+ * already there. Pixels whose centre lies exactly on an edge count as inside
+ * for all polygons that share that edge; the depth test makes the second write
+ * harmless, and the alternative - dropping them - leaves one-pixel seams
+ * through a closed solid.</p>
+ */
+public final class Raster {
+
+    private Raster() {
+    }
+
+    /**
+     * @param xs    screen-space x per vertex
+     * @param ys    screen-space y per vertex
+     * @param depth reciprocal depth per vertex
+     * @param count 3 for a triangle, 4 for a clipped quad
+     * @param argb  flat colour
+     */
+    public static void fill(final FrameBuffer frame, final double[] xs, final double[] ys,
+                            final double[] depth, final int count, final int argb) {
+        if (count < 3) {
+            return;
+        }
+        final double area = area(xs, ys, count);
+        if (area == 0) {
+            return;
+        }
+        final boolean positive = area > 0;
+        double minX = xs[0];
+        double maxX = xs[0];
+        double minY = ys[0];
+        double maxY = ys[0];
+        for (int i = 1; i < count; i++) {
+            minX = Math.min(minX, xs[i]);
+            maxX = Math.max(maxX, xs[i]);
+            minY = Math.min(minY, ys[i]);
+            maxY = Math.max(maxY, ys[i]);
+        }
+        final int firstX = (int) Math.max(0, Math.ceil(minX - 0.5));
+        final int lastX = (int) Math.min(frame.width() - 1, Math.floor(maxX - 0.5));
+        final int firstY = (int) Math.max(0, Math.ceil(minY - 0.5));
+        final int lastY = (int) Math.min(frame.height() - 1, Math.floor(maxY - 0.5));
+        final double[] edges = new double[4];
+        for (int y = firstY; y <= lastY; y++) {
+            final double pixelY = y + 0.5;
+            for (int x = firstX; x <= lastX; x++) {
+                final double pixelX = x + 0.5;
+                boolean inside = true;
+                for (int i = 0; i < count; i++) {
+                    final int j = (i + 1) % count;
+                    final double edge = (xs[j] - xs[i]) * (pixelY - ys[i])
+                            - (ys[j] - ys[i]) * (pixelX - xs[i]);
+                    if (positive ? edge < 0 : edge > 0) {
+                        inside = false;
+                        break;
+                    }
+                    edges[i] = edge;
+                }
+                if (!inside) {
+                    continue;
+                }
+                double interpolated = 0;
+                for (int i = 0; i < count; i++) {
+                    interpolated += (edges[i] / area) * depth[i];
+                }
+                if (interpolated > frame.depthAt(x, y)) {
+                    frame.write(x, y, argb, interpolated);
+                }
+            }
+        }
+    }
+
+    /** Twice the signed area; only its sign and the weights built from it are used. */
+    private static double area(final double[] xs, final double[] ys, final int count) {
+        double total = 0;
+        for (int i = 0; i < count; i++) {
+            final int j = (i + 1) % count;
+            total += xs[i] * ys[j] - xs[j] * ys[i];
+        }
+        return total;
+    }
+}
diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Renderer.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Renderer.java
new file mode 100644 (file)
index 0000000..9d62628
--- /dev/null
@@ -0,0 +1,95 @@
+package eu.svjatoslav.aukio.render;
+
+import eu.svjatoslav.aukio.world.Camera;
+import eu.svjatoslav.aukio.world.Scene;
+
+/**
+ * One frame, start to finish: compose the scene, project it, drop what cannot
+ * be seen, rasterise what is left.
+ *
+ * <p>Single threaded on purpose. A frame is small enough that the ordering
+ * guarantees are worth more than the threads, and the scheduler module is where
+ * a parallel dispatch will be argued for; a renderer that owns a pool would be
+ * a second place deciding how much CPU this process may use.</p>
+ *
+ * <p>The same scene and the same camera produce the same pixels: the walk order
+ * comes from the scene, the geometry is read, never mutated, and nothing here
+ * consults a clock or a random source.</p>
+ */
+public final class Renderer {
+
+    /** Everything nearer than this is clipped away; a vertex behind the eye cannot be projected. */
+    private static final double NEAR = 0.1;
+
+    private Renderer() {
+    }
+
+    public static void render(final Scene scene, final Camera camera, final FrameBuffer frame) {
+        final Projection projection = new Projection(camera, frame.width(), frame.height());
+        final double[][] cameraSpace = new double[3][3];
+        final double[][] clipped = new double[4][3];
+        final double[] screenX = new double[4];
+        final double[] screenY = new double[4];
+        final double[] screenDepth = new double[4];
+        final double[] vertex = new double[3];
+
+        scene.forEachTriangle((x0, y0, z0, x1, y1, z1, x2, y2, z2, argb) -> {
+            projection.toCameraSpace(x0, y0, z0, cameraSpace[0]);
+            projection.toCameraSpace(x1, y1, z1, cameraSpace[1]);
+            projection.toCameraSpace(x2, y2, z2, cameraSpace[2]);
+            final int count = clipToNearPlane(cameraSpace, clipped);
+            if (count < 3) {
+                return;
+            }
+            for (int i = 0; i < count; i++) {
+                projection.toScreenSpace(clipped[i], vertex);
+                screenX[i] = vertex[0];
+                screenY[i] = vertex[1];
+                screenDepth[i] = vertex[2];
+            }
+            if (!Cull.onScreen(screenX, screenY, count, frame.width(), frame.height())) {
+                return;
+            }
+            Raster.fill(frame, screenX, screenY, screenDepth, count, argb);
+        });
+    }
+
+    /**
+     * Sutherland-Hodgman against the near plane, in camera space.
+     *
+     * <p>A triangle crossing the plane becomes a quad - three vertices and one
+     * intersection - and that quad is what the raster then fills. Dropping a
+     * straddling triangle instead would leave the hole the previous engine had
+     * to fix by hand.</p>
+     *
+     * @param triangle the three camera-space vertices
+     * @param out      receives at most four clipped vertices
+     * @return the number of vertices written, 0 to 4
+     */
+    private static int clipToNearPlane(final double[][] triangle, final double[][] out) {
+        int count = 0;
+        for (int i = 0; i < 3; i++) {
+            final double[] current = triangle[i];
+            final double[] next = triangle[(i + 1) % 3];
+            final boolean currentInside = current[2] >= NEAR;
+            final boolean nextInside = next[2] >= NEAR;
+            if (currentInside) {
+                copy(current, out[count++]);
+            }
+            if (currentInside != nextInside) {
+                final double t = (NEAR - current[2]) / (next[2] - current[2]);
+                out[count][0] = current[0] + t * (next[0] - current[0]);
+                out[count][1] = current[1] + t * (next[1] - current[1]);
+                out[count][2] = NEAR;
+                count++;
+            }
+        }
+        return count;
+    }
+
+    private static void copy(final double[] from, final double[] to) {
+        to[0] = from[0];
+        to[1] = from[1];
+        to[2] = from[2];
+    }
+}
diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/package-info.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/package-info.java
new file mode 100644 (file)
index 0000000..9b9f288
--- /dev/null
@@ -0,0 +1,26 @@
+/**
+ * The renderer: algorithms that turn a world into pixels.
+ *
+ * <p>Nothing here is scene data. Geometry, transforms, the object tree, the
+ * primitives and the camera pose all belong to {@code
+ * eu.svjatoslav.aukio.world}; this module reads them and produces an image.
+ * The distinction that keeps it honest: a pose is world data, a projection is
+ * not - turning a pose into screen coordinates needs the viewport, and the
+ * viewport is a property of the image being painted.</p>
+ *
+ * <ul>
+ *   <li>frame buffer - the pixels and the depth buffer being written.</li>
+ *   <li>transform - camera pose and viewport in, screen coordinates and depth
+ *       out. The camera's {@code scale = width / 3} convention lives here,
+ *       because only this module knows how wide the picture is.</li>
+ *   <li>cull - backface verdict, viewport rejection, and the per-node bounding
+ *       test that uses the world's boxes.</li>
+ *   <li>raster - tile fill, depth test, flat colour.</li>
+ * </ul>
+ *
+ * <p>Two rules carry over from the shell and belong here instead: a frame is
+ * produced whole, never half-written to something another thread can see, and
+ * the same world and pose must produce the same pixels - a rendering feature is
+ * verifiable only if its output is deterministic.</p>
+ */
+package eu.svjatoslav.aukio.render;
diff --git a/Modules/renderer/src/main/java/module-info.java b/Modules/renderer/src/main/java/module-info.java
new file mode 100644 (file)
index 0000000..da204f9
--- /dev/null
@@ -0,0 +1,15 @@
+/**
+ * The renderer module: the algorithms that turn a world into pixels.
+ *
+ * <p>Projection, culling, rasterisation and the frame buffer it paints into.
+ * The scene itself - geometry, transforms, the object tree, the primitives -
+ * lives in {@code eu.svjatoslav.aukio.world}, so this module reads the world
+ * and produces pixels, and the world has never heard of it.</p>
+ */
+module eu.svjatoslav.aukio.render {
+    // transitive: the renderer's own API takes world types (a scene and a pose
+    // in, pixels out), so anything that requires the renderer needs the world
+    // to name those types.
+    requires transitive eu.svjatoslav.aukio.world;
+    exports eu.svjatoslav.aukio.render;
+}
diff --git a/Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/ModuleShapeTest.java b/Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/ModuleShapeTest.java
new file mode 100644 (file)
index 0000000..fbed070
--- /dev/null
@@ -0,0 +1,176 @@
+package eu.svjatoslav.aukio.render;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * The module's shape, checked rather than promised: one public package, one
+ * export, no file longer than the agreed limit, and no import of another module
+ * in this tree.
+ *
+ * <p>These are the rules that keep the renderer from turning into the whole
+ * engine again. Rules that live only in prose are the ones that get broken
+ * first, so they live here as a build failure.</p>
+ */
+class ModuleShapeTest {
+
+    private static final int MAX_FILE_LINES = 800;
+
+    private static final Path SOURCE_ROOT = Path.of("src", "main", "java");
+
+    private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.render";
+
+    private static final String WORLD_PACKAGE = "eu.svjatoslav.aukio.world";
+
+    private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE);
+
+    private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    @Test
+    void sourcesLiveInExactlyOnePackage() throws IOException {
+        final List<String> problems = new ArrayList<>();
+        for (final Path file : sources()) {
+            final String declared = declaredPackage(file);
+            if (!MODULE_PACKAGE.equals(declared)) {
+                problems.add(relativize(file) + " declares package " + declared);
+                continue;
+            }
+            final Path directory = file.getParent();
+            if (!directory.endsWith(Path.of("", MODULE_PACKAGE.split("\\.")))) {
+                problems.add(relativize(file) + " sits in " + relativize(directory)
+                        + " but declares " + MODULE_PACKAGE);
+            }
+        }
+        assertTrue(problems.isEmpty(), "one public package per module, found: " + problems);
+    }
+
+    @Test
+    void theDescriptorExportsThatOnePackageAndRequiresTheWorldOnly() throws IOException {
+        final String descriptor = descriptor();
+        assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor),
+                "the module name is derived from its package, so a requires clause reads naturally");
+        final List<String> exports = allMatches(EXPORT, descriptor);
+        assertTrue(exports.size() <= 1, "the module exports at most its one public package, found: " + exports);
+        for (final String exported : exports) {
+            assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported");
+        }
+        final List<String> required = allMatches(REQUIRES, descriptor);
+        assertTrue(required.contains(WORLD_PACKAGE),
+                "the renderer draws the world, so its descriptor says so: " + required);
+        for (final String module : required) {
+            final boolean ours = module.startsWith("eu.svjatoslav.aukio.");
+            if (ours && !module.equals(WORLD_PACKAGE)) {
+                fail("the renderer requires no engine module but the world, found: " + module);
+            }
+        }
+    }
+
+    @Test
+    void noFileExceedsTheLineLimit() throws IOException {
+        final List<String> tooLong = new ArrayList<>();
+        for (final Path file : sources()) {
+            final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size();
+            if (lines > MAX_FILE_LINES) {
+                tooLong.add(relativize(file) + " " + lines + " lines");
+            }
+        }
+        assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong);
+    }
+
+    @Test
+    void importsReachIntoTheWorldAndNoFurther() throws IOException {
+        final List<String> foreign = new ArrayList<>();
+        for (final Path file : sources()) {
+            for (final String imported : imports(file)) {
+                if (imported.startsWith("eu.svjatoslav.aukio.")
+                        && !imported.startsWith(MODULE_PACKAGE)
+                        && !imported.startsWith(WORLD_PACKAGE)) {
+                    foreign.add(relativize(file) + " imports " + imported);
+                }
+            }
+        }
+        assertTrue(foreign.isEmpty(), "the renderer may see the world and nothing else: " + foreign);
+    }
+
+    @Test
+    void theModuleItselfHasSources() throws IOException {
+        assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous");
+    }
+
+    private static List<Path> sources() throws IOException {
+        if (!Files.isDirectory(SOURCE_ROOT)) {
+            fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist");
+        }
+        try (Stream<Path> walk = Files.walk(SOURCE_ROOT)) {
+            return walk.filter(Files::isRegularFile)
+                    .filter(path -> path.toString().endsWith(".java"))
+                    .filter(path -> !path.getFileName().toString().equals("module-info.java"))
+                    .sorted()
+                    .toList();
+        }
+    }
+
+    private static String descriptor() throws IOException {
+        final Path file = SOURCE_ROOT.resolve("module-info.java");
+        if (!Files.isRegularFile(file)) {
+            fail("the module declares no descriptor: " + relativize(file) + " is missing");
+        }
+        return Files.readString(file, StandardCharsets.UTF_8);
+    }
+
+    private static String declaredPackage(final Path file) throws IOException {
+        final String text = Files.readString(file, StandardCharsets.UTF_8);
+        final Matcher matcher = PACKAGE.matcher(text);
+        if (!matcher.find()) {
+            return "<none>";
+        }
+        assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file));
+        return matcher.group(1);
+    }
+
+    private static List<String> imports(final Path file) throws IOException {
+        return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8));
+    }
+
+    private static String firstMatch(final Pattern pattern, final String text) {
+        final List<String> found = allMatches(pattern, text);
+        return found.isEmpty() ? "<none>" : found.get(0);
+    }
+
+    private static List<String> allMatches(final Pattern pattern, final String text) {
+        final List<String> found = new ArrayList<>();
+        final Matcher matcher = pattern.matcher(text);
+        while (matcher.find()) {
+            found.add(matcher.group(1));
+        }
+        return found;
+    }
+
+    private static int countMatches(final Pattern pattern, final String text) {
+        return allMatches(pattern, text).size();
+    }
+
+    private static String relativize(final Path path) {
+        return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString();
+    }
+}
diff --git a/Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/RendererTest.java b/Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/RendererTest.java
new file mode 100644 (file)
index 0000000..d479fe7
--- /dev/null
@@ -0,0 +1,198 @@
+package eu.svjatoslav.aukio.render;
+
+import eu.svjatoslav.aukio.world.Boxes;
+import eu.svjatoslav.aukio.world.Camera;
+import eu.svjatoslav.aukio.world.Mesh;
+import eu.svjatoslav.aukio.world.Node;
+import eu.svjatoslav.aukio.world.Scene;
+import eu.svjatoslav.aukio.world.Vec3;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * One frame of the first scene, checked against the picture the first engine
+ * actually drew.
+ *
+ * <p>The silhouette numbers are measurements of that engine's golden image at
+ * the same size and pose, so this test is a cross-engine comparison and not a
+ * self-portrait: if the projection convention, the depth test or the field of
+ * view drifts, the box lands somewhere else.</p>
+ */
+class RendererTest {
+
+    private static final int WIDTH = 1920;
+    private static final int HEIGHT = 1080;
+    private static final int BACKGROUND = 0xFF000000;
+    private static final int RED = 0xFFFF0000;
+
+    /** Measured on the first engine's 1920x1080 minimal-scene golden. */
+    private static final int GOLDEN_MIN_X = 832;
+    private static final int GOLDEN_MAX_X = 1087;
+    private static final int GOLDEN_MIN_Y = 632;
+    private static final int GOLDEN_MAX_Y = 924;
+    private static final int GOLDEN_PIXELS = 73548;
+
+    @Test
+    void theBoxLandsWhereTheFirstEngineDrewIt() {
+        final FrameBuffer frame = renderBox();
+        assertEquals(GOLDEN_MIN_X, leftmostRed(frame), 1, "left edge");
+        assertEquals(GOLDEN_MAX_X, rightmostRed(frame), 1, "right edge");
+        assertEquals(GOLDEN_MIN_Y, topmostRed(frame), 1, "top edge");
+        assertEquals(GOLDEN_MAX_Y, bottommostRed(frame), 1, "bottom edge");
+    }
+
+    @Test
+    void theBoxCoversTheSameAreaWithinTwoPercent() {
+        final FrameBuffer frame = renderBox();
+        final int covered = redPixels(frame);
+        final double drift = Math.abs(covered - GOLDEN_PIXELS) / (double) GOLDEN_PIXELS;
+        assertTrue(drift < 0.02, "covered " + covered + " pixels against " + GOLDEN_PIXELS
+                + " in the golden image, a drift of " + String.format("%.3f%%", drift * 100));
+    }
+
+    @Test
+    void theBoxIsOneFlatColour() {
+        final FrameBuffer frame = renderBox();
+        for (int y = 0; y < HEIGHT; y++) {
+            for (int x = 0; x < WIDTH; x++) {
+                final int pixel = frame.pixelAt(x, y);
+                if (pixel != BACKGROUND) {
+                    assertEquals(RED, pixel, "shaded pixel at " + x + "," + y);
+                }
+            }
+        }
+    }
+
+    @Test
+    void aFrameBufferRendersIntoTheArrayItWasGiven() {
+        // a host that renders into an image's own raster passes that array here
+        final int[] pixels = new int[640 * 480];
+        final FrameBuffer frame = new FrameBuffer(640, 480, pixels);
+        frame.clear(BACKGROUND);
+        assertEquals(BACKGROUND, pixels[0], "clearing writes the caller's array");
+        Renderer.render(new Scene(Node.mesh(
+                Boxes.box(new Vec3(-50, -50, -50), new Vec3(50, 50, 50), RED))),
+                Camera.of(new Vec3(0, 100, -300), 0, 0), frame);
+        int red = 0;
+        for (final int pixel : pixels) {
+            if (pixel == RED) {
+                red++;
+            }
+        }
+        assertTrue(red > 0, "the render landed in the caller's array, not a copy of it");
+        assertEquals(pixels, frame.pixels(), "the buffer exposes the array it was given");
+    }
+
+    @Test
+    void theSameSceneAndPoseProduceTheSamePixels() {
+        final FrameBuffer first = renderBox();
+        final FrameBuffer second = renderBox();
+        assertArrayEquals(first.pixels(), second.pixels(), "rendering is deterministic");
+    }
+
+    @Test
+    void theNearerSurfaceWins() {
+        // a small red box in front of a large blue plane: the box hides the
+        // plane where they overlap, the plane shows everywhere else
+        final Mesh bluePlane = Mesh.builder()
+                .quad(new Vec3(-5000, -5000, 500), new Vec3(5000, -5000, 500),
+                        new Vec3(5000, 5000, 500), new Vec3(-5000, 5000, 500), 0xFF0000FF)
+                .build();
+        final Scene scene = new Scene(Node.group(eu.svjatoslav.aukio.world.Transform.IDENTITY,
+                Node.of(eu.svjatoslav.aukio.world.Transform.of(new Vec3(0, 0, 500 - 50), 0, 0),
+                        Boxes.box(new Vec3(-50, -50, -50), new Vec3(50, 50, 50), RED)),
+                Node.mesh(bluePlane)));
+        final FrameBuffer frame = new FrameBuffer(WIDTH, HEIGHT);
+        frame.clear(BACKGROUND);
+        Renderer.render(scene, Camera.at(Vec3.ORIGIN), frame);
+        assertEquals(RED, frame.pixelAt(WIDTH / 2, HEIGHT / 2), "the box is in front of the plane");
+        assertEquals(0xFF0000FF, frame.pixelAt(WIDTH / 2, HEIGHT - 2), "the plane fills the rest");
+    }
+
+    @Test
+    void aTriangleCrossingTheNearPlaneKeepsItsVisiblePart() {
+        final Mesh triangle = Mesh.builder()
+                .triangle(new Vec3(-100, -100, 100), new Vec3(100, -100, 100),
+                        new Vec3(0, 100, -310), 0xFF00FF00)
+                .build();
+        final FrameBuffer frame = new FrameBuffer(640, 480);
+        frame.clear(BACKGROUND);
+        Renderer.render(new Scene(Node.mesh(triangle)), Camera.at(Vec3.ORIGIN), frame);
+        int green = 0;
+        for (int y = 0; y < frame.height(); y++) {
+            for (int x = 0; x < frame.width(); x++) {
+                if (frame.pixelAt(x, y) == 0xFF00FF00) {
+                    green++;
+                }
+            }
+        }
+        assertTrue(green > 0, "the part in front of the camera must still be drawn");
+    }
+
+    private static FrameBuffer renderBox() {
+        final Scene scene = new Scene(Node.mesh(
+                Boxes.box(new Vec3(-50, -50, -50), new Vec3(50, 50, 50), RED)));
+        final Camera camera = Camera.of(new Vec3(0, 100, -300), 0, 0);
+        final FrameBuffer frame = new FrameBuffer(WIDTH, HEIGHT);
+        frame.clear(BACKGROUND);
+        Renderer.render(scene, camera, frame);
+        return frame;
+    }
+
+    private static int redPixels(final FrameBuffer frame) {
+        int count = 0;
+        for (int y = 0; y < HEIGHT; y++) {
+            for (int x = 0; x < WIDTH; x++) {
+                if (frame.pixelAt(x, y) == RED) {
+                    count++;
+                }
+            }
+        }
+        return count;
+    }
+
+    private static int leftmostRed(final FrameBuffer frame) {
+        return bound(frame, true);
+    }
+
+    private static int rightmostRed(final FrameBuffer frame) {
+        return bound(frame, false);
+    }
+
+    private static int topmostRed(final FrameBuffer frame) {
+        for (int y = 0; y < HEIGHT; y++) {
+            for (int x = 0; x < WIDTH; x++) {
+                if (frame.pixelAt(x, y) == RED) {
+                    return y;
+                }
+            }
+        }
+        return -1;
+    }
+
+    private static int bottommostRed(final FrameBuffer frame) {
+        for (int y = HEIGHT - 1; y >= 0; y--) {
+            for (int x = 0; x < WIDTH; x++) {
+                if (frame.pixelAt(x, y) == RED) {
+                    return y;
+                }
+            }
+        }
+        return -1;
+    }
+
+    private static int bound(final FrameBuffer frame, final boolean left) {
+        for (int step = 0; step < WIDTH; step++) {
+            final int x = left ? step : WIDTH - 1 - step;
+            for (int y = 0; y < HEIGHT; y++) {
+                if (frame.pixelAt(x, y) == RED) {
+                    return x;
+                }
+            }
+        }
+        return -1;
+    }
+}
diff --git a/Modules/scheduler/Documentation/index.org b/Modules/scheduler/Documentation/index.org
new file mode 100644 (file)
index 0000000..d222045
--- /dev/null
@@ -0,0 +1,78 @@
+#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme
+#+TITLE: Scheduler
+#+LANGUAGE: en
+
+:PROPERTIES:
+:CUSTOM_ID: scheduler-page
+:END:
+
+#+OPTIONS: H:20 num:nil author:nil
+
+[[file:../../../Documentation/index.html#outline-container-scheduler][<- Back to index]]
+
+* What it owns
+:PROPERTIES:
+:CUSTOM_ID: what-it-owns
+:END:
+
+The scheduler is the only component that knows how many worker threads
+the process may use, and the only one that decides which queued work
+runs next.
+
+It is the Java module =eu.svjatoslav.aukio.sched=, declared in
+=src/main/java/module-info.java=, and it exports exactly one package. Any other
+module that wants it must name it in its own descriptor, so the dependency is
+visible in the language, not only in the build file.
+
+* The budget
+:PROPERTIES:
+:CUSTOM_ID: the-budget
+:END:
+
+- The default is 75% of available CPU cores, rounded down and never
+  below 1.
+- The remainder is not waste: JVM threads (GC, JIT, compiler,
+  finalizers) and the OS need to run, and a pool that claims every
+  core starves itself exactly when it matters.
+- It is a policy default, not a property of any machine. Any caller
+  can override it per scheduler with =setThreadCount(int)=.
+
+* Implemented today
+:PROPERTIES:
+:CUSTOM_ID: implemented-today
+:END:
+
+=-= Scheduler holds the budget only.
+
+| Member             | Meaning                                        |
+|--------------------+------------------------------------------------|
+| =Scheduler()=      | Detects the cores, takes 75% of them.          |
+| =threadCount()=    | The current budget, in worker threads.         |
+| =setThreadCount()= | Replaces the budget; refuses anything below 1. |
+
+* The model
+:PROPERTIES:
+:CUSTOM_ID: the-model
+:END:
+
+=Model/FrameGate.tla= models the scheduler's two ordering rules as a state
+machine, before either exists in code: a background item is taken only when no
+frame item is queued, and the frame gate fires once, only after every frame
+item has finished.
+
+| Config                        | What it shows                                    |
+|-------------------------------+--------------------------------------------------|
+| =FrameGate_gate.cfg=          | the intended design: completes with no error     |
+| =FrameGate_buggy_bgfirst.cfg= | violates =NoBadTake=: background taken too early |
+| =FrameGate_buggy_countbg.cfg= | violates =GateNotEarly=: background advances it  |
+
+The buggy configurations are why the gate configuration means anything: an
+invariant that also holds when the scheduler does the wrong thing proves
+nothing.
+
+#+begin_src sh
+Modules/scheduler/Model/check-models.sh   # gate passes, both probes fail as named
+./gradlew -Ptla :scheduler:check         # the gate alone, wired into the build
+#+end_src
+
+
diff --git a/Modules/scheduler/Model/FrameGate.tla b/Modules/scheduler/Model/FrameGate.tla
new file mode 100644 (file)
index 0000000..7b3ad22
--- /dev/null
@@ -0,0 +1,105 @@
+------------------------------ MODULE FrameGate ------------------------------
+(*
+ The scheduler's two ordering rules, modelled before they are implemented.
+
+   F1  a background item is taken only when no frame item is queued
+   F2  the frame gate fires once, and only after every frame item has finished
+   F3  no pre-emption: an item leaves `running` only through Complete
+
+ Bug = "none"     both rules hold
+ Bug = "bgFirst"  a worker may take a background item while frame work waits
+ Bug = "countBg"  a background completion also advances the gate
+
+ A buggy run is not a demonstration, it is the non-vacuity probe: each buggy
+ config must violate the invariant that names its rule.
+*)
+EXTENDS Naturals, FiniteSets, TLC
+
+CONSTANTS Workers, FrameItems, BgItems, Bug
+
+Items == FrameItems \cup BgItems
+
+ASSUME FrameItems # {}
+ASSUME BgItems # {}
+ASSUME FrameItems \cap BgItems = {}
+ASSUME Bug \in {"none", "bgFirst", "countBg"}
+
+\* A worker may ignore the frame queue only on purpose.
+AllowBgFirst == Bug \in {"bgFirst", "countBg"}
+
+VARIABLES queue, running, done, remaining, fired, fires, badTake
+
+vars == <<queue, running, done, remaining, fired, fires, badTake>>
+
+TypeOK ==
+    /\ queue \subseteq Items
+    /\ done \subseteq Items
+    /\ remaining \in 0..Cardinality(FrameItems)
+    /\ fired \in BOOLEAN
+    /\ fires \in 0..1
+    /\ badTake \in BOOLEAN
+    /\ \A w \in Workers : running[w] \in Items \cup {0}
+
+Init ==
+    /\ queue = {}
+    /\ running = [w \in Workers |-> 0]
+    /\ done = {}
+    /\ remaining = Cardinality(FrameItems)
+    /\ fired = FALSE
+    /\ fires = 0
+    /\ badTake = FALSE
+
+Submit(i) ==
+    /\ i \in Items
+    /\ i \notin queue
+    /\ i \notin done
+    /\ \A w \in Workers : running[w] # i
+    /\ queue' = queue \cup {i}
+    /\ UNCHANGED <<running, done, remaining, fired, fires, badTake>>
+
+\* Which queued item may this worker start: frame work first, unless the bug
+\* says otherwise.
+Pool ==
+    IF AllowBgFirst THEN queue
+    ELSE IF queue \cap FrameItems # {} THEN queue \cap FrameItems
+    ELSE queue
+
+Take(w) ==
+    /\ running[w] = 0
+    /\ queue # {}
+    /\ \E i \in Pool :
+         /\ queue' = queue \ {i}
+         /\ running' = [running EXCEPT ![w] = i]
+         /\ badTake' = (badTake \/ (i \in BgItems /\ queue \cap FrameItems # {}))
+         /\ UNCHANGED <<done, remaining, fired, fires>>
+
+Complete(w) ==
+    /\ running[w] # 0
+    /\ LET i == running[w] IN
+       /\ done' = done \cup {i}
+       /\ running' = [running EXCEPT ![w] = 0]
+       /\ remaining' =
+            IF i \in FrameItems THEN remaining - 1
+            ELSE IF Bug = "countBg" THEN remaining - 1
+            ELSE remaining
+       /\ fired' = (fired \/ remaining' = 0)
+       /\ fires' = IF ~fired /\ remaining' = 0 THEN fires + 1 ELSE fires
+       /\ UNCHANGED <<queue, badTake>>
+
+Next ==
+    \/ \E i \in Items : Submit(i)
+    \/ \E w \in Workers : Take(w)
+    \/ \E w \in Workers : Complete(w)
+
+Spec == Init /\ [][Next]_vars /\ WF_vars(Next)
+
+\* F1: no worker ever started background work while frame work was waiting.
+NoBadTake == badTake = FALSE
+
+\* F2: the gate never fires before every frame item is done.
+GateNotEarly == fired => FrameItems \subseteq done
+
+\* F2: the gate fires once, never twice.
+GateOnce == fires <= 1
+
+=============================================================================
diff --git a/Modules/scheduler/Model/FrameGate_buggy_bgfirst.cfg b/Modules/scheduler/Model/FrameGate_buggy_bgfirst.cfg
new file mode 100644 (file)
index 0000000..4169e67
--- /dev/null
@@ -0,0 +1,16 @@
+\* Non-vacuity probe for F1: a worker may start background work while frame work
+\* waits. Expected: NoBadTake is violated.
+CONSTANT Workers = {w1, w2}
+CONSTANT FrameItems = {1, 2}
+CONSTANT BgItems = {3, 4}
+CONSTANT Bug = "bgFirst"
+
+SPECIFICATION Spec
+
+\* Every item finished is a legitimate terminal state, not a deadlock.
+CHECK_DEADLOCK FALSE
+
+INVARIANT TypeOK
+INVARIANT NoBadTake
+INVARIANT GateNotEarly
+INVARIANT GateOnce
diff --git a/Modules/scheduler/Model/FrameGate_buggy_countbg.cfg b/Modules/scheduler/Model/FrameGate_buggy_countbg.cfg
new file mode 100644 (file)
index 0000000..11e3060
--- /dev/null
@@ -0,0 +1,17 @@
+\* Non-vacuity probe for F2 only: a background completion also advances the
+\* gate. NoBadTake is deliberately not listed here — this bug also lets
+\* background work start early, and that violation would mask the one this
+\* config exists to show. Expected: GateNotEarly is violated.
+CONSTANT Workers = {w1, w2}
+CONSTANT FrameItems = {1, 2}
+CONSTANT BgItems = {3, 4}
+CONSTANT Bug = "countBg"
+
+SPECIFICATION Spec
+
+\* Every item finished is a legitimate terminal state, not a deadlock.
+CHECK_DEADLOCK FALSE
+
+INVARIANT TypeOK
+INVARIANT GateNotEarly
+INVARIANT GateOnce
diff --git a/Modules/scheduler/Model/FrameGate_gate.cfg b/Modules/scheduler/Model/FrameGate_gate.cfg
new file mode 100644 (file)
index 0000000..4ca1364
--- /dev/null
@@ -0,0 +1,15 @@
+\* The design as intended: both rules hold. This is the gate config.
+CONSTANT Workers = {w1, w2}
+CONSTANT FrameItems = {1, 2}
+CONSTANT BgItems = {3, 4}
+CONSTANT Bug = "none"
+
+SPECIFICATION Spec
+
+\* Every item finished is a legitimate terminal state, not a deadlock.
+CHECK_DEADLOCK FALSE
+
+INVARIANT TypeOK
+INVARIANT NoBadTake
+INVARIANT GateNotEarly
+INVARIANT GateOnce
diff --git a/Modules/scheduler/Model/check-models.sh b/Modules/scheduler/Model/check-models.sh
new file mode 100755 (executable)
index 0000000..5125605
--- /dev/null
@@ -0,0 +1,43 @@
+#!/bin/sh
+# Runs the scheduler's TLA+ model.
+#
+#   FrameGate_gate.cfg            must finish with no error
+#   FrameGate_buggy_bgfirst.cfg   must violate NoBadTake     (rule F1)
+#   FrameGate_buggy_countbg.cfg   must violate GateNotEarly  (rule F2)
+#
+# A buggy config that passes is a vacuous model: the invariant would hold even
+# if the code did the wrong thing, so it proves nothing.
+set -u
+cd "$(dirname "$0")" || exit 1
+
+fail=0
+
+check() {
+    cfg=$1
+    want=$2
+    out=$(tlc -config "$cfg.cfg" FrameGate 2>&1)
+    if [ "$want" = "pass" ]; then
+        if printf '%s\n' "$out" | grep -q "No error has been found"; then
+            echo "PASS $cfg (no error)"
+        else
+            echo "FAIL $cfg (expected no error)"
+            printf '%s\n' "$out" | tail -5
+            fail=1
+        fi
+    else
+        if printf '%s\n' "$out" | grep -q "Invariant $want is violated"; then
+            echo "PASS $cfg ($want violated as expected)"
+        else
+            echo "FAIL $cfg (expected $want to be violated)"
+            printf '%s\n' "$out" | tail -5
+            fail=1
+        fi
+    fi
+}
+
+check FrameGate_gate pass
+check FrameGate_buggy_bgfirst NoBadTake
+check FrameGate_buggy_countbg GateNotEarly
+
+rm -rf states
+exit $fail
diff --git a/Modules/scheduler/build.gradle b/Modules/scheduler/build.gradle
new file mode 100644 (file)
index 0000000..c4d1070
--- /dev/null
@@ -0,0 +1,17 @@
+// The TLA+ gate for this module's model. It runs the green configuration only:
+// the buggy configurations fail by design and are run by Model/check-models.sh,
+// because a probe that passes proves the invariant is vacuous.
+
+tasks.register('tlaCheck', Exec) {
+    group = 'verification'
+    description = 'Model-checks Model/FrameGate.tla with the gate configuration.'
+    workingDir = layout.projectDirectory.dir('Model')
+    commandLine 'tlc', '-config', 'FrameGate_gate.cfg', 'FrameGate'
+}
+
+// Opt-in, like the Maven profile it replaces: ./gradlew -Ptla check
+if (providers.gradleProperty('tla').isPresent()) {
+    tasks.named('check') {
+        dependsOn tasks.named('tlaCheck')
+    }
+}
diff --git a/Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/Scheduler.java b/Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/Scheduler.java
new file mode 100644 (file)
index 0000000..d21fab0
--- /dev/null
@@ -0,0 +1,53 @@
+package eu.svjatoslav.aukio.sched;
+
+/**
+ * The one owner of the CPU budget.
+ */
+public final class Scheduler {
+
+    /**
+     * The CPU budget: how many worker threads this process may use. This is the
+     * one number the scheduler exists to own — it decides how wide every
+     * parallel subsystem is allowed to be, so nothing else in the process keeps
+     * its own thread count.
+     */
+    private volatile int threads;
+
+    /**
+     * The share of the logical cores a scheduler claims by default.
+     */
+    static final int BUDGET_PERCENT = 75;
+
+    public Scheduler() {
+        this.threads = defaultThreadCount();
+    }
+
+    /** The budget this constructor would pick on this machine. */
+    static int defaultThreadCount() {
+        final int cores = Runtime.getRuntime().availableProcessors();
+        return Math.max(1, cores * BUDGET_PERCENT / 100);
+    }
+
+    /** The current budget, in worker threads. */
+    public int threadCount() {
+        return threads;
+    }
+
+    /**
+     * Changes the budget of an already initialised scheduler.
+     *
+     * @param threads the new budget, in worker threads; must be at least 1
+     * @throws IllegalArgumentException when {@code threads} is below 1
+     */
+    public void setThreadCount(final int threads) {
+        this.threads = requireValid(threads);
+    }
+
+    private static int requireValid(final int threads) {
+        if (threads < 1) {
+            throw new IllegalArgumentException(
+                    "threads must be >= 1: " + threads);
+        }
+        return threads;
+    }
+}
diff --git a/Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/package-info.java b/Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/package-info.java
new file mode 100644 (file)
index 0000000..7a14f45
--- /dev/null
@@ -0,0 +1,5 @@
+/**
+ * CPU scheduler: a fixed thread budget, work items that declare dependencies,
+ * a frame-completion signal, and admission control for optional work.
+ */
+package eu.svjatoslav.aukio.sched;
diff --git a/Modules/scheduler/src/main/java/module-info.java b/Modules/scheduler/src/main/java/module-info.java
new file mode 100644 (file)
index 0000000..b55cce5
--- /dev/null
@@ -0,0 +1,10 @@
+/**
+ * The scheduler module: a fixed thread budget for the whole process.
+ *
+ * <p>One exported package. Nothing else exists to export yet; when the queues
+ * and the frame gate arrive they belong to this same package, because this
+ * module's whole job is the budget and the order work runs in.</p>
+ */
+module eu.svjatoslav.aukio.sched {
+    exports eu.svjatoslav.aukio.sched;
+}
diff --git a/Modules/scheduler/src/test/java/eu/svjatoslav/aukio/sched/SchedulerTest.java b/Modules/scheduler/src/test/java/eu/svjatoslav/aukio/sched/SchedulerTest.java
new file mode 100644 (file)
index 0000000..42dedbe
--- /dev/null
@@ -0,0 +1,43 @@
+package eu.svjatoslav.aukio.sched;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** The budget: what it starts at, what it becomes, what is refused. */
+final class SchedulerTest {
+
+    @Test
+    void aNewSchedulerTakesSeventyFivePercentOfTheCores() {
+        final int cores = Runtime.getRuntime().availableProcessors();
+        final int expected = Math.max(1, cores * Scheduler.BUDGET_PERCENT / 100);
+
+        assertEquals(expected, Scheduler.defaultThreadCount(),
+                "the default is 75% of the logical cores, rounded down");
+        assertEquals(expected, new Scheduler().threadCount());
+        assertTrue(new Scheduler().threadCount() <= cores,
+                "the budget must stay at or below the core count, never above it");
+    }
+
+    @Test
+    void theBudgetCanBeChangedOnAnInitialisedScheduler() {
+        final Scheduler scheduler = new Scheduler();
+        scheduler.setThreadCount(18);
+        assertEquals(18, scheduler.threadCount());
+        scheduler.setThreadCount(3);
+        assertEquals(3, scheduler.threadCount());
+    }
+
+    @Test
+    void aBudgetBelowOneIsRefused() {
+        final Scheduler scheduler = new Scheduler();
+        final int before = scheduler.threadCount();
+
+        assertThrows(IllegalArgumentException.class, () -> scheduler.setThreadCount(0));
+        assertThrows(IllegalArgumentException.class, () -> scheduler.setThreadCount(-4));
+        assertEquals(before, scheduler.threadCount(),
+                "a refused change must not alter the budget");
+    }
+}
diff --git a/Modules/swing/Documentation/index.org b/Modules/swing/Documentation/index.org
new file mode 100644 (file)
index 0000000..ec21d82
--- /dev/null
@@ -0,0 +1,104 @@
+#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme
+#+TITLE: Swing adapter
+#+LANGUAGE: en
+
+:PROPERTIES:
+:CUSTOM_ID: swing-page
+:END:
+
+#+OPTIONS: H:20 num:nil author:nil
+
+[[file:../../../Documentation/index.html#outline-container-swing][<- Back to index]]
+
+* What it owns
+:PROPERTIES:
+:CUSTOM_ID: swing-owns
+:END:
+
+The component a host application puts in its own window, and the render loop
+that feeds it. Everything a desktop application needs to show an Aukio scene,
+and nothing a different host would have to remove.
+
+It is the Java module =eu.svjatoslav.aukio.swing=: it requires
+=eu.svjatoslav.aukio.render= and =java.desktop=, and it is the only engine
+module allowed to require the latter. The renderer never sees this module, so
+the engine stays usable without a window at all - in a test, on a server, or
+under another toolkit.
+
+* What it does not own
+:PROPERTIES:
+:CUSTOM_ID: swing-not-owns
+:END:
+
+- No window of its own. A host that already has a frame, a tab or a split pane
+  needs only the component, so the frame stays the application's business.
+- No scene, camera or passes. Those belong to the world and the renderer; this
+  module only drives them.
+- No navigation policy and no input vocabulary. A frame of input is
+  =Modules/navigation='s record, so a policy can be tested with no toolkit present;
+  the adapter fills that record and calls the driver.
+- No toolkit other than Swing. A different host gets its own adapter module next
+  to this one, not a flag inside it.
+
+* The three rules it exists to keep
+:PROPERTIES:
+:CUSTOM_ID: swing-rules
+:END:
+
+1. The render thread publishes a complete frame by swapping a reference under a
+   lock; the event dispatch thread only copies the published frame. A
+   half-rendered frame must never reach the screen.
+2. Input arrives as events and leaves as events. The component records them, a
+   pass consumes them, and nothing that reads input also consumes it - a mouse
+   delta that is read twice is a delta that is applied twice.
+3. Rendering is on demand. No change to scene, camera or input means no frame is
+   computed, only a cheap poll; a static scene must cost almost nothing while
+   the window is idle.
+
+* What the build checks
+:PROPERTIES:
+:CUSTOM_ID: swing-checks
+:END:
+
+=ModuleShapeTest= holds the shape: one package, files under 800 lines, imports
+that reach into the renderer and the world and nowhere else in the engine, and a
+descriptor that asks for =java.desktop= and the renderer.
+
+#+begin_src sh
+export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
+./gradlew --offline :swing:test    # adapter alone, other modules absent
+#+end_src
+
+* Implemented today
+:PROPERTIES:
+:CUSTOM_ID: swing-implemented
+:END:
+
+=AukioView=, the panel a host embeds: hand it a =Scene=, a =Camera= and - when
+the application wants to move - a =CameraDriver=, call =start()=, and it renders
+on demand on its own daemon thread and blits the finished frame in
+=paintComponent=.
+
+Input is recorded here and applied somewhere else. The key, pointer and wheel
+listeners write into the =InputRecorder= that =Modules/navigation= owns; each
+rendered frame the render thread drains exactly one =ViewInput= and hands it to
+the =CameraDriver= it was given, which returns the pose for that frame. Keys and
+3D-device deflection are levels and survive into every frame; the pointer delta
+and the wheel notches are spent by the frame that reads them. That split is the
+rule the previous engine learned the hard way - a value read and consumed in the
+same place is a value applied twice - and here it is structural rather than a
+convention.
+
+The component takes the focus back whenever its window gains it, because a host
+owns the window and nothing else would hand the keyboard over; a lost focus drops
+every held key, so a key released elsewhere cannot stick. Device deflection
+arrives through =setDeviceMotion=, so a 3D mouse producer is one method call away
+and needs no toolkit knowledge.
+
+Rendering is still on demand: a held key, a pointer movement or a deflected cap
+keeps asking for frames at a fast poll, and an idle window falls back to a slow
+one.
+
+A =JFrame= convenience is absent on purpose - an application that already owns a
+window needs the panel, and the demo applications show what the few lines around
+it look like.
diff --git a/Modules/swing/build.gradle b/Modules/swing/build.gradle
new file mode 100644 (file)
index 0000000..849cf3f
--- /dev/null
@@ -0,0 +1,14 @@
+// The Swing adapter. It is the only engine module allowed to touch java.desktop,
+// which is why it is a module of its own: the renderer stays headless and can
+// run in a test, a server, or any other toolkit.
+
+dependencies {
+    // api, not implementation: a caller of the view passes renderer types
+    // (scene, camera) straight through, so those types are part of this
+    // module's own surface.
+    api project(':renderer')
+    // implementation: the view uses the driver contract and the input record,
+    // but nothing in this module's surface needs a caller to name them - an
+    // application that supplies its own driver requires navigation itself.
+    implementation project(':navigation')
+}
diff --git a/Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/AukioView.java b/Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/AukioView.java
new file mode 100644 (file)
index 0000000..57b613a
--- /dev/null
@@ -0,0 +1,370 @@
+package eu.svjatoslav.aukio.swing;
+
+import eu.svjatoslav.aukio.navigation.CameraDriver;
+import eu.svjatoslav.aukio.navigation.InputRecorder;
+import eu.svjatoslav.aukio.navigation.ViewInput;
+import eu.svjatoslav.aukio.render.FrameBuffer;
+import eu.svjatoslav.aukio.render.Renderer;
+import eu.svjatoslav.aukio.world.Camera;
+import eu.svjatoslav.aukio.world.Scene;
+
+import javax.swing.JPanel;
+import javax.swing.SwingUtilities;
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Window;
+import java.awt.event.FocusAdapter;
+import java.awt.event.FocusEvent;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseMotionAdapter;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.awt.image.BufferedImage;
+import java.awt.image.DataBufferInt;
+import java.awt.image.WritableRaster;
+
+/**
+ * The component a host application drops into its own window.
+ *
+ * <p>It owns no frame, no title and no menu: a host that already has a window, a
+ * tab or a split pane needs only this panel, and the panel needs only a scene, a
+ * camera pose and - when the application wants to move - a {@link CameraDriver}.</p>
+ *
+ * <p>Three rules from the previous engine's shell are kept here rather than
+ * documented and forgotten. The render thread publishes a complete frame by
+ * swapping the reference under a lock, so the event dispatch thread only ever
+ * copies an image that is finished. Nothing renders on the event dispatch
+ * thread, which is what keeps a window responsive while a frame is computed. And
+ * input is recorded here and consumed there: the listeners write keys, pointer
+ * movement and device deflection into a {@link InputRecorder}, the render thread
+ * drains exactly one snapshot per frame and hands it to the driver. Nothing that
+ * records input also applies it, which is why the same pointer delta cannot be
+ * counted twice.</p>
+ *
+ * <p>Rendering stays on demand. A key held, a pointer moving or a 3D device
+ * deflected keeps asking for frames; so does a resize or an explicit
+ * {@link #requestFrame()}. When nothing asks, the loop only wakes up to check.</p>
+ *
+ * <p>Nothing is allocated per frame. Each surface is a small pair of a render
+ * buffer and the image whose own raster the buffer writes into - the same trick
+ * the first engine used: take the image's data buffer and render straight into
+ * it - so publishing a frame is a reference swap and the event dispatch thread
+ * blits an image that already holds the pixels. Three surfaces are kept: one
+ * may be published, one may be mid-blit, and the render thread still has a free
+ * one. They are allocated on a resize and then reused forever.</p>
+ */
+public final class AukioView extends JPanel {
+
+    private static final long serialVersionUID = 1L;
+
+    /** How often an idle view checks whether anything asked for a frame. */
+    private static final int IDLE_POLL_MILLIS = 30;
+
+    /** How often a view that is being steered asks again, so motion looks continuous. */
+    private static final int ACTIVE_POLL_MILLIS = 8;
+
+    /** What a view shows before its first frame is ready. */
+    private static final int EMPTY_ARGB = 0xFF000000;
+
+    /** Longest frame the driver is told about; a stalled window must not teleport the camera. */
+    private static final double MAX_FRAME_SECONDS = 0.25;
+
+    /**
+     * Frames kept ready: one published, one possibly mid-blit, one being drawn.
+     * The count is what makes "never write the image being shown" free to satisfy.
+     */
+    private static final int SURFACES = 3;
+
+    private final Scene scene;
+
+    private final InputRecorder recorder = new InputRecorder();
+
+    private volatile Camera camera;
+
+    private volatile CameraDriver driver;
+
+    private final Object publishLock = new Object();
+
+    /** The last complete frame, or null before the first one. Written under the lock. */
+    private BufferedImage published;
+
+    private volatile boolean requested = true;
+
+    private volatile boolean running;
+
+    /** The image the event dispatch thread is blitting right now, if any. */
+    private volatile BufferedImage presenting;
+
+    // Owned by the event dispatch thread.
+    private WindowAdapter windowFocus;
+    private int pointerX;
+    private int pointerY;
+
+    // Owned by the render thread only.
+    private Surface[] surfaces;
+    private int nextSurface;
+    private int frameWidth;
+    private int frameHeight;
+    private long lastFrameNanos = -1;
+
+    public AukioView(final Scene scene, final Camera camera) {
+        this.scene = scene;
+        this.camera = camera;
+        setOpaque(true);
+        setBackground(Color.BLACK);
+        setFocusable(true);
+        installInputRecording();
+    }
+
+    /** A new pose: the next poll renders exactly one frame. */
+    public void setCamera(final Camera newCamera) {
+        this.camera = newCamera;
+        requested = true;
+    }
+
+    /** The camera policy for this view, or null for a camera that never moves by itself. */
+    public void setDriver(final CameraDriver newDriver) {
+        this.driver = newDriver;
+        requested = true;
+    }
+
+    /**
+     * The current deflection of a 3D device, normalised to -1..1. Written by the
+     * device's own thread; a device that is being held keeps the view rendering
+     * until it is released and reports zero.
+     */
+    public void setDeviceMotion(final double x, final double y, final double z,
+                                final double yaw, final double pitch, final double roll) {
+        recorder.setDeviceMotion(x, y, z, yaw, pitch, roll);
+    }
+
+    /** Asks for one more frame from the current pose and scene. */
+    public void requestFrame() {
+        requested = true;
+    }
+
+    /** Starts the render thread. Calling this twice starts nothing new. */
+    public void start() {
+        if (running) {
+            return;
+        }
+        running = true;
+        final Thread thread = new Thread(this::renderLoop, "aukio-view");
+        thread.setDaemon(true);
+        thread.start();
+    }
+
+    /** Asks the render thread to finish after its current frame. */
+    public void stop() {
+        running = false;
+    }
+
+    @Override
+    public void addNotify() {
+        super.addNotify();
+        // The host owns the window and this component owns no frame, so it
+        // cannot assume it already holds the focus. A request made while the
+        // window is unfocused is refused rather than queued, so the focus is
+        // taken back every time the window itself gains it - otherwise the
+        // keyboard only works after the user happens to click the panel.
+        SwingUtilities.invokeLater(() -> {
+            final Window window = SwingUtilities.getWindowAncestor(this);
+            if (window != null && windowFocus == null) {
+                windowFocus = new WindowAdapter() {
+                    @Override
+                    public void windowGainedFocus(final WindowEvent event) {
+                        requestFocusInWindow();
+                    }
+                };
+                window.addWindowFocusListener(windowFocus);
+            }
+            requestFocusInWindow();
+        });
+    }
+
+    @Override
+    public void removeNotify() {
+        for (final Window window : Window.getWindows()) {
+            if (windowFocus != null) {
+                window.removeWindowFocusListener(windowFocus);
+            }
+        }
+        windowFocus = null;
+        super.removeNotify();
+    }
+
+    @Override
+    protected void paintComponent(final Graphics graphics) {
+        final BufferedImage image;
+        synchronized (publishLock) {
+            image = published;
+        }
+        if (image == null) {
+            graphics.setColor(getBackground());
+            graphics.fillRect(0, 0, getWidth(), getHeight());
+            return;
+        }
+        // the host may have resized the panel since the frame was rendered, so
+        // the finished image is stretched rather than re-rendered on the event
+        // dispatch thread; the render thread catches up on the next poll
+        presenting = image;
+        try {
+            graphics.drawImage(image, 0, 0, getWidth(), getHeight(), null);
+        } finally {
+            presenting = null;
+        }
+    }
+
+    private void installInputRecording() {
+        addKeyListener(new KeyAdapter() {
+            @Override
+            public void keyPressed(final KeyEvent event) {
+                recorder.keyDown(event.getKeyCode());
+            }
+
+            @Override
+            public void keyReleased(final KeyEvent event) {
+                recorder.keyUp(event.getKeyCode());
+            }
+        });
+        addMouseListener(new MouseAdapter() {
+            @Override
+            public void mousePressed(final MouseEvent event) {
+                requestFocusInWindow();
+                pointerX = event.getX();
+                pointerY = event.getY();
+            }
+        });
+        addMouseMotionListener(new MouseMotionAdapter() {
+            @Override
+            public void mouseDragged(final MouseEvent event) {
+                // the delta is measured from the previous event, not from the
+                // press, so a long drag stays in step with the pointer
+                recorder.addPointerDelta(event.getX() - pointerX, event.getY() - pointerY);
+                pointerX = event.getX();
+                pointerY = event.getY();
+            }
+        });
+        addMouseWheelListener(event -> {
+            // notches, not pixels: AWT's own count keeps one notch on one notch
+            // across every platform, and the same accumulation rule applies as
+            // for the pointer - the frame that reads it spends it
+            recorder.addWheel(event.getWheelRotation());
+        });
+        addFocusListener(new FocusAdapter() {
+            @Override
+            public void focusLost(final FocusEvent event) {
+                // releases would never arrive after the focus is gone, and a
+                // stuck key is a camera that flies away on its own
+                recorder.clearKeys();
+            }
+        });
+    }
+
+    private void renderLoop() {
+        while (running) {
+            final int width = getWidth();
+            final int height = getHeight();
+            final boolean resized = width != frameWidth || height != frameHeight;
+            if (width > 0 && height > 0 && (requested || resized || recorder.isActive())) {
+                requested = false;
+                final ViewInput input = recorder.drain();
+                final double seconds = secondsSincePreviousFrame();
+                final CameraDriver currentDriver = driver;
+                if (currentDriver != null) {
+                    final Camera next = currentDriver.frame(input, seconds);
+                    if (next != null) {
+                        camera = next;
+                    }
+                }
+                render(width, height);
+            }
+            if (!poll(recorder.isActive() ? ACTIVE_POLL_MILLIS : IDLE_POLL_MILLIS)) {
+                return;
+            }
+        }
+    }
+
+    private double secondsSincePreviousFrame() {
+        final long now = System.nanoTime();
+        final double seconds = lastFrameNanos < 0 ? 0.0 : (now - lastFrameNanos) / 1e9;
+        lastFrameNanos = now;
+        return Math.min(seconds, MAX_FRAME_SECONDS);
+    }
+
+    private void render(final int width, final int height) {
+        ensureSurfaces(width, height);
+        final Surface surface = freeSurface();
+        surface.frame.clear(EMPTY_ARGB);
+        Renderer.render(scene, camera, surface.frame);
+        synchronized (publishLock) {
+            published = surface.image;
+        }
+        repaint();
+    }
+
+    /** Allocated once per size and then reused: a frame must not cost an allocation. */
+    private void ensureSurfaces(final int width, final int height) {
+        frameWidth = width;
+        frameHeight = height;
+        if (surfaces != null && surfaces[0].frame.width() == width && surfaces[0].frame.height() == height) {
+            return;
+        }
+        final Surface[] fresh = new Surface[SURFACES];
+        for (int index = 0; index < SURFACES; index++) {
+            fresh[index] = new Surface(width, height);
+        }
+        surfaces = fresh;
+        nextSurface = 0;
+    }
+
+    /**
+     * A surface that is neither on screen nor inside the blit the event dispatch
+     * thread is performing. Three of them make this always satisfiable, because
+     * at most one image is published and at most one is being blitted.
+     */
+    private Surface freeSurface() {
+        for (int attempt = 0; attempt < SURFACES; attempt++) {
+            final Surface candidate = surfaces[nextSurface];
+            nextSurface = (nextSurface + 1) % SURFACES;
+            if (candidate.image != published && candidate.image != presenting) {
+                return candidate;
+            }
+        }
+        return surfaces[nextSurface];
+    }
+
+    /**
+     * One reusable frame: the render buffer and the image that shares its pixels.
+     *
+     * <p>The image's raster is the render target, so there is no copy between
+     * rendering and showing - the same arrangement the first engine used, where
+     * the pixels array was the image's own data buffer.</p>
+     */
+    private static final class Surface {
+
+        private final FrameBuffer frame;
+        private final BufferedImage image;
+
+        private Surface(final int width, final int height) {
+            image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
+            final WritableRaster raster = image.getRaster();
+            final int[] pixels = ((DataBufferInt) raster.getDataBuffer()).getData();
+            frame = new FrameBuffer(width, height, pixels);
+        }
+    }
+
+    /** @return false when the thread was interrupted and must stop */
+    private static boolean poll(final int millis) {
+        try {
+            Thread.sleep(millis);
+            return true;
+        } catch (final InterruptedException interrupted) {
+            Thread.currentThread().interrupt();
+            return false;
+        }
+    }
+}
diff --git a/Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/package-info.java b/Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/package-info.java
new file mode 100644 (file)
index 0000000..33851da
--- /dev/null
@@ -0,0 +1,24 @@
+/**
+ * The Swing adapter.
+ *
+ * <p>Its job is small on purpose: take a scene and a camera pose from the world,
+ * run a render thread, and paint the finished frame into a component. It owns
+ * no window of its own — a host that already has a frame, a tab or a split pane
+ * only needs the component — and it never renders on the event dispatch thread,
+ * because the EDT must stay free to repaint.</p>
+ *
+ * <p>Rules that came out of the previous engine's shell, and that this module
+ * exists to keep:</p>
+ *
+ * <ul>
+ *   <li>The render thread publishes a complete frame by swapping a reference
+ *       under a lock; the EDT only copies the published frame. A half-rendered
+ *       frame must never reach the screen.</li>
+ *   <li>Input arrives as events and leaves as events. The component records
+ *       them; a pass consumes them. Nothing that reads input may also consume
+ *       it, or the same mouse delta is applied twice or lost.</li>
+ *   <li>Rendering is on demand: no change to scene, camera or input means no
+ *       frame is computed, only a cheap poll.</li>
+ * </ul>
+ */
+package eu.svjatoslav.aukio.swing;
diff --git a/Modules/swing/src/main/java/module-info.java b/Modules/swing/src/main/java/module-info.java
new file mode 100644 (file)
index 0000000..ea16a02
--- /dev/null
@@ -0,0 +1,17 @@
+/**
+ * The Swing adapter: the component a host application drops into its own
+ * window, and the render loop that feeds it.
+ *
+ * <p>This module is the only place in the engine that may touch
+ * =java.desktop=. Everything below it - the renderer, the scene, the passes -
+ * stays headless, so the same engine can be driven from a test, a server or a
+ * different toolkit without a window existing anywhere.</p>
+ */
+module eu.svjatoslav.aukio.swing {
+    requires eu.svjatoslav.aukio.render;
+    // The input record, its recorder and the driver contract live in navigation:
+    // what a frame of input is does not depend on a toolkit having produced it.
+    requires eu.svjatoslav.aukio.navigation;
+    requires java.desktop;
+    exports eu.svjatoslav.aukio.swing;
+}
diff --git a/Modules/swing/src/test/java/eu/svjatoslav/aukio/swing/ModuleShapeTest.java b/Modules/swing/src/test/java/eu/svjatoslav/aukio/swing/ModuleShapeTest.java
new file mode 100644 (file)
index 0000000..e7f870a
--- /dev/null
@@ -0,0 +1,185 @@
+package eu.svjatoslav.aukio.swing;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * The adapter's shape, checked rather than promised: one public package, a
+ * descriptor that asks for the toolkit, the renderer and navigation and for
+ * nothing else in the engine, and no file longer than the agreed limit.
+ *
+ * <p>The direction matters as much as the list. This module may depend on the
+ * renderer; the renderer may never depend on this one, and the descriptor is
+ * where that is written down.</p>
+ */
+class ModuleShapeTest {
+
+    private static final int MAX_FILE_LINES = 800;
+
+    private static final Path SOURCE_ROOT = Path.of("src", "main", "java");
+
+    private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.swing";
+
+    private static final String RENDERER_PACKAGE = "eu.svjatoslav.aukio.render";
+
+    // The renderer requires the world transitively, so the adapter may name
+    // world types (a scene, a camera pose) as well as renderer types.
+    private static final String WORLD_PACKAGE = "eu.svjatoslav.aukio.world";
+
+    // The input record and the driver contract are navigation's, not the
+    // adapter's: what a frame of input is does not depend on a toolkit having
+    // produced it, and a test or a device can fill the same record.
+    private static final String NAVIGATION_PACKAGE = "eu.svjatoslav.aukio.navigation";
+
+    private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE);
+
+    private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    @Test
+    void sourcesLiveInExactlyOnePackage() throws IOException {
+        final List<String> problems = new ArrayList<>();
+        for (final Path file : sources()) {
+            final String declared = declaredPackage(file);
+            if (!MODULE_PACKAGE.equals(declared)) {
+                problems.add(relativize(file) + " declares package " + declared);
+            }
+        }
+        assertTrue(problems.isEmpty(), "one public package per module, found: " + problems);
+    }
+
+    @Test
+    void theDescriptorAsksForTheToolkitTheRendererAndNavigationOnly() throws IOException {
+        final String descriptor = descriptor();
+        assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor),
+                "the module name is derived from its package");
+        final List<String> required = allMatches(REQUIRES, descriptor);
+        assertTrue(required.contains("java.desktop"),
+                "this module exists to touch the toolkit, so its descriptor says so: " + required);
+        assertTrue(required.contains(RENDERER_PACKAGE),
+                "the adapter draws what the renderer produces: " + required);
+        assertTrue(required.contains(NAVIGATION_PACKAGE),
+                "the adapter records input into navigation's recorder: " + required);
+        for (final String module : required) {
+            final boolean ours = module.startsWith("eu.svjatoslav.aukio.");
+            if (ours && !module.equals(RENDERER_PACKAGE) && !module.equals(NAVIGATION_PACKAGE)) {
+                fail("the adapter requires no other engine module, found: " + module);
+            }
+        }
+        final List<String> exports = allMatches(EXPORT, descriptor);
+        assertTrue(exports.size() <= 1, "one public package at most, found: " + exports);
+        for (final String exported : exports) {
+            assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported");
+        }
+    }
+
+    @Test
+    void noFileExceedsTheLineLimit() throws IOException {
+        final List<String> tooLong = new ArrayList<>();
+        for (final Path file : sources()) {
+            final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size();
+            if (lines > MAX_FILE_LINES) {
+                tooLong.add(relativize(file) + " " + lines + " lines");
+            }
+        }
+        assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong);
+    }
+
+    @Test
+    void importsReachIntoTheRendererAndTheWorldOnly() throws IOException {
+        final List<String> foreign = new ArrayList<>();
+        for (final Path file : sources()) {
+            for (final String imported : imports(file)) {
+                if (imported.startsWith("eu.svjatoslav.aukio.")
+                        && !imported.startsWith(MODULE_PACKAGE)
+                        && !imported.startsWith(RENDERER_PACKAGE)
+                        && !imported.startsWith(WORLD_PACKAGE)
+                        && !imported.startsWith(NAVIGATION_PACKAGE)) {
+                    foreign.add(relativize(file) + " imports " + imported);
+                }
+            }
+        }
+        assertTrue(foreign.isEmpty(), "the adapter may see the renderer, the world and navigation, nothing else: " + foreign);
+    }
+
+    @Test
+    void theModuleItselfHasSources() throws IOException {
+        assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous");
+    }
+
+    private static List<Path> sources() throws IOException {
+        if (!Files.isDirectory(SOURCE_ROOT)) {
+            fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist");
+        }
+        try (Stream<Path> walk = Files.walk(SOURCE_ROOT)) {
+            return walk.filter(Files::isRegularFile)
+                    .filter(path -> path.toString().endsWith(".java"))
+                    .filter(path -> !path.getFileName().toString().equals("module-info.java"))
+                    .sorted()
+                    .toList();
+        }
+    }
+
+    private static String descriptor() throws IOException {
+        final Path file = SOURCE_ROOT.resolve("module-info.java");
+        if (!Files.isRegularFile(file)) {
+            fail("the module declares no descriptor: " + relativize(file) + " is missing");
+        }
+        return Files.readString(file, StandardCharsets.UTF_8);
+    }
+
+    private static String declaredPackage(final Path file) throws IOException {
+        final String text = Files.readString(file, StandardCharsets.UTF_8);
+        final Matcher matcher = PACKAGE.matcher(text);
+        if (!matcher.find()) {
+            return "<none>";
+        }
+        assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file));
+        return matcher.group(1);
+    }
+
+    private static List<String> imports(final Path file) throws IOException {
+        return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8));
+    }
+
+    private static String firstMatch(final Pattern pattern, final String text) {
+        final List<String> found = allMatches(pattern, text);
+        return found.isEmpty() ? "<none>" : found.get(0);
+    }
+
+    private static List<String> allMatches(final Pattern pattern, final String text) {
+        final List<String> found = new ArrayList<>();
+        final Matcher matcher = pattern.matcher(text);
+        while (matcher.find()) {
+            found.add(matcher.group(1));
+        }
+        return found;
+    }
+
+    private static int countMatches(final Pattern pattern, final String text) {
+        return allMatches(pattern, text).size();
+    }
+
+    private static String relativize(final Path path) {
+        return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString();
+    }
+}
diff --git a/Modules/world/Documentation/index.org b/Modules/world/Documentation/index.org
new file mode 100644 (file)
index 0000000..c4c2045
--- /dev/null
@@ -0,0 +1,110 @@
+#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme
+#+TITLE: World
+#+LANGUAGE: en
+
+:PROPERTIES:
+:CUSTOM_ID: world-page
+:END:
+
+#+OPTIONS: H:20 num:nil author:nil
+
+[[file:../../../Documentation/index.html#outline-container-world][<- Back to index]]
+
+* What it owns
+:PROPERTIES:
+:CUSTOM_ID: world-owns
+:END:
+
+The scene as data: geometry, transforms, the object tree, triangle storage in
+object space, the primitives, and the camera pose. Everything a scene *is*,
+before anything is drawn.
+
+It is the Java module =eu.svjatoslav.aukio.world=, and it requires nothing at
+all - not the renderer, not the toolkit, not the scheduler. That is a property
+the build enforces rather than promises: a =requires= on any other engine module
+fails to compile, so the bottom of the engine cannot quietly stop being the
+bottom.
+
+* A pose is data, a projection is not
+:PROPERTIES:
+:CUSTOM_ID: world-pose
+:END:
+
+The camera's position and rotation live here; the =scale = width / 3= that turns
+them into screen coordinates does not. Projection needs the viewport, and the
+viewport is a property of the picture being painted, so it belongs to the
+renderer.
+
+That single rule is what keeps the arrow one-way. The moment the world needed to
+know how wide the window is, the two modules would be one module again.
+
+* The seams inside it
+:PROPERTIES:
+:CUSTOM_ID: world-seams
+:END:
+
+One package, concerns kept apart by class:
+
+| Seam     | Owns                                                        |
+|----------+-------------------------------------------------------------|
+| geometry | vectors, quaternions, matrices, boxes, =Transform= and chain |
+| scene    | nodes: transform, children, optional mesh, group             |
+| mesh     | triangles in object space; a published mesh is immutable     |
+| shapes   | primitives in local coordinates                              |
+| camera   | a pose, nothing more                                         |
+
+* Invariants
+:PROPERTIES:
+:CUSTOM_ID: world-invariants
+:END:
+
+- Local coordinates never leave this module uncomposed. A node's geometry is
+  local, its world matrix is derived, and anything downstream receives world
+  space.
+- A pose writes node transforms, never mesh vertices. A mesh is published once
+  and may be shared, so anything derived from it - an index, a baked light -
+  stays valid while the scene moves.
+
+* What does not belong here
+:PROPERTIES:
+:CUSTOM_ID: world-not-here
+:END:
+
+Loading, streaming, file formats, light, and anything that owns a clock or a
+thread. Those read from outside the process and belong to modules that can be
+absent; the world stays testable as plain data.
+
+* What the build checks
+:PROPERTIES:
+:CUSTOM_ID: world-checks
+:END:
+
+=ModuleShapeTest= holds the shape: one package, a descriptor that requires no
+other engine module, files under 800 lines, and imports that never leave the
+module.
+
+#+begin_src sh
+export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
+./gradlew --offline :world:test    # the world alone, other modules absent
+#+end_src
+
+* Implemented today
+:PROPERTIES:
+:CUSTOM_ID: world-implemented
+:END:
+
+Geometry, the object tree, one primitive and the camera pose:
+
+| Type        | What it is                                                    |
+|-------------+---------------------------------------------------------------|
+| =Vec3=      | an immutable point or direction                                |
+| =Transform= | a translation and a rotation, held as a matrix so chains compose |
+| =Mesh=      | flat triangle storage in object space, immutable once published |
+| =Boxes=     | the box primitive, six quads wound outwards                    |
+| =Node=      | a pose, an optional mesh and children posed inside it           |
+| =Scene=     | the tree, and the one place local coordinates become world ones |
+| =Camera=    | a position, a yaw and a pitch; no viewport, no field of view    |
+
+Still to come: quaternions and axis-aligned boxes as published types, the other
+primitives (cylinder, sphere, cone, arrow, grid), and per-node bounds for the
+renderer's per-node cull.
diff --git a/Modules/world/build.gradle b/Modules/world/build.gradle
new file mode 100644 (file)
index 0000000..8d18188
--- /dev/null
@@ -0,0 +1,7 @@
+// The data model of a scene: geometry, transforms, the object tree and the
+// primitives. It requires nothing at all - not the renderer, not the toolkit,
+// not the scheduler - which is what lets it be tested as plain data.
+
+dependencies {
+    // none
+}
diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Boxes.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Boxes.java
new file mode 100644 (file)
index 0000000..83e3288
--- /dev/null
@@ -0,0 +1,37 @@
+package eu.svjatoslav.aukio.world;
+
+/**
+ * The box primitive, built in object space.
+ *
+ * <p>Six quads, each wound so its normal points out of the solid. That winding
+ * is the same one the first engine's box used, so a scene built from it looks
+ * the same under either engine; the renderer here does not cull backfaces, so a
+ * wrong winding would still show a solid, only inside out.</p>
+ */
+public final class Boxes {
+
+    private Boxes() {
+    }
+
+    /**
+     * @param min   corner with the smallest coordinates
+     * @param max   corner with the largest coordinates
+     * @param argb  flat colour of all twelve triangles
+     */
+    public static Mesh box(final Vec3 min, final Vec3 max, final int argb) {
+        final double x0 = min.x();
+        final double y0 = min.y();
+        final double z0 = min.z();
+        final double x1 = max.x();
+        final double y1 = max.y();
+        final double z1 = max.z();
+        final Mesh.Builder mesh = Mesh.builder();
+        mesh.quad(new Vec3(x0, y0, z1), new Vec3(x1, y0, z1), new Vec3(x1, y1, z1), new Vec3(x0, y1, z1), argb);
+        mesh.quad(new Vec3(x1, y0, z0), new Vec3(x0, y0, z0), new Vec3(x0, y1, z0), new Vec3(x1, y1, z0), argb);
+        mesh.quad(new Vec3(x0, y1, z1), new Vec3(x1, y1, z1), new Vec3(x1, y1, z0), new Vec3(x0, y1, z0), argb);
+        mesh.quad(new Vec3(x0, y0, z0), new Vec3(x1, y0, z0), new Vec3(x1, y0, z1), new Vec3(x0, y0, z1), argb);
+        mesh.quad(new Vec3(x1, y0, z1), new Vec3(x1, y0, z0), new Vec3(x1, y1, z0), new Vec3(x1, y1, z1), argb);
+        mesh.quad(new Vec3(x0, y0, z0), new Vec3(x0, y0, z1), new Vec3(x0, y1, z1), new Vec3(x0, y1, z0), argb);
+        return mesh.build();
+    }
+}
diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Camera.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Camera.java
new file mode 100644 (file)
index 0000000..eed8516
--- /dev/null
@@ -0,0 +1,46 @@
+package eu.svjatoslav.aukio.world;
+
+/**
+ * A camera pose: where it stands and which way it looks. Nothing else.
+ *
+ * <p>There is no viewport here and no field of view, because a pose is world
+ * data while a projection needs the picture width. Turning this into screen
+ * coordinates is the renderer's job; that split is what keeps the world free of
+ * any knowledge of screens.</p>
+ *
+ * <p>Angles follow the module convention: +Y is up, yaw = pitch = 0 looks along
+ * +Z, positive yaw turns towards +X, positive pitch looks up.</p>
+ */
+public final class Camera {
+
+    private final Vec3 position;
+    private final double yaw;
+    private final double pitch;
+
+    private Camera(final Vec3 position, final double yaw, final double pitch) {
+        this.position = position;
+        this.yaw = yaw;
+        this.pitch = pitch;
+    }
+
+    public static Camera of(final Vec3 position, final double yaw, final double pitch) {
+        return new Camera(position, yaw, pitch);
+    }
+
+    /** Level camera looking along +Z. */
+    public static Camera at(final Vec3 position) {
+        return new Camera(position, 0, 0);
+    }
+
+    public Vec3 position() {
+        return position;
+    }
+
+    public double yaw() {
+        return yaw;
+    }
+
+    public double pitch() {
+        return pitch;
+    }
+}
diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Mesh.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Mesh.java
new file mode 100644 (file)
index 0000000..9fbc260
--- /dev/null
@@ -0,0 +1,84 @@
+package eu.svjatoslav.aukio.world;
+
+import java.util.Arrays;
+
+/**
+ * Triangles in object space, stored flat and never mutated after publication.
+ *
+ * <p>Nine doubles per triangle plus one colour per triangle: this engine is
+ * flat shaded, so a triangle carries a colour rather than a material. A
+ * published mesh is immutable, which is what lets several nodes share one and
+ * keeps any index derived from it valid while the scene moves - a pose writes
+ * node transforms, never vertices.</p>
+ */
+public final class Mesh {
+
+    private final double[] positions;
+    private final int[] colors;
+
+    private Mesh(final double[] positions, final int[] colors) {
+        this.positions = positions;
+        this.colors = colors;
+    }
+
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    public int triangleCount() {
+        return colors.length;
+    }
+
+    /**
+     * One coordinate of one vertex.
+     *
+     * @param triangle triangle index, 0-based
+     * @param vertex   vertex of that triangle, 0..2
+     * @param axis     0 = x, 1 = y, 2 = z
+     */
+    public double position(final int triangle, final int vertex, final int axis) {
+        return positions[triangle * 9 + vertex * 3 + axis];
+    }
+
+    public int color(final int triangle) {
+        return colors[triangle];
+    }
+
+    /** Collects triangles, then publishes them as one immutable mesh. */
+    public static final class Builder {
+
+        private double[] positions = new double[9 * 16];
+        private int[] colors = new int[16];
+        private int triangles;
+
+        public Builder triangle(final Vec3 a, final Vec3 b, final Vec3 c, final int argb) {
+            if ((triangles + 1) * 9 > positions.length) {
+                positions = Arrays.copyOf(positions, Math.max(positions.length * 2, triangles * 9 + 9));
+                colors = Arrays.copyOf(colors, colors.length * 2);
+            }
+            final int base = triangles * 9;
+            positions[base] = a.x();
+            positions[base + 1] = a.y();
+            positions[base + 2] = a.z();
+            positions[base + 3] = b.x();
+            positions[base + 4] = b.y();
+            positions[base + 5] = b.z();
+            positions[base + 6] = c.x();
+            positions[base + 7] = c.y();
+            positions[base + 8] = c.z();
+            colors[triangles] = argb;
+            triangles++;
+            return this;
+        }
+
+        /** Adds a quad as two triangles, keeping the winding of the four points. */
+        public Builder quad(final Vec3 a, final Vec3 b, final Vec3 c, final Vec3 d, final int argb) {
+            triangle(a, b, c, argb);
+            return triangle(a, c, d, argb);
+        }
+
+        public Mesh build() {
+            return new Mesh(Arrays.copyOf(positions, triangles * 9), Arrays.copyOf(colors, triangles));
+        }
+    }
+}
diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Node.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Node.java
new file mode 100644 (file)
index 0000000..e70caa7
--- /dev/null
@@ -0,0 +1,52 @@
+package eu.svjatoslav.aukio.world;
+
+import java.util.List;
+
+/**
+ * One object in the tree: a pose, optionally a mesh, and children posed inside
+ * this node's space.
+ *
+ * <p>A node without a mesh is a group, which is how a pile of parts is moved as
+ * one thing. A mesh is shared, never copied: two nodes may name the same mesh
+ * and only their transforms differ, which is what instancing is here.</p>
+ */
+public final class Node {
+
+    private final Transform transform;
+    private final Mesh mesh;
+    private final List<Node> children;
+
+    private Node(final Transform transform, final Mesh mesh, final List<Node> children) {
+        this.transform = transform;
+        this.mesh = mesh;
+        this.children = List.copyOf(children);
+    }
+
+    /** A leaf: one mesh at the given pose. */
+    public static Node of(final Transform transform, final Mesh mesh) {
+        return new Node(transform, mesh, List.of());
+    }
+
+    /** One mesh at the identity pose, the common case. */
+    public static Node mesh(final Mesh mesh) {
+        return new Node(Transform.IDENTITY, mesh, List.of());
+    }
+
+    /** A pose with children under it, no geometry of its own. */
+    public static Node group(final Transform transform, final Node... children) {
+        return new Node(transform, null, List.of(children));
+    }
+
+    public Transform transform() {
+        return transform;
+    }
+
+    /** @return the mesh, or null when this node only groups. */
+    public Mesh mesh() {
+        return mesh;
+    }
+
+    public List<Node> children() {
+        return children;
+    }
+}
diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Scene.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Scene.java
new file mode 100644 (file)
index 0000000..a3a0dee
--- /dev/null
@@ -0,0 +1,63 @@
+package eu.svjatoslav.aukio.world;
+
+/**
+ * The root of the object tree, and the one place where local coordinates become
+ * world coordinates.
+ *
+ * <p>A caller never sees a local vertex: {@link #forEachTriangle} composes the
+ * transform chain down to each node and reports world-space triangles in a
+ * fixed order. That order is part of the contract, because the renderer's
+ * output is only reproducible while the walk is.</p>
+ */
+public final class Scene {
+
+    /** Receives one world-space triangle at a time. */
+    @FunctionalInterface
+    public interface TriangleConsumer {
+        void triangle(double x0, double y0, double z0,
+                      double x1, double y1, double z1,
+                      double x2, double y2, double z2,
+                      int argb);
+    }
+
+    private final Node root;
+
+    public Scene(final Node root) {
+        this.root = root;
+    }
+
+    public Node root() {
+        return root;
+    }
+
+    /** Walks the whole tree, depth first, in child order. */
+    public void forEachTriangle(final TriangleConsumer consumer) {
+        visit(root, Transform.IDENTITY, consumer);
+    }
+
+    private static void visit(final Node node, final Transform parent,
+                              final TriangleConsumer consumer) {
+        final Transform world = parent.then(node.transform());
+        final Mesh mesh = node.mesh();
+        if (mesh != null) {
+            for (int triangle = 0; triangle < mesh.triangleCount(); triangle++) {
+                final Vec3 a = world.apply(vertex(mesh, triangle, 0));
+                final Vec3 b = world.apply(vertex(mesh, triangle, 1));
+                final Vec3 c = world.apply(vertex(mesh, triangle, 2));
+                consumer.triangle(a.x(), a.y(), a.z(),
+                        b.x(), b.y(), b.z(),
+                        c.x(), c.y(), c.z(),
+                        mesh.color(triangle));
+            }
+        }
+        for (final Node child : node.children()) {
+            visit(child, world, consumer);
+        }
+    }
+
+    private static Vec3 vertex(final Mesh mesh, final int triangle, final int vertex) {
+        return new Vec3(mesh.position(triangle, vertex, 0),
+                mesh.position(triangle, vertex, 1),
+                mesh.position(triangle, vertex, 2));
+    }
+}
diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Transform.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Transform.java
new file mode 100644 (file)
index 0000000..b0f1533
--- /dev/null
@@ -0,0 +1,97 @@
+package eu.svjatoslav.aukio.world;
+
+/**
+ * A pose: a rotation followed by a translation, applied to object-space
+ * coordinates to produce the parent's coordinates.
+ *
+ * <p>The rotation is held as a matrix, not as a yaw/pitch pair. Two yaw/pitch
+ * pairs do not compose back into a yaw/pitch pair once a node has been turned
+ * about both axes, so the pair is only how a pose is written down while the
+ * matrix is what the chain multiplies.</p>
+ *
+ * <p>Axis convention, shared with the camera: +Y is up, yaw = pitch = 0 maps
+ * object axes onto parent axes, positive yaw turns object +Z towards +X (the
+ * right), and positive pitch tilts object +Z towards +Y (up).</p>
+ */
+public final class Transform {
+
+    /** Leaves a point exactly where it is. */
+    public static final Transform IDENTITY =
+            new Transform(Vec3.ORIGIN, new double[]{1, 0, 0, 0, 1, 0, 0, 0, 1});
+
+    private final Vec3 translation;
+
+    /** Row-major 3x3: object space in, parent space out. */
+    private final double[] rotation;
+
+    private Transform(final Vec3 translation, final double[] rotation) {
+        this.translation = translation;
+        this.rotation = rotation;
+    }
+
+    /** A pure translation. */
+    public static Transform at(final Vec3 translation) {
+        return new Transform(translation, IDENTITY.rotation);
+    }
+
+    /** A translation and a rotation, written the way a pose is spoken. */
+    public static Transform of(final Vec3 translation, final double yaw, final double pitch) {
+        return new Transform(translation, rotation(yaw, pitch));
+    }
+
+    public Vec3 translation() {
+        return translation;
+    }
+
+    /** Object space to parent space. */
+    public Vec3 apply(final Vec3 local) {
+        return new Vec3(
+                rotation[0] * local.x() + rotation[1] * local.y() + rotation[2] * local.z() + translation.x(),
+                rotation[3] * local.x() + rotation[4] * local.y() + rotation[5] * local.z() + translation.y(),
+                rotation[6] * local.x() + rotation[7] * local.y() + rotation[8] * local.z() + translation.z());
+    }
+
+    /**
+     * This pose applied after {@code child}'s own: the child is posed in this
+     * node's space, which is what makes a chain of parts out of one mesh.
+     */
+    public Transform then(final Transform child) {
+        final double[] a = rotation;
+        final double[] b = child.rotation;
+        final double[] composed = new double[9];
+        for (int row = 0; row < 3; row++) {
+            for (int column = 0; column < 3; column++) {
+                composed[row * 3 + column] =
+                        a[row * 3] * b[column]
+                        + a[row * 3 + 1] * b[3 + column]
+                        + a[row * 3 + 2] * b[6 + column];
+            }
+        }
+        final Vec3 moved = new Vec3(
+                a[0] * child.translation.x() + a[1] * child.translation.y() + a[2] * child.translation.z()
+                        + translation.x(),
+                a[3] * child.translation.x() + a[4] * child.translation.y() + a[5] * child.translation.z()
+                        + translation.y(),
+                a[6] * child.translation.x() + a[7] * child.translation.y() + a[8] * child.translation.z()
+                        + translation.z());
+        return new Transform(moved, composed);
+    }
+
+    /**
+     * Ry(yaw) * Rx(-pitch): the inverse of the rotation the renderer applies
+     * when it turns a world point into a camera-space one, so a node posed with
+     * yaw and pitch faces the same way a camera with the same angles looks.
+     */
+    private static double[] rotation(final double yaw, final double pitch) {
+        final double cosYaw = Math.cos(yaw);
+        final double sinYaw = Math.sin(yaw);
+        // Rx(-pitch): b = -pitch
+        final double cosPitch = Math.cos(-pitch);
+        final double sinPitch = Math.sin(-pitch);
+        return new double[]{
+                cosYaw, sinYaw * sinPitch, sinYaw * cosPitch,
+                0, cosPitch, -sinPitch,
+                -sinYaw, cosYaw * sinPitch, cosYaw * cosPitch
+        };
+    }
+}
diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Vec3.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Vec3.java
new file mode 100644 (file)
index 0000000..b48f875
--- /dev/null
@@ -0,0 +1,27 @@
+package eu.svjatoslav.aukio.world;
+
+/**
+ * A point or a direction in three dimensions.
+ *
+ * <p>Immutable and unitless. The same type is a world position, an object-space
+ * position and a direction, because nothing in this module needs to tell them
+ * apart: which one a value is, is a property of where it is used, not of the
+ * number.</p>
+ */
+public record Vec3(double x, double y, double z) {
+
+    /** The origin of whichever coordinate system a value is read in. */
+    public static final Vec3 ORIGIN = new Vec3(0, 0, 0);
+
+    public Vec3 plus(final Vec3 other) {
+        return new Vec3(x + other.x, y + other.y, z + other.z);
+    }
+
+    public Vec3 minus(final Vec3 other) {
+        return new Vec3(x - other.x, y - other.y, z - other.z);
+    }
+
+    public Vec3 scaled(final double factor) {
+        return new Vec3(x * factor, y * factor, z * factor);
+    }
+}
diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/package-info.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/package-info.java
new file mode 100644 (file)
index 0000000..6872743
--- /dev/null
@@ -0,0 +1,31 @@
+/**
+ * The world: everything a scene is before anything is drawn.
+ *
+ * <p>The module holds the data model and nothing that behaves like a device.
+ * Its concerns, kept apart by class rather than by package:</p>
+ *
+ * <ul>
+ *   <li>geometry - vectors, quaternions, matrices, axis-aligned boxes,
+ *       {@code Transform} and the chain that composes them.</li>
+ *   <li>scene - the object tree: nodes carrying a transform, children, an
+ *       optional mesh and a group; world matrices are composed here and
+ *       nowhere else.</li>
+ *   <li>mesh - triangles in object space. A published mesh is immutable and
+ *       may be shared by many nodes.</li>
+ *   <li>shapes - primitives built in local coordinates: box, box frame,
+ *       cylinder, sphere, cone, arrow, grid.</li>
+ *   <li>camera - a pose, nothing more. The viewport and the projection belong
+ *       to the renderer, so this module never needs to know a screen size.</li>
+ * </ul>
+ *
+ * <p>Two invariants cross every concern. Local coordinates never leave this
+ * module uncomposed: a node's geometry is local, its world matrix is derived,
+ * and anything downstream receives world space. And a pose writes node
+ * transforms, never mesh vertices, so a shared mesh stays shared and any index
+ * or baked light derived from it stays valid while the scene moves.</p>
+ *
+ * <p>What does not belong here, however convenient: loading, streaming, file
+ * formats, light, and anything that owns a clock or a thread. Those read from
+ * outside and belong to modules that can be absent.</p>
+ */
+package eu.svjatoslav.aukio.world;
diff --git a/Modules/world/src/main/java/module-info.java b/Modules/world/src/main/java/module-info.java
new file mode 100644 (file)
index 0000000..4b9e2a6
--- /dev/null
@@ -0,0 +1,13 @@
+/**
+ * The world module: the scene as data - geometry, transforms, the object tree
+ * and the primitives - with no knowledge of screens, windows or threads.
+ *
+ * <p>A pose lives here; a projection does not. The camera's position and
+ * rotation are world data, while turning them into screen coordinates needs the
+ * viewport and therefore belongs to the renderer. That one rule is what keeps
+ * the arrow pointing one way: the renderer reads the world, and the world has
+ * never heard of the renderer.</p>
+ */
+module eu.svjatoslav.aukio.world {
+    exports eu.svjatoslav.aukio.world;
+}
diff --git a/Modules/world/src/test/java/eu/svjatoslav/aukio/world/BoxesTest.java b/Modules/world/src/test/java/eu/svjatoslav/aukio/world/BoxesTest.java
new file mode 100644 (file)
index 0000000..4bfb442
--- /dev/null
@@ -0,0 +1,68 @@
+package eu.svjatoslav.aukio.world;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The box primitive: twelve triangles, inside its corners, wound outwards.
+ *
+ * <p>The outward winding is checked because nothing downstream would notice if
+ * it broke, and the first engine's meshes are compared against this geometry by
+ * eye and by pixel.</p>
+ */
+class BoxesTest {
+
+    private static final Vec3 CORNER = new Vec3(-50, -50, -50);
+    private static final Vec3 OPPOSITE = new Vec3(50, 50, 50);
+
+    @Test
+    void aBoxIsTwelveTriangles() {
+        assertEquals(12, Boxes.box(CORNER, OPPOSITE, 0xFFFF0000).triangleCount());
+    }
+
+    @Test
+    void everyVertexLiesOnOneOfItsCorners() {
+        final Mesh box = Boxes.box(CORNER, OPPOSITE, 0xFFFF0000);
+        for (int triangle = 0; triangle < box.triangleCount(); triangle++) {
+            for (int vertex = 0; vertex < 3; vertex++) {
+                for (int axis = 0; axis < 3; axis++) {
+                    final double value = box.position(triangle, vertex, axis);
+                    assertTrue(value >= -50 && value <= 50, "coordinate " + value + " outside the box");
+                    assertTrue(value == -50 || value == 50, "a box vertex sits on a corner, not at " + value);
+                }
+            }
+        }
+    }
+
+    @Test
+    void everyTriangleFacesOutOfTheSolid() {
+        final Mesh box = Boxes.box(CORNER, OPPOSITE, 0xFFFF0000);
+        for (int triangle = 0; triangle < box.triangleCount(); triangle++) {
+            final Vec3 a = vertex(box, triangle, 0);
+            final Vec3 b = vertex(box, triangle, 1);
+            final Vec3 c = vertex(box, triangle, 2);
+            final Vec3 normal = cross(b.minus(a), c.minus(a));
+            final Vec3 centroid = new Vec3((a.x() + b.x() + c.x()) / 3,
+                    (a.y() + b.y() + c.y()) / 3,
+                    (a.z() + b.z() + c.z()) / 3);
+            final double outward = normal.x() * centroid.x()
+                    + normal.y() * centroid.y()
+                    + normal.z() * centroid.z();
+            assertTrue(outward > 0, "triangle " + triangle + " faces inwards, its normal is " + normal);
+        }
+    }
+
+    private static Vec3 vertex(final Mesh mesh, final int triangle, final int vertex) {
+        return new Vec3(mesh.position(triangle, vertex, 0),
+                mesh.position(triangle, vertex, 1),
+                mesh.position(triangle, vertex, 2));
+    }
+
+    private static Vec3 cross(final Vec3 a, final Vec3 b) {
+        return new Vec3(a.y() * b.z() - a.z() * b.y(),
+                a.z() * b.x() - a.x() * b.z(),
+                a.x() * b.y() - a.y() * b.x());
+    }
+}
diff --git a/Modules/world/src/test/java/eu/svjatoslav/aukio/world/ModuleShapeTest.java b/Modules/world/src/test/java/eu/svjatoslav/aukio/world/ModuleShapeTest.java
new file mode 100644 (file)
index 0000000..86b5ae3
--- /dev/null
@@ -0,0 +1,161 @@
+package eu.svjatoslav.aukio.world;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * The world's shape, checked rather than promised: one public package, one
+ * descriptor, no requirement on any other engine module, and no file longer
+ * than the agreed limit.
+ *
+ * <p>The requirement list is the important one here. The world is the bottom of
+ * the engine: if it ever requires the renderer, the layering is gone and the
+ * two modules have become one with extra ceremony.</p>
+ */
+class ModuleShapeTest {
+
+    private static final int MAX_FILE_LINES = 800;
+
+    private static final Path SOURCE_ROOT = Path.of("src", "main", "java");
+
+    private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.world";
+
+    private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE);
+
+    private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE);
+
+    @Test
+    void sourcesLiveInExactlyOnePackage() throws IOException {
+        final List<String> problems = new ArrayList<>();
+        for (final Path file : sources()) {
+            final String declared = declaredPackage(file);
+            if (!MODULE_PACKAGE.equals(declared)) {
+                problems.add(relativize(file) + " declares package " + declared);
+            }
+        }
+        assertTrue(problems.isEmpty(), "one public package per module, found: " + problems);
+    }
+
+    @Test
+    void theDescriptorRequiresNoEngineModule() throws IOException {
+        final String descriptor = descriptor();
+        assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor),
+                "the module name is derived from its package");
+        for (final String required : allMatches(REQUIRES, descriptor)) {
+            assertFalse(required.startsWith("eu.svjatoslav.aukio."),
+                    "the world is the bottom of the engine and requires no other module, found: " + required);
+        }
+        final List<String> exports = allMatches(EXPORT, descriptor);
+        assertTrue(exports.size() <= 1, "one public package at most, found: " + exports);
+        for (final String exported : exports) {
+            assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported");
+        }
+    }
+
+    @Test
+    void noFileExceedsTheLineLimit() throws IOException {
+        final List<String> tooLong = new ArrayList<>();
+        for (final Path file : sources()) {
+            final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size();
+            if (lines > MAX_FILE_LINES) {
+                tooLong.add(relativize(file) + " " + lines + " lines");
+            }
+        }
+        assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong);
+    }
+
+    @Test
+    void importsStayInsideThisModule() throws IOException {
+        final List<String> foreign = new ArrayList<>();
+        for (final Path file : sources()) {
+            for (final String imported : imports(file)) {
+                if (imported.startsWith("eu.svjatoslav.aukio.") && !imported.startsWith(MODULE_PACKAGE)) {
+                    foreign.add(relativize(file) + " imports " + imported);
+                }
+            }
+        }
+        assertTrue(foreign.isEmpty(), "the world imports no other engine module: " + foreign);
+    }
+
+    @Test
+    void theModuleItselfHasSources() throws IOException {
+        assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous");
+    }
+
+    private static List<Path> sources() throws IOException {
+        if (!Files.isDirectory(SOURCE_ROOT)) {
+            fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist");
+        }
+        try (Stream<Path> walk = Files.walk(SOURCE_ROOT)) {
+            return walk.filter(Files::isRegularFile)
+                    .filter(path -> path.toString().endsWith(".java"))
+                    .filter(path -> !path.getFileName().toString().equals("module-info.java"))
+                    .sorted()
+                    .toList();
+        }
+    }
+
+    private static String descriptor() throws IOException {
+        final Path file = SOURCE_ROOT.resolve("module-info.java");
+        if (!Files.isRegularFile(file)) {
+            fail("the module declares no descriptor: " + relativize(file) + " is missing");
+        }
+        return Files.readString(file, StandardCharsets.UTF_8);
+    }
+
+    private static String declaredPackage(final Path file) throws IOException {
+        final String text = Files.readString(file, StandardCharsets.UTF_8);
+        final Matcher matcher = PACKAGE.matcher(text);
+        if (!matcher.find()) {
+            return "<none>";
+        }
+        assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file));
+        return matcher.group(1);
+    }
+
+    private static List<String> imports(final Path file) throws IOException {
+        return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8));
+    }
+
+    private static String firstMatch(final Pattern pattern, final String text) {
+        final List<String> found = allMatches(pattern, text);
+        return found.isEmpty() ? "<none>" : found.get(0);
+    }
+
+    private static List<String> allMatches(final Pattern pattern, final String text) {
+        final List<String> found = new ArrayList<>();
+        final Matcher matcher = pattern.matcher(text);
+        while (matcher.find()) {
+            found.add(matcher.group(1));
+        }
+        return found;
+    }
+
+    private static int countMatches(final Pattern pattern, final String text) {
+        return allMatches(pattern, text).size();
+    }
+
+    private static String relativize(final Path path) {
+        return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString();
+    }
+}
diff --git a/Modules/world/src/test/java/eu/svjatoslav/aukio/world/TransformTest.java b/Modules/world/src/test/java/eu/svjatoslav/aukio/world/TransformTest.java
new file mode 100644 (file)
index 0000000..b7b8318
--- /dev/null
@@ -0,0 +1,56 @@
+package eu.svjatoslav.aukio.world;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * The pose convention, pinned: a yaw turns object +Z towards +X, a pitch tilts
+ * it towards +Y, and a chain applies the child first.
+ *
+ * <p>These are the numbers a camera and a node must agree on for a scene to
+ * look the same as it did in the previous engine, so they are asserted rather
+ * than described.</p>
+ */
+class TransformTest {
+
+    private static final double EPSILON = 1e-9;
+
+    private static final Vec3 FORWARD = new Vec3(0, 0, 1);
+
+    @Test
+    void identityLeavesAPointWhereItIs() {
+        final Vec3 point = new Vec3(3, -4, 5);
+        assertVec(point, Transform.IDENTITY.apply(point));
+    }
+
+    @Test
+    void yawTurnsForwardTowardsTheRight() {
+        assertVec(new Vec3(1, 0, 0), Transform.of(Vec3.ORIGIN, Math.PI / 2, 0).apply(FORWARD));
+    }
+
+    @Test
+    void pitchTiltsForwardUpwards() {
+        assertVec(new Vec3(0, 1, 0), Transform.of(Vec3.ORIGIN, 0, Math.PI / 2).apply(FORWARD));
+    }
+
+    @Test
+    void translationIsAppliedAfterRotation() {
+        assertVec(new Vec3(1, 10, 0), Transform.of(new Vec3(0, 10, 0), Math.PI / 2, 0).apply(FORWARD));
+    }
+
+    @Test
+    void aChainAppliesTheChildBeforeItsParent() {
+        final Transform parent = Transform.of(new Vec3(100, 0, 0), 0, 0);
+        final Transform child = Transform.of(new Vec3(0, 0, 5), Math.PI / 2, 0);
+        // forward, turned right and pushed five along the child's own +Z, then
+        // slid a hundred along the parent's +X
+        assertVec(new Vec3(101, 0, 5), parent.then(child).apply(FORWARD));
+    }
+
+    private static void assertVec(final Vec3 expected, final Vec3 actual) {
+        assertEquals(expected.x(), actual.x(), EPSILON, "x");
+        assertEquals(expected.y(), actual.y(), EPSILON, "y");
+        assertEquals(expected.z(), actual.z(), EPSILON, "z");
+    }
+}
diff --git a/README.org b/README.org
new file mode 100644 (file)
index 0000000..d3e316e
--- /dev/null
@@ -0,0 +1,41 @@
+#+TITLE: Aukio V3
+#+AUTHOR: Svjatoslav Agejenko
+#+STARTUP: overview
+#+OPTIONS: toc:nil num:nil
+
+:PROPERTIES:
+:CUSTOM_ID: aukio-readme
+:END:
+
+* Modules
+
+| Path                | What it is          |
+|---------------------+---------------------|
+| =Modules/scheduler/= | CPU time scheduler. |
+| =Modules/world/=     | Scene data: geometry, object tree. |
+| =Modules/gi/=        | Light: direct, indirect, lightmaps. |
+| =Modules/renderer/=  | Projection, culling, rasterisation. |
+| =Modules/navigation/= | Input record and camera policy. |
+| =Modules/swing/=     | Embeddable view component. |
+| =Modules/hid/=       | 3D input devices read off /dev/hidraw. |
+
+
+* Apps
+
+| Path          | What it is         |
+|---------------+--------------------|
+| =Applications/demos/= | Demo app launcher. |
+
+
+* Build
+
+#+begin_src sh
+export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
+./gradlew --offline build
+#+end_src
+
+Gradle 8.7 through the wrapper, offline: every dependency comes from
+=~/.m2= via =mavenLocal()=. Each module also builds alone:
+=./gradlew --offline :renderer:build=.
+
+
diff --git a/build.gradle b/build.gradle
new file mode 100644 (file)
index 0000000..9f32be4
--- /dev/null
@@ -0,0 +1,47 @@
+// Every module in this build is a Java library with the same compiler settings
+// and the same test platform. A module carries its own build.gradle only when it
+// has a dependency or a task of its own.
+
+subprojects {
+    apply plugin: 'java-library'
+
+    // Compile and test on the oldest JDK the artifacts claim to support, not on
+    // whatever JVM happened to launch Gradle: a suite that is green on a newer
+    // JDK can hide a regression that only bites a host running 21. The daemon
+    // may still run on a newer JVM; only the compiler and the test workers move.
+    java {
+        toolchain {
+            languageVersion = JavaLanguageVersion.of(21)
+        }
+    }
+
+    group = 'eu.svjatoslav'
+    version = '3.0.0-SNAPSHOT'
+
+    base {
+        archivesName = "aukio-${project.name}"
+    }
+
+    repositories {
+        // Dependencies are already in the local Maven repository, so the build
+        // runs without network access.
+        mavenLocal()
+    }
+
+    dependencies {
+        testImplementation platform('org.junit:junit-bom:5.11.4')
+        testImplementation 'org.junit.jupiter:junit-jupiter'
+        testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
+    }
+
+    tasks.withType(JavaCompile).configureEach {
+        options.encoding = 'UTF-8'
+        options.release = 21
+    }
+
+    // A module's own tests run with the modules it does not depend on absent
+    // from its classpath - that is the isolation proof AGENTS.org asks for.
+    tasks.named('test') {
+        useJUnitPlatform()
+    }
+}
diff --git a/gradle.properties b/gradle.properties
new file mode 100644 (file)
index 0000000..df2d1df
--- /dev/null
@@ -0,0 +1,4 @@
+# This build is meant to run offline against toolchains already installed on the
+# machine. When the JDK the build asks for is missing, fail with a readable
+# message instead of trying to download it.
+org.gradle.java.installations.auto-download=false
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644 (file)
index 0000000..e644113
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644 (file)
index 0000000..7e7d24f
--- /dev/null
@@ -0,0 +1,7 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
new file mode 100755 (executable)
index 0000000..1aa94a4
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,249 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+#
+#   Gradle start up script for POSIX generated by Gradle.
+#
+#   Important for running:
+#
+#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+#       noncompliant, but you have some other compliant shell such as ksh or
+#       bash, then to run this script, type that shell name before the whole
+#       command line, like:
+#
+#           ksh Gradle
+#
+#       Busybox and similar reduced shells will NOT work, because this script
+#       requires all of these POSIX shell features:
+#         * functions;
+#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+#         * compound commands having a testable exit status, especially «case»;
+#         * various built-in commands including «command», «set», and «ulimit».
+#
+#   Important for patching:
+#
+#   (2) This script targets any POSIX shell, so it avoids extensions provided
+#       by Bash, Ksh, etc; in particular arrays are avoided.
+#
+#       The "traditional" practice of packing multiple parameters into a
+#       space-separated string is a well documented source of bugs and security
+#       problems, so this is (mostly) avoided, by progressively accumulating
+#       options in "$@", and eventually passing that to Java.
+#
+#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+#       see the in-line comments for details.
+#
+#       There are tweaks for specific operating systems such as AIX, CygWin,
+#       Darwin, MinGW, and NonStop.
+#
+#   (3) This script is generated from the Groovy template
+#       https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+#       within the Gradle project.
+#
+#       You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+    APP_HOME=${app_path%"${app_path##*/}"}  # leaves a trailing /; empty if no leading path
+    [ -h "$app_path" ]
+do
+    ls=$( ls -ld "$app_path" )
+    link=${ls#*' -> '}
+    case $link in             #(
+      /*)   app_path=$link ;; #(
+      *)    app_path=$APP_HOME$link ;;
+    esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+    echo "$*"
+} >&2
+
+die () {
+    echo
+    echo "$*"
+    echo
+    exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in                #(
+  CYGWIN* )         cygwin=true  ;; #(
+  Darwin* )         darwin=true  ;; #(
+  MSYS* | MINGW* )  msys=true    ;; #(
+  NONSTOP* )        nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD=$JAVA_HOME/jre/sh/java
+    else
+        JAVACMD=$JAVA_HOME/bin/java
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD=java
+    if ! command -v java >/dev/null 2>&1
+    then
+        die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+    case $MAX_FD in #(
+      max*)
+        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+        # shellcheck disable=SC2039,SC3045
+        MAX_FD=$( ulimit -H -n ) ||
+            warn "Could not query maximum file descriptor limit"
+    esac
+    case $MAX_FD in  #(
+      '' | soft) :;; #(
+      *)
+        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+        # shellcheck disable=SC2039,SC3045
+        ulimit -n "$MAX_FD" ||
+            warn "Could not set maximum file descriptor limit to $MAX_FD"
+    esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+#   * args from the command line
+#   * the main class name
+#   * -classpath
+#   * -D...appname settings
+#   * --module-path (only if needed)
+#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+    APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+    CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+    JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    for arg do
+        if
+            case $arg in                                #(
+              -*)   false ;;                            # don't mess with options #(
+              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath
+                    [ -e "$t" ] ;;                      #(
+              *)    false ;;
+            esac
+        then
+            arg=$( cygpath --path --ignore --mixed "$arg" )
+        fi
+        # Roll the args list around exactly as many times as the number of
+        # args, so each arg winds up back in the position where it started, but
+        # possibly modified.
+        #
+        # NB: a `for` loop captures its iteration list before it begins, so
+        # changing the positional parameters here affects neither the number of
+        # iterations, nor the values presented in `arg`.
+        shift                   # remove old arg
+        set -- "$@" "$arg"      # push replacement arg
+    done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+#   * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+#     and any embedded shellness will be escaped.
+#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+#     treated as '${Hostname}' itself on the command line.
+
+set -- \
+        "-Dorg.gradle.appname=$APP_BASE_NAME" \
+        -classpath "$CLASSPATH" \
+        org.gradle.wrapper.GradleWrapperMain \
+        "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+    die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+#   readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+#   set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+        printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+        xargs -n1 |
+        sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+        tr '\n' ' '
+    )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644 (file)
index 0000000..25da30d
--- /dev/null
@@ -0,0 +1,92 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem      https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem  Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/pom.xml b/pom.xml
deleted file mode 100644 (file)
index d15d786..0000000
--- a/pom.xml
+++ /dev/null
@@ -1,55 +0,0 @@
-<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-    <modelVersion>4.0.0</modelVersion>
-    <groupId>eu.svjatoslav</groupId>
-    <artifactId>aukio</artifactId>
-    <version>2.0.0-SNAPSHOT</version>
-    <packaging>pom</packaging>
-    <name>Aukio</name>
-    <description>Spatial computing environment on Aukio 3D 2</description>
-
-    <properties>
-        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
-        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
-        <maven.compiler.release>21</maven.compiler.release>
-    </properties>
-
-    <organization>
-        <name>svjatoslav.eu</name>
-        <url>http://svjatoslav.eu</url>
-    </organization>
-
-    <!-- The workspace is the application; aukio-3d-2 is its engine and the
-         Fallout 4 loader is an add-on (its own repository). Aukio 3D v1
-         support was removed on 2026-10-31: nothing here depends on it. -->
-    <modules>
-        <module>workspace-v2</module>
-    </modules>
-
-    <distributionManagement>
-        <snapshotRepository>
-            <id>svjatoslav.eu</id>
-            <name>svjatoslav.eu</name>
-            <url>scpexe://svjatoslav.eu:10006/srv/maven</url>
-        </snapshotRepository>
-        <repository>
-            <id>svjatoslav.eu</id>
-            <name>svjatoslav.eu</name>
-            <url>scpexe://svjatoslav.eu:10006/srv/maven</url>
-        </repository>
-    </distributionManagement>
-
-    <repositories>
-        <repository>
-            <id>svjatoslav.eu</id>
-            <name>Svjatoslav repository</name>
-            <url>https://www3.svjatoslav.eu/maven/</url>
-        </repository>
-    </repositories>
-
-    <scm>
-        <connection>scm:git:ssh://n0@svjatoslav.eu:10006/home/n0/git/aukio.git</connection>
-        <developerConnection>scm:git:ssh://n0@svjatoslav.eu:10006/home/n0/git/aukio.git</developerConnection>
-        <tag>HEAD</tag>
-    </scm>
-</project>
diff --git a/settings.gradle b/settings.gradle
new file mode 100644 (file)
index 0000000..5d495a8
--- /dev/null
@@ -0,0 +1,14 @@
+rootProject.name = 'aukio'
+
+// Flat project names, directory layout kept: Modules/ and Applications/ are
+// folders, not projects, so no empty jar is built for them.
+include 'scheduler', 'world', 'gi', 'renderer', 'navigation', 'swing', 'hid', 'demos'
+
+project(':scheduler').projectDir = file('Modules/scheduler')
+project(':world').projectDir = file('Modules/world')
+project(':gi').projectDir = file('Modules/gi')
+project(':renderer').projectDir = file('Modules/renderer')
+project(':navigation').projectDir = file('Modules/navigation')
+project(':swing').projectDir = file('Modules/swing')
+project(':hid').projectDir = file('Modules/hid')
+project(':demos').projectDir = file('Applications/demos')
diff --git a/verify.sh b/verify.sh
deleted file mode 100755 (executable)
index 3ae8946..0000000
--- a/verify.sh
+++ /dev/null
@@ -1,130 +0,0 @@
-#!/usr/bin/env bash
-# THE GATE. Nothing is reported fixed until this prints GATE PASS.
-#
-#   ./verify.sh           unit suites + every scenario in verification/scenarios.tsv
-#   ./verify.sh --quick   unit suites only (no game data, ~1.5 min)
-#   ./verify.sh --list    show the registered scenarios
-#
-# Rules this script exists to enforce (AGENTS.org, "Streaming coverage"):
-#  - a scenario drives the PRODUCTION code over time; a screenshot cannot
-#    distinguish "did not load" from "loaded and hidden"
-#  - every bug report becomes a scenario here, with the reporter's pose
-#  - a subsystem fix that breaks another subsystem's scenario fails the gate
-#
-# Exit code 0 = everything passed.
-set -uo pipefail
-
-HERE="$(cd "$(dirname "$0")" && pwd)"
-ENGINE="$HERE/../aukio-3d-2"
-FO4="$HERE/../aukio-environment-fo4-2"
-SCENARIOS="$HERE/verification/scenarios.tsv"
-KNOWN_FAILURES="$HERE/verification/known-failures.tsv"
-CLASSES="$HOME/.hermes/cache/scratch/verify-gate/classes"
-LOGS="$HOME/.hermes/cache/scratch/verify-gate/logs"
-JAVA_HOME_21="${JAVA_HOME_21:-/usr/lib/jvm/java-21-openjdk-amd64}"
-JAVA_BIN="${JAVA_BIN:-/usr/lib/jvm/java-25-openjdk-amd64/bin/java}"
-
-mkdir -p "$CLASSES" "$LOGS"
-
-MODE="${1:-all}"
-if [ "$MODE" = "--list" ]; then
-    cat "$SCENARIOS"
-    exit 0
-fi
-
-fail=0
-declare -a ROWS
-
-step() { # name, command-string
-    local name="$1"; shift
-    local log="$LOGS/$(echo "$name" | tr ' /' '__').log"
-    local start; start=$(date +%s)
-    if "$@" > "$log" 2>&1; then
-        local took=$(( $(date +%s) - start ))
-        ROWS+=("$(printf '%-34s PASS  %4ds' "$name" "$took")")
-        printf '%-34s PASS  %4ds\n' "$name" "$took"
-        return 0
-    fi
-    local took=$(( $(date +%s) - start ))
-    ROWS+=("$(printf '%-34s FAIL  %4ds  %s' "$name" "$took" "$log")")
-    printf '%-34s FAIL  %4ds  %s\n' "$name" "$took" "$log"
-    tail -20 "$log" | sed 's/^/    /'
-    fail=1
-    return 1
-}
-
-echo "== unit suites =="
-step "engine tests (aukio-3d-2)" \
-    bash -c "cd '$ENGINE' && xvfb-run -a mvn -o -q test"
-step "engine install" \
-    bash -c "cd '$ENGINE' && mvn -o -q -DskipTests install"
-step "fo4 tests (fo4-2)" \
-    bash -c "cd '$FO4' && xvfb-run -a mvn -o -q test"
-# The memory model: TLC proves the protocol, jcstress proves the ORDERING the
-# protocol relies on on real CPUs (one writer, one reader, C2 stress flags).
-# A forbidden outcome here is a lost update or a hole, not a crash.
-step "memory model (jcstress)" \
-    bash -c "'$ENGINE/verification/jcstress/run.sh'"
-# The model registry: every active TLA+ model must have a gate config, a
-# non-vacuity config and a Maven execution, or it silently stops being checked.
-step "model registry (TLA+) engine" \
-    bash -c "cd '$ENGINE/Model' && ./check-models.sh"
-# The FO4 environment owns its own models (streaming coverage, atomic
-# replacement, the triangle budget, the residency plan). They used to live in
-# the engine repo, which meant FO4 policies were gated by a repo they do not
-# belong to — and a model could be added on one side and never run.
-step "model registry (TLA+) fo4" \
-    bash -c "cd '$FO4/Model' && ./check-models.sh"
-
-if [ "$MODE" = "--quick" ]; then
-    [ "$fail" -eq 0 ] && echo && echo "GATE PASS (quick: unit suites only)"
-    exit "$fail"
-fi
-
-echo
-echo "== scenarios (verification/scenarios.tsv) =="
-CP="$FO4/target/classes:$(cat "$FO4/target/cp.txt" 2>/dev/null):$CLASSES"
-step "compile scenario drivers" \
-    bash -c "'$JAVA_HOME_21/bin/javac' -cp '$CP' -d '$CLASSES' '$FO4'/verification/*.java"
-
-while IFS=$'\t' read -r name class args opts timeout; do
-    case "$name" in ''|'#'*) continue ;; esac
-    # Scenarios open a REAL window. Run them on a VIRTUAL display unless the
-    # caller already provided one: the gate must never put a window on the
-    # user's screen (it steals focus and, on a shared desktop, corrupts what
-    # the user is doing).
-    step "scenario $name" \
-        bash -c "cd '$FO4' && xvfb-run -a -s '-screen 0 3840x2160x24' timeout ${timeout:-300} '$JAVA_BIN' -Xmx20g -cp '$CP' $opts $class $args"
-done < "$SCENARIOS"
-
-# KNOWN FAILURES: reproduced, user-visible defects that are NOT fixed yet.
-# They are run and reported, and the gate does NOT pass them off as green —
-# but an entry that STARTS PASSING is an error too: either the fix landed and
-# the row must move to scenarios.tsv, or the row became vacuous.
-knownFail=0
-unexpectedPass=0
-if [ -f "$KNOWN_FAILURES" ]; then
-    echo
-    echo "== known failures (reported, not green) =="
-    while IFS=$'\t' read -r name class args opts timeout; do
-        case "$name" in ''|'#'*) continue ;; esac
-        log="$LOGS/known_$(echo "$name" | tr ' /' '__').log"
-        if (cd "$FO4" && xvfb-run -a -s '-screen 0 3840x2160x24' \
-                timeout ${timeout:-300} "$JAVA_BIN" -Xmx20g -cp "$CP" $opts $class $args) \
-                > "$log" 2>&1; then
-            unexpectedPass=$((unexpectedPass + 1))
-            printf '%-34s UNEXPECTED PASS — move it to scenarios.tsv\n' "known-fail $name"
-        else
-            knownFail=$((knownFail + 1))
-            printf '%-34s KNOWN-FAIL  %s\n' "known-fail $name" "$log"
-        fi
-    done < "$KNOWN_FAILURES"
-fi
-
-echo
-if [ "$fail" -eq 0 ] && [ "$unexpectedPass" -eq 0 ]; then
-    echo "GATE PASS${knownFail:+ (known failures: $knownFail)}"
-else
-    echo "GATE FAIL — logs in $LOGS"
-fi
-exit "$(( fail + unexpectedPass ))"