Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

addons: Tatami, a screensaver of small rooms that rearrange themselves

pbanddev19a22b25d806
diff --git a/addons/README.md b/addons/README.md
index 2d96e9c83..e9ceb9c03 100644
--- a/addons/README.md
+++ b/addons/README.md
@@ -9,6 +9,7 @@ the core bigger or change how it behaves. You install an add-on only if you want
| Add-on | What it does | Author | Tested on | Permissions | Screenshot |
|---|---|---|---|---|---|
+| [Tatami](tatami/) | A screensaver of small rooms that rearrange themselves in slow, quiet motion, in two looks that take turns, drawn live on the TV with no network; the card shows it full screen, with its effects one press away | [@PBandDev](https://github.com/PBandDev) | Sony Android TV 10 (model private) | None | <img src="tatami/screenshot.jpg" width="240" alt="Tatami on a TV"> |
| [Jewish Calendar](jewish-calendar/) | Offline Hebrew and Gregorian dates, holiday/Shabbat greetings, and an optional clock screensaver | [lionlev21](https://github.com/lionlev21) | Android TV 12 (model private) | None | <img src="jewish-calendar/screenshot.jpg" width="240" alt="Jewish Calendar on a TV"> |
| [Nepali Calendar](nepali-calendar/) | Offline Bikram Sambat and Gregorian dates in Devanagari and Latin, a BS month grid with weekends and fixed-date national days in red, and an optional clock screensaver | [@1yuv](https://github.com/1yuv) | Hisense 50A6H4 (SmartTV 4K, songshan), Android TV 11 | None | <img src="nepali-calendar/screenshot.jpg" width="240" alt="Nepali Calendar on a TV"> |
| [Frigate Glance](frigate-glance/) | Frigate camera pop-ups over whatever is playing | [NickLD](https://github.com/NickLD) | TCL 65Q650G | overlay, accessibility (card keys), network, foreground service, start at boot | <img src="frigate-glance/screenshot.jpg" width="240" alt="Frigate Glance on a TV"> |
diff --git a/addons/tatami/.gitignore b/addons/tatami/.gitignore
new file mode 100644
index 000000000..4718a20ac
--- /dev/null
+++ b/addons/tatami/.gitignore
@@ -0,0 +1,9 @@
+.gradle/
+build/
+app/build/
+local.properties
+*.apk
+shots/
+.idea/
+*.iml
+__pycache__/
diff --git a/addons/tatami/LICENSE b/addons/tatami/LICENSE
new file mode 100644
index 000000000..ecf02c96f
--- /dev/null
+++ b/addons/tatami/LICENSE
@@ -0,0 +1,22 @@
+MIT License
+
+Copyright (c) 2026 PBandDev
+Copyright (c) 2026 Gathin (the home screen launcher, from https://github.com/Gathin23/cleanyourtv)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/addons/tatami/README.md b/addons/tatami/README.md
new file mode 100644
index 000000000..34644c14b
--- /dev/null
+++ b/addons/tatami/README.md
@@ -0,0 +1,79 @@
+# Tatami
+
+A screensaver for Android TV, and a card on cleanyourtv's Home. Small rooms rearrange themselves in slow, quiet
+motion, drawn live on the TV. Inspired by the ending of *The Tatami Galaxy* (2010). It has two looks, and by
+default they take turns:
+
+- **Nagaya**: rows of small, warm rooms, like a row house. A few walls at a time glide to new places, each on its
+ own time, and then rest. The doors swing open and shut in a slow ripple, and the camera slowly rolls, zooms and
+ drifts.
+- **Yojōhan**: olive rooms cut like tatami mats around a half mat. One room grows while the room next to it
+ shrinks.
+
+![Tatami full screen: Nagaya's walls glide and its doors swing, a dip to dark swaps it for Yojōhan, and one room grows as the next shrinks](https://raw.githubusercontent.com/PBandDev/tatami-home/bf3b3d9eaa09572d4a962dc57241dd48c000991c/docs/tatami.webp)
+
+- Package: `io.github.pbanddev.tatami`
+- Author: [PBandDev](https://github.com/PBandDev) ([issues](https://github.com/PBandDev/tatami-home/issues))
+- Tested on: Sony Android TV 10 (model private), 1080p, a steady 60 fps
+
+## Permissions
+
+None. No network access (no `INTERNET` permission): nothing leaves the TV. No background service: Tatami runs
+only while the screensaver or its own screen is showing. It is drawn live with OpenGL ES 2.0 and uses no footage
+from the show.
+
+## Install
+
+From your cleanyourtv checkout, with its `tools/venv` set up as its README says:
+
+```bash
+TV_HOST=<tv ip> tools/venv/bin/python -I tools/manage.py install tatami
+```
+
+Or tell your coding agent: *Install the Tatami add-on from addons/tatami on my TV at \<tv ip\>.*
+
+Or run its script yourself:
+
+```bash
+TV_HOST=<tv ip> addons/tatami/install.sh # macOS, Linux, Git Bash
+powershell -ExecutionPolicy Bypass -File addons\tatami\install.ps1 -TvHost <tv ip> # Windows
+```
+
+No JDK or Android SDK on this computer? Build it with Docker, then install what it built:
+
+```bash
+tools/docker-build.sh addons/tatami
+SKIP_BUILD=1 TV_HOST=<tv ip> addons/tatami/install.sh
+```
+
+The script builds Tatami, installs it, makes it the TV's screensaver (it keeps the old one, for the undo below),
+says when the screensaver starts, and opens Tatami once so you see it. Then press Home: the launcher asks once
+whether to show the Tatami card.
+
+## Use it
+
+- **The card:** press OK on it to see Tatami full screen. Press OK again for the effects, Back to leave.
+- **The effects:** the first row picks the **Look**: Both (the default), Nagaya or Yojōhan. The next sets how
+ often Both swaps looks: every 5, 10, 30 or 60 minutes, with a short dip to dark. Below them, turn each effect on
+ or off and see it change behind the list: film grain, vignette, tilt-shift edges, doors, fixtures, and camera
+ drift and zoom. In Nagaya, the vignette switch turns its colour wash on and off, the camera switch holds the
+ view still (the walls and doors still move), and fixtures do nothing.
+- **The screensaver** uses the same look and effects. It starts when the TV's own wait runs out: Settings >
+ Device Preferences > Screen saver > When to start. To see it now:
+ `TV_HOST=<tv ip> tools/venv/bin/python -I tools/tv.py 'am start -n com.android.systemui/.Somnambulator'`
+- **Any launcher:** Tatami is also a normal app tile, and the screensaver works with every launcher.
+
+## Remove
+
+```bash
+TV_HOST=<tv ip> addons/tatami/install.sh --uninstall # the old screensaver back, Tatami removed
+```
+
+## Tatami behind your apps
+
+Want Tatami moving behind the apps on Home, not only as a screensaver? [Tatami Home](https://github.com/PBandDev/tatami-home)
+is cleanyourtv's launcher with Tatami built in. You need only one of the two.
+
+## License
+
+MIT: [LICENSE](LICENSE). How Tatami is drawn and tested: [how it works](https://github.com/PBandDev/tatami-home/blob/main/docs/how-it-works.md).
diff --git a/addons/tatami/app/build.gradle b/addons/tatami/app/build.gradle
new file mode 100644
index 000000000..e9f7f153d
--- /dev/null
+++ b/addons/tatami/app/build.gradle
@@ -0,0 +1,35 @@
+plugins {
+ id 'com.android.application'
+}
+
+android {
+ namespace 'io.github.pbanddev.tatami.app'
+ compileSdk 34
+
+ defaultConfig {
+ applicationId 'io.github.pbanddev.tatami'
+ minSdk 26
+ targetSdk 34
+ versionCode 1
+ versionName '1.0'
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled true
+ shrinkResources true
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ // Sideloaded over ADB like cleanyourtv's launcher: signed with the local debug key.
+ signingConfig signingConfigs.debug
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+}
+
+dependencies {
+ implementation project(':plan')
+}
diff --git a/addons/tatami/app/proguard-rules.pro b/addons/tatami/app/proguard-rules.pro
new file mode 100644
index 000000000..7bb3d36ed
--- /dev/null
+++ b/addons/tatami/app/proguard-rules.pro
@@ -0,0 +1,4 @@
+# Shrink and optimise, but keep class and method names: the size win comes from dropping unused
+# AndroidX code, not from renaming, and readable stack traces matter more in a sideloaded app
+# where crash reports arrive as screenshots.
+-dontobfuscate
diff --git a/addons/tatami/app/src/main/AndroidManifest.xml b/addons/tatami/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..a004c090b
--- /dev/null
+++ b/addons/tatami/app/src/main/AndroidManifest.xml
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- No permissions: Tatami is drawn on the TV, and nothing goes over the network. -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses-feature android:name="android.software.leanback" android:required="false" />
+ <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
+
+ <application
+ android:allowBackup="false"
+ android:banner="@drawable/banner"
+ android:icon="@drawable/icon"
+ android:label="@string/app_name"
+ android:theme="@style/Theme.Tatami">
+
+ <!-- The tile, and the card on cleanyourtv's Home (docs/modules.md): Tatami full screen. OK opens the
+ effects list, Back leaves. -->
+ <activity
+ android:name="io.github.pbanddev.tatami.PreviewActivity"
+ android:exported="true"
+ android:screenOrientation="landscape">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="com.gathin.tvhome.category.DOCK_CARD" />
+ </intent-filter>
+ <meta-data android:name="com.gathin.tvhome.card" android:resource="@xml/module_card" />
+ </activity>
+
+ <!-- The effects list over Tatami. Exported so the TV's screensaver settings can open it (dream_info.xml).
+ Single-top, so a look given as an extra reaches it while it is open. -->
+ <activity
+ android:name="io.github.pbanddev.tatami.SettingsActivity"
+ android:exported="true"
+ android:launchMode="singleTop"
+ android:screenOrientation="landscape" />
+
+ <!-- The screensaver: Settings > Device Preferences > Screen saver > Tatami. install.sh sets it. -->
+ <service
+ android:name="io.github.pbanddev.tatami.FloorPlanDream"
+ android:exported="true"
+ android:label="@string/app_name"
+ android:permission="android.permission.BIND_DREAM_SERVICE">
+ <intent-filter>
+ <action android:name="android.service.dreams.DreamService" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ <meta-data
+ android:name="android.service.dream"
+ android:resource="@xml/dream_info" />
+ </service>
+ </application>
+</manifest>
diff --git a/addons/tatami/app/src/main/res/values/strings.xml b/addons/tatami/app/src/main/res/values/strings.xml
new file mode 100644
index 000000000..31e8e3964
--- /dev/null
+++ b/addons/tatami/app/src/main/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Tatami</string>
+</resources>
diff --git a/addons/tatami/app/src/main/res/xml/dream_info.xml b/addons/tatami/app/src/main/res/xml/dream_info.xml
new file mode 100644
index 000000000..d3de0d9f8
--- /dev/null
+++ b/addons/tatami/app/src/main/res/xml/dream_info.xml
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="utf-8"?>
+<dream xmlns:android="http://schemas.android.com/apk/res/android"
+ android:settingsActivity="io.github.pbanddev.tatami/.SettingsActivity" />
diff --git a/addons/tatami/app/src/main/res/xml/module_card.xml b/addons/tatami/app/src/main/res/xml/module_card.xml
new file mode 100644
index 000000000..631aabe5c
--- /dev/null
+++ b/addons/tatami/app/src/main/res/xml/module_card.xml
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- cleanyourtv's module card (docs/specs/card.md). The accent is Nagaya's amber. -->
+<card spec="1" label="Tatami" accent="#DA8417" />
diff --git a/addons/tatami/build.gradle b/addons/tatami/build.gradle
new file mode 100644
index 000000000..c9d9f3b91
--- /dev/null
+++ b/addons/tatami/build.gradle
@@ -0,0 +1,4 @@
+plugins {
+ id 'com.android.application' version '8.5.2' apply false
+ id 'com.android.library' version '8.5.2' apply false
+}
diff --git a/addons/tatami/gradle.properties b/addons/tatami/gradle.properties
new file mode 100644
index 000000000..fa57cfcbc
--- /dev/null
+++ b/addons/tatami/gradle.properties
@@ -0,0 +1,2 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+android.nonTransitiveRClass=true
diff --git a/addons/tatami/gradle/wrapper/gradle-wrapper.jar b/addons/tatami/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..2c3521197
Binary files /dev/null and b/addons/tatami/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/addons/tatami/gradle/wrapper/gradle-wrapper.properties b/addons/tatami/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..77f5d0ba6
--- /dev/null
+++ b/addons/tatami/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,8 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
+distributionSha256Sum=d725d707bfabd4dfdc958c624003b3c80accc03f7037b5122c4b1d0ef15cecab
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/addons/tatami/gradlew b/addons/tatami/gradlew
new file mode 100755
index 000000000..f5feea6d6
--- /dev/null
+++ b/addons/tatami/gradlew
@@ -0,0 +1,252 @@
+#!/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.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# 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/platforms/jvm/plugins-application/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 -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || 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/addons/tatami/gradlew.bat b/addons/tatami/gradlew.bat
new file mode 100644
index 000000000..9d21a2183
--- /dev/null
+++ b/addons/tatami/gradlew.bat
@@ -0,0 +1,94 @@
+@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
+@rem SPDX-License-Identifier: Apache-2.0
+@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/addons/tatami/install.ps1 b/addons/tatami/install.ps1
new file mode 100644
index 000000000..a4e1000a0
--- /dev/null
+++ b/addons/tatami/install.ps1
@@ -0,0 +1,84 @@
+# Windows version of install.sh: build Tatami, install it on the TV, make it the TV's screensaver and open it once.
+#
+# Usage: .\install.ps1 -TvHost 192.168.1.50 build, install, make it the screensaver, show it
+# .\install.ps1 -TvHost 192.168.1.50 -NoShow the same, without opening Tatami at the end
+# .\install.ps1 -TvHost 192.168.1.50 -SkipBuild install the APK already built (tools/docker-build.sh addons/tatami)
+# .\install.ps1 -TvHost 192.168.1.50 -Uninstall previous screensaver back, app removed
+# $env:TV_HOST and $env:SKIP_BUILD = '1' work as well.
+#
+# In a cleanyourtv checkout this is addons\tatami\install.ps1 and uses that checkout's tools\. Anywhere else it uses
+# the cleanyourtv checkout in $env:CLEANYOURTV (default: ..\cleanyourtv next to this folder).
+param(
+ [string]$TvHost = $env:TV_HOST,
+ [switch]$Uninstall,
+ [switch]$NoShow,
+ [switch]$SkipBuild
+)
+$ErrorActionPreference = 'Stop'
+if (-not $TvHost) { throw 'pass -TvHost <tv ip> or set $env:TV_HOST' }
+$env:TV_HOST = $TvHost
+if ($env:SKIP_BUILD) { $SkipBuild = [switch]$true }
+$here = $PSScriptRoot
+$tools = Join-Path (Split-Path (Split-Path $here -Parent) -Parent) 'tools'
+if (-not (Test-Path (Join-Path $tools 'tv.py'))) {
+ if ($env:CLEANYOURTV) { $cyt = $env:CLEANYOURTV } else { $cyt = Join-Path (Split-Path $here -Parent) 'cleanyourtv' }
+ $tools = Join-Path $cyt 'tools'
+}
+if (-not (Test-Path (Join-Path $tools 'tv.py'))) {
+ throw "no cleanyourtv tools at ${tools}: clone https://github.com/Gathin23/cleanyourtv next to this folder, or set `$env:CLEANYOURTV to your checkout"
+}
+$py = Join-Path $tools 'venv\Scripts\python.exe'
+if (-not (Test-Path $py)) { throw 'run: python -m venv tools\venv; tools\venv\Scripts\python.exe -m pip install -r tools\requirements.txt' }
+$tvpy = Join-Path $tools 'tv.py'
+$pkg = 'io.github.pbanddev.tatami'
+$dream = "$pkg/.FloorPlanDream"
+# The screensaver the TV had before the first run, so -Uninstall can put it back.
+$before = '/data/local/tmp/cyt-tatami-before'
+function Tv([string]$cmd) { & $py -I $tvpy $cmd; if ($LASTEXITCODE) { throw "tv.py failed: $cmd" } }
+
+if ($Uninstall) {
+ # Put the screensaver from before the first run back, then remove the app.
+ Tv "if [ -f $before ]; then { read c; read e; } < $before; if [ `"`$c`" = null ]; then settings delete secure screensaver_components >/dev/null; else settings put secure screensaver_components `"`$c`"; fi; [ `"`$e`" = null ] || settings put secure screensaver_enabled `"`$e`"; rm -f $before; fi; pm uninstall $pkg; echo screensaver: `$(settings get secure screensaver_components)"
+ exit 0
+}
+
+if (-not $SkipBuild) {
+ Push-Location $here
+ try {
+ & .\gradlew.bat assembleRelease -q
+ if ($LASTEXITCODE) { throw 'build failed (JDK 17 and Android SDK 34 needed; or build with tools/docker-build.sh addons/tatami and pass -SkipBuild)' }
+ } finally { Pop-Location }
+}
+$apk = Join-Path $here 'app\build\outputs\apk\release\app-release.apk'
+if (-not (Test-Path $apk)) { throw "no ${apk}: build it first (gradlew.bat assembleRelease, or tools/docker-build.sh addons/tatami)" }
+
+# Wake first: on some sets an install waits while a screensaver is up.
+Tv 'input keyevent WAKEUP' | Out-Null
+& $py -I (Join-Path $tools 'b64push.py') $apk /data/local/tmp/tatami.apk | Out-Null
+if ($LASTEXITCODE) { throw 'sending the APK failed' }
+$out = (Tv 'pm install -r /data/local/tmp/tatami.apk; rm -f /data/local/tmp/tatami.apk') -join "`n"
+if ($out -notmatch 'Success') { throw "install failed: Tatami is not on the TV. $out" }
+# Compiled ahead of time, so the first frames are smooth. Not every Android version has the command.
+try { & $py -I $tvpy "cmd package compile -m speed -f $pkg" | Out-Null } catch { }
+Tv "[ -f $before ] || { settings get secure screensaver_components; settings get secure screensaver_enabled; } > $before; settings put secure screensaver_components $dream; settings put secure screensaver_enabled 1" | Out-Null
+# TCL's TclAppBoot keeps sideloaded apps from starting, a screensaver too, unless they may auto-start (AUTO_START on
+# G08 builds, APP_AUTO_START on G10); elsewhere the op doesn't exist. write-settings saves it before the next reboot.
+Tv "appops set $pkg AUTO_START allow 2>/dev/null; appops set $pkg APP_AUTO_START allow 2>/dev/null; appops write-settings 2>/dev/null; true" | Out-Null
+
+# When the screensaver starts is the TV's own setting. Say what it is and how to change it; never change it here.
+$ms = ''
+try { $ms = "$((Tv 'settings get system screen_off_timeout') | Select-Object -Last 1)".Trim() } catch { }
+[long]$n = 0
+if ([long]::TryParse($ms, [ref]$n)) {
+ if ($n -lt 0 -or $n -ge 2147483647) {
+ Write-Host 'The TV never starts its screensaver by itself (Settings > Device Preferences > Screen saver > When to start).'
+ } else {
+ $min = [long][math]::Ceiling($n / 60000)
+ if ($min -ge 60 -and $min % 60 -eq 0) { $when = "$($min / 60) h" } else { $when = "$min min" }
+ Write-Host "The screensaver starts after $when with no key press (Settings > Device Preferences > Screen saver > When to start)."
+ }
+ Write-Host "To make it 5 min, from your cleanyourtv checkout: `$env:TV_HOST = '$TvHost'; tools\venv\Scripts\python.exe -I tools\tv.py 'settings put system screen_off_timeout 300000'"
+}
+
+if (-not $NoShow) { Tv "am start -n $pkg/.PreviewActivity" | Out-Null }
+Write-Host "Installed: Tatami is the screensaver. Undo with: $PSCommandPath -Uninstall"
diff --git a/addons/tatami/install.sh b/addons/tatami/install.sh
new file mode 100755
index 000000000..09a1ccf12
--- /dev/null
+++ b/addons/tatami/install.sh
@@ -0,0 +1,68 @@
+#!/usr/bin/env bash
+# Build Tatami, install it on the TV, make it the TV's screensaver and open it once so you see it.
+#
+# Usage: TV_HOST=192.168.1.50 ./install.sh build, install, make it the screensaver, show it
+# TV_HOST=192.168.1.50 ./install.sh --no-show the same, without opening Tatami at the end
+# TV_HOST=192.168.1.50 SKIP_BUILD=1 ./install.sh install the APK already built (tools/docker-build.sh addons/tatami)
+# TV_HOST=192.168.1.50 ./install.sh --uninstall previous screensaver back, app removed
+#
+# In a cleanyourtv checkout this is addons/tatami/install.sh and uses that checkout's tools/. Anywhere else it uses
+# the cleanyourtv checkout in CLEANYOURTV (default: ../cleanyourtv next to this folder).
+set -euo pipefail
+HERE="$(cd "$(dirname "$0")" && (pwd -W 2>/dev/null || pwd))"
+case "$#:${1:-}" in 0:|1:--no-show|1:--uninstall) ;; *) echo "usage: $0 [--no-show | --uninstall]" >&2; exit 2 ;; esac
+: "${TV_HOST:?set TV_HOST to the TV IP address, e.g. TV_HOST=192.168.1.50 $0}"
+if [ -f "$HERE/../../tools/tv.py" ]; then TOOLS="$HERE/../../tools"; else TOOLS="${CLEANYOURTV:-$HERE/../cleanyourtv}/tools"; fi
+[ -f "$TOOLS/tv.py" ] || { echo "no cleanyourtv tools at $TOOLS: clone https://github.com/Gathin23/cleanyourtv next to this folder, or set CLEANYOURTV to your checkout" >&2; exit 1; }
+# Windows Python cannot open /c/... paths, so hand it C:/... where Git Bash has them.
+TOOLS="$(cd "$TOOLS" && (pwd -W 2>/dev/null || pwd))"
+PY="$TOOLS/venv/bin/python"
+[ -x "$PY" ] || PY="$TOOLS/venv/Scripts/python.exe"
+[ -x "$PY" ] || { echo "run: python3 -m venv tools/venv && tools/venv/bin/pip install -r tools/requirements.txt" >&2; exit 1; }
+export MSYS_NO_PATHCONV=1
+PKG=io.github.pbanddev.tatami
+DREAM=$PKG/.FloorPlanDream
+# The screensaver the TV had before the first run, so --uninstall can put it back.
+BEFORE=/data/local/tmp/cyt-tatami-before
+tv() { "$PY" -I "$TOOLS/tv.py" "$@"; }
+
+if [ "${1:-}" = --uninstall ]; then
+ tv "if [ -f $BEFORE ]; then { read c; read e; } < $BEFORE; if [ \"\$c\" = null ]; then settings delete secure screensaver_components >/dev/null; else settings put secure screensaver_components \"\$c\"; fi; [ \"\$e\" = null ] || settings put secure screensaver_enabled \"\$e\"; rm -f $BEFORE; fi; pm uninstall $PKG; echo screensaver: \$(settings get secure screensaver_components)"
+ exit 0
+fi
+
+if [ -z "${SKIP_BUILD:-}" ]; then
+ (cd "$HERE" && ./gradlew assembleRelease -q) || {
+ echo "build failed (JDK 17 and Android SDK 34 needed; or build with tools/docker-build.sh addons/tatami and run with SKIP_BUILD=1)" >&2; exit 1; }
+fi
+APK="$HERE/app/build/outputs/apk/release/app-release.apk"
+[ -f "$APK" ] || { echo "no $APK: build it first (./gradlew assembleRelease, or tools/docker-build.sh addons/tatami)" >&2; exit 1; }
+
+# Wake first: on some sets an install waits while a screensaver is up.
+tv 'input keyevent WAKEUP' >/dev/null
+"$PY" -I "$TOOLS/b64push.py" "$APK" /data/local/tmp/tatami.apk >/dev/null
+OUT="$(tv 'pm install -r /data/local/tmp/tatami.apk; rm -f /data/local/tmp/tatami.apk')"
+case "$OUT" in *Success*) ;; *) echo "$OUT" >&2; echo "install failed: Tatami is not on the TV" >&2; exit 1 ;; esac
+# Compiled ahead of time, so the first frames are smooth. Not every Android version has the command.
+tv "cmd package compile -m speed -f $PKG" >/dev/null 2>&1 || true
+tv "[ -f $BEFORE ] || { settings get secure screensaver_components; settings get secure screensaver_enabled; } > $BEFORE; settings put secure screensaver_components $DREAM; settings put secure screensaver_enabled 1" >/dev/null
+# TCL's TclAppBoot keeps sideloaded apps from starting, a screensaver too, unless they may auto-start (AUTO_START on
+# G08 builds, APP_AUTO_START on G10); elsewhere the op doesn't exist. write-settings saves it before the next reboot.
+tv "appops set $PKG AUTO_START allow 2>/dev/null; appops set $PKG APP_AUTO_START allow 2>/dev/null; appops write-settings 2>/dev/null; true" >/dev/null
+
+# When the screensaver starts is the TV's own setting. Say what it is and how to change it; never change it here.
+MS="$(tv 'settings get system screen_off_timeout' | tr -d '\r' | tail -n 1)" || MS=""
+SHOWPY="tools/${PY#"$TOOLS/"}"
+if [[ "$MS" =~ ^-?[0-9]+$ ]]; then
+ if [ "$MS" -lt 0 ] || [ "$MS" -ge 2147483647 ]; then
+ echo "The TV never starts its screensaver by itself (Settings > Device Preferences > Screen saver > When to start)."
+ else
+ MIN=$(( (MS + 59999) / 60000 ))
+ if [ "$MIN" -ge 60 ] && [ $(( MIN % 60 )) -eq 0 ]; then WHEN="$(( MIN / 60 )) h"; else WHEN="$MIN min"; fi
+ echo "The screensaver starts after $WHEN with no key press (Settings > Device Preferences > Screen saver > When to start)."
+ fi
+ echo "To make it 5 min, from your cleanyourtv checkout: TV_HOST=$TV_HOST $SHOWPY -I tools/tv.py 'settings put system screen_off_timeout 300000'"
+fi
+
+[ "${1:-}" = --no-show ] || tv "am start -n $PKG/.PreviewActivity" >/dev/null
+echo "Installed: Tatami is the screensaver. Undo with: $0 --uninstall"
diff --git a/addons/tatami/plan/build.gradle b/addons/tatami/plan/build.gradle
new file mode 100644
index 000000000..a0a33ae8b
--- /dev/null
+++ b/addons/tatami/plan/build.gradle
@@ -0,0 +1,23 @@
+plugins {
+ id 'com.android.library'
+}
+
+// Tatami itself: the plan, its two looks, the effects, the full-screen view, the effects list and the
+// screensaver. The apps that use it (app/ and home/app/) declare the activities and the screensaver.
+android {
+ namespace 'io.github.pbanddev.tatami'
+ compileSdk 34
+
+ defaultConfig {
+ minSdk 26
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+}
+
+dependencies {
+ testImplementation 'junit:junit:4.13.2'
+}
diff --git a/addons/tatami/plan/src/main/AndroidManifest.xml b/addons/tatami/plan/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..b44786248
--- /dev/null
+++ b/addons/tatami/plan/src/main/AndroidManifest.xml
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- No components here: each app declares the ones it shows. -->
+<manifest />
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Camera.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Camera.java
new file mode 100644
index 000000000..fe81dfa51
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Camera.java
@@ -0,0 +1,54 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * The view onto the plan: tilted by the look's angle, drifting slowly and pulling in and back out
+ * over a few minutes. The plan is sized so that, tilted and panned as far as the drift goes, it
+ * still covers every corner of the screen; the zoom only ever pulls in, so it never shows an edge.
+ */
+public final class Camera {
+ private static final float PAN = 0.03f;
+ private static final double PAN_SPEED_X = 0.05;
+ private static final double PAN_SPEED_Y = 0.037;
+ private static final float ZOOM_RANGE = 0.15f;
+ private static final double ZOOM_SPEED = 0.021;
+ /**
+ * Spare plan past the screen's corners at the farthest pan. The copy to blur is drawn up to 24 px past
+ * every screen edge ({@link Lens#margin}, padded to whole GPU tiles), so that strip must be plan too:
+ * 6 % covers it down to 720p.
+ */
+ private static final float MARGIN = 1.06f;
+
+ private Camera() {}
+
+ public static float panX(double t, float w, boolean moving) {
+ return moving ? (float) (PAN * w * Math.sin(t * PAN_SPEED_X)) : 0f;
+ }
+
+ public static float panY(double t, float h, boolean moving) {
+ return moving ? (float) (PAN * h * Math.cos(t * PAN_SPEED_Y)) : 0f;
+ }
+
+ /** 1 is the widest view; the camera pulls in to 1.15 and back. */
+ public static float zoom(double t, boolean moving) {
+ return moving ? 1f + ZOOM_RANGE * 0.5f * (1f - (float) Math.cos(t * ZOOM_SPEED)) : 1f;
+ }
+
+ /** The plan's width for a w by h screen with the plan tilted by {@code angleDeg}. */
+ public static float planWidth(float w, float h, float angleDeg) {
+ double a = Math.toRadians(angleDeg), cos = Math.cos(a), sin = Math.abs(Math.sin(a));
+ return (float) (2 * MARGIN * (reachX(w) * cos + reachY(h) * sin));
+ }
+
+ public static float planHeight(float w, float h, float angleDeg) {
+ double a = Math.toRadians(angleDeg), cos = Math.cos(a), sin = Math.abs(Math.sin(a));
+ return (float) (2 * MARGIN * (reachX(w) * sin + reachY(h) * cos));
+ }
+
+ private static double reachX(float w) {
+ return w / 2.0 + PAN * w;
+ }
+
+ private static double reachY(float h) {
+ return h / 2.0 + PAN * h;
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/CameraCurve.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/CameraCurve.java
new file mode 100644
index 000000000..1e18f02ac
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/CameraCurve.java
@@ -0,0 +1,10 @@
+package io.github.pbanddev.tatami;
+
+/** A look's camera: what it sees at a time. */
+interface CameraCurve {
+ /**
+ * Fills {@code view} and {@code matrix} (plan units to clip space, column-major 4x4) for time {@code t} on a
+ * {@code w} by {@code h} screen. {@code moving} false holds the camera at rest.
+ */
+ void at(double t, int w, int h, boolean moving, View view, float[] matrix);
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/CameraMatrix.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/CameraMatrix.java
new file mode 100644
index 000000000..3e2ee8325
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/CameraMatrix.java
@@ -0,0 +1,26 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * The {@link Camera} as one OpenGL matrix (column-major, 4x4): plan units in, clip space out.
+ * Screen = centre + rotate(angle) * zoom * plan, with y pointing down, then mapped to -1..1.
+ */
+public final class CameraMatrix {
+ private CameraMatrix() {}
+
+ public static void build(double t, float w, float h, boolean moving, float angleDeg, float[] out) {
+ double angle = Math.toRadians(angleDeg);
+ float zoom = Camera.zoom(t, moving);
+ float cos = (float) Math.cos(angle) * zoom, sin = (float) Math.sin(angle) * zoom;
+ float cx = w / 2 + Camera.panX(t, w, moving);
+ float cy = h / 2 + Camera.panY(t, h, moving);
+ java.util.Arrays.fill(out, 0f);
+ out[0] = 2 * cos / w; // clip x from plan x
+ out[1] = -2 * sin / h; // clip y from plan x
+ out[4] = -2 * sin / w; // clip x from plan y
+ out[5] = -2 * cos / h; // clip y from plan y
+ out[10] = 1f;
+ out[12] = 2 * cx / w - 1;
+ out[13] = 1 - 2 * cy / h;
+ out[15] = 1f;
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/DoorPlacer.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/DoorPlacer.java
new file mode 100644
index 000000000..1a4eb6f86
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/DoorPlacer.java
@@ -0,0 +1,6 @@
+package io.github.pbanddev.tatami;
+
+/** A look's doors: fills the door arrays of a laid-out {@link Frame} for time {@code t}. Runs every frame. */
+interface DoorPlacer {
+ void place(Frame f, double t, View view);
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/DoorShapes.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/DoorShapes.java
new file mode 100644
index 000000000..765436d21
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/DoorShapes.java
@@ -0,0 +1,64 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * Draws one door of a {@link Frame} into the {@link SceneMesh}: a pale bar inside the wall,
+ * always there, and the swing, a filled sector from the wall face to the leaf with dark strokes on the arc
+ * and the leaf (none along the wall face). A shut door is only its bar. The bar and the sector are fills, which a
+ * {@link Wash} reaches; the strokes are ink, which it never does.
+ *
+ * <p>In the door's own frame u runs along the wall from the hinge toward the bar's far end and v across
+ * the wall toward the swing side, with the wall's centre line at v = 0. The swing turns about the hinge on
+ * the wall face, (0, wall / 2), from u (shut) toward v.
+ */
+final class DoorShapes {
+ private static final int ARC_SEGMENTS = 10;
+ /** The most vertices one door adds: the bar, the sector's fan, the leaf, then the arc as lines. */
+ static final int MAX_VERTICES = 6 + 3 * ARC_SEGMENTS + 6 + 6 * ARC_SEGMENTS;
+
+ private DoorShapes() {}
+
+ static void add(SceneMesh m, Frame f, int d, float screenHeight, Look look) {
+ Look.Doors door = look.doors;
+ float wall = screenHeight * look.walls.widthH, length = screenHeight * door.lengthH;
+ float bar = Math.min(screenHeight * door.barHalfH, wall / 2);
+ float radius = screenHeight * door.radiusH, line = screenHeight * door.lineH;
+ boolean vertical = f.wallVertical[f.doorWall[d]];
+ float ux = vertical ? 0 : f.doorAlong[d], uy = vertical ? f.doorAlong[d] : 0;
+ float vx = vertical ? f.doorSide[d] : 0, vy = vertical ? 0 : f.doorSide[d];
+ float x = f.doorX[d], y = f.doorY[d];
+
+ m.color(look.palette.door);
+ float x0 = x - vx * bar, y0 = y - vy * bar, x1 = x + vx * bar, y1 = y + vy * bar;
+ float lx = ux * length, ly = uy * length;
+ m.triangle(x0, y0, x0 + lx, y0 + ly, x1 + lx, y1 + ly);
+ m.triangle(x0, y0, x1 + lx, y1 + ly, x1, y1);
+
+ double open = f.doorOpening[d];
+ if (!(open > 0)) return;
+ float hx = x + vx * wall / 2, hy = y + vy * wall / 2;
+ float px = hx + ux * radius, py = hy + uy * radius;
+ for (int s = 1; s <= ARC_SEGMENTS; s++) {
+ double a = open * s / ARC_SEGMENTS;
+ float c = radius * (float) Math.cos(a), n = radius * (float) Math.sin(a);
+ float qx = hx + ux * c + vx * n, qy = hy + uy * c + vy * n;
+ m.triangle(hx, hy, px, py, qx, qy);
+ px = qx;
+ py = qy;
+ }
+ m.ink(look.palette.line);
+ // the leaf reaches half a stroke past the arc, closing the corner where they meet
+ float reach = radius + line / 2;
+ float c = (float) Math.cos(open), n = (float) Math.sin(open);
+ m.line(hx, hy, hx + reach * (ux * c + vx * n), hy + reach * (uy * c + vy * n), line);
+ px = hx + ux * radius;
+ py = hy + uy * radius;
+ for (int s = 1; s <= ARC_SEGMENTS; s++) {
+ double a = open * s / ARC_SEGMENTS;
+ float ca = radius * (float) Math.cos(a), na = radius * (float) Math.sin(a);
+ float qx = hx + ux * ca + vx * na, qy = hy + uy * ca + vy * na;
+ m.line(px, py, qx, qy, line);
+ px = qx;
+ py = qy;
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/DoorTrack.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/DoorTrack.java
new file mode 100644
index 000000000..c1aaf9b39
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/DoorTrack.java
@@ -0,0 +1,67 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * Nagaya's door opening: one shared angle on a clock of its own ({@link Look.Doors.Track}), apart from the walls', so
+ * doors and walls rarely start together. Cycle c starts at {@code c * cycleSeconds} plus a jitter hashed from the seed
+ * and c. In a cycle the doors swing open along {@link Ease#glide}, stay open for a time hashed per cycle, swing shut
+ * the same way, then rest shut until the next cycle. The ease starts and stops at rest and never overshoots, so the
+ * opening never jumps and never passes its most.
+ *
+ * <p>Each door runs a fixed delay behind the shared opening, hashed from the seed and its wall piece's id, so the
+ * doors swing in a ripple instead of all at once.
+ *
+ * <p>Pure: the same t always gives the same opening, whichever way the clock runs. The clock stays in double.
+ */
+final class DoorTrack {
+ private static final long STREAM = 0x7472616B636C6BL;
+ private static final int JITTER = 1, OPEN = 2, DELAY = 3;
+
+ private final Look.Doors.Track track;
+ private final long seed;
+ /** The most a door opens, in radians. */
+ private final double most;
+
+ DoorTrack(Look.Doors doors, long seed) {
+ track = doors.track;
+ this.seed = seed ^ STREAM;
+ most = Math.toRadians(doors.swingMaxDeg);
+ Look.Doors.Track k = track;
+ if (!(k.cycleSeconds > 0 && k.cycleJitterSeconds >= 0 && k.swingSeconds > 0 && k.openSeconds >= 0
+ && k.openSpreadSeconds >= 0 && k.rippleSeconds >= 0
+ && 2 * k.swingSeconds + k.openSeconds + k.openSpreadSeconds <= k.cycleSeconds - 2 * k.cycleJitterSeconds)) {
+ throw new IllegalArgumentException("door cycles would overlap");
+ }
+ }
+
+ /** When cycle c starts, in seconds of the wall clock. */
+ double start(long c) {
+ return c * track.cycleSeconds + track.cycleJitterSeconds * (2 * MoveClock.unit(MoveClock.hash(seed, c, JITTER, 0)) - 1);
+ }
+
+ /** The last cycle that has started by time t. */
+ long cycle(double t) {
+ long c = (long) Math.floor(t / track.cycleSeconds);
+ if (start(c + 1) <= t) return c + 1;
+ return start(c) <= t ? c : c - 1;
+ }
+
+ /** How far the doors are open at time t, in radians: 0 shut. */
+ double opening(double t) {
+ long c = cycle(t);
+ double u = t - start(c), swing = track.swingSeconds;
+ if (u < swing) return most * Ease.glide(u / swing);
+ double close = swing + track.openSeconds + track.openSpreadSeconds * MoveClock.unit(MoveClock.hash(seed, c, OPEN, 0));
+ if (u < close) return most;
+ return most * (1 - Ease.glide((u - close) / swing));
+ }
+
+ /** How far the door on wall piece {@code piece} is open at time t: the shared opening, its delay ago. */
+ double opening(double t, int piece) {
+ return opening(t - delay(piece));
+ }
+
+ /** The door on wall piece {@code piece} runs this many seconds behind the shared opening, for good. */
+ double delay(int piece) {
+ return track.rippleSeconds * MoveClock.unit(MoveClock.hash(seed, piece, DELAY, 0));
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Doors.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Doors.java
new file mode 100644
index 000000000..527753034
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Doors.java
@@ -0,0 +1,76 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * Places the doors on the walls of a laid-out {@link Frame} and sets how far each one is open.
+ *
+ * <p>Each wall id draws, from the plan's seed, whether it has a door, where along the wall the door sits
+ * (a share of the wall's length), which end of the bar the hinge is at and which way the leaf swings. These
+ * never change. A door rides its wall: the joins of other walls slide past it, and it never
+ * hides, jumps or pops back. Its bar stays a gap away from the wall's own ends (centred when the wall is too
+ * short for that). It reads only wall pieces, never how the plan was cut.
+ *
+ * <p>All doors swing at one speed, their phases spread around a shared one, so they open and shut in
+ * loose waves. The swing is a clipped sine: doors pause shut and pause open.
+ *
+ * <p>It runs every frame on the GL thread: no allocation, one step per wall.
+ */
+public final class Doors {
+ /** How fast doors swing, in radians per second. The pace, not the look: it stays the same in every look. */
+ static final double SPEED = 1.3;
+
+ // what each wall draws from the seed
+ private static final int HAS_DOOR = 0, AT = 1, HINGE = 2, SIDE = 3, PHASE = 4;
+ /** The shared phase draws as wall -1. */
+ private static final int ALL = -1;
+
+ private final Look.Doors look;
+ private final long seed;
+ private final double sharedPhase;
+
+ public Doors(Look look) {
+ this.look = look.doors;
+ seed = look.plan.seed;
+ sharedPhase = 2 * Math.PI * draw(seed, ALL, PHASE);
+ }
+
+ /** Fills the door arrays of {@code f} at time {@code t}, and its door count. Sizes follow {@code screenHeight}. */
+ public void place(Frame f, double t, float screenHeight) {
+ int walls = Math.min(f.doorWall.length, f.wallCount);
+ float length = screenHeight * look.lengthH, gap = screenHeight * look.joinGapH;
+ int count = 0;
+ for (int w = 0; w < walls; w++) {
+ if (draw(seed, w, HAS_DOOR) >= look.chance) continue;
+ boolean vertical = f.wallVertical[w];
+ float from = vertical ? f.wallY0[w] : f.wallX0[w], to = vertical ? f.wallY1[w] : f.wallX1[w];
+ float at = look.nearAt + (look.farAt - look.nearAt) * (float) draw(seed, w, AT);
+ // the bar's middle, kept a gap from the wall's ends; both limits meet in the middle on a short wall
+ float low = from + gap + length / 2, high = to - gap - length / 2;
+ float middle = low <= high ? Math.max(low, Math.min(high, from + at * (to - from))) : (from + to) / 2;
+ int along = draw(seed, w, HINGE) < 0.5 ? 1 : -1;
+ float hinge = middle - along * length / 2;
+ f.doorWall[count] = w;
+ f.doorAlong[count] = along;
+ f.doorSide[count] = draw(seed, w, SIDE) < 0.5 ? 1 : -1;
+ f.doorX[count] = vertical ? f.wallX0[w] : hinge;
+ f.doorY[count] = vertical ? hinge : f.wallY0[w];
+ f.doorOpening[count] = opening(t, sharedPhase + look.phaseSpread * (2 * draw(seed, w, PHASE) - 1));
+ count++;
+ }
+ f.doorCount = count;
+ }
+
+ /** How far a door with this phase is open at time t, in radians. */
+ private double opening(double t, double phase) {
+ double deg = look.swingMiddleDeg + look.swingAmplitudeDeg * Math.sin(SPEED * t + phase);
+ return Math.toRadians(Math.max(0, Math.min(look.swingMaxDeg, deg)));
+ }
+
+ /** A number in [0, 1) that depends only on the seed, the wall and what is drawn (SplitMix64's mixer). */
+ private static double draw(long seed, int wall, int what) {
+ long z = seed * 0x9E3779B97F4A7C15L + (wall + 1L) * 0xD1B54A32D192ED03L + what * 0x8CB92BA72F3D8DD7L;
+ z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L;
+ z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL;
+ z ^= z >>> 31;
+ return (z >>> 11) * 0x1.0p-53;
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Ease.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Ease.java
new file mode 100644
index 000000000..93511fe07
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Ease.java
@@ -0,0 +1,16 @@
+package io.github.pbanddev.tatami;
+
+/** Easing curves: progress u from 0 to 1 in, share of the way out. */
+final class Ease {
+ private Ease() {}
+
+ /**
+ * A sine ease in and out, (1 - cos(pi u)) / 2: it starts and stops at zero speed, never overshoots and never
+ * turns back. Held at 0 before u = 0 and at 1 after u = 1.
+ */
+ static double glide(double u) {
+ if (u <= 0) return 0;
+ if (u >= 1) return 1;
+ return (1 - Math.cos(Math.PI * u)) / 2;
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Effects.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Effects.java
new file mode 100644
index 000000000..5fbb38825
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Effects.java
@@ -0,0 +1,131 @@
+package io.github.pbanddev.tatami;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+
+/**
+ * Which floor plan effects are on, which look shows and how often both looks swap. All effects on, both looks and
+ * a swap every 10 minutes by default; the choices are kept on the TV.
+ */
+public final class Effects {
+ public static final String GRAIN = "grain";
+ public static final String VIGNETTE = "vignette";
+ public static final String TILT_SHIFT = "tilt_shift";
+ public static final String DOORS = "doors";
+ public static final String FIXTURES = "fixtures";
+ public static final String CAMERA = "camera";
+
+ /** Every effect in the order the settings list shows them. The look and the swap period are not effects. */
+ public static final String[] ALL = {GRAIN, VIGNETTE, TILT_SHIFT, DOORS, FIXTURES, CAMERA};
+
+ /** The look, stored by its {@link LookSchedule.Mode#key}. */
+ public static final String LOOK = "look";
+ /** Minutes between swaps when both looks show, 1 to 60. */
+ public static final String SWAP_MINUTES = "swap_minutes";
+
+ private static final String FILE = "effects";
+ private static final LookSchedule.Mode DEFAULT_LOOK = LookSchedule.Mode.BOTH;
+ private static final int DEFAULT_SWAP_MINUTES = 10;
+ /** The swap periods OK steps through in the settings. */
+ private static final int[] SWAP_CHOICES = {5, 10, 30, 60};
+
+ public final boolean grain, vignette, tiltShift, doors, fixtures, camera;
+ public final LookSchedule.Mode look;
+ public final int swapMinutes;
+
+ private Effects(SharedPreferences p) {
+ grain = p.getBoolean(GRAIN, true);
+ vignette = p.getBoolean(VIGNETTE, true);
+ tiltShift = p.getBoolean(TILT_SHIFT, true);
+ doors = p.getBoolean(DOORS, true);
+ fixtures = p.getBoolean(FIXTURES, true);
+ camera = p.getBoolean(CAMERA, true);
+ look = storedLook(p);
+ swapMinutes = storedSwapMinutes(p);
+ }
+
+ private Effects(Effects e, LookSchedule.Mode look) {
+ grain = e.grain;
+ vignette = e.vignette;
+ tiltShift = e.tiltShift;
+ doors = e.doors;
+ fixtures = e.fixtures;
+ camera = e.camera;
+ this.look = look;
+ swapMinutes = e.swapMinutes;
+ }
+
+ /** These effects with another look, not saved. */
+ public Effects withLook(LookSchedule.Mode look) {
+ return new Effects(this, look);
+ }
+
+ public boolean isOn(String key) {
+ switch (key) {
+ case GRAIN: return grain;
+ case VIGNETTE: return vignette;
+ case TILT_SHIFT: return tiltShift;
+ case DOORS: return doors;
+ case FIXTURES: return fixtures;
+ case CAMERA: return camera;
+ default: throw new IllegalArgumentException(key);
+ }
+ }
+
+ /** The look stored as {@code stored}; any value that names none gives both looks. */
+ static LookSchedule.Mode look(String stored) {
+ LookSchedule.Mode mode = LookSchedule.Mode.of(stored);
+ return mode != null ? mode : DEFAULT_LOOK;
+ }
+
+ /** The swap period stored as {@code stored}, if it is 1 to 60 minutes; 10 otherwise. */
+ static int swapMinutes(int stored) {
+ return stored >= 1 && stored <= 60 ? stored : DEFAULT_SWAP_MINUTES;
+ }
+
+ /** The swap period after {@code minutes}, as OK steps through 5, 10, 30 and 60 minutes. */
+ static int nextSwapMinutes(int minutes) {
+ for (int choice : SWAP_CHOICES) {
+ if (choice > minutes) return choice;
+ }
+ return SWAP_CHOICES[0];
+ }
+
+ /** A value of another type under the key (written by hand, say) gives the default too. */
+ private static LookSchedule.Mode storedLook(SharedPreferences p) {
+ try {
+ return look(p.getString(LOOK, null));
+ } catch (RuntimeException wrongType) {
+ return DEFAULT_LOOK;
+ }
+ }
+
+ private static int storedSwapMinutes(SharedPreferences p) {
+ try {
+ return swapMinutes(p.getInt(SWAP_MINUTES, DEFAULT_SWAP_MINUTES));
+ } catch (RuntimeException wrongType) {
+ return DEFAULT_SWAP_MINUTES;
+ }
+ }
+
+ static SharedPreferences prefs(Context context) {
+ return context.getSharedPreferences(FILE, Context.MODE_PRIVATE);
+ }
+
+ public static Effects load(Context context) {
+ return new Effects(prefs(context));
+ }
+
+ public static void set(Context context, String key, boolean on) {
+ prefs(context).edit().putBoolean(key, on).apply();
+ }
+
+ public static void setLook(Context context, LookSchedule.Mode look) {
+ prefs(context).edit().putString(LOOK, look.key).apply();
+ }
+
+ /** Keeps {@code minutes} if it is 1 to 60; other values are not saved. */
+ public static void setSwapMinutes(Context context, int minutes) {
+ if (swapMinutes(minutes) == minutes) prefs(context).edit().putInt(SWAP_MINUTES, minutes).apply();
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FixtureShapes.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FixtureShapes.java
new file mode 100644
index 000000000..d0f49bf74
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FixtureShapes.java
@@ -0,0 +1,173 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * Draws one fixture of a {@link Frame} into the {@link SceneMesh}: a toilet, a tub or stairs. Every size
+ * here is in fixture units
+ * ({@link Look.Fixtures#unitH}, 1 px at 1080p), so a fixture never scales with its room.
+ *
+ * <p>Each shape is drawn unturned with its box's top-left corner at 0, 0: the toilet with its tank up, the
+ * tub lying along x, the stairs running along +x from the free end to the arrow, with the free side at the
+ * top. Then its vertices are scaled to plan units and turned clockwise on screen, a quarter turn per
+ * {@link Frame#fixtureTurn}, about the centre of the fixture's box.
+ */
+final class FixtureShapes {
+ // toilet: a tank bar with an oval bowl under it, one outline round both
+ private static final float TANK_W = 40f, TANK_D = 15.5f, BOWL_W = 35f, BOWL_D = 52f;
+ /** From the tank's back edge to the bowl's centre. */
+ private static final float BOWL_Y = 34f;
+ private static final int BOWL_SEGMENTS = 24;
+
+ // tub: a rounded rim round a rounded basin
+ private static final float TUB_W = 117.5f, TUB_D = 67.6f, TUB_RADIUS = 10f;
+ /** From the tub's edge to the basin's edge. */
+ private static final float RIM = 7f;
+ private static final float BASIN_RADIUS = 4f;
+ private static final int CORNER_SEGMENTS = 4;
+
+ // stairs: u along the run from the free end, v across from the free side
+ private static final float RUN = 211.7f, ACROSS = 95.1f;
+ private static final float FREE_SIDE_LINE = 2.6f, FREE_END_LINE = 3.5f, STAIRS_LINE = 3f;
+ private static final float RAIL_NEAR = 6.6f, RAIL_FAR = 91f, SHAFT = 50.3f;
+ /** Tread k (1 to 10) is at u = FIRST_TREAD + k * TREAD_STEP: 11 equal cells from the free-end line. */
+ private static final float FIRST_TREAD = FREE_END_LINE / 2, TREAD_STEP = 19.2f;
+ private static final int TREADS = 10;
+ private static final float DOT = 7f, CHEVRON_BACK = 13.5f, CHEVRON_ASIDE = 12f;
+ private static final float CHEVRON_ARM = (float) Math.hypot(CHEVRON_BACK, CHEVRON_ASIDE);
+ private static final int DOT_SEGMENTS = 12;
+
+ /** A unit circle in 48 steps; the shapes above take every 2nd, 3rd or 4th. */
+ private static final int STEPS = 48;
+ private static final float[] COS = new float[STEPS], SIN = new float[STEPS];
+
+ static {
+ for (int i = 0; i < STEPS; i++) {
+ COS[i] = (float) Math.cos(2 * Math.PI * i / STEPS);
+ SIN[i] = (float) Math.sin(2 * Math.PI * i / STEPS);
+ }
+ }
+
+ private static final int TOILET_VERTICES = 2 * (6 + 3 * BOWL_SEGMENTS);
+ private static final int TUB_VERTICES = 4 * 3 * 4 * (CORNER_SEGMENTS + 1);
+ /** Fill and 2 edge bars; rails, treads, shaft and 2 chevron arms; the dot; the chevron's point. */
+ private static final int STAIRS_VERTICES = 3 * 6 + (2 + TREADS + 1 + 2) * 6 + 3 * DOT_SEGMENTS + 6;
+ /** The most vertices one fixture adds. */
+ static final int MAX_VERTICES = Math.max(TOILET_VERTICES, Math.max(TUB_VERTICES, STAIRS_VERTICES));
+
+ private FixtureShapes() {}
+
+ /** The kind's width, unturned, in units. */
+ static float width(int kind) {
+ switch (kind) {
+ case Fixtures.TUB: return TUB_W;
+ case Fixtures.TOILET: return TANK_W;
+ case Fixtures.STAIRS: return RUN;
+ default: return 0f;
+ }
+ }
+
+ /** The kind's depth, unturned, in units: from the toilet's back to its front, the stairs' free side to its wall. */
+ static float depth(int kind) {
+ switch (kind) {
+ case Fixtures.TUB: return TUB_D;
+ case Fixtures.TOILET: return BOWL_Y + BOWL_D / 2;
+ case Fixtures.STAIRS: return ACROSS;
+ default: return 0f;
+ }
+ }
+
+ static void add(SceneMesh m, Frame f, int k, float screenHeight, Look look) {
+ int kind = f.fixtureKind[k], start = m.floats;
+ switch (kind) {
+ case Fixtures.TUB: tub(m, look); break;
+ case Fixtures.TOILET: toilet(m, look); break;
+ case Fixtures.STAIRS: stairs(m, look); break;
+ default: return;
+ }
+ float unit = screenHeight * look.fixtures.unitH;
+ int turn = f.fixtureTurn[k] & 3;
+ float cos = turn == 0 ? unit : turn == 2 ? -unit : 0f, sin = turn == 1 ? unit : turn == 3 ? -unit : 0f;
+ float halfW = width(kind) / 2, halfD = depth(kind) / 2;
+ float cx = f.fixtureX[k] + f.fixtureW[k] / 2, cy = f.fixtureY[k] + f.fixtureH[k] / 2;
+ float[] d = m.data;
+ for (int i = start; i < m.floats; i += SceneMesh.FLOATS_PER_VERTEX) {
+ float a = d[i] - halfW, b = d[i + 1] - halfD;
+ d[i] = cx + cos * a - sin * b;
+ d[i + 1] = cy + sin * a + cos * b;
+ }
+ }
+
+ /** Both black shapes, then both fills one stroke in, so no line shows where the bowl meets the tank. */
+ private static void toilet(SceneMesh m, Look look) {
+ float s = look.fixtures.line, cx = TANK_W / 2;
+ m.color(look.palette.line);
+ m.rect(0, 0, TANK_W, TANK_D);
+ oval(m, cx, BOWL_Y, BOWL_W / 2, BOWL_D / 2, STEPS / BOWL_SEGMENTS);
+ m.color(look.palette.fixture);
+ m.rect(s, s, TANK_W - 2 * s, TANK_D - 2 * s);
+ oval(m, cx, BOWL_Y, BOWL_W / 2 - s, BOWL_D / 2 - s, STEPS / BOWL_SEGMENTS);
+ }
+
+ /** 4 rounded boxes on one centre: black, fill one stroke in, black at the basin, fill one stroke in. */
+ private static void tub(SceneMesh m, Look look) {
+ float s = look.fixtures.line;
+ m.color(look.palette.line);
+ roundBox(m, 0, TUB_RADIUS);
+ m.color(look.palette.fixture);
+ roundBox(m, s, TUB_RADIUS - s);
+ m.color(look.palette.line);
+ roundBox(m, RIM, BASIN_RADIUS);
+ m.color(look.palette.fixture);
+ roundBox(m, RIM + s, Math.max(0f, BASIN_RADIUS - s));
+ }
+
+ private static void stairs(SceneMesh m, Look look) {
+ m.color(look.palette.stairs);
+ m.rect(0, 0, RUN, ACROSS);
+ m.color(look.palette.line);
+ m.rect(0, 0, RUN, FREE_SIDE_LINE);
+ m.rect(0, 0, FREE_END_LINE, ACROSS);
+ m.line(0, RAIL_NEAR, RUN, RAIL_NEAR, STAIRS_LINE);
+ m.line(0, RAIL_FAR, RUN, RAIL_FAR, STAIRS_LINE);
+ for (int k = 1; k <= TREADS; k++) {
+ float u = FIRST_TREAD + k * TREAD_STEP;
+ m.line(u, RAIL_NEAR, u, RAIL_FAR, STAIRS_LINE);
+ }
+ float tip = FIRST_TREAD + TREADS * TREAD_STEP;
+ m.line(FIRST_TREAD, SHAFT, tip, SHAFT, STAIRS_LINE);
+ oval(m, FIRST_TREAD, SHAFT, DOT / 2, DOT / 2, STEPS / DOT_SEGMENTS);
+ m.line(tip - CHEVRON_BACK, SHAFT - CHEVRON_ASIDE, tip, SHAFT, STAIRS_LINE);
+ m.line(tip - CHEVRON_BACK, SHAFT + CHEVRON_ASIDE, tip, SHAFT, STAIRS_LINE);
+ // fill the point between the two flat arm ends (a mitre)
+ float half = STAIRS_LINE / 2;
+ float ox = tip + half * CHEVRON_ASIDE / CHEVRON_ARM, oy = half * CHEVRON_BACK / CHEVRON_ARM;
+ float point = tip + half * CHEVRON_ARM / CHEVRON_ASIDE;
+ m.triangle(tip, SHAFT, ox, SHAFT - oy, point, SHAFT);
+ m.triangle(tip, SHAFT, point, SHAFT, ox, SHAFT + oy);
+ }
+
+ /** A filled oval as a fan, every {@code step}-th step of the circle. */
+ private static void oval(SceneMesh m, float cx, float cy, float rx, float ry, int step) {
+ for (int i = 0; i < STEPS; i += step) {
+ int j = (i + step) % STEPS;
+ m.triangle(cx, cy, cx + rx * COS[i], cy + ry * SIN[i], cx + rx * COS[j], cy + ry * SIN[j]);
+ }
+ }
+
+ /** The tub's box inset by {@code in} on every side, with corners of radius {@code r}, as a fan from its centre. */
+ private static void roundBox(SceneMesh m, float in, float r) {
+ float x0 = in + r, y0 = in + r, x1 = TUB_W - in - r, y1 = TUB_D - in - r;
+ float cx = TUB_W / 2, cy = TUB_D / 2;
+ int points = 4 * (CORNER_SEGMENTS + 1);
+ float px = 0, py = 0;
+ for (int p = 0; p <= points; p++) {
+ // corners in turn from the top-left, clockwise on screen; each arc a quarter of the circle
+ int corner = (p % points) / (CORNER_SEGMENTS + 1), along = (p % points) % (CORNER_SEGMENTS + 1);
+ int i = (STEPS / 2 + corner * STEPS / 4 + along * STEPS / 4 / CORNER_SEGMENTS) % STEPS;
+ float x = (corner == 0 || corner == 3 ? x0 : x1) + r * COS[i];
+ float y = (corner < 2 ? y0 : y1) + r * SIN[i];
+ if (p > 0) m.triangle(cx, cy, px, py, x, y);
+ px = x;
+ py = y;
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Fixtures.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Fixtures.java
new file mode 100644
index 000000000..d2b02b6f9
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Fixtures.java
@@ -0,0 +1,213 @@
+package io.github.pbanddev.tatami;
+
+import java.util.Random;
+
+/**
+ * Puts toilets, tubs and stairs in their rooms. A fixture keeps its size from {@link FixtureShapes} and never
+ * shrinks, so a room hosts one only if the smallest the room ever gets ({@link Frame#roomMinW},
+ * {@link Frame#roomMinH}) holds it with its gaps, between the wall faces. Rooms that also leave
+ * {@link Look.Fixtures#clearance} on its open sides come first.
+ *
+ * <p>The hosts, kinds, walls or corners and turns are picked once from the plan's seed, for
+ * {@link Look.Fixtures#share} of the rooms, dealt to the kinds by {@link Look.Fixtures#weights}. They are
+ * picked again only when the screen height or the rooms' minimums change. Every frame each fixture then
+ * follows its room's wall faces (half a wall inside the room's box). Nothing is allocated per frame.
+ *
+ * <ul>
+ * <li>Toilet: centred on its back wall, {@link Look.Fixtures#toiletGap} from the wall's face. Turn 0
+ * backs onto the top wall, then clockwise: right, bottom, left.</li>
+ * <li>Tub: in any corner, {@link Look.Fixtures#tubGap} from both faces. Turn 0 lies along x, turn 1 along y.</li>
+ * <li>Stairs: flush in a corner, the arrow pointing into it. Turn 0 runs right into the bottom-right
+ * corner, then clockwise: bottom-left, top-left, top-right.</li>
+ * </ul>
+ */
+public final class Fixtures {
+ public static final int TUB = 0;
+ public static final int TOILET = 1;
+ public static final int STAIRS = 2;
+ private static final int KINDS = 3;
+
+ /** Biggest first, so smaller kinds do not take the few rooms the stairs fit. */
+ private static final int[] BIGGEST_FIRST = {STAIRS, TUB, TOILET};
+ /** Corner bits. */
+ private static final int RIGHT = 1, BOTTOM = 2;
+ /** The corner the stairs run into at each turn. */
+ private static final int[] STAIRS_CORNER = {RIGHT | BOTTOM, BOTTOM, 0, RIGHT};
+ /** Keeps these picks apart from the plan's other seeded choices. */
+ private static final long SALT = 0x5F1C_7E55L;
+
+ private final Look look;
+ private final Random random = new Random();
+ private final int[] dealt = new int[KINDS];
+
+ // what the picks were made for
+ private float pickedHeight = Float.NaN;
+ private int pickedRooms = -1;
+ private float[] pickedMinW = new float[0], pickedMinH = new float[0];
+ // the picks
+ private int hosts;
+ private int[] hostRoom = new int[0], hostKind = new int[0], hostTurn = new int[0], hostCorner = new int[0];
+ private int[] order = new int[0];
+ private boolean[] taken = new boolean[0];
+
+ public Fixtures(Look look) {
+ this.look = look;
+ }
+
+ /** Fills the fixture arrays of {@code f} from its rooms. Sizes follow {@code screenHeight}. */
+ public void place(Frame f, float screenHeight) {
+ if (!pickedFor(f, screenHeight)) pick(f, screenHeight);
+ float unit = screenHeight * look.fixtures.unitH, half = screenHeight * look.walls.widthH / 2;
+ int n = 0;
+ for (int j = 0; j < hosts; j++) {
+ int r = hostRoom[j], kind = hostKind[j], turn = hostTurn[j];
+ float left = f.roomX[r] + half, top = f.roomY[r] + half;
+ float right = f.roomX[r] + f.roomW[r] - half, bottom = f.roomY[r] + f.roomH[r] - half;
+ // the minimums promise a fit; should a room ever break that, leave its fixture out, never cross a wall
+ if (!fits(kind, turn, right - left, bottom - top, unit, 0f)) continue;
+ float w = unit * FixtureShapes.width(kind), h = unit * FixtureShapes.depth(kind);
+ if ((turn & 1) == 1) {
+ float swap = w;
+ w = h;
+ h = swap;
+ }
+ float x, y;
+ if (kind == TOILET) {
+ float gap = unit * look.fixtures.toiletGap;
+ x = turn == 1 ? right - gap - w : turn == 3 ? left + gap : (left + right - w) / 2;
+ y = turn == 0 ? top + gap : turn == 2 ? bottom - gap - h : (top + bottom - h) / 2;
+ } else {
+ float gap = kind == TUB ? unit * look.fixtures.tubGap : 0f;
+ int corner = hostCorner[j];
+ x = (corner & RIGHT) != 0 ? right - gap - w : left + gap;
+ y = (corner & BOTTOM) != 0 ? bottom - gap - h : top + gap;
+ }
+ f.fixtureKind[n] = kind;
+ f.fixtureRoom[n] = r;
+ f.fixtureTurn[n] = turn;
+ f.fixtureX[n] = x;
+ f.fixtureY[n] = y;
+ f.fixtureW[n] = w;
+ f.fixtureH[n] = h;
+ n++;
+ }
+ f.fixtureCount = n;
+ }
+
+ /**
+ * True when the floor between the wall faces, {@code across} by {@code down}, holds the kind at this turn
+ * with its gaps and {@code clearance} units of floor on its open sides.
+ */
+ private boolean fits(int kind, int turn, float across, float down, float unit, float clearance) {
+ float w = unit * FixtureShapes.width(kind), h = unit * FixtureShapes.depth(kind), c = unit * clearance;
+ boolean odd = (turn & 1) == 1;
+ if (odd) {
+ float swap = w;
+ w = h;
+ h = swap;
+ }
+ if (kind == TOILET) {
+ float gap = unit * look.fixtures.toiletGap;
+ return odd ? h + 2 * c <= down && gap + w + c <= across : w + 2 * c <= across && gap + h + c <= down;
+ }
+ float gap = kind == TUB ? unit * look.fixtures.tubGap : 0f;
+ return gap + w + c <= across && gap + h + c <= down;
+ }
+
+ private boolean pickedFor(Frame f, float screenHeight) {
+ if (screenHeight != pickedHeight || f.roomCount != pickedRooms) return false;
+ for (int i = 0; i < f.roomCount; i++) {
+ if (f.roomMinW[i] != pickedMinW[i] || f.roomMinH[i] != pickedMinH[i]) return false;
+ }
+ return true;
+ }
+
+ /** Picks the hosts. Allocates only when the frame holds more rooms than ever before. */
+ private void pick(Frame f, float screenHeight) {
+ int rooms = f.roomCount;
+ if (order.length < rooms) {
+ pickedMinW = new float[rooms];
+ pickedMinH = new float[rooms];
+ hostRoom = new int[rooms];
+ hostKind = new int[rooms];
+ hostTurn = new int[rooms];
+ hostCorner = new int[rooms];
+ order = new int[rooms];
+ taken = new boolean[rooms];
+ }
+ System.arraycopy(f.roomMinW, 0, pickedMinW, 0, rooms);
+ System.arraycopy(f.roomMinH, 0, pickedMinH, 0, rooms);
+ pickedHeight = screenHeight;
+ pickedRooms = rooms;
+ hosts = 0;
+
+ random.setSeed(look.plan.seed ^ SALT);
+ for (int i = 0; i < rooms; i++) {
+ order[i] = i;
+ taken[i] = false;
+ }
+ for (int i = rooms - 1; i > 0; i--) {
+ int j = random.nextInt(i + 1), swap = order[i];
+ order[i] = order[j];
+ order[j] = swap;
+ }
+ deal(Math.round(look.fixtures.share * rooms));
+ float unit = screenHeight * look.fixtures.unitH, wall = screenHeight * look.walls.widthH;
+ for (int kind : BIGGEST_FIRST) {
+ for (int c = 0; c < dealt[kind]; c++) host(f, kind, unit, wall);
+ }
+ }
+
+ /** Splits {@code count} fixtures between the kinds by weight, the leftovers to the largest remainders. */
+ private void deal(int count) {
+ float[] weights = look.fixtures.weights;
+ float total = 0f;
+ for (int kind = 0; kind < KINDS; kind++) total += kind < weights.length ? Math.max(0f, weights[kind]) : 0f;
+ int left = count;
+ for (int kind = 0; kind < KINDS; kind++) {
+ dealt[kind] = total > 0f && kind < weights.length ? (int) (count * Math.max(0f, weights[kind]) / total) : 0;
+ left -= dealt[kind];
+ }
+ while (left > 0 && total > 0f) {
+ int best = 0;
+ float bestRest = -Float.MAX_VALUE;
+ for (int kind = 0; kind < KINDS && kind < weights.length; kind++) {
+ float rest = count * Math.max(0f, weights[kind]) / total - dealt[kind];
+ if (rest > bestRest) {
+ bestRest = rest;
+ best = kind;
+ }
+ }
+ dealt[best]++;
+ left--;
+ }
+ }
+
+ /**
+ * Gives one fixture of this kind to the first free room, in the seeded order, that it fits at some seeded
+ * turn with the clearance. If no room does, to the first it fits at all.
+ */
+ private void host(Frame f, int kind, float unit, float wall) {
+ int options = kind == TUB ? 8 : 4; // the tub: 2 turns in each of 4 corners
+ for (int pass = 0; pass < 2; pass++) {
+ float clearance = pass == 0 ? look.fixtures.clearance : 0f;
+ for (int o = 0; o < pickedRooms; o++) {
+ int r = order[o];
+ if (taken[r]) continue;
+ float across = f.roomMinW[r] - wall, down = f.roomMinH[r] - wall;
+ int first = random.nextInt(options);
+ for (int i = 0; i < options; i++) {
+ int option = (first + i) % options, turn = kind == TUB ? option & 1 : option;
+ if (!fits(kind, turn, across, down, unit, clearance)) continue;
+ taken[r] = true;
+ hostRoom[hosts] = r;
+ hostKind[hosts] = kind;
+ hostTurn[hosts] = turn;
+ hostCorner[hosts] = kind == TUB ? option >> 1 : kind == STAIRS ? STAIRS_CORNER[turn] : 0;
+ hosts++;
+ return;
+ }
+ }
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlan.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlan.java
new file mode 100644
index 000000000..763f67077
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlan.java
@@ -0,0 +1,596 @@
+package io.github.pbanddev.tatami;
+
+import java.util.Arrays;
+import java.util.Random;
+
+/**
+ * The floor plan: one rectangle cut into rooms by a tree that is grown once per seed. Each part of the tree
+ * is a room, a straight cut across its longer side (2 parts, 1 wall), or a windmill: 4 parts wrapped round a
+ * centre room (5 parts, 4 walls), so no straight wall runs through it. The whole plan is a windmill too, so
+ * no wall crosses it from edge to edge.
+ *
+ * <p>Every wall is held as a share of its part. Each share slides on a slow sine, so the room on one side of a
+ * wall gains exactly the space its neighbour loses: no gaps, no overlaps. Only the shares move; the tree, and
+ * so every room's and wall's index, stays the same in every frame.
+ *
+ * <p>No room's short side ever drops below {@link Look.Plan#minSideH}, and no room is ever longer than
+ * {@link Look.Plan#maxAspect} times its width. Each part knows the sizes it can take while all of its own
+ * parts keep theirs (its fit: a least width, a least height, and a range of width over height), and every
+ * frame it holds its shares where its parts stay in their fits. That only stops a wall for a moment, and
+ * never moves a share past the range its sine sweeps anyway.
+ *
+ * <p>Pure: the same seed and time give the same plan, so Home and the screensaver, both driven by the wall
+ * clock, draw the same frame and the hand-off between them does not jump.
+ */
+public final class FloorPlan {
+ /** Each share swings this far either side of its base. */
+ private static final float AMPLITUDE = 0.12f;
+ /** A share's speed, in radians per second: from SPEED to SPEED + SPEED_SPREAD. */
+ private static final float SPEED = 0.15f, SPEED_SPREAD = 0.20f;
+ /**
+ * A part is cut with a vertical wall if it is at least this wide for its height, else with a horizontal
+ * one. Below 1, so near-square parts make tall rooms, against the wide ones windmills on wide parts make.
+ */
+ private static final float CUT_X_ASPECT = 0.8f;
+ /** A cut's base share is picked in CUT_BASE + [0, CUT_SPREAD), and the cut stays inside CUT_MIN to CUT_MAX. */
+ private static final float CUT_BASE = 0.38f, CUT_SPREAD = 0.24f, CUT_MIN = 0.25f, CUT_MAX = 0.75f;
+ /**
+ * A windmill's two walls on each axis: base shares in MILL_LOW + [0, MILL_SPREAD) and MILL_HIGH +
+ * [0, MILL_SPREAD), kept MILL_EDGE from its sides and MILL_GAP apart.
+ */
+ private static final float MILL_LOW = 0.35f, MILL_HIGH = 0.58f, MILL_SPREAD = 0.07f;
+ private static final float MILL_EDGE = 0.12f, MILL_GAP = 0.15f;
+ /**
+ * A windmill's 4 shares swing at one speed, each off by up to MILL_JITTER radians, so its centre glides
+ * back and forth on a diagonal and keeps its shape. On a wide windmill all 4 swing together, which keeps
+ * the long top and bottom rooms' shapes too; on a tall one the y-walls swing against the x-walls, which
+ * keeps the long side rooms' shapes.
+ */
+ private static final float MILL_JITTER = 0.3f;
+ /**
+ * The whole plan's windmill sits as close to the middle as the windmill bases allow, so its four long
+ * walls end on screen instead of running across it.
+ */
+ private static final float ROOT_LOW = 0.42f, ROOT_HIGH = 0.58f;
+ /**
+ * Parts this close to square and at most this big (H² on screen) may become windmills. Up to
+ * MILL_ROOMS_AREA the 4 outer parts are rooms; above, they may be cut again.
+ */
+ private static final float MILL_MAX_ASPECT = 1.8f, MILL_MAX_AREA = 1.0f, MILL_ROOMS_AREA = 0.65f;
+ /**
+ * A windmill's fit is worked out for heights from this share of its height at the base shares up: its
+ * parent holds it there, which it seldom needs to.
+ */
+ private static final float MILL_SHRINK = 0.65f;
+ /** Tries at fresh base shares before a part gives up on a windmill or a cut. */
+ private static final int TRIES = 8;
+ /** Sizes are judged on screen at the camera's middle zoom (it breathes from 1 to 1.15). */
+ private static final float ZOOM = 1.075f;
+ /** Rooms keep this much inside the longest shape and the shortest side allowed, for rounding. */
+ private static final float ROUNDING = 0.99f;
+
+ private static final int ROOM = 0, CUT_X = 1, CUT_Y = 2, MILL = 3, MILL_MIRRORED = 4;
+
+ public final int rooms;
+ /** The least side of a room, in plan heights. */
+ private final float minSide;
+ // The tree. The Builder grows these once; after that they are only read.
+ /** Per part: its kind, its first share, its first wall (or its room), and its children. */
+ private int[] kind = new int[64], share = new int[64], index = new int[64];
+ private int[][] child = new int[64][];
+ /**
+ * Per part, its fit: the least and most width over height, and the least width and height (in plan
+ * heights), it can take while its own parts keep theirs.
+ */
+ private float[] fitLo = new float[64], fitHi = new float[64], fitW = new float[64], fitH = new float[64];
+ /** Per share: its sine, and the least and most it can be after the fixed clamps. */
+ private float[] base = new float[64], speed = new float[64], phase = new float[64], lo = new float[64], hi = new float[64];
+ /** Per room: the smallest share of the plan's width and height it gets with every share at its worst. */
+ private float[] minShareW = new float[64], minShareH = new float[64];
+
+ public FloorPlan(Look look) {
+ this(look, look.plan.seed);
+ }
+
+ /** Kept for tests written before the windmill layout: Look.YOJOHAN with another seed. The depth is not used. */
+ public FloorPlan(long seed, int depth) {
+ this(Look.YOJOHAN, seed);
+ }
+
+ FloorPlan(Look look, long seed) {
+ float angle = look.camera.angleDeg;
+ // the plan Scene lays out on a 16:9 screen, in screen heights
+ float planW = Camera.planWidth(16, 9, angle) / 9, planH = Camera.planHeight(16, 9, angle) / 9;
+ minSide = look.plan.minSideH / planH;
+ Builder b = new Builder(look.plan, new Random(seed), planH);
+ b.root(planW / planH);
+ rooms = b.rooms;
+ kind = Arrays.copyOf(kind, b.parts);
+ share = Arrays.copyOf(share, b.parts);
+ index = Arrays.copyOf(index, b.parts);
+ child = Arrays.copyOf(child, b.parts);
+ fitLo = Arrays.copyOf(fitLo, b.parts);
+ fitHi = Arrays.copyOf(fitHi, b.parts);
+ fitW = Arrays.copyOf(fitW, b.parts);
+ fitH = Arrays.copyOf(fitH, b.parts);
+ base = Arrays.copyOf(base, b.shares);
+ speed = Arrays.copyOf(speed, b.shares);
+ phase = Arrays.copyOf(phase, b.shares);
+ lo = Arrays.copyOf(lo, b.shares);
+ hi = Arrays.copyOf(hi, b.shares);
+ minShareW = Arrays.copyOf(minShareW, rooms);
+ minShareH = Arrays.copyOf(minShareH, rooms);
+ }
+
+ /**
+ * Fills {@code out} with the rooms and walls of the plan at time {@code t} (seconds), inside x, y, w, h, and
+ * a stand-in door in the middle of every wall, for {@link Doors} to replace.
+ */
+ public void layout(double t, float x, float y, float w, float h, Frame out) {
+ // a Frame made for fewer rooms, or an empty plan, gets no rooms: never an exception
+ boolean fits = out.roomX.length >= rooms && w > 0 && h > 0;
+ out.roomCount = fits ? rooms : 0;
+ out.wallCount = fits ? rooms - 1 : 0;
+ out.doorCount = out.wallCount;
+ if (!fits) return;
+ place(0, t, x, y, w, h, h, out);
+ for (int k = 0; k < rooms; k++) {
+ out.roomMinW[k] = Math.max(minShareW[k] * w, minSide * ROUNDING * h);
+ out.roomMinH[k] = Math.max(minShareH[k] * h, minSide * ROUNDING * h);
+ }
+ for (int k = 0; k < out.wallCount; k++) {
+ out.doorWall[k] = k;
+ out.doorX[k] = (out.wallX0[k] + out.wallX1[k]) / 2;
+ out.doorY[k] = (out.wallY0[k] + out.wallY1[k]) / 2;
+ out.doorAlong[k] = out.wallVertical[k] ? -1 : 1;
+ out.doorSide[k] = 1;
+ out.doorOpening[k] = Math.toRadians(90 * (0.55 + 0.45 * Math.sin(1.3 * t + k)));
+ }
+ }
+
+ private float raw(int s, double t) {
+ return base[s] + AMPLITUDE * (float) Math.sin(speed[s] * t + phase[s]);
+ }
+
+ private static float clamp(float v, float least, float most) {
+ return Math.max(least, Math.min(most, v));
+ }
+
+ private static float clampCut(float raw) {
+ return clamp(raw, CUT_MIN, CUT_MAX);
+ }
+
+ /** A windmill's lower wall on one axis, from its two raw shares: kept off the sides and MILL_GAP below the upper wall. */
+ private static float millLow(float a, float b) {
+ a = edge(a);
+ b = edge(b);
+ return b - a >= MILL_GAP ? a : middle(a, b) - MILL_GAP / 2;
+ }
+
+ private static float millHigh(float a, float b) {
+ a = edge(a);
+ b = edge(b);
+ return b - a >= MILL_GAP ? b : middle(a, b) + MILL_GAP / 2;
+ }
+
+ private static float edge(float s) {
+ return clamp(s, MILL_EDGE, 1 - MILL_EDGE);
+ }
+
+ private static float middle(float a, float b) {
+ return clamp((a + b) / 2, MILL_EDGE + MILL_GAP / 2, 1 - MILL_EDGE - MILL_GAP / 2);
+ }
+
+ /** The least gap between the windmill walls held by shares s and s + 1, at any time. */
+ private float millGap(int s) {
+ return Math.max(MILL_GAP, edge(base[s + 1] - AMPLITUDE) - edge(base[s] + AMPLITUDE));
+ }
+
+ /**
+ * Where cut n with this raw share goes in a w by h part: as near the raw share as keeps both of its parts
+ * in their fits. {@code unit} is the plan's height.
+ */
+ private float cutAt(int n, float raw, float w, float h, float unit) {
+ int s = share[n], p = child[n][0], q = child[n][1];
+ float r = clampCut(raw), a = w / h;
+ if (kind[n] == CUT_X) { // parts r * w by h and (1 - r) * w by h
+ r = clamp(r, Math.max(fitW[p] * unit / w, Math.max(fitLo[p] / a, 1 - fitHi[q] / a)),
+ Math.min(1 - fitW[q] * unit / w, Math.min(fitHi[p] / a, 1 - fitLo[q] / a)));
+ } else { // parts w by r * h and w by (1 - r) * h
+ r = clamp(r, Math.max(fitH[p] * unit / h, Math.max(a / fitHi[p], 1 - a / fitLo[q])),
+ Math.min(1 - fitH[q] * unit / h, Math.min(a / fitLo[p], 1 - a / fitHi[q])));
+ }
+ return clamp(r, lo[s], hi[s]);
+ }
+
+ /**
+ * Windmill n's lower (or upper) y-wall, as a share of its height h, from its raw y-shares: as near them as
+ * gives each of its 5 parts its least height. Heights: top s1, right s2, bottom 1 - s2, left 1 - s1,
+ * centre s2 - s1.
+ */
+ private float millY(int n, boolean upper, float h, float unit, float sa, float sb) {
+ int s = share[n] + 2;
+ int[] c = child[n];
+ float lowLo = Math.max(lo[s], fitH[c[0]] * unit / h), lowHi = Math.min(hi[s], 1 - fitH[c[3]] * unit / h);
+ float highLo = Math.max(lo[s + 1], fitH[c[1]] * unit / h), highHi = Math.min(hi[s + 1], 1 - fitH[c[2]] * unit / h);
+ float gap = Math.max(millGap(s), fitH[c[4]] * unit / h);
+ float s2 = clamp(clamp(millHigh(sa, sb), Math.max(highLo, lowLo + gap), highHi), lo[s + 1], hi[s + 1]);
+ if (upper) return s2;
+ float s1 = clamp(millLow(sa, sb), lowLo, Math.min(lowHi, s2 - gap));
+ return clamp(s1, lo[s], Math.min(hi[s], s2 - millGap(s)));
+ }
+
+ /**
+ * Windmill n's lower (or upper) x-wall, as a share of its width w, from its raw x-shares, given its y-walls
+ * s1 and s2: as near the raw shares as keeps its 5 parts in their fits. Widths: top r2, right 1 - r2,
+ * bottom 1 - r1, left r1, centre r2 - r1; the heights are as in {@link #millY}.
+ */
+ private float millX(int n, boolean upper, float w, float h, float unit, float s1, float s2, float ra, float rb) {
+ int s = share[n];
+ int[] c = child[n];
+ float a = w / h, u = unit / w;
+ float highLo = Math.max(Math.max(lo[s + 1], fitW[c[0]] * u), Math.max(fitLo[c[0]] * s1 / a, 1 - fitHi[c[1]] * s2 / a));
+ float highHi = Math.min(Math.min(hi[s + 1], 1 - fitW[c[1]] * u), Math.min(fitHi[c[0]] * s1 / a, 1 - fitLo[c[1]] * s2 / a));
+ float lowLo = Math.max(Math.max(lo[s], fitW[c[3]] * u), Math.max(fitLo[c[3]] * (1 - s1) / a, 1 - fitHi[c[2]] * (1 - s2) / a));
+ float lowHi = Math.min(Math.min(hi[s], 1 - fitW[c[2]] * u), Math.min(fitHi[c[3]] * (1 - s1) / a, 1 - fitLo[c[2]] * (1 - s2) / a));
+ float gapLo = Math.max(Math.max(millGap(s), fitW[c[4]] * u), fitLo[c[4]] * (s2 - s1) / a);
+ float gapHi = fitHi[c[4]] * (s2 - s1) / a;
+ float r2 = clamp(millHigh(ra, rb), Math.max(highLo, lowLo + gapLo), Math.min(highHi, lowHi + gapHi));
+ r2 = clamp(r2, lo[s + 1], hi[s + 1]);
+ if (upper) return r2;
+ float r1 = clamp(millLow(ra, rb), Math.max(lowLo, r2 - gapHi), Math.min(lowHi, r2 - gapLo));
+ return clamp(r1, lo[s], Math.min(hi[s], r2 - millGap(s)));
+ }
+
+ private void place(int n, double t, float x, float y, float w, float h, float unit, Frame out) {
+ int[] c = child[n];
+ int s = share[n];
+ switch (kind[n]) {
+ case ROOM: {
+ int k = index[n];
+ out.roomX[k] = x;
+ out.roomY[k] = y;
+ out.roomW[k] = w;
+ out.roomH[k] = h;
+ return;
+ }
+ case CUT_X: {
+ float at = x + w * cutAt(n, raw(s, t), w, h, unit);
+ wall(out, index[n], at, y, at, y + h);
+ place(c[0], t, x, y, at - x, h, unit, out);
+ place(c[1], t, at, y, x + w - at, h, unit, out);
+ return;
+ }
+ case CUT_Y: {
+ float at = y + h * cutAt(n, raw(s, t), w, h, unit);
+ wall(out, index[n], x, at, x + w, at);
+ place(c[0], t, x, y, w, at - y, unit, out);
+ place(c[1], t, x, at, w, y + h - at, unit, out);
+ return;
+ }
+ default: {
+ float ra = raw(s, t), rb = raw(s + 1, t), sa = raw(s + 2, t), sb = raw(s + 3, t);
+ float s1 = millY(n, false, h, unit, sa, sb), s2 = millY(n, true, h, unit, sa, sb);
+ float r1 = millX(n, false, w, h, unit, s1, s2, ra, rb), r2 = millX(n, true, w, h, unit, s1, s2, ra, rb);
+ // Clockwise, from the left side: the top part runs to x2, the bottom part from x1.
+ // Mirrored, the same from the right side.
+ boolean mirrored = kind[n] == MILL_MIRRORED;
+ float near = mirrored ? x + w : x, far = mirrored ? x : x + w;
+ float x1 = near + (far - near) * r1, x2 = near + (far - near) * r2;
+ float y1 = y + h * s1, y2 = y + h * s2, bottom = y + h;
+ int k = index[n];
+ wall(out, k, near, y1, x2, y1);
+ wall(out, k + 1, x2, y, x2, y2);
+ wall(out, k + 2, x1, y2, far, y2);
+ wall(out, k + 3, x1, y1, x1, bottom);
+ between(c[0], t, near, y, x2, y1, unit, out);
+ between(c[1], t, x2, y, far, y2, unit, out);
+ between(c[2], t, x1, y2, far, bottom, unit, out);
+ between(c[3], t, near, y1, x1, bottom, unit, out);
+ between(c[4], t, x1, y1, x2, y2, unit, out);
+ }
+ }
+ }
+
+ /** Places part n in the box between two x and two y edges, given in either order. */
+ private void between(int n, double t, float xa, float ya, float xb, float yb, float unit, Frame out) {
+ place(n, t, Math.min(xa, xb), Math.min(ya, yb), Math.abs(xb - xa), Math.abs(yb - ya), unit, out);
+ }
+
+ private static void wall(Frame out, int k, float xa, float ya, float xb, float yb) {
+ out.wallX0[k] = Math.min(xa, xb);
+ out.wallX1[k] = Math.max(xa, xb);
+ out.wallY0[k] = Math.min(ya, yb);
+ out.wallY1[k] = Math.max(ya, yb);
+ out.wallVertical[k] = xa == xb;
+ }
+
+ /**
+ * Grows the tree once, from the seed, in plan heights. A part is judged at its base shares: a cut or a
+ * windmill is only kept if it fits there, and a part only stays a room if a room fits there.
+ */
+ private final class Builder {
+ private final Look.Plan look;
+ private final Random random;
+ /** Plan heights to screen heights at the middle zoom. */
+ private final float screen;
+ private final float roomFit;
+ int parts, shares, rooms, walls;
+
+ Builder(Look.Plan look, Random random, float planH) {
+ this.look = look;
+ this.random = random;
+ screen = planH * ZOOM;
+ roomFit = look.maxAspect * ROUNDING;
+ }
+
+ void root(float aspect) {
+ Size plan = new Size(aspect, 1);
+ boolean mirrored = random.nextFloat() >= look.clockwiseShare;
+ if (mill(plan, ROOT_LOW, ROOT_HIGH, ROOT_LOW, ROOT_HIGH, mirrored, true, true) < 0) part(plan);
+ }
+
+ private int part(Size p) {
+ float area = p.w * p.h * screen * screen;
+ boolean split = area > look.splitAboveH2 || (area >= look.stopBelowH2 && random.nextBoolean())
+ || !roomFits(p);
+ if (!split) return room(p);
+ float aspect = Math.max(p.w / p.h, p.h / p.w);
+ if (aspect <= MILL_MAX_ASPECT && area >= look.windmillMinH2 && area <= MILL_MAX_AREA
+ && random.nextFloat() < look.windmillOdds) {
+ boolean mirrored = random.nextFloat() >= look.clockwiseShare;
+ for (int i = 0; i < TRIES; i++) {
+ float ra = MILL_LOW + MILL_SPREAD * random.nextFloat(), rb = MILL_HIGH + MILL_SPREAD * random.nextFloat();
+ float sa = MILL_LOW + MILL_SPREAD * random.nextFloat(), sb = MILL_HIGH + MILL_SPREAD * random.nextFloat();
+ int n = mill(p, ra, rb, sa, sb, mirrored, area > MILL_ROOMS_AREA, false);
+ if (n >= 0) return n;
+ }
+ }
+ for (int i = 0; i < TRIES; i++) {
+ int n = cut(p, CUT_BASE + CUT_SPREAD * random.nextFloat());
+ if (n >= 0) return n;
+ }
+ return room(p);
+ }
+
+ private boolean roomFits(Size p) {
+ float side = minSide / ROUNDING;
+ return p.w >= side && p.h >= side && p.w <= look.roomAspect * p.h && p.h <= look.roomAspect * p.w;
+ }
+
+ /** True if part n fits at size p: else its parent could not hold it at its base shares. */
+ private boolean fits(int n, Size p) {
+ float a = p.w / p.h;
+ return p.w >= fitW[n] && p.h >= fitH[n] && a >= fitLo[n] && a <= fitHi[n];
+ }
+
+ private int cut(Size p, float b) {
+ boolean across = p.w >= CUT_X_ASPECT * p.h;
+ float least = clampCut(b - AMPLITUDE), most = clampCut(b + AMPLITUDE);
+ Size first = across ? p.scale(b, least, 1, 1) : p.scale(1, 1, b, least);
+ Size second = across ? p.scale(1 - b, 1 - most, 1, 1) : p.scale(1, 1, 1 - b, 1 - most);
+ int partsBefore = parts, sharesBefore = shares, roomsBefore = rooms, wallsBefore = walls;
+ int n = node(across ? CUT_X : CUT_Y, 2);
+ share[n] = newShare(b, least, most, SPEED + SPEED_SPREAD * random.nextFloat(), (float) (2 * Math.PI * random.nextFloat()));
+ index[n] = walls++;
+ int one = part(first), two = part(second);
+ child[n][0] = one;
+ child[n][1] = two;
+ // The cut's fit, worked out along the axis it divides ("along") and the other ("across"):
+ // l, u bound along / across; a, b are the least along and across.
+ float l0 = across ? fitLo[one] : 1 / fitHi[one], u0 = across ? fitHi[one] : 1 / fitLo[one];
+ float l1 = across ? fitLo[two] : 1 / fitHi[two], u1 = across ? fitHi[two] : 1 / fitLo[two];
+ float a0 = across ? fitW[one] : fitH[one], b0 = across ? fitH[one] : fitW[one];
+ float a1 = across ? fitW[two] : fitH[two], b1 = across ? fitH[two] : fitW[two];
+ float l = Math.max(l0 + l1, Math.max(l0 / most, l1 / (1 - least)));
+ float u = Math.min(u0 + u1, Math.min(u0 / least, u1 / (1 - most)));
+ float alongLeast = Math.max(Math.max(a0 + a1, Math.max(a0 / most, a1 / (1 - least))),
+ Math.max(a0 / (1 - l1 / l), a1 / (1 - l0 / l)));
+ float acrossLeast = Math.max(Math.max(b0, b1), Math.max(a0 / u0, a1 / u1));
+ fitLo[n] = across ? l : 1 / u;
+ fitHi[n] = across ? u : 1 / l;
+ fitW[n] = across ? alongLeast : acrossLeast;
+ fitH[n] = across ? acrossLeast : alongLeast;
+ if (!fits(n, p)) return undo(partsBefore, sharesBefore, roomsBefore, wallsBefore);
+ return n;
+ }
+
+ /**
+ * A windmill on part p with these base shares, or -1 if it does not fit (the whole plan's windmill is
+ * always made). Its 4 outer parts are rooms, or grow on if {@code grows}; its centre is always a room.
+ */
+ private int mill(Size p, float ra, float rb, float sa, float sb, boolean mirrored, boolean grows, boolean whole) {
+ float a = ra - AMPLITUDE, b = rb - AMPLITUDE, c = ra + AMPLITUDE, d = rb + AMPLITUDE;
+ float x1 = millLow(ra, rb), x1Lo = millLow(a, b), x1Hi = millLow(c, d);
+ float x2 = millHigh(ra, rb), x2Lo = millHigh(a, b), x2Hi = millHigh(c, d);
+ float gx = x2 - x1, gxLo = Math.max(MILL_GAP, edge(b) - edge(c));
+ a = sa - AMPLITUDE;
+ b = sb - AMPLITUDE;
+ c = sa + AMPLITUDE;
+ d = sb + AMPLITUDE;
+ float y1 = millLow(sa, sb), y1Lo = millLow(a, b), y1Hi = millLow(c, d);
+ float y2 = millHigh(sa, sb), y2Lo = millHigh(a, b), y2Hi = millHigh(c, d);
+ float gy = y2 - y1, gyLo = Math.max(MILL_GAP, edge(b) - edge(c));
+ Size[] kids = {
+ p.scale(x2, x2Lo, y1, y1Lo), // top
+ p.scale(1 - x2, 1 - x2Hi, y2, y2Lo), // right
+ p.scale(1 - x1, 1 - x1Hi, 1 - y2, 1 - y2Hi), // bottom
+ p.scale(x1, x1Lo, 1 - y1, 1 - y1Hi), // left
+ p.scale(gx, gxLo, gy, gyLo)}; // centre
+ int partsBefore = parts, sharesBefore = shares, roomsBefore = rooms, wallsBefore = walls;
+ int n = node(mirrored ? MILL_MIRRORED : MILL, 5);
+ float turn = SPEED + SPEED_SPREAD * random.nextFloat(), at = (float) (2 * Math.PI * random.nextFloat());
+ float against = p.w >= p.h ? 0 : (float) Math.PI;
+ share[n] = newShare(ra, x1Lo, x1Hi, turn, at + jitter());
+ newShare(rb, x2Lo, x2Hi, turn, at + jitter());
+ newShare(sa, y1Lo, y1Hi, turn, at + against + jitter());
+ newShare(sb, y2Lo, y2Hi, turn, at + against + jitter());
+ index[n] = walls;
+ walls += 4;
+ for (int i = 0; i < 4; i++) child[n][i] = grows ? part(kids[i]) : room(kids[i]);
+ child[n][4] = room(kids[4]);
+ millFit(n, p.w / p.h, whole ? p.h : MILL_SHRINK * p.h);
+ if (!whole && !fits(n, p)) return undo(partsBefore, sharesBefore, roomsBefore, wallsBefore);
+ return n;
+ }
+
+ /** Drops every part, share, room and wall made since the counts were these; returns -1. */
+ private int undo(int partsBefore, int sharesBefore, int roomsBefore, int wallsBefore) {
+ parts = partsBefore;
+ shares = sharesBefore;
+ rooms = roomsBefore;
+ walls = wallsBefore;
+ return -1;
+ }
+
+ /**
+ * Windmill n's fit. Its least height is {@code h}, or more if y-walls that give all 5 parts their least
+ * heights need more. Its widths over heights are the run round {@code a} at which, at that height (taller
+ * only makes it easier) and for every pair of y-walls the shares can make, x-walls exist that keep all 5
+ * parts in their fits; found in steps of 2 %, a step inside the last that held, for the y-walls between
+ * the samples.
+ */
+ private void millFit(int n, float a, float h) {
+ float low = 0, high = 64;
+ for (int i = 0; i < 40; i++) {
+ float mid = (low + high) / 2;
+ if (millYFits(n, mid)) high = mid; else low = mid;
+ }
+ float least = Math.max(h, high), step = 1.02f;
+ float from = a, to = a;
+ if (millXFits(n, a, least)) {
+ while (from > 0.05f && millXFits(n, from / step, least)) from /= step;
+ while (to < 20f && millXFits(n, to * step, least)) to *= step;
+ from = Math.min(a, from * step);
+ to = Math.max(a, to / step);
+ } else {
+ from = Float.MAX_VALUE;
+ to = 0;
+ }
+ fitLo[n] = from;
+ fitHi[n] = to;
+ fitH[n] = least;
+ fitW[n] = from * least;
+ }
+
+ /** True if windmill n, h plan heights tall, has y-walls that give all 5 parts their least heights. */
+ private boolean millYFits(int n, float h) {
+ int s = share[n] + 2;
+ int[] c = child[n];
+ float lowLo = Math.max(lo[s], fitH[c[0]] / h), lowHi = Math.min(hi[s], 1 - fitH[c[3]] / h);
+ float highLo = Math.max(lo[s + 1], fitH[c[1]] / h), highHi = Math.min(hi[s + 1], 1 - fitH[c[2]] / h);
+ float gap = Math.max(millGap(s), fitH[c[4]] / h);
+ return lowLo <= lowHi && highLo <= highHi && lowLo + gap <= highHi;
+ }
+
+ /** True if windmill n, h tall and a times as wide, keeps its parts in their fits whatever its y-walls. */
+ private boolean millXFits(int n, float a, float h) {
+ int s = share[n];
+ int[] c = child[n];
+ float w = a * h;
+ int samples = 8;
+ for (int i = 0; i <= samples; i++) {
+ for (int j = 0; j <= samples; j++) {
+ float sa = base[s + 2] + AMPLITUDE * (2f * i / samples - 1), sb = base[s + 3] + AMPLITUDE * (2f * j / samples - 1);
+ float s1 = millLow(sa, sb), s2 = millHigh(sa, sb);
+ float r1 = millX(n, false, w, h, 1, s1, s2, base[s], base[s + 1]);
+ float r2 = millX(n, true, w, h, 1, s1, s2, base[s], base[s + 1]);
+ if (!inFit(c[0], r2 * w, s1 * h) || !inFit(c[1], (1 - r2) * w, s2 * h)
+ || !inFit(c[2], (1 - r1) * w, (1 - s2) * h) || !inFit(c[3], r1 * w, (1 - s1) * h)
+ || !inFit(c[4], (r2 - r1) * w, (s2 - s1) * h)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ /** True if part n keeps its least width and its widths over heights at w by h (its height is checked apart). */
+ private boolean inFit(int n, float w, float h) {
+ float a = w / h, slack = 1e-4f;
+ return w >= fitW[n] * (1 - slack) && a >= fitLo[n] * (1 - slack) && a <= fitHi[n] * (1 + slack);
+ }
+
+ private int room(Size p) {
+ int n = node(ROOM, 0);
+ int k = rooms++;
+ index[n] = k;
+ fitLo[n] = 1 / roomFit;
+ fitHi[n] = roomFit;
+ fitW[n] = minSide;
+ fitH[n] = minSide;
+ if (k == minShareW.length) {
+ minShareW = Arrays.copyOf(minShareW, 2 * k);
+ minShareH = Arrays.copyOf(minShareH, 2 * k);
+ }
+ minShareW[k] = p.wLo / p.planW;
+ minShareH[k] = p.hLo;
+ return n;
+ }
+
+ private int node(int type, int children) {
+ int n = parts++;
+ if (n == kind.length) {
+ kind = Arrays.copyOf(kind, 2 * n);
+ share = Arrays.copyOf(share, 2 * n);
+ index = Arrays.copyOf(index, 2 * n);
+ child = Arrays.copyOf(child, 2 * n);
+ fitLo = Arrays.copyOf(fitLo, 2 * n);
+ fitHi = Arrays.copyOf(fitHi, 2 * n);
+ fitW = Arrays.copyOf(fitW, 2 * n);
+ fitH = Arrays.copyOf(fitH, 2 * n);
+ }
+ kind[n] = type;
+ child[n] = new int[children];
+ return n;
+ }
+
+ private float jitter() {
+ return MILL_JITTER * (2 * random.nextFloat() - 1);
+ }
+
+ /** A new share with this base, reaching from least to most after the clamps, swinging at this speed and phase. */
+ private int newShare(float b, float least, float most, float swing, float from) {
+ int s = shares++;
+ if (s == base.length) {
+ base = Arrays.copyOf(base, 2 * s);
+ speed = Arrays.copyOf(speed, 2 * s);
+ phase = Arrays.copyOf(phase, 2 * s);
+ lo = Arrays.copyOf(lo, 2 * s);
+ hi = Arrays.copyOf(hi, 2 * s);
+ }
+ base[s] = b;
+ lo[s] = least;
+ hi[s] = most;
+ speed[s] = swing;
+ phase[s] = from;
+ return s;
+ }
+ }
+
+ /**
+ * A part's size in plan heights: at the base shares, and its least with every share at its worst.
+ * {@code planW} is the whole plan's width.
+ */
+ private static final class Size {
+ final float w, h, wLo, hLo, planW;
+
+ /** The whole plan. */
+ Size(float w, float h) {
+ this(w, h, w, h, w);
+ }
+
+ private Size(float w, float h, float wLo, float hLo, float planW) {
+ this.w = w;
+ this.h = h;
+ this.wLo = wLo;
+ this.hLo = hLo;
+ this.planW = planW;
+ }
+
+ /** This part's child that gets these shares of its width and height, at the base and at the worst. */
+ Size scale(float sw, float swLo, float sh, float shLo) {
+ return new Size(w * sw, h * sh, wLo * swLo, hLo * shLo, planW);
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlanDream.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlanDream.java
new file mode 100644
index 000000000..bca0bd65b
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlanDream.java
@@ -0,0 +1,30 @@
+package io.github.pbanddev.tatami;
+
+import android.service.dreams.DreamService;
+
+/** The TV screensaver: the floor plan, full screen. Any key wakes the TV back to where it was. */
+public final class FloorPlanDream extends DreamService {
+ private FloorPlanView plan;
+
+ @Override
+ public void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ setInteractive(false);
+ setFullscreen(true);
+ plan = new FloorPlanView(this);
+ setContentView(plan);
+ }
+
+ @Override
+ public void onDreamingStarted() {
+ super.onDreamingStarted();
+ plan.setEffects(Effects.load(this));
+ plan.onResume();
+ }
+
+ @Override
+ public void onDreamingStopped() {
+ plan.onPause();
+ super.onDreamingStopped();
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlanGlRenderer.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlanGlRenderer.java
new file mode 100644
index 000000000..af2b1d249
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlanGlRenderer.java
@@ -0,0 +1,437 @@
+package io.github.pbanddev.tatami;
+
+import android.opengl.GLES20;
+import android.opengl.GLSurfaceView;
+import android.util.Log;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.FloatBuffer;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10;
+
+/**
+ * Draws the floor plan with OpenGL ES 2, all on the GPU, through a film-like lens ({@link Look.Post}):
+ * <ol>
+ * <li>the copy to blur: the bare scene (the cheapest shader there is) into a texture {@link Lens#margin} bigger
+ * than the screen on every side, so walls just off screen blur in at the edges as they should;</li>
+ * <li>that copy averaged down to a quarter size as a 4x4 box;</li>
+ * <li>one separable Gaussian round there, across and then down (2 passes);</li>
+ * <li>the scene into the window (the window asks for 4x MSAA, so tilted walls stay smooth), with the
+ * vignette, the colour ramp and the grain;</li>
+ * <li>the blurred copy, given the same vignette and colour ramp, blended over it everywhere but a sharp
+ * oval in the middle. Both are smooth over hundreds of pixels, so giving them after the blur looks the
+ * same as before it, and the blurred copy's scene pass stays cheap.</li>
+ * </ol>
+ * The vignette, the colour ramp and the blur's oval come from a small picture of the screen made once per
+ * size ({@link Lens}), so each pixel reads them instead of working them out. Nagaya's fills come washed from the
+ * CPU ({@link Wash}), so its 2 window passes take no vignette or colour ramp; its blend reads the map's oval only.
+ * Six passes; with tilt-shift off, only the scene into the window. Nothing is copied from the CPU to the GPU
+ * each frame except the scene's triangles. The grain tile goes up once per GL context.
+ *
+ * <p>Each look has its own {@link Slot}; the {@link LookSchedule} picks the one to draw each frame and how bright.
+ * Yojōhan's scene is built here, at once, as it always was. Nagaya's is built once per process on a background
+ * thread ({@link NagayaScene}), after this view's first frame, and only once the Look setting asks for it. Anything
+ * Nagaya throws marks it failed for the process ({@link Scenes#APP}) and Yojōhan is drawn instead; only a failure
+ * of Yojōhan's frame, or of what both share, sets {@link #broken}.
+ */
+final class FloorPlanGlRenderer implements GLSurfaceView.Renderer {
+
+ /** Attribute slots, bound before every program links. */
+ private static final int POS = 0, COLOR = 1;
+ private static final long GRAIN_SEED = 1L;
+ /** Its lens values size the render targets and make the lens map, which Nagaya reads only for the blur's oval. */
+ private final Look look = Look.YOJOHAN;
+ private final Slot yojohan = new Slot(Look.YOJOHAN);
+ private final Slot nagaya = new Slot(Look.NAGAYA);
+ private final LookSchedule schedule = new LookSchedule();
+ /** The wall-clock time of this view's first frame, for the schedule; NaN before it. */
+ private double startedAt = Double.NaN;
+ private final float floorR, floorG, floorB;
+ private final FloatBuffer quadBuffer;
+ /** The grain tile, made once on the GL thread, off Home's main thread. Its GPU copy dies with each GL context. */
+ private ByteBuffer grainPixels;
+ private final float[] grainOffset = new float[2];
+ /**
+ * Index 0 is the full-size copy of the scene, a margin bigger than the screen on every side; 1 and 2
+ * are the 1/4-size blur targets of the same area; 3 is the lens map.
+ */
+ private final int[] texture = new int[4];
+ private final int[] framebuffer = new int[3];
+ /**
+ * The copy to blur reaches this far past the screen's left and right, and top and bottom, edges, so walls
+ * just off screen blur in too: {@link Lens#margin}, padded so the copy is whole GPU tiles.
+ */
+ private int marginX, marginY;
+ /** The camera matrix for the copy to blur: the screen's, shrunk to fit the wider target. */
+ private final float[] wideMatrix = new float[16];
+ private volatile Effects effects;
+ private int width, height, wideWidth, wideHeight, blurWidth, blurHeight;
+ /** The passes both looks share: their shaders are the same for both. */
+ private int plainProgram, downsample, blur, meshVbo, quadVbo, grainTexture;
+ /** Uniform locations, named as in the shaders. */
+ private int uPlainMatrix, uTexel, uStep;
+
+ /**
+ * One look's part of the renderer: its scene, its own copy of each frame's triangles and matrix (Nagaya's scene is
+ * shared by the process, so a frame is copied out under its lock), and its programs, made in every GL context.
+ */
+ private static final class Slot {
+ final Look look;
+ /** Yojōhan's from the start; Nagaya's once its shared build is ready. Read on the GL thread only. */
+ Scene scene;
+ /** Sized from the scene's own mesh. */
+ FloatBuffer mesh;
+ int floats;
+ final float[] matrix = new float[16];
+ /** True once the programs exist in the current GL context. */
+ boolean made;
+ int sceneProgram, blend;
+ /** Uniform locations, named as in the shaders. uLens reads texture unit 1; every other sampler unit 0. */
+ int uMatrix, uInvSize, uVig, uGrainAmp, uGrainOffset, uFade, uBlendVig, uBlendFade, uBlurArea;
+
+ Slot(Look look) {
+ this.look = look;
+ }
+
+ /** Takes the scene and a buffer for its triangles. */
+ void hold(Scene scene) {
+ mesh = floats(scene.mesh.data.length);
+ this.scene = scene;
+ }
+ }
+
+ FloorPlanGlRenderer(Effects effects) {
+ this.effects = effects;
+ floorR = ((look.palette.floor >> 16) & 0xFF) / 255f;
+ floorG = ((look.palette.floor >> 8) & 0xFF) / 255f;
+ floorB = (look.palette.floor & 0xFF) / 255f;
+ yojohan.hold(Scenes.APP.make(Look.YOJOHAN, NagayaScene::report));
+ quadBuffer = floats(8);
+ quadBuffer.put(new float[] {-1, -1, 1, -1, -1, 1, 1, 1}).position(0);
+ }
+
+ void setEffects(Effects effects) {
+ this.effects = effects;
+ }
+
+ /**
+ * A GL call failed (a shader or a render target the driver refused, or memory ran out, say right after a 4K app):
+ * clear to the floor colour instead. The GL thread must keep drawing, because the window that holds this view
+ * waits for its first frame before Android shows it; a dead GL thread left Home black and not responding.
+ * A new context (the next time the surface is created) tries again.
+ */
+ private boolean broken;
+
+ @Override
+ public void onSurfaceCreated(GL10 unused, EGLConfig config) {
+ broken = false;
+ try {
+ setUp();
+ } catch (RuntimeException | OutOfMemoryError failure) {
+ fail(failure);
+ }
+ }
+
+ @Override
+ public void onSurfaceChanged(GL10 unused, int w, int h) {
+ width = w;
+ height = h;
+ if (broken) return;
+ try {
+ size(w, h);
+ } catch (RuntimeException | OutOfMemoryError failure) {
+ fail(failure);
+ }
+ }
+
+ @Override
+ public void onDrawFrame(GL10 unused) {
+ if (!broken) {
+ try {
+ draw();
+ return;
+ } catch (RuntimeException | OutOfMemoryError failure) {
+ fail(failure);
+ }
+ }
+ GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
+ GLES20.glViewport(0, 0, width, height);
+ GLES20.glClearColor(floorR, floorG, floorB, 1f);
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+ }
+
+ private void fail(Throwable failure) {
+ broken = true;
+ Log.e("Tatami", "the floor plan cannot draw on this context", failure);
+ }
+
+ /** A new context: everything from the old one is gone, its render targets and grain tile too. */
+ private void setUp() {
+ texture[0] = 0; // so size() does not delete the old names, which may be live ones in this context
+ nagaya.made = false; // made when Nagaya is first ready in this context
+ make(yojohan);
+ plainProgram = program(Shaders.SCENE_VERTEX, Shaders.PLAIN_FRAGMENT);
+ downsample = program(Shaders.QUAD_VERTEX, Shaders.DOWNSAMPLE_FRAGMENT);
+ blur = program(Shaders.QUAD_VERTEX, Shaders.blurFragment(look.post));
+ uPlainMatrix = GLES20.glGetUniformLocation(plainProgram, "uMatrix");
+ uTexel = GLES20.glGetUniformLocation(downsample, "uTexel");
+ uStep = GLES20.glGetUniformLocation(blur, "uStep");
+ int[] buffers = new int[2];
+ GLES20.glGenBuffers(2, buffers, 0);
+ meshVbo = buffers[0];
+ quadVbo = buffers[1];
+ GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, quadVbo);
+ GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, 8 * 4, quadBuffer, GLES20.GL_STATIC_DRAW);
+ if (grainPixels == null) grainPixels = ByteBuffer.wrap(Grain.texture(Grain.field(GRAIN_SEED)));
+ int[] grain = new int[1];
+ GLES20.glGenTextures(1, grain, 0);
+ grainTexture = grain[0];
+ GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, grainTexture);
+ GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, Grain.SIZE, Grain.SIZE, 0,
+ GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, grainPixels);
+ sampling(GLES20.GL_NEAREST, GLES20.GL_REPEAT);
+ GLES20.glDisable(GLES20.GL_DEPTH_TEST);
+ GLES20.glClearColor(floorR, floorG, floorB, 1f);
+ }
+
+ private void size(int w, int h) {
+ int least = Lens.margin(look.post);
+ marginX = Lens.padded(w, least, look.post.blurDivisor);
+ marginY = Lens.padded(h, least, look.post.blurDivisor);
+ wideWidth = w + 2 * marginX;
+ wideHeight = h + 2 * marginY;
+ blurWidth = Math.max(1, wideWidth / look.post.blurDivisor);
+ blurHeight = Math.max(1, wideHeight / look.post.blurDivisor);
+ if (texture[0] != 0) {
+ GLES20.glDeleteTextures(4, texture, 0);
+ GLES20.glDeleteFramebuffers(3, framebuffer, 0);
+ }
+ GLES20.glGenTextures(4, texture, 0);
+ GLES20.glGenFramebuffers(3, framebuffer, 0);
+ for (int i = 0; i < 3; i++) {
+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[i]);
+ GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, i == 0 ? wideWidth : blurWidth, i == 0 ? wideHeight : blurHeight, 0,
+ GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
+ sampling(GLES20.GL_LINEAR, GLES20.GL_CLAMP_TO_EDGE);
+ GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebuffer[i]);
+ GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
+ GLES20.GL_TEXTURE_2D, texture[i], 0);
+ int status = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER);
+ if (status != GLES20.GL_FRAMEBUFFER_COMPLETE) throw new IllegalStateException("render target " + i + " incomplete: " + status);
+ }
+ GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[3]);
+ GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, Lens.width(w), Lens.height(h), 0,
+ GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, ByteBuffer.wrap(Lens.map(w, h, look.post)));
+ sampling(GLES20.GL_LINEAR, GLES20.GL_CLAMP_TO_EDGE);
+ }
+
+ /** The slot's look's own passes: the scene into the window, and the blurred copy over it. */
+ private static void make(Slot s) {
+ Look.Post post = s.look.post;
+ s.sceneProgram = program(Shaders.SCENE_VERTEX, Shaders.sceneFragment(post));
+ s.blend = program(Shaders.QUAD_VERTEX, Shaders.blendFragment(post));
+ s.uMatrix = GLES20.glGetUniformLocation(s.sceneProgram, "uMatrix");
+ s.uInvSize = GLES20.glGetUniformLocation(s.sceneProgram, "uInvSize");
+ s.uVig = GLES20.glGetUniformLocation(s.sceneProgram, "uVig");
+ s.uGrainAmp = GLES20.glGetUniformLocation(s.sceneProgram, "uGrainAmp");
+ s.uGrainOffset = GLES20.glGetUniformLocation(s.sceneProgram, "uGrainOffset");
+ s.uFade = GLES20.glGetUniformLocation(s.sceneProgram, "uFade");
+ s.uBlendVig = GLES20.glGetUniformLocation(s.blend, "uVig");
+ s.uBlurArea = GLES20.glGetUniformLocation(s.blend, "uBlurArea");
+ s.uBlendFade = GLES20.glGetUniformLocation(s.blend, "uFade");
+ lensOnUnit1(s.sceneProgram);
+ lensOnUnit1(s.blend);
+ s.made = true;
+ }
+
+ /** Points the program's uLens sampler at texture unit 1. */
+ private static void lensOnUnit1(int program) {
+ GLES20.glUseProgram(program);
+ GLES20.glUniform1i(GLES20.glGetUniformLocation(program, "uLens"), 1);
+ }
+
+ private void draw() {
+ Effects fx = effects;
+ double t = FloorPlanView.now();
+ boolean wantsNagaya = fx.look != LookSchedule.Mode.YOJOHAN;
+ if (Double.isNaN(startedAt)) startedAt = t;
+ schedule.at(t, fx.look, fx.swapMinutes * 60.0, wantsNagaya ? nagayaSince() : Double.POSITIVE_INFINITY, startedAt);
+ if (schedule.look == Look.NAGAYA) {
+ try {
+ draw(nagaya, fx, t, schedule.fade);
+ } catch (Throwable failure) {
+ Scenes.APP.failed(Look.NAGAYA, failure, NagayaScene::report);
+ draw(yojohan, fx, t, 1f);
+ }
+ } else {
+ draw(yojohan, fx, t, schedule.fade);
+ }
+ if (wantsNagaya) NagayaScene.request(); // after the first frame, so the plan shows at once
+ }
+
+ /**
+ * When Nagaya became ready to draw, for the schedule: positive infinity until its shared scene is built and,
+ * in this context, its programs are made. A failure here marks it failed and keeps Yojōhan.
+ */
+ private double nagayaSince() {
+ Scene shared = NagayaScene.scene();
+ if (shared == null) return Double.POSITIVE_INFINITY;
+ try {
+ if (nagaya.scene != shared) nagaya.hold(shared);
+ if (!nagaya.made) make(nagaya);
+ } catch (Throwable failure) {
+ Scenes.APP.failed(Look.NAGAYA, failure, NagayaScene::report);
+ return Double.POSITIVE_INFINITY;
+ }
+ return NagayaScene.readySince();
+ }
+
+ /** One frame of the slot's look; {@code fade} darkens all of it, 1 as drawn, 0 black. */
+ private void draw(Slot s, Effects fx, double t, float fade) {
+ Scene scene = s.scene;
+ synchronized (scene) {
+ scene.build(t, width, height, fx.doors, fx.fixtures, fx.camera, fx.vignette);
+ s.floats = scene.mesh.floats;
+ s.mesh.clear();
+ s.mesh.put(scene.mesh.data, 0, s.floats).position(0);
+ System.arraycopy(scene.matrix, 0, s.matrix, 0, 16);
+ }
+ GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, meshVbo);
+ GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, s.floats * 4, s.mesh, GLES20.GL_STREAM_DRAW);
+ Grain.offset(t, s.look.post.grainFps, grainOffset);
+ // a look washed on the CPU has no uVig: the vignette switch turned its wash off in the build above
+ float vignette = fx.vignette ? 1f : 0f;
+ GLES20.glActiveTexture(GLES20.GL_TEXTURE1);
+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[3]);
+ GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
+
+ if (fx.tiltShift) {
+ GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebuffer[0]);
+ GLES20.glViewport(0, 0, wideWidth, wideHeight);
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+ drawPlainScene(s); // no lens yet, and no grain: grain belongs to the sharp layer only
+ GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebuffer[1]);
+ GLES20.glViewport(0, 0, blurWidth, blurHeight);
+ GLES20.glUseProgram(downsample);
+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[0]);
+ GLES20.glUniform2f(uTexel, 1f / wideWidth, 1f / wideHeight);
+ drawQuad();
+ blurInto(2, texture[1], 1f / blurWidth, 0f);
+ blurInto(1, texture[2], 0f, 1f / blurHeight);
+ }
+
+ GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
+ GLES20.glViewport(0, 0, width, height);
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+ drawScene(s, vignette, fx.grain ? 1f : 0f, fade);
+
+ if (fx.tiltShift) {
+ GLES20.glEnable(GLES20.GL_BLEND);
+ GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
+ GLES20.glUseProgram(s.blend);
+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[1]);
+ GLES20.glUniform1f(s.uBlendVig, vignette);
+ GLES20.glUniform1f(s.uBlendFade, fade);
+ // where the screen sits inside the wider blurred copy: scale x, y, then offset x, y
+ GLES20.glUniform4f(s.uBlurArea, (float) width / wideWidth, (float) height / wideHeight,
+ (float) marginX / wideWidth, (float) marginY / wideHeight);
+ drawQuad();
+ GLES20.glDisable(GLES20.GL_BLEND);
+ }
+ }
+
+ /**
+ * The scene's triangles through the lens into the bound target. {@code vignette} and {@code grain} are 1 (on) or
+ * 0 (off); {@code fade} darkens the result.
+ */
+ private void drawScene(Slot s, float vignette, float grain, float fade) {
+ GLES20.glUseProgram(s.sceneProgram);
+ GLES20.glUniformMatrix4fv(s.uMatrix, 1, false, s.matrix, 0);
+ GLES20.glUniform2f(s.uInvSize, 1f / width, 1f / height);
+ GLES20.glUniform1f(s.uVig, vignette);
+ GLES20.glUniform1f(s.uGrainAmp, grain);
+ GLES20.glUniform1f(s.uFade, fade);
+ GLES20.glUniform2f(s.uGrainOffset, grainOffset[0], grainOffset[1]);
+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, grainTexture);
+ drawTriangles(s);
+ }
+
+ /** The scene's triangles as they are into the wider copy to blur: the screen's view, shrunk to fit it. */
+ private void drawPlainScene(Slot s) {
+ float[] m = s.matrix, wide = wideMatrix;
+ float sx = (float) width / wideWidth, sy = (float) height / wideHeight;
+ System.arraycopy(m, 0, wide, 0, 16);
+ wide[0] = m[0] * sx;
+ wide[4] = m[4] * sx;
+ wide[12] = m[12] * sx;
+ wide[1] = m[1] * sy;
+ wide[5] = m[5] * sy;
+ wide[13] = m[13] * sy;
+ GLES20.glUseProgram(plainProgram);
+ GLES20.glUniformMatrix4fv(uPlainMatrix, 1, false, wide, 0);
+ drawTriangles(s);
+ }
+
+ private void drawTriangles(Slot s) {
+ GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, meshVbo);
+ int stride = SceneMesh.FLOATS_PER_VERTEX * 4;
+ GLES20.glEnableVertexAttribArray(POS);
+ GLES20.glVertexAttribPointer(POS, 2, GLES20.GL_FLOAT, false, stride, 0);
+ GLES20.glEnableVertexAttribArray(COLOR);
+ GLES20.glVertexAttribPointer(COLOR, 4, GLES20.GL_FLOAT, false, stride, 8);
+ GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, s.floats / SceneMesh.FLOATS_PER_VERTEX);
+ GLES20.glDisableVertexAttribArray(COLOR);
+ }
+
+ private void blurInto(int target, int source, float stepX, float stepY) {
+ GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebuffer[target]);
+ GLES20.glUseProgram(blur);
+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, source);
+ GLES20.glUniform2f(uStep, stepX, stepY);
+ drawQuad();
+ }
+
+ private void drawQuad() {
+ GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, quadVbo);
+ GLES20.glEnableVertexAttribArray(POS);
+ GLES20.glVertexAttribPointer(POS, 2, GLES20.GL_FLOAT, false, 8, 0);
+ GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
+ }
+
+ /** Filtering and wrapping of the bound texture. */
+ private static void sampling(int filter, int wrap) {
+ GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, filter);
+ GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, filter);
+ GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, wrap);
+ GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, wrap);
+ }
+
+ private static int program(String vertex, String fragment) {
+ int program = GLES20.glCreateProgram();
+ GLES20.glAttachShader(program, shader(GLES20.GL_VERTEX_SHADER, vertex));
+ GLES20.glAttachShader(program, shader(GLES20.GL_FRAGMENT_SHADER, fragment));
+ GLES20.glBindAttribLocation(program, POS, "aPos");
+ GLES20.glBindAttribLocation(program, COLOR, "aColor");
+ GLES20.glLinkProgram(program);
+ int[] ok = new int[1];
+ GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, ok, 0);
+ if (ok[0] == 0) throw new IllegalStateException("link: " + GLES20.glGetProgramInfoLog(program));
+ return program;
+ }
+
+ private static int shader(int type, String source) {
+ int shader = GLES20.glCreateShader(type);
+ GLES20.glShaderSource(shader, source);
+ GLES20.glCompileShader(shader);
+ int[] ok = new int[1];
+ GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, ok, 0);
+ if (ok[0] == 0) throw new IllegalStateException("compile: " + GLES20.glGetShaderInfoLog(shader));
+ return shader;
+ }
+
+ private static FloatBuffer floats(int count) {
+ return ByteBuffer.allocateDirect(count * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlanView.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlanView.java
new file mode 100644
index 000000000..fb1a83b19
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/FloorPlanView.java
@@ -0,0 +1,212 @@
+package io.github.pbanddev.tatami;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.os.Handler;
+import android.os.Looper;
+import android.opengl.GLSurfaceView;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.Choreographer;
+import android.view.SurfaceHolder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+import javax.microedition.khronos.egl.EGL10;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.egl.EGLDisplay;
+
+/**
+ * The animated floor plan on an OpenGL surface. The host calls {@link #onResume()} and
+ * {@link #onPause()}. Time comes from the wall clock, so every view of it shows the same frame.
+ *
+ * <p>One frame per display refresh, asked for by the Choreographer, never as fast as the surface takes them.
+ * Free-running (RENDERMODE_CONTINUOUSLY), the GL thread queued frames until the surface's buffers were full, and
+ * after Home sat still for a while it could settle one frame further ahead (44 ms to the screen became 61 ms)
+ * and stay there. Its GPU work then landed on the start of every refresh, where SurfaceFlinger composes this
+ * layer on the GPU, and the launcher's own frames waited behind both: 98 % janky over the dock on the test
+ * TV, while the plan itself still showed 60 fps. A request made while a frame is still being drawn
+ * simply waits for it, so the queue cannot grow.
+ */
+public final class FloorPlanView extends GLSurfaceView {
+ private final FloorPlanGlRenderer renderer;
+ private final Choreographer choreographer = Choreographer.getInstance();
+ private boolean ticking;
+ private final Choreographer.FrameCallback tick = new Choreographer.FrameCallback() {
+ @Override
+ public void doFrame(long frameTimeNanos) {
+ if (!ticking) return;
+ requestRender();
+ choreographer.postFrameCallback(this);
+ }
+ };
+
+ public FloorPlanView(Context context) {
+ this(context, null);
+ }
+
+ public FloorPlanView(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ recordsGlFailure(context);
+ setEGLContextClientVersion(2);
+ setEGLConfigChooser(new SmoothEdges());
+ renderer = new FloorPlanGlRenderer(Effects.load(context));
+ setRenderer(renderer);
+ setRenderMode(RENDERMODE_WHEN_DIRTY);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (ticking) return;
+ ticking = true;
+ choreographer.postFrameCallback(tick);
+ }
+
+ @Override
+ public void onPause() {
+ ticking = false;
+ choreographer.removeFrameCallback(tick);
+ super.onPause();
+ }
+
+ private static final String FAILURE_FILE = "floor_plan";
+ private static final String FAILED_INSTALL = "gl_failed_install";
+ private static boolean recording;
+ /** A GL thread in this process died; set and read on the main thread. */
+ private static boolean glDead;
+ /** The plans on screen now, so a dead GL thread can let their windows draw. Main thread only. */
+ private static final List<FloorPlanView> attached = new ArrayList<>();
+ /** The window's wait for this surface's next frame, handed to the GL thread; null once it ran. */
+ private Runnable pendingDraw;
+
+ /**
+ * True when the plan's OpenGL setup failed in GLSurfaceView itself (no config, a context the driver refuses) since
+ * this version of the app was installed. Home then leaves the plan out, as with floor_plan false. Installing an
+ * update tries again.
+ */
+ public static boolean failedOnThisInstall(Context context) {
+ return context.getSharedPreferences(FAILURE_FILE, Context.MODE_PRIVATE).getLong(FAILED_INSTALL, -1) == installed(context);
+ }
+
+ /**
+ * The renderer survives its own GL failures (FloorPlanGlRenderer#broken); these come from GLSurfaceView's own EGL
+ * setup, which throws on its GL thread. The app must not crash: on Android 10 any crash of a Home that is not a
+ * system app makes Android forget it as the default Home, and the next Home press shows the chooser (seen on the
+ * test TV). So only that thread ends. Without it the window would wait forever for the frame it asked the thread
+ * for, and Home would stay black and not responding, so that wait is let go here; the plan stays black and the
+ * UI over it works. The failure is written down, so Home's next start leaves the plan out.
+ * GLSurfaceView names its thread "GLThread &lt;id&gt;". Other threads keep the handler they had.
+ */
+ private static synchronized void recordsGlFailure(Context context) {
+ if (recording) return;
+ recording = true;
+ Context app = context.getApplicationContext();
+ Handler main = new Handler(Looper.getMainLooper());
+ Thread.UncaughtExceptionHandler next = Thread.getDefaultUncaughtExceptionHandler();
+ Thread.setDefaultUncaughtExceptionHandler((thread, error) -> {
+ if (!thread.getName().startsWith("GLThread")) {
+ if (next != null) next.uncaughtException(thread, error);
+ return;
+ }
+ Log.e("Tatami", "the floor plan cannot draw on this TV", error);
+ app.getSharedPreferences(FAILURE_FILE, Context.MODE_PRIVATE).edit()
+ .putLong(FAILED_INSTALL, installed(app)).apply();
+ main.post(() -> {
+ glDead = true;
+ for (FloorPlanView view : new ArrayList<>(attached)) view.releasePendingDraw();
+ });
+ });
+ }
+
+ @Override
+ protected void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ attached.add(this);
+ }
+
+ @Override
+ protected void onDetachedFromWindow() {
+ attached.remove(this);
+ releasePendingDraw();
+ super.onDetachedFromWindow();
+ }
+
+ /** The window waits for this surface's next frame; the GL thread runs it after drawing, unless it is dead. */
+ @Override
+ public void surfaceRedrawNeededAsync(SurfaceHolder holder, Runnable finishDrawing) {
+ if (glDead) {
+ finishDrawing.run();
+ return;
+ }
+ AtomicBoolean done = new AtomicBoolean();
+ Runnable once = () -> {
+ if (done.compareAndSet(false, true)) finishDrawing.run();
+ };
+ pendingDraw = once;
+ super.surfaceRedrawNeededAsync(holder, once);
+ }
+
+ private void releasePendingDraw() {
+ Runnable draw = pendingDraw;
+ pendingDraw = null;
+ if (draw != null && glDead) draw.run();
+ }
+
+ private static long installed(Context context) {
+ try {
+ return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).lastUpdateTime;
+ } catch (PackageManager.NameNotFoundException impossible) {
+ return 0;
+ }
+ }
+
+ static double now() {
+ return System.currentTimeMillis() / 1000.0;
+ }
+
+ void setEffects(Effects effects) {
+ renderer.setEffects(effects);
+ }
+
+ /** RGB 888 with 4x multisampling where the TV has it, plain RGB 888 where it does not. */
+ private static final class SmoothEdges implements EGLConfigChooser {
+ private static final int EGL_OPENGL_ES2_BIT = 4;
+
+ @Override
+ public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
+ EGLConfig smooth = pick(egl, display, true);
+ if (smooth != null) return smooth;
+ EGLConfig plain = pick(egl, display, false);
+ if (plain != null) return plain;
+ throw new IllegalStateException("no OpenGL ES 2 window config");
+ }
+
+ private static EGLConfig pick(EGL10 egl, EGLDisplay display, boolean multisample) {
+ int[] spec = multisample
+ ? new int[] {EGL10.EGL_RED_SIZE, 8, EGL10.EGL_GREEN_SIZE, 8, EGL10.EGL_BLUE_SIZE, 8,
+ EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
+ EGL10.EGL_SAMPLE_BUFFERS, 1, EGL10.EGL_SAMPLES, 4, EGL10.EGL_NONE}
+ : new int[] {EGL10.EGL_RED_SIZE, 8, EGL10.EGL_GREEN_SIZE, 8, EGL10.EGL_BLUE_SIZE, 8,
+ EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL10.EGL_NONE};
+ int[] count = new int[1];
+ if (!egl.eglChooseConfig(display, spec, null, 0, count) || count[0] == 0) return null;
+ EGLConfig[] configs = new EGLConfig[count[0]];
+ if (!egl.eglChooseConfig(display, spec, configs, configs.length, count)) return null;
+ int[] value = new int[1];
+ for (EGLConfig config : configs) {
+ if (size(egl, display, config, EGL10.EGL_RED_SIZE, value) == 8
+ && size(egl, display, config, EGL10.EGL_GREEN_SIZE, value) == 8
+ && size(egl, display, config, EGL10.EGL_BLUE_SIZE, value) == 8
+ && size(egl, display, config, EGL10.EGL_DEPTH_SIZE, value) == 0) {
+ return config;
+ }
+ }
+ return configs[0];
+ }
+
+ private static int size(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int[] value) {
+ return egl.eglGetConfigAttrib(display, config, attribute, value) ? value[0] : -1;
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Frame.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Frame.java
new file mode 100644
index 000000000..0ccb6f794
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Frame.java
@@ -0,0 +1,102 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * One drawn moment of the floor plan, in plan units (screen pixels at zoom 1, before the tilt; y points
+ * down). Allocated once and refilled every frame. The contract between the stages of {@link Scene}:
+ *
+ * <ul>
+ * <li><b>Rooms</b> (filled by the {@link Layout}): a room's index holds for one frame; {@code roomId} holds for
+ * good and picks its paint. {@code roomX, roomY, roomW, roomH} box the room's cells. {@code roomMinW} and
+ * {@code roomMinH} are the smallest the room ever gets, at any time; NaN for a room of more than one cell.
+ * {@code roomColor} is an index into {@link Look.Palette#deck} (set by {@link Scene}). In Yojōhan the
+ * index is the id, and each room is one box.</li>
+ * <li><b>Cells</b> (filled by the {@link Layout}): boxes that fill the plan without gaps or overlaps; each
+ * belongs to the room at index {@code cellRoom}. A room is 1 or more cells. Yojōhan copies each room to one
+ * cell.</li>
+ * <li><b>Walls</b> (filled by the {@link Layout}): the wall pieces between rooms, on the wall's centre line,
+ * with {@code x0 <= x1} and {@code y0 <= y1}. {@code wallId} holds for good; {@code wallRoomA} and
+ * {@code wallRoomB} are the room ids on its 2 sides and {@code wallMinLength} the shortest the piece ever
+ * gets (-1 and NaN in Yojōhan, where the index is the id: there is always one wall fewer than rooms, a cut
+ * adds 1 room and 1 wall and a windmill 4 and 4). The plan's outer edge is not a wall.</li>
+ * <li><b>Doors</b> (filled by the {@link DoorPlacer}): each hinges at {@code doorX, doorY} on the centre line of
+ * the wall at index {@code doorWall}. {@code doorAlong} is +1 when the bar runs from the hinge toward +x
+ * (or +y on a vertical wall), -1 the other way. {@code doorSide} is +1 when the leaf swings toward +y (or +x
+ * on a vertical wall), -1 the other way. {@code doorOpening} is in radians: 0 shut, pi/2 open.</li>
+ * <li><b>Fixtures</b> (filled by {@link Fixtures}): a kind in room {@code fixtureRoom}, turned
+ * {@code fixtureTurn} quarter turns (0 to 3), filling the box {@code x, y, w, h} after the turn.</li>
+ * </ul>
+ *
+ * A layout that has more to show than the arrays hold leaves the rest out and sets {@link #clipped}.
+ */
+public final class Frame {
+ public final float[] roomX, roomY, roomW, roomH, roomMinW, roomMinH;
+ public final int[] roomColor, roomId;
+
+ public final float[] cellX, cellY, cellW, cellH;
+ public final int[] cellRoom;
+
+ public final float[] wallX0, wallY0, wallX1, wallY1, wallMinLength;
+ public final boolean[] wallVertical;
+ /** True for a wall piece that may hold a door: the plan keeps it long enough at every moment. Never set in Yojōhan. */
+ public final boolean[] wallDoor;
+ public final int[] wallId, wallRoomA, wallRoomB;
+
+ public final int[] doorWall, doorAlong, doorSide;
+ public final float[] doorX, doorY;
+ public final double[] doorOpening;
+
+ public final int[] fixtureKind, fixtureRoom, fixtureTurn;
+ public final float[] fixtureX, fixtureY, fixtureW, fixtureH;
+
+ /** The most fill pieces {@link SceneMesh} may cut this frame's cells into, for the wash. */
+ public final int fillCapacity;
+
+ public int roomCount, cellCount, wallCount, doorCount, fixtureCount;
+ /** True when the last layout had more than these arrays hold. */
+ public boolean clipped;
+
+ /** Yojōhan's: one cell per room, one wall fewer than rooms, a door per wall at most, a fixture per room. */
+ public Frame(int rooms) {
+ this(rooms, rooms, Math.max(0, rooms - 1), Math.max(0, rooms - 1), rooms, rooms);
+ }
+
+ public Frame(int rooms, int cells, int walls, int doors, int fixtures, int fills) {
+ roomX = new float[rooms];
+ roomY = new float[rooms];
+ roomW = new float[rooms];
+ roomH = new float[rooms];
+ roomMinW = new float[rooms];
+ roomMinH = new float[rooms];
+ roomColor = new int[rooms];
+ roomId = new int[rooms];
+ cellX = new float[cells];
+ cellY = new float[cells];
+ cellW = new float[cells];
+ cellH = new float[cells];
+ cellRoom = new int[cells];
+ wallX0 = new float[walls];
+ wallY0 = new float[walls];
+ wallX1 = new float[walls];
+ wallY1 = new float[walls];
+ wallMinLength = new float[walls];
+ wallVertical = new boolean[walls];
+ wallDoor = new boolean[walls];
+ wallId = new int[walls];
+ wallRoomA = new int[walls];
+ wallRoomB = new int[walls];
+ doorWall = new int[doors];
+ doorAlong = new int[doors];
+ doorSide = new int[doors];
+ doorX = new float[doors];
+ doorY = new float[doors];
+ doorOpening = new double[doors];
+ fixtureKind = new int[fixtures];
+ fixtureRoom = new int[fixtures];
+ fixtureTurn = new int[fixtures];
+ fixtureX = new float[fixtures];
+ fixtureY = new float[fixtures];
+ fixtureW = new float[fixtures];
+ fixtureH = new float[fixtures];
+ fillCapacity = fills;
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Grain.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Grain.java
new file mode 100644
index 000000000..9efdeb720
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Grain.java
@@ -0,0 +1,84 @@
+package io.github.pbanddev.tatami;
+
+import java.util.Random;
+
+/**
+ * The film grain: a tile of noise the scene shader adds to every pixel, and where the tile sits each
+ * frame. Pure Java.
+ *
+ * <p>The grain is grey, zero-mean and comes in clumps of about 2 px (neighbours correlate ~0.5).
+ * The tile is seeded Gaussian noise filtered across and down by a small kernel that wraps around, so the
+ * tile repeats without a seam, then set to mean 0 and std 1. The GPU gets it as GL_LUMINANCE bytes,
+ * {@code 0.5 + n / 8} clamped (4 std each way), and the shader reads back {@code n = (texel - 0.5) * 8}.
+ */
+final class Grain {
+ /** The tile is SIZE x SIZE texels, one texel per screen pixel. */
+ static final int SIZE = 256;
+ private static final float[] KERNEL = {-0.14f, 0.42f, 1f, 0.42f, -0.14f};
+ /** Steps of the R2 sequence: each source frame moves the tile far from the last few. */
+ private static final double STEP_X = 0.7548777, STEP_Y = 0.5698403;
+
+ private Grain() {
+ }
+
+ /** The noise, row-major, mean 0 and std 1. */
+ static float[] field(long seed) {
+ Random random = new Random(seed);
+ float[] noise = new float[SIZE * SIZE];
+ for (int i = 0; i < noise.length; i++) noise[i] = (float) random.nextGaussian();
+ float[] across = new float[noise.length];
+ filter(noise, across, 1, 0);
+ filter(across, noise, 0, 1);
+ double sum = 0, squares = 0;
+ for (float v : noise) {
+ sum += v;
+ squares += (double) v * v;
+ }
+ double mean = sum / noise.length;
+ double std = Math.sqrt(squares / noise.length - mean * mean);
+ for (int i = 0; i < noise.length; i++) noise[i] = (float) ((noise[i] - mean) / std);
+ return noise;
+ }
+
+ /** One GL_LUMINANCE byte per texel: {@code 0.5 + n / 8}, clamped to 0..1. */
+ static byte[] texture(float[] field) {
+ byte[] bytes = new byte[field.length];
+ for (int i = 0; i < field.length; i++) {
+ float level = Math.min(1f, Math.max(0f, 0.5f + field[i] / 8f));
+ bytes[i] = (byte) Math.round(level * 255f);
+ }
+ return bytes;
+ }
+
+ /**
+ * Where the tile sits at {@code seconds}: a shift in texture units into {@code out[0]} (x) and
+ * {@code out[1]} (y), each in [0, 1). It jumps once per source frame ({@code fps} times a second) and
+ * lands on whole texels, so every pixel centre samples one texel centre. The seconds are the wall
+ * clock, ~1.8e9, which needs double.
+ */
+ static void offset(double seconds, double fps, float[] out) {
+ double tick = Math.floor(seconds * fps);
+ out[0] = wholeTexels(0.5 + tick * STEP_X);
+ out[1] = wholeTexels(0.5 + tick * STEP_Y);
+ }
+
+ private static float wholeTexels(double v) {
+ return (float) (Math.floor((v - Math.floor(v)) * SIZE) / SIZE);
+ }
+
+ /** out = in filtered by KERNEL along (dx, dy), wrapping at the tile's edges. */
+ private static void filter(float[] in, float[] out, int dx, int dy) {
+ int mask = SIZE - 1;
+ int half = KERNEL.length / 2;
+ for (int y = 0; y < SIZE; y++) {
+ for (int x = 0; x < SIZE; x++) {
+ float sum = 0;
+ for (int k = 0; k < KERNEL.length; k++) {
+ int o = k - half;
+ sum += KERNEL[k] * in[((y + o * dy) & mask) * SIZE + ((x + o * dx) & mask)];
+ }
+ out[y * SIZE + x] = sum;
+ }
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/IntList.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/IntList.java
new file mode 100644
index 000000000..2eb62b7da
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/IntList.java
@@ -0,0 +1,26 @@
+package io.github.pbanddev.tatami;
+
+import java.util.Arrays;
+
+/** A growing list of ints, for build time only. */
+final class IntList {
+ private int[] values = new int[16];
+ int size;
+
+ void add(int v) {
+ if (size == values.length) values = Arrays.copyOf(values, size * 2);
+ values[size++] = v;
+ }
+
+ int get(int i) {
+ return values[i];
+ }
+
+ void set(int i, int v) {
+ values[i] = v;
+ }
+
+ int[] array() {
+ return Arrays.copyOf(values, size);
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Layout.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Layout.java
new file mode 100644
index 000000000..9bd104663
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Layout.java
@@ -0,0 +1,13 @@
+package io.github.pbanddev.tatami;
+
+/** A look's rooms, cells and walls: built once per look, then laid out into a {@link Frame} every frame. */
+interface Layout {
+ /** Room ids run from 0 to {@code rooms() - 1}; each id gets one paint. */
+ int rooms();
+
+ /** A frame big enough for every layout of this plan. */
+ Frame newFrame();
+
+ /** Fills the rooms, cells and walls of {@code out} for time {@code t}, as seen through {@code view}. */
+ void layout(double t, View view, Frame out);
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Lens.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Lens.java
new file mode 100644
index 000000000..911103aa7
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Lens.java
@@ -0,0 +1,79 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * The lens's slow parts as a small RGBA picture of the screen ({@link Look.Post}): rgb is half the gain
+ * (the vignette times the colour ramp, which reaches a little over 1), a is the blurred copy's weight.
+ * Both change over hundreds of pixels, so one texel per {@link #STEP} x {@link #STEP} pixels, read with
+ * bilinear filtering, stands in for working them out at every pixel. Rows run bottom up, as GL reads them.
+ */
+final class Lens {
+ /** Screen pixels per texel, each way. */
+ static final int STEP = 8;
+
+ private Lens() {}
+
+ /**
+ * How far past every screen edge the copy to blur is drawn, in screen pixels: as far as the blur reaches
+ * (the 4x4 box's 2 px, then each tap's offset plus one small texel for the bilinear read), rounded up to
+ * whole small texels. Without it, walls just off screen would be missing from the blur and the walls
+ * near the edges would smear along it as they come and go.
+ */
+ static int margin(Look.Post post) {
+ float farthest = 0;
+ for (float o : post.blurOffsets) farthest = Math.max(farthest, o);
+ int d = post.blurDivisor;
+ return d * (int) Math.ceil((2 + d * (farthest + 1)) / d);
+ }
+
+ /** The GPU's tile, in pixels each way (16 on most mobile GPUs). A render target in whole tiles draws faster. */
+ private static final int TILE = 16;
+
+ /**
+ * The margin for one side of a screen {@code size} pixels long: at least {@code least}, in whole small
+ * texels ({@code divisor}), and grown so the wider copy is whole GPU tiles when that is possible.
+ */
+ static int padded(int size, int least, int divisor) {
+ for (int m = least; m < least + TILE; m += divisor) {
+ if ((size + 2 * m) % TILE == 0) return m;
+ }
+ return least;
+ }
+
+ static int width(int screenWidth) {
+ return Math.max(1, (screenWidth + STEP - 1) / STEP);
+ }
+
+ static int height(int screenHeight) {
+ return Math.max(1, (screenHeight + STEP - 1) / STEP);
+ }
+
+ /** The picture for a w by h screen, 4 bytes per texel. */
+ static byte[] map(int w, int h, Look.Post post) {
+ int mw = width(w), mh = height(h);
+ byte[] out = new byte[4 * mw * mh];
+ for (int j = 0; j < mh; j++) {
+ double py = ((j + 0.5) * h / mh - h / 2.0) / (h / 2.0);
+ for (int i = 0; i < mw; i++) {
+ double px = ((i + 0.5) * w / mw - w / 2.0) / (h / 2.0);
+ double k = oval(post.vignetteOval, px, py);
+ double vignette = 1 - post.vignette * k * k * k;
+ int at = 4 * (j * mw + i);
+ for (int c = 0; c < 3; c++) {
+ out[at + c] = level(vignette * Math.exp(post.tintX[c] * px + post.tintY[c] * py) / 2);
+ }
+ out[at + 3] = level(oval(post.blurOval, px, py));
+ }
+ }
+ return out;
+ }
+
+ private static double oval(Look.Post.Oval o, double px, double py) {
+ double d = Math.hypot((px - o.x) * o.scaleX, py - o.y);
+ double t = Math.max(0, Math.min(1, (d - o.inner) / (o.outer - o.inner)));
+ return t * t * (3 - 2 * t);
+ }
+
+ private static byte level(double v) {
+ return (byte) Math.round(255 * Math.max(0, Math.min(1, v)));
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Look.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Look.java
new file mode 100644
index 000000000..29f1a3696
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Look.java
@@ -0,0 +1,594 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * Every look value in one place: the cut of the plan, its pace, paints, walls, camera, doors, fixtures and the
+ * lens. One instance per look: {@link #YOJOHAN} (4 mats round a half mat, cut as a tree of rooms) and
+ * {@link #NAGAYA} (rows of small rooms, one tile repeated).
+ *
+ * <p>Yojōhan's motion is not here: its wall speeds, door speed and camera pan and zoom stay in
+ * {@link FloorPlan}, {@link io.github.pbanddev.tatami.Doors} and {@link io.github.pbanddev.tatami.Camera}.
+ * Nagaya's motion is here, in {@link Rhythm}, {@link Motion}, {@link Camera} and {@link Doors}.
+ *
+ * <p>Sizes whose names end in {@code H} are a share of the screen height and become plan units as
+ * {@code screenHeight * size}. The camera's zoom then scales them with the plan, like the walls. Yojōhan's are
+ * given at its middle zoom (1.075), Nagaya's at zoom 1 (its camera zooms from 1 out to 0.78).
+ *
+ * <p>One block per part of the scene. Each block keeps its own instances, one per look, so a change to one
+ * block never touches another block's lines.
+ */
+public final class Look {
+ public static final Look YOJOHAN = new Look(Plan.YOJOHAN, null, null, Palette.OLIVE, Walls.YOJOHAN,
+ Camera.YOJOHAN, Doors.YOJOHAN, Fixtures.YOJOHAN, Post.YOJOHAN);
+ public static final Look NAGAYA = new Look(Plan.NAGAYA, Rhythm.NAGAYA, Motion.NAGAYA, Palette.EMBER,
+ Walls.NAGAYA, Camera.NAGAYA, Doors.NAGAYA, Fixtures.NAGAYA, Post.NAGAYA);
+
+ public final Plan plan;
+ /** When walls move. Null in Yojōhan, whose walls each slide on their own sine. */
+ public final Rhythm rhythm;
+ /** Which walls move and how far. Null in Yojōhan. */
+ public final Motion motion;
+ public final Palette palette;
+ public final Walls walls;
+ public final Camera camera;
+ public final Doors doors;
+ public final Fixtures fixtures;
+ public final Post post;
+
+ Look(Plan plan, Rhythm rhythm, Motion motion, Palette palette, Walls walls, Camera camera, Doors doors,
+ Fixtures fixtures, Post post) {
+ this.plan = plan;
+ this.rhythm = rhythm;
+ this.motion = motion;
+ this.palette = palette;
+ this.walls = walls;
+ this.camera = camera;
+ this.doors = doors;
+ this.fixtures = fixtures;
+ this.post = post;
+ }
+
+ // ------------------------------------------------------------------------------------------ plan
+
+ /**
+ * How the plan is cut into rooms.
+ *
+ * <p>{@link Kind#TREE} (Yojōhan): straight cuts and windmills (4 rooms round a centre room). Areas are in H² on
+ * screen at the camera's middle zoom (1.075).
+ *
+ * <p>{@link Kind#TILE} (Nagaya): one tile of rooms, repeated on a staggered lattice. Every wall lies on a line
+ * whose place is a whole number of {@link #unitH} steps. The tile is {@link #tileWUnits} wide and
+ * {@link #tileHUnits} tall; each row of tiles is shifted half a tile.
+ */
+ public static final class Plan {
+ public enum Kind { TREE, TILE }
+
+ static final Plan YOJOHAN = new Plan(5L, 0.25f, 0.07f, 0.05f, 5f, 2.1f, 0.8f, 0.3f, 0.6f);
+ /** A tile 270 x 174 steps (2.50 x 1.61 H). The smaller knob value is 135 x 87. */
+ static final Plan NAGAYA = new Plan(5L, 1f / 108f, 270, 174, 0.046f, 2, 2, 15.5, 18.5, 0.8,
+ new double[][] {{0.5, 0.5, 0}, {0.2, 0.7, 0.1}, {0.1, 0.3, 0.6}});
+
+ public final Kind kind;
+ /** Picks the layout; every seeded choice in the scene starts from it. */
+ public final long seed;
+
+ // TREE
+
+ /** A part bigger than this is always cut again. */
+ public final float splitAboveH2;
+ /** A part smaller than this is always a room. In between, a coin decides. */
+ public final float stopBelowH2;
+ /** No room's short side is ever below this. */
+ public final float minSideH;
+ /** No room is ever longer than this many times its width. */
+ public final float maxAspect;
+ /** A part stays a room only if, with every wall at its middle, it is at most this long for its width. */
+ public final float roomAspect;
+ /** The chance that a part that can be a windmill is one. */
+ public final float windmillOdds;
+ /** Only parts at least this big become windmills, so the centre room is not too small. */
+ public final float windmillMinH2;
+ /** The share of windmills that turn clockwise. */
+ public final float clockwiseShare;
+
+ // TILE
+
+ /** One step: lines sit and move on whole steps. */
+ public final float unitH;
+ /** The tile in steps: the lattice is (tileW, 0) and (tileW / 2, tileH). */
+ public final int tileWUnits, tileHUnits;
+ /** No room is ever thinner than this across: each cell's height in its row, a room's width between its joints. */
+ public final float minCrossH;
+ /** The least step in a room's edge, and the least offset between 2 joints that meet one wall from both sides. */
+ public final int minStepUnits;
+ /** The least width of a cell. */
+ public final int minCellUnits;
+ /** Rooms per H² that {@link SkylineBuilder} aims for. */
+ public final double roomsPerH2;
+ /** A row's mean height in steps, before its edges step. */
+ public final double courseUnits;
+ /** One row line in every this much tile height (H) runs straight all the way round. */
+ public final double straightEveryH;
+ /** The shares of rooms with 0, 1 and 2 steps in their edges: under 0.3 H wide, 0.3 to 0.5 H, over 0.5 H. */
+ public final double[][] stepsByWidth;
+
+ Plan(long seed, float splitAboveH2, float stopBelowH2, float minSideH, float maxAspect, float roomAspect,
+ float windmillOdds, float windmillMinH2, float clockwiseShare) {
+ this.kind = Kind.TREE;
+ this.seed = seed;
+ this.splitAboveH2 = splitAboveH2;
+ this.stopBelowH2 = stopBelowH2;
+ this.minSideH = minSideH;
+ this.maxAspect = maxAspect;
+ this.roomAspect = roomAspect;
+ this.windmillOdds = windmillOdds;
+ this.windmillMinH2 = windmillMinH2;
+ this.clockwiseShare = clockwiseShare;
+ this.unitH = 0f;
+ this.tileWUnits = 0;
+ this.tileHUnits = 0;
+ this.minCrossH = 0f;
+ this.minStepUnits = 0;
+ this.minCellUnits = 0;
+ this.roomsPerH2 = 0;
+ this.courseUnits = 0;
+ this.straightEveryH = 0;
+ this.stepsByWidth = new double[0][];
+ }
+
+ Plan(long seed, float unitH, int tileWUnits, int tileHUnits, float minCrossH, int minStepUnits,
+ int minCellUnits, double roomsPerH2, double courseUnits, double straightEveryH, double[][] stepsByWidth) {
+ this.kind = Kind.TILE;
+ this.seed = seed;
+ this.splitAboveH2 = 0f;
+ this.stopBelowH2 = 0f;
+ this.minSideH = 0f;
+ this.maxAspect = 0f;
+ this.roomAspect = 0f;
+ this.windmillOdds = 0f;
+ this.windmillMinH2 = 0f;
+ this.clockwiseShare = 0f;
+ this.unitH = unitH;
+ this.tileWUnits = tileWUnits;
+ this.tileHUnits = tileHUnits;
+ this.minCrossH = minCrossH;
+ this.minStepUnits = minStepUnits;
+ this.minCellUnits = minCellUnits;
+ this.roomsPerH2 = roomsPerH2;
+ this.courseUnits = courseUnits;
+ this.straightEveryH = straightEveryH;
+ this.stepsByWidth = stepsByWidth;
+ }
+
+ /** This TILE plan with another seed and tile size, for tests and tools. */
+ Plan withTile(long seed, int tileWUnits, int tileHUnits) {
+ return new Plan(seed, unitH, tileWUnits, tileHUnits, minCrossH, minStepUnits, minCellUnits, roomsPerH2,
+ courseUnits, straightEveryH, stepsByWidth);
+ }
+ }
+
+ // ---------------------------------------------------------------------------------------- rhythm
+
+ /**
+ * When Nagaya's walls move: in slots. Slot k starts at {@code k * slotSeconds} plus a jitter of up to
+ * {@code jitterSeconds} either way. In a slot each moving wall starts up to {@code staggerSeconds} after the
+ * slot does and glides for {@code glideMinSeconds} to {@code glideSeconds}, each its own; then all rest until
+ * the next slot. {@code staggerSeconds + glideSeconds} fits in the shortest slot, so a slot's glides are over
+ * before the next one starts. Every {@code checkpointSeconds} of the wall clock all walls are home; the last
+ * {@code homeSlots} slots before it lead them there, and the very last takes them all home together.
+ */
+ public static final class Rhythm {
+ static final Rhythm NAGAYA = new Rhythm(7.0, 1.0, 2.4, 3.2, 1.8, 600.0, 3);
+
+ public final double slotSeconds, jitterSeconds, glideMinSeconds, glideSeconds, staggerSeconds, checkpointSeconds;
+ public final int homeSlots;
+
+ Rhythm(double slotSeconds, double jitterSeconds, double glideMinSeconds, double glideSeconds,
+ double staggerSeconds, double checkpointSeconds, int homeSlots) {
+ this.slotSeconds = slotSeconds;
+ this.jitterSeconds = jitterSeconds;
+ this.glideMinSeconds = glideMinSeconds;
+ this.glideSeconds = glideSeconds;
+ this.staggerSeconds = staggerSeconds;
+ this.checkpointSeconds = checkpointSeconds;
+ this.homeSlots = homeSlots;
+ }
+ }
+
+ // ---------------------------------------------------------------------------------------- motion
+
+ /**
+ * Which of Nagaya's walls move in a slot, and how far. With {@code quietShare} a slot moves nothing (never one
+ * that leads home). Otherwise lines are picked in a shuffled order until the slot's share of the wall length
+ * moves: {@code moveShare / (1 - quietShare)} times 1 give or take {@code shareSpread}, picked per slot, so over
+ * all slots {@code moveShare} moves on average. Each aims at home plus 1 to {@code maxUnits} steps to one side
+ * and goes as far toward it as the rooms around it allow. It turns back from its last side with
+ * {@code reverseShare}, else a coin picks the side. With {@code alignShare} it instead lines up with a nearby
+ * parallel line. No cell's width or height and no room's width ever gets below {@code keepShare} of its size at
+ * home.
+ */
+ public static final class Motion {
+ static final Motion NAGAYA = new Motion(0.25f, 13, 0.56f, 0.20f, 0.5f, 0.15f, 0.7f);
+
+ public final float moveShare;
+ public final int maxUnits;
+ public final float reverseShare;
+ public final float alignShare;
+ public final float shareSpread;
+ public final float quietShare;
+ public final float keepShare;
+
+ Motion(float moveShare, int maxUnits, float reverseShare, float alignShare, float shareSpread, float quietShare,
+ float keepShare) {
+ this.moveShare = moveShare;
+ this.maxUnits = maxUnits;
+ this.reverseShare = reverseShare;
+ this.alignShare = alignShare;
+ this.shareSpread = shareSpread;
+ this.quietShare = quietShare;
+ this.keepShare = keepShare;
+ }
+ }
+
+ // --------------------------------------------------------------------------------------- palette
+
+ /** Room paints and the colours of everything drawn on top of the rooms. ARGB. */
+ public static final class Palette {
+ /** How paints go to rooms. APART: rooms that ever touch never share a paint. SHUFFLE: in any order. */
+ public enum Deal { APART, SHUFFLE }
+
+ /** Olive: 22 paints, dark to light, as they look in the middle of the screen, before the lens's colour ramp. */
+ static final Palette OLIVE = new Palette(
+ new int[] {
+ 0xFF1F120C, 0xFF1B1D0F, 0xFF251E16, 0xFF2F2913, 0xFF344234, 0xFF645535,
+ 0xFFA03E1C, 0xFF577048, 0xFF776924, 0xFF6F7420, 0xFF82723D, 0xFF97804A,
+ 0xFF669469, 0xFF909156, 0xFFA29240, 0xFF8D987B, 0xFFBA9535, 0xFFC39449,
+ 0xFFB3A66C, 0xFFBDB65E, 0xFFCABA82, 0xFFF4ECCA},
+ new int[] {
+ 3, 5, 5, 5, 2, 4,
+ 1, 4, 2, 3, 4, 3,
+ 1, 4, 2, 2, 3, 2,
+ 3, 2, 2, 2},
+ 0xFFC4BF74, 0xFF6E9F86, 0xFFAEB099, 0xFF040404, 0xFF1B1D0F, Deal.APART);
+
+ /** Ember: 23 warm and olive paints, as they look in the middle of the screen, before the wash. */
+ static final Palette EMBER = new Palette(
+ new int[] {
+ 0xFF100E08, 0xFF1A0D08, 0xFF262516, 0xFF4B1703, 0xFF34291A, 0xFF542407,
+ 0xFF680B05, 0xFF2A3B21, 0xFF463C26, 0xFF6F380F, 0xFFA21504, 0xFF675115,
+ 0xFF734D24, 0xFF8B4925, 0xFFC01B04, 0xFF845A31, 0xFF94572A, 0xFF317B34,
+ 0xFF2E863C, 0xFFA78437, 0xFFC58030, 0xFFDA8417, 0xFFCF9611},
+ new int[] {
+ 1, 7, 5, 1, 2, 8,
+ 5, 2, 1, 1, 2, 1,
+ 3, 1, 2, 1, 1, 4,
+ 1, 2, 5, 6, 2},
+ 0xFFE1B03C, 0xFFE1B03C, 0xFFE1B03C, 0xFF040103, 0xFF1A0D08, Deal.SHUFFLE);
+
+ /** The room paints. {@link Frame#roomColor} holds an index into this. */
+ public final int[] deck;
+ /**
+ * How often each paint of {@link #deck} comes up: its cards in a deck of 64, one card per room.
+ * {@link RoomColours} deals in proportion for other room counts.
+ */
+ public final int[] cards;
+ /** Door bar and swing. */
+ public final int door;
+ /** Toilet and tub. */
+ public final int fixture;
+ public final int stairs;
+ /** Outlines of doors and fixtures. */
+ public final int line;
+ /** Shown only if the plan cannot draw. */
+ public final int floor;
+ public final Deal deal;
+
+ Palette(int[] deck, int[] cards, int door, int fixture, int stairs, int line, int floor, Deal deal) {
+ this.deck = deck;
+ this.cards = cards;
+ this.door = door;
+ this.fixture = fixture;
+ this.stairs = stairs;
+ this.line = line;
+ this.floor = floor;
+ this.deal = deal;
+ }
+ }
+
+ // ----------------------------------------------------------------------------------------- walls
+
+ public static final class Walls {
+ /** 0.0094 H on screen at the middle zoom (1.075): 10.2 px at 1080p. Near-black. */
+ static final Walls YOJOHAN = new Walls(0.0094f / 1.075f, 0xFF040404);
+ /** 0.0097 H at zoom 1: 10.5 px at 1080p. */
+ static final Walls NAGAYA = new Walls(0.0097f, 0xFF040103);
+
+ public final float widthH;
+ public final int color;
+
+ Walls(float widthH, int color) {
+ this.widthH = widthH;
+ this.color = color;
+ }
+ }
+
+ // ---------------------------------------------------------------------------------------- camera
+
+ /**
+ * Yojōhan's camera keeps one tilt; its pan and zoom are in {@link io.github.pbanddev.tatami.Camera}.
+ *
+ * <p>Nagaya's rolls between {@code rollFromDeg} and {@code rollToDeg} (ramps of {@code rollRampSeconds}, sine
+ * eased, with {@code rollHoldSeconds} holds between), zooms between {@code zoomFrom} and {@code zoomTo}
+ * (eased ramps of {@code zoomRampSeconds}, each starting halfway through a roll ramp), and drifts
+ * {@code driftH} a second toward {@code driftHeadingDeg} on screen at the middle roll (0 right, 90 down; a fixed
+ * heading in plan axes, so it turns with the roll), plus a slow wander of
+ * up to {@code wanderH} a second and {@code wanderDeg} of heading over about {@code wanderSeconds}.
+ * With the camera switch off it holds {@code angleDeg} and {@code restZoom} and does not drift.
+ */
+ public static final class Camera {
+ static final Camera YOJOHAN = new Camera(11f);
+ /** A 26 s glide over 8 degrees peaks at 0.48 degrees a second. */
+ static final Camera NAGAYA = new Camera(-20f, -16f, -24f, 40f, 26f, 1f, 0.78f, 20f, 0.89f,
+ 0.04f, 111.6f, 0.01f, 8f, 30f);
+
+ /** The plan's tilt on screen, in degrees. Positive: walls fall to the right (y points down). */
+ public final float angleDeg;
+ public final float rollFromDeg, rollToDeg, rollHoldSeconds, rollRampSeconds;
+ public final float zoomFrom, zoomTo, zoomRampSeconds, restZoom;
+ public final float driftH, driftHeadingDeg, wanderH, wanderDeg, wanderSeconds;
+
+ Camera(float angleDeg) {
+ this(angleDeg, 0f, 0f, 0f, 0f, 1f, 1f, 0f, 1f, 0f, 0f, 0f, 0f, 0f);
+ }
+
+ Camera(float angleDeg, float rollFromDeg, float rollToDeg, float rollHoldSeconds, float rollRampSeconds,
+ float zoomFrom, float zoomTo, float zoomRampSeconds, float restZoom,
+ float driftH, float driftHeadingDeg, float wanderH, float wanderDeg, float wanderSeconds) {
+ this.angleDeg = angleDeg;
+ this.rollFromDeg = rollFromDeg;
+ this.rollToDeg = rollToDeg;
+ this.rollHoldSeconds = rollHoldSeconds;
+ this.rollRampSeconds = rollRampSeconds;
+ this.zoomFrom = zoomFrom;
+ this.zoomTo = zoomTo;
+ this.zoomRampSeconds = zoomRampSeconds;
+ this.restZoom = restZoom;
+ this.driftH = driftH;
+ this.driftHeadingDeg = driftHeadingDeg;
+ this.wanderH = wanderH;
+ this.wanderDeg = wanderDeg;
+ this.wanderSeconds = wanderSeconds;
+ }
+ }
+
+ // ----------------------------------------------------------------------------------------- doors
+
+ /**
+ * Doors: a pale bar in the wall, always drawn, and a swing that opens into one room. Yojōhan's sizes are given
+ * on screen at the camera's middle zoom, 1.075, so each one is divided by it; Nagaya's at zoom 1.
+ */
+ public static final class Doors {
+ /** WAVES: each door on a clipped sine of its own phase. TRACK: all doors on one shared opening. */
+ public enum Timing { WAVES, TRACK }
+
+ static final Doors YOJOHAN = new Doors(0.8f, 0.28f, 0.73f, 0.017f / 1.075f,
+ 0.0361f / 1.075f, 0.00315f / 1.075f, 0.0364f / 1.075f, 0.0020f / 1.075f,
+ 45f, 56f, 90f, 1.6f);
+ static final Doors NAGAYA = new Doors(Timing.TRACK, 0.28f, 0.18f, 0.74f, 0.017f,
+ 0.0302f, 0.00245f, 0.0323f, 0.0020f, 0f, 0f, 100f, 0f, 0.78f, 1.7f,
+ new Track(13.0, 1.2, 4.1, 0.9, 1.4, 2.0));
+
+ public final Timing timing;
+ /**
+ * Yojōhan: the share of walls that get a door, tuned so about 0.6 doors per room show on screen
+ * ({@code tools/shot.sh --stats}). Nagaya: the share of touching room pairs that get one.
+ */
+ public final float chance;
+ /** Where along its wall a door wants its middle, as a share of the wall: each wall draws one in this range. */
+ public final float nearAt, farAt;
+ /** The least gap between a bar's end and its wall's ends. */
+ public final float joinGapH;
+ /** The bar in the wall: its length from the hinge, and half its thickness. */
+ public final float lengthH, barHalfH;
+ /** The swing, from the hinge to the middle of its arc's stroke. */
+ public final float radiusH;
+ /** The arc and the leaf. */
+ public final float lineH;
+ /** The opening, in degrees: clamp(middle + amplitude * sin(speed * t + phase), 0, max). TRACK uses max only. */
+ public final float swingMiddleDeg, swingAmplitudeDeg, swingMaxDeg;
+ /** Each door's phase is one shared phase plus up to this much either way, in radians. 0: all in step. */
+ public final float phaseSpread;
+ /** TRACK: the share of doors that swing up (on horizontal walls) or right (on vertical ones). */
+ public final float swingBias;
+ /** TRACK: a wall piece hosts a door only if it is at least this many bar lengths long. */
+ public final float hostBars;
+ /** TRACK: when the doors swing. {@link Track#NONE} for WAVES. */
+ public final Track track;
+
+ Doors(float chance, float nearAt, float farAt, float joinGapH, float lengthH, float barHalfH, float radiusH,
+ float lineH, float swingMiddleDeg, float swingAmplitudeDeg, float swingMaxDeg, float phaseSpread) {
+ this(Timing.WAVES, chance, nearAt, farAt, joinGapH, lengthH, barHalfH, radiusH, lineH,
+ swingMiddleDeg, swingAmplitudeDeg, swingMaxDeg, phaseSpread, 0f, 0f, Track.NONE);
+ }
+
+ Doors(Timing timing, float chance, float nearAt, float farAt, float joinGapH, float lengthH, float barHalfH,
+ float radiusH, float lineH, float swingMiddleDeg, float swingAmplitudeDeg, float swingMaxDeg,
+ float phaseSpread, float swingBias, float hostBars, Track track) {
+ this.timing = timing;
+ this.chance = chance;
+ this.nearAt = nearAt;
+ this.farAt = farAt;
+ this.joinGapH = joinGapH;
+ this.lengthH = lengthH;
+ this.barHalfH = barHalfH;
+ this.radiusH = radiusH;
+ this.lineH = lineH;
+ this.swingMiddleDeg = swingMiddleDeg;
+ this.swingAmplitudeDeg = swingAmplitudeDeg;
+ this.swingMaxDeg = swingMaxDeg;
+ this.phaseSpread = phaseSpread;
+ this.swingBias = swingBias;
+ this.hostBars = hostBars;
+ this.track = track;
+ }
+
+ /**
+ * One opening for every door, on a clock of its own, apart from the walls': cycle c starts at
+ * {@code c * cycleSeconds} plus up to {@code cycleJitterSeconds} either way. In a cycle the doors swing open
+ * over {@code swingSeconds}, stay open {@code openSeconds} plus up to {@code openSpreadSeconds} more, swing
+ * shut, then rest shut until the next cycle. Each door runs its own fixed delay of up to
+ * {@code rippleSeconds} behind that opening, so they swing in a ripple, not all at once.
+ */
+ public static final class Track {
+ static final Track NONE = new Track(0, 0, 0, 0, 0, 0);
+
+ public final double cycleSeconds, cycleJitterSeconds, swingSeconds, openSeconds, openSpreadSeconds,
+ rippleSeconds;
+
+ Track(double cycleSeconds, double cycleJitterSeconds, double swingSeconds, double openSeconds,
+ double openSpreadSeconds, double rippleSeconds) {
+ this.cycleSeconds = cycleSeconds;
+ this.cycleJitterSeconds = cycleJitterSeconds;
+ this.swingSeconds = swingSeconds;
+ this.openSeconds = openSeconds;
+ this.openSpreadSeconds = openSpreadSeconds;
+ this.rippleSeconds = rippleSeconds;
+ }
+ }
+ }
+
+ // -------------------------------------------------------------------------------------- fixtures
+
+ /**
+ * Toilets, tubs and stairs. Their shapes and sizes are in {@link FixtureShapes}. Those sizes and the ones
+ * below are in units of {@link #unitH}, so they never change with the room.
+ */
+ public static final class Fixtures {
+ static final Fixtures YOJOHAN = new Fixtures(1f / (1080f * 1.075f), 2.2f, 0.18f,
+ new float[] {0.17f, 0.5f, 0.33f}, 31f, 28.5f, 20f);
+ /** Nagaya has none. */
+ static final Fixtures NAGAYA = new Fixtures(1f / 1080f, 2.2f, 0f,
+ new float[] {0.17f, 0.5f, 0.33f}, 31f, 28.5f, 20f);
+
+ /** One unit: 1 px at 1080p on screen at the camera's middle zoom (1.075), as a share of the screen height. */
+ public final float unitH;
+ /** The outline of the toilet and the tub. */
+ public final float line;
+ /** The share of rooms that hold a fixture. 0 for none. */
+ public final float share;
+ /** How often each kind shows up, by kind: tub, toilet, stairs ({@code Fixtures.TUB} and so on). */
+ public final float[] weights;
+ /** From the toilet's back to the face of the wall it backs onto. */
+ public final float toiletGap;
+ /** From the tub to the faces of the 2 walls of its corner. */
+ public final float tubGap;
+ /** Floor to leave between a fixture's open sides and the walls they face, in rooms that allow it. */
+ public final float clearance;
+
+ Fixtures(float unitH, float line, float share, float[] weights, float toiletGap, float tubGap, float clearance) {
+ this.unitH = unitH;
+ this.line = line;
+ this.share = share;
+ this.weights = weights;
+ this.toiletGap = toiletGap;
+ this.tubGap = tubGap;
+ this.clearance = clearance;
+ }
+ }
+
+ // ------------------------------------------------------------------------------------------ post
+
+ /**
+ * The lens: what the GPU does to the drawn plan, all of it fixed to the screen. A screen position p is
+ * measured from the screen centre in half screen heights, x to the right and y up. Colours stay
+ * gamma-encoded (0 to 1, as drawn), and so do the blur and the blend.
+ *
+ * <p>Yojōhan reads its vignette and colour ramp from the lens map. Nagaya instead washes its room and door
+ * fills on the CPU ({@link #wash}, {@link Wash}), so its walls stay flat black.
+ */
+ public static final class Post {
+ static final Post YOJOHAN = new Post(
+ new Oval(-0.071f, 0.054f, 0.574f, 0.206f, 1.64f), 0.42f,
+ new float[] {0.045f, 0f, -0.05f}, new float[] {0f, 0f, 0.03f},
+ 1.3f, 1.75f, 23.976,
+ new Oval(0.030f, 0f, 0.611f, 0.837f, 1.157f), 4,
+ new float[] {0.2719f, 0.3235f, 0.0406f}, new float[] {0f, 1.3333f, 3.1650f});
+ /** Grain at 2/3 strength, as Yojōhan's; the blur is Yojōhan's. */
+ static final Post NAGAYA = new Post(
+ YOJOHAN.vignetteOval, 0f, new float[] {0f, 0f, 0f}, new float[] {0f, 0f, 0f},
+ 1.4f * 2f / 3f, 0f, 23.976,
+ YOJOHAN.blurOval, YOJOHAN.blurDivisor, YOJOHAN.blurWeights, YOJOHAN.blurOffsets,
+ 2.35f * 2f / 3f, 0.25f, 0.30f, true, 0.07f);
+
+ /** Where the vignette darkens: k = 0 inside the oval, 1 outside it. */
+ public final Oval vignetteOval;
+ /** Gain {@code 1 - vignette * k^3}: edge middles ~0.90-0.94, corners ~0.6-0.78. */
+ public final float vignette;
+ /**
+ * The colour ramp: r, g and b times {@code exp(tintX * p.x + tintY * p.y)}, bluer to the left and
+ * warmer to the right. The vignette switch turns it off too.
+ */
+ public final float[] tintX, tintY;
+ /**
+ * Grain std in 8-bit levels: {@code grainBase + grainSlope * luma^2 + grainStep * smoothstep(grainStepFrom,
+ * grainStepTo, luma)}, luma 0 to 1. A term that is 0 is left out of the shader.
+ */
+ public final float grainBase, grainSlope, grainStep, grainStepFrom, grainStepTo;
+ /** A new grain pattern this many times a second: film's frame rate. */
+ public final double grainFps;
+ /** Where the blurred copy shows: its weight is 0 inside the oval, 1 outside it. */
+ public final Oval blurOval;
+ /** The blurred copy is this many times smaller than the screen. */
+ public final int blurDivisor;
+ /**
+ * One separable Gaussian round on the small copy: {@code blurWeights[i]} at {@code +-blurOffsets[i]}
+ * of its texels (each tap between 2 texels, read bilinear). Sigma ~6 px at 1080p, 0.0056 H.
+ */
+ public final float[] blurWeights, blurOffsets;
+ /** True: room and door fills take the screen's colour {@link Wash} on the CPU, in place of the lens map. */
+ public final boolean wash;
+ /** The wash is worked out at the corners of pieces at most this big each way, so it stays smooth. */
+ public final float washPieceH;
+
+ Post(Oval vignetteOval, float vignette, float[] tintX, float[] tintY,
+ float grainBase, float grainSlope, double grainFps,
+ Oval blurOval, int blurDivisor, float[] blurWeights, float[] blurOffsets) {
+ this(vignetteOval, vignette, tintX, tintY, grainBase, grainSlope, grainFps, blurOval, blurDivisor,
+ blurWeights, blurOffsets, 0f, 0f, 0f, false, 0f);
+ }
+
+ Post(Oval vignetteOval, float vignette, float[] tintX, float[] tintY,
+ float grainBase, float grainSlope, double grainFps,
+ Oval blurOval, int blurDivisor, float[] blurWeights, float[] blurOffsets,
+ float grainStep, float grainStepFrom, float grainStepTo, boolean wash, float washPieceH) {
+ this.vignetteOval = vignetteOval;
+ this.vignette = vignette;
+ this.tintX = tintX;
+ this.tintY = tintY;
+ this.grainBase = grainBase;
+ this.grainSlope = grainSlope;
+ this.grainFps = grainFps;
+ this.blurOval = blurOval;
+ this.blurDivisor = blurDivisor;
+ this.blurWeights = blurWeights;
+ this.blurOffsets = blurOffsets;
+ this.grainStep = grainStep;
+ this.grainStepFrom = grainStepFrom;
+ this.grainStepTo = grainStepTo;
+ this.wash = wash;
+ this.washPieceH = washPieceH;
+ }
+
+ /** {@code smoothstep(inner, outer, length(vec2((p.x - x) * scaleX, p.y - y)))}: 0 in the middle, 1 out. */
+ public static final class Oval {
+ public final float x, y, scaleX, inner, outer;
+
+ Oval(float x, float y, float scaleX, float inner, float outer) {
+ this.x = x;
+ this.y = y;
+ this.scaleX = scaleX;
+ this.inner = inner;
+ this.outer = outer;
+ }
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/LookSchedule.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/LookSchedule.java
new file mode 100644
index 000000000..6de060fd4
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/LookSchedule.java
@@ -0,0 +1,115 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * Which look the plan shows at a moment, and how bright: the Look setting ({@link Mode}), the swap period, the wall
+ * clock, when Nagaya became ready and when this view started decide, so every view of the plan agrees once it has
+ * settled. Pure Java; {@link #at} fills {@link #look} and {@link #fade} without allocating.
+ *
+ * <p>Nagaya is the look the plan leads with; Yojōhan is built at once and stands in whenever Nagaya is not there.
+ * {@link Mode#BOTH}: period n = floor(t / swapSeconds) shows Nagaya when n is even and Yojōhan when n is odd. A swap
+ * dips to dark: the picture fades out over the {@link #DIP_SECONDS} before the period starts and back in over the
+ * {@link #DIP_SECONDS} after; the look changes at the start, in the dark. A swap between 2 periods that show the same
+ * look has no dip.
+ *
+ * <p>Nagaya builds in the background when a view first asks for it. If a view starts while Nagaya is wanted and not
+ * ready, the picture stays dark for up to {@link #WAIT_SECONDS} and fades Nagaya in as soon as it is ready. Later
+ * than that, Yojōhan fades in instead, and Nagaya takes over with a dip once ready (in Both, only in its own periods).
+ */
+public final class LookSchedule {
+
+ /** The Look setting, in the order OK steps through them. {@link #key} is its stored name. */
+ public enum Mode {
+ NAGAYA("nagaya"), YOJOHAN("yojohan"), BOTH("both");
+
+ public final String key;
+
+ Mode(String key) {
+ this.key = key;
+ }
+
+ /** The mode stored as {@code key}, or null for any other value. */
+ public static Mode of(String key) {
+ for (Mode mode : values()) {
+ if (mode.key.equals(key)) return mode;
+ }
+ return null;
+ }
+
+ /** The mode after this one, as OK steps through them in the settings. */
+ public Mode next() {
+ Mode[] all = values();
+ return all[(ordinal() + 1) % all.length];
+ }
+ }
+
+ /** A swap fades out over this many seconds and back in over as many. */
+ public static final double DIP_SECONDS = 1.2;
+ /** The longest a starting view waits in the dark for Nagaya before Yojōhan fades in. */
+ public static final double WAIT_SECONDS = 2.0;
+
+ /** The look to draw. */
+ public Look look = Look.YOJOHAN;
+ /** How bright: 1 as drawn, 0 black. */
+ public float fade = 1f;
+
+ /**
+ * Picks the look and the fade for wall-clock time {@code t} (seconds).
+ *
+ * @param readySince when Nagaya became ready to draw, on the same clock; positive infinity while it is not
+ * (not built yet, or failed)
+ * @param startedAt when this view drew its first frame, on the same clock
+ */
+ public void at(double t, Mode mode, double swapSeconds, double readySince, double startedAt) {
+ look = Look.YOJOHAN;
+ fade = 1f;
+ if (mode == Mode.YOJOHAN) return;
+ long n = (long) Math.floor(t / swapSeconds);
+ boolean now = nagaya(t, n, mode, readySince, startedAt);
+ if (now) look = Look.NAGAYA;
+ // a view that starts while Nagaya is wanted and not ready: dark, then whichever look comes first fades in
+ if (readySince > startedAt && wanted(nOf(startedAt, swapSeconds), mode)) {
+ double settle = Math.min(readySince, startedAt + WAIT_SECONDS);
+ if (t < settle) {
+ fade = 0f;
+ return;
+ }
+ fade = Math.min(fade, dip(t - settle));
+ }
+ // a Nagaya that is ready too late for the start takes over with a dip, in a period that wants it
+ double over = readySince + DIP_SECONDS;
+ if (readySince > startedAt + WAIT_SECONDS && over < Double.POSITIVE_INFINITY
+ && wanted((long) Math.floor(over / swapSeconds), mode)) {
+ fade = Math.min(fade, dip(Math.abs(t - over)));
+ }
+ if (mode == Mode.BOTH) {
+ double start = n * swapSeconds, end = start + swapSeconds;
+ if (now != nagaya(start, n - 1, mode, readySince, startedAt)) fade = Math.min(fade, dip(t - start));
+ if (now != nagaya(end, n + 1, mode, readySince, startedAt)) fade = Math.min(fade, dip(end - t));
+ }
+ }
+
+ private static long nOf(double t, double swapSeconds) {
+ return (long) Math.floor(t / swapSeconds);
+ }
+
+ /** True when period n wants Nagaya: always in {@link Mode#NAGAYA}, even periods in {@link Mode#BOTH}. */
+ private static boolean wanted(long n, Mode mode) {
+ return mode == Mode.NAGAYA || (mode == Mode.BOTH && Math.floorMod(n, 2) == 0);
+ }
+
+ /**
+ * True when Nagaya shows (fade aside) at time t, counted in period n: it is wanted, and ready by then, or, when it
+ * was ready too late for the view's start, a dip after that.
+ */
+ private static boolean nagaya(double t, long n, Mode mode, double readySince, double startedAt) {
+ if (!wanted(n, mode)) return false;
+ return readySince <= startedAt + WAIT_SECONDS ? t >= readySince : t >= readySince + DIP_SECONDS;
+ }
+
+ /** The brightness {@code seconds} away from a swap: 0 at it, 1 from {@link #DIP_SECONDS} on, eased at both ends. */
+ private static float dip(double seconds) {
+ if (seconds >= DIP_SECONDS) return 1f;
+ if (seconds <= 0) return 0f;
+ return (float) ((1 - Math.cos(Math.PI * seconds / DIP_SECONDS)) / 2);
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/MoveClock.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/MoveClock.java
new file mode 100644
index 000000000..52a03ece8
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/MoveClock.java
@@ -0,0 +1,88 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * Nagaya's shared rhythm, from the wall clock and the seed alone ({@link Look.Rhythm}). Slot k starts at
+ * {@code k * slotSeconds} plus a jitter in [-jitterSeconds, jitterSeconds] hashed from k. In each slot each moving
+ * group of walls starts its glide {@link #delay} after the slot does and glides for {@link #glide}, both hashed from
+ * the slot and the group; then everything rests until the next slot starts. Every {@link #slotsPerCheckpoint} slots
+ * is a checkpoint, when every wall is home; a checkpoint slot's jitter is never negative, so it starts at or after
+ * its checkpoint's time. The last slot before it takes every group home together: no delay, the longest glide.
+ *
+ * <p>Slot numbers are longs worked out from the double clock; the clock itself never goes into a float.
+ */
+final class MoveClock {
+ private static final int DELAY = 1, GLIDE = 2;
+
+ final double slotSeconds, jitterSeconds, glideMinSeconds, glideSeconds, staggerSeconds;
+ final int slotsPerCheckpoint;
+ private final long seed;
+
+ MoveClock(Look.Rhythm rhythm, long seed) {
+ slotSeconds = rhythm.slotSeconds;
+ jitterSeconds = rhythm.jitterSeconds;
+ glideMinSeconds = rhythm.glideMinSeconds;
+ glideSeconds = rhythm.glideSeconds;
+ staggerSeconds = rhythm.staggerSeconds;
+ slotsPerCheckpoint = (int) Math.round(rhythm.checkpointSeconds / rhythm.slotSeconds);
+ this.seed = seed;
+ if (!(slotSeconds > 0 && jitterSeconds >= 0 && glideMinSeconds > 0 && glideMinSeconds <= glideSeconds
+ && staggerSeconds >= 0 && staggerSeconds + glideSeconds <= slotSeconds - 2 * jitterSeconds
+ && slotsPerCheckpoint >= 2)) {
+ throw new IllegalArgumentException("glides would overlap: slot " + slotSeconds + " s, jitter "
+ + jitterSeconds + " s, glide " + glideMinSeconds + " to " + glideSeconds + " s, stagger "
+ + staggerSeconds + " s, " + slotsPerCheckpoint + " slots per checkpoint");
+ }
+ }
+
+ /** When slot k starts, in seconds of the wall clock. */
+ double start(long k) {
+ double j = jitterSeconds * (2 * unit(hash(seed, k, 0, 0)) - 1);
+ if (Math.floorMod(k, slotsPerCheckpoint) == 0) j = Math.abs(j);
+ return k * slotSeconds + j;
+ }
+
+ /** The last slot that has started by time t. */
+ long slot(double t) {
+ long k = (long) Math.floor(t / slotSeconds);
+ if (start(k + 1) <= t) return k + 1;
+ return start(k) <= t ? k : k - 1;
+ }
+
+ /** The checkpoint slot at or before slot k. */
+ long checkpoint(long k) {
+ return Math.floorDiv(k, slotsPerCheckpoint) * slotsPerCheckpoint;
+ }
+
+ /** True for the last slot before a checkpoint, which takes every group home together. */
+ boolean homeTogether(long k) {
+ return Math.floorMod(k, slotsPerCheckpoint) == slotsPerCheckpoint - 1;
+ }
+
+ /** How long after slot k starts group g's glide starts, in [0, staggerSeconds]. */
+ double delay(long k, int g) {
+ return homeTogether(k) ? 0 : staggerSeconds * unit(hash(seed, k, g, DELAY));
+ }
+
+ /** How long group g's glide in slot k lasts, in [glideMinSeconds, glideSeconds]. */
+ double glide(long k, int g) {
+ return homeTogether(k) ? glideSeconds : glideMinSeconds + (glideSeconds - glideMinSeconds) * unit(hash(seed, k, g, GLIDE));
+ }
+
+ /** 64 well-mixed bits from a seed and 3 numbers (SplitMix64's mixer, chained). */
+ static long hash(long seed, long a, long b, long c) {
+ long z = mix(seed * 0x9E3779B97F4A7C15L + a);
+ z = mix(z + b * 0xD1B54A32D192ED03L);
+ return mix(z + c * 0x8CB92BA72F3D8DD7L);
+ }
+
+ /** A hash as a number in [0, 1). */
+ static double unit(long hash) {
+ return (hash >>> 11) * 0x1.0p-53;
+ }
+
+ private static long mix(long z) {
+ z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L;
+ z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL;
+ return z ^ (z >>> 31);
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/NagayaCamera.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/NagayaCamera.java
new file mode 100644
index 000000000..98d894789
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/NagayaCamera.java
@@ -0,0 +1,102 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * Nagaya's camera ({@link Look.Camera}): a closed form in the wall clock, with no state, so Home, the screensaver
+ * and the settings show the same view at the same time. It pivots on the screen's centre.
+ *
+ * <p>One cycle: the roll holds at {@code rollFromDeg}, glides to {@code rollToDeg} ({@link Ease#glide}), holds, and
+ * glides back. The zoom glides the same way from {@code zoomFrom} to {@code zoomTo} from halfway through the glide to
+ * {@code rollToDeg}, and back from halfway through the glide back, so the widest view comes with the steepest roll.
+ *
+ * <p>The plan drifts along one fixed heading in plan axes: the one that shows as {@code driftHeadingDeg} on screen
+ * at the middle roll, and turns with the roll by up to half its range either side. The wander adds a sine along
+ * that heading (the speed swings by {@code wanderH}) and one across it (the heading swings by about
+ * {@code wanderDeg}). The centre is the sum of their integrals, worked out in double and brought back to within a
+ * tile of 0 by whole lattice steps; every copy of the tile is the same, so the step never shows.
+ *
+ * <p>The clock never goes into a float: every phase is a remainder of the double clock.
+ */
+final class NagayaCamera implements CameraCurve {
+ /** The speed's wander takes this many times as long as the heading's, so the 2 rarely fall into step. */
+ private static final double SPEED_WANDER = 1.3;
+
+ private final Look.Camera camera;
+ private final float unitH, margin;
+ private final int tileW, tileH, shift;
+ private final double hold, ramp, cycle, zoomStart;
+ /** The way the plan moves on screen, in plan axes, and the way across it. */
+ private final double alongX, alongY;
+ /** The wander's periods (s) and its sizes in H: speed along and how far it carries, likewise across. */
+ private final double speedPeriod, speedReach, headPeriod, headReach;
+
+ NagayaCamera(Look look) {
+ camera = look.camera;
+ Look.Camera c = camera;
+ unitH = look.plan.unitH;
+ tileW = look.plan.tileWUnits;
+ tileH = look.plan.tileHUnits;
+ shift = tileW / 2;
+ margin = Scene.margin(look);
+ hold = c.rollHoldSeconds;
+ ramp = c.rollRampSeconds;
+ cycle = 2 * (hold + ramp);
+ zoomStart = hold + ramp / 2;
+ if (!(ramp > 0 && hold >= 0 && c.zoomRampSeconds > 0 && c.zoomRampSeconds <= hold + ramp
+ && c.wanderSeconds > 0 && tileW > 0 && tileH > 0 && unitH > 0)) {
+ throw new IllegalArgumentException("camera: roll ramp " + ramp + " s, hold " + hold + " s, zoom ramp "
+ + c.zoomRampSeconds + " s, wander " + c.wanderSeconds + " s");
+ }
+ double heading = Math.toRadians(c.driftHeadingDeg - (c.rollFromDeg + c.rollToDeg) / 2.0);
+ alongX = Math.cos(heading);
+ alongY = Math.sin(heading);
+ headPeriod = c.wanderSeconds;
+ speedPeriod = c.wanderSeconds * SPEED_WANDER;
+ speedReach = c.wanderH * speedPeriod / (2 * Math.PI);
+ headReach = c.driftH * Math.tan(Math.toRadians(c.wanderDeg)) * headPeriod / (2 * Math.PI);
+ }
+
+ @Override
+ public void at(double t, int w, int h, boolean moving, View view, float[] matrix) {
+ if (!moving) {
+ view.set(w, h, camera.angleDeg, camera.restZoom, 0.0, 0.0, margin);
+ } else {
+ double p = rem(t, cycle);
+ // how far the plan has moved on screen, in H, along its heading and across it
+ double along = camera.driftH * t - speedReach * Math.cos(2 * Math.PI * rem(t, speedPeriod) / speedPeriod);
+ double across = -headReach * Math.cos(2 * Math.PI * rem(t, headPeriod) / headPeriod);
+ // the camera moves the other way; plan units are px at zoom 1
+ double x = -h * (along * alongX - across * alongY), y = -h * (along * alongY + across * alongX);
+ // TilePlan's step, so the lattice here is the one it lays copies on
+ float unit = h * unitH;
+ double a1x = tileW * (double) unit, a2x = shift * (double) unit, a2y = tileH * (double) unit;
+ double j = Math.floor(y / a2y);
+ y -= j * a2y;
+ x -= j * a2x;
+ x -= Math.floor(x / a1x) * a1x;
+ view.set(w, h, (float) roll(p), (float) zoom(p), x, y, margin);
+ }
+ view.matrix(matrix);
+ }
+
+ /** The roll at p seconds into the cycle. */
+ private double roll(double p) {
+ double from = camera.rollFromDeg, to = camera.rollToDeg;
+ if (p < hold) return from;
+ if (p < hold + ramp) return from + (to - from) * Ease.glide((p - hold) / ramp);
+ if (p < 2 * hold + ramp) return to;
+ return to + (from - to) * Ease.glide((p - 2 * hold - ramp) / ramp);
+ }
+
+ /** The zoom at p seconds into the cycle: out from halfway through the first glide, back in half a cycle later. */
+ private double zoom(double p) {
+ double from = camera.zoomFrom, to = camera.zoomTo, q = rem(p - zoomStart, cycle), half = cycle / 2;
+ if (q < half) return from + (to - from) * Ease.glide(q / camera.zoomRampSeconds);
+ return to + (from - to) * Ease.glide((q - half) / camera.zoomRampSeconds);
+ }
+
+ /** t modulo a period, in [0, period). */
+ private static double rem(double t, double period) {
+ double r = t % period;
+ return r < 0 ? r + period : r;
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/NagayaDoors.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/NagayaDoors.java
new file mode 100644
index 000000000..e22042c83
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/NagayaDoors.java
@@ -0,0 +1,73 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * Nagaya's doors: one on every wall piece the plan flags as a host ({@link Frame#wallDoor}), so at most one per pair
+ * of rooms, open as far as the one {@link DoorTrack} says, each at its own small delay behind it.
+ *
+ * <p>Each piece draws from the seed and its {@link Frame#wallId}, the same in every copy of the tile and never
+ * changing: where along the piece the bar's middle sits (a share of the piece between {@link Look.Doors#nearAt} and
+ * {@link Look.Doors#farAt}), and which room the leaf swings into (up on a row wall, or right on a joint, with
+ * {@link Look.Doors#swingBias}). The swing side sets the hinge end, so every door opens clockwise, and the plan hosts
+ * doors only where that room stays deep enough for the swing ({@link TilePlan#doorHosts}). The bar keeps its share as
+ * the piece glides, a gap from the piece's ends (centred on a piece too short for that), so it rides its piece and
+ * never jumps.
+ *
+ * <p>It runs every frame: no allocation, one step per wall piece.
+ */
+final class NagayaDoors implements DoorPlacer {
+ private static final long STREAM = 0x646F6F72L;
+ // what each piece draws from the seed
+ private static final int AT = 1, SIDE = 2;
+
+ private final Look.Doors look;
+ private final long seed;
+ private final DoorTrack track;
+
+ NagayaDoors(Look look) {
+ this.look = look.doors;
+ seed = look.plan.seed;
+ track = new DoorTrack(look.doors, look.plan.seed);
+ }
+
+ /**
+ * The room the door on wall piece {@code piece} of the plan with this seed swings into: +1 toward +y (+x on a
+ * joint), -1 the other way; up on a row wall or right on a joint with share {@code bias}. The plan asks this too,
+ * when it picks hosts.
+ */
+ static int side(long seed, float bias, int piece, boolean vertical) {
+ boolean usual = MoveClock.unit(MoveClock.hash(seed ^ STREAM, piece, SIDE, 0)) < bias;
+ return vertical == usual ? 1 : -1;
+ }
+
+ @Override
+ public void place(Frame f, double t, View view) {
+ float length = view.h * look.lengthH, gap = view.h * look.joinGapH;
+ int count = 0;
+ for (int w = 0; w < f.wallCount; w++) {
+ if (!f.wallDoor[w]) continue;
+ if (count == f.doorWall.length) {
+ f.clipped = true;
+ break;
+ }
+ int id = f.wallId[w];
+ boolean vertical = f.wallVertical[w];
+ float from = vertical ? f.wallY0[w] : f.wallX0[w], to = vertical ? f.wallY1[w] : f.wallX1[w];
+ float at = look.nearAt + (look.farAt - look.nearAt) * (float) MoveClock.unit(MoveClock.hash(seed ^ STREAM, id, AT, 0));
+ // the bar's middle, kept a gap from the piece's ends; both limits meet in the middle on a short piece
+ float low = from + gap + length / 2, high = to - gap - length / 2;
+ float middle = low <= high ? Math.max(low, Math.min(high, from + at * (to - from))) : (from + to) / 2;
+ // clockwise turns the bar's way from the hinge (u) into the swing's (v), with y down
+ int side = side(seed, look.swingBias, id, vertical);
+ int along = vertical ? -side : side;
+ float hinge = middle - along * length / 2;
+ f.doorWall[count] = w;
+ f.doorAlong[count] = along;
+ f.doorSide[count] = side;
+ f.doorX[count] = vertical ? f.wallX0[w] : hinge;
+ f.doorY[count] = vertical ? hinge : f.wallY0[w];
+ f.doorOpening[count] = track.opening(t, id);
+ count++;
+ }
+ f.doorCount = count;
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/NagayaScene.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/NagayaScene.java
new file mode 100644
index 000000000..ab09234fb
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/NagayaScene.java
@@ -0,0 +1,62 @@
+package io.github.pbanddev.tatami;
+
+import android.os.Process;
+import android.os.SystemClock;
+import android.util.Log;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Nagaya's {@link Scene}, built once per process on a background thread the first time a view of the plan asks for
+ * it, then shared by every view in the process: Home, the screensaver and the settings. Building it takes many
+ * frames, so it never runs on the main thread or a GL thread, and the views do not each build their own.
+ *
+ * <p>A scene is filled in place for each frame, so a renderer holds the scene's lock while it builds a frame and
+ * copies the result out. Two views draw at once only for a moment, as the screensaver takes over from Home.
+ *
+ * <p>It builds through {@link Scenes#APP}: a build that fails marks Nagaya failed for the process, and
+ * {@link #scene} then stays null.
+ */
+final class NagayaScene {
+ private static final AtomicBoolean started = new AtomicBoolean();
+ private static volatile Scene scene;
+ /** The wall-clock time the scene was ready; written after {@link #scene}. */
+ private static volatile double readySince = Double.POSITIVE_INFINITY;
+
+ private NagayaScene() {}
+
+ /** Starts the build on the first call; later calls do nothing. Cheap enough to call every frame. */
+ static void request() {
+ if (started.compareAndSet(false, true)) new Thread(NagayaScene::build, "TatamiScene").start();
+ }
+
+ /** The built scene, or null while it builds, before {@link #request}, or once Nagaya has failed. */
+ static Scene scene() {
+ return Scenes.APP.usable(Look.NAGAYA) ? scene : null;
+ }
+
+ /** When {@link #scene} became ready, in wall-clock seconds; positive infinity until then and once it fails. */
+ static double readySince() {
+ return Scenes.APP.usable(Look.NAGAYA) ? readySince : Double.POSITIVE_INFINITY;
+ }
+
+ static void report(Throwable failure) {
+ Log.e("Tatami", "Nagaya cannot be drawn; Yojōhan shows instead", failure);
+ }
+
+ /** On its own thread. Nothing may escape it: an uncaught throw on any thread but a GL one ends the app. */
+ private static void build() {
+ try {
+ Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
+ long start = SystemClock.elapsedRealtime();
+ Scene built = Scenes.APP.make(Look.NAGAYA, NagayaScene::report);
+ if (built.look != Look.NAGAYA) return;
+ // one frame here catches the walls up from their last checkpoint, so the GL thread only steps forward
+ built.build(FloorPlanView.now(), 1920, 1080, true, true, true);
+ Log.i("Tatami", "Nagaya's scene built in " + (SystemClock.elapsedRealtime() - start) + " ms");
+ scene = built;
+ readySince = FloorPlanView.now();
+ } catch (Throwable failure) {
+ Scenes.APP.failed(Look.NAGAYA, failure, NagayaScene::report);
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/PlanGeometry.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/PlanGeometry.java
new file mode 100644
index 000000000..595d0d6ce
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/PlanGeometry.java
@@ -0,0 +1,82 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * Questions about the rooms of a laid-out {@link Frame}: which room holds a point, where two rooms meet,
+ * and which rooms are windmill centres. Linear scans: fine for setup, tests and tools, too slow to run for
+ * every room every frame.
+ */
+public final class PlanGeometry {
+ private PlanGeometry() {}
+
+ /**
+ * The room (its index) that holds the point, or -1 outside the plan. A point on a wall goes to the first room
+ * found. Reads the cells when the frame has them, else the rooms as boxes.
+ */
+ public static int roomAt(Frame f, float x, float y) {
+ if (f.cellCount > 0) {
+ for (int c = 0; c < f.cellCount; c++) {
+ if (x >= f.cellX[c] && x < f.cellX[c] + f.cellW[c] && y >= f.cellY[c] && y < f.cellY[c] + f.cellH[c]) {
+ return f.cellRoom[c];
+ }
+ }
+ return -1;
+ }
+ for (int i = 0; i < f.roomCount; i++) {
+ if (x >= f.roomX[i] && x < f.roomX[i] + f.roomW[i] && y >= f.roomY[i] && y < f.roomY[i] + f.roomH[i]) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * The length of the wall piece rooms i and j share, or 0 when they meet only at a corner or not at all.
+ * When it is longer than 0, {@code out} gets its ends: x0, y0, x1, y1. Sides closer than {@code eps} touch.
+ */
+ public static float sharedEdge(Frame f, int i, int j, float eps, float[] out) {
+ float ax0 = f.roomX[i], ay0 = f.roomY[i], ax1 = ax0 + f.roomW[i], ay1 = ay0 + f.roomH[i];
+ float bx0 = f.roomX[j], by0 = f.roomY[j], bx1 = bx0 + f.roomW[j], by1 = by0 + f.roomH[j];
+ boolean right = Math.abs(ax1 - bx0) <= eps, left = Math.abs(bx1 - ax0) <= eps;
+ if (right || left) {
+ float x = right ? ax1 : ax0, lo = Math.max(ay0, by0), hi = Math.min(ay1, by1);
+ if (hi - lo > eps) return edge(out, x, lo, x, hi);
+ }
+ boolean below = Math.abs(ay1 - by0) <= eps, above = Math.abs(by1 - ay0) <= eps;
+ if (below || above) {
+ float y = below ? ay1 : ay0, lo = Math.max(ax0, bx0), hi = Math.min(ax1, bx1);
+ if (hi - lo > eps) return edge(out, lo, y, hi, y);
+ }
+ return 0f;
+ }
+
+ private static float edge(float[] out, float x0, float y0, float x1, float y1) {
+ out[0] = x0;
+ out[1] = y0;
+ out[2] = x1;
+ out[3] = y1;
+ return (x1 - x0) + (y1 - y0);
+ }
+
+ /**
+ * True when room k is a windmill centre: 4 rooms wrap around it, so no straight wall runs through it.
+ * At each of its corners exactly one of its two sides runs on past the corner (a T join), and the sides
+ * that run on take turns around the room: horizontal, vertical, horizontal, vertical. Rooms on the plan's
+ * edge never count. {@code delta} is how far from a corner to look; keep it below the thinnest room.
+ */
+ public static boolean isWindmillCentre(Frame f, int k, float delta) {
+ float x0 = f.roomX[k], y0 = f.roomY[k], x1 = x0 + f.roomW[k], y1 = y0 + f.roomH[k];
+ // corners in turn round the room, each with the direction that points away from the room
+ float[][] corners = {{x0, y0, -1, -1}, {x1, y0, 1, -1}, {x1, y1, 1, 1}, {x0, y1, -1, 1}};
+ boolean[] horizontal = new boolean[4];
+ for (int c = 0; c < 4; c++) {
+ float cx = corners[c][0], cy = corners[c][1], sx = corners[c][2], sy = corners[c][3];
+ int above = roomAt(f, cx + sx * delta, cy - delta), below = roomAt(f, cx + sx * delta, cy + delta);
+ int left = roomAt(f, cx - delta, cy + sy * delta), right = roomAt(f, cx + delta, cy + sy * delta);
+ if (above < 0 || below < 0 || left < 0 || right < 0) return false;
+ boolean runsOnSideways = above != below, runsOnUpOrDown = left != right;
+ if (runsOnSideways == runsOnUpOrDown) return false;
+ horizontal[c] = runsOnSideways;
+ }
+ return horizontal[0] == horizontal[2] && horizontal[1] == horizontal[3] && horizontal[0] != horizontal[1];
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/PreviewActivity.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/PreviewActivity.java
new file mode 100644
index 000000000..76899e6ce
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/PreviewActivity.java
@@ -0,0 +1,67 @@
+package io.github.pbanddev.tatami;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.view.KeyEvent;
+
+/**
+ * Shows the floor plan full screen from its own tile, without changing the TV's screensaver.
+ * OK or Menu opens the effects; Back closes.
+ *
+ * <p>{@code --es look yojohan|nagaya|both} shows that look here without keeping it, for timing one look:
+ * {@code am start -n io.github.pbanddev.tatami/.PreviewActivity --es look nagaya}.
+ */
+public final class PreviewActivity extends Activity {
+ private FloorPlanView plan;
+ /** The look given as an extra, or null for the one in the settings. */
+ private LookSchedule.Mode look;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ look = LookSchedule.Mode.of(getIntent().getStringExtra(SettingsActivity.EXTRA_LOOK));
+ plan = new FloorPlanView(this);
+ setContentView(plan);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ Effects effects = Effects.load(this); // picks up changes made in the effects list
+ plan.setEffects(look == null ? effects : effects.withLook(look));
+ plan.onResume();
+ }
+
+ @Override
+ protected void onPause() {
+ plan.onPause();
+ super.onPause();
+ }
+
+ @Override
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
+ if (opensEffects(keyCode)) {
+ event.startTracking();
+ return true;
+ }
+ return super.onKeyDown(keyCode, event);
+ }
+
+ /**
+ * Only a press that began here: a launcher that opens apps on the press leaves its release to this screen, which
+ * would otherwise open the effects at once.
+ */
+ @Override
+ public boolean onKeyUp(int keyCode, KeyEvent event) {
+ if (opensEffects(keyCode)) {
+ if (event.isTracking() && !event.isCanceled()) startActivity(new Intent(this, SettingsActivity.class));
+ return true;
+ }
+ return super.onKeyUp(keyCode, event);
+ }
+
+ private static boolean opensEffects(int keyCode) {
+ return keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_MENU;
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/RoomColours.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/RoomColours.java
new file mode 100644
index 000000000..c083e92e1
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/RoomColours.java
@@ -0,0 +1,305 @@
+package io.github.pbanddev.tatami;
+
+import java.util.Random;
+
+/**
+ * Picks the paint of every room once, for the life of the plan. A seeded deal from the look's deck that keeps
+ * each paint's share of the cards. Rooms that touch at any time never share a paint (hard rule) and try not to
+ * get two paints that look alike (soft rule). When the cards and the hard rule clash, the hard rule wins.
+ */
+public final class RoomColours {
+ /** The screen the plan is laid out for to find which rooms touch. Every 16:9 screen gives the same answer. */
+ private static final float SCREEN_W = 1920, SCREEN_H = 1080;
+ /** How many times the plan is laid out at, drawn at random over {@link #SPAN} seconds. */
+ private static final int SAMPLES = 64;
+ private static final double SPAN = 100_000;
+ /**
+ * Rooms whose facing sides lie on one wall line count as touching when they come within this share of the
+ * screen height of each other along it. The walls keep sliding, so rooms that only nearly touch at every
+ * sample time can touch in between; sampling alone misses some of those.
+ */
+ private static final float NEAR_H = 0.25f;
+ /** Sides closer than this, in plan units, lie on one wall line. */
+ private static final float EPS = 0.05f;
+ /** Paints closer than this (CIEDE2000) look alike side by side. */
+ private static final double ALIKE = 8;
+ /** What two touching rooms with one paint cost. Two touching rooms whose paints look alike cost 1. */
+ private static final int SAME = 1000;
+ private static final int STEPS_PER_ROOM = 50;
+ /** Keeps the deal's random numbers apart from the layout's, which start from the same seed. */
+ private static final long STREAM = 0x7A7A3141L;
+
+ private RoomColours() {}
+
+ /** One index into {@link Look.Palette#deck} per room. A room keeps its index in every frame. */
+ public static int[] deal(FloorPlan plan, Look look) {
+ Random random = new Random(look.plan.seed ^ STREAM);
+ boolean[][] touching = touching(plan, look.camera.angleDeg, random);
+ int[] deck = look.palette.deck;
+ double[][] lab = new double[deck.length][];
+ for (int c = 0; c < deck.length; c++) lab[c] = lab(deck[c]);
+ boolean[][] alike = new boolean[deck.length][deck.length];
+ for (int c = 0; c < deck.length; c++) {
+ for (int d = 0; d < deck.length; d++) alike[c][d] = c != d && deltaE2000(lab[c], lab[d]) < ALIKE;
+ }
+ return assign(quotas(look.palette.cards, plan.rooms), touching, alike, random);
+ }
+
+ /**
+ * One index into {@link Look.Palette#deck} per room id, the quotas in a random order fixed by the seed: no rule
+ * about neighbours, so equal paints may touch.
+ */
+ public static int[] shuffle(int rooms, Look look) {
+ Random random = new Random(look.plan.seed ^ STREAM);
+ int[] quotas = quotas(look.palette.cards, rooms);
+ int[] paint = new int[rooms];
+ int k = 0;
+ for (int c = 0; c < quotas.length; c++) {
+ for (int n = 0; n < quotas[c]; n++) paint[k++] = c;
+ }
+ for (int i = rooms - 1; i > 0; i--) swap(paint, i, random.nextInt(i + 1));
+ return paint;
+ }
+
+ /**
+ * How many rooms get each paint: {@code cards} scaled to {@code rooms} by largest remainder, so each count
+ * is the exact share rounded down or up and the counts add up to {@code rooms}. Ties go to the paint with
+ * more cards, then to the earlier paint.
+ */
+ static int[] quotas(int[] cards, int rooms) {
+ long total = 0;
+ for (int c : cards) total += c;
+ int[] out = new int[cards.length];
+ if (total <= 0) return out;
+ long[] remainder = new long[cards.length];
+ int left = rooms;
+ for (int c = 0; c < cards.length; c++) {
+ long share = (long) rooms * cards[c];
+ out[c] = (int) (share / total);
+ remainder[c] = share % total;
+ left -= out[c];
+ }
+ for (; left > 0; left--) {
+ int pick = 0;
+ for (int c = 1; c < cards.length; c++) {
+ if (remainder[c] > remainder[pick] || (remainder[c] == remainder[pick] && cards[c] > cards[pick])) {
+ pick = c;
+ }
+ }
+ out[pick]++;
+ remainder[pick] = -1;
+ }
+ return out;
+ }
+
+ /** Which rooms touch, or nearly touch, at any of the sample times. */
+ static boolean[][] touching(FloorPlan plan, float angleDeg, Random random) {
+ int n = plan.rooms;
+ Frame f = new Frame(n);
+ float w = Camera.planWidth(SCREEN_W, SCREEN_H, angleDeg), h = Camera.planHeight(SCREEN_W, SCREEN_H, angleDeg);
+ float near = NEAR_H * SCREEN_H;
+ boolean[][] out = new boolean[n][n];
+ for (int s = 0; s < SAMPLES; s++) {
+ plan.layout(random.nextDouble() * SPAN, -w / 2, -h / 2, w, h, f);
+ for (int i = 0; i < f.roomCount; i++) {
+ for (int j = i + 1; j < f.roomCount; j++) {
+ if (gap(f, i, j) < near) {
+ out[i][j] = true;
+ out[j][i] = true;
+ }
+ }
+ }
+ }
+ return out;
+ }
+
+ /**
+ * How far apart rooms i and j are along the wall line their facing sides lie on: below 0 when they share
+ * a wall that long, infinite when no sides of theirs face each other on one line.
+ */
+ private static float gap(Frame f, int i, int j) {
+ float ax0 = f.roomX[i], ay0 = f.roomY[i], ax1 = ax0 + f.roomW[i], ay1 = ay0 + f.roomH[i];
+ float bx0 = f.roomX[j], by0 = f.roomY[j], bx1 = bx0 + f.roomW[j], by1 = by0 + f.roomH[j];
+ float gap = Float.POSITIVE_INFINITY;
+ if (Math.abs(ax1 - bx0) <= EPS || Math.abs(bx1 - ax0) <= EPS) {
+ gap = Math.max(ay0, by0) - Math.min(ay1, by1);
+ }
+ if (Math.abs(ay1 - by0) <= EPS || Math.abs(by1 - ay0) <= EPS) {
+ gap = Math.min(gap, Math.max(ax0, bx0) - Math.min(ax1, bx1));
+ }
+ return gap;
+ }
+
+ /**
+ * Shuffles the cards onto the rooms, then swaps rooms' cards until no touching rooms share a paint or look
+ * alike, or the steps run out (swaps keep every paint's count). Any room still sharing a paint with a
+ * neighbour then gets a paint none of its neighbours has, whatever its count.
+ */
+ static int[] assign(int[] quotas, boolean[][] touching, boolean[][] alike, Random random) {
+ int n = touching.length;
+ int[][] neighbours = neighbours(touching);
+ int[] paint = new int[n];
+ for (int c = 0, k = 0; c < quotas.length; c++) {
+ for (int i = 0; i < quotas[c] && k < n; i++) paint[k++] = c;
+ }
+ for (int k = n - 1; k > 0; k--) swap(paint, k, random.nextInt(k + 1));
+ int cost = 0;
+ for (int k = 0; k < n; k++) cost += cost(k, paint[k], paint, neighbours, alike);
+ cost /= 2;
+ int[] best = paint.clone();
+ int bestCost = cost;
+ int[] conflicted = new int[n];
+ for (int step = 0; step < STEPS_PER_ROOM * n && bestCost > 0; step++) {
+ int count = 0;
+ for (int k = 0; k < n; k++) {
+ if (cost(k, paint[k], paint, neighbours, alike) > 0) conflicted[count++] = k;
+ }
+ if (count == 0) break;
+ int a = conflicted[random.nextInt(count)];
+ // the swap that helps most; among equals, one at random
+ int pick = -1, pickDelta = Integer.MAX_VALUE, ties = 0;
+ for (int b = 0; b < n; b++) {
+ if (paint[b] == paint[a]) continue;
+ int delta = swapDelta(a, b, paint, neighbours, alike);
+ if (delta < pickDelta) {
+ pick = b;
+ pickDelta = delta;
+ ties = 1;
+ } else if (delta == pickDelta && random.nextInt(++ties) == 0) {
+ pick = b;
+ }
+ }
+ if (pick < 0) break;
+ swap(paint, a, pick);
+ cost += pickDelta;
+ if (cost < bestCost) {
+ bestCost = cost;
+ System.arraycopy(paint, 0, best, 0, n);
+ }
+ }
+ keepApart(best, neighbours, alike);
+ return best;
+ }
+
+ private static int[][] neighbours(boolean[][] touching) {
+ int n = touching.length;
+ int[][] out = new int[n][];
+ for (int i = 0; i < n; i++) {
+ int count = 0;
+ for (int j = 0; j < n; j++) if (touching[i][j] && i != j) count++;
+ out[i] = new int[count];
+ count = 0;
+ for (int j = 0; j < n; j++) if (touching[i][j] && i != j) out[i][count++] = j;
+ }
+ return out;
+ }
+
+ /** What room k costs with paint p, against its neighbours as painted now. */
+ private static int cost(int k, int p, int[] paint, int[][] neighbours, boolean[][] alike) {
+ int cost = 0;
+ for (int m : neighbours[k]) {
+ int q = paint[m];
+ if (q == p) cost += SAME;
+ else if (alike[p][q]) cost++;
+ }
+ return cost;
+ }
+
+ /** How the total cost changes when rooms a and b swap paints. */
+ private static int swapDelta(int a, int b, int[] paint, int[][] neighbours, boolean[][] alike) {
+ int pa = paint[a], pb = paint[b];
+ int before = cost(a, pa, paint, neighbours, alike) + cost(b, pb, paint, neighbours, alike);
+ swap(paint, a, b);
+ int after = cost(a, pb, paint, neighbours, alike) + cost(b, pa, paint, neighbours, alike);
+ swap(paint, a, b);
+ return after - before;
+ }
+
+ /** The hard rule wins: a room that shares a paint with a neighbour takes the best paint no neighbour has. */
+ private static void keepApart(int[] paint, int[][] neighbours, boolean[][] alike) {
+ for (int k = 0; k < paint.length; k++) {
+ if (cost(k, paint[k], paint, neighbours, alike) < SAME) continue;
+ int pick = -1, pickCost = SAME;
+ for (int c = 0; c < alike.length; c++) {
+ int cost = cost(k, c, paint, neighbours, alike);
+ if (cost < pickCost) {
+ pick = c;
+ pickCost = cost;
+ }
+ }
+ if (pick >= 0) paint[k] = pick;
+ }
+ }
+
+ private static void swap(int[] values, int i, int j) {
+ int v = values[i];
+ values[i] = values[j];
+ values[j] = v;
+ }
+
+ /** CIELAB (D65) of an sRGB colour: L*, a*, b*. */
+ static double[] lab(int argb) {
+ double r = linear((argb >> 16) & 0xFF), g = linear((argb >> 8) & 0xFF), b = linear(argb & 0xFF);
+ double fx = labF((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / 0.95047);
+ double fy = labF(0.2126729 * r + 0.7151522 * g + 0.0721750 * b);
+ double fz = labF((0.0193339 * r + 0.1191920 * g + 0.9503041 * b) / 1.08883);
+ return new double[] {116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)};
+ }
+
+ private static double linear(int channel) {
+ double c = channel / 255.0;
+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
+ }
+
+ private static double labF(double t) {
+ return t > 216.0 / 24389 ? Math.cbrt(t) : (24389.0 / 27 * t + 16) / 116;
+ }
+
+ /** The CIEDE2000 colour difference of two CIELAB colours (Sharma, Wu and Dalal 2005). */
+ static double deltaE2000(double[] lab1, double[] lab2) {
+ double l1 = lab1[0], a1 = lab1[1], b1 = lab1[2];
+ double l2 = lab2[0], a2 = lab2[1], b2 = lab2[2];
+ double cMean7 = Math.pow((Math.hypot(a1, b1) + Math.hypot(a2, b2)) / 2, 7);
+ double g = 0.5 * (1 - Math.sqrt(cMean7 / (cMean7 + 6103515625.0))); // 25^7
+ double a1p = (1 + g) * a1, a2p = (1 + g) * a2;
+ double c1p = Math.hypot(a1p, b1), c2p = Math.hypot(a2p, b2);
+ double h1p = hueDeg(a1p, b1), h2p = hueDeg(a2p, b2);
+ boolean grey = c1p * c2p == 0;
+
+ double dL = l2 - l1, dC = c2p - c1p;
+ double dh = grey ? 0 : h2p - h1p;
+ if (dh > 180) dh -= 360;
+ else if (dh < -180) dh += 360;
+ double dH = 2 * Math.sqrt(c1p * c2p) * Math.sin(Math.toRadians(dh / 2));
+
+ double lMean = (l1 + l2) / 2, cMeanP = (c1p + c2p) / 2;
+ double hMean;
+ if (grey) hMean = h1p + h2p;
+ else if (Math.abs(h1p - h2p) <= 180) hMean = (h1p + h2p) / 2;
+ else if (h1p + h2p < 360) hMean = (h1p + h2p + 360) / 2;
+ else hMean = (h1p + h2p - 360) / 2;
+
+ double t = 1 - 0.17 * cosDeg(hMean - 30) + 0.24 * cosDeg(2 * hMean) + 0.32 * cosDeg(3 * hMean + 6)
+ - 0.20 * cosDeg(4 * hMean - 63);
+ double dTheta = 30 * Math.exp(-Math.pow((hMean - 275) / 25, 2));
+ double cMeanP7 = Math.pow(cMeanP, 7);
+ double rc = 2 * Math.sqrt(cMeanP7 / (cMeanP7 + 6103515625.0));
+ double l50 = (lMean - 50) * (lMean - 50);
+ double sl = 1 + 0.015 * l50 / Math.sqrt(20 + l50);
+ double sc = 1 + 0.045 * cMeanP;
+ double sh = 1 + 0.015 * cMeanP * t;
+ double rt = -Math.sin(Math.toRadians(2 * dTheta)) * rc;
+ double kl = dL / sl, kc = dC / sc, kh = dH / sh;
+ return Math.sqrt(kl * kl + kc * kc + kh * kh + rt * kc * kh);
+ }
+
+ private static double hueDeg(double a, double b) {
+ if (a == 0 && b == 0) return 0;
+ double h = Math.toDegrees(Math.atan2(b, a));
+ return h < 0 ? h + 360 : h;
+ }
+
+ private static double cosDeg(double deg) {
+ return Math.cos(Math.toRadians(deg));
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Scene.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Scene.java
new file mode 100644
index 000000000..9c15c8303
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Scene.java
@@ -0,0 +1,150 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * One frame of the floor plan, from the time to triangles and a camera matrix. The renderer on the TV
+ * and the desktop tools (tools/PlanShot.java, tools/PlanStats.java) all run this, so they draw the same
+ * frame. Pure Java. Build one through {@link Scenes} in the app, so a look that fails gives way to Yojōhan.
+ *
+ * <p>The steps, in order: the look's {@link CameraCurve} sets the {@link View} and the matrix, its
+ * {@link Layout} lays out rooms, cells and walls, the paints dealt once go on, its {@link DoorPlacer} and
+ * {@link Fixtures} add theirs, and {@link SceneMesh} makes the triangles.
+ *
+ * <p>Yojōhan: {@link FloorPlan}, {@link RoomColours#deal}, {@link Doors} and {@link CameraMatrix}, as they were.
+ * Nagaya: {@link TilePlan} with {@link SkylineBuilder}, {@link RoomColours#shuffle}, {@link NagayaDoors},
+ * {@link NagayaCamera} and the {@link Wash}.
+ */
+public final class Scene {
+ public final Look look;
+ final Layout layout;
+ public final Frame frame;
+ public final SceneMesh mesh;
+ /** What the camera sees this frame. */
+ public final View view = new View();
+ /** Plan units to clip space, column-major 4x4. */
+ public final float[] matrix = new float[16];
+ private final int[] paints;
+ private final CameraCurve camera;
+ private final DoorPlacer doors;
+ /** Null when the look has no fixtures. */
+ private final Fixtures fixtures;
+ /** Null when the look has no wash. */
+ private final Wash wash;
+
+ public Scene(Look look) {
+ this(look, new SkylineBuilder());
+ }
+
+ /** A scene whose TILE plan comes from {@code builder} (the tools try builders this way); TREE ignores it. */
+ Scene(Look look, TileBuilder builder) {
+ this.look = look;
+ if (look.plan.kind == Look.Plan.Kind.TREE) {
+ FloorPlan tree = new FloorPlan(look);
+ layout = new TreeLayout(tree, look);
+ paints = look.palette.deal == Look.Palette.Deal.SHUFFLE
+ ? RoomColours.shuffle(tree.rooms, look) : RoomColours.deal(tree, look);
+ camera = new TreeCamera(look);
+ Doors placer = new Doors(look);
+ doors = (f, t, v) -> placer.place(f, t, v.h);
+ } else {
+ layout = new TilePlan(look, builder);
+ paints = RoomColours.shuffle(layout.rooms(), look);
+ camera = new NagayaCamera(look);
+ doors = new NagayaDoors(look);
+ }
+ frame = layout.newFrame();
+ mesh = new SceneMesh(frame, look);
+ fixtures = look.fixtures.share > 0 ? new Fixtures(look) : null;
+ wash = look.post.wash ? Wash.NAGAYA : null;
+ }
+
+ /** Fills {@link #frame}, {@link #mesh} and {@link #matrix} for time {@code t} on a w by h screen, washed. */
+ public void build(double t, int w, int h, boolean showDoors, boolean showFixtures, boolean moveCamera) {
+ build(t, w, h, showDoors, showFixtures, moveCamera, true);
+ }
+
+ /** As above; {@code washOn} false leaves Nagaya's fills unwashed (the vignette switch). Yojōhan has no wash. */
+ public void build(double t, int w, int h, boolean showDoors, boolean showFixtures, boolean moveCamera,
+ boolean washOn) {
+ camera.at(t, w, h, moveCamera, view, matrix);
+ fill(t, showDoors, showFixtures, washOn ? wash : null);
+ }
+
+ /** Everything after the camera, through the {@link #view} and {@link #matrix} as they are. */
+ void fill(double t, boolean showDoors, boolean showFixtures, Wash wash) {
+ layout.layout(t, view, frame);
+ for (int k = 0; k < frame.roomCount; k++) frame.roomColor[k] = paints[frame.roomId[k]];
+ if (showDoors) doors.place(frame, t, view); else frame.doorCount = 0;
+ if (showFixtures && fixtures != null) fixtures.place(frame, view.h); else frame.fixtureCount = 0;
+ if (look.plan.kind == Look.Plan.Kind.TREE) mesh.build(frame, view.h); else mesh.build(frame, view, matrix, wash);
+ }
+
+ /** How far past each screen edge the plan must be drawn, in px: the blur's strip, padded to whole GPU tiles. */
+ static float margin(Look look) {
+ return Lens.margin(look.post) + 16;
+ }
+
+ /** Yojōhan's rooms: {@link FloorPlan} as it is, sized as the tilted camera needs, one cell per room. */
+ private static final class TreeLayout implements Layout {
+ private final FloorPlan tree;
+ private final float angleDeg;
+
+ TreeLayout(FloorPlan tree, Look look) {
+ this.tree = tree;
+ angleDeg = look.camera.angleDeg;
+ }
+
+ @Override
+ public int rooms() {
+ return tree.rooms;
+ }
+
+ @Override
+ public Frame newFrame() {
+ Frame f = new Frame(tree.rooms);
+ for (int k = 0; k < f.roomId.length; k++) f.roomId[k] = k;
+ for (int k = 0; k < f.wallId.length; k++) {
+ f.wallId[k] = k;
+ f.wallRoomA[k] = -1;
+ f.wallRoomB[k] = -1;
+ f.wallMinLength[k] = Float.NaN;
+ }
+ return f;
+ }
+
+ @Override
+ public void layout(double t, View v, Frame f) {
+ float pw = Camera.planWidth(v.w, v.h, angleDeg), ph = Camera.planHeight(v.w, v.h, angleDeg);
+ tree.layout(t, -pw / 2, -ph / 2, pw, ph, f);
+ for (int k = 0; k < f.roomCount; k++) {
+ f.cellX[k] = f.roomX[k];
+ f.cellY[k] = f.roomY[k];
+ f.cellW[k] = f.roomW[k];
+ f.cellH[k] = f.roomH[k];
+ f.cellRoom[k] = k;
+ }
+ f.cellCount = f.roomCount;
+ }
+ }
+
+ /** Yojōhan's camera: {@link Camera} and {@link CameraMatrix} as they are; the view follows their pan. */
+ private static final class TreeCamera implements CameraCurve {
+ private final float angleDeg, margin;
+ private final double cos, sin;
+
+ TreeCamera(Look look) {
+ angleDeg = look.camera.angleDeg;
+ margin = margin(look);
+ cos = Math.cos(Math.toRadians(angleDeg));
+ sin = Math.sin(Math.toRadians(angleDeg));
+ }
+
+ @Override
+ public void at(double t, int w, int h, boolean moving, View view, float[] matrix) {
+ float zoom = Camera.zoom(t, moving);
+ double px = Camera.panX(t, w, moving), py = Camera.panY(t, h, moving);
+ // the screen centre, back through the pan, the turn and the zoom
+ view.set(w, h, angleDeg, zoom, (-cos * px - sin * py) / zoom, (sin * px - cos * py) / zoom, margin);
+ CameraMatrix.build(t, w, h, moving, angleDeg, matrix);
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/SceneMesh.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/SceneMesh.java
new file mode 100644
index 000000000..2d804edfd
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/SceneMesh.java
@@ -0,0 +1,251 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * Turns a {@link Frame} into coloured triangles for OpenGL: x, y in plan units, then r, g, b, a.
+ * Fills, then walls, then doors ({@link DoorShapes}), then fixtures ({@link FixtureShapes}), so later
+ * shapes cover earlier ones. Sizes and colours come from the {@link Look}.
+ *
+ * <p>Yojōhan ({@link #build(Frame, float)}): each room a fill and 4 wall quads round it. Nagaya
+ * ({@link #build(Frame, View, float[], Wash)}): each cell a fill, cut into pieces whose corners take the
+ * {@link Wash}, then a quad per wall piece. Fills use {@link #color}, which the wash reaches; walls and strokes
+ * use {@link #ink}, which it never does.
+ *
+ * <p>The arrays are sized from the frame's capacities. A shape that does not fit is left out and sets
+ * {@link #clipped}.
+ */
+public final class SceneMesh {
+ public static final int FLOATS_PER_VERTEX = 6;
+
+ /** A room's fill and its 4 wall quads. */
+ private static final int VERTICES_PER_ROOM = 6 + 4 * 6;
+ /**
+ * Nagaya's fills reach this many screen px past their cells. Cells of one room meet with no wall over the seam,
+ * and their pieces' corners do not line up across it, so without it a rasterizer leaves hairline cracks there.
+ * Past a wall the bleed is under the wall.
+ */
+ static final float BLEED_PX = 0.5f;
+
+ public final float[] data;
+ public int floats;
+ /** True when the last build had more triangles than {@link #data} holds. */
+ public boolean clipped;
+ private final Look look;
+ private float r, g, b;
+ /** Set while a Nagaya build runs; null otherwise. */
+ private Wash wash;
+ private boolean washing;
+ private float[] matrix;
+ private float screenW, screenH;
+ private final float[] washed = new float[3];
+ /** Washed corner colours of 2 rows of pieces; they grow if a cell needs more. */
+ private float[] upper = new float[3 * 16], lower = new float[3 * 16];
+
+ public SceneMesh(int rooms, Look look) {
+ this(new Frame(rooms), look);
+ }
+
+ public SceneMesh(Frame f, Look look) {
+ this.look = look;
+ int doors = f.doorWall.length * DoorShapes.MAX_VERTICES;
+ int fixtures = look.fixtures.share > 0 ? f.fixtureKind.length * FixtureShapes.MAX_VERTICES : 0;
+ int vertices = look.plan.kind == Look.Plan.Kind.TREE
+ ? f.cellX.length * VERTICES_PER_ROOM + doors + fixtures
+ : f.fillCapacity * 6 + f.wallX0.length * 6 + doors + fixtures;
+ data = new float[FLOATS_PER_VERTEX * vertices];
+ }
+
+ /** Yojōhan: each room's fill, then its outline as walls. */
+ public void build(Frame f, float screenHeight) {
+ floats = 0;
+ clipped = false;
+ int[] deck = look.palette.deck;
+ for (int i = 0; i < f.roomCount; i++) {
+ color(deck[f.roomColor[i]]);
+ rect(f.roomX[i], f.roomY[i], f.roomW[i], f.roomH[i]);
+ }
+ float wall = screenHeight * look.walls.widthH;
+ ink(look.walls.color);
+ for (int i = 0; i < f.roomCount; i++) outline(f.roomX[i], f.roomY[i], f.roomW[i], f.roomH[i], wall);
+ for (int d = 0; d < f.doorCount; d++) DoorShapes.add(this, f, d, screenHeight, look);
+ for (int k = 0; k < f.fixtureCount; k++) FixtureShapes.add(this, f, k, screenHeight, look);
+ }
+
+ /**
+ * Nagaya: cell fills, washed by {@code wash} at the screen positions {@code matrix} gives them (null: not
+ * washed, and not cut), then a quad per wall piece, half a wall longer at each end, then doors.
+ */
+ public void build(Frame f, View view, float[] matrix, Wash wash) {
+ floats = 0;
+ clipped = false;
+ this.wash = wash;
+ this.matrix = matrix;
+ screenW = view.w;
+ screenH = view.h;
+ try {
+ int[] deck = look.palette.deck;
+ float side = view.h * look.post.washPieceH, bleed = BLEED_PX / view.zoom;
+ for (int c = 0; c < f.cellCount; c++) {
+ color(deck[f.roomColor[f.cellRoom[c]]]);
+ fill(f.cellX[c] - bleed, f.cellY[c] - bleed, f.cellW[c] + 2 * bleed, f.cellH[c] + 2 * bleed, side);
+ }
+ float half = view.h * look.walls.widthH / 2;
+ ink(look.walls.color);
+ for (int i = 0; i < f.wallCount; i++) {
+ rect(f.wallX0[i] - half, f.wallY0[i] - half,
+ f.wallX1[i] - f.wallX0[i] + 2 * half, f.wallY1[i] - f.wallY0[i] + 2 * half);
+ }
+ for (int d = 0; d < f.doorCount; d++) DoorShapes.add(this, f, d, view.h, look);
+ if (look.fixtures.share > 0) {
+ for (int k = 0; k < f.fixtureCount; k++) FixtureShapes.add(this, f, k, view.h, look);
+ }
+ } finally {
+ this.wash = null;
+ this.matrix = null;
+ washing = false;
+ }
+ }
+
+ /** How many pieces a w by h fill is cut into for the wash, with pieces at most {@code side} each way. */
+ static int pieces(float w, float h, float side) {
+ return Math.max(1, (int) Math.ceil(w / side)) * Math.max(1, (int) Math.ceil(h / side));
+ }
+
+ /** The colour of the fills that follow: the wash reaches it, if there is one. */
+ void color(int argb) {
+ set(argb);
+ washing = wash != null;
+ }
+
+ /** The colour of the walls and strokes that follow: never washed. */
+ void ink(int argb) {
+ set(argb);
+ washing = false;
+ }
+
+ private void set(int argb) {
+ r = ((argb >> 16) & 0xFF) / 255f;
+ g = ((argb >> 8) & 0xFF) / 255f;
+ b = (argb & 0xFF) / 255f;
+ }
+
+ /** A box outline of the given width, centred on the box's edges. */
+ void outline(float x, float y, float w, float h, float width) {
+ float half = width / 2;
+ rect(x - half, y - half, w + width, width);
+ rect(x - half, y + h - half, w + width, width);
+ rect(x - half, y - half, width, h + width);
+ rect(x + w - half, y - half, width, h + width);
+ }
+
+ /** A straight line of the given width with flat ends at the end points. Always 2 triangles. */
+ void line(float x0, float y0, float x1, float y1, float width) {
+ float dx = x1 - x0, dy = y1 - y0;
+ float length = (float) Math.hypot(dx, dy);
+ if (length == 0) {
+ triangle(x0, y0, x0, y0, x0, y0);
+ triangle(x0, y0, x0, y0, x0, y0);
+ return;
+ }
+ float nx = -dy / length * width / 2, ny = dx / length * width / 2;
+ triangle(x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny);
+ triangle(x0 + nx, y0 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny);
+ }
+
+ void rect(float x, float y, float w, float h) {
+ triangle(x, y, x + w, y, x + w, y + h);
+ triangle(x, y, x + w, y + h, x, y + h);
+ }
+
+ void triangle(float x0, float y0, float x1, float y1, float x2, float y2) {
+ if (floats + 3 * FLOATS_PER_VERTEX > data.length) {
+ clipped = true;
+ return;
+ }
+ vertex(x0, y0);
+ vertex(x1, y1);
+ vertex(x2, y2);
+ }
+
+ /** A fill: one box, or with a wash, pieces at most {@code side} each way whose corners are washed once. */
+ private void fill(float x, float y, float w, float h, float side) {
+ if (!washing) {
+ rect(x, y, w, h);
+ return;
+ }
+ int nx = Math.max(1, (int) Math.ceil(w / side)), ny = Math.max(1, (int) Math.ceil(h / side));
+ if (upper.length < 3 * (nx + 1)) {
+ upper = new float[3 * (nx + 1)];
+ lower = new float[3 * (nx + 1)];
+ }
+ washRow(upper, x, y, w, nx);
+ float top = y;
+ for (int j = 1; j <= ny; j++) {
+ float bottom = j == ny ? y + h : y + h * j / ny;
+ washRow(lower, x, bottom, w, nx);
+ float left = x;
+ for (int i = 0; i < nx; i++) {
+ float right = i + 1 == nx ? x + w : x + w * (i + 1) / nx;
+ if (floats + 6 * FLOATS_PER_VERTEX > data.length) {
+ clipped = true;
+ return;
+ }
+ put(left, top, upper, i);
+ put(right, top, upper, i + 1);
+ put(right, bottom, lower, i + 1);
+ put(left, top, upper, i);
+ put(right, bottom, lower, i + 1);
+ put(left, bottom, lower, i);
+ left = right;
+ }
+ float[] swap = upper;
+ upper = lower;
+ lower = swap;
+ top = bottom;
+ }
+ }
+
+ /** The washed colours of the nx + 1 corners along y, from x to x + w. */
+ private void washRow(float[] row, float x, float y, float w, int nx) {
+ for (int i = 0; i <= nx; i++) {
+ washAt(i == nx ? x + w : x + w * i / nx, y);
+ row[3 * i] = washed[0];
+ row[3 * i + 1] = washed[1];
+ row[3 * i + 2] = washed[2];
+ }
+ }
+
+ /** The current colour, washed where plan point (x, y) lands on screen, into {@link #washed}. */
+ private void washAt(float x, float y) {
+ float[] m = matrix;
+ float cx = m[0] * x + m[4] * y + m[12], cy = m[1] * x + m[5] * y + m[13];
+ washed[0] = r;
+ washed[1] = g;
+ washed[2] = b;
+ wash.apply((cx + 1) / 2 * screenW, (1 - cy) / 2 * screenH, screenW, screenH, washed);
+ }
+
+ private void vertex(float x, float y) {
+ if (washing) {
+ washAt(x, y);
+ put(x, y, washed[0], washed[1], washed[2]);
+ } else {
+ put(x, y, r, g, b);
+ }
+ }
+
+ private void put(float x, float y, float[] row, int i) {
+ put(x, y, row[3 * i], row[3 * i + 1], row[3 * i + 2]);
+ }
+
+ private void put(float x, float y, float red, float green, float blue) {
+ float[] d = data;
+ int i = floats;
+ d[i] = x;
+ d[i + 1] = y;
+ d[i + 2] = red;
+ d[i + 3] = green;
+ d[i + 4] = blue;
+ d[i + 5] = 1f;
+ floats = i + FLOATS_PER_VERTEX;
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Scenes.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Scenes.java
new file mode 100644
index 000000000..2bdf8878f
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Scenes.java
@@ -0,0 +1,45 @@
+package io.github.pbanddev.tatami;
+
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+/**
+ * The one way the app makes a {@link Scene}, so Home never crashes over a look. Yojōhan builds as it always has.
+ * Any other look that throws anything while it builds, or later fails to draw ({@link #failed}), is reported once
+ * and not used again in this process: {@link #make} then gives Yojōhan's scene.
+ */
+final class Scenes {
+ /** The app's: Home, the screensaver and the settings views share it. */
+ static final Scenes APP = new Scenes(Scene::new);
+
+ private final Function<Look, Scene> build;
+ private volatile boolean nagayaFailed;
+
+ Scenes(Function<Look, Scene> build) {
+ this.build = build;
+ }
+
+ /** False once the look has failed in this process. Yojōhan is always usable. */
+ boolean usable(Look look) {
+ return look == Look.YOJOHAN || !nagayaFailed;
+ }
+
+ /** The look's scene, or Yojōhan's if the look has failed or fails now; {@code report} hears of a new failure. */
+ Scene make(Look look, Consumer<Throwable> report) {
+ if (look != Look.YOJOHAN && !nagayaFailed) {
+ try {
+ return build.apply(look);
+ } catch (Throwable failure) {
+ failed(look, failure, report);
+ }
+ }
+ return build.apply(Look.YOJOHAN);
+ }
+
+ /** The look failed to draw: it is not used again in this process. */
+ void failed(Look look, Throwable failure, Consumer<Throwable> report) {
+ if (look == Look.YOJOHAN) return;
+ nagayaFailed = true;
+ report.accept(failure);
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/SettingsActivity.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/SettingsActivity.java
new file mode 100644
index 000000000..917e91c9e
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/SettingsActivity.java
@@ -0,0 +1,175 @@
+package io.github.pbanddev.tatami;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.graphics.drawable.ColorDrawable;
+import android.graphics.drawable.StateListDrawable;
+import android.os.Bundle;
+import android.util.TypedValue;
+import android.view.Gravity;
+import android.view.ViewGroup;
+import android.widget.CheckBox;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+/**
+ * The effects list over the live floor plan, so every switch shows its result at once. The look and the swap period
+ * come first; OK steps through their choices. Up and Down move one row, OK switches, Back closes. Opened from the
+ * preview with OK, and from the TV's screensaver settings where the firmware offers it.
+ *
+ * <p>The look and the swap period can also be set without key presses, and are kept:
+ * {@code am start -n io.github.pbanddev.tatami/.SettingsActivity --es look nagaya --ei swap_minutes 1}.
+ * {@code look} is yojohan, nagaya or both; {@code swap_minutes} is 1 to 60 (the row itself offers 5, 10, 30 and 60).
+ */
+public final class SettingsActivity extends Activity {
+ static final String EXTRA_LOOK = "look";
+ static final String EXTRA_SWAP_MINUTES = "swap_minutes";
+ private static final int TEXT = 0xFFEDE6D3;
+ private static final int ACCENT = 0xFFE8D87A;
+
+ private FloorPlanView plan;
+ private TextView lookRow, swapRow;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ keepExtras(getIntent());
+ FrameLayout root = new FrameLayout(this);
+ plan = new FloorPlanView(this);
+ root.addView(plan, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
+
+ LinearLayout panel = new LinearLayout(this);
+ panel.setOrientation(LinearLayout.VERTICAL);
+ panel.setGravity(Gravity.CENTER_VERTICAL);
+ panel.setPadding(dp(40), dp(32), dp(32), dp(32));
+ panel.setBackgroundColor(0xE6151310);
+
+ TextView title = new TextView(this);
+ title.setText(R.string.effects_title);
+ title.setTextColor(ACCENT);
+ title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28);
+ title.setPadding(dp(12), 0, 0, dp(16));
+ panel.addView(title);
+
+ Effects current = Effects.load(this);
+ lookRow = choiceRow(rowText(R.string.look_label, lookName(current.look)));
+ lookRow.setOnClickListener(view -> {
+ LookSchedule.Mode next = Effects.load(this).look.next();
+ Effects.setLook(this, next);
+ lookRow.setText(rowText(R.string.look_label, lookName(next)));
+ plan.setEffects(Effects.load(this));
+ });
+ panel.addView(lookRow, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+ swapRow = choiceRow(rowText(R.string.swap_label, minutes(current.swapMinutes)));
+ swapRow.setOnClickListener(view -> {
+ int next = Effects.nextSwapMinutes(Effects.load(this).swapMinutes);
+ Effects.setSwapMinutes(this, next);
+ swapRow.setText(rowText(R.string.swap_label, minutes(next)));
+ plan.setEffects(Effects.load(this));
+ });
+ panel.addView(swapRow, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+
+ for (String key : Effects.ALL) {
+ CheckBox box = new CheckBox(this);
+ box.setText(label(key));
+ box.setTextColor(TEXT);
+ box.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
+ box.setPadding(dp(12), dp(10), dp(12), dp(10));
+ box.setBackground(focusBackground());
+ box.setChecked(current.isOn(key));
+ box.setOnCheckedChangeListener((view, on) -> {
+ Effects.set(this, key, on);
+ plan.setEffects(Effects.load(this));
+ });
+ panel.addView(box, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+ }
+ root.addView(panel, new FrameLayout.LayoutParams(dp(460), ViewGroup.LayoutParams.MATCH_PARENT, Gravity.START));
+ setContentView(root);
+ lookRow.requestFocus();
+ }
+
+ /** Opened again while it is on top (it is single-top): keeps the new extras and shows them. */
+ @Override
+ protected void onNewIntent(Intent intent) {
+ super.onNewIntent(intent);
+ setIntent(intent);
+ keepExtras(intent);
+ Effects current = Effects.load(this);
+ lookRow.setText(rowText(R.string.look_label, lookName(current.look)));
+ swapRow.setText(rowText(R.string.swap_label, minutes(current.swapMinutes)));
+ plan.setEffects(current);
+ }
+
+ /** Keeps a look and a swap period given as extras; values that name none are left out. */
+ private void keepExtras(Intent intent) {
+ LookSchedule.Mode look = LookSchedule.Mode.of(intent.getStringExtra(EXTRA_LOOK));
+ if (look != null) Effects.setLook(this, look);
+ if (intent.hasExtra(EXTRA_SWAP_MINUTES)) Effects.setSwapMinutes(this, intent.getIntExtra(EXTRA_SWAP_MINUTES, 0));
+ }
+
+ /** A row OK steps through, styled as the switches below it. */
+ private TextView choiceRow(String text) {
+ TextView row = new TextView(this);
+ row.setText(text);
+ row.setTextColor(TEXT);
+ row.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
+ row.setPadding(dp(12), dp(10), dp(12), dp(10));
+ row.setBackground(focusBackground());
+ row.setFocusable(true);
+ row.setClickable(true);
+ return row;
+ }
+
+ /** "Label: value". */
+ private String rowText(int label, String value) {
+ return getString(R.string.setting_row, getString(label), value);
+ }
+
+ private String lookName(LookSchedule.Mode look) {
+ switch (look) {
+ case YOJOHAN: return getString(R.string.look_yojohan);
+ case NAGAYA: return getString(R.string.look_nagaya);
+ default: return getString(R.string.look_both);
+ }
+ }
+
+ private String minutes(int minutes) {
+ return getString(R.string.swap_minutes, minutes);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ plan.onResume();
+ }
+
+ @Override
+ protected void onPause() {
+ plan.onPause();
+ super.onPause();
+ }
+
+ private int label(String key) {
+ switch (key) {
+ case Effects.GRAIN: return R.string.effect_grain;
+ case Effects.VIGNETTE: return R.string.effect_vignette;
+ case Effects.TILT_SHIFT: return R.string.effect_tilt_shift;
+ case Effects.DOORS: return R.string.effect_doors;
+ case Effects.FIXTURES: return R.string.effect_fixtures;
+ case Effects.CAMERA: return R.string.effect_camera;
+ default: throw new IllegalArgumentException(key);
+ }
+ }
+
+ private static StateListDrawable focusBackground() {
+ StateListDrawable background = new StateListDrawable();
+ background.addState(new int[] {android.R.attr.state_focused}, new ColorDrawable(0x40E8D87A));
+ background.addState(new int[] {}, new ColorDrawable(0x00000000));
+ return background;
+ }
+
+ private int dp(int value) {
+ return Math.round(value * getResources().getDisplayMetrics().density);
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Shaders.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Shaders.java
new file mode 100644
index 000000000..335d4f2df
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Shaders.java
@@ -0,0 +1,112 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * The GLSL ES 1.00 sources of the plan's passes, made from a look's lens values ({@link Look.Post}). Pure Java,
+ * so a test can hold Yojōhan's text still. {@link FloorPlanGlRenderer} compiles them.
+ *
+ * <p>uFade, applied last in the 2 passes that reach the window, darkens the whole picture: 1 as drawn, 0 black.
+ */
+final class Shaders {
+ private static final String PRECISION =
+ "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n";
+ /**
+ * Mediump maths, about twice as fast as highp on many TV GPUs, with HIGHP for the texture coordinates that must
+ * land on the right pixel: the grain tile's (in mediump, gl_FragCoord / 256 cannot hit texel centres across
+ * a 1080p screen) and the blurred copy's (mediump is about 1 px off near the right edge).
+ */
+ private static final String LENS_PRECISION = "precision mediump float;\n"
+ + "#ifdef GL_FRAGMENT_PRECISION_HIGH\n#define HIGHP highp\n#else\n#define HIGHP mediump\n#endif\n";
+ /** The scene's colours as they are, for the copy to blur. */
+ static final String PLAIN_FRAGMENT = "precision mediump float;\nvarying vec4 vColor;\n"
+ + "void main() { gl_FragColor = vColor; }\n";
+ static final String SCENE_VERTEX =
+ "uniform mat4 uMatrix;\nattribute vec2 aPos;\nattribute vec4 aColor;\nvarying vec4 vColor;\n"
+ + "void main() { vColor = aColor; gl_Position = uMatrix * vec4(aPos, 0.0, 1.0); }\n";
+ static final String QUAD_VERTEX =
+ "attribute vec2 aPos;\nvarying vec2 vUv;\n"
+ + "void main() { vUv = aPos * 0.5 + 0.5; gl_Position = vec4(aPos, 0.0, 1.0); }\n";
+ /**
+ * Full size down to 1/4 as a 4x4 box: 4 bilinear taps, each the average of 2x2 texels. A wall
+ * thinner than one small pixel then fades in and out smoothly instead of popping, which is
+ * what made the blurred edges flicker when the scene was drawn straight at 1/4 size.
+ */
+ static final String DOWNSAMPLE_FRAGMENT = PRECISION
+ + "uniform sampler2D uTex;\nuniform vec2 uTexel;\nvarying vec2 vUv;\n"
+ + "void main() {\n"
+ + " gl_FragColor = 0.25 * (texture2D(uTex, vUv + uTexel * vec2(-1.0, -1.0))\n"
+ + " + texture2D(uTex, vUv + uTexel * vec2(1.0, -1.0))\n"
+ + " + texture2D(uTex, vUv + uTexel * vec2(-1.0, 1.0))\n"
+ + " + texture2D(uTex, vUv + uTexel * vec2(1.0, 1.0)));\n}\n";
+
+ private Shaders() {}
+
+ /**
+ * The plan's triangles through the lens, into the window. The vignette and colour ramp (uVig 1 or 0)
+ * come from the lens map. Grain is zero-mean and added after them (uGrainAmp 1 or 0); only this sharp layer
+ * has it, so it fades where the blurred copy covers it. A look washed on the CPU ({@link Look.Post#wash}) comes
+ * with its colours done, so it reads no lens map here: grain only.
+ */
+ static String sceneFragment(Look.Post post) {
+ StringBuilder amp = new StringBuilder(glsl(post.grainBase / 255f));
+ if (post.grainSlope != 0f) amp.append(" + ").append(glsl(post.grainSlope / 255f)).append(" * luma * luma");
+ if (post.grainStep != 0f) {
+ amp.append(" + ").append(glsl(post.grainStep / 255f)).append(" * smoothstep(")
+ .append(glsl(post.grainStepFrom)).append(", ").append(glsl(post.grainStepTo)).append(", luma)");
+ }
+ String lensUniforms = post.wash ? "" : "uniform vec2 uInvSize;\nuniform float uVig;\n";
+ String lensSampler = post.wash ? "" : "uniform sampler2D uLens;\n";
+ String gain = post.wash ? "" : " * mix(vec3(1.0), texture2D(uLens, gl_FragCoord.xy * uInvSize).rgb * 2.0, uVig)";
+ return LENS_PRECISION
+ + lensUniforms + "uniform float uGrainAmp;\nuniform float uFade;\n"
+ + "uniform HIGHP vec2 uGrainOffset;\n"
+ + "uniform sampler2D uGrain;\n" + lensSampler + "varying vec4 vColor;\n"
+ + "void main() {\n"
+ + " vec3 c = vColor.rgb" + gain + ";\n"
+ + " float luma = dot(c, vec3(0.2126, 0.7152, 0.0722));\n"
+ + " HIGHP vec2 g = gl_FragCoord.xy / " + glsl(Grain.SIZE) + " + uGrainOffset;\n"
+ + " float n = (texture2D(uGrain, g).r - 0.5) * 8.0;\n"
+ + " c += n * (" + amp + ") * uGrainAmp;\n"
+ + " gl_FragColor = vec4(c * uFade, 1.0);\n}\n";
+ }
+
+ /** One separable Gaussian round, along uStep (one texel across or down). */
+ static String blurFragment(Look.Post post) {
+ StringBuilder s = new StringBuilder(PRECISION)
+ .append("uniform sampler2D uTex;\nuniform vec2 uStep;\nvarying vec2 vUv;\n")
+ .append("void main() {\n vec4 c = vec4(0.0);\n");
+ for (int i = 0; i < post.blurWeights.length; i++) {
+ String w = glsl(post.blurWeights[i]), o = glsl(post.blurOffsets[i]);
+ if (post.blurOffsets[i] == 0f) {
+ s.append(" c += texture2D(uTex, vUv) * ").append(w).append(";\n");
+ } else {
+ s.append(" c += (texture2D(uTex, vUv + uStep * ").append(o).append(") + texture2D(uTex, vUv - uStep * ")
+ .append(o).append(")) * ").append(w).append(";\n");
+ }
+ }
+ return s.append(" gl_FragColor = c;\n}\n").toString();
+ }
+
+ /**
+ * The blurred copy through the same lens, see-through in the sharp oval and opaque outside it. A look washed on
+ * the CPU takes no gain here either; the lens map's alpha still shapes the oval.
+ */
+ static String blendFragment(Look.Post post) {
+ return LENS_PRECISION
+ + "uniform sampler2D uTex;\nuniform sampler2D uLens;\n" + (post.wash ? "" : "uniform float uVig;\n")
+ + "uniform float uFade;\n"
+ + "uniform HIGHP vec4 uBlurArea;\n"
+ + "varying HIGHP vec2 vUv;\n"
+ + "void main() {\n"
+ + " vec4 lens = texture2D(uLens, vUv);\n"
+ + " HIGHP vec2 uv = vUv * uBlurArea.xy + uBlurArea.zw;\n"
+ + " vec3 blurred = texture2D(uTex, uv).rgb;\n"
+ + " gl_FragColor = vec4(blurred" + (post.wash ? "" : " * mix(vec3(1.0), lens.rgb * 2.0, uVig)")
+ + " * uFade, lens.a);\n}\n";
+ }
+
+ /** A GLSL ES 1.00 float literal. Float.toString always writes a decimal point ("2.0", "0.42", "1.0E-5"). */
+ static String glsl(float v) {
+ if (Float.isNaN(v) || Float.isInfinite(v)) throw new IllegalArgumentException("not a number: " + v);
+ return Float.toString(v);
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/SkylineBuilder.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/SkylineBuilder.java
new file mode 100644
index 000000000..341ede351
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/SkylineBuilder.java
@@ -0,0 +1,623 @@
+package io.github.pbanddev.tatami;
+
+import java.util.Arrays;
+import java.util.Random;
+
+/**
+ * A {@link TileBuilder} that settles each room's shape class before its walls. Rooms are laid course by course onto
+ * the row line the course above left behind (its skyline), and each room's number of steps (0, 1 or 2) is drawn
+ * from its width, so the count is decided per room and never runs to 3.
+ *
+ * <p>A course is laid in one go: its joints are drawn from every joint set that fits the skyline, each set weighted
+ * by how likely its rooms' widths are and how likely each room's count of skyline jogs is for its width. A joint
+ * may sit exactly on a jog of the skyline (the step is then the room above's alone, and the joint runs on from it),
+ * exactly on a joint of the course above (one joint through 2 courses), or clear of both. Then each room draws its
+ * class, given its width and the jogs it already has, and puts the steps it still needs into its bottom row line as
+ * jogs, some near its end as a deeper arm; some joints also put a jog under themselves, a step for the room below.
+ * Last, the bottom line's levels are drawn round the tile so it closes, every jog is at least a step and every cell
+ * keeps a sound height. Each draw of a class leans toward what the tile is short of for that width, and each course
+ * is drawn a few times to keep the tile's room count on its aim.
+ *
+ * <p>About one row line in every 0.8 H runs straight all round, the first among them. The last course's bottom line
+ * is the first line half a tile on, so that course, like any above a straight line, takes its steps from its
+ * skyline alone, and the course above it leaves it more jogs.
+ */
+final class SkylineBuilder implements TileBuilder {
+ private static final long SALT = 0x536B796C696E65L;
+ private static final int ATTEMPTS = 64;
+ /** Most draws of a course (4 times as many for the last); the first to meet the room aim, or else the nearest. */
+ private static final int DRAWS = 16;
+
+ /** Before the row lines jog, most courses are TALL and some THIN; their mean is {@link Look.Plan#courseUnits}. */
+ private static final int TALL_MIN = 17, TALL_MAX = 22, THIN_MIN = 10, THIN_MAX = 13;
+ private static final double THIN_SHARE = 0.2;
+ /** Room widths in steps: a bell round the mean with this spread (a share of the mean), plus a flat tail below. */
+ private static final double WIDTH_SPREAD = 0.22, WIDTH_TAIL = 0.25;
+ private static final int WIDTH_MIN = 10, WIDTH_MAX = 72;
+ /** How hard a room's class draw leans toward the classes its width has had too few of in the tile so far. */
+ private static final double DEAL = 1.5;
+ /**
+ * The share of a room's steps it takes from its skyline (the rest go into its bottom line), and the chance that a
+ * joint puts a jog under itself, a step for the room below. Over a course whose bottom line is straight, the
+ * FEED values: that course can only take steps from its skyline, so the course above leaves it more.
+ */
+ private static final double TOP_SHARE = 0.5, JOINT_JOG = 0.4, FEED_SHARE = 0.3, FEED_JOINT_JOG = 0.55;
+ /** The fewest jogs per H of a row line that is not straight. */
+ private static final double LINE_JOGS = 1.6;
+ /** Weights of a joint place on a jog of the skyline, on a jog under a joint above, and on a joint above. */
+ private static final double ON_JOG = 1, ON_JOINT_JOG = 0.15, THROUGH = 5.5;
+ /**
+ * How far a row line's levels may sit from its base, and the spread they are drawn with; and the spread of a
+ * course's height round its base height. In steps.
+ */
+ private static final int LEVEL_REACH = 10;
+ private static final double LEVEL_SPREAD = 10, HEIGHT_SPREAD = 12;
+ /** Relative weights of jog heights 0, 1, 2 ... steps; for an arm's jog, ARMS. */
+ private static final double[] JOGS = {0, 0, 4, 6, 8, 9, 10, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
+ private static final double[] ARMS = {0, 0, 0, 0, 0, 0, 1, 2, 4, 6, 8, 9, 10, 10, 9, 8, 6, 4, 2, 1};
+ /** Steps a jog keeps clear of joints and other jogs, unless in line with them. */
+ private static final int JOG_CLEAR = 5;
+ /** The share of single new jogs put near their room's end (at most ARM_REACH past the clearance): an arm. */
+ private static final double ARM_SHARE = 0.4;
+ private static final int ARM_REACH = 4;
+ /** Steps a cell is kept taller than the plan's least cross-section; the most a cell is ever tall. */
+ private static final int HEIGHT_EXTRA = 2, HEIGHT_MAX = 27;
+
+ @Override
+ public TileLayout build(Look.Plan plan) {
+ Random random = new Random(plan.seed ^ SALT);
+ for (int attempt = 0; attempt < ATTEMPTS; attempt++) {
+ TileLayout tile = new Attempt(plan, random).build();
+ if (tile != null) return tile;
+ }
+ throw new IllegalStateException("no layout for seed " + plan.seed);
+ }
+
+ /** A row line round the tile, y down, in steps. */
+ private static final class Line {
+ final int w;
+ /** Jog places, sorted, in [0, w); level[i] holds from at[i] to the next jog. With no jogs, level[0] alone. */
+ final int[] at, level;
+ /**
+ * Per place, what meets the line there from one side: {@link #JOG}, a {@link #JOINT}, a {@link #CUT} between
+ * 2 cells of a room (its step's edge runs the room's full height); and the places next to one, where nothing
+ * from the other side may end.
+ */
+ final int[] event;
+ final boolean[] near;
+ /** Jogs before each place of [0, 2w], places repeated a tile on. */
+ final int[] count;
+ static final int JOG = 1, JOINT = 2, CUT = 4;
+
+ Line(int w, int[] at, int[] level, int[] joints, int[] cuts) {
+ this.w = w;
+ this.at = at;
+ this.level = level;
+ event = new int[w];
+ for (int x : at) event[x] |= JOG;
+ for (int x : joints) event[x] |= JOINT;
+ for (int x : cuts) event[x] |= CUT;
+ near = new boolean[w];
+ for (int x = 0; x < w; x++) {
+ if (event[x] == 0) continue;
+ int reach = (event[x] & JOG) != 0 ? JOG_CLEAR - 1 : 1;
+ for (int d = -reach; d <= reach; d++) {
+ if (event[Math.floorMod(x + d, w)] == 0) near[Math.floorMod(x + d, w)] = true;
+ }
+ }
+ count = new int[2 * w + 1];
+ for (int x = 0; x < 2 * w; x++) count[x + 1] = count[x] + ((event[x % w] & JOG) != 0 ? 1 : 0);
+ }
+
+ int levelAt(int x) {
+ if (at.length == 0) return level[0];
+ int i = Arrays.binarySearch(at, Math.floorMod(x, w));
+ if (i < 0) i = -i - 2;
+ return level[i < 0 ? at.length - 1 : i];
+ }
+
+ /** Jogs strictly between x0 and x1, for 0 <= x0 < w and x0 < x1 <= x0 + w. */
+ int jogs(int x0, int x1) {
+ return count[x1] - count[x0 + 1];
+ }
+
+ boolean jog(int x) {
+ return (event[Math.floorMod(x, w)] & JOG) != 0;
+ }
+
+ /** The same line moved right by dx and down by dy, with the given joints and cuts meeting it. */
+ Line moved(int dx, int dy, int[] joints, int[] cuts) {
+ int m = at.length;
+ int[] a = new int[m], l = new int[Math.max(1, m)];
+ if (m == 0) l[0] = level[0] + dy;
+ Integer[] order = new Integer[m];
+ for (int i = 0; i < m; i++) order[i] = i;
+ Arrays.sort(order, (p, q) -> Integer.compare(Math.floorMod(at[p] + dx, w), Math.floorMod(at[q] + dx, w)));
+ for (int i = 0; i < m; i++) {
+ a[i] = Math.floorMod(at[order[i]] + dx, w);
+ l[i] = level[order[i]] + dy;
+ }
+ return new Line(w, a, l, shifted(joints, dx), shifted(cuts, dx));
+ }
+
+ private int[] shifted(int[] xs, int dx) {
+ int[] out = new int[xs.length];
+ for (int i = 0; i < xs.length; i++) out[i] = Math.floorMod(xs[i] + dx, w);
+ return out;
+ }
+ }
+
+ /** One try at a tile; {@link #build} gives null when a course or a row line finds no fit. */
+ private static final class Attempt {
+ final Random random;
+ final double unit;
+ final int w, h, s, n, minHeight;
+ final int[] base;
+ final double[] widthWeight;
+ final Line[] lines;
+ final int[][] joints;
+ /** Row lines with no jogs; line 0 always. */
+ final boolean[] straight;
+ /** The tile's aim for its room count. */
+ final int roomAim;
+ /** {@link Look.Plan#stepsByWidth}. */
+ final double[][] classes;
+ /** Rooms so far per width band (under 0.3 H, 0.3 to 0.5 H, over 0.5 H), and per band and step count. */
+ final int[] seen = new int[3];
+ final int[][] dealt = new int[3][3];
+ /** Per band, the shares of 0, 1 and 2 steps leaned toward what the band is short of. */
+ final double[][] lean = new double[3][3];
+ /** The last course's bottom line: the first line half a tile on, with course 0's joints and cuts on it. */
+ Line last;
+
+ Attempt(Look.Plan plan, Random random) {
+ this.random = random;
+ classes = plan.stepsByWidth;
+ unit = plan.unitH;
+ w = plan.tileWUnits;
+ h = plan.tileHUnits;
+ s = w / 2;
+ n = Math.max(2, (int) Math.round(h / plan.courseUnits));
+ int cross = (int) Math.ceil((double) plan.minCrossH / plan.unitH - 1e-3);
+ minHeight = Math.max(cross, plan.minStepUnits) + HEIGHT_EXTRA;
+ if (w < WIDTH_MAX + WIDTH_MIN || h < n * THIN_MIN) {
+ throw new IllegalArgumentException("tile " + w + " x " + h);
+ }
+ base = new int[n + 1];
+ int[] height = courseHeights();
+ base[0] = LEVEL_REACH;
+ for (int k = 0; k < n; k++) base[k + 1] = base[k] + height[k];
+ widthWeight = widths(n * (double) w / (plan.roomsPerH2 * w * h * unit * unit));
+ lines = new Line[n];
+ joints = new int[n][];
+ straight = new boolean[n];
+ int count = Math.max(1, (int) Math.round(h * unit / plan.straightEveryH));
+ for (int i = 0; i < count; i++) straight[(int) Math.round((double) i * n / count) % n] = true;
+ roomAim = (int) Math.round(plan.roomsPerH2 * w * h * unit * unit);
+ for (int b = 0; b < 3; b++) leanBand(b);
+ }
+
+ TileLayout build() {
+ lines[0] = new Line(w, new int[0], new int[] {base[0]}, new int[0], new int[0]);
+ int rooms = 0;
+ for (int k = 0; k < n; k++) {
+ int aim = (int) Math.round((double) (roomAim - rooms) / (n - k));
+ int[] js = lay(k, aim);
+ if (js == null) return null;
+ joints[k] = js;
+ rooms += js.length;
+ if (k == 0) last = lines[0].moved(s, h, js, new int[0]);
+ if (k < n - 1 && !nextLine(k)) return null;
+ if (k == 0) last = lines[0].moved(s, h, js, cuts(lines[0], lines[1], js));
+ }
+ return emit();
+ }
+
+ /** A straight line with nothing on it yet: what a course over a straight line sees below it. */
+ private Line flat() {
+ return new Line(w, new int[0], new int[] {0}, new int[0], new int[0]);
+ }
+
+ /** Where a course's rooms are cut: at every jog of its 2 row lines that is not at one of its joints. */
+ private int[] cuts(Line top, Line bottom, int[] js) {
+ boolean[] cut = new boolean[w];
+ for (int x : top.at) cut[x] = true;
+ for (int x : bottom.at) cut[x] = true;
+ for (int x : js) cut[x] = false;
+ IntList out = new IntList();
+ for (int x = 0; x < w; x++) if (cut[x]) out.add(x);
+ return out.array();
+ }
+
+ /** Base heights round the tile, summing to h. */
+ private int[] courseHeights() {
+ int[] height = new int[n];
+ int sum = 0;
+ for (int k = 0; k < n; k++) {
+ boolean thin = random.nextDouble() < THIN_SHARE;
+ height[k] = thin ? THIN_MIN + random.nextInt(THIN_MAX - THIN_MIN + 1)
+ : TALL_MIN + random.nextInt(TALL_MAX - TALL_MIN + 1);
+ sum += height[k];
+ }
+ int least = THIN_MIN, most = TALL_MAX + LEVEL_REACH;
+ for (int guard = 0; sum != h && guard < 100 * h; guard++) {
+ int k = random.nextInt(n), d = sum < h ? 1 : -1;
+ if (height[k] + d < least || height[k] + d > most) continue;
+ height[k] += d;
+ sum += d;
+ }
+ if (sum != h) throw new IllegalArgumentException("courses do not fit " + h);
+ return height;
+ }
+
+ /** Relative weights of room widths, for a mean width of about {@code mean}. */
+ private static double[] widths(double mean) {
+ double[] weight = new double[WIDTH_MAX + 1];
+ double spread = WIDTH_SPREAD * mean, total = 0;
+ for (int x = WIDTH_MIN; x <= WIDTH_MAX; x++) {
+ double z = (x - mean) / spread;
+ weight[x] = (1 - WIDTH_TAIL) * Math.exp(-z * z / 2) / (spread * Math.sqrt(2 * Math.PI))
+ + (x < mean ? WIDTH_TAIL / (mean - WIDTH_MIN) : 0);
+ total += weight[x];
+ }
+ for (int x = WIDTH_MIN; x <= WIDTH_MAX; x++) weight[x] /= total;
+ return weight;
+ }
+
+ /** True when course k's bottom line is set before it is laid: straight, or the first line half a tile on. */
+ private boolean fixedBottom(int k) {
+ return k == n - 1 || straight[k + 1];
+ }
+
+ /** The share of course k's steps its rooms take from their skyline. */
+ private double share(int k) {
+ if (lines[k].at.length == 0) return 0;
+ return k + 1 < n && fixedBottom(k + 1) ? FEED_SHARE : TOP_SHARE;
+ }
+
+ private int band(int width) {
+ double x = width * unit;
+ return x < 0.3 ? 0 : x <= 0.5 ? 1 : 2;
+ }
+
+ private double[] classes(int width) {
+ return lean[band(width)];
+ }
+
+ /** Counts a room of this width with m steps, and leans its band's shares again. */
+ private void deal(int width, int m) {
+ int b = band(width);
+ seen[b]++;
+ dealt[b][m]++;
+ leanBand(b);
+ }
+
+ private void leanBand(int b) {
+ for (int m = 0; m < 3; m++) {
+ lean[b][m] = classes[b][m] * Math.exp(DEAL * (seen[b] * classes[b][m] - dealt[b][m]));
+ }
+ }
+
+ /** The chance that t of a room's n steps come from its skyline. */
+ private static double split(double top, int t, int n) {
+ if (t > n) return 0;
+ double c = n == 2 && t == 1 ? 2 : 1;
+ return c * Math.pow(top, t) * Math.pow(1 - top, n - t);
+ }
+
+ /**
+ * Course k's joints, sorted: of up to {@link #DRAWS} draws round the tile, each in proportion to its weight,
+ * the first with {@code aim} rooms or else the nearest; null when none fit.
+ */
+ private int[] lay(int k, int aim) {
+ Line top = lines[k];
+ Line bottom = k == n - 1 ? last : straight[k + 1] ? flat() : null;
+ double share = share(k);
+ double[] place = new double[w];
+ double placeTotal = 0;
+ for (int x = 0; x < w; x++) {
+ place[x] = placeWeight(top, x);
+ if (bottom != null) place[x] *= placeWeight(bottom, x) * overlap(top, bottom, x);
+ placeTotal += place[x];
+ }
+ if (placeTotal == 0) return null;
+ double[][] room = new double[w][WIDTH_MAX + 1];
+ for (int x = 0; x < w; x++) {
+ for (int d = WIDTH_MIN; d <= WIDTH_MAX; d++) room[x][d] = room(top, bottom, share, x, d);
+ }
+ int[] best = null;
+ int draws = k == n - 1 ? 4 * DRAWS : DRAWS;
+ for (int draw = 0; draw < draws && (best == null || best.length != aim); draw++) {
+ int[] js = chain(place, placeTotal, room);
+ if (js != null && (best == null || Math.abs(js.length - aim) < Math.abs(best.length - aim))) best = js;
+ }
+ return best;
+ }
+
+ /** One draw of joints round the tile: a first joint, then the rest over all chains of rooms back to it. */
+ private int[] chain(double[] place, double placeTotal, double[][] room) {
+ double pick = random.nextDouble() * placeTotal;
+ int p0 = 0;
+ while (p0 < w - 1 && (pick -= place[p0]) > 0) p0++;
+ if (place[p0] == 0) return null;
+ double[] chain = new double[w + 1];
+ chain[0] = 1;
+ for (int i = 1; i <= w; i++) {
+ double weight = i == w ? 1 : place[(p0 + i) % w];
+ if (weight == 0) continue;
+ double sum = 0;
+ for (int d = WIDTH_MIN; d <= Math.min(WIDTH_MAX, i); d++) {
+ sum += chain[i - d] * room[(p0 + i - d) % w][d];
+ }
+ chain[i] = weight * sum;
+ }
+ if (!(chain[w] > 0)) return null;
+ IntList out = new IntList();
+ double[] odds = new double[WIDTH_MAX + 1];
+ for (int i = w; i > 0; ) {
+ Arrays.fill(odds, 0);
+ for (int d = WIDTH_MIN; d <= Math.min(WIDTH_MAX, i); d++) {
+ odds[d] = chain[i - d] * room[(p0 + i - d) % w][d];
+ }
+ int d = draw(odds);
+ if (d < 0) return null;
+ i -= d;
+ out.add((p0 + i) % w);
+ }
+ int[] js = out.array();
+ Arrays.sort(js);
+ return js;
+ }
+
+ /** A joint's weight at x against one row line: 0 next to what meets the line, more on some of it. */
+ private double placeWeight(Line line, int x) {
+ if (line.near[x]) return 0;
+ int e = line.event[x];
+ if ((e & Line.JOG) != 0) return (e & Line.JOINT) != 0 ? ON_JOINT_JOG : ON_JOG;
+ return (e & Line.JOINT) != 0 ? THROUGH : 1;
+ }
+
+ /** 0 where a joint at x would sit on a jog of both lines with too little of a cell's side between them. */
+ private int overlap(Line top, Line bottom, int x) {
+ if (!top.jog(x) || !bottom.jog(x)) return 1;
+ int upper = Math.max(top.levelAt(x - 1), top.levelAt(x));
+ int lower = Math.min(bottom.levelAt(x - 1), bottom.levelAt(x));
+ return lower - upper >= minHeight ? 1 : 0;
+ }
+
+ /** The weight of a room from x0, d wide: its width and its count of steps for that width. */
+ private double room(Line top, Line bottom, double share, int x0, int d) {
+ int x = Math.floorMod(x0, w), t = top.jogs(x, x + d);
+ if (t > 2) return 0;
+ double[] c = classes(d);
+ if (bottom == null) {
+ double sum = 0;
+ for (int m = t; m <= 2; m++) sum += c[m] * split(share, t, m);
+ return widthWeight[d] * sum;
+ }
+ int b = bottom.jogs(x, x + d);
+ if (t + b > 2) return 0;
+ if (t == 1 && b == 1 && !apart(top, bottom, x, x + d)) return 0;
+ return widthWeight[d] * c[t + b];
+ }
+
+ /** True when a room's one skyline jog and one bottom jog are a cell apart or in line with room to join. */
+ private boolean apart(Line top, Line bottom, int x0, int x1) {
+ int a = -1, b = -1;
+ for (int x = x0 + 1; x < x1; x++) {
+ if (top.jog(x)) a = x;
+ if (bottom.jog(x)) b = x;
+ }
+ if (a == b) return overlap(top, bottom, a) == 1;
+ return Math.abs(a - b) >= JOG_CLEAR;
+ }
+
+ /** Course k's rooms take their classes and put their bottom jogs into line k + 1; then its levels. */
+ private boolean nextLine(int k) {
+ Line top = lines[k];
+ int[] js = joints[k];
+ double share = share(k);
+ boolean[] jog = new boolean[w], arms = new boolean[w];
+ // a straight line takes no jogs: its rooms above took all their steps from their skyline
+ for (int i = 0; i < js.length; i++) {
+ int x0 = js[i], x1 = i + 1 < js.length ? js[i + 1] : js[0] + w, d = x1 - x0, t = top.jogs(x0, x1);
+ if (straight[k + 1]) {
+ deal(d, t);
+ continue;
+ }
+ IntList free = new IntList();
+ for (int x = x0 + JOG_CLEAR; x <= x1 - JOG_CLEAR; x++) {
+ boolean clear = !top.near[x % w] && (k + 1 < n - 1 || !last.near[x % w]);
+ for (int y = x - JOG_CLEAR + 1; y < x + JOG_CLEAR && clear; y++) clear = !top.jog(y);
+ if (clear) free.add(x);
+ }
+ double[] c = classes(d), odds = new double[3];
+ double total = 0;
+ for (int m = t; m <= 2; m++) {
+ boolean fits = m - t == 0 || (m - t == 1 && free.size > 0)
+ || (m - t == 2 && free.size > 0 && free.get(free.size - 1) - free.get(0) >= JOG_CLEAR);
+ odds[m] = fits ? c[m] * split(share, t, m) : 0;
+ total += odds[m];
+ }
+ int m = t;
+ if (total > 0) {
+ double r = random.nextDouble() * total;
+ for (m = t; m < 2 && (r -= odds[m]) > 0; ) m++;
+ while (odds[m] == 0) m--;
+ }
+ deal(d, m);
+ if (m - t == 1) {
+ IntList arm = new IntList();
+ for (int a = 0; a < free.size; a++) {
+ int x = free.get(a);
+ if (Math.min(x - x0, x1 - x) <= JOG_CLEAR + ARM_REACH) arm.add(x);
+ }
+ boolean deep = arm.size > 0 && random.nextDouble() < ARM_SHARE;
+ IntList from = deep ? arm : free;
+ int x = from.get(random.nextInt(from.size)) % w;
+ jog[x] = true;
+ arms[x] = deep;
+ }
+ if (m - t == 2) {
+ // a pair drawn evenly from the pairs a cell apart
+ IntList pairs = new IntList();
+ for (int a = 0; a < free.size; a++) {
+ for (int b = a + 1; b < free.size; b++) {
+ if (free.get(b) - free.get(a) >= JOG_CLEAR) pairs.add(a * free.size + b);
+ }
+ }
+ int pair = pairs.get(random.nextInt(pairs.size));
+ jog[free.get(pair / free.size) % w] = true;
+ jog[free.get(pair % free.size) % w] = true;
+ }
+ }
+ // jogs under joints: a step for the room below
+ IntList under = new IntList();
+ for (int x : js) {
+ if (!top.jog(x) && (k + 1 < n - 1 || !last.near[x])) under.add(x);
+ }
+ for (int i = 0; i < under.size && !straight[k + 1]; i++) {
+ if (random.nextDouble() < (fixedBottom(k + 1) ? FEED_JOINT_JOG : JOINT_JOG)) jog[under.get(i)] = true;
+ }
+ int count = 0;
+ for (boolean b : jog) if (b) count++;
+ // a line that is not straight jogs a few times at least (and never once: it could not close)
+ while (!straight[k + 1] && count < Math.max(2, Math.round(LINE_JOGS * w * unit))) {
+ IntList spare = new IntList();
+ for (int i = 0; i < under.size; i++) if (!jog[under.get(i)]) spare.add(under.get(i));
+ if (spare.size == 0) break;
+ jog[spare.get(random.nextInt(spare.size))] = true;
+ count++;
+ }
+ if (count == 1) return false;
+ IntList at = new IntList();
+ for (int x = 0; x < w; x++) if (jog[x]) at.add(x);
+ boolean[] deep = new boolean[at.size];
+ for (int i = 0; i < at.size; i++) deep[i] = arms[at.get(i)];
+ int[] level = levels(k + 1, at.array(), deep);
+ if (level == null) return false;
+ Line next = new Line(w, at.array(), level, new int[0], new int[0]);
+ lines[k + 1] = new Line(w, next.at, level, js, cuts(top, next, js));
+ return true;
+ }
+
+ /** Levels for row line j between jogs at the given places, drawn round the tile; null when none fit. */
+ private int[] levels(int j, int[] at, boolean[] deep) {
+ int m = at.length, reach = LEVEL_REACH, size = 2 * reach + 1, y = base[j];
+ Line above = lines[j - 1];
+ boolean lastLine = j == n - 1;
+ int segments = Math.max(1, m);
+ // per segment, the levels the cells above and below it allow, and the course height it would give
+ int[] lo = new int[segments], hi = new int[segments];
+ double[] mean = new double[segments];
+ for (int i = 0; i < segments; i++) {
+ int x0 = m == 0 ? 0 : at[i], x1 = m == 0 ? w : i + 1 < m ? at[i + 1] : at[0] + w;
+ int deepest = Integer.MIN_VALUE, shallowest = Integer.MAX_VALUE;
+ int highest = Integer.MAX_VALUE, lowest = Integer.MIN_VALUE;
+ for (int x = x0; x < x1; x++) {
+ int top = above.levelAt(x);
+ deepest = Math.max(deepest, top);
+ shallowest = Math.min(shallowest, top);
+ mean[i] += top / (double) (x1 - x0);
+ if (lastLine) {
+ highest = Math.min(highest, last.levelAt(x));
+ lowest = Math.max(lowest, last.levelAt(x));
+ }
+ }
+ lo[i] = deepest + minHeight;
+ hi[i] = Math.min(lastLine ? highest - minHeight : base[j + 1] + reach - minHeight,
+ shallowest + HEIGHT_MAX);
+ if (lastLine) lo[i] = Math.max(lo[i], lowest - HEIGHT_MAX);
+ }
+ double[][] weight = new double[segments][size];
+ int course = base[j] - base[j - 1];
+ for (int i = 0; i < segments; i++) {
+ for (int v = 0; v < size; v++) {
+ int level = y - reach + v;
+ double z = (level - y) / LEVEL_SPREAD, zh = (level - mean[i] - course) / HEIGHT_SPREAD;
+ weight[i][v] = level >= lo[i] && level <= hi[i] ? Math.exp(-(z * z + zh * zh) / 2) : 0;
+ }
+ }
+ if (m == 0) {
+ int v = draw(weight[0]);
+ return v < 0 ? null : new int[] {y - reach + v};
+ }
+ // forward over the cycle for each first level, then draw the first level and walk back
+ double[][][] f = new double[size][][];
+ double[] first = new double[size];
+ for (int v0 = 0; v0 < size; v0++) {
+ if (weight[0][v0] == 0) continue;
+ double[][] g = new double[m][size];
+ g[0][v0] = weight[0][v0];
+ for (int i = 1; i < m; i++) {
+ for (int v = 0; v < size; v++) {
+ if (weight[i][v] == 0) continue;
+ double sum = 0;
+ for (int u = 0; u < size; u++) if (g[i - 1][u] > 0) sum += g[i - 1][u] * jog(u, v, deep[i]);
+ g[i][v] = weight[i][v] * sum;
+ }
+ }
+ double sum = 0;
+ for (int u = 0; u < size; u++) sum += g[m - 1][u] * jog(u, v0, deep[0]);
+ first[v0] = sum;
+ f[v0] = g;
+ }
+ int v0 = draw(first);
+ if (v0 < 0) return null;
+ int[] out = new int[m];
+ out[0] = v0;
+ int next = v0;
+ for (int i = m - 1; i >= 1; i--) {
+ double[] odds = new double[size];
+ for (int u = 0; u < size; u++) odds[u] = f[v0][i][u] * jog(u, next, deep[(i + 1) % m]);
+ next = draw(odds);
+ out[i] = next;
+ }
+ for (int i = 0; i < m; i++) out[i] += y - reach;
+ return out;
+ }
+
+ private static double jog(int u, int v, boolean arm) {
+ double[] table = arm ? ARMS : JOGS;
+ int d = Math.abs(u - v);
+ return d < table.length ? table[d] : 0;
+ }
+
+ /** An index drawn in proportion to its weight; -1 when all are 0. */
+ private int draw(double[] odds) {
+ double total = 0;
+ for (double o : odds) total += o;
+ if (!(total > 0)) return -1;
+ double r = random.nextDouble() * total;
+ int i = 0;
+ while (i < odds.length - 1 && (r -= odds[i]) > 0) i++;
+ while (odds[i] == 0) i--;
+ return i;
+ }
+
+ /** Cells: each room cut at its steps, as tall as its course is there. */
+ private TileLayout emit() {
+ IntList x0s = new IntList(), y0s = new IntList(), x1s = new IntList(), y1s = new IntList();
+ IntList rooms = new IntList();
+ int room = 0;
+ for (int k = 0; k < n; k++) {
+ Line top = lines[k], bottom = k < n - 1 ? lines[k + 1] : last;
+ int[] js = joints[k];
+ for (int i = 0; i < js.length; i++, room++) {
+ int x0 = js[i], x1 = i + 1 < js.length ? js[i + 1] : js[0] + w;
+ int from = x0;
+ for (int x = x0 + 1; x <= x1; x++) {
+ if (x < x1 && !top.jog(x) && !bottom.jog(x)) continue;
+ x0s.add(from);
+ x1s.add(x);
+ y0s.add(top.levelAt(from));
+ y1s.add(bottom.levelAt(from));
+ rooms.add(room);
+ from = x;
+ }
+ }
+ }
+ return new TileLayout(w, h, room, x0s.array(), y0s.array(), x1s.array(), y1s.array(), rooms.array());
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileBuilder.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileBuilder.java
new file mode 100644
index 000000000..ccdbcca1a
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileBuilder.java
@@ -0,0 +1,6 @@
+package io.github.pbanddev.tatami;
+
+/** Makes the static layout of one tile: its rows, joints and steps. Everything that moves is the plan's. */
+interface TileBuilder {
+ TileLayout build(Look.Plan plan);
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileGraph.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileGraph.java
new file mode 100644
index 000000000..a7f543713
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileGraph.java
@@ -0,0 +1,557 @@
+package io.github.pbanddev.tatami;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The static shape of a {@link TileLayout}, worked out once and checked: the lines its cells sit on, the wall pieces
+ * on those lines, the groups of lines that move as one, and the rules that keep every rest state of the motion
+ * valid. Sizes and places are whole steps.
+ *
+ * <p>Places are on the plane with the tile's copy (0, 0) at the origin; copy (i, j) sits at
+ * {@code (i * width + j * shift, j * height)}. At time t, a cell's edge or a piece's end is at its place here plus
+ * the offset of the group its line moves with ({@link TileMotion}).
+ *
+ * <ul>
+ * <li><b>Lines:</b> maximal straight runs of cell edges, followed across the tile's seams. A row line that runs
+ * all the way round is one periodic line.</li>
+ * <li><b>Pieces:</b> the stretches of a line between the same 2 rooms, merged, and listed once per tile.</li>
+ * <li><b>Rules:</b> each says {@code gap + offset[hi] - offset[lo] >= min} for 2 groups: every cell's width and
+ * height and every room's width (each at least {@link Look.Motion#keepShare} of its size at home), every step
+ * and T-offset (2 lines that end on a third from its 2 sides), every door host's length. They hold at home.
+ * Any offsets that keep them keep every line's order, so the cells still tile the plane and rooms keep their
+ * neighbours. {@link TileMotion} keeps them at every moment of every glide.</li>
+ * <li><b>Groups:</b> lines glued to move as one. A rule with less than {@link #GLUE_SLACK} to spare at home glues
+ * its 2 lines, so thin cells, small steps and short door hosts move whole instead of standing still.</li>
+ * </ul>
+ */
+final class TileGraph {
+ /** Rules with less slack than this at home glue their 2 lines into one group. */
+ static final int GLUE_SLACK = 3;
+ /** How far along its length a line looks for another to line up with, and the most it keeps. */
+ private static final int ALIGN_REACH = 40, ALIGN_PARTNERS = 6;
+
+ final int width, height, shift, rooms, cells;
+ /** Least cell height and room width, least step, least cell width, least door host, farthest offset: steps. */
+ final int minCross, minStep, minCell, hostMin, maxUnits;
+ /** The share of its size at home that a cell's width or height or a room's width always keeps. */
+ private final float keepShare;
+ final int[] cellX0, cellY0, cellX1, cellY1, cellRoom;
+ /** The group each cell edge moves with. */
+ final int[] cellLeft, cellRight, cellTop, cellBottom;
+ /** Room r's cells: roomCellList[roomCellStart[r] .. roomCellStart[r + 1]). */
+ final int[] roomCellStart, roomCellList;
+ /** Lower bounds of a one-cell room's width and height at any time; -1 for a room of more cells. */
+ final int[] roomMinW, roomMinH;
+
+ final int lines;
+ final boolean[] lineVertical, linePeriodic;
+ /** A line's place across (x for a vertical line) and its ends along it, on the plane at home. */
+ final int[] lineAt, lineFrom, lineTo, lineGroup;
+
+ final int pieces, pairs;
+ final boolean[] pieceVertical;
+ final int[] pieceAt, pieceFrom, pieceTo, pieceLine, pieceGroup, pieceFromGroup, pieceToGroup;
+ /** The room ids on its low side (left of it, or above it) and high side; its pair of rooms. */
+ final int[] pieceRoomA, pieceRoomB, piecePair;
+ /** A lower bound of its length at any time. */
+ final int[] pieceMinLength;
+ /** True for the pieces that may hold a door ({@link TilePlan#doorHosts}). */
+ final boolean[] pieceHost;
+
+ final int groups;
+ /** Wall length on a group's lines, per tile, at home. 0: moving it would show nothing. */
+ final int[] groupLength;
+ final int[] ruleHi, ruleLo, ruleGap, ruleMin;
+ /** The rules on group g: ruleList[ruleStart[g] .. ruleStart[g + 1]). */
+ final int[] ruleStart, ruleList;
+ /** Lines group g may line up with: group alignGroup[a] sits alignDelta[a] steps past it, a from alignStart[g]. */
+ final int[] alignStart, alignGroup, alignDelta;
+
+ /** Per unit square of the tile, the cell that covers it, and that cell's copy (packed). */
+ private final int[] squareCell, squareCopy;
+
+ TileGraph(TileLayout tile, Look look) {
+ Look.Plan plan = look.plan;
+ width = tile.width;
+ height = tile.height;
+ shift = tile.shift;
+ rooms = tile.rooms;
+ cells = tile.cells();
+ cellX0 = tile.cellX0;
+ cellY0 = tile.cellY0;
+ cellX1 = tile.cellX1;
+ cellY1 = tile.cellY1;
+ cellRoom = tile.cellRoom;
+ minCross = steps((double) plan.minCrossH / plan.unitH);
+ minStep = plan.minStepUnits;
+ minCell = plan.minCellUnits;
+ hostMin = steps((double) look.doors.hostBars * look.doors.lengthH / plan.unitH);
+ maxUnits = look.motion.maxUnits;
+ keepShare = look.motion.keepShare;
+ if (minStep < 1 || minCell < 1 || minCross < 1 || maxUnits < 1 || !(keepShare >= 0 && keepShare < 1)) {
+ throw new IllegalArgumentException("minimums");
+ }
+
+ // the plane at home: every unit square of the tile covered by exactly one cell copy
+ int n = width * height;
+ squareCell = new int[n];
+ squareCopy = new int[n];
+ Arrays.fill(squareCell, -1);
+ for (int c = 0; c < cells; c++) {
+ for (int y = cellY0[c]; y < cellY1[c]; y++) {
+ int j = Math.floorDiv(y, height), yb = y - j * height;
+ for (int x = cellX0[c]; x < cellX1[c]; x++) {
+ int xr = x - j * shift, i = Math.floorDiv(xr, width), k = xr - i * width + yb * width;
+ if (squareCell[k] >= 0) {
+ throw new IllegalArgumentException("cells " + squareCell[k] + " and " + c + " overlap at " + x + ", " + y);
+ }
+ squareCell[k] = c;
+ squareCopy[k] = pack(-i, -j);
+ }
+ }
+ }
+ for (int k = 0; k < n; k++) {
+ if (squareCell[k] < 0) throw new IllegalArgumentException("no cell covers " + k % width + ", " + k / width);
+ }
+
+ // rooms: 1 to 3 cells that join along edges
+ roomCellStart = new int[rooms + 1];
+ for (int c = 0; c < cells; c++) roomCellStart[cellRoom[c] + 1]++;
+ for (int r = 0; r < rooms; r++) roomCellStart[r + 1] += roomCellStart[r];
+ roomCellList = new int[cells];
+ int[] fill = Arrays.copyOf(roomCellStart, rooms);
+ for (int c = 0; c < cells; c++) roomCellList[fill[cellRoom[c]]++] = c;
+ for (int r = 0; r < rooms; r++) checkRoom(r);
+
+ // lines: maximal straight runs of edges between 2 cell copies, followed across the seams
+ int[] vLine = new int[n], hLine = new int[n];
+ Arrays.fill(vLine, -1);
+ Arrays.fill(hLine, -1);
+ IntList lv = new IntList(), la = new IntList(), lf = new IntList(), lt = new IntList(), lp = new IntList();
+ for (int pass = 0; pass < 2; pass++) {
+ boolean vertical = pass == 0;
+ int[] of = vertical ? vLine : hLine;
+ for (int k = 0; k < n; k++) {
+ int x = k % width, y = k / width, at = vertical ? x : y, a0 = vertical ? y : x;
+ if (of[k] >= 0 || !edge(vertical, at, a0)) continue;
+ int id = lv.size;
+ of[k] = id;
+ boolean periodic = false;
+ int a = a0 + 1;
+ for (; edge(vertical, at, a); a++) {
+ int e = edgeIndex(vertical, at, a);
+ if (e == k) {
+ periodic = true;
+ break;
+ }
+ of[e] = id;
+ if (a - a0 > n) throw new IllegalArgumentException("a line runs on for good");
+ }
+ int to = a, from = a0;
+ if (!periodic) {
+ for (a = a0 - 1; edge(vertical, at, a); a--) {
+ of[edgeIndex(vertical, at, a)] = id;
+ if (a0 - a > n) throw new IllegalArgumentException("a line runs on for good");
+ }
+ from = a + 1;
+ }
+ lv.add(vertical ? 1 : 0);
+ la.add(at);
+ lf.add(from);
+ lt.add(to);
+ lp.add(periodic ? 1 : 0);
+ }
+ }
+ lines = lv.size;
+ lineVertical = new boolean[lines];
+ linePeriodic = new boolean[lines];
+ for (int l = 0; l < lines; l++) {
+ lineVertical[l] = lv.get(l) == 1;
+ linePeriodic[l] = lp.get(l) == 1;
+ }
+ lineAt = la.array();
+ lineFrom = lf.array();
+ lineTo = lt.array();
+
+ // the lines of every cell edge
+ int[] left = new int[cells], right = new int[cells], top = new int[cells], bottom = new int[cells];
+ for (int c = 0; c < cells; c++) {
+ left[c] = vLine[index(cellX0[c], cellY0[c])];
+ right[c] = vLine[index(cellX1[c], cellY0[c])];
+ top[c] = hLine[index(cellX0[c], cellY0[c])];
+ bottom[c] = hLine[index(cellX0[c], cellY1[c])];
+ }
+
+ // rules between lines (hi, lo, gap, min), then pieces with their T-offset and step rules
+ IntList rHi = new IntList(), rLo = new IntList(), rGap = new IntList(), rMin = new IntList();
+ for (int c = 0; c < cells; c++) {
+ boolean alone = roomCellStart[cellRoom[c] + 1] - roomCellStart[cellRoom[c]] == 1;
+ int w = cellX1[c] - cellX0[c], h = cellY1[c] - cellY0[c];
+ rule(rHi, rLo, rGap, rMin, right[c], left[c], w, kept(w, alone ? Math.max(minCell, minCross) : minCell),
+ "cell " + c + " width");
+ rule(rHi, rLo, rGap, rMin, bottom[c], top[c], h, kept(h, minCross), "cell " + c + " height");
+ }
+ for (int r = 0; r < rooms; r++) {
+ if (roomCellStart[r + 1] - roomCellStart[r] < 2) continue;
+ int lo = -1, hi = -1;
+ for (int i = roomCellStart[r]; i < roomCellStart[r + 1]; i++) {
+ int c = roomCellList[i];
+ if (lo < 0 || cellX0[c] < cellX0[lo]) lo = c;
+ if (hi < 0 || cellX1[c] > cellX1[hi]) hi = c;
+ }
+ int w = cellX1[hi] - cellX0[lo];
+ rule(rHi, rLo, rGap, rMin, right[hi], left[lo], w, kept(w, minCross), "room " + r + " width");
+ }
+ IntList pv = new IntList(), pa = new IntList(), pf = new IntList(), pt = new IntList(), pl = new IntList(),
+ pfl = new IntList(), ptl = new IntList(), pra = new IntList(), prb = new IntList(), pp = new IntList();
+ Map<Long, Integer> pairOf = new HashMap<>();
+ IntList evAt = new IntList(), evLine = new IntList(), evSide = new IntList();
+ for (int l = 0; l < lines; l++) {
+ boolean v = lineVertical[l];
+ int at = lineAt[l], from = lineFrom[l], to = lineTo[l], period = to - from;
+ boolean periodic = linePeriodic[l];
+ int end = periodic ? from + 2 * period : to;
+ int[] perp = v ? hLine : vLine;
+ // events: lines that end on this one or cross it, by side (1 low, 2 high, 3 both)
+ evAt.size = 0;
+ evLine.size = 0;
+ evSide.size = 0;
+ for (int a = from; a <= end; a++) {
+ boolean low = edge(!v, a, at - 1), high = edge(!v, a, at);
+ if (!low && !high) continue;
+ evAt.add(a);
+ evLine.add(perp[edgeIndex(!v, a, low ? at - 1 : at)]);
+ evSide.add((low ? 1 : 0) | (high ? 2 : 0));
+ }
+ if (!periodic && (evAt.size == 0 || evAt.get(0) != from || evAt.get(evAt.size - 1) != to)) {
+ throw new IllegalArgumentException("line " + l + " has a loose end");
+ }
+ for (int e = 0; e + 1 < evAt.size && (!periodic || evAt.get(e) < from + period); e++) {
+ if ((evSide.get(e) | evSide.get(e + 1)) == 3 && evSide.get(e) != 3 && evSide.get(e + 1) != 3) {
+ rule(rHi, rLo, rGap, rMin, evLine.get(e + 1), evLine.get(e), evAt.get(e + 1) - evAt.get(e), minStep,
+ (v ? "x " : "y ") + at + " near " + evAt.get(e) + ": a step or T-offset");
+ }
+ }
+ // pieces: runs of wall between the same 2 room copies; a periodic line starts where its rooms change
+ int a0 = from, a1 = to;
+ if (periodic) {
+ a0 = -1;
+ for (int a = from; a < from + period && a0 < 0; a++) {
+ if (sideRoom(v, at, a, 0) != sideRoom(v, at, a - 1, 0) || sideRoom(v, at, a, 1) != sideRoom(v, at, a - 1, 1)) {
+ a0 = a;
+ }
+ }
+ a1 = a0 + period;
+ }
+ long runA = 0, runB = 0;
+ int start = Integer.MIN_VALUE;
+ for (int a = a0; a <= a1; a++) {
+ long ra = a < a1 ? sideRoom(v, at, a, 0) : 0, rb = a < a1 ? sideRoom(v, at, a, 1) : 0;
+ boolean wall = a < a1 && ra != rb;
+ boolean same = wall && start != Integer.MIN_VALUE && ra == runA && rb == runB;
+ if (start != Integer.MIN_VALUE && !same) {
+ pv.add(v ? 1 : 0);
+ pa.add(at);
+ pf.add(start);
+ pt.add(a);
+ pl.add(l);
+ pfl.add(eventLine(evAt, evLine, start));
+ ptl.add(eventLine(evAt, evLine, a));
+ pra.add((int) (runA >>> 32));
+ prb.add((int) (runB >>> 32));
+ long key = pairKey(runA, runB);
+ Integer pair = pairOf.get(key);
+ if (pair == null) {
+ pair = pairOf.size();
+ pairOf.put(key, pair);
+ }
+ pp.add(pair);
+ start = Integer.MIN_VALUE;
+ }
+ if (wall && start == Integer.MIN_VALUE) {
+ start = a;
+ runA = ra;
+ runB = rb;
+ }
+ }
+ }
+ pieces = pv.size;
+ pairs = pairOf.size();
+ pieceVertical = new boolean[pieces];
+ for (int p = 0; p < pieces; p++) pieceVertical[p] = pv.get(p) == 1;
+ pieceAt = pa.array();
+ pieceFrom = pf.array();
+ pieceTo = pt.array();
+ pieceLine = pl.array();
+ pieceRoomA = pra.array();
+ pieceRoomB = prb.array();
+ piecePair = pp.array();
+ int[] pieceFromLine = pfl.array(), pieceToLine = ptl.array();
+
+ pieceHost = TilePlan.doorHosts(this, look);
+ for (int p = 0; p < pieces; p++) {
+ if (pieceHost[p]) {
+ rule(rHi, rLo, rGap, rMin, pieceToLine[p], pieceFromLine[p], pieceTo[p] - pieceFrom[p], hostMin, "door host " + p);
+ }
+ }
+
+ // groups: lines glued where a rule has little slack, tightest first
+ int rules = rHi.size;
+ int[] parent = new int[lines];
+ for (int l = 0; l < lines; l++) parent[l] = l;
+ Integer[] bySlack = new Integer[rules];
+ for (int r = 0; r < rules; r++) bySlack[r] = r;
+ Arrays.sort(bySlack, (a, b) -> Integer.compare(rGap.get(a) - rMin.get(a), rGap.get(b) - rMin.get(b)));
+ for (int r : bySlack) {
+ if (rGap.get(r) - rMin.get(r) >= GLUE_SLACK) break;
+ int a = root(parent, rHi.get(r)), b = root(parent, rLo.get(r));
+ if (a != b) parent[Math.max(a, b)] = Math.min(a, b);
+ }
+ lineGroup = new int[lines];
+ int[] groupOfRoot = new int[lines];
+ Arrays.fill(groupOfRoot, -1);
+ int count = 0;
+ for (int l = 0; l < lines; l++) {
+ int r = root(parent, l);
+ if (groupOfRoot[r] < 0) groupOfRoot[r] = count++;
+ lineGroup[l] = groupOfRoot[r];
+ }
+ groups = count;
+ cellLeft = groupsOf(left);
+ cellRight = groupsOf(right);
+ cellTop = groupsOf(top);
+ cellBottom = groupsOf(bottom);
+ pieceGroup = groupsOf(pieceLine);
+ pieceFromGroup = groupsOf(pieceFromLine);
+ pieceToGroup = groupsOf(pieceToLine);
+ groupLength = new int[groups];
+ for (int p = 0; p < pieces; p++) groupLength[pieceGroup[p]] += pieceTo[p] - pieceFrom[p];
+
+ // rules between groups, the tightest of each kind kept once
+ Map<Long, Integer> ruleOf = new HashMap<>();
+ IntList gHi = new IntList(), gLo = new IntList(), gGap = new IntList(), gMin = new IntList();
+ for (int r = 0; r < rules; r++) {
+ int hi = lineGroup[rHi.get(r)], lo = lineGroup[rLo.get(r)];
+ if (hi == lo) continue;
+ long key = ((long) hi << 42) | ((long) lo << 21) | rGap.get(r);
+ Integer at = ruleOf.get(key);
+ if (at == null) {
+ ruleOf.put(key, gHi.size);
+ gHi.add(hi);
+ gLo.add(lo);
+ gGap.add(rGap.get(r));
+ gMin.add(rMin.get(r));
+ } else if (rMin.get(r) > gMin.get(at)) {
+ gMin.set(at, rMin.get(r));
+ }
+ }
+ ruleHi = gHi.array();
+ ruleLo = gLo.array();
+ ruleGap = gGap.array();
+ ruleMin = gMin.array();
+ ruleStart = new int[groups + 1];
+ for (int r = 0; r < ruleHi.length; r++) {
+ ruleStart[ruleHi[r] + 1]++;
+ ruleStart[ruleLo[r] + 1]++;
+ }
+ for (int g = 0; g < groups; g++) ruleStart[g + 1] += ruleStart[g];
+ ruleList = new int[ruleStart[groups]];
+ fill = Arrays.copyOf(ruleStart, groups);
+ for (int r = 0; r < ruleHi.length; r++) {
+ ruleList[fill[ruleHi[r]]++] = r;
+ ruleList[fill[ruleLo[r]]++] = r;
+ }
+
+ // lower bounds over all time, for doors and fixtures
+ pieceMinLength = new int[pieces];
+ for (int p = 0; p < pieces; p++) {
+ int length = pieceTo[p] - pieceFrom[p];
+ int least = pieceFromGroup[p] == pieceToGroup[p] ? length : Math.max(length - 2 * maxUnits, Math.min(minStep, minCell));
+ pieceMinLength[p] = pieceHost[p] ? Math.max(least, hostMin) : least;
+ }
+ roomMinW = new int[rooms];
+ roomMinH = new int[rooms];
+ for (int r = 0; r < rooms; r++) {
+ if (roomCellStart[r + 1] - roomCellStart[r] > 1) {
+ roomMinW[r] = -1;
+ roomMinH[r] = -1;
+ continue;
+ }
+ int c = roomCellList[roomCellStart[r]], w = cellX1[c] - cellX0[c], h = cellY1[c] - cellY0[c];
+ roomMinW[r] = cellLeft[c] == cellRight[c] ? w : Math.max(w - 2 * maxUnits, kept(w, Math.max(minCell, minCross)));
+ roomMinH[r] = cellTop[c] == cellBottom[c] ? h : Math.max(h - 2 * maxUnits, kept(h, minCross));
+ }
+
+ // partners to line up with: parallel lines a little way along, within reach across
+ IntList[] partners = new IntList[groups];
+ for (int l = 0; l < lines; l++) {
+ int g = lineGroup[l];
+ if (groupLength[g] == 0 || linePeriodic[l]) continue;
+ boolean v = lineVertical[l];
+ for (int q = 0; q < lines; q++) {
+ if (lineVertical[q] != v || linePeriodic[q] || lineGroup[q] == g) continue;
+ for (int j = -1; j <= 1; j++) {
+ for (int i = -1; i <= 1; i++) {
+ int across = lineAt[q] + (v ? i * width + j * shift : j * height);
+ int along = v ? j * height : i * width + j * shift;
+ int delta = across - lineAt[l];
+ int apart = Math.max(lineFrom[q] + along - lineTo[l], lineFrom[l] - lineTo[q] - along);
+ if (Math.abs(delta) > 2 * maxUnits || apart <= 0 || apart > ALIGN_REACH) continue;
+ if (partners[g] == null) partners[g] = new IntList();
+ partners[g].add(lineGroup[q]);
+ partners[g].add(delta);
+ partners[g].add(apart);
+ }
+ }
+ }
+ }
+ alignStart = new int[groups + 1];
+ IntList ag = new IntList(), ad = new IntList();
+ for (int g = 0; g < groups; g++) {
+ alignStart[g] = ag.size;
+ if (partners[g] == null) continue;
+ IntList list = partners[g];
+ Integer[] order = new Integer[list.size / 3];
+ for (int i = 0; i < order.length; i++) order[i] = i;
+ Arrays.sort(order, (a, b) -> {
+ int da = Math.abs(list.get(3 * a + 1)), db = Math.abs(list.get(3 * b + 1));
+ if (da != db) return Integer.compare(da, db);
+ return Integer.compare(list.get(3 * a + 2), list.get(3 * b + 2));
+ });
+ for (int i = 0; i < order.length && ag.size - alignStart[g] < ALIGN_PARTNERS; i++) {
+ int partner = list.get(3 * order[i]), delta = list.get(3 * order[i] + 1);
+ boolean seen = false;
+ for (int s = alignStart[g]; s < ag.size; s++) seen |= ag.get(s) == partner && ad.get(s) == delta;
+ if (seen) continue;
+ ag.add(partner);
+ ad.add(delta);
+ }
+ }
+ alignStart[groups] = ag.size;
+ alignGroup = ag.array();
+ alignDelta = ad.array();
+ }
+
+ /** The room copy on one side of a line at unit stretch a: side 0 is left of it (or above), 1 right (or below). */
+ long sideRoom(boolean vertical, int at, int a, int side) {
+ return vertical ? roomAt(at - 1 + side, a) : roomAt(a, at - 1 + side);
+ }
+
+ /** The room copy that covers unit square (x, y) of the plane: the room id in the high half, its copy in the low. */
+ long roomAt(int x, int y) {
+ long c = cellAt(x, y);
+ return ((long) cellRoom[(int) (c >>> 32)] << 32) | (c & 0xFFFFFFFFL);
+ }
+
+ /** The cell copy that covers unit square (x, y) of the plane: the cell in the high half, its copy in the low. */
+ long cellAt(int x, int y) {
+ int j = Math.floorDiv(y, height), xr = x - j * shift, i = Math.floorDiv(xr, width);
+ int k = xr - i * width + (y - j * height) * width, p = squareCopy[k];
+ return ((long) squareCell[k] << 32) | (pack((p >> 16) + i, (short) p + j) & 0xFFFFFFFFL);
+ }
+
+ /** The tile square that unit square (x, y) of the plane is a copy of. */
+ private int index(int x, int y) {
+ int j = Math.floorDiv(y, height), xr = x - j * shift, i = Math.floorDiv(xr, width);
+ return xr - i * width + (y - j * height) * width;
+ }
+
+ /**
+ * True when the unit edge that starts at {@code a} along a line at {@code at} parts 2 cell copies: the edge from
+ * (at, a) to (at, a + 1) for a vertical line, from (a, at) to (a + 1, at) for a horizontal one.
+ */
+ private boolean edge(boolean vertical, int at, int a) {
+ return vertical ? cellAt(at - 1, a) != cellAt(at, a) : cellAt(a, at - 1) != cellAt(a, at);
+ }
+
+ private int edgeIndex(boolean vertical, int at, int a) {
+ return vertical ? index(at, a) : index(a, at);
+ }
+
+ private void checkRoom(int r) {
+ int from = roomCellStart[r], to = roomCellStart[r + 1];
+ if (to - from < 1 || to - from > 3) throw new IllegalArgumentException("room " + r + " has " + (to - from) + " cells");
+ // joined: grow from the first cell through shared edges
+ int joined = 1 << 0, size = to - from;
+ for (int pass = 0; pass < size; pass++) {
+ for (int a = 0; a < size; a++) {
+ if ((joined & (1 << a)) == 0) continue;
+ for (int b = 0; b < size; b++) {
+ if (touch(roomCellList[from + a], roomCellList[from + b])) joined |= 1 << b;
+ }
+ }
+ }
+ if (joined != (1 << size) - 1) throw new IllegalArgumentException("room " + r + " is in pieces");
+ }
+
+ /** True when 2 cells share a stretch of edge. */
+ private boolean touch(int a, int b) {
+ boolean side = (cellX1[a] == cellX0[b] || cellX1[b] == cellX0[a])
+ && Math.min(cellY1[a], cellY1[b]) > Math.max(cellY0[a], cellY0[b]);
+ boolean end = (cellY1[a] == cellY0[b] || cellY1[b] == cellY0[a])
+ && Math.min(cellX1[a], cellX1[b]) > Math.max(cellX0[a], cellX0[b]);
+ return side || end;
+ }
+
+ /**
+ * The least a cell's width or height or a room's width may get, in steps, from its size at home: least, and
+ * never under {@link #keepShare} of its size.
+ */
+ int kept(int size, int least) {
+ return Math.max(least, steps((double) keepShare * size));
+ }
+
+ private int[] groupsOf(int[] lineIds) {
+ int[] out = new int[lineIds.length];
+ for (int i = 0; i < out.length; i++) out[i] = lineGroup[lineIds[i]];
+ return out;
+ }
+
+ private static void rule(IntList hi, IntList lo, IntList gap, IntList min, int h, int l, int g, int m, String what) {
+ if (g < m) throw new IllegalArgumentException(what + " is " + g + " steps, below " + m);
+ hi.add(h);
+ lo.add(l);
+ gap.add(g);
+ min.add(m);
+ }
+
+ /** The line of the event at place a; there is always one where a piece starts or ends. */
+ private static int eventLine(IntList at, IntList line, int a) {
+ int lo = 0, hi = at.size - 1;
+ while (lo <= hi) {
+ int mid = (lo + hi) >>> 1;
+ if (at.get(mid) < a) lo = mid + 1; else if (at.get(mid) > a) hi = mid - 1; else return line.get(mid);
+ }
+ throw new IllegalArgumentException("a piece ends where nothing meets its line, at " + a);
+ }
+
+ /** The same key for both orders of 2 room copies, and for every copy of the pair. */
+ private static long pairKey(long a, long b) {
+ int ra = (int) (a >>> 32), rb = (int) (b >>> 32);
+ int di = ((int) b >> 16) - ((int) a >> 16), dj = (short) b - (short) a;
+ if (ra > rb || (ra == rb && (di < 0 || (di == 0 && dj < 0)))) {
+ int r = ra;
+ ra = rb;
+ rb = r;
+ di = -di;
+ dj = -dj;
+ }
+ return ((long) ra << 42) | ((long) rb << 21) | ((di & 0x3FFL) << 10) | (dj & 0x3FFL);
+ }
+
+ private static int pack(int i, int j) {
+ return (i << 16) | (j & 0xFFFF);
+ }
+
+ private static int root(int[] parent, int l) {
+ while (parent[l] != l) l = parent[l] = parent[parent[l]];
+ return l;
+ }
+
+ /** A size in steps, rounded up. */
+ private static int steps(double units) {
+ return (int) Math.ceil(units - 1e-3);
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileLayout.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileLayout.java
new file mode 100644
index 000000000..88077be3c
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileLayout.java
@@ -0,0 +1,61 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * One tile of a TILE plan at rest, in whole steps ({@link Look.Plan#unitH}), as a {@link TileBuilder} makes it.
+ * This is the contract a builder writes to. {@link TileGraph} checks all of it when the plan is built and throws
+ * {@link IllegalArgumentException} on the first rule that fails (the app then shows Yojōhan instead).
+ *
+ * <ul>
+ * <li><b>Lattice.</b> Copies of the tile sit at {@code i * (width, 0) + j * (shift, height)}, with
+ * {@code shift = width / 2}: each row of tiles is shifted half a tile.</li>
+ * <li><b>Cells</b> are boxes {@code [cellX0, cellX1) x [cellY0, cellY1)} with whole-step corners. Their copies
+ * fill the plane exactly, with no gaps and no overlaps. A cell may reach past the tile's own edges: a row's
+ * last room may end past {@code x = width}, and a cell may hang below {@code y = height}; its copies then
+ * cover the matching part of the neighbouring tiles.</li>
+ * <li><b>Rooms</b> are numbered 0 to {@code rooms - 1}; {@code cellRoom} gives each cell's room. A room is 1 to 3
+ * cells that join along edges, as given (not through a copy): a box, an L, a T, a Z, a U and so on. Cut a
+ * room into cells with vertical cuts at its steps, so each cell is as tall as the room is at that place.</li>
+ * <li><b>Lines.</b> The core finds them: every maximal straight run of cell edges is one line, and it moves as a
+ * whole. Joints of 2 courses that meet exactly at the row line between them form one line (a through-joint)
+ * and stay in line for good. Rooms keep their neighbours for good: nothing a builder makes ever changes
+ * which rooms touch.</li>
+ * <li><b>Rules at rest</b>, in steps: every cell at least {@code minCross} tall and {@code minCell} wide
+ * ({@link Look.Plan#minCrossH} over {@code unitH}, rounded up, and {@link Look.Plan#minCellUnits}); a room of
+ * one cell at least {@code minCross} wide, and a room of more cells at least {@code minCross} from its
+ * leftmost edge to its rightmost. Where 2 lines end on a third from its 2 sides (a step in a row edge, or
+ * joints of 2 courses on the row line between them), they are either one line or at least
+ * {@link Look.Plan#minStepUnits} apart.</li>
+ * </ul>
+ *
+ * The core keeps every rule true at every moment while the lines move, and picks the door hosts itself.
+ */
+final class TileLayout {
+ final int width, height, shift;
+ final int rooms;
+ final int[] cellX0, cellY0, cellX1, cellY1, cellRoom;
+
+ TileLayout(int width, int height, int rooms, int[] cellX0, int[] cellY0, int[] cellX1, int[] cellY1, int[] cellRoom) {
+ if (width <= 0 || height <= 0) throw new IllegalArgumentException("tile " + width + " x " + height);
+ int n = cellRoom.length;
+ if (cellX0.length != n || cellY0.length != n || cellX1.length != n || cellY1.length != n) {
+ throw new IllegalArgumentException("cell arrays differ in length");
+ }
+ for (int c = 0; c < n; c++) {
+ if (cellX1[c] <= cellX0[c] || cellY1[c] <= cellY0[c]) throw new IllegalArgumentException("empty cell " + c);
+ if (cellRoom[c] < 0 || cellRoom[c] >= rooms) throw new IllegalArgumentException("cell " + c + " has no room");
+ }
+ this.width = width;
+ this.height = height;
+ this.shift = width / 2;
+ this.rooms = rooms;
+ this.cellX0 = cellX0;
+ this.cellY0 = cellY0;
+ this.cellX1 = cellX1;
+ this.cellY1 = cellY1;
+ this.cellRoom = cellRoom;
+ }
+
+ int cells() {
+ return cellRoom.length;
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileMotion.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileMotion.java
new file mode 100644
index 000000000..2fbeda784
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TileMotion.java
@@ -0,0 +1,232 @@
+package io.github.pbanddev.tatami;
+
+import java.util.Arrays;
+
+/**
+ * Nagaya's walls in motion: how far every group of lines of a {@link TileGraph} is from home at any time, in steps.
+ *
+ * <p>Between glides the plan is at a rest state: one whole-step offset per group that keeps every rule of the graph.
+ * Each slot of the {@link MoveClock} makes the next rest state from the last. With {@link Look.Motion#quietShare} a
+ * slot moves nothing. Otherwise groups are picked in a shuffled order fixed by the seed and the slot until the slot's
+ * share of the wall length moves ({@link Look.Motion#moveShare}, spread per slot by {@link Look.Motion#shareSpread}).
+ * A picked group aims at home plus 1 to {@link Look.Motion#maxUnits} steps to one side (it turns to the other side of
+ * home with {@link Look.Motion#reverseShare}, else a coin picks), or with {@link Look.Motion#alignShare} at the place
+ * that lines it up with a nearby parallel line.
+ *
+ * <p>In the glide each moving group starts at its own {@link MoveClock#delay} and goes from its old offset to its new
+ * one along its own {@link Ease#glide} of {@link MoveClock#glide} seconds. Each moves one way only, so a rule on 2
+ * groups is at its least when each of them is at one end of its glide: both at the start, both at the end, or one
+ * at each. A pick goes as far toward its aim as every rule lets it at those ends, given the picks before it; one that
+ * aims home or into line goes all the way or stays put. So every moment of every glide keeps every rule, whatever
+ * the timing.
+ *
+ * <p>Every checkpoint ({@link MoveClock#slotsPerCheckpoint} slots) all groups are home. In the last
+ * {@link Look.Rhythm#homeSlots} slots before it, groups aim home, and the last slot takes every group home together
+ * along one shared glide, which is always valid. The state at any slot is simulated from its checkpoint with integers
+ * and hashes in a fixed order, so every view and every start agree. Going forward costs one step per slot, a jump at
+ * most one checkpoint's worth; nothing is allocated.
+ */
+final class TileMotion {
+ private static final long STREAM = 0x2545F4914F6CDD1DL;
+ private static final int ORDER = 1, PICK = 2, ALIGN = 3, PARTNER = 4, TURN = 5, SIDE = 6, AMP = 7, QUIET = 8, SHARE = 9;
+
+ final MoveClock clock;
+ private final TileGraph g;
+ private final long seed;
+ private final double reverse, align, quiet, spread;
+ private final int maxUnits, homeSlots;
+ /** The wall length a busy slot moves on average: the share of all of it, made up for the quiet slots. */
+ private final double wanted;
+ private final int[] order;
+ /** The rest state before glide {@link #slot}, and after it. */
+ private int[] from, to;
+ /** When each moving group's glide in slot {@link #slot} starts, after the slot does, and how long it lasts. */
+ private final double[] delay, span;
+ private long slot;
+ private boolean ready, aligning;
+ /** True when {@link #delay} and {@link #span} are worked out for slot {@link #slot}. */
+ private boolean timed;
+ /** The range {@link #room} found. */
+ private int low, high;
+ /**
+ * What the last slot's step did: picks that would move, picks turned down by a rule, picks a rule cut short,
+ * aligns that went through.
+ */
+ int tried, rejected, shortened, aligned;
+
+ TileMotion(Look look, TileGraph graph) {
+ g = graph;
+ clock = new MoveClock(look.rhythm, look.plan.seed);
+ seed = look.plan.seed ^ STREAM;
+ Look.Motion motion = look.motion;
+ reverse = motion.reverseShare;
+ align = motion.alignShare;
+ quiet = motion.quietShare;
+ spread = motion.shareSpread;
+ maxUnits = motion.maxUnits;
+ homeSlots = look.rhythm.homeSlots;
+ if (homeSlots < 1 || homeSlots >= clock.slotsPerCheckpoint) throw new IllegalArgumentException("home slots " + homeSlots);
+ if (!(quiet >= 0 && quiet < 1 && spread >= 0 && spread <= 1)) {
+ throw new IllegalArgumentException("quiet " + quiet + ", spread " + spread);
+ }
+ long total = 0;
+ for (int length : g.groupLength) total += length;
+ wanted = motion.moveShare / (1 - quiet) * total;
+ order = new int[g.groups];
+ from = new int[g.groups];
+ to = new int[g.groups];
+ delay = new double[g.groups];
+ span = new double[g.groups];
+ }
+
+ /** Every group's offset from home at time t, in steps: whole between glides, eased within them. */
+ void offsets(double t, float[] out) {
+ long k = clock.slot(t);
+ seek(k);
+ if (!timed) time(k);
+ double since = t - clock.start(k);
+ int n = g.groups;
+ for (int i = 0; i < n; i++) {
+ int a = from[i], b = to[i];
+ out[i] = a == b ? b : (float) (a + (b - a) * Ease.glide((since - delay[i]) / span[i]));
+ }
+ }
+
+ /** The rest states before and after slot k's glide. */
+ void glide(long k, int[] before, int[] after) {
+ seek(k);
+ System.arraycopy(from, 0, before, 0, g.groups);
+ System.arraycopy(to, 0, after, 0, g.groups);
+ }
+
+ /** Each moving group's timing in slot k, which {@link #from} and {@link #to} are at. */
+ private void time(long k) {
+ for (int i = 0; i < g.groups; i++) {
+ if (from[i] == to[i]) continue;
+ delay[i] = clock.delay(k, i);
+ span[i] = clock.glide(k, i);
+ }
+ timed = true;
+ }
+
+ /** Brings {@link #from} and {@link #to} to slot k: one step from the slot before, else from its checkpoint. */
+ private void seek(long k) {
+ if (ready && k == slot) return;
+ timed = false;
+ long checkpoint = clock.checkpoint(k);
+ if (!ready || k < slot || checkpoint > slot) {
+ slot = checkpoint;
+ Arrays.fill(from, 0);
+ next(slot);
+ ready = true;
+ }
+ while (slot < k) {
+ int[] swap = from;
+ from = to;
+ to = swap;
+ slot++;
+ next(slot);
+ }
+ }
+
+ /** The rest state after slot k's glide, into {@link #to}, from the one before it in {@link #from}. */
+ private void next(long k) {
+ int n = g.groups;
+ System.arraycopy(from, 0, to, 0, n);
+ tried = 0;
+ rejected = 0;
+ shortened = 0;
+ aligned = 0;
+ if (clock.homeTogether(k)) {
+ Arrays.fill(to, 0);
+ return;
+ }
+ long local = k - clock.checkpoint(k);
+ // in the slots before the last, an even share of the groups still away go home each time
+ double homeOdds = local >= clock.slotsPerCheckpoint - homeSlots ? 1.0 / (clock.slotsPerCheckpoint - local) : 0;
+ long want = 0;
+ if (homeOdds == 0) {
+ if (MoveClock.unit(MoveClock.hash(seed, k, 0, QUIET)) < quiet) return;
+ want = Math.round(wanted * (1 + spread * (2 * MoveClock.unit(MoveClock.hash(seed, k, 0, SHARE)) - 1)));
+ }
+ for (int i = 0; i < n; i++) order[i] = i;
+ for (int i = n - 1; i > 0; i--) {
+ int j = (int) (MoveClock.unit(MoveClock.hash(seed, k, -1 - i, ORDER)) * (i + 1));
+ int swap = order[i];
+ order[i] = order[j];
+ order[j] = swap;
+ }
+ long moving = 0;
+ for (int i = 0; i < n && (homeOdds > 0 || moving < want); i++) {
+ int gr = order[i];
+ if (g.groupLength[gr] == 0) continue;
+ int target;
+ if (homeOdds > 0) {
+ if (to[gr] == 0 || MoveClock.unit(MoveClock.hash(seed, k, gr, PICK)) >= homeOdds) continue;
+ target = 0;
+ aligning = false;
+ } else {
+ target = aim(k, gr);
+ }
+ if (target == to[gr]) continue;
+ tried++;
+ room(gr);
+ if (target < low || target > high) {
+ // a free aim goes as far toward its target as the rules let it; home or into line is all or nothing
+ if (homeOdds > 0 || aligning) {
+ rejected++;
+ continue;
+ }
+ target = Math.max(low, Math.min(high, target));
+ if (target == to[gr]) {
+ rejected++;
+ continue;
+ }
+ shortened++;
+ }
+ to[gr] = target;
+ moving += g.groupLength[gr];
+ if (aligning) aligned++;
+ }
+ }
+
+ /** Where a picked group aims: in line with a partner, or home plus a few steps to one side. */
+ private int aim(long k, int gr) {
+ aligning = false;
+ int a0 = g.alignStart[gr], a1 = g.alignStart[gr + 1];
+ if (a1 > a0 && MoveClock.unit(MoveClock.hash(seed, k, gr, ALIGN)) < align) {
+ int a = a0 + (int) (MoveClock.unit(MoveClock.hash(seed, k, gr, PARTNER)) * (a1 - a0));
+ int target = g.alignDelta[a] + to[g.alignGroup[a]];
+ if (Math.abs(target) <= maxUnits) {
+ aligning = true;
+ return target;
+ }
+ }
+ int now = Integer.signum(to[gr]);
+ int side = now != 0 && MoveClock.unit(MoveClock.hash(seed, k, gr, TURN)) < reverse ? -now
+ : MoveClock.unit(MoveClock.hash(seed, k, gr, SIDE)) < 0.5 ? 1 : -1;
+ return side * (1 + (int) (maxUnits * MoveClock.unit(MoveClock.hash(seed, k, gr, AMP))));
+ }
+
+ /**
+ * The offsets group gr may glide to, into [{@link #low}, {@link #high}]: every rule on it holds with it at its end
+ * and each other group at either end of its own glide as it stands. With gr at its start every rule holds already:
+ * at the rest state before the slot, and against each group picked before it, whose own pick checked that. The
+ * range always holds where gr is now.
+ */
+ private void room(int gr) {
+ low = Integer.MIN_VALUE;
+ high = Integer.MAX_VALUE;
+ for (int i = g.ruleStart[gr]; i < g.ruleStart[gr + 1]; i++) {
+ int r = g.ruleList[i], least = g.ruleMin[r] - g.ruleGap[r];
+ // offset[hi] - offset[lo] >= least, with the other group wherever it is in its glide
+ if (g.ruleHi[r] == gr) {
+ int other = g.ruleLo[r];
+ low = Math.max(low, least + Math.max(from[other], to[other]));
+ } else {
+ int other = g.ruleHi[r];
+ high = Math.min(high, Math.min(from[other], to[other]) - least);
+ }
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TilePlan.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TilePlan.java
new file mode 100644
index 000000000..7f8a6e06e
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/TilePlan.java
@@ -0,0 +1,325 @@
+package io.github.pbanddev.tatami;
+
+import java.util.Arrays;
+
+/**
+ * Nagaya's {@link Layout}: one tile of rooms ({@link TileBuilder}, checked and worked out by {@link TileGraph})
+ * repeated on a staggered lattice, its lines moved by {@link TileMotion}, and cut down to what the view can show.
+ *
+ * <p>Each frame puts every group of lines at its offset for time t, then, for each copy of the tile that can show,
+ * emits the cells and wall pieces the view sees, grown by the blur's strip (in the view), a door's swing and half a
+ * wall. Each cell and piece belongs to one copy and is emitted whole, so pieces that run across a seam are never
+ * cut. Rooms are boxed from all their cells. Every copy shows the same paints, doors and motion.
+ *
+ * <p>The frame's arrays are sized from the most the widest views can ask for, with every line anywhere in its range.
+ * A frame that wants more leaves the rest out and sets {@link Frame#clipped}; nothing here throws once built, for any
+ * time.
+ */
+final class TilePlan implements Layout {
+ /** The widest views, sampled to size the frame: this many centres each way over the tile. */
+ private static final int SAMPLES = 7;
+ /** A view this size, the smallest the app draws, sees the most plan: the blur's strip is the same px on all. */
+ private static final int SAMPLE_W = 1280, SAMPLE_H = 720;
+ private static final long HOSTS = 0x6D6F7665L;
+ /** A view never needs more copies than this each way, nor a centre farther out than this many steps. */
+ private static final int COPIES = 64;
+ private static final double LATTICE_REACH = 1e6;
+
+ private final Look look;
+ final TileGraph graph;
+ final TileMotion motion;
+ private final float[] offset;
+ private final int[] roomIndex, touched;
+ private final double[] reach = new double[4];
+ /** The box every cell and piece of copy (0, 0) stays inside at any time, in steps. */
+ private final int minX, minY, maxX, maxY;
+ private final int cellCapacity, wallCapacity, doorCapacity, fillCapacity;
+
+ TilePlan(Look look, TileBuilder builder) {
+ this.look = look;
+ graph = new TileGraph(builder.build(look.plan), look);
+ motion = new TileMotion(look, graph);
+ offset = new float[graph.groups];
+ roomIndex = new int[graph.rooms];
+ Arrays.fill(roomIndex, -1);
+ touched = new int[graph.rooms];
+ TileGraph g = graph;
+ int x0 = Integer.MAX_VALUE, y0 = Integer.MAX_VALUE, x1 = Integer.MIN_VALUE, y1 = Integer.MIN_VALUE;
+ for (int c = 0; c < g.cells; c++) {
+ x0 = Math.min(x0, g.cellX0[c]);
+ y0 = Math.min(y0, g.cellY0[c]);
+ x1 = Math.max(x1, g.cellX1[c]);
+ y1 = Math.max(y1, g.cellY1[c]);
+ }
+ for (int p = 0; p < g.pieces; p++) {
+ boolean v = g.pieceVertical[p];
+ x0 = Math.min(x0, v ? g.pieceAt[p] : g.pieceFrom[p]);
+ y0 = Math.min(y0, v ? g.pieceFrom[p] : g.pieceAt[p]);
+ x1 = Math.max(x1, v ? g.pieceAt[p] : g.pieceTo[p]);
+ y1 = Math.max(y1, v ? g.pieceTo[p] : g.pieceAt[p]);
+ }
+ int r = g.maxUnits;
+ minX = x0 - r;
+ minY = y0 - r;
+ maxX = x1 + r;
+ maxY = y1 + r;
+ int[] most = widest();
+ cellCapacity = most[0] + most[0] / 5 + 16;
+ wallCapacity = most[1] + most[1] / 5 + 16;
+ fillCapacity = most[2] + most[2] / 5 + 16;
+ doorCapacity = most[3] + most[3] / 5 + 16;
+ }
+
+ /**
+ * Picks the wall pieces that may hold a door, once per plan: at most one per pair of rooms that touch, on that
+ * pair's longest piece that is at least {@link Look.Doors#hostBars} bar lengths at home and has the cells on the
+ * side its door swings to ({@link NagayaDoors#side}) deep enough at every moment for the swing. It picks
+ * {@link Look.Doors#chance} of all touching pairs (or every pair that can have one, if fewer), long pieces more
+ * often than short ones: each pair's key is a hash over its piece's length squared, and the smallest keys go
+ * first. A first pass in that order takes only pairs that give a room its first door, so almost every room gets
+ * one; a second takes the rest. The motion keeps every host that long at every moment. {@link Frame#wallDoor}
+ * carries the choice to the door placer.
+ */
+ static boolean[] doorHosts(TileGraph g, Look look) {
+ boolean[] host = new boolean[g.pieces];
+ int[] best = new int[g.pairs];
+ Arrays.fill(best, -1);
+ // a door swings across the cell beside it: the swing, its stroke and both walls, in steps
+ Look.Doors d = look.doors;
+ int swing = (int) Math.ceil((double) (d.radiusH + d.lineH + look.walls.widthH) / look.plan.unitH - 1e-3);
+ for (int p = 0; p < g.pieces; p++) {
+ int length = g.pieceTo[p] - g.pieceFrom[p], b = best[g.piecePair[p]];
+ if (length < g.hostMin || (b >= 0 && length <= g.pieceTo[b] - g.pieceFrom[b])) continue;
+ // every cell beside it on the side its door swings to stays that deep at every moment: a cell never gets
+ // below its kept share of its width or height, nor below its rule's minimum (TileGraph.kept)
+ boolean vertical = g.pieceVertical[p], roomy = true;
+ int s = NagayaDoors.side(look.plan.seed, d.swingBias, p, vertical) > 0 ? g.pieceAt[p] : g.pieceAt[p] - 1;
+ for (int a = g.pieceFrom[p]; a < g.pieceTo[p] && roomy; a++) {
+ int c = (int) ((vertical ? g.cellAt(s, a) : g.cellAt(a, s)) >>> 32), r = g.cellRoom[c];
+ boolean alone = g.roomCellStart[r + 1] - g.roomCellStart[r] == 1;
+ int across = vertical ? g.cellX1[c] - g.cellX0[c] : g.cellY1[c] - g.cellY0[c];
+ int least = vertical && !alone ? g.minCell : g.minCross;
+ roomy = g.kept(across, least) >= swing;
+ }
+ if (roomy) best[g.piecePair[p]] = p;
+ }
+ int can = 0;
+ Integer[] order = new Integer[g.pairs];
+ double[] key = new double[g.pairs];
+ for (int pair = 0; pair < g.pairs; pair++) {
+ if (best[pair] < 0) continue;
+ double length = g.pieceTo[best[pair]] - g.pieceFrom[best[pair]];
+ key[pair] = MoveClock.unit(MoveClock.hash(look.plan.seed ^ HOSTS, pair, 0, 0)) / (length * length);
+ order[can++] = pair;
+ }
+ Arrays.sort(order, 0, can, (a, b) -> Double.compare(key[a], key[b]));
+ long wanted = Math.min(can, Math.round((double) look.doors.chance * g.pairs)), count = 0;
+ int[] doors = new int[g.rooms];
+ for (int pass = 0; pass < 2; pass++) {
+ for (int i = 0; i < can && count < wanted; i++) {
+ int p = best[order[i]], a = g.pieceRoomA[p], b = g.pieceRoomB[p];
+ if (host[p] || (pass == 0 && doors[a] > 0 && doors[b] > 0)) continue;
+ host[p] = true;
+ doors[a]++;
+ doors[b]++;
+ count++;
+ }
+ }
+ return host;
+ }
+
+ @Override
+ public int rooms() {
+ return graph.rooms;
+ }
+
+ @Override
+ public Frame newFrame() {
+ // doors go only on host pieces
+ return new Frame(cellCapacity, cellCapacity, wallCapacity, doorCapacity, 0, fillCapacity);
+ }
+
+ @Override
+ public void layout(double t, View v, Frame f) {
+ f.roomCount = 0;
+ f.cellCount = 0;
+ f.wallCount = 0;
+ f.clipped = false;
+ motion.offsets(t, offset);
+ float unit = v.h * look.plan.unitH;
+ float grow = v.h * (look.doors.radiusH + look.walls.widthH / 2);
+ TileGraph g = graph;
+ if (!(unit > 0 && v.zoom > 0 && v.w > 0)) return;
+ reach(v, unit, grow);
+ int jFrom = (int) Math.floor((reach[1] - reach[3] - maxY) / g.height);
+ int jTo = (int) Math.ceil((reach[1] + reach[3] - minY) / g.height);
+ if (!(Math.abs(reach[0]) < LATTICE_REACH && Math.abs(reach[1]) < LATTICE_REACH && jTo - jFrom < COPIES)) {
+ f.clipped = true;
+ return;
+ }
+ for (int j = jFrom; j <= jTo; j++) {
+ int oy = j * g.height, sx = j * g.shift;
+ int iFrom = (int) Math.floor((reach[0] - reach[2] - maxX - sx) / g.width);
+ int iTo = (int) Math.ceil((reach[0] + reach[2] - minX - sx) / g.width);
+ for (int i = iFrom; i <= iTo && i - iFrom < COPIES; i++) {
+ int ox = i * g.width + sx;
+ if (!v.sees((minX + ox) * unit, (minY + oy) * unit, (maxX + ox) * unit, (maxY + oy) * unit, grow)) continue;
+ cells(f, v, ox, oy, unit, grow);
+ walls(f, v, ox, oy, unit, grow);
+ }
+ }
+ }
+
+ /** The view's centre and how far it reaches along plan x and y, in steps, into {@link #reach}. */
+ private void reach(View v, float unit, float grow) {
+ double c = Math.abs(Math.cos(Math.toRadians(v.rollDeg))), s = Math.abs(Math.sin(Math.toRadians(v.rollDeg)));
+ double ex = (v.w / 2.0 + v.margin) / v.zoom, ey = (v.h / 2.0 + v.margin) / v.zoom;
+ reach[0] = v.centreX / unit;
+ reach[1] = v.centreY / unit;
+ reach[2] = (ex * c + ey * s + grow) / unit;
+ reach[3] = (ex * s + ey * c + grow) / unit;
+ }
+
+ private void cells(Frame f, View v, int ox, int oy, float unit, float grow) {
+ TileGraph g = graph;
+ float[] o = offset;
+ int count = 0;
+ for (int k = 0; k < g.cells; k++) {
+ float x0 = (g.cellX0[k] + ox + o[g.cellLeft[k]]) * unit, x1 = (g.cellX1[k] + ox + o[g.cellRight[k]]) * unit;
+ float y0 = (g.cellY0[k] + oy + o[g.cellTop[k]]) * unit, y1 = (g.cellY1[k] + oy + o[g.cellBottom[k]]) * unit;
+ if (!v.sees(x0, y0, x1, y1, grow)) continue;
+ if (f.cellCount == f.cellX.length) {
+ f.clipped = true;
+ continue;
+ }
+ int id = g.cellRoom[k], r = roomIndex[id];
+ if (r < 0) {
+ if (f.roomCount == f.roomX.length) {
+ f.clipped = true;
+ continue;
+ }
+ r = f.roomCount++;
+ roomIndex[id] = r;
+ touched[count++] = id;
+ room(f, r, id, ox, oy, unit);
+ }
+ int c = f.cellCount++;
+ f.cellX[c] = x0;
+ f.cellY[c] = y0;
+ f.cellW[c] = x1 - x0;
+ f.cellH[c] = y1 - y0;
+ f.cellRoom[c] = r;
+ }
+ for (int i = 0; i < count; i++) roomIndex[touched[i]] = -1;
+ }
+
+ /** Room r of the frame: room id's box over all its cells in this copy, and its least size. */
+ private void room(Frame f, int r, int id, int ox, int oy, float unit) {
+ TileGraph g = graph;
+ float[] o = offset;
+ float x0 = Float.MAX_VALUE, y0 = Float.MAX_VALUE, x1 = -Float.MAX_VALUE, y1 = -Float.MAX_VALUE;
+ for (int i = g.roomCellStart[id]; i < g.roomCellStart[id + 1]; i++) {
+ int k = g.roomCellList[i];
+ x0 = Math.min(x0, (g.cellX0[k] + ox + o[g.cellLeft[k]]) * unit);
+ x1 = Math.max(x1, (g.cellX1[k] + ox + o[g.cellRight[k]]) * unit);
+ y0 = Math.min(y0, (g.cellY0[k] + oy + o[g.cellTop[k]]) * unit);
+ y1 = Math.max(y1, (g.cellY1[k] + oy + o[g.cellBottom[k]]) * unit);
+ }
+ f.roomId[r] = id;
+ f.roomX[r] = x0;
+ f.roomY[r] = y0;
+ f.roomW[r] = x1 - x0;
+ f.roomH[r] = y1 - y0;
+ f.roomMinW[r] = g.roomMinW[id] < 0 ? Float.NaN : g.roomMinW[id] * unit;
+ f.roomMinH[r] = g.roomMinH[id] < 0 ? Float.NaN : g.roomMinH[id] * unit;
+ }
+
+ private void walls(Frame f, View v, int ox, int oy, float unit, float grow) {
+ TileGraph g = graph;
+ float[] o = offset;
+ for (int p = 0; p < g.pieces; p++) {
+ boolean vertical = g.pieceVertical[p];
+ int across = vertical ? ox : oy, along = vertical ? oy : ox;
+ float at = (g.pieceAt[p] + across + o[g.pieceGroup[p]]) * unit;
+ float a0 = (g.pieceFrom[p] + along + o[g.pieceFromGroup[p]]) * unit;
+ float a1 = (g.pieceTo[p] + along + o[g.pieceToGroup[p]]) * unit;
+ float x0 = vertical ? at : a0, y0 = vertical ? a0 : at, x1 = vertical ? at : a1, y1 = vertical ? a1 : at;
+ if (!v.sees(x0, y0, x1, y1, grow)) continue;
+ if (f.wallCount == f.wallX0.length) {
+ f.clipped = true;
+ continue;
+ }
+ int w = f.wallCount++;
+ f.wallId[w] = p;
+ f.wallRoomA[w] = g.pieceRoomA[p];
+ f.wallRoomB[w] = g.pieceRoomB[p];
+ f.wallX0[w] = x0;
+ f.wallY0[w] = y0;
+ f.wallX1[w] = x1;
+ f.wallY1[w] = y1;
+ f.wallVertical[w] = vertical;
+ f.wallMinLength[w] = g.pieceMinLength[p] * unit;
+ f.wallDoor[w] = g.pieceHost[p];
+ }
+ }
+
+ /** The most cells, wall pieces, fill pieces and door hosts any of the widest views asks for, with every line anywhere. */
+ private int[] widest() {
+ Look.Camera cam = look.camera;
+ float zoom = Math.min(cam.restZoom, Math.min(cam.zoomFrom, cam.zoomTo));
+ float[] rolls = {cam.angleDeg, cam.rollFromDeg, cam.rollToDeg};
+ float margin = Scene.margin(look), unit = SAMPLE_H * look.plan.unitH;
+ TileGraph g = graph;
+ View v = new View();
+ int[] most = new int[4];
+ for (float roll : rolls) {
+ for (int i = 0; i < SAMPLES; i++) {
+ for (int j = 0; j < SAMPLES; j++) {
+ double x = (g.width * i + g.shift * j) * unit / SAMPLES, y = g.height * j * unit / (double) SAMPLES;
+ v.set(SAMPLE_W, SAMPLE_H, roll, zoom, x, y, margin);
+ count(v, unit, most);
+ }
+ }
+ }
+ return most;
+ }
+
+ /** What view v can ask for with every line anywhere in its range, into most where it is more. */
+ private void count(View v, float unit, int[] most) {
+ TileGraph g = graph;
+ float grow = v.h * (look.doors.radiusH + look.walls.widthH / 2), side = v.h * look.post.washPieceH;
+ int r = g.maxUnits, cells = 0, walls = 0, fills = 0, hosts = 0;
+ reach(v, unit, grow);
+ int jFrom = (int) Math.floor((reach[1] - reach[3] - maxY) / g.height);
+ int jTo = (int) Math.ceil((reach[1] + reach[3] - minY) / g.height);
+ for (int j = jFrom; j <= jTo; j++) {
+ int oy = j * g.height, sx = j * g.shift;
+ int iFrom = (int) Math.floor((reach[0] - reach[2] - maxX - sx) / g.width);
+ int iTo = (int) Math.ceil((reach[0] + reach[2] - minX - sx) / g.width);
+ for (int i = iFrom; i <= iTo; i++) {
+ int ox = i * g.width + sx;
+ if (!v.sees((minX + ox) * unit, (minY + oy) * unit, (maxX + ox) * unit, (maxY + oy) * unit, grow)) continue;
+ for (int k = 0; k < g.cells; k++) {
+ float x0 = (g.cellX0[k] - r + ox) * unit, x1 = (g.cellX1[k] + r + ox) * unit;
+ float y0 = (g.cellY0[k] - r + oy) * unit, y1 = (g.cellY1[k] + r + oy) * unit;
+ if (!v.sees(x0, y0, x1, y1, grow)) continue;
+ cells++;
+ fills += SceneMesh.pieces(x1 - x0, y1 - y0, side);
+ }
+ for (int p = 0; p < g.pieces; p++) {
+ boolean vertical = g.pieceVertical[p];
+ int across = g.pieceAt[p] + (vertical ? ox : oy), along = vertical ? oy : ox;
+ float a = (across - r) * unit, b = (across + r) * unit;
+ float c = (g.pieceFrom[p] + along - r) * unit, d = (g.pieceTo[p] + along + r) * unit;
+ if (!(vertical ? v.sees(a, c, b, d, grow) : v.sees(c, a, d, b, grow))) continue;
+ walls++;
+ if (g.pieceHost[p]) hosts++;
+ }
+ }
+ }
+ most[0] = Math.max(most[0], cells);
+ most[1] = Math.max(most[1], walls);
+ most[2] = Math.max(most[2], fills);
+ most[3] = Math.max(most[3], hosts);
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/View.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/View.java
new file mode 100644
index 000000000..4f0c1392d
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/View.java
@@ -0,0 +1,65 @@
+package io.github.pbanddev.tatami;
+
+/**
+ * What the camera sees in one frame: the screen, the plan's tilt and zoom, and the plan point at the screen's
+ * centre. In screen px with y down:
+ * {@code screen = (w / 2, h / 2) + zoom * rotate(rollDeg) * (plan - centre)}; a positive roll turns the plan
+ * clockwise on screen (walls fall to the right). A {@link CameraCurve} fills it every frame with {@link #set};
+ * no allocation.
+ */
+public final class View {
+ /** The screen, in px. */
+ public float w, h;
+ /** The plan's tilt on screen, in degrees. */
+ public float rollDeg;
+ /** Screen px per plan unit. */
+ public float zoom = 1f;
+ /** The plan point at the screen's centre, in plan units. Nagaya keeps it within a tile of 0, so floats stay exact. */
+ public double centreX, centreY;
+ /** How far past each screen edge the plan must still be drawn, in screen px: the strip the blur reads. */
+ public float margin;
+ private double cos = 1, sin;
+
+ public void set(float w, float h, float rollDeg, float zoom, double centreX, double centreY, float margin) {
+ this.w = w;
+ this.h = h;
+ this.rollDeg = rollDeg;
+ this.zoom = zoom;
+ this.centreX = centreX;
+ this.centreY = centreY;
+ this.margin = margin;
+ double a = Math.toRadians(rollDeg);
+ cos = Math.cos(a);
+ sin = Math.sin(a);
+ }
+
+ /** Plan units to clip space, column-major 4x4. */
+ public void matrix(float[] out) {
+ double c = cos * zoom, s = sin * zoom;
+ java.util.Arrays.fill(out, 0f);
+ out[0] = (float) (2 * c / w);
+ out[1] = (float) (-2 * s / h);
+ out[4] = (float) (-2 * s / w);
+ out[5] = (float) (-2 * c / h);
+ out[10] = 1f;
+ out[12] = (float) (2 * (s * centreY - c * centreX) / w);
+ out[13] = (float) (2 * (s * centreX + c * centreY) / h);
+ out[15] = 1f;
+ }
+
+ /**
+ * True when the plan box [x0, x1] x [y0, y1], grown by {@code grow} plan units on every side, can show on the
+ * screen grown by {@link #margin}: the 2 rectangles overlap on all 4 of their axes.
+ */
+ public boolean sees(float x0, float y0, float x1, float y1, float grow) {
+ double hx = (x1 - x0) / 2.0 + grow, hy = (y1 - y0) / 2.0 + grow;
+ double dx = (x0 + x1) / 2.0 - centreX, dy = (y0 + y1) / 2.0 - centreY;
+ double ex = (w / 2.0 + margin) / zoom, ey = (h / 2.0 + margin) / zoom;
+ double c = Math.abs(cos), s = Math.abs(sin);
+ if (Math.abs(dx) > hx + ex * c + ey * s) return false;
+ if (Math.abs(dy) > hy + ex * s + ey * c) return false;
+ // the screen's own axes in plan units: across (cos, -sin) and down (sin, cos)
+ if (Math.abs(dx * cos - dy * sin) > ex + hx * c + hy * s) return false;
+ return Math.abs(dx * sin + dy * cos) <= ey + hx * s + hy * c;
+ }
+}
diff --git a/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Wash.java b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Wash.java
new file mode 100644
index 000000000..2a992c120
--- /dev/null
+++ b/addons/tatami/plan/src/main/java/io/github/pbanddev/tatami/Wash.java
@@ -0,0 +1,139 @@
+package io.github.pbanddev.tatami;
+
+import java.util.Arrays;
+
+/**
+ * Screen-space colour wash, 17x10 nodes, row 0 at the top: {@code c' = W * softLight(c, b)}, per channel, on
+ * gamma-encoded colours (0 to 1). Node (i, j) sits at (i * w / 16, j * h / 9) px from the screen's top left;
+ * between nodes W and b are bilinear, past the outer nodes they hold the edge's values. W = 1 and b = 0.5
+ * change nothing; black stays black. {@link SceneMesh} applies it to room and door fills, never to walls or ink.
+ */
+public final class Wash {
+ static final int NX = 17, NY = 10;
+ /** Changes nothing. */
+ static final Wash NONE = new Wash(filled(1f), filled(0.5f));
+ /** Nagaya's wash: bluer to the left, darker toward the bottom, no change in the middle. */
+ static final Wash NAGAYA = new Wash(nodes(NagayaMaps.W), nodes(NagayaMaps.B));
+
+ /** W and b per node and channel: index (j * NX + i) * 3 + channel, channels r, g, b. */
+ private final float[] gain, blend;
+
+ Wash(float[] gain, float[] blend) {
+ if (gain.length != NX * NY * 3 || blend.length != NX * NY * 3) throw new IllegalArgumentException("17 x 10 x 3");
+ this.gain = gain.clone();
+ this.blend = blend.clone();
+ }
+
+ /** Washes {@code rgb} in place for the point (x, y) px from the top left of a w by h screen. */
+ void apply(float x, float y, float w, float h, float[] rgb) {
+ float fx = Math.max(0f, Math.min(NX - 1f, x / w * (NX - 1)));
+ float fy = Math.max(0f, Math.min(NY - 1f, y / h * (NY - 1)));
+ int i = Math.min((int) fx, NX - 2), j = Math.min((int) fy, NY - 2);
+ float tx = fx - i, ty = fy - j;
+ int n00 = (j * NX + i) * 3, n10 = n00 + 3, n01 = n00 + NX * 3, n11 = n01 + 3;
+ for (int c = 0; c < 3; c++) {
+ float w0 = gain[n00 + c] + (gain[n10 + c] - gain[n00 + c]) * tx;
+ float w1 = gain[n01 + c] + (gain[n11 + c] - gain[n01 + c]) * tx;
+ float b0 = blend[n00 + c] + (blend[n10 + c] - blend[n00 + c]) * tx;
+ float b1 = blend[n01 + c] + (blend[n11 + c] - blend[n01 + c]) * tx;
+ float washed = (w0 + (w1 - w0) * ty) * softLight(rgb[c], b0 + (b1 - b0) * ty);
+ rgb[c] = Math.max(0f, Math.min(1f, washed));
+ }
+ }
+
+ /** The W3C soft light of {@code a} (the colour below) by {@code b} (the blend), both 0 to 1. */
+ static float softLight(float a, float b) {
+ if (b <= 0.5f) return a - (1f - 2f * b) * a * (1f - a);
+ float d = a <= 0.25f ? ((16f * a - 12f) * a + 4f) * a : (float) Math.sqrt(a);
+ return a + (2f * b - 1f) * (d - a);
+ }
+
+ /** Maps given per channel as rows of nodes from the top, in thousandths, in the node order of {@link #gain}. */
+ private static float[] nodes(int[][] thousandths) {
+ float[] a = new float[NX * NY * 3];
+ for (int c = 0; c < 3; c++) {
+ for (int n = 0; n < NX * NY; n++) a[n * 3 + c] = thousandths[c][n] / 1000f;
+ }
+ return a;
+ }
+
+ private static float[] filled(float v) {
+ float[] a = new float[NX * NY * 3];
+ Arrays.fill(a, v);
+ return a;
+ }
+
+ /** Screen-space colour wash, 17x10 nodes, row 0 at the top: red, then green, then blue, in thousandths. */
+ private static final class NagayaMaps {
+ /** W, the gain after the soft light: 1000 changes nothing. */
+ static final int[][] W = {{
+ 107, 144, 194, 276, 429, 601, 714, 794, 841, 856, 864, 862, 846, 828, 814, 767, 699,
+ 151, 208, 273, 386, 565, 704, 798, 872, 919, 936, 944, 935, 909, 901, 889, 854, 791,
+ 254, 349, 442, 578, 695, 769, 847, 918, 969, 993, 991, 978, 956, 950, 933, 899, 842,
+ 395, 509, 612, 709, 760, 803, 859, 939, 1003, 1033, 1023, 1002, 978, 963, 949, 913, 861,
+ 508, 625, 712, 745, 772, 805, 856, 941, 1016, 1050, 1047, 1015, 981, 966, 953, 911, 858,
+ 554, 668, 739, 753, 768, 784, 823, 906, 984, 1026, 1031, 1007, 981, 966, 949, 909, 854,
+ 559, 654, 719, 750, 767, 766, 788, 852, 924, 968, 986, 983, 970, 952, 930, 894, 840,
+ 534, 601, 670, 722, 743, 749, 762, 813, 863, 888, 921, 936, 927, 919, 896, 857, 807,
+ 493, 541, 587, 647, 688, 711, 734, 764, 785, 805, 850, 870, 873, 867, 842, 805, 754,
+ 440, 473, 509, 556, 604, 642, 666, 687, 712, 736, 778, 798, 799, 791, 773, 743, 693,
+ }, {
+ 538, 611, 675, 712, 732, 740, 748, 748, 744, 743, 755, 742, 701, 646, 574, 487, 413,
+ 637, 725, 792, 824, 839, 844, 852, 859, 868, 879, 891, 875, 841, 804, 741, 635, 528,
+ 720, 812, 870, 894, 903, 902, 911, 923, 943, 963, 968, 954, 934, 918, 877, 783, 656,
+ 773, 864, 910, 927, 931, 926, 927, 946, 968, 980, 984, 986, 986, 981, 952, 877, 755,
+ 782, 879, 927, 942, 938, 926, 933, 960, 986, 989, 982, 984, 999, 1002, 987, 929, 818,
+ 748, 865, 931, 946, 932, 925, 947, 983, 1014, 1007, 987, 986, 999, 1003, 994, 946, 836,
+ 670, 806, 896, 929, 946, 973, 1008, 1032, 1043, 1030, 1008, 993, 991, 984, 968, 913, 801,
+ 541, 676, 792, 861, 913, 974, 1042, 1070, 1059, 1033, 1006, 973, 949, 932, 903, 828, 723,
+ 395, 489, 612, 712, 796, 887, 974, 1009, 1003, 983, 949, 906, 866, 830, 774, 703, 621,
+ 279, 320, 399, 508, 609, 712, 803, 864, 897, 879, 832, 783, 731, 676, 636, 595, 527,
+ }, {
+ 1343, 1263, 1181, 1093, 1001, 905, 812, 725, 651, 593, 553, 513, 453, 408, 390, 353, 300,
+ 1327, 1284, 1232, 1162, 1078, 987, 903, 826, 755, 701, 668, 639, 593, 553, 533, 489, 426,
+ 1298, 1284, 1250, 1194, 1123, 1045, 972, 905, 842, 800, 779, 771, 760, 732, 687, 630, 561,
+ 1243, 1252, 1235, 1194, 1130, 1068, 1009, 955, 909, 879, 883, 894, 898, 881, 832, 771, 703,
+ 1159, 1186, 1190, 1162, 1117, 1074, 1038, 1003, 971, 938, 957, 990, 1007, 999, 964, 910, 848,
+ 1046, 1090, 1115, 1109, 1087, 1071, 1065, 1050, 1030, 1003, 1024, 1068, 1098, 1098, 1078, 1041, 993,
+ 910, 962, 1010, 1034, 1044, 1060, 1078, 1080, 1073, 1067, 1088, 1132, 1165, 1175, 1171, 1155, 1129,
+ 762, 821, 873, 927, 968, 1010, 1056, 1081, 1092, 1107, 1140, 1179, 1204, 1222, 1239, 1249, 1250,
+ 614, 679, 737, 802, 865, 930, 993, 1038, 1071, 1103, 1142, 1178, 1214, 1258, 1300, 1335, 1367,
+ 471, 539, 603, 677, 751, 826, 898, 964, 1019, 1063, 1105, 1154, 1219, 1290, 1358, 1423, 1484,
+ }};
+ /** b, the soft light's blend value: 500 changes nothing, more lifts a channel, less darkens it. */
+ static final int[][] B = {{
+ 340, 287, 235, 215, 250, 327, 389, 428, 451, 465, 476, 489, 517, 531, 528, 509, 482,
+ 230, 169, 118, 129, 208, 311, 388, 440, 470, 477, 479, 482, 494, 497, 490, 468, 448,
+ 130, 72, 50, 99, 200, 312, 398, 460, 494, 498, 495, 482, 468, 465, 464, 451, 441,
+ 80, 53, 72, 133, 225, 324, 412, 476, 510, 513, 506, 487, 469, 463, 462, 460, 456,
+ 80, 83, 125, 186, 250, 315, 384, 460, 514, 518, 507, 498, 484, 467, 461, 462, 460,
+ 103, 126, 171, 217, 247, 273, 323, 406, 486, 508, 500, 499, 480, 454, 451, 456, 453,
+ 139, 170, 204, 224, 224, 218, 248, 326, 412, 470, 485, 478, 460, 444, 448, 448, 440,
+ 175, 210, 227, 232, 220, 197, 205, 266, 357, 439, 470, 467, 455, 443, 440, 433, 423,
+ 210, 243, 263, 271, 249, 221, 224, 269, 357, 433, 466, 471, 463, 443, 429, 417, 403,
+ 246, 280, 309, 313, 291, 270, 272, 309, 379, 437, 472, 476, 462, 436, 413, 398, 381,
+ }, {
+ 1198, 1187, 1163, 1118, 1060, 992, 931, 876, 844, 829, 843, 873, 922, 967, 1006, 1047, 1091,
+ 1158, 1152, 1126, 1071, 997, 917, 845, 789, 752, 726, 728, 766, 829, 878, 909, 947, 987,
+ 1103, 1092, 1057, 993, 911, 830, 759, 705, 658, 628, 628, 669, 734, 780, 808, 841, 880,
+ 1030, 1003, 957, 884, 803, 737, 682, 634, 582, 551, 561, 597, 640, 682, 722, 751, 780,
+ 953, 898, 834, 762, 695, 651, 616, 575, 524, 510, 522, 545, 575, 616, 651, 679, 704,
+ 885, 803, 725, 656, 598, 558, 530, 506, 475, 473, 492, 519, 545, 573, 602, 630, 642,
+ 855, 748, 658, 580, 513, 457, 422, 415, 423, 436, 467, 502, 525, 544, 572, 589, 583,
+ 873, 748, 649, 562, 477, 393, 356, 357, 375, 404, 450, 492, 516, 530, 542, 536, 523,
+ 940, 805, 689, 583, 475, 376, 327, 315, 343, 390, 439, 481, 500, 502, 486, 470, 452,
+ 1025, 882, 743, 612, 479, 367, 304, 297, 344, 376, 401, 427, 440, 438, 435, 425, 395,
+ }, {
+ 679, 778, 870, 929, 960, 960, 945, 932, 937, 963, 1016, 1080, 1130, 1171, 1210, 1229, 1237,
+ 763, 861, 941, 974, 964, 924, 871, 827, 796, 797, 835, 903, 968, 1020, 1061, 1076, 1079,
+ 830, 909, 955, 960, 926, 865, 788, 718, 657, 637, 665, 734, 817, 879, 914, 930, 929,
+ 869, 915, 927, 907, 858, 796, 715, 624, 544, 500, 536, 603, 676, 737, 774, 791, 792,
+ 887, 899, 884, 845, 799, 751, 683, 586, 491, 405, 434, 508, 573, 625, 660, 674, 670,
+ 895, 886, 857, 810, 766, 731, 688, 606, 508, 403, 402, 463, 521, 552, 577, 584, 571,
+ 903, 881, 854, 810, 767, 742, 709, 639, 554, 469, 435, 461, 490, 500, 508, 501, 477,
+ 918, 893, 862, 831, 789, 757, 728, 669, 593, 525, 489, 477, 450, 427, 415, 396, 365,
+ 944, 915, 883, 851, 808, 770, 731, 672, 606, 545, 491, 432, 382, 356, 332, 298, 260,
+ 978, 942, 906, 868, 817, 766, 712, 656, 598, 525, 433, 356, 316, 287, 254, 217, 171,
+ }};
+ }
+}
diff --git a/addons/tatami/plan/src/main/res/drawable/banner.xml b/addons/tatami/plan/src/main/res/drawable/banner.xml
new file mode 100644
index 000000000..bb4ee965a
--- /dev/null
+++ b/addons/tatami/plan/src/main/res/drawable/banner.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="320dp" android:height="180dp" android:viewportWidth="320" android:viewportHeight="180">
+ <path android:fillColor="#1C1A14" android:pathData="M0,0 H320 V180 H0 Z" />
+ <group android:rotation="-20" android:pivotX="160" android:pivotY="90">
+ <path android:fillColor="#8A8F3A" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M-60,-80 H40 V70 H-60 Z" />
+ <path android:fillColor="#86A0A6" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M40,-80 H130 V70 H40 Z" />
+ <path android:fillColor="#B24A2E" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M-60,70 H20 V260 H-60 Z" />
+ <path android:fillColor="#C9A43B" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M20,70 H130 V260 H20 Z" />
+ <path android:fillColor="#E0A05A" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M130,-80 H250 V120 H130 Z" />
+ <path android:fillColor="#5D7F5F" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M250,-80 H380 V120 H250 Z" />
+ <path android:fillColor="#C0B98A" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M130,120 H230 V260 H130 Z" />
+ <path android:fillColor="#A9B56B" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M230,120 H380 V260 H230 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M130,90 L130,80 A10,10 0 0,1 140,90 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M35,70 L45,70 A10,10 0 0,1 35,80 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M255,120 L265,120 A10,10 0 0,1 255,130 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M250,20 L250,10 A10,10 0 0,1 260,20 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M20,165 L20,155 A10,10 0 0,1 30,165 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M230,190 L230,180 A10,10 0 0,1 240,190 Z" />
+ </group>
+</vector>
diff --git a/addons/tatami/plan/src/main/res/drawable/icon.xml b/addons/tatami/plan/src/main/res/drawable/icon.xml
new file mode 100644
index 000000000..7d8bd90f8
--- /dev/null
+++ b/addons/tatami/plan/src/main/res/drawable/icon.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="180" android:viewportHeight="180">
+ <path android:fillColor="#1C1A14" android:pathData="M0,0 H180 V180 H0 Z" />
+ <group android:translateX="-70">
+ <group android:rotation="-20" android:pivotX="160" android:pivotY="90">
+ <path android:fillColor="#8A8F3A" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M-60,-80 H40 V70 H-60 Z" />
+ <path android:fillColor="#86A0A6" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M40,-80 H130 V70 H40 Z" />
+ <path android:fillColor="#B24A2E" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M-60,70 H20 V260 H-60 Z" />
+ <path android:fillColor="#C9A43B" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M20,70 H130 V260 H20 Z" />
+ <path android:fillColor="#E0A05A" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M130,-80 H250 V120 H130 Z" />
+ <path android:fillColor="#5D7F5F" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M250,-80 H380 V120 H250 Z" />
+ <path android:fillColor="#C0B98A" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M130,120 H230 V260 H130 Z" />
+ <path android:fillColor="#A9B56B" android:strokeColor="#15130E" android:strokeWidth="4" android:pathData="M230,120 H380 V260 H230 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M130,90 L130,80 A10,10 0 0,1 140,90 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M35,70 L45,70 A10,10 0 0,1 35,80 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M255,120 L265,120 A10,10 0 0,1 255,130 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M250,20 L250,10 A10,10 0 0,1 260,20 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M20,165 L20,155 A10,10 0 0,1 30,165 Z" />
+ <path android:fillColor="#E8D87A" android:strokeColor="#15130E" android:strokeWidth="1.2" android:pathData="M230,190 L230,180 A10,10 0 0,1 240,190 Z" />
+ </group>
+ </group>
+</vector>
diff --git a/addons/tatami/plan/src/main/res/values/tatami_colors.xml b/addons/tatami/plan/src/main/res/values/tatami_colors.xml
new file mode 100644
index 000000000..cd466a11a
--- /dev/null
+++ b/addons/tatami/plan/src/main/res/values/tatami_colors.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="floor">#FF1C1A14</color>
+</resources>
diff --git a/addons/tatami/plan/src/main/res/values/tatami_strings.xml b/addons/tatami/plan/src/main/res/values/tatami_strings.xml
new file mode 100644
index 000000000..caa1da7c8
--- /dev/null
+++ b/addons/tatami/plan/src/main/res/values/tatami_strings.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="effects_title">Effects</string>
+ <string name="setting_row">%1$s: %2$s</string>
+ <string name="look_label">Look</string>
+ <string name="look_yojohan">Yojōhan</string>
+ <string name="look_nagaya">Nagaya</string>
+ <string name="look_both">Both</string>
+ <string name="swap_label">Swap every</string>
+ <string name="swap_minutes">%d min</string>
+ <string name="effect_grain">Film grain</string>
+ <string name="effect_vignette">Vignette</string>
+ <string name="effect_tilt_shift">Tilt-shift edges</string>
+ <string name="effect_doors">Doors</string>
+ <string name="effect_fixtures">Fixtures</string>
+ <string name="effect_camera">Camera drift and zoom</string>
+</resources>
diff --git a/addons/tatami/plan/src/main/res/values/tatami_styles.xml b/addons/tatami/plan/src/main/res/values/tatami_styles.xml
new file mode 100644
index 000000000..c2855bf3c
--- /dev/null
+++ b/addons/tatami/plan/src/main/res/values/tatami_styles.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- Explicitly opaque: on some firmware a DeviceDefault theme comes out translucent (cleanyourtv PROMPT.md). -->
+ <style name="Theme.Tatami" parent="android:Theme.Material.NoActionBar.Fullscreen">
+ <item name="android:windowBackground">@color/floor</item>
+ <item name="android:colorBackground">@color/floor</item>
+ <item name="android:windowIsTranslucent">false</item>
+ <item name="android:windowIsFloating">false</item>
+ <item name="android:windowSwipeToDismiss">false</item>
+ <item name="android:windowAnimationStyle">@null</item>
+ </style>
+</resources>
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/CameraMatrixTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/CameraMatrixTest.java
new file mode 100644
index 000000000..c53e3447e
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/CameraMatrixTest.java
@@ -0,0 +1,32 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class CameraMatrixTest {
+ private static final float ANGLE = Look.YOJOHAN.camera.angleDeg;
+
+ @Test
+ public void matrixPutsEveryPlanPointWhereTheCameraSays() {
+ float w = 1920, h = 1080;
+ float[] m = new float[16];
+ for (int i = 0; i < 300; i++) {
+ double t = i * 13.3 + (i % 2 == 0 ? 0 : 1_793_500_000.0);
+ boolean moving = i % 3 != 0;
+ CameraMatrix.build(t, w, h, moving, ANGLE, m);
+ float px = (i * 97 % 2000) - 1000f, py = (i * 61 % 1600) - 800f;
+ // column-major: clip = M * (px, py, 0, 1)
+ float cx = m[0] * px + m[4] * py + m[12];
+ float cy = m[1] * px + m[5] * py + m[13];
+ float sx = (cx + 1) / 2 * w, sy = (1 - cy) / 2 * h;
+ // undo the camera the way CameraTest does
+ float dx = sx - (w / 2 + Camera.panX(t, w, moving));
+ float dy = sy - (h / 2 + Camera.panY(t, h, moving));
+ double a = Math.toRadians(-ANGLE);
+ float z = Camera.zoom(t, moving);
+ assertEquals(px, (float) ((dx * Math.cos(a) - dy * Math.sin(a)) / z), 0.05f);
+ assertEquals(py, (float) ((dx * Math.sin(a) + dy * Math.cos(a)) / z), 0.05f);
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/CameraTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/CameraTest.java
new file mode 100644
index 000000000..fcebe3e9a
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/CameraTest.java
@@ -0,0 +1,61 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class CameraTest {
+ private static final float ANGLE = Look.YOJOHAN.camera.angleDeg;
+
+ /** Maps a screen point into plan space the way the renderer's canvas transform does, in reverse. */
+ private static float[] toPlan(float sx, float sy, double t, float w, float h, boolean moving) {
+ float dx = sx - (w / 2 + Camera.panX(t, w, moving));
+ float dy = sy - (h / 2 + Camera.panY(t, h, moving));
+ double a = Math.toRadians(-ANGLE);
+ float zoom = Camera.zoom(t, moving);
+ return new float[] {
+ (float) ((dx * Math.cos(a) - dy * Math.sin(a)) / zoom),
+ (float) ((dx * Math.sin(a) + dy * Math.cos(a)) / zoom)
+ };
+ }
+
+ /** The renderer draws the copy to blur past every screen edge (padded as it pads it), so the plan must reach it too. */
+ private static float margin(int size) {
+ Look.Post post = Look.YOJOHAN.post;
+ return Lens.padded(size, Lens.margin(post), post.blurDivisor);
+ }
+
+ private static void assertCovers(int w, int h, boolean moving) {
+ float pw = Camera.planWidth(w, h, ANGLE), ph = Camera.planHeight(w, h, ANGLE);
+ float mx = margin(w), my = margin(h);
+ for (int i = 0; i < 2000; i++) {
+ double t = i * 7.9 + (i % 2 == 0 ? 0 : 1_793_500_000.0);
+ for (float[] corner : new float[][] {{-mx, -my}, {w + mx, -my}, {-mx, h + my}, {w + mx, h + my}}) {
+ float[] p = toPlan(corner[0], corner[1], t, w, h, moving);
+ assertTrue("corner " + corner[0] + "," + corner[1] + " leaves the plan at t=" + t,
+ Math.abs(p[0]) <= pw / 2 && Math.abs(p[1]) <= ph / 2);
+ }
+ }
+ }
+
+ @Test
+ public void tiltedPlanAlwaysCoversTheScreenAndTheBlurMarginAt1080p() {
+ assertCovers(1920, 1080, true);
+ assertCovers(1920, 1080, false);
+ }
+
+ @Test
+ public void tiltedPlanAlwaysCoversTheScreenAndTheBlurMarginAt720p() {
+ assertCovers(1280, 720, true);
+ assertCovers(1280, 720, false);
+ }
+
+ @Test
+ public void zoomOnlyPullsInAndStaysGentle() {
+ for (int i = 0; i < 5000; i++) {
+ float z = Camera.zoom(i * 3.7, true);
+ assertTrue("zoom " + z, z >= 1f && z <= 1.15f);
+ }
+ assertTrue(Camera.zoom(123.0, false) == 1f);
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/DoorTrackTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/DoorTrackTest.java
new file mode 100644
index 000000000..3d01fcd2e
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/DoorTrackTest.java
@@ -0,0 +1,120 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Random;
+import org.junit.Test;
+
+public class DoorTrackTest {
+ private static final Look LOOK = Look.NAGAYA;
+ private static final DoorTrack TRACK = new DoorTrack(LOOK.doors, LOOK.plan.seed);
+ private static final double NOW = 1_793_500_000.0, FRAME = 1.0 / 60;
+
+ private static double deg(double t) {
+ return Math.toDegrees(TRACK.opening(t));
+ }
+
+ @Test
+ public void staysBetweenShutAndItsMostAndReachesBoth() {
+ double most = 0, least = Double.MAX_VALUE;
+ for (double t = NOW; t < NOW + 600; t += FRAME / 3) {
+ double a = deg(t);
+ most = Math.max(most, a);
+ least = Math.min(least, a);
+ }
+ assertEquals(0, least, 0);
+ assertEquals(LOOK.doors.swingMaxDeg, most, 1e-9);
+ }
+
+ @Test
+ public void neverJumpsBetweenFrames() {
+ long c0 = TRACK.cycle(NOW);
+ double most = 0;
+ for (long base : new long[] {c0, -3, 0}) {
+ for (long c = base; c < base + (base == c0 ? 300 : 10); c++) {
+ for (double t = TRACK.start(c) - 0.5; t < TRACK.start(c + 1); t += FRAME) {
+ most = Math.max(most, Math.abs(deg(t + FRAME) - deg(t)));
+ }
+ }
+ }
+ assertTrue("largest step " + most + " deg in 1/60 s", most <= 2);
+ }
+
+ @Test
+ public void opensEachCycleAndIsShutBeforeTheNext() {
+ long c0 = TRACK.cycle(NOW);
+ for (long c = c0; c < c0 + 400; c++) {
+ double start = TRACK.start(c);
+ assertEquals("cycle " + c, 0, deg(start), 0);
+ assertTrue("cycle " + c + " opens", deg(start + 0.25) > 0);
+ assertEquals("cycle " + c + " shut before the next", 0, deg(TRACK.start(c + 1) - 1e-6), 0);
+ }
+ }
+
+ @Test
+ public void cyclesComeAtUnevenTimes() {
+ long c0 = TRACK.cycle(NOW);
+ double least = Double.MAX_VALUE, most = 0;
+ for (long c = c0; c < c0 + 400; c++) {
+ double gap = TRACK.start(c + 1) - TRACK.start(c);
+ least = Math.min(least, gap);
+ most = Math.max(most, gap);
+ }
+ assertTrue("gaps " + least + " to " + most + " s", most - least > 2 * LOOK.doors.track.cycleJitterSeconds);
+ }
+
+ @Test
+ public void doorsDoNotStartWithTheWalls() {
+ MoveClock walls = new MoveClock(LOOK.rhythm, LOOK.plan.seed);
+ long c0 = TRACK.cycle(NOW);
+ int near = 0, cycles = 3000;
+ for (long c = c0; c < c0 + cycles; c++) {
+ double start = TRACK.start(c);
+ long k = walls.slot(start);
+ double gap = Math.min(start - walls.start(k), walls.start(k + 1) - start);
+ if (gap < 0.25) near++;
+ }
+ assertTrue(near + " of " + cycles + " door cycles start with a wall slot", near < cycles / 5);
+ }
+
+ @Test
+ public void aboutAThirdShutAThirdMovingAThirdOpen() {
+ int shut = 0, open = 0, all = 0;
+ for (double t = NOW; t < NOW + 30_000; t += 0.05) {
+ double a = deg(t);
+ if (a <= 5) shut++;
+ if (a >= 75) open++;
+ all++;
+ }
+ double s = shut / (double) all, o = open / (double) all, m = 1 - s - o;
+ String shares = String.format("shut %.3f, moving %.3f, open %.3f", s, m, o);
+ assertTrue(shares, s > 0.28 && s < 0.39);
+ assertTrue(shares, m > 0.28 && m < 0.39);
+ assertTrue(shares, o > 0.28 && o < 0.39);
+ }
+
+ @Test
+ public void eachDoorRipplesUpToItsMostBehindTheTrack() {
+ double ripple = LOOK.doors.track.rippleSeconds, least = Double.MAX_VALUE, most = 0;
+ for (int piece = 0; piece < 500; piece++) {
+ double d = TRACK.delay(piece);
+ least = Math.min(least, d);
+ most = Math.max(most, d);
+ assertEquals(TRACK.opening(NOW - d), TRACK.opening(NOW, piece), 0);
+ }
+ assertTrue(least >= 0 && most <= ripple);
+ assertTrue("delays spread over the ripple", most - least > 0.8 * ripple);
+ }
+
+ @Test
+ public void theSameAtAnyTimeWhicheverWayTheClockRuns() {
+ DoorTrack fresh = new DoorTrack(LOOK.doors, LOOK.plan.seed);
+ Random random = new Random(11);
+ double[] times = new double[500];
+ for (int i = 0; i < times.length; i++) times[i] = NOW + random.nextDouble() * 1e5;
+ double[] forward = new double[times.length];
+ for (int i = 0; i < times.length; i++) forward[i] = TRACK.opening(times[i]);
+ for (int i = times.length - 1; i >= 0; i--) assertEquals(forward[i], fresh.opening(times[i]), 0);
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/DoorsTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/DoorsTest.java
new file mode 100644
index 000000000..6ed0471af
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/DoorsTest.java
@@ -0,0 +1,160 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import org.junit.Test;
+
+public class DoorsTest {
+
+ private static final Look LOOK = Look.YOJOHAN;
+ private static final double EPOCH = 1_793_500_000.0;
+ private static final float EPS = 0.05f;
+ private static final double ANGLE_EPS = 1e-9;
+
+ /** Early times and wall-clock times like the TV's, on two screen sizes. */
+ private static double time(int i) {
+ return i % 2 == 0 ? i * 7.3 : EPOCH + i * 61.7;
+ }
+
+ private static int height(int i) {
+ return i % 3 == 0 ? 720 : 1080;
+ }
+
+ private static Scene build(Scene scene, int i) {
+ int h = height(i);
+ scene.build(time(i), h * 16 / 9, h, true, false, true);
+ return scene;
+ }
+
+ @Test
+ public void swingStaysBetweenShutAndOpenAndPausesAtBoth() {
+ Scene scene = new Scene(LOOK);
+ double open = Math.toRadians(LOOK.doors.swingMaxDeg), step = 1.0 / 60;
+ int steps = 12 * 60; // more than 2 swings
+ int walls = scene.layout.rooms() - 1;
+ int[] present = new int[walls], shutRun = new int[walls], openRun = new int[walls];
+ int[] longestShut = new int[walls], longestOpen = new int[walls];
+ for (int s = 0; s < steps; s++) {
+ scene.build(EPOCH + s * step, 1920, 1080, true, false, true);
+ Frame f = scene.frame;
+ for (int d = 0; d < f.doorCount; d++) {
+ double a = f.doorOpening[d];
+ assertTrue("opening " + a, a >= 0 && a <= open + ANGLE_EPS);
+ int w = f.doorWall[d];
+ present[w]++;
+ shutRun[w] = a == 0 ? shutRun[w] + 1 : 0;
+ openRun[w] = a >= open - ANGLE_EPS ? openRun[w] + 1 : 0;
+ longestShut[w] = Math.max(longestShut[w], shutRun[w]);
+ longestOpen[w] = Math.max(longestOpen[w], openRun[w]);
+ }
+ }
+ int followed = 0;
+ for (int w = 0; w < walls; w++) {
+ if (present[w] < steps) continue;
+ followed++;
+ assertTrue("wall " + w + " never pauses shut", longestShut[w] * step >= 0.5);
+ assertTrue("wall " + w + " never pauses open", longestOpen[w] * step >= 0.5);
+ }
+ assertTrue("no door stayed for the whole run", followed > 0);
+ }
+
+ @Test
+ public void everyDoorSitsOnItsWallClearOfTheWallsEnds() {
+ Scene scene = new Scene(LOOK);
+ int doors = 0;
+ for (int i = 0; i < 150; i++) {
+ Frame f = build(scene, i).frame;
+ float length = height(i) * LOOK.doors.lengthH, gap = height(i) * LOOK.doors.joinGapH;
+ for (int d = 0; d < f.doorCount; d++) {
+ int w = f.doorWall[d];
+ boolean vertical = f.wallVertical[w];
+ String at = "door " + d + " on wall " + w + " at t=" + time(i);
+ // the hinge is on the wall's centre line
+ assertEquals(at, vertical ? f.wallX0[w] : f.wallY0[w], vertical ? f.doorX[d] : f.doorY[d], EPS);
+ float hinge = vertical ? f.doorY[d] : f.doorX[d];
+ float end = hinge + f.doorAlong[d] * length;
+ float lo = Math.min(hinge, end), hi = Math.max(hinge, end);
+ float from = vertical ? f.wallY0[w] : f.wallX0[w], to = vertical ? f.wallY1[w] : f.wallX1[w];
+ float clear = Math.min(gap, (to - from - length) / 2);
+ assertTrue(at + ": too near the wall's start", lo - from >= clear - EPS);
+ assertTrue(at + ": too near the wall's end", to - hi >= clear - EPS);
+ doors++;
+ }
+ }
+ assertTrue("no doors", doors > 0);
+ }
+
+ /** Joins slide past a door: doors ride their wall and never hide, jump or pop back. */
+ @Test
+ public void doorsNeverPopInOrOutOrJump() {
+ Scene scene = new Scene(LOOK);
+ double step = 1.0 / 60;
+ int[] walls = null;
+ float[] x = null, y = null;
+ float most = 1080 * 0.01f;
+ for (int s = 0; s < 60 * 60; s++) {
+ scene.build(EPOCH + s * step, 1920, 1080, true, false, true);
+ Frame f = scene.frame;
+ int n = f.doorCount;
+ int[] nowWalls = Arrays.copyOf(f.doorWall, n);
+ float[] nowX = Arrays.copyOf(f.doorX, n), nowY = Arrays.copyOf(f.doorY, n);
+ if (walls != null) {
+ assertArrayEquals("the doors changed at frame " + s, walls, nowWalls);
+ for (int d = 0; d < n; d++) {
+ float moved = (float) Math.hypot(nowX[d] - x[d], nowY[d] - y[d]);
+ assertTrue("door on wall " + walls[d] + " jumped " + moved + " at frame " + s, moved < most);
+ }
+ }
+ walls = nowWalls;
+ x = nowX;
+ y = nowY;
+ }
+ assertTrue("no doors", walls.length > 0);
+ }
+
+ @Test
+ public void sameSeedAndTimeGiveTheSameDoors() {
+ Scene a = new Scene(LOOK), b = new Scene(LOOK);
+ for (int i = 0; i < 40; i++) {
+ build(b, 39 - i); // a different past changes nothing
+ Frame fa = build(a, i).frame, fb = build(b, i).frame;
+ assertTrue(fa.doorCount > 0);
+ assertEquals(fa.doorCount, fb.doorCount);
+ int n = fa.doorCount;
+ assertArrayEquals(Arrays.copyOf(fa.doorWall, n), Arrays.copyOf(fb.doorWall, n));
+ assertArrayEquals(Arrays.copyOf(fa.doorAlong, n), Arrays.copyOf(fb.doorAlong, n));
+ assertArrayEquals(Arrays.copyOf(fa.doorSide, n), Arrays.copyOf(fb.doorSide, n));
+ assertArrayEquals(Arrays.copyOf(fa.doorX, n), Arrays.copyOf(fb.doorX, n), 0f);
+ assertArrayEquals(Arrays.copyOf(fa.doorY, n), Arrays.copyOf(fb.doorY, n), 0f);
+ assertArrayEquals(Arrays.copyOf(fa.doorOpening, n), Arrays.copyOf(fb.doorOpening, n), 0.0);
+ }
+ }
+
+ @Test
+ public void eachWallKeepsItsHingeEndAndSwingSide() {
+ Scene scene = new Scene(LOOK);
+ int walls = scene.layout.rooms() - 1;
+ int[] along = new int[walls], side = new int[walls];
+ for (int i = 0; i < 150; i++) {
+ Frame f = build(scene, i).frame;
+ for (int d = 0; d < f.doorCount; d++) {
+ int w = f.doorWall[d];
+ if (along[w] == 0) {
+ along[w] = f.doorAlong[d];
+ side[w] = f.doorSide[d];
+ }
+ assertEquals("wall " + w, along[w], f.doorAlong[d]);
+ assertEquals("wall " + w, side[w], f.doorSide[d]);
+ }
+ }
+ // and they are drawn at random: both ends and both sides show up
+ assertNotEquals(0, Arrays.stream(along).filter(s -> s > 0).count());
+ assertNotEquals(0, Arrays.stream(along).filter(s -> s < 0).count());
+ assertNotEquals(0, Arrays.stream(side).filter(s -> s > 0).count());
+ assertNotEquals(0, Arrays.stream(side).filter(s -> s < 0).count());
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/EffectsTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/EffectsTest.java
new file mode 100644
index 000000000..67383db83
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/EffectsTest.java
@@ -0,0 +1,50 @@
+package io.github.pbanddev.tatami;
+
+import static io.github.pbanddev.tatami.LookSchedule.Mode.BOTH;
+import static io.github.pbanddev.tatami.LookSchedule.Mode.NAGAYA;
+import static io.github.pbanddev.tatami.LookSchedule.Mode.YOJOHAN;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+
+import org.junit.Test;
+
+public class EffectsTest {
+
+ @Test
+ public void lookIsReadFromItsStoredName() {
+ assertSame(YOJOHAN, Effects.look("yojohan"));
+ assertSame(NAGAYA, Effects.look("nagaya"));
+ assertSame(BOTH, Effects.look("both"));
+ for (LookSchedule.Mode mode : LookSchedule.Mode.values()) assertSame(mode, LookSchedule.Mode.of(mode.key));
+ }
+
+ @Test
+ public void anUnknownLookGivesBoth() {
+ for (String stored : new String[] {null, "", "Nagaya", "default", "yojōhan"}) {
+ assertSame(stored, BOTH, Effects.look(stored));
+ assertNull(stored, LookSchedule.Mode.of(stored));
+ }
+ }
+
+ @Test
+ public void swapMinutesFrom1To60AreKept() {
+ for (int minutes : new int[] {1, 5, 7, 10, 30, 60}) assertEquals(minutes, Effects.swapMinutes(minutes));
+ }
+
+ @Test
+ public void otherSwapMinutesGiveTen() {
+ for (int minutes : new int[] {0, -10, 61, Integer.MAX_VALUE, Integer.MIN_VALUE}) {
+ assertEquals(10, Effects.swapMinutes(minutes));
+ }
+ }
+
+ @Test
+ public void okStepsThroughTheRowsChoices() {
+ assertSame(NAGAYA, BOTH.next());
+ assertSame(YOJOHAN, NAGAYA.next());
+ assertSame(BOTH, YOJOHAN.next());
+ int[][] steps = {{5, 10}, {10, 30}, {30, 60}, {60, 5}, {1, 5}, {7, 10}, {45, 60}};
+ for (int[] step : steps) assertEquals("from " + step[0], step[1], Effects.nextSwapMinutes(step[0]));
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/FixturesTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/FixturesTest.java
new file mode 100644
index 000000000..3c335c7d0
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/FixturesTest.java
@@ -0,0 +1,162 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import org.junit.Test;
+
+public class FixturesTest {
+
+ private static final float EPS = 0.05f;
+ private static final int[][] SCREENS = {{1920, 1080}, {1280, 720}};
+ /** The fixtures' boxes in px at 1080p, unturned, by kind: tub, toilet, stairs. */
+ private static final float[][] BOX = {{117.5f, 67.6f}, {40f, 60f}, {211.7f, 95.1f}};
+
+ /** A minute of steps, then wall-clock times like the TV's. */
+ private static double time(int i) {
+ return i < 60 ? i * 23.1 : 1_793_500_000.0 + i * 401.3;
+ }
+
+ /** Px at 1080p (on screen at the middle zoom 1.075) in plan units on a screen this tall. */
+ private static float px(float px, float screenH) {
+ return px / 1080f * screenH / 1.075f;
+ }
+
+ /** From fixture k's box to its room's wall faces: left, top, right, bottom. */
+ private static float[] faceGaps(Frame f, int k, float screenH) {
+ float half = screenH * Look.YOJOHAN.walls.widthH / 2;
+ int r = f.fixtureRoom[k];
+ return new float[] {
+ f.fixtureX[k] - (f.roomX[r] + half),
+ f.fixtureY[k] - (f.roomY[r] + half),
+ f.roomX[r] + f.roomW[r] - half - (f.fixtureX[k] + f.fixtureW[k]),
+ f.roomY[r] + f.roomH[r] - half - (f.fixtureY[k] + f.fixtureH[k])};
+ }
+
+ @Test
+ public void fixturesStayInsideTheirWallFacesWithTheirGapsAtAnyTime() {
+ Scene scene = new Scene(Look.YOJOHAN);
+ int seen = 0;
+ for (int i = 0; i < 80; i++) {
+ int[] screen = SCREENS[i % 2];
+ float h = screen[1];
+ scene.build(time(i), screen[0], screen[1], false, true, false);
+ Frame f = scene.frame;
+ for (int k = 0; k < f.fixtureCount; k++) {
+ seen++;
+ float[] gap = faceGaps(f, k, h);
+ int kind = f.fixtureKind[k], turn = f.fixtureTurn[k];
+ String at = "kind " + kind + " turn " + turn + " in room " + f.fixtureRoom[k] + " at t=" + time(i)
+ + ", " + screen[1] + "p, gaps " + Arrays.toString(gap);
+ for (float g : gap) assertTrue("crosses a wall face: " + at, g >= -EPS);
+ if (kind == Fixtures.TOILET) {
+ // turn 0 backs onto the top wall, then clockwise: right, bottom, left
+ float back = gap[(turn + 1) % 4];
+ assertTrue("toilet gap: " + at, back >= px(0.020f * 1080, h) && back <= px(0.040f * 1080, h));
+ assertEquals("toilet off centre: " + at, gap[turn % 4], gap[(turn + 2) % 4], EPS);
+ } else if (kind == Fixtures.TUB) {
+ boolean corner = false;
+ for (int s = 0; s < 4; s++) corner |= inTubGap(gap[s], h) && inTubGap(gap[(s + 1) % 4], h);
+ assertTrue("tub not in a corner: " + at, corner);
+ }
+ }
+ }
+ assertTrue(seen > 0);
+ }
+
+ private static boolean inTubGap(float gap, float h) {
+ return gap >= px(0.025f * 1080, h) - EPS && gap <= px(0.028f * 1080, h) + EPS;
+ }
+
+ @Test
+ public void stairsSitFlushInTheCornerTheirArrowPointsInto() {
+ Scene scene = new Scene(Look.YOJOHAN);
+ int seen = 0;
+ for (int i = 0; i < 80; i++) {
+ scene.build(time(i), 1920, 1080, false, true, false);
+ Frame f = scene.frame;
+ for (int k = 0; k < f.fixtureCount; k++) {
+ if (f.fixtureKind[k] != Fixtures.STAIRS) continue;
+ seen++;
+ int turn = f.fixtureTurn[k];
+ float[] gap = faceGaps(f, k, 1080);
+ // turn 0 runs right into the bottom-right corner, then clockwise
+ String at = "turn " + turn + " at t=" + time(i) + ", gaps " + Arrays.toString(gap);
+ assertEquals("end not flush: " + at, 0f, gap[(turn + 2) % 4], EPS);
+ assertEquals("side not flush: " + at, 0f, gap[(turn + 3) % 4], EPS);
+ }
+ }
+ assertTrue(seen > 0);
+ }
+
+ @Test
+ public void fixturesKeepTheirRoomKindTurnAndSizeOverTime() {
+ Scene scene = new Scene(Look.YOJOHAN);
+ Frame f = scene.frame;
+ scene.build(time(0), 1920, 1080, false, true, false);
+ int count = f.fixtureCount;
+ int[] room = Arrays.copyOf(f.fixtureRoom, count), kind = Arrays.copyOf(f.fixtureKind, count),
+ turn = Arrays.copyOf(f.fixtureTurn, count);
+ for (int i = 0; i < 80; i++) {
+ scene.build(time(i), 1920, 1080, false, true, false);
+ assertEquals(count, f.fixtureCount);
+ for (int k = 0; k < count; k++) {
+ assertEquals(room[k], f.fixtureRoom[k]);
+ assertEquals(kind[k], f.fixtureKind[k]);
+ assertEquals(turn[k], f.fixtureTurn[k]);
+ int odd = turn[k] % 2;
+ assertEquals(px(BOX[kind[k]][odd], 1080), f.fixtureW[k], px(1, 1080));
+ assertEquals(px(BOX[kind[k]][1 - odd], 1080), f.fixtureH[k], px(1, 1080));
+ }
+ }
+ }
+
+ @Test
+ public void aboutOneRoomInFiveHoldsAFixtureAndTheKindsFollowTheirWeights() {
+ Scene scene = new Scene(Look.YOJOHAN);
+ scene.build(0, 1920, 1080, false, true, false);
+ Frame f = scene.frame;
+ int[] count = new int[3];
+ for (int k = 0; k < f.fixtureCount; k++) count[f.fixtureKind[k]]++;
+ float share = (float) f.fixtureCount / f.roomCount;
+ assertTrue("share " + share, share >= 0.15f && share <= 0.25f);
+ assertTrue("tub, toilet, stairs: " + Arrays.toString(count),
+ count[Fixtures.TOILET] >= count[Fixtures.STAIRS] && count[Fixtures.STAIRS] >= count[Fixtures.TUB]
+ && count[Fixtures.TUB] > 0);
+ }
+
+ @Test
+ public void everyShapeFillsItsBoxAtEveryTurnWithinTheVertexBudget() {
+ float h = 1080f;
+ Frame f = new Frame(1);
+ SceneMesh mesh = new SceneMesh(1, Look.YOJOHAN);
+ for (int kind = 0; kind < 3; kind++) {
+ for (int turn = 0; turn < 4; turn++) {
+ f.fixtureKind[0] = kind;
+ f.fixtureTurn[0] = turn;
+ f.fixtureX[0] = 300f;
+ f.fixtureY[0] = -200f;
+ f.fixtureW[0] = px(BOX[kind][turn % 2], h);
+ f.fixtureH[0] = px(BOX[kind][1 - turn % 2], h);
+ mesh.floats = 0;
+ FixtureShapes.add(mesh, f, 0, h, Look.YOJOHAN);
+ String at = "kind " + kind + " turn " + turn;
+ assertTrue(at, mesh.floats / SceneMesh.FLOATS_PER_VERTEX <= FixtureShapes.MAX_VERTICES);
+ float x0 = Float.MAX_VALUE, y0 = Float.MAX_VALUE, x1 = -Float.MAX_VALUE, y1 = -Float.MAX_VALUE;
+ for (int i = 0; i < mesh.floats; i += SceneMesh.FLOATS_PER_VERTEX) {
+ x0 = Math.min(x0, mesh.data[i]);
+ x1 = Math.max(x1, mesh.data[i]);
+ y0 = Math.min(y0, mesh.data[i + 1]);
+ y1 = Math.max(y1, mesh.data[i + 1]);
+ }
+ // the stairs' dot sits on the free-end line, so it reaches 1.75 px past the box
+ float tolerance = px(2, h);
+ assertEquals(at, f.fixtureX[0], x0, tolerance);
+ assertEquals(at, f.fixtureY[0], y0, tolerance);
+ assertEquals(at, f.fixtureX[0] + f.fixtureW[0], x1, tolerance);
+ assertEquals(at, f.fixtureY[0] + f.fixtureH[0], y1, tolerance);
+ }
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/FloorPlanTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/FloorPlanTest.java
new file mode 100644
index 000000000..200c29065
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/FloorPlanTest.java
@@ -0,0 +1,207 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.Test;
+
+public class FloorPlanTest {
+
+ private static final Look LOOK = Look.YOJOHAN;
+ private static final float SCREEN_H = 1080f;
+ /** The plan Scene lays out for a 1080p screen: plan units are screen pixels at zoom 1. */
+ private static final float W = Camera.planWidth(1920, SCREEN_H, LOOK.camera.angleDeg);
+ private static final float H = Camera.planHeight(1920, SCREEN_H, LOOK.camera.angleDeg);
+ private static final float EPS = 0.05f;
+ /** Epoch seconds in November 2026: the clock Home and the screensaver both read. */
+ private static final double NOW = 1_793_500_000.0;
+ private static final long[] SEEDS = {LOOK.plan.seed, 1, 2, 3, 4, 5, 6, 8};
+
+ private static Frame layout(FloorPlan plan, double t) {
+ Frame frame = new Frame(plan.rooms);
+ plan.layout(t, -W / 2, -H / 2, W, H, frame);
+ return frame;
+ }
+
+ private static double[] times(int count) {
+ double[] out = new double[count];
+ for (int i = 0; i < count; i++) out[i] = i % 2 == 0 ? i * 13.7 : NOW + i * 97.3;
+ return out;
+ }
+
+ @Test
+ public void roomsFillThePlanExactlyAtAnyTime() {
+ FloorPlan plan = new FloorPlan(LOOK);
+ for (double t : times(60)) {
+ Frame f = layout(plan, t);
+ assertEquals(plan.rooms, f.roomCount);
+ double area = 0;
+ for (int i = 0; i < f.roomCount; i++) area += (double) f.roomW[i] * f.roomH[i];
+ assertEquals("t=" + t, (double) W * H, area, W * H * 1e-4);
+ }
+ }
+
+ @Test
+ public void roomsNeverOverlapAndStayInsideThePlan() {
+ FloorPlan plan = new FloorPlan(LOOK);
+ for (double t : times(60)) {
+ Frame f = layout(plan, t);
+ for (int i = 0; i < f.roomCount; i++) {
+ assertTrue(f.roomW[i] > 0 && f.roomH[i] > 0);
+ assertTrue(f.roomX[i] >= -W / 2 - EPS && f.roomX[i] + f.roomW[i] <= W / 2 + EPS);
+ assertTrue(f.roomY[i] >= -H / 2 - EPS && f.roomY[i] + f.roomH[i] <= H / 2 + EPS);
+ for (int j = i + 1; j < f.roomCount; j++) {
+ float ox = Math.min(f.roomX[i] + f.roomW[i], f.roomX[j] + f.roomW[j]) - Math.max(f.roomX[i], f.roomX[j]);
+ float oy = Math.min(f.roomY[i] + f.roomH[i], f.roomY[j] + f.roomH[j]) - Math.max(f.roomY[i], f.roomY[j]);
+ assertTrue("rooms " + i + " and " + j + " overlap at t=" + t, ox <= EPS || oy <= EPS);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void sameSeedAndTimeGiveTheSameFrame() {
+ Frame a = layout(new FloorPlan(LOOK), NOW);
+ Frame b = layout(new FloorPlan(LOOK), NOW);
+ assertArrayEquals(a.roomX, b.roomX, 0f);
+ assertArrayEquals(a.roomY, b.roomY, 0f);
+ assertArrayEquals(a.roomW, b.roomW, 0f);
+ assertArrayEquals(a.roomH, b.roomH, 0f);
+ assertArrayEquals(a.wallX0, b.wallX0, 0f);
+ assertArrayEquals(a.wallY0, b.wallY0, 0f);
+ assertArrayEquals(a.wallX1, b.wallX1, 0f);
+ assertArrayEquals(a.wallY1, b.wallY1, 0f);
+ }
+
+ @Test
+ public void wallsMoveOverTime() {
+ FloorPlan plan = new FloorPlan(LOOK);
+ Frame a = layout(plan, NOW);
+ Frame b = layout(plan, NOW + 2);
+ float moved = 0;
+ for (int i = 0; i < a.roomCount; i++) moved = Math.max(moved, Math.abs(a.roomW[i] - b.roomW[i]));
+ assertTrue(moved > 0.5f);
+ }
+
+ @Test
+ public void everyWallIsARoomBoundaryOnBothSidesAndThereIsOneFewerThanRooms() {
+ FloorPlan plan = new FloorPlan(LOOK);
+ for (double t : times(60)) {
+ Frame f = layout(plan, t);
+ assertEquals(f.roomCount - 1, f.wallCount);
+ for (int k = 0; k < f.wallCount; k++) {
+ boolean vertical = f.wallVertical[k];
+ float line = vertical ? f.wallX0[k] : f.wallY0[k];
+ float from = vertical ? f.wallY0[k] : f.wallX0[k], to = vertical ? f.wallY1[k] : f.wallX1[k];
+ assertEquals(line, vertical ? f.wallX1[k] : f.wallY1[k], 0f);
+ assertTrue("wall " + k + " has no length at t=" + t, to > from);
+ float before = 0, after = 0;
+ for (int i = 0; i < f.roomCount; i++) {
+ float lo = vertical ? f.roomY[i] : f.roomX[i], hi = lo + (vertical ? f.roomH[i] : f.roomW[i]);
+ float near = vertical ? f.roomX[i] : f.roomY[i], far = near + (vertical ? f.roomW[i] : f.roomH[i]);
+ float overlap = Math.min(hi, to) - Math.max(lo, from);
+ if (overlap <= 0) continue;
+ if (Math.abs(far - line) < EPS) before += overlap;
+ if (Math.abs(near - line) < EPS) after += overlap;
+ }
+ assertEquals("wall " + k + " at t=" + t, to - from, before, 0.5f);
+ assertEquals("wall " + k + " at t=" + t, to - from, after, 0.5f);
+ }
+ }
+ }
+
+ @Test
+ public void everyRoomStaysAtLeastItsSmallestSize() {
+ for (long seed : SEEDS) {
+ FloorPlan plan = new FloorPlan(LOOK, seed);
+ for (double t : times(400)) {
+ Frame f = layout(plan, t);
+ for (int i = 0; i < f.roomCount; i++) {
+ assertTrue(f.roomMinW[i] > 0 && f.roomMinH[i] > 0);
+ assertTrue("seed " + seed + " room " + i + " narrower than its smallest at t=" + t, f.roomW[i] >= f.roomMinW[i] - EPS);
+ assertTrue("seed " + seed + " room " + i + " shorter than its smallest at t=" + t, f.roomH[i] >= f.roomMinH[i] - EPS);
+ }
+ }
+ }
+ }
+
+ /** A wall sliding past a windmill centre's corner, or past a wall in line with it, lines up only for a moment. */
+ private static final double MOMENT = 3;
+
+ @Test
+ public void atLeastOneRoomInTwelveIsAWindmillCentre() {
+ for (long seed : SEEDS) {
+ FloorPlan plan = new FloorPlan(LOOK, seed);
+ for (double t : times(40)) {
+ int mills = Math.max(windmillCentres(layout(plan, t)), windmillCentres(layout(plan, t + MOMENT)));
+ assertTrue("seed " + seed + ": " + mills + " windmill centres in " + plan.rooms + " rooms at t=" + t,
+ mills * 12 >= plan.rooms);
+ }
+ }
+ }
+
+ @Test
+ public void noStraightWallRunsFromOneEdgeOfThePlanToTheOtherForMoreThanAMoment() {
+ for (long seed : SEEDS) {
+ FloorPlan plan = new FloorPlan(LOOK, seed);
+ for (double t : times(400)) {
+ assertTrue("seed " + seed + ": a wall crosses the plan at t=" + t,
+ !crossesThePlan(layout(plan, t)) || !crossesThePlan(layout(plan, t + MOMENT)));
+ }
+ }
+ }
+
+ private static int windmillCentres(Frame f) {
+ int mills = 0;
+ for (int k = 0; k < f.roomCount; k++) if (PlanGeometry.isWindmillCentre(f, k, 1f)) mills++;
+ return mills;
+ }
+
+ private static boolean crossesThePlan(Frame f) {
+ for (float[] line : straightWalls(f)) {
+ boolean vertical = line[0] == 1;
+ float start = vertical ? -H / 2 : -W / 2, end = -start;
+ if (line[2] <= start + 1 && line[3] >= end - 1) return true;
+ }
+ return false;
+ }
+
+ @Test
+ public void everyRoomKeepsItsShortSideAndShapeAtAnyTime() {
+ float shortest = LOOK.plan.minSideH * SCREEN_H;
+ for (long seed : SEEDS) {
+ FloorPlan plan = new FloorPlan(LOOK, seed);
+ for (double t : times(3000)) {
+ Frame f = layout(plan, t);
+ for (int i = 0; i < f.roomCount; i++) {
+ float lo = Math.min(f.roomW[i], f.roomH[i]), hi = Math.max(f.roomW[i], f.roomH[i]);
+ assertTrue("seed " + seed + " room " + i + " short side " + lo + " at t=" + t, lo >= shortest - EPS);
+ assertTrue("seed " + seed + " room " + i + " aspect " + hi / lo + " at t=" + t, hi <= LOOK.plan.maxAspect * lo);
+ }
+ }
+ }
+ }
+
+ /** Joins collinear walls that touch: {vertical 1 or 0, coordinate, from, to}. */
+ private static List<float[]> straightWalls(Frame f) {
+ List<float[]> pieces = new ArrayList<>();
+ for (int k = 0; k < f.wallCount; k++) {
+ boolean v = f.wallVertical[k];
+ pieces.add(new float[] {v ? 1 : 0, v ? f.wallX0[k] : f.wallY0[k], v ? f.wallY0[k] : f.wallX0[k], v ? f.wallY1[k] : f.wallX1[k]});
+ }
+ pieces.sort((a, b) -> a[0] != b[0] ? Float.compare(a[0], b[0]) : a[1] != b[1] ? Float.compare(a[1], b[1]) : Float.compare(a[2], b[2]));
+ List<float[]> lines = new ArrayList<>();
+ for (float[] p : pieces) {
+ float[] last = lines.isEmpty() ? null : lines.get(lines.size() - 1);
+ if (last != null && last[0] == p[0] && Math.abs(last[1] - p[1]) < EPS && p[2] <= last[3] + EPS) {
+ last[3] = Math.max(last[3], p[3]);
+ } else {
+ lines.add(p.clone());
+ }
+ }
+ return lines;
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/GrainTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/GrainTest.java
new file mode 100644
index 000000000..f5f8022b3
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/GrainTest.java
@@ -0,0 +1,80 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import org.junit.Test;
+
+public class GrainTest {
+ private static final int S = Grain.SIZE;
+ private static final double FPS = 23.976;
+
+ @Test
+ public void theFieldHasMeanZeroAndStdOne() {
+ float[] n = Grain.field(1L);
+ assertEquals(S * S, n.length);
+ double sum = 0, squares = 0;
+ for (float v : n) {
+ sum += v;
+ squares += (double) v * v;
+ }
+ double mean = sum / n.length;
+ assertEquals(0, mean, 1e-4);
+ assertEquals(1, Math.sqrt(squares / n.length - mean * mean), 1e-4);
+ }
+
+ /** The grain comes in clumps of about 2 px: neighbours correlate ~0.5 across and down, and the tile wraps. */
+ @Test
+ public void neighboursCorrelateLikeFilmGrain() {
+ float[] n = Grain.field(1L);
+ double across = 0, down = 0;
+ for (int y = 0; y < S; y++) {
+ for (int x = 0; x < S; x++) {
+ float v = n[y * S + x];
+ across += v * n[y * S + (x + 1) % S];
+ down += v * n[((y + 1) % S) * S + x];
+ }
+ }
+ assertEquals(0.52, across / n.length, 0.05);
+ assertEquals(0.52, down / n.length, 0.05);
+ }
+
+ @Test
+ public void textureBytesAreHalfPlusAnEighthOfTheNoiseClamped() {
+ float[] n = Grain.field(1L);
+ byte[] bytes = Grain.texture(n);
+ assertEquals(n.length, bytes.length);
+ for (int i = 0; i < n.length; i++) {
+ double level = Math.min(1, Math.max(0, 0.5 + n[i] / 8.0));
+ assertEquals("texel " + i, Math.round(level * 255), bytes[i] & 0xFF);
+ }
+ }
+
+ @Test
+ public void theSameSeedGivesTheSameTexture() {
+ assertArrayEquals(Grain.texture(Grain.field(1L)), Grain.texture(Grain.field(1L)));
+ assertFalse(Arrays.equals(Grain.texture(Grain.field(1L)), Grain.texture(Grain.field(2L))));
+ }
+
+ /** The wall clock is ~1.8e9 s, which float cannot split into 1/24 s steps. */
+ @Test
+ public void theTileJumpsOncePerSourceFrameToWholeTexelsInsideTheTile() {
+ long first = (long) Math.floor(1_793_500_000.0 * FPS);
+ float[] previous = new float[2], early = new float[2], late = new float[2];
+ Grain.offset((first - 0.5) / FPS, FPS, previous);
+ for (long tick = first; tick < first + 500; tick++) {
+ Grain.offset((tick + 0.1) / FPS, FPS, early);
+ Grain.offset((tick + 0.9) / FPS, FPS, late);
+ assertArrayEquals("held within a source frame", early, late, 0f);
+ assertFalse("moved at tick " + tick, Arrays.equals(previous, early));
+ for (float o : early) {
+ assertTrue(o >= 0f && o < 1f);
+ assertEquals("whole texels", Math.rint(o * S), o * S, 0.0);
+ }
+ System.arraycopy(early, 0, previous, 0, 2);
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/LensTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/LensTest.java
new file mode 100644
index 000000000..a89265395
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/LensTest.java
@@ -0,0 +1,79 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class LensTest {
+ private static final Look.Post POST = Look.YOJOHAN.post;
+ private static final int W = 1920, H = 1080;
+
+ /** The lens formulas, written out in Java: vignette times colour ramp for channel c at p (half heights, y up). */
+ private static double gain(double px, double py, int c) {
+ double k = smoothstep(0.206, 1.64, Math.hypot((px + 0.071) * 0.574, py - 0.054));
+ double[] ramp = {0.045 * px, 0.0, -0.05 * px + 0.03 * py};
+ return (1 - 0.42 * k * k * k) * Math.exp(ramp[c]);
+ }
+
+ private static double blur(double px, double py) {
+ return smoothstep(0.837, 1.157, Math.hypot((px - 0.030) * 0.611, py));
+ }
+
+ private static double smoothstep(double a, double b, double x) {
+ double t = Math.max(0, Math.min(1, (x - a) / (b - a)));
+ return t * t * (3 - 2 * t);
+ }
+
+ @Test
+ public void everyTexelHoldsHalfTheGainAndTheBlurMaskAtItsCentre() {
+ int mw = Lens.width(W), mh = Lens.height(H);
+ byte[] map = Lens.map(W, H, POST);
+ assertEquals(4 * mw * mh, map.length);
+ for (int j = 0; j < mh; j += 7) {
+ for (int i = 0; i < mw; i += 5) {
+ // texel centre in screen pixels, y up (row 0 is the bottom, as GL reads it)
+ double x = (i + 0.5) * W / mw, y = (j + 0.5) * H / mh;
+ double px = (x - W / 2.0) / (H / 2.0), py = (y - H / 2.0) / (H / 2.0);
+ int at = 4 * (j * mw + i);
+ for (int c = 0; c < 3; c++) {
+ assertEquals("texel " + i + "," + j + " channel " + c, gain(px, py, c) / 2, (map[at + c] & 0xFF) / 255.0, 0.6 / 255);
+ }
+ assertEquals("texel " + i + "," + j + " blur", blur(px, py), (map[at + 3] & 0xFF) / 255.0, 0.6 / 255);
+ }
+ }
+ }
+
+ @Test
+ public void theCornersDarkenAndTheMiddleStaysSharp() {
+ int mw = Lens.width(W), mh = Lens.height(H);
+ byte[] map = Lens.map(W, H, POST);
+ int corner = 0, middle = 4 * ((mh / 2) * mw + mw / 2);
+ double cornerGain = 2 * (map[corner + 1] & 0xFF) / 255.0;
+ assertTrue("corner gain " + cornerGain, cornerGain > 0.55 && cornerGain < 0.8);
+ assertEquals(0, map[middle + 3] & 0xFF);
+ assertEquals(255, map[corner + 3] & 0xFF);
+ }
+
+ @Test
+ public void theMarginCoversHowFarTheBlurReachesAndKeepsTheSmallCopyWhole() {
+ int m = Lens.margin(POST), d = POST.blurDivisor;
+ float farthest = 0;
+ for (float o : POST.blurOffsets) farthest = Math.max(farthest, o);
+ // the 4x4 box reaches 2 px, each blur tap 1 small texel past its offset (bilinear)
+ assertTrue("margin " + m, m >= 2 + d * (farthest + 1));
+ assertEquals("a whole number of small texels", 0, m % d);
+ }
+
+ @Test
+ public void thePaddedMarginKeepsTheWiderCopyInWholeGpuTilesWhenItCan() {
+ int m = Lens.margin(POST), d = POST.blurDivisor;
+ assertEquals(24, Lens.padded(1920, m, d)); // 1968 = 123 tiles of 16
+ assertEquals(20, Lens.padded(1080, m, d)); // 1120 = 70 tiles
+ assertEquals(m, Lens.padded(1279, m, d)); // an odd size never fits whole tiles: keep the least
+ for (int size : new int[] {720, 1280, 1920, 1080, 2160, 3840, 1279}) {
+ int p = Lens.padded(size, m, d);
+ assertTrue(p >= m && p % d == 0);
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/LookScheduleTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/LookScheduleTest.java
new file mode 100644
index 000000000..f8d07d126
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/LookScheduleTest.java
@@ -0,0 +1,140 @@
+package io.github.pbanddev.tatami;
+
+import static io.github.pbanddev.tatami.LookSchedule.Mode.BOTH;
+import static io.github.pbanddev.tatami.LookSchedule.Mode.NAGAYA;
+import static io.github.pbanddev.tatami.LookSchedule.Mode.YOJOHAN;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class LookScheduleTest {
+ private static final double DIP = LookSchedule.DIP_SECONDS, WAIT = LookSchedule.WAIT_SECONDS;
+ private static final double NEVER = Double.POSITIVE_INFINITY;
+ private static final double LONG_AGO = 0;
+ /** A wall-clock time near today's. */
+ private static final double NOW = 1_793_500_000.0;
+ private static final int[] PERIODS = {1, 5, 10, 30, 60};
+
+ private final LookSchedule s = new LookSchedule();
+
+ private void check(double t, LookSchedule.Mode mode, double swapSeconds, double readySince, double startedAt,
+ Look look, float fade) {
+ s.at(t, mode, swapSeconds, readySince, startedAt);
+ String at = "t=" + t + " mode=" + mode + " swap=" + swapSeconds;
+ assertSame(at, look, s.look);
+ assertEquals(at, fade, s.fade, 1e-5f);
+ }
+
+ /** Started long ago, Nagaya ready long ago. */
+ private void settled(double t, LookSchedule.Mode mode, double swapSeconds, Look look, float fade) {
+ check(t, mode, swapSeconds, LONG_AGO, LONG_AGO, look, fade);
+ }
+
+ @Test
+ public void yojohanAndNagayaModesHoldTheirLook() {
+ for (double t = NOW; t < NOW + 7200; t += 37.3) {
+ settled(t, YOJOHAN, 600, Look.YOJOHAN, 1f);
+ settled(t, NAGAYA, 600, Look.NAGAYA, 1f);
+ }
+ }
+
+ @Test
+ public void bothShowsNagayaInEvenPeriodsAndYojohanInOddOnes() {
+ for (int minutes : PERIODS) {
+ double p = minutes * 60.0;
+ long first = (long) Math.floor(NOW / p);
+ for (long n = first; n < first + 4; n++) {
+ settled((n + 0.5) * p, BOTH, p, n % 2 == 0 ? Look.NAGAYA : Look.YOJOHAN, 1f);
+ }
+ }
+ }
+
+ @Test
+ public void everySwapDipsToDarkAndChangesLookInTheDark() {
+ for (int minutes : PERIODS) {
+ double p = minutes * 60.0;
+ long first = (long) Math.ceil(NOW / p);
+ for (long k = first; k < first + 2; k++) { // one swap into each look
+ double b = k * p;
+ Look before = k % 2 == 0 ? Look.YOJOHAN : Look.NAGAYA, after = k % 2 == 0 ? Look.NAGAYA : Look.YOJOHAN;
+ settled(b - DIP - 0.01, BOTH, p, before, 1f);
+ settled(b - DIP / 2, BOTH, p, before, 0.5f);
+ settled(b, BOTH, p, after, 0f);
+ settled(b + DIP / 2, BOTH, p, after, 0.5f);
+ settled(b + DIP + 0.01, BOTH, p, after, 1f);
+ s.at(b - 1 / 60.0, BOTH, p, LONG_AGO, LONG_AGO);
+ assertTrue("one frame before the swap it is all but black", s.fade < 1e-3f);
+ s.at(b + 1 / 60.0, BOTH, p, LONG_AGO, LONG_AGO);
+ assertTrue("one frame after the swap it is all but black", s.fade < 1e-3f);
+ }
+ }
+ }
+
+ @Test
+ public void fadeIsOneOutsideSwaps() {
+ for (int minutes : PERIODS) {
+ double p = minutes * 60.0;
+ double b = Math.ceil(NOW / p) * p;
+ for (double t = b; t < b + 2 * p; t += p / 997) {
+ double fromSwap = Math.min(t - b, Math.min(Math.abs(b + p - t), b + 2 * p - t));
+ if (fromSwap <= DIP) continue;
+ s.at(t, BOTH, p, LONG_AGO, LONG_AGO);
+ assertEquals("t=" + t, 1f, s.fade, 0f);
+ }
+ }
+ }
+
+ @Test
+ public void aStartWhileNagayaBuildsWaitsInTheDarkThenFadesNagayaIn() {
+ double start = NOW, ready = NOW + 0.2;
+ for (LookSchedule.Mode mode : new LookSchedule.Mode[] {NAGAYA, BOTH}) {
+ double p = 600, t0 = Math.floor(NOW / (2 * p)) * 2 * p + 100; // in an even period: Nagaya's
+ double s0 = mode == BOTH ? t0 : start, r0 = s0 + (ready - start);
+ check(s0, mode, p, r0, s0, Look.YOJOHAN, 0f);
+ check(r0, mode, p, r0, s0, Look.NAGAYA, 0f);
+ check(r0 + DIP / 2, mode, p, r0, s0, Look.NAGAYA, 0.5f);
+ check(r0 + DIP + 0.01, mode, p, r0, s0, Look.NAGAYA, 1f);
+ }
+ }
+
+ @Test
+ public void aStartInYojohansPeriodShowsItAtOnce() {
+ double p = 600, t0 = Math.floor(NOW / (2 * p)) * 2 * p + p + 100; // an odd period
+ check(t0, BOTH, p, t0 + 0.2, t0, Look.YOJOHAN, 1f);
+ check(t0 + 1, BOTH, p, t0 + 0.2, t0, Look.YOJOHAN, 1f);
+ }
+
+ @Test
+ public void aLateNagayaLetsYojohanInThenDipsOver() {
+ double start = NOW, ready = NOW + WAIT + 10;
+ check(start + WAIT / 2, NAGAYA, 600, ready, start, Look.YOJOHAN, 0f);
+ check(start + WAIT + DIP / 2, NAGAYA, 600, ready, start, Look.YOJOHAN, 0.5f);
+ check(start + WAIT + DIP + 0.01, NAGAYA, 600, ready, start, Look.YOJOHAN, 1f);
+ check(ready + DIP / 2, NAGAYA, 600, ready, start, Look.YOJOHAN, 0.5f);
+ check(ready + DIP, NAGAYA, 600, ready, start, Look.NAGAYA, 0f);
+ check(ready + 1.5 * DIP, NAGAYA, 600, ready, start, Look.NAGAYA, 0.5f);
+ check(ready + 2 * DIP + 0.01, NAGAYA, 600, ready, start, Look.NAGAYA, 1f);
+ }
+
+ @Test
+ public void aNagayaThatNeverComesLeavesYojohanWithoutDips() {
+ for (int minutes : PERIODS) {
+ double p = minutes * 60.0;
+ double b = Math.ceil(NOW / p) * p;
+ for (double t = b; t < b + 3 * p; t += 0.3) check(t, BOTH, p, NEVER, LONG_AGO, Look.YOJOHAN, 1f);
+ }
+ check(NOW + WAIT + DIP + 1, NAGAYA, 600, NEVER, NOW, Look.YOJOHAN, 1f);
+ }
+
+ @Test
+ public void aLateNagayaWaitsForItsOwnPeriodInBoth() {
+ double p = 600, odd = (Math.floor(NOW / (2 * p)) * 2 + 1) * p; // Yojōhan's period
+ double ready = odd + 100;
+ check(ready + DIP, BOTH, p, ready, LONG_AGO, Look.YOJOHAN, 1f); // no dip in Yojōhan's period
+ check(odd + p - DIP / 2, BOTH, p, ready, LONG_AGO, Look.YOJOHAN, 0.5f);
+ check(odd + p, BOTH, p, ready, LONG_AGO, Look.NAGAYA, 0f);
+ check(odd + p + DIP + 0.01, BOTH, p, ready, LONG_AGO, Look.NAGAYA, 1f);
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/MoveClockTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/MoveClockTest.java
new file mode 100644
index 000000000..e161e8009
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/MoveClockTest.java
@@ -0,0 +1,113 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class MoveClockTest {
+ private static final Look.Rhythm RHYTHM = Look.NAGAYA.rhythm;
+ private static final MoveClock CLOCK = new MoveClock(RHYTHM, Look.NAGAYA.plan.seed);
+ private static final double NOW = 1_793_500_000.0;
+ /** From a slot's start to the end of its last glide, at the most. */
+ private static final double WINDOW = RHYTHM.staggerSeconds + RHYTHM.glideSeconds;
+
+ @Test
+ public void slotsAreOrderedAndSpacedWithinTheJitter() {
+ double p = RHYTHM.slotSeconds, j = RHYTHM.jitterSeconds;
+ for (long base : new long[] {-5, 0, (long) (NOW / p) - 300}) {
+ for (long k = base; k < base + 600; k++) {
+ double gap = CLOCK.start(k + 1) - CLOCK.start(k);
+ assertTrue("slot " + k + " gap " + gap, gap >= p - 2 * j - 1e-9 && gap <= p + 2 * j + 1e-9);
+ assertTrue("glides of " + k + " overlap the next slot", CLOCK.start(k) + WINDOW <= CLOCK.start(k + 1));
+ }
+ }
+ }
+
+ @Test
+ public void everyTimeFallsInTheSlotThatHasStarted() {
+ java.util.Random random = new java.util.Random(7);
+ for (int i = 0; i < 20_000; i++) {
+ double t = i % 2 == 0 ? random.nextDouble() * 5000 - 100 : NOW + random.nextDouble() * 1e6;
+ long k = CLOCK.slot(t);
+ assertTrue("t=" + t, CLOCK.start(k) <= t && t < CLOCK.start(k + 1));
+ }
+ }
+
+ @Test
+ public void checkpointSlotsStartAtOrAfterTheirCheckpoint() {
+ int n = CLOCK.slotsPerCheckpoint;
+ assertEquals(Math.round(RHYTHM.checkpointSeconds / RHYTHM.slotSeconds), n);
+ for (long c = -3; c < 300; c++) {
+ long k = c * n;
+ assertEquals(k, CLOCK.checkpoint(k + n - 1));
+ assertEquals(k, CLOCK.checkpoint(k));
+ assertTrue(CLOCK.start(k) >= k * RHYTHM.slotSeconds);
+ // the last glide before it is over by then
+ assertTrue(CLOCK.start(k - 1) + WINDOW <= k * RHYTHM.slotSeconds);
+ }
+ }
+
+ @Test
+ public void eachGroupStartsWithinTheStaggerAndGlidesBetweenItsShortestAndLongest() {
+ long k0 = CLOCK.slot(NOW);
+ double earliest = Double.MAX_VALUE, latest = 0, shortest = Double.MAX_VALUE, longest = 0;
+ for (long k = k0; k < k0 + 50; k++) {
+ if (CLOCK.homeTogether(k)) continue;
+ for (int g = 0; g < 100; g++) {
+ double delay = CLOCK.delay(k, g), glide = CLOCK.glide(k, g);
+ assertTrue("delay " + delay, delay >= 0 && delay <= RHYTHM.staggerSeconds);
+ assertTrue("glide " + glide, glide >= RHYTHM.glideMinSeconds && glide <= RHYTHM.glideSeconds);
+ assertEquals(delay, CLOCK.delay(k, g), 0);
+ assertEquals(glide, CLOCK.glide(k, g), 0);
+ earliest = Math.min(earliest, delay);
+ latest = Math.max(latest, delay);
+ shortest = Math.min(shortest, glide);
+ longest = Math.max(longest, glide);
+ }
+ }
+ assertTrue("delays span the stagger", latest - earliest > 0.95 * RHYTHM.staggerSeconds);
+ assertTrue("glides span their range", longest - shortest > 0.95 * (RHYTHM.glideSeconds - RHYTHM.glideMinSeconds));
+ }
+
+ @Test
+ public void theLastSlotBeforeACheckpointTakesEveryGroupHomeTogether() {
+ int n = CLOCK.slotsPerCheckpoint;
+ for (long c = -2; c < 50; c++) {
+ long k = c * n - 1;
+ assertTrue(CLOCK.homeTogether(k));
+ assertTrue(!CLOCK.homeTogether(k - 1) && !CLOCK.homeTogether(k + 1));
+ for (int g = 0; g < 100; g++) {
+ assertEquals(0, CLOCK.delay(k, g), 0);
+ assertEquals(RHYTHM.glideSeconds, CLOCK.glide(k, g), 0);
+ }
+ }
+ }
+
+ @Test
+ public void aRhythmWhoseGlidesRunIntoTheNextSlotIsRefused() {
+ long seed = Look.NAGAYA.plan.seed;
+ assertThrows(IllegalArgumentException.class, () -> new MoveClock(new Look.Rhythm(7, 1, 2.4, 3.2, 1.9, 600, 3), seed));
+ assertThrows(IllegalArgumentException.class, () -> new MoveClock(new Look.Rhythm(7, 1, 3.3, 3.2, 1.0, 600, 3), seed));
+ new MoveClock(new Look.Rhythm(7, 1, 2.4, 3.2, 1.8, 600, 3), seed);
+ }
+
+ @Test
+ public void glideStartsAndStopsAtRestAndNeverTurnsBack() {
+ assertEquals(0, Ease.glide(0), 0);
+ assertEquals(1, Ease.glide(1), 0);
+ assertEquals(0.5, Ease.glide(0.5), 1e-12);
+ assertEquals(0, Ease.glide(-1), 0);
+ assertEquals(1, Ease.glide(2), 0);
+ double h = 1e-6;
+ assertEquals("zero speed at the start", 0, (Ease.glide(h) - Ease.glide(0)) / h, 1e-5);
+ assertEquals("zero speed at the end", 0, (Ease.glide(1) - Ease.glide(1 - h)) / h, 1e-5);
+ double last = 0;
+ for (int i = 1; i <= 1000; i++) {
+ double e = Ease.glide(i / 1000.0);
+ assertTrue(e >= last && e <= 1);
+ last = e;
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/NagayaCameraTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/NagayaCameraTest.java
new file mode 100644
index 000000000..07b8b29e5
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/NagayaCameraTest.java
@@ -0,0 +1,202 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Random;
+import org.junit.Test;
+
+public class NagayaCameraTest {
+ private static final Look LOOK = Look.NAGAYA;
+ private static final Look.Camera CAM = LOOK.camera;
+ private static final double FRAME = 1 / 60.0;
+ private static final double[] STARTS = {0, 1_790_000_000.0, 1_793_500_000.0, 1_800_000_000.0};
+ private static final int W = 1920, H = 1080;
+
+ /** The lattice at 1080p in plan units: a1 = (a1x, 0), a2 = (a2x, a2y). */
+ private static final float UNIT = H * LOOK.plan.unitH;
+ private static final double A1X = LOOK.plan.tileWUnits * (double) UNIT;
+ private static final double A2X = LOOK.plan.tileWUnits / 2 * (double) UNIT;
+ private static final double A2Y = LOOK.plan.tileHUnits * (double) UNIT;
+
+ /** Screen px of plan point (x, y) through a matrix. */
+ private static double[] screen(float[] m, double x, double y) {
+ double cx = m[0] * x + m[4] * y + m[12], cy = m[1] * x + m[5] * y + m[13];
+ return new double[] {(cx + 1) / 2 * W, (1 - cy) / 2 * H};
+ }
+
+ /** Where the copy of one fixed plan point that lands nearest to screen point (sx, sy) lands, in px. */
+ private static double[] nearestCopy(float[] m, double sx, double sy) {
+ double[] best = null;
+ double bestD = Double.MAX_VALUE;
+ for (int j = -3; j <= 3; j++) {
+ for (int i = -3; i <= 3; i++) {
+ double[] p = screen(m, 0.37 * A1X + i * A1X + j * A2X, 0.61 * A2Y + j * A2Y);
+ double d = Math.hypot(p[0] - sx, p[1] - sy);
+ if (d < bestD) {
+ bestD = d;
+ best = p;
+ }
+ }
+ }
+ return best;
+ }
+
+ @Test
+ public void rollAndZoomSweepTheirWholeRangesAndNoFurther() {
+ NagayaCamera c = new NagayaCamera(LOOK);
+ View v = new View();
+ float[] m = new float[16];
+ for (double start : STARTS) {
+ float rollMin = 0, rollMax = -90, zoomMin = 9, zoomMax = 0;
+ for (int k = 0; k < 3000; k++) {
+ double t = start + k * 0.1;
+ c.at(t, W, H, true, v, m);
+ assertTrue("t=" + t + " roll " + v.rollDeg, v.rollDeg >= -24f && v.rollDeg <= -16f);
+ assertTrue("t=" + t + " zoom " + v.zoom, v.zoom >= 0.78f && v.zoom <= 1f);
+ rollMin = Math.min(rollMin, v.rollDeg);
+ rollMax = Math.max(rollMax, v.rollDeg);
+ zoomMin = Math.min(zoomMin, v.zoom);
+ zoomMax = Math.max(zoomMax, v.zoom);
+ }
+ assertEquals(-24f, rollMin, 0f);
+ assertEquals(-16f, rollMax, 0f);
+ assertEquals(0.78f, zoomMin, 0f);
+ assertEquals(1f, zoomMax, 0f);
+ }
+ }
+
+ @Test
+ public void zoomStartsAndStopsGently() {
+ NagayaCamera c = new NagayaCamera(LOOK);
+ View v = new View();
+ float[] m = new float[16];
+ double peak = 0, last = 0, worstStart = 0;
+ int starts = 0;
+ float before = Float.NaN;
+ for (double t = STARTS[2]; t < STARTS[2] + 300; t += FRAME) {
+ c.at(t, W, H, true, v, m);
+ double step = Float.isNaN(before) ? 0 : Math.abs(v.zoom - before);
+ peak = Math.max(peak, step);
+ if (last == 0 && step > 0 && !Float.isNaN(before)) {
+ starts++;
+ worstStart = Math.max(worstStart, step);
+ }
+ last = step;
+ before = v.zoom;
+ }
+ assertTrue("zoom ramps seen: " + starts, starts >= 2);
+ assertTrue("first step " + worstStart + " of a peak " + peak, worstStart < 0.05 * peak);
+ }
+
+ @Test
+ public void framesASixtiethApartTurnAtMostHalfADegreeASecondAndNeverJumpAcrossLatticeWraps() {
+ NagayaCamera c = new NagayaCamera(LOOK);
+ // an eased ramp peaks at pi / 2 times the even rate
+ double zoomRate = Math.PI / 2 * (CAM.zoomFrom - CAM.zoomTo) / CAM.zoomRampSeconds;
+ // the middle and 2 corners: the roll and the zoom move the corners most
+ double[][] targets = {{W / 2.0, H / 2.0}, {0, 0}, {W, H}};
+ for (double start : new double[] {1_790_000_000.0, 1_800_000_000.0 - 600}) {
+ View v0 = new View(), v1 = new View();
+ float[] m0 = new float[16], m1 = new float[16];
+ c.at(start, W, H, true, v0, m0);
+ int wraps = 0;
+ for (int k = 1; k <= 600 * 60; k++) {
+ double t = start + k * FRAME;
+ c.at(t, W, H, true, v1, m1);
+ String at = "t=" + t;
+ assertTrue(at + " roll " + v0.rollDeg + " to " + v1.rollDeg, Math.abs(v1.rollDeg - v0.rollDeg) <= 0.5 * FRAME);
+ assertTrue(at + " zoom " + v0.zoom + " to " + v1.zoom, Math.abs(v1.zoom - v0.zoom) <= zoomRate * FRAME * 1.01);
+ assertTrue(at + " centre " + v1.centreX + ", " + v1.centreY + " within a tile of 0",
+ Math.abs(v1.centreX) <= A1X + A2X && Math.abs(v1.centreY) <= A2Y);
+ if (Math.abs(v1.centreX - v0.centreX) > A2X / 2 || Math.abs(v1.centreY - v0.centreY) > A2Y / 2) wraps++;
+ for (double[] target : targets) {
+ double[] s0 = nearestCopy(m0, target[0], target[1]), s1 = nearestCopy(m1, s0[0], s0[1]);
+ double moved = Math.hypot(s1[0] - s0[0], s1[1] - s0[1]);
+ assertTrue(at + " a plan point near " + target[0] + ", " + target[1] + " moved " + moved + " px", moved <= 2);
+ }
+ View v = v0;
+ v0 = v1;
+ v1 = v;
+ float[] m = m0;
+ m0 = m1;
+ m1 = m;
+ }
+ assertTrue("only " + wraps + " lattice wraps in 10 minutes", wraps >= 5);
+ }
+ }
+
+ @Test
+ public void thePlanDriftsDownTheScreenAndALittleLeft() {
+ NagayaCamera c = new NagayaCamera(LOOK);
+ float[] m0 = new float[16], m1 = new float[16];
+ View v = new View();
+ // the plan under the screen's middle, step by step, over 20 minutes
+ double start = 1_793_500_000.0, seconds = 1200, step = 0.1, dx = 0, dy = 0;
+ c.at(start, W, H, true, v, m0);
+ for (int k = 1; k <= seconds / step; k++) {
+ c.at(start + k * step, W, H, true, v, m1);
+ double[] s0 = nearestCopy(m0, W / 2.0, H / 2.0), s1 = nearestCopy(m1, s0[0], s0[1]);
+ dx += s1[0] - s0[0];
+ dy += s1[1] - s0[1];
+ float[] m = m0;
+ m0 = m1;
+ m1 = m;
+ }
+ double heading = Math.toDegrees(Math.atan2(dy, dx)), speedH = Math.hypot(dx, dy) / seconds / H;
+ assertEquals(111.6, heading, 3);
+ assertTrue("speed " + speedH + " H/s", speedH >= 0.78 * 0.04 && speedH <= 0.04);
+ }
+
+ @Test
+ public void theSameTimeGivesTheSameViewWhateverCameBefore() {
+ // as Home and the screensaver: 2 cameras, one with its own history
+ NagayaCamera a = new NagayaCamera(LOOK), b = new NagayaCamera(LOOK);
+ View va = new View(), vb = new View();
+ float[] ma = new float[16], mb = new float[16];
+ Random random = new Random(3);
+ for (int i = 0; i < 2000; i++) {
+ double t = 1_790_000_000.0 + random.nextDouble() * 1e7;
+ a.at(t - random.nextDouble() * 1000, W, H, true, va, ma);
+ a.at(t, W, H, true, va, ma);
+ b.at(t, W, H, true, vb, mb);
+ assertEquals(vb.rollDeg, va.rollDeg, 0f);
+ assertEquals(vb.zoom, va.zoom, 0f);
+ assertEquals(vb.centreX, va.centreX, 0);
+ assertEquals(vb.centreY, va.centreY, 0);
+ assertArrayEquals(mb, ma, 0f);
+ }
+ }
+
+ @Test
+ public void cameraOffHoldsTheRestViewAndDoesNotDrift() {
+ NagayaCamera c = new NagayaCamera(LOOK);
+ View v = new View();
+ float[] m = new float[16], first = null;
+ for (double t : new double[] {0, 61.3, 1_793_500_000.0, 1_800_000_000.0}) {
+ c.at(t, W, H, false, v, m);
+ assertEquals(-20f, v.rollDeg, 0f);
+ assertEquals(0.89f, v.zoom, 0f);
+ assertEquals(Scene.margin(LOOK), v.margin, 0f);
+ if (first == null) first = m.clone();
+ assertArrayEquals("t=" + t, first, m, 0f);
+ }
+ }
+
+ @Test
+ public void aNagayaSceneOverAFewMinutesNeverLeavesAnythingOut() {
+ Scene s = new Scene(LOOK);
+ double cycle = 2 * (CAM.rollHoldSeconds + CAM.rollRampSeconds);
+ for (int[] size : new int[][] {{1280, 720}, {1920, 1080}, {3840, 2160}}) {
+ for (double t = 1_800_000_000.0; t < 1_800_000_000.0 + 2 * cycle; t += 1.0) {
+ s.build(t, size[0], size[1], true, true, true);
+ String at = size[0] + "x" + size[1] + " t=" + t + " roll " + s.view.rollDeg + " zoom " + s.view.zoom;
+ assertTrue(at + ": no cells", s.frame.cellCount > 0);
+ assertFalse(at + ": frame clipped", s.frame.clipped);
+ assertFalse(at + ": mesh clipped", s.mesh.clipped);
+ }
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/NagayaDoorsTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/NagayaDoorsTest.java
new file mode 100644
index 000000000..db4b57f83
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/NagayaDoorsTest.java
@@ -0,0 +1,249 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.HashSet;
+import java.util.Random;
+import java.util.Set;
+import org.junit.Test;
+
+public class NagayaDoorsTest {
+ private static final double NOW = 1_793_500_000.0, FRAME = 1.0 / 60;
+ private static final int W = 1920, H = 1080;
+ /** Nagaya's camera: its rest zoom, and its rest roll and the ends of its roll. */
+ private static final float ZOOM = Look.NAGAYA.camera.restZoom;
+ private static final float[] ROLLS = {Look.NAGAYA.camera.angleDeg, Look.NAGAYA.camera.rollFromDeg, Look.NAGAYA.camera.rollToDeg};
+ private static final float EPS = 1e-2f;
+
+ /** Nagaya with another seed. */
+ private static Look look(long seed) {
+ Look n = Look.NAGAYA;
+ Look.Plan p = n.plan;
+ return new Look(p.withTile(seed, p.tileWUnits, p.tileHUnits),
+ n.rhythm, n.motion, n.palette, n.walls, n.camera, n.doors, n.fixtures, n.post);
+ }
+
+ /** The scene's frame at time t, seen with this roll over plan point (cx, cy), doors on. */
+ private static Frame frame(Scene s, double t, float roll, double cx, double cy) {
+ s.view.set(W, H, roll, ZOOM, cx, cy, Scene.margin(s.look));
+ s.view.matrix(s.matrix);
+ s.fill(t, true, false, null);
+ return s.frame;
+ }
+
+ private static MoveClock clock(Scene s) {
+ return ((TilePlan) s.layout).motion.clock;
+ }
+
+ /** Times at rest, early in a slot's glides, mid-way and at their end. */
+ private static double time(MoveClock clock, Random random, int i) {
+ long k = clock.slot(NOW + random.nextDouble() * 5000);
+ double s = clock.start(k), d = clock.staggerSeconds + clock.glideSeconds;
+ double[] at = {s - 0.5, s + 0.1 * d, s + 0.5 * d, s + d, s + d * random.nextDouble()};
+ return at[i % at.length];
+ }
+
+ private static float along(Frame f, int w, float x, float y) {
+ return f.wallVertical[w] ? y : x;
+ }
+
+ @Test
+ public void everyDoorFollowsTheOneTrackWithItsOwnRipple() {
+ Scene s = new Scene(Look.NAGAYA);
+ DoorTrack track = new DoorTrack(Look.NAGAYA.doors, Look.NAGAYA.plan.seed);
+ Random random = new Random(1);
+ boolean apart = false;
+ for (int i = 0; i < 200; i++) {
+ double t = NOW + random.nextDouble() * 3000;
+ s.build(t, W, H, true, false, true);
+ Frame f = s.frame;
+ assertTrue(f.doorCount > 0);
+ for (int d = 0; d < f.doorCount; d++) {
+ assertEquals(track.opening(t, f.wallId[f.doorWall[d]]), f.doorOpening[d], 0);
+ apart |= f.doorOpening[d] != f.doorOpening[0];
+ }
+ }
+ assertTrue("doors ripple apart", apart);
+ }
+
+ @Test
+ public void doorsSitOnlyOnHostsOneEachAndClearOfThePieceEnds() {
+ Look l = Look.NAGAYA;
+ float length = H * l.doors.lengthH, gap = H * l.doors.joinGapH, host = l.doors.hostBars * length;
+ Random random = new Random(2);
+ for (long seed = 1; seed <= 4; seed++) {
+ Scene s = new Scene(look(seed));
+ for (int i = 0; i < 60; i++) {
+ double t = time(clock(s), random, i);
+ Frame f = frame(s, t, ROLLS[i % 3], random.nextDouble() * 2000 - 1000, random.nextDouble() * 1200 - 600);
+ int hosts = 0;
+ for (int w = 0; w < f.wallCount; w++) if (f.wallDoor[w]) hosts++;
+ assertEquals("every host shows its door", hosts, f.doorCount);
+ Set<Integer> walls = new HashSet<>();
+ for (int d = 0; d < f.doorCount; d++) {
+ int w = f.doorWall[d];
+ String at = "seed " + seed + " t=" + t + " door on piece " + f.wallId[w];
+ assertTrue(at, f.wallDoor[w] && walls.add(w));
+ // the hinge on the piece's centre line, the bar inside it a gap from its ends, or centred
+ assertEquals(at, f.wallVertical[w] ? f.wallX0[w] : f.wallY0[w], f.wallVertical[w] ? f.doorX[d] : f.doorY[d], 0);
+ float from = along(f, w, f.wallX0[w], f.wallY0[w]), to = along(f, w, f.wallX1[w], f.wallY1[w]);
+ float middle = along(f, w, f.doorX[d], f.doorY[d]) + f.doorAlong[d] * length / 2;
+ assertTrue(at + " host " + (to - from), to - from >= host - EPS);
+ if (to - from >= length + 2 * gap) {
+ assertTrue(at, middle - length / 2 >= from + gap - EPS && middle + length / 2 <= to - gap + EPS);
+ } else {
+ assertEquals(at, (from + to) / 2, middle, EPS);
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void everyDoorOpensClockwiseOnScreenAndMostSwingUpOrRight() {
+ int doors = 0, upOrRight = 0;
+ float[] p = new float[6];
+ for (long seed = 1; seed <= 8; seed++) {
+ Scene s = new Scene(look(seed));
+ Set<Integer> seen = new HashSet<>();
+ for (float roll : ROLLS) {
+ Frame f = frame(s, NOW, roll, 0, 0);
+ float[] m = s.matrix;
+ for (int d = 0; d < f.doorCount; d++) {
+ boolean vertical = f.wallVertical[f.doorWall[d]];
+ // the hinge, a step along the bar (u) and a step toward the swing (v), on screen with y down
+ float x = f.doorX[d], y = f.doorY[d], a = f.doorAlong[d], b = f.doorSide[d];
+ float[] plan = {x, y, x + (vertical ? 0 : a), y + (vertical ? a : 0), x + (vertical ? b : 0), y + (vertical ? 0 : b)};
+ for (int i = 0; i < 3; i++) {
+ p[2 * i] = (m[0] * plan[2 * i] + m[4] * plan[2 * i + 1] + m[12] + 1) / 2 * W;
+ p[2 * i + 1] = (1 - (m[1] * plan[2 * i] + m[5] * plan[2 * i + 1] + m[13])) / 2 * H;
+ }
+ float ux = p[2] - p[0], uy = p[3] - p[1], vx = p[4] - p[0], vy = p[5] - p[1];
+ assertTrue("seed " + seed + " roll " + roll + " door on piece " + f.wallId[f.doorWall[d]] + " opens clockwise",
+ ux * vy - uy * vx > 0);
+ if (seen.add(f.wallId[f.doorWall[d]])) {
+ doors++;
+ if (vertical ? b > 0 : b < 0) upOrRight++;
+ }
+ }
+ }
+ }
+ double share = upOrRight / (double) doors;
+ assertTrue(doors + " doors, " + share + " swing up or right", doors > 100 && share > 0.68 && share < 0.88);
+ }
+
+ @Test
+ public void anOpenDoorSwingsWithinTheRoomItOpensInto() {
+ float radius = H * Look.NAGAYA.doors.radiusH, wall = H * Look.NAGAYA.walls.widthH;
+ int doors = 0;
+ for (long seed = 1; seed <= 8; seed++) {
+ Scene s = new Scene(look(seed));
+ MoveClock clock = clock(s);
+ for (int i = 0; i < 40; i++) {
+ // wide open, the walls near the end of a glide
+ long k = clock.slot(NOW + i * 41.3);
+ Frame f = frame(s, clock.start(k) + 2.3, ROLLS[i % 3], 0, 0);
+ for (int d = 0; d < f.doorCount; d++) {
+ if (Math.abs(f.doorX[d]) > 600 || Math.abs(f.doorY[d]) > 350) continue;
+ boolean vertical = f.wallVertical[f.doorWall[d]];
+ float ux = vertical ? 0 : f.doorAlong[d], uy = vertical ? f.doorAlong[d] : 0;
+ float vx = vertical ? f.doorSide[d] : 0, vy = vertical ? 0 : f.doorSide[d];
+ float hx = f.doorX[d] + vx * wall / 2, hy = f.doorY[d] + vy * wall / 2;
+ int room = PlanGeometry.roomAt(f, hx + ux + vx, hy + uy + vy);
+ for (int q = 1; q <= 10; q++) {
+ double a = f.doorOpening[d] * q / 10;
+ float x = hx + (float) (radius * (ux * Math.cos(a) + vx * Math.sin(a)));
+ float y = hy + (float) (radius * (uy * Math.cos(a) + vy * Math.sin(a)));
+ assertEquals("seed " + seed + " door on piece " + f.wallId[f.doorWall[d]] + " at " + Math.round(Math.toDegrees(a)) + " deg",
+ f.roomId[room], f.roomId[PlanGeometry.roomAt(f, x, y)]);
+ }
+ doors++;
+ }
+ }
+ }
+ assertTrue(doors + " doors", doors > 1000);
+ }
+
+ @Test
+ public void atMostOneDoorPerRoomPairOnAboutTheWantedShareOfPairsAndAlmostEveryRoomHasOne() {
+ int hosts = 0, rooms = 0, without = 0;
+ for (long seed = 1; seed <= 8; seed++) {
+ TileGraph g = new TilePlan(look(seed), new PlainRowsBuilder()).graph;
+ int[] perPair = new int[g.pairs], perRoom = new int[g.rooms];
+ int here = 0;
+ for (int p = 0; p < g.pieces; p++) {
+ if (!g.pieceHost[p]) continue;
+ if (++perPair[g.piecePair[p]] > 1) throw new AssertionError("seed " + seed + ": 2 doors on a pair");
+ perRoom[g.pieceRoomA[p]]++;
+ perRoom[g.pieceRoomB[p]]++;
+ here++;
+ }
+ double share = here / (double) g.pairs;
+ assertTrue("seed " + seed + ": doors on " + share + " of touching pairs", share > 0.24 && share < 0.32);
+ for (int n : perRoom) if (n == 0) without++;
+ hosts += here;
+ rooms += g.rooms;
+ }
+ double perRoom = hosts / (double) rooms;
+ assertTrue(perRoom + " doors per room", perRoom > 0.7 && perRoom < 0.95);
+ assertTrue(without + " of " + rooms + " rooms without a door", without <= 0.03 * rooms);
+ }
+
+ @Test
+ public void aDoorRidesItsPieceThroughAGlideWithoutAJump() {
+ Scene s = new Scene(Look.NAGAYA);
+ Look.Doors doors = Look.NAGAYA.doors;
+ float length = H * doors.lengthH, gap = H * doors.joinGapH;
+ // the fastest a line glides, in plan units per frame, and a little more for the line under the door
+ double fastest = Math.PI / 2 * 2 * Look.NAGAYA.motion.maxUnits * H * Look.NAGAYA.plan.unitH / Look.NAGAYA.rhythm.glideSeconds * FRAME;
+ MoveClock clock = clock(s);
+ long k0 = clock.slot(NOW);
+ int moved = 0, followed = 0;
+ for (long k = k0; k < k0 + 6; k++) {
+ float[][] last = null;
+ for (double t = clock.start(k) - 0.2; t < clock.start(k) + clock.glideSeconds + 0.2; t += FRAME) {
+ Frame f = frame(s, t, ROLLS[0], 0, 0);
+ // per door: piece id, hinge x, y, share along its piece (NaN where held from an end), screen-inside flag
+ float[][] now = new float[f.doorCount][];
+ for (int d = 0; d < f.doorCount; d++) {
+ int w = f.doorWall[d];
+ float from = along(f, w, f.wallX0[w], f.wallY0[w]), to = along(f, w, f.wallX1[w], f.wallY1[w]);
+ float middle = along(f, w, f.doorX[d], f.doorY[d]) + f.doorAlong[d] * length / 2;
+ boolean free = middle - length / 2 > from + gap + 0.5f && middle + length / 2 < to - gap - 0.5f;
+ float share = free ? (middle - from) / (to - from) : Float.NaN;
+ boolean inside = Math.abs(f.doorX[d]) < 600 && Math.abs(f.doorY[d]) < 350;
+ now[d] = new float[] {f.wallId[w], f.doorX[d], f.doorY[d], share, inside ? 1 : 0};
+ }
+ if (last != null) {
+ for (float[] a : last) {
+ if (a[4] == 0) continue;
+ float[] b = nearest(now, a);
+ assertTrue("door on piece " + (int) a[0] + " left or jumped at t=" + t, b != null);
+ double step = Math.hypot(b[1] - a[1], b[2] - a[2]);
+ assertTrue("door on piece " + (int) a[0] + " moved " + step + " in a frame", step <= fastest * 1.5);
+ if (!Float.isNaN(a[3]) && !Float.isNaN(b[3])) assertEquals(a[3], b[3], 1e-4);
+ followed++;
+ if (step > 1e-3) moved++;
+ }
+ }
+ last = now;
+ }
+ }
+ assertTrue(followed + " door frames, " + moved + " moving", followed > 1000 && moved > 50);
+ }
+
+ /** The door in {@code doors} on the same piece as {@code a} nearest to it, if within a bar's length. */
+ private static float[] nearest(float[][] doors, float[] a) {
+ float[] best = null;
+ double least = H * Look.NAGAYA.doors.lengthH;
+ for (float[] b : doors) {
+ double d = Math.hypot(b[1] - a[1], b[2] - a[2]);
+ if (b[0] == a[0] && d < least) {
+ least = d;
+ best = b;
+ }
+ }
+ return best;
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/NagayaFuzzTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/NagayaFuzzTest.java
new file mode 100644
index 000000000..2a8557727
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/NagayaFuzzTest.java
@@ -0,0 +1,52 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.fail;
+
+import java.util.Random;
+import org.junit.Test;
+
+/** Nagaya at random times and views: never throws, never runs out of room, never leaves anything out. */
+public class NagayaFuzzTest {
+ private static final int[][] SIZES = {{1280, 720}, {1920, 1080}, {3840, 2160}};
+
+ @Test
+ public void randomTimesAndViewsNeverThrowOverflowOrLeaveAnythingOut() {
+ for (long seed = 1; seed <= 50; seed++) {
+ Look look = TilePlanTest.look(seed, 270, 174);
+ Scene s = new Scene(look);
+ Look.Plan p = look.plan;
+ Random random = new Random(seed);
+ float margin = Scene.margin(look);
+ // times in bursts over a few hours, out of order: frames jump back and forth, across checkpoints too
+ double burst = TilePlanTest.NOW;
+ for (int i = 0; i < 2000; i++) {
+ if (i % 20 == 7) burst = TilePlanTest.NOW + random.nextDouble() * 3 * 3600;
+ double t = burst + random.nextDouble() * 120;
+ for (int z = 0; z < SIZES.length; z++) {
+ int[] size = SIZES[z];
+ float unit = size[1] * p.unitH;
+ double cx = (random.nextDouble() * 3 - 1.5) * p.tileWUnits * unit;
+ double cy = (random.nextDouble() * 3 - 1.5) * p.tileHUnits * unit;
+ float roll = -16f - 8f * random.nextFloat(), zoom = 0.78f + 0.22f * random.nextFloat();
+ s.view.set(size[0], size[1], roll, zoom, cx, cy, margin);
+ s.view.matrix(s.matrix);
+ // the wash cuts fills into pieces; it is slow, so every frame counts the pieces it would cut and
+ // every tenth one runs it
+ s.fill(t, true, true, i % 10 == 0 ? Wash.NAGAYA : null);
+ float side = size[1] * look.post.washPieceH;
+ int pieces = 0;
+ float bleed = 2 * SceneMesh.BLEED_PX / zoom;
+ for (int c = 0; c < s.frame.cellCount; c++) {
+ pieces += SceneMesh.pieces(s.frame.cellW[c] + bleed, s.frame.cellH[c] + bleed, side);
+ }
+ boolean whole = s.frame.cellCount > 0 && !s.frame.clipped && !s.mesh.clipped && pieces <= s.frame.fillCapacity
+ && s.mesh.floats <= s.mesh.data.length && s.mesh.floats % (3 * SceneMesh.FLOATS_PER_VERTEX) == 0;
+ if (!whole) {
+ fail("seed " + seed + " t=" + t + " " + size[0] + "x" + size[1] + ": cells " + s.frame.cellCount
+ + ", frame clipped " + s.frame.clipped + ", mesh clipped " + s.mesh.clipped + ", fill pieces " + pieces);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/PlainRowsBuilder.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/PlainRowsBuilder.java
new file mode 100644
index 000000000..885af034b
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/PlainRowsBuilder.java
@@ -0,0 +1,212 @@
+package io.github.pbanddev.tatami;
+
+import java.util.Random;
+
+/**
+ * A stand-in {@link TileBuilder}: rows of rooms with joints at random, where some rooms reach an arm down into the
+ * row below. A corner arm fills the overlap of a room and the room below it a little way down, so both become an L
+ * (2 cells each); a middle arm, inside both rooms, makes a T above and a U below (3 cells each). A joint that lands
+ * closer than a step to a joint of the next row snaps into line with it, and an arm is kept only where it breaks no
+ * rule of {@link TileLayout}. Each room takes part in one arm at most.
+ */
+final class PlainRowsBuilder implements TileBuilder {
+ private static final int ROW_MIN = 16, ROW_MAX = 24, ROOM_MIN = 24, ROOM_MAX = 48;
+ /** The share of rooms that try an arm into the row below. */
+ private static final float ARM_SHARE = 0.5f;
+ /** The deepest arm, and the narrowest and widest middle arm, in steps. */
+ private static final int ARM_DEPTH = 10, MIDDLE_MIN = 6, MIDDLE_MAX = 14;
+
+ @Override
+ public TileLayout build(Look.Plan plan) {
+ int w = plan.tileWUnits, h = plan.tileHUnits, s = w / 2;
+ if (w < 2 * ROOM_MAX || h < 2 * ROW_MAX) throw new IllegalArgumentException("tile " + w + " x " + h);
+ int step = plan.minStepUnits, cell = plan.minCellUnits;
+ int cross = (int) Math.ceil((double) plan.minCrossH / plan.unitH - 1e-3);
+ Random random = new Random(plan.seed);
+
+ IntList tops = new IntList();
+ for (int top = 0; top < h; ) {
+ tops.add(top);
+ top = h - top < ROW_MAX + ROW_MIN ? h : top + ROW_MIN + random.nextInt(ROW_MAX - ROW_MIN + 1);
+ }
+ int n = tops.size;
+ int[] top = new int[n + 1];
+ for (int r = 0; r < n; r++) top[r] = tops.get(r);
+ top[n] = h;
+
+ // joints, as places in [0, w) on the row's own lines; row n - 1's bottom line is row 0's top, half a tile on
+ int[][] joints = new int[n][];
+ for (int r = 0; r < n; r++) {
+ IntList row = new IntList();
+ int start = random.nextInt(w);
+ for (int x = start; x < start + w; ) {
+ row.add(Math.floorMod(x, w));
+ int next = x + ROOM_MIN + random.nextInt(ROOM_MAX - ROOM_MIN + 1);
+ x = start + w - next < ROOM_MIN ? start + w : next;
+ }
+ int[] p = row.array();
+ for (int k = 0; k < p.length; k++) {
+ p[k] = settle(p[k], w, step, r > 0 ? joints[r - 1] : null, 0, r == n - 1 ? joints[0] : null, s);
+ }
+ java.util.Arrays.sort(p);
+ joints[r] = p;
+ }
+
+ // rooms: each a list of columns, x0 x1 top bottom
+ IntList roomRow = new IntList();
+ int[][][] cols = new int[n * (w / ROOM_MIN + 2)][][];
+ int[] first = new int[n + 1];
+ int rooms = 0;
+ for (int r = 0; r < n; r++) {
+ first[r] = rooms;
+ int[] p = joints[r];
+ for (int k = 0; k < p.length; k++) {
+ int x1 = k + 1 < p.length ? p[k + 1] : p[0] + w;
+ cols[rooms++] = new int[][] {{p[k], x1, top[r], top[r + 1]}};
+ roomRow.add(r);
+ }
+ }
+ first[n] = rooms;
+
+ // the places where lines end on each row line from above and from below, as places on that line
+ IntList[] above = new IntList[n], below = new IntList[n];
+ for (int r = 0; r < n; r++) {
+ above[r] = new IntList();
+ below[r] = new IntList();
+ for (int x : joints[r]) below[r].add(x);
+ int[] up = r > 0 ? joints[r - 1] : joints[n - 1];
+ for (int x : up) above[r].add(r > 0 ? x : Math.floorMod(x - s, w));
+ }
+
+ boolean[] used = new boolean[rooms];
+ for (int r = 0; r + 1 < n; r++) {
+ int depthMost = Math.min(ARM_DEPTH, top[r + 2] - top[r + 1] - cross);
+ if (depthMost < step) continue;
+ for (int u = first[r]; u < first[r + 1]; u++) {
+ if (used[u] || random.nextFloat() >= ARM_SHARE) continue;
+ int u0 = cols[u][0][0], u1 = cols[u][0][1];
+ // every arm that fits: the room below, its shift by a tile, the kind, and the arm's ends
+ IntList options = new IntList();
+ for (int l = first[r + 1]; l < first[r + 2]; l++) {
+ if (used[l]) continue;
+ for (int shift = -w; shift <= w; shift += w) {
+ int l0 = cols[l][0][0] + shift, l1 = cols[l][0][1] + shift;
+ if (u0 + cell <= l0 && l0 + cell <= u1 && u1 + cell <= l1) addOption(options, l, shift, l0, u1);
+ if (l0 + cell <= u0 && u0 + cell <= l1 && l1 + cell <= u1) addOption(options, l, shift, u0, l1);
+ int lo = Math.max(u0, l0) + cell, hi = Math.min(u1, l1) - cell;
+ if (hi - lo >= MIDDLE_MIN) {
+ int width = MIDDLE_MIN + random.nextInt(Math.min(MIDDLE_MAX, hi - lo) - MIDDLE_MIN + 1);
+ int a = lo + random.nextInt(hi - lo - width + 1);
+ addOption(options, l, shift, a, a + width);
+ }
+ }
+ }
+ if (options.size == 0) continue;
+ int o = 4 * random.nextInt(options.size / 4);
+ int l = options.get(o), shift = options.get(o + 1), a = options.get(o + 2), b = options.get(o + 3);
+ int depth = step + random.nextInt(depthMost - step + 1);
+ int l0 = cols[l][0][0] + shift, l1 = cols[l][0][1] + shift;
+ // cuts: the room above is cut at the arm's ends inside it, the room below likewise
+ int[] cutsAbove = cuts(a, b, u0, u1), cutsBelow = cuts(a, b, l0, l1);
+ IntList farBelow = r + 2 < n ? below[r + 2] : below[0];
+ int farShift = r + 2 < n ? 0 : s;
+ boolean fits = true;
+ for (int x : cutsAbove) fits &= !clashes(x, above[r], 0, w, step);
+ for (int x : cutsBelow) fits &= !clashes(x, farBelow, farShift, w, step);
+ if (!fits) continue;
+ for (int x : cutsAbove) below[r].add(Math.floorMod(x, w));
+ IntList farAbove = r + 2 < n ? above[r + 2] : above[0];
+ for (int x : cutsBelow) farAbove.add(Math.floorMod(x - farShift, w));
+ cols[u] = split(u0, u1, a, b, top[r], top[r + 1], 0, depth);
+ cols[l] = split(l0, l1, a, b, top[r + 1], top[r + 2], depth, 0);
+ used[u] = true;
+ used[l] = true;
+ }
+ }
+
+ IntList x0 = new IntList(), y0 = new IntList(), x1 = new IntList(), y1 = new IntList(), room = new IntList();
+ for (int k = 0; k < rooms; k++) {
+ for (int[] c : cols[k]) {
+ x0.add(c[0]);
+ x1.add(c[1]);
+ y0.add(c[2]);
+ y1.add(c[3]);
+ room.add(k);
+ }
+ }
+ return new TileLayout(w, h, rooms, x0.array(), y0.array(), x1.array(), y1.array(), room.array());
+ }
+
+ private static void addOption(IntList options, int room, int shift, int a, int b) {
+ options.add(room);
+ options.add(shift);
+ options.add(a);
+ options.add(b);
+ }
+
+ /** The arm's ends that fall strictly inside [x0, x1]: where that room gets cut. */
+ private static int[] cuts(int a, int b, int x0, int x1) {
+ IntList out = new IntList();
+ if (a > x0 && a < x1) out.add(a);
+ if (b > x0 && b < x1) out.add(b);
+ return out.array();
+ }
+
+ /**
+ * A room [x0, x1] x [top, bottom] cut at the arm [a, b]: the arm's part has its top lowered by {@code lower}
+ * and its bottom dropped by {@code drop}.
+ */
+ private static int[][] split(int x0, int x1, int a, int b, int top, int bottom, int lower, int drop) {
+ int from = Math.max(x0, a), to = Math.min(x1, b);
+ IntList out = new IntList();
+ if (from > x0) addColumn(out, x0, from, top, bottom);
+ addColumn(out, from, to, top + lower, bottom + drop);
+ if (to < x1) addColumn(out, to, x1, top, bottom);
+ int[] flat = out.array();
+ int[][] columns = new int[flat.length / 4][];
+ for (int c = 0; c < columns.length; c++) columns[c] = java.util.Arrays.copyOfRange(flat, 4 * c, 4 * c + 4);
+ return columns;
+ }
+
+ private static void addColumn(IntList out, int x0, int x1, int top, int bottom) {
+ out.add(x0);
+ out.add(x1);
+ out.add(top);
+ out.add(bottom);
+ }
+
+ /** True when x lies closer than a step to a place in {@code line} (each moved by {@code shift}), but not on it. */
+ private static boolean clashes(int x, IntList line, int shift, int w, int step) {
+ for (int i = 0; i < line.size; i++) {
+ int d = Math.floorMod(x - line.get(i) - shift, w);
+ d = Math.min(d, w - d);
+ if (d > 0 && d < step) return true;
+ }
+ return false;
+ }
+
+ /**
+ * A joint at x, moved as little as it takes so it is in line with, or a step clear of, every joint of the row
+ * above (moved by shiftAbove) and the row below (moved by shiftBelow). Either may be null.
+ */
+ private static int settle(int x, int w, int step, int[] above, int shiftAbove, int[] below, int shiftBelow) {
+ for (int d = 0; d <= 2 * step + 2; d++) {
+ for (int sign = 1; sign >= -1; sign -= 2) {
+ int c = Math.floorMod(x + sign * d, w);
+ if (clear(c, w, step, above, shiftAbove) && clear(c, w, step, below, shiftBelow)) return c;
+ if (d == 0) break;
+ }
+ }
+ throw new IllegalStateException("no place for a joint near " + x);
+ }
+
+ private static boolean clear(int x, int w, int step, int[] row, int shift) {
+ if (row == null) return true;
+ for (int q : row) {
+ int d = Math.floorMod(x - q - shift, w);
+ d = Math.min(d, w - d);
+ if (d > 0 && d < step) return false;
+ }
+ return true;
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/PlanGeometryTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/PlanGeometryTest.java
new file mode 100644
index 000000000..67e30e5a7
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/PlanGeometryTest.java
@@ -0,0 +1,108 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class PlanGeometryTest {
+ private static final float DELTA = 1f;
+
+ /** A frame holding the given rooms, each as x0, y0, x1, y1. */
+ private static Frame rooms(float[]... boxes) {
+ Frame f = new Frame(boxes.length);
+ for (float[] b : boxes) {
+ int k = f.roomCount++;
+ f.roomX[k] = b[0];
+ f.roomY[k] = b[1];
+ f.roomW[k] = b[2] - b[0];
+ f.roomH[k] = b[3] - b[1];
+ }
+ return f;
+ }
+
+ /** The clockwise windmill of a 100 x 100 square: top, right, bottom, left, then the centre. */
+ private static final float[][] CLOCKWISE = {
+ {0, 0, 70, 30}, {70, 0, 100, 70}, {30, 70, 100, 100}, {0, 30, 30, 100}, {30, 30, 70, 70}};
+
+ private static float[][] mirrored(float[][] boxes) {
+ float[][] out = new float[boxes.length][];
+ for (int i = 0; i < boxes.length; i++) {
+ float[] b = boxes[i];
+ out[i] = new float[] {100 - b[2], b[1], 100 - b[0], b[3]};
+ }
+ return out;
+ }
+
+ @Test
+ public void findsTheRoomByItsCellsWhenThereAreCells() {
+ // one L-shaped room of 2 cells, and the room in its notch
+ Frame f = new Frame(2, 3, 0, 0, 0, 3);
+ f.roomCount = 2;
+ float[][] cells = {{0, 0, 60, 20}, {0, 20, 30, 40}, {30, 20, 60, 40}};
+ int[] room = {0, 0, 1};
+ for (float[] c : cells) {
+ int k = f.cellCount++;
+ f.cellX[k] = c[0];
+ f.cellY[k] = c[1];
+ f.cellW[k] = c[2] - c[0];
+ f.cellH[k] = c[3] - c[1];
+ f.cellRoom[k] = room[k];
+ }
+ assertEquals(0, PlanGeometry.roomAt(f, 50, 10));
+ assertEquals(0, PlanGeometry.roomAt(f, 10, 30));
+ assertEquals(1, PlanGeometry.roomAt(f, 50, 30));
+ assertEquals(-1, PlanGeometry.roomAt(f, 70, 30));
+ }
+
+ @Test
+ public void findsTheRoomThatHoldsAPoint() {
+ Frame f = rooms(CLOCKWISE);
+ assertEquals(4, PlanGeometry.roomAt(f, 50, 50));
+ assertEquals(0, PlanGeometry.roomAt(f, 10, 10));
+ assertEquals(-1, PlanGeometry.roomAt(f, 150, 50));
+ }
+
+ @Test
+ public void sharedEdgeIsTheOverlapOfTwoTouchingSides() {
+ Frame f = rooms(new float[] {0, 0, 50, 100}, new float[] {50, 20, 100, 60}, new float[] {50, 60, 100, 100});
+ float[] out = new float[4];
+ assertEquals(40f, PlanGeometry.sharedEdge(f, 0, 1, 0.01f, out), 1e-4f);
+ assertArrayEquals(new float[] {50, 20, 50, 60}, out, 1e-4f);
+ assertEquals(50f, PlanGeometry.sharedEdge(f, 2, 1, 0.01f, out), 1e-4f);
+ assertArrayEquals(new float[] {50, 60, 100, 60}, out, 1e-4f);
+ }
+
+ @Test
+ public void roomsThatMeetOnlyAtACornerShareNoEdge() {
+ Frame f = rooms(new float[] {0, 0, 50, 50}, new float[] {50, 50, 100, 100});
+ assertEquals(0f, PlanGeometry.sharedEdge(f, 0, 1, 0.01f, new float[4]), 0f);
+ }
+
+ @Test
+ public void theCentreOfAWindmillIsAWindmillCentreEitherWayRound() {
+ assertTrue(PlanGeometry.isWindmillCentre(rooms(CLOCKWISE), 4, DELTA));
+ assertTrue(PlanGeometry.isWindmillCentre(rooms(mirrored(CLOCKWISE)), 4, DELTA));
+ }
+
+ @Test
+ public void roomsOnThePlanEdgeAreNeverWindmillCentres() {
+ Frame f = rooms(CLOCKWISE);
+ for (int k = 0; k < 4; k++) assertFalse(PlanGeometry.isWindmillCentre(f, k, DELTA));
+ }
+
+ @Test
+ public void aRoomInAGridOrBetweenTwoBandsIsNoWindmillCentre() {
+ float[][] grid = new float[9][];
+ for (int i = 0; i < 9; i++) {
+ float x = (i % 3) * 30, y = (i / 3) * 30;
+ grid[i] = new float[] {x, y, x + 30, y + 30};
+ }
+ assertFalse("a + join at every corner", PlanGeometry.isWindmillCentre(rooms(grid), 4, DELTA));
+ Frame bands = rooms(new float[] {0, 0, 100, 30}, new float[] {0, 30, 30, 70}, new float[] {30, 30, 70, 70},
+ new float[] {70, 30, 100, 70}, new float[] {0, 70, 100, 100});
+ assertFalse("T joins that do not take turns", PlanGeometry.isWindmillCentre(bands, 2, DELTA));
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/RoomColoursTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/RoomColoursTest.java
new file mode 100644
index 000000000..5c30cb8a9
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/RoomColoursTest.java
@@ -0,0 +1,141 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Random;
+
+import org.junit.Test;
+
+public class RoomColoursTest {
+ private static final Look LOOK = Look.YOJOHAN;
+ private static final int[] CARDS = LOOK.palette.cards;
+ /** Epoch seconds in November 2026: the clock Home and the screensaver both read. */
+ private static final double NOW = 1_793_500_000.0;
+ private static final float EPS = 0.05f;
+
+ private static int sum(int[] values) {
+ int total = 0;
+ for (int v : values) total += v;
+ return total;
+ }
+
+ @Test
+ public void quotasAreTheCardsFor64Rooms() {
+ assertEquals(LOOK.palette.deck.length, CARDS.length);
+ assertEquals(64, sum(CARDS));
+ assertArrayEquals(CARDS, RoomColours.quotas(CARDS, 64));
+ }
+
+ @Test
+ public void quotasStayInProportionForOtherRoomCounts() {
+ for (int rooms : new int[] {1, 9, 30, 41, 63, 65, 100, 200}) {
+ int[] quotas = RoomColours.quotas(CARDS, rooms);
+ assertEquals(rooms, sum(quotas));
+ for (int c = 0; c < CARDS.length; c++) {
+ double share = (double) rooms * CARDS[c] / 64;
+ assertTrue(rooms + " rooms, paint " + c + ": " + quotas[c] + " for " + share,
+ Math.abs(quotas[c] - share) < 1);
+ }
+ }
+ }
+
+ @Test
+ public void dealHandsOutExactlyTheQuotas() {
+ FloorPlan plan = new FloorPlan(LOOK);
+ int[] paints = RoomColours.deal(plan, LOOK);
+ assertEquals(plan.rooms, paints.length);
+ int[] count = new int[LOOK.palette.deck.length];
+ for (int p : paints) count[p]++;
+ assertArrayEquals(RoomColours.quotas(CARDS, plan.rooms), count);
+ }
+
+ @Test
+ public void shuffleHandsOutExactlyTheQuotasTheSameWayEachTime() {
+ Look ember = Look.NAGAYA;
+ assertEquals(64, sum(ember.palette.cards));
+ assertEquals(ember.palette.deck.length, ember.palette.cards.length);
+ int[] paints = RoomColours.shuffle(70, ember);
+ int[] count = new int[ember.palette.deck.length];
+ for (int p : paints) count[p]++;
+ assertArrayEquals(RoomColours.quotas(ember.palette.cards, 70), count);
+ assertArrayEquals(paints, RoomColours.shuffle(70, ember));
+ }
+
+ @Test
+ public void touchingRoomsNeverSharePaintAtAnyTime() {
+ FloorPlan plan = new FloorPlan(LOOK);
+ int[] paints = RoomColours.deal(plan, LOOK);
+ float angle = LOOK.camera.angleDeg;
+ float w = Camera.planWidth(1920, 1080, angle), h = Camera.planHeight(1920, 1080, angle);
+ Frame f = new Frame(plan.rooms);
+ float[] edge = new float[4];
+ Random random = new Random(1);
+ for (int s = 0; s < 4000; s++) {
+ double t = s % 2 == 0 ? random.nextDouble() * 100_000 : NOW + random.nextDouble() * 1_000_000;
+ plan.layout(t, -w / 2, -h / 2, w, h, f);
+ for (int i = 0; i < f.roomCount; i++) {
+ for (int j = i + 1; j < f.roomCount; j++) {
+ if (PlanGeometry.sharedEdge(f, i, j, EPS, edge) > EPS) {
+ assertNotEquals("rooms " + i + " and " + j + " touch at t=" + t, paints[i], paints[j]);
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void hardRuleWinsOverTheCards() {
+ // 3 rooms that all touch, but only 2 paints have cards
+ boolean[][] triangle = {{false, true, true}, {true, false, true}, {true, true, false}};
+ int[] paints = RoomColours.assign(new int[] {2, 1, 0}, triangle, new boolean[3][3], new Random(1));
+ assertNotEquals(paints[0], paints[1]);
+ assertNotEquals(paints[1], paints[2]);
+ assertNotEquals(paints[0], paints[2]);
+ }
+
+ @Test
+ public void touchingRoomsAvoidPaintsThatLookAlikeWhenTheyCan() {
+ // a row of 3 rooms where paints 0 and 1 look alike, so paint 2 belongs in the middle
+ boolean[][] row = {{false, true, false}, {true, false, true}, {false, true, false}};
+ boolean[][] alike = new boolean[3][3];
+ alike[0][1] = true;
+ alike[1][0] = true;
+ for (long seed = 0; seed < 20; seed++) {
+ assertEquals(2, RoomColours.assign(new int[] {1, 1, 1}, row, alike, new Random(seed))[1]);
+ }
+ }
+
+ @Test
+ public void sameSeedGivesTheSameDeal() {
+ assertArrayEquals(RoomColours.deal(new FloorPlan(LOOK), LOOK), RoomColours.deal(new FloorPlan(LOOK), LOOK));
+ }
+
+ @Test
+ public void labMatchesTheSrgbReference() {
+ assertArrayEquals(new double[] {53.585, 0, 0}, RoomColours.lab(0xFF808080), 0.01);
+ assertArrayEquals(new double[] {39.589, 38.928, 40.101}, RoomColours.lab(0xFFA03E1C), 0.01);
+ }
+
+ /** Pairs from Sharma, Wu and Dalal (2005), "The CIEDE2000 color-difference formula", table 1. */
+ @Test
+ public void ciede2000MatchesSharmaReferencePairs() {
+ double[][] pairs = {
+ {50, 2.6772, -79.7751, 50, 0, -82.7485, 2.0425},
+ {50, 0, 0, 50, -1, 2, 2.3669},
+ {50, 2.49, -0.001, 50, -2.49, 0.0011, 7.2195},
+ {50, -0.001, 2.49, 50, 0.0011, -2.49, 4.7461},
+ {50, 2.5, 0, 73, 25, -18, 27.1492},
+ {50, 2.5, 0, 56, -27, -3, 31.9030},
+ {60.2574, -34.0099, 36.2677, 60.4626, -34.1751, 39.4387, 1.2644},
+ {2.0776, 0.0795, -1.135, 0.9033, -0.0636, -0.5514, 0.9082},
+ };
+ for (double[] p : pairs) {
+ double[] a = {p[0], p[1], p[2]}, b = {p[3], p[4], p[5]};
+ assertEquals(p[6], RoomColours.deltaE2000(a, b), 1e-4);
+ assertEquals(p[6], RoomColours.deltaE2000(b, a), 1e-4);
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/SceneMeshTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/SceneMeshTest.java
new file mode 100644
index 000000000..4c61d71c2
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/SceneMeshTest.java
@@ -0,0 +1,135 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+
+import org.junit.Test;
+
+public class SceneMeshTest {
+
+ @Test
+ public void meshNeverOverflowsAndHoldsWholeTriangles() {
+ Scene scene = new Scene(Look.YOJOHAN);
+ int most = 0;
+ for (int i = 0; i < 200; i++) {
+ double t = i * 17.7 + (i % 2 == 0 ? 0 : 1_793_500_000.0);
+ scene.build(t, i % 3 == 0 ? 1280 : 1920, i % 3 == 0 ? 720 : 1080, true, true, true);
+ assertTrue(scene.mesh.floats <= scene.mesh.data.length);
+ assertEquals(0, scene.mesh.floats % (3 * SceneMesh.FLOATS_PER_VERTEX));
+ most = Math.max(most, scene.mesh.floats);
+ }
+ assertTrue("mesh is empty", most > 0);
+ }
+
+ @Test
+ public void doorsAndFixturesCanBeLeftOut() {
+ Scene scene = new Scene(Look.YOJOHAN);
+ scene.build(0, 1920, 1080, false, false, true);
+ int without = scene.mesh.floats;
+ scene.build(0, 1920, 1080, true, false, true);
+ int doors = scene.mesh.floats;
+ scene.build(0, 1920, 1080, true, true, true);
+ assertTrue(doors > without);
+ assertTrue(scene.mesh.floats > doors);
+ }
+
+ // ------------------------------------------------------------------------------------- Nagaya
+
+ private static final int F = SceneMesh.FLOATS_PER_VERTEX;
+
+ /** Lays out and meshes Nagaya through the given view, past its camera. */
+ private static void nagaya(Scene s, View v, Wash wash) {
+ s.view.set(v.w, v.h, v.rollDeg, v.zoom, v.centreX, v.centreY, v.margin);
+ s.view.matrix(s.matrix);
+ s.fill(1_793_500_000.0, true, true, wash);
+ }
+
+ @Test
+ public void nagayaNeverClipsOrOverflowsInItsWidestViews() {
+ Scene s = new Scene(Look.NAGAYA);
+ Look.Plan p = Look.NAGAYA.plan;
+ View v = new View();
+ for (int[] size : new int[][] {{1280, 720}, {1920, 1080}, {3840, 2160}}) {
+ float unit = size[1] * p.unitH, tw = p.tileWUnits * unit, th = p.tileHUnits * unit;
+ for (float roll : new float[] {-24f, -16f}) {
+ for (int i = 0; i < 6; i++) {
+ for (int j = 0; j < 6; j++) {
+ double cx = tw * i / 6.0 + tw / 2 * j / 6.0, cy = th * j / 6.0;
+ v.set(size[0], size[1], roll, 0.78f, cx, cy, s.view.margin);
+ nagaya(s, v, Wash.NONE);
+ assertTrue(s.frame.cellCount > 0);
+ assertFalse("frame clipped", s.frame.clipped);
+ assertFalse("mesh clipped", s.mesh.clipped);
+ assertTrue(s.mesh.floats <= s.mesh.data.length);
+ assertEquals(0, s.mesh.floats % (3 * F));
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void nagayaWashesFillsButNeverWalls() {
+ Scene s = new Scene(Look.NAGAYA);
+ float[] gain = new float[Wash.NX * Wash.NY * 3], blend = new float[gain.length];
+ Arrays.fill(gain, 0.5f);
+ Arrays.fill(blend, 0.5f);
+ View v = new View();
+ v.set(1920, 1080, -20f, 0.89f, 0.0, 0.0, 0f);
+ nagaya(s, v, new Wash(gain, blend));
+ float[] ink = rgb(Look.NAGAYA.walls.color);
+ int walls = 0, fills = 0;
+ for (int k = 0; k < s.mesh.floats; k += F) {
+ float[] c = Arrays.copyOfRange(s.mesh.data, k + 2, k + 5);
+ if (Arrays.equals(c, ink)) {
+ walls++;
+ continue;
+ }
+ fills++;
+ assertTrue("a fill at half a paint: " + Arrays.toString(c), isHalfAPaint(c));
+ }
+ assertTrue(walls > 0 && fills > 0);
+ }
+
+ @Test
+ public void nagayaCutsWashedFillsIntoSmallPieces() {
+ Scene s = new Scene(Look.NAGAYA);
+ View v = new View();
+ v.set(1920, 1080, -20f, 0.89f, 0.0, 0.0, 0f);
+ nagaya(s, v, Wash.NONE);
+ float side = 1080 * Look.NAGAYA.post.washPieceH + 1e-2f;
+ float[] ink = rgb(Look.NAGAYA.walls.color), d = s.mesh.data;
+ int pieces = 0;
+ for (int k = 0; k < s.mesh.floats; k += 3 * F) {
+ if (Arrays.equals(Arrays.copyOfRange(d, k + 2, k + 5), ink)) continue;
+ float w = Math.max(d[k], Math.max(d[k + F], d[k + 2 * F])) - Math.min(d[k], Math.min(d[k + F], d[k + 2 * F]));
+ float h = Math.max(d[k + 1], Math.max(d[k + 1 + F], d[k + 1 + 2 * F]))
+ - Math.min(d[k + 1], Math.min(d[k + 1 + F], d[k + 1 + 2 * F]));
+ assertTrue("piece " + w + " x " + h, w <= side && h <= side);
+ pieces++;
+ }
+ assertTrue(pieces > 2 * s.frame.cellCount);
+ nagaya(s, v, null);
+ assertTrue("unwashed fills stay whole", s.mesh.floats < pieces * 3 * F);
+ }
+
+ private static float[] rgb(int argb) {
+ return new float[] {((argb >> 16) & 0xFF) / 255f, ((argb >> 8) & 0xFF) / 255f, (argb & 0xFF) / 255f};
+ }
+
+ /** True for half of a room paint or of the door's: doors are fills, washed too. */
+ private static boolean isHalfAPaint(float[] c) {
+ int[] deck = Look.NAGAYA.palette.deck, paints = Arrays.copyOf(deck, deck.length + 1);
+ paints[deck.length] = Look.NAGAYA.palette.door;
+ for (int paint : paints) {
+ float[] p = rgb(paint);
+ if (Math.abs(c[0] - p[0] / 2) < 1e-6 && Math.abs(c[1] - p[1] / 2) < 1e-6 && Math.abs(c[2] - p[2] / 2) < 1e-6) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/ScenesTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/ScenesTest.java
new file mode 100644
index 000000000..8aa231c8d
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/ScenesTest.java
@@ -0,0 +1,63 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.Test;
+
+public class ScenesTest {
+ private final List<Throwable> reported = new ArrayList<>();
+ private int nagayaTries;
+
+ private Scenes failing(Throwable failure) {
+ return new Scenes(look -> {
+ if (look == Look.YOJOHAN) return new Scene(look);
+ nagayaTries++;
+ if (failure instanceof Error) throw (Error) failure;
+ throw (RuntimeException) failure;
+ });
+ }
+
+ @Test
+ public void eachLookBuildsAsItself() {
+ Scenes scenes = new Scenes(Scene::new);
+ assertSame(Look.YOJOHAN, scenes.make(Look.YOJOHAN, reported::add).look);
+ assertSame(Look.NAGAYA, scenes.make(Look.NAGAYA, reported::add).look);
+ assertTrue(reported.isEmpty());
+ assertTrue(scenes.usable(Look.NAGAYA));
+ }
+
+ @Test
+ public void aFailedBuildGivesYojohanAndIsNotTriedAgain() {
+ IllegalStateException boom = new IllegalStateException("boom");
+ Scenes scenes = failing(boom);
+ assertSame(Look.YOJOHAN, scenes.make(Look.NAGAYA, reported::add).look);
+ assertSame(Look.YOJOHAN, scenes.make(Look.NAGAYA, reported::add).look);
+ assertEquals(1, nagayaTries);
+ assertEquals(List.of(boom), reported);
+ assertFalse(scenes.usable(Look.NAGAYA));
+ assertTrue(scenes.usable(Look.YOJOHAN));
+ }
+
+ @Test
+ public void errorsAreCaughtToo() {
+ Scenes scenes = failing(new OutOfMemoryError("test"));
+ assertSame(Look.YOJOHAN, scenes.make(Look.NAGAYA, reported::add).look);
+ assertSame(Look.YOJOHAN, failing(new StackOverflowError()).make(Look.NAGAYA, reported::add).look);
+ assertEquals(2, reported.size());
+ }
+
+ @Test
+ public void aLookThatFailsToDrawIsNotUsedAgain() {
+ Scenes scenes = new Scenes(Scene::new);
+ RuntimeException boom = new RuntimeException("draw");
+ scenes.failed(Look.NAGAYA, boom, reported::add);
+ assertFalse(scenes.usable(Look.NAGAYA));
+ assertSame(Look.YOJOHAN, scenes.make(Look.NAGAYA, reported::add).look);
+ assertEquals(List.of(boom), reported);
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/ShadersTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/ShadersTest.java
new file mode 100644
index 000000000..597046020
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/ShadersTest.java
@@ -0,0 +1,214 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+
+import org.junit.Test;
+
+/** Yojōhan's shader text never changes, except the one reviewed edit: the fade to dark, applied last. */
+public class ShadersTest {
+ private static final Look.Post POST = Look.YOJOHAN.post;
+
+ @Test
+ public void yojohanSourcesAreAsFirstShipped() {
+ assertEquals(SCENE_VERTEX, Shaders.SCENE_VERTEX);
+ assertEquals(QUAD_VERTEX, Shaders.QUAD_VERTEX);
+ assertEquals(PLAIN_FRAGMENT, Shaders.PLAIN_FRAGMENT);
+ assertEquals(DOWNSAMPLE_FRAGMENT, Shaders.DOWNSAMPLE_FRAGMENT);
+ assertEquals(BLUR_FRAGMENT, Shaders.blurFragment(POST));
+ }
+
+ @Test
+ public void sceneAndBlendOnlyGainTheFade() {
+ assertEquals(fade(SCENE_FRAGMENT, "uniform float uGrainAmp;\n",
+ "gl_FragColor = vec4(c, 1.0);", "gl_FragColor = vec4(c * uFade, 1.0);"),
+ Shaders.sceneFragment(POST));
+ assertEquals(fade(BLEND_FRAGMENT, "uniform float uVig;\n",
+ "gl_FragColor = vec4(blurred * mix(vec3(1.0), lens.rgb * 2.0, uVig), lens.a);",
+ "gl_FragColor = vec4(blurred * mix(vec3(1.0), lens.rgb * 2.0, uVig) * uFade, lens.a);"),
+ Shaders.blendFragment(POST));
+ }
+
+ @Test
+ public void nagayaBlursAsYojohan() {
+ Look.Post nagaya = Look.NAGAYA.post;
+ assertSame(POST.blurOval, nagaya.blurOval);
+ assertEquals(POST.blurDivisor, nagaya.blurDivisor);
+ assertArrayEquals(POST.blurWeights, nagaya.blurWeights, 0f);
+ assertArrayEquals(POST.blurOffsets, nagaya.blurOffsets, 0f);
+ assertEquals(Shaders.blurFragment(POST), Shaders.blurFragment(nagaya));
+ }
+
+ /** Its fills come washed from the CPU: no gain from the lens map, whose alpha still shapes the blur's oval. */
+ @Test
+ public void nagayaTakesNoLensGainAndHasItsOwnGrain() {
+ assertEquals(NAGAYA_SCENE_FRAGMENT, Shaders.sceneFragment(Look.NAGAYA.post));
+ assertEquals(NAGAYA_BLEND_FRAGMENT, Shaders.blendFragment(Look.NAGAYA.post));
+ }
+
+ @Test
+ public void grainStepIsWrittenOnlyWhenItIsThere() {
+ String nagaya = Shaders.sceneFragment(Look.NAGAYA.post);
+ assertEquals(1, count(nagaya, "smoothstep("));
+ assertEquals(0, count(Shaders.sceneFragment(POST), "smoothstep("));
+ }
+
+ /** Declares uFade after {@code after} and swaps the final line for its faded one. */
+ private static String fade(String source, String after, String last, String faded) {
+ assertEquals(1, count(source, after));
+ assertEquals(1, count(source, last));
+ return source.replace(after, after + "uniform float uFade;\n").replace(last, faded);
+ }
+
+ private static int count(String s, String part) {
+ int n = 0;
+ for (int i = s.indexOf(part); i >= 0; i = s.indexOf(part, i + 1)) n++;
+ return n;
+ }
+
+ // Yojōhan's sources as first shipped.
+
+ private static final String SCENE_VERTEX = """
+ uniform mat4 uMatrix;
+ attribute vec2 aPos;
+ attribute vec4 aColor;
+ varying vec4 vColor;
+ void main() { vColor = aColor; gl_Position = uMatrix * vec4(aPos, 0.0, 1.0); }
+ """;
+
+ private static final String QUAD_VERTEX = """
+ attribute vec2 aPos;
+ varying vec2 vUv;
+ void main() { vUv = aPos * 0.5 + 0.5; gl_Position = vec4(aPos, 0.0, 1.0); }
+ """;
+
+ private static final String PLAIN_FRAGMENT = """
+ precision mediump float;
+ varying vec4 vColor;
+ void main() { gl_FragColor = vColor; }
+ """;
+
+ private static final String DOWNSAMPLE_FRAGMENT = """
+ #ifdef GL_FRAGMENT_PRECISION_HIGH
+ precision highp float;
+ #else
+ precision mediump float;
+ #endif
+ uniform sampler2D uTex;
+ uniform vec2 uTexel;
+ varying vec2 vUv;
+ void main() {
+ gl_FragColor = 0.25 * (texture2D(uTex, vUv + uTexel * vec2(-1.0, -1.0))
+ + texture2D(uTex, vUv + uTexel * vec2(1.0, -1.0))
+ + texture2D(uTex, vUv + uTexel * vec2(-1.0, 1.0))
+ + texture2D(uTex, vUv + uTexel * vec2(1.0, 1.0)));
+ }
+ """;
+
+ private static final String BLEND_FRAGMENT = """
+ precision mediump float;
+ #ifdef GL_FRAGMENT_PRECISION_HIGH
+ #define HIGHP highp
+ #else
+ #define HIGHP mediump
+ #endif
+ uniform sampler2D uTex;
+ uniform sampler2D uLens;
+ uniform float uVig;
+ uniform HIGHP vec4 uBlurArea;
+ varying HIGHP vec2 vUv;
+ void main() {
+ vec4 lens = texture2D(uLens, vUv);
+ HIGHP vec2 uv = vUv * uBlurArea.xy + uBlurArea.zw;
+ vec3 blurred = texture2D(uTex, uv).rgb;
+ gl_FragColor = vec4(blurred * mix(vec3(1.0), lens.rgb * 2.0, uVig), lens.a);
+ }
+ """;
+
+ private static final String SCENE_FRAGMENT = """
+ precision mediump float;
+ #ifdef GL_FRAGMENT_PRECISION_HIGH
+ #define HIGHP highp
+ #else
+ #define HIGHP mediump
+ #endif
+ uniform vec2 uInvSize;
+ uniform float uVig;
+ uniform float uGrainAmp;
+ uniform HIGHP vec2 uGrainOffset;
+ uniform sampler2D uGrain;
+ uniform sampler2D uLens;
+ varying vec4 vColor;
+ void main() {
+ vec3 c = vColor.rgb * mix(vec3(1.0), texture2D(uLens, gl_FragCoord.xy * uInvSize).rgb * 2.0, uVig);
+ float luma = dot(c, vec3(0.2126, 0.7152, 0.0722));
+ HIGHP vec2 g = gl_FragCoord.xy / 256.0 + uGrainOffset;
+ float n = (texture2D(uGrain, g).r - 0.5) * 8.0;
+ c += n * (0.005098039 + 0.006862745 * luma * luma) * uGrainAmp;
+ gl_FragColor = vec4(c, 1.0);
+ }
+ """;
+
+ private static final String BLUR_FRAGMENT = """
+ #ifdef GL_FRAGMENT_PRECISION_HIGH
+ precision highp float;
+ #else
+ precision mediump float;
+ #endif
+ uniform sampler2D uTex;
+ uniform vec2 uStep;
+ varying vec2 vUv;
+ void main() {
+ vec4 c = vec4(0.0);
+ c += texture2D(uTex, vUv) * 0.2719;
+ c += (texture2D(uTex, vUv + uStep * 1.3333) + texture2D(uTex, vUv - uStep * 1.3333)) * 0.3235;
+ c += (texture2D(uTex, vUv + uStep * 3.165) + texture2D(uTex, vUv - uStep * 3.165)) * 0.0406;
+ gl_FragColor = c;
+ }
+ """;
+
+ // Nagaya's: Yojōhan's without the lens map's gain. Grain (1.4 + 2.35 * smoothstep(0.25, 0.30, luma)) * 2/3 levels.
+
+ private static final String NAGAYA_SCENE_FRAGMENT = """
+ precision mediump float;
+ #ifdef GL_FRAGMENT_PRECISION_HIGH
+ #define HIGHP highp
+ #else
+ #define HIGHP mediump
+ #endif
+ uniform float uGrainAmp;
+ uniform float uFade;
+ uniform HIGHP vec2 uGrainOffset;
+ uniform sampler2D uGrain;
+ varying vec4 vColor;
+ void main() {
+ vec3 c = vColor.rgb;
+ float luma = dot(c, vec3(0.2126, 0.7152, 0.0722));
+ HIGHP vec2 g = gl_FragCoord.xy / 256.0 + uGrainOffset;
+ float n = (texture2D(uGrain, g).r - 0.5) * 8.0;
+ c += n * (0.0036601308 + 0.0061437907 * smoothstep(0.25, 0.3, luma)) * uGrainAmp;
+ gl_FragColor = vec4(c * uFade, 1.0);
+ }
+ """;
+
+ private static final String NAGAYA_BLEND_FRAGMENT = """
+ precision mediump float;
+ #ifdef GL_FRAGMENT_PRECISION_HIGH
+ #define HIGHP highp
+ #else
+ #define HIGHP mediump
+ #endif
+ uniform sampler2D uTex;
+ uniform sampler2D uLens;
+ uniform float uFade;
+ uniform HIGHP vec4 uBlurArea;
+ varying HIGHP vec2 vUv;
+ void main() {
+ vec4 lens = texture2D(uLens, vUv);
+ HIGHP vec2 uv = vUv * uBlurArea.xy + uBlurArea.zw;
+ vec3 blurred = texture2D(uTex, uv).rgb;
+ gl_FragColor = vec4(blurred * uFade, lens.a);
+ }
+ """;
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/SkylineBuilderTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/SkylineBuilderTest.java
new file mode 100644
index 000000000..0bc14a3b2
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/SkylineBuilderTest.java
@@ -0,0 +1,122 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import org.junit.Test;
+
+/** Nagaya's tile from {@link SkylineBuilder}: valid at both tile sizes, about 15.5 rooms per H², steps by width. */
+public class SkylineBuilderTest {
+ private static final int[][] TILES = {{270, 174}, {135, 87}};
+ private static final int SEEDS = 16;
+
+ private static Look look(long seed, int[] tile) {
+ return TilePlanTest.look(seed, tile[0], tile[1]);
+ }
+
+ /** Each room's step count: where its next cell's top or bottom differs, a cell at a time from left to right. */
+ private static int[] steps(TileLayout tile) {
+ int[] steps = new int[tile.rooms];
+ Integer[] order = new Integer[tile.cells()];
+ for (int c = 0; c < order.length; c++) order[c] = c;
+ Arrays.sort(order, (a, b) -> tile.cellRoom[a] != tile.cellRoom[b]
+ ? Integer.compare(tile.cellRoom[a], tile.cellRoom[b]) : Integer.compare(tile.cellX0[a], tile.cellX0[b]));
+ for (int i = 1; i < order.length; i++) {
+ int a = order[i - 1], b = order[i];
+ if (tile.cellRoom[a] != tile.cellRoom[b]) continue;
+ if (tile.cellY0[a] != tile.cellY0[b]) steps[tile.cellRoom[b]]++;
+ if (tile.cellY1[a] != tile.cellY1[b]) steps[tile.cellRoom[b]]++;
+ }
+ return steps;
+ }
+
+ /** Each room's width in H, from its leftmost cell edge to its rightmost. */
+ private static double[] widths(TileLayout tile, float unitH) {
+ int[] x0 = new int[tile.rooms], x1 = new int[tile.rooms];
+ Arrays.fill(x0, Integer.MAX_VALUE);
+ Arrays.fill(x1, Integer.MIN_VALUE);
+ for (int c = 0; c < tile.cells(); c++) {
+ x0[tile.cellRoom[c]] = Math.min(x0[tile.cellRoom[c]], tile.cellX0[c]);
+ x1[tile.cellRoom[c]] = Math.max(x1[tile.cellRoom[c]], tile.cellX1[c]);
+ }
+ double[] out = new double[tile.rooms];
+ for (int r = 0; r < tile.rooms; r++) out[r] = (x1[r] - x0[r]) * (double) unitH;
+ return out;
+ }
+
+ private static int band(double width) {
+ return width < 0.3 ? 0 : width <= 0.5 ? 1 : 2;
+ }
+
+ @Test
+ public void everySeedBuildsATileTheGraphAcceptsAtBothSizes() {
+ for (int[] size : TILES) {
+ for (long seed = 1; seed <= SEEDS; seed++) {
+ Look look = look(seed, size);
+ // throws, naming the rule, on any tile the contract does not allow
+ TileGraph graph = new TileGraph(new SkylineBuilder().build(look.plan), look);
+ assertTrue(graph.rooms > 0);
+ }
+ }
+ }
+
+ @Test
+ public void noRoomEverHasThreeSteps() {
+ for (int[] size : TILES) {
+ for (long seed = 1; seed <= SEEDS; seed++) {
+ int[] steps = steps(new SkylineBuilder().build(look(seed, size).plan));
+ for (int r = 0; r < steps.length; r++) assertTrue("seed " + seed + " room " + r, steps[r] <= 2);
+ }
+ }
+ }
+
+ @Test
+ public void aboutFifteenRoomsPerH2InAMixOfBoxesLsAndTwoSteps() {
+ int[] mix = new int[3];
+ for (int[] size : TILES) {
+ for (long seed = 1; seed <= SEEDS; seed++) {
+ Look look = look(seed, size);
+ TileLayout tile = new SkylineBuilder().build(look.plan);
+ double area = size[0] * size[1] * (double) look.plan.unitH * look.plan.unitH;
+ double density = tile.rooms / area;
+ assertTrue("seed " + seed + ": " + density + " rooms per H^2", density >= 12.7 && density <= 16.4);
+ if (size != TILES[0]) continue;
+ for (int s : steps(tile)) mix[s]++;
+ }
+ }
+ double rooms = mix[0] + mix[1] + mix[2];
+ String at = Arrays.toString(mix);
+ // between 30 / 59 / 11 as seen on screen and 26 / 57 / 17 over all rooms, give or take a few
+ assertTrue(at, mix[0] / rooms >= 0.20 && mix[0] / rooms <= 0.32);
+ assertTrue(at, mix[1] / rooms >= 0.53 && mix[1] / rooms <= 0.66);
+ assertTrue(at, mix[2] / rooms >= 0.09 && mix[2] / rooms <= 0.20);
+ }
+
+ @Test
+ public void widerRoomsHaveMoreSteps() {
+ int[][] mix = new int[3][3];
+ for (long seed = 1; seed <= SEEDS; seed++) {
+ Look look = look(seed, TILES[0]);
+ TileLayout tile = new SkylineBuilder().build(look.plan);
+ int[] steps = steps(tile);
+ double[] width = widths(tile, look.plan.unitH);
+ for (int r = 0; r < tile.rooms; r++) mix[band(width[r])][steps[r]]++;
+ }
+ double[] share = new double[3];
+ double[] mean = new double[3];
+ for (int b = 0; b < 3; b++) {
+ int rooms = mix[b][0] + mix[b][1] + mix[b][2];
+ assertTrue("band " + b + " has rooms", rooms > 0);
+ share[b] = mix[b][2] / (double) rooms;
+ mean[b] = (mix[b][1] + 2.0 * mix[b][2]) / rooms;
+ }
+ String at = Arrays.deepToString(mix);
+ // under 0.3 H: half boxes, half Ls; 0.3 to 0.5 H: 20 / 70 / 10; over 0.5 H: mostly two steps
+ assertTrue(at, mix[0][2] == 0);
+ double narrowBoxes = mix[0][0] / (double) (mix[0][0] + mix[0][1]);
+ assertTrue(at, narrowBoxes >= 0.4 && narrowBoxes <= 0.6);
+ assertTrue(at, share[1] >= 0.05 && share[1] <= 0.2);
+ assertTrue(at, share[2] >= 0.5);
+ assertTrue(at, mean[0] < mean[1] && mean[1] < mean[2]);
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/TileMotionTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/TileMotionTest.java
new file mode 100644
index 000000000..0d673a5ac
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/TileMotionTest.java
@@ -0,0 +1,203 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import org.junit.Test;
+
+/** Nagaya's staggered glides: every rule holds at every moment, rooms keep most of their size, and slots differ. */
+public class TileMotionTest {
+ private static final double EPS = 1e-6;
+ private static final int[][] TILES = {{270, 174}, {135, 87}};
+ private static final long[] SEEDS = {5, 11, 23, 1, 2};
+
+ static TilePlan skyline(long seed, int[] tile) {
+ return new TilePlan(TilePlanTest.look(seed, tile[0], tile[1]), new SkylineBuilder());
+ }
+
+ /** The first of the slots to run: some way before a checkpoint, so the slots that lead home and the next ones run too. */
+ private static long firstSlot(MoveClock clock) {
+ return clock.checkpoint(clock.slot(TilePlanTest.NOW)) + clock.slotsPerCheckpoint - 60;
+ }
+
+ /** Every group of slot k at time t, by the slot's own timing: from before to after along its own glide. */
+ private static void timed(MoveClock clock, long k, int[] before, int[] after, double t, double[] out) {
+ double since = t - clock.start(k);
+ for (int i = 0; i < out.length; i++) {
+ out[i] = before[i] + (after[i] - before[i]) * Ease.glide((since - clock.delay(k, i)) / clock.glide(k, i));
+ }
+ }
+
+ /**
+ * Every group somewhere on its way: at its start, its end, or anywhere between, each on its own; all the same way
+ * along in the slot that takes every group home together, which never staggers.
+ */
+ private static void anyTiming(Random random, boolean together, int[] before, int[] after, double[] out) {
+ double shared = random.nextDouble();
+ for (int i = 0; i < out.length; i++) {
+ double e = together ? shared : random.nextInt(3) == 0 ? random.nextInt(2) : random.nextDouble();
+ out[i] = before[i] + (after[i] - before[i]) * e;
+ }
+ }
+
+ private static void rules(TileGraph g, double[] off, String at) {
+ for (int r = 0; r < g.ruleHi.length; r++) {
+ double v = g.ruleGap[r] + off[g.ruleHi[r]] - off[g.ruleLo[r]];
+ if (v < g.ruleMin[r] - EPS) throw new AssertionError(at + ": rule " + r + " is " + v + ", below " + g.ruleMin[r]);
+ }
+ }
+
+ @Test
+ public void everyRuleHoldsAtEveryMomentWhateverEachGroupsTiming() {
+ for (long seed : SEEDS) {
+ for (int[] tile : TILES) {
+ TilePlan plan = skyline(seed, tile);
+ TileGraph g = plan.graph;
+ MoveClock clock = plan.motion.clock;
+ int n = g.groups;
+ int[] before = new int[n], after = new int[n];
+ double[] off = new double[n];
+ float[] shown = new float[n];
+ Random random = new Random(seed);
+ long k0 = firstSlot(clock);
+ for (long k = k0; k < k0 + 160; k++) {
+ plan.motion.glide(k, before, after);
+ String at = "seed " + seed + " tile " + tile[0] + " slot " + k;
+ for (int s = 0; s < 6; s++) {
+ anyTiming(random, clock.homeTogether(k), before, after, off);
+ rules(g, off, at + " any timing");
+ }
+ // the slot's own timing: at a group's start, end or inside its glide, and anywhere in the slot
+ double start = clock.start(k), window = clock.staggerSeconds + clock.glideSeconds;
+ for (int s = 0; s < 12; s++) {
+ int i = random.nextInt(n);
+ double from = start + clock.delay(k, i), u = s % 3 == 0 ? 0 : s % 3 == 1 ? 1 : random.nextDouble();
+ double t = s < 9 ? from + u * clock.glide(k, i) : start + random.nextDouble() * window;
+ timed(clock, k, before, after, t, off);
+ rules(g, off, at + " t=" + t);
+ plan.motion.offsets(t, shown);
+ for (int j = 0; j < n; j++) assertEquals(at + " t=" + t, off[j], shown[j], 1e-4);
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void noCellOrRoomEverGetsBelowItsKeptShareOfHome() {
+ double keep = Look.NAGAYA.motion.keepShare;
+ for (long seed : SEEDS) {
+ for (int[] tile : TILES) {
+ TilePlan plan = skyline(seed, tile);
+ TileGraph g = plan.graph;
+ int[] before = new int[g.groups], after = new int[g.groups];
+ double[] off = new double[g.groups];
+ Random random = new Random(seed);
+ MoveClock clock = plan.motion.clock;
+ long k0 = firstSlot(clock);
+ for (long k = k0; k < k0 + 160; k++) {
+ plan.motion.glide(k, before, after);
+ anyTiming(random, clock.homeTogether(k), before, after, off);
+ String at = "seed " + seed + " tile " + tile[0] + " slot " + k;
+ for (int c = 0; c < g.cells; c++) {
+ int w = g.cellX1[c] - g.cellX0[c], h = g.cellY1[c] - g.cellY0[c];
+ assertTrue(at + " cell " + c, w + off[g.cellRight[c]] - off[g.cellLeft[c]] >= keep * w - EPS);
+ assertTrue(at + " cell " + c, h + off[g.cellBottom[c]] - off[g.cellTop[c]] >= keep * h - EPS);
+ }
+ for (int r = 0; r < g.rooms; r++) {
+ int lo = -1, hi = -1;
+ for (int i = g.roomCellStart[r]; i < g.roomCellStart[r + 1]; i++) {
+ int c = g.roomCellList[i];
+ if (lo < 0 || g.cellX0[c] < g.cellX0[lo]) lo = c;
+ if (hi < 0 || g.cellX1[c] > g.cellX1[hi]) hi = c;
+ }
+ int w = g.cellX1[hi] - g.cellX0[lo];
+ assertTrue(at + " room " + r, w + off[g.cellRight[hi]] - off[g.cellLeft[lo]] >= keep * w - EPS);
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void groupsInASlotStartAtDifferentTimesAndAllRestBeforeTheNextSlot() {
+ TilePlan plan = skyline(5, TILES[0]);
+ MoveClock clock = plan.motion.clock;
+ int n = plan.graph.groups;
+ int[] before = new int[n], after = new int[n];
+ float[] shown = new float[n];
+ List<Double> spreads = new ArrayList<>();
+ int busy = 0, staggered = 0;
+ long k0 = clock.slot(TilePlanTest.NOW);
+ for (long k = k0; k < k0 + 300; k++) {
+ plan.motion.glide(k, before, after);
+ double start = clock.start(k), first = Double.MAX_VALUE, last = 0;
+ int movers = 0;
+ for (int i = 0; i < n; i++) {
+ if (before[i] == after[i]) continue;
+ movers++;
+ first = Math.min(first, clock.delay(k, i));
+ last = Math.max(last, clock.delay(k, i));
+ assertTrue("slot " + k + " group " + i, start + clock.delay(k, i) + clock.glide(k, i) <= clock.start(k + 1));
+ }
+ // all at rest from the end of the slot's glides until the next slot starts
+ for (double t : new double[] {start + clock.staggerSeconds + clock.glideSeconds, clock.start(k + 1) - 1e-6}) {
+ plan.motion.offsets(t, shown);
+ for (int i = 0; i < n; i++) assertEquals("slot " + k, after[i], shown[i], 0f);
+ }
+ if (movers < 4) continue;
+ busy++;
+ spreads.add(last - first);
+ // halfway through the starts some groups are on their way and some still wait
+ plan.motion.offsets(start + (first + last) / 2, shown);
+ int going = 0, waiting = 0;
+ for (int i = 0; i < n; i++) {
+ if (before[i] == after[i]) continue;
+ if (shown[i] == before[i]) waiting++; else going++;
+ }
+ if (going > 0 && waiting > 0) staggered++;
+ }
+ Collections.sort(spreads);
+ double median = spreads.get(spreads.size() / 2);
+ assertTrue("median spread of starts " + median + " s", median > 0.6 * clock.staggerSeconds);
+ assertTrue(staggered + " of " + busy + " slots staggered", busy > 200 && staggered > 0.9 * busy);
+ }
+
+ @Test
+ public void quietSlotsComeAtAboutTheirShareAndBusySlotsVaryInShare() {
+ Look.Motion motion = Look.NAGAYA.motion;
+ for (long seed : new long[] {5, 11, 23}) {
+ TilePlan plan = skyline(seed, TILES[0]);
+ TileGraph g = plan.graph;
+ MoveClock clock = plan.motion.clock;
+ int n = g.groups;
+ long total = 0;
+ for (int length : g.groupLength) total += length;
+ int[] before = new int[n], after = new int[n];
+ List<Double> busy = new ArrayList<>();
+ int free = 0, quiet = 0, slots = 3000;
+ double sum = 0;
+ long k0 = clock.slot(TilePlanTest.NOW);
+ for (long k = k0; k < k0 + slots; k++) {
+ plan.motion.glide(k, before, after);
+ long moving = 0;
+ for (int i = 0; i < n; i++) if (before[i] != after[i]) moving += g.groupLength[i];
+ double share = moving / (double) total;
+ sum += share;
+ if (k - clock.checkpoint(k) >= clock.slotsPerCheckpoint - Look.NAGAYA.rhythm.homeSlots) continue;
+ free++;
+ if (moving == 0) quiet++; else busy.add(share);
+ }
+ Collections.sort(busy);
+ double p10 = busy.get(busy.size() / 10), p90 = busy.get(busy.size() * 9 / 10), mean = sum / slots;
+ String at = "seed " + seed + ": quiet " + quiet / (double) free + ", busy p10 " + p10 + " p90 " + p90 + ", mean " + mean;
+ assertEquals(at, motion.quietShare, quiet / (double) free, 0.03);
+ assertTrue(at, p90 >= 1.6 * p10);
+ assertTrue(at, mean >= motion.moveShare - 0.03 && mean <= motion.moveShare + 0.05);
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/TilePlanStatsTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/TilePlanStatsTest.java
new file mode 100644
index 000000000..95f93b006
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/TilePlanStatsTest.java
@@ -0,0 +1,90 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import org.junit.Test;
+
+/** Nagaya's motion over many slots: how much moves, how far, and that it turns back. */
+public class TilePlanStatsTest {
+ private static final int SLOTS = 2000;
+ private static final long[] SEEDS = {5, 11, 23};
+
+ @Test
+ public void slotsMoveTheLooksShareOfWallsAShortWayAndMostlyBack() {
+ Look.Motion motion = Look.NAGAYA.motion;
+ float share = motion.moveShare;
+ // the most a busy slot aims for
+ double most = share * (1 + motion.shareSpread) / (1 - motion.quietShare);
+ for (long seed : SEEDS) {
+ TilePlan plan = TilePlanTest.plan(seed, new int[] {270, 174});
+ TileGraph g = plan.graph;
+ int n = g.groups;
+ long total = 0;
+ for (int length : g.groupLength) total += length;
+ int[] before = new int[n], after = new int[n], lastWay = new int[n];
+ List<Double> shares = new ArrayList<>();
+ List<Integer> travel = new ArrayList<>();
+ int turns = 0, pairs = 0;
+ long k0 = plan.motion.clock.slot(TilePlanTest.NOW);
+ for (long k = k0; k < k0 + SLOTS; k++) {
+ plan.motion.glide(k, before, after);
+ long moving = 0;
+ for (int i = 0; i < n; i++) {
+ int d = after[i] - before[i];
+ if (d == 0) continue;
+ moving += g.groupLength[i];
+ travel.add(Math.abs(d));
+ if (lastWay[i] != 0) {
+ pairs++;
+ if (Integer.signum(d) != lastWay[i]) turns++;
+ }
+ lastWay[i] = Integer.signum(d);
+ }
+ shares.add(moving / (double) total);
+ }
+ Collections.sort(shares);
+ Collections.sort(travel);
+ // over all slots, quiet ones too
+ double median = shares.get(SLOTS / 2), p90 = shares.get(SLOTS * 9 / 10);
+ String at = "seed " + seed + ": share median " + median + ", p90 " + p90;
+ assertTrue(at, median >= share - 0.03 && median <= share + 0.06);
+ assertTrue(at, p90 <= most + 0.08);
+ int t50 = travel.get(travel.size() / 2), t90 = travel.get(travel.size() * 9 / 10);
+ assertTrue("seed " + seed + ": travel median " + t50, t50 >= 5 && t50 <= 8);
+ assertTrue("seed " + seed + ": travel p90 " + t90, t90 >= 10 && t90 <= 14);
+ assertTrue("seed " + seed + ": reversal " + turns / (double) pairs, turns >= 0.70 * pairs);
+ }
+ }
+
+ @Test
+ public void aColdStartEqualsASteppedRun() {
+ TilePlan stepped = TilePlanTest.plan(5, new int[] {270, 174});
+ int n = stepped.graph.groups;
+ int[] a = new int[n], b = new int[n], c = new int[n], d = new int[n];
+ float[] x = new float[n], y = new float[n];
+ MoveClock clock = stepped.motion.clock;
+ long k0 = clock.slot(TilePlanTest.NOW) - 37;
+ Random random = new Random(1);
+ for (long k = k0; k < k0 + 450; k++) {
+ stepped.motion.glide(k, a, b);
+ double t = clock.start(k) + random.nextDouble() * (clock.staggerSeconds + clock.glideSeconds);
+ stepped.motion.offsets(t, x);
+ if (random.nextInt(10) != 0) continue;
+ TilePlan cold = TilePlanTest.plan(5, new int[] {270, 174});
+ cold.motion.glide(k, c, d);
+ assertArrayEquals("slot " + k, a, c);
+ assertArrayEquals("slot " + k, b, d);
+ // and after a jump back, mid-glide too
+ cold.motion.offsets(clock.start(k - 1 - random.nextInt(300)) + 2.0, y);
+ cold.motion.offsets(t, y);
+ assertArrayEquals("slot " + k + " t=" + t, x, y, 0f);
+ cold.motion.glide(k, c, d);
+ assertArrayEquals("slot " + k, b, d);
+ }
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/TilePlanTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/TilePlanTest.java
new file mode 100644
index 000000000..7812b780f
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/TilePlanTest.java
@@ -0,0 +1,252 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Random;
+import java.util.Set;
+import org.junit.Test;
+
+public class TilePlanTest {
+ static final double NOW = 1_793_500_000.0;
+ private static final double EPS = 1e-3;
+ private static final int[][] TILES = {{270, 174}, {135, 87}};
+
+ /** Nagaya with another seed and tile size. */
+ static Look look(long seed, int tileW, int tileH) {
+ Look n = Look.NAGAYA;
+ Look.Plan p = n.plan;
+ return new Look(p.withTile(seed, tileW, tileH),
+ n.rhythm, n.motion, n.palette, n.walls, n.camera, n.doors, n.fixtures, n.post);
+ }
+
+ static TilePlan plan(long seed, int[] tile) {
+ return new TilePlan(look(seed, tile[0], tile[1]), new PlainRowsBuilder());
+ }
+
+ /** Times all over a slot: its glides' start, middle and end, and the rest after them; and checkpoints. */
+ private static double[] times(TileMotion m, int count, long seed) {
+ Random random = new Random(seed);
+ MoveClock clock = m.clock;
+ double[] out = new double[count];
+ for (int i = 0; i < count; i++) {
+ long k = clock.slot(NOW + random.nextDouble() * 4000 - (i % 5 == 0 ? 1e6 : 0));
+ double s = clock.start(k), d = clock.staggerSeconds + clock.glideSeconds;
+ double[] at = {s, s + d * random.nextDouble(), s + d / 2, s + d + 1e-3, (s + d + clock.start(k + 1)) / 2};
+ out[i] = at[i % at.length];
+ }
+ return out;
+ }
+
+ /** Cell boxes of copy (0, 0) at time t, in steps: x0, y0, x1, y1 per cell. */
+ private static double[][] cells(TilePlan plan, double t) {
+ TileGraph g = plan.graph;
+ float[] off = new float[g.groups];
+ plan.motion.offsets(t, off);
+ double[][] box = new double[g.cells][];
+ for (int c = 0; c < g.cells; c++) {
+ box[c] = new double[] {g.cellX0[c] + off[g.cellLeft[c]], g.cellY0[c] + off[g.cellTop[c]],
+ g.cellX1[c] + off[g.cellRight[c]], g.cellY1[c] + off[g.cellBottom[c]]};
+ }
+ return box;
+ }
+
+ /** Every pair of cell copies that share a stretch of edge at time t: cell a of copy (0, 0), cell b of copy (i, j). */
+ private static Set<String> touching(TilePlan plan, double[][] box) {
+ TileGraph g = plan.graph;
+ Set<String> out = new HashSet<>();
+ for (int a = 0; a < g.cells; a++) {
+ for (int j = -1; j <= 1; j++) {
+ for (int i = -2; i <= 2; i++) {
+ double dx = i * g.width + j * g.shift, dy = j * g.height;
+ for (int b = 0; b < g.cells; b++) {
+ double[] p = box[a], q = box[b];
+ double x0 = q[0] + dx, x1 = q[2] + dx, y0 = q[1] + dy, y1 = q[3] + dy;
+ double ox = Math.min(p[2], x1) - Math.max(p[0], x0), oy = Math.min(p[3], y1) - Math.max(p[1], y0);
+ if (ox > EPS && oy > EPS && !(a == b && i == 0 && j == 0)) {
+ throw new AssertionError("cells " + a + " and " + b + " (" + i + ", " + j + ") overlap");
+ }
+ if ((Math.abs(ox) <= EPS && oy > EPS) || (Math.abs(oy) <= EPS && ox > EPS)) out.add(a + " " + b + " " + i + " " + j);
+ }
+ }
+ }
+ }
+ return out;
+ }
+
+ @Test
+ public void cellsTileTheLatticeAndKeepTheirNeighboursAtAnyTime() {
+ for (long seed : new long[] {5, 1, 2}) {
+ for (int[] tile : TILES) {
+ TilePlan plan = plan(seed, tile);
+ // t = 0 is a checkpoint: every line home
+ Set<String> home = touching(plan, cells(plan, 0.0));
+ for (double t : times(plan.motion, 40, seed)) {
+ double[][] box = cells(plan, t);
+ double area = 0;
+ for (double[] b : box) area += (b[2] - b[0]) * (b[3] - b[1]);
+ assertEquals("seed " + seed + " t=" + t, (double) tile[0] * tile[1], area, 0.05);
+ assertEquals("seed " + seed + " t=" + t, home, touching(plan, box));
+ }
+ }
+ }
+ }
+
+ @Test
+ public void everyMinimumAndDoorHostHoldsAtRestAndInGlides() {
+ for (long seed : new long[] {5, 3, 4}) {
+ for (int[] tile : TILES) {
+ TilePlan plan = plan(seed, tile);
+ TileGraph g = plan.graph;
+ float[] off = new float[g.groups];
+ for (double t : times(plan.motion, 300, seed)) {
+ plan.motion.offsets(t, off);
+ for (int c = 0; c < g.cells; c++) {
+ boolean alone = g.roomCellStart[g.cellRoom[c] + 1] - g.roomCellStart[g.cellRoom[c]] == 1;
+ double w = g.cellX1[c] + off[g.cellRight[c]] - g.cellX0[c] - off[g.cellLeft[c]];
+ double h = g.cellY1[c] + off[g.cellBottom[c]] - g.cellY0[c] - off[g.cellTop[c]];
+ assertTrue("cell width " + w, w >= (alone ? Math.max(g.minCell, g.minCross) : g.minCell) - EPS);
+ assertTrue("cell height " + h, h >= g.minCross - EPS);
+ }
+ for (int r = 0; r < g.rooms; r++) {
+ double lo = Double.MAX_VALUE, hi = -Double.MAX_VALUE;
+ for (int i = g.roomCellStart[r]; i < g.roomCellStart[r + 1]; i++) {
+ int c = g.roomCellList[i];
+ lo = Math.min(lo, g.cellX0[c] + off[g.cellLeft[c]]);
+ hi = Math.max(hi, g.cellX1[c] + off[g.cellRight[c]]);
+ }
+ assertTrue("room width", hi - lo >= g.minCross - EPS);
+ }
+ for (int p = 0; p < g.pieces; p++) {
+ double length = g.pieceTo[p] + off[g.pieceToGroup[p]] - g.pieceFrom[p] - off[g.pieceFromGroup[p]];
+ assertTrue("a step or T-offset of " + length, length >= g.minStep - EPS);
+ assertTrue(length >= g.pieceMinLength[p] - EPS);
+ if (g.pieceHost[p]) assertTrue("door host " + length, length >= g.hostMin - EPS);
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void roomsAreOneToThreeJoinedCellsAndWallsPartRooms() {
+ for (long seed = 1; seed <= 8; seed++) {
+ TilePlan plan = plan(seed, TILES[0]);
+ TileGraph g = plan.graph;
+ int[] cells = new int[g.rooms];
+ for (int c = 0; c < g.cells; c++) cells[g.cellRoom[c]]++;
+ int multi = 0;
+ for (int n : cells) {
+ assertTrue(n >= 1 && n <= 3);
+ if (n > 1) multi++;
+ }
+ assertTrue("some rooms are L, T, U or Z", multi > g.rooms / 5);
+ for (int p = 0; p < g.pieces; p++) assertTrue(g.pieceRoomA[p] != g.pieceRoomB[p]);
+ }
+ }
+
+ @Test
+ public void doorHostsAreOnePerPairAtMostOnLongPieces() {
+ int hosts = 0, pairs = 0;
+ for (long seed = 1; seed <= 8; seed++) {
+ TileGraph g = plan(seed, TILES[0]).graph;
+ int[] perPair = new int[g.pairs];
+ for (int p = 0; p < g.pieces; p++) {
+ if (!g.pieceHost[p]) continue;
+ perPair[g.piecePair[p]]++;
+ assertTrue(g.pieceTo[p] - g.pieceFrom[p] >= g.hostMin);
+ hosts++;
+ }
+ for (int n : perPair) assertTrue(n <= 1);
+ pairs += g.pairs;
+ }
+ double share = hosts / (double) pairs;
+ assertTrue("hosts on " + share + " of touching pairs", share > 0.6 * Look.NAGAYA.doors.chance && share < 1.1 * Look.NAGAYA.doors.chance);
+ }
+
+ @Test
+ public void nothingMovesBetweenGlidesAndAllIsHomeAtCheckpoints() {
+ TilePlan plan = plan(5, TILES[0]);
+ MoveClock clock = plan.motion.clock;
+ float[] a = new float[plan.graph.groups], b = new float[a.length];
+ long k0 = clock.slot(NOW);
+ int moved = 0;
+ for (long k = k0; k < k0 + 200; k++) {
+ double window = clock.staggerSeconds + clock.glideSeconds;
+ double end = clock.start(k) + window, next = clock.start(k + 1);
+ plan.motion.offsets(end + 1e-6, a);
+ plan.motion.offsets(next - 1e-6, b);
+ assertArrayEquals("slot " + k, a, b, 0f);
+ plan.motion.offsets(clock.start(k) + window / 2, b);
+ if (!Arrays.equals(a, b)) moved++;
+ }
+ assertTrue("walls glide in most slots", moved > 140);
+ for (long c = clock.checkpoint(k0); c < k0 + 400; c += clock.slotsPerCheckpoint) {
+ plan.motion.offsets(c * clock.slotSeconds, a);
+ for (float o : a) assertEquals(0f, o, 0f);
+ }
+ }
+
+ @Test
+ public void sameSeedAndTimeGiveTheSameFrameWhicheverWayTheClockWent() {
+ Scene a = new Scene(Look.NAGAYA), b = new Scene(Look.NAGAYA);
+ Random random = new Random(3);
+ for (int i = 0; i < 60; i++) {
+ double t = NOW + random.nextDouble() * 3000;
+ a.build(t, 1920, 1080, true, true, true);
+ b.build(t + (i % 2 == 0 ? -1700 : 900), 1920, 1080, true, true, true);
+ b.build(t, 1920, 1080, true, true, true);
+ assertEquals(a.frame.cellCount, b.frame.cellCount);
+ assertArrayEquals(Arrays.copyOf(a.frame.cellX, a.frame.cellCount), Arrays.copyOf(b.frame.cellX, b.frame.cellCount), 0f);
+ assertArrayEquals(Arrays.copyOf(a.frame.wallY0, a.frame.wallCount), Arrays.copyOf(b.frame.wallY0, b.frame.wallCount), 0f);
+ assertArrayEquals(Arrays.copyOf(a.mesh.data, a.mesh.floats), Arrays.copyOf(b.mesh.data, b.mesh.floats), 0f);
+ }
+ }
+
+ @Test
+ public void framesHoldWholePiecesBetweenRoomsAndFlagTheirHosts() {
+ Scene s = new Scene(Look.NAGAYA);
+ float bar = Look.NAGAYA.doors.hostBars * Look.NAGAYA.doors.lengthH * 1080, step = Look.NAGAYA.plan.minStepUnits * Look.NAGAYA.plan.unitH * 1080;
+ int hosts = 0;
+ for (double t : times(((TilePlan) s.layout).motion, 50, 9)) {
+ s.build(t, 1920, 1080, true, true, true);
+ Frame f = s.frame;
+ assertFalse(f.clipped);
+ for (int w = 0; w < f.wallCount; w++) {
+ float length = f.wallX1[w] - f.wallX0[w] + f.wallY1[w] - f.wallY0[w];
+ assertTrue(f.wallRoomA[w] != f.wallRoomB[w]);
+ assertTrue("piece " + length, length >= step - 1e-2);
+ assertTrue(length >= f.wallMinLength[w] - 1e-2);
+ if (f.wallDoor[w]) {
+ hosts++;
+ assertTrue("host " + length, length >= bar - 1e-2);
+ }
+ }
+ for (int r = 0; r < f.roomCount; r++) assertTrue(Float.isNaN(f.roomMinW[r]) || f.roomW[r] >= f.roomMinW[r] - 1e-2);
+ }
+ assertTrue(hosts > 0);
+ }
+
+ @Test
+ public void everySeedAndBothTileSizesBuildQuickly() {
+ double[] ms = new double[100];
+ View view = new View();
+ view.set(1920, 1080, -20f, 0.89f, 0.0, 0.0, Scene.margin(Look.NAGAYA));
+ for (int round = 0; round < 2; round++) {
+ for (long seed = 1; seed <= 50; seed++) {
+ for (int s = 0; s < 2; s++) {
+ long start = System.nanoTime();
+ TilePlan plan = plan(seed, TILES[s]);
+ plan.layout(NOW, view, plan.newFrame());
+ ms[(int) (seed - 1) * 2 + s] = (System.nanoTime() - start) / 1e6;
+ }
+ }
+ }
+ Arrays.sort(ms);
+ assertTrue("median build " + ms[50] + " ms", ms[50] < 20);
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/ViewTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/ViewTest.java
new file mode 100644
index 000000000..283b7fc52
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/ViewTest.java
@@ -0,0 +1,71 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class ViewTest {
+
+ /** Screen px of a plan point through a matrix. */
+ private static float[] screen(float[] m, float x, float y, float w, float h) {
+ float cx = m[0] * x + m[4] * y + m[12], cy = m[1] * x + m[5] * y + m[13];
+ return new float[] {(cx + 1) / 2 * w, (1 - cy) / 2 * h};
+ }
+
+ @Test
+ public void matrixPutsTheCentreMidScreenAndTurnsAndScales() {
+ View v = new View();
+ v.set(1920, 1080, 30f, 0.8f, 500.0, -200.0, 0f);
+ float[] m = new float[16];
+ v.matrix(m);
+ float[] mid = screen(m, 500, -200, 1920, 1080);
+ assertEquals(960, mid[0], 1e-2);
+ assertEquals(540, mid[1], 1e-2);
+ // one plan unit along x: 0.8 px, turned 30 degrees clockwise on screen (y down)
+ float[] step = screen(m, 600, -200, 1920, 1080);
+ assertEquals(80 * Math.cos(Math.toRadians(30)), step[0] - mid[0], 1e-2);
+ assertEquals(80 * Math.sin(Math.toRadians(30)), step[1] - mid[1], 1e-2);
+ }
+
+ @Test
+ public void yojohanViewAgreesWithItsCameraMatrix() {
+ Scene s = new Scene(Look.YOJOHAN);
+ float[] m = new float[16];
+ for (double t : new double[] {0, 37.5, 1_793_500_321.7}) {
+ s.build(t, 1920, 1080, false, false, true);
+ s.view.matrix(m);
+ for (int k = 0; k < 16; k++) assertEquals("t=" + t + " k=" + k, s.matrix[k], m[k], 1e-5);
+ }
+ }
+
+ @Test
+ public void seesBoxesOnTheTurnedScreenAndNotPastIt() {
+ View v = new View();
+ v.set(1600, 900, 45f, 1f, 0.0, 0.0, 0f);
+ assertTrue(v.sees(-10, -10, 10, 10, 0));
+ // the screen's corner reaches sqrt(800^2 + 450^2) = 918 px out; turned 45 degrees it points along a diagonal
+ assertFalse("past the long side", v.sees(700, -700, 720, -680, 0));
+ assertTrue("grown into view", v.sees(700, -700, 720, -680, 400));
+ // along plan x the turned screen ends where its short side does: 450 * sqrt(2) = 636 px
+ assertTrue(v.sees(630, -1, 632, 1, 0));
+ assertFalse(v.sees(640, -1, 642, 1, 0));
+ assertTrue("the margin reaches further", withMargin(v, 20).sees(640, -1, 642, 1, 0));
+ }
+
+ @Test
+ public void zoomAndCentreMoveWhatIsSeen() {
+ View v = new View();
+ v.set(1000, 1000, 0f, 0.5f, 3000.0, 0.0, 0f);
+ assertTrue("1000 px wide at zoom 0.5 shows 2000 plan units", v.sees(3990, 0, 3999, 1, 0));
+ assertFalse(v.sees(4001, 0, 4010, 1, 0));
+ assertFalse("nothing near 0", v.sees(-10, -10, 10, 10, 0));
+ }
+
+ private static View withMargin(View v, float margin) {
+ View m = new View();
+ m.set(v.w, v.h, v.rollDeg, v.zoom, v.centreX, v.centreY, margin);
+ return m;
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/WashTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/WashTest.java
new file mode 100644
index 000000000..9f1e54752
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/WashTest.java
@@ -0,0 +1,105 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class WashTest {
+
+ /** The W3C soft light, written out as the spec gives it. */
+ private static double w3c(double cb, double cs) {
+ if (cs <= 0.5) return cb - (1 - 2 * cs) * cb * (1 - cb);
+ double d = cb <= 0.25 ? ((16 * cb - 12) * cb + 4) * cb : Math.sqrt(cb);
+ return cb + (2 * cs - 1) * (d - cb);
+ }
+
+ @Test
+ public void softLightIsTheW3cFormula() {
+ for (int i = 0; i <= 20; i++) {
+ for (int j = 0; j <= 20; j++) {
+ float a = i / 20f, b = j / 20f;
+ assertEquals("a=" + a + " b=" + b, w3c(a, b), Wash.softLight(a, b), 1e-6);
+ }
+ }
+ assertEquals("black stays black", 0f, Wash.softLight(0f, 0.9f), 0f);
+ }
+
+ @Test
+ public void noneChangesNothing() {
+ float[] c = {0.1f, 0.5f, 0.93f};
+ Wash.NONE.apply(123, 456, 1920, 1080, c);
+ assertArrayEquals(new float[] {0.1f, 0.5f, 0.93f}, c, 1e-6f);
+ }
+
+ @Test
+ public void nodesSitOnAGridFromTheTopLeftAndHoldPastTheEdges() {
+ float[] gain = new float[Wash.NX * Wash.NY * 3], blend = new float[gain.length];
+ java.util.Arrays.fill(gain, 1f);
+ java.util.Arrays.fill(blend, 0.5f);
+ gain[(2 * Wash.NX + 4) * 3] = 0.5f; // node (4, 2), red: 4/16 across, 2/9 down
+ Wash wash = new Wash(gain, blend);
+ float[] c = {0.8f, 0.8f, 0.8f};
+ wash.apply(1920 * 4 / 16f, 1080 * 2 / 9f, 1920, 1080, c);
+ assertArrayEquals(new float[] {0.4f, 0.8f, 0.8f}, c, 1e-5f);
+ c = new float[] {0.8f, 0.8f, 0.8f};
+ wash.apply(1920 * 4.5f / 16, 1080 * 2 / 9f, 1920, 1080, c);
+ assertEquals("halfway to the next node", 0.6f, c[0], 1e-5f);
+ gain[0] = 0.25f;
+ Wash corner = new Wash(gain, blend);
+ c = new float[] {0.8f, 0.8f, 0.8f};
+ corner.apply(-50, -50, 1920, 1080, c);
+ assertEquals("past the top left: the corner node", 0.2f, c[0], 1e-5f);
+ }
+
+ /** Upside down or mirrored, the maps would put the blue at the bottom and the dark at the top. */
+ @Test
+ public void nagayaTurnsMidGreyBlueAtTheTopLeftAndDarkAtTheBottomMiddle() {
+ assertGrey(100, 80, 0x10, 0x85, 0xD0);
+ assertGrey(960, 1020, 0x53, 0x67, 0x91);
+ assertGrey(960, 540, 0x80, 0x80, 0x80);
+ }
+
+ private static void assertGrey(float x, float y, int r, int g, int b) {
+ float[] c = {128 / 255f, 128 / 255f, 128 / 255f};
+ Wash.NAGAYA.apply(x, y, 1920, 1080, c);
+ assertArrayEquals("grey at " + x + ", " + y, new float[] {r / 255f, g / 255f, b / 255f}, c, 0.6f / 255);
+ }
+
+ @Test
+ public void nagayaWallsKeepTheirInkWhereTheRoomsAreWashed() {
+ Scene s = new Scene(Look.NAGAYA);
+ s.build(1_793_500_000.0, 1920, 1080, false, false, false, true); // the camera at rest, so walls reach the corner
+ assertFalse(s.mesh.clipped);
+ float[] d = s.mesh.data, m = s.matrix;
+ int ink = Look.NAGAYA.walls.color, walls = s.mesh.floats - s.frame.wallCount * 6 * SceneMesh.FLOATS_PER_VERTEX;
+ int wallsInCorner = 0, fillsInCorner = 0;
+ for (int k = 0; k < s.mesh.floats; k += SceneMesh.FLOATS_PER_VERTEX) {
+ float x = (m[0] * d[k] + m[4] * d[k + 1] + m[12] + 1) / 2 * 1920;
+ float y = (1 - (m[1] * d[k] + m[5] * d[k + 1] + m[13])) / 2 * 1080;
+ boolean corner = x >= 0 && x < 240 && y >= 0 && y < 240; // where red's W is under 0.45
+ if (k >= walls) {
+ assertEquals(((ink >> 16) & 0xFF) / 255f, d[k + 2], 0f);
+ assertEquals(((ink >> 8) & 0xFF) / 255f, d[k + 3], 0f);
+ assertEquals((ink & 0xFF) / 255f, d[k + 4], 0f);
+ if (corner) wallsInCorner++;
+ } else if (corner) {
+ fillsInCorner++;
+ assertFalse("a fill in the corner keeps its paint", isPaint(d[k + 2], d[k + 3], d[k + 4]));
+ }
+ }
+ assertTrue(wallsInCorner > 0);
+ assertTrue(fillsInCorner > 0);
+ }
+
+ private static boolean isPaint(float r, float g, float b) {
+ float near = 0.5f / 255;
+ for (int p : Look.NAGAYA.palette.deck) {
+ if (Math.abs(((p >> 16) & 0xFF) / 255f - r) < near && Math.abs(((p >> 8) & 0xFF) / 255f - g) < near
+ && Math.abs((p & 0xFF) / 255f - b) < near) return true;
+ }
+ return false;
+ }
+}
diff --git a/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/YojohanGoldenTest.java b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/YojohanGoldenTest.java
new file mode 100644
index 000000000..6cffd9fb3
--- /dev/null
+++ b/addons/tatami/plan/src/test/java/io/github/pbanddev/tatami/YojohanGoldenTest.java
@@ -0,0 +1,27 @@
+package io.github.pbanddev.tatami;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+/** Yojōhan never changes: every float of its mesh and camera matrix, hashed over times, sizes and switches. */
+public class YojohanGoldenTest {
+
+ @Test
+ public void meshAndMatrixAreBitForBitTheSame() {
+ Scene s = new Scene(Look.YOJOHAN);
+ long h = 1125899906842597L;
+ int[][] sizes = {{1920, 1080}, {1280, 720}, {3840, 2160}};
+ for (int i = 0; i < 40; i++) {
+ double t = i % 2 == 0 ? i * 13.7 : 1_793_500_000.0 + i * 97.3;
+ for (int[] sz : sizes) {
+ for (int c = 0; c < 8; c++) {
+ s.build(t, sz[0], sz[1], (c & 1) != 0, (c & 2) != 0, (c & 4) != 0);
+ for (int k = 0; k < s.mesh.floats; k++) h = 31 * h + Float.floatToIntBits(s.mesh.data[k]);
+ for (float m : s.matrix) h = 31 * h + Float.floatToIntBits(m);
+ }
+ }
+ }
+ assertEquals(Long.toHexString(0xfae415ea9e25215dL), Long.toHexString(h));
+ }
+}
diff --git a/addons/tatami/screenshot.jpg b/addons/tatami/screenshot.jpg
new file mode 100644
index 000000000..df9bbfcd1
Binary files /dev/null and b/addons/tatami/screenshot.jpg differ
diff --git a/addons/tatami/settings.gradle b/addons/tatami/settings.gradle
new file mode 100644
index 000000000..619b4640b
--- /dev/null
+++ b/addons/tatami/settings.gradle
@@ -0,0 +1,18 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "tatami"
+// The Tatami add-on: app/ is the installed app, plan/ draws Tatami. Tatami Home, the launcher with
+// Tatami behind the apps, is a separate build in home/ that uses the same plan/.
+include ':app', ':plan'