diff --git a/.changeset/design-bills.md b/.changeset/design-bills.md new file mode 100644 index 000000000..9dfd9da45 --- /dev/null +++ b/.changeset/design-bills.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Ballistic guns and the mine launcher are priced from what they are built from, and the heavier guns need rarer metals: rifled barrels from titanium, lined barrels from tungsten, charged scatter barrels from niobium, rare earths and platinum; flak and point defence guns take a tracking feed. diff --git a/.changeset/ore-batch-rescale.md b/.changeset/ore-batch-rescale.md new file mode 100644 index 000000000..adab3b927 --- /dev/null +++ b/.changeset/ore-batch-rescale.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Belts hold named ores by body class and province, mining stations name them, and gear, hull and consumable prices and the starting purse are a hundredth of what they were. diff --git a/.changeset/recipe-facilities.md b/.changeset/recipe-facilities.md new file mode 100644 index 000000000..d947d2322 --- /dev/null +++ b/.changeset/recipe-facilities.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Stations carry facility gear on a new Facility mount: every recipe names the facility that runs it, every station kind lists the facilities it is fitted with, and every station hull that serves a kind has the Facility row to take them (Zenith and the Arsenal Depot each have one). Nothing runs a recipe yet. Because the hardpoint tints spread across one more type, every hardpoint on the schematic turns a little around the colour wheel. diff --git a/.changeset/release-pipeline.md b/.changeset/release-pipeline.md new file mode 100644 index 000000000..f73efa641 --- /dev/null +++ b/.changeset/release-pipeline.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Releases are built and published by a pipeline. diff --git a/.changeset/shields.md b/.changeset/shields.md new file mode 100644 index 000000000..1bc06d016 --- /dev/null +++ b/.changeset/shields.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Shields are on sale: a light 1x1 and a heavy 2x2 projector fit the Djinni's and the Nakovalnya's shield mounts and every starter ship's, and the Zenith's fourth radiator mount takes radiators again. diff --git a/.changeset/starting-purse.md b/.changeset/starting-purse.md new file mode 100644 index 000000000..38d4ef0c0 --- /dev/null +++ b/.changeset/starting-purse.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +The starting purse is 4000 credits: one first upgrade, not the ladder. diff --git a/.changeset/tactical-view.md b/.changeset/tactical-view.md new file mode 100644 index 000000000..260337812 --- /dev/null +++ b/.changeset/tactical-view.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +The tactical view is a camera of its own: scroll out past a bump to a three-quarters top-down view over the grid, drag to move it, scroll back in through the bump to return to your ship. diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml new file mode 100644 index 000000000..d3025c59a --- /dev/null +++ b/.forgejo/workflows/release.yml @@ -0,0 +1,117 @@ +# The one actor that turns .changeset/ files and VERSION into a tag and a forge release (docs/release-checklist.md). +# Dispatch by hand on the branch to release. Runs on the Starfire runner in host mode, as the operator's Windows user, +# because the Unity Personal licence lives there. Every host prerequisite is checked by the first step, before any build or +# push (list: docs/release-checklist.md, One-time setup). Nothing is pushed until both players have built: a failed +# preflight or build leaves the forge untouched. After the push, a failed forge release has a recovery in the checklist. +name: release + +on: + workflow_dispatch: + +concurrency: + group: release + cancel-in-progress: false + +jobs: + release: + runs-on: starfire + env: + UNITY_EDITOR: ${{ vars.UNITY_EDITOR }} + CULTLIB_ROOT: ${{ vars.CULTLIB_ROOT }} + CULTMATH_ROOT: ${{ vars.CULTMATH_ROOT }} + BUILD_NAME: release-${{ github.run_id }} + defaults: + run: + shell: '"C:/Program Files/Git/bin/bash.exe" -e {0}' + steps: + # The composite forgejo-release action runs its steps with `shell: bash`, resolved through PATH, where System32's WSL + # bash.exe can win. Git's bin goes first for every later step of this job. + - name: Put Git Bash first on PATH + run: printf '%s\n' 'C:\Program Files\Git\bin' >> "$GITHUB_PATH" + + - name: Preflight host prerequisites + env: + RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }} + run: | + set -u + missing="" + first_bash="$(cmd.exe //c where bash 2>/dev/null | head -n 1 | tr -d '\r')" + case "${first_bash//$'\x5c'//}" in + "C:/Program Files/Git/"*) ;; + *) missing="$missing"$'\n'" PATH resolves bash to '$first_bash', not Git Bash (the forgejo-release action would run WSL bash)" ;; + esac + note() { missing="$missing"$'\n'" $1"; } + for tool in jq curl knope git tar dotnet; do + command -v "$tool" >/dev/null || note "$tool is not on PATH" + done + test -x /c/Windows/System32/tar.exe || note "C:/Windows/System32/tar.exe is missing" + test -n "$RELEASE_TOKEN" || note "secret RELEASE_TOKEN is not set" + test -f "$UNITY_EDITOR" || note "repo variable UNITY_EDITOR is unset or not a file: '$UNITY_EDITOR'" + test -d "$CULTLIB_ROOT" || note "repo variable CULTLIB_ROOT is unset or not a directory: '$CULTLIB_ROOT'" + test -d "$CULTMATH_ROOT" || note "repo variable CULTMATH_ROOT is unset or not a directory: '$CULTMATH_ROOT'" + if test -n "$missing"; then echo "release preflight failed, nothing was built or pushed:$missing"; exit 1; fi + + - uses: actions/checkout@v4 + with: + lfs: true + fetch-depth: 0 + token: ${{ secrets.RELEASE_TOKEN }} + + - name: Prepare release + id: prepare + run: | + set -euo pipefail + knope prepare-release + version="$(tr -d '\r\n' < VERSION)" + if git rev-parse -q --verify "refs/tags/v$version" >/dev/null; then + echo "v$version already exists: no change file asked for a new version"; exit 1 + fi + awk -v heading="## $version " 'index($0, heading) == 1 { found = 1; next } /^## / { if (found) exit } found' CHANGELOG.md > "$RUNNER_TEMP/notes.md" + test -s "$RUNNER_TEMP/notes.md" || { echo "CHANGELOG.md has no section for $version"; exit 1; } + git add VERSION CHANGELOG.md .changeset + git -c user.name="Aetheria release" -c user.email="release@gamecult.invalid" commit -m "Release $version" + git -c user.name="Aetheria release" -c user.email="release@gamecult.invalid" tag -a "v$version" -m "Aetheria $version" + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + echo "notes=$RUNNER_TEMP/notes.md" >> "$GITHUB_OUTPUT" + + - name: Build and zip players + run: | + set -euo pipefail + version="${{ steps.prepare.outputs.version }}" + build="$(cd .. && pwd)/$BUILD_NAME" + mkdir -p "$build/dist" + project="$(pwd -W)" + for target in win64 linux64; do + name="Aetheria-$version-$target" + "$UNITY_EDITOR" -batchmode -quit -projectPath "$project" -executeMethod AetheriaBuild.Build \ + -aetheriaVersion "$version" -aetheriaOut "$(cd "$build" && pwd -W)/$name" -aetheriaTarget "$target" \ + -logFile "$(cd "$build" && pwd -W)/$target.log" + /c/Windows/System32/tar.exe -a -c -f "$build/dist/$name.zip" -C "$build" "$name" + size="$(stat -c %s "$build/dist/$name.zip")" + test "$size" -le 2147483648 || { echo "$name.zip is $size bytes: over the forge's 2048 MB attachment limit"; exit 1; } + done + + - name: Publish tag and release commit + run: | + set -euo pipefail + git push --atomic origin "HEAD:refs/heads/${{ github.ref_name }}" "refs/tags/v${{ steps.prepare.outputs.version }}" + + - name: Forge release + uses: actions/forgejo-release@v2.13.4 + with: + direction: upload + tag: v${{ steps.prepare.outputs.version }} + sha: ${{ steps.prepare.outputs.sha }} + title: Aetheria ${{ steps.prepare.outputs.version }} + token: ${{ secrets.RELEASE_TOKEN }} + release-dir: ../${{ env.BUILD_NAME }}/dist + release-notes-file: ${{ steps.prepare.outputs.notes }} + + - name: Show build logs on failure + if: failure() + run: tail -n 40 ../"$BUILD_NAME"/*.log || true + + - name: Remove build directory + if: success() + run: rm -rf ../"$BUILD_NAME" diff --git a/.gitattributes b/.gitattributes index d530ed421..87c9db929 100644 --- a/.gitattributes +++ b/.gitattributes @@ -51,11 +51,12 @@ *.dylib filter=lfs diff=lfs merge=lfs -text *.bundle filter=lfs diff=lfs merge=lfs -text *.engine filter=lfs diff=lfs merge=lfs -text -*.sbsar filter=lfs diff=lfs merge=lfs -text *.msgpack filter=lfs diff=lfs merge=lfs -text GameData/*.cc filter=lfs diff=lfs merge=lfs -text GameData/Mods/**/*.cc filter=lfs diff=lfs merge=lfs -text GameData/Mods/**/*.glb filter=lfs diff=lfs merge=lfs -text +tests/fixtures/mods/**/*.cc filter=lfs diff=lfs merge=lfs -text +tests/fixtures/mods/**/*.glb filter=lfs diff=lfs merge=lfs -text tools/blender/tests/fixtures/*.glb filter=lfs diff=lfs merge=lfs -text *.a filter=lfs diff=lfs merge=lfs -text *AkSoundEngine filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore index ac9c49142..8f15133d1 100644 --- a/.gitignore +++ b/.gitignore @@ -113,3 +113,4 @@ tests/_scratch_* # Stryker.NET mutation reports (regenerated per run) StrykerOutput/ +native/aetherlight/target/ diff --git a/Aetheria.Shared/Aetheria.Shared.csproj b/Aetheria.Shared/Aetheria.Shared.csproj index a8a4c97bc..591e1f42c 100644 --- a/Aetheria.Shared/Aetheria.Shared.csproj +++ b/Aetheria.Shared/Aetheria.Shared.csproj @@ -26,6 +26,8 @@ + + diff --git a/Assets/Content/Prefabs/Turrets/Turret.prefab b/Assets/Content/Prefabs/Turrets/Turret.prefab index 748ca8a29..2df968941 100644 --- a/Assets/Content/Prefabs/Turrets/Turret.prefab +++ b/Assets/Content/Prefabs/Turrets/Turret.prefab @@ -998,8 +998,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: 3720744386649352057, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} + - {fileID: 2100000, guid: 38f8ba6b169127249b6532be2b3926ee, type: 2} + - {fileID: 2100000, guid: 5e43f48908cce2949a41677ec48affe5, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Materials/Aluminium brushed.mat b/Assets/Materials/Aluminium brushed.mat index b8ade999f..a624f95e1 100644 --- a/Assets/Materials/Aluminium brushed.mat +++ b/Assets/Materials/Aluminium brushed.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 4730978449518085612, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 2800000, guid: c3ef09438e3e46d18a4c267810aeb285, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -45,23 +44,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 7556082237344091230, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 2800000, guid: f70b6df0395b4752b4ec80cb7bfd8f42, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 6373266012617290493, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 2800000, guid: 40f5e915d2734d43bc01f984772e9d29, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: 342959783478273704, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: -9132138291289375396, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Floats: @@ -85,7 +80,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.951, g: 0.951, b: 0.951, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint Magenta.mat b/Assets/Materials/Car Paint Magenta.mat index dbe95bd62..bff25331a 100644 --- a/Assets/Materials/Car Paint Magenta.mat +++ b/Assets/Materials/Car Paint Magenta.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _FadeTex: @@ -35,18 +34,15 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -59,6 +55,6 @@ Material: - _Metallic: 1 - _OcclusionStrength: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.5, g: 0, b: 0.228113, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint Red.mat b/Assets/Materials/Car Paint Red.mat index 8a7ffa46f..063e9367c 100644 --- a/Assets/Materials/Car Paint Red.mat +++ b/Assets/Materials/Car Paint Red.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -45,23 +44,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: -1652887728991447519, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Floats: @@ -85,7 +80,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 1, g: 0.15685, b: 0, a: 1} - _EdgeColor: {r: 6.0235295, g: 6.0235295, b: 24.094118, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint White Small.mat b/Assets/Materials/Car Paint White Small.mat index aab8a3663..cca6010f3 100644 --- a/Assets/Materials/Car Paint White Small.mat +++ b/Assets/Materials/Car Paint White Small.mat @@ -29,8 +29,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -54,23 +53,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 16, y: 16} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: -1652887728991447519, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -95,7 +90,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 1, g: 0.891509, b: 0.946396, a: 1} - _EdgeColor: {r: 6.0235295, g: 6.0235295, b: 24.094118, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint White.mat b/Assets/Materials/Car Paint White.mat index ba32280af..ad0af17d2 100644 --- a/Assets/Materials/Car Paint White.mat +++ b/Assets/Materials/Car Paint White.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _FadeTex: @@ -35,18 +34,15 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -59,6 +55,6 @@ Material: - _Metallic: 1 - _OcclusionStrength: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 1, g: 0.891509, b: 0.946396, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Cockpit.mat b/Assets/Materials/Cockpit.mat index 543d0d608..fb19e541a 100644 --- a/Assets/Materials/Cockpit.mat +++ b/Assets/Materials/Cockpit.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -3419035557588562233, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 2800000, guid: 3a10044baac4438f9fc0930783eccdf7, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -51,23 +50,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 2800000, guid: 5a9cee903a2d48718aaf6b224126f279, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 2800000, guid: 8b24d7ea11c341408a146fa39f59b7b0, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -3436886866959827803, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 7009887839391554354, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -92,7 +87,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.85, g: 0.65, b: 0.30, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Metal 003.mat b/Assets/Materials/Metal 003.mat index 4d07d4c1a..09330e338 100644 --- a/Assets/Materials/Metal 003.mat +++ b/Assets/Materials/Metal 003.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -2508943184622041221, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 2800000, guid: 3a10044baac4438f9fc0930783eccdf7, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -41,23 +40,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -1236254257114565538, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 2800000, guid: 5a9cee903a2d48718aaf6b224126f279, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 4019402794555593307, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 2800000, guid: 8b24d7ea11c341408a146fa39f59b7b0, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1475328947160444094, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 7523010977671448217, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Floats: diff --git a/Assets/Materials/Mine Glow.mat b/Assets/Materials/Mine Glow.mat index e1627f2d9..7d6d630e7 100644 --- a/Assets/Materials/Mine Glow.mat +++ b/Assets/Materials/Mine Glow.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} + m_Texture: {fileID: 2800000, guid: 8bc10cfce8a64defaf9f67d156003f09, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -41,13 +40,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: 2195885db9e846999fd10aa7f5c629b1, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: d91bff887b764847a484d0a9bedce9e9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: diff --git a/Assets/Models/Discobolus/Discobolus Bronze.mat b/Assets/Materials/Pickup Trim.mat similarity index 64% rename from Assets/Models/Discobolus/Discobolus Bronze.mat rename to Assets/Materials/Pickup Trim.mat index 30697d42a..0cea43f4f 100644 --- a/Assets/Models/Discobolus/Discobolus Bronze.mat +++ b/Assets/Materials/Pickup Trim.mat @@ -2,25 +2,34 @@ %TAG !u! tag:unity3d.com,2011: --- !u!21 &2100000 Material: - serializedVersion: 6 + serializedVersion: 8 m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_Name: Discobolus Bronze - m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - m_ShaderKeywords: _METALLICGLOSSMAP _NORMALMAP + m_Name: Pickup Trim + m_Shader: {fileID: 4800000, guid: ddff0b48b92c991499817d2a0f5d5059, type: 3} + m_Parent: {fileID: 0} + m_ModifiedSerializedProperties: 0 + m_ValidKeywords: [] + m_InvalidKeywords: + - _MAINTEX + - _METALLICGLOSSMAP + - _NORMALMAP + - _OCCLUSIONMAP + - _PARALLAXMAP m_LightmapFlags: 4 m_EnableInstancingVariants: 0 m_DoubleSidedGI: 0 m_CustomRenderQueue: -1 stringTagMap: {} disabledShaderPasses: [] + m_LockedProperties: m_SavedProperties: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 2800000, guid: 9863db663524d9a4eab030a666b1f2da, type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -37,35 +46,41 @@ Material: m_Offset: {x: 0, y: 0} - _EmissionMap: m_Texture: {fileID: 0} + m_Scale: {x: 16, y: 16} + m_Offset: {x: 0, y: 0} + - _FadeTex: + m_Texture: {fileID: 2800000, guid: df0632a08c5f1a1498fa325c755dc459, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - m_Scale: {x: 1, y: 1} + m_Texture: {fileID: 0} + m_Scale: {x: 16, y: 16} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: 2800000, guid: d60207b632e464d4b884dded41db5b9b, type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} + m_Ints: [] m_Floats: - _BumpScale: 1 - _Cutoff: 0.5 - _DetailNormalMapScale: 1 - _DstBlend: 0 + - _Fade: 1 + - _FadeEdge: 0.1 + - _FadeSharpness: 16 - _GlossMapScale: 1 - - _Glossiness: 0.5 + - _Glossiness: 0.7 - _GlossyReflections: 1 - - _Metallic: 0 + - _Metallic: 0.6 - _Mode: 0 - _OcclusionStrength: 1 - _Parallax: 0.005 @@ -75,6 +90,8 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0, g: 0.605881, b: 1, a: 1} + - _EdgeColor: {r: 6.0235295, g: 6.0235295, b: 24.094118, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] + m_AllowLocking: 1 diff --git a/Assets/Steel.mat.meta b/Assets/Materials/Pickup Trim.mat.meta similarity index 79% rename from Assets/Steel.mat.meta rename to Assets/Materials/Pickup Trim.mat.meta index d645ba6a4..d57d829c2 100644 --- a/Assets/Steel.mat.meta +++ b/Assets/Materials/Pickup Trim.mat.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 4c998decce894b4458e1bc667975aeea +guid: bebc82079e5d4e578a73c3ab48d2c2da NativeFormatImporter: externalObjects: {} mainObjectFileID: 2100000 diff --git a/Assets/Materials/Radiators 1.mat b/Assets/Materials/Radiators 1.mat deleted file mode 100644 index a6219fe9d..000000000 --- a/Assets/Materials/Radiators 1.mat +++ /dev/null @@ -1,87 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Radiators 1 - m_Shader: {fileID: 4800000, guid: d69ef48273708ef4680762f5cdcfc860, type: 3} - m_ShaderKeywords: - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpPower: 2 - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _Emission: 15 - - _EmissionFresnel: 4 - - _EmissionRoughnessFresnelPower: 0.5 - - _GlossMapScale: 1 - - _Glossiness: 1 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _ReverseRim: 0 - - _Rotation: 0 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 1, g: 0.40135294, b: 0, a: 1} - m_BuildTextureStacks: [] diff --git a/Assets/Materials/Radiators 1.mat.meta b/Assets/Materials/Radiators 1.mat.meta deleted file mode 100644 index c562a84de..000000000 --- a/Assets/Materials/Radiators 1.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: f396635dc77c59c44ac85ae278a2e909 -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 0 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Materials/Radiators.mat b/Assets/Materials/Radiators.mat index aa7eaf0fb..1e5c52a54 100644 --- a/Assets/Materials/Radiators.mat +++ b/Assets/Materials/Radiators.mat @@ -21,8 +21,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} + m_Texture: {fileID: 2800000, guid: 8bc10cfce8a64defaf9f67d156003f09, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -46,13 +45,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: 2195885db9e846999fd10aa7f5c629b1, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: d91bff887b764847a484d0a9bedce9e9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: diff --git a/Assets/Materials/Silver.mat b/Assets/Materials/Silver.mat index e02d24f97..0bb79d6a1 100644 --- a/Assets/Materials/Silver.mat +++ b/Assets/Materials/Silver.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 8947980237086559854, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 2800000, guid: c3ef09438e3e46d18a4c267810aeb285, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -51,23 +50,19 @@ Material: m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -1383037052668628532, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 2800000, guid: f70b6df0395b4752b4ec80cb7bfd8f42, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 6429125567479694453, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 2800000, guid: 40f5e915d2734d43bc01f984772e9d29, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -9097439929179392311, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 425190381137097012, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] diff --git a/Assets/Materials/Station Lights.mat b/Assets/Materials/Station Lights.mat index f863306a1..2aac54ac7 100644 --- a/Assets/Materials/Station Lights.mat +++ b/Assets/Materials/Station Lights.mat @@ -24,8 +24,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} + m_Texture: {fileID: 2800000, guid: 8bc10cfce8a64defaf9f67d156003f09, type: 3} m_Scale: {x: 8, y: 8} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -49,13 +48,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: 2195885db9e846999fd10aa7f5c629b1, type: 3} m_Scale: {x: 16, y: 16} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: d91bff887b764847a484d0a9bedce9e9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: diff --git a/Assets/Materials/Steel brushed.mat b/Assets/Materials/Steel brushed.mat deleted file mode 100644 index dba1bd074..000000000 --- a/Assets/Materials/Steel brushed.mat +++ /dev/null @@ -1,83 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Steel brushed - m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - m_ShaderKeywords: _MAINTEX _METALLICGLOSSMAP _NORMALMAP _OCCLUSIONMAP _PARALLAXMAP - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -4471413742775304797, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: -4638397344074346932, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: 5049811794194361025, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: 1753668427856518731, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: -3498708498072814504, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _GlossMapScale: 1 - - _Glossiness: 0.5 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - m_BuildTextureStacks: [] diff --git a/Assets/Materials/Steel brushed.mat.meta b/Assets/Materials/Steel brushed.mat.meta deleted file mode 100644 index 73afa8139..000000000 --- a/Assets/Materials/Steel brushed.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: df3e704fc59794a45b8e14a78d96cca3 -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 0 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Materials/Steel parkerized.mat b/Assets/Materials/Steel parkerized.mat index b4194ab66..ba47afb87 100644 --- a/Assets/Materials/Steel parkerized.mat +++ b/Assets/Materials/Steel parkerized.mat @@ -29,8 +29,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 885599758852769373, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 2800000, guid: dc71e34b4a1f4de7aa826d18b67b5852, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -54,23 +53,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -4474525002722929857, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 2800000, guid: 1ed06708491744fe944217d19e450157, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -2334804936223627746, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 2800000, guid: 31e7d642ff8a49a28390c82626c4b6b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -8380876848358870972, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 172713863077875830, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] diff --git a/Assets/Materials/Steel.mat b/Assets/Materials/Steel.mat index 37420bfd4..6eeb29385 100644 --- a/Assets/Materials/Steel.mat +++ b/Assets/Materials/Steel.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 2800000, guid: c3ef09438e3e46d18a4c267810aeb285, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -51,23 +50,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 2800000, guid: f70b6df0395b4752b4ec80cb7bfd8f42, type: 3} m_Scale: {x: 4, y: 4} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 2800000, guid: 40f5e915d2734d43bc01f984772e9d29, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] diff --git a/Assets/Materials/Substance/Metal.meta b/Assets/Materials/Substance/Metal.meta deleted file mode 100644 index e8c0226e7..000000000 --- a/Assets/Materials/Substance/Metal.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 09aee558716a08d4c9806b9b4273a209 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Materials/Substance/Metal/Pickup Base.sbsar b/Assets/Materials/Substance/Metal/Pickup Base.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Base.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/Pickup Base.sbsar.meta b/Assets/Materials/Substance/Metal/Pickup Base.sbsar.meta deleted file mode 100644 index 2966159bc..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Base.sbsar.meta +++ /dev/null @@ -1,382 +0,0 @@ -fileFormatVersion: 2 -guid: 26a894e543f3ed44893b1620707ca62c -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n - \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 1 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 1 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: 3068890721646206586, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: -3552914696322007609, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: -1242281561028671816, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: -1652887728991447519, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} diff --git a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar b/Assets/Materials/Substance/Metal/Pickup Trim.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar.meta b/Assets/Materials/Substance/Metal/Pickup Trim.sbsar.meta deleted file mode 100644 index 302e453b5..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar.meta +++ /dev/null @@ -1,381 +0,0 @@ -fileFormatVersion: 2 -guid: c00b5a4f1e4743a4ca59b8030251f900 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.005 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3068890721646206586, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: -3552914696322007609, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: -1242281561028671816, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: -1652887728991447519, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} diff --git a/Assets/Materials/Substance/Metal/galvanized_001.sbsar b/Assets/Materials/Substance/Metal/galvanized_001.sbsar deleted file mode 100644 index 5d6237210..000000000 --- a/Assets/Materials/Substance/Metal/galvanized_001.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:274db26d631b6cd53024c1366c01322d99b6194b5e211d04c5430bb8174ae8f6 -size 8207 diff --git a/Assets/Materials/Substance/Metal/galvanized_001.sbsar.meta b/Assets/Materials/Substance/Metal/galvanized_001.sbsar.meta deleted file mode 100644 index 9815351c0..000000000 --- a/Assets/Materials/Substance/Metal/galvanized_001.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 2be0f689f5b01be4aa1032bc86f15eab -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: galvanized_001/galvanized_001 - - first: - 4: 400000 - second: galvanized_001/galvanized_001/Transform - - first: - 21: 2100000 - second: mat.Galvanized_001 - - first: - 23: 2300000 - second: galvanized_001/galvanized_001/MeshRenderer - - first: - 28: 2800000 - second: Galvanized_001_baseColor - - first: - 28: 2800002 - second: Galvanized_001_normal - - first: - 28: 2800004 - second: Galvanized_001_metallic - - first: - 28: 2800006 - second: Galvanized_001_ambientOcclusion - - first: - 28: 2800008 - second: Galvanized_001_height - - first: - 33: 3300000 - second: galvanized_001/galvanized_001/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: galvanized_001/galvanized_001/SphereCollider - - first: - 1001: 100100000 - second: galvanized_001 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Galvanized_001 - prototypeName: Galvanized_001 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2787997366030867252, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 7907137595978400316, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 1034366337303036879, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4470803051826786927, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3422293810953865746, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Galvanized_001_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -231086597109407277, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - generatedTextures: - - {fileID: 7907137595978400316, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: -2787997366030867252, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: 1034366337303036879, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: 4470803051826786927, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: -3422293810953865746, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} diff --git a/Assets/Materials/Substance/Metal/iron_damaged.sbsar b/Assets/Materials/Substance/Metal/iron_damaged.sbsar deleted file mode 100644 index cb09572e5..000000000 --- a/Assets/Materials/Substance/Metal/iron_damaged.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4a12de208077d6dfd8e70dfa8a8976bb9e5b2ca2d258bb34aa50c81a58a6451c -size 30808 diff --git a/Assets/Materials/Substance/Metal/iron_damaged.sbsar.meta b/Assets/Materials/Substance/Metal/iron_damaged.sbsar.meta deleted file mode 100644 index d7a4d07d7..000000000 --- a/Assets/Materials/Substance/Metal/iron_damaged.sbsar.meta +++ /dev/null @@ -1,293 +0,0 @@ -fileFormatVersion: 2 -guid: d15fc45ed0000934d946b5f271f637ef -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Iron Damaged - prototypeName: Iron Damaged - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -1855041196637152199, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -2789335455068261637, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 7922211451800446260, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4424499752615739725, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7474978398744299577, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambientocclusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Iron Damaged - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 1736733470071950104, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - generatedTextures: - - {fileID: -2789335455068261637, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: -1855041196637152199, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: 7922211451800446260, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: 7474978398744299577, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: -4424499752615739725, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} diff --git a/Assets/Materials/Substance/Metal/iron_rugged.sbsar b/Assets/Materials/Substance/Metal/iron_rugged.sbsar deleted file mode 100644 index d211f88ad..000000000 --- a/Assets/Materials/Substance/Metal/iron_rugged.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5f2bc787cbb3f6511050a4faddaa07077bf54814131752687ed3717914d77de5 -size 28930 diff --git a/Assets/Materials/Substance/Metal/iron_rugged.sbsar.meta b/Assets/Materials/Substance/Metal/iron_rugged.sbsar.meta deleted file mode 100644 index 4d3540662..000000000 --- a/Assets/Materials/Substance/Metal/iron_rugged.sbsar.meta +++ /dev/null @@ -1,293 +0,0 @@ -fileFormatVersion: 2 -guid: afbd691d0ea2a5a47b5a43b244593a56 -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Iron Rugged - prototypeName: Iron Rugged - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2323688274092838296, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -3909611376798458227, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -1417795912608492100, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -7795300588429949130, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 3868076301887189615, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambientocclusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Iron Rugged - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -7894845242109240131, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - generatedTextures: - - {fileID: -3909611376798458227, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: -2323688274092838296, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: -1417795912608492100, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: 3868076301887189615, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: -7795300588429949130, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_002.sbsar b/Assets/Materials/Substance/Metal/metal_002.sbsar deleted file mode 100644 index 97dcc5ffe..000000000 --- a/Assets/Materials/Substance/Metal/metal_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9282e9326add2015fd2748e98c38062e438b085036eae00825551986e30d002f -size 11670 diff --git a/Assets/Materials/Substance/Metal/metal_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_002.sbsar.meta deleted file mode 100644 index 725363c0a..000000000 --- a/Assets/Materials/Substance/Metal/metal_002.sbsar.meta +++ /dev/null @@ -1,372 +0,0 @@ -fileFormatVersion: 2 -guid: 2b42584452fe0cc4fa4e8a115230b156 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_002/metal_002 - - first: - 4: 400000 - second: metal_002/metal_002/Transform - - first: - 21: 2100000 - second: mat.Metal 002 - - first: - 23: 2300000 - second: metal_002/metal_002/MeshRenderer - - first: - 28: 2800000 - second: Metal 002_baseColor - - first: - 28: 2800002 - second: Metal 002_normal - - first: - 28: 2800004 - second: Metal 002_metallic - - first: - 28: 2800006 - second: Metal 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal 002_height - - first: - 33: 3300000 - second: metal_002/metal_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_002/metal_002/SphereCollider - - first: - 1001: 100100000 - second: metal_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal 002 - prototypeName: Metal 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1550000119726971649, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -6882973941229436791, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 6347190432477724635, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3766318789785789000, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - generatedTextures: - - {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: 1550000119726971649, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: -6882973941229436791, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: 6347190432477724635, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_003.sbsar b/Assets/Materials/Substance/Metal/metal_003.sbsar deleted file mode 100644 index bbc118a2d..000000000 --- a/Assets/Materials/Substance/Metal/metal_003.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4ef8ee0ce61d17b7c84433ea0f780f32609c81f580f2c7d3a9c78303b9051a47 -size 7739 diff --git a/Assets/Materials/Substance/Metal/metal_003.sbsar.meta b/Assets/Materials/Substance/Metal/metal_003.sbsar.meta deleted file mode 100644 index f3ab67932..000000000 --- a/Assets/Materials/Substance/Metal/metal_003.sbsar.meta +++ /dev/null @@ -1,372 +0,0 @@ -fileFormatVersion: 2 -guid: 885e680924fc12c439a842a2142d4b78 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_003/metal_003 - - first: - 4: 400000 - second: metal_003/metal_003/Transform - - first: - 21: 2100000 - second: mat.Metal 003 - - first: - 23: 2300000 - second: metal_003/metal_003/MeshRenderer - - first: - 28: 2800000 - second: Metal 003_baseColor - - first: - 28: 2800002 - second: Metal 003_normal - - first: - 28: 2800004 - second: Metal 003_metallic - - first: - 28: 2800006 - second: Metal 003_height - - first: - 28: 2800008 - second: Metal 003_ambientOcclusion - - first: - 33: 3300000 - second: metal_003/metal_003/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_003/metal_003/SphereCollider - - first: - 1001: 100100000 - second: metal_003 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal 003 - prototypeName: Metal 003 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2508943184622041221, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 8, y: 8} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -1236254257114565538, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 8, y: 8} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 4019402794555593307, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1475328947160444094, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7523010977671448217, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Metal 003_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -741235592913766832, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - generatedTextures: - - {fileID: -1236254257114565538, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: -2508943184622041221, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: 4019402794555593307, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: 7523010977671448217, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: -1475328947160444094, guid: 885e680924fc12c439a842a2142d4b78, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_006.sbsar b/Assets/Materials/Substance/Metal/metal_006.sbsar deleted file mode 100644 index ac614998f..000000000 --- a/Assets/Materials/Substance/Metal/metal_006.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c7cdd662d4c7ee3124366ac316fe6aa5dd247c279bba053a9084916e0510d8df -size 12109 diff --git a/Assets/Materials/Substance/Metal/metal_006.sbsar.meta b/Assets/Materials/Substance/Metal/metal_006.sbsar.meta deleted file mode 100644 index f304dd2c0..000000000 --- a/Assets/Materials/Substance/Metal/metal_006.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 53adf8e53222e6f4791d7bf2110fb70c -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_006/metal_006 - - first: - 4: 400000 - second: metal_006/metal_006/Transform - - first: - 21: 2100000 - second: mat.Metal 006 - - first: - 23: 2300000 - second: metal_006/metal_006/MeshRenderer - - first: - 28: 2800000 - second: Metal 006_baseColor - - first: - 28: 2800002 - second: Metal 006_normal - - first: - 28: 2800004 - second: Metal 006_metallic - - first: - 28: 2800006 - second: Metal 006_height - - first: - 28: 2800008 - second: Metal 006_ambientOcclusion - - first: - 33: 3300000 - second: metal_006/metal_006/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_006/metal_006/SphereCollider - - first: - 1001: 100100000 - second: metal_006 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal 006 - prototypeName: Metal 006 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -9145106948908842110, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 8714526317094329886, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 8283496261199770474, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -247870979206812949, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 4895182546727821380, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Metal 006_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3954565982357225544, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - generatedTextures: - - {fileID: 8714526317094329886, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: -9145106948908842110, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: 8283496261199770474, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: 4895182546727821380, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: -247870979206812949, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar b/Assets/Materials/Substance/Metal/metal_aluminium.sbsar deleted file mode 100644 index 088b73bee..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b19246651deb85c3c0a8d424507e0711ccce8c9eae241da396a36cd210f38f20 -size 10491 diff --git a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar.meta b/Assets/Materials/Substance/Metal/metal_aluminium.sbsar.meta deleted file mode 100644 index 95addd8d7..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: 6b2eb94965ca27542b8627d3521f5b5b -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_aluminium/metal_aluminium - - first: - 4: 400000 - second: metal_aluminium/metal_aluminium/Transform - - first: - 21: 2100000 - second: mat.Aluminium - - first: - 23: 2300000 - second: metal_aluminium/metal_aluminium/MeshRenderer - - first: - 28: 2800000 - second: Aluminium_baseColor - - first: - 28: 2800002 - second: Aluminium_normal - - first: - 28: 2800004 - second: Aluminium_metallic - - first: - 28: 2800006 - second: Aluminium_ambientOcclusion - - first: - 28: 2800008 - second: Aluminium_height - - first: - 33: 3300000 - second: metal_aluminium/metal_aluminium/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_aluminium/metal_aluminium/SphereCollider - - first: - 1001: 100100000 - second: metal_aluminium - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Aluminium - prototypeName: Aluminium - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -7227111979962756822, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5122202571912407749, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -5067940305606501900, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 9049458111962441826, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -7751791800289965735, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Aluminium_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 2717629391965333470, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - generatedTextures: - - {fileID: 5122202571912407749, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: -7227111979962756822, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: -5067940305606501900, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: 9049458111962441826, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: -7751791800289965735, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar b/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar deleted file mode 100644 index 7f2ec6e98..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:41bfd12f87e8255f00383022aa8a1d0c83273a8a23e21233db9f8f08eb89738f -size 12223 diff --git a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar.meta b/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar.meta deleted file mode 100644 index cafdf3d25..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: 06d6a565d43fba5409712ce9a10bfbef -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_aluminium_brushed/metal_aluminium_brushed - - first: - 4: 400000 - second: metal_aluminium_brushed/metal_aluminium_brushed/Transform - - first: - 21: 2100000 - second: mat.Aluminium brushed - - first: - 23: 2300000 - second: metal_aluminium_brushed/metal_aluminium_brushed/MeshRenderer - - first: - 28: 2800000 - second: Aluminium brushed_baseColor - - first: - 28: 2800002 - second: Aluminium brushed_normal - - first: - 28: 2800004 - second: Aluminium brushed_metallic - - first: - 28: 2800006 - second: Aluminium brushed_ambientOcclusion - - first: - 28: 2800008 - second: Aluminium brushed_height - - first: - 33: 3300000 - second: metal_aluminium_brushed/metal_aluminium_brushed/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_aluminium_brushed/metal_aluminium_brushed/SphereCollider - - first: - 1001: 100100000 - second: metal_aluminium_brushed - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Aluminium brushed - prototypeName: Aluminium brushed - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n - \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 4730978449518085612, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 7556082237344091230, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 6373266012617290493, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 342959783478273704, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -9132138291289375396, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Aluminium brushed_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -5899741495057040748, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - generatedTextures: - - {fileID: 7556082237344091230, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: 4730978449518085612, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: 6373266012617290493, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: 342959783478273704, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: -9132138291289375396, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_brass.sbsar b/Assets/Materials/Substance/Metal/metal_brass.sbsar deleted file mode 100644 index 8db7e53b4..000000000 --- a/Assets/Materials/Substance/Metal/metal_brass.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:26e440c8cc91202789c408e82dfa3caca98938014aaf63baade897fade94f212 -size 12658 diff --git a/Assets/Materials/Substance/Metal/metal_brass.sbsar.meta b/Assets/Materials/Substance/Metal/metal_brass.sbsar.meta deleted file mode 100644 index dad220291..000000000 --- a/Assets/Materials/Substance/Metal/metal_brass.sbsar.meta +++ /dev/null @@ -1,375 +0,0 @@ -fileFormatVersion: 2 -guid: 9fc901afb8a434e46b9405eaec2df5a4 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_brass/metal_brass - - first: - 4: 400000 - second: metal_brass/metal_brass/Transform - - first: - 21: 2100000 - second: mat.Brass - - first: - 23: 2300000 - second: metal_brass/metal_brass/MeshRenderer - - first: - 28: 2800000 - second: Brass_baseColor - - first: - 28: 2800002 - second: Brass_normal - - first: - 28: 2800004 - second: Brass_metallic - - first: - 28: 2800006 - second: Brass_ambientOcclusion - - first: - 28: 2800008 - second: Brass_height - - first: - 33: 3300000 - second: metal_brass/metal_brass/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_brass/metal_brass/SphereCollider - - first: - 1001: 100100000 - second: metal_brass - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Brass - prototypeName: Brass - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3419035557588562233, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -3436886866959827803, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7009887839391554354, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Brass_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -4907982557009795279, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - generatedTextures: - - {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: -3419035557588562233, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: -3436886866959827803, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: 7009887839391554354, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar.meta deleted file mode 100644 index d6786ba5e..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar.meta +++ /dev/null @@ -1,379 +0,0 @@ -fileFormatVersion: 2 -guid: 1c858fec5b74c7c46b1712494192b6b5 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 16, y: 16} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 16, y: 16} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.005 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: 3068890721646206586, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: -3552914696322007609, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: -1242281561028671816, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: -1652887728991447519, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar.meta deleted file mode 100644 index c839a27b8..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar.meta +++ /dev/null @@ -1,381 +0,0 @@ -fileFormatVersion: 2 -guid: a1d39ea984432bf44b4a0686afe2bf1a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 2, y: 2} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 1 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 1 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: 3068890721646206586, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: -3552914696322007609, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: -1242281561028671816, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: -1652887728991447519, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar.meta deleted file mode 100644 index ded098ca6..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar.meta +++ /dev/null @@ -1,381 +0,0 @@ -fileFormatVersion: 2 -guid: 504c7bfe0d50ff64a88b8eac2ceb46f8 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.005 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: 3068890721646206586, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: -3552914696322007609, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: -1242281561028671816, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: -1652887728991447519, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar.meta deleted file mode 100644 index 98f20f5ea..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar.meta +++ /dev/null @@ -1,382 +0,0 @@ -fileFormatVersion: 2 -guid: b2bec4b400153d745b2915f1c43e5c96 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n - \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 1 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 1 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: 3068890721646206586, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: -3552914696322007609, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: -1242281561028671816, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: -1652887728991447519, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_copper.sbsar b/Assets/Materials/Substance/Metal/metal_copper.sbsar deleted file mode 100644 index b9eaa9f10..000000000 --- a/Assets/Materials/Substance/Metal/metal_copper.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7e0b38479a336f09f0f273488c666a1eb025ddd9a65366da00c80179ca0a64ee -size 7413 diff --git a/Assets/Materials/Substance/Metal/metal_copper.sbsar.meta b/Assets/Materials/Substance/Metal/metal_copper.sbsar.meta deleted file mode 100644 index d1afb9abd..000000000 --- a/Assets/Materials/Substance/Metal/metal_copper.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 8249e9ffcbd97c84d8ce73343e156c82 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_copper/metal_copper - - first: - 4: 400000 - second: metal_copper/metal_copper/Transform - - first: - 21: 2100000 - second: mat.Copper - - first: - 23: 2300000 - second: metal_copper/metal_copper/MeshRenderer - - first: - 28: 2800000 - second: Copper_baseColor - - first: - 28: 2800002 - second: Copper_normal - - first: - 28: 2800004 - second: Copper_metallic - - first: - 28: 2800006 - second: Copper_ambientOcclusion - - first: - 28: 2800008 - second: Copper_height - - first: - 33: 3300000 - second: metal_copper/metal_copper/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_copper/metal_copper/SphereCollider - - first: - 1001: 100100000 - second: metal_copper - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Copper - prototypeName: Copper - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3792452219542522299, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -595311359069952391, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -1397886531756242709, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 2236529815293478155, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1739956823984805281, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Copper_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 9219180724257492359, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - generatedTextures: - - {fileID: -595311359069952391, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: -3792452219542522299, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: -1397886531756242709, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: 2236529815293478155, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: -1739956823984805281, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar b/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar deleted file mode 100644 index 24237719c..000000000 --- a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5b798bdf0e774a7d826b7080b18c91ac8000cf6ac617dc395d8cf105aba8d7da -size 12826 diff --git a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar.meta deleted file mode 100644 index 3de9c9e1e..000000000 --- a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 9d0963470d3545a4e932ed4ea95b9d62 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_corrugated_002/metal_corrugated_002 - - first: - 4: 400000 - second: metal_corrugated_002/metal_corrugated_002/Transform - - first: - 21: 2100000 - second: mat.Metal Corrugated 002 - - first: - 23: 2300000 - second: metal_corrugated_002/metal_corrugated_002/MeshRenderer - - first: - 28: 2800000 - second: Metal Corrugated 002_baseColor - - first: - 28: 2800002 - second: Metal Corrugated 002_normal - - first: - 28: 2800004 - second: Metal Corrugated 002_metallic - - first: - 28: 2800006 - second: Metal Corrugated 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal Corrugated 002_height - - first: - 33: 3300000 - second: metal_corrugated_002/metal_corrugated_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_corrugated_002/metal_corrugated_002/SphereCollider - - first: - 1001: 100100000 - second: metal_corrugated_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Corrugated 002 - prototypeName: Metal Corrugated 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3654691528969531916, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 4818317370781631303, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 5859956115695178477, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -8111981235355854162, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -5667621616349238808, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Corrugated 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1355354389579744761, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - generatedTextures: - - {fileID: 4818317370781631303, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: -3654691528969531916, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: 5859956115695178477, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: -8111981235355854162, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: -5667621616349238808, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar b/Assets/Materials/Substance/Metal/metal_floor_002.sbsar deleted file mode 100644 index af4adc50c..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5815e5257550f8315dd80831c4cab398a3ae7b234b25e716ecca18c9facbd9be -size 11140 diff --git a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_floor_002.sbsar.meta deleted file mode 100644 index c100570af..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: ddc6970cc883b9845bdadc91983130c2 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_floor_002/metal_floor_002 - - first: - 4: 400000 - second: metal_floor_002/metal_floor_002/Transform - - first: - 21: 2100000 - second: mat.Metal Floor 002 - - first: - 23: 2300000 - second: metal_floor_002/metal_floor_002/MeshRenderer - - first: - 28: 2800000 - second: Metal Floor 002_baseColor - - first: - 28: 2800002 - second: Metal Floor 002_normal - - first: - 28: 2800004 - second: Metal Floor 002_metallic - - first: - 28: 2800006 - second: Metal Floor 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal Floor 002_height - - first: - 33: 3300000 - second: metal_floor_002/metal_floor_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_floor_002/metal_floor_002/SphereCollider - - first: - 1001: 100100000 - second: metal_floor_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Floor 002 - prototypeName: Metal Floor 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 351554284034007472, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -7508666898770042810, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -4403901252400104909, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4356325417559842052, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3247329771169464856, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Floor 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3616699503892477274, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - generatedTextures: - - {fileID: -7508666898770042810, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: 351554284034007472, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: -4403901252400104909, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: -4356325417559842052, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: -3247329771169464856, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar b/Assets/Materials/Substance/Metal/metal_floor_004.sbsar deleted file mode 100644 index f7136c15b..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3d30688944fced2d854f8375ebecd8ad7a6a8021cee07e89710b44ad8272addd -size 8634 diff --git a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar.meta b/Assets/Materials/Substance/Metal/metal_floor_004.sbsar.meta deleted file mode 100644 index 031cbe6c4..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 50192727b92e0af4cbe5c773bec3537f -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_floor_004/metal_floor_004 - - first: - 4: 400000 - second: metal_floor_004/metal_floor_004/Transform - - first: - 21: 2100000 - second: mat.Metal Floor 004 - - first: - 23: 2300000 - second: metal_floor_004/metal_floor_004/MeshRenderer - - first: - 28: 2800000 - second: Metal Floor 004_baseColor - - first: - 28: 2800002 - second: Metal Floor 004_normal - - first: - 28: 2800004 - second: Metal Floor 004_metallic - - first: - 28: 2800006 - second: Metal Floor 004_ambientOcclusion - - first: - 28: 2800008 - second: Metal Floor 004_height - - first: - 33: 3300000 - second: metal_floor_004/metal_floor_004/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_floor_004/metal_floor_004/SphereCollider - - first: - 1001: 100100000 - second: metal_floor_004 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Floor 004 - prototypeName: Metal Floor 004 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 5886398526092406922, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 1550179426837470591, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 4385304290797446058, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -3130265262045919237, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 4866469902769357514, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Floor 004_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1891697860355797410, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - generatedTextures: - - {fileID: 1550179426837470591, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: 5886398526092406922, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: 4385304290797446058, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: -3130265262045919237, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: 4866469902769357514, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar b/Assets/Materials/Substance/Metal/metal_floor_006.sbsar deleted file mode 100644 index 81ce60800..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9604a8c7814d09f90d8bc64061cdc39c733d9f96de43143717f9a951b1f08a0e -size 10884 diff --git a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar.meta b/Assets/Materials/Substance/Metal/metal_floor_006.sbsar.meta deleted file mode 100644 index 91f291c9d..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 06833951ebae4cc45ad88d58cb5571de -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_floor_006/metal_floor_006 - - first: - 4: 400000 - second: metal_floor_006/metal_floor_006/Transform - - first: - 21: 2100000 - second: mat.Metal Floor 006 - - first: - 23: 2300000 - second: metal_floor_006/metal_floor_006/MeshRenderer - - first: - 28: 2800000 - second: Metal Floor 006_baseColor - - first: - 28: 2800002 - second: Metal Floor 006_normal - - first: - 28: 2800004 - second: Metal Floor 006_metallic - - first: - 28: 2800006 - second: Metal Floor 006_ambientOcclusion - - first: - 28: 2800008 - second: Metal Floor 006_height - - first: - 33: 3300000 - second: metal_floor_006/metal_floor_006/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_floor_006/metal_floor_006/SphereCollider - - first: - 1001: 100100000 - second: metal_floor_006 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Floor 006 - prototypeName: Metal Floor 006 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2252411089510067877, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -446378320346000722, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 877764506763962143, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4232129871321120126, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 3318615130639472310, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Floor 006_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -6975397259061671394, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - generatedTextures: - - {fileID: -446378320346000722, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: -2252411089510067877, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: 877764506763962143, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: -4232129871321120126, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: 3318615130639472310, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_gold.sbsar b/Assets/Materials/Substance/Metal/metal_gold.sbsar deleted file mode 100644 index 5aa377680..000000000 --- a/Assets/Materials/Substance/Metal/metal_gold.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:29ef1a459ab7d090b32ee563d729038527c4d031595abef2a49398543d11343c -size 7428 diff --git a/Assets/Materials/Substance/Metal/metal_gold.sbsar.meta b/Assets/Materials/Substance/Metal/metal_gold.sbsar.meta deleted file mode 100644 index c4e7f4644..000000000 --- a/Assets/Materials/Substance/Metal/metal_gold.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: a74970be876d3554ea0f279f39314c9c -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_gold/metal_gold - - first: - 4: 400000 - second: metal_gold/metal_gold/Transform - - first: - 21: 2100000 - second: mat.Gold - - first: - 23: 2300000 - second: metal_gold/metal_gold/MeshRenderer - - first: - 28: 2800000 - second: Gold_baseColor - - first: - 28: 2800002 - second: Gold_normal - - first: - 28: 2800004 - second: Gold_metallic - - first: - 28: 2800006 - second: Gold_ambientOcclusion - - first: - 28: 2800008 - second: Gold_height - - first: - 33: 3300000 - second: metal_gold/metal_gold/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_gold/metal_gold/SphereCollider - - first: - 1001: 100100000 - second: metal_gold - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Gold - prototypeName: Gold - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -6248678595456566848, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 2039085267362074300, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8783136193678078058, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7384525862955468029, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -8934633548313413119, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Gold_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -905690159841262435, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - generatedTextures: - - {fileID: 2039085267362074300, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: -6248678595456566848, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: -8783136193678078058, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: 7384525862955468029, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: -8934633548313413119, guid: a74970be876d3554ea0f279f39314c9c, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_nickel.sbsar b/Assets/Materials/Substance/Metal/metal_nickel.sbsar deleted file mode 100644 index e7cf69c6b..000000000 --- a/Assets/Materials/Substance/Metal/metal_nickel.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a0395691305bc49406088b12b65ea186d65d5101bc230a2e91b4ddbf2c7b65ea -size 8935 diff --git a/Assets/Materials/Substance/Metal/metal_nickel.sbsar.meta b/Assets/Materials/Substance/Metal/metal_nickel.sbsar.meta deleted file mode 100644 index 65531754c..000000000 --- a/Assets/Materials/Substance/Metal/metal_nickel.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: c5f2177e1f35daa499f4d7e0b7f3370a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_nickel/metal_nickel - - first: - 4: 400000 - second: metal_nickel/metal_nickel/Transform - - first: - 21: 2100000 - second: mat.Nickel - - first: - 23: 2300000 - second: metal_nickel/metal_nickel/MeshRenderer - - first: - 28: 2800000 - second: Nickel_baseColor - - first: - 28: 2800002 - second: Nickel_normal - - first: - 28: 2800004 - second: Nickel_metallic - - first: - 28: 2800006 - second: Nickel_ambientOcclusion - - first: - 28: 2800008 - second: Nickel_height - - first: - 33: 3300000 - second: metal_nickel/metal_nickel/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_nickel/metal_nickel/SphereCollider - - first: - 1001: 100100000 - second: metal_nickel - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Nickel - prototypeName: Nickel - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1040180909335529060, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -3896990606402278735, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8156577797594723071, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -7935365347593253955, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -4922792887777872198, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Nickel_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -443055228576417237, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - generatedTextures: - - {fileID: -3896990606402278735, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: 1040180909335529060, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: -8156577797594723071, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: -7935365347593253955, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: -4922792887777872198, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar b/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar deleted file mode 100644 index d764cd35f..000000000 --- a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bc8dcd55f0619c028037c7225720acb4eea87b28cc7c120125fa2b38d02f775a -size 13628 diff --git a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar.meta b/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar.meta deleted file mode 100644 index 467fa07bd..000000000 --- a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar.meta +++ /dev/null @@ -1,376 +0,0 @@ -fileFormatVersion: 2 -guid: b7e648471e9dfc44490bd41973711541 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_painted_steel/metal_painted_steel - - first: - 4: 400000 - second: metal_painted_steel/metal_painted_steel/Transform - - first: - 21: 2100000 - second: mat.Painted steel - - first: - 23: 2300000 - second: metal_painted_steel/metal_painted_steel/MeshRenderer - - first: - 28: 2800000 - second: Painted steel_baseColor - - first: - 28: 2800002 - second: Painted steel_normal - - first: - 28: 2800004 - second: Painted steel_metallic - - first: - 28: 2800006 - second: Painted steel_ambientOcclusion - - first: - 28: 2800008 - second: Painted steel_height - - first: - 33: 3300000 - second: metal_painted_steel/metal_painted_steel/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_painted_steel/metal_painted_steel/SphereCollider - - first: - 1001: 100100000 - second: metal_painted_steel - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Painted steel - prototypeName: Painted steel - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 4387638379454744182, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 5280895355680202213, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 1053975553097811288, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -5932748352949090903, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Painted steel_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -4658142721435264040, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - generatedTextures: - - {fileID: 4387638379454744182, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: 5280895355680202213, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: 1053975553097811288, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: -5932748352949090903, guid: b7e648471e9dfc44490bd41973711541, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar b/Assets/Materials/Substance/Metal/metal_panels_001.sbsar deleted file mode 100644 index 2ee3b87ea..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e868f72fde8e3c55a2d8c097ebb39c05157670897d14eeb86932021feec16158 -size 11295 diff --git a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar.meta b/Assets/Materials/Substance/Metal/metal_panels_001.sbsar.meta deleted file mode 100644 index a423b3b51..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 7363fcc4a3c41a349b29de7ec34555be -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_panels_001/metal_panels_001 - - first: - 4: 400000 - second: metal_panels_001/metal_panels_001/Transform - - first: - 21: 2100000 - second: mat.Metal Panels 001 - - first: - 23: 2300000 - second: metal_panels_001/metal_panels_001/MeshRenderer - - first: - 28: 2800000 - second: Metal Panels 001_baseColor - - first: - 28: 2800002 - second: Metal Panels 001_normal - - first: - 28: 2800004 - second: Metal Panels 001_metallic - - first: - 28: 2800006 - second: Metal Panels 001_ambientOcclusion - - first: - 28: 2800008 - second: Metal Panels 001_height - - first: - 33: 3300000 - second: metal_panels_001/metal_panels_001/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_panels_001/metal_panels_001/SphereCollider - - first: - 1001: 100100000 - second: metal_panels_001 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Panels 001 - prototypeName: Metal Panels 001 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 2945532018097518028, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 6344665451385196243, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -103584793617860315, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -2941359408041138506, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 1361220934952870948, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Panels 001_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 1523472303362493764, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - generatedTextures: - - {fileID: 6344665451385196243, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: 2945532018097518028, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: -103584793617860315, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: -2941359408041138506, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: 1361220934952870948, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar b/Assets/Materials/Substance/Metal/metal_panels_002.sbsar deleted file mode 100644 index 2cf3cd0b5..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b16e09a1b06ae6b857d9f9478af0838a31ba554a2455b9e65e9db43a125ce633 -size 7592 diff --git a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_panels_002.sbsar.meta deleted file mode 100644 index fe8ecd2b6..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 2e9a9dbacde66a446852af882f33e9e2 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_panels_002/metal_panels_002 - - first: - 4: 400000 - second: metal_panels_002/metal_panels_002/Transform - - first: - 21: 2100000 - second: mat.Metal Panels 002 - - first: - 23: 2300000 - second: metal_panels_002/metal_panels_002/MeshRenderer - - first: - 28: 2800000 - second: Metal Panels 002_baseColor - - first: - 28: 2800002 - second: Metal Panels 002_normal - - first: - 28: 2800004 - second: Metal Panels 002_metallic - - first: - 28: 2800006 - second: Metal Panels 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal Panels 002_height - - first: - 33: 3300000 - second: metal_panels_002/metal_panels_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_panels_002/metal_panels_002/SphereCollider - - first: - 1001: 100100000 - second: metal_panels_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Panels 002 - prototypeName: Metal Panels 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -7157783387845257801, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 6030008930922367719, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -5177487458041023939, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -6221273311826804186, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -2755774738339798629, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Panels 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3282252981698000714, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - generatedTextures: - - {fileID: 6030008930922367719, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -7157783387845257801, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -5177487458041023939, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -6221273311826804186, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -2755774738339798629, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar b/Assets/Materials/Substance/Metal/metal_plate_001.sbsar deleted file mode 100644 index 3d06effb9..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7c9aea022bbc0138be51bb7b89314a569ad359390a0b8d1b6b2c717d317acd8b -size 10171 diff --git a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar.meta b/Assets/Materials/Substance/Metal/metal_plate_001.sbsar.meta deleted file mode 100644 index 9a0327632..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 180b85899b4b1f848b348230339ce984 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_plate_001/metal_plate_001 - - first: - 4: 400000 - second: metal_plate_001/metal_plate_001/Transform - - first: - 21: 2100000 - second: mat.Metal plate 001 - - first: - 23: 2300000 - second: metal_plate_001/metal_plate_001/MeshRenderer - - first: - 28: 2800000 - second: Metal plate 001_baseColor - - first: - 28: 2800002 - second: Metal plate 001_normal - - first: - 28: 2800004 - second: Metal plate 001_metallic - - first: - 28: 2800006 - second: Metal plate 001_ambientOcclusion - - first: - 28: 2800008 - second: Metal plate 001_height - - first: - 33: 3300000 - second: metal_plate_001/metal_plate_001/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_plate_001/metal_plate_001/SphereCollider - - first: - 1001: 100100000 - second: metal_plate_001 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal plate 001 - prototypeName: Metal plate 001 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 6805374924820727666, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 443512894100413061, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3656363544911682969, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 6012193567810889268, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 1247009903862830065, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal plate 001_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1468868417959000437, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - generatedTextures: - - {fileID: 443512894100413061, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: 6805374924820727666, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: -3656363544911682969, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: 6012193567810889268, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: 1247009903862830065, guid: 180b85899b4b1f848b348230339ce984, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar b/Assets/Materials/Substance/Metal/metal_plate_004.sbsar deleted file mode 100644 index dc0474e13..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:65295627150c30fc70fe138aee16c2266bffdd0a5b1fbcbe7fe040a3d0309d39 -size 14216 diff --git a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar.meta b/Assets/Materials/Substance/Metal/metal_plate_004.sbsar.meta deleted file mode 100644 index fd4373932..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 0b5dfc86c0681a3459a57d197804191b -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_plate_004/metal_plate_004 - - first: - 4: 400000 - second: metal_plate_004/metal_plate_004/Transform - - first: - 21: 2100000 - second: mat.Metal plate 004 - - first: - 23: 2300000 - second: metal_plate_004/metal_plate_004/MeshRenderer - - first: - 28: 2800000 - second: Metal plate 004_baseColor - - first: - 28: 2800002 - second: Metal plate 004_normal - - first: - 28: 2800004 - second: Metal plate 004_metallic - - first: - 28: 2800006 - second: Metal plate 004_ambientOcclusion - - first: - 28: 2800008 - second: Metal plate 004_height - - first: - 33: 3300000 - second: metal_plate_004/metal_plate_004/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_plate_004/metal_plate_004/SphereCollider - - first: - 1001: 100100000 - second: metal_plate_004 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal plate 004 - prototypeName: Metal plate 004 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -7484568915117973449, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 1309396409266656355, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -5781884682247363129, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 5620992320681838871, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 6570316561944570698, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal plate 004_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -5894754650268316995, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - generatedTextures: - - {fileID: 1309396409266656355, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: -7484568915117973449, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: -5781884682247363129, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: 5620992320681838871, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: 6570316561944570698, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar b/Assets/Materials/Substance/Metal/metal_plate_011.sbsar deleted file mode 100644 index c1e0a3922..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:829bc422cbe5b984103972cd7cf36d207fe0a6b561a2619301dec3e684009784 -size 9674 diff --git a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar.meta b/Assets/Materials/Substance/Metal/metal_plate_011.sbsar.meta deleted file mode 100644 index 55c1cd50c..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: ca8f080ab60226e4097841eee2bfa8db -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_plate_011/metal_plate_011 - - first: - 4: 400000 - second: metal_plate_011/metal_plate_011/Transform - - first: - 21: 2100000 - second: mat.Metal plate 011 - - first: - 23: 2300000 - second: metal_plate_011/metal_plate_011/MeshRenderer - - first: - 28: 2800000 - second: Metal plate 011_baseColor - - first: - 28: 2800002 - second: Metal plate 011_normal - - first: - 28: 2800004 - second: Metal plate 011_metallic - - first: - 28: 2800006 - second: Metal plate 011_ambientOcclusion - - first: - 28: 2800008 - second: Metal plate 011_height - - first: - 33: 3300000 - second: metal_plate_011/metal_plate_011/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_plate_011/metal_plate_011/SphereCollider - - first: - 1001: 100100000 - second: metal_plate_011 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal plate 011 - prototypeName: Metal plate 011 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1206901763152500494, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -562402163750398719, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8211546087015286653, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7355910353852850503, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -2794334530799708578, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal plate 011_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 5028268363422298589, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - generatedTextures: - - {fileID: -562402163750398719, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: 1206901763152500494, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: -8211546087015286653, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: 7355910353852850503, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: -2794334530799708578, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_platinum.sbsar b/Assets/Materials/Substance/Metal/metal_platinum.sbsar deleted file mode 100644 index ffaec19de..000000000 --- a/Assets/Materials/Substance/Metal/metal_platinum.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b880030baaf5ccc272c780265fc4b1570a55a63a8b804223ccbdc54a576b9be7 -size 5196 diff --git a/Assets/Materials/Substance/Metal/metal_platinum.sbsar.meta b/Assets/Materials/Substance/Metal/metal_platinum.sbsar.meta deleted file mode 100644 index f39efaf0d..000000000 --- a/Assets/Materials/Substance/Metal/metal_platinum.sbsar.meta +++ /dev/null @@ -1,372 +0,0 @@ -fileFormatVersion: 2 -guid: 9458f33b8e7e51a42aa19686b9779d82 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_platinum/metal_platinum - - first: - 4: 400000 - second: metal_platinum/metal_platinum/Transform - - first: - 21: 2100000 - second: mat.Platinum - - first: - 23: 2300000 - second: metal_platinum/metal_platinum/MeshRenderer - - first: - 28: 2800000 - second: Platinum_baseColor - - first: - 28: 2800002 - second: Platinum_normal - - first: - 28: 2800004 - second: Platinum_metallic - - first: - 28: 2800006 - second: Platinum_ambientOcclusion - - first: - 28: 2800008 - second: Platinum_height - - first: - 33: 3300000 - second: metal_platinum/metal_platinum/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_platinum/metal_platinum/SphereCollider - - first: - 1001: 100100000 - second: metal_platinum - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Platinum - prototypeName: Platinum - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3498638986299907941, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -8172963137857357993, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8040379993892829019, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 225164955126363719, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -130007606447889175, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Platinum_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 8636029498071112704, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - generatedTextures: - - {fileID: -8172963137857357993, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: 3498638986299907941, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: -8040379993892829019, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: 225164955126363719, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: -130007606447889175, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar b/Assets/Materials/Substance/Metal/metal_roll_up.sbsar deleted file mode 100644 index db99f183e..000000000 --- a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1a2036e21cdd2d392fdcb755d2faf982335fc4deaa8c7b913110db234fa04f3a -size 11017 diff --git a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar.meta b/Assets/Materials/Substance/Metal/metal_roll_up.sbsar.meta deleted file mode 100644 index 3d93351e8..000000000 --- a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 4e39297ae4fe9ee4b803c04eabb69da7 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_roll_up/metal_roll_up - - first: - 4: 400000 - second: metal_roll_up/metal_roll_up/Transform - - first: - 21: 2100000 - second: mat.Metal roll up - - first: - 23: 2300000 - second: metal_roll_up/metal_roll_up/MeshRenderer - - first: - 28: 2800000 - second: Metal roll up_baseColor - - first: - 28: 2800002 - second: Metal roll up_normal - - first: - 28: 2800004 - second: Metal roll up_metallic - - first: - 28: 2800006 - second: Metal roll up_ambientOcclusion - - first: - 28: 2800008 - second: Metal roll up_height - - first: - 33: 3300000 - second: metal_roll_up/metal_roll_up/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_roll_up/metal_roll_up/SphereCollider - - first: - 1001: 100100000 - second: metal_roll_up - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal roll up - prototypeName: Metal roll up - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1258325809611119299, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -5250987364813910665, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -1897870436205287166, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7199963334284863655, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 1153539711168243343, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal roll up_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 7440086527666654772, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - generatedTextures: - - {fileID: -5250987364813910665, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: 1258325809611119299, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: -1897870436205287166, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: 7199963334284863655, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: 1153539711168243343, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_silver.sbsar b/Assets/Materials/Substance/Metal/metal_silver.sbsar deleted file mode 100644 index 08b0ac146..000000000 --- a/Assets/Materials/Substance/Metal/metal_silver.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4b18ce39a69d5e25641d53fcbe04f281c92ca7e01936e6a9b279476be8ff3255 -size 6898 diff --git a/Assets/Materials/Substance/Metal/metal_silver.sbsar.meta b/Assets/Materials/Substance/Metal/metal_silver.sbsar.meta deleted file mode 100644 index 326559316..000000000 --- a/Assets/Materials/Substance/Metal/metal_silver.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 0be5fb1df83ac8e499a3f6a060041e49 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_silver/metal_silver - - first: - 4: 400000 - second: metal_silver/metal_silver/Transform - - first: - 21: 2100000 - second: mat.Silver - - first: - 23: 2300000 - second: metal_silver/metal_silver/MeshRenderer - - first: - 28: 2800000 - second: Silver_baseColor - - first: - 28: 2800002 - second: Silver_normal - - first: - 28: 2800004 - second: Silver_metallic - - first: - 28: 2800006 - second: Silver_ambientOcclusion - - first: - 28: 2800008 - second: Silver_height - - first: - 33: 3300000 - second: metal_silver/metal_silver/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_silver/metal_silver/SphereCollider - - first: - 1001: 100100000 - second: metal_silver - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Silver - prototypeName: Silver - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 8947980237086559854, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -1383037052668628532, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 6429125567479694453, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -9097439929179392311, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 425190381137097012, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Silver_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 7490952440742008943, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - generatedTextures: - - {fileID: -1383037052668628532, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: 8947980237086559854, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: 6429125567479694453, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: -9097439929179392311, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: 425190381137097012, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel.sbsar b/Assets/Materials/Substance/Metal/metal_steel.sbsar deleted file mode 100644 index 31ec34fd3..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d559edac51ad4c529c197d7c9a813fe8c2fa1bcb0963cd0f8bad8ab1403b3821 -size 10697 diff --git a/Assets/Materials/Substance/Metal/metal_steel.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel.sbsar.meta deleted file mode 100644 index 172d4668b..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel.sbsar.meta +++ /dev/null @@ -1,375 +0,0 @@ -fileFormatVersion: 2 -guid: cbc61995a46604441ab9de4f1c68e290 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel/metal_steel - - first: - 4: 400000 - second: metal_steel/metal_steel/Transform - - first: - 21: 2100000 - second: mat.Steel - - first: - 23: 2300000 - second: metal_steel/metal_steel/MeshRenderer - - first: - 28: 2800000 - second: Steel_baseColor - - first: - 28: 2800002 - second: Steel_normal - - first: - 28: 2800004 - second: Steel_metallic - - first: - 28: 2800006 - second: Steel_ambientOcclusion - - first: - 28: 2800008 - second: Steel_height - - first: - 33: 3300000 - second: metal_steel/metal_steel/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel/metal_steel/SphereCollider - - first: - 1001: 100100000 - second: metal_steel - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel - prototypeName: Steel - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -3155047780354543793, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - generatedTextures: - - {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar b/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar deleted file mode 100644 index 45c0b10b3..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bf6b40453b42e050b2ce05478f1c1964d9489cdf02413f12b40f4ce1e49b4432 -size 12832 diff --git a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar.meta deleted file mode 100644 index d08c0d290..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar.meta +++ /dev/null @@ -1,370 +0,0 @@ -fileFormatVersion: 2 -guid: ea7457b9a4f0bcb43becaa33de541cbd -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel_brushed/metal_steel_brushed - - first: - 4: 400000 - second: metal_steel_brushed/metal_steel_brushed/Transform - - first: - 21: 2100000 - second: mat.Steel brushed - - first: - 23: 2300000 - second: metal_steel_brushed/metal_steel_brushed/MeshRenderer - - first: - 28: 2800000 - second: Steel brushed_baseColor - - first: - 28: 2800002 - second: Steel brushed_normal - - first: - 28: 2800004 - second: Steel brushed_metallic - - first: - 28: 2800006 - second: Steel brushed_ambientOcclusion - - first: - 28: 2800008 - second: Steel brushed_height - - first: - 33: 3300000 - second: metal_steel_brushed/metal_steel_brushed/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel_brushed/metal_steel_brushed/SphereCollider - - first: - 1001: 100100000 - second: metal_steel_brushed - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel brushed - prototypeName: Steel brushed - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -4471413742775304797, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -4638397344074346932, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 5049811794194361025, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 1753668427856518731, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3498708498072814504, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel brushed_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 7852708265981260911, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - generatedTextures: - - {fileID: -4638397344074346932, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: -4471413742775304797, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: 5049811794194361025, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: 1753668427856518731, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: -3498708498072814504, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar b/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar deleted file mode 100644 index 6580295bb..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a9ae449451a55abd8466e8af67685a45d86fd39ea2070294dde7f2a07776bea5 -size 17275 diff --git a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar.meta deleted file mode 100644 index 1dd652796..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 092bdd8d243488141aeab5bb0d72429a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel_bumped/metal_steel_bumped - - first: - 4: 400000 - second: metal_steel_bumped/metal_steel_bumped/Transform - - first: - 21: 2100000 - second: mat.Steel bumped - - first: - 23: 2300000 - second: metal_steel_bumped/metal_steel_bumped/MeshRenderer - - first: - 28: 2800000 - second: Steel bumped_baseColor - - first: - 28: 2800002 - second: Steel bumped_normal - - first: - 28: 2800004 - second: Steel bumped_metallic - - first: - 28: 2800006 - second: Steel bumped_ambientOcclusion - - first: - 28: 2800008 - second: Steel bumped_height - - first: - 33: 3300000 - second: metal_steel_bumped/metal_steel_bumped/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel_bumped/metal_steel_bumped/SphereCollider - - first: - 1001: 100100000 - second: metal_steel_bumped - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel bumped - prototypeName: Steel bumped - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3586080781697202320, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 86365302875955127, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 9208498935135840223, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7740971908710523460, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 6493472383464308858, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel bumped_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -864409875390858066, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - generatedTextures: - - {fileID: 86365302875955127, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 3586080781697202320, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 9208498935135840223, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 7740971908710523460, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 6493472383464308858, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar b/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar deleted file mode 100644 index 92bee293c..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:54993a1aae47acf7e1aba24812f215e1787969016dd1f420899ab363342a7b6d -size 9206 diff --git a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar.meta deleted file mode 100644 index a7cabf9ff..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: e7758cad28ae98f478940e55222419a6 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel_parkerized/metal_steel_parkerized - - first: - 4: 400000 - second: metal_steel_parkerized/metal_steel_parkerized/Transform - - first: - 21: 2100000 - second: mat.Steel parkerized - - first: - 23: 2300000 - second: metal_steel_parkerized/metal_steel_parkerized/MeshRenderer - - first: - 28: 2800000 - second: Steel parkerized_baseColor - - first: - 28: 2800002 - second: Steel parkerized_normal - - first: - 28: 2800004 - second: Steel parkerized_metallic - - first: - 28: 2800006 - second: Steel parkerized_ambientOcclusion - - first: - 28: 2800008 - second: Steel parkerized_height - - first: - 33: 3300000 - second: metal_steel_parkerized/metal_steel_parkerized/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel_parkerized/metal_steel_parkerized/SphereCollider - - first: - 1001: 100100000 - second: metal_steel_parkerized - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel parkerized - prototypeName: Steel parkerized - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 885599758852769373, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -4474525002722929857, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -2334804936223627746, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -8380876848358870972, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 172713863077875830, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel parkerized_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -6026401407715332296, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - generatedTextures: - - {fileID: -4474525002722929857, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: 885599758852769373, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: -2334804936223627746, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: -8380876848358870972, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: 172713863077875830, guid: e7758cad28ae98f478940e55222419a6, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_titanium.sbsar b/Assets/Materials/Substance/Metal/metal_titanium.sbsar deleted file mode 100644 index ede9cde4d..000000000 --- a/Assets/Materials/Substance/Metal/metal_titanium.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e3aabfbcb813fef9ef20793d54c93bf5c37255573bb8ad043620f60041acd6d1 -size 5206 diff --git a/Assets/Materials/Substance/Metal/metal_titanium.sbsar.meta b/Assets/Materials/Substance/Metal/metal_titanium.sbsar.meta deleted file mode 100644 index e4ece6915..000000000 --- a/Assets/Materials/Substance/Metal/metal_titanium.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 58e16b7dbc1c31f4585e11544cdce127 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_titanium/metal_titanium - - first: - 4: 400000 - second: metal_titanium/metal_titanium/Transform - - first: - 21: 2100000 - second: mat.Titanium - - first: - 23: 2300000 - second: metal_titanium/metal_titanium/MeshRenderer - - first: - 28: 2800000 - second: Titanium_baseColor - - first: - 28: 2800002 - second: Titanium_normal - - first: - 28: 2800004 - second: Titanium_metallic - - first: - 28: 2800006 - second: Titanium_ambientOcclusion - - first: - 28: 2800008 - second: Titanium_height - - first: - 33: 3300000 - second: metal_titanium/metal_titanium/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_titanium/metal_titanium/SphereCollider - - first: - 1001: 100100000 - second: metal_titanium - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Titanium - prototypeName: Titanium - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -5074057273227030627, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 3009319823116150993, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 3613456606582262254, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7558371940554398246, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3774795931012705877, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Titanium_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 9178725544925813344, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - generatedTextures: - - {fileID: 3009319823116150993, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: -5074057273227030627, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: 3613456606582262254, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: 7558371940554398246, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: -3774795931012705877, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_used.sbsar b/Assets/Materials/Substance/Metal/metal_used.sbsar deleted file mode 100644 index 5a8b87d9c..000000000 --- a/Assets/Materials/Substance/Metal/metal_used.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:03b72a9708206dd2c10aba185b507def52bbbcb713666711ed5d67926fbedd68 -size 14332 diff --git a/Assets/Materials/Substance/Metal/metal_used.sbsar.meta b/Assets/Materials/Substance/Metal/metal_used.sbsar.meta deleted file mode 100644 index 37fcc6a20..000000000 --- a/Assets/Materials/Substance/Metal/metal_used.sbsar.meta +++ /dev/null @@ -1,371 +0,0 @@ -fileFormatVersion: 2 -guid: 130f566ffa0b2424fbb47de2194c136a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_used/metal_used - - first: - 4: 400000 - second: metal_used/metal_used/Transform - - first: - 21: 2100000 - second: mat.Metal used - - first: - 23: 2300000 - second: metal_used/metal_used/MeshRenderer - - first: - 28: 2800000 - second: Metal used_baseColor - - first: - 28: 2800002 - second: Metal used_normal - - first: - 28: 2800004 - second: Metal used_metallic - - first: - 28: 2800006 - second: Metal used_ambientOcclusion - - first: - 28: 2800008 - second: Metal used_height - - first: - 33: 3300000 - second: metal_used/metal_used/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_used/metal_used/SphereCollider - - first: - 1001: 100100000 - second: metal_used - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal used - prototypeName: Metal used - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 8398852885706109728, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 8357651109123355072, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -435054815742279573, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 6248133906606842143, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 2780512161145013460, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal used_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -890370705972978167, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - generatedTextures: - - {fileID: 8357651109123355072, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: 8398852885706109728, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: -435054815742279573, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: 6248133906606842143, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: 2780512161145013460, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_weapon.sbsar b/Assets/Materials/Substance/Metal/metal_weapon.sbsar deleted file mode 100644 index d96236940..000000000 --- a/Assets/Materials/Substance/Metal/metal_weapon.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8e9033843201f75f1b86df82b69fd89ee6b9aa317df18f9105d0f8904d56be8f -size 10547 diff --git a/Assets/Materials/Substance/Metal/metal_weapon.sbsar.meta b/Assets/Materials/Substance/Metal/metal_weapon.sbsar.meta deleted file mode 100644 index 05d1fcf4b..000000000 --- a/Assets/Materials/Substance/Metal/metal_weapon.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: 07f679eadba9fb14abac26b1e165f7d5 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_weapon/metal_weapon - - first: - 4: 400000 - second: metal_weapon/metal_weapon/Transform - - first: - 21: 2100000 - second: mat.Metal Weapon - - first: - 23: 2300000 - second: metal_weapon/metal_weapon/MeshRenderer - - first: - 28: 2800000 - second: Metal Weapon_baseColor - - first: - 28: 2800002 - second: Metal Weapon_normal - - first: - 28: 2800004 - second: Metal Weapon_metallic - - first: - 28: 2800006 - second: Metal Weapon_ambientOcclusion - - first: - 28: 2800008 - second: Metal Weapon_height - - first: - 33: 3300000 - second: metal_weapon/metal_weapon/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_weapon/metal_weapon/SphereCollider - - first: - 1001: 100100000 - second: metal_weapon - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Weapon - prototypeName: Metal Weapon - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -6635831357954291190, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -6402586014670071135, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 854616604008364032, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4606406952830974004, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -5822151887330517421, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Weapon_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -6659110875122461561, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - generatedTextures: - - {fileID: -6402586014670071135, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: -6635831357954291190, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: 854616604008364032, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: 4606406952830974004, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: -5822151887330517421, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_woven.sbsar b/Assets/Materials/Substance/Metal/metal_woven.sbsar deleted file mode 100644 index 576f8c4a5..000000000 --- a/Assets/Materials/Substance/Metal/metal_woven.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6c50e25516df1c3d2cb879d4e3e78491462296d92f05ac5774b6aa1290a777ee -size 9445 diff --git a/Assets/Materials/Substance/Metal/metal_woven.sbsar.meta b/Assets/Materials/Substance/Metal/metal_woven.sbsar.meta deleted file mode 100644 index 27d8bfafe..000000000 --- a/Assets/Materials/Substance/Metal/metal_woven.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: deb7e15e5f95294498d18869d9f11302 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_woven/metal_woven - - first: - 4: 400000 - second: metal_woven/metal_woven/Transform - - first: - 21: 2100000 - second: mat.Metal woven - - first: - 23: 2300000 - second: metal_woven/metal_woven/MeshRenderer - - first: - 28: 2800000 - second: Metal woven_baseColor - - first: - 28: 2800002 - second: Metal woven_normal - - first: - 28: 2800004 - second: Metal woven_metallic - - first: - 28: 2800006 - second: Metal woven_ambientOcclusion - - first: - 28: 2800008 - second: Metal woven_height - - first: - 33: 3300000 - second: metal_woven/metal_woven/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_woven/metal_woven/SphereCollider - - first: - 1001: 100100000 - second: metal_woven - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal woven - prototypeName: Metal woven - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 549858149917880910, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -5021036940690714266, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -4741193760961545063, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4441773978818050154, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -8782013540898460330, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal woven_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1778075352807424672, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - generatedTextures: - - {fileID: -5021036940690714266, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: 549858149917880910, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: -4741193760961545063, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: 4441773978818050154, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: -8782013540898460330, guid: deb7e15e5f95294498d18869d9f11302, type: 3} diff --git a/Assets/Materials/Substance/Metal/snatched_metal.sbsar b/Assets/Materials/Substance/Metal/snatched_metal.sbsar deleted file mode 100644 index 35980ce5c..000000000 --- a/Assets/Materials/Substance/Metal/snatched_metal.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:556e67022b660530d0afc8296e37706b09e9ef08db46b5421edbd80f0c8993f2 -size 28573 diff --git a/Assets/Materials/Substance/Metal/snatched_metal.sbsar.meta b/Assets/Materials/Substance/Metal/snatched_metal.sbsar.meta deleted file mode 100644 index 3da7ab6e7..000000000 --- a/Assets/Materials/Substance/Metal/snatched_metal.sbsar.meta +++ /dev/null @@ -1,311 +0,0 @@ -fileFormatVersion: 2 -guid: 9aa51bbe4dd46874a906608c34a739e4 -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Snatched Metal - prototypeName: Snatched Metal - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 8651868829797956950, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 3043754869544600785, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8730703347107057792, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 8639218750153593357, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 8363912540366899318, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambientocclusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: opacity - identifier: opacity - usageName: opacity - channelStr: opacity - label: Opacity - usage: 2 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: opacity - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: opacity - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: opacity - components: - - sourceName: opacity - from: 0 - to: 3 - textureParameters: - - textureName: Snatched Metal - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - opacity - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -2363654054484809406, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - generatedTextures: - - {fileID: 3043754869544600785, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: 8651868829797956950, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: -8730703347107057792, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: 8363912540366899318, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: 8639218750153593357, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} diff --git a/Assets/Materials/Substance/marble_002.sbsar b/Assets/Materials/Substance/marble_002.sbsar deleted file mode 100644 index 728270967..000000000 --- a/Assets/Materials/Substance/marble_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2859e24557bccbe309d8946052849b828cabd34b8e45b933faee212eeffd462e -size 8113 diff --git a/Assets/Materials/Substance/marble_002.sbsar.meta b/Assets/Materials/Substance/marble_002.sbsar.meta deleted file mode 100644 index 624e0d1a6..000000000 --- a/Assets/Materials/Substance/marble_002.sbsar.meta +++ /dev/null @@ -1,296 +0,0 @@ -fileFormatVersion: 2 -guid: ef9a54b8dacea9f44be70da43472f701 -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Marble 002 - prototypeName: Marble 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 5777664804669422655, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -5564000130503291907, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3258750942226492355, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4985089394248351555, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7116303992264550, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Marble 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 4096 - textureHeight: 4096 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -4681939019719023292, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - generatedTextures: - - {fileID: -5564000130503291907, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: 5777664804669422655, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: -3258750942226492355, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: 4985089394248351555, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: 7116303992264550, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} diff --git a/Assets/Materials/Thrusters.mat b/Assets/Materials/Thrusters.mat deleted file mode 100644 index f9b21ae83..000000000 --- a/Assets/Materials/Thrusters.mat +++ /dev/null @@ -1,87 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Thrusters - m_Shader: {fileID: 4800000, guid: d69ef48273708ef4680762f5cdcfc860, type: 3} - m_ShaderKeywords: - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpPower: 2 - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _Emission: 0 - - _EmissionFresnel: 1 - - _EmissionRoughnessFresnelPower: 0.5 - - _GlossMapScale: 1 - - _Glossiness: 1 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _ReverseRim: 0 - - _Rotation: 0 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 0.7112653, g: 0.4292453, b: 1, a: 1} - m_BuildTextureStacks: [] diff --git a/Assets/Materials/Thrusters.mat.meta b/Assets/Materials/Thrusters.mat.meta deleted file mode 100644 index 5fd79a1be..000000000 --- a/Assets/Materials/Thrusters.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 616adaf59c64a444f8249cc7cf13c527 -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 0 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Models/Discobolus/Discobolus Bronze.mat.meta b/Assets/Models/Discobolus/Discobolus Bronze.mat.meta deleted file mode 100644 index 4ca3a3b46..000000000 --- a/Assets/Models/Discobolus/Discobolus Bronze.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 45f1ac126982c314a8471da3d264210b -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 2100000 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Models/Discobolus/Discobolus Marble.mat b/Assets/Models/Discobolus/Discobolus Marble.mat index 3c862a22c..f4331ed09 100644 --- a/Assets/Models/Discobolus/Discobolus Marble.mat +++ b/Assets/Models/Discobolus/Discobolus Marble.mat @@ -40,13 +40,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -5564000130503291907, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3258750942226492355, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: @@ -63,7 +61,7 @@ Material: - _DetailNormalMapScale: 1 - _DstBlend: 0 - _GlossMapScale: 1 - - _Glossiness: 0.5 + - _Glossiness: 0.45 - _GlossyReflections: 1 - _Metallic: 0 - _Mode: 0 @@ -75,6 +73,6 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.7, g: 0.654348, b: 0.525, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Models/Zenith_Blender.fbx.meta b/Assets/Models/Zenith_Blender.fbx.meta index 2094752dc..6f719ce83 100644 --- a/Assets/Models/Zenith_Blender.fbx.meta +++ b/Assets/Models/Zenith_Blender.fbx.meta @@ -8,8 +8,7 @@ ModelImporter: type: UnityEngine:Material assembly: UnityEngine.CoreModule name: Black - second: {fileID: 3720744386649352057, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + second: {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} - first: type: UnityEngine:Material assembly: UnityEngine.CoreModule @@ -19,8 +18,7 @@ ModelImporter: type: UnityEngine:Material assembly: UnityEngine.CoreModule name: White - second: {fileID: -741235592913766832, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + second: {fileID: 2100000, guid: 39af4e3978df92f40a55e2a114aa242a, type: 2} materials: materialImportMode: 1 materialName: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab b/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab index 7a65a0864..7be70840f 100644 --- a/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab b/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab index f9a477cda..4a8609c7c 100644 --- a/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab b/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab index 4252e74cc..b80967c41 100644 --- a/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Octahedron.prefab b/Assets/Prefabs/RPG/Pickups/Octahedron.prefab index 099083195..9cabd7b79 100644 --- a/Assets/Prefabs/RPG/Pickups/Octahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Octahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab b/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab index 6dad19967..20f8073a7 100644 --- a/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Wormhole 1.prefab b/Assets/Prefabs/RPG/Wormhole 1.prefab index e1ca93be7..eff50285a 100644 --- a/Assets/Prefabs/RPG/Wormhole 1.prefab +++ b/Assets/Prefabs/RPG/Wormhole 1.prefab @@ -28,6 +28,7 @@ Transform: m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 8249320701965103923} + - {fileID: 7100000000000000014} m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} @@ -112,3 +113,443 @@ MeshRenderer: m_SortingLayer: 0 m_SortingOrder: 0 m_AdditionalVertexStreams: {fileID: 0} +--- !u!1 &7100000000000000007 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 7100000000000000014} + m_Layer: 0 + m_Name: Anchor Beacon + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 0 +--- !u!4 &7100000000000000014 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000007} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: -15, z: 110} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 7100000000000000028} + - {fileID: 7100000000000000056} + - {fileID: 7100000000000000084} + - {fileID: 7100000000000000112} + - {fileID: 7100000000000000140} + m_Father: {fileID: 463084220523011477} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &7100000000000000021 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 7100000000000000028} + - component: {fileID: 7100000000000000035} + - component: {fileID: 7100000000000000042} + m_Layer: 0 + m_Name: Base + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &7100000000000000028 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000021} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: -4, z: 0} + m_LocalScale: {x: 36, y: 1.5, z: 36} + m_Children: [] + m_Father: {fileID: 7100000000000000014} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &7100000000000000035 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000021} + m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &7100000000000000042 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000021} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 0635cf2d392265944afa2b9ce2aab35f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!1 &7100000000000000049 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 7100000000000000056} + - component: {fileID: 7100000000000000063} + - component: {fileID: 7100000000000000070} + m_Layer: 0 + m_Name: Spire + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &7100000000000000056 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000049} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 3, z: 0} + m_LocalScale: {x: 5, y: 5, z: 5} + m_Children: [] + m_Father: {fileID: 7100000000000000014} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &7100000000000000063 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000049} + m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &7100000000000000070 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000049} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 0635cf2d392265944afa2b9ce2aab35f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!1 &7100000000000000077 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 7100000000000000084} + - component: {fileID: 7100000000000000091} + - component: {fileID: 7100000000000000098} + m_Layer: 0 + m_Name: Crown + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &7100000000000000084 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000077} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 8, z: 0} + m_LocalScale: {x: 10, y: 10, z: 10} + m_Children: [] + m_Father: {fileID: 7100000000000000014} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &7100000000000000091 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000077} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &7100000000000000098 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000077} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 0635cf2d392265944afa2b9ce2aab35f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!1 &7100000000000000105 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 7100000000000000112} + - component: {fileID: 7100000000000000119} + - component: {fileID: 7100000000000000126} + m_Layer: 0 + m_Name: Arm X + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &7100000000000000112 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000105} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 4, z: 0} + m_LocalScale: {x: 34, y: 1, z: 3} + m_Children: [] + m_Father: {fileID: 7100000000000000014} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &7100000000000000119 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000105} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &7100000000000000126 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000105} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 0635cf2d392265944afa2b9ce2aab35f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!1 &7100000000000000133 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 7100000000000000140} + - component: {fileID: 7100000000000000147} + - component: {fileID: 7100000000000000154} + m_Layer: 0 + m_Name: Arm Z + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &7100000000000000140 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000133} + m_LocalRotation: {x: 0, y: 0.7071068, z: 0, w: 0.7071068} + m_LocalPosition: {x: 0, y: 4, z: 0} + m_LocalScale: {x: 34, y: 1, z: 3} + m_Children: [] + m_Father: {fileID: 7100000000000000014} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &7100000000000000147 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000133} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &7100000000000000154 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7100000000000000133} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 0635cf2d392265944afa2b9ce2aab35f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_AdditionalVertexStreams: {fileID: 0} diff --git a/Assets/Resources/Aetheria.inputactions b/Assets/Resources/Aetheria.inputactions index fe1ef6086..8201c8471 100644 --- a/Assets/Resources/Aetheria.inputactions +++ b/Assets/Resources/Aetheria.inputactions @@ -36,6 +36,36 @@ "initialStateCheck": false, "priority": 0 }, + { + "name": "Zoom", + "type": "Value", + "id": "47ee174a-e711-4dd1-885c-f1cfbdd3681e", + "expectedControlType": "Axis", + "processors": "", + "interactions": "", + "initialStateCheck": true, + "priority": 0 + }, + { + "name": "Pan", + "type": "Button", + "id": "591eacf3-8726-4393-8a6d-f09410b745a4", + "expectedControlType": "Button", + "processors": "", + "interactions": "", + "initialStateCheck": false, + "priority": 0 + }, + { + "name": "Point", + "type": "Value", + "id": "f0ec75bc-84a5-4ea4-8e0f-e72f725e6b9d", + "expectedControlType": "Vector2", + "processors": "", + "interactions": "", + "initialStateCheck": true, + "priority": 0 + }, { "name": "Target Reticle", "type": "Button", @@ -353,6 +383,50 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "c2b6406d-0c48-47e1-ad45-9f05fc7b7017", + "path": "/scroll/y", + "interactions": "", + "processors": "", + "groups": "Keyboard&Mouse", + "action": "Zoom", + "isComposite": false, + "isPartOfComposite": false + }, + { + "name": "", + "id": "e4e6d330-0963-4690-8e53-a1b52c5c6bce", + "path": "/leftButton", + "interactions": "", + "processors": "", + "groups": "Keyboard&Mouse", + "action": "Pan", + "isComposite": false, + "isPartOfComposite": false + }, + { + "name": "", + "id": "fe708e7d-0f9e-4b03-b983-d60e769e4292", + "path": "/middleButton", + "interactions": "", + "processors": "", + "groups": "Keyboard&Mouse", + "action": "Pan", + "isComposite": false, + "isPartOfComposite": false + }, + { + "name": "", + "id": "8ad98e17-f4bd-4d92-8300-f562b96f3750", + "path": "/position", + "interactions": "", + "processors": "", + "groups": "Keyboard&Mouse", + "action": "Point", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "5211a58c-428b-4ee6-820d-2f67789806d6", diff --git a/Assets/Resources/Settings.asset b/Assets/Resources/Settings.asset index c12d32c99..2da386267 100644 --- a/Assets/Resources/Settings.asset +++ b/Assets/Resources/Settings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:711ded55b95c512e3803df7682e44f0a9bb83ad36a384432781dc12dc5dadf0a -size 12630 +oid sha256:7981565178e096ee594ebce89bad849f017750051aaa72c7fd8f043e549bebcd +size 12453 diff --git a/Assets/Scripts/AetheriaInput.cs b/Assets/Scripts/AetheriaInput.cs index 373c0b8bb..d9248909e 100644 --- a/Assets/Scripts/AetheriaInput.cs +++ b/Assets/Scripts/AetheriaInput.cs @@ -122,6 +122,36 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable ""initialStateCheck"": false, ""priority"": 0 }, + { + ""name"": ""Zoom"", + ""type"": ""Value"", + ""id"": ""47ee174a-e711-4dd1-885c-f1cfbdd3681e"", + ""expectedControlType"": ""Axis"", + ""processors"": """", + ""interactions"": """", + ""initialStateCheck"": true, + ""priority"": 0 + }, + { + ""name"": ""Pan"", + ""type"": ""Button"", + ""id"": ""591eacf3-8726-4393-8a6d-f09410b745a4"", + ""expectedControlType"": ""Button"", + ""processors"": """", + ""interactions"": """", + ""initialStateCheck"": false, + ""priority"": 0 + }, + { + ""name"": ""Point"", + ""type"": ""Value"", + ""id"": ""f0ec75bc-84a5-4ea4-8e0f-e72f725e6b9d"", + ""expectedControlType"": ""Vector2"", + ""processors"": """", + ""interactions"": """", + ""initialStateCheck"": true, + ""priority"": 0 + }, { ""name"": ""Target Reticle"", ""type"": ""Button"", @@ -439,6 +469,50 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable ""isComposite"": false, ""isPartOfComposite"": false }, + { + ""name"": """", + ""id"": ""c2b6406d-0c48-47e1-ad45-9f05fc7b7017"", + ""path"": ""/scroll/y"", + ""interactions"": """", + ""processors"": """", + ""groups"": ""Keyboard&Mouse"", + ""action"": ""Zoom"", + ""isComposite"": false, + ""isPartOfComposite"": false + }, + { + ""name"": """", + ""id"": ""e4e6d330-0963-4690-8e53-a1b52c5c6bce"", + ""path"": ""/leftButton"", + ""interactions"": """", + ""processors"": """", + ""groups"": ""Keyboard&Mouse"", + ""action"": ""Pan"", + ""isComposite"": false, + ""isPartOfComposite"": false + }, + { + ""name"": """", + ""id"": ""fe708e7d-0f9e-4b03-b983-d60e769e4292"", + ""path"": ""/middleButton"", + ""interactions"": """", + ""processors"": """", + ""groups"": ""Keyboard&Mouse"", + ""action"": ""Pan"", + ""isComposite"": false, + ""isPartOfComposite"": false + }, + { + ""name"": """", + ""id"": ""8ad98e17-f4bd-4d92-8300-f562b96f3750"", + ""path"": ""/position"", + ""interactions"": """", + ""processors"": """", + ""groups"": ""Keyboard&Mouse"", + ""action"": ""Point"", + ""isComposite"": false, + ""isPartOfComposite"": false + }, { ""name"": """", ""id"": ""5211a58c-428b-4ee6-820d-2f67789806d6"", @@ -1303,6 +1377,9 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable m_Player_Move = m_Player.FindAction("Move", throwIfNotFound: true); m_Player_Look = m_Player.FindAction("Look", throwIfNotFound: true); m_Player_MinimapZoom = m_Player.FindAction("Minimap Zoom", throwIfNotFound: true); + m_Player_Zoom = m_Player.FindAction("Zoom", throwIfNotFound: true); + m_Player_Pan = m_Player.FindAction("Pan", throwIfNotFound: true); + m_Player_Point = m_Player.FindAction("Point", throwIfNotFound: true); m_Player_TargetReticle = m_Player.FindAction("Target Reticle", throwIfNotFound: true); m_Player_TargetPrevious = m_Player.FindAction("Target Previous", throwIfNotFound: true); m_Player_TargetNext = m_Player.FindAction("Target Next", throwIfNotFound: true); @@ -1422,6 +1499,9 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable private readonly InputAction m_Player_Move; private readonly InputAction m_Player_Look; private readonly InputAction m_Player_MinimapZoom; + private readonly InputAction m_Player_Zoom; + private readonly InputAction m_Player_Pan; + private readonly InputAction m_Player_Point; private readonly InputAction m_Player_TargetReticle; private readonly InputAction m_Player_TargetPrevious; private readonly InputAction m_Player_TargetNext; @@ -1461,6 +1541,18 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable /// public InputAction @MinimapZoom => m_Wrapper.m_Player_MinimapZoom; /// + /// Provides access to the underlying input action "Player/Zoom". + /// + public InputAction @Zoom => m_Wrapper.m_Player_Zoom; + /// + /// Provides access to the underlying input action "Player/Pan". + /// + public InputAction @Pan => m_Wrapper.m_Player_Pan; + /// + /// Provides access to the underlying input action "Player/Point". + /// + public InputAction @Point => m_Wrapper.m_Player_Point; + /// /// Provides access to the underlying input action "Player/TargetReticle". /// public InputAction @TargetReticle => m_Wrapper.m_Player_TargetReticle; @@ -1555,6 +1647,15 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable @MinimapZoom.started += instance.OnMinimapZoom; @MinimapZoom.performed += instance.OnMinimapZoom; @MinimapZoom.canceled += instance.OnMinimapZoom; + @Zoom.started += instance.OnZoom; + @Zoom.performed += instance.OnZoom; + @Zoom.canceled += instance.OnZoom; + @Pan.started += instance.OnPan; + @Pan.performed += instance.OnPan; + @Pan.canceled += instance.OnPan; + @Point.started += instance.OnPoint; + @Point.performed += instance.OnPoint; + @Point.canceled += instance.OnPoint; @TargetReticle.started += instance.OnTargetReticle; @TargetReticle.performed += instance.OnTargetReticle; @TargetReticle.canceled += instance.OnTargetReticle; @@ -1620,6 +1721,15 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable @MinimapZoom.started -= instance.OnMinimapZoom; @MinimapZoom.performed -= instance.OnMinimapZoom; @MinimapZoom.canceled -= instance.OnMinimapZoom; + @Zoom.started -= instance.OnZoom; + @Zoom.performed -= instance.OnZoom; + @Zoom.canceled -= instance.OnZoom; + @Pan.started -= instance.OnPan; + @Pan.performed -= instance.OnPan; + @Pan.canceled -= instance.OnPan; + @Point.started -= instance.OnPoint; + @Point.performed -= instance.OnPoint; + @Point.canceled -= instance.OnPoint; @TargetReticle.started -= instance.OnTargetReticle; @TargetReticle.performed -= instance.OnTargetReticle; @TargetReticle.canceled -= instance.OnTargetReticle; @@ -2101,6 +2211,27 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable /// void OnMinimapZoom(InputAction.CallbackContext context); /// + /// Method invoked when associated input action "Zoom" is either , or . + /// + /// + /// + /// + void OnZoom(InputAction.CallbackContext context); + /// + /// Method invoked when associated input action "Pan" is either , or . + /// + /// + /// + /// + void OnPan(InputAction.CallbackContext context); + /// + /// Method invoked when associated input action "Point" is either , or . + /// + /// + /// + /// + void OnPoint(InputAction.CallbackContext context); + /// /// Method invoked when associated input action "Target Reticle" is either , or . /// /// diff --git a/Assets/Scripts/Editor/ShipModPlaySmoke.cs b/Assets/Scripts/Editor/ShipModPlaySmoke.cs index b453162fb..0aa678d40 100644 --- a/Assets/Scripts/Editor/ShipModPlaySmoke.cs +++ b/Assets/Scripts/Editor/ShipModPlaySmoke.cs @@ -15,6 +15,9 @@ using UnityEngine; // accepts it, so it composes, and the importer cannot build it, so Preload faults Loading with ImportFault naming it. // RemovePackage then moves it aside and the next Compose leaves it out. // +// A Station package takes the same path to an EntityInstance with no ShipInstance (a station does not fly), checked without +// thruster or weapon asserts; its .broken sibling swaps the map-icon anchor with the shield anchor, which has no mesh. +// // Unity -batchmode -nographics -projectPath -executeMethod ShipModPlaySmoke.Run // -shipModPath //ship.cc [-shippedCatalog GameData/Aetheria.cc] -logFile // @@ -39,11 +42,12 @@ public static class ShipModPlaySmoke if (packagePath == null) throw new InvalidOperationException("-shipModPath is required"); var package = ShipModCatalog.ReadPackage(packagePath); Install(package.Visual.Id, package, modsRoot, Path.GetFullPath(packagePath)); + var station = package.Hull.HullType == HullType.Station; var broken = InstallSibling(package, modsRoot, ".broken", ship => { var mapIcon = ship.Anchors.Single(anchor => anchor.Role == "map-icon"); - var muzzle = ship.Anchors.First(anchor => anchor.Role == "weapon-muzzle"); - (mapIcon.ModelNodeId, muzzle.ModelNodeId) = (muzzle.ModelNodeId, mapIcon.ModelNodeId); + var meshless = station ? ship.Anchors.Single(anchor => anchor.Role == "shield") : ship.Anchors.First(anchor => anchor.Role == "weapon-muzzle"); + (mapIcon.ModelNodeId, meshless.ModelNodeId) = (meshless.ModelNodeId, mapIcon.ModelNodeId); }, null); var shipped = Path.GetFullPath(Option("-shippedCatalog", "GameData/Aetheria.cc")); var composition = ShipModCatalog.Compose(shipped, derived, modsRoot); @@ -60,13 +64,23 @@ public static class ShipModPlaySmoke var hull = Hull(package.Hull.Name); zone = new GameObject("Play Smoke Zone"); - var ship = ShipModShips.Instantiate(hull, zone.transform).GetComponent(); - if (ship == null) throw new InvalidOperationException("The mod ship body has no ShipInstance."); + var body = ShipModShips.Instantiate(hull, zone.transform); + var ship = body.GetComponent(); + if (ship == null) throw new InvalidOperationException("The mod hull's body has no EntityInstance."); var thrusters = ship.ThrusterHardpoints?.Length ?? 0; var weapons = ship.WeaponHardpoints?.Length ?? 0; - if (thrusters == 0) throw new InvalidOperationException("ThrusterHardpoints is empty."); - if (weapons == 0 || ship.WeaponHardpoints.Any(node => node.FiringPoint == null || node.FiringPoint.Length == 0)) - throw new InvalidOperationException("WeaponHardpoints is empty or a weapon has no muzzle."); + if (station) + { + // A station renders as an EntityInstance: a ShipInstance would throw in Update (SetEntity returns before _thrusters). + if (body.GetComponent() != null) throw new InvalidOperationException("A station body must not carry a ShipInstance."); + } + else + { + if (ship is not ShipInstance) throw new InvalidOperationException("The mod ship body has no ShipInstance."); + if (thrusters == 0) throw new InvalidOperationException("ThrusterHardpoints is empty."); + if (weapons == 0 || ship.WeaponHardpoints.Any(node => node.FiringPoint == null || node.FiringPoint.Length == 0)) + throw new InvalidOperationException("WeaponHardpoints is empty or a weapon has no muzzle."); + } if (ship.HullColliders == null || ship.HullColliders.Length != 1) throw new InvalidOperationException("The ship needs exactly one hull collider."); var collider = ship.HullColliders[0].GetComponent(); diff --git a/Assets/Scripts/Editor/ShipModPreview.cs b/Assets/Scripts/Editor/ShipModPreview.cs index 9ed4fcec4..c5b7c9a70 100644 --- a/Assets/Scripts/Editor/ShipModPreview.cs +++ b/Assets/Scripts/Editor/ShipModPreview.cs @@ -47,17 +47,24 @@ public static class ShipModPreview if (template == null) throw new InvalidOperationException($"{TemplatePath} is missing or has no ShipModTemplate."); var plan = ShipModPlan.Build(package.Hull, package.Visual); var ship = ShipModShips.Assemble(visual, package.Hull, package.Visual, template); + // A station is a plain EntityInstance: ShipInstance flies, and SetEntity would read thrusters it does not have. + if ((package.Hull.HullType == HullType.Ship) != (ship is ShipInstance)) + throw new InvalidOperationException($"assembled: a {package.Hull.HullType} hull got {ship.GetType().Name}; only a Ship gets a ShipInstance."); CheckShip(ship, plan, "assembled"); // Instantiate clones the assembled root, and Unity must remap every array reference into the clone. - var clone = UnityEngine.Object.Instantiate(ship.gameObject).GetComponent(); - try { CheckShip(clone, plan, "clone"); CheckExhaust(clone); } + var clone = UnityEngine.Object.Instantiate(ship.gameObject).GetComponent(); + try + { + CheckShip(clone, plan, "clone"); + if (clone is ShipInstance flier) CheckExhaust(flier); + } finally { UnityEngine.Object.DestroyImmediate(clone.gameObject); } Debug.Log($"SHIP_MOD_ASSEMBLY_SMOKE thrusters={plan.Thrusters.Length} exhaust=ok collider=hidden " + $"weapons={plan.Weapons.Length} radiators={plan.Radiators.Length}"); } - private static void CheckShip(ShipInstance ship, ShipModPlan plan, string what) + private static void CheckShip(EntityInstance ship, ShipModPlan plan, string what) { void Require(bool ok, string claim) { if (!ok) throw new InvalidOperationException($"{what}: {claim}"); } bool Inside(Component part) => part != null && part.transform.IsChildOf(ship.transform); @@ -66,7 +73,8 @@ public static class ShipModPreview Require(ship.HullColliders[0].GetComponentsInChildren(true).All(renderer => renderer.sharedMaterials.All(material => material == ship.InvisibleMaterial)), "a hull collider that draws nothing"); - Require(Inside(ship.MapIcon) && Inside(ship.Shield) && Inside(ship.TractorBeam), "map icon, shield and tractor inside the ship"); + Require(Inside(ship.MapIcon) && Inside(ship.Shield) && (ship is not ShipInstance flier || Inside(flier.TractorBeam)), + "map icon, shield and tractor inside the ship"); Require(ship.ThrusterHardpoints.Select(node => node.name).SequenceEqual(plan.Thrusters) && ship.ThrusterHardpoints.All(node => Inside(node) && Inside(node.Emitter) && node.Emitter.sharedMaterials.All(material => material == ship.InvisibleMaterial)), diff --git a/Assets/Scripts/Editor/ShipPrefabAuthoring.cs b/Assets/Scripts/Editor/ShipPrefabAuthoring.cs index d2937b79d..45bbc8609 100644 --- a/Assets/Scripts/Editor/ShipPrefabAuthoring.cs +++ b/Assets/Scripts/Editor/ShipPrefabAuthoring.cs @@ -112,6 +112,7 @@ public static class ShipPrefabAuthoring case "Thruster": var emitter = DirectChild(node, "Emitter")?.GetComponent(); if (emitter == null) throw new InvalidOperationException($"{name} needs an Emitter mesh child"); + ShipModShips.Hide(emitter, invisible); AddOrGet(node.gameObject).Emitter = emitter; thrusters.Add(node.GetComponent()); break; diff --git a/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs b/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs index 9f740f557..5342eb352 100644 --- a/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs +++ b/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs @@ -28,6 +28,8 @@ public static class ShipPrefabAuthoringSmoke ShipPrefabAuthoring.Configure(root); var ship = root.GetComponent(); Require(ship != null && ship.ThrusterHardpoints.Length == 1 && ship.ThrusterHardpoints[0].Emitter != null, "thruster emitter"); + Require(Array.TrueForAll(ship.ThrusterHardpoints[0].Emitter.sharedMaterials, material => material == ship.InvisibleMaterial), + "thruster emitter drawn with the invisible material only"); Require(ship.WeaponHardpoints.Length == 1 && ship.WeaponHardpoints[0].FiringPoint.Length == 2, "weapon muzzles"); Require(ship.WeaponHardpoints[0].FiringPoint[0].name == "Muzzle.0", "numeric muzzle order"); Require(ship.RadiatorHardpoints.Length == 1 && ship.RadiatorHardpoints[0].Mesh != null, "radiator mesh"); diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index 8c2b38345..ab6c43176 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -106,6 +106,9 @@ public class ActionGameManager : MonoBehaviour } public static Galaxy CurrentGalaxy; + // Whether a run is live: a failed start and a finished run both clear the galaxy, and the scene's update paths (this + // manager's, the renderer's) step and draw nothing without one. + public static bool RunLive => CurrentGalaxy != null; // The scenario a new run starts from: MainMenu.Launch sets it, and StartGame's new-run branch consumes it once. public static Scenario PendingScenario; @@ -137,7 +140,6 @@ public class ActionGameManager : MonoBehaviour public ZoneRenderer ZoneRenderer; public CinemachineVirtualCamera DockCamera; public CinemachineVirtualCamera FollowCamera; - public CinemachineVirtualCamera WormholeCamera; //public SectorRenderer SectorRenderer; public SectorMap SectorMap; @@ -188,9 +190,6 @@ public class ActionGameManager : MonoBehaviour //public PlayerInput Input; - // private CinemachineFramingTransposer _transposer; - // private CinemachineComposer _composer; - private bool _paused; private float _time; private int _zoomLevelIndex; @@ -274,13 +273,25 @@ public class ActionGameManager : MonoBehaviour private void OnApplicationQuit() { SaveRun(); + DiscardSimulation(); SavePlayerSettings(); } - // Wormhole arrival and quit save the run; a dead run has no galaxy, so it is not saved. + // The live simulation (Scenario.Saved false), or null while a saved run or nothing is live. Whether the session is + // saved is derived from it alone: StartScenario is the only setter and DiscardSimulation the only clearer. + public static RunSave.Simulation Simulation { get; private set; } + + // Removes what the simulation wrote to the run store, so the saved run and the next run never see it. + private void DiscardSimulation() + { + Simulation?.Discard(CultCache); + Simulation = null; + } + + // Wormhole arrival and quit save the run; a dead run has no galaxy, so it is not saved, and a simulation never is. public void SaveRun() { - if (CurrentGalaxy != null) + if (Simulation == null && CurrentGalaxy != null) { var (game, zones) = RunSave.Capture(CultCache, CurrentGalaxy, Zone, DockedEntity ?? CurrentEntity, _actionBarSlots.Select(s => s.Save()).ToArray(), Credits); @@ -321,7 +332,7 @@ public class ActionGameManager : MonoBehaviour Input.Global.Enable(); // The latch is the game's own, so it can disagree with the keyboard's Caps Lock light: show it. - Input.Player.ToggleFaceAim.performed += context => _helm.Toggle(); + Bind(Input.Player.ToggleFaceAim, context => _helm.Toggle()); var markParent = GameplayUI != null ? GameplayUI.transform : UiRoot.transform; var markObject = new GameObject("Face Aim Mark", typeof(RectTransform)); markObject.transform.SetParent(markParent, false); @@ -335,23 +346,59 @@ public class ActionGameManager : MonoBehaviour _faceAimMark.enabled = false; _zoomLevelIndex = Settings.DefaultMinimapZoom; - Input.Player.MinimapZoom.performed += context => + Bind(Input.Player.MinimapZoom, context => { _zoomLevelIndex = (_zoomLevelIndex + 1) % Settings.MinimapZoomLevels.Length; ZoneRenderer.MinimapDistance = Settings.MinimapZoomLevels[_zoomLevelIndex]; - }; + }); - Input.Global.ZoneMap.performed += context => + // The tactical view is a distinct camera over the grid (ruling tactical-view-distinct-mode): the wheel is one axis + // from the chase view through a detent into it, and TacticalView the one owner of where on that axis the camera is. + _tactical = new TacticalView(Settings.TacticalZoomStep, Settings.TacticalBlendStart, Settings.TacticalBlendEnd, + Settings.TacticalTimeScale, Settings.TacticalFitPerRadius, Settings.DetentResistance, Settings.DetentRelaxTime, + Settings.ViewEaseTime); + // The view rig: the chase camera (child 0) and the tactical camera (child 1) mixed by the blend, built here so the + // scene stays as authored. The mix is a function of the eased distance, not a brain blend on a priority switch. + var rig = new GameObject("View Rig"); + _viewRig = rig.AddComponent(); + _viewRig.Priority = FollowCamera.Priority; + FollowCamera.transform.SetParent(rig.transform, false); + FollowCamera.transform.SetAsFirstSibling(); + var tacticalCamera = new GameObject("Tactical Camera"); + tacticalCamera.transform.SetParent(rig.transform, false); + _tacticalCamera = tacticalCamera.AddComponent(); + _tacticalFade = ScriptableObject.CreateInstance(); + _tacticalFade.enabled.Override(true); + _tacticalFade.Background.Override(Settings.TacticalBackground); + _tacticalVolume = PostProcessManager.instance.QuickVolume(DeathPost.gameObject.layer, 100f, _tacticalFade); + _tacticalVolume.weight = 0; + var schematic = new GameObject("Tactical Schematic Camera"); + schematic.transform.SetParent(ZoneRenderer.MainCamera.transform, false); + _schematicCamera = schematic.AddComponent(); + _schematicCamera.clearFlags = CameraClearFlags.Depth; + _schematicCamera.depth = ZoneRenderer.MainCamera.depth + 1; + _schematicCamera.cullingMask = 1 << LayerMask.NameToLayer("Minimap"); + _schematicCamera.enabled = false; + Bind(Input.Player.Zoom, context => + { + var scroll = context.ReadValue(); + if (scroll == 0 || !Flying) return; + var was = _tactical.Tactical; + _tactical.Scroll(-Mathf.Sign(scroll)); + if (_tactical.Tactical != was) EnablePlayerInput(); + }); + + Bind(Input.Global.ZoneMap, context => { ToggleMenuTab(MenuTab.Map); MenuMap.Position = DrawAhead.Position(CurrentEntity, Clock.Lead).xz; - }; + }); - Input.Global.Inventory.performed += context => ToggleMenuTab(MenuTab.Inventory); + Bind(Input.Global.Inventory, context => ToggleMenuTab(MenuTab.Inventory)); - Input.Global.GalaxyMap.performed += context => ToggleMenuTab(MenuTab.Galaxy); + Bind(Input.Global.GalaxyMap, context => ToggleMenuTab(MenuTab.Galaxy)); - Input.Global.Interact.performed += context => + Bind(Input.Global.Interact, context => { if (EventSystem.current.currentSelectedGameObject != null && EventSystem.current.currentSelectedGameObject.GetComponent() != null) return; if (MainMenu.gameObject.activeSelf) return; @@ -368,6 +415,15 @@ public class ActionGameManager : MonoBehaviour foreach (var wormhole in ZoneRenderer.WormholeInstances.Keys) { if (!(length(wormhole.Position - CurrentEntity.Position.xz) < Settings.GameplaySettings.WormholeExitRadius)) continue; + if (Simulation != null) + { + // The simulation's wormhole is its exit (ruling ifl-wormhole-exit-standin). + Dialog.Clear(); + Dialog.Title.text = "Leave the simulation and start a run?"; + Dialog.Show(onConfirm: LeaveSimulation, onCancel: () => { }, confirmText: "Leave", cancelText: "Stay"); + Dialog.MoveToCursor(); + return; + } if (wormhole.Exit) { // The exit gate leads nowhere: TryWin consults RunGoal and ends the run when the gate is open. @@ -385,53 +441,57 @@ public class ActionGameManager : MonoBehaviour Dock(); } else Undock(); - }; + }); - Input.Global.MainMenu.performed += context => + Bind(Input.Global.MainMenu, context => { if(Menu.gameObject.activeSelf) ToggleMenuTab(Menu.CurrentTab); else ToggleFullscreenMenu(MainMenu.gameObject); - }; + }); - Input.Global.InputScreen.performed += context => ToggleFullscreenMenu(HelpScreen); + Bind(Input.Global.InputScreen, context => ToggleFullscreenMenu(HelpScreen)); - Input.Player.HideUI.performed += context => + Bind(Input.Player.HideUI, context => { _uiHidden = !_uiHidden; GameplayUI.alpha = _uiHidden ? 0 : 1; ActionBar.gameObject.SetActive(!_uiHidden); - }; + }); // The switches and the ping are presses on the entity's command, flipped at the next step. - Input.Player.OverrideShutdown.performed += context => CurrentEntity.Command.ToggleOverrideShutdown(); - Input.Player.Ping.performed += context => CurrentEntity.Command.Ping(); + Bind(Input.Player.OverrideShutdown, context => CurrentEntity.Command.ToggleOverrideShutdown()); + Bind(Input.Player.Ping, context => CurrentEntity.Command.Ping()); // TODO: SFX: Success/Fail - Input.Player.ToggleHeatsinks.performed += context => CurrentEntity.Command.ToggleHeatsinks(); + Bind(Input.Player.ToggleHeatsinks, context => CurrentEntity.Command.ToggleHeatsinks()); // TODO: SFX: Success/Fail - Input.Player.ToggleShield.performed += context => CurrentEntity.Command.ToggleShield(); + Bind(Input.Player.ToggleShield, context => CurrentEntity.Command.ToggleShield()); // Flips the player's own stance on the current target between hostile and neutral. Going // neutral mid-fight safes weapons (Weapon.StanceAllowsFire); an unmarked/undetected target // reads as non-hostile, so the first press declares hostile. The flip reads the target and its stance when applied, // after the step's target presses, so two presses in a step cancel. - Input.Player.ToggleStance.performed += context => CurrentEntity.Command.ToggleStance(); + Bind(Input.Player.ToggleStance, context => CurrentEntity.Command.ToggleStance()); #region Targeting // The reticle, nearest, next and previous presses each command a verb; the applier chooses through Entity at the // next step (mining target-queries cut): the rule lives with the entity, so the player, the test agent and any // director pick alike. - Input.Player.TargetReticle.performed += context => CurrentEntity.Command.Verb(TargetVerb.UnderReticle); - Input.Player.TargetNearest.performed += context => CurrentEntity.Command.Verb(TargetVerb.NearestEnemy); - Input.Player.TargetNext.performed += context => CurrentEntity.Command.Verb(TargetVerb.Next); - Input.Player.TargetPrevious.performed += context => CurrentEntity.Command.Verb(TargetVerb.Previous); + Bind(Input.Player.TargetReticle, context => CurrentEntity.Command.Verb(TargetVerb.UnderReticle)); + Bind(Input.Player.TargetNearest, context => CurrentEntity.Command.Verb(TargetVerb.NearestEnemy)); + Bind(Input.Player.TargetNext, context => CurrentEntity.Command.Verb(TargetVerb.Next)); + Bind(Input.Player.TargetPrevious, context => CurrentEntity.Command.Verb(TargetVerb.Previous)); // Cut 2 (docs/fire-control-cut.md): steps the aim through the target's schematic rows -- every mount this ship // has located, empty or not, minus the ones it saw destroyed. Decides nothing: the entity owns the cycle, applied at // the next step. - Input.Player.CycleTargetItem.performed += context => CurrentEntity.Command.CycleAim(); + Bind(Input.Player.CycleTargetItem, context => CurrentEntity.Command.CycleAim()); + + // The tractor is held while its key is: a press and a release each set it. It is not polled, so a key already down when the + // flight view returns does nothing until it is pressed again, as with fire; Update releases it while the view is tactical. + Bind(Input.Player.TractorBeam, context => CurrentEntity.Command.Tractor = context.ReadValue(), context => CurrentEntity.Command.Tractor = 0); #endregion @@ -556,11 +616,7 @@ public class ActionGameManager : MonoBehaviour { FollowCamera.Follow = x.missile.transform; FollowCamera.LookAt = x.target ? x.target : x.missile.transform; - x.missile.OnKill += () => - { - FollowCamera.LookAt = ZoneRenderer.EntityInstances[CurrentEntity].LookAtPoint; - FollowCamera.Follow = ZoneRenderer.EntityInstances[CurrentEntity].transform; - }; + x.missile.OnKill += () => FrameFollow(CurrentEntity); }); } }); @@ -577,6 +633,33 @@ public class ActionGameManager : MonoBehaviour ItemManager.Random.NextFloat2Direction() * ItemManager.Random.NextFloat(50, 500); Zone.Admit(turret, piloted: false); }); + // "summon" lists the formations; "summon " places one 400 m ahead of the current ship, facing back toward it. The + // faction rule decides who fights whom: a summon writes no stance. + ConsoleController.AddCommand("summon", + args => + { + var console = ConsoleController.Instance; + if (args.Length == 0) + { + console.AppendLogLine("Formations: " + string.Join(", ", Formations.All.Select(formation => formation.Id))); + return; + } + var formation = Formations.ById(args[0]); + if (formation == null) + { + console.AppendLogLine($"No formation \"{args[0]}\"; summon alone lists them"); + return; + } + if (_currentEntity == null || _currentEntity.Parent != null) + { + console.AppendLogLine("Refused: undock first"); + return; + } + var failures = new List(); + var summoned = formation.Summon(ItemManager, Zone, _currentEntity.Position.xz + _currentEntity.Direction * 400, -_currentEntity.Direction, failures); + foreach (var failure in failures) console.AppendLogLine($"summon {formation.Id}: {failure}"); + if (summoned != null) console.AppendLogLine($"Summoned {formation.Name}: {string.Join(", ", summoned.Select(entity => entity.Name))}"); + }); // "fly Djinni": a freshly fitted ship of the named hull beside the current one, and you in it. The ship you leave // stays where it is, unpiloted. ConsoleController.AddCommand("fly", @@ -619,6 +702,12 @@ public class ActionGameManager : MonoBehaviour //Temporary, or not ConsoleController.AddCommand("tow", _ => TowShip()); + ConsoleController.AddCommand("leave", _ => + { + if (Simulation == null) Debug.Log("leave: only a simulation can be left; there is no simulation"); + else LeaveSimulation(); + }); + // Manual IFF override for the player's current target, for hand-testing combat. // "iff hostile"/"iff neutral" force a stance; "iff clear" restores the derived faction rule. ConsoleController.AddCommand("iff", args => @@ -688,11 +777,37 @@ public class ActionGameManager : MonoBehaviour return success ?? false; } + // Ruling tactical-input-hands-off: the one route every Player and Global action is subscribed and read through. TacticalInput + // decides per action whether it is live (an unclassified action is not); a press, a release or a read that is not live is + // dropped, never queued, so the ship holds its last commands. A test scans this file and fails if an action is touched anywhere else. + private bool Live(InputAction action) => TacticalInput.Live(_tactical, action.actionMap.name, action.name); + + private void Bind(InputAction action, Action performed, Action canceled = null) + { + action.performed += context => { if (Live(action)) performed(context); }; + if (canceled != null) action.canceled += context => { if (Live(action)) canceled(context); }; + } + + private bool TryRead(InputAction action, out T value) where T : struct + { + value = default; + if (!Live(action)) return false; + value = action.ReadValue(); + return true; + } + + private bool Held(InputAction action) => Live(action) && action.IsPressed(); + + private InputControl ActiveControl(InputAction action) => Live(action) ? action.activeControl : null; + + // The one writer of the cursor lock and the action bar while playing: the tactical view frees the cursor and gives the + // mouse buttons to Pan, so the bar is off there. It is re-applied whenever Tactical changes. public void EnablePlayerInput() { - Cursor.lockState = CursorLockMode.Locked; + Cursor.lockState = _tactical.Tactical ? CursorLockMode.None : CursorLockMode.Locked; Input.Player.Enable(); - foreach (var a in _actionBarActions) a.Enable(); + foreach (var a in _actionBarActions) + if (_tactical.Tactical) a.Disable(); else a.Enable(); } public void DisablePlayerInput() @@ -705,13 +820,10 @@ public class ActionGameManager : MonoBehaviour private void EnterWormhole(Wormhole wormhole) { if (!(CurrentEntity is Ship ship) || ship.WormholeAnimationInProgress) return; - // var wormholeCameraFollow = new GameObject("Wormhole Camera Follow").transform; - // wormholeCameraFollow.position = new Vector3(wormhole.Position.x, -50, wormhole.Position.y); - // wormholeCameraFollow.rotation = Quaternion.LookRotation(Vector3.down, ship.Aim); - // WormholeCamera.enabled = true; - // WormholeCamera.Follow = wormholeCameraFollow; - // FollowCamera.enabled = false; ship.EnterWormhole(wormhole.Position); + WormholeWarpPresenter.Begin(ship, DeathPost.gameObject.layer, + Mathf.Max(DeathPost.priority, HeatstrokePost.priority, HypothermiaPost.priority, + SevereHeatstrokePost.priority, SevereHypothermiaPost.priority) + 1); ship.OnEnteredWormhole += () => { var oldZone = Zone; @@ -726,6 +838,13 @@ public class ActionGameManager : MonoBehaviour }; } + // The one way out of a simulation: starts the Terminus run. AL7 puts the pilot pick in front of this call. + public void LeaveSimulation() + { + MainMenu.gameObject.SetActive(true); // Launch starts a coroutine on it + MainMenu.Launch(Scenarios.Terminus); + } + public void PopulateLevel(GalaxyZone galaxyZone) { if (galaxyZone == null) throw new ArgumentNullException(nameof(galaxyZone)); @@ -737,8 +856,7 @@ public class ActionGameManager : MonoBehaviour Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, - galaxyZone, - CurrentGalaxy.IsPrelude + galaxyZone ); galaxyZone.Contents = new Zone(ItemManager, Settings.PlanetSettings, galaxyZone.PackedContents, galaxyZone, CurrentGalaxy); } @@ -816,6 +934,7 @@ public class ActionGameManager : MonoBehaviour private void StartGame() { + DiscardSimulation(); // a run's Replace never sees simulation records if (CurrentGalaxy != null) { if (PendingScenario != null) StartScenario(); @@ -847,28 +966,27 @@ public class ActionGameManager : MonoBehaviour } // RunStart owns what a new run starts with (docs/scenarios-cut.md, R.4); this enters and binds. The saved run is - // replaced only once the scenario has staged. A start that fails leaves the saved run as it was and says why on + // replaced only once the scenario has staged; a simulation starts beside it and never replaces it. A start that fails leaves the saved run as it was and says why on // the main menu, where Continue still resumes the saved run. private void StartScenario() { var scenario = PendingScenario; PendingScenario = null; var failures = new List(); - RunStart.Staged staged = null; - try + RunSave.Simulation simulation = null; + Func start = () => { - staged = RunSave.Replace(CultCache, () => - { - RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, scenario); - PopulateLevel(CurrentGalaxy.Entrance); - return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, Settings.TutorialGenerationSettings, failures); - }); - } - catch (Exception exception) + RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, scenario); + PopulateLevel(CurrentGalaxy.Entrance); + return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, failures); + }; + var staged = RunStart.Launch(() => { - Debug.LogException(exception); - failures.Add(exception.Message); - } + if (scenario.Saved) return RunSave.Replace(CultCache, start); + var (started, begun) = RunSave.Beside(CultCache, start); + simulation = begun; + return started; + }, failures, Debug.LogException); if (staged == null) { @@ -877,6 +995,7 @@ public class ActionGameManager : MonoBehaviour MainMenu.Refuse($"{scenario.Name} could not start", string.Join("\n", failures)); return; } + Simulation = simulation; Credits = staged.Credits; SectorMap.QueueZoneReveal(CurrentGalaxy.Entrance.AdjacentZones.Prepend(CurrentGalaxy.Entrance)); BindToEntity(staged.Player); @@ -922,7 +1041,7 @@ public class ActionGameManager : MonoBehaviour ZoneRenderer.PerspectiveEntity = DockedEntity; DockingBay = dockingBay; DockCamera.enabled = true; - FollowCamera.enabled = false; + _viewRig.enabled = false; var orbital = (OrbitalEntity) entity; DockCamera.Follow = ZoneRenderer.EntityInstances[orbital].transform; var parentOrbit = Zone.Orbits[orbital.OrbitData].Data.Parent.Key; @@ -1024,7 +1143,6 @@ public class ActionGameManager : MonoBehaviour if(_incomingLockIndicator.indicator != null) _incomingLockIndicator.indicator.GetComponent().ReturnToPool(); _incomingLockIndicator = default; DisablePlayerInput(); - Cursor.lockState = CursorLockMode.None; GameplayUI.gameObject.SetActive(false); foreach(var subscription in _shipSubscriptions) subscription.Dispose(); @@ -1064,6 +1182,8 @@ public class ActionGameManager : MonoBehaviour private void BindToEntity(Entity entity) { + // A tractor held through a ship change would stay on for the ship we leave: its release is a press we will no longer see. + if (CurrentEntity != null) CurrentEntity.Command.Tractor = 0; if (!ZoneRenderer.EntityInstances.ContainsKey(entity)) { Debug.LogError($"Attempted to bind to entity {entity.Name}, but SectorRenderer has no such instance!"); @@ -1071,6 +1191,7 @@ public class ActionGameManager : MonoBehaviour } CurrentEntity = entity; + _tactical.Reset(entity.Zone.Pack.Radius, BaseFollowDistance(entity), DrawAhead.Position(entity, Clock.Lead).xz); DeathPost.weight = 0; ZoneRenderer.PerspectiveEntity = CurrentEntity; @@ -1078,12 +1199,11 @@ public class ActionGameManager : MonoBehaviour DockedEntity = null; DockingBay = null; DockCamera.enabled = false; - FollowCamera.enabled = true; + _viewRig.enabled = true; if (length(CurrentEntity.Direction) > .1f) _viewDirection = float3(CurrentEntity.Direction.x,0,CurrentEntity.Direction.y); - - Cursor.lockState = CursorLockMode.Locked; + EnablePlayerInput(); GameplayUI.gameObject.SetActive(true); ShipPanel.Display(CurrentEntity, true); @@ -1099,8 +1219,7 @@ public class ActionGameManager : MonoBehaviour if (EventLog != null) EventLog.LogMessage(HaulFeed.Line(gain, ItemManager), gain.Adrift > 0 ? Color.yellow : Color.white); })); - FollowCamera.LookAt = ZoneRenderer.EntityInstances[CurrentEntity].LookAtPoint; - FollowCamera.Follow = ZoneRenderer.EntityInstances[CurrentEntity].transform; + FrameFollow(CurrentEntity); _articulationGroups = CurrentEntity.Equipment .Where(item => item.Behaviors.Any(x => x.Data is WeaponData && !(x.Data is LauncherData))) .GroupBy(item => ZoneRenderer.EntityInstances[CurrentEntity] @@ -1208,6 +1327,85 @@ public class ActionGameManager : MonoBehaviour _incomingLockIndicator = (incoming, incoming.GetComponent()); } + private CinemachineFramingTransposer _framingTransposer; + private CinemachineMixingCamera _viewRig; + private CinemachineVirtualCamera _tacticalCamera; + // The grid point the Pan drag holds under the cursor; one gesture's state, nothing else. + private float2? _grab; + private TacticalView _tactical; + private TacticalFade _tacticalFade; + private PostProcessVolume _tacticalVolume; + private Camera _schematicCamera; + + // Flying: a ship under the player's hand, not docked. Everything tactical reads 0 otherwise. + private bool Flying => RunLive && CurrentEntity != null && DockedEntity == null; + + // The one writer of the follow camera's Follow, LookAt and distance for an entity: the distance is + // the hull's reach (from its centre of mass, where Follow sits) times the authored ratio. + private void FrameFollow(Entity entity) + { + var instance = ZoneRenderer.EntityInstances[entity]; + FollowCamera.LookAt = instance.LookAtPoint; + FollowCamera.Follow = instance.transform; + ApplyFraming(entity); + } + + private float BaseFollowDistance(Entity entity) => Settings.FollowCameraDistancePerReach * Contacts.Radius(entity); + + // The one writer of the follow camera's distance: the eased view distance. It asks ZoneRenderer, the one writer of the + // far clip, to see the whole zone from there. + private void ApplyFraming(Entity entity) + { + if (_framingTransposer == null) + _framingTransposer = FollowCamera.GetCinemachineComponent(); + var distance = _tactical.Distance; + _framingTransposer.m_CameraDistance = distance; + ZoneRenderer.FarClipNeeded = distance + 2 * entity.Zone.Pack.Radius; + } + + // The one writer of the tactical camera: three-quarters top-down over the view target on the grid surface, the chase + // view's yaw held, at the eased distance. Its lens is the chase camera's, so the far clip is the one writer's. + private void PoseTactical() + { + var target = _tactical.Target; + var target3 = new Vector3(target.x, DrawAhead.Height(CurrentEntity.Zone, target, Clock.Lead), target.y); + var rotation = Quaternion.Euler(Settings.TacticalPitch, _entityYawPitch.x * Mathf.Rad2Deg, 0); + _tacticalCamera.transform.SetPositionAndRotation(target3 - rotation * Vector3.forward * _tactical.Distance, rotation); + _tacticalCamera.m_Lens = FollowCamera.m_Lens; + } + + // Drag: the grid point under the cursor when the button went down stays under it. + private void PanTarget() + { + if (!Held(Input.Player.Pan)) + { + _grab = null; + return; + } + var height = DrawAhead.Height(CurrentEntity.Zone, _tactical.Target, Clock.Lead); + TryRead(Input.Player.Point, out Vector2 pointer); + var ray = ZoneRenderer.MainCamera.ScreenPointToRay(pointer); + if (!new Plane(Vector3.up, new Vector3(0, height, 0)).Raycast(ray, out var hit)) return; + var point = ray.GetPoint(hit); + var ground = float2(point.x, point.z); + if (_grab is { } grab) _tactical.Pan(grab - ground); + else _grab = ground; + } + + // Everything the tactical view shows is read off the eased camera distance: the fade, the rig's mix, the schematic, the + // map icons' size and the minimap cameras. Time is the Update line that feeds the clock. + private float TacticalBlend() => Flying ? _tactical.Blend(_tactical.Distance) : 0f; + + private void ShowTactical(float blend) + { + _viewRig.SetWeight(0, 1 - blend); + _viewRig.SetWeight(1, blend); + _tacticalVolume.weight = blend; + _schematicCamera.enabled = blend > 0; + ZoneRenderer.Map.SetTacticalScale(blend > 0 ? _tactical.Distance * Settings.TacticalIconSize : 0); + foreach (var camera in ZoneRenderer.MinimapCameras) camera.enabled = blend == 0; + } + private void UpdatePlayerPanel() { ShipPanel.Display(CurrentEntity, true); @@ -1234,7 +1432,8 @@ public class ActionGameManager : MonoBehaviour MainMenu.gameObject.SetActive(true); Menu.gameObject.SetActive(false); CurrentGalaxy = null; - RunSave.Clear(CultCache); + if (Simulation != null) DiscardSimulation(); + else RunSave.Clear(CultCache); SavePlayerSettings(); } @@ -1256,7 +1455,7 @@ public class ActionGameManager : MonoBehaviour var deathTime = Time.time; EndRun(); Observable.EveryUpdate() - .Where(_ => Time.time - deathTime < DeathPostTransitionTime) + .TakeWhile(_ => Time.time - deathTime < DeathPostTransitionTime) .Subscribe(_ => { var t = (Time.time - deathTime) / DeathPostTransitionTime; @@ -1279,7 +1478,11 @@ public class ActionGameManager : MonoBehaviour HypothermiaPost.weight = 0; SevereHypothermiaPost.weight = 0; DeathPost.weight = 1; - }); + // Every run begins in the simulation (ruling terminus-boots-into-ifl), so death anywhere returns to it. + // A New Game or Continue click during the fade has already launched; the scene reload ends the subscription. + if (!MainMenu.Launching) MainMenu.Launch(Scenarios.Simulation); + }) + .AddTo(this); } // public void ToggleEditMode() @@ -1348,6 +1551,18 @@ public class ActionGameManager : MonoBehaviour void Update() { + if (Flying) + { + _tactical.Tick(Time.unscaledDeltaTime); + _tactical.Track(DrawAhead.Position(CurrentEntity, Clock.Lead).xz); + if (_tactical.Tactical) PanTarget(); + else _grab = null; + ApplyFraming(CurrentEntity); + PoseTactical(); + } + var blend = TacticalBlend(); + ShowTactical(blend); + if (!RunLive) return; if(!_paused) { _time += Time.deltaTime; @@ -1368,10 +1583,13 @@ public class ActionGameManager : MonoBehaviour indicator.Value.Place.Target = DrawAhead.Position(indicator.Key, Clock.Lead).ToUnity(); PlaceFill(indicator.Value, indicator.Key); } - var look = Input.Player.Look.ReadValue(); - var sensitivity = PlayerSettings.InputSettings.Sensitivity; - _entityYawPitch = float2(_entityYawPitch.x + look.x * sensitivity.x, clamp(_entityYawPitch.y + look.y * sensitivity.y, -.45f * PI, .45f * PI)); - _viewDirection = mul(float3(0, 0, 1), CultMath.float3x3.Euler(float3(_entityYawPitch.yx, 0), RotationOrder.YXZ)); + // The tactical view does not steer: the aim and the chase yaw hold while the mouse pans the view. + if (TryRead(Input.Player.Look, out Vector2 look)) + { + var sensitivity = PlayerSettings.InputSettings.Sensitivity; + _entityYawPitch = float2(_entityYawPitch.x + look.x * sensitivity.x, clamp(_entityYawPitch.y + look.y * sensitivity.y, -.45f * PI, .45f * PI)); + _viewDirection = mul(float3(0, 0, 1), CultMath.float3x3.Euler(float3(_entityYawPitch.yx, 0), RotationOrder.YXZ)); + } CurrentEntity.Command.Aim = _viewDirection; HeatstrokePost.weight = saturate(unlerp(0, Settings.GameplaySettings.SevereHeatstrokeRiskThreshold, CurrentEntity.Heatstroke)); var severeHeatstrokeLerp = saturate(unlerp(Settings.GameplaySettings.SevereHeatstrokeRiskThreshold, 1, CurrentEntity.Heatstroke)); @@ -1380,13 +1598,14 @@ public class ActionGameManager : MonoBehaviour max(Settings.HeatstrokePhasingFloor, sin(Time.time * Settings.HeatstrokePhasingFrequency)); _faceAimMark.enabled = _helm.Latched; - if(CurrentEntity is Ship ship) + if (CurrentEntity is Ship ship && TryRead(Input.Player.Move, out Vector2 move)) { - ship.Command.Movement = Input.Player.Move.ReadValue().ToCultMath(); - _helm.Held = Input.Player.FaceAim.IsPressed(); - if (Input.Player.Turn.activeControl is { } turnControl) + ship.Command.Movement = move.ToCultMath(); + _helm.Held = Held(Input.Player.FaceAim); + if (ActiveControl(Input.Player.Turn) is { } turnControl) _turnDigital = turnControl.device is UnityEngine.InputSystem.Keyboard; - var turnAxis = _helm.TurnAxis(Input.Player.Turn.ReadValue(), _turnDigital, Time.deltaTime, KeyboardTurnRampTime); + TryRead(Input.Player.Turn, out float turn); + var turnAxis = _helm.TurnAxis(turn, _turnDigital, Time.deltaTime, KeyboardTurnRampTime); ship.Command.Turn = _helm.Demand(_viewDirection.xz, ship.BandedTurn(turnAxis)); } @@ -1402,7 +1621,7 @@ public class ActionGameManager : MonoBehaviour TargetShieldsFill.fillAmount = target.Shield == null ? 0 : lerp(.25f, .75f, target.Shield.Progress); } - CurrentEntity.Command.Tractor = Input.Player.TractorBeam.ReadValue(); + if (!Live(Input.Player.TractorBeam)) CurrentEntity.Command.Tractor = 0; } } // One clock steps the zone, paused or not: a paused frame feeds it no real time. @@ -1410,6 +1629,7 @@ public class ActionGameManager : MonoBehaviour void EnterNewZone() { if (_zoneEntered) { Clock.Reset(); _zoneEntered = false; } } EnterNewZone(); var steppedZone = Zone; + Clock.Rate = _tactical.TimeRate(blend); Clock.Advance(_paused ? 0f : Time.deltaTime, delta => { if (Zone != steppedZone) return; @@ -1499,6 +1719,11 @@ public class ActionGameManager : MonoBehaviour private void LateUpdate() { + // The schematic camera is the game camera's pose and lens, seeing only the map's layer. + var output = ZoneRenderer.MainCamera; + _schematicCamera.fieldOfView = output.fieldOfView; + _schematicCamera.nearClipPlane = output.nearClipPlane; + _schematicCamera.farClipPlane = output.farClipPlane; UpdateTargetIndicators(); } diff --git a/Assets/Scripts/Gameplay/GameSettings.cs b/Assets/Scripts/Gameplay/GameSettings.cs index 9d89c5822..b63a8154e 100644 --- a/Assets/Scripts/Gameplay/GameSettings.cs +++ b/Assets/Scripts/Gameplay/GameSettings.cs @@ -14,6 +14,9 @@ public class GameSettings : ScriptableObject public float HeatstrokePhasingFloor = 0; public float HeatstrokePhasingFrequency = 5; public float WormholeDistanceRatio; + // The follow camera's distance from the hull's centre of mass, as a multiple of the hull's reach + // (Contacts.Radius); 1.5 keeps the Longinus at about 30 m. + public float FollowCameraDistancePerReach = 1.5f; public float DefaultViewDistance; public float[] MinimapZoomLevels; public int DefaultMinimapZoom; @@ -21,9 +24,32 @@ public class GameSettings : ScriptableObject public int AsteroidMeshCount = 5; public float MinimapAsteroidSize = 3; public float MinimapIconSize = 1f / 32; + // Tactical view (rulings tactical-view-distinct-mode, tactical-view-in-runs-slow-time): one wheel notch multiplies the + // camera distance by this, in either view. Every feel constant here (step, band, detent, ease, pitch) is a placeholder + // the operator tunes by eye. + public float TacticalZoomStep = 1.25f; + // The camera distance (m) where the scene starts to fade to the schematic: the chase view's farthest distance and the + // detent band's near edge; and where it is fully faded: the tactical view's nearest distance and the band's far edge. + public float TacticalBlendStart = 250; + public float TacticalBlendEnd = 1000; + // Inside the detent band a notch moves the view this fraction as far as outside it (lower holds harder). + public float DetentResistance = .6f; + // Seconds, e-folding, for the band to push the view back to the edge it came from. + public float DetentRelaxTime = .4f; + // Seconds the camera takes to settle on where the wheel put it (critically damped). + public float ViewEaseTime = .15f; + // The tactical camera's pitch down from the horizon, degrees. + public float TacticalPitch = 55; + // Sim seconds per real second at full fade (about 100x slower). + public float TacticalTimeScale = .01f; + // The farthest zoom, as a multiple of the zone radius. + public float TacticalFitPerRadius = 2; + // Schematic icon size as a fraction of the camera distance. + public float TacticalIconSize = 1f / 40; + // The colour the scene fades toward. + public Color TacticalBackground = new Color(.02f, .03f, .05f, 1); public float PlanetRotationSpeed = 1; - public TutorialGenerationSettings TutorialGenerationSettings; - public SectorBackgroundSettings TutorialBackgroundSettings; + public SectorBackgroundSettings CastBackgroundSettings; public SectorBackgroundSettings SectorBackgroundSettings; public SectorGenerationSettings SectorGenerationSettings; public BodySettingsCollection[] BodySettingsCollections; @@ -43,7 +69,16 @@ public class GameSettings : ScriptableObject [HideInInspector] public Sprite[] WeaponFireTypeIcons; [HideInInspector] public Sprite[] WeaponModifierIcons; - public Sprite GetIcon(HardpointType type) => ItemIcons[(int) type]; + // Every HardpointType has an entry in the asset's ItemIcons; a missing one is named, never an IndexOutOfRange. + public Sprite GetIcon(HardpointType type) => IconOf(ItemIcons, type); + + public static Sprite IconOf(Sprite[] icons, HardpointType type) + { + var index = (int) type; + if (icons == null || index < 0 || index >= icons.Length || icons[index] == null) + throw new InvalidOperationException($"GameSettings.ItemIcons has no sprite for HardpointType.{type} (index {index}, {icons?.Length ?? 0} entries); set it in the Settings asset."); + return icons[index]; + } public Sprite GetIcon(WeaponType type) => WeaponTypeIcons[(int) type]; public Sprite GetIcon(WeaponRange range) => WeaponRangeIcons[(int) range]; public Sprite GetIcon(WeaponCaliber caliber) => WeaponCaliberIcons[(int) caliber]; diff --git a/Assets/Scripts/Gameplay/ShipModShips.cs b/Assets/Scripts/Gameplay/ShipModShips.cs index 89106a6b7..15e9205bb 100644 --- a/Assets/Scripts/Gameplay/ShipModShips.cs +++ b/Assets/Scripts/Gameplay/ShipModShips.cs @@ -6,9 +6,10 @@ using GameCult.Caching; using UnityEngine; using Object = UnityEngine.Object; -// Mod ships in the running game. Compose decides which mod hulls exist; Preload builds a prototype for each, keyed by the -// hull's record key, into an inactive assembled copy that Instantiate clones synchronously, so LoadEntity never loads async. -// A composed hull Preload cannot build is an import fault: Loading faults with ImportFault, naming every such hull's package. +// Mod ships in the running game. Compose (Bind) is the one verdict on whether a mod hull exists, from the package's files; +// Preload only builds a prototype for each, keyed by the hull's record key, into an inactive assembled copy that Instantiate +// clones synchronously, so LoadEntity never loads async. ImportFault reports what the Unity importer made of a composed hull: +// a composed hull Preload cannot build is an import fault: Loading faults with ImportFault, naming every such hull's package. // The prototypes are cache-only: rebuilt every boot from the catalog, the mod GLBs and the template. public static class ShipModShips { @@ -84,10 +85,11 @@ public static class ShipModShips return body; } - // Fills a ShipInstance on the visual's root from its anchors, as ShipModPlan says; the shared effects come from the + // Fills an instance on the visual's root from its anchors, as ShipModPlan says; the shared effects come from the // template. Nothing here decides a slot: the plan does. The schematic lines stay in the prototype but are hidden in - // world; the in-world ship is the GLB. - public static ShipInstance Assemble(ShipModVisual.Instance visual, HullData hull, ShipAuthoring ship, ShipModTemplate template) + // world; the in-world ship is the GLB. A Ship hull gets a ShipInstance and a tractor beam; any other hull (a station) + // gets a plain EntityInstance, because ShipInstance flies (SetEntity and Update read its thrusters) and a station does not. + public static EntityInstance Assemble(ShipModVisual.Instance visual, HullData hull, ShipAuthoring ship, ShipModTemplate template) { var plan = ShipModPlan.Build(hull, ship); var minimap = LayerMask.NameToLayer("Minimap"); @@ -101,6 +103,7 @@ public static class ShipModShips node.name = id; return node; } + // An importer report, not a verdict: Bind has already judged the file. MeshRenderer Renderer(string id) { var found = Node(id).GetComponentInChildren(true); @@ -130,14 +133,17 @@ public static class ShipModShips var surface = AddOrGet(hullNode.gameObject); var shieldMarker = Node(plan.Shield); - var scale = shieldMarker.localScale; - if (!(scale.x > 0 && scale.y > 0 && scale.z > 0)) - throw new InvalidOperationException($"{ship.Id}: the shield anchor scale must have three positive radii."); var shield = Object.Instantiate(template.Shield.GetComponent(), shieldMarker, false); Reset(shield.transform); AddOrGet(shield.gameObject); - var tractor = Object.Instantiate(template.TractorBeam.GetComponent(), Node(plan.Tractor), false); - Reset(tractor.transform); + var isShip = hull.HullType == HullType.Ship; + // The tractor anchor stays required by the plan; a station leaves it unused. + TractorBeam tractor = null; + if (isShip) + { + tractor = Object.Instantiate(template.TractorBeam.GetComponent(), Node(plan.Tractor), false); + Reset(tractor.transform); + } var thrusters = plan.Thrusters.Select(id => { @@ -165,7 +171,7 @@ public static class ShipModShips var lines = visual.Root.transform.Find("Schematic Lines"); if (lines != null) lines.gameObject.SetActive(false); - var instance = AddOrGet(visual.Root); + EntityInstance instance = isShip ? AddOrGet(visual.Root) : AddOrGet(visual.Root); instance.MapIcon = mapIcon; instance.InfluencePrefab = null; instance.PingPrefab = template.Ping.transform; @@ -177,7 +183,7 @@ public static class ShipModShips instance.RadiatorHardpoints = radiators; instance.ArticulationPoints = Array.Empty(); instance.DestroyEffect = template.DestroyEffect; - instance.TractorBeam = tractor; + if (instance is ShipInstance flier) flier.TractorBeam = tractor; return instance; } diff --git a/Assets/Scripts/ServerShared/AetheriaStores.cs b/Assets/Scripts/ServerShared/AetheriaStores.cs index 7c93ba979..9e4084f88 100644 --- a/Assets/Scripts/ServerShared/AetheriaStores.cs +++ b/Assets/Scripts/ServerShared/AetheriaStores.cs @@ -8,7 +8,7 @@ using GameCult.Caching.MessagePack; public static class AetheriaStores { public static readonly Type[] CatalogTypes = { typeof(ItemData), typeof(ShipAuthoring), typeof(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(InputLayout), typeof(Loadout), typeof(FieldKindData), typeof(ProvinceData), typeof(VerseGrammar), typeof(VerseVerb), typeof(StationKindData), typeof(RecipeData), typeof(OutsideMarketData) }; - public static readonly Type[] RunTypes = { typeof(OrbitData), typeof(BodyData), typeof(SavedZone), typeof(SavedGame), typeof(ProvenanceLedger) }; + public static readonly Type[] RunTypes = { typeof(OrbitData), typeof(BodyData), typeof(SavedZone), typeof(SavedGame), typeof(ProvenanceLedger), typeof(HaulOrderData) }; public static readonly Type[] PlayerTypes = { typeof(PlayerSettings) }; // Attaches (hydrates) the catalog read-only unless catalogWritable, then the run and player stores when given. diff --git a/Assets/Scripts/ServerShared/Agents/Minion.cs b/Assets/Scripts/ServerShared/Agents/Minion.cs index c95b7cfbb..5f89892ef 100644 --- a/Assets/Scripts/ServerShared/Agents/Minion.cs +++ b/Assets/Scripts/ServerShared/Agents/Minion.cs @@ -20,6 +20,14 @@ public class Minion : Agent followState.AddTransition(patrolState, () => Task is PatrolOrbitsTask, Patrol); followState.AddTransition(_rootState, () => !(Task is FollowTask)); + // The hauler's task (HaulRun.TaskOf): the same switch as patrol's, ignoring the other task states each walk could reach. + var haulState = new HaulState(this); + _rootState.AddTransition(haulState, () => Task is HaulingTask); + haulState.AddTransition(followState, () => Task is FollowTask, null, true, _rootState); + haulState.AddTransition(_rootState, () => !(Task is HaulingTask), null, true, _rootState, followState); + followState.AddTransition(haulState, () => Task is HaulingTask); + patrolState.AddTransition(haulState, () => Task is HaulingTask, null, true, _rootState, followState); + var combatState = new CombatState(this); _rootState.AddTransition(combatState, () => View.TargetOf(Ship) != null, null, true, _rootState); diff --git a/Assets/Scripts/ServerShared/Agents/States/Haul.cs b/Assets/Scripts/ServerShared/Agents/States/Haul.cs new file mode 100644 index 000000000..30ff78b6d --- /dev/null +++ b/Assets/Scripts/ServerShared/Agents/States/Haul.cs @@ -0,0 +1,23 @@ +// A hauler's pilot: it flies to the orbit of HaulRun.Leg and, within docking distance of a station where the call would move a unit, +// commands the call (HaulRun.Call docks, moves the goods and undocks it, which gives it a fresh pilot on the same task). No field +// but its child: the leg is derived from the hold on every update, so a hand-emptied hold changes it at once. +public class HaulState : BaseState +{ + public HaulState(Agent agent) : base(agent) + { + var move = new MoveToOrbitState(agent); + HaulOrderData Order() => _agent.Task is HaulingTask task ? HaulRun.OrderOf(_agent.ItemManager, task.Order) : null; + OrbitalEntity Station() => HaulRun.Station(_agent.Ship.Zone, move.Orbit); + bool Callable() + { + var order = Order(); + var station = order == null ? null : Station(); + return station != null && move.Distance < _agent.Settings.DockingDistance && HaulRun.CanCall(_agent.Ship, station, order); + } + + Transitions.Add(new StateTransition(move, () => Order() != null, () => move.Orbit = HaulRun.Leg(_agent.Ship, Order()))); + // A changed leg re-enters this state, which points the child at it; a callable station commands the call. + move.Transitions.Add(new StateTransition(this, () => Order() is HaulOrderData order && !HaulRun.Leg(_agent.Ship, order).Equals(move.Orbit), null)); + move.Transitions.Add(new StateTransition(this, Callable, () => _agent.Ship.Command.Call(Station()))); + } +} diff --git a/Assets/Scripts/ServerShared/Agents/States/Haul.cs.meta b/Assets/Scripts/ServerShared/Agents/States/Haul.cs.meta new file mode 100644 index 000000000..434438a7a --- /dev/null +++ b/Assets/Scripts/ServerShared/Agents/States/Haul.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c8eaf78200fa454292cd86bdde3f4903 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Agents/Tasks/HaulingTask.cs b/Assets/Scripts/ServerShared/Agents/Tasks/HaulingTask.cs index e657ef0aa..2dad82b3a 100644 --- a/Assets/Scripts/ServerShared/Agents/Tasks/HaulingTask.cs +++ b/Assets/Scripts/ServerShared/Agents/Tasks/HaulingTask.cs @@ -1,27 +1,16 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ using GameCult.Caching; -using System; -using System.Collections; -using System.Collections.Generic; using MessagePack; using Newtonsoft.Json; +// The order key alone: the leg is HaulRun.Leg's, derived from the hold and the order every update, never stored here. public class HaulingTask : AgentTask { public override TaskType Type => TaskType.Haul; - - [JsonProperty("origin"), Key(4)] - public Entity Origin; - - [JsonProperty("target"), Key(5)] - public Entity Target; - - [JsonProperty("itemType"), Key(6)] - public CultRecordKey ItemType; - - [JsonProperty("quantity"), Key(7)] - public int Quantity; + + [JsonProperty("order"), Key(4)] + public CultRecordKey Order; } diff --git a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs index 300229d3f..5034b6460 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs @@ -200,6 +200,7 @@ public interface IPowerConsumer Union(50, typeof(ListenerData)), Union(51, typeof(ScannerData)), Union(52, typeof(LockWeaponData)), + Union(53, typeof(FacilityData)), JsonObject(MemberSerialization.OptIn)] public abstract class BehaviorData { diff --git a/Assets/Scripts/ServerShared/Behaviors/Facility.cs b/Assets/Scripts/ServerShared/Behaviors/Facility.cs new file mode 100644 index 000000000..e49a7c518 --- /dev/null +++ b/Assets/Scripts/ServerShared/Behaviors/Facility.cs @@ -0,0 +1,60 @@ +using System.Collections.Generic; +using MessagePack; +using Newtonsoft.Json; + +// The facility gear a station carries to run recipes: a GearData of HardpointType Facility whose Behaviors hold one of these. The type +// says where it mounts (a hull's Facility rows), this says it runs recipes. It holds no field of its own: which recipes a facility +// runs is derived from RecipeData.Facility, so no list is stored here. A facility is installed gear, never a consumable's effect. +[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class FacilityData : BehaviorData +{ + public override Behavior CreateInstance(EquippedItem item) + { + return new Facility(this, item); + } + public override Behavior CreateInstance(ConsumableItemEffect item) + { + throw new System.InvalidOperationException($"{item.Data.Name} cannot carry a facility: a facility is installed gear, never a consumable effect."); + } +} + +// The installed facility (ruling demand-consumed-inputs-processed-by-facilities). It ticks once per zone step, from EquippedItem.Update +// while the item is active, and on screen only; an unloaded zone is frozen and the strategic tick (target r3 cut 8) calls the same +// Production.Advance for what is off screen. Its recipes are the run list of its design, fixed for a run because the catalog is. +public class Facility : Behavior +{ + private IReadOnlyList _runList; + private EntityHold _hold; + + // Why the facility advanced no further this step: derived by Advance every step, never stored on the unit. + public Stall Stall { get; private set; } + + // The hold's Revision when an idle facility last failed to take a cycle's inputs. A failed take reads nothing but the hold, so + // until the hold changes a retry fails the same way and is skipped. Not persisted: a restored facility tries once on its first step. + private long _failedAt; + + // How many steps tried to take a cycle's inputs: a diagnostic of the skip above, derived and not persisted. + public int Attempts { get; private set; } + + public Facility(FacilityData data, EquippedItem item) : base(data, item) + { + _runList = Production.RunList(ItemManager.ItemData, Item.EquippableItem.Data.Key); + } + + public override bool Execute(float dt) + { + _hold ??= new EntityHold(Entity); + var idle = Item.EquippableItem.Run == null || Item.EquippableItem.Run.Progress <= 0; + if (idle && Stall == Stall.Inputs && _hold.Revision == _failedAt) return true; + Attempts++; + // A running cycle whose recipe left the catalog or stopped running here is dropped by Advance: the list it was built from is + // stale, so it is rebuilt from the catalog before that step. + if (!idle && Production.Live(ItemManager.ItemData, Item.EquippableItem.Run.Recipe) == null) + _runList = Production.RunList(ItemManager.ItemData, Item.EquippableItem.Data.Key); + var (run, stall) = Production.Advance(ItemManager.ItemData, _runList, Item.EquippableItem.Run, dt, _hold); + Item.EquippableItem.Run = run; + Stall = stall; + if (idle && stall == Stall.Inputs) _failedAt = _hold.Revision; + return true; + } +} diff --git a/Assets/Scripts/ServerShared/Behaviors/Facility.cs.meta b/Assets/Scripts/ServerShared/Behaviors/Facility.cs.meta new file mode 100644 index 000000000..f3f429e8c --- /dev/null +++ b/Assets/Scripts/ServerShared/Behaviors/Facility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a65a21b40f2a4daba2b058018ba5e8d7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Behaviors/ItemUsage.cs b/Assets/Scripts/ServerShared/Behaviors/ItemUsage.cs index e8c5e7dd0..29de67727 100644 --- a/Assets/Scripts/ServerShared/Behaviors/ItemUsage.cs +++ b/Assets/Scripts/ServerShared/Behaviors/ItemUsage.cs @@ -45,10 +45,8 @@ public class ItemUsage : Behavior if (cargo == null) return false; var item = cargo.ItemsOfType[_data.Item.Key][0]; - if (item is SimpleCommodity simpleCommodity) - cargo.Remove(simpleCommodity, 1); - if (item is CraftedItemInstance craftedItemInstance) - cargo.Remove(craftedItemInstance); + // One unit of a stack, or the unit itself. + cargo.Remove(item, 1); return true; } diff --git a/Assets/Scripts/ServerShared/CargoTransfer.cs b/Assets/Scripts/ServerShared/CargoTransfer.cs index 32f49b611..f7d789bcf 100644 --- a/Assets/Scripts/ServerShared/CargoTransfer.cs +++ b/Assets/Scripts/ServerShared/CargoTransfer.cs @@ -23,7 +23,8 @@ public enum GiveEnd public sealed class GiveOrder { public readonly Entity Receiver; - // A commodity order is for any stack of this item's design in the giver's bays; a crafted order is for this instance. + // A stack order is for any stack the item StacksWith in the giver's bays (the same design, and for a compound + // commodity the same lot); a unit order is for this instance. public readonly ItemInstance Item; // Units still to move. public int Remaining { get; internal set; } @@ -99,27 +100,25 @@ public static class CargoTransfer } } - // Where the next unit comes from: the first stack of the order's design in the giver's bays, or the crafted instance. + // Where the next unit comes from: the first stack in the giver's bays the order's item StacksWith, or the unit itself. private static (EquippedCargoBay Bay, ItemInstance Item) Source(Entity giver, GiveOrder order) { foreach (var bay in giver.CargoBays) { - if (order.Item is CraftedItemInstance crafted) + if (order.Item is ICommodityStack wanted) { - if (bay.Cargo.ContainsKey(crafted)) return (bay, crafted); - } - else if (bay.ItemsOfType.TryGetValue(order.Item.Data.Key, out var stacks)) - { - var stack = stacks.OfType().FirstOrDefault(); - if (stack != null) return (bay, stack); + if (bay.ItemsOfType.TryGetValue(order.Item.Data.Key, out var stacks)) + { + var stack = stacks.FirstOrDefault(wanted.StacksWith); + if (stack != null) return (bay, stack); + } } + else if (bay.Cargo.ContainsKey(order.Item)) return (bay, order.Item); } return (null, null); } - // One unit of a commodity, or the crafted item, into the first receiver bay that takes it. + // One unit of a stack, or the unit itself, into the first receiver bay that takes it. private static bool Move(EquippedCargoBay from, ItemInstance item, Entity receiver) => - item is SimpleCommodity commodity - ? receiver.CargoBays.Any(bay => from.TryTransferItem(bay, commodity, 1)) - : receiver.CargoBays.Any(bay => from.TryTransferItem(bay, (CraftedItemInstance) item)); + receiver.CargoBays.Any(bay => from.TryTransferItem(bay, item, 1)); } diff --git a/Assets/Scripts/ServerShared/Corporations.cs b/Assets/Scripts/ServerShared/Corporations.cs index 080f42aac..680436520 100644 --- a/Assets/Scripts/ServerShared/Corporations.cs +++ b/Assets/Scripts/ServerShared/Corporations.cs @@ -49,7 +49,10 @@ public class Faction // Keys 13 to 15 (overworldMusic, combatMusic, bossMusic) held Wwise ids; retired, never reuse them. - // Key 16 is reserved for Relations (operator ruling faction-relations-field). + // How this faction regards each other faction; absent is Neutral. Directed: this map says how this faction regards them, theirs + // says how they regard it. Read only through Entity.Regard (ruling faction-relations-field). + [Inspectable, CultReference(typeof(Faction), many: true), JsonProperty("relations"), Key(16)] + public Dictionary, FactionRelationship> Relations = new Dictionary, FactionRelationship>(); // The faction's rules of engagement; null fights as FactionDoctrine.Default. [Inspectable, JsonProperty("doctrine"), Key(17)] @@ -58,7 +61,7 @@ public class Faction // The maker's final assembly: the distribution every lot of theirs draws its own quality from, and the hard ceiling on each // of its roles (quality-lean-assembly-hard-ceiling). Null is not authored: a lot of theirs assembles at AssemblyDistribution's // defaults. assembly-from-maker derives it once at the part mean plus a tolerance margin (quality-min-tolerance-binned-assembly); - // tune it in Studio after that. Key 16 is reserved for Relations and 18 for Livery. Key 20 was assemblyDeviation (retired); never reuse it. + // tune it in Studio after that. Key 18 is reserved for Livery. Key 20 was assemblyDeviation (retired); never reuse it. [Inspectable, JsonProperty("assembly"), Key(19)] public AssemblyDistribution Assembly; diff --git a/Assets/Scripts/ServerShared/Delaunay.cs b/Assets/Scripts/ServerShared/Delaunay.cs index b6a25bba6..911de658a 100644 --- a/Assets/Scripts/ServerShared/Delaunay.cs +++ b/Assets/Scripts/ServerShared/Delaunay.cs @@ -1,17 +1,33 @@ using System; using System.Collections.Generic; +using System.Numerics; using CultMath; // The Delaunay triangulation of a galaxy's zone positions, as the edges Galaxy links zones along. Bowyer-Watson -// (Bowyer 1981, Watson 1981) in double precision: each point is inserted by removing every triangle whose -// circumcircle holds it and fanning the cavity's boundary to it. Every point lands in the triangulation, so for two or -// more distinct points the edge graph is connected. +// (Bowyer 1981, Watson 1981): each point is inserted by removing every triangle whose circumcircle strictly holds it and +// fanning the cavity's boundary to it. The orientation and in-circle predicates are exact: a double-precision +// determinant answers when it clears its rounding-error bound (Shewchuk 1997), otherwise the determinant is evaluated +// in BigInteger, since every double is a dyadic rational. For two or more distinct points the edge graph is connected: +// collinear points link each to its neighbour along the line; duplicate or non-finite points throw. public static class Delaunay { // Each edge once, as (lower index, higher index), in ascending order. public static List<(int a, int b)> Edges(IReadOnlyList points) { var n = points.Count; + var order = new int[n]; + for (var i = 0; i < n; i++) + { + if (!float.IsFinite(points[i].x) || !float.IsFinite(points[i].y)) + throw new ArgumentException($"Delaunay point {i} is not finite: ({points[i].x}, {points[i].y})"); + order[i] = i; + } + // Lexicographic order runs along any line, and puts equal points side by side. + Array.Sort(order, (i, j) => points[i].x != points[j].x ? points[i].x.CompareTo(points[j].x) : points[i].y.CompareTo(points[j].y)); + for (var i = 1; i < n; i++) + if (points[order[i - 1]].x == points[order[i]].x && points[order[i - 1]].y == points[order[i]].y) + throw new ArgumentException($"Delaunay points {Math.Min(order[i - 1], order[i])} and {Math.Max(order[i - 1], order[i])} are the same point ({points[order[i]].x}, {points[order[i]].y})"); + var x = new double[n + 3]; var y = new double[n + 3]; double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; @@ -25,9 +41,22 @@ public static class Delaunay maxY = Math.Max(maxY, y[i]); } - // A super-triangle far outside the points, so its vertices bend no edge between them; its triangles are - // dropped at the end. - var size = Math.Max(Math.Max(maxX - minX, maxY - minY), 1e-6) * 1000; + var collinear = true; + for (var i = 2; i < n && collinear; i++) + collinear = Orientation(x, y, order[0], order[1], order[i]) == 0; + if (collinear) + { + var line = new List<(int a, int b)>(); + for (var i = 1; i < n; i++) line.Add(Ordered(order[i - 1], order[i])); + line.Sort(); + return line; + } + + // A super-triangle so far outside the points that its vertices bend no edge between them: a float's coordinates + // are multiples of 2^-149, so a triple of distinct non-collinear points has circumradius under extent^3 * 2^300, + // which 2^700 * extent exceeds for any extent a float holds. Its triangles are dropped at the end. Its + // coordinates overflow the double determinants, which then fail every comparison and fall to the exact path. + var size = Math.Max(maxX - minX, maxY - minY) * Math.Pow(2, 700); double midX = (minX + maxX) / 2, midY = (minY + maxY) / 2; x[n] = midX - size; y[n] = midY - size; x[n + 1] = midX + size; y[n + 1] = midY - size; @@ -41,9 +70,7 @@ public static class Delaunay for (var t = triangles.Count - 1; t >= 0; t--) { var triangle = triangles[t]; - var dx = x[p] - triangle.CenterX; - var dy = y[p] - triangle.CenterY; - if (dx * dx + dy * dy >= triangle.RadiusSquared) continue; + if (InCircle(x, y, triangle.A, triangle.B, triangle.C, p) * triangle.Orientation <= 0) continue; Count(cavity, triangle.A, triangle.B); Count(cavity, triangle.B, triangle.C); Count(cavity, triangle.C, triangle.A); @@ -79,19 +106,90 @@ public static class Delaunay private readonly struct Triangle { public readonly int A, B, C; - public readonly double CenterX, CenterY, RadiusSquared; + // +1 if A, B, C run counter-clockwise, -1 if clockwise; a triangle never has zero area. + public readonly int Orientation; public Triangle(int a, int b, int c, double[] x, double[] y) { A = a; B = b; C = c; - double ax = x[a], ay = y[a], bx = x[b], by = y[b], cx = x[c], cy = y[c]; - var d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)); - double a2 = ax * ax + ay * ay, b2 = bx * bx + by * by, c2 = cx * cx + cy * cy; - CenterX = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d; - CenterY = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d; - RadiusSquared = (ax - CenterX) * (ax - CenterX) + (ay - CenterY) * (ay - CenterY); + Orientation = Delaunay.Orientation(x, y, a, b, c); + if (Orientation == 0) throw new InvalidOperationException($"Delaunay built a zero-area triangle on points {a}, {b}, {c}"); + } + } + + // Shewchuk's error bounds for the double-precision determinants: (3 + 16e)e and (10 + 96e)e, e = 2^-53. + private const double OrientationBound = 3.3306690738754716e-16; + private const double InCircleBound = 1.1102230246251577e-15; + + // The sign of the area a, b, c span: +1 counter-clockwise, -1 clockwise, 0 collinear. + private static int Orientation(double[] x, double[] y, int a, int b, int c) + { + var left = (x[a] - x[c]) * (y[b] - y[c]); + var right = (y[a] - y[c]) * (x[b] - x[c]); + var det = left - right; + var bound = OrientationBound * (Math.Abs(left) + Math.Abs(right)); + if (det > bound) return 1; + if (-det > bound) return -1; + var exact = Exact.Of(x, y, a, b, c); + return (exact[0] * exact[3] - exact[1] * exact[2]).Sign; + } + + // The sign of the in-circle determinant: +1 when p is strictly inside the circle through a, b, c taken + // counter-clockwise, -1 strictly outside, 0 on it. + private static int InCircle(double[] x, double[] y, int a, int b, int c, int p) + { + double adx = x[a] - x[p], ady = y[a] - y[p], bdx = x[b] - x[p], bdy = y[b] - y[p], cdx = x[c] - x[p], cdy = y[c] - y[p]; + double abL = adx * bdy, abR = bdx * ady, bcL = bdx * cdy, bcR = cdx * bdy, caL = cdx * ady, caR = adx * cdy; + double alift = adx * adx + ady * ady, blift = bdx * bdx + bdy * bdy, clift = cdx * cdx + cdy * cdy; + var det = alift * (bcL - bcR) + blift * (caL - caR) + clift * (abL - abR); + var permanent = (Math.Abs(bcL) + Math.Abs(bcR)) * alift + (Math.Abs(caL) + Math.Abs(caR)) * blift + (Math.Abs(abL) + Math.Abs(abR)) * clift; + var bound = InCircleBound * permanent; + if (det > bound) return 1; + if (-det > bound) return -1; + var e = Exact.Of(x, y, a, b, c, p); + BigInteger ax = e[0], ay = e[1], bx = e[2], by = e[3], cx = e[4], cy = e[5]; + return (e[6] * (bx * cy - cx * by) + e[7] * (cx * ay - ax * cy) + e[8] * (ax * by - bx * ay)).Sign; + } + + // Coordinates exactly, as integers in units of the smallest binary exponent among them. + private static class Exact + { + // Orientation: [a.x - c.x, a.y - c.y, b.x - c.x, b.y - c.y] with the cross product the caller takes. + public static BigInteger[] Of(double[] x, double[] y, int a, int b, int c) + { + var v = Scaled(new[] { x[a], y[a], x[b], y[b], x[c], y[c] }); + return new[] { v[0] - v[4], v[1] - v[5], v[2] - v[4], v[3] - v[5] }; + } + + // In-circle: [a - p (x, y), b - p, c - p, then each one's squared length]. + public static BigInteger[] Of(double[] x, double[] y, int a, int b, int c, int p) + { + var v = Scaled(new[] { x[a], y[a], x[b], y[b], x[c], y[c], x[p], y[p] }); + BigInteger adx = v[0] - v[6], ady = v[1] - v[7], bdx = v[2] - v[6], bdy = v[3] - v[7], cdx = v[4] - v[6], cdy = v[5] - v[7]; + return new[] { adx, ady, bdx, bdy, cdx, cdy, adx * adx + ady * ady, bdx * bdx + bdy * bdy, cdx * cdx + cdy * cdy }; + } + + private static BigInteger[] Scaled(double[] values) + { + var mantissa = new long[values.Length]; + var exponent = new int[values.Length]; + var lowest = int.MaxValue; + for (var i = 0; i < values.Length; i++) + { + var bits = BitConverter.DoubleToInt64Bits(values[i]); + var biased = (int) ((bits >> 52) & 0x7FF); + var fraction = bits & 0xFFFFFFFFFFFFFL; + mantissa[i] = biased == 0 ? fraction : fraction | (1L << 52); + exponent[i] = biased == 0 ? -1074 : biased - 1075; + if (bits < 0) mantissa[i] = -mantissa[i]; + if (mantissa[i] != 0) lowest = Math.Min(lowest, exponent[i]); + } + var scaled = new BigInteger[values.Length]; + for (var i = 0; i < values.Length; i++) + scaled[i] = mantissa[i] == 0 ? BigInteger.Zero : new BigInteger(mantissa[i]) << (exponent[i] - lowest); + return scaled; } } } diff --git a/Assets/Scripts/ServerShared/DemoPressure.cs b/Assets/Scripts/ServerShared/DemoPressure.cs new file mode 100644 index 000000000..25987b3b2 --- /dev/null +++ b/Assets/Scripts/ServerShared/DemoPressure.cs @@ -0,0 +1,67 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Linq; + +// The demo's pressure curve (aetheria-release, cut demo-pressure-curve): how many hostiles, of what hull tier, a zone of a +// galaxy with a gate antagonist (Galaxy.Antagonist) holds, as a function of its depth toward the gate. The single owner of these numbers; +// ZoneGenerator asks and draws. Pure: no Unity, no cache, no randomness, so the same persisted galaxy yields the same zone. +public static class DemoPressure +{ + // Depth at or below which a zone carries no hostiles. Depth is e / (e + x), the share of the way from the entrance to the + // gate a zone sits at, so a quarter covers the entrance, its neighbours, and on a short galaxy the first jump out. + public const float GraceDepth = 0.25f; + + // Hostiles at the gate (its ring, besides the boss), the most the curve ever asks for. + public const int MaxHostiles = 6; + + // Tier is depth raised to this power: above 1 keeps heavy hulls rare until the last stretch. + public const float TierExponent = 2f; + + public readonly struct Pressure + { + public readonly int Hostiles; + // 0..1: the antagonist's ship hulls up to this quantile of cost may be drawn. + public readonly float Tier; + public Pressure(int hostiles, float tier) { Hostiles = hostiles; Tier = tier; } + } + + // e / (e + x) for e = jumps from the entrance and x = jumps to the exit: 0 only at the entrance, 1 only at the gate, from + // the persisted Entrance and Exit alone. On a shortest entrance-exit path it is the share of the way travelled; a zone + // behind the entrance rises slowly with its distance from it rather than sitting at 0. + public static float Depth(Galaxy galaxy, GalaxyZone zone) + { + float e = galaxy.Entrance.Distance[zone], x = galaxy.Exit.Distance[zone]; + return e + x == 0 ? 0f : e / (e + x); + } + + // The entrance and this many jumps around it are quiet whatever the galaxy's depth scale, so a short galaxy's first + // neighbours are no deeper than the grace. + public const int GraceJumps = 1; + + // No antagonist ship, station or turret holds a zone in grace. + public static bool InGrace(Galaxy galaxy, GalaxyZone zone) => + galaxy.Entrance.Distance[zone] <= GraceJumps || Depth(galaxy, zone) <= GraceDepth; + + // What the zone holds: the curve at its depth, none in grace. + public static Pressure Of(Galaxy galaxy, GalaxyZone zone) => + InGrace(galaxy, zone) ? new Pressure(0, At(Depth(galaxy, zone)).Tier) : At(Depth(galaxy, zone)); + + public static Pressure At(float depth) + { + depth = Math.Clamp(depth, 0f, 1f); + var ramp = Math.Clamp((depth - GraceDepth) / (1f - GraceDepth), 0f, 1f); + var smooth = ramp * ramp * (3f - 2f * ramp); + return new Pressure((int)MathF.Round(MaxHostiles * smooth), MathF.Pow(depth, TierExponent)); + } + + // The dearest hull price the tier admits: the price at that quantile of the hulls offered, cheapest first. Never below the + // cheapest hull offered, so the draw is never empty while any hull is offered. + public static int PriceCeiling(int[] offeredPrices, float tier) + { + var sorted = offeredPrices.OrderBy(price => price).ToArray(); + return sorted[(int)MathF.Round(Math.Clamp(tier, 0f, 1f) * (sorted.Length - 1))]; + } +} diff --git a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs.meta b/Assets/Scripts/ServerShared/DemoPressure.cs.meta similarity index 83% rename from Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs.meta rename to Assets/Scripts/ServerShared/DemoPressure.cs.meta index 3f7c8777a..df1cf5708 100644 --- a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs.meta +++ b/Assets/Scripts/ServerShared/DemoPressure.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 94d688b37c5044dd9b67865c706d8918 +guid: 7c1e9a40d3b84f26a5e08b19f6d2c371 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/Scripts/ServerShared/DrawAhead.cs b/Assets/Scripts/ServerShared/DrawAhead.cs index a5d4736c5..a1d389083 100644 --- a/Assets/Scripts/ServerShared/DrawAhead.cs +++ b/Assets/Scripts/ServerShared/DrawAhead.cs @@ -106,7 +106,7 @@ public static class DrawAhead } public static BeltDraw DrawListOf(AsteroidBelt belt, PlanetSettings settings, IReadOnlyList meshes, System.Func radius, int keep, CultRecordKey beltKey) => - new(Enumerable.Range(0, belt.Data.Asteroids.Length).Select(i => belt.UndamagedSize(i, settings)).ToArray(), meshes, radius, keep, beltKey.Value); + new(Enumerable.Range(0, belt.Data.Asteroids.Length).Select(i => belt.UndamagedSize(i, settings)).ToArray(), meshes, radius, keep, belt.Data.SiteOr(beltKey)); // A ship in a wormhole animation has its pose scripted by the step, not integrated from Velocity and TurnRate, // so it is drawn where the step put it: extrapolating a scripted pose draws a streak that resets every step. diff --git a/Assets/Scripts/ServerShared/EconomyBalance.cs b/Assets/Scripts/ServerShared/EconomyBalance.cs new file mode 100644 index 000000000..0b513dd04 --- /dev/null +++ b/Assets/Scripts/ServerShared/EconomyBalance.cs @@ -0,0 +1,193 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; + +// One recipe read as a chain link. Wage is the implied credits per worker-second at the authored prices; null when the link +// is unpriced (an input, any filler of a role, or the output at Price 0) or has no labour. Cost is the derived cost of one output unit. +public sealed class BalanceLink +{ + public string Output, Name, StationKind; + public double Labour, Price, Cost; + public double? Wage; + public double? WageRatio; + // Why Wage is null: "output" (the output is at Price 0), "input" (an input, upkeep or role filler is at Price 0), "labour" (no labour); + // null when priced. The first that applies, in that order. + public string Unpriced; +} + +// One ore a kind of belt holds: its share of the kind's abundance, its extraction link's wage over the median, its price and cost. +public sealed class BeltYield +{ + public string Ore; + public double Share, Price, Cost; + public double? WageRatio; +} + +public sealed class BeltRow +{ + public string Kind; + public List Yields = new List(); + public double Price, Cost; +} + +public sealed class BalanceReport +{ + public double WageReference; + public List Links; + public List Faults; + public List Belts; +} + +// The static economy balance: a steady-state input-output reading of the chain (Leontief 1936; Sraffa 1960 zero-profit prices under +// one wage; Samuelson 1951: with labour the only primary factor the cheapest filler of a role is demand-independent; Lewis 1954: the +// extraction sector sets the going wage). Pure: reads the catalog, writes nothing. ItemData.Price stays the one price the game charges; +// for a made good it is the price Prices derives, which economy author writes. Balance's faults are report-only. +public static class EconomyBalance +{ + public const string HMargin = "H-margin", HWage = "H-wage", HConverge = "H-converge"; + private const int SweepCap = 10000, SettleWindow = 100; + + // The stored price a derived price becomes: whole credits, at least 1. + public static int Rounded(double derived) => (int) Math.Max(1, Math.Round(derived, MidpointRounding.AwayFromZero)); + + // The words for goods whose price does not settle. + public static string Unsettled(CultCache catalog, IEnumerable keys) => + $"No price settles within {SweepCap} sweeps: these goods sit on a cycle of recipes whose requirements do not shrink: " + + string.Join(", ", keys.Select(k => catalog.Get(new CultRecordKey(k))?.Name ?? k)); + + private static double Price(CultCache catalog, string key) => catalog.Get(new CultRecordKey(key))?.Price ?? 0; + + // Authored-price wage per link; the cheapest filler fills a role, and a role with any filler at Price 0 leaves the link unpriced. + private static List Links(CultCache catalog, List columns) + { + double? CheapestPriced(string[] fillers) => fillers.Length == 0 || fillers.Any(f => Price(catalog, f) <= 0) ? (double?) null : fillers.Min(f => Price(catalog, f)); + var links = new List(); + foreach (var c in columns) + { + var link = new BalanceLink { Output = c.Output, Name = catalog.Get(c.Recipe.Output)?.Name ?? c.Output, Labour = c.Labour, Price = Price(catalog, c.Output), StationKind = catalog.Get(c.Recipe.StationKind)?.Name ?? "no kind" }; + var cost = 0.0; + var inputsPriced = true; + foreach (var (commodity, count) in c.Inputs.Concat(c.Upkeep)) + { + if (count <= 0) continue; + var p = Price(catalog, commodity); + if (p <= 0) inputsPriced = false; + cost += count * p; + } + foreach (var slot in c.Slots) + { + if (slot.Count <= 0) continue; + var p = CheapestPriced(slot.Fillers); + if (p == null) inputsPriced = false; + else cost += slot.Count * p.Value; + } + link.Unpriced = link.Price <= 0 ? "output" : !inputsPriced ? "input" : c.Labour <= 0 ? "labour" : null; + if (link.Unpriced == null) link.Wage = (c.OutputCount * link.Price - cost) / c.Labour; + links.Add(link); + } + return links; + } + + // The going wage: the median implied wage of the priced raw links, 0 when none is priced. + private static double RawWage(CultCache catalog, List columns, List links) + { + var wages = links.Where((l, i) => l.Wage.HasValue && columns[i].IsCommodity && Recipes.IsRaw(catalog, columns[i].Recipe)).Select(l => l.Wage.Value).OrderBy(w => w).ToList(); + return wages.Count == 0 ? 0 : wages.Count % 2 == 1 ? wages[wages.Count / 2] : (wages[wages.Count / 2 - 1] + wages[wages.Count / 2]) / 2; + } + + public static double Wage(CultCache catalog) + { + var columns = EconomyChecks.Columns(catalog); + return RawWage(catalog, columns, Links(catalog, columns)); + } + + // Value iteration from zero over every recipe at one wage. A good in fixedOutputs, or with no recipe, holds its authored price. + // Two recipes for one output: the cheaper sets its price, as a role takes its cheapest filler. + private static Dictionary Sweep(CultCache catalog, List columns, double wage, ISet fixedOutputs, out List unsettled) + { + var derived = new Dictionary(StringComparer.Ordinal); + foreach (var c in columns) if (!fixedOutputs.Contains(c.Output)) derived[c.Output] = 0; + double Cost(string key) => derived.TryGetValue(key, out var v) ? v : Price(catalog, key); + var converged = false; + // The last sweep each good moved in: a cycle can move one good per sweep, so the last sweep alone would name half of it. + var lastMoved = new Dictionary(StringComparer.Ordinal); + for (var sweep = 0; sweep < SweepCap && !converged; sweep++) + { + converged = true; + var best = new Dictionary(StringComparer.Ordinal); + foreach (var c in columns.Where(c => !fixedOutputs.Contains(c.Output))) + { + var sum = wage * c.Labour; + foreach (var (commodity, count) in c.Inputs.Concat(c.Upkeep)) if (count > 0) sum += count * Cost(commodity); + foreach (var slot in c.Slots) + if (slot.Count > 0 && slot.Fillers.Length > 0) sum += slot.Count * slot.Fillers.Min(Cost); + var next = sum / c.OutputCount; + if (!best.TryGetValue(c.Output, out var held) || next < held) best[c.Output] = next; + } + foreach (var (output, next) in best) + { + // A price that is not a finite number is not settled, however little it moved. + if (!double.IsFinite(next) || Math.Abs(next - derived[output]) > 1e-12 * Math.Max(1, Math.Abs(next))) { converged = false; lastMoved[output] = sweep; } + derived[output] = next; + } + } + unsettled = converged ? new List() : lastMoved.Where(p => p.Value >= SweepCap - SettleWindow).Select(p => p.Key).OrderBy(k => k, StringComparer.Ordinal).ToList(); + return derived; + } + + // The price of every made good (an output whose recipe is not raw) at the going wage: its inputs, upkeep and cheapest + // role fillers at their prices, plus the wage times its labour, over its output count. A design with a recipe is a made good + // priced like a commodity; raw goods and designs with no recipe keep their authored price. Unsettled names the goods still moving + // when the sweep gave up: a cycle of recipes whose requirements do not shrink has no price, so none of the values are a price. + public static Dictionary Prices(CultCache catalog, out List unsettled) + { + var columns = EconomyChecks.Columns(catalog); + var raw = new HashSet(columns.Where(c => Recipes.IsRaw(catalog, c.Recipe)).Select(c => c.Output), StringComparer.Ordinal); + var derived = Sweep(catalog, columns, RawWage(catalog, columns, Links(catalog, columns)), raw, out unsettled); + return columns.Where(c => !raw.Contains(c.Output)).Select(c => c.Output).Distinct(StringComparer.Ordinal) + .ToDictionary(key => key, key => derived[key], StringComparer.Ordinal); + } + + public static BalanceReport Balance(CultCache catalog, double wageSpread = 2) + { + var columns = EconomyChecks.Columns(catalog); + var links = Links(catalog, columns); + var reference = RawWage(catalog, columns, links); + foreach (var l in links) l.WageRatio = reference > 0 ? l.Wage / reference : null; + + // Derived cost: nothing fixed, so an ore costs its labour; belt rows show price minus cost, the rent. + var derived = Sweep(catalog, columns, reference, new HashSet(), out var unsettled); + var converged = unsettled.Count == 0; + double Cost(string key) => derived.TryGetValue(key, out var v) ? v : Price(catalog, key); + foreach (var l in links) l.Cost = derived[l.Output]; + + var faults = new List(); + if (!converged) faults.Add(new EconomyFault(HConverge, "(chain)", $"Derived cost did not settle within {SweepCap} sweeps.")); + foreach (var l in links.Where(l => l.Wage.HasValue)) + { + if (l.Wage.Value <= 0) + faults.Add(new EconomyFault(HMargin, l.Output, $"{l.Name} sells at or below its inputs: implied wage {l.Wage.Value:0.#####} per worker-second.")); + else if (reference > 0 && (l.Wage.Value < reference / wageSpread || l.Wage.Value > reference * wageSpread)) + faults.Add(new EconomyFault(HWage, l.Output, $"{l.Name}: implied wage {l.Wage.Value:0.#####} is {l.WageRatio:0.##}x the median {reference:0.#####}, outside the spread of {wageSpread:0.##}.")); + } + + var belts = new List(); + foreach (var kind in catalog.GetAll().OrderBy(k => k.Name, StringComparer.Ordinal)) + { + var row = new BeltRow { Kind = kind.Name }; + var total = kind.Yields.Where(y => y.Abundance > 0).Sum(y => (double) y.Abundance); + foreach (var y in kind.Yields.Where(y => y.Abundance > 0 && total > 0)) + { + var ore = y.Commodity.Key.Value; + var share = y.Abundance / total; + var yield = new BeltYield { Ore = ore, Share = share, Price = Price(catalog, ore), Cost = Cost(ore), WageRatio = links.FirstOrDefault(l => l.Output == ore)?.WageRatio }; + row.Price += share * yield.Price; + row.Cost += share * yield.Cost; + row.Yields.Add(yield); + } + belts.Add(row); + } + return new BalanceReport { WageReference = reference, Links = links, Faults = faults, Belts = belts }; + } +} diff --git a/Assets/Scripts/ServerShared/EconomyChecks.cs b/Assets/Scripts/ServerShared/EconomyChecks.cs index 75de68f57..13b72d1c3 100644 --- a/Assets/Scripts/ServerShared/EconomyChecks.cs +++ b/Assets/Scripts/ServerShared/EconomyChecks.cs @@ -56,13 +56,16 @@ public sealed class EconomyReport // The one owner of the catalog's economy invariants. Pure: draws nothing, reads no clock, writes nothing. One method per rule. public static class EconomyChecks { - public const string LRecipe = "L-recipe", LOneKindList = "L-one-kind-list", LLore = "L-lore", LSource = "L-source-sink", LProductive = "L-productive", LDemand = "L-consumer-demand"; + public const string LRecipe = "L-recipe", LOneKindList = "L-one-kind-list", LLore = "L-lore", LSource = "L-source-sink", LProductive = "L-productive", LDemand = "L-consumer-demand", LWeights = "L-weights", LShape = "L-shape", LPrice = "L-price", LFacility = "L-facility"; private const double Margin = 1e-9; public static EconomyReport Check(CultCache catalog, EconomyLoad load = null) { var faults = new List(); faults.AddRange(Recipe(catalog)); + faults.AddRange(Shapes(catalog)); + faults.AddRange(PriceCheck(catalog)); + faults.AddRange(Weights(catalog)); faults.AddRange(Lore(catalog)); faults.AddRange(SourceSink(catalog)); faults.AddRange(Productive(catalog, load)); @@ -85,7 +88,7 @@ public static class EconomyChecks : new RecipeData { Output = recipe.Output, OutputCount = recipe.OutputCount, Cycle = recipe.Cycle, Workforce = recipe.Workforce, - StationKind = recipe.StationKind, LoreHook = recipe.LoreHook, + StationKind = recipe.StationKind, Facility = recipe.Facility, LoreHook = recipe.LoreHook, Inputs = (recipe.Inputs ?? new List()).Where(c => c != null).ToList(), Upkeep = (recipe.Upkeep ?? new List()).Where(c => c != null).ToList(), Fills = (recipe.Fills ?? new List()).Where(f => f != null).ToList(), @@ -93,7 +96,7 @@ public static class EconomyChecks }; // The designs some faction offers, but a Station or Turret hull, distinct and ordered by key: the designs that need a recipe. - private static List OfferedDesigns(CultCache catalog) + public static List OfferedDesigns(CultCache catalog) { var designs = new Dictionary(StringComparer.Ordinal); foreach (var product in catalog.GetAll().Where(p => LoadoutGenerator.IsOffered(catalog, p))) @@ -113,6 +116,75 @@ public static class EconomyChecks private static IEnumerable Commodities(CultCache catalog) => catalog.GetAll().Where(Recipes.IsCommodity).OrderBy(item => catalog.RefOf(item).Key.Value, StringComparer.Ordinal); + // Ore geography is weighted draws: a field kind's generation weight and abundances, a province's card count and its kind and ore + // weights are finite and not negative, and every yield, kind weight and province ore names a record this catalog holds. A weight of + // zero is legal (never drawn); a negative or NaN weight corrupts the weighted pick. + public static List Weights(CultCache catalog) + { + var faults = new List(); + void Weight(string record, string field, double value) + { + if (!double.IsFinite(value) || value < 0) faults.Add(new EconomyFault(LWeights, record, $"{field} is {value}, not a finite number from zero up.")); + } + void Names(string record, string field, CultRecordRef reference) where T : class + { + if (catalog.Get(reference) == null) faults.Add(new EconomyFault(LWeights, record, $"{field} names no record this catalog holds.")); + } + foreach (var kind in catalog.GetAll().OrderBy(k => catalog.RefOf(k).Key.Value, StringComparer.Ordinal)) + { + var key = catalog.RefOf(kind).Key.Value; + Weight(key, "GenerationWeight", kind.GenerationWeight); + for (var i = 0; i < (kind.Yields?.Count ?? 0); i++) + { + Weight(key, $"Yields[{i}].Abundance", kind.Yields[i].Abundance); + Names(key, $"Yields[{i}].Commodity", kind.Yields[i].Commodity); + } + } + foreach (var province in catalog.GetAll().OrderBy(p => catalog.RefOf(p).Key.Value, StringComparer.Ordinal)) + { + var key = catalog.RefOf(province).Key.Value; + Weight(key, "GenerationWeight", province.GenerationWeight); + for (var i = 0; i < (province.Kinds?.Count ?? 0); i++) + { + Weight(key, $"Kinds[{i}].Weight", province.Kinds[i].Weight); + Names(key, $"Kinds[{i}].Kind", province.Kinds[i].Kind); + } + for (var i = 0; i < (province.Ores?.Count ?? 0); i++) + { + Weight(key, $"Ores[{i}].Weight", province.Ores[i].Weight); + Names(key, $"Ores[{i}].Commodity", province.Ores[i].Commodity); + } + } + return faults; + } + + // Every commodity holds a Shape with at least one cell: a cargo bay reads it to store the good, and a commodity without one cannot be held. + public static List Shapes(CultCache catalog) => + Commodities(catalog).Where(item => item.Shape?.Coordinates == null || item.Shape.Coordinates.Length == 0) + .Select(item => new EconomyFault(LShape, catalog.RefOf(item).Key.Value, $"Commodity '{item.Name}' has no Shape cell: a cargo bay cannot hold it.")).ToList(); + + // A made good's Price (a commodity, or a design with a recipe) is the price EconomyBalance derives from its chain, rounded to whole credits (at least 1); economy author + // writes it, and a stored price off it is drift (an inspector edit) that the next author run repairs. + public static List PriceCheck(CultCache catalog) + { + var faults = new List(); + var prices = EconomyBalance.Prices(catalog, out var unsettled); + if (unsettled.Count > 0) + { + faults.Add(new EconomyFault(LPrice, unsettled[0], EconomyBalance.Unsettled(catalog, unsettled))); + return faults; + } + foreach (var (key, derived) in prices.OrderBy(p => p.Key, StringComparer.Ordinal)) + { + var item = catalog.Get(new CultRecordKey(key)); + if (item == null) continue; + var want = EconomyBalance.Rounded(derived); + if (item.Price != want) + faults.Add(new EconomyFault(LPrice, key, $"'{item.Name}' is priced {item.Price}; its chain derives {want}.")); + } + return faults; + } + // Every commodity and every offered design (but a Station or Turret hull) has a recipe, and each recipe is well formed. public static List Recipe(CultCache catalog) { @@ -131,6 +203,9 @@ public static class EconomyChecks else if (market.Rows.Contains(null)) Add(marketKey, "Rows holds a null entry."); } var kindsPlaced = new HashSet(catalog.GetAll().SelectMany(f => StationKinds.KindsOf(catalog, f)).Select(k => k.Key.Value), StringComparer.Ordinal); + var kindsInOrder = catalog.GetAll().Select(kind => (Key: catalog.RefOf(kind).Key.Value, Kind: kind)).OrderBy(pair => pair.Key, StringComparer.Ordinal).ToList(); + var facilitiesListed = new HashSet(kindsInOrder.SelectMany(pair => pair.Kind.Facilities ?? new List>()).Select(f => f.Key.Value), StringComparer.Ordinal); + void NoFacility(string record, string message) => faults.Add(new EconomyFault(LFacility, record, message)); foreach (var (key, stored) in StoredRecipes(catalog)) { var recipe = Sound(stored); @@ -158,6 +233,16 @@ public static class EconomyChecks if (kind == null) Add(key, "StationKind names no station kind this catalog holds."); else if (!kindsPlaced.Contains(recipe.StationKind.Key.Value)) faults.Add(new EconomyFault(LOneKindList, key, $"No faction places station kind '{kind.Name}', so nothing can run this recipe.")); + var facility = catalog.Get(recipe.Facility); + if (!recipe.Facility.IsSet()) NoFacility(key, "Facility is unset; a recipe names the facility gear that runs it."); + else if (facility == null) NoFacility(key, $"Facility '{recipe.Facility.Key.Value}' names no item this catalog holds."); + else if (!StationKinds.IsRecipeFacility(facility)) NoFacility(key, $"Facility '{facility.Name}' is not a recipe facility (gear of hardpoint type Facility holding a FacilityData)."); + else + { + if (!facilitiesListed.Contains(recipe.Facility.Key.Value)) NoFacility(key, $"No station kind lists facility '{facility.Name}' in its Facilities, so no station is fitted to run this recipe."); + if (kind != null && !(kind.Facilities ?? new List>()).Any(listed => listed.Key.Equals(recipe.Facility.Key))) + NoFacility(key, $"Station kind '{kind.Name}' does not list facility '{facility.Name}' in its Facilities; the recipe's kind and facility must agree."); + } var roles = Recipes.RolesOf(output); if (!Recipes.IsCommodity(output)) { @@ -173,6 +258,19 @@ public static class EconomyChecks if (Recipes.Fillers(catalog, role.Name).Length == 0) Add(key, $"Role '{role.Name}' has no commodity whose recipe fills it."); } } + foreach (var (kindKey, kind) in kindsInOrder) + for (var i = 0; i < (kind.Facilities?.Count ?? 0); i++) + { + var listed = kind.Facilities[i]; + var item = catalog.Get(listed); + if (!listed.IsSet()) NoFacility(kindKey, $"Station kind '{kind.Name}' Facilities[{i}] is unset."); + else if (item == null) NoFacility(kindKey, $"Station kind '{kind.Name}' Facilities[{i}] names no item this catalog holds."); + else if (!StationKinds.IsRecipeFacility(item) && !(item is SiloData)) NoFacility(kindKey, $"Station kind '{kind.Name}' Facilities[{i}] '{item.Name}' is not a recipe facility or a silo."); + } + foreach (var gear in catalog.GetAll().Select(gear => (Key: catalog.RefOf(gear).Key.Value, Gear: gear)).OrderBy(pair => pair.Key, StringComparer.Ordinal)) + if (gear.Gear.Behaviors != null && gear.Gear.Behaviors.Any(behavior => behavior is FacilityData) && gear.Gear.HardpointType != HardpointType.Facility) + NoFacility(gear.Key, $"'{gear.Gear.Name}' holds a FacilityData but is hardpoint type {gear.Gear.HardpointType}; a recipe facility mounts on a Facility row."); + foreach (var line in StationKinds.FacilityRoomFaults(catalog)) NoFacility("station-facilities", line); return faults; } @@ -272,6 +370,35 @@ public static class EconomyChecks return deepest + 1; } + // One recipe's consumption per cycle, unscaled: the one reader of what a recipe takes, for Productive's matrix and EconomyBalance. + // Labour is Workforce x Cycle worker-seconds; Slots are the role slots (a role recipe's design roles, or the recipe's RoleInputs) + // with every commodity that fills the role. + internal sealed class Column + { + public string Output; + public RecipeData Recipe; + public bool IsCommodity; + public int OutputCount; + public double Labour; + public List<(string Commodity, int Count)> Inputs; + public List<(string Commodity, int Count)> Upkeep; + public List<(string Role, int Count, string[] Fillers)> Slots; + } + + // Every recipe whose output exists, produces something and has a finite cycle, ordered by output key. + internal static List Columns(CultCache catalog) => + AllRecipes(catalog).Where(p => catalog.Get(p.Recipe.Output) != null && p.Recipe.OutputCount > 0 && float.IsFinite(p.Recipe.Cycle)).Select(p => new Column + { + Output = p.Recipe.Output.Key.Value, + Recipe = p.Recipe, + IsCommodity = Recipes.IsCommodity(catalog.Get(p.Recipe.Output)), + OutputCount = p.Recipe.OutputCount, + Labour = p.Recipe.Workforce * (double) p.Recipe.Cycle, + Inputs = p.Recipe.Inputs.Select(i => (i.Commodity.Key.Value, i.Count)).ToList(), + Upkeep = p.Recipe.Upkeep.Select(i => (i.Commodity.Key.Value, i.Count)).ToList(), + Slots = Recipes.RoleInputsOf(catalog, p.Recipe).Select(r => (r.Name, r.Count, Recipes.Fillers(catalog, r.Name).Select(k => k.Value).ToArray())).ToList() + }).ToList(); + // Hawkins-Simon over commodities plus one labour good, at the worst single filler of every role slot (a recipe's role inputs): the spectral radius // of the requirements matrix stays below one however the roles are filled. The worst fill is the spectral simplex // (Nesterov and Protasov 2013) on the matrix nudged strictly positive, then the radius of the chosen matrix is taken exactly. @@ -280,8 +407,8 @@ public static class EconomyChecks load = load ?? new EconomyLoad(); if (!(load.InputFactor >= 1) || !(load.WorkforceFactor >= 1) || !(load.UpkeepFactor >= 1)) throw new ArgumentException("Setting factors are at least 1.", nameof(load)); - var columns = AllRecipes(catalog).Where(p => Recipes.IsCommodity(catalog.Get(p.Recipe.Output)) && p.Recipe.OutputCount > 0 && float.IsFinite(p.Recipe.Cycle)).ToList(); - var names = columns.Select(p => p.Recipe.Output.Key.Value).ToList(); + var columns = Columns(catalog).Where(c => c.IsCommodity).ToList(); + var names = columns.Select(c => c.Output).ToList(); var index = new Dictionary(StringComparer.Ordinal); for (var i = 0; i < names.Count; i++) index[names[i]] = i; var n = names.Count + 1; @@ -290,16 +417,16 @@ public static class EconomyChecks var slots = new List<(int Column, double Amount, int[] Fillers)>(); for (var j = 0; j < columns.Count; j++) { - var recipe = columns[j].Recipe; - foreach (var input in recipe.Inputs) - if (index.TryGetValue(input.Commodity.Key.Value, out var row) && input.Count > 0) fixedTerms[row, j] += input.Count * load.InputFactor / recipe.OutputCount; - foreach (var upkeep in recipe.Upkeep) - if (index.TryGetValue(upkeep.Commodity.Key.Value, out var row) && upkeep.Count > 0) fixedTerms[row, j] += upkeep.Count * load.UpkeepFactor / recipe.OutputCount; - fixedTerms[labour, j] = recipe.Workforce * (double) recipe.Cycle * load.WorkforceFactor / recipe.OutputCount; - foreach (var role in Recipes.RoleInputsOf(catalog, recipe)) + var column = columns[j]; + foreach (var input in column.Inputs) + if (index.TryGetValue(input.Commodity, out var row) && input.Count > 0) fixedTerms[row, j] += input.Count * load.InputFactor / column.OutputCount; + foreach (var upkeep in column.Upkeep) + if (index.TryGetValue(upkeep.Commodity, out var row) && upkeep.Count > 0) fixedTerms[row, j] += upkeep.Count * load.UpkeepFactor / column.OutputCount; + fixedTerms[labour, j] = column.Labour * load.WorkforceFactor / column.OutputCount; + foreach (var slot in column.Slots) { - var fillers = Recipes.Fillers(catalog, role.Name).Where(k => index.ContainsKey(k.Value)).Select(k => index[k.Value]).ToArray(); - if (fillers.Length > 0 && role.Count > 0) slots.Add((j, role.Count * load.InputFactor / recipe.OutputCount, fillers)); + var fillers = slot.Fillers.Where(k => index.ContainsKey(k)).Select(k => index[k]).ToArray(); + if (fillers.Length > 0 && slot.Count > 0) slots.Add((j, slot.Count * load.InputFactor / column.OutputCount, fillers)); } } foreach (var need in load.LabourNeeds) diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index b520db17d..1da2d7ade 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -22,6 +22,10 @@ public abstract class Entity public Faction Faction; // The mark of a zone's boss, written only by ZoneGenerator and restored from the pack. RunGoal reads it. public bool IsBoss; + // The standing haul order this ship carries for (aetheria-living-world:ruling:transit-depots-buy-for-onward-haul): its task is derived from + // it at admission (HaulRun.TaskOf). Interim actor state (target r3, L-actors), deleted with EntityPack Key 24 when offices + // issue haul acts (follow-up haul-run-to-offices). + public CultRecordRef Haul; public EquippableItem Hull; public EquippedItem EquippedHull; @@ -51,6 +55,11 @@ public abstract class Entity public readonly ReactiveCollection Equipment = new ReactiveCollection(); public readonly ReactiveCollection CargoBays = new ReactiveCollection(); + // The one counter of what the entity's bays hold: it moves on every change to any bay's contents and on every bay seated or removed, + // and never returns to a value it had. Not persisted. A holder that remembers the value it last read learns whether anything it could + // hold changed since, without comparing the contents. + public long CargoRevision { get; private set; } + internal void CargoChanged() => CargoRevision++; public readonly ReactiveCollection DockingBays = new ReactiveCollection(); public readonly ReactiveCollection VisibleEntities = new ReactiveCollection(); // The cache of IsHostileTo for each zone entity: written only by RefreshStance, refreshed each Update. @@ -551,7 +560,7 @@ public abstract class Entity foreach (var candidate in _targetCandidates) if (candidate.Target.Chunk is ChunkId chunk && ChunkVisible(chunk)) into.Add(chunk); - into.Sort(ByIndexThenField); + into.Sort(ByIndexThenSite); } // The one search every chunk question asks the zone's targeting index: from here, as far as the longest range @@ -737,8 +746,12 @@ public abstract class Entity } private readonly List _targetCandidates = new List(); - private static readonly Comparison ByIndexThenField = (a, b) => - a.Index != b.Index ? a.Index.CompareTo(b.Index) : a.Field.GetHashCode().CompareTo(b.Field.GetHashCode()); + private int ByIndexThenSite(ChunkId a, ChunkId b) + { + if (a.Index != b.Index) return a.Index.CompareTo(b.Index); + var bySite = string.CompareOrdinal(Zone.AsteroidBelts[a.Field].Data.SiteOr(a.Field), Zone.AsteroidBelts[b.Field].Data.SiteOr(b.Field)); + return bySite != 0 ? bySite : string.CompareOrdinal(a.Field.Value, b.Field.Value); + } // The planar distance per unit of visibility beyond which no target can pass ChunkVisible's threshold: an upper // bound, never a decision. ChunkInfo is saturate(sum_i v s_i c_i(angle) / d / (n k)), linear in v and falling as @@ -1261,13 +1274,15 @@ public abstract class Entity // This observer's stance toward `other`: its own override, else its belief. Allies (the observer's own non-null faction) are // known by datalink; any other contact is believed by the telemetry received with its track, and unknown (never hostile) - // without it. In a zone owned by a faction a contact is hostile when its claimed faction is the owner's and the owner does - // not permit its presence, or when this is the owner's ship and believes the contact trespasses. + // without it. A contact whose claimed faction this observer's faction Hates is hostile in any zone, owned or not; Hostile to + // Beloved govern presence instead. In a zone owned by a faction a contact is hostile when its claimed faction is the owner's and + // the owner does not permit its presence, or when this is the owner's ship and believes the contact trespasses. public bool IsHostileTo(Entity other) { if (_iffOverrides.TryGetValue(other, out var overrideHostile)) return overrideHostile; if (Faction != null && other.Faction == Faction) return false; if (!_telemetry.TryGetValue(other, out var claimed)) return false; + if (Regard(Faction, claimed) == FactionRelationship.Hated) return true; var owner = Zone.GalaxyZone.Owner; if (owner == null) return false; return (claimed == owner && !(PresencePermitted?.Value ?? true)) || (Faction == owner && BelievesTrespassing(other)); @@ -1300,14 +1315,27 @@ public abstract class Entity return false; } - // TODO: Inter-faction relationships + // How `faction` regards this entity's faction. public FactionRelationship GetFactionRelationship(Faction faction) { if (faction == null) return FactionRelationship.Neutral; if (this is Ship {IsPlayerShip: true}) return Zone.Galaxy.FactionRelationships[faction]; - return faction == Faction ? FactionRelationship.Beloved : FactionRelationship.Neutral; + return Regard(faction, Faction); + } + + // The one reader of Faction.Relations: how `regarding` regards `regarded`. Unset either side is Neutral, a faction regards + // itself Beloved, and absent from the map is Neutral. A faction the catalog does not hold has no key and is Neutral. + private FactionRelationship Regard(Faction regarding, Faction regarded) + { + if (regarding == null || regarded == null) return FactionRelationship.Neutral; + if (regarding == regarded) return FactionRelationship.Beloved; + if (regarding.Relations == null || regarding.Relations.Count == 0) return FactionRelationship.Neutral; + var key = ItemManager.ItemData.TryGetHandle(regarded)?.Key; + return key != null && regarding.Relations.TryGetValue(new CultRecordRef(key.Value), out var relationship) + ? relationship + : FactionRelationship.Neutral; } public static bool IsPresencePermitted(FactionRelationship relationship, SecurityLevel securityLevel) => @@ -1429,19 +1457,7 @@ public abstract class Entity Temperature[position.x, position.y] += heat / ThermalMass[position.x, position.y]; } - public int CountItemsInCargo(CultRecordKey itemDataID) - { - int sum = 0; - foreach (var x in CargoBays) - { - if (x.ItemsOfType.ContainsKey(itemDataID)) - { - foreach (var i in x.ItemsOfType[itemDataID]) sum += i is SimpleCommodity simpleCommodity ? simpleCommodity.Quantity : 1; - } - } - - return sum; - } + public int CountItemsInCargo(CultRecordKey itemDataID) => CargoBays.Sum(bay => bay.Count(itemDataID)); public EquippedCargoBay FindItemInCargo(CultRecordKey itemDataID) { @@ -1484,6 +1500,7 @@ public abstract class Entity } CargoBays.Remove(cargoBay); + CargoChanged(); } Equipment.Remove(item); @@ -1545,9 +1562,8 @@ public abstract class Entity } else { - hardpoint = HardpointAt(itemData, hullData, hullCoord, moving); + hardpoint = HardpointAt(itemData, hullData, hullCoord, item.Rotation, moving); if (hardpoint == null) return false; - item.Rotation = hardpoint.Rotation; } return true; @@ -1560,10 +1576,12 @@ public abstract class Entity // The one placement rule for hardpoint gear. At this origin the item lies within a hardpoint of its type, turned to // that hardpoint's rotation (HardpointData.TakesAt, the fit rule); its own cells are free, since a hardpoint's // leftover cells may hold general gear (operator, 2026-09-30: "saving slots in a hardpoint can be a valid tradeoff - // for crowded ships"); and that hardpoint holds no other hardpoint item, since it holds one at most. - private HardpointData HardpointAt(EquippableItemData itemData, HullData hullData, int2 hullCoord, EquippedItem moving) + // for crowded ships"); and that hardpoint holds no other hardpoint item, since it holds one at most. Where several hardpoints accept the origin, the + // one whose rotation equals the item's own (saved) rotation is preferred, so reload seats gear where it was; an item whose + // rotation names none of them takes the first (stable order). + private HardpointData HardpointAt(EquippableItemData itemData, HullData hullData, int2 hullCoord, ItemRotation seated, EquippedItem moving) { - foreach (var hardpoint in hullData.Hardpoints) + foreach (var hardpoint in hullData.Hardpoints.OrderBy(h => h.Rotation == seated ? 0 : 1)) { if (!hardpoint.TakesAt(itemData, hullCoord - hardpoint.Position)) continue; var ownCellsFree = itemData.Shape.Coordinates @@ -1580,14 +1598,22 @@ public abstract class Entity // Check whether the given item will fit when its origin is placed at the given coordinate on the hull. An item that // is already equipped here is judged without its own cells, so a gun can be moved within its own hardpoint; // TryEquip stays strict (it never sees an item as its own occupant), so equipping an equipped item twice is refused. - public bool ItemFits(EquippableItem item, int2 hullCoord) + public bool ItemFits(EquippableItem item, int2 hullCoord) => ItemFits(item, hullCoord, out _); + + // As above, and reports the rotation TryEquip would seat the item at: its hardpoint's for hardpoint gear, otherwise + // its own. A probe never writes item.Rotation; TryEquip is the only seat. + public bool ItemFits(EquippableItem item, int2 hullCoord, out ItemRotation seated) { + seated = item.Rotation; // Don't allow equipping while deployed if (_active) return false; var itemData = ItemManager.GetData(item); var hullData = ItemManager.GetData(Hull) as HullData; - return ItemFits(itemData, hullData, item, hullCoord, out _, Equipment.FirstOrDefault(e => e.EquippableItem == item)); + if (!ItemFits(itemData, hullData, item, hullCoord, out var hardpoint, Equipment.FirstOrDefault(e => e.EquippableItem == item))) + return false; + seated = hardpoint?.Rotation ?? item.Rotation; + return true; } public bool TryFindSpace(EquippableItem item, out int2 hullCoord) @@ -1660,29 +1686,31 @@ public abstract class Entity var hullData = ItemManager.GetData(Hull) as HullData; if (!ItemFits(itemData, hullData, item, hullCoord, out var hardpoint)) return false; - + // The one seat of hardpoint gear's rotation, before EquippedItem's ctor reads it. + if (hardpoint != null) item.Rotation = hardpoint.Rotation; + + // A bay is decided by its type before its hardpoint: a docking bay or cargo bay, a silo among them, is a bay whether it + // sits free (Tool) or on a row (a silo on its Facility row); then Tool gear, then hardpoint gear. EquippedItem equippedItem; - if (itemData.HardpointType == HardpointType.Tool) + if (itemData is CargoBayData) { - if(itemData is CargoBayData) + if (itemData is DockingBayData) { - if (itemData is DockingBayData) - { - equippedItem = new EquippedDockingBay(ItemManager, item, hullCoord, this, $"{Name} Docking Bay {DockingBays.Count + 1}"); - DockingBays.Add((EquippedDockingBay) equippedItem); - } - else - { - equippedItem = new EquippedCargoBay(ItemManager, item, hullCoord, this, $"{Name} Cargo Bay {CargoBays.Count + 1}"); - CargoBays.Add((EquippedCargoBay) equippedItem); - } + equippedItem = new EquippedDockingBay(ItemManager, item, hullCoord, this, $"{Name} Docking Bay {DockingBays.Count + 1}"); + DockingBays.Add((EquippedDockingBay) equippedItem); } else { - equippedItem = new EquippedItem(ItemManager, item, hullCoord, this, null); - Equipment.Add(equippedItem); + equippedItem = new EquippedCargoBay(ItemManager, item, hullCoord, this, $"{Name} Cargo Bay {CargoBays.Count + 1}", hardpoint); + CargoBays.Add((EquippedCargoBay) equippedItem); + CargoChanged(); } } + else if (itemData.HardpointType == HardpointType.Tool) + { + equippedItem = new EquippedItem(ItemManager, item, hullCoord, this, null); + Equipment.Add(equippedItem); + } else { equippedItem = new EquippedItem(ItemManager, item, hullCoord, this, hardpoint); @@ -1737,7 +1765,7 @@ public abstract class Entity return bay; } - public bool TryUndock(Ship ship) + public bool TryUndock(Ship ship, bool piloted = false) { var bay = DockingBays.FirstOrDefault(x => x.DockedShip == ship); if (bay == null) @@ -1751,7 +1779,7 @@ public abstract class Entity bay.DockedShip = null; ship.RemoveParent(); - Zone.Admit(ship, piloted: false); + Zone.Admit(ship, piloted); return true; } @@ -2418,7 +2446,7 @@ public class EquippedCargoBay : EquippedItem } } - public EquippedCargoBay(ItemManager itemManager, EquippableItem item, int2 position, Entity entity, string name) : base(itemManager, item, position, entity, null) + public EquippedCargoBay(ItemManager itemManager, EquippableItem item, int2 position, Entity entity, string name, HardpointData hardpoint = null) : base(itemManager, item, position, entity, hardpoint) { Data = ItemManager.GetData(EquippableItem) as CargoBayData; Name = name; @@ -2432,6 +2460,8 @@ public class EquippedCargoBay : EquippedItem // Check whether the given item will fit when its origin is placed at the given coordinate public bool ItemFits(ItemInstance item, int2 cargoCoord) { + // A silo holds bulk only: gear, consumables and crafted sales never land in it. + if (Data is SiloData && !(item is ICommodityStack)) return false; var itemData = ItemManager.GetData(item); // Check every cell of the item's shape foreach (var i in itemData.Shape.Coordinates) @@ -2446,38 +2476,39 @@ public class EquippedCargoBay : EquippedItem public bool TryFindSpace(ItemInstance item) { - if (item is SimpleCommodity simpleCommodity) - return TryFindSpace(simpleCommodity, out _); + if (item is ICommodityStack) + return TryFindStackSpace(item, out _); if (item is CraftedItemInstance craftedItem) - return TryFindSpace(craftedItem, out _); + return TryFindUnitSpace(craftedItem, out _); return false; } - // Tries to find a place to put the given items in the inventory - // Will attempt to fill existing item stacks first - // Returns true only when ALL of the items have places to go - public bool TryFindSpace(SimpleCommodity item, out List positions) + // Tries to find a place to put the given stack in the inventory + // Will attempt to fill existing stacks it StacksWith first + // Returns true only when ALL of the units have places to go + private bool TryFindStackSpace(ItemInstance item, out List positions) { positions = new List(); - var itemData = ItemManager.GetData(item); - var remainingQuantity = item.Quantity; - - // For simple commodities, search for existing item stacks to add to + var stack = (ICommodityStack) item; + var maxStack = ItemManager.MaxStack(item); + var remainingQuantity = stack.Quantity; + + // Search for existing stacks to add to foreach (var cargoItem in Cargo.Keys) { - if (!item.Data.Key.Equals(cargoItem.Data.Key) || item.Lot != cargoItem.Lot) continue; - - var cargoCommodity = (SimpleCommodity) cargoItem; - if (cargoCommodity.Quantity >= itemData.MaxStack) continue; - + if (!stack.StacksWith(cargoItem)) continue; + + var held = (ICommodityStack) cargoItem; + if (held.Quantity >= maxStack) continue; + // Subtract remaining space in existing stack from remaining quantity - remainingQuantity -= min(itemData.MaxStack - cargoCommodity.Quantity, remainingQuantity); + remainingQuantity -= min(maxStack - held.Quantity, remainingQuantity); positions.Add(Cargo[cargoItem]); - + // If we've moved all of the items into existing stacks, no need to search for empty space! if (remainingQuantity == 0) return true; } - + // TODO: Try alternate item rotations / use Shape.FitsWithin // Search all the space in the cargo bay for an empty space where the item fits foreach (var cargoCoord in Data.InteriorShape.Coordinates) @@ -2493,7 +2524,7 @@ public class EquippedCargoBay : EquippedItem } // Searches the cargo bay for a position where the item will fit, returns true when found - public bool TryFindSpace(CraftedItemInstance item, out int2 position) + private bool TryFindUnitSpace(CraftedItemInstance item, out int2 position) { // Search all the space in the cargo bay for an empty space where the item fits foreach (var cargoCoord in Data.InteriorShape.Coordinates) @@ -2508,48 +2539,50 @@ public class EquippedCargoBay : EquippedItem position = int2.zero; return false; } - + public bool TryStore(ItemInstance item) { - if (item is SimpleCommodity simpleCommodity) - return TryStore(simpleCommodity); + if (item is ICommodityStack) + return TryStoreStack(item); if (item is CraftedItemInstance craftedItem) - return TryStore(craftedItem); + return TryStoreUnit(craftedItem); return false; } public bool TryStore(ItemInstance item, int2 cargoCoord) { - if (item is SimpleCommodity simpleCommodity) - return TryStore(simpleCommodity, cargoCoord); + if (item is ICommodityStack) + return TryStoreStack(item, cargoCoord); if (item is CraftedItemInstance craftedItem) - return TryStore(craftedItem, cargoCoord); + return TryStoreUnit(craftedItem, cargoCoord); return false; } - // Attempts to store all of the given item anywhere in the inventory - // Will attempt to fill existing item stacks first - // Returns true only when ALL of the items are successfully stored - public bool TryStore(SimpleCommodity item) + // Attempts to store all of the given stack anywhere in the inventory + // Will attempt to fill existing stacks first + // Returns true only when ALL of the units are successfully stored + private bool TryStoreStack(ItemInstance item) { - if (!TryFindSpace(item, out var positions)) return false; + if (!TryFindStackSpace(item, out var positions)) return false; foreach (var position in positions) { - if (TryStore(item, position)) return true; + if (TryStoreStack(item, position)) return true; } return false; } - // Try to store the given commodity at the given position - // If there's a stack at the given position it will be added to - // Returns true only when ALL of the items are successfully stored + // Try to store the given stack at the given position + // If there's a stack it StacksWith at the given position it will be added to + // Returns true only when ALL of the units are successfully stored // The bay decides what quantity may sit in it: a stack below one unit or above its design's MaxStack is refused with // the bay as it was, so no caller, loot, pickup or restore has to check for it. - public bool TryStore(SimpleCommodity item, int2 cargoCoord) + private bool TryStoreStack(ItemInstance item, int2 cargoCoord) { + var stack = (ICommodityStack) item; var itemData = ItemManager.GetData(item); - if (item.Quantity < 1 || item.Quantity > itemData.MaxStack) return false; + var maxStack = ItemManager.MaxStack(item); + if (stack.Quantity < 1 || stack.Quantity > maxStack) return false; if (ItemFits(item, cargoCoord)) { foreach (var p in itemData.Shape.Coordinates) @@ -2558,43 +2591,45 @@ public class EquippedCargoBay : EquippedItem Occupancy[pos.x, pos.y] = item; } Cargo[item] = cargoCoord; - + Entity.CargoChanged(); + if(!ItemsOfType.ContainsKey(item.Data.Key)) ItemsOfType[item.Data.Key] = new List(); ItemsOfType[item.Data.Key].Add(item); } - else if (Occupancy[cargoCoord.x, cargoCoord.y] is SimpleCommodity cargoCommodity && cargoCommodity.Data.Key.Equals(item.Data.Key) && cargoCommodity.Lot == item.Lot) + else if (Occupancy[cargoCoord.x, cargoCoord.y] is ICommodityStack held && stack.StacksWith(Occupancy[cargoCoord.x, cargoCoord.y])) { - if (cargoCommodity.Quantity + item.Quantity <= itemData.MaxStack) + Entity.CargoChanged(); + if (held.Quantity + stack.Quantity <= maxStack) { - cargoCommodity.Quantity += item.Quantity; + held.Quantity += stack.Quantity; } else { - var quantityTransferred = itemData.MaxStack - cargoCommodity.Quantity; - item.Quantity -= quantityTransferred; - cargoCommodity.Quantity = itemData.MaxStack; - + var quantityTransferred = maxStack - held.Quantity; + stack.Quantity -= quantityTransferred; + held.Quantity = maxStack; + Mass += itemData.Mass * quantityTransferred; ThermalMass += itemData.Mass * itemData.SpecificHeat * quantityTransferred; return false; } } else return false; - + Mass += ItemManager.GetMass(item); ThermalMass += ItemManager.GetThermalMass(item); return true; } // Try to store the given item anywhere it will fit, returns true when the item was successfully stored - public bool TryStore(CraftedItemInstance item) => TryFindSpace(item, out var position) && TryStore(item, position); + private bool TryStoreUnit(CraftedItemInstance item) => TryFindUnitSpace(item, out var position) && TryStoreUnit(item, position); // Try to store the given item at the given position, returns true when the item was successfully stored - public bool TryStore(CraftedItemInstance item, int2 cargoCoord) + private bool TryStoreUnit(CraftedItemInstance item, int2 cargoCoord) { if (!ItemFits(item, cargoCoord)) return false; - + var itemData = ItemManager.GetData(item); foreach (var p in itemData.Shape.Coordinates) { @@ -2602,19 +2637,55 @@ public class EquippedCargoBay : EquippedItem Occupancy[pos.x, pos.y] = item; } Cargo[item] = cargoCoord; - + Entity.CargoChanged(); + if(!ItemsOfType.ContainsKey(item.Data.Key)) ItemsOfType[item.Data.Key] = new List(); ItemsOfType[item.Data.Key].Add(item); - + Mass += ItemManager.GetMass(item); ThermalMass += ItemManager.GetThermalMass(item); return true; } - // The part removed: null, with the bay as it was, when the item is not here or the quantity is below one unit. - public SimpleCommodity Remove(SimpleCommodity item, int quantity) + // The units of a design in the bay: a stack counts its Quantity, any other item one. The one reader of how many + // units a bay holds; Entity.CountItemsInCargo and the trade menu's Owned column derive from it. + public int Count(CultRecordKey design) => + ItemsOfType.TryGetValue(design, out var items) ? items.Sum(i => i is ICommodityStack stack ? stack.Quantity : 1) : 0; + + // Pours each stack into an earlier stack (InteriorShape.Coordinates order) it StacksWith that has room, through + // Remove and TryStore, so Mass and ThermalMass conserve and the merge rule stays StacksWith's. Emptied stacks leave. + // Run once after a restore: a saved bay may hold fragments that were stored before the bay merged them. + public void Consolidate() + { + var stacks = new List(); + foreach (var coordinate in Data.InteriorShape.Coordinates) + if (Occupancy[coordinate.x, coordinate.y] is ICommodityStack && !stacks.Contains(Occupancy[coordinate.x, coordinate.y])) + stacks.Add(Occupancy[coordinate.x, coordinate.y]); + + for (var later = 1; later < stacks.Count; later++) + { + var from = stacks[later]; + for (var earlier = 0; earlier < later && Cargo.ContainsKey(from); earlier++) + { + var into = stacks[earlier]; + if (!Cargo.ContainsKey(into) || !((ICommodityStack) into).StacksWith(from)) continue; + var room = ItemManager.MaxStack(into) - ((ICommodityStack) into).Quantity; + if (room < 1) continue; + + var origin = Cargo[from]; + var part = Remove(from, Math.Min(room, ((ICommodityStack) from).Quantity)); + // Whole or nothing: the part fits the room it was sized to, and a refusal puts it back where it was. + if (!TryStore(part, Cargo[into])) TryStore(part, origin); + } + } + } + + // The part removed: null, with the bay as it was, when the item is not here or the quantity is below one unit. A + // stack gives up `quantity` units through its own Split (the stack itself, whole, when it holds no more); a unit + // leaves whole for any quantity of one or more. + public ItemInstance Remove(ItemInstance item, int quantity) { if (quantity < 1) return null; if (!Cargo.ContainsKey(item)) @@ -2622,60 +2693,48 @@ public class EquippedCargoBay : EquippedItem ItemManager.Log("Attempted to remove item from a cargo bay that it wasn't even in! Something went wrong here!"); return null; } - var itemData = ItemManager.GetData(item); - if(quantity >= item.Quantity) + if (item is ICommodityStack stack && quantity < stack.Quantity) { - foreach(var v in Data.InteriorShape.Coordinates) - if (Occupancy[v.x, v.y] == item) - Occupancy[v.x, v.y] = null; - - Cargo.Remove(item); - ItemsOfType[item.Data.Key].Remove(item); - if (!ItemsOfType[item.Data.Key].Any()) - ItemsOfType.Remove(item.Data.Key); - - Mass -= ItemManager.GetMass(item); - ThermalMass -= ItemManager.GetThermalMass(item); - - return item; + var itemData = ItemManager.GetData(item); + Entity.CargoChanged(); + stack.Quantity -= quantity; + Mass -= itemData.Mass * quantity; + ThermalMass -= itemData.Mass * itemData.SpecificHeat * quantity; + return stack.Split(quantity); } - item.Quantity -= quantity; - Mass -= itemData.Mass * quantity; - ThermalMass -= itemData.Mass * itemData.SpecificHeat * quantity; - return new SimpleCommodity{Data = item.Data, Lot = item.Lot, Quantity = quantity, Rotation = item.Rotation}; - } - - public void Remove(CraftedItemInstance item) - { - if (!Cargo.ContainsKey(item)) - { - ItemManager.Log("Attempted to remove item from a cargo bay that it wasn't even in! Something went wrong here!"); - return; - } - var itemData = ItemManager.GetData(item); - foreach(var v in Data.InteriorShape.Coordinates) - if (Occupancy[v.x, v.y] == item) - Occupancy[v.x, v.y] = null; - - Cargo.Remove(item); - ItemsOfType[item.Data.Key].Remove(item); - if (!ItemsOfType[item.Data.Key].Any()) - ItemsOfType.Remove(item.Data.Key); - - Mass -= ItemManager.GetMass(item); - ThermalMass -= ItemManager.GetThermalMass(item); + RemoveWhole(item); + return item; } public void Remove(ItemInstance item) { - if (item is SimpleCommodity simpleCommodity) - Remove(simpleCommodity, simpleCommodity.Quantity); - if (item is CraftedItemInstance craftedItem) - Remove(craftedItem); + if (item is ICommodityStack stack) + Remove(item, stack.Quantity); + else if (item is CraftedItemInstance) + Remove(item, 1); } - - public bool TryTransferItem(EquippedCargoBay target, SimpleCommodity item, int quantity) + + // The item, with everything it holds, leaves the bay: the one place a cell is freed. + private void RemoveWhole(ItemInstance item) + { + Entity.CargoChanged(); + foreach(var v in Data.InteriorShape.Coordinates) + if (Occupancy[v.x, v.y] == item) + Occupancy[v.x, v.y] = null; + + Cargo.Remove(item); + ItemsOfType[item.Data.Key].Remove(item); + if (!ItemsOfType[item.Data.Key].Any()) + ItemsOfType.Remove(item.Data.Key); + + Mass -= ItemManager.GetMass(item); + ThermalMass -= ItemManager.GetThermalMass(item); + } + + // Moves `quantity` units of a stack, or the one unit, to the target bay. The part goes across, never the stack left + // behind; whole or nothing: a refusal puts the part back where it came from. + public bool TryTransferItem(EquippedCargoBay target, ItemInstance item, int quantity) { if (quantity < 1) return false; if (!Cargo.ContainsKey(item)) @@ -2684,25 +2743,15 @@ public class EquippedCargoBay : EquippedItem return false; } - var oldPos = Cargo[item]; - var newItem = Remove(item, quantity); - - // The part removed goes across, never the stack left behind. - if (target.TryStore(newItem)) return true; - - // Whole or nothing: TryStore takes all of the part or none of it, so a refusal puts the part back where it came from. - TryStore(newItem, oldPos); - return false; - } - - public bool TryTransferItem(EquippedCargoBay target, CraftedItemInstance item) - { - if (!Cargo.ContainsKey(item)) + if (item is ICommodityStack) { - ItemManager.Log("Attempted to remove item from a cargo bay that it wasn't even in! Something went wrong here!"); + var oldPos = Cargo[item]; + var part = Remove(item, quantity); + if (target.TryStore(part)) return true; + TryStore(part, oldPos); return false; } - + if (!target.TryStore(item)) return false; Remove(item); return true; diff --git a/Assets/Scripts/ServerShared/EntitySerializer.cs b/Assets/Scripts/ServerShared/EntitySerializer.cs index 73656b87e..ad820e839 100644 --- a/Assets/Scripts/ServerShared/EntitySerializer.cs +++ b/Assets/Scripts/ServerShared/EntitySerializer.cs @@ -30,6 +30,7 @@ public static class EntitySerializer pack.Settings = entity.Settings; pack.Boss = entity.IsBoss; + pack.Haul = entity.Haul; pack.Hull = entity.Hull; pack.Name = entity.Name; @@ -54,38 +55,38 @@ public static class EntitySerializer // first MaxStack units go back where it was and the rest is returned to be placed by SpillOversize once every stack // has its own cell, so a spill cannot take a cell a later stack was saved in. private static void RestoreStack(ItemManager itemManager, EquippedCargoBay bay, int2 position, ItemInstance item, - List<(EquippedCargoBay home, SimpleCommodity rest)> spill) + List<(EquippedCargoBay home, ItemInstance rest)> spill) { - if (item is SimpleCommodity commodity && commodity.Quantity > itemManager.GetData(commodity).MaxStack - && itemManager.GetData(commodity).MaxStack >= 1) + if (item is ICommodityStack stack && stack.Quantity > itemManager.MaxStack(item) && itemManager.MaxStack(item) >= 1) { - var maxStack = itemManager.GetData(commodity).MaxStack; - var first = new SimpleCommodity { Data = commodity.Data, Lot = commodity.Lot, Rotation = commodity.Rotation, Quantity = maxStack }; - var rest = new SimpleCommodity { Data = commodity.Data, Lot = commodity.Lot, Rotation = commodity.Rotation, Quantity = commodity.Quantity - maxStack }; - if (!bay.TryStore(first, position)) rest.Quantity += first.Quantity; + var maxStack = itemManager.MaxStack(item); + var first = stack.Split(maxStack); + var rest = stack.Split(stack.Quantity - maxStack); + if (!bay.TryStore(first, position)) ((ICommodityStack) rest).Quantity += maxStack; spill.Add((bay, rest)); return; } if (bay.TryStore(item, position)) return; - var quantity = item is SimpleCommodity c ? $" x{c.Quantity}" : ""; + var quantity = item is ICommodityStack c ? $" x{c.Quantity}" : ""; itemManager.Log($"Dropped a saved item the bay refused at {position}: {itemManager.GetData(item).Name}{quantity}"); } // Places the units an oversize saved stack left over, in stacks of at most MaxStack: the stack's own bay first, then // the entity's other bays. Only the units that fit nowhere are dropped, logged with their design and quantity. private static void SpillOversize(ItemManager itemManager, IReadOnlyList bays, - List<(EquippedCargoBay home, SimpleCommodity rest)> spill) + List<(EquippedCargoBay home, ItemInstance rest)> spill) { foreach (var (home, rest) in spill) { - var maxStack = itemManager.GetData(rest).MaxStack; - var remaining = rest.Quantity; + var maxStack = itemManager.MaxStack(rest); + var remaining = ((ICommodityStack) rest).Quantity; while (remaining > 0) { - var chunk = new SimpleCommodity { Data = rest.Data, Lot = rest.Lot, Rotation = rest.Rotation, Quantity = Math.Min(remaining, maxStack) }; + var chunk = ((ICommodityStack) rest).Split(Math.Min(remaining, maxStack)); + var chunkStack = (ICommodityStack) chunk; var placed = home.TryStore(chunk) || bays.Where(b => b != home).Any(b => b.TryStore(chunk)); // A refused store may still have topped up a stack; what is left in the chunk found no room. - remaining -= Math.Min(remaining, maxStack) - (placed ? 0 : chunk.Quantity); + remaining -= Math.Min(remaining, maxStack) - (placed ? 0 : chunkStack.Quantity); if (placed) continue; itemManager.Log($"Dropped saved units no bay has room for: {itemManager.GetData(rest).Name} x{remaining}"); break; @@ -130,6 +131,7 @@ public static class EntitySerializer { entity.Name = pack.Name; entity.IsBoss = pack.Boss; + entity.Haul = pack.Haul; entity.Faction = itemManager.ItemData.Get(pack.Faction); entity.Children = pack.Children.Select(c => { @@ -147,7 +149,7 @@ public static class EntitySerializer entity.DockingBays[i].DockedShip = entity.Children[pack.DockingBayAssignments[i]] as Ship; } - var spill = new List<(EquippedCargoBay home, SimpleCommodity rest)>(); + var spill = new List<(EquippedCargoBay home, ItemInstance rest)>(); for (var bayIndex = 0; bayIndex < pack.CargoContents.Length; bayIndex++) if(entity.CargoBays.Count >= bayIndex + 1) foreach (var (position, item) in pack.CargoContents[bayIndex]) @@ -158,7 +160,10 @@ public static class EntitySerializer foreach (var (position, item) in pack.DockingBayContents[bayIndex]) RestoreStack(itemManager, entity.DockingBays[bayIndex], position, item, spill); - SpillOversize(itemManager, entity.CargoBays.Cast().Concat(entity.DockingBays).ToList(), spill); + var bays = entity.CargoBays.Cast().Concat(entity.DockingBays).ToList(); + SpillOversize(itemManager, bays, spill); + // Fragments saved before the bay merged them, and the parts a spill placed, fold into the stacks that take them. + foreach (var bay in bays) bay.Consolidate(); entity.Temperature = pack.Temperature; @@ -240,8 +245,9 @@ public abstract class EntityPack [Key(14)] public EntitySettings Settings; [Key(15)] public CultRecordRef Faction; [Key(16)] public int[][] WeaponGroups; - // Keys 17-20 belong to the subclasses; the base's next free key is 23 (Boss is 21, the orbital pack's Kind is 22). + // Keys 17-20 belong to the subclasses; the base's next free key is 25 (Id is 23, Haul is 24, Boss is 21, the orbital pack's Kind is 22). [Key(21)] public bool Boss; + [Key(24)] public CultRecordRef Haul; private int _price; @@ -273,10 +279,7 @@ public abstract class EntityPack foreach (var (_, item) in t) { var itemData = itemManager.GetData(item); - if (item is SimpleCommodity s) - _price += itemData.Price * s.Quantity; - else - _price += itemData.Price; + _price += item is ICommodityStack s ? itemData.Price * s.Quantity : itemData.Price; } } @@ -285,10 +288,7 @@ public abstract class EntityPack foreach (var (_, item) in t) { var itemData = itemManager.GetData(item); - if (item is SimpleCommodity s) - _price += itemData.Price * s.Quantity; - else - _price += itemData.Price; + _price += item is ICommodityStack s ? itemData.Price * s.Quantity : itemData.Price; } } diff --git a/Assets/Scripts/ServerShared/Enums.cs b/Assets/Scripts/ServerShared/Enums.cs index 0a6449dc1..e42e956a5 100644 --- a/Assets/Scripts/ServerShared/Enums.cs +++ b/Assets/Scripts/ServerShared/Enums.cs @@ -49,7 +49,10 @@ public enum HardpointType Energy, Ballistic, Launcher, - ControlModule + ControlModule, + // A station facility mount: only a station hull carries one (StationKinds.HullKindFault). Internal: no anchor, nothing on the + // model. Filled only by a kind's Facilities; the random hardpoint fill never touches it. Appended: stored types keep their values. + Facility } public enum WeaponType diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 9102b16eb..06448cc95 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -1850,7 +1850,7 @@ public static class FireControl var total = 0f; for (var i = 0; i < ores.Length; i++) { - var g = $"{chunk.Field.Value}:{chunk.Index}:{ores[i].Commodity.Key.Value}".StableHash() / 2147483648.0 - 1.0; + var g = $"{belt.Data.SiteOr(chunk.Field)}:{chunk.Index}:{ores[i].Commodity.Key.Value}".StableHash() / 2147483648.0 - 1.0; total += weights[i] = ores[i].Amount * (float) Math.Exp(settings.ChunkCompositionVariance * g); } var counts = new int[ores.Length]; @@ -1864,18 +1864,16 @@ public static class FireControl var at = zone.ChunkPose(chunk.Field, chunk.Index).xy; var velocity = zone.ChunkVelocity(chunk); - var zoneIndex = zone.Galaxy?.Zones == null ? -1 : Array.IndexOf(zone.Galaxy.Zones, zone.GalaxyZone); var present = zone.Entities.Contains(shooter); for (var i = 0; i < ores.Length; i++) { var key = ores[i].Commodity.Key; var commodity = (SimpleCommodityData) catalog.Get(ores[i].Commodity); var maxStack = Math.Max(1, commodity.MaxStack); - var lot = counts[i] > 0 ? shooter.ItemManager.ExtractedLot(zoneIndex, chunk.Field, commodity) : 0; var adrift = 0; for (var left = counts[i]; left > 0; left -= maxStack) { - var stack = new SimpleCommodity { Data = new CultRecordRef(key), Lot = lot, Quantity = Math.Min(left, maxStack) }; + var stack = new SimpleCommodity { Data = new CultRecordRef(key), Quantity = Math.Min(left, maxStack) }; // A partial store leaves the remainder in Quantity and returns false, so the next bay is offered the rest. var stored = false; if (present) foreach (var bay in shooter.CargoBays) if (stored = bay.TryStore(stack)) break; @@ -1888,7 +1886,7 @@ public static class FireControl if (counts[i] > 0) zone.CargoGained.OnNext(new CargoGain { - Taker = shooter, Design = new CultRecordRef(key), Lot = lot, Stored = counts[i] - adrift, Adrift = adrift, Kind = GainKind.Mined + Taker = shooter, Design = new CultRecordRef(key), Stored = counts[i] - adrift, Adrift = adrift, Kind = GainKind.Mined }); } } diff --git a/Assets/Scripts/ServerShared/Formation.cs b/Assets/Scripts/ServerShared/Formation.cs new file mode 100644 index 000000000..5dbfd9e5e --- /dev/null +++ b/Assets/Scripts/ServerShared/Formation.cs @@ -0,0 +1,85 @@ +using System.Collections.Generic; +using System.Linq; +using CultMath; +using static CultMath.math; +using float2 = CultMath.float2; + +// A formation is a compiled group of ships a summon places into a running zone (ruling summons-follow-faction-logic): a +// script, a stable id and the faction it is cast as. It declares; ZoneStage.Summon is the one admission, and the stance of +// what arrives is the faction rule's and its grudges', so a formation writes none. The IFL palette calls the same Summon. +public abstract class Formation +{ + // The formation's stable identity: kebab-case, unique across Formations, never shown to the player. Name is display only. + public abstract string Id { get; } + + public abstract string Name { get; } + + // A catalog faction the formation's ships are fitted for and belong to, resolved through Galaxy.ResolveFaction. Null is + // factionless. + public virtual string Faction => null; + + // Places the formation with the stage's verbs, around a point and facing a direction. The faction is the resolved one, null + // when the formation is factionless; only a Generated fit carries it. + public abstract void Place(ZoneStage stage, Faction faction, float2 at, float2 facing); + + // Summons the formation into a running zone, or returns null with every failure listed and the zone, item stream and + // lot ledger unchanged. A faction the catalog does not hold refuses the summon: it would otherwise arrive factionless. + public IReadOnlyList Summon(ItemManager items, Zone zone, float2 at, float2 facing, List failures) + { + Faction faction = null; + if (Faction != null) + { + faction = zone.Galaxy.ResolveFaction(Faction); + if (faction == null) + { + failures.Add($"formation {Id}: no faction named {Faction}"); + return null; + } + } + return ZoneStage.Summon(items, zone, stage => Place(stage, faction, at, facing), failures); + } +} + +// Every formation, in the order the console lists them. +public static class Formations +{ + public static readonly Formation[] All = + { + new Squad("sparring-target", "Sparring Target", null, 1), + new Squad("zhestokost-pair", "Zhestokost Pair", "Zhe", 2), + new Squad("pirates-pair", "Pirates Pair", "Pirates", 2), + new Squad("lucent-pair", "Lucent Media Pair", "Luc", 2), + new Squad("aeronautics-pair", "Aeronautics Unlimited Pair", "Aero", 2) + }; + + public static Formation ById(string id) => All.FirstOrDefault(formation => formation.Id == id); + + // Piloted generated ships of any hull, side by side across the line of facing, 60 m apart, centred on the point. + // Faction names are the demo cast's (DemoTerminus.Cast). + private sealed class Squad : Formation + { + private const float Spacing = 60f; + private readonly string _faction; + private readonly int _ships; + + public Squad(string id, string name, string faction, int ships) + { + Id = id; + Name = name; + _faction = faction; + _ships = ships; + } + + public override string Id { get; } + public override string Name { get; } + public override string Faction => _faction; + + public override void Place(ZoneStage stage, Faction faction, float2 at, float2 facing) + { + var forward = lengthsq(facing) > 0 ? normalize(facing) : float2(0, 1); + var across = float2(-forward.y, forward.x); + for (var ship = 0; ship < _ships; ship++) + stage.Place(stage.Generated("", faction), at + across * ((ship - (_ships - 1) / 2f) * Spacing), forward, piloted: true); + } + } +} diff --git a/Assets/Scripts/ServerShared/Formation.cs.meta b/Assets/Scripts/ServerShared/Formation.cs.meta new file mode 100644 index 000000000..ae1475310 --- /dev/null +++ b/Assets/Scripts/ServerShared/Formation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dfed2b8eaa234dd88ad6ada0315e6ee2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Galaxy.cs b/Assets/Scripts/ServerShared/Galaxy.cs index 797e77764..5861f7131 100644 --- a/Assets/Scripts/ServerShared/Galaxy.cs +++ b/Assets/Scripts/ServerShared/Galaxy.cs @@ -26,7 +26,15 @@ public class Galaxy public GalaxyZone Exit { get; private set; } public Dictionary FactionRelationships { get; } = new Dictionary(); private Action Log { get; } - public bool IsPrelude { get; } + + // How far each faction's authored InfluenceDistance reaches in this galaxy (InfluenceOf): the cast's InfluenceScale, + // 1 for a main galaxy. Carried by the save because every zone generated after Continue reads it. + public float InfluenceScale { get; } + + // The faction whose gate this galaxy has, null when it has none: the scope and the source of the demo's raids + // (ZoneGenerator reads it through DemoPressure). Written only by PlaceGate and the save constructor; carried by the + // save because every zone generated after Continue reads it and nothing else persisted regenerates it. + public Faction Antagonist { get; private set; } // The run's seed, minted once by GalaxyStage.SeedFrom and carried by the save (SavedGame.Seed). It seeds // generation, the run's item draws (RunStart) and the zone's drop dice (Zone.DropSeed). @@ -51,7 +59,9 @@ public class Galaxy public Galaxy(CultCache cultCache, SavedGame savedGame, Action log) { - IsPrelude = savedGame.IsTutorial; + InfluenceScale = savedGame.InfluenceScale > 0 + ? savedGame.InfluenceScale + : throw new InvalidOperationException($"the save has no {nameof(InfluenceScale)} ({savedGame.InfluenceScale}); a run saved before InfluenceScale existed cannot be continued"); _cache = cultCache; Log = log; Background = savedGame.Background; @@ -97,6 +107,11 @@ public class Galaxy if(savedGame.Exit != -1) Exit = Zones[savedGame.Exit]; + // Unset: no gate antagonist (a save from before key 18). Set but not one of the save's factions: refused. + if (savedGame.Antagonist.IsSet()) + Antagonist = Factions.Contains(cultCache.Get(savedGame.Antagonist)) ? cultCache.Get(savedGame.Antagonist) + : throw new InvalidOperationException("SavedGame.Antagonist is not one of the save's factions"); + // A save from before ore geography has no provinces: it gets them by the rule generation uses. BuildProvinces(global::Provinces.DefaultZonesPerProvince, savedGame.Provinces == null ? null : savedZones.Select(zone => zone.Province).ToArray(), savedGame.Provinces); @@ -112,7 +127,7 @@ public class Galaxy uint seed) { _cache = cache; - IsPrelude = false; + InfluenceScale = 1; Background = background; Log = log; var factions = cache.GetAll(); @@ -186,35 +201,37 @@ public class Galaxy return _cache.GetAll().FirstOrDefault(f => f.Name.StartsWith(name, StringComparison.InvariantCultureIgnoreCase)); } - // A cast member of a prelude galaxy, by name. A name the catalog does not hold refuses the galaxy, naming the field. + // A cast member of a cast galaxy, by name. A name the catalog does not hold refuses the galaxy, naming the field. private Faction ResolveCast(string field, string name) => ResolveFaction(name) ?? throw new InvalidOperationException($"cast faction {name} ({field}) is not in the catalog"); - // Gives a prelude galaxy its gate: the antagonist's home is the boss zone and the exit. The only writer of Exit - // besides the constructors. + // Gives a cast galaxy its gate: the antagonist's home is the boss zone and the exit. The only writer of Exit and + // Antagonist besides the constructors. public void PlaceGate(Faction antagonist) { + Antagonist = antagonist; BossZones[antagonist] = HomeZones[antagonist]; Exit = HomeZones[antagonist]; } - // How many jumps a faction's influence reaches in this galaxy: its authored distance, halved (rounding up) in a - // prelude. Derived, never written back to the catalog's Faction, so one galaxy's generation cannot change the next. + // How many jumps a faction's influence reaches in this galaxy: its authored distance scaled by the galaxy's + // InfluenceScale (the cast decides the scale), rounding up. Derived, never written back to the catalog's Faction, + // so one galaxy's generation cannot change the next. public int InfluenceOf(Faction faction) => - IsPrelude ? (faction.InfluenceDistance + 1) / 2 : faction.InfluenceDistance; + (int) MathF.Ceiling(faction.InfluenceDistance * InfluenceScale); public Galaxy( - TutorialGenerationSettings settings, + GalaxyCast cast, SectorBackgroundSettings background, CultCache cache, - PlayerSettings playerSettings, - DirectoryInfo narrativeDirectory, Action log, Action progressCallback, uint seed) { _cache = cache; - IsPrelude = true; + InfluenceScale = cast.InfluenceScale > 0 + ? cast.InfluenceScale + : throw new InvalidOperationException($"the cast's {nameof(cast.InfluenceScale)} must be positive, got {cast.InfluenceScale}"); Background = background; Log = log; @@ -223,32 +240,32 @@ public class Galaxy var factions = new List(); - var protagonistFaction = ResolveCast(nameof(settings.ProtagonistFaction), settings.ProtagonistFaction); + var protagonistFaction = ResolveCast(nameof(cast.ProtagonistFaction), cast.ProtagonistFaction); factions.Add(protagonistFaction); - var antagonistFaction = ResolveCast(nameof(settings.AntagonistFaction), settings.AntagonistFaction); + var antagonistFaction = ResolveCast(nameof(cast.AntagonistFaction), cast.AntagonistFaction); factions.Add(antagonistFaction); - var bufferFaction = ResolveCast(nameof(settings.BufferFaction), settings.BufferFaction); + var bufferFaction = ResolveCast(nameof(cast.BufferFaction), cast.BufferFaction); factions.Add(bufferFaction); // A cast without a quest faction places no quest zone. - var questFaction = string.IsNullOrEmpty(settings.QuestFaction) + var questFaction = string.IsNullOrEmpty(cast.QuestFaction) ? null - : ResolveCast(nameof(settings.QuestFaction), settings.QuestFaction); + : ResolveCast(nameof(cast.QuestFaction), cast.QuestFaction); if (questFaction != null) factions.Add(questFaction); - var neutralFactions = settings.NeutralFactions - .Select(name => ResolveCast(nameof(settings.NeutralFactions), name)) + var neutralFactions = cast.NeutralFactions + .Select(name => ResolveCast(nameof(cast.NeutralFactions), name)) .ToArray(); factions.AddRange(neutralFactions); Factions = factions.ToArray(); foreach (var faction in Factions) FactionRelationships[faction] = FactionRelationship.Neutral; - Zones = GenerateZones(settings.ZoneCount, ref random, progressCallback); + Zones = GenerateZones(cast.ZoneCount, ref random, progressCallback); - GenerateLinks(settings.LinkDensity, progressCallback); + GenerateLinks(cast.LinkDensity, progressCallback); CalculateDistanceMatrix(progressCallback); @@ -302,15 +319,11 @@ public class Galaxy CalculateFactionInfluence(progressCallback); - // No boss zone and no Exit yet (PlaceGate comes after): the prelude is one region. - BuildProvinces(settings.ProvinceZones); + // No boss zone and no Exit yet (PlaceGate comes after): a cast galaxy is one region. + BuildProvinces(cast.ProvinceZones); NamePlaces(ref random, progressCallback); - // progressCallback?.Invoke("Weaving Narrative"); - // var processor = new StoryProcessor(playerSettings, narrativeDirectory, this, ref random, Log); - // processor.ProcessStories(); - progressCallback?.Invoke("Done!"); if(progressCallback!=null) Thread.Sleep(500); // Inserting Delay to make it seem like it's doing more work lmao } @@ -449,6 +462,21 @@ public class Galaxy } } + // A zone no link reaches would throw far from here, placing homes or the entrance; refuse it where it is made. + public static void RequireEveryZoneLinked(GalaxyZone[] zones, IEnumerable<(GalaxyZone, GalaxyZone)> links) + { + if (zones.Length < 2) return; + var linked = new HashSet(); + foreach (var link in links) + { + linked.Add(link.Item1); + linked.Add(link.Item2); + } + var stranded = zones.Where(zone => !linked.Contains(zone)).ToList(); + if (stranded.Count > 0) + throw new InvalidOperationException($"Triangulation left {stranded.Count} of {zones.Length} zones unlinked, first at {stranded[0].Position}"); + } + private void GenerateLinks(float linkDensity, Action progressCallback = null) { progressCallback?.Invoke("Triangulating Zone Positions"); @@ -458,6 +486,7 @@ public class Galaxy var links = Delaunay.Edges(Zones.Select(z => z.Position).ToArray()) .Select(edge => (Zones[edge.a], Zones[edge.b])) .ToList(); + RequireEveryZoneLinked(Zones, links); progressCallback?.Invoke("Eliminating Zone Links"); if (progressCallback != null) Thread.Sleep(500); // Inserting Delay to make it seem like it's doing more work lmao diff --git a/Assets/Scripts/ServerShared/GalaxyStage.cs b/Assets/Scripts/ServerShared/GalaxyStage.cs index a93e25f89..4bea4d6c7 100644 --- a/Assets/Scripts/ServerShared/GalaxyStage.cs +++ b/Assets/Scripts/ServerShared/GalaxyStage.cs @@ -1,5 +1,4 @@ using System; -using System.IO; using GameCult.Caching; using MessagePack; using static CultMath.math; @@ -13,11 +12,8 @@ public sealed class GalaxyStage { private readonly SectorGenerationSettings _sector; private readonly SectorBackgroundSettings _sectorBackground; - private readonly TutorialGenerationSettings _prelude; - private readonly SectorBackgroundSettings _preludeBackground; + private readonly SectorBackgroundSettings _castBackground; private readonly CultCache _cache; - private readonly PlayerSettings _playerSettings; - private readonly DirectoryInfo _narrativeDirectory; private readonly Action _log; private readonly Action _progress; private readonly Func _clock; @@ -25,22 +21,16 @@ public sealed class GalaxyStage public GalaxyStage( SectorGenerationSettings sector, SectorBackgroundSettings sectorBackground, - TutorialGenerationSettings prelude, - SectorBackgroundSettings preludeBackground, + SectorBackgroundSettings castBackground, CultCache cache, - PlayerSettings playerSettings, - DirectoryInfo narrativeDirectory, Action log, Action progress = null, Func clock = null) { _sector = sector; _sectorBackground = sectorBackground; - _prelude = prelude; - _preludeBackground = preludeBackground; + _castBackground = castBackground; _cache = cache; - _playerSettings = playerSettings; - _narrativeDirectory = narrativeDirectory; _log = log; _progress = progress; _clock = clock ?? (() => (uint) (DateTime.Now.Ticks % uint.MaxValue)); @@ -65,13 +55,10 @@ public sealed class GalaxyStage return new Galaxy(_sector, background, _cache, _log, _progress, Seed); } - // A prelude galaxy: the tutorial settings and their fixed factions, centred in dense cloud. - public Galaxy Prelude() => Prelude(_prelude); - - // A prelude galaxy of the given fixed cast, centred in dense cloud. - public Galaxy Prelude(TutorialGenerationSettings cast) + // A galaxy of the given fixed cast, centred in dense cloud. + public Galaxy Cast(GalaxyCast cast) { - var background = Copy(_preludeBackground); + var background = Copy(_castBackground); var random = new Random(Seed); var iteration = 1; do @@ -79,7 +66,7 @@ public sealed class GalaxyStage background.NoisePosition = random.NextFloat() * 1000; _progress?.Invoke($"Finding Galaxy Position: iteration {iteration++}"); } while (background.CloudDensity(float2(.5f)) < .5f); - return new Galaxy(cast, background, _cache, _playerSettings, _narrativeDirectory, _log, _progress, Seed); + return new Galaxy(cast, background, _cache, _log, _progress, Seed); } private static SectorBackgroundSettings Copy(SectorBackgroundSettings settings) => diff --git a/Assets/Scripts/ServerShared/HaulFeed.cs b/Assets/Scripts/ServerShared/HaulFeed.cs index b6f4055c8..838c28198 100644 --- a/Assets/Scripts/ServerShared/HaulFeed.cs +++ b/Assets/Scripts/ServerShared/HaulFeed.cs @@ -10,7 +10,6 @@ public struct CargoGain { public Entity Taker; public CultRecordRef Design; - public int Lot; public int Stored; public int Adrift; public GainKind Kind; diff --git a/Assets/Scripts/ServerShared/HaulRun.cs b/Assets/Scripts/ServerShared/HaulRun.cs new file mode 100644 index 000000000..16e95290a --- /dev/null +++ b/Assets/Scripts/ServerShared/HaulRun.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; + +// The interim haul (aetheria-living-world:ruling:transit-depots-buy-for-onward-haul, demo-zenith-ore-depot): which ship carries for which +// standing order (Entity.Haul), where it flies (the leg, derived from its hold every update), and the one dock call that moves goods: +// the hauler docks (ruling docking-is-enclosed-bays), the From station's silo loads it or the To station takes its cargo through +// StationServices.TryStorePart, and it undocks piloted. No payment moves: both ends are in one comms cell and no station holds an account +// (ruling comms-cells-are-zones). The ship's task, orders and cargo are the ship's own; nothing here is stored. +public static class HaulRun +{ + public static HaulOrderData OrderOf(ItemManager items, CultRecordKey order) => + order.IsSet() ? items.ItemData.Get(order) : null; + + // The task a ship carrying a haul order starts on, derived at every admission; null for a ship with no order or whose order is gone. + public static HaulingTask TaskOf(Ship ship) => + ship.Haul.Key.IsSet() && OrderOf(ship.ItemManager, ship.Haul.Key) != null ? new HaulingTask { Order = ship.Haul.Key } : null; + + // The orbit to steer for: the To station's while the hold holds any good of the order, the From station's otherwise. + public static CultRecordKey Leg(Ship ship, HaulOrderData order) => + Carried(ship, order).Any() ? order.To.Key : order.From.Key; + + public static OrbitalEntity Station(Zone zone, CultRecordKey orbit) => + zone.Entities.OfType().FirstOrDefault(station => station.OrbitData.Equals(orbit)); + + // Whether a call at this station would move a unit: read-only, stored nowhere. At the From station the silo holds a good of the order the + // hold has room for; at the To station the station wants a carried good and has room for a unit of it. Either needs a free docking bay. + public static bool CanCall(Ship ship, OrbitalEntity station, HaulOrderData order) + { + if (station.DockingBays.All(bay => bay.DockedShip != null)) return false; + var orbit = station.OrbitData; + if (orbit.Equals(order.From.Key)) + return station.CargoBays.Where(bay => bay.Data is SiloData).SelectMany(bay => bay.Cargo.Keys).OfType() + .Any(stack => Goods(order).Contains(((ItemInstance) stack).Data.Key) && ship.CargoBays.Any(bay => bay.TryFindSpace(stack.Split(1)))); + if (orbit.Equals(order.To.Key)) + return Carried(ship, order).Any(stack => StationWants.Bays(station, ((ItemInstance) stack).Data.Key).Any(bay => bay.TryFindSpace(stack.Split(1)))); + return false; + } + + // Docks at the station, loads at the From station or delivers at the To station, and undocks piloted: a ship that cannot + // move a unit does not dock. The pilot's Call verb is the only caller (PilotApplier). + public static void Call(Ship ship, Entity station) + { + var order = OrderOf(ship.ItemManager, ship.Haul.Key); + if (order == null || !(station is OrbitalEntity depot) || !CanCall(ship, depot, order) || depot.TryDock(ship) == null) return; + if (depot.OrbitData.Equals(order.From.Key)) StationServices.Load(depot, Goods(order), ship); + else + foreach (var bay in ship.CargoBays.ToArray()) + foreach (var stack in bay.Cargo.Keys.OfType().Where(stack => Goods(order).Contains(((ItemInstance) stack).Data.Key)).ToArray()) + StationServices.TryStorePart(bay, depot, stack); + depot.TryUndock(ship, piloted: true); + } + + private static IReadOnlyCollection Goods(HaulOrderData order) => order.Goods.Select(good => good.Key).ToArray(); + + private static IEnumerable Carried(Ship ship, HaulOrderData order) + { + var goods = Goods(order); + return ship.CargoBays.SelectMany(bay => bay.Cargo.Keys).OfType().Where(stack => goods.Contains(((ItemInstance) stack).Data.Key)).ToArray(); + } +} diff --git a/Assets/Scripts/ServerShared/HaulRun.cs.meta b/Assets/Scripts/ServerShared/HaulRun.cs.meta new file mode 100644 index 000000000..44c9003d2 --- /dev/null +++ b/Assets/Scripts/ServerShared/HaulRun.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3d0757eadcb14d11a9b559eb79cef9e6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/ItemData.cs b/Assets/Scripts/ServerShared/ItemData.cs index ab9c9dcfc..6d2893cb8 100644 --- a/Assets/Scripts/ServerShared/ItemData.cs +++ b/Assets/Scripts/ServerShared/ItemData.cs @@ -327,6 +327,8 @@ public class SimpleCommodityData : ItemData [Inspectable, JsonProperty("maxStackSize"), Key(9)] public int MaxStack = 10; + // A commodity is one cell unless authored otherwise: crate size is a balance knob, and a cargo bay reads Shape to store the good. + public SimpleCommodityData() => Shape = new Shape(); } [JsonObject(MemberSerialization.OptIn)] @@ -357,6 +359,13 @@ public class ItemRole public class CompoundCommodityData : CraftedItemData { // MessagePack keys 10 and 11 belonged to the removed demand weights and classification; do not reuse them. + + // The most units of one lot a cargo cell holds. A sim-tuned knob; records written before it existed read 10. + [Inspectable, JsonProperty("maxStackSize"), Key(12)] + public int MaxStack = 10; + + // A commodity is one cell unless authored otherwise: crate size is a balance knob, and a cargo bay reads Shape to store the good. + public CompoundCommodityData() => Shape = new Shape(); } [CultDocument("aetheria.consumableitemdata", "1"), Inspectable, MessagePackObject] @@ -479,6 +488,15 @@ public class DockingBayData : CargoBayData public int2 MaxSize; } +// A silo: bulk storage seated on a Facility row (idea stations-gear-map.one-mount-for-station-gear). It is a cargo bay that holds +// commodity stacks only, so gear, consumables and crafted sales never land in it; what a station buys for one is its haul +// orders' goods (StationWants). +[CultDocument("aetheria.silodata", "1"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class SiloData : CargoBayData +{ + [IgnoreMember] public override HardpointType HardpointType => HardpointType.Facility; +} + [CultDocument("aetheria.weaponitemdata", "1"), MessagePackObject, JsonObject(MemberSerialization.OptIn)] public class WeaponItemData : GearData { diff --git a/Assets/Scripts/ServerShared/ItemInstance.cs b/Assets/Scripts/ServerShared/ItemInstance.cs index a16553b9f..6e94cc049 100644 --- a/Assets/Scripts/ServerShared/ItemInstance.cs +++ b/Assets/Scripts/ServerShared/ItemInstance.cs @@ -25,10 +25,6 @@ public abstract class ItemInstance [JsonProperty("data"), Key(0)] public CultRecordRef Data; [JsonProperty("rotation"), Key(1)] public ItemRotation Rotation; - // The lot this unit was minted or mined from: crafted units' design, provenance, workmanship and role fills all - // live there; a mined SimpleCommodity names its Extracted lot (zone, belt, ore). Lot 0 is no lot: bought, staged - // and loadout commodities, and every save from before the field reached SimpleCommodity. - [JsonProperty("lot"), Key(11)] public int Lot; } [Union(0, typeof(CompoundCommodity)), @@ -38,16 +34,51 @@ public abstract class ItemInstance public abstract class CraftedItemInstance : ItemInstance { // Keys 2 (Quality), 9 (Ingredients) and 10 (Product) belonged to fields moved to Lot; do not reuse them. - // Key 11 (Lot) lives on ItemInstance. + + // The lot a crafted unit was minted from: its design, provenance, workmanship and role fills all live there. A + // simple commodity has none (ruling simple-commodities-fungible). + [JsonProperty("lot"), Key(11)] public int Lot; +} + +// A commodity that stacks: the one owner of which units are interchangeable (StacksWith) and of what a split carries +// (Split). The cargo bay applies it at every merge and ItemManager.MaxStack bounds it; nothing else decides either. +public interface ICommodityStack +{ + int Quantity { get; set; } + + // True when `other` is a unit this stack may merge with. + bool StacksWith(ItemInstance other); + + // A new stack of `quantity` units interchangeable with this one; this stack is left as it was. + ItemInstance Split(int quantity); +} + +// Units of a compound commodity merge only within one lot (ruling compound-commodities-stack-by-lot): the lot is the +// units' provenance, workmanship and role fills. +[MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class CompoundCommodity : CraftedItemInstance, ICommodityStack +{ + // Keys 2, 9, 10 and 11 are CraftedItemInstance's and 12 EquippableItem's. A unit saved before Quantity existed has + // no slot 13 and reads one. + [JsonProperty("quantity"), Key(13)] public int Quantity { get; set; } = 1; + + public bool StacksWith(ItemInstance other) => + other is CompoundCommodity compound && compound.Data.Key.Equals(Data.Key) && compound.Lot == Lot; + + public ItemInstance Split(int quantity) => + new CompoundCommodity { Data = Data, Rotation = Rotation, Lot = Lot, Quantity = quantity }; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] -public class CompoundCommodity : CraftedItemInstance { } - -[MessagePackObject, JsonObject(MemberSerialization.OptIn)] -public class SimpleCommodity : ItemInstance +public class SimpleCommodity : ItemInstance, ICommodityStack { - [JsonProperty("quantity"), Key(2)] public int Quantity; + // Key 11 belonged to a lot before ruling simple-commodities-fungible and is never reused; a pre-ruling stack's + // slot 11 is skipped on read. + [JsonProperty("quantity"), Key(2)] public int Quantity { get; set; } + + public bool StacksWith(ItemInstance other) => other is SimpleCommodity && other.Data.Key.Equals(Data.Key); + + public ItemInstance Split(int quantity) => new SimpleCommodity { Data = Data, Rotation = Rotation, Quantity = quantity }; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] @@ -65,6 +96,10 @@ public class EquippableItem : CraftedItemInstance // it from the schematic UI; from then on PowerBus only ever reads it, never derives it. An old run store // missing key 12 deserializes to this same field initializer, so no migration is needed (§ Cut 5). [JsonProperty("powerTier"), Key(12)] public int PowerTier = PowerTiers.Unassigned; + + // A facility's cycle in progress: per-unit installation state like PowerTier, null on everything but a facility that has started + // a cycle. Its one writer is Facility.Execute, storing Production.Advance's result. 13 is CompoundCommodity's, so 14. + [JsonProperty("run"), Key(14)] public FacilityRun Run; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/ItemManager.cs b/Assets/Scripts/ServerShared/ItemManager.cs index c91568efd..25b467992 100644 --- a/Assets/Scripts/ServerShared/ItemManager.cs +++ b/Assets/Scripts/ServerShared/ItemManager.cs @@ -26,10 +26,6 @@ public class ItemManager public CultCache ItemData { get; } public ProvenanceLedger Lots { get; } - // (zone index, belt, commodity) -> the Extracted lot minted for it. Derived from Lots at construction and on mint, - // never persisted: a reload rebuilds it from the ledger, so the same source finds the same lot. - private readonly Dictionary<(int, CultRecordKey, CultRecordKey), int> _extracted = - new Dictionary<(int, CultRecordKey, CultRecordKey), int>(); public GameplaySettings GameplaySettings { get; } public ItemManager(uint seed, CultCache itemData, ProvenanceLedger lots, GameplaySettings settings, Action logger) @@ -38,13 +34,28 @@ public class ItemManager Random = new Random(seed); ItemData = itemData; Lots = lots; - foreach (var (id, lot) in lots.Lots) - if (lot.Origin is Extracted extracted) - _extracted[(extracted.Zone, extracted.Body.Key, extracted.Commodity.Key)] = id; GameplaySettings = settings; _logger = logger; } + // A restore point over everything building items draws or mints: the item stream and the lot ledger, which a run save + // persists. Rewind puts both back, so a refused build is neither a draw nor a lot. + public readonly struct Checkpoint + { + internal readonly Random Stream; + internal readonly int NextLot; + internal Checkpoint(Random stream, int nextLot) { Stream = stream; NextLot = nextLot; } + } + + public Checkpoint Mark() => new Checkpoint(Random, Lots.NextLot); + + public void Rewind(Checkpoint mark) + { + Random = mark.Stream; + foreach (var id in Lots.Lots.Keys.Where(id => id >= mark.NextLot).ToList()) Lots.Lots.Remove(id); + Lots.NextLot = mark.NextLot; + } + public void Log(string s) { _logger(s); @@ -63,8 +74,8 @@ public class ItemManager { return item switch { + ICommodityStack stack => GetData(item).Mass * stack.Quantity, CraftedItemInstance _ => GetData(item).Mass, - SimpleCommodity commodity => GetData(item).Mass * commodity.Quantity, _ => 0 }; } @@ -74,15 +85,23 @@ public class ItemManager var data = GetData(item); return item switch { + ICommodityStack stack => data.Mass * data.SpecificHeat * stack.Quantity, CraftedItemInstance _ => data.Mass * data.SpecificHeat, - SimpleCommodity commodity => data.Mass * data.SpecificHeat * commodity.Quantity, _ => 0 }; } - // The one resolution path from an instance to the lot it was minted or mined from. Lot 0 throws: a bought or - // staged commodity has no lot, and the caller asks Lot != 0 first. - public Lot GetLot(ItemInstance item) => Lots[item.Lot]; + // The most units of the item one cell holds: the design's MaxStack for a commodity, one for anything else. The one + // reader of either design's MaxStack outside authoring. + public int MaxStack(ItemInstance item) => GetData(item) switch + { + SimpleCommodityData simple => simple.MaxStack, + CompoundCommodityData compound => compound.MaxStack, + _ => 1 + }; + + // The one path from a crafted instance to its lot; a simple commodity has no lot. + public Lot GetLot(CraftedItemInstance item) => Lots[item.Lot]; // Returns stat when not equipped: a null-entity context with no heat, no power and no modifiers. It says so // in its own name (UnequippedStatContext) rather than being a third quiet dialect of the arithmetic. @@ -189,24 +208,6 @@ public class ItemManager return Lots.Add(lot); } - // Mining Cut 5b: the lot of every unit mined from one commodity in one belt of one zone, found or minted. Unbranded - // (Product unset) and unworked (Quality 1, no roles). FireControl.Extract is the only caller. - public int ExtractedLot(int zone, CultRecordKey belt, SimpleCommodityData commodity) - { - var key = (zone, belt, ItemData.RefOf(commodity).Key); - if (_extracted.TryGetValue(key, out var found)) return found; - var id = Lots.Add(new Lot - { - Design = ItemData.RefOf(commodity), - Origin = new Extracted - { - Zone = zone, Body = new CultRecordRef(belt), Commodity = ItemData.RefOf(commodity) - }, - Quality = 1 - }); - return _extracted[key] = id; - } - // The one writer of a crafted instance's Data: copied from the lot's design, never independently set. public CraftedItemInstance CreateInstance(int lot) { @@ -242,7 +243,7 @@ public class ItemManager } // Who made an item and what it is branded as. The maker derives from its lot's provenance and the product is the - // one its lot records; nothing re-derives it. Null maker (an unset faction, or an Extracted lot with none) means + // one its lot records; nothing re-derives it. Null maker (an unset faction) means // no brand at all; a set maker whose lot records no product (or one the catalog no longer holds) still shows // the maker, with no product name or flavour text. public (Faction Maker, FactionProductData Product) Brand(CraftedItemInstance item) @@ -261,7 +262,7 @@ public class ItemManager } // What the player reads an item as: its lot's product name when it records one, - // otherwise the design's own name (unbranded, console-given and extracted lots, and commodities). + // otherwise the design's own name (unbranded and console-given lots, and commodities). public string Title(ItemInstance item) => (item is CraftedItemInstance crafted ? Brand(crafted).Product?.Name : null) ?? GetData(item).Name; diff --git a/Assets/Scripts/ServerShared/LoadoutGenerator.cs b/Assets/Scripts/ServerShared/LoadoutGenerator.cs index fcd554efd..5bec63b34 100644 --- a/Assets/Scripts/ServerShared/LoadoutGenerator.cs +++ b/Assets/Scripts/ServerShared/LoadoutGenerator.cs @@ -21,6 +21,10 @@ public class LoadoutGenerator // station draws 1 to the maximum. public const float StationConsumableChance = .25f; public const int StationConsumableUnits = 2; + // The share of a station's stock bay its generated gear may fill; the rest stays free for what the station buys (rulings + // no-market-absorption, station-intake-few-sorties). A first value of a sim-tuned knob (economy-numbers-are-sim-tuned-knobs): + // follow-up economy-balance-station-drain tunes it. + public const float StationStockShare = .5f; public const float ShipConsumableChance = .1f; public const int ShipConsumableUnits = 1; @@ -64,6 +68,11 @@ public class LoadoutGenerator return EntitySerializer.Pack(entity); } + // The ship hulls this faction's generator can draw (its products, with the any-manufacturer fallback a required hull has). + public HullData[] OfferedShipHulls() => + AvailableProducts(hull => hull.HullType == HullType.Ship, required: true).available + .Select(entry => entry.design).Distinct().ToArray(); + public OrbitalEntityPack GenerateTurretLoadout() { var (hullProduct, hullData) = RandomHull(HullType.Turret); @@ -98,8 +107,9 @@ public class LoadoutGenerator // A stand-in hull keeps its own model but not its own name: the station is what its kind says it is. if (!hullData.Kind.Key.Equals(kind.Key) && ItemManager.ItemData.Get(kind) is { } kindData) entity.Name = kindData.Name; - // Hardpoint gear goes in first so the docking bay can only take space that gear left free + // Hardpoint gear, then the kind's facilities, go in before any interior gear so the docking bay can only take space they left free EquipHardpoints(entity); + EquipFacilities(entity, kind); var emptyShape = entity.UnoccupiedSpace; @@ -134,14 +144,21 @@ public class LoadoutGenerator // offer nothing is drawn here, so the gear draws are exactly what they were. StockConsumables(entity, StationConsumableChance, StationConsumableUnits); - var cargo = entity.CargoBays.First(); + // The gear stock goes to the first bay that is not a silo and stops short of StationStockShare of its cells, so a + // station's hold keeps room for what it buys (ruling no-market-absorption). All sixteen picks are still drawn, so no + // random stream moves; only storing stops. + var cargo = entity.CargoBays.First(bay => !(bay.Data is SiloData)); + var stockCells = (int) (cargo.Data.InteriorShape.Coordinates.Length * StationStockShare); + var stocked = cargo.Data.InteriorShape.Coordinates.Count(cell => cargo.Occupancy[cell.x, cell.y] != null); var inventory = RandomProducts(16, 1, data => !(data is HullData hull && hull.HullType != HullType.Ship) && !(data is CargoBayData)) .OrderByDescending(entry => entry.design.Shape.Coordinates.Length); foreach (var entry in inventory) { var instance = ItemManager.CreateInstance(entry.product); - cargo.TryStore(instance); + var cells = entry.design.Shape.Coordinates.Length; + if (stocked + cells > stockCells) continue; + if (cargo.TryStore(instance)) stocked += cells; } entity.CanTow = hullData.CanTow; @@ -168,7 +185,7 @@ public class LoadoutGenerator } } - private static bool IsHeater(GearData item) => + internal static bool IsHeater(GearData item) => item.HardpointType == HardpointType.Tool && item.Behaviors.Any(b => b is ThermotoggleData { HighPass: false }) && item.Behaviors.Any(b => b is HeatData); @@ -257,8 +274,11 @@ public class LoadoutGenerator // Whether a product is on the market at all (ruling off-market-is-unoffered-product). The one reader of NotOffered. A bin is // offered only if both it and its line are (ruling bin-inherits-line-offered); the catalog read guarantees a bin's line exists. - public static bool IsOffered(CultCache items, FactionProductData product) => - !product.NotOffered && (product.Bin == null || !items.Get(product.Bin.Line).NotOffered); + public static bool IsOffered(CultCache items, FactionProductData product) => IsOffered(product, line => items.Get(line)); + + // The same reader for a caller whose bin lines are not all in one catalog yet (ShipModCatalog.MarketFault, over a package's own products). + public static bool IsOffered(FactionProductData product, Func, FactionProductData> lineOf) => + !product.NotOffered && (product.Bin == null || !lineOf(product.Bin.Line).NotOffered); // How much this outfitter favors a product: its maker's preference times the product's share of it. The one weight of // generation and of ChooseProduct. A bin takes the share of its maker's stock that would pass its floor and its line takes @@ -357,6 +377,29 @@ public class LoadoutGenerator throw new InvalidLoadoutException("Failed to equip selected tractor beam!"); } + // Installs the station kind's Facilities, largest shape first then by name (StationKinds.FacilityRoomFaults' order), each on a free + // Facility row that takes it. The brand is derived, never drawn: the station faction's own product of the design, else the first by + // name. A facility is on no market, so the product need not be offered. Draws nothing from Random. + private void EquipFacilities(Entity entity, CultRecordRef kind) + { + var kindData = ItemManager.ItemData.Get(kind); + if (kindData == null) return; + var designs = kindData.Facilities.Select(facility => ItemManager.ItemData.Get(facility)).OfType() + .OrderByDescending(design => design.Shape.Coordinates.Length).ThenBy(design => design.Name, StringComparer.Ordinal); + foreach (var design in designs) + { + var key = ItemManager.ItemData.RefOf(design).Key; + var products = ItemManager.ItemData.GetAll() + .Where(product => product.Design.Key.Equals(key)).OrderBy(product => product.Name, StringComparer.Ordinal).ToArray(); + var product = products.FirstOrDefault(p => ItemManager.ItemData.Get(p.Manufacturer) == Faction) ?? products.FirstOrDefault(); + var hullName = ItemManager.GetData(entity.Hull).Name; + if (product == null) + throw new InvalidLoadoutException($"Station hull '{hullName}' of kind '{kindData.Name}' has no product of facility {design.Name}."); + if (!entity.TryEquip(ItemManager.CreateInstance(product) as EquippableItem)) + throw new InvalidLoadoutException($"Station hull '{hullName}' has no free Facility row that takes {design.Name}, a facility of station kind '{kindData.Name}'."); + } + } + private void EquipHardpoints(Entity entity) { var hullData = ItemManager.GetData(entity.Hull) as HullData; @@ -364,6 +407,8 @@ public class LoadoutGenerator var previousProducts = new List<(FactionProductData product, GearData design)>(); foreach (var hardpoint in hullData.Hardpoints.OrderByDescending(h=>h.Shape.Coordinates.Length)) { + // A Facility row is filled only by EquipFacilities, from its kind's Facilities; the random fill never does. + if (hardpoint.Type == HardpointType.Facility) continue; if (hardpoint.Type == HardpointType.ControlModule) { var (controllerProduct, controllerData) = RandomProduct(hardpoint, 2, @@ -407,7 +452,7 @@ public class LoadoutGenerator var emptyShape = entity.UnoccupiedSpace; var (cargoProduct, cargoData) = RandomProduct(3, item => - !(item is DockingBayData) && + !(item is DockingBayData) && !(item is SiloData) && item.Shape.FitsWithin(emptyShape, out _, out _), required: true); if (cargoData == null) throw new InvalidLoadoutException("No compatible cargo bay found for entity!"); diff --git a/Assets/Scripts/ServerShared/Pilot.cs b/Assets/Scripts/ServerShared/Pilot.cs index 0ef20f96c..6600d95fd 100644 --- a/Assets/Scripts/ServerShared/Pilot.cs +++ b/Assets/Scripts/ServerShared/Pilot.cs @@ -58,12 +58,15 @@ public sealed class PilotCommand internal TargetVerb TargetVerb; // The step's give verb: a Give, or a stop when its Receiver is null. The last one in a step wins. internal (Entity Receiver, ItemInstance Item, int Quantity)? GiveVerb; + // The step's call on a station (HaulRun.Call): a one-shot a hauler's pilot commands. + internal Entity CallVerb; internal int AimCycles; internal int ShutdownOverrideToggles, HeatsinkToggles, ShieldToggles, Pings; public void Designate(TargetRef target) => Designations.Add(target); public void SelectItem(EquippedItem item) => Selections.Add(item); public void Hail(string message) => Hails.Add(message); + public void Call(Entity station) => CallVerb = station; public void Use(ConsumableItemData consumable) => Uses.Add(consumable); public void Pull(ActivatedBehavior behavior) => Triggers.Add((behavior, true)); public void Release(ActivatedBehavior behavior) => Triggers.Add((behavior, false)); @@ -79,13 +82,13 @@ public sealed class PilotCommand public void ToggleHeatsinks() => HeatsinkToggles++; public void ToggleShield() => ShieldToggles++; public void Ping() => Pings++; - // Offers goods from this entity's hold to a ship alongside (ruling transfer-is-give-only): the quantity of a commodity, - // or the one crafted instance. It replaces any give under way. A give of nothing, or of less than one, is ignored, and + // Offers goods from this entity's hold to a ship alongside (ruling transfer-is-give-only): the quantity of a commodity + // stack, or the one unit. It replaces any give under way. A give of nothing, or of less than one, is ignored, and // so is one to oneself when applied. The last give or stop in a step wins. public void Give(Entity receiver, ItemInstance item, int quantity) { if (receiver == null || item == null) return; - var count = item is CraftedItemInstance ? 1 : quantity; + var count = item is ICommodityStack ? quantity : 1; if (count < 1) return; GiveVerb = (receiver, item, count); } @@ -120,6 +123,7 @@ public sealed class PilotCommand Iffs.Clear(); TargetVerb = TargetVerb.None; GiveVerb = null; + CallVerb = null; AimCycles = 0; ShutdownOverrideToggles = HeatsinkToggles = ShieldToggles = Pings = 0; } @@ -161,6 +165,7 @@ public static class PilotApplier if (give.Receiver == null) CargoTransfer.End(entity, GiveEnd.Stopped); else if (!ReferenceEquals(give.Receiver, entity)) CargoTransfer.Begin(entity, new GiveOrder(give.Receiver, give.Item, give.Quantity)); } + if (command.CallVerb is Entity station && entity is Ship caller) HaulRun.Call(caller, station); if (command.Aim is float3 aim) entity.Aim = aim; foreach (var (behavior, pull) in command.Triggers) if (pull) behavior.Activate(); diff --git a/Assets/Scripts/ServerShared/Production.cs b/Assets/Scripts/ServerShared/Production.cs new file mode 100644 index 000000000..189f5ceb2 --- /dev/null +++ b/Assets/Scripts/ServerShared/Production.cs @@ -0,0 +1,211 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using GameCult.Caching; +using MessagePack; +using Newtonsoft.Json; + +// A facility's cycle in progress, on the installed unit (EquippableItem.Run): the recipe it last ran or is running, and the sim +// seconds of the running cycle. Progress 0 is idle, and Recipe is then the round-robin cursor. Written only by Facility.Execute +// from Production.Advance's result; the inputs of a running cycle are already taken and live nowhere else. +[MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class FacilityRun +{ + [JsonProperty("recipe"), Key(0)] public CultRecordRef Recipe; + [JsonProperty("progress"), Key(1)] public double Progress; +} + +// Why a facility is not advancing, derived on each call and stored nowhere. +public enum Stall { None, Inputs, Room, Unrunnable } + +// Where a facility's goods are: its host's bays on screen, a stock ledger off screen. Each write is whole or nothing. +public interface IProductionHold +{ + int Held(CultRecordKey design); + bool TryTake(IReadOnlyList<(CultRecordKey design, int units)> units); + bool TryPut(CultRecordKey design, int units); +} + +// The one rule for a facility cycle: which recipe starts, which units it takes, how far it has run, what it stores. On screen its +// one caller is Facility.Execute, with one zone step; off screen the strategic tick calls it with a longer span. It reads no +// random, no clock and no crew. +public static class Production +{ + // A recipe a facility can run today: it takes something, and makes a simple commodity (a graded output needs a lot). + public static bool Runs(CultCache catalog, RecipeData recipe) => + !Recipes.IsRaw(catalog, recipe) && catalog.Get(recipe.Output) is SimpleCommodityData; + + // The recipe a run names as the catalog holds it now, or null when the catalog no longer has it or no longer runs it here. + public static RecipeData Live(CultCache catalog, CultRecordRef recipe) + { + var held = catalog.Get(recipe); + return held != null && Runs(catalog, held) ? held : null; + } + + // The recipes a facility design runs, in recipe-key order. Derived from the catalog, never stored. + public static IReadOnlyList RunList(CultCache catalog, CultRecordKey facilityDesign) => + Recipes.RunOn(catalog, facilityDesign).Where(recipe => Runs(catalog, recipe)).ToArray(); + + // The designs Take can take for the recipe: Inputs, Upkeep, and the fillers of each role slot, in that order, each once. Beside + // Take, which it must never disagree with: a good a recipe draws is a good its facility's station wants (StationWants). + public static IReadOnlyList Draws(CultCache catalog, RecipeData recipe) => + recipe.Inputs.Select(input => input.Commodity.Key) + .Concat(recipe.Upkeep.Select(upkeep => upkeep.Commodity.Key)) + .Concat(Recipes.RoleInputsOf(catalog, recipe).SelectMany(role => Recipes.Fillers(catalog, role.Name))) + .Distinct().ToArray(); + + // The units one cycle of the recipe takes from the hold, summed per design: Inputs, then Upkeep, then each role slot filled + // greedily across Recipes.Fillers order. Null when the hold is short of any. + public static IReadOnlyList<(CultRecordKey design, int units)> Take(CultCache catalog, RecipeData recipe, IProductionHold hold) + { + var need = new List<(CultRecordKey design, int units)>(); + void Add(CultRecordKey design, int units) + { + var at = need.FindIndex(entry => entry.design.Equals(design)); + if (at < 0) need.Add((design, units)); + else need[at] = (design, need[at].units + units); + } + int Needed(CultRecordKey design) => need.Where(entry => entry.design.Equals(design)).Sum(entry => entry.units); + + foreach (var input in recipe.Inputs) Add(input.Commodity.Key, input.Count); + foreach (var upkeep in recipe.Upkeep) Add(upkeep.Commodity.Key, upkeep.Count); + if (need.Any(entry => hold.Held(entry.design) < entry.units)) return null; + + foreach (var role in Recipes.RoleInputsOf(catalog, recipe)) + { + var left = role.Count; + foreach (var filler in Recipes.Fillers(catalog, role.Name)) + { + var units = Math.Min(left, hold.Held(filler) - Needed(filler)); + if (units < 1) continue; + Add(filler, units); + left -= units; + if (left == 0) break; + } + if (left > 0) return null; + } + return need; + } + + // The facility's state after `seconds` of sim time, and why it is not advancing. An idle facility (run null or Progress 0) + // starts the first recipe after the cursor, wrapping, whose units the hold grants, and takes them at once; a running one adds + // time; at Progress >= Cycle it stores the output and goes idle, the recipe staying as the cursor. A store the hold refuses + // holds the batch at Cycle (Room) and retries on the next call. Time left after a cycle ends runs the next one in the same call, + // so a long span runs several cycles (the rule that makes one span equal as many steps as it covers); time that no cycle can start is + // dropped. A facility with nothing to start writes nothing. + public static (FacilityRun run, Stall stall) Advance(CultCache catalog, IReadOnlyList runList, FacilityRun run, + double seconds, IProductionHold hold) + { + // A run whose recipe the catalog no longer has, or no longer runs here (a save outliving a catalog edit), is dropped: its + // progress is gone and the inputs it took stay consumed, as they are taken whole at cycle start and the recipe that named + // them is not there to return them against. The facility then starts its next recipe. Nothing below can meet a run that is not + // live: a start is of a recipe the catalog holds and runs, so Advance never throws on one and never spins. + if (run != null && run.Progress > 0 && Live(catalog, run.Recipe) == null) run = null; + if (runList.Count == 0) return (run, Stall.Unrunnable); + while (true) + { + if (run == null || run.Progress <= 0) + { + if (seconds <= 0) return (run, Stall.None); + var cursor = run == null ? -1 : IndexOf(runList, run.Recipe.Key); + RecipeData start = null; + for (var step = 1; step <= runList.Count && start == null; step++) + { + // The list may be older than the catalog: a candidate starts only as the catalog now holds it and runs it, so a + // started run is always one the next pass of this loop resolves, and a pass over the whole list ends the loop. + var candidate = Live(catalog, new CultRecordRef(RecipeData.KeyOf(runList[(cursor + step + runList.Count) % runList.Count].Output.Key))); + if (candidate == null) continue; + var units = Take(catalog, candidate, hold); + if (units != null && hold.TryTake(units)) start = candidate; + } + if (start == null) return (run, Stall.Inputs); + run = new FacilityRun { Recipe = new CultRecordRef(RecipeData.KeyOf(start.Output.Key)), Progress = 0 }; + } + + var recipe = Live(catalog, run.Recipe); + var progress = run.Progress; + if (progress < recipe.Cycle) + { + var spent = Math.Min(seconds, recipe.Cycle - progress); + progress += spent; + seconds -= spent; + } + if (progress < recipe.Cycle) return (new FacilityRun { Recipe = run.Recipe, Progress = progress }, Stall.None); + if (!hold.TryPut(recipe.Output.Key, recipe.OutputCount)) + return (new FacilityRun { Recipe = run.Recipe, Progress = recipe.Cycle }, Stall.Room); + run = new FacilityRun { Recipe = run.Recipe, Progress = 0 }; + if (seconds <= 0) return (run, Stall.None); + } + } + + private static int IndexOf(IReadOnlyList runList, CultRecordKey recipe) + { + for (var at = 0; at < runList.Count; at++) + if (RecipeData.KeyOf(runList[at].Output.Key).Equals(recipe)) return at; + return -1; + } +} + +// An entity's bays as a production hold. Takes go bay by bay in cell order, so a take never depends on how the stacks came to +// lie; a take or a put that cannot finish puts everything back. +public sealed class EntityHold : IProductionHold +{ + private readonly Entity _entity; + + public EntityHold(Entity entity) => _entity = entity; + + // The entity's cargo revision: moves on every change to the bays' contents and on every bay seated or removed, never repeats. + public long Revision => _entity.CargoRevision; + + public int Held(CultRecordKey design) => _entity.CargoBays.Sum(bay => bay.Count(design)); + + public bool TryTake(IReadOnlyList<(CultRecordKey design, int units)> units) + { + var taken = new List<(EquippedCargoBay bay, ItemInstance part, int2 origin)>(); + foreach (var (design, count) in units) + { + var left = count; + foreach (var bay in _entity.CargoBays) + { + var stacks = new List(); + foreach (var cell in bay.Data.InteriorShape.Coordinates) + { + var held = bay.Occupancy[cell.x, cell.y]; + if (held is ICommodityStack && held.Data.Key.Equals(design) && !stacks.Contains(held)) stacks.Add(held); + } + foreach (var stack in stacks) + { + if (left == 0) break; + var origin = bay.Cargo[stack]; + var part = bay.Remove(stack, Math.Min(left, ((ICommodityStack) stack).Quantity)); + taken.Add((bay, part, origin)); + left -= ((ICommodityStack) part).Quantity; + } + } + if (left == 0) continue; + for (var at = taken.Count - 1; at >= 0; at--) taken[at].bay.TryStore(taken[at].part, taken[at].origin); + return false; + } + return true; + } + + public bool TryPut(CultRecordKey design, int units) + { + var data = _entity.ItemManager.ItemData.Get(design); + var stored = 0; + for (var left = units; left > 0;) + { + var chunk = Math.Min(left, data.MaxStack); + var part = new SimpleCommodity { Data = new CultRecordRef(design), Quantity = chunk }; + if (!_entity.CargoBays.Any(bay => bay.TryStore(part))) + { + if (stored > 0) TryTake(new[] { (design, stored) }); + return false; + } + stored += chunk; + left -= chunk; + } + return true; + } +} diff --git a/Assets/Scripts/ServerShared/Production.cs.meta b/Assets/Scripts/ServerShared/Production.cs.meta new file mode 100644 index 000000000..c56d9203a --- /dev/null +++ b/Assets/Scripts/ServerShared/Production.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 450f5de3887646f385e4142c577202b7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Provenance.cs b/Assets/Scripts/ServerShared/Provenance.cs index 71c260496..be28ef2e6 100644 --- a/Assets/Scripts/ServerShared/Provenance.cs +++ b/Assets/Scripts/ServerShared/Provenance.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using System.Linq; using GameCult.Caching; using MessagePack; @@ -35,6 +36,8 @@ public class ProvenanceLedger // A new ledger holding only lots reachable from roots, closed over Produced.Facility and Produced.Inputs. Never // mutates this: the live ledger keeps unreachable lots, because a floor pickup can still be collected after a save. + // An input whose lot is RetiredExtracted names a lot RunSave.Commit drops (no item roots it), so the reached copy of + // the Produced lot omits it rather than name a lot the saved ledger lacks (finding input-keeps-retired-lot). public ProvenanceLedger Reachable(IEnumerable roots) { var reached = new Dictionary(); @@ -44,14 +47,22 @@ public class ProvenanceLedger var id = pending.Dequeue(); if (reached.ContainsKey(id)) continue; var lot = this[id]; - reached[id] = lot; if (lot.Origin is Produced produced) { + var inputs = produced.Inputs?.Where(input => !(this[input].Origin is RetiredExtracted)).ToArray(); + if (inputs != null && inputs.Length != produced.Inputs.Length) + lot = new Lot + { + Design = lot.Design, Quality = lot.Quality, Roles = lot.Roles, Product = lot.Product, Id = lot.Id, + Origin = new Produced { Faction = produced.Faction, Station = produced.Station, Facility = produced.Facility, Inputs = inputs } + }; + reached[id] = lot; pending.Enqueue(produced.Facility); - if (produced.Inputs != null) - foreach (var input in produced.Inputs) + if (inputs != null) + foreach (var input in inputs) pending.Enqueue(input); } + else reached[id] = lot; } return new ProvenanceLedger { NextLot = NextLot, Lots = reached }; @@ -69,7 +80,7 @@ public class Lot [Key(3)] public List Roles; // The product the lot was made as: the one owner of which product names its units. Unset for unbranded lots - // (console give, presets, extracted), which brand their maker only. + // (console give, presets), which brand their maker only. [Key(4)] public CultRecordRef Product; // The quality a stat reads for one of the design's roles: the part's, capped by the lot's own final assembly @@ -109,11 +120,11 @@ public class RoleFill [Key(2)] [CultElementId] public string Id = ""; } -// Who built a lot, where, and from what. Terminus mints Attributed placeholders; Produced and Extracted are the -// forward shape for backward generation, next scope. +// Who built a lot, where, and from what. Terminus mints Attributed placeholders; Produced is the forward shape for +// backward generation, next scope. [Union(0, typeof(Attributed)), Union(1, typeof(Produced)), - Union(2, typeof(Extracted))] + Union(2, typeof(RetiredExtracted))] public abstract class Provenance { } // The Terminus placeholder: only the faction is known. No other level of the crafting pyramid is generated yet. @@ -123,7 +134,8 @@ public class Attributed : Provenance [Key(0)] public CultRecordRef Faction; } -// Built in place at a station, from a factory item's own lot and a set of input lots. +// Built in place at a station, from a factory item's own lot and a set of input lots. Inputs names the compound input +// lots; a simple input carries no lot and is not named per unit. [MessagePackObject] public class Produced : Provenance { @@ -133,12 +145,8 @@ public class Produced : Provenance [Key(3)] public int[] Inputs; } -// A raw commodity pulled from a zone. +// Key 2 held a per-source lot on mined simple commodities until ruling simple-commodities-fungible; nothing constructs or +// reads it. It is declared only because CultUnionGuard refuses an undeclared arm, so a run ledger saved before the ruling +// still loads, and RunSave.Commit drops those lots because no item roots them. Never reuse key 2. [MessagePackObject] -public class Extracted : Provenance -{ - // Zone is the zone's index in galaxy.Zones (SavedGame's convention), -1 with no galaxy; Body is the belt. - [Key(0)] public int Zone; - [Key(1)] public CultRecordRef Commodity; - [Key(2)] public CultRecordRef Body; -} +public class RetiredExtracted : Provenance { } diff --git a/Assets/Scripts/ServerShared/Recipes.cs b/Assets/Scripts/ServerShared/Recipes.cs index f9aa3ee4a..8bd6dc430 100644 --- a/Assets/Scripts/ServerShared/Recipes.cs +++ b/Assets/Scripts/ServerShared/Recipes.cs @@ -35,7 +35,8 @@ public class RecipeData [JsonProperty("upkeep"), Key(5)] public List Upkeep = new List(); - // The kind of station that runs this recipe. + // The kind of station that runs this recipe: the kind whose Facilities list Facility. A checked mirror of Facility, no longer an + // owner; follow-up recipe-station-kind-derived deletes it once every reader reads the facility. [JsonProperty("stationKind"), Key(6)] public CultRecordRef StationKind; @@ -52,6 +53,11 @@ public class RecipeData [JsonProperty("roleInputs"), Key(9)] public List RoleInputs = new List(); + // The facility gear design that runs this recipe: a GearData of HardpointType Facility holding a FacilityData. Records written + // before key 10 read it unset. + [JsonProperty("facility"), Key(10)] + public CultRecordRef Facility; + public static CultRecordKey KeyOf(CultRecordKey outputKey) => new CultRecordKey("recipe:" + outputKey.Value); } @@ -104,8 +110,8 @@ public class OutsideMarketRow [Key(5)] [CultElementId] public string Id = ""; } -// The one reader of recipes: which recipe makes a good, a recipe's role slots (RoleInputsOf), which commodities fill a role, and -// what a good is by its recipe. +// The one reader of recipes: which recipe makes a good, a recipe's role slots (RoleInputsOf), which commodities fill a role, which +// recipes a facility design runs (RunOn), and what a good is by its recipe. public static class Recipes { public static RecipeData RecipeOf(CultCache catalog, ItemData item) => @@ -134,11 +140,63 @@ public static class Recipes public static bool IsConsumerGood(CultCache catalog, RecipeData recipe) => IsCommodity(catalog.Get(recipe.Output)) && IsRoleRecipe(catalog, recipe); - // The commodities whose recipes Fill the role, ordered by key so a choice never depends on store order. - public static CultRecordKey[] Fillers(CultCache catalog, string role) => + // The commodities whose recipes Fill the role, ordered by key so a choice never depends on store order. Read from the catalog's + // filler index, which is built on the first read and rebuilt on the first read after a recipe or commodity changes. + public static CultRecordKey[] Fillers(CultCache catalog, string role) => FillerIndexes.GetValue(catalog, cache => new FillerIndex(cache)).Of(role); + + private static readonly System.Runtime.CompilerServices.ConditionalWeakTable FillerIndexes = new(); + + // Role to its fillers, derived from the recipes and owned by the catalog it was built from (one index per catalog, dropped with it). + // The catalog is read-only while a game runs, so a build serves every read; a write to a recipe or a commodity design (a test, an + // authoring batch) marks it stale, and the next read rebuilds it. It is right only for recipes written through the catalog: a + // document edited in place and never written back is outside the catalog's admission, so the index cannot see it and the scan it + // replaced could. Write an edited recipe back (every authoring path and fixture does). + private sealed class FillerIndex + { + private readonly CultCache _catalog; + private readonly object _gate = new object(); + private Dictionary _byRole; + private volatile bool _stale = true; + + public FillerIndex(CultCache catalog) + { + _catalog = catalog; + // The journal runs under the catalog's own gate and must wait for nothing, so it only raises the flag. + catalog.AddJournal(changes => + { + foreach (var change in changes) + if (Matters(change.Document) || Matters(change.PreviousDocument)) _stale = true; + }); + } + + private static bool Matters(object document) => document is RecipeData || document is SimpleCommodityData || document is CompoundCommodityData; + + public CultRecordKey[] Of(string role) + { + lock (_gate) + { + if (_stale) + { + _stale = false; + _byRole = Build(); + } + return _byRole.TryGetValue(role, out var fillers) ? fillers : Array.Empty(); + } + } + + private Dictionary Build() => + _catalog.GetAll() + .Where(recipe => recipe.Fills != null && IsCommodity(_catalog.Get(recipe.Output))) + .SelectMany(recipe => recipe.Fills.Where(role => role != null).Distinct().Select(role => (role, recipe.Output.Key))) + .GroupBy(pair => pair.role) + .ToDictionary(group => group.Key, group => group.Select(pair => pair.Key).OrderBy(key => key.Value, StringComparer.Ordinal).ToArray()); + } + + // The recipes a facility design runs, ordered by recipe key so a choice never depends on store order. The one reader of which + // recipes a facility runs; RecipeData.Facility owns it and nothing is stored on the facility. + public static RecipeData[] RunOn(CultCache catalog, CultRecordKey facilityDesign) => catalog.GetAll() - .Where(recipe => recipe.Fills != null && recipe.Fills.Contains(role) && IsCommodity(catalog.Get(recipe.Output))) - .Select(recipe => recipe.Output.Key) - .OrderBy(key => key.Value, StringComparer.Ordinal) + .Where(recipe => recipe.Facility.IsSet() && recipe.Facility.Key.Equals(facilityDesign)) + .OrderBy(recipe => RecipeData.KeyOf(recipe.Output.Key).Value, StringComparer.Ordinal) .ToArray(); } diff --git a/Assets/Scripts/ServerShared/RunStart.cs b/Assets/Scripts/ServerShared/RunStart.cs index cadd66bcc..754c61a89 100644 --- a/Assets/Scripts/ServerShared/RunStart.cs +++ b/Assets/Scripts/ServerShared/RunStart.cs @@ -27,42 +27,40 @@ public static class RunStart { SeedItems(itemManager, galaxy, ArenaStep); return galaxy.Entrance.PackedContents = ZoneGenerator.GenerateZone( - itemManager, zoneSettings, planetSettings, galaxy, galaxy.Entrance, galaxy.IsPrelude, scenario.Ambient); + itemManager, zoneSettings, planetSettings, galaxy, galaxy.Entrance, scenario.EntranceStations, scenario.Ambient); } - // Runs the scenario's Stage, then admits its player and everything it placed: each entity's stance set both ways - // with the player, a pilot for each piloted one. Returns null, with every failure listed and the arena unchanged, + // Runs a start and answers whether it produced a run: null, with the reason in `failures`, when `start` throws or + // returns nothing. The caller shows the failure and clears its run; nothing past a null may run the game. + public static Staged Launch(Func start, List failures, Action log = null) + { + Staged staged = null; + try { staged = start(); } + catch (Exception exception) + { + log?.Invoke(exception); + failures.Add(exception.Message); + } + if (staged == null && failures.Count == 0) failures.Add("the start produced no run"); + return staged; + } + + // Runs the scenario's Stage, then has the stage admit its player and everything it placed. + // Returns null, with every failure listed and the arena unchanged, // unless the whole scenario staged. public static Staged Stage(ItemManager itemManager, Zone arena, Scenario scenario, string startingHull, - TutorialGenerationSettings tutorialGenerationSettings, List failures) + List failures) { SeedItems(itemManager, arena.Galaxy, StageStep); - var stage = new ScenarioStage(itemManager, arena, startingHull, tutorialGenerationSettings); + var stage = new ScenarioStage(itemManager, arena, startingHull); scenario.Stage(stage); var reported = failures.Count; failures.AddRange(stage.Failures); if (!stage.PlayerPlaced) failures.Add("player: the scenario places no player"); if (failures.Count > reported) return null; - stage.StockUnauthoredAmmunition(); - - var player = stage.PlayerShip; - player.IsPlayerShip = true; - arena.Admit(player, piloted: false); - foreach (var placed in stage.Placed) - { - var hostile = placed.Stance == ScenarioStance.Hostile; - placed.Entity.SetIff(player, hostile); - player.SetIff(placed.Entity, hostile); - arena.Admit(placed.Entity, placed.Piloted, placed.Task); - } - - // A start state includes what a pilot knows (ruling stage-states-pilot-knowledge): its anchor is tracked from the first - // step, by the sensors' own path (info gathered past the detection threshold), so they can lose it like any track. - foreach (var placed in stage.Placed) - if (placed.Knows != null && placed.Piloted) - placed.Entity.EntityInfoGathered[placed.Knows] = (itemManager.GameplaySettings.TargetDetectionInfoThreshold + 1f) / 2f; - return new Staged { Player = player, Credits = stage.Credits, Entities = stage.Placed.Select(placed => placed.Entity).ToList() }; + stage.Admit(); + return new Staged { Player = stage.PlayerShip, Credits = stage.Credits, Entities = stage.Placed.Select(placed => placed.Entity).ToList() }; } // A new run's item draws (each lot's quality, each generated fit) come from its galaxy's seed, not the process clock, diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index cf225ab8b..01a0b876d 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -42,8 +42,7 @@ public class SavedGame [Key(10)] public SavedActionBarBinding[] ActionBarBindings; - [Key(11)] - public bool IsTutorial; + // Key(11): retired, do not reuse (a retired run-mode flag) // Read only by a save written before Standings: its entries follow galaxy.Factions order, not Factions order, so // Galaxy trusts it only when the two orders cannot differ (see Galaxy's save constructor). @@ -68,6 +67,17 @@ public class SavedGame // null in a save written before it, which then reads Relationships. [Key(16)] public List Standings; + + // Galaxy.InfluenceScale: every zone generated after Continue reads it (ZoneGenerator's factionPresence). Written only + // by RunSave.Capture and read only by Galaxy's save constructor, which refuses a save without one (0). + [Key(17)] + public float InfluenceScale; + + // Galaxy.Antagonist: the faction whose gate the galaxy has, the scope and source of the demo's raids, which every zone + // generated after Continue reads. Written only by RunSave.Capture and read only by Galaxy's save constructor; unset means + // no gate antagonist, set but not one of Factions refuses Continue. Keyed by the record, as Standings is. + [Key(18)] + public CultRecordRef Antagonist; } [MessagePackObject] @@ -122,7 +132,8 @@ public static class RunSave CurrentZoneEntity = currentZone.Entities.IndexOf(currentEntity), Entrance = Array.IndexOf(galaxy.Zones, galaxy.Entrance), Exit = Array.IndexOf(galaxy.Zones, galaxy.Exit), - IsTutorial = galaxy.IsPrelude, + InfluenceScale = galaxy.InfluenceScale, + Antagonist = galaxy.Antagonist == null ? default : cache.RefOf(galaxy.Antagonist), ActionBarBindings = actionBar, Credits = credits, Seed = galaxy.Seed @@ -223,11 +234,11 @@ public static class RunSave .ToArray(); game.Zones = keys.Select(key => new CultRecordRef(key)).ToArray(); // Every crafted item roots, Lot 0 included: a crafted item with no lot is corruption and Reachable throws on it. - // A SimpleCommodity roots only when it names a lot; Lot 0 is bought, staged or loadout stock. + // A simple commodity has no lot. var roots = zones .SelectMany(zone => zone.Contents?.Entities ?? new List()) .SelectMany(EntitySerializer.Items) - .Where(item => item != null && (item is CraftedItemInstance || item.Lot != 0)) + .OfType() .Select(item => item.Lot); cache.Commit(batch => { @@ -259,6 +270,34 @@ public static class RunSave return started; } + // A simulation starts beside the saved run and never replaces it. start runs with the saved run still in the store. + // When it returns null or throws, the records it wrote go and the saved run stays. When it returns a value, both the + // value and the Simulation that discards what start wrote come back; the saved run's records are never removed. + public static (T started, Simulation simulation) Beside(CultCache cache, Func start) where T : class + { + var saved = Records(cache); + T started = null; + try + { + started = start(); + } + finally + { + if (started == null) Remove(cache, Records(cache).Except(saved).ToArray()); + } + return started == null ? (null, null) : (started, new Simulation(saved)); + } + + // The run-record keys stored when a simulation began: everything else in the run store is the simulation's. + public sealed class Simulation + { + private readonly CultRecordKey[] _saved; + + internal Simulation(CultRecordKey[] saved) => _saved = saved; + + public void Discard(CultCache cache) => Remove(cache, Records(cache).Except(_saved).ToArray()); + } + private static CultRecordKey[] Records(CultCache cache) => cache.AllStoredDocuments .Where(stored => IsRunRecord(stored.Descriptor.DocumentType)) diff --git a/Assets/Scripts/ServerShared/Scenario.cs b/Assets/Scripts/ServerShared/Scenario.cs index 72b084866..1e970d9da 100644 --- a/Assets/Scripts/ServerShared/Scenario.cs +++ b/Assets/Scripts/ServerShared/Scenario.cs @@ -1,3 +1,6 @@ +using System; +using System.Collections.Generic; + // A scenario is one way to set up a new run (docs/scenarios-cut.md, R): a script, compiled with the game, that says // which galaxy to generate and what the run starts with. New Game lists them (Scenarios). RunStart runs one: it // generates the galaxy through GalaxyStage, the arena under Ambient, and admits what Stage placed through a @@ -22,15 +25,40 @@ public abstract class Scenario // the scenario's conditions. public virtual bool Ambient => true; - // Which galaxy the run is in: stage.Main() or stage.Prelude(). + // False: the scenario is a simulation. It starts through RunSave.Beside, so the saved run stays in the store and + // stays resumable; it is never captured or committed, and its records are discarded when it ends. The one + // declaration: nothing tests a scenario's type to decide saving. + public virtual bool Saved => true; + + // The stations the arena's zone always gets, in slot order after its story stations, whatever its seed rolls + // (ZoneGenerator). Empty: its stations are rolled like any other zone's. + public virtual IReadOnlyList EntranceStations => EntranceStationOrder.Any; + + // Which galaxy the run is in: stage.Main() or stage.Cast(cast). public abstract Galaxy Generate(GalaxyStage stage); // What the run starts with: exactly one stage.Player, and anything else the scenario places. public abstract void Stage(ScenarioStage stage); } +// A run-start placement's stance toward the player. Hostile is written as an override both ways; Neutral writes nothing, +// so the faction rule and grudges decide. public enum ScenarioStance { Neutral, Hostile } + +// One station a scenario's entrance zone must hold. Faction is a cast name Galaxy.ResolveFaction resolves (null: the zone's +// structure faction); Kind is a station-kind id, StationKindData.KeyOf (null: StationKinds.Choose picks one). +public sealed class EntranceStationOrder +{ + public string Faction { get; } + public string Kind { get; } + + public EntranceStationOrder(string faction, string kind) { Faction = faction; Kind = kind; } + + // One default order: the zone's structure faction, a chosen kind. + public static readonly IReadOnlyList Any = new[] { new EntranceStationOrder(null, null) }; + public static readonly IReadOnlyList None = Array.Empty(); +} diff --git a/Assets/Scripts/ServerShared/ScenarioStage.cs b/Assets/Scripts/ServerShared/ScenarioStage.cs index b7a19b87f..2580c629b 100644 --- a/Assets/Scripts/ServerShared/ScenarioStage.cs +++ b/Assets/Scripts/ServerShared/ScenarioStage.cs @@ -8,14 +8,18 @@ using float2 = CultMath.float2; using float3 = CultMath.float3; // The run half of a scenario's vocabulary (docs/scenarios-cut.md, R.4). A scenario's Stage builds its fits and places -// them here; nothing joins the arena until Stage returns with no failure, and then RunStart admits it all at once. +// them here; nothing joins the arena until Stage returns with no failure, and then the stage admits it all at once. // Every verb names what it could not do instead of throwing, so one bad name in a script lists every bad name. -// Designs, hulls and products are named as the catalog names them. Only RunStart builds a stage. -public sealed class ScenarioStage +// Designs, hulls and products are named as the catalog names them. +// ZoneStage is the placement vocabulary and the admission of what it placed; Zone.Admit stays the only admission. +// RunStart builds a ScenarioStage (a ZoneStage that also stages the player and authors stance); ZoneStage.Summon builds a +// ZoneStage for a running zone. A ZoneStage has no Player verb and no stance, so a summon placing a player or writing who +// fights whom is unrepresentable: a summon's stance is the faction rule's and its grudges'. +public class ZoneStage { private readonly ItemManager _items; private readonly Func _choose; - private readonly List _failures = new List(); + private protected readonly List _failures = new List(); private readonly List _placed = new List(); private int _placements; // The entities this stage built from a fit (a packed fit is a saved ship, whose cargo is its own) and those whose cargo the scenario @@ -23,13 +27,10 @@ public sealed class ScenarioStage private readonly HashSet _fitted = new HashSet(); private readonly HashSet _cargoAuthored = new HashSet(); - internal ScenarioStage(ItemManager items, Zone arena, string startingHull, TutorialGenerationSettings tutorialGenerationSettings) + internal ZoneStage(ItemManager items, Zone arena) { _items = items; Arena = arena; - StartingHull = startingHull; - TutorialGenerationSettings = tutorialGenerationSettings; - Credits = items.GameplaySettings.StartingCredits; // A design named without a product is chosen by the generator's ChooseProduct. The stage outfits with no faction, // so every maker is reachable and the run's seed draws. _choose = new LoadoutGenerator(ref items.Random, items, arena.Galaxy, arena.GalaxyZone, null, 2).ChooseProduct; @@ -37,29 +38,21 @@ public sealed class ScenarioStage public Galaxy Galaxy => Arena.Galaxy; public Zone Arena { get; } - public string StartingHull { get; } - public TutorialGenerationSettings TutorialGenerationSettings { get; } - - // What the run starts with: the gameplay settings' starting credits unless the scenario sets another amount. - public int Credits { get; set; } internal IReadOnlyList Failures => _failures; // Staging's last step: a fitted entity whose cargo the scenario did not author gets the crates its weapons draw, like every other // newly built armed entity (Loadouts.StockAmmunition). Draws nothing, so it moves no item roll. - internal void StockUnauthoredAmmunition() + private protected void StockUnauthoredAmmunition() { foreach (var entity in _fitted.Where(entity => !_cargoAuthored.Contains(entity))) Loadouts.StockAmmunition(_items, entity); } - internal bool PlayerPlaced { get; private set; } - internal Ship PlayerShip { get; private set; } internal IReadOnlyList Placed => _placed; internal sealed class Placement { public Entity Entity; - public ScenarioStance Stance; public bool Piloted; public AgentTask Task; // What the pilot already knows at the start: an entity its sensors hold a track of (Approach). Seeded through the @@ -115,42 +108,44 @@ public sealed class ScenarioStage public ScenarioFit Preset(string name) { var preset = _items.ItemData.GetAll().FirstOrDefault(loadout => loadout.Name == name); - if (preset != null) return new ScenarioFit(preset); - _failures.Add($"preset {name}: no such preset"); - return null; - } - - // The player's ship. A run has exactly one, and it is a ship hull. - public Ship Player(ScenarioFit fit, float2 at, float2 facing = default) - { - if (PlayerPlaced) + if (preset == null) { - _failures.Add("player: the scenario places a second player"); + _failures.Add($"preset {name}: no such preset"); return null; } - PlayerPlaced = true; - var entity = Build(fit, "player", at, facing); - if (entity == null) return null; - if (entity is Ship ship) return PlayerShip = ship; - _failures.Add($"player: {entity.Name} is not a ship hull"); - return null; + // A faction's boss is the zone generator's to place (boss-hulls-exclusive): Loadouts.BossOf owns which loadout it is. + if (_items.ItemData.GetAll().Any(faction => Loadouts.BossOf(_items.ItemData, faction, out _)?.Name == preset.Name)) + { + _failures.Add($"preset {name}: a faction's boss loadout is placed only by the zone generator"); + return null; + } + return new ScenarioFit(preset); } - // Anything else in the arena. A stance holds both ways between it and the player. A piloted ship gets the zone's - // pilot; an unpiloted entity has none and goes nowhere on its own unless it is placed moving: velocity is the planar - // velocity it starts with, and the sim carries it from there. A turret hull stays where it is put. - public Entity Place(ScenarioFit fit, float2 at, float2 facing = default, ScenarioStance stance = ScenarioStance.Neutral, bool piloted = false, - float2 velocity = default) + // Anything else in the arena. A piloted ship gets the zone's pilot; an unpiloted entity has none and goes nowhere on its + // own unless it is placed moving: velocity is the planar velocity it starts with, and the sim carries it from there. A + // turret hull stays where it is put. It writes no stance: who fights whom is the faction rule's (stance is ScenarioStage's). + public Entity Place(ScenarioFit fit, float2 at, float2 facing = default, bool piloted = false, float2 velocity = default) { var where = $"entity {_placements++}"; var entity = Build(fit, where, at, facing); if (entity == null) return null; entity.Velocity = velocity; if (piloted && !(entity is Ship)) _failures.Add($"{where}: {entity.Name} is not a ship hull, so it cannot be piloted"); - _placed.Add(new Placement { Entity = entity, Stance = stance, Piloted = piloted }); + _placed.Add(new Placement { Entity = entity, Piloted = piloted }); return entity; } + // A piloted ship that carries a standing haul order (ruling demo-zenith-ore-depot): its task is derived from the order at + // admission (HaulRun.TaskOf), so the order must exist by then; ScenarioStage writes its orders before it admits. A fit that is not + // a ship is Place's failure. + public Ship Hauler(ScenarioFit fit, string orderId, float2 at) + { + var ship = Place(fit, at, piloted: true) as Ship; + if (ship != null) ship.Haul = new CultRecordRef(HaulOrderData.KeyOf(orderId)); + return ship; + } + // The task a piloted entity starts on: it closes on the target and holds there (the flight's follow task, standoff // nothing), in place of the patrol circuit the zone would draw for it. The pilot starts knowing it (RunStart seeds a sensor track). A check that rests on where a pilot goes states // it here, so the pilot's course is the scenario's and not a draw. An entity that is not placed and piloted, or a @@ -195,7 +190,42 @@ public sealed class ScenarioStage } } - private Entity Build(ScenarioFit fit, string where, float2 at, float2 facing) + // Admits what was placed: Zone.Admit with a pilot for each piloted one. It writes no stance. A start state includes what a pilot knows (ruling stage-states-pilot-knowledge): its anchor is tracked + // from the first step, by the sensors' own path (info gathered past the detection threshold), so they can lose it + // like any track. The one owner of admitting placements. + private protected void AdmitPlaced() + { + foreach (var placed in _placed) + { + Arena.Admit(placed.Entity, placed.Piloted, placed.Task); + } + foreach (var placed in _placed) + if (placed.Knows != null && placed.Piloted) + placed.Entity.EntityInfoGathered[placed.Knows] = (_items.GameplaySettings.TargetDetectionInfoThreshold + 1f) / 2f; + } + + // Places ships into a running zone through the admission a run start uses: the script places with the stage's verbs, + // and the entities join with a pilot when piloted and the knowledge the script stated. A summon writes no stance: the + // faction rule decides who fights whom, and a grudge (Entity.Provoke) turns the summoned faction on whoever attacks it. + // Returns the placed entities in order, or null with every failure listed and the zone and the item stream and lot ledger unchanged. + // It draws from the live item stream and does not reseed (a reseed would give every summon the same fits). + public static IReadOnlyList Summon(ItemManager items, Zone zone, Action script, List failures) + { + var mark = items.Mark(); + var stage = new ZoneStage(items, zone); + script(stage); + failures.AddRange(stage._failures); + if (stage._failures.Count > 0) + { + items.Rewind(mark); // a refusal draws and mints nothing: the fits it built are discarded with it + return null; + } + stage.StockUnauthoredAmmunition(); + stage.AdmitPlaced(); + return stage._placed.Select(placed => placed.Entity).ToList(); + } + + private protected Entity Build(ScenarioFit fit, string where, float2 at, float2 facing) { if (fit == null) return null; // the verb that made it named why @@ -235,8 +265,107 @@ public sealed class ScenarioStage } } +// The run-start stage: a ZoneStage that also stages the player, the credits the run starts with and the hull it +// starts in, and the one place a script authors stance: a Hostile placement is hostile both ways with the player, written +// once at admission. Neutral writes nothing (the faction rule and grudges decide). Only RunStart builds one. +public sealed class ScenarioStage : ZoneStage +{ + private readonly ItemManager _runItems; + private readonly List<(string id, HaulOrderData order)> _haulOrders = new List<(string, HaulOrderData)>(); + + internal ScenarioStage(ItemManager items, Zone arena, string startingHull) : base(items, arena) + { + _runItems = items; + StartingHull = startingHull; + Credits = items.GameplaySettings.StartingCredits; + } + + public string StartingHull { get; } + + // What the run starts with: the gameplay settings' starting credits unless the scenario sets another amount. + public int Credits { get; set; } + + private readonly List _hostile = new List(); + + // Anything else in the arena, as ZoneStage.Place, with a stance toward the player: Hostile holds both ways from the start. + public new Entity Place(ScenarioFit fit, float2 at, float2 facing = default, ScenarioStance stance = ScenarioStance.Neutral, bool piloted = false, + float2 velocity = default) + { + var entity = base.Place(fit, at, facing, piloted, velocity); + if (entity != null && stance == ScenarioStance.Hostile) _hostile.Add(entity); + return entity; + } + + internal bool PlayerPlaced { get; private set; } + internal Ship PlayerShip { get; private set; } + + // The player's ship. A run has exactly one, and it is a ship hull. + public Ship Player(ScenarioFit fit, float2 at, float2 facing = default) + { + if (PlayerPlaced) + { + _failures.Add("player: the scenario places a second player"); + return null; + } + PlayerPlaced = true; + var entity = Build(fit, "player", at, facing); + if (entity == null) return null; + if (entity is Ship ship) return PlayerShip = ship; + _failures.Add($"player: {entity.Name} is not a ship hull"); + return null; + } + + // The arena's one station of a kind (what it is for, never its hull); a failure naming the kind when there is none or several. + public OrbitalEntity Station(string kindId) + { + var kind = StationKindData.KeyOf(kindId); + var found = Arena.Entities.OfType().Where(entity => entity.Kind.IsSet() && entity.Kind.Key.Equals(kind)).Take(2).ToArray(); + if (found.Length == 1) return found[0]; + _failures.Add(found.Length == 0 ? $"station {kindId}: the arena holds no station of that kind" : $"station {kindId}: the arena holds more than one station of that kind"); + return null; + } + + // A standing haul order between two of the arena's stations, by their orbits (ruling transit-depots-buy-for-onward-haul). + // Queued here and written only in Admit, so a refused stage writes nothing. + public void HaulOrder(string id, OrbitalEntity from, OrbitalEntity to, IEnumerable> goods, string commitment) + { + if (from == null || to == null) return; // the verb that found them named why + if (!from.OrbitData.IsSet() || !to.OrbitData.IsSet()) + { + _failures.Add($"haul order {id}: a station with no orbit record cannot be a haul order's end"); + return; + } + _haulOrders.Add((id, new HaulOrderData + { + From = new CultRecordRef(from.OrbitData), To = new CultRecordRef(to.OrbitData), + Goods = goods.ToList(), Commitment = commitment + })); + } + + // Run start's admission: stock unauthored ammunition, the player, then everything placed. Nothing at admission or + // activation reads cargo (ammunition is read when a weapon fires), so stocking is not ordered by admission; it keeps + // the run start's order. + internal void Admit() + { + if (_haulOrders.Count > 0) + _runItems.ItemData.Commit(batch => + { + foreach (var (id, order) in _haulOrders) batch.Upsert(typeof(HaulOrderData), order, HaulOrderData.KeyOf(id)); + }); + StockUnauthoredAmmunition(); + PlayerShip.IsPlayerShip = true; + Arena.Admit(PlayerShip, piloted: false); + foreach (var entity in _hostile) + { + entity.SetIff(PlayerShip, true); + PlayerShip.SetIff(entity, true); + } + AdmitPlaced(); + } +} + // What a scenario places: a fit built from named designs or a preset, or a ship generated as the game generates them. -// Only ScenarioStage makes one. +// Only a ZoneStage makes one. public sealed class ScenarioFit { internal readonly Loadout Loadout; diff --git a/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs b/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs index beb4235da..bdfc153fd 100644 --- a/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs +++ b/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs @@ -13,7 +13,7 @@ public sealed class AiFusedDiscipline : Scenario public static readonly CultMath.float2 Hostile = float2(0, 700), Neutral = float2(500, 300); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs index 8846d006b..6da63b0e2 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs @@ -26,7 +26,7 @@ public sealed class Arcs : Scenario // holding every gun down. The guided launchers fire only on a lock, which that run cannot give them, so they carry the default three crates. public const int TurretAmmoCrates = 22, PlayerAmmoCrates = 42, PlayerMissileCrates = 3; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Belt.cs b/Assets/Scripts/ServerShared/Scenarios/Belt.cs index 50c815f6d..7058b993b 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Belt.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Belt.cs @@ -17,7 +17,7 @@ public sealed class Belt : Scenario public override uint Seed => 86; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Crossing.cs b/Assets/Scripts/ServerShared/Scenarios/Crossing.cs index e77f50166..be5a1fe06 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Crossing.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Crossing.cs @@ -33,7 +33,7 @@ public sealed class Crossing : Scenario public const float ProjectorRange = 997f; public static readonly CultMath.float2 Waiting = Origin + float2(0, ProjectorRange * .8f); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs b/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs index f4dce7be7..91a00019c 100644 --- a/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs +++ b/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs @@ -1,11 +1,15 @@ +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; using float2 = CultMath.float2; // The demo: one gate, one region and one boss, with a fixed cast. The Pirates are the protagonist's ostensible // employer, Zhestokost the antagonist whose home is the boss zone and the exit, Lucent Media and Aeronautics Unlimited -// the neutrals. A prelude galaxy of that cast; the player, who is not a Pirate, flies the base Longinus. +// the neutrals. A galaxy of that cast at half influence; the player, who is not a Pirate, flies the base Longinus. Its +// entrance holds two stations on every seed: Aeronautics Unlimited's Zenith trade hub and the Pirates' refinery. public sealed class DemoTerminus : Scenario { - public static readonly TutorialGenerationSettings Cast = new TutorialGenerationSettings + public static readonly GalaxyCast Cast = new GalaxyCast { ProtagonistFaction = "Pirates", AntagonistFaction = "Zhe", @@ -13,7 +17,16 @@ public sealed class DemoTerminus : Scenario NeutralFactions = new[] { "Aero" }, QuestFaction = null, ZoneCount = 64, - LinkDensity = .5f + LinkDensity = .5f, + InfluenceScale = .5f + }; + + // Zenith (ruling demo-zenith-ore-depot) and the Pirates' processing station (ruling demo-processing-station-buys-ore), + // named from the cast so the cast and the orders cannot drift. + public override IReadOnlyList EntranceStations { get; } = new[] + { + new EntranceStationOrder(Cast.NeutralFactions[0], "trade-hub"), + new EntranceStationOrder(Cast.ProtagonistFaction, "processing") }; public override string Name => "Terminus (Demo)"; @@ -23,7 +36,7 @@ public sealed class DemoTerminus : Scenario public override Galaxy Generate(GalaxyStage stage) { - var galaxy = stage.Prelude(Cast); + var galaxy = stage.Cast(Cast); galaxy.PlaceGate(galaxy.ResolveFaction(Cast.AntagonistFaction)); return galaxy; } @@ -38,5 +51,16 @@ public sealed class DemoTerminus : Scenario foreach (var neutral in Cast.NeutralFactions) galaxy.FactionRelationships[galaxy.ResolveFaction(neutral)] = FactionRelationship.Neutral; stage.Player(stage.Generated("Longinus"), float2.zero); + + // Zenith's silo buys the ores the refinery's gear draws (ruling demo-zenith-ore-depot), by a standing order to the + // refinery, and a hauler of Zenith's faction carries it (ore-haul-run). + var zenith = stage.Station("trade-hub"); + var refinery = stage.Station("processing"); + if (refinery == null) return; + var items = refinery.ItemManager; + var ores = StationWants.Of(refinery).Where(good => FieldKinds.IsOre(items.ItemData, items.ItemData.Get(new CultRecordRef(good)))) + .OrderBy(good => good.Value, System.StringComparer.Ordinal).Select(good => new CultRecordRef(good)); + stage.HaulOrder("demo-terminus-ore", zenith, refinery, ores, "scenario:demo-terminus"); + stage.Hauler(stage.Generated(null, zenith.Faction), "demo-terminus-ore", stage.Arena.GetOrbitPosition(zenith.OrbitData)); } } diff --git a/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs b/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs index 43d23d0b3..1b853571c 100644 --- a/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs +++ b/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs @@ -14,7 +14,7 @@ public sealed class DjinniShakedown : Scenario // Where the targets sit: the ballistic mount faces +z, so Ahead is inside its arc and Abeam outside it. public static readonly float2 Ahead = new float2(0, 400), Abeam = new float2(400, 0); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Duel.cs b/Assets/Scripts/ServerShared/Scenarios/Duel.cs index 67bca118d..508277643 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Duel.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Duel.cs @@ -10,7 +10,7 @@ public sealed class Duel : Scenario public override uint Seed => 104; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs b/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs index 7498465c3..8f3fd024e 100644 --- a/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs +++ b/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs @@ -26,7 +26,7 @@ public sealed class FusedRounds : Scenario // The shooter is staged at this quality, so the damage its Cluster Cannon deals does not ride the item stream. public const float StagedQuality = .6f; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs b/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs new file mode 100644 index 000000000..96b401457 --- /dev/null +++ b/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs @@ -0,0 +1,18 @@ +using static CultMath.math; + +// Nibu's private simulation (ruling terminus-boots-into-ifl): New Game boots it, nothing in it is saved, and its +// wormhole asks to leave and starts a Terminus run (ruling ifl-wormhole-exit-standin). It stages the Longinus until +// the Nibu stand-in hull exists (ruling nibu-demo-hull-agent-standin); swapping the hull is the one line below. +public sealed class InfiniteFunLand : Scenario +{ + public override string Name => "Infinite Fun Land"; + public override string Id => "infinite-fun-land"; + public override string Brief => "Nibu's private simulation. Nothing in it is saved; leaving it starts a Terminus run."; + public override uint Seed => 7; + public override bool Ambient => false; + public override bool Saved => false; + + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); + + public override void Stage(ScenarioStage stage) => stage.Player(stage.Generated("Longinus"), float2(0, 0)); +} diff --git a/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs.meta b/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs.meta new file mode 100644 index 000000000..edf080d2b --- /dev/null +++ b/Assets/Scripts/ServerShared/Scenarios/InfiniteFunLand.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5a68fbe628ad4a49b947a97d4118c703 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs b/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs index 61a798b1c..efd13e1aa 100644 --- a/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs +++ b/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs @@ -10,7 +10,7 @@ public sealed class LauncherAngles : Scenario public override uint Seed => 105; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/LockOn.cs b/Assets/Scripts/ServerShared/Scenarios/LockOn.cs index 4f8c4dfa9..8e14c3ff6 100644 --- a/Assets/Scripts/ServerShared/Scenarios/LockOn.cs +++ b/Assets/Scripts/ServerShared/Scenarios/LockOn.cs @@ -35,7 +35,7 @@ public sealed class LockOn : Scenario _quality = quality; } - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs b/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs index 18e158247..692a5adbc 100644 --- a/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs +++ b/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs @@ -8,7 +8,7 @@ public sealed class LongHaul : Scenario "warp, quit and Continue keep items, tier and brand; death disables Continue."; public override uint Seed => 106; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) => stage.Player(stage.Generated(stage.StartingHull), float2.zero); diff --git a/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs b/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs index 3e4482d3c..3f7e4b1df 100644 --- a/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs +++ b/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using float2 = CultMath.float2; // The full galaxy: factions drawn from the catalog, bosses on the road to the exit, entered in the starting hull. @@ -7,6 +8,8 @@ public sealed class MainGalaxy : Scenario public override string Id => "main-galaxy"; public override string Brief => "The full galaxy: factions drawn at random, bosses guarding the road to the exit."; + public override IReadOnlyList EntranceStations => EntranceStationOrder.None; + public override Galaxy Generate(GalaxyStage stage) => stage.Main(); public override void Stage(ScenarioStage stage) => diff --git a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs index 2e490a2a6..7bde23745 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs @@ -22,7 +22,7 @@ public sealed class Pursuit : Scenario public override uint Seed => 111; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs b/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs index 88cdd3fdb..384a7f286 100644 --- a/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs +++ b/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs @@ -15,7 +15,7 @@ public sealed class RefusedRounds : Scenario // The one target, ahead of the nose: inside every forward mount's arc. public static readonly CultMath.float2 Target = float2(0, 300); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs b/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs index 752b33e28..615d6b139 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs @@ -3,9 +3,14 @@ // editor and development builds. public static class Scenarios { - public static readonly Scenario[] Modes = { new DemoTerminus() }; + // New Game boots Nibu's simulation; Terminus is the run its exit launches (a development build lists it too). + public static readonly Scenario Simulation = new InfiniteFunLand(); - public static readonly Scenario[] Development = { new TutorialGalaxy(), new MainGalaxy() }; + public static readonly Scenario Terminus = new DemoTerminus(); + + public static readonly Scenario[] Modes = { Simulation }; + + public static readonly Scenario[] Development = { new MainGalaxy(), Terminus }; public static readonly Scenario[] Tests = { diff --git a/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs b/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs index 2f3dff97b..ccef7e151 100644 --- a/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs +++ b/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs @@ -10,7 +10,7 @@ public sealed class StarvedReactor : Scenario public override uint Seed => 102; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs b/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs deleted file mode 100644 index 1ff521865..000000000 --- a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs +++ /dev/null @@ -1,17 +0,0 @@ -using float2 = CultMath.float2; - -// New Game as it has always been: a prelude galaxy, entered in the starting hull of the protagonist faction. -public sealed class TutorialGalaxy : Scenario -{ - public override string Name => "Tutorial Galaxy"; - public override string Id => "tutorial-galaxy"; - public override string Brief => "A small galaxy of fixed factions, entered in a ship of the protagonist faction."; - - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); - - public override void Stage(ScenarioStage stage) - { - var protagonist = stage.Galaxy.ResolveFaction(stage.TutorialGenerationSettings.ProtagonistFaction); - stage.Player(stage.Generated(stage.StartingHull, protagonist), float2.zero); - } -} diff --git a/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs b/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs index 0817cfa80..f6f8eb337 100644 --- a/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs +++ b/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs @@ -14,7 +14,7 @@ public sealed class WeaponFeel : Scenario // The one target, ahead of the nose: inside every forward mount's arc. public static readonly CultMath.float2 Target = float2(0, 400); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 1d83bd692..450f07048 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -94,8 +94,10 @@ public class SectorGenerationSettings public int BossCount; } -[Serializable, MessagePackObject(keyAsPropertyName:true), JsonObject] -public class TutorialGenerationSettings +// The fixed cast of a galaxy a scenario generates through GalaxyStage.Cast: who plays which part, how big the galaxy is, +// and how far the factions' authored influence reaches (Galaxy.InfluenceOf). Held by the scenario that casts it; no +// asset or store holds one. +public class GalaxyCast { public string ProtagonistFaction; public string AntagonistFaction; @@ -106,6 +108,8 @@ public class TutorialGenerationSettings public int ZoneCount = 32; // Zones per resource province (Provinces.Partition): calibration, not a gate. public int ProvinceZones = Provinces.DefaultZonesPerProvince; + // Multiplies every faction's authored InfluenceDistance in this galaxy (rounding up); 1 leaves them as authored. + public float InfluenceScale = 1; } [Serializable, MessagePackObject(keyAsPropertyName:true), JsonObject] @@ -184,7 +188,18 @@ public class GameplaySettings public float SellFraction = .5f; // What a station charges to restore worn gear, as a fraction of the price of the wear. public float RepairFraction = .25f; - public int StartingCredits = 15000000; + // Start rule (a sim-tuned knob, economy-numbers-are-sim-tuned-knobs): the derived price of the cheapest ballistic design above the + // starter Light Machine Gun (a Slug Rifle, 3138), rounded up to a thousand. It buys one upgrade, not the ladder + // (top-gear-within-one-region-run). + public int StartingCredits = 4000; + // A tuning tolerance, not a price: `economy balance` flags a chain link whose implied wage falls outside [median / k, median x k]. + public float EconomyWageSpread = 2; + // Tuning targets like it, not gates: the band `economy balance --loop` checks the width of an offered Weapon or Gear ladder against + // (dearest over cheapest offered design in a category; ruling ladder-band-weapons-and-gear, 10-30x), and the band of sorties at the + // median net it takes to afford the dearest design of such a category (rulings top-tier-per-item and top-gear-within-one-region-run, + // about 10-20 sorties). 0 means unset: the widths and sorties are reported and nothing is a fault. + public float EconomyLadderMin = 10, EconomyLadderMax = 30; + public float EconomySortiesMin = 10, EconomySortiesMax = 20; public float DurabilityQualityExponent = 2; public float DurabilityQualityMin = 2; public float DurabilityQualityMax = .25f; diff --git a/Assets/Scripts/ServerShared/Ship.cs b/Assets/Scripts/ServerShared/Ship.cs index 1266f5c90..922ab91b5 100644 --- a/Assets/Scripts/ServerShared/Ship.cs +++ b/Assets/Scripts/ServerShared/Ship.cs @@ -48,6 +48,16 @@ public class Ship : Entity public bool WormholeAnimationInProgress => _enteringWormhole || _exitingWormhole; + // How deep into the wormhole the ship is, 0..1: rising while entering, falling while exiting, 0 otherwise. Derived + // from the animation; presenters read it (the screen warp) and nothing in the sim does. + public float WormholeWarp => _enteringWormhole ? _wormholeAnimationProgress + : _exitingWormhole ? 1 - _wormholeAnimationProgress + : 0; + + // The wormhole the ship is at in the current half: the one it dives into, then the one it emerges from. Presenters + // read it (the screen warp centres on it); it is the sim's own position, so it needs no copy elsewhere. + public float2 WormholePosition => _wormholePosition; + public event Action OnExitedWormhole; public event Action OnEnteredWormhole; diff --git a/Assets/Scripts/ServerShared/ShipAuthoring.cs b/Assets/Scripts/ServerShared/ShipAuthoring.cs index 8441d0332..a2dce3a8f 100644 --- a/Assets/Scripts/ServerShared/ShipAuthoring.cs +++ b/Assets/Scripts/ServerShared/ShipAuthoring.cs @@ -114,17 +114,14 @@ public static class ShipAuthoringStore cache.UpsertAsync(typeof(ShipAuthoring), visual, ShipModCatalog.AuthoringKey(visual.Id)).GetAwaiter().GetResult(); } - // A package's product by one maker. These two are the only product writers; the key is the ship and the maker, so a - // maker has at most one product of the hull and writing again replaces it. + // A package's product by one maker, written when a package is made (the key is the ship and the maker); ship-authoring push + // is the product writer on an existing package, adds, changes and removals alike. public static void WriteProduct(CultCache cache, string shipId, FactionProductData product) => cache.UpsertAsync(typeof(FactionProductData), product, ShipModCatalog.ProductKey(shipId, product.Manufacturer.Key)).GetAwaiter().GetResult(); - public static bool DeleteProduct(CultCache cache, string shipId, CultRecordKey maker) => - cache.Remove(ShipModCatalog.ProductKey(shipId, maker)); - // A new mod hull that flies like a shipped one. Every member of the reference is copied through the type's own - // MessagePack round trip, so a member added to HullData later is copied too; then the six that are the shipped ship's - // own body and layout are reset: Name, Shape (one occupied cell, so the record loads), Hardpoints, Prefab, Schematic, + // MessagePack round trip, so a member added to HullData later is copied too; then the seven that are the shipped ship's + // own body and layout are reset: Name, Shape (one occupied cell, so the record loads), Hardpoints, Prefab, Schematic, Kind, // and Visual, which names this mod's visual record. public static HullData HullLike(HullData reference, string name, string shipId) { @@ -135,6 +132,8 @@ public static class ShipAuthoringStore hull.Hardpoints = new List(); hull.Prefab = null; hull.Schematic = null; + // A station's kind is its own fact, written by ship-authoring kind; a like hull's is never copied. + hull.Kind = default; hull.Visual = new CultRecordRef(ShipModCatalog.AuthoringKey(shipId)); return hull; } @@ -143,8 +142,11 @@ public static class ShipAuthoringStore // its deterministic key, the hull naming that visual by its typed ref, and the hull's products, each at its maker's key. public static (HullData Hull, ShipAuthoring Visual, FactionProductData[] Products) Load(string path) { - RefuseLegacyEmbeddedHull(path); - try { return LoadRecords(path); } + try + { + using var cache = Open(path); + return Load(cache, path); + } catch (Exception error) when (error is InvalidDataException or MessagePackSerializationException) { throw new InvalidOperationException($"{path}: a record does not decode as its schema: {error.Message}", error); @@ -155,6 +157,14 @@ public static class ShipAuthoringStore } } + // The same structure over a cache the caller opened on path, so a writer commits through the cache it loaded from. + // The records returned are the cache's own instances. + public static (HullData Hull, ShipAuthoring Visual, FactionProductData[] Products) Load(CultCache cache, string path) + { + RefuseLegacyEmbeddedHull(path); + return LoadRecords(cache, path); + } + // Key 1 of ShipAuthoring held the whole hull before S1. The type no longer has that member, so a deserialized record // shows nothing of it, and a file that still carries one would load as a ship silently ignoring its old hull. The // raw payload is the only place the old shape is visible. @@ -188,9 +198,8 @@ public static class ShipAuthoringStore private const int RetiredHullKey = 1; - private static (HullData Hull, ShipAuthoring Visual, FactionProductData[] Products) LoadRecords(string path) + private static (HullData Hull, ShipAuthoring Visual, FactionProductData[] Products) LoadRecords(CultCache cache, string path) { - using var cache = Open(path); var hulls = cache.GetAll().ToArray(); var visuals = cache.GetAll().ToArray(); if (visuals.Length != 1) diff --git a/Assets/Scripts/ServerShared/ShipModCatalog.cs b/Assets/Scripts/ServerShared/ShipModCatalog.cs index e9ed613a2..7d5582269 100644 --- a/Assets/Scripts/ServerShared/ShipModCatalog.cs +++ b/Assets/Scripts/ServerShared/ShipModCatalog.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using GameCult.Caching; using Newtonsoft.Json.Linq; +using System.Numerics; using System.Text; // Builds the one catalog snapshot CultCache needs. Sources remain the shipped catalog and each @@ -110,6 +111,7 @@ public static class ShipModCatalog if (shipIds.Contains(ship.Id)) Exclude(directory, $"ship ID collides with an existing catalog ship authoring record."); if (StationKinds.HullKindFault(cache, hull) is { } kindFault) Exclude(directory, kindFault); + if (MarketFault(cache, ship, package.Products) is { } marketFault) Exclude(directory, marketFault); foreach (var product in package.Products) { if (!factionKeys.Contains(product.Manufacturer.Key)) @@ -157,6 +159,26 @@ public static class ShipModCatalog } } + // Why a package's products cannot join the catalog, or null; the one judgement Compose and `ship-authoring validate` share. + // `items` is the shipped catalog. A product's bin may name only a product line the shipped catalog holds or one of the + // package's own products (and that line must not be a bin itself): the catalog read refuses any other bin, and a line in + // another package is no promise, since packages compose independently. With every bin resolved, a hull offered through any of its + // products is drawn on the map and the schematic by its lines (ShipModVisual.BuildLineMesh builds nothing from none), so an + // offered hull without any is refused; an unoffered stand-in is left alone. Offered is LoadoutGenerator.IsOffered, the one + // reader of NotOffered (ruling off-market-is-unoffered-product), resolving a line among the package's own products too. + public static string MarketFault(CultCache items, ShipAuthoring ship, FactionProductData[] products) + { + var own = new Dictionary(); + foreach (var product in products) own[ProductKey(ship.Id, product.Manufacturer.Key)] = product; + FactionProductData LineOf(CultRecordRef line) => items.Get(line) ?? (own.TryGetValue(line.Key, out var found) ? found : null); + foreach (var product in products.Where(product => product.Bin != null)) + if (LineOf(product.Bin.Line) is not { } line || line.Bin != null) + return $"{ship.Id}: product '{product.Name}' bins a line that is neither an unbinned shipped product nor an unbinned product of this package."; + if (ship.SchematicLines != null && ship.SchematicLines.Any(line => line?.Points != null && line.Points.Length > 0)) return null; + return products.Any(product => LoadoutGenerator.IsOffered(product, LineOf)) + ? $"{ship.Id}: the hull is offered on the market but has no schematic lines." : null; + } + public static Package ReadPackage(string shipPath) { var path = Path.GetFullPath(shipPath); @@ -239,7 +261,7 @@ public static class ShipModCatalog private static string RemovedRoot(string modsRoot) => Path.Combine(Path.GetDirectoryName(Path.GetFullPath(modsRoot).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)), "RemovedMods"); - private static Package Bind(HullData hull, ShipAuthoring ship, FactionProductData[] products, string directory, string path) + internal static Package Bind(HullData hull, ShipAuthoring ship, FactionProductData[] products, string directory, string path) { if (!string.Equals(Path.GetFileName(directory), ship.Id, StringComparison.Ordinal)) throw new InvalidOperationException($"{path}: ship ID must match its package directory name."); @@ -251,17 +273,19 @@ public static class ShipModCatalog foreach (var anchor in ship.Anchors) if (!modelNodes.ContainsKey(anchor.ModelNodeId)) throw new InvalidOperationException($"{ship.Id}: model has no node with aetheria.id={anchor.ModelNodeId} for anchor {anchor.Id}."); - // Assemble reads a renderer or collider mesh from these anchors' nodes and refuses without one, and reads the shield - // node's scale as three positive radii (ruling thrusters-radiators-are-meshes). These refusals stand in for Assemble's - // throws, so a package Compose includes is one the importer's assembler can build; the exhaust emission surface and - // the glowing radiator are meshes by that same ruling. A weapon mount and a tractor may be empties. + // Assemble reads a renderer or collider mesh from these anchors' nodes, and the shield node's scale as three positive + // radii (ruling thrusters-radiators-are-meshes). These refusals cover everything the package's files say about whether + // the importer can build a node (skin, dangling or empty mesh, not only "names a mesh") and are Assemble's only judge, + // so a package Compose includes is one the importer's assembler can build; the exhaust emission surface and the + // glowing radiator are meshes by that same ruling. A weapon mount and a tractor may be empties. foreach (var anchor in ship.Anchors) if ((anchor.Role == "thruster-emitter" || anchor.Role == "radiator-mesh" || anchor.Role == "map-icon" || anchor.Role == "hull-collider") && !modelNodes[anchor.ModelNodeId].HasMesh) - throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} needs a mesh, but model node {anchor.ModelNodeId} has none."); + throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} needs a mesh, but model node {anchor.ModelNodeId} has none the importer can build."); foreach (var anchor in ship.Anchors) if (anchor.Role == "shield" && !modelNodes[anchor.ModelNodeId].PositiveScale) throw new InvalidOperationException($"{ship.Id}: shield anchor {anchor.Id} needs three positive scale radii on model node {anchor.ModelNodeId}, with no matrix."); + BindExhaust(hull, ship, modelNodes, modelPath); BindRig(ship, modelNodes); CultRecordRefs.Validate(hull); return new Package @@ -271,6 +295,166 @@ public static class ShipModCatalog }; } + // A thruster emitter's mesh is the surface its exhaust is born from, along each triangle's normal, so the mesh has to face + // the way the exhaust goes. Every thruster is a directional thruster today: its Rotation faces its exhaust, the push + // is the opposite way, and an emitter triangle whose normal has a non-negative dot with the push would fire exhaust + // along it (a closed box fires both ways). A thruster of another class, a ring thruster whose exhaust leaves radially, + // is not this rule's to judge: it would come with its own class on the hardpoint and its own rule beside this one. + private static void BindExhaust(HullData hull, ShipAuthoring ship, Dictionary nodes, string modelPath) + { + var emitters = ship.Anchors.Where(anchor => anchor.Role == "thruster-emitter").ToArray(); + if (emitters.Length == 0) return; + var model = GlbGeometry.Read(modelPath); + foreach (var anchor in emitters) + { + var hardpoint = hull.Hardpoints.FirstOrDefault(candidate => candidate.Type == HardpointType.Thruster && candidate.Transform == anchor.Id); + // An emitter anchor with no thruster hardpoint is already a package fault: ShipAuthoringStore.Validate (run by Read and + // PackageOf before Bind) refuses a mount-role anchor that is not the mount of a hardpoint of its type. + if (hardpoint == null) continue; + var facing = hardpoint.Rotation.Direction(); + // The model's frame is glTF's, nose toward +Z and port toward +X (the Blender kit's nose at -Y and port at +X, + // through the exporter's Y-up conversion): a hardpoint facing (x, y) in the grid faces (-x, 0, y) in the model. + var push = -new Vector3(-facing.x, 0f, facing.y); + var wrong = model.Normals((int)nodes[anchor.ModelNodeId].Index).Count(normal => Vector3.Dot(normal, push) >= 0f); + if (wrong > 0) + throw new InvalidOperationException($"{ship.Id}: thruster emitter {anchor.Id} has {wrong} face or vertex normal(s) that do not face its exhaust " + + $"({hardpoint.Rotation}); a directional thruster's emitter fires only along its exhaust, so it must be one-sided, not a closed box."); + } + } + + // The triangles of a GLB as the node tree places them, read for the one question the emitter rule asks: which way each + // face points. Float positions and normals, indices of 1, 2 or 4 bytes or none, no sparse, no compression: a model the + // exporter writes. Anything else is refused as unreadable rather than guessed at. + private sealed class GlbGeometry + { + private readonly JObject _json; + private readonly byte[] _bin; + private readonly string _path; + + private GlbGeometry(JObject json, byte[] bin, string path) { _json = json; _bin = bin; _path = path; } + + public static GlbGeometry Read(string path) + { + var bytes = File.ReadAllBytes(path); + var jsonLength = (int)BitConverter.ToUInt32(bytes, 12); + var json = JObject.Parse(Encoding.UTF8.GetString(bytes, 20, jsonLength)); + var at = 20 + jsonLength; + var bin = at + 8 <= bytes.Length && BitConverter.ToUInt32(bytes, at + 4) == 0x004E4942u + ? bytes.Skip(at + 8).Take((int)BitConverter.ToUInt32(bytes, at)).ToArray() : Array.Empty(); + return new GlbGeometry(json, bin, path); + } + + // Unit normals in the model frame: each triangle's face normal (its winding, flipped when the node's world transform + // mirrors, as glTF says) and each vertex normal the primitive carries. + public IEnumerable Normals(int node) + { + var world = World(node); + var mirrored = world.GetDeterminant() < 0f; + var meshIndex = (int?)_json["nodes"][node]["mesh"]; + if (meshIndex == null) yield break; + foreach (var primitive in (JArray)_json["meshes"][meshIndex.Value]["primitives"]) + { + var attributes = (JObject)primitive["attributes"]; + if (primitive["extensions"] is JObject extensions && extensions.Properties().Any(p => HidesGeometry(p.Name))) + throw Unreadable($"mesh {meshIndex} is compressed by {extensions.Properties().First(p => HidesGeometry(p.Name)).Name}"); + var normalMatrix = Matrix4x4.Invert(world, out var inverse) ? Matrix4x4.Transpose(inverse) : throw Unreadable($"node {node} has a transform that cannot be inverted"); + var positions = Vectors((int)attributes["POSITION"]).Select(point => Vector3.Transform(point, world)).ToArray(); + var indices = primitive["indices"] == null ? Enumerable.Range(0, positions.Length).ToArray() : Indices((int)primitive["indices"]); + for (var i = 0; i + 2 < indices.Length; i += 3) + { + var face = Vector3.Cross(positions[indices[i + 1]] - positions[indices[i]], positions[indices[i + 2]] - positions[indices[i]]); + if (face.LengthSquared() < 1e-12f) continue; + yield return Vector3.Normalize(mirrored ? -face : face); + } + if (attributes["NORMAL"] != null) + foreach (var normal in Vectors((int)attributes["NORMAL"])) + if (normal.LengthSquared() > 1e-12f) yield return Vector3.Normalize(Vector3.TransformNormal(normal, normalMatrix)); + } + } + + // Row-vector matrices, so a child's world is its local times its parent's world. + private Matrix4x4 World(int node) + { + var parents = new Dictionary(); + var nodes = (JArray)_json["nodes"]; + for (var parent = 0; parent < nodes.Count; parent++) + foreach (var child in nodes[parent]["children"]?.Select(token => (int)token) ?? Enumerable.Empty()) parents[child] = parent; + var world = Matrix4x4.Identity; + for (int at = node, steps = 0; steps <= nodes.Count; steps++) + { + world *= Local((JObject)nodes[at]); + if (!parents.TryGetValue(at, out at)) break; + } + return world; + } + + private static Matrix4x4 Local(JObject node) + { + if (node["matrix"] is JArray m) + { + var v = m.Select(token => (float)token).ToArray(); + return new Matrix4x4(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13], v[14], v[15]); + } + float[] Of(string key, float[] fallback) => node[key] is JArray a ? a.Select(token => (float)token).ToArray() : fallback; + var scale = Of("scale", new[] { 1f, 1f, 1f }); + var rotation = Of("rotation", new[] { 0f, 0f, 0f, 1f }); + var translation = Of("translation", new[] { 0f, 0f, 0f }); + return Matrix4x4.CreateScale(scale[0], scale[1], scale[2]) * + Matrix4x4.CreateFromQuaternion(new Quaternion(rotation[0], rotation[1], rotation[2], rotation[3])) * + Matrix4x4.CreateTranslation(translation[0], translation[1], translation[2]); + } + + // The bytes an accessor reads from: its view's slice of the BIN chunk, at the view's stride. + private (int Offset, int Stride, int Count, int Component, string Type) Locate(int accessor) + { + var a = (JObject)_json["accessors"][accessor]; + if (a["sparse"] != null || a["bufferView"] == null) throw Unreadable($"accessor {accessor} is sparse or has no buffer view"); + var view = (JObject)_json["bufferViews"][(int)a["bufferView"]]; + if (view["extensions"] is JObject viewExtensions && viewExtensions.Properties().Any(p => HidesGeometry(p.Name))) + throw Unreadable($"accessor {accessor} is compressed by {viewExtensions.Properties().First(p => HidesGeometry(p.Name)).Name}"); + var component = (int)a["componentType"]; + var type = (string)a["type"]; + var width = (component == 5126 || component == 5125 ? 4 : component == 5123 ? 2 : 1) * (type == "VEC3" ? 3 : 1); + var offset = ((int?)view["byteOffset"] ?? 0) + ((int?)a["byteOffset"] ?? 0); + var stride = (int?)view["byteStride"] ?? width; + var count = (int)a["count"]; + if (offset < 0 || count < 0 || (count > 0 && offset + (long)(count - 1) * stride + width > _bin.Length)) throw Unreadable($"accessor {accessor} reaches past the BIN chunk"); + return (offset, stride, count, component, type); + } + + private Vector3[] Vectors(int accessor) + { + var (offset, stride, count, component, type) = Locate(accessor); + if (component != 5126 || type != "VEC3") throw Unreadable($"accessor {accessor} is not float VEC3"); + var result = new Vector3[count]; + for (var i = 0; i < count; i++) + { + var at = offset + i * stride; + result[i] = new Vector3(BitConverter.ToSingle(_bin, at), BitConverter.ToSingle(_bin, at + 4), BitConverter.ToSingle(_bin, at + 8)); + } + return result; + } + + private int[] Indices(int accessor) + { + var (offset, stride, count, component, type) = Locate(accessor); + if (type != "SCALAR" || component != 5121 && component != 5123 && component != 5125) throw Unreadable($"accessor {accessor} is not an index accessor"); + var result = new int[count]; + for (var i = 0; i < count; i++) + { + var at = offset + i * stride; + result[i] = component == 5121 ? _bin[at] : component == 5123 ? BitConverter.ToUInt16(_bin, at) : (int)BitConverter.ToUInt32(_bin, at); + } + return result; + } + + // The extensions that store geometry in a form this reader does not decode; any other (materials, variants) leaves the + // positions and normals where the accessors say. + private static bool HidesGeometry(string extension) => extension == "KHR_draco_mesh_compression" || extension == "EXT_meshopt_compression"; + + private InvalidOperationException Unreadable(string reason) => new InvalidOperationException($"{_path}: emitter geometry is unreadable: {reason}."); + } + // The rig the record states must be the rig the model has: every joint is a node, each joint's Parent and each mount's // Joint is the nearest joint above its node, ancestors without an id being walked through by ReadNodeIds, and a radiator // mesh sits under no joint. @@ -309,7 +493,23 @@ public static class ShipModCatalog private static bool PositiveScale(JObject node) => node["matrix"] == null && (node["scale"] == null || node["scale"].Select(component => (double)component).All(component => component > 0)); - // GLB is the xenos asset boundary. Only its node extras, whether each node names a mesh, and its nearest identified ancestor's node index + // A mesh the importer builds as a plain mesh node: no skin (glTFast makes a skinned node a SkinnedMeshRenderer, which + // Assemble's MeshRenderer/MeshFilter reads cannot see), a mesh index inside meshes, at least one primitive, and every + // primitive with POSITION and a mode absent or 4 (triangles). Geometry accessors and buffers are not read. + private static bool BuildsMesh(JObject json, JObject node) + { + if (node["skin"] != null && node["skin"].Type != JTokenType.Null) return false; + var meshes = json["meshes"] as JArray; + if (node["mesh"] == null || node["mesh"].Type != JTokenType.Integer || meshes == null) return false; + var index = (long)node["mesh"]; + if (index < 0 || index >= meshes.Count) return false; + var primitives = (meshes[(int)index] as JObject)?["primitives"] as JArray; + return primitives != null && primitives.Count > 0 && primitives.All(primitive => + primitive is JObject p && p["attributes"]?["POSITION"] != null && + (p["mode"] == null || (p["mode"].Type == JTokenType.Integer && (int)p["mode"] == 4))); + } + + // GLB is the xenos asset boundary. Only its node extras, whether each node carries a mesh the importer builds as a plain mesh node, and its nearest identified ancestor's node index // (-1 for none) are read here, plus whether the node's scale is three positive radii with no matrix; geometry belongs to the runtime importer. public static Dictionary ReadNodeIds(string path) { @@ -333,7 +533,7 @@ public static class ShipModCatalog { var id = (string)node["extras"]?["aetheria.id"]; if (string.IsNullOrEmpty(id)) { index++; continue; } - if (!ids.TryAdd(id, (index, node["mesh"] != null && node["mesh"].Type != JTokenType.Null, IdentifiedAncestor(parents, nodes, (int)index), PositiveScale(node)))) + if (!ids.TryAdd(id, (index, BuildsMesh(json, node), IdentifiedAncestor(parents, nodes, (int)index), PositiveScale(node)))) throw new InvalidOperationException($"{path}: duplicate GLB node aetheria.id={id}."); index++; } diff --git a/Assets/Scripts/ServerShared/SimClock.cs b/Assets/Scripts/ServerShared/SimClock.cs index ee260a50b..ace4f9856 100644 --- a/Assets/Scripts/ServerShared/SimClock.cs +++ b/Assets/Scripts/ServerShared/SimClock.cs @@ -53,11 +53,28 @@ public sealed class SimClock _accumulator = 0; } + private float _rate = 1f; + + // Real-time dilation: how much sim time a real second buys, in (0, 1]. It scales the real seconds fed and never + // changes Step, so every step and trajectory is the same and only the wall-clock pace differs. Its one writer is + // ActionGameManager, from TacticalView.TimeRate. + public float Rate + { + get => _rate; + set + { + // NaN is no rate: it would poison the accumulator for good (only Reset clears it), so it is refused and the + // last rate stands. Anything else is clamped into (0, 1]: the sim never runs faster than real time or backward. + if (float.IsNaN(value)) return; + _rate = Math.Min(Math.Max(value, float.Epsilon), 1f); + } + } + // Feeds real seconds (negative counts as none, one frame counts at most MaxFrameSeconds) and runs the whole // steps they pay for. Returns how many ran. public int Advance(float realSeconds, Action step) { - _accumulator += Math.Min(Math.Max(realSeconds, 0f), MaxFrameSeconds); + _accumulator += Math.Min(Math.Max(realSeconds, 0f), MaxFrameSeconds) * (double) Rate; var ran = 0; _advancing = true; try diff --git a/Assets/Scripts/ServerShared/StationKinds.cs b/Assets/Scripts/ServerShared/StationKinds.cs index eb2662eee..02d5efc2c 100644 --- a/Assets/Scripts/ServerShared/StationKinds.cs +++ b/Assets/Scripts/ServerShared/StationKinds.cs @@ -23,6 +23,11 @@ public class StationKindData [JsonProperty("standIns"), Key(2)] public List StandIns = new List(); + // The facility gear a station of this kind is fitted with (ruling installed-gear-decides-what-a-station-buys). Records written + // before key 3 read it empty. + [JsonProperty("facilities"), Key(3)] + public List> Facilities = new List>(); + public static CultRecordKey KeyOf(string id) => new CultRecordKey("station-kind:" + id); } @@ -98,7 +103,50 @@ public static class StationKinds return standIn != null && standIn.Kind.IsSet() && OfferedKinds(catalog).Contains(standIn.Kind.Key.Value) ? standIn.Kind : default; } - // What is wrong with a hull's kind, or null: a Station hull names a kind the catalog holds, and no other hull names one. + // A recipe facility: facility gear a station runs recipes on. The hardpoint type says where it mounts, FacilityData says it runs + // recipes. + public static bool IsRecipeFacility(ItemData item) => + item is GearData gear && gear.HardpointType == HardpointType.Facility && gear.Behaviors != null && gear.Behaviors.Any(behavior => behavior is FacilityData); + + // Every offered station hull takes the facilities of every kind it serves, one station at a time (a station is one kind, so the + // designs of one kind each take a distinct Facility row; two kinds may share a row). A hull of kind H serves H itself and every + // kind some faction places whose hull kind is H (HullKindFor). One line per design that finds no row, naming the hull, the kind and + // the design, ordered by hull name then kind key. Reads the catalog and nothing else. + public static string[] FacilityRoomFaults(CultCache catalog) + { + var served = new Dictionary>(StringComparer.Ordinal); + foreach (var faction in catalog.GetAll()) + foreach (var kind in KindsOf(catalog, faction)) + { + var hullKind = HullKindFor(catalog, faction, kind).Key.Value; + if (!served.TryGetValue(hullKind, out var kinds)) served[hullKind] = kinds = new HashSet(StringComparer.Ordinal); + kinds.Add(kind.Key.Value); + } + var faults = new List<(string Hull, string Kind, string Line)>(); + foreach (var hull in DrawableStationProducts(catalog).Select(entry => entry.hull).Distinct().OrderBy(hull => hull.Name, StringComparer.Ordinal)) + { + var own = hull.Kind.Key.Value; + var kinds = new HashSet(served.TryGetValue(own, out var found) ? found : new HashSet(), StringComparer.Ordinal) { own }; + foreach (var kindKey in kinds.OrderBy(key => key, StringComparer.Ordinal)) + { + var kind = catalog.Get(new CultRecordKey(kindKey)); + if (kind == null) continue; + var rows = hull.Hardpoints.Where(hardpoint => hardpoint.Type == HardpointType.Facility).ToList(); + var designs = kind.Facilities.Select(facility => catalog.Get(facility)).OfType() + .OrderByDescending(design => design.Shape.Coordinates.Length).ThenBy(design => design.Name, StringComparer.Ordinal); + foreach (var design in designs) + { + var row = rows.FirstOrDefault(hardpoint => hardpoint.Takes(design)); + if (row != null) rows.Remove(row); + else faults.Add((hull.Name, kindKey, $"Station hull '{hull.Name}' has no free Facility row that takes {design.Name}, a facility of station kind '{kind.Name}'.")); + } + } + } + return faults.OrderBy(fault => fault.Hull, StringComparer.Ordinal).ThenBy(fault => fault.Kind, StringComparer.Ordinal).Select(fault => fault.Line).ToArray(); + } + + // What is wrong with a hull's station facts, or null: a Station hull names a kind the catalog holds, and no other hull names one + // or carries a Facility row. // The one rule, applied to the catalog on Open and to each mod package on Compose. public static string HullKindFault(CultCache catalog, HullData hull) { @@ -109,8 +157,13 @@ public static class StationKinds if (catalog.Get(hull.Kind) == null) return $"Station hull '{hull.Name}' Kind names no station kind this catalog holds."; } - else if (hull.Kind.IsSet()) - return $"Hull '{hull.Name}' is a {hull.HullType} and names a Kind; only a station hull has one."; + else + { + if (hull.Kind.IsSet()) + return $"Hull '{hull.Name}' is a {hull.HullType} and names a Kind; only a station hull has one."; + if (hull.Hardpoints != null && hull.Hardpoints.Any(hardpoint => hardpoint.Type == HardpointType.Facility)) + return $"Hull '{hull.Name}' is a {hull.HullType} and has a Facility row; only a station hull takes facilities."; + } return null; } diff --git a/Assets/Scripts/ServerShared/StationServices.cs b/Assets/Scripts/ServerShared/StationServices.cs index dace9288e..3af42a483 100644 --- a/Assets/Scripts/ServerShared/StationServices.cs +++ b/Assets/Scripts/ServerShared/StationServices.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using GameCult.Caching; // What a station pays for goods and charges to mend gear. The one owner of the sell price, the repair cost, and the // two commits that move goods or restore durability against the run's credits; TradeMenu shows these numbers and @@ -8,12 +9,14 @@ using System.Linq; // durabilities exactly as they were. public static class StationServices { - // What the station charges for the item, or for `quantity` units of a commodity (a crafted item is one unit). The - // number TradeMenu shows, checks against the run's credits and charges. + // What the station charges for the item, or for `quantity` units of a commodity, simple or compound (a crafted item + // is one unit). The number TradeMenu shows, checks against the run's credits and charges. public static int BuyPrice(ItemManager items, ItemInstance item, int quantity = 1) { switch (item) { + case CompoundCommodity compound: + return (int) Math.Min((long) items.GetPrice(compound) * quantity, int.MaxValue); case CraftedItemInstance crafted: return items.GetPrice(crafted); case SimpleCommodity commodity: @@ -24,12 +27,14 @@ public static class StationServices } // What the station pays for the item: its price, scaled by SellFraction and by its condition. A commodity has no - // wear, so it sells at the fraction alone; a simple commodity's price is per unit. + // wear, so it sells at the fraction alone; a commodity's price, simple or compound, is per unit. public static int SellPrice(ItemManager items, ItemInstance item) { var fraction = (double) items.GameplaySettings.SellFraction; switch (item) { + case CompoundCommodity compound: + return (int) Math.Floor((long) items.GetPrice(compound) * compound.Quantity * fraction); case CraftedItemInstance crafted: return SellValue(items.GetPrice(crafted), fraction, Condition(items, crafted)); case SimpleCommodity commodity: @@ -83,59 +88,125 @@ public static class StationServices // design's MaxStack, so a stack the station holds is a lot already; a stack above it comes from outside a bay and is // refused, as is a purchase of more than the stack holds or of a stack that holds nothing. All of that is refused // before anything moves, so `deliver` moves units the station has and the charge is for the units it delivered. - public static BuyResult TryBuyLots(ItemManager items, SimpleCommodity stock, int quantity, ref int credits, Func deliver) + public static BuyResult TryBuyLots(ItemManager items, ItemInstance stock, int quantity, ref int credits, Func deliver) { - if (quantity < 1 || quantity > stock.Quantity || stock.Quantity > items.GetData(stock).MaxStack) return BuyResult.NoRoom; + if (!(stock is ICommodityStack stack) || quantity < 1 || quantity > stack.Quantity || stack.Quantity > items.MaxStack(stock)) + return BuyResult.NoRoom; return TryBuy(items, stock, quantity, ref credits, () => deliver(quantity)); } // The quantity a Buy Quantity field may hold: what was typed, at most what the credits cover and what the station // has, and never below one unit (a price the credits do not cover is then refused as short of credits). - public static int BuyableQuantity(ItemManager items, SimpleCommodity stock, int typed, int credits) => - Math.Max(1, Math.Min(Math.Min(typed, credits / BuyPrice(items, stock)), stock.Quantity)); + public static int BuyableQuantity(ItemManager items, ItemInstance stock, int typed, int credits) => + Math.Max(1, Math.Min(Math.Min(typed, credits / BuyPrice(items, stock)), stock is ICommodityStack stack ? stack.Quantity : 1)); - // The sale: the item leaves the bay and the station pays SellPrice. A crafted item goes to one of the station's - // cargo bays; false, with the item in its bay and the credits unchanged, when no bay can take it. A simple - // commodity always sells (aetheria-release:ruling:station-market-absorbs-sold-commodity): the bays take as much of - // the stack as fits and the market absorbs the rest, at the full price. + // The sale of a crafted item: it leaves the bay and the station pays SellPrice, into one of the station's cargo bays; + // false, with the item in its bay and the credits unchanged, when no bay can take it. A commodity stack sells by + // TrySellPart, which says how many units sold and why not more (aetheria-living-world:ruling:no-market-absorption: no + // unit is paid for that no bay took). The crafted branch is ungated: follow-up gear-sale-by-answer gates it once the + // operator answers question gear-resale-under-installed-gear. public static bool TrySell(EquippedCargoBay from, Entity station, ItemInstance item, ref int credits) { + if (item is ICommodityStack) + throw new ArgumentException("A commodity stack sells through TrySellPart, which says how many units sold.", nameof(item)); var price = SellPrice(station.ItemManager, item); - if (item is SimpleCommodity commodity) - { - if (!from.Cargo.ContainsKey(commodity)) return false; - var offered = commodity.Quantity; - for (var quantity = offered; quantity >= 1; quantity--) - if (station.CargoBays.Any(bay => from.TryTransferItem(bay, commodity, quantity))) break; - if (from.Cargo.ContainsKey(commodity)) from.Remove(commodity, commodity.Quantity); - } - else if (!station.CargoBays.Any(bay => from.TryTransferItem(bay, (CraftedItemInstance) item))) return false; + if (!station.CargoBays.Any(bay => from.TryTransferItem(bay, item, 1))) return false; credits += price; return true; } - // The mined stacks of the bays: simple commodities with a lot whose origin is Extracted. Ammunition and consumables are - // simple commodities too, and a bought or staged commodity has Lot 0, which GetLot cannot resolve. + // The sale of a commodity stack: TryStorePart, and the station pays SellPrice for the units its bays took, added to + // `credits` (aetheria-living-world:ruling:no-market-absorption: no unit is paid for that no bay took). The rest stays in the + // seller's hold with the refusal NoRoom; a good the station does not want moves nothing (NotWanted). + public static SaleResult TrySellPart(EquippedCargoBay from, Entity station, ICommodityStack stack, ref int credits) + { + var paid = 0; + var result = TryStorePart(from, station, stack, part => paid += SellPrice(station.ItemManager, part)); + credits += paid; + return result; + } + + // The station taking a commodity stack into the bays that may hold it (StationWants.Bays), as far as they hold, with no + // price: the gate and the move of every sale and of a hauler's delivery (ruling transit-depots-buy-for-onward-haul). + // `moved` is called with each part that went across. Sold units are moved, never absorbed. + public static SaleResult TryStorePart(EquippedCargoBay from, Entity station, ICommodityStack stack, Action moved = null) + { + var item = (ItemInstance) stack; + var offered = stack.Quantity; + if (!from.Cargo.ContainsKey(item)) return new SaleResult(0, offered, SaleRefusal.None); + if (!StationWants.Of(station).Contains(item.Data.Key)) return new SaleResult(0, offered, SaleRefusal.NotWanted); + var stored = MoveParts(from, StationWants.Bays(station, item.Data.Key).ToArray(), stack, moved); + return new SaleResult(stored, offered, stored < offered ? SaleRefusal.NoRoom : SaleRefusal.None); + } + + // The station's silo bays giving the ship the units of `goods` they hold, as far as the ship's bays take them. The one writer + // of a station-to-hauler move; a hauler docks to call it (ruling docking-is-enclosed-bays). Returns the units moved. + public static int Load(Entity station, IReadOnlyCollection goods, Entity ship) + { + var into = ship.CargoBays.ToArray(); + var loaded = 0; + foreach (var silo in station.CargoBays.Where(bay => bay.Data is SiloData).ToArray()) + foreach (var stack in silo.Cargo.Keys.OfType().Where(stack => goods.Contains(((ItemInstance) stack).Data.Key)).ToArray()) + loaded += MoveParts(silo, into, stack, null); + return loaded; + } + + // Moves the stack into the bays, the whole quantity first and then fewer, until nothing more fits: the units moved. + private static int MoveParts(EquippedCargoBay from, IReadOnlyCollection into, ICommodityStack stack, Action moved) + { + var item = (ItemInstance) stack; + var total = 0; + var remaining = stack.Quantity; + while (remaining > 0) + { + var count = 0; + for (var quantity = remaining; quantity >= 1 && count == 0; quantity--) + { + var q = quantity; + var part = stack.Split(q); + if (!into.Any(bay => from.TryTransferItem(bay, item, q))) continue; + count = q; + moved?.Invoke(part); + } + if (count == 0) break; + total += count; + remaining -= count; + } + return total; + } + + // The ore stacks of the bays are the stacks of any design a field kind yields, mined, bought or looted alike (ruling + // simple-commodities-fungible); ammunition and other simple goods no belt yields are not ore. private static ItemInstance[] OreStacks(ItemManager items, IEnumerable bays) => - bays.SelectMany(bay => bay.Cargo.Keys.OfType().Where(stack => stack.Lot != 0 && items.GetLot(stack).Origin is Extracted).Select(stack => (ItemInstance) stack)).ToArray(); + bays.SelectMany(bay => bay.Cargo.Keys.OfType().Where(stack => FieldKinds.IsOre(items.ItemData, items.GetData(stack))).Select(stack => (ItemInstance) stack)).ToArray(); - // What the station pays for every mined stack of the bays: the sum of SellPrice over the stacks TrySellOre sells. - public static int OreValue(ItemManager items, IEnumerable bays) => - (int) Math.Min(OreStacks(items, bays).Sum(stack => (long) SellPrice(items, stack)), int.MaxValue); + // What the station would pay for every ore stack of the bays that it wants: the sum of SellPrice over the stacks TrySellOre + // sells. A display value: it ignores the station's room. + public static int OreValue(ItemManager items, IEnumerable bays, Entity station) => + (int) Math.Min(WantedOreStacks(items, bays, station).Sum(stack => (long) SellPrice(items, stack)), int.MaxValue); - // Sells every mined stack of the bays, each through TrySell, so the market's absorb rule and the price are the - // single-stack path's. Returns the units sold. - public static int TrySellOre(IEnumerable bays, Entity station, ref int credits) + private static ItemInstance[] WantedOreStacks(ItemManager items, IEnumerable bays, Entity station) + { + var wants = StationWants.Of(station); + return OreStacks(items, bays).Where(stack => wants.Contains(stack.Data.Key)).ToArray(); + } + + // Sells every ore stack of the bays that the station wants, each through TrySellPart, so the price and the room rule are the single-stack + // path's. Returns the units sold and offered, with the last refusal. + public static SaleResult TrySellOre(IEnumerable bays, Entity station, ref int credits) { var bayList = bays.ToArray(); - var units = 0; - foreach (var stack in OreStacks(station.ItemManager, bayList)) + int sold = 0, offered = 0; + var refusal = SaleRefusal.None; + foreach (var stack in WantedOreStacks(station.ItemManager, bayList, station)) { - var quantity = ((SimpleCommodity) stack).Quantity; var from = bayList.First(bay => bay.Cargo.ContainsKey(stack)); - if (TrySell(from, station, stack, ref credits)) units += quantity; + var result = TrySellPart(from, station, (ICommodityStack) stack, ref credits); + sold += result.Sold; + offered += result.Offered; + if (result.Refusal != SaleRefusal.None) refusal = result.Refusal; } - return units; + return new SaleResult(sold, offered, refusal); } // The repair: armour and every durability go back to design and the station charges RepairCost. False, with @@ -185,3 +256,21 @@ public static class StationServices } public enum BuyResult { Bought, ShortOfCredits, NoRoom } + +// Why a commodity sale moved fewer units than it offered: the station does not buy the good, or its bays are full. +public enum SaleRefusal { None, NotWanted, NoRoom } + +// A commodity sale: the units sold, the units offered, and why the rest stayed. +public readonly struct SaleResult +{ + public readonly int Sold; + public readonly int Offered; + public readonly SaleRefusal Refusal; + + public SaleResult(int sold, int offered, SaleRefusal refusal) + { + Sold = sold; + Offered = offered; + Refusal = refusal; + } +} diff --git a/Assets/Scripts/ServerShared/StationWants.cs b/Assets/Scripts/ServerShared/StationWants.cs new file mode 100644 index 000000000..68eab133e --- /dev/null +++ b/Assets/Scripts/ServerShared/StationWants.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using MessagePack; +using Newtonsoft.Json; + +// What a station buys (aetheria-living-world:ruling:installed-gear-decides-what-a-station-buys): the goods its installed +// recipe facilities draw, and, when it carries a silo, the goods of the haul orders that start at its orbit +// (ruling transit-depots-buy-for-onward-haul). Derived on every call from the station's gear and the catalog, stored nowhere. +// StationServices.TrySellPart is gated by it and limited by the bays' room. +public static class StationWants +{ + public static IReadOnlyCollection Of(Entity station) + { + var wants = Drawn(station); + wants.UnionWith(Ordered(station)); + return wants; + } + + // The bays a bought or delivered good may land in: every bay when an installed recipe facility draws it, only the silo bays + // when the station wants it only through a haul order (a transit depot holds goods in its silo, never in its stock bay). The + // one owner of where a good lands; none when the station does not want it. + public static IEnumerable Bays(Entity station, CultRecordKey good) + { + if (Drawn(station).Contains(good)) return station.CargoBays; + return Ordered(station).Contains(good) ? station.CargoBays.Where(bay => bay.Data is SiloData) : Enumerable.Empty(); + } + + private static HashSet Drawn(Entity station) + { + var catalog = station.ItemManager.ItemData; + var wants = new HashSet(); + foreach (var equipped in station.Equipment) + { + var design = station.ItemManager.GetData(equipped.EquippableItem); + if (!StationKinds.IsRecipeFacility(design)) continue; + foreach (var recipe in Production.RunList(catalog, catalog.RefOf(design).Key)) + foreach (var draw in Production.Draws(catalog, recipe)) + wants.Add(draw); + } + return wants; + } + + private static IEnumerable Ordered(Entity station) + { + if (!(station is OrbitalEntity { OrbitData: var orbit }) || !orbit.IsSet() || !station.CargoBays.Any(bay => bay.Data is SiloData)) + return Enumerable.Empty(); + return station.ItemManager.ItemData.GetAll().Where(order => order.From.Key.Equals(orbit)) + .SelectMany(order => order.Goods.Select(good => good.Key)).ToArray(); + } +} + +// A standing haul order: goods that move from one station's orbit to another's, keyed haul-order:. A run document: saved +// with the run, cleared, replaced and discarded with it. Fixed until offices issue orders (ruling transit-depots-buy-for-onward-haul); +// From and To are the stations' orbit records until installations give a station a key of its own. +[CultDocument("aetheria.haulorderdata", "1"), MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class HaulOrderData +{ + [JsonProperty("from"), Key(0)] public CultRecordRef From; + [JsonProperty("to"), Key(1)] public CultRecordRef To; + [JsonProperty("goods"), Key(2)] public List> Goods = new List>(); + // What stood this order up (scenario:), so a reader can tell a staged order from one an office issues. + [JsonProperty("commitment"), Key(3)] public string Commitment; + + public static CultRecordKey KeyOf(string id) => new CultRecordKey("haul-order:" + id); +} diff --git a/Assets/Scripts/ServerShared/StationWants.cs.meta b/Assets/Scripts/ServerShared/StationWants.cs.meta new file mode 100644 index 000000000..a491ffd4d --- /dev/null +++ b/Assets/Scripts/ServerShared/StationWants.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: edaecca4f1754e26af8a65743e4d6da6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/TacticalInput.cs b/Assets/Scripts/ServerShared/TacticalInput.cs new file mode 100644 index 000000000..73208da9f --- /dev/null +++ b/Assets/Scripts/ServerShared/TacticalInput.cs @@ -0,0 +1,44 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System.Collections.Generic; + +// The one place that decides, per input action, whether it is ship input or view input (ruling tactical-input-hands-off). +// Ship input drives the ship and pauses in the tactical view, which holds the ship's last commands; view input steers the +// view and the interface and stays live. TacticalView.Direct is the only source of the mode. An action absent from the table +// is not live (it fails closed), and a test requires every action of the Player and Global maps to be listed. +public static class TacticalInput +{ + private static readonly HashSet Ship = new HashSet + { + "Player/Move", "Player/Look", "Player/Turn", "Player/Face Aim", "Player/Toggle Face Aim", "Player/Tractor Beam", + "Player/Target Reticle", "Player/Target Previous", "Player/Target Next", "Player/Target Nearest", + "Player/Cycle Target Item", "Player/Toggle Heatsinks", "Player/Toggle Shield", "Player/Toggle Stance", + "Player/Override Shutdown", "Player/Ping", "Global/Interact", + }; + + private static readonly HashSet View = new HashSet + { + "Player/Zoom", "Player/Pan", "Player/Point", "Player/Minimap Zoom", "Player/Hide UI", + "Global/Zone Map", "Global/Galaxy Map", "Global/Inventory", "Global/Main Menu", "Global/Input Screen", + }; + + public static IEnumerable Classified + { + get + { + foreach (var a in Ship) yield return a; + foreach (var a in View) yield return a; + } + } + + public static bool IsShip(string map, string action) => Ship.Contains(map + "/" + action); + + // Whether the action's input is taken now. + public static bool Live(TacticalView view, string map, string action) + { + var key = map + "/" + action; + return View.Contains(key) || (Ship.Contains(key) && view.Direct); + } +} diff --git a/Assets/Scripts/ServerShared/TacticalInput.cs.meta b/Assets/Scripts/ServerShared/TacticalInput.cs.meta new file mode 100644 index 000000000..32c124e65 --- /dev/null +++ b/Assets/Scripts/ServerShared/TacticalInput.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b1a9c9c14cc8d834380ff8fc62592d92 \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/TacticalView.cs b/Assets/Scripts/ServerShared/TacticalView.cs new file mode 100644 index 000000000..0ed4d5781 --- /dev/null +++ b/Assets/Scripts/ServerShared/TacticalView.cs @@ -0,0 +1,148 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using CultMath; +using static CultMath.math; + +// The one owner of the view (rulings tactical-view-distinct-mode, tactical-view-in-runs-slow-time). One scalar, the camera +// distance in log space, is the view: flight owns [ln base, ln BlendStart], the tactical view owns [ln BlendEnd, ln max], +// and the band between is a detent the player scrolls through with intent. Scroll moves a commanded position; an eased +// position follows it on a critically damped spring and is what the camera is. Nothing stores a mode: Tactical is derived +// from the commanded position against the band's crest, and Blend, TimeRate and the rig weight are derived from the +// eased distance, by whoever draws or steps. +// Every feel constant (notch step, detent resistance and relaxation, ease time, the band's edges) is a placeholder the +// operator tunes by eye (GameSettings). +public sealed class TacticalView +{ + private readonly float _zoomStep, _blendStart, _blendEnd, _timeScale, _fitPerRadius; + private readonly float _detentResistance, _detentRelaxTime, _easeTime; + private readonly float _lnStart, _lnEnd, _crest; + private float _lnBase, _lnMax, _zoneRadius; + + public TacticalView(float zoomStep, float blendStart, float blendEnd, float timeScale, float fitPerRadius, + float detentResistance, float detentRelaxTime, float easeTime) + { + _zoomStep = zoomStep; + _blendStart = blendStart; + _blendEnd = blendEnd; + _timeScale = timeScale; + _fitPerRadius = fitPerRadius; + _detentResistance = detentResistance; + _detentRelaxTime = detentRelaxTime; + _easeTime = easeTime; + _lnStart = log(blendStart); + _lnEnd = log(blendEnd); + _crest = (_lnStart + _lnEnd) / 2; + } + + // Commanded and eased positions and the ease velocity, in ln metres; the grid point the tactical camera looks at. + public float Commanded { get; private set; } + private float _eased, _velocity; + private float2 _ship, _pan; + + // The grid point the camera looks at: the ship in flight, the panned grid point in tactical, eased between by the + // rig's own weight (the blend of the eased distance), never by the commanded flip. + public float2 Target => _ship + (_pan - _ship) * Blend(Distance); + + // Derived, never stored: the commanded position is past the detent's crest. + public bool Tactical => Commanded > _crest; + + // Whether direct ship input is taken (ruling tactical-input-hands-off): in the tactical view every keyboard, mouse and + // toggle input pauses and the ship holds its last commands. The one expression of that gate; nothing else stores it. + public bool Direct => !Tactical; + + // What the camera is: the eased position. + public float Distance => exp(_eased); + + // Back to the hull's own framing over the ship, in the zone the camera is now in. + public void Reset(float zoneRadius, float baseDistance, float2 shipXZ) + { + _lnBase = log(baseDistance); + _lnMax = max(log(max(zoneRadius * _fitPerRadius, _blendEnd)), _lnBase); + _zoneRadius = zoneRadius; + Commanded = _eased = _lnBase; + _velocity = 0; + _ship = _pan = shipXZ; + } + + // Each notch (positive zooms out) moves the commanded position by ln ZoomStep. Inside a view it moves freely. A notch + // that carries it deeper into the band moves it DetentResistance times as far there; one that carries it past the + // crest commits, and the position jumps to the band's far edge. Symmetric from the tactical side. + public void Scroll(float notches) + { + var step = log(_zoomStep); + var count = (int) abs(notches); + var sign = notches < 0 ? -1f : 1f; + for (var i = 0; i < count; i++) Notch(sign * step); + } + + private void Notch(float delta) + { + // Depth is how far into the band from the edge on the commanded side; negative is out in that view's free range. + var side = Tactical ? -1f : 1f; + var edge = Tactical ? _lnEnd : _lnStart; + var depth = side * (Commanded - edge); + var deeper = side * delta; + if (deeper <= 0) + { + Commanded = clamp(Commanded + delta, _lnBase, _lnMax); + return; + } + var free = min(deeper, max(-depth, 0f)); + var newDepth = depth + free + (deeper - free) * _detentResistance; + if (newDepth > _crest - _lnStart) + { + Commanded = Tactical ? _lnStart : _lnEnd; + return; + } + Commanded = clamp(edge + side * newDepth, _lnBase, _lnMax); + } + + // Real seconds: the band's relaxation toward the edge on the commanded side of the crest (it never crosses the crest), + // then the critically damped ease of the eased position toward the commanded one. + public void Tick(float realSeconds) + { + if (realSeconds <= 0) return; + if (Commanded > _lnStart && Commanded < _lnEnd) + { + var edge = Tactical ? _lnEnd : _lnStart; + Commanded = edge + (Commanded - edge) * exp(-realSeconds / _detentRelaxTime); + } + // Exact solution of x'' = -2w(x' + w(x - c)) over dt: no overshoot from rest, stable at any dt. + var w = 2 / _easeTime; + var offset = _eased - Commanded; + var carried = _velocity + w * offset; + var decay = exp(-w * realSeconds); + _eased = Commanded + (offset + carried * realSeconds) * decay; + _velocity = (_velocity - w * carried * realSeconds) * decay; + } + + // The ship's grid position, every frame. The panned point rides the ship while the eased camera is in flight (to within + // float noise of the band's near edge, a weight of about a millionth), so a pan starts from the hull; once the camera + // leaves flight it stays where the player put it, and the eased weight carries Target back to the ship on the way home. + public void Track(float2 shipXZ) + { + _ship = shipXZ; + if (!Tactical && Distance <= _blendStart * 1.001f) _pan = shipXZ; + } + + // Move the target over the grid by a ground delta, never off the zone. + public void Pan(float2 groundDelta) + { + if (!Tactical) return; + var moved = _pan + groundDelta; + var reach = length(moved); + _pan = reach > _zoneRadius && reach > 0 ? moved * (_zoneRadius / reach) : moved; + } + + // 0 at or below the band's near edge, 1 at or above its far edge, smooth in the logarithm of distance between. + public float Blend(float distance) + { + var t = saturate((log(max(distance, 1e-6f)) - log(_blendStart)) / (log(_blendEnd) - log(_blendStart))); + return t * t * (3 - 2 * t); + } + + // Real seconds feed the sim clock at this rate: 1 in flight, TacticalTimeScale fully zoomed out. + public float TimeRate(float blend) => pow(_timeScale, saturate(blend)); +} diff --git a/Assets/Scripts/ServerShared/TacticalView.cs.meta b/Assets/Scripts/ServerShared/TacticalView.cs.meta new file mode 100644 index 000000000..c14ea0555 --- /dev/null +++ b/Assets/Scripts/ServerShared/TacticalView.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c994fb45f71d4a7fa9ed80a9ab8b034d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index 74d1486c3..a60583d42 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -201,7 +201,7 @@ public class Zone case AsteroidBeltData belt: // Mining Cut 3 (Q16 B): a belt from before field kinds existed gets its kind here, once, by // the rule generation uses, and keeps it. - FieldKinds.Ensure(body.Key.Value, belt, cache, GalaxyZone?.Province?.Type ?? default); + FieldKinds.Ensure(belt.SiteOr(body.Key), belt, cache, GalaxyZone?.Province?.Type ?? default); AsteroidBelts[body.Key] = new AsteroidBelt(belt); break; case SunData sun: @@ -327,7 +327,7 @@ public class Zone _flights[key] = flight = new Flight(ship.Faction?.Doctrine, _itemManager.GameplaySettings); var id = NextAgentId(); var agent = new Minion(ship, flight.Combatant) { Id = id }; - flight.Join(agent, stated ?? PatrolCircuit(id)); + flight.Join(agent, stated ?? (AgentTask) HaulRun.TaskOf(ship) ?? PatrolCircuit(id)); return agent; } @@ -445,12 +445,12 @@ public class Zone if (floating == null || (floating.Holder != null && !ReferenceEquals(floating.Holder, taker))) return false; // The quantity is read before the store: a store that merges into a part-filled stack and spills the rest into a // new cell rewrites the item's Quantity. - var stored = floating.Item is SimpleCommodity stack ? stack.Quantity : 1; + var stored = floating.Item is ICommodityStack stack ? stack.Quantity : 1; if (!taker.CargoBays.Any(bay => bay.TryStore(floating.Item))) return false; FloatingItems.Remove(floating); CargoGained.OnNext(new CargoGain { - Taker = taker, Design = floating.Item.Data, Lot = floating.Item.Lot, Kind = GainKind.Collected, + Taker = taker, Design = floating.Item.Data, Kind = GainKind.Collected, Stored = stored }); return true; diff --git a/Assets/Scripts/ServerShared/ZoneData.cs b/Assets/Scripts/ServerShared/ZoneData.cs index e76963a43..4f8379c8d 100644 --- a/Assets/Scripts/ServerShared/ZoneData.cs +++ b/Assets/Scripts/ServerShared/ZoneData.cs @@ -88,6 +88,14 @@ public abstract class BodyData [JsonProperty("bodyRadiusMul")] [Key(5)] public float BodyRadiusMultiplier = 1; + + // The body's generation coordinate: the zone seed, its kind and its place in the pack. Written once, by ZoneGenerator. + // The key is identity and is minted by the cache; no content hash reads it when a Site exists (SiteOr). + [JsonProperty("site"), Key(23)] + public string Site; + + public string SiteOr(GameCult.Caching.CultRecordKey key) => string.IsNullOrEmpty(Site) ? key.Value : Site; + public static string NameOf(string site) => site.StableHash().ToString("x8"); } [CultDocument("aetheria.planetdata", "1"), MessagePackObject, JsonObject(MemberSerialization.OptIn)] @@ -284,6 +292,14 @@ public static class FieldKinds .Where(yield => yield.Amount > 0f) .ToArray(); } + + // Whether the design is raw ore: some field kind yields it. Ore is what a belt can put in a hold; derived on every + // call, never stored. The one owner of the raw-ore kind. + public static bool IsOre(CultCache catalog, ItemData design) + { + var key = catalog.RefOf(design).Key; + return catalog.GetAll().Any(kind => kind.Yields.Any(yield => yield.Commodity.Key.Equals(key))); + } } // Ore geography (rulings provinces-within-regions, boss-zone-is-near-side, province-partition-by-size, province-types-dealt-per-region). diff --git a/Assets/Scripts/ServerShared/ZoneGenerator.cs b/Assets/Scripts/ServerShared/ZoneGenerator.cs index 5b82a9a1a..7d34e48ef 100644 --- a/Assets/Scripts/ServerShared/ZoneGenerator.cs +++ b/Assets/Scripts/ServerShared/ZoneGenerator.cs @@ -7,6 +7,7 @@ using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; +using GameCult.Caching; using MessagePack; using UniRx; using CultMath; @@ -35,6 +36,8 @@ public static class ZoneGenerator private const int MaximumPlacementSamples = 32; + // entranceStations: the stations the scenario's arena must hold (Scenario.EntranceStations); the orders apply only + // when galaxyZone == galaxy.Entrance, null or empty rolls the zone's stations like any other's. // ambient: false keeps the planets, orbits and stations but generates no ship and no turret, so nothing wanders // into a scenario's authored conditions (docs/scenarios-cut.md, 2.1). The rule is applied here, not by pruning. public static ZonePack GenerateZone( @@ -43,7 +46,7 @@ public static class ZoneGenerator PlanetSettings planetSettings, Galaxy galaxy, GalaxyZone galaxyZone, - bool isTutorial = false, + IReadOnlyList entranceStations = null, bool ambient = true) { var pack = new ZonePack(); @@ -209,12 +212,11 @@ public static class ZoneGenerator gas.SecondOffsetDomainRotationSpeed = -25; } - // A body is named for the first eight characters of the key the cache mints for it - var bodyKey = cache.Upsert(planetData).Key; - planetData.Name = bodyKey.Value.Substring(0, 8); - // Mining Cut 3 (Q16 B): a belt's field kind is chosen here, at generation, and saved with it. - if (planetData is AsteroidBeltData generatedBelt) FieldKinds.Ensure($"{seed}:belt:{index}", generatedBelt, cache, galaxyZone.Province?.Type ?? default); - return cache.Upsert(planetData); + planetData.Site = planetData is AsteroidBeltData ? $"{seed}:belt:{index}" : $"{seed}:body:{index}"; + planetData.Name = BodyData.NameOf(planetData.Site); + var held = cache.Upsert(planetData); + if (planetData is AsteroidBeltData generatedBelt) FieldKinds.Ensure(planetData.Site, generatedBelt, cache, galaxyZone.Province?.Type ?? default); + return held; }).ToList(); // Trojan swarms (rulings trojans-first, trojans-ride-host-period-with-stations): a belt on a copy of its host's rail, its @@ -237,10 +239,10 @@ public static class ZoneGenerator Asteroids = TrojanRocks(zoneSettings, ref swarmRandom, rail.Distance, rail.Phase) }; BodyData swarmBody = swarm; - var swarmKey = cache.Upsert(swarmBody).Key; - swarm.Name = swarmKey.Value.Substring(0, 8); - FieldKinds.Ensure($"{seed}:swarm:{swarmHosts.Count}", swarm, cache, galaxyZone.Province?.Type ?? default); + swarm.Site = $"{seed}:swarm:{swarmHosts.Count}"; + swarm.Name = BodyData.NameOf(swarm.Site); pack.Planets.Add(cache.Upsert(swarmBody)); + FieldKinds.Ensure(swarm.Site, swarm, cache, galaxyZone.Province?.Type ?? default); } // Laned belts (rulings belt-shapes-direction, lanes-two-sided-visual-margin): a belt candidate that kept its body carries @@ -266,10 +268,10 @@ public static class ZoneGenerator Asteroids = LaneRocks(zoneSettings, ref laneRandom, host.Mass, rail.Distance, lane, host.SlotInner, host.SlotOuter) }; BodyData lanedBody = laned; - var lanedKey = cache.Upsert(lanedBody).Key; - laned.Name = lanedKey.Value.Substring(0, 8); - FieldKinds.Ensure($"{seed}:lane:{shaped.Count}", laned, cache, galaxyZone.Province?.Type ?? default); + laned.Site = $"{seed}:lane:{shaped.Count}"; + laned.Name = BodyData.NameOf(laned.Site); pack.Planets.Add(cache.Upsert(lanedBody)); + FieldKinds.Ensure(laned.Site, laned, cache, galaxyZone.Province?.Type ?? default); } // The generator's own well tree, for clearance only (the Zone builds its own): what a rail must stay out of is the body's @@ -292,17 +294,42 @@ public static class ZoneGenerator var nearestFactionHomeZone = galaxy.HomeZones[nearestFaction]; var factionPresence = galaxy.InfluenceOf(nearestFaction) - nearestFactionHomeZone.Distance[galaxyZone] + 1; + // In a galaxy with a gate antagonist that faction raids by DemoPressure's curve (below); inside its grace its stations and + // turrets are as absent as its ships, so the zone's structures belong to the nearest faction that is not the antagonist. + var antagonist = galaxy.Antagonist; + var structureFaction = antagonist != null && nearestFaction == antagonist && DemoPressure.InGrace(galaxy, galaxyZone) + ? galaxy.Factions.Where(f => f != antagonist).MinBy(f => galaxy.HomeZones[f].Distance[galaxyZone]) + : nearestFaction; + var storyStations = galaxyZone.Locations.Where(story => story.Type == LocationType.Station).ToArray(); var stationCount = (int)(random.NextFloat() * (factionPresence + 1)) + storyStations.Length; - // Enemy count below is based on this pre-override value, so the tutorial entrance doesn't gain an enemy + // Enemy count below is based on this pre-override value, so the entrance station zone doesn't gain an enemy // just because its station got forced. var baseStationCount = stationCount; - // Operator ruling, 2026-09-25 (docs/locomotion-cut.md, "Tutorial station"): the entrance zone always - // gets a generated faction station with a docking bay, deterministically. Galaxy.cs halves influence and - // picks the lowest-influence unowned zone for Entrance, which otherwise rolls stationCount 0 on every - // seed. galaxy.Entrance is reference-identity, not a name comparison. - var isTutorialEntrance = isTutorial && galaxyZone == galaxy.Entrance; - if (isTutorialEntrance && stationCount < 1) stationCount = 1; + // Operator ruling, 2026-09-25 (docs/locomotion-cut.md): a scenario that declares entrance stations + // (Scenario.EntranceStations) gets them in its entrance zone, deterministically, one per order after the story + // stations. A cast galaxy's halved influence and its lowest-influence unowned Entrance otherwise roll + // stationCount 0 on every seed. galaxy.Entrance is reference-identity, not a name comparison. + var orders = galaxyZone == galaxy.Entrance && entranceStations != null ? entranceStations : Array.Empty(); + var orderFactions = new Faction[orders.Count]; + var orderKinds = new CultRecordRef[orders.Count]; + for (var o = 0; o < orders.Count; o++) + { + if (orders[o].Faction != null) + { + orderFactions[o] = galaxy.ResolveFaction(orders[o].Faction); + if (orderFactions[o] == null || !galaxy.Factions.Contains(orderFactions[o])) + throw new InvalidOperationException($"Entrance station order faction {orders[o].Faction} is not in the galaxy."); + } + if (orders[o].Kind != null) + { + orderKinds[o] = new CultRecordRef(StationKindData.KeyOf(orders[o].Kind)); + if (cache.Get(orderKinds[o]) == null) + throw new InvalidOperationException($"Entrance station order kind {orders[o].Kind} is not in the catalog."); + } + } + var required = storyStations.Length + orders.Count; + if (orders.Count > 0 && stationCount < required) stationCount = required; // A station's source is a well-bearing body alone on its ring whose rail clears every massive sibling's extent (the // sibling's support, or its Roche margin if more) and the largest reach of any station or turret hull: whatever hull // is built there, its Lagrange orbit then sits clear of any other body. @@ -318,21 +345,29 @@ public static class ZoneGenerator // (the rail, how far a body on it keeps others out, whether it is a station's own orbit rather than a base's) var sources = candidates.Skip(candidates.Length / 2).Take(stationCount) .Select(p => (orbit: orbitMap[p], extent: Extent(p), direct: false)).ToArray(); - if (isTutorialEntrance && candidates.Length == 0) + if (orders.Count > 0 && sources.Length < required) { - // The entrance gets a station whatever its bodies: it orbits a root node beyond its ring group (or, for a body, its - // whole family), never at a ring member's distance, and sits there, not at a Lagrange point. + // An order the rails cannot seat orbits a root node beyond its ring group (or, for a body, its whole family), never at + // a ring member's distance, and sits there, not at a Lagrange point. The shortfall shares the first one's phase + // (drawn once) spread evenly round the turn. var roots = planets.Where(p => p.Parent == null).ToList(); var rootNode = roots.FirstOrDefault(p => p.Children.Count > 0) ?? (roots.Count > 1 ? roots.OrderByDescending(p => p.Mass).First() : null); if (rootNode == null) throw new InvalidOperationException( - "The tutorial entrance zone must always get a station, but it has no candidate orbit at all -- every planet in the zone is a parentless root."); + "The entrance station zone must always get its stations, but it has no candidate orbit at all -- every planet in the zone is a parentless root."); var distance = rootNode.Empty ? (1 + GravityField.RingReach) * GravityField.Beta * rootNode.Children.Where(Massive).Min(c => c.Distance) : Extent(rootNode); - var direct = new OrbitData { Parent = cache.RefOf(orbitMap[rootNode]), Distance = distance, Phase = random.NextFloat() }; - pack.Orbits.Add(cache.Upsert(direct)); - sources = new[] { (orbit: direct, extent: float.NegativeInfinity, direct: true) }; + var shortfall = required - sources.Length; + var phase = random.NextFloat(); + var withDirect = sources.ToList(); + for (var k = 0; k < shortfall; k++) + { + var direct = new OrbitData { Parent = cache.RefOf(orbitMap[rootNode]), Distance = distance, Phase = phase + (float) k / shortfall }; + pack.Orbits.Add(cache.Upsert(direct)); + withDirect.Add((orbit: direct, extent: float.NegativeInfinity, direct: true)); + } + sources = withDirect.ToArray(); } var selectedStationOrbits = sources.Select(x => x.orbit).ToArray(); var extentOf = sources.ToDictionary(x => x.orbit, x => x.extent); @@ -440,14 +475,19 @@ public static class ZoneGenerator var orbit = selectedStationOrbits[i]; var security = (SecurityLevel) ((int) ((1f - pow(random.NextFloat(), factionPresence / 2f)) * 3f)); + var slot = i - storyStations.Length; + var isOrder = slot < orders.Count; + var slotFaction = isOrder && orderFactions[slot] != null ? orderFactions[slot] : structureFaction; + var slotKind = isOrder && orders[slot].Kind != null + ? orderKinds[slot] + : StationKinds.Choose(cache, slotFaction, $"{seed}:station:{i}", itemManager.Log); var lagrangeOrbit = CreateLagrangeOrbit(orbit); - var station = GetLoadoutGenerator(nearestFaction).GenerateStationLoadout( - StationKinds.Choose(cache, nearestFaction, $"{seed}:station:{i}", itemManager.Log)); + var station = GetLoadoutGenerator(slotFaction).GenerateStationLoadout(slotKind); if (station == null) { - if (isTutorialEntrance) + if (isOrder) throw new InvalidOperationException( - $"The tutorial entrance zone must always get a station, but {nearestFaction?.Name} has no station loadout to generate."); + $"The entrance station order for {slotFaction?.Name} ({slotKind.Key}) must always get a station, but it has no station loadout to generate."); continue; } station.Orbit = cache.RefOf(lagrangeOrbit); @@ -455,7 +495,7 @@ public static class ZoneGenerator station.SecurityRadius = pack.Radius; pack.Entities.Add(station); - if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(nearestFaction), 2, StationReach(station), orbit); + if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(slotFaction), 2, StationReach(station), orbit); } // A boss zone gets its faction's boss whether or not the zone is ambient: the boss is the run's goal, not @@ -489,18 +529,36 @@ public static class ZoneGenerator if (!ambient) return pack; - var enemyCount = (int)(random.NextFloat() * factionPresence * 2) + baseStationCount; - for (int i = 0; i < enemyCount; i++) + // A galaxy with a gate antagonist is raided by it in proportion to depth toward the gate (DemoPressure owns the curve); + // every other galaxy keeps the nearest faction's presence-sized patrol. + if (antagonist != null) { - var ship = GetLoadoutGenerator(nearestFaction).GenerateShipLoadout(); - if (ship == null) continue; - pack.Entities.Add(ship); + var pressure = DemoPressure.Of(galaxy, galaxyZone); + var raiders = GetLoadoutGenerator(antagonist); + var ceiling = pressure.Hostiles == 0 ? 0 : DemoPressure.PriceCeiling(raiders.OfferedShipHulls().Select(hull => hull.Price).ToArray(), pressure.Tier); + for (int i = 0; i < pressure.Hostiles; i++) + { + var ship = raiders.GenerateShipLoadout(hull => hull.Price <= ceiling); + if (ship == null) continue; + pack.Entities.Add(ship); + } + } + else + { + var enemyCount = (int)(random.NextFloat() * factionPresence * 2) + baseStationCount; + for (int i = 0; i < enemyCount; i++) + { + var ship = GetLoadoutGenerator(nearestFaction).GenerateShipLoadout(); + if (ship == null) continue; + pack.Entities.Add(ship); + } } // Neutral wanderers: ships belonging to a faction that neither owns the zone nor is its // nearest faction, so existing hostility rules leave them non-hostile to the player. // Testing affordance for hand-testing combat/targeting; none spawn if no faction qualifies. - var eligibleWandererFactions = EligibleWandererFactions(galaxy.Factions, galaxyZone.Owner, nearestFaction); + // The antagonist is no wanderer where DemoPressure raids: its presence is the curve's alone, and it is hostile. + var eligibleWandererFactions = EligibleWandererFactions(galaxy.Factions, galaxyZone.Owner, nearestFaction).Where(f => f != antagonist).ToArray(); if (zoneSettings.NeutralWandererCount > 0 && eligibleWandererFactions.Length > 0) { var wandererFaction = eligibleWandererFactions[random.NextInt(eligibleWandererFactions.Length)]; diff --git a/Assets/Scripts/UI/MainMenu.cs b/Assets/Scripts/UI/MainMenu.cs index e7aba3357..0b333e83b 100644 --- a/Assets/Scripts/UI/MainMenu.cs +++ b/Assets/Scripts/UI/MainMenu.cs @@ -29,6 +29,8 @@ public class MainMenu : MonoBehaviour private bool _fadeFromRight; private float _fadeLerp; private bool _fading; + // True from the moment a run is being generated or entered until it fails; the scene reload ends it. + public bool Launching { get; private set; } private Vector3 _panelPosition; //private Task _databaseLoad; @@ -120,9 +122,14 @@ public class MainMenu : MonoBehaviour Debug.Log("run store has no SavedGame; Continue disabled"); _nextMenu.panel.AddButton("Continue", saved == null ? (Action) null : () => { - try { RunSave.RequireDesigns(cache, saved); } + Galaxy galaxy; + try + { + RunSave.RequireDesigns(cache, saved); + galaxy = new Galaxy(cache, saved, Debug.Log); + } catch (InvalidOperationException error) { Refuse("Cannot continue this run", error.Message); return; } - ActionGameManager.CurrentGalaxy = new Galaxy(cache, saved, Debug.Log); + ActionGameManager.CurrentGalaxy = galaxy; EnterGame(); }); } @@ -232,10 +239,11 @@ public class MainMenu : MonoBehaviour // The only way into a new run: generates the scenario's galaxy off the main thread and enters the game, where // StartGame has RunStart stage it and only then replaces the saved run. A galaxy that cannot generate is refused // here, with the saved run untouched. - private void Launch(Scenario scenario) + public void Launch(Scenario scenario) { var generatorState = "Loading Database Contents"; + Launching = true; Fade(true); _nextMenu.panel.gameObject.SetActive(false); Dialog.Clear(); @@ -246,11 +254,8 @@ public class MainMenu : MonoBehaviour var stage = new GalaxyStage( Settings.SectorGenerationSettings, Settings.SectorBackgroundSettings, - Settings.TutorialGenerationSettings, - Settings.TutorialBackgroundSettings, + Settings.CastBackgroundSettings, ActionGameManager.CultCache, - ActionGameManager.PlayerSettings, - ActionGameManager.GameDataDirectory.CreateSubdirectory("Narrative"), Debug.Log, state => generatorState = state); Task.Run(() => RunStart.Generate(scenario, stage)).ContinueWith(generation => @@ -259,6 +264,7 @@ public class MainMenu : MonoBehaviour if (generation.IsFaulted) { Debug.LogException(generation.Exception); + Launching = false; ShowMain(); Fade(false); Refuse($"{scenario.Name} could not generate its galaxy", generation.Exception.GetBaseException().Message); @@ -272,7 +278,11 @@ public class MainMenu : MonoBehaviour // The one way into the game scene. Mod ship prototypes import asynchronously at boot, so the scene waits for them, // and a preload that could not run at all stops here with its reason rather than in the first zone. - private void EnterGame() => StartCoroutine(EnterGameWhenModShipsAreReady()); + private void EnterGame() + { + Launching = true; + StartCoroutine(EnterGameWhenModShipsAreReady()); + } private IEnumerator EnterGameWhenModShipsAreReady() { @@ -280,6 +290,7 @@ public class MainMenu : MonoBehaviour while (!loading.IsCompleted) yield return null; if (loading.IsFaulted) { + Launching = false; if (loading.Exception.GetBaseException() is ShipModShips.ImportFault fault) RefuseMods("Mod ships failed to load", fault.Faults); else Refuse("Mod ships failed to load", loading.Exception.GetBaseException().Message); yield break; diff --git a/Assets/Scripts/UI/Menu/InventoryPanel.cs b/Assets/Scripts/UI/Menu/InventoryPanel.cs index 2087a3870..eaa6212ac 100644 --- a/Assets/Scripts/UI/Menu/InventoryPanel.cs +++ b/Assets/Scripts/UI/Menu/InventoryPanel.cs @@ -386,11 +386,11 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler var itemData = GameManager.ItemManager.GetData(item); if (!(item is EquippableItem equippableItem)) return; var placementPosition = v + itemDragObject.OriginCellOffset; - if (entity.ItemFits(equippableItem, placementPosition)) + if (entity.ItemFits(equippableItem, placementPosition, out var seated)) { //foreach (var cell in _dragCells) cell.gameObject.SetActive(false); FakeItem = item; - FakeOccupancy = hullData.Shape.Inset(itemData.Shape, placementPosition, item.Rotation); + FakeOccupancy = hullData.Shape.Inset(itemData.Shape, placementPosition, seated); RefreshCells(); GameManager.RegisterDragTarget(drag => { diff --git a/Assets/Scripts/UI/Menu/TradeMenu.cs b/Assets/Scripts/UI/Menu/TradeMenu.cs index 5f4123ff2..fa7cec638 100644 --- a/Assets/Scripts/UI/Menu/TradeMenu.cs +++ b/Assets/Scripts/UI/Menu/TradeMenu.cs @@ -211,18 +211,14 @@ public class TradeMenu : MonoBehaviour { if (x.data is HullData) return GameManager.DockedEntity.Children.Count(s => s.Hull.Data.Key.Equals(GameManager.ItemManager.ItemData.RefOf(x.data).Key) && s is Ship {IsPlayerShip: true}).ToString(); - if(x.data is SimpleCommodityData) - return (_targetCargo.ItemsOfType.ContainsKey(GameManager.ItemManager.ItemData.RefOf(x.data).Key) ? _targetCargo.ItemsOfType[GameManager.ItemManager.ItemData.RefOf(x.data).Key].Cast().Sum(s=>s.Quantity) : 0).ToString(); - return (_targetCargo.ItemsOfType.ContainsKey(GameManager.ItemManager.ItemData.RefOf(x.data).Key) ? _targetCargo.ItemsOfType[GameManager.ItemManager.ItemData.RefOf(x.data).Key].Count : 0).ToString(); + return _targetCargo.Count(GameManager.ItemManager.ItemData.RefOf(x.data).Key).ToString(); }, x => { var data = x.data; if (data is HullData) return GameManager.DockedEntity.Children.Count(s => s.Hull.Data.Key.Equals(GameManager.ItemManager.ItemData.RefOf(data).Key) && s is Ship {IsPlayerShip: true}); - if(data is SimpleCommodityData) - return _targetCargo.ItemsOfType.ContainsKey(GameManager.ItemManager.ItemData.RefOf(data).Key) ? _targetCargo.ItemsOfType[GameManager.ItemManager.ItemData.RefOf(data).Key].Cast().Sum(s=>s.Quantity) : 0; - return _targetCargo.ItemsOfType.ContainsKey(GameManager.ItemManager.ItemData.RefOf(data).Key) ? _targetCargo.ItemsOfType[GameManager.ItemManager.ItemData.RefOf(data).Key].Count : 0; + return _targetCargo.Count(GameManager.ItemManager.ItemData.RefOf(data).Key); })); Spreadsheet.ShowData( @@ -241,12 +237,12 @@ public class TradeMenu : MonoBehaviour if (_selling) return; switch (i.item) { + case ICommodityStack _: + Buy(i.item, 1); + break; case CraftedItemInstance c: Buy(c); break; - case SimpleCommodity s: - Buy(s, 1); - break; } Populate(); @@ -256,10 +252,11 @@ public class TradeMenu : MonoBehaviour if (_selling) { ContextMenu.Clear(); - ContextMenu.AddOption($"Sell ({StationServices.SellPrice(GameManager.ItemManager, i.item):N0})", () => Sell(i.item)); + // A compound stack sells only the units the station's bays take: its price is the most it can pay. + ContextMenu.AddOption($"Sell ({(i.item is CompoundCommodity ? "up to " : "")}{StationServices.SellPrice(GameManager.ItemManager, i.item):N0})", () => Sell(i.item)); ContextMenu.Show(); } - else if (i.item is SimpleCommodity s) + else if (i.item is ICommodityStack) { ContextMenu.Clear(); ContextMenu.AddOption("Buy Quantity", @@ -270,10 +267,10 @@ public class TradeMenu : MonoBehaviour Dialog.Title.text = $"Buying {GameManager.ItemManager.Title(i.item)}"; Dialog.AddField("Quantity", () => quantity, - q => quantity = StationServices.BuyableQuantity(GameManager.ItemManager, s, q, GameManager.Credits)); + q => quantity = StationServices.BuyableQuantity(GameManager.ItemManager, i.item, q, GameManager.Credits)); Dialog.Show(() => { - Buy(s,quantity); + Buy(i.item, quantity); Populate(); }); @@ -300,6 +297,12 @@ public class TradeMenu : MonoBehaviour private void Sell(ItemInstance item) { + // A commodity stack sells by what the station wants and as far as its bays hold (StationServices.TrySellPart). + if (item is ICommodityStack stack) + { + Report(StationServices.TrySellPart(_targetCargo, GameManager.DockedEntity, stack, ref GameManager.Credits), GameManager.ItemManager.Title(item)); + return; + } if (StationServices.TrySell(_targetCargo, GameManager.DockedEntity, item, ref GameManager.Credits)) { UpdateCreditsLabel(); @@ -312,14 +315,24 @@ public class TradeMenu : MonoBehaviour Dialog.MoveToCursor(); } - // Sells every mined stack of the player's ships' bays in one step; the station pays through TrySell, so nothing refuses. - private void SellOre() + // Refreshes the menu after a commodity sale and says what happened when the station took less than was offered. + private void Report(SaleResult result, string good) { - StationServices.TrySellOre(PlayerBays(), GameManager.DockedEntity, ref GameManager.Credits); UpdateCreditsLabel(); Populate(); + if (result.Refusal == SaleRefusal.None) return; + Dialog.Clear(); + Dialog.Title.text = result.Refusal == SaleRefusal.NotWanted + ? $"{GameManager.DockedEntity.Name} does not buy {good}" + : $"Sold {result.Sold} of {result.Offered}: station hold full"; + Dialog.Show(); + Dialog.MoveToCursor(); } + // Sells every mined stack of the player's ships' bays the station wants in one step, as far as its bays hold them. + private void SellOre() => + Report(StationServices.TrySellOre(PlayerBays(), GameManager.DockedEntity, ref GameManager.Credits), "ore"); + private IEnumerable PlayerBays() => GameManager.CurrentEntity.Parent.Children.Where(e => e is Ship {IsPlayerShip: true}).SelectMany(s => s.CargoBays); @@ -348,14 +361,14 @@ public class TradeMenu : MonoBehaviour GameManager.CommissionShip(item as EquippableItem); return true; } - return Inventory.TryTransferItem(_targetCargo, item); + return Inventory.TryTransferItem(_targetCargo, item, 1); })); } - private void Buy(SimpleCommodity simpleCommodity, int quantity) + private void Buy(ItemInstance stock, int quantity) { - Bought(StationServices.TryBuyLots(GameManager.ItemManager, simpleCommodity, quantity, ref GameManager.Credits, - lot => Inventory.TryTransferItem(_targetCargo, simpleCommodity, lot))); + Bought(StationServices.TryBuyLots(GameManager.ItemManager, stock, quantity, ref GameManager.Credits, + lot => Inventory.TryTransferItem(_targetCargo, stock, lot))); } // Refreshes the credits after a purchase, or tells the player why the station refused it. @@ -409,7 +422,7 @@ public class TradeMenu : MonoBehaviour }); var repairCost = StationServices.RepairCost(GameManager.ItemManager, GameManager.CurrentEntity); if (repairCost > 0) ContextMenu.AddOption($"Repair ({repairCost:N0})", Repair); - var oreValue = StationServices.OreValue(GameManager.ItemManager, PlayerBays()); + var oreValue = StationServices.OreValue(GameManager.ItemManager, PlayerBays(), GameManager.DockedEntity); if (oreValue > 0) ContextMenu.AddOption($"Sell Ore ({oreValue:N0})", SellOre); ContextMenu.Show(); }); diff --git a/Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs b/Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs index 053e148b8..e034acc01 100644 --- a/Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs +++ b/Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs @@ -364,11 +364,12 @@ public class PropertiesPanel : MonoBehaviour AddProperty(data.Description); - if (item is SimpleCommodity simpleCommodity) - AddProperty("Quantity", () => simpleCommodity.Quantity.ToString()); + if (item is ICommodityStack stack) + AddProperty("Quantity", () => stack.Quantity.ToString()); var sheet = AddStatSheet(); - // Branding is derived from provenance, not stored on the design; a SimpleCommodity carries no lot and shows none. + // Branding is derived from provenance, not stored on the design: a simple commodity carries no lot and shows none, + // a compound stack's brand reads its lot below. if (item is CraftedItemInstance crafted) { var (maker, product) = GameManager.ItemManager.Brand(crafted); diff --git a/Assets/Scripts/Zone Display/MapPresenter.cs b/Assets/Scripts/Zone Display/MapPresenter.cs index 71ffcc7e7..fecd875ab 100644 --- a/Assets/Scripts/Zone Display/MapPresenter.cs +++ b/Assets/Scripts/Zone Display/MapPresenter.cs @@ -48,7 +48,7 @@ public class MapPresenter private readonly Dictionary _entityIcons = new Dictionary(); private readonly Material[] _gravityMaterials; private readonly int _layer = LayerMask.NameToLayer("Minimap"); - private float _minimapScale = 1, _mapScreenScale; + private float _minimapScale = 1, _mapScreenScale, _tacticalScale; private bool _mapScreenOpen; private readonly Material _asteroidMaterial; private readonly Vector4 _spriteSheet; @@ -63,8 +63,10 @@ public class MapPresenter _asteroidSize = asteroidSize; } - // The icon size: the map screen's scale while it is open, else the minimap's zoom. - public float IconSize => _mapScreenOpen ? _mapScreenScale : _minimapScale; + // The icon size: the map screen's scale while it is open, else the tactical scale while the schematic shows, else + // the minimap's zoom. + public float IconSize => _mapScreenOpen ? _mapScreenScale : _tacticalScale > 0 ? _tacticalScale : _minimapScale; + public void SetTacticalScale(float scale) => _tacticalScale = scale; public void SetMinimapScale(float scale) => _minimapScale = scale; public void OpenMapScreen(bool open) => _mapScreenOpen = open; diff --git a/Assets/Scripts/Zone Display/TacticalFade.cs b/Assets/Scripts/Zone Display/TacticalFade.cs new file mode 100644 index 000000000..e35e1cc80 --- /dev/null +++ b/Assets/Scripts/Zone Display/TacticalFade.cs @@ -0,0 +1,32 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using UnityEngine; +using UnityEngine.Rendering.PostProcessing; + +// The tactical view's fade (ruling tactical-view-is-zoom-out): after the post stack the scene colour lerps toward the +// background by Strength. The volume's weight is the tactical blend, so Strength stays 1 and the fade is derived from +// camera distance like everything else about the view. +[Serializable] +[PostProcess(typeof(TacticalFadeRenderer), PostProcessEvent.AfterStack, "Aetheria/Tactical Fade", false)] +public sealed class TacticalFade : PostProcessEffectSettings +{ + [Range(0, 1)] public FloatParameter Strength = new FloatParameter { value = 1 }; + public ColorParameter Background = new ColorParameter { value = Color.black }; +} + +public sealed class TacticalFadeRenderer : PostProcessEffectRenderer +{ + private static readonly int StrengthId = Shader.PropertyToID("_Strength"); + private static readonly int BackgroundId = Shader.PropertyToID("_Background"); + + public override void Render(PostProcessRenderContext context) + { + var sheet = context.propertySheets.Get(Shader.Find("Aetheria/PostProcessing/TacticalFade")); + sheet.properties.SetFloat(StrengthId, settings.Strength); + sheet.properties.SetColor(BackgroundId, settings.Background); + context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0); + } +} diff --git a/Assets/Scripts/Zone Display/TacticalFade.cs.meta b/Assets/Scripts/Zone Display/TacticalFade.cs.meta new file mode 100644 index 000000000..7c11eb8e5 --- /dev/null +++ b/Assets/Scripts/Zone Display/TacticalFade.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: edb50c44dcb243aeacbc04ec22a8d013 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Zone Display/WormholeWarp.cs b/Assets/Scripts/Zone Display/WormholeWarp.cs new file mode 100644 index 000000000..7646c1dfe --- /dev/null +++ b/Assets/Scripts/Zone Display/WormholeWarp.cs @@ -0,0 +1,88 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using UnityEngine; +using UnityEngine.Rendering.PostProcessing; + +// The screen-space effect of wormhole travel: lensing, swirl and a chromatic split toward the wormhole. Display only: +// Ship.WormholeWarp is the one input and nothing here writes sim state. +[Serializable] +[PostProcess(typeof(WormholeWarpRenderer), PostProcessEvent.AfterStack, "Aetheria/Wormhole Warp")] +public sealed class WormholeWarp : PostProcessEffectSettings +{ + [Tooltip("Where the wormhole is on screen, in viewport uv.")] + public Vector2Parameter Center = new Vector2Parameter { value = new Vector2(.5f, .5f) }; + + [Range(0, 1), Tooltip("How far into the warp the screen is.")] + public FloatParameter Strength = new FloatParameter { value = 0 }; + + public override bool IsEnabledAndSupported(PostProcessRenderContext context) => + enabled.value && Strength.value > 0; +} + +[UnityEngine.Scripting.Preserve] +internal sealed class WormholeWarpRenderer : PostProcessEffectRenderer +{ + // The shader sits under a Resources folder so a player build always carries it; Shader.Find finds it by name. + private static bool _missingLogged; + + public override void Render(PostProcessRenderContext context) + { + var shader = Shader.Find("Hidden/Aetheria/WormholeWarp"); + if (shader == null) + { + if (!_missingLogged) Debug.LogError("WormholeWarp shader missing from the build"); + _missingLogged = true; + context.command.BuiltinBlit(context.source, context.destination); + return; + } + var sheet = context.propertySheets.Get(shader); + sheet.properties.SetVector("_Center", settings.Center.value); + sheet.properties.SetFloat("_Strength", settings.Strength.value); + sheet.properties.SetFloat("_Aspect", (float)context.screenWidth / context.screenHeight); + context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0); + } +} + +// Holds the warp volume for one transition: from entering the wormhole through the exit animation on the same ship. +// It reads the ship and the live camera and writes only the volume. +public sealed class WormholeWarpPresenter : MonoBehaviour +{ + private Ship _ship; + private PostProcessVolume _volume; + private WormholeWarp _settings; + private bool _seenAnimation; + + public static void Begin(Ship ship, int layer, float priority) + { + var presenter = new GameObject("Wormhole Warp").AddComponent(); + presenter._ship = ship; + presenter._settings = ScriptableObject.CreateInstance(); + presenter._settings.enabled.Override(true); + presenter._volume = PostProcessManager.instance.QuickVolume(layer, priority, presenter._settings); + } + + private void LateUpdate() + { + if (!_ship.WormholeAnimationInProgress) + { + if (_seenAnimation) Destroy(gameObject); + return; + } + _seenAnimation = true; + var camera = Camera.main; + if (camera == null) return; + // The wormhole the ship is at in this half, read from the ship each frame. + var wormhole = _ship.WormholePosition; + var viewport = camera.WorldToViewportPoint(new Vector3(wormhole.x, 0, wormhole.y)); + _settings.Center.value = new Vector2(viewport.x, viewport.y); + _settings.Strength.value = _ship.WormholeWarp; + } + + private void OnDestroy() + { + if (_volume != null) RuntimeUtilities.DestroyVolume(_volume, true, true); + } +} diff --git a/Assets/Scripts/Zone Display/WormholeWarp.cs.meta b/Assets/Scripts/Zone Display/WormholeWarp.cs.meta new file mode 100644 index 000000000..dd979ab73 --- /dev/null +++ b/Assets/Scripts/Zone Display/WormholeWarp.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4d6d1ab718884b94b70c511f1f126d91 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Zone Display/ZoneRenderer.cs b/Assets/Scripts/Zone Display/ZoneRenderer.cs index f63f746bd..0a257811d 100644 --- a/Assets/Scripts/Zone Display/ZoneRenderer.cs +++ b/Assets/Scripts/Zone Display/ZoneRenderer.cs @@ -144,10 +144,26 @@ public class ZoneRenderer : MonoBehaviour _viewDistance = value; foreach (var camera in FogCameras) camera.orthographicSize = value; - SceneCamera.m_Lens.FarClipPlane = value * FarPlaneDistanceMultiplier; + ApplyFarClip(); } } + // How far the camera must see to take in the whole zone from where the follow camera sits (the tactical view's + // reach). The view distance sets the floor; ApplyFarClip is the one writer of the scene camera's far clip. + public float FarClipNeeded + { + set + { + _farClipNeeded = value; + ApplyFarClip(); + } + } + + private float _farClipNeeded; + + private void ApplyFarClip() => + SceneCamera.m_Lens.FarClipPlane = Mathf.Max(_viewDistance * FarPlaneDistanceMultiplier, _farClipNeeded); + public float MinimapDistance { set @@ -326,10 +342,19 @@ public class ZoneRenderer : MonoBehaviour _clouds.Add(cloud, instance); } + private const string BeaconChildName = "Anchor Beacon"; + public void AddWormhole(Wormhole wormhole) { var instance = Instantiate(WormholePrefab); instance.position = new Vector3(wormhole.Position.x, 0, wormhole.Position.y); + // Its local +z points away from the zone centre, so the beacon prefab child stands beyond the wormhole. + if (wormhole.Position.x != 0 || wormhole.Position.y != 0) + instance.rotation = Quaternion.LookRotation(new Vector3(wormhole.Position.x, 0, wormhole.Position.y)); + // The prefab ships the beacon inactive so menu dressing instances stay bare; a zone wormhole turns it on. + var beacon = instance.Find(BeaconChildName); + if (beacon == null) throw new InvalidOperationException($"Wormhole prefab has no '{BeaconChildName}' child"); + beacon.gameObject.SetActive(true); var icon = CompassIconPrototype.Instantiate(); icon.Icon.sprite = WormholeIcon; WormholeInstances.Add(wormhole, (instance.gameObject, icon)); @@ -508,6 +533,7 @@ public class ZoneRenderer : MonoBehaviour void LateUpdate() { + if (!ActionGameManager.RunLive) return; Map.Draw(Zone, ActionGameManager.Clock.Lead); } @@ -550,6 +576,7 @@ public class ZoneRenderer : MonoBehaviour void Update() { + if (!ActionGameManager.RunLive) return; var lead = ActionGameManager.Clock.Lead; GravityLowering.Lower(Zone, lead, ref _gravityWells); foreach (var loot in _floatingItems.Values) diff --git a/Assets/Materials/Substance.meta b/Assets/Shaders/Resources.meta similarity index 77% rename from Assets/Materials/Substance.meta rename to Assets/Shaders/Resources.meta index c6926c786..05251681e 100644 --- a/Assets/Materials/Substance.meta +++ b/Assets/Shaders/Resources.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 7de1c11cf7591ec48bdb53e9818172f5 +guid: ef7b30a9009e498fb4d5933bd723992b folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/Shaders/Resources/TacticalFade.shader b/Assets/Shaders/Resources/TacticalFade.shader new file mode 100644 index 000000000..cd695e580 --- /dev/null +++ b/Assets/Shaders/Resources/TacticalFade.shader @@ -0,0 +1,28 @@ +Shader "Aetheria/PostProcessing/TacticalFade" +{ + // Lerps the scene colour toward a flat background by Strength: the scene fades out as the tactical view comes in. + // The schematic camera renders after the post stack, so this never dims it. + SubShader + { + Cull Off ZWrite Off ZTest Always + + Pass + { + HLSLPROGRAM + #pragma vertex VertDefault + #pragma fragment Frag + #include "Packages/com.unity.postprocessing/PostProcessing/Shaders/StdLib.hlsl" + + TEXTURE2D_SAMPLER2D(_MainTex, sampler_MainTex); + float _Strength; + float4 _Background; + + float4 Frag(VaryingsDefault i) : SV_Target + { + float4 scene = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.texcoordStereo); + return float4(lerp(scene.rgb, _Background.rgb, saturate(_Strength)), scene.a); + } + ENDHLSL + } + } +} diff --git a/Assets/Shaders/Resources/TacticalFade.shader.meta b/Assets/Shaders/Resources/TacticalFade.shader.meta new file mode 100644 index 000000000..c67b3aad5 --- /dev/null +++ b/Assets/Shaders/Resources/TacticalFade.shader.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 20fc266aaa8644d392ec11bfaf7fc4f3 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Shaders/Resources/WormholeWarp.shader b/Assets/Shaders/Resources/WormholeWarp.shader new file mode 100644 index 000000000..5e8edbbcf --- /dev/null +++ b/Assets/Shaders/Resources/WormholeWarp.shader @@ -0,0 +1,56 @@ +// The screen-space transition into a wormhole: a radial lensing pull toward the wormhole, a swirl and a small chromatic +// split, all scaled by one strength. Lives under Resources so the player build always carries it (WormholeWarp.cs finds +// it with Shader.Find). +Shader "Hidden/Aetheria/WormholeWarp" +{ + SubShader + { + Cull Off ZWrite Off ZTest Always + + Pass + { + HLSLPROGRAM + #pragma target 3.5 + #pragma vertex VertDefault + #pragma fragment Frag + #include "../CustomDoF/StdLib.hlsl" + + TEXTURE2D_SAMPLER2D(_MainTex, sampler_MainTex); + float2 _Center; // viewport uv of the wormhole + float _Strength; // 0..1 + float _Aspect; // width / height + + // The colour the pixel shows when the screen is pulled toward the centre by pull, turned by swirl. + half3 Warp(float2 uv, float pull, float swirl) + { + float2 d = (uv - _Center) * float2(_Aspect, 1); + float s, c; + sincos(swirl, s, c); + d = float2(c * d.x - s * d.y, s * d.x + c * d.y) * (1 + pull); + float2 src = _Center + d / float2(_Aspect, 1); + return SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, src).rgb; + } + + float4 Frag(VaryingsDefault i) : SV_Target + { + float2 uv = UnityStereoTransformScreenSpaceTex(i.texcoordStereo); + float2 d = (uv - _Center) * float2(_Aspect, 1); + float r = length(d); + float well = exp(-r * 2.2); // 1 at the wormhole, fading out across the screen + float pull = _Strength * (0.35 + 1.4 * well); + float swirl = _Strength * 2.4 * well * well; + float split = 0.06 * _Strength * well; + + half3 col; + col.r = Warp(uv, pull + split, swirl).r; + col.g = Warp(uv, pull, swirl).g; + col.b = Warp(uv, pull - split, swirl).b; + + // The throat darkens as the dive deepens. + col *= 1 - saturate(_Strength * _Strength * well * 1.1); + return float4(col, 1); + } + ENDHLSL + } + } +} diff --git a/Assets/Shaders/Resources/WormholeWarp.shader.meta b/Assets/Shaders/Resources/WormholeWarp.shader.meta new file mode 100644 index 000000000..0b7ffe143 --- /dev/null +++ b/Assets/Shaders/Resources/WormholeWarp.shader.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 04f163edfb284c52903ef7796af0df2b +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Steel.mat b/Assets/Steel.mat deleted file mode 100644 index fc4d8d0ca..000000000 --- a/Assets/Steel.mat +++ /dev/null @@ -1,83 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Steel - m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - m_ShaderKeywords: _MAINTEX _METALLICGLOSSMAP _NORMALMAP _OCCLUSIONMAP _PARALLAXMAP - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 4, y: 4} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 4, y: 4} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _GlossMapScale: 1 - - _Glossiness: 0.5 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - m_BuildTextureStacks: [] diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..168b0cefc --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +## 0.2.0 (2026-10-29) + +### Features + +- First test build since 2020, for Windows and Linux (x86-64), published to GitHub by hand. Flight under the weaker gravity field: thrust is a tenth of its authored push and drag applies only above top speed, so orbits coast instead of decaying. Keyboard turning ramps up and down, and thrusters join a turn in order of the yaw they give per unit of push. Weapons aim along your view's pitch and the crosshair follows; weapon groups bind to the mouse buttons and number row the first time you fly a ship. Stardust and dithered particles draw under the nebula fog. Undocking no longer flings the ship into the void. Console: `fly ` puts you in a freshly fitted ship of that hull. `ModTools/AetherDb` is the mod and data tool. diff --git a/CLAUDE.md b/CLAUDE.md index 16fe9b214..2ed5ea4a4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,3 +19,8 @@ `Directory.Build.props` (`Directory.Build.targets` enforces it). When `F:\Projects\CultLib` is elsewhere, point `CULTLIB_ROOT` and `CULTMATH_ROOT` at detached worktrees of those revisions; never move the shared checkout. - CultCache Studio is the operator's GUI over the same files. It is not an agent path. + +## Releases + +- Player-visible means a player of the shipped game could notice it, or a modder using the shipped ModTools could. Needs a change file: gameplay or balance changes, new or changed content, UI or controls, fixes to bugs a player could hit, modding format changes. Needs none: tests, refactors, docs, editor-only tools, build and CI changes, internal data layout that players and modders never see. +- A player-visible change lands with a `.changeset/` file (bump level and one player-facing line), written by whoever lands it, agents included. Change files decide the release's version bump and changelog; `docs/release-checklist.md` has the format. diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index ef463cde8..abb012cc4 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:62a6678e741e296449b6ac8cd8698e071a873ea39bc9c0303abe68887310dceb -size 220731 +oid sha256:00e840dbad797c0ce62cb6038dea24963cbda2c273c1f5bcf22481bf2b10f4bf +size 293693 diff --git a/GameData/Mods/aetheria.arsenal-depot/hull.scad b/GameData/Mods/aetheria.arsenal-depot/hull.scad new file mode 100644 index 000000000..f7fc3c4a6 --- /dev/null +++ b/GameData/Mods/aetheria.arsenal-depot/hull.scad @@ -0,0 +1,78 @@ +// Zhestokost Arsenal Depot, a station: the hull bench's cast-iron Dutch oven with its lid on (AetheriaLore, Brainstorming/Ship +// Prompt Bench.md, Stations and Station Modules). One squat charcoal pot, a heavy iron-grey stepped lid with a round knob +// for its control tower, two thick lugs on opposite flanks that are the docking piers, four broad magazine bands round the +// pot wall with oxide hatches. Built only from the Zhestokost kit and lowpoly primitives. +// part = lang | brief | anchors | lines | primary | secondary | accent | recess | marking | rad: +// Frame: Ship Root, metres, nose -Y, starboard -X, up +Z. The piers stand on the X axis; the rest of the outline is round. +include +part = "primary"; + +HULL_FACTION = "zhestokost"; +HULL_DONOR = ""; +HULL_ROLE = "depot"; +HULL_LENGTH = [20, 26]; +HULL_TRIANGLES = [800, 9000]; +HULL_READS = ["the hull is a cast-iron Dutch oven with its lid on: one squat thick charcoal pot, a heavy stepped iron lid, a round knob on top", + "the knob is the control tower, ringed by narrow observation slits", + "two thick lugs on opposite flanks are the docking piers, each ending in one square-set docking collar with guide lugs", + "four broad magazine bands ring the pot wall, oxide-red square hatches set in them", + "two radiator troughs on the lid, either side of the knob; no thrusters and no guns, a depot does not move or fight"]; +if (part == "brief") echo(brief = [HULL_FACTION, HULL_DONOR, HULL_ROLE, HULL_LENGTH, HULL_TRIANGLES, HULL_READS]); + +POT_R = 11.7; // pot wall circumradius; its top-view raster must stay a disc of about 12 cells +POT_H = 7.2; +BAND_R = 11.85; // bands stand 0.15 m proud: the widest the top view gets (23.7 m, 12 cells) +BANDS = [[0.5, 2.0], [2.3, 3.8], [4.1, 5.6], [5.9, 7.1]]; +LID = [[POT_H - 0.2, 11.85], [8.7, 10.0], [10.4, 8.0]]; // [z, radius]: lip, first step, deck +DECK_Z = 10.4; +TOWER_R = 2.4; +TOWER_TOP = 13.2; +LUG_X = [9.4, 13.1]; // piers: x from the pot into the flank; the collars end at 13.95 m +LUG_Y = 4.0; +LUG_H = 5.2; +HATCH_AT = [50, 130, 230, 310]; // azimuths, deg: clear of the piers on the X axis and of the y extremes +RAD_Y = 4.9; RAD_W = 5.2; RAD_L = 2.4; +RADS = [["Ra.N1", -1, 1], ["Ra.N2", -1, -1], ["Ra.S1", 1, 1], ["Ra.S2", 1, -1]]; // [id, trough y sign, trough side] + +// A round mass from z0 to z1, r0 at the base and r1 at the top. +module cone(z0, z1, r0, r1, fn=24) translate([0, 0, z0]) cylinder(r1=r0, r2=r1, h=z1 - z0, $fn=fn); + +// pot (charcoal) with its bottom chamfer +zh_z("secondary") { + cone(0, 0.6, POT_R - 0.9, POT_R); + cone(0.6, POT_H, POT_R, POT_R); +} +// four magazine bands, proud of the pot +for (b = BANDS) zh_z("secondary") cone(b[0], b[1], BAND_R, BAND_R); +// lid: a lip, then two steps up to a flat deck (iron grey) +zh_z("primary") { + cone(LID[0][0], 7.7, LID[0][1], LID[0][1]); + cone(7.7, LID[1][0], LID[0][1], LID[1][1]); + cone(LID[1][0], LID[2][0] + 0.05, LID[1][1], LID[2][1]); + // knob: the control tower + cone(DECK_Z - 0.05, TOWER_TOP, TOWER_R + 0.5, TOWER_R, 12); +} +zh_z("secondary") cone(TOWER_TOP - 0.05, TOWER_TOP + 0.45, TOWER_R + 0.35, TOWER_R + 0.35, 12); +// observation slits ring the tower: black recesses sunk in its wall +zh_z("recess") for (k = [0:11]) rotate([0, 0, k*30 + 15]) translate([TOWER_R - 0.05, 0, 12.2]) cube([0.28, 0.5, 0.45], center=true); +// the piers: a thick lug on each flank, one docking collar on each outer face +for (s = [-1, 1]) { + zh_z("secondary") translate([s*(LUG_X[0] + LUG_X[1])/2, 0, LUG_H/2]) cbox([LUG_X[1] - LUG_X[0], LUG_Y, LUG_H], 0.3); + lp_at(t=[s*LUG_X[1], 0, LUG_H/2], r=[0, 90*s, 0]) zh_collar(1.5, 0.55); + lp_at(t=[s*(LUG_X[0] + LUG_X[1])/2, 0, LUG_H], r=[0, 0, 90]) zh_stripes(2.4, 1.4, 3); +} +// magazine hatches on each band, at four azimuths; cream serials on the bands between them +for (b = BANDS, a = HATCH_AT) + lp_at(t=[BAND_R*cos(a), BAND_R*sin(a), (b[0] + b[1])/2], r=[90, 0, a + 90]) zh_hatch(1.9, 1.0, dogs=false); +for (a = [80, 100, 260, 280]) + lp_at(t=[BAND_R*cos(a), BAND_R*sin(a), 3.05], r=[90, 0, a + 90]) zh_serial(0.5, 3); +// two radiator troughs on the deck, either side of the knob +for (y = [-RAD_Y, RAD_Y]) lp_at(t=[0, y, DECK_Z]) zh_rad_trough(RAD_W, RAD_L, 0.45); +// silhouette lines: the pot's cast belt and the lid deck edge +lp_line("outline", [for (a = [0:15:345]) [BAND_R*cos(a), BAND_R*sin(a), POT_H]], true); +lp_line("step", [for (a = [0:15:345]) [LID[2][1]*cos(a), LID[2][1]*sin(a), DECK_Z]], true); + +// ---- anchor meshes: each radiator is one half of a trough ---- +for (r = RADS) if (part == str("rad:", r[0])) lp_at(t=[0, r[1]*RAD_Y, DECK_Z]) zh_rad_vanes(RAD_W, RAD_L, r[2], 4, 1.0); +if (part == "anchors") for (r = RADS) + echo(anchor=[r[0], "radiator-mesh", [0, r[1]*RAD_Y, DECK_Z] + zh_rad_centre(RAD_W, r[2], 1.0), 0, ""]); diff --git a/GameData/Mods/aetheria.arsenal-depot/ship.cc b/GameData/Mods/aetheria.arsenal-depot/ship.cc new file mode 100644 index 000000000..949c10991 --- /dev/null +++ b/GameData/Mods/aetheria.arsenal-depot/ship.cc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:39161fd005235347759ea079c962e4749b3c5c81410c83b1f871f9de5d08bfe3 +size 16300 diff --git a/GameData/Mods/aetheria.arsenal-depot/ship.glb b/GameData/Mods/aetheria.arsenal-depot/ship.glb new file mode 100644 index 000000000..ef3312415 --- /dev/null +++ b/GameData/Mods/aetheria.arsenal-depot/ship.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f68823688181d712c979224701858a716f00feaed56237d957ce6ade0546db2 +size 294628 diff --git a/GameData/Mods/aetheria.nakovalnya/ship.cc b/GameData/Mods/aetheria.nakovalnya/ship.cc index 1def7b776..c0f3c416c 100644 --- a/GameData/Mods/aetheria.nakovalnya/ship.cc +++ b/GameData/Mods/aetheria.nakovalnya/ship.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0228aa7ec3a2e060bd49e46aa64f52eea4c4cdb25951c164646c1d031ad17851 +oid sha256:f941afb95cac379b22347ab9465b7d95bd6fd2969e23e97d1b63721a2d97f800 size 30457 diff --git a/GameData/Mods/aetheria.nakovalnya/ship.glb b/GameData/Mods/aetheria.nakovalnya/ship.glb index 3dac76cc9..af1e370e6 100644 --- a/GameData/Mods/aetheria.nakovalnya/ship.glb +++ b/GameData/Mods/aetheria.nakovalnya/ship.glb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:90a503473e3b12251c225b7fe283b2fc5b45a25e6e47839d1c3d78e3ac61b00c -size 843452 +oid sha256:ab3fdd340bf27fc8c2a6149ce6be9159215cf26b3eabd290064ffe40b2e96512 +size 839556 diff --git a/GameData/Mods/aetheria.seized-refinery/hull.scad b/GameData/Mods/aetheria.seized-refinery/hull.scad new file mode 100644 index 000000000..fe3850921 --- /dev/null +++ b/GameData/Mods/aetheria.seized-refinery/hull.scad @@ -0,0 +1,110 @@ +// Pirate Coalition station "Seized Refinery" on a stolen Zhestokost donor: a cast-iron pot-bellied stove, the furnace, with +// Pirate additions welded on one side. The firebox is an octagonal cast box, not a drum: flat faces keep the station's interior roomy. An agent-built hull source: the donor body and its fittings come from the Zhestokost +// language (zones keyed zhestokost:), every addition from the Pirate language. No bench prompt names a refinery; this +// is a first proposal of the form, not a ruling on it. +// part = lang | brief | anchors | lines | marks | zhestokost: | primer | weld | accent | recess | rad: +// Frame: Ship Root, metres, nose -Y, starboard -X, up +Z. The docking door faces the nose; the stovepipe is the control tower. +include +include +part = "zhestokost:primary"; + +HULL_FACTION = "pirate"; +HULL_DONOR = "zhestokost"; +HULL_ROLE = "refinery"; +HULL_LENGTH = [14, 26]; +HULL_TRIANGLES = [800, 9000]; +HULL_READS = ["the stolen Zhestokost body is still a cast-iron pot-bellied stove: one squat octagonal firebox belly, a flat cooktop, a tall stovepipe that is the control tower", + "a square firebox door on the nose with a docking collar in it is the ore intake, an ash-pan drawer below it", + "bolted primer-red salvage plates cover a breach in the belly, an exposed cable run climbs from a stolen reactor saddle on the cooktop to a second docking collar welded on the starboard flank", + "one oversized stolen gun on an adapted saddle, out of proportion to the stove", + "Zhestokost stencils on the belly are crossed out in the crew's own colour", + "no thrusters, a refinery does not move; asymmetric"]; +if (part == "brief") echo(brief = [HULL_FACTION, HULL_DONOR, HULL_ROLE, HULL_LENGTH, HULL_TRIANGLES, HULL_READS]); + +A = 10.2; // belly apothem (centre to the middle of a flat face) +TOP_A = 7.6; // cooktop apothem +TOP = 9.0; // cooktop height +PIPE = [0, 1.0]; // stovepipe centre +PIER_X = [A - 0.8, A + 3.0]; // the welded pier on the starboard flank: x from the belly out (mirrored to -X) +PIER_Y = -1.5; +PIER_W = 9.0; // the pier's width along Y +RAD_W = 2.6; RAD_L = 3.6; +TROUGH = [[4.1, 1.0], [-4.1, 1.0]]; +RADS = [["Ra.1", 0, 1], ["Ra.2", 1, -1]]; // [id, trough index, side of the trough its vanes stand in] + +// A round mass from z0 to z1, r0 at the base and r1 at the top. +module cone(z0, z1, r0, r1, fn=28) translate([0, 0, z0]) cylinder(r1=r0, r2=r1, h=z1 - z0, $fn=fn); +// An octagonal mass, flat faces on the axes, from z0 to z1; a0 and a1 are apothems. +module oct(z0, z1, a0, a1) rotate([0, 0, 22.5]) cone(z0, z1, a0/cos(22.5), a1/cos(22.5), 8); +function oct_ring(a, z) = [for (k = [0:7]) let(t = 22.5 + 45*k) [a/cos(22.5)*cos(t), a/cos(22.5)*sin(t), z]]; +// A frame on a flat face of the belly at azimuth a (a multiple of 45), height z: local +Z points out of the face. +module on_wall(a, z, out=0) lp_at(t=[(A + out)*cos(a), (A + out)*sin(a), z], r=[90, 0, a + 90]) children(); + +// ---- the donor: the stove ---- +// firebox belly (body): a chamfered foot, the cast belly, a battered shoulder up to the cooktop +zh_z("primary") { + oct(0.4, 1.4, A - 1.0, A); + oct(1.4, 6.0, A, A); + oct(6.0, TOP - 0.4, A, TOP_A - 0.2); +} +// the cooktop, two cast belts, the stovepipe's flared foot and its cap +zh_z("secondary") { + oct(TOP - 0.6, TOP, TOP_A, TOP_A - 0.2); + oct(3.0, 3.6, A + 0.15, A + 0.15); + oct(5.0, 5.5, A + 0.15, A + 0.15); + translate([PIPE[0], PIPE[1], 0]) { cone(TOP - 0.05, TOP + 1.3, 2.4, 1.5, 12); cone(TOP + 6.9, TOP + 7.5, 1.85, 1.85, 12); } +} +// the stovepipe: the control tower, ringed by narrow observation slits +zh_z("primary") translate([PIPE[0], PIPE[1], 0]) cone(TOP + 1.2, TOP + 7.0, 1.5, 1.3, 12); +zh_z("recess") translate([PIPE[0], PIPE[1], 0]) for (k = [0:9]) rotate([0, 0, k*36 + 18]) translate([1.3, 0, TOP + 5.4]) cube([0.3, 0.55, 0.5], center=true); +// the firebox door on the nose face: the ore intake, with the docking collar in it; the ash-pan drawer below +lp_at(t=[0, -A, 3.2], r=[90, 0, 0]) zh_hatch(4.4, 3.6, dogs=false); +lp_at(t=[0, -A - 0.2, 3.2], r=[90, 0, 0]) zh_collar(1.6, 0.6); +zh_z("secondary") translate([0, -A - 0.5, 0.95]) cbox([5.0, 2.6, 1.5], 0.2); +zh_z("accent") translate([0, -A - 1.85, 0.95]) cbox([2.6, 0.4, 0.4], 0.08); +// two radiator troughs on the cooktop, either side of the pipe +for (t = TROUGH) lp_at(t=[t[0], t[1], TOP]) zh_rad_trough(RAD_W, RAD_L, 0.45); +// Zhestokost stencils on the two faces flanking the door +for (a = [225, 315]) on_wall(a, 3.2) zh_serial(0.9, 3); +// silhouette lines: the belly's cast belt and the cooktop edge +lp_line("outline", oct_ring(A + 0.15, 3.6), true); +lp_line("step", oct_ring(TOP_A, TOP), true); + +// ---- the Pirate additions, one side and unmatched ---- +// primer-red salvage plates bolted over a breach in the starboard rear face +module wall_plate(a, y, z, w, l, tilt) translate([A*cos(a), y, z]) rotate([0, 0, a + 90]) rotate([90, 0, 0]) pi_plate(w, l, 0.14, tilt); +if (part == "primer") { + translate([-(A + 0.02)*cos(45), (A + 0.02)*sin(45), 0]) {} // (faces at 135 degrees carry the plates below) + for (p = [[2.6, 2.4, 3.2, 3.0, 4], [4.3, -0.8, 2.4, 2.0, -6], [1.9, 3.8, 1.8, 1.6, 7]]) + translate([A*cos(135) + 0.0, A*sin(135) + 0, 0]) rotate([0, 0, 135 + 90]) translate([p[1], 0, p[0]]) rotate([90, 0, 0]) pi_plate(p[2], p[3], 0.14, p[4]); + translate([-4.6, 5.0, TOP + 0.1]) pi_plate(2.2, 1.8, 0.12, 5); +} +// the welded pier with its second docking collar, the stolen reactor on its saddle, the exposed cable run, the oversized gun +module cables() { + pi_cable([[-3.0, -3.9, TOP + 1.0], [-5.4, -3.5, TOP + 0.6], [-(TOP_A + 0.8), -3.0, TOP - 1.2], [-(A + 0.1), -2.6, 5.0], [-(A + 1.2), -2.0, 4.6]]); + pi_cable([[-3.4, -3.3, TOP + 0.8], [-5.6, -2.4, TOP + 0.5], [-(TOP_A + 0.9), -1.9, TOP - 1.3], [-(A + 0.1), -1.4, 5.0], [-(A + 1.4), -1.2, 4.6]], 0.05); +} +if (part == "weld") { + translate([-(PIER_X[0] + PIER_X[1])/2, PIER_Y, 2.6]) cbox([PIER_X[1] - PIER_X[0], PIER_W, 3.6], 0.2); + translate([-(PIER_X[0] + 1.6), PIER_Y, 5.1]) rotate([0, 0, 90]) pi_plate(1.6, 1.4, 0.12, 3); + strut([-(PIER_X[0] + 0.4), PIER_Y - 1.4, 4.4], [-(A - 0.6), PIER_Y - 3.4, 6.4], 0.12); + strut([-(PIER_X[0] + 0.4), PIER_Y + 1.4, 4.4], [-(A - 0.4), PIER_Y + 3.2, 6.0], 0.12); + translate([-(PIER_X[1] + 0.05), PIER_Y, 2.6]) rotate([0, 90, 0]) pi_collar(1.8, 0.3); + translate([-3.0, -3.8, TOP]) { pi_saddle(2.6, 3.2, 1.0); translate([0, 0, 1.0]) cylinder(r=0.85, h=1.3, $fn=10); } + cables(); + translate([2.8, -3.2, TOP]) { pi_saddle(1.4, 2.6, 0.6); translate([0, 0, 1.0]) pi_big_gun(8.0, 0.2); } +} +if (part == "recess") translate([-(PIER_X[1] + 0.2), PIER_Y, 2.6]) rotate([0, 90, 0]) pi_collar(1.25, 0.2); +// the crew's own colour: one slash across a crossed-out stencil, one across the cooktop, a sensor pod on the stovepipe +if (part == "accent") { + translate([(A + 0.06)*cos(315), (A + 0.06)*sin(315), 3.2]) rotate([0, 0, 315 + 90]) rotate([90, 0, 0]) rotate([0, 0, 40]) cube([3.4, 0.4, 0.12], center=true); + translate([-0.5, -1.2, TOP + 0.04]) rotate([0, 0, -38]) cube([0.7, 7.0, 0.06], center=true); + translate([2.5, PIPE[1] + 0.4, TOP + 4.4]) pi_sensor_pod(1.6, 0.34); + strut([1.2, PIPE[1] + 0.2, TOP + 4.2], [2.5, PIPE[1] + 0.4, TOP + 4.4], 0.07); +} + +// ---- anchor meshes: each radiator is one half of a trough; the other half was stripped ---- +for (r = RADS) if (part == str("rad:", r[0])) + lp_at(t=[TROUGH[r[1]][0], TROUGH[r[1]][1], TOP]) zh_rad_vanes(RAD_W, RAD_L, r[2], 4, 1.0); +if (part == "anchors") for (r = RADS) + echo(anchor=[r[0], "radiator-mesh", [TROUGH[r[1]][0], TROUGH[r[1]][1], TOP] + zh_rad_centre(RAD_W, r[2], 1.0), 0, ""]); diff --git a/GameData/Mods/aetheria.seized-refinery/ship.cc b/GameData/Mods/aetheria.seized-refinery/ship.cc new file mode 100644 index 000000000..46c77cca7 --- /dev/null +++ b/GameData/Mods/aetheria.seized-refinery/ship.cc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78fbcc524b4a8537b8266b70700f41eb5f62019a7cb8a40bace90718eee1acd1 +size 11942 diff --git a/GameData/Mods/aetheria.seized-refinery/ship.glb b/GameData/Mods/aetheria.seized-refinery/ship.glb new file mode 100644 index 000000000..6fadc4319 --- /dev/null +++ b/GameData/Mods/aetheria.seized-refinery/ship.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f86da950d672dbb40147668dcce187e6c438d7ad775be9bdb988601480b70c32 +size 192728 diff --git a/GameData/Mods/aetheria.wren/ship.glb b/GameData/Mods/aetheria.wren/ship.glb deleted file mode 100644 index 03b70b729..000000000 --- a/GameData/Mods/aetheria.wren/ship.glb +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:98bf1b4a0e19e67568930ca79b9d61529c21c63dd74ee8df3d3f1d419d3a81cc -size 6964 diff --git a/ProjectSettings/ProjectSettings.asset b/ProjectSettings/ProjectSettings.asset index 1b000cd89..76b6938ad 100644 --- a/ProjectSettings/ProjectSettings.asset +++ b/ProjectSettings/ProjectSettings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1f95917a4ca95a4f6977be90d80185648b012099467fa2275b31b868aca88b6f -size 24058 +oid sha256:900f257853e7bf436c28cb323c323f2ef43e8d0659253ca7545cd23255d8ea57 +size 24033 diff --git a/VERSION b/VERSION new file mode 100644 index 000000000..0ea3a944b --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.2.0 diff --git a/docs/aetheria-living-world-map.md b/docs/aetheria-living-world-map.md index 6a98e8cec..6d3377a00 100644 --- a/docs/aetheria-living-world-map.md +++ b/docs/aetheria-living-world-map.md @@ -82,6 +82,62 @@ Role slots per recipe (`RoleInputsOf`), fillers per role, `OfferedDesigns`, `Des - needs tables (cut 7): the needs half of L-consumer-demand and the consumer-good sink in SourceSink. - Open follow-up: `recipe-less-design-roles` (pre-existing, left alone by cut-economy-checks h2). +## Body facts: player loop (nibu-imagination, 2026-11-27, at 305d9cde7) + +Probe: a throwaway env-gated test in a detached worktree (removed), on the shipped catalog through the RunStartTests fixture. Spec: `aetheria-living-world:cut_spec:cut-economy-balance-player-loop.r1`. + +- Mining sortie, DemoTerminus seeds 1 2 3 69 97: the driver holds the ship 40 units off each rock in index order and fires every weapon, with at most 60 s a rock and a 900 s cap. Seed 1 (2x Light Laser, Metallic belt) broke 32 rocks in 155 sim-s, filled the 16-cell hold, got 130 units, and sells for 1088 (about 420 credits a sim-minute). Seeds 2, 3, 69 and 97 (Cell Blaster fits) broke 1 to 6 rocks in 900 s and sell for 8 to 233. Follow-up `demo-starter-fit-cannot-mine`. +- Cost, measured as two interleaved repetitions over the five seeds: a median 0.0625 wall-s per sim-second (eight 900 s runs took 51.5 to 61.1 s each). A launch takes a median 141 ms after a 455 ms first warm-up. +- Determinism: one ItemManager shared across launches changes same-seed results (seed 97 sold for 233 then 63), so each sample needs its own ItemManager. +- Offered-design ladders (dearest over cheapest offered design, authored prices): ExplosivelyPropelled 30x, Laser 3.6x, MicroMissile 3.3x, ParticleProjection 2.3x, Reactor 14.4x, Sensors 30x, Radiator 10x, Thruster 10x, Tool 6x, CargoBay 14x, Hull/Ship 1.3x. Nine offered designs have recipes. At design-bills (nibu/design-bills) those nine are priced from their chains (ExplosivelyPropelled ladder 10.6x, LMG 2756 to Charged Scattergun 29221, top gun 18.8 sorties on the one measured sortie) and StartingCredits is 4000, which buys one upgrade, not the ladder; the 57 offered designs without a recipe keep their rescaled authored prices and ladders. Before design-bills the ExplosivelyPropelled ladder was an authored 30x and StartingCredits (150000) covered every offered design. +- `economy balance` at head: median implied wage 0.00722 per worker-second, 70 links, 23 faults. At design-bills: 74 links, 14 faults (H-wage on ores only); `economy balance --loop` adds the H-ladder band (10-30x, Weapon/* and Gear/* only) and the H-afford band (10-20 sorties to the dearest design of a category), both reported against one measured sortie. + +## Body facts: zone body identity (nibu-imagination, 2026-11-27, at d3e51f22d and e32b04d5d) + +Probe: throwaway tests `ZzZoneKeyProbe` / `ZzZoneKeyOverlapProbe` in a detached worktree at e32b04d5d (the player-loop head), two processes each, shipped catalog. Spec: `aetheria-living-world:cut_spec:cut-zone-body-sites.r1`. + +- Identity now: `ZoneGenerator` writes each body and orbit with a keyless `cache.Upsert`; CultCache mints `Guid.NewGuid().ToString("N")` for a document it holds no handle for (`CultCache.CreateStoredDocument`). A body's `Name` ([CultName]) is the key's first eight characters. Nothing reads a body's `Name`; nothing calls `GetByName` on a body type. CultCache refuses shared index values, not shared names. +- Three readers hash a body's key and so carry its randomness: `FireControl.Extract` (ore weights: StableHash of `field:index:ore`), `Entity.ByIndexThenField` (chunk tie-break on `CultRecordKey.GetHashCode`, which is .NET's process-randomized string hash, so the order differs between processes even for one key) and `DrawAhead.DrawListOf` (which rock meshes a belt draws). `FieldKinds.Ensure` already takes a seed-derived site (`{seed}:belt:{index}`, `:swarm:`, `:lane:`), except on first load of a kindless belt, where `Zone` passes the key. +- Readers that keep keys as opaque identity: `ZonePack.Planets`/`Orbits`, `ChunkId.Field`, `ChunkWearPack.Field`, `Zone.Planets`/`AsteroidBelts`, `ZoneRenderer._beltDraw`, `WellNode`. No CultNet contract and nothing in `native/aetherlight` names a body. +- The run store holds two runs at once: `RunSave.Replace` starts a new run with the saved run's records still stored and, on success, removes the saved keys; `RunSave.Beside` runs a simulation beside it. Every scenario but InfiniteFunLand is `Saved` with a fixed `Seed`, so replaying one while its save exists generates the same zone seed into the same keyspace. A key that is a pure function of the seed would be upserted over the saved run's body, and Replace would then delete the new run's body. +- Baseline at e32b04d5d, DemoTerminus seed 1, cap 300 s, starter fit, two calls in each of two processes: rocks 32/32/32/31, units 131/133/131/129, hold full 160.42/160.42/160.42/148.28 s, sell 1255/3099/1261/1577. Seed 2: sell 16/16 in one process and 11/11 in the other. +- Prototype (a persisted `BodyData.Site` that the generator writes, `SiteOr(key)` in Extract, tie-break and DrawAhead, names from `StableHash(Site)`): seed 1 rocks 32, units 131, hold full 160.42 s and sell 1734 in all four samples. Seed 2 sold 13 in all four. +- Same seed generated twice into one store (the shape of Replace), prototype: 11 bodies, then 22. Keys are disjoint, both generations' sites and names are equal, the first generation's documents are still held at their keys, and the duplicate names are admitted. + +## Body facts: compound stacks (nibu-imagination, 2026-11-27, at 6702b01bf) + +Probe: throwaway test `ZzImagStackProbe` in the detached worktree `F:\aeth-wt\imag-compound-stacks` (CultLib 7225835d, CultMath f1edfa45), with `CompoundCommodity` given `[Key(13)] Quantity { get; set; } = 1`, `SimpleCommodity.Quantity` made a property and `CompoundCommodityData` given `[Key(12)] MaxStack = 10`; reverted after. Spec: `aetheria-living-world:cut_spec:cut-compound-commodity-stacks.r2`. + +- A pre-cut `CompoundCommodity` (union arm 1, 12 slots, lot in slot 11, hand-written bytes) reads with `Lot` 42 and `Quantity` 1: a missing trailing key keeps the property initializer. A new one round-trips `Lot` 7, `Quantity` 5 (22 bytes); its JSON gains `"quantity"`. +- `SimpleCommodity.Quantity` as an auto-property writes the same three-slot array as the field (`92 00 93 A5 probe 00 09`), and all eight `FungibleCommodityTests` pass with it, the pre-ruling 3- and 12-slot reads included. +- The shipped catalog loads with the extra `CompoundCommodityData` slot: 63 compound records, every `MaxStack` 10 (CultCache `CompatibleDrift` defaults the missing slot; precedent `HullData.Kind`, fba7bd1b4, added a slot with no catalog rewrite). Simple records: `MaxStack` 10 on 47, 5 on 3. +- Keys taken on the item side: `ItemInstance` 0-1; `CraftedItemInstance` 2, 9, 10 retired, 11 `Lot`; `EquippableItem` 7, 8, 12; keys 3-6 held fields removed before 2026-09 (Ingredients, Name, Blueprint, SourceEntity). So `CompoundCommodity.Quantity` takes 13. On the design side `CraftedItemData` holds 9 (`Roles`) and `CompoundCommodityData` retired 10 and 11, so its `MaxStack` takes 12. +- No live path mints more than one compound unit per lot today: `ItemManager.CreateInstance(int lot)` returns one unit, station stock draws only equippables (`LoadoutGenerator` 142-150), and the only other compound source is the debug console (`ActionGameManager` 606). Stacking matters once a producer mints a lot of N units; the cut builds the bay rule ahead of it, as ruling compound-commodities-stack-by-lot orders. +- Bay entry points at base: `EquippedCargoBay` has typed public overloads for `SimpleCommodity` and `CraftedItemInstance` (Entity.cs 2477-2740). A `CompoundCommodity` binds statically to the crafted overloads, so any stack rule added beside them can be bypassed by a caller holding a typed compound; the cut makes the typed entries private behind the `ItemInstance` dispatchers. +- Diamond: the only raw recipe with a compound output (Diamond, `station-kind:mining`, no inputs, workforce 12, cycle 1200); its record key is minted (`8776c2fd-...`), and a recipe key is `recipe:`. Gun Barrel (fabrication) takes Gun Forging x1 and Diamond x1. `EconomyChecks` L-source-sink and L-consumer-demand would judge a Cut Diamond that nothing uses. + +## Body facts: commodity stacking (nibu-imagination, 2026-11-27, at 587d19f52) + +Probe: throwaway test `ZzImagCommodProbe` in the detached worktree `F:\aeth-wt\imag-commod-lots` (CultLib 7225835d), shipped catalog through `AetherDb.Open()`, plus source reads. Spec: `aetheria-living-world:cut_spec:cut-simple-commodities-fungible.r1`. + +- Serialization: `CultUnionGuard` (CultLib `GameCult.Caching.MessagePack/CultUnionGuard.cs`) refuses an undeclared union arm on read ("Union Provenance has no arm for key 7"). So deleting the `Extracted` arm (key 2) outright would make every run ledger saved with a mined stack unloadable. An arm with fewer fields than the payload reads it (Attributed, one field, read a three-slot payload), and a concrete item reads an array longer than its keys, skipping the extra slots (CompoundCommodity read 14 slots and took slot 11). So an empty retired arm loads old Extracted lots, and a SimpleCommodity without key 11 loads an old lot-stamped stack. +- CultCache's schema id is a fingerprint of a document's top-level members only (`CultCache.BuildSemanticFingerprint`): `ProvenanceLedger` is `NextLot` plus `Dictionary`, so reshaping a provenance arm or an item instance changes no schema id. +- Shipped catalog: 50 simple and 63 compound commodities. The 19 commodities field kinds yield (Regolith, Troilite, Nickel-Iron, Pentlandite, Chalcopyrite, Sperrylite, Ilmenite, Anorthite, Native Copper, Orthoclase, Uraninite, Brannerite, Monazite, Columbite, Wolframite, Magnetite, Sylvite, Native Gold, Isoferroplatinum) are exactly the simple commodities with a raw recipe at `station-kind:mining`. Water, Methane and Ammonia are raw at `volatiles` and no field yields them. Diamond is a compound commodity with a raw mining recipe and no field yields it. Mining Rights, Travel Permit, Local Newscast and SpaceCast are compound. +- Lot writers on simple stacks at base: only `FireControl.Extract` (via `ItemManager.ExtractedLot`). Copiers: bay split (`EquippedCargoBay.Remove`), restore split (`EntitySerializer.RestoreStack`/`SpillOversize`). Readers: the bay's merge test (two sites), `StationServices.OreStacks`, `EconomyLoop.Ammunition`, `RunSave.Commit` roots, `CargoGain.Lot` (no reader outside tests). `Produced` has no writer; `Brand` and `Reachable` read it. + +## Body facts: the demo region (nibu-imagination, 2026-11-28, at 016219f53) + +Probes: throwaway RunStartTests facts `ZzRegionCensus`, `ZzRegionCost` and `ZzRegionBuildable` in the detached worktree `F:\aeth-wt\imag-region` (CultLib 7225835d, CultMath f1edfa45), Debug, Starfire, shipped catalog; never committed. Ruling `demo-chain-spans-the-region`. + +- The demo galaxy is one region of 64 zones (`DemoTerminus.Cast.ZoneCount`), four factions: Pirates (influence 2), Zhestokost, Lucent Media, Aeronautics Unlimited (3 each). The entrance is 0 jumps, the exit (Zhestokost home and boss zone) 6 to 13 jumps away by seed (seeds 1, 2, 3, 69, 97). +- Fieldable kinds (`StationKinds.FieldableKindsOf`): Pirates mining, processing; AU mining, trade-hub; Lucent mining only; Zhestokost agriculture, depot, fabrication, mining, munitions-works, processing, volatiles. Shipyard, habitat and power kinds have no facilities and no faction fields them. +- Generation already places a chain across the region. Seed 1 totals: Lucent mining 14, AU mining 6, AU trade-hub 7, Pirates mining 4, Pirates processing 5, Zhestokost volatiles 4, agriculture 1, processing 1, depot 1, and no fabrication or munitions-works at all; seed 2 has Zhestokost fabrication 2 and munitions-works 4. Each station's kind is a hash pick (`StationKinds.Choose`, ZoneGenerator 483), so no chain link is guaranteed on any seed. Zhestokost structures appear only deep (DemoPressure grace gives grace zones to the nearest non-antagonist, ZoneGenerator 300-302), so chemistry, munitions and fabrication sit near the boss. +- Belts: four field kinds; province types (Shattered Core, Chondrite Plain, Basalt Shards, Evolved Crust, Primitive Reach) decide the regional ores, so the region's 19 field raws exist in some zone but not near every refinery. No field yields Diamond; Water, Methane and Ammonia come only from the Volatiles Skimmer. +- Buildability (`ZzRegionBuildable`, raws from every belt over the five seeds, facilities of every fieldable kind): every simple commodity but Animal Products, Bacteria, Fungi and Hydrogen closes inside the region, Ammo, Mines and Missiles included. Of the offered designs only Autocannon, Charged Scattergun, Cluster Cannon and Mine Launcher close. Five ballistic weapons (Light Machine Gun, Slug Rifle, Long Slug Rifle, Flak Gun, Point Defense Gun) fail only on a barrel role that needs Diamond. Every hull, facility, reactor, drive, shield, sensor, bay, radiator and energy or missile weapon has no recipe (follow-up `design-bills-remaining`). +- What simulates when: a zone is generated on first entry (`ActionGameManager.PopulateLevel` 852-862) and kept as a live `Zone` afterwards, but only the player's zone steps (`ActionGameManager` 1630-1641, one `SimClock`). A never-visited zone has no stations at all; a visited zone is frozen. Haulers fly inside one zone: `HaulRun.Station(Zone, orbit)` scans one zone, and the haul order names orbits. +- Cost of holding every zone live (`ZzRegionCost`, seeds 1-3, medians): generating a zone 50-89 ms, building its `Zone` 2-4 ms, 3.7-6.1 s for the 63 non-entrance zones, +37-43 MiB managed; one off-screen pass calling `Facility.Execute(60)` on every facility (28-36) 0.003 ms while idle; `RunSave.Capture` of 64 live zones 2-3 ms, `RunSave.Commit` 113-153 ms. No entrance-only baseline was paired, so the save figures are absolutes, not a delta. +- Conjuring sites (ruling `economy-is-never-faked`, `demo-conjures-only-at-the-gate`): `LoadoutGenerator.GenerateShipLoadout` (ZoneGenerator enemies 548-551, wanderers 561-566, DemoPressure raiders 537-541, `ScenarioStage.Generated` for the player and the hauler), `GenerateTurretLoadout` (406), `GenerateStationLoadout` (94-158: hull, hardpoint gear, facilities, docking bay, heater, interior, `StockConsumables`, the 16-pick gear stock), the boss (`Loadouts.BossOf`, ZoneGenerator 505-524), the ruled opening stock (`demo-fabricator-opening-stock`) and the gate's scarce-metal sale (`scarce-metal-fallback`). `Zone.DropLoot` only releases what a dead entity held, so it conjures nothing itself. + ## Stale and missing - `docs/aetheria-living-world-target.md` (the target r2 DocRef, commit d61948f6) lives only on `origin/eureka/aetheria-living-world-target`; master has no copy. The target r2 statement of L-recipe ("inputs are commodities except in gear, hull and consumer-good recipes, which take roles") and L-roles are already contradicted by live code: intermediate commodities take roles through `RecipeData.RoleInputs` (ruling `ores-fill-metal-roles`). The next target revision should restate them. diff --git a/docs/aetheria-living-world-target.md b/docs/aetheria-living-world-target.md new file mode 100644 index 000000000..e9773991c --- /dev/null +++ b/docs/aetheria-living-world-target.md @@ -0,0 +1,394 @@ +# Aetheria living world: target, revision 3 (the economy and its actors) + +Date: 2026-11-27. Status: target r3, written by Imagination (nibu-imagination, session nibu-self-2026-11-17). +It supersedes r2 (this file at `d61948f6`). Body read at `GameCult/Aetheria` origin/master `80c3555c7`. + +Revision 3 maps the seam between the economy and Aetherlight. It also folds in the 2026-11-27 rulings +(all `aetheria-living-world:ruling:` unless named): + +- `living-world-supersedes-njordr` +- `installed-gear-decides-what-a-station-buys` +- `demand-consumed-inputs-processed-by-facilities` +- `mass-populations-live-in-blooms` +- `planetary-habitats-are-populations-too` +- `no-market-absorption` +- `cluster-syndicates-are-aetherlight-actors` +- `ethical-sourcing-is-audited-certification` +- `simple-commodities-fungible` +- `compound-commodities-stack-by-lot` +- `no-grade-on-simple-goods` +- `aetheria-release:ruling:no-ftl-comms` +- `aetheria-release:ruling:aetherlight-narrative-state-owner` + +It closes follow-ups `target-r3-roles-and-home` and `target-r3-commodity-lots`. Ownership change, expansion, the lore +institutions as damping rules and strategic scoring still wait for a later revision. + +## 1. Why + +The economy is the engine the strategic layer, the arenas and the demo run on (r2, section 1: `crafting-is-the-game`, +`demo-live-expansion`). Two operator rulings of 2026-11-27 change its shape. First, the actors are not the economy's. +Aetherlight, already Aetheria's in-process owner of who is alive, who holds whom and who knows what, also owns the +factions, the sub-factions, the unions and syndicates, their offices, their commitments and their knowledge. The +economy owns only physical facts: stock, recipes, installed gear, aggregate populations, gates and prices +(`living-world-supersedes-njordr`). Second, no information crosses a gate except in something that makes the trip +(`no-ftl-comms`). So an actor knows only what records carried to it say, exactly as the player does. + +The physical side changes too: + +- A station buys only what its installed gear uses. Facilities process industrial inputs. Crew and habitation modules + house the people who consume (`installed-gear-decides-what-a-station-buys`, + `demand-consumed-inputs-processed-by-facilities`). +- Most of those people live in Blooms, and many in planetary habitats (`mass-populations-live-in-blooms`, + `planetary-habitats-are-populations-too`). +- A station never absorbs goods it cannot hold (`no-market-absorption`). +- Simple goods are fungible counts with no grade. Compound goods carry their lot (`simple-commodities-fungible`, + `no-grade-on-simple-goods`, `compound-commodities-stack-by-lot`). +- Origin trust is a certification that audit can expose (`ethical-sourcing-is-audited-certification`). + +## 2. Body facts (read at origin/master 80c3555c7) + +- **Live economy code is catalog-only.** `RecipeData` (`aetheria.recipedata`, keys 0-9, 9 = `RoleInputs`), + `OutsideMarketData` and `EconomyChecks` exist (`Assets/Scripts/ServerShared/Recipes.cs`, `EconomyChecks.cs`). + No stock ledger, grade, allocator, obligation, workforce, population or gate flow exists in the running simulation + (`docs/aetheria-living-world-map.md`, opening paragraph). +- **Intermediate commodities already take roles.** `RecipeData.RoleInputs` lets an intermediate take a role (iron takes + `iron-ore`, which hematite or ilmenite fills; ruling `ores-fill-metal-roles`, since `30030af6e`). + `Recipes.RoleInputsOf` is the one reader of a recipe's role slots. r2's L-recipe and L-roles ("inputs are commodities + except in gear, hull and consumer-good recipes") are false of live code. +- **Facilities are being specified.** Cut spec `cut-recipe-facilities.r1` (in force, unreported) adds `FacilityData` (an + inert behaviour on gear), `RecipeData.Facility` (key 10) and `StationKindData.Facilities` (key 3), with check + `L-facility`. It demotes `RecipeData.StationKind` to a checked mirror, which follow-up `recipe-station-kind-derived` + deletes. `StationKindData` today has keys 0-2: Name, Description and StandIns (`StationKinds.cs:13`). +- **Factions are catalog records.** `Faction` (`Corporations.cs:14`) carries Personality, Allegiance (key 12), Relations + (key 16), Doctrine (key 17) and Places (key 21). No runtime faction state exists. +- **Aetherlight is sealed.** `native/aetherlight` (Rust, a fork of Ghostlight `c43eb549`; `PROVENANCE.md`) has no entry + point yet: "the ABI that creates, opens and drives a world arrives in AL4" (`src/lib.rs` crate docs). Its state + partitions (`lib.rs`, `world_state!`) are the following: + - subjects, of kind Person, Institution or Population, each with an optional `ImportKey` (a CultCache schema and + record key); + - entities: places, resources, facts and channels; + - routes, positions and holdings (conserved `Quantity` per subject and resource, through Transfer, Transform, Consume + and Admit); + - dependencies, facts, channels, knowledge (subject and fact; confidence; source Witnessed, Told, Seen or Evidenced); + - authority grants (kind over a subject or a place subtree), offices (`selection`: institution, office and incumbent, + with delegated authority kinds), redress forums; + - commitments (Routine, Obligation or Goal; counterparty, due date, period, checks and statement; key = command id + and index; `DischargeCommitment` removes one); + - pressures, and the affordance catalog and grants. + + After genesis only the play table writes: an Act, an AdmitPatch or an AdvanceTime. Ids are derived and never drawn. + The clock counts whole fictional minutes; one AdvanceTime spans 1 to 525,600 of them (`clock.rs`). +- **Only subjects carry import keys.** `EntityDeclaration` (places, resources) and `FactDeclaration` have none + (`patch.rs:1007,1034`). +- **The game clock.** `SimClock` is the one owner of simulation time: 30 steps a second, `GameStep` = 1/30 s + (`SimClock.cs:11-24`). `SimulationDice` is the one draw (`SimulationDice.cs:9`). + +## 3. The seam (authority map) + +**Owner split.** Each decision and fact has one owner. + +| Decision or fact | Owner | Notes | +|---|---|---| +| Who the actors are: factions, sub-factions, unions, syndicates, councils and the persons in their offices | Aetherlight (subjects) | Seeded at genesis from the catalog (`Faction` records) and from world generation (cluster unions and syndicates, `cluster-syndicates-are-aetherlight-actors`) | +| Who has jurisdiction over an installation, a facility or a cluster | Aetherlight (authority grants over the installation's place subtree) | The controlling faction of a cluster is authored (`cluster-syndicates-are-aetherlight-actors`) | +| Which office decides what, and who sits in it | Aetherlight (`selection`) | | +| What an actor has promised, to whom, and by when | Aetherlight (commitments) | Including obligations posted to haulers and quotas set on facilities | +| What an actor knows | Aetherlight (knowledge) | Rows arrive only from records that reached the actor's cell (section 3, Knowledge) | +| Whether a certification claim is honest | Nobody decides it; an audit exposes it | The audit is an actor's act that reads records (section 3, Certification) | +| Stock: every count of every good outside an entity's hold, and every money balance not carried by an entity | The economy's stock ledger | One writer, the ledger's commit primitive | +| Recipes, commodities, station kinds, facility and habitation designs | The catalog | Authored; never changed during a run | +| What is installed where, and what each facility is set to run | The economy (installation state) | It changes only by executing an order | +| Aggregate populations: size, composition, needs met, migration | The economy's population step | | +| Prices | The economy, derived each tick from committed stock inside the band the operating actor set | An actor sets a band and a target; it never writes a price | +| Gate flows | The economy's gate step | | +| Time | `SimClock`, through the strategic tick | Aetherlight's clock is advanced by exactly each tick's span and decides nothing | + +**What crosses.** The two runtimes share no mutable state. They exchange two documents each strategic tick, and +nothing else crosses: + +- **Facts out** (economy to Aetherlight), `F_k`: the records the economy issued at tick `k`, each with its issuer, + date, subject and confidence, and the cell it landed in. They include the following: + - market reports: settled prices and trades, and stock levels as reported by the installation; + - shortage and shortfall reports: a facility idle for want of input, or a population below a need; + - delivery receipts, and receipts for settled orders; + - population reports: size, needs met, migration; + - extraction and certification tallies by operator, which audits read; + - and every record a hauler carried into the cell by docking. +- **Orders in** (Aetherlight to economy), `O_k`: the typed payloads of the acts Aetherlight admitted at tick `k`. They + include the following: + - a facility setting (which recipe, good/fast/cheap, certify output or not); + - a ration on a population's consumption; + - an install or removal of gear, which is a build order paid from stock; + - a price band and stock target; + - a posted obligation, whose reward is escrowed in the ledger; + - a haul order, which moves stock between installations; + - a strike or withdrawal of labour, which the economy executes as workforce unavailability. + + Each order names the commitment it executes. + +**The allocator becomes an office.** r2's `L-allocator` put a compiled allocator on the faction record, and that +allocator read needs, stock and prices. In r3 the allocator is the compiled brain of an Aetherlight office: a +faction's quartermaster, a syndicate's foreman, a Bloom council's supply office. + +- **What it reads.** Each tick it reads only its incumbent's own Aetherlight snapshot: the knowledge rows that records + brought, its commitments, its pressures and its authority. +- **What it does.** It proposes acts. Aetherlight admits an act only if the office's delegated authority covers the + installation or facility the act names. +- **What an admitted act does.** It records the commitment, and its payload becomes an order in `O_k`. +- **What executes the order.** The economy executes it through the ledger's one writer at tick `k+1`. The economy never + judges authority, and Aetherlight never touches stock. + +The four economy kinds (plan, market, project-contract and contraband) remain four compiled brain families +(`allocator-per-economy-kind`, `A-compiled`). The catalog names which family each office runs. + +Demotions: + +- **The faction record is no longer an economic owner.** It is the authored seed Aetherlight imports at genesis. +- **The allocator is no longer an owner.** It is a brain, and its output is derived into orders only through admitted + acts. +- **`RecipeData.StationKind` is no longer an owner.** The facility decides (cut `cut-recipe-facilities`). +- **Needs tables are no longer a kind.** A crew or habitation module design carries its consumption table. + +**Knowledge arrives by record.** The economy issues every record at an installation. A record lands in that +installation's comms cell, and Aetherlight adds a knowledge row for each subject whose position or channel reaches that +cell. The size of a cell is question `comms-cell`. + +Between cells a record travels only as cargo. It is a one-cell chip, by `intangibles-are-cargo`, in a hold that makes +the trip. It lands when that hold docks in another cell. A seized courier's records belong to whoever seized them. +The region gate's outside market is itself a record: the outside prices as the last courier brought them. + +No actor, brain or player surface reads the ledger, the population step or another subject's state. This is r2's +`L-no-omniscience`, extended to actors. + +**Determinism across two runtimes.** One strategic tick `k`, with a span of whole fictional minutes derived from +`SimClock` steps, runs in this order and no other: + +1. The economy step reads its state `S_{k-1}`, the orders `O_{k-1}` and the tick's structured seed. It writes `S_k` + and `F_k`. +2. Aetherlight admits `F_k` as one patch, advances by the tick's span, then runs each office's brain in subject-id + order. It writes its journal head `J_k` and the orders `O_k`. +3. The composite digest is `H(digest(S_k), state_digest(J_k))`. + +The strategic-tick driver in ServerShared owns this sequence, and neither runtime calls the other. Feedback always +takes one tick, so there is no same-tick fixed point and no ordering race. Both steps are pure (`A-pure`), and both +documents are sorted by id before they cross. The same seed and the same orders give the same `D_k` on Windows and in +the Linux headless arena. On screen and off screen run the same sequence (`L-one-sim`). + +**Cross-runtime names.** The economy names an Aetherlight referent only by `ImportKey`, never by a derived Aetherlight +id. Those referents are actors, installations (as places) and records (as facts). Aetherlight names an economy fact +only by its catalog or ledger key, carried in an order payload. + +Places and facts need import keys, and acts need a typed payload. Both are Aetherlight changes, in follow-up +`aetherlight-economy-referents`. + +**Certification.** The economy carries the "certified" stamp as part of a compound batch's key. It writes the stamp +when the producing facility's setting says to certify, and it never checks whether the claim is true. + +The audit is an actor's act. The auditor reads the producer's extraction tallies and its certified output from +records, and finds a mismatch or none; the finding is a fact Aetherlight holds. A producer that buys open-market raw +goods and certifies anyway is exposed by audit, not refused by the ledger (`ethical-sourcing-is-audited-certification`). +Follow-up `sourcing-certification` reads "minted only when the producer's faction oversaw extraction", which is a +gate the ruling does not order. Its next revision should drop the gate. + +**Forbidden writers.** + +- Aetherlight `holdings` never hold a commodity or a money balance. Its resources are narrative tokens only. +- No brain or Aetherlight path writes a stock count, a price, a grade or an installation's state, except through an + order the economy executes. +- No economy step creates, retires, positions or informs an actor, or writes a commitment, except by issuing a record + in `F_k`. +- No station-level demand table. No absorption. +- No Aetherlight clock advance other than the tick's span. + +**Shared paths.** Player trade at a dock, an NPC hauler's delivery, an off-screen haul flow, production, consumption and +the gate all change counts through the one ledger commit primitive. The player's dock purchase is not an order: it is a +trade the economy settles directly at the posted price, and its record goes out in `F_k` like any other. + +## 4. Invariants + +These are the ends. Each label is what Soul measures against. Labels kept from r2 keep their meaning unless restated. + +- `L-actors`: Aetherlight owns every actor and its offices, jurisdiction, commitments and knowledge. The economy owns + stock, recipes, installed gear, aggregate populations, gates and prices. No actor state is stored in the economy and + no physical count is stored in Aetherlight. +- `L-orders`: An actor's decision reaches the economy only as the payload of an act Aetherlight admitted, and it is + executed by the stock ledger's one writer at the next tick. The economy never judges authority, and a brain never + writes economy state. +- `L-tick-order`: Each strategic tick runs the economy step, then Aetherlight, which ingests the facts out, advances + time and runs the brains. Only the facts-out and orders-in documents cross, sorted by id. The composite digest of + both states is a pure function of the seed and the orders. Feedback takes one tick. +- `L-no-omniscience`: No player surface and no actor or brain reads the stock ledger, the population step, installation + state or another subject's state. Each reads only the price band where docked (the player) and records, each with an + issuer, a date and a confidence. +- `L-records-carried`: A record reaches an actor only by landing in the actor's comms cell. Between cells a record + travels only as cargo in a hold that makes the trip, and it can be delayed, lost or seized. +- `L-installed`: Every good an installation buys is used by gear installed on it. Facilities process industrial inputs + by recipe. Crew and habitation modules house populations that consume by the module's table. No installation-level + demand table exists. +- `L-no-absorb`: A sale moves only what the buyer's bays can hold, and only goods its installed gear uses. The rest stays + in the seller's hold. Nothing a station pays for vanishes. +- `L-populations`: Consumer demand comes from mass populations living in installed crew and habitation modules. Blooms, + stations and planetary habitats are one installation kind with different gear, and most people live in Blooms. A + population's size scales its module tables. +- `L-prices`: Every price is derived by the economy from committed stock and the operating actor's band and target. No + actor, record or UI writes a price. +- `L-recipe`: Every commodity has exactly one authored recipe. It names its inputs (commodity counts), its role inputs + (through `RoleInputs`, or the output's own roles for a role recipe), its cycle, workforce, upkeep, the facility design + that runs it, and its lore hook. No recipe is generated at runtime. +- `L-roles`: A role is filled by any commodity tagged for it. Gear, hull and consumer-good recipes take only roles, and + any recipe may take a role through `RoleInputs`. `Recipes.RoleInputsOf` is the one reader of a recipe's role slots. +- `L-one-stock`: The stock ledger is the one owner of every count of every good outside an entity's hold, and of every + money balance not carried by an entity. Trade, hauling, production, consumption, upkeep, destruction and gate flows + all go through its commits. +- `L-fungible`: Simple stock is a count per (holder, commodity) with no grade, lot or origin. Units of one simple design + always merge. +- `L-graded`: Grade first appears on compound stock. A production step's output grade is its facility's assembly at + its setting, capped by the grades of compound inputs (min with tolerance). Simple inputs cap nothing, and only + production writes a grade. +- `L-lot-at-boundary`: Compound stock is held in batches keyed by holder, design, producing installation and facility, + grade and certification. A batch becomes a `Lot` with a Produced origin when it crosses into an entity. Simple stock + crosses as a count with no lot. +- `L-certified`: A certified stamp is written only by a producing facility whose operator's setting certifies output. + The economy never checks a claim. An audit is an actor's act over records, and a dishonest claim is exposed, not + refused. +- `L-obligations`: All work posted to the world is a commitment of the actor that posted it. Its reward is escrowed in + the ledger by its order, and the job board lists only posted obligations, as records. +- `L-allocator`: Each office that decides economy matters runs one compiled brain of one economy kind, named by the + catalog. A brain reads only its incumbent's snapshot and emits only proposed acts. +- `L-workforce`: A facility's throughput is gated by a workforce of a kind its operator permits. Each workforce kind + lives in its own module design with its own table. Zhestokost facilities never hold biodrones or AGI. +- `L-zone-crew`: A facility's human crew comes only from populations in its own zone. People cross zones only by the + population step's slow migration toward work and goods. Biodrones move as cargo. +- `L-sinks`: Goods leave only by consumption (module tables and recipe inputs), destruction (on screen, or the matchup + model's expected losses), upkeep, and export through the region gate. No stock decays. +- `L-gate-cap`: The region gate trades each commodity at no more than its capped rate per tick, at band prices around + the outside price, through ledger commits. The cap is below regional demand for every good the region can make. +- `L-source-sink`: Every commodity has a source (an extraction recipe, a recipe output, or the gate selling it) and a + sink (a recipe input or upkeep, a role fill, a module table, destruction, or the gate buying it). The catalog check + refuses either one missing. +- `L-consumer-demand`: Every shared component reaches some consumer good, a commodity a crew or habitation module's + table names. The gate does not count. The window is guidance (`consumer-demand-shared-only`); the role half is live + and the module half arrives with module tables. +- `L-productive`: The recipe graph, augmented with each module table per worker and with upkeep, has spectral radius + below 1 at the most input-hungry setting. It is checked on every catalog build, and a failure names the cycle. +- `L-deep`: Depth from extraction is reported per good. Chains are deep where each step is real production + (`chain-depth-is-justified-not-counted`). It is reported and refuses nothing. +- `L-no-stall`: Over the arena's generated seeds, a region left alone with its gate open at the cap and its offices' + brains running keeps every recipe in its kind set producing, and no population pinned at its floor. The strategic + arena runs the check. +- `L-one-sim`: On screen and off screen are one rule set at two levels of detail, sharing the arena's `A-one-sim`, + `A-pure` and `A-no-clock`. Both runtimes run inside it, and every draw is `SimulationDice` keyed by a structured seed. +- `L-lore`: Every commodity carries a lore hook: what a player learns by inspecting or intercepting it. +- `L-one-kind-list`: The station kinds the simulation runs and the kinds hulls are authored for are one catalog list. A + kind lists its facilities, and a kind without its faction's model names a stand-in kind, which is deleted when the + model lands. + +## 5. What is not a consumer, and not in scope + +Not consumers (nothing keeps them working): + +- r2's list: `DemandProfile`, stored commodity categories, `RandomProducts` as station stock, `station-restock`, the + deleted factory designs, the `INDEX.md` factory-design claim, AetheriaEve. +- Market absorption (`no-market-absorption`). +- Njordr, which is parked (`living-world-supersedes-njordr`). +- r2's needs-table kind, which module designs replace. +- The faction-record allocator field r2 planned, which offices replace. +- Aetherlight `holdings` as a store of commodities or money. + +Not in scope: + +- Ownership changing hands, expansion, snowball-damping institutions and strategic scoring. They come in the next + revision, under these owners. +- Aetherlight's ABI (AL4) and its narrative scope, which belong to campaign `aetheria-release`. This campaign consumes + them and owns only follow-up `aetherlight-economy-referents`. +- Lore text for Aethernet and couriers, which belongs to `aetheria-release` cut `cut-lore-no-ftl-comms` (spec `cut-cut-lore-no-ftl-comms.r1`). +- Planetary-habitat placement, which waits on Asura bodies. The installation kind is shaped for it now. +- Population subjects as Aetherlight actors (idea `seam-map.population-subjects`). +- Matchup-model fitting (`aetheria-matchups`), named components and disassembly, alternative recipes, an omniscient + economy panel, runtime model calls, station hull art, and passenger transport. All are as in r2. + +## 6. Identity, lifecycle, authority (Eureka step 0b) + +| Kind | What names it | What happens to it over time | Who decides (owner; forbidden writers) | +|---|---|---|---| +| Actor | An Aetherlight subject (Institution or Person). It carries an `ImportKey`: `aetheria.faction` and the record key for catalog factions; `aetheria.actor` and a seed-derived site label (`{seed}:{cluster}:union:{n}`) for generated unions and syndicates | Created at genesis or by a later patch. It acts, holds offices, and is retired, never deleted | Owner: Aetherlight. Forbidden: Faction or other economy records holding runtime actor state | +| Office | (institution, office name) in Aetherlight `selection`. Its brain family is named by the catalog per office kind | Seeded at genesis. Its incumbent changes by Aetherlight acts | Owner: Aetherlight. The brain is compiled code (`A-compiled`). Forbidden: a brain chosen at runtime | +| Commitment | Aetherlight `CommitmentKey` (command id, index) under its promisor | Admitted by an act, then discharged, or it falls past due and raises pressure. Never edited | Owner: Aetherlight. Forbidden: the economy writing or discharging one | +| Order | The admitted act's event id, plus the payload's index. It is typed: setting, ration, install, band, obligation, haul, labour | Born in `O_k`. Executed once at `k+1`: it commits, or it fails with a receipt record. Never re-executed | Owner: the economy executes it; Aetherlight authorized it. Forbidden: an order with no admitted act | +| Installation | A catalog-independent runtime record keyed by its zone body site (`zone-body-site-identity`) or its station key. In Aetherlight it is a place with `ImportKey` `aetheria.installation` and that key | Generated with its zone, and gains or loses gear by install orders. Destroyed with its body or hull | Owner: the economy. Its jurisdiction is Aetherlight's. Forbidden: two kinds for station, Bloom and habitat | +| Installed gear | (installation, slot ordinal). It holds a gear design: a facility, a crew or habitation module, or other gear | Installed or removed only by an order. A facility runs its setting; a module houses a population | Owner: the economy, through orders. Forbidden: a generator or UI installing gear outside the build order path (world generation seeds it once) | +| Facility setting | (installation, slot) | Changed only by a setting order. Read by the production step | Owner: the operator actor, through orders. Forbidden: any other writer | +| Population | (installation, module slot, workforce or population kind). It holds a size and its needs met | Grows while basic needs are met. It shrinks slowly to a floor under shortfall, and migrates slowly between zones | Owner: the population step. Forbidden: any other writer of size or zone | +| Simple stockpile | (holder, commodity) and a count | Changed only by ledger commits | Owner: the stock ledger. Forbidden: grade, lot or origin on it | +| Compound batch | (holder, design, producing installation, facility, grade, certified) and a count | Created by production. It merges with an equal key, and splits by moves | Owner: the stock ledger, and production for grade and stamp | +| Lot | Minted at the boundary from (batch key, crossing event) | It stacks in a hold by (design, lot), and carries a Produced origin | Owner: `ItemManager` at the boundary. Forbidden: minting for stock no entity holds | +| Account | (holder actor `ImportKey`, cell); see question `money-across-cells` | Changed only by ledger commits: settlements, escrow, wages | Owner: the stock ledger. Forbidden: Aetherlight holdings, and any UI balance edit | +| Record | (issuer installation, tick, ordinal). It holds a subject, a payload, a confidence and the cell it landed in. In Aetherlight it is a fact with `ImportKey` `aetheria.record` and the record id | Issued once and never edited. It travels as cargo between cells | Owner: the economy issues it; Aetherlight owns who knows it. Forbidden: a record with no issuer, and any reader of the payload without a knowledge row | +| Knowledge row | Aetherlight (subject, fact) | Added when a record lands in the subject's cell. Forgetting removes it | Owner: Aetherlight. Forbidden: any economy-side "who knows" store | +| Comms cell | A zone or a region; question `comms-cell` | Fixed by the galaxy | Owner: galaxy generation. Forbidden: a record crossing a cell boundary other than as cargo | +| Certification | A stamp in a compound batch key and on its lots. An audit finding is an Aetherlight fact | The stamp is written by production under a certify setting. A finding is written by an auditor's act | Owner: the operator decides the claim; the auditor decides the finding. Forbidden: the ledger refusing a claim | +| Tick exchange | (`F_k`, `O_k`) for tick `k` | Built once per tick, sorted by id. Consumed once | Owner: the strategic-tick driver. Forbidden: any other channel between the runtimes | +| Commodity, Recipe, Station kind, Facility design, Module design, Workforce kind, Outside market | Catalog keys, as in r2. A module design carries its consumption table per occupant | Authored, and revised by commit | Owner: the catalog, written by economy batches. Forbidden: runtime edits | +| Price band | (installation, commodity) | The band and target come from a band order; the price is derived each tick | Owner: the economy for the price, the operator actor for the band. Forbidden: a price from catalog price alone once stock exists | + +## 7. Cut sequence + +Landed: catalog subtraction, the station-kind datum, recipe schema and checks, recipe role inputs, the ore batches, +derived prices, commodity shapes, and simple fungibility. In force and unreported: `cut-compound-commodity-stacks`, +`cut-design-bills-of-materials` and `cut-recipe-facilities`. The rest are follow-ups in the mind, and each names what +it waits on. + +1. Facility production (follow-up `facility-production`, named by `cut-recipe-facilities`). It waits on that cut and + on the stock ledger. +2. The stock ledger: simple stockpiles, compound batches and lots at the boundary. It is r2's cut 4, re-scoped by + `L-fungible`, `L-lot-at-boundary` and `L-no-absorb`. +3. Installations and habitation (follow-up `installations-and-habitation`): one installation kind; crew and habitation + module designs with tables; populations in modules; the module half of `L-consumer-demand`. It replaces r2's cuts 6 + and 7 as kinds. It waits on 2. +4. Station outflow, mapped now by another Imagination against r2. It re-anchors on r3 (section 8). +5. Aetherlight economy referents (follow-up `aetherlight-economy-referents`): import keys on places and facts, and a + typed order payload on acts. It waits on AL4 (`aetheria-release`). +6. The tick exchange (follow-up `seam-tick-exchange`): the strategic-tick driver, `F_k` and `O_k`, records landing in + cells, the composite digest, and the office brains replacing r2's allocators. It waits on 2, 3 and 5, and on + question `comms-cell`. +7. Accounts: money in the ledger, escrow and wages. It waits on question `money-across-cells` and on 2. +8. Off-screen tick, legibility and stall checks: r2's cuts 9 to 11, unchanged in purpose, run inside 6's sequence. + +## 8. What changes for the station-outflow mapping + +The station-outflow pass was mapped against r2 and `no-market-absorption`. Under r3: + +- **Consumption at a station is not a station rate.** It is the consumption of the populations housed in its installed + crew modules, by each module's table (`L-installed`, `L-populations`). A "local consumption at its demand rate" with + no module behind it is forbidden. +- **Industrial drain is facility production.** Ore drains only through an installed facility running a recipe. A + station with no such facility does not buy ore (`L-no-absorb`). Where the outflow work needs this, it waits on + facility production, or names that follow-up as its first step. +- **Onward trade is an actor's haul order, not an economy flow.** Until offices run (follow-up `seam-tick-exchange`), + an outflow cut may feed the ledger orders from a fixed order document (a test fixture or a generator-seeded standing + order). That document has the r3 order shape, and it is deleted when offices issue orders. It must never be a brain + or a second issuer that lives on. +- **Starting stock that leaves room** is generation, and it is still the economy's. It is written through ledger + commits. +- **Prices respond through `L-prices`.** A price is derived from stock inside a band. Until band orders exist, the + band is the catalog default. + +## 9. Prior art + +These notes come from the designers' published systems, recalled for this pass rather than fetched in it (the mind's +`known` index did not answer during this pass). An Eyes pass should pin sources before the questions are ruled. + +- **Victoria 3** separates pops from interest groups. Pops are economic aggregates in buildings: employment, wages, + standard of living and needs met. Interest groups are the political actors, and their clout is derived from the pops + that back them. Buildings run production methods that their owners choose. The lesson is the seam this revision + takes: aggregates on the physical side, actors whose pressure reads them. The known failure is opaque pop-to-IG + attribution, which players could not read; records with issuers answer it here. +- **X4: Foundations** builds stations from modules. Production modules consume wares. Habitat modules house a workforce + that consumes food and medical supplies and speeds production. A station manager (an actor) sets buy and sell offers + and budgets inside the station's physical limits. Its known failures are seed-dependent shortages and stations that + stop buying when storage fills. `L-no-absorb` and `L-no-stall` answer them. +- **Dwarf Fortress** keeps civilisations and their sub-entities (guilds, religions, governments) as historical entities + that hold positions with holders over sites. World generation seeds them, and their knowledge spreads with travellers. + That is the shape of offices over installations and of records carried by traffic. +- **Bills of exchange**: medieval merchant banking moved value between cities by carried instruments drawn on + correspondents, because no message travelled faster than a courier. It is prior art for `money-across-cells`. diff --git a/docs/aetheria-release-map.md b/docs/aetheria-release-map.md index 72e96f22e..b02dbd624 100644 --- a/docs/aetheria-release-map.md +++ b/docs/aetheria-release-map.md @@ -502,10 +502,8 @@ record. | follow-up | `hull-damage-wear` | demo | Damage visible on the hull (line 6). | | follow-up | `mod-ship-single-existence-gate` | demo | A skipped package throws on spawn; demo hulls are packages. | | follow-up | `ambiguous-hardpoint-origin` | demo | Save correctness for package hulls. | -| follow-up | `remove-sbsar-files` | demo | Clean break from Substance before a public build. | | follow-up | `delaunay-exact-predicates` | demo | Galaxy links; a silently unlinked zone could strand a demo run. | | follow-up | `failed-start-scene-halts` | demo | The New Game failure path the demo's missing-cast refusal uses. | -| follow-up | `stale-docs-after-scenarios-menu` | demo | Docs that describe the old New Game path. | | follow-up | `scratch-carry-drafts` | demo | The ship `.cc` draft bears on `demo-ship-cc-timing`. | | follow-up | `faction-lore-notes-r3` | full game | Vault setting notes; no demo cut reads them. | | follow-up | `mining-impacts-through-contract` | full game | Mining Cut 4 is parked. | @@ -867,7 +865,7 @@ deletes the flag with no behaviour change except where named. to its owner: - influence halving -> the cast's own `InfluenceScale` (the demo's cast sets .5, so its galaxy is unchanged), carried by the Galaxy and the save (key 15) because later zones read it (PR2); -- the entrance station -> `Scenario.EntranceStation`, a declaration beside `Ambient`, default true, +- the entrance station -> `Scenario.EntranceStations`, a declaration beside `Ambient`, a list of `EntranceStationOrder` (default one), false for MainGalaxy, so every scenario's arena is unchanged; RunStart.GenerateArena applies it; - availability -> the general rule of gear-without-presence; - the save flag -> deleted (key 11 retired; ruling `no-save-compatibility-before-players`). @@ -901,7 +899,7 @@ name. Per ruling `no-save-compatibility-before-players` nothing reads key 11. | EmojiOne sample | none | Deleted by `emoji-font` | none | | Galaxy cast (replaces `TutorialGenerationSettings`) | A scenario's code constant (`DemoTerminus.Cast`) | Compiled with the game; no authored settings copy | The scenario | | `Galaxy.InfluenceScale` | Its galaxy | Set by the constructor (the cast's value, 1 for main), saved as `SavedGame` key 15 | The cast | -| `Scenario.EntranceStation` | Its scenario | Compiled | The scenario; `RunStart` applies it | +| `Scenario.EntranceStations` | Its scenario | Compiled | The scenario; `RunStart` applies it | | `SavedGame` key 11 (`IsTutorial`) | Retired | Not read, not written | none | | `Galaxy.IsPrelude`, `TutorialGalaxy`, `TutorialGenerationSettings`, `GameSettings.TutorialGenerationSettings` | Deleted by `retire-prelude` | | none | @@ -2188,7 +2186,7 @@ wear comes from baked maps. Grunge is baked into `ship.maps.png` A. - r2's region tint (`_PaintStrength`, `RegionLuminance`, a tiling `_WearNoise`) and its `Livery` of three colours are never built. - Revision 1's vertex mask is gone. - - The 41 `.sbsar` files go with follow-up `remove-sbsar-files`. + - The 41 `.sbsar` files are removed (follow-up `remove-sbsar-files`). #### Parity @@ -8969,7 +8967,7 @@ in a detached worktree; anchors are file:line at b6262467. not a scripting surface), ship-roles-are-tags (unrelated: add-on object roles). Withdrawn ships-hull-material r2 and ships-hull-livery r1 are not depended on; r3 did not either. - Shape change from r3: Write(cache, hull, visual) is NOT widened (11 callers). A separate - WriteProduct/DeleteProduct pair is the one product writer. Load/Read become a 3-tuple + WriteProduct is the one product writer at creation (ship-authoring push adds, changes and removes). Load/Read become a 3-tuple (18 deconstruction sites in 6 files, one of them the Unity-only Editor file). ## Probes diff --git a/docs/build-delivery-target.md b/docs/build-delivery-target.md index 95c7437f9..4306138ae 100644 --- a/docs/build-delivery-target.md +++ b/docs/build-delivery-target.md @@ -53,9 +53,13 @@ artifact: Idunn deploys services to Yggdrasil, not files. - **Git LFS and repo size** are part of the problem: the checkout alone is 1.7 GB. A build path that needs a fresh clone per release has to say so. +## Live state (2026-11-25) + +- The release home is the forge release (rulings `auto-release-pipeline`, `starfire-build-trigger`, `version-bump-source`): `.changeset/` files and `VERSION` decide the version and CHANGELOG, `.forgejo/workflows/release.yml` builds the Windows 64-bit and Linux 64-bit players on Starfire and publishes them. `docs/release-checklist.md` is the procedure. +- The site download page, the version feed and the Yggdrasil serving path above are still targets. + ## Not in scope - Auto-updating clients, launchers, patching, or delta updates. -- Platforms other than Windows 64-bit, until one is asked for. - Accounts, entitlements, or telemetry. The download is public and anonymous. - Selling anything. diff --git a/docs/cultcache-migration-cut.md b/docs/cultcache-migration-cut.md index 16e885490..f27bde97d 100644 --- a/docs/cultcache-migration-cut.md +++ b/docs/cultcache-migration-cut.md @@ -95,7 +95,7 @@ recorded, none blocking: `WeaponData.AmmoType` refs. - One cache holds all three stores for the process. - `RunSave` commits a save atomically with stable zone keys and clears the run - on New Game or death. + on death or victory (`RunSave.Replace` drops the old run once a new one has staged). - `SavedRun`, the msgpack settings and layout I/O, `.loadout`, `SaveState`, `SaveZone` and the importer are deleted. - **Loadouts are authored ship presets in the catalog.** This was reworked @@ -138,9 +138,6 @@ The first Soul pass found untested all-or-nothing, availability and price rules, weapon-group corruption, dictionary-ordered product choice, and a premature "done". All are fixed. -Recorded, not fixed: New Game clears the previous run before generation, as the -spec says, so a generation fault loses that run. - `GameData/PlayerSettings.msgpack` entered history through `5c5c3d5e`. It holds defaults and the username, and about 65 earlier versions are already in LFS history, so history is left alone. @@ -151,7 +148,7 @@ death clearing the run across relaunch, stance toggle, `FieldShieldTest`. It fou migration defect: CultMath types are not Unity-serializable, so Unity-serialized CultMath fields load as zero. Mouse sensitivity (lost look control) moved to `PlayerSettings` in `00ebe46a`; the rest, including the black rarity colours, is `docs/settings-globals-cut.md`. -Scene materials are broken by the dead Substance plugin, not by this migration. +The Substance maps are removed and the materials repointed to Assets/Materials/PBR. History, before the smoke: - nothing else from agents. The preset rework's Soul findings were fixed in @@ -651,7 +648,9 @@ After Cut 10, every runtime write is a single-store `Commit` on one cache that holds catalog, run and player stores from first access: - `RunSave.Commit` saves the run at wormhole arrival and quit, with stable `SavedZone` keys. -- `RunSave.Clear` deletes every run record at New Game and at death. +- `RunSave.Clear` deletes every run record at death and victory (`ActionGameManager.EndRun`). +- `RunSave.Replace` swaps the saved run for a new one only after the new run has + staged; a start that fails leaves the saved run in place. - The settings getter creates `PlayerSettings` on first launch, and `SavePlayerSettings` commits it. - `Loadouts.Save` writes loadouts to the player store, and @@ -849,7 +848,7 @@ reads a global back (Q4). | Global | Store | Read by | Existence owned by | Missing at main menu | Missing at resume | Missing at new game | |---|---|---|---|---|---|---| | `PlayerSettings` | Player | `MainMenu` (name, tutorial flag), `ActionGameManager` (credits) | boot: `ActionGameManager.Awake` after `AetheriaStores.Open`, when `GetGlobal()` is null, upserts one and flushes (Cut 10) | cannot happen after boot | same | same | -| `SavedGame` | Run | `MainMenu` (resume), `Galaxy(CultCache, SavedGame, ...)` | new game: `ActionGameManager.BeginRun()` creates the run store and writes it; `Die()` deletes the run store (Cut 10) | no run file: Resume hidden; run file without `SavedGame`: refuse to resume, log the key, New Game only | as main menu | new game deletes any run store first | +| `SavedGame` | Run | `MainMenu` (resume), `Galaxy(CultCache, SavedGame, ...)` | new run: `RunSave.Replace` writes the new run's records and removes the old run's once the scenario has staged; `EndRun` calls `RunSave.Clear` at death and victory | no run file: Continue disabled; run file without `SavedGame`: Continue disabled, log the key | as main menu | a new run keeps the saved run until it has staged | | catalog globals | Catalog | none exist | authored data; catalog is read-only | `AetheriaStores.Open` throws naming every `[CultGlobal]` type routed to the catalog with no record | same | same | **CultLib's role.** `[CultGlobal]` means exactly: at most one record of the @@ -1772,8 +1771,8 @@ Probes behind 8a (scratch copies; nothing committed): Math audit: - **Not used:** `float4x4`, `transpose`, `determinant`, `_11` names. The - `determinant` hits (`AetheriaMath.cs:98-112`, `NIH\MIConvexHull`) are locals - and comments; the `half` hits are locals. `float2x2`/`float3x3`, `int3`/`int4`, + `determinant` hits were locals and comments (in `AetheriaMath.cs` and the + vendored `NIH\MIConvexHull`, both since deleted); the `half` hits are locals. `float2x2`/`float3x3`, `int3`/`int4`, `double2`/`double3`, `quaternion.LookRotation`, `Random` and `snoise` all compile against CultMath. - **Accepted by Cut 6b:** `hash`, `normalize`, `Random`, `snoise` and NaN @@ -2596,28 +2595,31 @@ AetherDb and test edits made by Cut 9 (landed `70fbaca1`, recorded `e3af23fa`). - `SavedGame` global and `savedzone-{i}` records in `run.cc`. - `PlayerSettings` global in `player.cc`. - Orbit and body records in `run.cc`, written by zone generation and landed by the next save. - - **Run begins:** New Game calls `RunSave.Clear(CultCache)` as its first - statement (the `MainMenu.cs:110` handler), before the `Task.Run` at `:127` - or `:154`. - - Galaxy generation writes nothing. - - Zone generation (`PopulateLevel` `:615`, then `ZoneGenerator.cs:99, 108, - 200-201, 239, 253`) upserts orbits and bodies into the attached run store. - They stay staged until the next `RunSave.Commit`. + - **Run begins:** a scenario launch (`MainMenu.Launch`) generates the galaxy on a + background task and writes nothing to the run store. `StartGame` then calls + `StartScenario`, which runs arena generation, `PopulateLevel` and staging + inside `RunSave.Replace(CultCache, ...)`. The saved run's records are removed + only when staging succeeds; on failure the records the start wrote are removed + and the saved run stays. + - Zone generation (`PopulateLevel`, then `ZoneGenerator`) upserts orbits and + bodies into the attached run store. They stay staged until the next + `RunSave.Commit`, or are removed by `Replace` on a failed start. - **Run saves:** `ActionGameManager.SaveRun()`: - - It is `if (CurrentGalaxy != null) { var (game, zones) = RunSave.Capture(CultCache, CurrentGalaxy, Zone, DockedEntity ?? CurrentEntity, IsTutorial, _actionBarSlots.Select(s => s.Save()).ToArray()); RunSave.Commit(CultCache, game, zones); }`. + - It captures the live run (`RunSave.Capture`, which writes `SavedGame.IsTutorial` from `galaxy.IsPrelude`) and commits it with `RunSave.Commit` (`ActionGameManager.SaveRun`, `:284`). - Callers: wormhole arrival (`:605`) and `OnApplicationQuit() { SaveRun(); SavePlayerSettings(); }`. - - **Run ends:** `Die` replaces `SavePlayerSettings()` at `:1059` with - `RunSave.Clear(CultCache); SavePlayerSettings();`. - - `CurrentGalaxy` is already null (`:1058`), so a quit afterwards does not save a run. + - **Run ends:** `EndRun` (death and victory) nulls `CurrentGalaxy`, then calls + `RunSave.Clear(CultCache); SavePlayerSettings();` (`ActionGameManager.cs:1224-1232`). + - `CurrentGalaxy` is already null, so a quit afterwards does not save a run. - **Run exists:** derived only as `CultCache.GetGlobal() != null`. - `MainMenu.ShowMain` enables Continue from it. Continue sets - `IsTutorial = saved.IsTutorial` and - `CurrentGalaxy = new Galaxy(CultCache, saved, Debug.Log)`. - - `StartGame` (`:695-741`) reads it once at the top: `null` takes the - new-run branch; otherwise it resumes from `CurrentZone`, - `CurrentZoneEntity` and `ActionBarBindings` (`:722, 723, 737`). + `CurrentGalaxy = new Galaxy(CultCache, saved, Debug.Log)`, whose `IsPrelude` + comes from `saved.IsTutorial`. + - `StartGame` (`ActionGameManager.cs:820`) branches on `PendingScenario`: set + means a new run (`StartScenario`); otherwise it resumes from `CurrentZone`, + `CurrentZoneEntity` and `ActionBarBindings` of the saved run. - A run store that holds records but no `SavedGame` logs - `run store has no SavedGame; Continue disabled`. New Game clears it. + `run store has no SavedGame; Continue disabled`. The next scenario launch + replaces those records once it has staged. - **Player settings:** - The `ActionGameManager.PlayerSettings` getter returns `CultCache.GetGlobal()`. - When that is absent (first launch), the getter commits @@ -2651,7 +2653,7 @@ AetherDb and test edits made by Cut 9 (landed `70fbaca1`, recorded `e3af23fa`). - The cache never creates either. `AetheriaStores.Open` keeps its missing-global check catalog-only (`AetheriaStores.cs:24-29`). - **Derived state:** - "Run exists" is derived from the `SavedGame` global. - - `IsTutorial` is set from it on Continue and written back by `Capture`. + - `Galaxy.IsPrelude` is set from `SavedGame.IsTutorial` on Continue; `Capture` writes it back from `galaxy.IsPrelude`. No static copy exists. - `PlayerSettings.SavedRun` is deleted, not demoted. - **Forbidden writers:** - `File.*` I/O for game state anywhere in `Assets\Scripts`. @@ -2660,10 +2662,10 @@ AetherDb and test edits made by Cut 9 (landed `70fbaca1`, recorded `e3af23fa`). - A second `AetheriaStores.Open` in `Assets\Scripts`. - Any upsert of `SavedGame` or `SavedZone` outside `RunSave.Commit`. - **Shared paths:** - - Normal and tutorial New Game both call `Clear`. + - Every scenario launch goes through `RunSave.Replace`. - Continue and a new run's `StartGame` read the same global. - Wormhole and quit call `SaveRun`. - - Death calls `Clear`. + - Death and victory call `Clear` through `EndRun`. - **Deletion line:** `SavedRun`, `SaveState`, the msgpack settings and layout I/O, `SaveLoadout`, `SaveZone` and the `SavedGame` constructor go before `RunSave` lands. diff --git a/docs/element-ids.md b/docs/element-ids.md index b4ae9584a..32ccdafc8 100644 --- a/docs/element-ids.md +++ b/docs/element-ids.md @@ -26,7 +26,7 @@ that some intermediate pins read a single-file v3 store silently and drop the id writers, keep a pre-upgrade copy of any real store (`GameData/Aetheria.cc` and the mod packages are tracked in git; player saves and run stores are not), and do not roll the pin back after a store has been written under the new one. -The shipped mod packages (`GameData/Mods/aetheria.wren/ship.cc`, `aetheria.nakovalnya/ship.cc`) held only default +The shipped mod package (`GameData/Mods/aetheria.nakovalnya/ship.cc`) and the test fixture package (`tests/fixtures/mods/aetheria.wren/ship.cc`) held only default placeholders (`0` and `[]`) in the retired `HullData` slots 21 and 22, which the new CultLib refuses to write over (`CultSchemaConflictException`). They were regenerated with `AetherDb ship-authoring regenerate apply`, which loads the records, writes them into a fresh file under the current schema, requires them to read back identical and replaces the file. Both diff --git a/docs/headless-playground-cut.md b/docs/headless-playground-cut.md index bea30aa46..d6ca6104a 100644 --- a/docs/headless-playground-cut.md +++ b/docs/headless-playground-cut.md @@ -10,6 +10,13 @@ probe was built with `--artifacts-path` in scratch, so this tree got no `bin`/`o writes. CultLib was a temporary detached worktree at `a0813c6`, since removed. The probe source is not kept; §2.8 records what it did. +Since this map, the new-run path moved: `MainMenu.Launch` starts a `Scenario` and +`ActionGameManager.StartScenario` replaces the saved run through `RunSave.Replace` +after `RunStart` stages it (`docs/scenarios-cut.md` R.9); the `IsTutorial` static is +gone (`Galaxy.IsPrelude` is the one owner) and `ItemManager` takes its seed in its +constructor. Passages below that name the old `MainMenu` new-game anchors or those +statics are rewritten to that path; the `Run` owner itself is still unbuilt. + ## 0. Target Operator, 2026-09-17: player inputs "map directly to the same entity inputs the AI @@ -107,11 +114,11 @@ All of this is Unity code: | Concern | Anchor | Unity dependencies | |---|---|---| | Store composition | `ActionGameManager.cs:43-63` (static, `Application.dataPath`) | path only | -| Handoff across scene load | statics `CurrentGalaxy`, `IsTutorial` (`:96-97`), written by `MainMenu.cs:104-105,126,138,152,166`, read by `SectorMap.cs:114-310` | `SceneManager.LoadScene` (`MainMenu.cs:106,139,167`) | -| New game: clear | `MainMenu.cs:112` | none | -| New game: galaxy | `MainMenu.cs:125,148` (`UnityEngine.Random.value` background noise), `:127-141,153-169` (`Task.Run`, then `Observable.NextFrame`) | Random, UniRx main-thread scheduler | -| ItemManager | `ActionGameManager.cs:264`; RNG clock-seeded at `ItemManager.cs:20` | `Debug.Log` | -| Start / Continue | `StartGame` `:725-770`: spawn player ship `:733-744`; Continue resolves the docked child `:751-762`; action bar restore `:764-767` | renderer binding, `SectorMap` reveal | +| Handoff across scene load | statics `CurrentGalaxy` and `PendingScenario` (`ActionGameManager.cs:108,113`), written by `MainMenu.Launch` and Continue, read by `SectorMap` | `SceneManager.LoadScene` (`MainMenu.EnterGame`, `MainMenu.cs:287`) | +| New game: replace | `ActionGameManager.StartScenario` (`:855-876`): `RunSave.Replace` drops the saved run only after the scenario stages; `MainMenu` clears nothing | none | +| New game: galaxy | `MainMenu.Launch` builds a `GalaxyStage` and runs `Task.Run(() => RunStart.Generate(scenario, stage))`, then `Observable.NextFrame`; background noise and galaxy draw from `GalaxyStage.Seed`, not `UnityEngine.Random` | UniRx main-thread scheduler | +| ItemManager | `ActionGameManager.cs:309`; seed is a constructor argument, `RunStart.ItemSeed(galaxy, step)` (`RunStart.cs:99`), reseeded by `RunStart.SeedItems` | `Debug.Log` | +| Start / Continue | `StartGame` (`:820`): `PendingScenario` set runs `StartScenario` (new run, player staged by `RunStart.Stage`); otherwise Continue resolves the saved zone and docked child and restores the action bar | renderer binding, `SectorMap` reveal | | Zone entry | `PopulateLevel` `:639-675`: generate/unpack `:643-654`; move pilot `:659-666` | `ZoneRenderer.LoadZone`, `Debug.Log` | | Wormhole placement (a game rule) | `ZoneRenderer.cs:222-231` (`dir * Pack.Radius * GameSettings.WormholeDistanceRatio`) | lives in a MonoBehaviour | | Warp | detect `ActionGameManager.cs:312-316`; `EnterWormhole` `:615-637`, which saves on arrival (`:635`) | `ZoneRenderer.WormholeInstances` as the wormhole list | @@ -120,10 +127,11 @@ All of this is Unity code: | Save | `SaveRun` `:241-249`, called at quit `:236` and warp `:635` | action-bar slots (`:246`) | | Death | `BindToEntity` subscribes `Death` -> `Die` (`:1053`); `Die` `:1080-1115` clears the run (`:1088`) | `Time.time`, `Observable.EveryUpdate` post-fx | | Tick | `Update` `:1151-1220`: input `:1189-1216`, then `Zone.Update(Time.deltaTime)` `:1218` | `Time.deltaTime`, pause flag | -| Dead code | `IntroCutscene` `:772-799`; its only call is commented out (`:760`) | coroutine, `Time.time` | ### 2.2 Already headless +- Past probe: the measurements below were taken at an earlier commit and their line anchors + are not maintained; re-run the probe before relying on a number or an anchor. - `Aetheria.Shared/Aetheria.Shared.csproj` compiles `Assets/Scripts/ServerShared/**` plus UniRx (`UniRxLibrary`) and Ink with no Unity defines. It is the Unity-independence check. @@ -134,23 +142,23 @@ All of this is Unity code: - a player `LonginusX` spawned through `LoadoutGenerator`; - thrust by hand-set `MovementDirection` reached 142 m/s in 5 s; - a `Minion` patrol moved the player ship 642 units in 10 s; - - `TryDock` and `TryUndock` succeeded (`Entity.cs:721-755`); - - `Ship.EnterWormhole` followed by stepping fired `OnEnteredWormhole` (`Ship.cs:82-90,372`); - - `Death` fired on hull damage (`Entity.cs:277-280`); + - `TryDock` and `TryUndock` succeeded; + - `Ship.EnterWormhole` followed by stepping fired `OnEnteredWormhole`; + - `Death` fired on hull damage; - `RunSave.Capture` and `RunSave.Commit` wrote a 489 KB `run.cc`. - Settings: `GameSettings` is a ScriptableObject (`GameSettings.cs:11`) holding ServerShared classes. - `tools/AetherDb/AuthoredSettings.cs` reads them from the asset YAML. The probe placed every field (0 unplaced). - Two lifecycle inputs are Unity-only `GameSettings` fields: `StartingHullName` - (`GameSettings.cs:17`, authored `LonginusX`) and `WormholeDistanceRatio` (`:23`, + (`GameSettings.cs:13`, authored `Longinus`) and `WormholeDistanceRatio` (`:16`, authored 0.75). - Randomness: - - `ItemManager.Random` is clock-seeded (`ItemManager.cs:20`). - - `Galaxy` is clock-seeded only when `seed == 0` (`Galaxy.cs:108,158`). - - `Zone` seeds from the zone name (`Zone.cs:54`). - - `Zone.Update` runs belt updates on `Task.Run` (`Zone.cs:144`). It is still - deterministic (probe: identical traces). + - `ItemManager.Random` is seeded by the constructor argument (`ItemManager.cs:35`); a new run's seed is `RunStart.ItemSeed(galaxy, step)`, from `Galaxy.Seed`. + - `Galaxy` takes its seed from the run (`Galaxy.cs:119`); a zero seed throws. + - `Zone` seeds from the zone name: `CombatSeed` (`Zone.cs:162`), with `DropSeed` mixing in the run's seed (`:163`). + - Probe: `Zone.Update` was deterministic (identical traces) when belt updates ran on `Task.Run`; + no `Task.Run` remains in `Zone.cs`. ### 2.3 Agents @@ -243,7 +251,7 @@ Continue and death. There is one instance per run. It holds no Unity type. - `GameplaySettings`, `ZoneGenerationSettings`, `PlanetSettings`; - a `uint seed` for `ItemManager`; - `Action log`; - - for a new run, a caller-built `Galaxy` and `isTutorial`; + - for a new run, a caller-built `Galaxy` (`Galaxy.IsPrelude` says whether it is the prelude) and the staged start (`RunStart.Stage`); - `dt` per step; - commands from either lowering; - `SavedActionBarBinding[]` at save, owned by the Unity action bar (the playground @@ -305,10 +313,8 @@ Continue and death. There is one instance per run. It holds no Unity type. - `ActionGameManager`: bodies of `SaveRun`, `EnterWormhole`, `PopulateLevel`'s simulation half, `StartGame`, `Dock`, `DoDock`'s state half, `Undock`'s checks, `TowShip`, `Die`'s clear, and `IntroCutscene` (entirely); - - statics `CurrentGalaxy` and `IsTutorial`; - - `MainMenu.cs:104-105,112`; - - `ZoneRenderer.cs:222-231`'s wormhole construction; - - `ItemManager.cs:20`'s clock seed. + - statics `CurrentGalaxy` and `PendingScenario`; + - `ZoneRenderer.cs:222-231`'s wormhole construction. All of these go in the same cut that adds `Run`. None survives as a fallback. @@ -318,12 +324,12 @@ Unity dependencies, each injected or cut: |---|---|---| | `Time.deltaTime` | `:1218` | injected: `Run.Step(float dt)` | | `Time.time` | `IntroCutscene`, `Die` post-fx | cutscene deleted; post-fx stays in Unity, on `Died` | -| `UnityEngine.Random` | `MainMenu.cs:125,148` (background noise), `EntityInstance.cs:413-428` (loot) | noise stays in the menu as a galaxy-generation input; loot roll moves to `Zone` on `ItemManager.Random` (Cut 2); effect spread jitter (`ProjectileManager.cs:20-26`) stays visual | -| Clock RNG | `ItemManager.cs:20` | cut; the seed is a constructor argument, and Unity passes a clock-derived one | +| `UnityEngine.Random` | `EntityInstance.cs:413-428` (loot) | galaxy noise already draws from `GalaxyStage.Seed`; loot roll moves to `Zone` on `ItemManager.Random` (Cut 2); effect spread jitter (`ProjectileManager.cs:20-26`) stays visual | +| Clock RNG | `Scenario.Seed` of 0 (`GalaxyStage.SeedFrom`) | the clock seeds only the galaxy seed; every item stream derives from it through `RunStart.ItemSeed` | | Coroutines | `IntroCutscene` | deleted (dead) | | UniRx | `Observable.NextFrame` in the menu, `EveryUpdate` in `Die` | stay in Unity; `Run` uses C# events, and `Entity.Death` (UniRx, headless-compiled) is what `Run` subscribes to | | `Debug.Log` | `:264`, `:657`, `MainMenu` | injected `Action` | -| Scene load | `MainMenu` | stays; the handoff static becomes `ActionGameManager.NewRun : (Galaxy, bool)?`, command-only, consumed once in `Start`; null means Continue | +| Scene load | `MainMenu` | stays; the handoff static is `ActionGameManager.PendingScenario`, command-only, consumed once by `StartGame`; null means Continue | | MonoBehaviour state | `_currentEntity`, `DockedEntity`, `DockingBay`, `TowingStation`, `Zone`, `ItemManager` | projections of `Run` | | Barrel transforms | `EntityInstance.cs:516` -> `HardpointTransforms` | `HardpointTransforms` deleted (Cut 2); the arc is item rotation plus `FiringArc` (fork A); barrels and `ArticulationPoint` are presentation only, `GetBarrel` | | `Physics.*` hit queries | `Projectile`, `GuidedProjectile`, `Laser`, `Lightning`, `HullCollider` subjects | deleted from damage paths; `FireControl` rolls (Cut 2) | @@ -374,7 +380,7 @@ This is subtraction first, then one new file. - Deletes and moves: - `ActionGameManager.cs`: - `IntroCutscene` `:772-799` (dead). - - Statics `CurrentGalaxy` and `IsTutorial` (`:96-97`). + - Statics `CurrentGalaxy` and `PendingScenario` (`:108,113`). - `SaveRun` body `:243-248` becomes `Run?.Save(actionBar)`. Quit (`:236`) calls it. - `EnterWormhole` `:615-637` and the detect loop `:312-316` become `Run.TryEnterWormhole()`. `WarpArrived` drives `SectorMap.QueueZoneReveal`. @@ -393,14 +399,13 @@ This is subtraction first, then one new file. `Run.Died`. - `:264` constructs no `ItemManager`. - `Update` `:1218` becomes `Run.Step(Time.deltaTime)`. - - `MainMenu.cs`: - - Continue (`:102-107`) sets `ActionGameManager.NewRun = null` and loads the scene. - - New Game drops `:112` and sets `NewRun = (sector, tutorial)` at `:138,166`. + - `MainMenu`: already built. Continue (`ShowMain`) loads the scene with no + `PendingScenario`; `MainMenu.Launch` sets `PendingScenario` and clears nothing. - `SectorMap.cs:114-310` reads `ActionGameManager.Instance.Run.Galaxy`. - `InventoryPanel.cs:117-118` becomes `GameManager.Run.Board(ship)`. - `ZoneRenderer.cs:222-231` iterates `zone.Wormholes`. - - `ItemManager.cs:20`: the seed becomes a constructor argument. Call sites: 11 in - tests, 1 in `AetherDb`, and `Run`. + - `ItemManager`: the seed is already a constructor argument (`ItemManager.cs:35`); + `Run` supplies `RunStart.ItemSeed(galaxy, step)`. - Settings (fork S (a)): - `StartingHullName` and `WormholeDistanceRatio` move from `GameSettings.cs:17,23` to `GameplaySettings` (`Settings.cs:155`). @@ -412,8 +417,8 @@ This is subtraction first, then one new file. `GalaxyZone.AdjacentZones` with the rule from `ZoneRenderer.cs:226-230`. Null galaxy zone gives an empty array. - New `Run.cs`: types and rules, no bodies here. - - `static Run New(CultCache, GameplaySettings, ZoneGenerationSettings, PlanetSettings, Galaxy, bool isTutorial, uint seed, Action log)` - 1. `RunSave.Clear`. + - `static Run New(CultCache, GameplaySettings, ZoneGenerationSettings, PlanetSettings, Galaxy, Scenario, Action log)` + 1. `RunSave.Replace` around steps 2-5 (the saved run goes only once the scenario has staged). 2. `ItemManager` over `RunSave.Lots`, seeded. 3. `EnterZone(Entrance)`. 4. Spawn the player ship per `:734-743`. @@ -446,7 +451,7 @@ This is subtraction first, then one new file. child; updates `Bay.DockedShip`. - `void Tow()`: the rule from `:891-911`. - `void Save(SavedActionBarBinding[] actionBar)` - - `RunSave.Capture(cache, Galaxy, Zone, Station ?? Pilot, isTutorial, actionBar)`, + - `RunSave.Capture(cache, Galaxy, Zone, Station ?? Pilot, actionBar, credits)`, then `Commit(…, ItemManager.Lots)`. - No-op when `Ended`. - Remembers `actionBar` for warp saves. @@ -461,7 +466,7 @@ This is subtraction first, then one new file. | Test | Asserts | Mutation that must kill it | |---|---|---| -| `NewRunSpawnsPilotInEntrance` | pilot is a `Ship` with `IsPlayerShip`, in `Zone.Entities`, `Zone.GalaxyZone == Galaxy.Entrance`; the run store is cleared of a prior `SavedGame` | `New` skips `RunSave.Clear`; spawn omits `Zones.Entities.Add` | +| `NewRunSpawnsPilotInEntrance` | pilot is a `Ship` with `IsPlayerShip`, in `Zone.Entities`, `Zone.GalaxyZone == Galaxy.Entrance`; the run store holds no prior `SavedGame` once the run has staged | `New` skips `RunSave.Replace`; spawn omits `Zones.Entities.Add` | | `WarpMovesPilotAndSaves` | stepping after `TryEnterWormhole` lands the pilot in the target zone, out of the old zone's entities, with `SavedGame.CurrentZone` equal to the target index after reopen | arrival skips `Save`; `EnterZone` leaves the pilot in the old zone | | `ContinueLandsDocked` | save while docked, reopen, `Continue`: `Station` is the saved orbital, `Pilot` is its player child | `Land` binds to the orbital itself | | `DeathEndsAndClears` | hull death clears every run record; `Step` throws; `Save` writes nothing | `Died` handler omits `Clear`; `Ended` not set | @@ -473,7 +478,7 @@ This is subtraction first, then one new file. - Unity batchmode has no `error CS`. - Negative greps: - `rg -n "RunSave\.(Clear|Commit|Capture)" Assets/Scripts --glob '!ServerShared/**'` is empty. - - `rg -n "CurrentGalaxy|IsTutorial\s*=" Assets/Scripts` is empty. + - `rg -n "CurrentGalaxy|PendingScenario" Assets/Scripts` matches only the `Run` lowering in `ActionGameManager` and `MainMenu`. - `rg -n "new Wormhole" Assets/Scripts` matches only `Zone.cs`. - `rg -n "new ItemManager\(" Assets/Scripts` matches only `Run.cs`. - `rg -n "ZoneGenerator\.GenerateZone|new Zone\(" Assets/Scripts --glob '!ServerShared/**'` is empty. @@ -1161,7 +1166,7 @@ Options as mapped before the ruling: - **Recommend (a).** **N. Is the scene handoff static acceptable?** Low-blocking. -- (a) `ActionGameManager.NewRun : (Galaxy, bool)?`, consumed once by `Start`. +- (a) `ActionGameManager.PendingScenario : Scenario`, consumed once by `StartGame` (built this way). - (b) `MainMenu` builds the whole `Run` on its generation thread. That moves zone generation's run-store upserts off the main thread, and the `CultCache` threading contract is not checked here. diff --git a/docs/item-provenance-cut.md b/docs/item-provenance-cut.md index 473ec76c2..a0ccd947f 100644 --- a/docs/item-provenance-cut.md +++ b/docs/item-provenance-cut.md @@ -166,9 +166,9 @@ Contradictions and corrections found in the Body: `LoadoutTests` fixture is not: `FirstAvailableProductInKeyOrderBuildsTheSlot` (`LoadoutTests.cs:289-312`) adds two same-maker Lamp products and reads `.Product`. 6. **`ItemManager` lives one scene load, and every run starts with a scene load.** It is - constructed in `ActionGameManager.Start` (`:264`). There is one scene, `ARPG`. New Game - and Continue both end in `SceneManager.LoadScene("ARPG")` (`MainMenu.cs:106,139,167`), and - no `DontDestroyOnLoad` exists. So a ledger held by `ItemManager` spans exactly one run. + constructed in `ActionGameManager.Start` (`:309`). There is one scene, `ARPG`. A scenario + launch and Continue both end in `SceneManager.LoadScene("ARPG")` (`MainMenu.EnterGame`, + `:287`), and no `DontDestroyOnLoad` guards the `ItemManager`. So a ledger held by `ItemManager` spans exactly one run. 7. **Aside, not this cut:** `CreateInstance(CraftedItemData, float)` mints a `CompoundCommodity` for a `ConsumableItemData` design (`ItemManager.cs:136-141`), while `TryActivateConsumable` casts to `ConsumableItem` (`Entity.cs:336`). This map keeps @@ -252,9 +252,11 @@ Not probed: CultCache Studio's rendering of the ledger (operator check); Unity c `ZoneGenerator`'s staged-upsert pattern (`ZoneGenerator.cs:99-108`) is not used for lots: the ledger is live simulation state, captured at commit like entities. - Lifecycle: the run begins with a scene load (§1.6), whose `Start` reads - `RunSave.Lots(CultCache)`. New Game has already cleared the run store (`MainMenu.cs:112`), - so it gets an empty ledger. Continue gets the stored one. Death clears the run store - (`ActionGameManager.cs:1090`); the next run reloads the scene. + `RunSave.Lots(CultCache)`. A scenario launch has `PendingScenario` set, so `Start` builds an + empty `ProvenanceLedger` instead (`ActionGameManager.cs:312`); the saved run's records stay + in the store until `RunSave.Replace` drops them once the new run has staged + (`SavedGame.cs:247`). Continue reads the stored ledger. Death and victory end in `EndRun`, + which calls `RunSave.Clear` (`ActionGameManager.cs:1224-1231`); the next run reloads the scene. **Branding.** - Owner: `ItemManager.Brand(CraftedItemInstance)` -> `(Faction Maker, FactionProductData Product)`. @@ -526,7 +528,7 @@ Subtraction, plus a data rewrite. worktrees. Operator-only checks after Cut C: -- New Game and fly through one zone. The starting ship's items show tier colour, and the +- New Game, pick a scenario, and fly through one zone. The starting ship's items show tier colour, and the properties panel shows Manufacturer, product name and flavour text for branded gear. - Dock and buy an item: its brand still shows in your cargo. - Kill an NPC and pick up loot: brand shown. diff --git a/docs/item-provenance-substrate.md b/docs/item-provenance-substrate.md index 0bc310942..956d79138 100644 --- a/docs/item-provenance-substrate.md +++ b/docs/item-provenance-substrate.md @@ -68,8 +68,7 @@ catalog, built a 196-zone sector galaxy from the authored `Settings.asset`, and `47189c8a`). The commented `HaulingControllerData` union (`Behaviors.cs:179`) is the same kind of residue. - **No recipe, blueprint or ingredient model exists.** "Factory", "fabricat", - "assembler", "blueprint", "recipe" and "refiner" appear in no live C# outside - `NIH/MIConvexHull`. + "assembler", "blueprint", "recipe" and "refiner" appear in no live C#. `ItemData.Manufacturer` readers: `PropertiesPanel.cs:371-372` (shows "Manufacturer", falling back to "GameCult"), `tools/AetherDb/Program.cs:54` (census), and the @@ -83,7 +82,7 @@ All crafted instances come from three `ItemManager` overloads: - `CreateInstance(CraftedItemData, float quality)` (`ItemManager.cs:126-142`) sets Quality and Durability, with no product and no ingredients. - `CreateInstance(CraftedItemData)` (`:144-160`) rolls a rarity tier with the - **time-seeded** `ItemManager.Random` (`:20`) and stores the tier's *discrete* + `ItemManager.Random` (`:22`; seeded per run from the galaxy seed by `RunStart.ItemSeed`) and stores the tier's *discrete* Quality. - `CreateInstance(FactionProductData)` (`:164-187`) calls the previous overload, sets `Product`, and draws a gaussian `RoleFill` per design role. Since no role is @@ -130,9 +129,12 @@ unexecuted stubs. `TradeMenu.Inventory = entity.CargoBays.First()` (`ActionGameManager.cs:827-829`). - **Zones generate lazily on first entry** (`ActionGameManager.cs:643-652`, `PackedContents ??=`) from a deterministic zone seed - (`ZoneGenerator.cs:47`: name hash xor position hash). Item *selection* follows that - seed, but item *quality* comes from the time-seeded `ItemManager.Random`. A zone is - never regenerated within a run. New Game clears the run store (`MainMenu.cs:111`). + (`ZoneGenerator.cs:52`: name hash xor position hash). Item *selection* follows that + seed, but item *quality* comes from `ItemManager.Random`, a stream seeded per run from + the galaxy seed (`RunStart.SeedItems`, steps `ArenaStep`, `StageStep`, `ContinueStep`) + and drawn in the order zones are entered. A zone is never regenerated within a run. A + new run does not clear the run store up front: `RunSave.Replace` drops the old run's + records once the new run has staged (`SavedGame.cs:247`). - Each station carries hull, hardpoint gear, one docking bay, cargo bay, capacitor and stock, all embedded by value. No station equips a factory; none can, because factory designs have no product (§1). @@ -150,8 +152,9 @@ unexecuted stubs. `FactionProductData`, `PersonalityAttribute`, `NameFile`, `InputLayout`, `Loadout`. - Run (`:10`): `OrbitData`, `BodyData`, `SavedZone`, `SavedGame`. Written only by `RunSave.Commit`, which does one commit, keys zones `savedzone-{i}` and removes stale - zones (`SavedGame.cs:96-111`). `RunSave.Clear` removes every run-typed record - (`:114-124`). The single-file store writes its whole view on commit. + zones (`SavedGame.cs:216`). `RunSave.Clear` removes every run-typed + record (`:242`); `RunSave.Replace` (`:247`) does the same for a new run, but only once + the new run has staged. The single-file store writes its whole view on commit. - Player (`:11`): `PlayerSettings`. - **Every item instance is a value** embedded in `EntityPack` (hull, equipment, bays, cargo contents; `EntitySerializer.cs:179-196`), inside `SavedZone.Contents`. No @@ -237,7 +240,7 @@ Every stat and wear reader goes through the instance: "F" marks a fork (§9). "D" marks a recorded default. -| Kind | Named by | Mint | Transfer / loot / sell | Consume | Zone unload / save | New Game / death | Decides | +| Kind | Named by | Mint | Transfer / loot / sell | Consume | Zone unload / save | New run / death | Decides | |---|---|---|---|---|---|---|---| | **Lot** (provenance node) | run-scoped `LotId` (F1) | synthesis, at the mint site's call (F3) | never moves; instances point at it (D) | synthesized inputs are consumed at synthesis and have no instance (D) | kept while reachable from any instance, route or station; GC on `RunSave.Commit` (D, from the orphan-SavedZone scar) | cleared with the run store (D) | the synthesizer, one function in `ServerShared` | | **Lot properties** (mocked quality per role) | on the lot (F4) | rolled once at synthesis from factory quality and input qualities, seeded by lot id (F4) | immutable | n/a | with the lot | with the lot | synthesizer; stat readers only read | @@ -301,7 +304,7 @@ synthesized?** Blocks station identity, routes, stock and loot provenance. pirated freighter's cargo should come from a station the player can fly to. The skeleton is about 200 stations, small next to 16k instances. It demotes `ZoneGenerator`'s station count and faction choice to reading the roster. It also - moves item quality from the time-seeded `ItemManager.Random` to seeded synthesis, + moves item quality from the per-run `ItemManager.Random` stream, which depends on the order zones are entered, to lot-seeded synthesis, which makes the chain regenerable. - Sub-default: stations keep no identity outside a run. Zones never regenerate within one. diff --git a/docs/merge-to-master-checklist.md b/docs/merge-to-master-checklist.md index d5d70e17b..5d8e5ad33 100644 --- a/docs/merge-to-master-checklist.md +++ b/docs/merge-to-master-checklist.md @@ -33,7 +33,7 @@ Compiled 2026-09-29 by Eyes from the maps on the branch. Pointers are `doc:line` ### 2b. Fresh launch (no `run.cc`, no `player.cc`) 3. **Launch to main menu.** Expect no Addressables errors, and the Groups window shows `Assets/Content` under `Default Local Group` (`addressables-cut.md:301`). `player.cc` appears and Continue is disabled (`cultcache-migration-cut.md:2746`). Proves: Addressables Cut 1, CultCache cutover. The 09-17 smoke covered the last two on the old tree; this is a cheap recheck on the new schema. -4. **New Game (tutorial).** Expect the galaxy generates and the start ship is the Longinus (`settings-globals-cut.md:498`, an expectation, not a recorded check for this stack). Expect a Zenith station with a docking bay in the entrance zone every time (`locomotion-cut.md:375`). Proves: locomotion Cut 1 station rule. +4. **New Game, then a scenario.** New Game opens the scenario picker (`MainMenu.ShowScenarios`); a development build lists modes (Terminus (Demo)), development (Main Galaxy) and test arenas, a release build lists only the modes. Pick Terminus (Demo). Expect the galaxy generates and the start ship is the Longinus (`settings-globals-cut.md:498`, an expectation, not a recorded check for this stack). Expect Zenith (Aeronautics Unlimited trade hub) and the Pirates refinery in the entrance zone every time, because the scenario declares `EntranceStations` (`locomotion-cut.md:375`). Proves: locomotion Cut 1 station rule. 5. **Addressables, "Use Asset Database".** Ships, turret and Zenith spawn; thruster and aether-drive particles show; fire an instant weapon (Autocannon) and a charged one (ChargeBlast SG); action bar icons show (`addressables-cut.md:362-366`). Proves: Addressables Cut 2. ### 2c. Flight, power and economy diff --git a/docs/mining-cut-refresh.md b/docs/mining-cut-refresh.md index a96d10b40..8a5fdcd9e 100644 --- a/docs/mining-cut-refresh.md +++ b/docs/mining-cut-refresh.md @@ -63,8 +63,9 @@ rows are kept for the combined test count. The three file sets are disjoint. I checked with `git diff --name-only` over each branch's own range, and none of the three pairs shares a file. So each anchored line is byte-identical in the merged tree. - **Tests ran on Yggdrasil, against synthetic merges** (section 0). CultLib `45c2f40` and CultMath `6d5e209` are - the pins in `Directory.Build.props`. The two LFS files the tests read (`GameData/Aetheria.cc`, - `Assets/Resources/Settings.asset`) were staged beside the job, because the verify mirror carries no LFS. + the pins in `Directory.Build.props`. The LFS files the tests read were staged beside the job, because the verify mirror carries no LFS. The Mining + cut tests needed `GameData/Aetheria.cc` and `Assets/Resources/Settings.asset`; `SubstanceCleanBreakTests` needs 97 and the whole suite needs more + (see the LFS staging set under Verification). - **Catalog facts** come from a probe that opens the merged tree's `GameData/Aetheria.cc` through `AetheriaStores.Open` (section 0). @@ -289,7 +290,7 @@ Every mining question is ruled. - Mark the `:396-412` table as history, anchored at `8bd25f6f`. - **Verification:** - Yggdrasil, the same job that section 0 ran: - `ygg-verify.sh dotnet ''`. + `ygg-verify.sh dotnet ''`. Both roots are mandatory (shared precondition). - The job mounts the Yggdrasil mirrors read-only with `DOCKER_ARGS="-v /home/gamecultadmin/eureka-verify/repos:/repos:ro -v /home/gamecultadmin/eureka-verify/lfs-aetheria:/lfs:ro"`. @@ -298,8 +299,16 @@ Every mining question is ruled. Rule pinned: fire control and mining compose without a behaviour change on either side. Every pre-existing test passes unchanged. - The verify mirror has no LFS (the push from `F:\Projects\Aetheria` fails in the LFS pre-push hook on an - `ssh:` remote). Push from a `--shared --no-checkout` clone, and mount the two LFS blobs. This is recorded + `ssh:` remote). Push from a `--shared --no-checkout` clone, and mount the LFS blobs. This is recorded so the next Hands does not rediscover it. + - LFS staging set. `SubstanceCleanBreakTests` fails loudly on any LFS pointer it scans, so the job must restore + every LFS-tracked file under `Assets/`, `Packages/`, `ProjectSettings/`, `GameData/*.cc` and `tests/fixtures/mods/*.cc` that is not a + binary-media extension (the test's `BinaryExtensions` denylist): 99 files at `83e6957de`, 96 `*.asset` and 3 + `*.cc` (`GameData/Aetheria.cc`, `GameData/Mods/aetheria.nakovalnya/ship.cc`, `tests/fixtures/mods/aetheria.wren/ship.cc`), + which includes `ProjectSettings/ProjectSettings.asset` and `Assets/Resources/Settings.asset`. Derive the list from + the merged tree instead of hand-copying it: + `git ls-files Assets Packages ProjectSettings 'GameData/*.cc' 'tests/fixtures/mods/*.cc' | git check-attr --stdin filter | grep 'lfs$' | sed 's/: filter: lfs//' | grep -viE '\.(png|jpg|jpeg|tga|tif|tiff|psd|bmp|gif|exr|hdr|dds|wav|mp3|ogg|mp4|fbx|glb|blend|ttf|otf|dll|so|pdb|msgpack|zip|bank)$'`, + then copy each path from the `/lfs` mount over the checkout. That set (99: the 97 the sbsar guards read plus the two mod `ship.cc` files the Nakovalnya and Wren tests open) makes `SubstanceCleanBreakTests` green and nothing more: staging only two files turns it red. For a fully green suite also stage `GameData/Mods/*/ship.glb` and `tests/fixtures/mods/*/ship.glb` (the catalog excludes a package with an invalid GLB header, failing about 520 tests) and the LFS `.ttf`/`.otf` fonts `CreditsTests.FontCreditsShowWhatTheFontsThemselvesEmbed` reads. - Unity batchmode compile of the merged tree (Self, in a worktree, never with the operator's editor open on the main tree). This is the Cut 1 renderer compile the map still owes. - Operator: fly through a belt (the Cut 1 check the map still owes). Rocks orbit smoothly, and the minimap diff --git a/docs/mining-cut.md b/docs/mining-cut.md index 7c5be8297..7f20f81ec 100644 --- a/docs/mining-cut.md +++ b/docs/mining-cut.md @@ -89,8 +89,8 @@ nothing per tick. the exact Gaussian mass over a silhouette. A chunk's silhouette is its disc. 5. **The loot is decided at Commit.** The yield and the ore picks come from the shot's own generator, in a fixed draw order after the hit draw. Apply only performs them. -6. **Every mined unit carries a lot.** The lot is `Extracted` from this zone and this belt, and stacks merge only - within one lot. A mined unit never exists without a ledger entry. +6. **Mined units carry no lot.** They merge with every unit of their design, mined or not (ruling + aetheria-living-world:ruling:simple-commodities-fungible, which supersedes Q6b A of 2026-09-30). 7. **A chunk never yields more than its authored total**, whatever weapon breaks it. 8. **Composition is derived, never stored** (recommended in Q7): a pure function of the belt's identity and the catalog's ore table. @@ -139,8 +139,8 @@ nothing per tick. | **Chunk composition** | Derived: `(belt identity, ChunkId, catalog ore table)`. | Never stored (recommended, Q7). A retune of the catalog retunes every belt. | The catalog author, through per-ore data on `SimpleCommodityData`. The derivation function is the only reader of that data for belts. | | **Ore affinity and abundance** | Per ore: new nullable fields on `SimpleCommodityData` (keys 12 and 13 are free. Only key 11 is retired on `SimpleCommodityData`; keys 6, 7 and 8 are live, inherited from `ItemData` (`SpecificHeat`, `Conductivity`, `Price`, `ItemData.cs:291-298` @`b66ba524`). The comment at `ItemData.cs:304` wrongly lists 6, 7, 8 and 11). | Authored in Studio. Changes with the catalog. | Catalog author. | | **Global loot tunables** | `GameplaySettings` / `PlanetSettings` fields (Cut 5). | Authored. Today they live in `Settings.asset`. They move with the settings-globals campaign (`docs/settings-globals-cut.md`, mapped, not landed). | Catalog author. | -| **Mined lot** | `LotId` in the run's `ProvenanceLedger`. `Lot { Design = the commodity, Origin = Extracted { Zone, Commodity, Body }, Quality, Roles = null }`. | Minted at the first extraction from a (zone index, belt, commodity) source (Q6). Reused for later units from that source. Collected by `Reachable` when no instance reaches it. A later extraction after collection mints a fresh lot. | `ItemManager.ExtractedLot(zone, belt, commodity)` is the only writer. Its source→lot index is derived at load, not persisted. | -| **Mined unit** | A `SimpleCommodity` instance, `Data` = commodity, `Lot` = the source lot (`Lot` moves to the `ItemInstance` base, key 11). | Stored in cargo. Stacks merge only within the same `Data` and `Lot`. A split copies `Lot`. | `EquippedCargoBay` owns placement. The mint owns `Lot`. | +| **Mined lot** | Retired by ruling simple-commodities-fungible: a mined unit has no lot and Extract mints nothing. A run ledger saved before the ruling may hold `RetiredExtracted` lots (Provenance arm 2); they load, and `Reachable` drops them. | | | +| **Mined unit** | A `SimpleCommodity` instance, `Data` = commodity, no lot (`Lot` lives on `CraftedItemInstance`; key 11 is never reused on `SimpleCommodity`). | Stored in cargo. Stacks merge on `Data` alone, from any source. | `EquippedCargoBay` owns placement. | | **Current target** | `Entity.Target` (runtime; not packed, `EntitySerializer.cs` has no target field **(read)**). | Set by targeting inputs or AI state. Cleared by the existing entity-removal paths. A broken chunk stays held and prices 0 until retargeted (Cut 3). | Player: the `ActionGameManager` targeting handlers. AI: the Minion states. Both write the one slot. | | **Mining shot** | `ShotId` (`Zone.NextShotId`), as every shot. | Fire → Commit → arrival. Never serialized (`FireControl.cs:852-855`). | `FireControl`. | @@ -301,7 +301,7 @@ resources **(probe: 8 belts, 0 authored)**. - A: Composition is derived: `Comp_c(o) = Abundance_o × exp(Variance × g(hash(belt key, index, o)))`, normalized, with `g ∈ [-1, 1]`. Nothing is stored. Existing saves work, and key 4 is retired. - B: `ZoneGenerator` writes `BodyData.Resources` per belt at generation, and the chunk jitter is derived. Belts in - runs started before Cut 5 have empty compositions until New Game. + runs started before Cut 5 have empty compositions until a new run. - C: Per-belt only, with no per-chunk variation. - **Recommended: A.** It has one owner (the catalog) and nothing to migrate. It follows the same "derived, never stored" spirit as branding. The operator's wording ("the chunk's composition") argues against C. If B is chosen, diff --git a/docs/moddable-ship-authoring.md b/docs/moddable-ship-authoring.md index 81871b2dc..04358c644 100644 --- a/docs/moddable-ship-authoring.md +++ b/docs/moddable-ship-authoring.md @@ -27,31 +27,37 @@ authored `HullData.Shape` in the `.cc`; strokes do not decide armor or mount footprints. `tools/blender/aetheria_ships` is a separate Blender add-on in Brokkr's -sidebar. It uses Brokkr's configured CultLib Python source and edits the +sidebar. It reads a ship file only through AetherDb's `ship-authoring open` and +writes it only through `ship-authoring push`, run from the Game folder's ModTools: +no CultLib path and no msgpack in Blender. It edits the line slot of a ship file's `aetheria.ship_authoring` visual record and the hull shape and hardpoint slots of the `aetheria.hulldata` record beside it. To try it, make `F:\Projects\Brokkr\surfaces\blender` and this repo's `tools\blender` visible -to Blender's add-on search path, enable `brokkr_bridge` then -`aetheria_ships`, and install `msgpack` into Blender's Python environment. +to Blender's add-on search path and enable `brokkr_bridge` then +`aetheria_ships`. Create a draft with `dotnet run --project tools/AetherDb -- ship-authoring create [--like ]`; `--like Djinni` copies that shipped ship's stats and leaves the body and layout empty. Choose that `.cc` in the **Aetheria -Ship** panel, select an object in its ship collection, and press **Bind Ship -Collection**. The collection stores `aetheria.asset_kind=ship`, the stable +Ship** panel's Ship .cc field, select an object in its ship collection, and press **Open Ship**. An unbound +collection is bound to that file first: it stores `aetheria.asset_kind=ship`, the stable `aetheria.id`, and a relative `.cc` path. Select a Grease Pencil object in that bound collection and press **Capture Ship Lines**. Capture checks the collection ID against the record before writing; object and collection display names are not IDs. -**Load Ship Layout** opens the same `.cc` file's hull grid and hardpoints in +**Open Ship** also reads the `.cc` file's hull grid and hardpoints into the panel. Toggle occupied grid cells, resize up to 32×32, and edit each hardpoint's type, mount ID, position, footprint, rotation, armor, and firing arc. A footprint uses top-to-bottom rows of `#` (occupied) and `.` (empty), -separated by `/`; `##/##` is a 2×2 mount. **Save Layout to .cc** replaces only -the hull shape and hardpoint slots. It preserves hull stats, anchors, visual -assets, lines, the record key, and schema. Save rejects a changed ship ID or -layout revision; reload first if another editor changed those fields. A line -capture leaves the loaded layout revision intact. The saved layout is a draft until +separated by `/`; `##/##` is a 2×2 mount. **Push (dry run)** shows, in the panel, the lines AetherDb would +change (`armor: 40 -> 45`) and writes nothing. **Apply to .cc** then writes exactly what that dry run showed, and +replaces only the hull shape and hardpoint slots: it preserves hull stats, anchors, visual +assets, lines, the record key, and schema. Apply is refused with no dry run, or when the scene changed since it, and +AetherDb refuses the write when a record the push writes was changed since Open; open again. The first Apply of a new +ship creates its file. The applied layout is a draft until its mount IDs resolve to visual anchors and C# validation passes. +Agents may call Open and Push through Brokkr (`aetheria.open_ship`, `aetheria.push_ship`, listed in the add-on's +`brokkr_actions.json`) once you press **Reload Host Actions** in the Brokkr panel; the change lines come back in the +receipt. Apply, Capture Ship Lines and Package Ship are not in that file: they stay your buttons. **Package Ship** turns the bound collection into the package. Tag each anchor object with the custom properties `aetheria.role` (`map-icon`, `hull-collider`, `shield`, `tractor`, `thruster-emitter`, `radiator-mesh`, `weapon-mount`, @@ -140,9 +146,10 @@ is not yet an end-to-end ship loader in the current game. `ship-authoring validate`, the catalog composer, and the visual importer call the same `ShipAuthoringStore.Validate(hull, visual)`; that shared path is true of the C# callers only. -The Blender side checks grid bounds and footprint shape (`ship_cc.py`) and -nothing semantic. Blender edits the hull grid, hardpoints, and -captured lines in the typed source records; `inspect` reads incomplete drafts. +Blender builds requests; AetherDb `push` checks and writes. `ship_cc.py` holds the +ship id rule, the enum names and Grease Pencil capture, and nothing that reads or writes a record. +Blender edits the hull grid, hardpoints, and +captured lines through `open` and `push`; `inspect` reads incomplete drafts. Unity's **Aetheria / Preview Mod Ship Package** imports a validated package from disk, resolves stable GLB node IDs, and draws the captured polylines directly as 3D line segments. Point opacity @@ -216,7 +223,12 @@ a radiator, `weapon-mount` for an energy, ballistic or launcher hardpoint. An internal hardpoint (reactor, sensors, shield and the rest) has no anchor, and an anchor taking its id is refused. A thruster's or radiator's anchor node is a mesh: the thruster's is not rendered and is the surface its exhaust emits from, -the radiator's is rendered. A weapon mount is a point, and each one needs at +the radiator's is rendered. A directional thruster's emitter is one-sided: the +exhaust is born along each triangle's normal, so every normal must face the way +the hardpoint's Rotation faces (opposite the push), and a closed box, which also +fires along the push, is refused by Compose and `validate` naming the anchor. In +the Blender kit's frame a hull source's emit mesh is cut to the side facing its +anchor's yaw. A ring thruster would be its own class with its own rule. A weapon mount is a point, and each one needs at least one `weapon-muzzle` anchor whose `ParentId` is the weapon's mount id. `articulation` is reserved for pivots and is never a mount; no pivot is planned until pivots move onto `HullData`. `ShipModPlan` then maps the diff --git a/docs/release-checklist.md b/docs/release-checklist.md new file mode 100644 index 000000000..22d3f1f5e --- /dev/null +++ b/docs/release-checklist.md @@ -0,0 +1,40 @@ +# Release checklist + +A release is `.changeset/*.md` files plus `VERSION`, turned into a tag and a forge release by +`.forgejo/workflows/release.yml`, and by nothing else. A by-hand build for testing calls `AetheriaBuild` directly and publishes +nothing. A published version is never edited; a mistake is a new version. + +## Around every change + +- A player-visible change lands with a change file, written by whoever lands it (agents included): `knope document-change`, + or a file `.changeset/.md` holding front matter `default: patch|minor|major` and one player-facing line. +- Below 1.0 knope bumps one step lower than the level named: `patch` and `minor` give 0.x.(y+1), `major` gives 0.(x+1).0. + Choose `major` when the release should be a new minor line. + +## Cutting a release + +1. Check the change files on the branch read as the changelog you want. +2. Dispatch the `release` workflow on that branch (Actions tab). It runs on Starfire, one job at a time. It prepares the + release, builds win64 then linux64, and only then pushes the `Release X.Y.Z` commit and tag `vX.Y.Z` (one atomic push) + and publishes. The first step checks every host prerequisite and fails before any build or push. The first release this + pipeline makes is v0.2.1. +3. Check the forge release: the notes match the CHANGELOG section, and `Aetheria-X.Y.Z-win64.zip` and `-linux64.zip` are + attached. Unpack both and launch. The zips are made on Windows and lose the exec bit, so on Linux run + `chmod +x Aetheria.x86_64 ModTools/AetherDb` first (those are the only executables in the linux64 player). +4. If the run fails after the push (the forge release step), the commit and tag are already on the forge and the build + directory `../release-` is kept on Starfire. Do not rerun: the tag exists and the change files are consumed. + Create the release by hand on tag `vX.Y.Z`, paste the CHANGELOG section as notes, attach the two zips from that + directory's `dist/`, then delete the directory. A failure before the push needs only a rerun (delete the leftover build + directory). +5. Mirroring to GitHub is by hand if wanted; there is no GitHub automation. + +## One-time setup (operator acts) + +- Register the runner on Starfire with label `starfire` in host mode, capacity 1, running as the operator's Windows user + (follow-up `starfire-forge-runner`). Runner prerequisites, all checked by the workflow's preflight: Git for Windows at + `C:\Program Files\Git` (the workflow pins its `bash.exe`), and on PATH `knope`, `jq` and `curl` (both needed by the forge + release action), `git`, `dotnet` (publishes AetherDb) and `tar`; `C:/Windows/System32/tar.exe` makes the zips. +- Repo secret `RELEASE_TOKEN` (write:repository); repo variables `UNITY_EDITOR` (Unity.exe, 6000.3.24f1), and `CULTLIB_ROOT` + and `CULTMATH_ROOT` (checkouts holding the pinned CultLib and CultMath revisions). All are required. +- Ruling `sbsar-lfs-objects`: prune the 41 `.sbsar` LFS objects from Forgejo's LFS store and the Raven LFS mirror. Git + history keeps its pointers. This is an operator act, not the workflow's. diff --git a/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md b/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md index 42f0ee20c..87a1bb7c9 100644 --- a/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md +++ b/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md @@ -390,7 +390,8 @@ Battlecode, Halite, CodinGame, BWAPI/SSCAIT/AIIDE/CIG, SC2 AI Arena, Lux, CodeCl - **The Colosseum follow-up.** `aetheria-release:follow_up:colosseum-npc-lab` (in force; owner "Aetheria Agents and the headless simulation") names its foundations: - an observation and action seam (agents hold live `Ship`, `Zone` and `ItemManager` references); - - seeding `ItemManager.Random` and the MIConvexHull randoms; + - seeding for tournament reproducibility: `ItemManager.Random` already takes the run's seed + (`RunStart.ItemSeed`), and no MIConvexHull source remains in the repo; - a replay recorder; - a headless tournament runner on Yggdrasil with ratings; - a primitive vocabulary; diff --git a/docs/settings-globals-cut.md b/docs/settings-globals-cut.md index b031ba4bf..f1b2e0582 100644 --- a/docs/settings-globals-cut.md +++ b/docs/settings-globals-cut.md @@ -495,8 +495,9 @@ landed type differs from it by the one attribute. (the helper) [2 now]. - `rg -n "ScriptableObject" Assets/Scripts/ServerShared` must stay 0. - operator: - - Play smoke: main menu, then New Game (tutorial). The tutorial galaxy generates, - and the starting ship is LonginusX. + - Play smoke: main menu, then New Game, then the Tutorial Galaxy scenario (listed under + development, in editor and development builds). The prelude galaxy generates, and the + starting ship is `Settings.StartingHullName` (`Longinus`). - In a station trade menu and the properties panel, item names show tier colours: Legendary orange, Uncommon green. None is black. - The inventory shows armour and durability gradients, and hit flashes use the diff --git a/docs/tutorial-script-sketch.md b/docs/tutorial-script-sketch.md index 7e9233988..3fcbbebb6 100644 --- a/docs/tutorial-script-sketch.md +++ b/docs/tutorial-script-sketch.md @@ -16,7 +16,7 @@ Status: sketch for the operator to react to. Nothing here is built or canon. ## Shape -One contained tutorial run in a small prelude galaxy (`IsTutorial`, +One contained tutorial run in a small prelude galaxy (`Galaxy.IsPrelude`, `TutorialGenerationSettings`). The player is a newly incorporated subsidiary of the protagonist faction. Threefra, a debt-born assessor with opinions, walks them through a "qualification module" whose checklist is theatre. The real test is how the player diff --git a/knope.toml b/knope.toml new file mode 100644 index 000000000..63fa5cd13 --- /dev/null +++ b/knope.toml @@ -0,0 +1,22 @@ +# Release preparation. Change files in .changeset/ decide the bump and the CHANGELOG; commit subjects are never read. +# Knope only prepares: it bumps VERSION, writes CHANGELOG.md and consumes the change files. Tagging and publishing +# are .forgejo/workflows/release.yml (knope cannot upload release assets to this forge). + +[package] +versioned_files = [{ path = "VERSION", regex = '^(?\S+)' }] +changelog = "CHANGELOG.md" + +[changes] +ignore_conventional_commits = true + +[[workflows]] +name = "document-change" + +[[workflows.steps]] +type = "CreateChangeFile" + +[[workflows]] +name = "prepare-release" + +[[workflows.steps]] +type = "PrepareRelease" diff --git a/native/aetherlight/Cargo.lock b/native/aetherlight/Cargo.lock new file mode 100644 index 000000000..494df4f1d --- /dev/null +++ b/native/aetherlight/Cargo.lock @@ -0,0 +1,430 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aetherlight" +version = "0.1.0" +dependencies = [ + "rmp-serde", + "serde", + "serde_json", + "sha2", + "thiserror", + "unicode-normalization", + "unicode-properties", + "uuid", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmp-serde" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" +dependencies = [ + "rmp", + "serde", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "uuid" +version = "1.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cefc03fd367c0c6d4305de1b312cf00248c4114f4a0418ce6a6af769e3b0bd9" +dependencies = [ + "getrandom", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/native/aetherlight/Cargo.toml b/native/aetherlight/Cargo.toml new file mode 100644 index 000000000..49c9a5965 --- /dev/null +++ b/native/aetherlight/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "aetherlight" +version = "0.1.0" +edition = "2024" +license = "MIT" +publish = false + +# Its own workspace: the crate builds on its own, outside any parent manifest. +[workspace] + +[dependencies] +rmp-serde = "1.3" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +thiserror = "2" +unicode-normalization = "0.1.25" +unicode-properties = "0.1.4" +uuid = { version = "1", features = ["serde"] } + +[dev-dependencies] +# Test fixtures draw random ids; no shipped path does. +uuid = { version = "1", features = ["v4"] } diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md new file mode 100644 index 000000000..d56b93a69 --- /dev/null +++ b/native/aetherlight/PROVENANCE.md @@ -0,0 +1,628 @@ +# Aetherlight provenance + +Aetherlight is a fork of the synchronous world kernel of Ghostlight. + +- Upstream: `GameCult/Ghostlight`, `crates/ghostlight/` +- Commit: `c43eb54962ed4a09cc737ecac73a16b0d7ce62b4` (origin/main) +- Taken: 2026-11-19 +- Authority: cut `aetherlight-fork-import` r1 of campaign `aetheria-release`; + rulings `aetherlight-narrative-state-owner` and `dialogue-is-world-action`. + +Every file below was copied as a raw git blob (`git show`), never `git archive`. +The blobs are LF, as upstream. A Windows checkout with `core.autocrlf` turns the +`.rs` files and the two text fixtures into CRLF; rustc, the fixture readers +(`lines()`, `trim()`) and the golden test absorb that, so no `.gitattributes` is +kept (a first commit had one; its stated reason did not hold). The recorded-world +fixture (removed in AL2a) was binary and no newline rule touched it. Line ranges are in the c43eb54 file. + +## Taken + +| c43eb54 path (under `crates/ghostlight/`) | Here | Range | Edits | +| --- | --- | --- | --- | +| `src/lib.rs` | `src/lib.rs` | all | E1-E5, E10-E12 | +| `src/action.rs` | `src/action.rs` | all | E11, E12 | +| `src/clock.rs` | `src/clock.rs` | all | none | +| `src/journal.rs` | `src/journal.rs` | all | E12 | +| `src/grammar.rs` | `src/grammar.rs` | all | none | +| `src/grammar/tests.rs` | `src/grammar/tests.rs` | all | E12 | +| `src/import_key_tests.rs` | `src/import_key_tests.rs` | all | E12 | +| `src/patch.rs` | `src/patch.rs` | 1-6059 and 7906-9606 (dropped 6060-7905: the patch tool catalog, `PATCH_TOOLS`, `patch_tools()`, the `field_example` helpers, `mod catalog_tests`) | E6, E7, E12 | +| `Cargo.lock` | `Cargo.lock` | all | pruned by cargo to the dependencies below | + +`Cargo.toml` is new: package `aetherlight`, its own `[workspace]`, no features, +dependencies rmp-serde, serde, serde_json, sha2, thiserror, unicode-normalization, +unicode-properties, uuid (serde only); dev uuid with v4 (AL3a). + +## Edits + +- E1. `lib.rs`: dropped the `mod` lines and every `pub`/`pub(crate) use` of + aetheria, consumer, controllers, elaboration, local_inference (with its + `cfg(feature = "test-support")` re-export), mailbox, sdk_inference, table, + tool_schema, vault, verse. +- E2. `lib.rs` crate docs: retitled to Aetherlight with a pointer to this file; + the `compile_fail` doc-tests name `aetherlight::` instead of `ghostlight::`. + The sealing prose is kept. +- E3. `lib.rs`: `#![allow(dead_code)]`. The kernel has no entry point until AL4 + adds the ABI; AL4 removes the attribute. +- E4. `lib.rs`: imports that only dropped code used are removed + (`cover::{CellId, Constituent, Resolution}`), or moved under `#[cfg(test)]` + because only tests use them (`patch::{Bounds, Declaration, EntityDeclaration, + SubjectDeclaration}`). +- E5. `lib.rs`: `let mut` removed from the closures `confine_subject` and + `confine_place` (unused-mut in the non-test build). +- E6. `patch.rs`: deleted `use super::tool_schema;`, + `use codex_connector::CodexToolDefinition;` and `use serde_json::{Value, json};` + (only the dropped catalog used the last one); `let mut` removed from the + `controller_id` closure. +- E7. `patch.rs`: lines 6060-7905 dropped as above. +- E8. `lens.rs`: deleted test `every_lead_names_a_patch_tool` and its + `use crate::patch::PATCH_TOOLS;`, which read the dropped catalog. +- E9. `lens.rs`: the doc comment on `leads_with` says "patch tool names" instead + of naming `PATCH_TOOLS`. +- E10. `lib.rs` crate docs describe the fork as it is (no runner, no ports, no + controllers); the compile_fail doc-tests keep no error code (stable rustdoc does + not check one) and the two that named items absent from the fork + (`fixture_controller_opportunities`, `fixture_inference_output`) are deleted. + The `VerifiedPrincipalEvidence` doc no longer links `WorldMailbox`/`SeedPort` + and says nothing here enforces `valid_until`; the ABI must (AL4). +- E11. New tests, not upstream, each killing a mutant that survived upstream's 810 + tests: `action::tests::holding_exactly_the_threshold_satisfies_holds`, + `clock_tests::committed_requires_the_named_counterparty`, + `clock_tests::committed_requires_the_named_kind`, + `soul_knowledge_tests::a_telling_by_a_speaker_outside_its_audience_does_not_apply`. + +- E12. Cut AL2a deletes the model-guidance lanes; see the section below. It + supersedes E4's `cover` import, E8 and E9 (`lens.rs` is gone), and `lib.rs`, + `patch.rs`, `journal.rs`, `action.rs`, `grammar/tests.rs` and + `import_key_tests.rs` lose the symbols and tests listed there. + +The `ghostlight.*` schema ids were renamed in AL3a (see the last section). The +golden replay AL2a removed is back as `fixtures/golden.digests` (AL3a). + +## Left behind + +| Upstream file | Why it is not here | +| --- | --- | +| `mailbox.rs` | the async port/mailbox lane around the kernel; AL4's ABI replaces it | +| `controllers.rs` | model decider lane; composes an invocation's speech text, which Aetheria's player and C# brains do themselves | +| `elaboration.rs` | model elaboration lane | +| `consumer.rs` | consumer patch admission over HTTP-shaped ports; speech only in its fixtures | +| `table.rs` | encodes actor calls as model tools | +| `vault.rs` | evidence source over a vault | +| `local_inference.rs`, `sdk_inference.rs` | model backends (tokio, reqwest, codex-connector) | +| `tool_schema.rs` | tool schemas for model calls | +| `aetheria.rs`, `aetheria/` | Ghostlight's Aetheria catalog reader; Aetheria content is read by Aetheria | +| `verse/` | one example world; its speech affordances are a pattern to copy into Aetheria content, not a kernel dependency | +| `tests/external_admission.rs` | the cross-crate proof that forged, serde-minted opportunities and ids are refused at the public surface; dropped with the consumer lane it drove. AL4 must carry an equivalent proof against the ABI's own surface | +| crates `ghostlight-persona-projection`, `ghostlight-verse`; `sidecar/` | outside the synchronous kernel | + +Speech as world action stays whole: affordance declarations with `carries_speech`, +preconditions, audience, effect slots and outcome bands, `Communicate` and +`Display`, `Knowledge` and `Told`, commitments (`patch.rs`); exercise, role +binding, preconditions, audience, band selection and lowering (`action.rs`); +`DecisionInvocation`, `DecisionEvent` and `ResolvedOp::Communicate` apply +(`lib.rs`); the `SpeakRenderPath` check (`grammar.rs`). + +## Dependency pin + +The crate no longer pins CultLib: `cultcache-rs` (Ghostlight's rev +`85f7024a35ea42cf9f0a0199a064526427150191`) left the manifest in AL3a with the +redb store it served. + +## Pulling a later Ghostlight fix + +By hand, against this file: read the upstream diff for the taken files, apply it +here, and record it in this file with its upstream commit and the files it +touched. A fix that lands in a left-behind file is not pulled. + +## Cut AL2a: the model-guidance lanes + +Authority: cut `aetherlight-cut-agency-a` r1 of campaign `aetheria-release`; +rulings `aetherlight-narrative-state-owner` and `dialogue-is-world-action`. +Deleted, with their c43eb54 homes: + +- Lens (`src/lens.rs`, 361 lines): `Lens`, `LensWeights`; the genesis input, + `WorldState`, snapshot and creation field `lens_weights`; + `CommandBody::SetLensWeights`; `WorldEffect::LensWeightsReplaced`; + `Mismatch::LensWeightsNeverDraw`; the draw-rule check in `verify_state_shape`. +- Cover and agency graph (`src/cover.rs`, 1105 lines): `Cover`, `Cell`, + `CoverBudget`, `derive_cover`, `AgencyGraph`; `WorldKernel::agency_graph` and + `fn agency_graph` (`lib.rs`); `CommandId::for_cell`, `for_cell_constituent`. +- Persona material (`lib.rs`, `patch.rs`): `PersonaMaterial`, `PersonaReadRef`, + `ComponentOp::SetPersonaMaterial` and `ResolvedOp::SetPersonaMaterial` with + resolution, apply and confinement arms, `WorldState.persona_material`, the + subject snapshot's `material`, `WorldPatch::sets_persona_of_existing_subject`. + The op set goes from 34 to 33. +- Brief: the `brief` string in `CreateWorld`, `CreateWorldIntent`, `WorldState`, + `WorldEffect::WorldCreated`, the snapshot and the shape checks. +- Elaborator lane: `SystemCapability::Elaborator`, `PatchAnswer`, + `CausalBoundary`, `BoundaryDigest` and `derive_boundaries`, `exact_boundary`, + `require_answer` (the `AnswerRequired` gate), `jurisdiction_deficit`, + `ground_covers`, `place_in`, `PatchGround::Jurisdiction`; `WorldScaleIntent`, + `WorldScaleIntentRef`, `JurisdictionKey`, `ScaleDeficitRow`, `qualifies`, + `derive_scale_deficit`, the subject snapshot's `qualified`, the snapshot's + `boundaries` and `scale_deficit`, `CreateWorld.scale_intent`, + `CreateWorldIntent.targets` and `jurisdictions`, `CreateJurisdictionIntent`, + `WorldState.scale_intent`; `CommandBody::AdmitPatch.answers` and + `WorldEffect::PatchAdmitted.answers`; `KernelError::AnswerRequired`, + `AnswerNotDerived`, `AnswerNotSatisfied`; `Mismatch::UnknownJurisdictionRoot` + and `ScaleWeightsExceedWhole`. `resolve_patch` loses its intent parameter. +- The golden replay `grammar::tests::existing_world_reopens_with_unchanged_digests` + and the recorded-world fixtures under `tests/fixtures`: removing state fields changed the state + shape, so Ghostlight's recorded world no longer decodes. AL4 adds + Aetherlight's own golden. + +Behaviour with the gate gone: `require_play_active` keeps the one rule +`require_answer` also held (`Play` authors nothing in Draft) and states the other +as a plain rule: in Active, declaring (new structure or evidence) is `Play`'s act +alone, and the owner is refused. A confined author's only remaining check is +`confine_to_ground`, which now serves the consumer ground alone. + +AL4's ABI must route the host through typed commands (the sim reports events, +scripts propose), never through owner declarations in Active: under +`aetherlight-narrative-state-owner` an owner declaring in Active would be a second +door beside that path. + +Kept untouched for AL2b: controllers and `ControllerMode`, consumers +(`ConsumerId`, `SystemCapability::Consumer`, `PatchGround::Consumer`, +`bound_to_consumer`), the draft phase and approvals, `VerifiedPrincipalEvidence`. +(Opportunities, scope digests, the attention order, `ExerciseDecision` and +`DeclineDecision` went in AL2b-1, below.) + +## Leave-set vocabulary still compiled (AL2b's and AL4's triage list) + +`#![allow(dead_code)]` still hides the dead code of a crate with no entry point. +What the cut deletes is gone; what remains is part B's: + +- Authenticated-caller vocabulary: `AuthenticatedCaller::fixture`, + `verified_principal` and `verified_play`; id helpers `text` and `nil_for_test`; + `commits_for_test`; grammar `verbs`. AL4's ABI + decides which of these it needs. +- Patch ingress: `decode_patch`, `check_patch_caps`, `PatchDecodeError` and + `MAX_PATCH_BYTES`, `MAX_PATCH_DECLARATIONS`, `MAX_PATCH_OPERATIONS`, + `MAX_PATCH_EVIDENCE`; the consumer ingress and elaboration lane read them, and + nothing here does. They stay: AL4's ABI decides whether it decodes patches + itself. +- Mailbox and vault comments (`WorldMailbox`, `vault:` evidence strings). + +Reproduce the list with `RUSTFLAGS=--force-warn dead_code cargo test --lib --no-run`: +under test configuration the items nothing exercises show up. + +## Cut AL2b-1: Play's Act replaces opportunity-based exercise + +Base `bf92a054f`. An act is one command, `Act { actor, invocation }`, admitted for +`System(Play)` in Active only, and one effect, `Acted { invocation, event }`. +`require_granted(state, actor, affordance)` is the only constructor of +`GrantedAffordance`: the actor's `affordance_grants` entry holds the affordance +and the catalog defines it, otherwise `AffordanceDenied`. `Retire` removes a +subject's grants, so a retired actor is refused by that check alone. +`action::exercise` takes the actor in place of an opportunity; its pipeline is +unchanged and the band draw keeps `command_id` as its only per-command term. +`DecisionEvent` carries `actor`, not `scope` and `controller_id`. `STATE_SCHEMA` +and `COMMIT_SCHEMA` moved to `consumer.v8`. + +Deleted, with their `bf92a054f` locations in `lib.rs`: + +- `ScopeDigest`, `ScopePreimage`, `DecisionOpportunity` (459-506) and + `scope_digest`, `exact_opportunity`, `derive_opportunities`, + `order_opportunities`, `pressure_total`, `attention_debt`, `granted_entries` + (3841-4034). `WorldSnapshot.opportunities`, `WorldState.last_opportunity_at` and + the attention-stamp shape check in `journal.rs` (730-738). +- `CommandBody::ExerciseDecision` and `DeclineDecision`, `WorldEffect:: + DecisionExercised` and `DecisionDeclined`, their `reduce` and `apply_effect` + arms, and `KernelError::OpportunityMismatch`, `ScopeChanged`, + `ControllerMismatch`. +- The operator log: `operator_log`, `OperatorEvent`, `BoundRole` (3518-3579, + 1109-1134), and the kernel readers `opportunities`, `clock_advances`, + `controller_receipt`, `controller_decline_receipt`. +- `WorldJournal::commits` and `FictionalMinutes::since`, dead once the readers + above went. + +Kept: the whole dialogue lane (`carries_speech`, `Communicate`, `Display`, the +kernel Speak entry, the grammar, `preconditions_hold`). `DecisionScope` stays the +grant key and `ControllerAssignment` stays; the owner's `AdmitPatch` and +`AdvanceTime` doors and `SystemCapability::Clock` stay. + +AL2b-2a (below) took the writers; AL2b-2b still owns the controller half under +`aetherlight-play-only-after-genesis`: `ControllerAssignment` (which until then +holds only the `Retired` flag and unread identity data), `NewController`, +`ControllerId`, `ControllerMode`, `DecisionScope` as the grant key, +`SubjectState.retired`, `Mismatch::UnadmittedController`, the `admits_human` +rename and the snapshot's controller fields. + +`last_acted_at` and `minted_at` in `snapshot` still read `state.events` (by +`event.actor`). AL3 needs keyed rows instead of a scan; that is the AL3 cut's. + +## Cut AL2b-2a: after genesis only Play writes + +Base `f51275c61`. A world is born Active: the genesis commit is the owner's +only act, and `WorldState::empty` has no phase and no approvals. After it +`CallerId::Play` is the only caller any command body admits. `CallerId` is +`{ Principal, Play }`; `Principal` survives as the genesis creator (and as the +refused caller of every post-genesis body). One rule, `require_play`, decides it +at the top of `reduce` and again at the top of `apply_effect`, so it holds on +commit and at replay; the journal gains no caller rule. +`require_ruler` is `forbid_rulings_at_genesis`: genesis may not rule or mint, +Play may. A grant row exists if and only if the subject holds a verb; a subject +may be declared with none, and revoking the last verb removes the row. +`GrantsOutsideControl` is `GrantsToRetired`. `STATE_SCHEMA` and `COMMIT_SCHEMA` +moved to `consumer.v9`. + +Deleted, with their `f51275c61` locations in `lib.rs` unless noted: + +- The Clock and Consumer capabilities and `CallerId::Controller`: + `SystemCapability` (388-406), `AuthenticatedCaller::verified_controller` (433), + `require_system_capability`, `require_clock_caller`, `require_play_active`, + `require_owner` and `require_patch_author` (1456-1514, 3594-3625, 3989-4006), + and `apply_effect`'s capability table. +- The consumer lane: `ConsumerId` and its namespace (317-338), `PatchGround` + (408-419), `NewController::External`, `ControllerAssignment:: + ExternallyControlled`, `expected_caller`, `consumer()`, `bound_to_consumer`, + `candidate_places`, `confine_to_ground` (3628-3792), `operation_ground` + (3826-3987), and in `patch.rs` the mirror and human candidate sets, + `Mismatch::OutsideJurisdiction`, `RetiresAMirror`, `ControllerGrantMismatch`. +- The draft phase: `WorldPhase`, `WorldState.phase` and `draft_approvals`, + `CommandBody::ApproveDraft` and `ActivateWorld`, `WorldEffect::DraftApproved` + and `WorldActivated`, `required_approvers`, `KernelError::WrongPhase`, + `NotDraftApprover`, `DraftAlreadyApproved`, `MissingApprovals`, the snapshot's + `phase`, `draft_approvals` and `required_approvers`, `Mismatch::RetiresAnApprover`, + and the Draft-only shape clause in `journal.rs`. +- The never-mute rule and the controller/grant pairing: in `admit_resolved`, the + resolver, `Mismatch::WouldLeaveSubjectMute`, and the shape clauses in + `verify_state_shape` that required a grant row per controlled scope. +- `CommandId::derived`, whose only caller was `ConsumerId::of_name`. +- `VerifiedPrincipalEvidence` (106-146), `CreateWorldIntent` (366-376) and + `PrincipalCommandIntent` (521-529). The `valid_until` enforcement that + Ghostlight's mailbox did is no longer an AL4 obligation: the type that carried + it is gone. + +Kept: the whole dialogue lane, `decode_patch`, `check_patch_caps`, +`PatchDecodeError` and the `MAX_PATCH_*` constants (AL4's ABI decides whether +it decodes patches itself), the `ghostlight.*` schema namespaces (AL3 renames +them), `Retire`, `GrantAffordance` and `RevokeAffordance` as Play's patch +operations, and `#![allow(dead_code)]`. + +Nothing decides with a controller after this cut. `ControllerAssignment`, +`NewController::{Human, NarrativePersona, OperationalAgent}`, `ControllerId`, +`ControllerMode`, `DecisionScope` as the grant key, `validate_assignment`, +`Mismatch::UnadmittedController` and `admits_human` (the genesis predicate three +places read) stay compiled for AL2b-2b, which removes the controllers and +renames the predicate. + +`last_acted_at` and `minted_at` in `snapshot` still read `state.events`; the +count of code readers of `state.events` did not rise (idea +`cutspecs-1119.al3-needs-keyed-rows`). + +## Obligations this cut hands to AL4 + +- A cross-crate proof that forged opportunities and ids are refused, equivalent to + the dropped `tests/external_admission.rs`, against the ABI's surface. +- Removal of `#![allow(dead_code)]`. + +## AL2b-2b: controllers go, retirement on the subject + +The subject controller is gone: `ControllerAssignment`, `ControllerId`, +`ControllerMode`, `NewController`, `DecisionScope`, `SubjectDeclaration.controller`, +`Mismatch::UnadmittedController`, `validate_assignment`, the snapshot's controller +fields and `ControllerId::issue`. Retirement is `SubjectState.retired`, and +`is_retired` is its only statement. `affordance_grants` is keyed by `SubjectId`. +`admits_human` is `is_genesis`: it says what the from-nothing lane may build (the +kernel Speak entry and the first subjects), not who may be bound. The schema is +`consumer.v10`; v9 rows are refused at the schema gate, with no migration. + +Not this cut's, and kept: the channel controller (`ChannelRecord.controller`, +`SetController`, `resolve_controller`), which is dialogue +(`dialogue-is-world-action`). An earlier version of this file listed +`resolve_controller` and `controller_key` as AL2b-2b's; that was wrong. + +## Cut AL3a: the journal is in memory; ids are derived + +Authority: cut `aetherlight-journal-a` r1 of campaign `aetheria-release`; rulings +`aetherlight-narrative-state-owner`, `cultnet-scale-is-not-negotiable`, +`dialogue-is-world-action`. Base `09a1c3256` (spec base `39c50acfc`; no `native/` +change between them). + +Ids. `CommandEnvelope::id()` is the first 16 bytes of sha256 over +`aetherlight.command.v1`, the world id, the big-endian expected revision and the +named messagepack of caller and body. `CreateWorld::id()` is the same over +`aetherlight.create.v1` and the whole creation. `WorldId::of(creation id)` is the +same over `aetherlight.world.v1`; a genesis commit whose world id is not that is +refused at open. The `id` fields on `CreateWorld` and `CommandEnvelope`, +`CommandId::new`/`parse_uuid` and `WorldId::issue` are gone; `CommandId::issue` +is a test fixture. Retry identity went with them: `SubmitReceipt` collapsed into +`CommitReceipt`, and a resubmitted applied command is a `RevisionMismatch`. +`WorldCommit.committed_at` is gone: wall time is the C# store's `stored_at`. + +Journal. `WorldJournal { commits }` is the only record of a world. `export()` is +canonical named messagepack of `{ schema: aetherlight.journal.v1, commits }`; +`open(bytes)` decodes canonically and replays through `verify_history`, which +reads the revision-ordered slice and returns the head state it derives. There is +no state row, no expected world id, no health or ownership check and no +`verify_append`. `STATE_SCHEMA` and `COMMIT_SCHEMA` are +`aetherlight.world_state.v1` and `aetherlight.world_commit.v1`; any `ghostlight.*` +schema is refused at the schema gate and at the commit chain. + +Dependencies. chrono, cultcache-rs (and with it redb) and tempfile left the +manifest; uuid keeps `serde` in `[dependencies]` and `v4` only in +`[dev-dependencies]`, so no shipped path draws a random id (`cargo build --lib` +compiles without it). + +Not taken from the spec's text: the spec's negative pattern `id: CommandId` +matches the `command_id: CommandId` parameters of the band draw and derivation +(the per-command term the spec keeps); the doc comment said `synchronous`, which +`chrono` matches, and now says `single-threaded`. + +Host contracts (AL3a, from Soul's pass): + +- Two byte-equal creations share a `WorldId` and every id under it. A host that + wants distinct worlds salts each run or profile into the creation, for example + a run seed in the patch. +- Truncation and rollback open: a chain verifies as a prefix, so an export with + its tail dropped, or an older export, opens as a valid shorter world. The + holder of the bytes keeps the head (revision and state digest from `snapshot()` + at export time) and compares after `open`. AL5's C# store owns this. +- The band draw is grindable through the command id (it hashes the body, so the + text, a magnitude or the revision re-roll it). Only Play submits acts after + genesis and Play is trusted, so it is not an authority hole. + +## Cut AL3b: partitions are tracked documents, the state digest is a set digest + +Authority: cut `aetherlight-journal-b` r1 of campaign `aetheria-release`; rulings +`aetherlight-narrative-state-owner`, `cultnet-scale-is-not-negotiable`, +`terminus-clockwork-world`. Base `36d1d2507`. + +Tracked documents. Each partition of `WorldState` is a `Docs` (`docs.rs`): +a map whose every write method records the key's value as it stood when the +transaction first touched it. `finish` reports the keys whose value really +changed with their old value; `rollback` puts the touched keys back. The world's +own fields (id, owner, title, grammar, clock) are one `Tracked`. +`revision`, the accumulator, `state_digest` and `last_commit_digest` are the +chain head, outside every document. `submit` checks, reduces, opens a +transaction, applies to the live state, then folds the change set and seals the +commit; any error before the commit is sealed rolls the state back. There is no +candidate clone, and replay uses the same begin, apply, finish path, so opening +a world costs what its commits touched. + +Set digest. A document digest is sha256 over `u64be len(schema)`, schema, +`u64be len(key)`, key and the named messagepack of the value. The accumulator is +LtHash16 (Lewi et al. 2019): a document digest is expanded to 2048 bytes by +sha256(digest, block) for blocks 0 to 63, read as 1024 little-endian `u16` +lanes, and added (or subtracted) with wrapping. An updated document subtracts +its old digest and adds its new one. `state_digest` is `sha256:` plus the hex of +sha256 over `aetherlight.world_state.v2`, `u64be revision` and the lanes. It +depends on the set of documents alone, never on write order. + +Document names are `aetherlight..v1` for world, subject, entity, edge, +position, holdings, dependencies, fact, channel, knowledge, authority, +selection, redress, commitments, pressures, affordance and affordance_grants. +Keys are the id's uuid text; redress is keyed by the grievance name and knowledge +by `subject/fact`. These schema ids exist only as digest input. + +Schemas. `aetherlight.world_state.v2` and `aetherlight.world_commit.v2`. An +export whose commits carry v1 is refused. Every state digest, every commit +digest and the export hash moved; `fixtures/golden.digests` was regenerated and +reproduces on Linux. + +Events and knowledge. `WorldState` no longer holds events: an event lives once, +in the `Acted` effect of the commit that applied it. `snapshot` folds +`minted_at` and `last_acted_at` over the journal (still one O(history) pass; an +index is the follow-up's). `verify_state_shape` no longer judges events; replay +re-derives each through `action::exercise` in `apply_effect`. Knowledge is one +document per (subject, fact), so a subject's knowledge is a range over the key +and forgetting removes one key. `WorldState` has no `Serialize` or `Deserialize`: +only documents are encoded, one at a time. + +The change set is transient here. AL3c records it through the CultLib type. + +Timing. The ratio of 1600 to 100 persons is not gated by this cut: the world +reads a commit makes (`audience`, `derive_motion`, the snapshot) are still +O(world), and follow-up `aetherlight-read-indexes-timing-gate` owns the gate. What +this cut owns is the work it does for the digest, which +`golden_tests::digest_work_is_equal_at_100_and_1600` pins: document digests per +commit equal at both sizes and equal to Added + Removed + 2 x Updated. + +## Cut AL3b-2: partition read indexes, and the read-work gate + +Authority: cut `aetherlight-read-indexes` r1 of campaign `aetheria-release`; +rulings `aetherlight-narrative-state-owner`, `cultnet-scale-is-not-negotiable`, +`terminus-clockwork-world`. Base `576605c7b`. No digested byte moves: +`fixtures/golden.digests` is identical at every commit of the cut. + +Read indexes are derived state. A `Docs` may carry a `Projection`, a pure function +of one document's value (`DueAt`, `StandsAt`, `ChildOf`, `BySource`, `ByEndpoint`, +`ByController`, `ByIncumbent`, in `lib.rs` beside `world_state!`). The index is the +projection of the map as of the last `finish`, folded by `Docs::finish` from the +same changed-key list the digest folds. It is not a partition: not digested, not +encoded, ignored by equality, never exported. Opening a world builds it by replay, +since genesis and every replayed commit close through `finish`; there is no rebuild +path. `Docs::indexed(range)` returns (point, key) in order and is corrected by the +open log (a logged key's committed entries are dropped and its current points are +read from the map), so it is true mid-transaction; `rollback` never touches the +index because the index never saw the transaction. `Docs` no longer derefs to its +map: every read is an inherent method, so no reader can step around the counter. + +Read work is counted where reads are owned. In test builds `docs::rows_read()` is +the number of rows any `Docs` iterator has yielded plus the entries every `indexed` +call returned. `golden_tests::read_work_is_equal_at_100_and_1600` asserts that a +tick (two routines rolled, two obligations pressed) and a colocated speech read +the same number of rows at 100 and 1600 persons; `operation_reads_are_equal_at_100_and_1600` +does the same for the reads no submit shape reaches (a two-level `under_place`, a +`DischargeCommitment` among N pressure rows, one incumbent's `delegated_authority`, +a three-route `reachable`). Wall time is reported by `clockwork_commit_cost` and +asserted nowhere: it is noise at this scale. The gate world holds a route, a +`Reach::Place` channel and an institution with an office per place, because an +empty partition hides its scan. + +Eight scans became index reads: `under_place`, `audience` (colocated), the pressure +holders of `DischargeCommitment`, `scope_components`' routes and controls, +`delegated_authority`, `derive_motion`'s commitment walk and `reachable`'s outbound +edges. Each old scan is kept as a `cfg(test)` `*_by_scan` reference, and +`index_reads_equal_reference_scans` compares them over every revision of the golden +session, the populated worlds and forty clockwork commits. `indexes_are_derived` +rebuilds every index from its map after each commit, after reopen and after each +failed apply; `a_corrupted_index_is_detected` damages each index both ways. + +Reads that still scan, each with its owner: `snapshot` (the host's whole-world +projection, never on the commit path); the resolver's reads of the whole world in +`AdmitPatch` (`aetherlight-resolver-reads-world`). The +"Timing" paragraph of AL3b above is superseded: the gate it deferred is +`read_work_is_equal_at_100_and_1600`. + +## Cut AL3d-2: cross-partition views + +Authority: cut `aetherlight-cross-partition-views` r1 of campaign +`aetheria-release`; rulings `cultnet-scale-is-not-negotiable`, +`aetherlight-narrative-state-owner`, `terminus-clockwork-world`, +`dialogue-is-world-action`. Base `609b3ba5e`. No digested byte moves: +`fixtures/golden.digests` is identical at every commit of the cut. + +Two questions the clock asks are joins, so no one partition's index answers them +(a `Docs` projection is a pure function of one document). Whether a dependency is +failing joins `dependencies` with `edges`, `holdings` and `positions`, and two of +its arms are anti-joins (a resource not held, a subject not placed); whether a due +commitment is live joins `commitments` with `subjects.retired`. `views.rs` owns +both as `Views { live_due, failing }`: `live_due` is the subjects with a +commitment due at each minute, retired subjects excluded, and `failing` is the +(dependent, target) pairs failing a live dependent. + +`Views` is derived state, a sibling of the `Docs` indexes and not a projection: a +field of `WorldState` outside `partitions()`, so not digested, not encoded and +never exported; its `PartialEq` is always true, so equality is the documents'. +Its one writer is `Views::fold`, called by `WorldState::finish` before the logs +close, from the `changes()` of the six partitions the views join. A subject whose +commitments or retirement changed loses its due points and regains them if it is +live; a subject whose dependencies, holdings or retirement changed has its +failing rows re-judged; a changed route or placement re-judges its dependents, +which the new `DependsOn` index on `dependencies` names. Rollback never touches +it, because the view never saw the transaction; genesis and every replayed +commit close through the same `finish`, so open rebuilds it by replay. + +`derive_motion` reads the views only with clean logs (`debug_assert` on the six +partitions; both callers satisfy it: `reduce`, and `apply_effect`'s +`TimeAdvanced` arm before its first write). `DueAt` is deleted, so the due +question has one owner, and `motion_of` no longer walks every dependency row or +visits retired subjects' past-due routines. Motion is byte-identical. The old +walks are `cfg(test)`: `derive_motion_by_scan` over every promisor and every +dependency, and `Views::rebuild`. A test that forges partitions and then calls +`derive_motion` must close its writes through `finish`; a forged state that never +finishes has a stale view by design, the same contract as a `Docs` index. + +Oracles: `views_are_derived` (the view is the rebuild after every walked commit, +reopen and failed apply, over a scenario world that closes and reopens a route, +empties and refills a holding, removes a depended-on subject's position, releases +a dependency and retires a subject holding past-due routines and a failing +dependency), `view_reads_equal_reference_scans`, `a_corrupted_view_is_detected` +and a debug refusal of a read with an open log. View reads are counted where they +are owned, like `Docs` reads, so the gate sees them. + +The gate world grows with them: a dependency per person (to the previous live +person, so each stays satisfied), two failing (persons 0 and 1 on the last +place's grain), a forum per place, every routine checking that its person holds +their place's grain, every tenth person from the 35th retired, and the clock +moved one period so every routine is past due. The fixed-count pins on +`dependencies` and `redress` are gone; `read_work_is_equal_at_100_and_1600` now +asserts the population at scale. + +Soul pass 1 (fix batch). The fold's moved-targets arm reads the dependencies +`DependsOn` index through `Docs::indexed_unchanged`, which names the committed +entries of keys the open log did not change and does not walk the log; a changed +dependencies key is already re-judged whole, so a bulk commit (genesis, every +replayed commit at open) folds in rows proportional to what it changed +(`folding_a_bulk_commit_reads_rows_in_proportion_to_the_change`). The clean-log +check on a view read is an `assert!`, not a `debug_assert!`: six flag tests, held +in every build. `Release` now clears the pressure its dependency raised through +`set_pressure`; before, a pressed dependency's pressure row outlived it and the +export failed to reopen (pre-existing at `609b3ba5e`). A seeded differential test +(`views_equal_their_rebuild_and_the_scans_over_random_commands`) holds the views +to their rebuild and the motion to the scans over random bind, release, route, +holding, relocate, retire, tick, speech and refused commands, reopening every 50. + +Not defended by the gate, on purpose: a tick's cost is linear in the number of +failing dependencies, because each failing dependency presses a pressure row each +tick. The gate world pins failing at two, so growth in failing is not seen; that +cost is inherent to pressing and is not a read of the world. `open` of a large +world is superlinear in rows from readers outside this cut (the resolver's reads +of the whole world at genesis, owner `aetherlight-resolver-reads-world`); +`open_cost` reports it. + +## Cut AL3d-1: the patch lane reads what the patch touches + +Authority: cut `aetherlight-resolver-reads-world` r1 of campaign +`aetheria-release`; rulings `cultnet-scale-is-not-negotiable`, +`aetherlight-narrative-state-owner`, `terminus-clockwork-world`, +`dialogue-is-world-action`. Base `609b3ba5e`. No digested byte moves: +`fixtures/golden.digests` is identical at every commit of the cut. + +`resolve_patch` used to seed fifteen candidate maps by copying every partition, +collect every catalog kind and every subject's import key into sets, and re-judge +every holder for overlap after each widening operation. Its reads grew with the +world: 936, 3696 and 14736 rows for one `DischargeCommitment` at 100, 400 and 1600 +persons, and 14,000 or more for every other shape. It now reads what the patch +touches. + +`patch/candidate.rs` owns the candidate graph of one resolution. Each candidate map +is an `Overlay`: the committed partition read through a base function (a point get; +a `Key::Draft` key has none), and the patch's writes in a local map. `Candidate` +holds the fifteen overlays and the named reads, each bounded by what the patch +wrote plus what it returns: `occupants_under` (`under_place` over `ChildOf` and +`StandsAt`, corrected by the written positions), `offices_of` and `offices_held_by` +(the committed row or `ByIncumbent`, corrected by the written offices), `kind_taken` +(`ByKind` on the catalog) and `import_key_held` (`ByImportKey` on the subjects), +`custody` (the sums over the written holders only: every other holder is on both +sides of the equation and cancels). `authority`, `selection` and `retired` are +private to the module: a write goes through `set_grants`, `set_office` or `retire`, +which re-judge the holders whose effective authority it can change (the holder and +an institution's incumbents; an office's old and new incumbent) and keep +`overlapping`, the set of holders with two grants of one kind over overlapping +ground. A widening operation is `OverlappingJurisdiction` exactly when the set is +non-empty. That is what `graph_overlaps` answered, because the committed world is +disjoint (every commit checks it and opening a world verifies it), so only a holder +the patch touched can enter the set. The mismatch list is unchanged, including the +later widening operations after a first overlap and a revoke that clears it +(`overlap_mismatches_are_unchanged`). The candidate lives for one `resolve_patch` +call and is never written back; `admit_resolved` stays the only writer of the +ontology partitions. + +`apply_operations` derives its two checks from the transaction's log. Conservation +sums the holders `holdings` logged as changed, each from its value when the +operations began (so a holder already written by the declarations above it is +measured from there). Disjointness judges only the holders whose grants, offices or +institution the transaction touched, through `holder_overlaps`, which +`overlapping_holder` also calls for the open-time whole-world check +(`verify_state_shape`, whole-world on purpose). `resource_total` survives only as +the test reference `resource_total_by_scan`. + +Two partitions gained read indexes, `subjects` by `ByImportKey` and +`affordance_catalog` by `ByKind`, so `held_import_keys` and the per-patch kind set +are gone and `import_key_fault` asks a predicate. + +The seeding block, `graph_overlaps`, the old effective-authority walk and +`key_covers_place` live on only as `cfg(test)` references (`Materialized`, whose +`seeded` is the old block verbatim). `candidate_reads_equal_materialized_scans` +walks a civic world through the shapes that move each read (a subject leaving and +entering a subtree, a declared place and subject, a retirement, a vacated and +refilled office, an overlapping grant and its revocation, the retirement of the +lending institution, a declared institution, custody written both ways) and holds +every named read and the overlap set to the scan after every step; +`an_untouched_overlay_reads_what_the_seeding_copied` holds every base function to +the copy in each populated world. The gate is +`golden_tests::patch_read_work_is_equal_at_100_and_1600`: ten patch shapes through +`AdmitPatch` read the same rows at 100, 400 and 1600 persons (at most 21 each), +and `apply_checks_read_the_log` pins the commit lane's two checks. The +`DischargeCommitment` case of `operation_reads_are_equal_at_100_and_1600`, which +called `apply_operation` directly, moved into the gate. + +Reads that still scan: `snapshot` (follow-up `aetherlight-snapshot-history-fold`) +and `verify_state_shape` at open, by design. + +Fix batch (verdict s1). `apply_operations` sums the union of the holders written at +entry and the holders the log reports, so a holder written before the operations and +restored to its start value still counts. Three missed mutants were not equivalent +and are pinned by `golden_tests::within_one_patch`; `random_patch_sequences_agree_with_the_scan_references` +runs seeded random patches through the kernel and holds resolver, apply and the scan +references to one answer. The retirement-flip clause of `touched_holders` is gone +(a retirement only removes lent authority). Accepted, not fixed +(`counter-blind-sizes`): the read gates count rows through the counted API, which +point reads bypass by design, and wire patches are capped at 128 operations +(`MAX_PATCH_OPERATIONS`), so the flat-read gates measure patches no larger than that; +nothing measures a patch whose operation count grows with the world. diff --git a/native/aetherlight/fixtures/golden.digests b/native/aetherlight/fixtures/golden.digests new file mode 100644 index 000000000..cd2c826c8 --- /dev/null +++ b/native/aetherlight/fixtures/golden.digests @@ -0,0 +1,10 @@ +0 sha256:2ca3c099943ec537cd4dad9eef0b79b7368daa5b2dbd93baac0cb57cba3dcabe sha256:a94b938beddc671d28803581c9c3711fc520603f2dc8ac192b7cb54e73b3ff14 +1 sha256:cc421710aaa5d92b07abe0d7c4d0506fd6f9b66d1c806e863942e8a0113c7620 sha256:1abfc74079a3894ad21923f6d195f5e067adf58c5806f6cfc6bf08094f72ce9f +2 sha256:c2c2c2631caa85f9a0721778a7a05515a6687dda65af71f916a6565314f20f1b sha256:58a46e1def214cba12ed5d6ba1e991fa43d6927f6467fe10c276c0bc5ec38691 +3 sha256:5326e779106a076a35b26deb2d1116813accd9c8ad7da32569d240d4631de85c sha256:1cb8fd189c2c64c7ebf8708ae7db856b020b156c5660ac9178a27b50421ddbd4 +4 sha256:8b6e54464a24af395e8f5c0149aab8993355fa79994c09c4be53eabc5688d23a sha256:c78021e910c535f333fa4fdf97742a1329c5eb788b874c5c6302613abeef639b +5 sha256:78af2b889c301251919c6d68cf397d2befdf9b4fc012d73887c7d56894e86ecf sha256:3ab475b3e27f2e4d0afabd973ff69fff3523182216aa1f4ff3331de1747e1482 +6 sha256:2ce1eee99f2a650d9ef212ec04c2042b5e63005c5c263063d4e53b79d7ba7214 sha256:575b25743bc6d1673a71d9d0dc7be3825bec261f485bae13984065028601fb98 +7 sha256:fd5454f623359764bb4afaae6305a9ca41bca8670c36fd1f4f1c38779add4aa4 sha256:ba97a6d5c09e018c6abe91f782ab8bc5e618d0d8a45ac22cb637f40ad01755ef +8 sha256:7762f695b8205cba054d957e9a9242399320683d6d34c30ee9612dc89844ff2f sha256:b531e0d1afdb4f11033fc19e5280f7b46fc2b27911194e5c34dcbe8d57fae10e +export sha256:ef186452fd00de5b85a44e4a623489264e649810ab95847a45f25d82a0ae36fd diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs new file mode 100644 index 000000000..4d3b3edad --- /dev/null +++ b/native/aetherlight/src/action.rs @@ -0,0 +1,2762 @@ +//! The invocation pipeline: catalog lookup, role binding, precondition +//! evaluation, effect-ceiling checking, band selection, and lowering. +//! +//! One entry point, [`exercise`], reached from `reduce`'s `Act` arm +//! and from `apply_effect`'s `Acted` arm, so a forged effect is +//! re-derived by the same function that produced the honest one. Nothing else +//! draws a band, and the draw goes through the one `digest()` owner. + +use super::patch::{ + self, Affordance, Audience, AudienceSpec, BoundPrecondition, Bounds, ComponentOpKind, Cost, + Precondition, Quantity, RefKind, Role, WorldPatch, +}; +use super::{ + AffordanceId, AuthorityGrant, AuthorityTarget, CommandId, DecisionEvent, DecisionInvocation, + EdgeId, EntityId, EventId, FictionalMinutes, GrantedAffordance, + KernelError, Magnitude, SubjectId, Target, WorldId, WorldState, digest, +}; +use serde::Serialize; +use std::collections::{BTreeMap, BTreeSet}; + +/// The complete failure set of one affordance invocation. Sorted and complete +/// like `Mismatch`, and like it never serialized: it states the affordance +/// contract, which no commit records. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum ActionMismatch { + UnboundRole { + role: Role, + }, + UnknownRole { + role: Role, + }, + DuplicateRoleBinding { + role: Role, + }, + UnknownTarget { + role: Role, + }, + TargetKindMismatch { + role: Role, + expected: RefKind, + actual: RefKind, + }, + ActorNotPresent { + precondition: usize, + }, + TargetUnreachable { + precondition: usize, + }, + InsufficientHolding { + precondition: usize, + }, + SlotNotProposed { + slot: usize, + }, + UnknownSlot { + slot: usize, + }, + DuplicateSlotProposal { + slot: usize, + }, + MagnitudeShapeMismatch { + slot: usize, + }, + MagnitudeOverCeiling { + slot: usize, + }, + ZeroMagnitude { + slot: usize, + }, + SpeechRequired, + SpeechNotCarried, + EmptySpeech, + EmptyDisplay, + /// The acting subject's effective authority covers no such target under + /// this kind. A target that walked out of the jurisdiction while the + /// proposal was in flight arrives here: what the actor is authorized over + /// is in its scope, the world it reaches is not. + NotAuthorized { + precondition: usize, + }, + /// No forum takes this grievance, or its standing does not reach the actor. + NoStanding { + precondition: usize, + }, + /// An invocation bound the reserved `actor` role. + ActorRoleBound, + /// A slot would grant authority the acting subject does not itself hold + /// over that ground. Without this, any holder mints unlimited authority in + /// one step and the whole component is decorative. + DelegationNotMonotone { + slot: usize, + }, + /// The actor does not hold the bound fact at the required confidence. A + /// re-appraisal that lowered its own confidence while the proposal was in + /// flight arrives here: confidence is admission-only. + FactUnknown { + precondition: usize, + }, + /// The actor has no audience at all: unplaced for co-location, or outside a + /// channel it does not control. + NoAudience { + precondition: usize, + }, + /// The addressed subject is not inside that audience. A target that walked + /// out of the room while the proposal was in flight arrives here: the + /// preimage holds what the actor *is*, not the world it reaches. + CannotReach { + precondition: usize, + }, + /// The actor holds no commitment of that kind to the bound referent. + NotCommitted { + precondition: usize, + }, +} + +/// The band draw's whole preimage. Five fields. `command_id` is derived from +/// the world, the expected revision, the caller and the whole body, so the +/// payload does reach the draw through it: changing the speech or display text, +/// a magnitude or the revision re-rolls the band, and a proposer who can vary +/// those can grind for a band. That is not an authority hole: only Play submits +/// an act after genesis, and Play is trusted. `affordance` is the id carried by +/// the kernel-verified grant, so the draw cannot be steered by an affordance the +/// actor does not hold. +#[derive(Serialize)] +struct BandPreimage { + world_id: WorldId, + revision: u64, + command_id: CommandId, + affordance: AffordanceId, + band_count: usize, +} + +/// Catalog lookup, binding, admission, draw, lowering, event. Stages 1 through 4 +/// accumulate one complete rejection set and return it sorted before anything is +/// drawn or lowered, so nothing past the gate can fail on caller input. +/// +/// The entry arrives as a [`GrantedAffordance`], which only `require_granted` +/// can build: the grant check is the type, not a call a third caller might +/// forget. Nothing here reads `invocation.affordance`. +pub(super) fn exercise( + state: &WorldState, + command_id: CommandId, + actor: SubjectId, + granted: &GrantedAffordance<'_>, + invocation: &DecisionInvocation, +) -> Result { + let entry = granted.entry; + let mut rejections = Vec::new(); + + let components = super::scope_components(state, actor); + let authority = super::effective_authority(&components.authority, &components.delegated); + let bindings = bind_roles(state, actor, entry, invocation, &mut rejections); + check_preconditions(state, actor, &authority, entry, &bindings, &mut rejections); + check_proposals(entry, invocation, &mut rejections); + check_delegation(state, &authority, entry, &bindings, &mut rejections); + + if !rejections.is_empty() { + rejections.sort(); + return Err(KernelError::ActionRejected(rejections)); + } + + let band = select_band(state, command_id, granted.id, entry)?; + let operations = lower(entry, band, actor, state.header.now, invocation, &bindings)?; + let mut effects = if operations.is_empty() { + Vec::new() + } else { + // The same resolver, the same per-operation preconditions, the same + // conservation equation the declaration lane passes. + patch::resolve_patch( + state, + command_id, + &WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + }, + ) + .map_err(KernelError::PatchRejected)? + .operations + }; + + // The speech lowering: kernel-owned, not a slot, and unreachable by any + // proposer, band, or effect ceiling. The audience comes from the entry's one + // speech precondition, so a world's `whisper` and `proclaim` lower through + // the same two operations with a different audience and the kernel learns no + // genre. Addressing does not narrow the fan-out: a voice fills its audience. + let speech = match (&invocation.speech, entry.carries_speech) { + (Some(statement), true) => { + let fact = EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + state.header.world_id, + command_id, + &patch::DraftHandle::new(SPEECH_HANDLE), + Some(SPEECH_INDEX), + )); + let to = speech_audience(entry, &bindings)?; + effects.splice( + 0..0, + [ + patch::ResolvedOp::AssertClaim { + fact, + statement: statement.clone(), + by: actor, + }, + patch::ResolvedOp::Communicate { + speaker: actor, + fact, + to, + }, + ], + ); + Some(fact) + } + _ => None, + }; + // The display lowering: the same standing as speech, from the same + // allocation site under the second discriminator. It needs no entry + // field and reads no audience precondition: a body is visible to the room + // whatever the entry addresses, so `proclaim` down a horn still shrugs at + // whoever stands beside the speaker. + let display = invocation.display.as_ref().map(|statement| { + let fact = EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + state.header.world_id, + command_id, + &patch::DraftHandle::new(SPEECH_HANDLE), + Some(DISPLAY_INDEX), + )); + let at = usize::from(speech.is_some()) * 2; + effects.splice( + at..at, + [ + patch::ResolvedOp::AssertClaim { + fact, + statement: statement.clone(), + by: actor, + }, + patch::ResolvedOp::Display { actor, fact }, + ], + ); + fact + }); + + let revision = super::resolution_revision(state)?; + Ok(DecisionEvent { + id: EventId::for_command(command_id), + revision, + actor, + affordance: granted.id, + speech, + display, + band, + effects, + }) +} + +/// The synthetic handle every minted claim allocates under. It is synthesized +/// in an act, which declares nothing, so no world-declared handle can collide +/// with it. +const SPEECH_HANDLE: &str = "ghostlight.speech"; + +/// The speech index, passed as `derive_id`'s discriminator. It is `0` for every +/// invocation because one invocation carries one utterance; it exists so a +/// second minted claim needs no second allocation idiom. +const SPEECH_INDEX: &str = "0"; + +/// The display index: the second claim one invocation may mint, under the +/// same handle and allocation site as speech. +const DISPLAY_INDEX: &str = "1"; + +/// The audience a speech-carrying entry names. The declaration validator already +/// refused an entry with none (`SpeechWithoutAudience`) or two +/// (`AmbiguousSpeechAudience`), so anything else here is a corrupt catalog. +fn speech_audience( + entry: &Affordance, + bindings: &BTreeMap, +) -> Result { + entry + .preconditions + .iter() + .find_map(|precondition| match precondition { + Precondition::CanBroadcast { via } | Precondition::CanReach { via, .. } => { + bound_audience(via, bindings) + } + _ => None, + }) + .ok_or_else(|| KernelError::Invariant("a speech-carrying entry names no audience".into())) +} + +/// Stage 2. The acting subject is never a declared role: the kernel binds the +/// reserved name `actor` to it and refuses an invocation that tries to. A +/// binding that happens to name the actor through a declared role is legal and +/// unremarkable. +fn bind_roles( + state: &WorldState, + actor: SubjectId, + entry: &Affordance, + invocation: &DecisionInvocation, + rejections: &mut Vec, +) -> BTreeMap { + let declared: BTreeMap<&Role, RefKind> = entry + .roles + .iter() + .map(|spec| (&spec.role, spec.kind)) + .collect(); + let mut bound: BTreeMap = BTreeMap::new(); + let mut seen: BTreeSet<&Role> = BTreeSet::new(); + for binding in &invocation.bindings { + if binding.role.0 == patch::ACTOR_ROLE { + rejections.push(ActionMismatch::ActorRoleBound); + continue; + } + if !seen.insert(&binding.role) { + rejections.push(ActionMismatch::DuplicateRoleBinding { + role: binding.role.clone(), + }); + continue; + } + let Some(expected) = declared.get(&binding.role).copied() else { + rejections.push(ActionMismatch::UnknownRole { + role: binding.role.clone(), + }); + continue; + }; + let Some(actual) = live_kind(state, binding.target) else { + rejections.push(ActionMismatch::UnknownTarget { + role: binding.role.clone(), + }); + continue; + }; + let fits = match (expected, actual) { + (RefKind::Subject(None), RefKind::Subject(_)) => true, + (expected, actual) => expected == actual, + }; + if fits { + bound.insert(binding.role.clone(), binding.target); + } else { + rejections.push(ActionMismatch::TargetKindMismatch { + role: binding.role.clone(), + expected, + actual, + }); + } + } + for spec in &entry.roles { + if !seen.contains(&spec.role) { + rejections.push(ActionMismatch::UnboundRole { + role: spec.role.clone(), + }); + } + } + // The kernel's own binding, added after the caller's so nothing can shadow + // it: a slot that must land on the actor says `actor` and the proposer has + // no say. Without it, a levy's `Transfer` would need the proposer to name + // the payee, and an authorized collector could lawfully take a tax and send + // it to a friend. + bound.insert(Role(patch::ACTOR_ROLE.into()), Target::Subject(actor)); + bound +} + +/// What a target actually is in committed state. `None` means the target keys no +/// live partition in its namespace. +fn live_kind(state: &WorldState, target: Target) -> Option { + match target { + Target::Subject(subject_id) => state + .subjects + .get(&subject_id) + .map(|subject| RefKind::Subject(Some(subject.kind))), + Target::Entity(entity_id) => state + .entities + .get(&entity_id) + .map(|record| RefKind::Entity(record.kind)), + Target::Edge(edge_id) => state + .edges + .get(&edge_id) + .map(|_| RefKind::Edge(patch::EdgeKind::Route)), + } +} + +/// Stage 3, in declaration order, each failure carrying its index so a test can +/// name the exact precondition that refused. Role binding is this caller's job: +/// each declared `Precondition` is lowered through stage 2's bindings into a +/// `BoundPrecondition` and handed to the one evaluator. A precondition whose +/// role stage 2 left unbound is skipped here, because stage 2 already named it. +fn check_preconditions( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + entry: &Affordance, + bindings: &BTreeMap, + rejections: &mut Vec, +) { + for (index, precondition) in entry.preconditions.iter().enumerate() { + let Some(bound) = bind_precondition(precondition, bindings) else { + continue; + }; + if let Some(mismatch) = evaluate(state, actor, authority, index, &bound) { + rejections.push(mismatch); + } + } +} + +/// The catalog's role indirection lowered to canonical referents. `None` means +/// a role is unbound or bound to the wrong namespace, which stage 2 named. +fn bind_precondition( + precondition: &Precondition, + bindings: &BTreeMap, +) -> Option { + let place = |role: &Role| match bindings.get(role)? { + Target::Entity(entity_id) => Some(*entity_id), + _ => None, + }; + Some(match precondition { + Precondition::Present { at } => BoundPrecondition::Present { at: place(at)? }, + Precondition::Reachable { to, within } => BoundPrecondition::Reachable { + to: place(to)?, + within: *within, + }, + Precondition::Holds { resource, at_least } => BoundPrecondition::Holds { + resource: place(resource)?, + at_least: *at_least, + }, + Precondition::Authorized { over, kind } => BoundPrecondition::Authorized { + over: bindings.get(over).copied()?, + kind: kind.clone(), + }, + Precondition::HasStanding { grievance } => BoundPrecondition::HasStanding { + grievance: grievance.clone(), + }, + Precondition::Knows { fact, at_least } => BoundPrecondition::Knows { + fact: place(fact)?, + at_least: *at_least, + }, + Precondition::CanBroadcast { via } => BoundPrecondition::CanBroadcast { + via: bound_audience(via, bindings)?, + }, + Precondition::CanReach { subject, via } => BoundPrecondition::CanReach { + subject: match bindings.get(subject)? { + Target::Subject(subject_id) => *subject_id, + _ => return None, + }, + via: bound_audience(via, bindings)?, + }, + Precondition::Committed { to, kind } => BoundPrecondition::Committed { + to: match bindings.get(to)? { + Target::Subject(subject_id) => *subject_id, + _ => return None, + }, + kind: *kind, + }, + }) +} + +/// The one precondition reader, over referents that are already canonical. +/// Returns the complete set in declaration order; an empty set is "all hold". +/// The tick reads only its emptiness — an `ActionMismatch` never surfaces to +/// anyone from there. +pub(super) fn preconditions_hold( + state: &WorldState, + actor: SubjectId, + checks: &[BoundPrecondition], +) -> Vec { + let components = super::scope_components(state, actor); + let authority = super::effective_authority(&components.authority, &components.delegated); + checks + .iter() + .enumerate() + .filter_map(|(index, check)| evaluate(state, actor, &authority, index, check)) + .collect() +} + +/// One check against committed state. `index` is the position within the slice +/// the caller passed in, which is what every `precondition: usize` means. +fn evaluate( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + index: usize, + check: &BoundPrecondition, +) -> Option { + let holds = match check { + BoundPrecondition::Present { at } => { + return (state.positions.get(&actor).map(|position| position.place) != Some(*at)) + .then_some(ActionMismatch::ActorNotPresent { + precondition: index, + }); + } + BoundPrecondition::Reachable { to, within } => { + return (!reachable(state, actor, authority, *to, *within)).then_some( + ActionMismatch::TargetUnreachable { + precondition: index, + }, + ); + } + BoundPrecondition::Holds { resource, at_least } => { + state + .holdings + .get(&actor) + .and_then(|held| held.get(resource)) + .map_or(0, |quantity| quantity.0) + >= at_least.0 + } + BoundPrecondition::Authorized { over, kind } => { + return (!authority + .iter() + .any(|grant| &grant.kind == kind && super::covers(state, grant.over, *over))) + .then_some(ActionMismatch::NotAuthorized { + precondition: index, + }); + } + BoundPrecondition::HasStanding { grievance } => { + return (!state.redress.get(grievance).is_some_and(|forum| { + super::covers(state, forum.standing, Target::Subject(actor)) + })) + .then_some(ActionMismatch::NoStanding { + precondition: index, + }); + } + BoundPrecondition::Knows { fact, at_least } => { + return (!state + .knowledge + .get(&(actor, *fact)) + .is_some_and(|held| held.confidence >= *at_least)) + .then_some(ActionMismatch::FactUnknown { + precondition: index, + }); + } + BoundPrecondition::CanBroadcast { via } => { + return (!super::can_broadcast(state, actor, via)).then_some( + ActionMismatch::NoAudience { + precondition: index, + }, + ); + } + BoundPrecondition::CanReach { subject, via } => { + return (!super::audience(state, actor, via).contains(subject)).then_some( + ActionMismatch::CannotReach { + precondition: index, + }, + ); + } + // A linear scan of one subject's own small map. No key lookup is needed + // and none is offered, which is why a `CommitmentKey` never has to be + // guessable. + BoundPrecondition::Committed { to, kind } => { + return (!state.commitments.get(&actor).is_some_and(|held| { + held.values().any(|commitment| { + commitment.counterparty == Some(*to) && commitment.kind == *kind + }) + })) + .then_some(ActionMismatch::NotCommitted { + precondition: index, + }); + } + }; + (!holds).then_some(ActionMismatch::InsufficientHolding { + precondition: index, + }) +} + +/// The catalog's role indirection lowered to the canonical audience: the entry +/// names a role, the invoker binds a channel to it, and every reader of reach +/// sees one shape. `None` means the role is unbound, which stage 2 already named. +fn bound_audience(via: &AudienceSpec, bindings: &BTreeMap) -> Option { + match via { + AudienceSpec::Colocated => Some(Audience::Colocated), + AudienceSpec::Channel(role) => match bindings.get(role).copied() { + Some(Target::Entity(entity_id)) => Some(Audience::Channel(entity_id)), + _ => None, + }, + } +} + +/// Stage 4, beside the ceilings: an authority a slot would grant or revoke +/// must not exceed the actor's own. For a grant this is the monotonicity +/// envelope — no holder mints authority it does not itself hold. For a +/// revocation it is the same envelope read the other way: an actor may not +/// strip ground it holds no jurisdiction over, so revocation is not a lever +/// for reaching past one's own authority. Every slot is checked, not just the +/// drawn band's, for the same reason every ceiling is — the proposer commits +/// to a complete attempt and cannot see the band. +/// +/// The rule is action-lane only, and that is not two truths. The patch lane's +/// `GrantAuthority`/`RevokeAuthority` is admitted for Play; +/// monotonicity *is* the action lane's authority envelope, and both lanes +/// reach one `apply_operation` with the identical mutation. +fn check_delegation( + state: &WorldState, + authority: &BTreeSet, + entry: &Affordance, + bindings: &BTreeMap, + rejections: &mut Vec, +) { + for (index, slot) in entry.effect_slots.iter().enumerate() { + let kind = match &slot.op_kind { + ComponentOpKind::GrantAuthority { kind } + | ComponentOpKind::RevokeAuthority { kind } => kind, + _ => continue, + }; + let Some(over) = slot + .roles + .get(1) + .and_then(|role| bindings.get(role)) + .copied() + .and_then(authority_target_of) + else { + continue; + }; + if !authority.iter().any(|grant| { + &grant.kind == kind && super::covers(state, grant.over, over.as_referent()) + }) { + rejections.push(ActionMismatch::DelegationNotMonotone { slot: index }); + } + } +} + +/// The authority target a bound referent names. A route is jurisdictional +/// ground but never a grant's target, so a slot bound to one lowers to nothing. +fn authority_target_of(target: Target) -> Option { + match target { + Target::Subject(subject_id) => Some(AuthorityTarget::Subject(subject_id)), + Target::Entity(entity_id) => Some(AuthorityTarget::PlaceSubtree(entity_id)), + Target::Edge(_) => None, + } +} + +/// Dijkstra over the live route graph, admitting the open routes this subject +/// may traverse — the same `route_admits` rule the resolver applies to a +/// `Relocate`, so a subject with the right authority can plan a path through +/// its own restricted ground — and +/// relaxing in `EdgeId` order, pruning any path whose accumulated cost exceeds +/// `within`. Cost 0 — already standing there — succeeds; `Present` is the strict +/// form. An unplaced actor reaches nothing. +/// +/// Admission runs at commit against live state, so a route that closed while +/// the proposal was in flight makes this fail rather than letting a stale path +/// commit. +pub(super) fn reachable( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + destination: EntityId, + within: Cost, +) -> bool { + reach(state, actor, authority, destination, within, |place| { + state + .edges + .indexed(place..=place) + .into_iter() + .map(|(_, edge_id)| edge_id) + .collect() + }) +} + +/// What `reachable` was before the index: every edge asked at every settled place. +#[cfg(test)] +pub(super) fn reachable_by_scan( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + destination: EntityId, + within: Cost, +) -> bool { + reach(state, actor, authority, destination, within, |place| { + state + .edges + .iter() + .filter(|(_, record)| { + let (from, to) = record.endpoints(); + from == place || to == place + }) + .map(|(edge_id, _)| *edge_id) + .collect() + }) +} + +/// The search, given how the routes touching a place are found, in `EdgeId` +/// order. +fn reach( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + destination: EntityId, + within: Cost, + routes_at: impl Fn(EntityId) -> Vec, +) -> bool { + let Some(origin) = state.positions.get(&actor).map(|position| position.place) else { + return false; + }; + let mut best: BTreeMap = BTreeMap::from([(origin, 0)]); + let mut settled: BTreeSet = BTreeSet::new(); + let ceiling = u64::from(within.0); + loop { + let Some((place, cost)) = best + .iter() + .filter(|(place, _)| !settled.contains(place)) + .min_by_key(|(place, cost)| (**cost, **place)) + .map(|(place, cost)| (*place, *cost)) + else { + return false; + }; + if place == destination { + return true; + } + settled.insert(place); + let outbound: Vec<(EdgeId, EntityId, u64)> = routes_at(place) + .into_iter() + .map(|edge_id| (edge_id, &state.edges[&edge_id])) + .filter(|(_, record)| record.is_open()) + .filter_map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + let next = if from == place { + to + } else if to == place { + from + } else { + return None; + }; + patch::route_admits(state, authority, record.access(), next) + .then(|| (edge_id, next, u64::from(record.cost().0))) + }) + .collect(); + for (_, next, step) in outbound { + let total = cost + step; + if total <= ceiling && best.get(&next).is_none_or(|known| total < *known) { + best.insert(next, total); + } + } + } +} + +/// Stage 4. Every slot is checked, not just the ones the selected band names: +/// the proposer cannot see the band, so it commits to a complete attempt, and +/// checking every slot makes the ceiling total. +fn check_proposals( + entry: &Affordance, + invocation: &DecisionInvocation, + rejections: &mut Vec, +) { + let mut seen: BTreeSet = BTreeSet::new(); + for proposed in &invocation.proposed { + if !seen.insert(proposed.slot) { + rejections.push(ActionMismatch::DuplicateSlotProposal { + slot: proposed.slot, + }); + continue; + } + let Some(slot) = entry.effect_slots.get(proposed.slot) else { + rejections.push(ActionMismatch::UnknownSlot { + slot: proposed.slot, + }); + continue; + }; + match (slot.bounds, proposed.magnitude) { + (Bounds::None, Magnitude::None) => {} + (Bounds::Quantity(ceiling), Magnitude::Quantity(value)) => { + if value.0 == 0 { + rejections.push(ActionMismatch::ZeroMagnitude { + slot: proposed.slot, + }); + } else if value.0 > ceiling.0 { + rejections.push(ActionMismatch::MagnitudeOverCeiling { + slot: proposed.slot, + }); + } + } + (Bounds::Cost(ceiling), Magnitude::Cost(value)) => { + if value.0 == 0 { + rejections.push(ActionMismatch::ZeroMagnitude { + slot: proposed.slot, + }); + } else if value.0 > ceiling.0 { + rejections.push(ActionMismatch::MagnitudeOverCeiling { + slot: proposed.slot, + }); + } + } + _ => rejections.push(ActionMismatch::MagnitudeShapeMismatch { + slot: proposed.slot, + }), + } + } + for slot in 0..entry.effect_slots.len() { + if !seen.contains(&slot) { + rejections.push(ActionMismatch::SlotNotProposed { slot }); + } + } + // `Statement` is serde-transparent, so a value that arrived through + // deserialization rather than through the constructor is re-checked here + // rather than trusted. + match (&invocation.speech, entry.carries_speech) { + // A speech-carrying entry addresses someone; a silent turn that only + // displays still addresses the room, so it is not `SpeechRequired`. + (None, true) if invocation.display.is_none() => { + rejections.push(ActionMismatch::SpeechRequired); + } + (Some(_), false) => rejections.push(ActionMismatch::SpeechNotCarried), + (Some(speech), true) if !patch::is_canonical_text(speech.as_str()) => { + rejections.push(ActionMismatch::EmptySpeech); + } + _ => {} + } + if invocation + .display + .as_ref() + .is_some_and(|display| !patch::is_canonical_text(display.as_str())) + { + rejections.push(ActionMismatch::EmptyDisplay); + } +} + +/// The only entropy in the kernel: one digest, one modulo, one cumulative walk. +/// Modulo rather than rejection sampling — the bias is bounded by +/// `total_weight / 2^64`, and a rejection loop would need its counter in the +/// preimage, which is a second entropy shape for a rounding error nobody can +/// measure. +fn select_band( + state: &WorldState, + command_id: CommandId, + affordance: AffordanceId, + entry: &Affordance, +) -> Result { + let draw = digest(&BandPreimage { + world_id: state.header.world_id, + revision: state.revision, + command_id, + affordance, + band_count: entry.outcome_bands.len(), + })?; + let head = draw + .strip_prefix("sha256:") + .and_then(|hex| hex.get(..16)) + .and_then(|head| u64::from_str_radix(head, 16).ok()) + .ok_or_else(|| KernelError::Invariant("band draw digest is not hex".into()))?; + let total: u128 = entry + .outcome_bands + .iter() + .map(|band| u128::from(band.weight)) + .sum(); + if total == 0 { + return Err(KernelError::Invariant( + "affordance has no outcome band".into(), + )); + } + let mut position = u128::from(head) % total; + for (index, band) in entry.outcome_bands.iter().enumerate() { + let weight = u128::from(band.weight); + if position < weight { + return Ok(index); + } + position -= weight; + } + Err(KernelError::Invariant( + "band weights did not cover the draw".into(), + )) +} + +/// Stage 7. One arm per `ComponentOpKind`, every referent read from the slot's +/// roles resolved through the bindings, every magnitude from the proposal for +/// that slot. An empty band lowers to nothing. +fn lower( + entry: &Affordance, + band: usize, + actor: SubjectId, + now: FictionalMinutes, + invocation: &DecisionInvocation, + bindings: &BTreeMap, +) -> Result, KernelError> { + let malformed = || KernelError::Invariant("admitted affordance slot is malformed".into()); + let band = entry + .outcome_bands + .get(band) + .ok_or_else(|| KernelError::Invariant("selected band does not exist".into()))?; + let mut operations = Vec::new(); + for slot_index in &band.effects { + let slot = entry.effect_slots.get(*slot_index).ok_or_else(malformed)?; + let magnitude = invocation + .proposed + .iter() + .find(|proposed| proposed.slot == *slot_index) + .map(|proposed| proposed.magnitude) + .ok_or_else(malformed)?; + let target = |position: usize| -> Result { + slot.roles + .get(position) + .and_then(|role| bindings.get(role)) + .copied() + .ok_or_else(malformed) + }; + let subject = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Subject(subject_id) => Ok(patch::Ref::Existing(subject_id)), + _ => Err(malformed()), + } + }; + let entity = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Entity(entity_id) => Ok(patch::Ref::Existing(entity_id)), + _ => Err(malformed()), + } + }; + let edge = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Edge(edge_id) => Ok(patch::Ref::Existing(edge_id)), + _ => Err(malformed()), + } + }; + let quantity = || -> Result { + match magnitude { + Magnitude::Quantity(value) => Ok(value), + _ => Err(malformed()), + } + }; + let dependency = |position: usize| -> Result { + Ok(match target(position)? { + Target::Subject(subject_id) => { + patch::DependencyRef::Subject(patch::Ref::Existing(subject_id)) + } + Target::Entity(entity_id) => { + patch::DependencyRef::Resource(patch::Ref::Existing(entity_id)) + } + Target::Edge(edge_id) => patch::DependencyRef::Route(patch::Ref::Existing(edge_id)), + }) + }; + let grant_over = |position: usize| -> Result { + Ok(match target(position)? { + Target::Subject(subject_id) => { + patch::AuthorityTargetRef::Subject(patch::Ref::Existing(subject_id)) + } + Target::Entity(entity_id) => { + patch::AuthorityTargetRef::PlaceSubtree(patch::Ref::Existing(entity_id)) + } + Target::Edge(_) => return Err(malformed()), + }) + }; + operations.push(match &slot.op_kind { + // `due` is computed here, so a proposer cannot set one, and the + // pressure source is the acting subject, so it cannot be forged. + ComponentOpKind::CreateCommitment { + kind, + horizon, + period, + } => patch::ComponentOp::CreateCommitment { + subject: subject(0)?, + counterparty: Some(subject(1)?), + kind: *kind, + due: now.checked_add(*horizon).ok_or_else(malformed)?, + period: *period, + checks: Vec::new(), + // The world named the action; that name is what was promised. + // A proposer cannot supply the text, so it cannot promise more + // than the affordance carries. + statement: patch::Statement::new(format!("a promise made through {}", entry.kind.0)) + .ok_or_else(malformed)?, + }, + ComponentOpKind::AdvancePressure { by } => patch::ComponentOp::AdvancePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + by: *by, + }, + ComponentOpKind::ReducePressure { by } => patch::ComponentOp::ReducePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + by: *by, + }, + ComponentOpKind::ResolvePressure => patch::ComponentOp::ResolvePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + }, + ComponentOpKind::Relocate => patch::ComponentOp::Relocate { + subject: subject(0)?, + via: edge(1)?, + }, + ComponentOpKind::OpenRoute => patch::ComponentOp::OpenRoute { route: edge(0)? }, + ComponentOpKind::CloseRoute => patch::ComponentOp::CloseRoute { route: edge(0)? }, + ComponentOpKind::AlterCost => patch::ComponentOp::AlterCost { + route: edge(0)?, + cost: match magnitude { + Magnitude::Cost(value) => value, + _ => return Err(malformed()), + }, + }, + ComponentOpKind::Transfer => patch::ComponentOp::Transfer { + from: subject(0)?, + to: subject(1)?, + resource: entity(2)?, + qty: quantity()?, + }, + ComponentOpKind::Transform => patch::ComponentOp::Transform { + holder: subject(0)?, + from_resource: entity(1)?, + into_resource: entity(2)?, + qty: quantity()?, + }, + ComponentOpKind::Consume => patch::ComponentOp::Consume { + holder: subject(0)?, + resource: entity(1)?, + qty: quantity()?, + }, + ComponentOpKind::Bind => patch::ComponentOp::Bind { + subject: subject(0)?, + target: dependency(1)?, + }, + ComponentOpKind::Release => patch::ComponentOp::Release { + subject: subject(0)?, + target: dependency(1)?, + }, + ComponentOpKind::GrantAuthority { kind } => patch::ComponentOp::GrantAuthority { + holder: subject(0)?, + grant: patch::AuthorityGrantRef { + kind: kind.clone(), + over: grant_over(1)?, + }, + }, + ComponentOpKind::RevokeAuthority { kind } => patch::ComponentOp::RevokeAuthority { + holder: subject(0)?, + grant: patch::AuthorityGrantRef { + kind: kind.clone(), + over: grant_over(1)?, + }, + }, + ComponentOpKind::InstallIncumbent { office } => patch::ComponentOp::InstallIncumbent { + institution: subject(0)?, + office: office.clone(), + incumbent: subject(1)?, + }, + ComponentOpKind::VacateOffice { office } => patch::ComponentOp::VacateOffice { + institution: subject(0)?, + office: office.clone(), + }, + ComponentOpKind::AcquireKnowledge { confidence } => { + patch::ComponentOp::AcquireKnowledge { + subject: subject(0)?, + fact: entity(1)?, + source: patch::AuthoredSource::Witnessed, + confidence: *confidence, + } + } + ComponentOpKind::Witness { confidence } => patch::ComponentOp::Witness { + fact: entity(0)?, + place: entity(1)?, + confidence: *confidence, + }, + ComponentOpKind::Forget => patch::ComponentOp::Forget { + subject: subject(0)?, + fact: entity(1)?, + }, + }); + } + Ok(operations) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::custody_tests::custody_kernel; + use crate::patch::{ + AffordanceDeclaration, ComponentOp, DraftHandle, OutcomeBand, Ref as PatchRef, ResolvedOp, + RoleSpec, + }; + use crate::tests::{ + ADMIT_KIND, COMMAND_KIND, Civic, LEVY_KIND, OPENING_BALANCE, SEIZURE_GRIEVANCE, Topology, + WARDEN_OFFICE, act, affordance_named, authority_kind, civic_world, + command, custody_world, grant_to, grievance, office, operations, over_place, + over_subject, play_caller, reject_play, submit_play, tick_body, + }; + use crate::{ + AffordanceKindName, AuthenticatedCaller, AuthoredSource, CommandBody, Confidence, + Declaration, EffectSlot, EntityKind, ProposedEffect, RoleBinding, Statement, CommitReceipt, + WorldEffect, WorldKernel, WorldPatch, WorldSnapshot, apply_effect, + }; + use std::collections::BTreeSet; + + struct Bench { + kernel: WorldKernel, + active: WorldSnapshot, + carry: AffordanceId, + clerk: SubjectId, + keeper: SubjectId, + tithe: EntityId, + ingot: EntityId, + yard: EntityId, + gate: EntityId, + shutter: EdgeId, + } + + fn bench(title: &str) -> Bench { + let mut kernel = custody_kernel(title); + let (topology, custody, active) = custody_world(&mut kernel); + let carry = affordance_named(&active, "carry"); + Bench { + kernel, + active, + carry, + clerk: custody.holder, + keeper: custody.counterparty, + tithe: custody.tithe, + ingot: custody.ingot, + yard: topology.yard, + gate: topology.gate, + shutter: topology.shutter, + } + } + + /// `exercise` only accepts a grant the kernel resolved, so a test walks the + /// same gate `reduce` does rather than reaching into the catalog. + fn draw_once( + state: &WorldState, + command_id: CommandId, + actor: SubjectId, + invocation: &DecisionInvocation, + ) -> Result { + let granted = crate::require_granted(state, actor, invocation.affordance)?; + exercise(state, command_id, actor, &granted, invocation) + } + + /// Commit `invocation` as the first command whose derived id draws `band`. + /// A band is a pure function of the pre-commit state and the command id, + /// and a command's id derives from the revision it targets, so a test + /// reaches a band by committing ordinary ticks until the id it would + /// carry draws it. + fn act_drawing( + kernel: &mut WorldKernel, + actor: SubjectId, + invocation: &DecisionInvocation, + band: usize, + ) -> CommitReceipt { + for _ in 0..256 { + let snapshot = kernel.snapshot().unwrap(); + let envelope = command( + &snapshot, + play_caller(), + CommandBody::Act { + actor, + invocation: invocation.clone(), + }, + ); + let draws = draw_once(&kernel.state, envelope.id(), actor, invocation) + .expect("the invocation is admissible") + .band; + if draws == band { + return kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the invocation commits"); + } + submit_play(kernel, &snapshot, tick_body(1)); + } + panic!("a two-band entry reaches both bands within 256 revisions"); + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + impl Bench { + /// A Carry the clerk proposes. The actor is never a role, so a Carry + /// that moves the actor's own goods binds `from` to its own id. + fn carry_of(&self, qty: u64, place: EntityId, resource: EntityId) -> DecisionInvocation { + DecisionInvocation { + affordance: self.carry, + bindings: vec![ + binding("from", Target::Subject(self.clerk)), + binding("recipient", Target::Subject(self.keeper)), + binding("place", Target::Entity(place)), + binding("resource", Target::Entity(resource)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(qty)), + }], + speech: None, + display: None, + } + } + + fn carry(&self, qty: u64, place: EntityId) -> DecisionInvocation { + self.carry_of(qty, place, self.tithe) + } + + fn try_exercise( + &self, + invocation: &DecisionInvocation, + ) -> Result { + draw_once( + &self.kernel.state, + CommandId::issue(), + self.clerk, + invocation, + ) + } + + fn rejections(&self, invocation: &DecisionInvocation) -> Vec { + match self.try_exercise(invocation) { + Err(KernelError::ActionRejected(rejected)) => rejected, + other => panic!("expected an action rejection, got {other:?}"), + } + } + + fn commit(&mut self, invocation: DecisionInvocation) -> CommitReceipt { + act(&mut self.kernel, self.clerk, invocation).expect("the invocation commits") + } + + fn held(&self, holder: SubjectId) -> u64 { + self.kernel + .state + .holdings + .get(&holder) + .and_then(|held| held.get(&self.tithe)) + .map_or(0, |quantity| quantity.0) + } + + /// The same Carry attempt against a sibling entry: one dial moved, one + /// name. The catalog is declared structure, so a variant is declared rather + /// than patched into committed state. + fn variant(&self, invocation: &DecisionInvocation, kind: &str) -> DecisionInvocation { + DecisionInvocation { + affordance: affordance_named(&self.active, kind), + ..invocation.clone() + } + } + + fn refresh(&mut self) { + self.active = self.kernel.snapshot().unwrap(); + } + } + + #[test] + fn a_missing_present_precondition_names_itself() { + let bench = bench("Present"); + let before = bench.kernel.state.clone(); + let before_events = bench.kernel.events(); + + // The clerk stands in the yard, so a Carry bound to the gate fails the + // first precondition and nothing else. + assert_eq!( + bench.rejections(&bench.carry(1, bench.gate)), + vec![ActionMismatch::ActorNotPresent { precondition: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.holdings, before.holdings); + assert_eq!(bench.kernel.events(), before_events); + } + + #[test] + fn spending_more_than_held_fails_the_holds_precondition() { + let bench = bench("Holds"); + let greedy = bench.variant(&bench.carry(1, bench.yard), "carry_greedy"); + assert_eq!( + bench.rejections(&greedy), + vec![ActionMismatch::InsufficientHolding { precondition: 1 }] + ); + + // Absence is zero, so a resource the clerk holds none of gives the same + // name at the boundary rather than a second one. + let ingot = bench.variant(&bench.carry_of(1, bench.yard, bench.ingot), "carry_holds"); + assert_eq!( + bench.rejections(&ingot), + vec![ActionMismatch::InsufficientHolding { precondition: 0 }] + ); + } + + /// `at_least` is inclusive: holding exactly the threshold passes. The clerk + /// spends down to one ingot-equivalent, and `carry_holds` asks for one. + #[test] + fn holding_exactly_the_threshold_satisfies_holds() { + let mut bench = bench("HoldsBoundary"); + for _ in 0..2 { + bench.commit(bench.carry(3, bench.yard)); + bench.refresh(); + } + assert_eq!(bench.held(bench.clerk), OPENING_BALANCE - 6); + let exact = bench.variant(&bench.carry(1, bench.yard), "carry_holds"); + bench + .try_exercise(&exact) + .expect("one held satisfies at_least one"); + + bench.commit(bench.carry(1, bench.yard)); + bench.refresh(); + assert_eq!(bench.held(bench.clerk), 0); + assert_eq!( + bench.rejections(&bench.variant(&bench.carry(1, bench.yard), "carry_holds")), + vec![ActionMismatch::InsufficientHolding { precondition: 0 }] + ); + } + + #[test] + fn a_reachable_precondition_reads_only_open_public_routes() { + let mut bench = bench("Reachable"); + // Yard to gate over open public routes is the ramp (12) plus the span + // (7): the shutter is closed and the toll stair is restricted. A budget + // of NEAR_REACH covers only the shutter, FAR_REACH covers the two-hop + // path. + let attempt = bench.carry(1, bench.gate); + let near = bench.variant(&attempt, "carry_near"); + let far = bench.variant(&attempt, "carry_far"); + assert_eq!( + bench.rejections(&near), + vec![ActionMismatch::TargetUnreachable { precondition: 0 }] + ); + assert!(bench.try_exercise(&far).is_ok()); + + // Opening the one-hop shutter shortens the path, and closing it again + // restores the two-hop cost: the check reads the live graph rather than + // anything the proposal was bound against. + let before = bench.kernel.snapshot().unwrap(); + submit_play( + &mut bench.kernel, + &before, + operations(vec![ComponentOp::OpenRoute { + route: PatchRef::Existing(bench.shutter), + }]), + ); + bench.refresh(); + assert!(bench.try_exercise(&near).is_ok()); + + let before = bench.kernel.snapshot().unwrap(); + submit_play( + &mut bench.kernel, + &before, + operations(vec![ComponentOp::CloseRoute { + route: PatchRef::Existing(bench.shutter), + }]), + ); + bench.refresh(); + assert_eq!( + bench.rejections(&near), + vec![ActionMismatch::TargetUnreachable { precondition: 0 }] + ); + } + + #[test] + fn an_unbound_or_miskinded_role_is_rejected_with_the_complete_set() { + let bench = bench("Roles"); + let mut invocation = bench.carry(1, bench.yard); + // Drop `recipient`, add an undeclared role, and bind `resource` to a + // place: one rejection carrying all three, sorted. + invocation.bindings = vec![ + binding("from", Target::Subject(bench.clerk)), + binding("place", Target::Entity(bench.yard)), + binding("resource", Target::Entity(bench.yard)), + binding("porter", Target::Subject(bench.keeper)), + ]; + let mut expected = vec![ + ActionMismatch::UnboundRole { + role: Role("recipient".into()), + }, + ActionMismatch::UnknownRole { + role: Role("porter".into()), + }, + ActionMismatch::TargetKindMismatch { + role: Role("resource".into()), + expected: RefKind::Entity(EntityKind::Resource), + actual: RefKind::Entity(EntityKind::Place), + }, + ]; + expected.sort(); + assert_eq!(bench.rejections(&invocation), expected); + } + + #[test] + fn a_duplicated_or_unknown_binding_target_is_rejected() { + let bench = bench("Bindings"); + let mut twice = bench.carry(1, bench.yard); + twice + .bindings + .push(binding("resource", Target::Entity(bench.tithe))); + assert!( + bench + .rejections(&twice) + .contains(&ActionMismatch::DuplicateRoleBinding { + role: Role("resource".into()) + }) + ); + + let mut unknown = bench.carry(1, bench.yard); + unknown.bindings[3] = binding("resource", Target::Entity(EntityId::issue())); + assert!( + bench + .rejections(&unknown) + .contains(&ActionMismatch::UnknownTarget { + role: Role("resource".into()) + }) + ); + } + + #[test] + fn a_magnitude_over_its_slot_ceiling_is_rejected_and_within_it_commits() { + let mut bench = bench("Ceiling"); + assert_eq!( + bench.rejections(&bench.carry(4, bench.yard)), + vec![ActionMismatch::MagnitudeOverCeiling { slot: 0 }] + ); + + let clerk_before = bench.held(bench.clerk); + let keeper_before = bench.held(bench.keeper); + let receipt = bench.commit(bench.carry(3, bench.yard)); + assert!(receipt.resulting_revision > 0); + assert_eq!(bench.held(bench.clerk), clerk_before - 3); + assert_eq!(bench.held(bench.keeper), keeper_before + 3); + assert_eq!( + bench.held(bench.clerk) + bench.held(bench.keeper), + clerk_before + keeper_before, + "the conserved total is unchanged" + ); + } + + #[test] + fn a_magnitude_of_the_wrong_shape_or_zero_is_rejected() { + let bench = bench("Shape"); + for magnitude in [Magnitude::Cost(Cost(2)), Magnitude::None] { + let mut invocation = bench.carry(1, bench.yard); + invocation.proposed[0].magnitude = magnitude; + assert_eq!( + bench.rejections(&invocation), + vec![ActionMismatch::MagnitudeShapeMismatch { slot: 0 }] + ); + } + assert_eq!( + bench.rejections(&bench.carry(0, bench.yard)), + vec![ActionMismatch::ZeroMagnitude { slot: 0 }] + ); + } + + #[test] + fn every_slot_must_be_proposed_exactly_once() { + let bench = bench("Slots"); + let mut missing = bench.carry(1, bench.yard); + missing.proposed.clear(); + assert_eq!( + bench.rejections(&missing), + vec![ActionMismatch::SlotNotProposed { slot: 0 }] + ); + + let mut twice = bench.carry(1, bench.yard); + twice.proposed.push(twice.proposed[0]); + assert_eq!( + bench.rejections(&twice), + vec![ActionMismatch::DuplicateSlotProposal { slot: 0 }] + ); + + let mut unknown = bench.carry(1, bench.yard); + unknown.proposed.push(ProposedEffect { + slot: 7, + magnitude: Magnitude::None, + }); + assert_eq!( + bench.rejections(&unknown), + vec![ActionMismatch::UnknownSlot { slot: 7 }] + ); + } + + #[test] + fn speech_is_required_exactly_when_the_entry_carries_it() { + let bench = bench("Speech"); + let mut spoken_carry = bench.carry(1, bench.yard); + spoken_carry.speech = Some(Statement::new("Take it.").unwrap()); + assert_eq!( + bench.rejections(&spoken_carry), + vec![ActionMismatch::SpeechNotCarried] + ); + + let speak = affordance_named(&bench.active, "speak"); + let mut silent_speak = DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + display: None, + }; + assert_eq!( + bench.rejections(&silent_speak), + vec![ActionMismatch::SpeechRequired] + ); + + // `Statement` is serde-transparent, so a value that arrived without the + // constructor is re-checked here rather than trusted. + silent_speak.speech = Some(serde_json::from_str::("\" \"").unwrap()); + assert_eq!( + bench.rejections(&silent_speak), + vec![ActionMismatch::EmptySpeech] + ); + } + + #[test] + fn the_same_command_id_always_selects_the_same_band() { + let bench = bench("Bands"); + // Three equally weighted bands, so the draw alone decides. + let invocation = bench.variant(&bench.carry(1, bench.yard), "carry_chance"); + let draw = |command_id: CommandId, invocation: &DecisionInvocation| { + draw_once(&bench.kernel.state, command_id, bench.clerk, invocation) + .expect("the invocation is admissible") + .band + }; + + let command_id = CommandId::issue(); + let fixed = draw(command_id, &invocation); + for _ in 0..100 { + assert_eq!(draw(command_id, &invocation), fixed); + } + + // No caller-supplied value influences the draw: not a binding order, + // not a magnitude. + let mut reordered = invocation.clone(); + reordered.bindings.reverse(); + assert_eq!(draw(command_id, &reordered), fixed); + let mut heavier = invocation.clone(); + heavier.proposed[0].magnitude = Magnitude::Quantity(Quantity(3)); + assert_eq!(draw(command_id, &heavier), fixed); + + // The command id is the only varying term at one revision. + let mut seen = BTreeSet::new(); + for _ in 0..64 { + seen.insert(draw(CommandId::issue(), &invocation)); + } + assert!( + seen.len() > 1, + "varying only the command id must reach more than one band" + ); + } + + #[test] + fn a_zero_effect_band_commits_nothing_but_the_event() { + let mut bench = bench("EmptyBand"); + let idle = bench.variant(&bench.carry(3, bench.yard), "carry_idle"); + + let holdings = bench.kernel.state.holdings.clone(); + let positions = bench.kernel.state.positions.clone(); + let edges = bench.kernel.state.edges.clone(); + let revision = bench.kernel.state.revision; + + let event = bench + .try_exercise(&idle) + .expect("an empty band is admissible"); + assert_eq!(event.band, 0); + assert!(event.effects.is_empty()); + + let receipt = bench.commit(idle); + assert!(receipt.resulting_revision > 0); + assert_eq!(bench.kernel.state.holdings, holdings); + assert_eq!(bench.kernel.state.positions, positions); + assert_eq!(bench.kernel.state.edges, edges); + assert_eq!(bench.kernel.events().len(), 1); + assert_eq!(bench.kernel.state.revision, revision + 1); + } + + #[test] + fn a_committed_event_carries_the_exact_lowered_operations() { + let mut bench = bench("Lowering"); + let receipt = bench.commit(bench.carry(2, bench.yard)); + assert!(receipt.resulting_revision > 0); + let events = bench.kernel.events(); + let event = events.last().expect("the committed event"); + assert_eq!( + event.effects, + vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(2), + }] + ); + } + + /// Soul: contract 10's discriminating case. `a_zero_effect_band_commits_ + /// nothing_but_the_event` proves an empty band commits nothing, and + /// `a_committed_event_carries_the_exact_lowered_operations` proves a + /// one-slot entry lowers what it declares — neither separates a slot the + /// proposer offered from a slot the draw admitted. This entry declares two + /// slots on disjoint bands and proposes both within their ceilings: only + /// the drawn band's slot may appear in `event.effects`, and the other slot + /// must move no partition. Both bands are exercised, so neither branch + /// passes by never being taken. + #[test] + fn soul_only_the_selected_bands_effects_are_committed() { + let mut bench = bench("SelectedBand"); + let split_id = affordance_named(&bench.active, "carry_split"); + let split = DecisionInvocation { + affordance: split_id, + bindings: vec![ + binding("from", Target::Subject(bench.clerk)), + binding("recipient", Target::Subject(bench.keeper)), + binding("place", Target::Entity(bench.yard)), + binding("resource", Target::Entity(bench.tithe)), + ], + proposed: vec![ + ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }, + ProposedEffect { + slot: 1, + magnitude: Magnitude::Quantity(Quantity(1)), + }, + ], + speech: None, + display: None, + }; + let mut seen: BTreeSet = BTreeSet::new(); + + for wanted in [0usize, 1] { + // The draw is a pure function of the pre-commit state and the + // command id; `act_drawing` finds the revision whose id reaches it. + let before_clerk = bench.held(bench.clerk); + let before_keeper = bench.held(bench.keeper); + let receipt = act_drawing(&mut bench.kernel, bench.clerk, &split, wanted); + assert!(receipt.resulting_revision > 0); + bench.refresh(); + let event = bench + .kernel + .events() + .last() + .expect("the committed event") + .clone(); + assert_eq!(event.band, wanted); + seen.insert(event.band); + match event.band { + 0 => { + assert_eq!( + event.effects, + vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(2), + }] + ); + assert_eq!(bench.held(bench.clerk), before_clerk - 2); + assert_eq!(bench.held(bench.keeper), before_keeper + 2); + } + 1 => { + assert_eq!( + event.effects, + vec![ResolvedOp::Consume { + holder: bench.clerk, + resource: bench.tithe, + qty: Quantity(1), + }] + ); + assert_eq!(bench.held(bench.clerk), before_clerk - 1); + assert_eq!(bench.held(bench.keeper), before_keeper); + } + other => panic!("the entry declares two bands, drew {other}"), + } + } + + assert_eq!( + seen.len(), + 2, + "both declared bands must be reachable across command ids" + ); + } + + /// Soul: `RoleSpec` persists inside the catalog, so `RefKind` had to become + /// serializable this pass. An internally tagged newtype over an `Option` + /// does not serialize; this one is adjacently tagged, and a stored + /// `Subject(None)` role is what would fault on first write if that were + /// wrong. The fixture catalog carries four such roles. + #[test] + fn soul_a_stored_role_spec_over_an_optional_subject_kind_round_trips() { + let bench = bench("OptionalSubjectKind"); + let entry = bench + .kernel + .state + .affordance_catalog + .get(&bench.carry) + .expect("the fixture entry"); + assert!( + entry + .roles + .iter() + .any(|spec| spec.kind == RefKind::Subject(None)) + ); + + // The affordance document round-trips through the `to_vec_named` path the + // state digest hashes. + let catalog = rmp_serde::to_vec_named(&bench.kernel.state.affordance_catalog) + .expect("the affordance document encodes"); + let decoded: std::collections::BTreeMap<_, crate::Affordance> = + rmp_serde::from_slice(&catalog).expect("the affordance document decodes"); + assert_eq!(decoded, *bench.kernel.state.affordance_catalog.as_map()); + assert!(bench.kernel.state.full_state_digest().is_ok()); + } + + #[test] + fn a_forged_band_or_forged_effect_does_not_apply() { + let bench = bench("ForgedAction"); + let command_id = CommandId::issue(); + let invocation = bench.carry(2, bench.yard); + let honest = draw_once(&bench.kernel.state, command_id, bench.clerk, &invocation).unwrap(); + let caller = play_caller(); + + for forged in [ + DecisionEvent { + band: 3, + ..honest.clone() + }, + DecisionEvent { + effects: vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(OPENING_BALANCE), + }], + ..honest.clone() + }, + ] { + let mut candidate = bench.kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, bench.kernel.state); + } + + // An event naming another actor does not apply either: the actor is + // read from the event, so a swapped actor is re-derived for the swap. + let mut candidate = bench.kernel.state.clone(); + assert!( + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation: invocation.clone(), + event: DecisionEvent { + actor: bench.keeper, + ..honest.clone() + }, + }, + ) + .is_err() + ); + assert_eq!(candidate, bench.kernel.state); + + // The honest event still applies through the same arm. + let mut candidate = bench.kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation: invocation.clone(), + event: honest, + }, + ) + .unwrap(); + assert_ne!(candidate.holdings, bench.kernel.state.holdings); + } + + #[test] + fn the_kernel_speak_entry_commits_its_utterance_and_no_operation() { + let mut kernel = custody_kernel("SpeakEntry"); + let _topology = kernel.snapshot().unwrap(); + let active = kernel.snapshot().unwrap(); + let speak = affordance_named(&active, "speak"); + let human = active + .subjects + .iter() + .find(|subject| subject.label == "The Human") + .expect("the human subject") + .id; + let holdings = kernel.state.holdings.clone(); + let receipt = act( + &mut kernel, + human, + DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("I open the door.").unwrap()), + display: None, + }, + ) + .expect("the Speak entry commits"); + assert!(receipt.resulting_revision > 0); + let events = kernel.events(); + let event = events.last().unwrap(); + assert_eq!(event.band, 0); + // The two the speech lowering prepends, and nothing from a slot. + assert_eq!(event.effects.len(), 2); + assert_eq!( + crate::tests::spoken(&kernel.state, event), + Some("I open the door.") + ); + assert_eq!(kernel.state.holdings, holdings); + } + + /// The civic bench: one world where an institution holds jurisdiction over + /// a hall, a person holds the same jurisdiction only through an office, and + /// two more people stand inside and outside that ground. + struct Civics { + kernel: WorldKernel, + active: WorldSnapshot, + topology: Topology, + civic: Civic, + } + + fn civics(title: &str) -> Civics { + let mut kernel = custody_kernel(title); + let (topology, civic, active) = civic_world(&mut kernel); + Civics { + kernel, + active, + topology, + civic, + } + } + + impl Civics { + fn refresh(&mut self) { + self.active = self.kernel.snapshot().unwrap(); + } + + fn call( + &self, + kind: &str, + bindings: Vec, + proposed: Vec, + speech: Option, + ) -> DecisionInvocation { + DecisionInvocation { + affordance: affordance_named(&self.active, kind), + bindings, + proposed, + speech, + display: None, + } + } + + /// A levy of `qty` from `payer`, always paid to the actor: the payee is + /// the reserved role, so it is not a binding the caller supplies. + fn levy(&self, payer: SubjectId, qty: u64) -> DecisionInvocation { + self.call( + "levy", + vec![ + binding("payer", Target::Subject(payer)), + binding("resource", Target::Entity(self.civic.grain)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(qty)), + }], + None, + ) + } + + fn delegate(&self, deputy: SubjectId, ground: EntityId) -> DecisionInvocation { + self.call( + "delegate", + vec![ + binding("deputy", Target::Subject(deputy)), + binding("ground", Target::Entity(ground)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + /// Commands a subordinate to traverse a route: the fixture's one + /// `Relocate`-lowering affordance, gated by `command` authority over + /// the subordinate rather than by the subordinate's own consent. + fn deploy(&self, subordinate: SubjectId, via: EdgeId) -> DecisionInvocation { + self.call( + "deploy", + vec![ + binding("subordinate", Target::Subject(subordinate)), + binding("via", Target::Edge(via)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + /// Strips `holder`'s `levy` grant over `ground`: the fixture's one + /// `RevokeAuthority`-lowering affordance, carrying no precondition of + /// its own so a rejection can only be the action lane's revocation + /// envelope. + fn revoke(&self, holder: SubjectId, ground: EntityId) -> DecisionInvocation { + self.call( + "revoke", + vec![ + binding("holder", Target::Subject(holder)), + binding("ground", Target::Entity(ground)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + fn try_as( + &self, + actor: SubjectId, + invocation: &DecisionInvocation, + ) -> Result { + draw_once( + &self.kernel.state, + CommandId::issue(), + actor, + invocation, + ) + } + + fn rejected_as( + &self, + actor: SubjectId, + invocation: &DecisionInvocation, + ) -> Vec { + match self.try_as(actor, invocation) { + Err(KernelError::ActionRejected(rejected)) => rejected, + other => panic!("expected an action rejection, got {other:?}"), + } + } + + fn commit_as(&mut self, actor: SubjectId, invocation: DecisionInvocation) -> CommitReceipt { + let receipt = act(&mut self.kernel, actor, invocation).expect("the invocation commits"); + self.refresh(); + receipt + } + + fn admit(&mut self, ops: Vec) { + let before = self.kernel.snapshot().unwrap(); + let receipt = submit_play(&mut self.kernel, &before, operations(ops)); + assert!(receipt.resulting_revision > 0); + self.refresh(); + } + + fn refuse(&mut self, ops: Vec) -> Vec { + let before = self.kernel.snapshot().unwrap(); + reject_play(&mut self.kernel, &before, operations(ops)) + } + } + + /// Contract 7's third rejection: commanding outside authority, with the + /// exact failed precondition and no allocation. + #[test] + fn an_unauthorized_actor_names_the_failed_precondition() { + let bench = civics("Unauthorized"); + let before = bench.kernel.state.clone(); + let before_events = bench.kernel.events(); + assert_eq!( + bench.rejected_as(bench.civic.farmer, &bench.levy(bench.civic.reeve, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.holdings, before.holdings); + assert_eq!(bench.kernel.events(), before_events); + } + + /// A place jurisdiction reaches everything under it and nothing else, and + /// the answer is read live: a target that walks out of the subtree stops + /// being authorized without any digest moving. + #[test] + fn place_jurisdiction_reaches_a_containment_subtree_and_stops_at_its_edge() { + let mut bench = civics("Subtree"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + + // The farmer stands in the chamber, whose container is the hall. + assert!(bench.try_as(treasury, &bench.levy(farmer, 1)).is_ok()); + + // The pedlar stands on the road, outside the hall entirely, and an + // unplaced subject is covered by no place target. + assert_eq!( + bench.rejected_as(treasury, &bench.levy(bench.civic.outsider, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + let unplaced = *bench + .kernel + .state + .subjects + .keys() + .find(|subject_id| !bench.kernel.state.positions.contains_key(subject_id)) + .expect("the genesis world declares an unplaced subject"); + assert_eq!( + bench.rejected_as(treasury, &bench.levy(unplaced, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // Walking the farmer out of the hall flips the same invocation, and a + // grant naming the subject directly authorizes it again. + bench.admit(vec![ + ComponentOp::Relocate { + subject: PatchRef::Existing(farmer), + via: PatchRef::Existing(bench.civic.passage), + }, + ComponentOp::Relocate { + subject: PatchRef::Existing(farmer), + via: PatchRef::Existing(bench.civic.causeway), + }, + ]); + assert_eq!( + bench.rejected_as(treasury, &bench.levy(farmer, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + bench.admit(vec![grant_to(treasury, LEVY_KIND, over_subject(farmer))]); + assert!(bench.try_as(treasury, &bench.levy(farmer, 1)).is_ok()); + } + + /// An office lends jurisdiction its holder does not own, and vacating takes + /// it back: the act is refused at admission. + #[test] + fn office_delegation_grants_and_vacating_revokes() { + let mut bench = civics("Office"); + let reeve = bench.civic.reeve; + let farmer = bench.civic.farmer; + assert!(bench.kernel.state.authority.get(&reeve).is_none()); + assert!(bench.try_as(reeve, &bench.levy(farmer, 1)).is_ok()); + + // The vacated office lends nothing: the act is refused at admission. + let invocation = bench.levy(farmer, 1); + bench.admit(vec![ComponentOp::VacateOffice { + institution: PatchRef::Existing(bench.civic.treasury), + office: office(WARDEN_OFFICE), + }]); + + let holdings = bench.kernel.state.holdings.clone(); + let error = act(&mut bench.kernel, reeve, invocation).unwrap_err(); + assert!(matches!(error, KernelError::ActionRejected(_)), "{error:?}"); + assert_eq!(bench.kernel.state.holdings, holdings); + assert_eq!( + bench.rejected_as(reeve, &bench.levy(farmer, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + } + + /// The reserved role in both directions: an invocation may not bind it, and + /// a catalog entry may not declare it. + #[test] + fn a_levy_cannot_be_directed_away_from_the_actor() { + let bench = civics("ActorRole"); + let mut redirected = bench.levy(bench.civic.farmer, 1); + redirected + .bindings + .push(binding("actor", Target::Subject(bench.civic.outsider))); + assert_eq!( + bench.rejected_as(bench.civic.treasury, &redirected), + vec![ActionMismatch::ActorRoleBound] + ); + + // The declaration half runs at genesis, so it runs against a fresh world. + let mut draft = custody_kernel("ReservedRole"); + let before = draft.snapshot().unwrap(); + let handle = DraftHandle::new("thief"); + let rejected = reject_play( + &mut draft, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: handle.clone(), + kind: AffordanceKindName("thief".into()), + roles: vec![RoleSpec { + role: Role("actor".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert!(rejected.contains(&crate::Mismatch::ReservedRole { handle })); + } + + /// The two rejection lanes stay distinguishable: an over-levy inside its + /// declared ceiling passes every affordance check and dies in the ledger. + #[test] + fn an_over_levy_fails_in_the_ledger_not_in_the_contract() { + let bench = civics("OverLevy"); + let error = bench + .try_as(bench.civic.treasury, &bench.levy(bench.civic.farmer, 9)) + .unwrap_err(); + let KernelError::PatchRejected(rejected) = error else { + panic!("an over-levy is a ledger rejection"); + }; + assert_eq!( + rejected, + vec![crate::Mismatch::InsufficientCustody { operation: 0 }] + ); + } + + /// A delegated grant may not exceed the granter's own, and the grant it + /// does mint is still subject to disjointness. + #[test] + fn a_delegated_grant_may_not_exceed_the_granter() { + let mut bench = civics("Monotone"); + let treasury = bench.civic.treasury; + let outsider = bench.civic.outsider; + + // The treasury commands the road but does not levy it, so the + // precondition passes and the delegation alone is refused. + let road = bench.topology.road; + bench.admit(vec![grant_to(treasury, COMMAND_KIND, over_place(road))]); + let outside = bench.delegate(outsider, road); + assert_eq!( + bench.rejected_as(treasury, &outside), + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + + // The chamber is inside it, so the same act commits and the deputy can + // then levy there. + let inside = bench.delegate(outsider, bench.civic.chamber); + assert!(bench.commit_as(treasury, inside).resulting_revision > 0); + assert!( + bench + .try_as(outsider, &bench.levy(bench.civic.farmer, 1)) + .is_ok() + ); + + // An office lends exactly the kinds it delegates: the warden's `levy` + // does not make its holder a commander. + let again = bench.delegate(outsider, bench.civic.chamber); + assert_eq!( + bench.rejected_as(bench.civic.reeve, &again), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The minted grant is ordinary state: repeating it changes nothing, and + // widening it to the hall would overlap what the deputy already holds. + let error = bench.try_as(treasury, &again).unwrap_err(); + let KernelError::PatchRejected(rejected) = error else { + panic!("a duplicate delegation is a patch rejection"); + }; + assert_eq!( + rejected, + vec![crate::Mismatch::NoOperationEffect { operation: 0 }] + ); + let hall = bench.civic.hall; + assert_eq!( + bench.refuse(vec![grant_to(outsider, LEVY_KIND, over_place(hall))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + } + + /// The revocation envelope is the same predicate as the grant one, read + /// the other way: an actor may strip a `levy` grant only over ground its + /// own authority covers, so a bystander cannot use `revoke` to reach past + /// what it may otherwise touch. + #[test] + fn revoking_a_grant_requires_covering_authority_over_its_ground() { + let mut bench = civics("RevokeEnvelope"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let hall = bench.civic.hall; + + // The farmer holds no authority at all, so stripping the treasury's + // own `levy` grant over the hall fails the envelope before the patch + // lane ever sees the operation. + assert_eq!( + bench.rejected_as(farmer, &bench.revoke(treasury, hall)), + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + + // The treasury's own `levy` grant over the hall covers the hall, so + // the treasury may strip its own grant, and the ledger loses it. + assert!(bench.commit_as(treasury, bench.revoke(treasury, hall)).resulting_revision > 0); + assert!( + !bench + .kernel + .state + .authority + .get(&treasury) + .is_some_and(|grants| grants.contains(&crate::AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: crate::AuthorityTarget::PlaceSubtree(hall), + })), + "the revoked grant is gone from the ledger" + ); + } + + /// The fixture's one `Relocate`-lowering affordance: a commander may move + /// a subordinate standing under its ground, and one standing outside it + /// fails the same `Authorized` precondition every other civic act reads. + #[test] + fn deploy_relocates_a_subordinate_under_command_and_refuses_one_outside_it() { + let mut bench = civics("Deploy"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let outsider = bench.civic.outsider; + let chamber = bench.civic.chamber; + let hall = bench.civic.hall; + let passage = bench.civic.passage; + + // The pedlar stands on the road, outside the hall the treasury + // commands, so the precondition alone refuses the attempt. + assert_eq!( + bench.rejected_as(treasury, &bench.deploy(outsider, passage)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The farmer stands in the chamber, under the treasury's command, and + // the passage carries it into the hall the same way a direct + // `Relocate` would. + assert_eq!( + bench + .kernel + .state + .positions + .get(&farmer) + .map(|position| position.place), + Some(chamber) + ); + assert!(bench.commit_as(treasury, bench.deploy(farmer, passage)).resulting_revision > 0); + assert_eq!( + bench + .kernel + .state + .positions + .get(&farmer) + .map(|position| position.place), + Some(hall) + ); + } + + /// `Redress` with a reducer reader: standing is the covering predicate over + /// the forum's target, and closing the forum removes the verb's ground. + #[test] + fn a_petition_requires_standing() { + let mut bench = civics("Petition"); + let petition = bench.call( + "petition", + Vec::new(), + Vec::new(), + Some(Statement::new("The tithe was taken twice.").unwrap()), + ); + assert_eq!( + bench.rejected_as(bench.civic.outsider, &petition), + vec![ActionMismatch::NoStanding { precondition: 0 }] + ); + + let farmer = bench.civic.farmer; + assert!(bench.commit_as(farmer, petition.clone()).resulting_revision > 0); + let events = bench.kernel.events(); + let event = events.last().expect("the committed event"); + assert_eq!(event.effects.len(), 2); + assert_eq!( + crate::tests::spoken(&bench.kernel.state, event), + Some("The tithe was taken twice.") + ); + + bench.admit(vec![ComponentOp::CloseForum { + grievance: grievance(SEIZURE_GRIEVANCE), + }]); + assert_eq!( + bench.rejected_as(farmer, &petition), + vec![ActionMismatch::NoStanding { precondition: 0 }] + ); + } + + /// One predicate, two callers: the resolver's `Relocate` arm and + /// `Reachable`'s edge admission read the same `Restricted` rule, and a + /// same-patch grant then move resolves through the candidate shadow. + #[test] + fn a_restricted_route_admits_exactly_its_named_authority() { + let mut bench = civics("Restricted"); + let walker = bench.topology.walker; + let step = ComponentOp::Relocate { + subject: PatchRef::Existing(walker), + via: PatchRef::Existing(bench.civic.postern), + }; + + // Holding nothing, and holding `admit` over the origin only, are both + // refused: the rule asks about the destination. + assert!( + bench + .refuse(vec![step.clone()]) + .contains(&crate::Mismatch::RouteAccessRestricted { operation: 0 }) + ); + let yard = bench.topology.yard; + bench.admit(vec![grant_to(walker, ADMIT_KIND, over_place(yard))]); + assert!( + bench + .refuse(vec![step.clone()]) + .contains(&crate::Mismatch::RouteAccessRestricted { operation: 0 }) + ); + + // Reachable reads the same rule from the other side. + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(!reachable( + &bench.kernel.state, + walker, + &authority, + bench.civic.chamber, + Cost(4) + )); + + // A grant covering the destination, minted in the same patch as the + // move, resolves through the candidate authority shadow. + let hall = bench.civic.hall; + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(!patch::route_admits( + &bench.kernel.state, + &authority, + bench.kernel.state.edges[&bench.civic.postern].access(), + bench.civic.chamber + )); + bench.admit(vec![grant_to(walker, ADMIT_KIND, over_place(hall)), step]); + assert_eq!( + bench.kernel.state.positions[&walker].place, + bench.civic.chamber + ); + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(patch::route_admits( + &bench.kernel.state, + &authority, + bench.kernel.state.edges[&bench.civic.postern].access(), + bench.civic.chamber + )); + } + + /// The remaining institutional affordances, each proving one lowering arm: + /// `sanction` closes shared topology under a legitimacy check with an + /// interdiction band that fails, and `appoint` makes succession an act + /// someone performs under authority rather than a declared method string. + #[test] + fn sanction_and_appoint_reach_the_reducer_under_authority() { + let mut bench = civics("Institutional"); + let treasury = bench.civic.treasury; + let passage = bench.civic.passage; + let sanction = bench.call( + "sanction", + vec![binding("road", Target::Edge(passage))], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + + // The reeve holds the verb but its office lends only `levy`, so the same + // act names the precondition it failed. + assert_eq!( + bench.rejected_as(bench.civic.reeve, &sanction), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The treasury commands the hall, and the passage has both endpoints + // under it. The draw decides whether the interdiction lands. + let receipt = act_drawing(&mut bench.kernel, treasury, &sanction, 0); + assert!(receipt.resulting_revision > 0); + bench.refresh(); + assert!(!bench.kernel.state.edges[&passage].is_open()); + + // Appointment installs an incumbent through the action lane. + let farmer = bench.civic.farmer; + let appoint = bench.call( + "appoint", + vec![ + binding("institution", Target::Subject(treasury)), + binding("candidate", Target::Subject(farmer)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + assert!(bench.commit_as(treasury, appoint).resulting_revision > 0); + assert_eq!( + bench.kernel.state.selection[&treasury][&office("bailiff")].incumbent, + Some(farmer) + ); + } + + // --- Soul: pass-5 falsification ------------------------------------- + + /// Submits an invocation through the real command path and hands back + /// whatever the kernel decided, refusal included. + fn soul_submit( + bench: &mut Civics, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + act(&mut bench.kernel, actor, invocation) + } + + /// `DelegationNotMonotone` is not a fixture-only verdict: the real `submit` + /// path reaches it, and the refused act commits nothing. + #[test] + fn soul_delegation_not_monotone_reaches_the_real_command_path() { + let mut bench = civics("SoulMonotone"); + let treasury = bench.civic.treasury; + let road = bench.topology.road; + let outsider = bench.civic.outsider; + bench.admit(vec![grant_to(treasury, COMMAND_KIND, over_place(road))]); + let invocation = bench.delegate(outsider, road); + let before = bench.kernel.state.clone(); + let before_events = bench.kernel.events(); + let error = soul_submit(&mut bench, treasury, invocation).unwrap_err(); + let KernelError::ActionRejected(rejected) = error else { + panic!("an over-wide delegation is an action rejection"); + }; + assert_eq!( + rejected, + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.authority, before.authority); + assert_eq!(bench.kernel.events().len(), before_events.len()); + } + + /// The `Restricted` rule is enforced by the component writer, not only by + /// the resolver: a forged `ResolvedOp` that skipped `resolve_patch` still + /// cannot walk a subject through a door it holds no key to, and the same + /// operation succeeds the moment the key exists. + #[test] + fn soul_a_restricted_relocate_is_refused_by_the_component_writer() { + let bench = civics("SoulReducerGate"); + let walker = bench.topology.walker; + let step = ResolvedOp::Relocate { + subject_id: walker, + edge_id: bench.civic.postern, + }; + + let mut forged = bench.kernel.state.clone(); + forged.positions.insert( + walker, + crate::patch::Position { + place: bench.topology.yard, + }, + ); + let mut refused = forged.clone(); + let resolves_to = refused.revision + 1; + let error = + crate::apply_operations(&mut refused, std::slice::from_ref(&step), &[], resolves_to) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + + let mut admitted = forged; + admitted.authority.insert( + walker, + BTreeSet::from([crate::AuthorityGrant { + kind: crate::tests::authority_kind(ADMIT_KIND), + over: crate::AuthorityTarget::PlaceSubtree(bench.civic.hall), + }]), + ); + let resolves_to = admitted.revision + 1; + crate::apply_operations(&mut admitted, std::slice::from_ref(&step), &[], resolves_to) + .expect("the named key opens the door at the component writer too"); + assert_eq!(admitted.positions[&walker].place, bench.civic.chamber); + } + + /// A grant change on the *granter* reaches the delegate: once the + /// treasury's levy ground is revoked, the reeve's act is refused at + /// admission, and nothing commits. + #[test] + fn soul_a_granter_revocation_refuses_the_delegates_act() { + let mut bench = civics("SoulRebind"); + let reeve = bench.civic.reeve; + let farmer = bench.civic.farmer; + let treasury = bench.civic.treasury; + let hall = bench.civic.hall; + + assert!(bench.try_as(reeve, &bench.levy(farmer, 1)).is_ok()); + let invocation = bench.levy(farmer, 1); + bench.admit(vec![ComponentOp::RevokeAuthority { + holder: PatchRef::Existing(treasury), + grant: crate::tests::grant_of(LEVY_KIND, over_place(hall)), + }]); + let events = bench.kernel.events().len(); + let error = act(&mut bench.kernel, reeve, invocation).unwrap_err(); + assert!( + matches!(error, KernelError::ActionRejected(_)), + "a revoked lend is a rejection: {error:?}" + ); + assert_eq!(bench.kernel.events().len(), events); + } + + /// Structural overlap alone does not see a `Subject` grant sitting inside + /// a `PlaceSubtree` grant of the same kind: `targets_overlap` compares + /// shapes, not position, and stays that way so the answer cannot decay + /// when a subject walks somewhere. Admission catches the cross-shape case + /// live instead, in the resolver where the second grant lands, using the + /// same covering predicate `Authorized` reads. Both directions fire the + /// identical check, so whichever grant is minted second is the one that + /// is refused. + #[test] + fn soul_a_subject_grant_inside_a_place_grant_is_a_second_source() { + let mut bench = civics("SoulOverlap"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let hall = bench.civic.hall; + + // The farmer stands under the hall the treasury already levies, so the + // covering predicate says both grants would answer for the same + // target, and admission refuses the narrower grant landing second. + assert!(crate::covers( + &bench.kernel.state, + crate::AuthorityTarget::PlaceSubtree(hall), + Target::Subject(farmer) + )); + assert_eq!( + bench.refuse(vec![grant_to(treasury, LEVY_KIND, over_subject(farmer))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // The symmetric order: a direct grant over the farmer, minted first + // under a fresh kind, blocks a later place grant that would cover + // him too. + const AUDIT_KIND: &str = "audit"; + bench.admit(vec![grant_to(treasury, AUDIT_KIND, over_subject(farmer))]); + assert_eq!( + bench.refuse(vec![grant_to(treasury, AUDIT_KIND, over_place(hall))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + } + + /// Replay for the new arms is not a separate machine: `reduce` is a pure + /// function of committed state and the envelope, so running it twice on the + /// same pre-state yields the same effect, and that effect is exactly what + /// the commit stored. No clock and no draw entropy enter. + #[test] + fn soul_reduce_is_pure_for_every_new_civic_arm() { + let mut bench = civics("SoulReplay"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let outsider = bench.civic.outsider; + let chamber = bench.civic.chamber; + let passage = bench.civic.passage; + + let sanction = bench.call( + "sanction", + vec![binding("road", Target::Edge(passage))], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + let appoint = bench.call( + "appoint", + vec![ + binding("institution", Target::Subject(treasury)), + binding("candidate", Target::Subject(farmer)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + for invocation in [ + bench.levy(farmer, 2), + bench.delegate(outsider, chamber), + sanction, + appoint, + ] { + let before = bench.kernel.state.clone(); + let caller = play_caller(); + let envelope = command( + &bench.active, + caller.clone(), + CommandBody::Act { + actor: treasury, + invocation, + }, + ); + let first = crate::reduce(&before, &envelope).expect("the act reduces"); + let second = crate::reduce(&before, &envelope).expect("the act reduces again"); + assert_eq!(first, second, "reduce is not a pure function of the state"); + let receipt = bench + .kernel + .submit(envelope, &AuthenticatedCaller::fixture(caller)) + .expect("the act commits"); + assert!(receipt.resulting_revision > 0); + bench.refresh(); + let WorldEffect::Acted { event, .. } = first else { + panic!("an acted effect"); + }; + assert_eq!( + bench.kernel.events().last().expect("a committed event"), + &event, + "the committed event is not what reduce produced" + ); + } + } + + /// `resolve_patch`'s candidate knowledge map never models `Communicate`'s + /// fan-out (see the comment beside its construction in `patch.rs`), and + /// that omission is safe only because no `ComponentOpKind` an affordance + /// may declare can lower to a knowledge write carrying + /// `KnowledgeSource::Told`. Two kinds touch knowledge: `AcquireKnowledge`, + /// whose source `lower` fixes to `AuthoredSource::Witnessed` — a type with + /// no `Told` variant to begin with — and `Witness`, which carries no source + /// field and no speaker field at all. This test pins both lowerings, at the + /// call sites that turn a declared slot into a `ComponentOp`, so a future + /// author cannot widen either without this assertion naming the change. + #[test] + fn no_component_op_kind_lowers_to_a_told_knowledge_write() { + let bench = bench("AcquireKnowledgeLowering"); + let entry = Affordance { + kind: AffordanceKindName("witness".into()), + roles: Vec::new(), + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AcquireKnowledge { + confidence: Confidence::Believed, + }, + roles: vec![Role("subject".into()), Role("fact".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }; + let bindings = BTreeMap::from([ + (Role("subject".into()), Target::Subject(bench.clerk)), + (Role("fact".into()), Target::Entity(bench.tithe)), + ]); + let invocation = DecisionInvocation { + affordance: bench.carry, + bindings: Vec::new(), + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }; + let lowered = lower( + &entry, + 0, + bench.clerk, + FictionalMinutes::default(), + &invocation, + &bindings, + ) + .expect("the acquire slot lowers"); + assert_eq!( + lowered, + vec![ComponentOp::AcquireKnowledge { + subject: PatchRef::Existing(bench.clerk), + fact: PatchRef::Existing(bench.tithe), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }], + "AcquireKnowledge must lower with a Witnessed source, never a forged teller" + ); + + let witnessing = Affordance { + kind: AffordanceKindName("beacon".into()), + roles: Vec::new(), + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Witness { + confidence: Confidence::Believed, + }, + roles: vec![Role("fact".into()), Role("place".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }; + let places = BTreeMap::from([ + (Role("fact".into()), Target::Entity(bench.tithe)), + (Role("place".into()), Target::Entity(bench.yard)), + ]); + let lowered = lower( + &witnessing, + 0, + bench.clerk, + FictionalMinutes::default(), + &invocation, + &places, + ) + .expect("the witness slot lowers"); + assert_eq!( + lowered, + vec![ComponentOp::Witness { + fact: PatchRef::Existing(bench.tithe), + place: PatchRef::Existing(bench.yard), + confidence: Confidence::Believed, + }], + "Witness must lower with no speaker field to forge" + ); + } + + /// The pin above names two knowledge-touching kinds by example, and a list + /// by example goes stale in silence. This match is exhaustive, so a new + /// `ComponentOpKind` breaks the build here and its author must say whether + /// it touches knowledge. The set that does is `AcquireKnowledge`, `Witness`, + /// and `Forget`; the first two are pinned above as unable to carry a teller, + /// and `Forget` writes no row at all — it only removes one, so it has no + /// source to forge. + #[test] + fn soul_every_knowledge_touching_op_kind_is_named_by_the_told_pin() { + fn touches_knowledge(kind: &ComponentOpKind) -> bool { + match kind { + ComponentOpKind::AcquireKnowledge { .. } + | ComponentOpKind::Witness { .. } + | ComponentOpKind::Forget => true, + ComponentOpKind::Relocate + | ComponentOpKind::OpenRoute + | ComponentOpKind::CloseRoute + | ComponentOpKind::AlterCost + | ComponentOpKind::Transfer + | ComponentOpKind::Transform + | ComponentOpKind::Consume + | ComponentOpKind::Bind + | ComponentOpKind::Release + | ComponentOpKind::GrantAuthority { .. } + | ComponentOpKind::RevokeAuthority { .. } + | ComponentOpKind::InstallIncumbent { .. } + | ComponentOpKind::VacateOffice { .. } + | ComponentOpKind::CreateCommitment { .. } + | ComponentOpKind::AdvancePressure { .. } + | ComponentOpKind::ReducePressure { .. } + | ComponentOpKind::ResolvePressure => false, + } + } + + let confidence = Confidence::Believed; + let touching = [ + ComponentOpKind::AcquireKnowledge { confidence }, + ComponentOpKind::Witness { confidence }, + ComponentOpKind::Forget, + ComponentOpKind::Relocate, + ComponentOpKind::Transfer, + ComponentOpKind::ResolvePressure, + ] + .iter() + .filter(|kind| touches_knowledge(kind)) + .count(); + assert_eq!( + touching, 3, + "the knowledge-touching set is not the one this pin names" + ); + } +} diff --git a/native/aetherlight/src/clock.rs b/native/aetherlight/src/clock.rs new file mode 100644 index 000000000..eaee01512 --- /dev/null +++ b/native/aetherlight/src/clock.rs @@ -0,0 +1,250 @@ +//! The world clock and the motion one tick produces. +//! +//! One entry point into the reducer, [`derive_motion`], reached from `reduce`'s +//! `AdvanceTime` arm and from `apply_effect`'s `TimeAdvanced` arm, so a forged +//! tick is re-derived by the same function that produced the honest one. It is +//! pure over `(state, to)`: no wall clock, no entropy, no caller value beyond +//! the span. + +use super::patch::{Commitment, CommitmentKey, CommitmentKind, DependencyTarget, MAX_ROUTE_COST}; +use super::{PressureMagnitude, PressureSource, SubjectId, WorldState, action, views}; +#[cfg(test)] +use super::is_retired; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// Minutes since genesis. Monotonic, kernel-owned, world-level. `u64` because a +/// world clock has no bound; `Cost` is `1..=MAX_ROUTE_COST` because it weighs +/// one edge, and reusing it here would put an edge's bound on the world's age. +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, +)] +#[serde(transparent)] +pub struct FictionalMinutes(pub u64); + +impl FictionalMinutes { + pub(crate) fn checked_add(self, span: TickMinutes) -> Option { + self.0.checked_add(u64::from(span.0)).map(Self) + } +} + +/// The span one `AdvanceTime` names, `1..=MAX_ROUTE_COST` (one year of +/// minutes), reusing pass 2's constant as a span bound rather than an edge +/// bound: an unbounded span lets one command jump the clock past every due date +/// in the world and makes the size of a commit a caller-chosen number. +/// +/// The type owns its bound at every door: `new` and decoding both go through +/// it, so a command, a routine's period or a stored commit that names a span +/// outside the bound cannot be read at all, and no reducer or replay clause +/// re-checks it. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[serde(try_from = "u32", into = "u32")] +pub struct TickMinutes(u32); + +impl TryFrom for TickMinutes { + type Error = &'static str; + + fn try_from(minutes: u32) -> Result { + Self::new(minutes).ok_or("a tick span is 1..=525600 minutes") + } +} + +impl From for u32 { + fn from(span: TickMinutes) -> u32 { + span.0 + } +} + +impl TickMinutes { + pub fn new(minutes: u32) -> Option { + (1..=MAX_ROUTE_COST) + .contains(&minutes) + .then_some(Self(minutes)) + } + + pub fn minutes(self) -> u32 { + self.0 + } +} + +/// Everything one tick moves, stated as outcomes rather than deltas so the +/// effect says what the world became. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Motion { + /// Routines that fulfilled, in `(subject, key)` order. + pub(crate) fulfilled: Vec, + /// Pressure rows written, in `(target, source)` order, with the resulting + /// magnitude — not the delta. + pub(crate) pressed: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct RoutineFulfilled { + pub(crate) subject: SubjectId, + pub(crate) key: CommitmentKey, + pub(crate) next_due: FictionalMinutes, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct PressureWritten { + pub(crate) target: SubjectId, + pub(crate) source: PressureSource, + pub(crate) magnitude: PressureMagnitude, +} + +/// The whole magnitude policy, in one place, with no per-world tuning. A +/// blocked routine raises none at all: it retries on the next tick, which is +/// what keeps an unattended subject free of spurious pressure. +mod step { + pub(super) const OBLIGATION_PAST_DUE: u32 = 1; + pub(super) const GOAL_PAST_DUE: u32 = 1; + pub(super) const DEPENDENCY_UNAVAILABLE: u32 = 1; +} + +/// Three stages, each reading only committed `state` and `to`. No stage sees +/// another stage's writes, which is what makes this a one-pass total function +/// with no ordering hazard and no partial state to reason about. +/// +/// Pressure accrues per command, not per minute: one thousand one-minute ticks +/// and one thousand-minute tick over the same span produce different +/// magnitudes. The kernel stays an exact function of the command sequence, and +/// the tick cadence is one operational constant in `runtime.rs`. +/// +/// What is due, and which dependencies fail, is read from `Views` (the one owner +/// of both questions: a live subject's due commitments and a live subject's +/// unavailable dependencies), so a tick reads the work it does and not the +/// world. A view is true only with clean logs, so it is read behind a check +/// that holds in every build (six flag tests), and both callers (`reduce`, and +/// `apply_effect`'s `TimeAdvanced` arm before its first write) call it clean. +pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion { + assert!(views::readable(state), "the views are read with an open log"); + motion_of(state, to, &state.views.due_by(to), state.views.failing().copied()) +} + +/// What `derive_motion` was before the views: every subject holding a promise +/// and every dependency row, with retirement and availability judged on the +/// spot. The view reads must derive the same motion. +#[cfg(test)] +pub(super) fn derive_motion_by_scan(state: &WorldState, to: FictionalMinutes) -> Motion { + let live = |subject: &SubjectId| !is_retired(state, *subject); + let promisors = state.commitments.keys().copied().filter(live).collect(); + let failing: Vec<_> = state + .dependencies + .iter() + .filter(|(subject, _)| live(subject)) + .flat_map(|(subject, targets)| targets.iter().map(move |target| (*subject, *target))) + .filter(|(subject, target)| dependency_unavailable(state, *subject, *target)) + .collect(); + motion_of(state, to, &promisors, failing.into_iter()) +} + +/// The motion over `promisors`, which must hold every live subject with a +/// commitment due by `to`, and the `failing` dependencies of live subjects. +fn motion_of( + state: &WorldState, + to: FictionalMinutes, + promisors: &std::collections::BTreeSet, + failing: impl Iterator, +) -> Motion { + let mut fulfilled = Vec::new(); + let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new(); + + for subject in promisors { + let held = &state.commitments[subject]; + for (key, commitment) in held { + if commitment.due > to { + continue; + } + match commitment.kind { + CommitmentKind::Routine => { + if let Some(next_due) = routine_rolls(state, *subject, commitment) { + fulfilled.push(RoutineFulfilled { + subject: *subject, + key: *key, + next_due, + }); + } + } + CommitmentKind::Obligation | CommitmentKind::Goal => { + let step = if commitment.kind == CommitmentKind::Obligation { + step::OBLIGATION_PAST_DUE + } else { + step::GOAL_PAST_DUE + }; + let source = PressureSource::Commitment { + subject: *subject, + key: *key, + }; + *pressed.entry((*subject, source)).or_default() += step; + } + } + } + } + + for (subject, target) in failing { + let source = PressureSource::Dependency(target); + *pressed.entry((subject, source)).or_default() += step::DEPENDENCY_UNAVAILABLE; + } + + Motion { + fulfilled, + pressed: pressed + .into_iter() + .map(|((target, source), step)| PressureWritten { + target, + source, + magnitude: PressureMagnitude( + state + .pressures + .get(&target) + .and_then(|held| held.get(&source)) + .map_or(0, |magnitude| magnitude.0) + .saturating_add(step), + ), + }) + .collect(), + } +} + +/// A routine fulfils when every one of its checks holds, and its `due` then +/// rolls forward by exactly one period per command. Catch-up arithmetic would +/// make the number of fulfilments a function of the operator's tick cadence in +/// a second place; one roll converges over subsequent ticks. +fn routine_rolls( + state: &WorldState, + subject: SubjectId, + commitment: &Commitment, +) -> Option { + if !action::preconditions_hold(state, subject, &commitment.checks).is_empty() { + return None; + } + commitment.due.checked_add(commitment.period?) +} + +/// Whether a subject's dependency is currently failing it. A closed route is a +/// supply failure; an unusable one is a permission question, and reading +/// authority here would drag `effective_authority` into every tick for every +/// dependency in the world. +pub(super) fn dependency_unavailable( + state: &WorldState, + subject: SubjectId, + target: DependencyTarget, +) -> bool { + match target { + DependencyTarget::Route(edge_id) => !state + .edges + .get(&edge_id) + .is_some_and(super::EdgeRecord::is_open), + // Absence is zero, per pass 3: the depender holds none of what it + // depends on. + DependencyTarget::Resource(entity_id) => !state + .holdings + .get(&subject) + .is_some_and(|held| held.contains_key(&entity_id)), + // The subject it depends on is nowhere in the world's topology. + DependencyTarget::Subject(other) => !state.positions.contains_key(&other), + } +} diff --git a/native/aetherlight/src/digest.rs b/native/aetherlight/src/digest.rs new file mode 100644 index 000000000..1cf891244 --- /dev/null +++ b/native/aetherlight/src/digest.rs @@ -0,0 +1,295 @@ +//! The state digest: a homomorphic set hash over per-document digests. +//! +//! Each document (one row of a partition, or the world header) has a digest +//! `sha256(len schema, schema, len key, key, rmp named value)`. The world's +//! accumulator is LtHash16 (Lewi et al. 2019): a document digest is expanded to +//! 2048 bytes and added lane-wise as 1024 wrapping `u16`; removing a document +//! subtracts it, and updating one subtracts the old and adds the new. So the +//! digest of a commit costs what the commit changed, not the size of the world, +//! and it depends on the set of documents alone, never on the order they were +//! written. `state_digest` seals the accumulator with the revision. + +use crate::docs::{DocKey, Docs, Tracked}; +use crate::{KernelError, STATE_SCHEMA}; +use serde::Serialize; +use sha2::{Digest, Sha256}; + +const LANES: usize = 1024; +/// 64 blocks of 32 bytes: 2048 bytes, 1024 lanes. +const BLOCKS: u8 = 64; + +pub(crate) type DocDigest = [u8; 32]; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct LtHash16(Box<[u16; LANES]>); + +impl Default for LtHash16 { + fn default() -> Self { + Self(Box::new([0; LANES])) + } +} + +impl LtHash16 { + fn lanes(doc: &DocDigest) -> impl Iterator + '_ { + (0..BLOCKS).flat_map(move |block| { + let mut hasher = Sha256::new(); + hasher.update(doc); + hasher.update([block]); + let expanded: [u8; 32] = hasher.finalize().into(); + (0..16).map(move |lane| u16::from_le_bytes([expanded[2 * lane], expanded[2 * lane + 1]])) + }) + } + + pub(crate) fn add(&mut self, doc: &DocDigest) { + for (slot, lane) in self.0.iter_mut().zip(Self::lanes(doc)) { + *slot = slot.wrapping_add(lane); + } + } + + pub(crate) fn subtract(&mut self, doc: &DocDigest) { + for (slot, lane) in self.0.iter_mut().zip(Self::lanes(doc)) { + *slot = slot.wrapping_sub(lane); + } + } + + /// The commit-facing digest: the accumulator sealed with the revision. + pub(crate) fn state_digest(&self, revision: u64) -> String { + let mut hasher = Sha256::new(); + hasher.update(STATE_SCHEMA.as_bytes()); + hasher.update(revision.to_be_bytes()); + for lane in self.0.iter() { + hasher.update(lane.to_le_bytes()); + } + format!("sha256:{:x}", hasher.finalize()) + } +} + +#[cfg(test)] +thread_local! { + /// Document digests computed on this thread, for the work-bound test. + pub(crate) static DOC_DIGESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +pub(crate) fn doc_digest( + schema: &str, + key: &str, + value: &V, +) -> Result { + #[cfg(test)] + DOC_DIGESTS.with(|count| count.set(count.get() + 1)); + let bytes = rmp_serde::to_vec_named(value) + .map_err(|error| KernelError::Serialization(error.to_string()))?; + let mut hasher = Sha256::new(); + hasher.update((schema.len() as u64).to_be_bytes()); + hasher.update(schema.as_bytes()); + hasher.update((key.len() as u64).to_be_bytes()); + hasher.update(key.as_bytes()); + hasher.update(bytes); + Ok(hasher.finalize().into()) +} + +/// One change of one document: subtract the old, add the new. +pub(crate) fn fold_change( + acc: &mut LtHash16, + schema: &str, + key: &str, + old: Option<&V>, + new: Option<&V>, +) -> Result<(), KernelError> { + if let Some(old) = old { + acc.subtract(&doc_digest(schema, key, old)?); + } + if let Some(new) = new { + acc.add(&doc_digest(schema, key, new)?); + } + Ok(()) +} + +/// What `WorldState` needs of a partition, whatever its key and value types. +pub(crate) trait Partition { + fn is_clean(&self) -> bool; + fn rollback(&mut self); + fn finish_log(&mut self); + /// Folds the open transaction's changes into `acc`. + fn fold_changes(&self, schema: &str, acc: &mut LtHash16) -> Result<(), KernelError>; + /// Every document's digest, by (schema, key): the full enumeration the + /// incremental digest is checked against. + #[cfg(test)] + fn documents( + &self, + schema: &str, + out: &mut std::collections::BTreeMap<(String, String), DocDigest>, + ) -> Result<(), KernelError>; + /// The partition as encoded: the bytes a test scans for what must never appear. + #[cfg(test)] + fn encoded(&self) -> Vec; + /// How many documents the partition holds. + #[cfg(test)] + fn rows(&self) -> usize; + /// Removes the first document, logged like any write; false when empty. + #[cfg(test)] + fn remove_first(&mut self) -> bool; + /// Whether the read index is exactly the projection of the documents. + #[cfg(test)] + fn index_is_derived(&self) -> bool; + /// Damages the read index in one place (a stray entry, else a missing one); + /// false when there is nothing to damage. + #[cfg(test)] + fn corrupt_index_first(&mut self, stray: bool) -> bool; +} + +impl Partition for Docs +where + K: Ord + Clone + DocKey + Serialize, + V: Clone + PartialEq + Serialize, + P: crate::docs::Projection, +{ + fn is_clean(&self) -> bool { + Docs::is_clean(self) + } + + fn rollback(&mut self) { + Docs::rollback(self); + } + + fn finish_log(&mut self) { + self.finish(); + } + + fn fold_changes(&self, schema: &str, acc: &mut LtHash16) -> Result<(), KernelError> { + for (key, old, new) in self.changes() { + fold_change(acc, schema, &key.key_text(), old, new)?; + } + Ok(()) + } + + #[cfg(test)] + fn documents( + &self, + schema: &str, + out: &mut std::collections::BTreeMap<(String, String), DocDigest>, + ) -> Result<(), KernelError> { + for (key, value) in self.iter() { + let key = key.key_text(); + let digest = doc_digest(schema, &key, value)?; + out.insert((schema.to_owned(), key), digest); + } + Ok(()) + } + + #[cfg(test)] + fn encoded(&self) -> Vec { + rmp_serde::to_vec_named(self).expect("a partition encodes") + } + + #[cfg(test)] + fn rows(&self) -> usize { + self.len() + } + + #[cfg(test)] + fn remove_first(&mut self) -> bool { + let Some(key) = self.keys().next().cloned() else { + return false; + }; + self.remove(&key).is_some() + } + + #[cfg(test)] + fn index_is_derived(&self) -> bool { + Docs::index_is_derived(self) + } + + #[cfg(test)] + fn corrupt_index_first(&mut self, stray: bool) -> bool { + self.corrupt_index_for_test(stray) + } +} + +/// The header's one change, keyed by its own world id. +pub(crate) fn fold_header( + acc: &mut LtHash16, + schema: &str, + key: &str, + header: &Tracked, +) -> Result<(), KernelError> { + if let Some((old, new)) = header.change() { + fold_change(acc, schema, key, old, Some(new))?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn documents(count: u32) -> Vec { + (0..count) + .map(|index| doc_digest("aetherlight.test.v1", &index.to_string(), &index).unwrap()) + .collect() + } + + /// Order never matters and a subtraction undoes an addition, so the digest + /// is a function of the set of documents alone. + #[test] + fn lthash_add_then_subtract_is_zero() { + let docs = documents(300); + let mut acc = LtHash16::default(); + for doc in &docs { + acc.add(doc); + } + assert_ne!(acc, LtHash16::default()); + + let mut backwards = LtHash16::default(); + for doc in docs.iter().rev() { + backwards.add(doc); + } + assert_eq!(acc, backwards, "equal sets in two orders differ"); + + let mut strided = LtHash16::default(); + for index in (0..docs.len()).map(|step| (step * 7) % docs.len()) { + strided.add(&docs[index]); + } + assert_eq!(acc, strided, "equal sets in a third order differ"); + + for index in (0..docs.len()).map(|step| (step * 11) % docs.len()) { + acc.subtract(&docs[index]); + } + assert_eq!(acc, LtHash16::default(), "add then subtract left a residue"); + } + + /// A lane that carries must wrap: 40 additions of one document overflow + /// nearly every lane of a `u16`, and the subtractions still return to zero. + #[test] + fn lanes_wrap_instead_of_saturating() { + let doc = documents(1)[0]; + let mut acc = LtHash16::default(); + for _ in 0..40 { + acc.add(&doc); + } + for _ in 0..40 { + acc.subtract(&doc); + } + assert_eq!(acc, LtHash16::default()); + } + + #[test] + fn the_state_digest_seals_the_revision_and_every_lane() { + let docs = documents(3); + let mut acc = LtHash16::default(); + docs.iter().for_each(|doc| acc.add(doc)); + assert_ne!(acc.state_digest(1), acc.state_digest(2), "the revision is not sealed"); + let mut other = acc.clone(); + other.0[1023] = other.0[1023].wrapping_add(1); + assert_ne!(acc.state_digest(1), other.state_digest(1), "the last lane is not hashed"); + } + + #[test] + fn a_document_digest_separates_schema_key_and_value() { + let one = doc_digest("ab", "c", &1u8).unwrap(); + assert_ne!(one, doc_digest("a", "bc", &1u8).unwrap(), "schema and key run together"); + assert_ne!(one, doc_digest("ab", "c", &2u8).unwrap()); + assert_ne!(one, doc_digest("ab", "d", &1u8).unwrap()); + assert_eq!(one, doc_digest("ab", "c", &1u8).unwrap()); + } +} diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs new file mode 100644 index 000000000..c9120754b --- /dev/null +++ b/native/aetherlight/src/docs.rs @@ -0,0 +1,766 @@ +//! Tracked documents: the one writer of a partition and the one recorder of +//! what a transaction changed. +//! +//! A `Docs` is a map whose every write goes through a method that remembers the +//! key's value as it stood before the transaction (first touch wins). `finish` +//! turns that record into the keys whose value really changed, with their old +//! values; `rollback` puts every touched key back. Reads see the plain map +//! through inherent methods, and no method hands out the map, so a write cannot skip the log. +//! The fields are private to this module for the same reason. + +use serde::{Serialize, Serializer}; +use std::collections::{BTreeMap, BTreeSet}; +use std::collections::btree_map::Entry; +use std::ops::Deref; + +#[cfg(test)] +thread_local! { + /// Rows any `Docs` iterator has yielded on this thread, and entries any + /// `indexed` read has returned: the work a read did, counted where the + /// reads are owned so no reader can skip it. + static ROWS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The rows read on this thread so far (test builds only). +#[cfg(test)] +pub(crate) fn rows_read() -> u64 { + ROWS_READ.with(|rows| rows.get()) +} + +/// Counts rows a view read, where the view is owned (test builds). +#[cfg(test)] +pub(crate) fn count_rows(rows: u64) { + ROWS_READ.with(|count| count.set(count.get() + rows)); +} + +/// A partition iterator that counts every row it yields (test builds); in a +/// shipped build it is the map's own iterator. +pub(crate) struct Counted(I); + +impl Iterator for Counted { + type Item = I::Item; + fn next(&mut self) -> Option { + let item = self.0.next(); + #[cfg(test)] + if item.is_some() { + count_rows(1); + } + item + } +} + +impl DoubleEndedIterator for Counted { + fn next_back(&mut self) -> Option { + let item = self.0.next_back(); + #[cfg(test)] + if item.is_some() { + count_rows(1); + } + item + } +} + +/// A key whose value changed in a transaction, with the value it had before +/// (`None` when the key was absent). The new value is whatever the map holds. +pub(crate) type Changed = (K, Option); + +/// Where a document sits in a partition's read index: a pure function of one +/// document's value, so the index can always be rebuilt from the map and never +/// disagrees with it. +pub(crate) trait Projection { + type Point: Ord + Clone + std::fmt::Debug; + /// Appends every point `value` sits at (duplicates allowed). + fn points(value: &V, out: &mut Vec); +} + +/// The projection of a partition nothing reads by value. +#[derive(Clone, Debug, Default)] +pub(crate) struct NoIndex; + +impl Projection for NoIndex { + type Point = (); + fn points(_: &V, _: &mut Vec<()>) {} +} + +/// A partition: its documents, the log of the open transaction, and the read +/// index (the projection of the documents as of the last `finish`). The index +/// is derived state: it is not digested, not encoded, and ignored by equality. +#[derive(Clone, Debug)] +pub(crate) struct Docs = NoIndex> { + map: BTreeMap, + touched: BTreeMap>, + index: BTreeMap>, +} + +impl> Default for Docs { + fn default() -> Self { + Self { + map: BTreeMap::new(), + touched: BTreeMap::new(), + index: BTreeMap::new(), + } + } +} + +/// Equality is the documents, never the log: two worlds with the same content +/// are equal whatever transaction state they are in. +impl> PartialEq for Docs { + fn eq(&self, other: &Self) -> bool { + self.map == other.map + } +} + +impl> Eq for Docs {} + +impl<'a, K: Ord + Clone, V: Clone + PartialEq, P: Projection> IntoIterator for &'a Docs { + type Item = (&'a K, &'a V); + type IntoIter = Counted>; + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +/// A partition encodes as its map, so the encoded world is what it was before +/// the partitions were tracked. +impl> Serialize for Docs { + fn serialize(&self, serializer: S) -> Result { + self.map.serialize(serializer) + } +} + +impl> std::ops::Index<&K> for Docs { + type Output = V; + fn index(&self, key: &K) -> &V { + &self.map[key] + } +} + +impl> Docs { + pub(crate) fn get(&self, key: &K) -> Option<&V> { + self.map.get(key) + } + + pub(crate) fn contains_key(&self, key: &K) -> bool { + self.map.contains_key(key) + } + + pub(crate) fn len(&self) -> usize { + self.map.len() + } + + pub(crate) fn is_empty(&self) -> bool { + self.map.is_empty() + } + + pub(crate) fn iter(&self) -> Counted> { + Counted(self.map.iter()) + } + + pub(crate) fn keys(&self) -> Counted> { + Counted(self.map.keys()) + } + + pub(crate) fn values(&self) -> Counted> { + Counted(self.map.values()) + } + + pub(crate) fn range>( + &self, + range: R, + ) -> Counted> { + Counted(self.map.range(range)) + } + + /// The plain map, for a test that compares a decoded partition to it. + #[cfg(test)] + pub(crate) fn as_map(&self) -> &BTreeMap { + &self.map + } + + fn touch(&mut self, key: &K) { + if !self.touched.contains_key(key) { + self.touched.insert(key.clone(), self.map.get(key).cloned()); + } + } + + pub(crate) fn insert(&mut self, key: K, value: V) -> Option { + self.touch(&key); + self.map.insert(key, value) + } + + pub(crate) fn remove(&mut self, key: &K) -> Option { + self.touch(key); + self.map.remove(key) + } + + /// Touches only a key that is present: a miss writes nothing. + pub(crate) fn get_mut(&mut self, key: &K) -> Option<&mut V> { + if self.map.contains_key(key) { + self.touch(key); + } + self.map.get_mut(key) + } + + pub(crate) fn entry(&mut self, key: K) -> Entry<'_, K, V> { + self.touch(&key); + self.map.entry(key) + } + + /// The open transaction's changed keys as (key, old, new), without closing it. + pub(crate) fn changes(&self) -> impl Iterator, Option<&V>)> + '_ { + self.touched.iter().filter_map(|(key, old)| { + let new = self.map.get(key); + (new != old.as_ref()).then_some((key, old.as_ref(), new)) + }) + } + + /// The keys whose value differs from the start of the transaction, with the + /// value they had then. A key written back to what it was is not reported. + /// The log is empty afterwards. + pub(crate) fn finish(&mut self) -> Vec> { + let changed: Vec> = std::mem::take(&mut self.touched) + .into_iter() + .filter(|(key, old)| self.map.get(key) != old.as_ref()) + .collect(); + for (key, old) in &changed { + self.fold_index(key, old.as_ref()); + } + changed + } + + /// Moves one changed key's entries: its old points out, its current points in. + fn fold_index(&mut self, key: &K, old: Option<&V>) { + let mut points = Vec::new(); + if let Some(old) = old { + P::points(old, &mut points); + for point in points.drain(..) { + if let Some(keys) = self.index.get_mut(&point) { + keys.remove(key); + if keys.is_empty() { + self.index.remove(&point); + } + } + } + } + if let Some(new) = self.map.get(key) { + P::points(new, &mut points); + for point in points { + self.index.entry(point).or_default().insert(key.clone()); + } + } + } + + /// Every (point, key) inside `range`, in order, true at this moment: the + /// committed index, corrected by the open log. A logged key's committed + /// entries are dropped and its current value's points are read from the + /// map, so a read inside a transaction sees what the transaction wrote and + /// the index itself never saw it (which is why `rollback` leaves it alone). + pub(crate) fn indexed>( + &self, + range: R, + ) -> Vec<(P::Point, K)> { + let mut found: Vec<(P::Point, K)> = self + .index + .range((range.start_bound(), range.end_bound())) + .flat_map(|(point, keys)| keys.iter().map(move |key| (point, key))) + .filter(|(_, key)| !self.touched.contains_key(*key)) + .map(|(point, key)| (point.clone(), key.clone())) + .collect(); + if !self.touched.is_empty() { + // Every logged key is walked whatever the range, so each is a row read. + #[cfg(test)] + count_rows(self.touched.len() as u64); + let mut points = Vec::new(); + for key in self.touched.keys() { + if let Some(value) = self.map.get(key) { + P::points(value, &mut points); + for point in points.drain(..) { + if range.contains(&point) { + found.push((point, key.clone())); + } + } + } + } + found.sort(); + found.dedup(); + } + #[cfg(test)] + count_rows(found.len() as u64); + found + } + + /// The committed index's (point, key) entries inside `range` for keys the + /// open log did not change: no walk of the log, so a bulk transaction pays + /// for the entries it returns and not for every key it touched. A key the + /// log changed is the caller's to judge from `changes()`. + pub(crate) fn indexed_unchanged>( + &self, + range: R, + ) -> Vec<(P::Point, K)> { + let found: Vec<(P::Point, K)> = self + .index + .range((range.start_bound(), range.end_bound())) + .flat_map(|(point, keys)| keys.iter().map(move |key| (point, key))) + .filter(|(_, key)| { + self.touched + .get(*key) + .is_none_or(|old| self.map.get(*key) == old.as_ref()) + }) + .map(|(point, key)| (point.clone(), key.clone())) + .collect(); + #[cfg(test)] + count_rows(found.len() as u64); + found + } + + /// Whether the index is exactly the projection of the map (test builds). + #[cfg(test)] + pub(crate) fn index_is_derived(&self) -> bool { + let mut rebuilt: BTreeMap> = BTreeMap::new(); + let mut points = Vec::new(); + for (key, value) in &self.map { + P::points(value, &mut points); + for point in points.drain(..) { + rebuilt.entry(point).or_default().insert(key.clone()); + } + } + rebuilt == self.index + } + + /// Makes the index disagree with the map in one place: a stray entry (a + /// document listed at a point it does not sit at) or a missing one. False + /// when this partition has no such place to damage (test builds). + #[cfg(test)] + pub(crate) fn corrupt_index_for_test(&mut self, stray: bool) -> bool { + if !stray { + let Some(point) = self.index.keys().next().cloned() else { + return false; + }; + let keys = self.index.get_mut(&point).expect("the point is present"); + let key = keys.iter().next().cloned().expect("a point holds a key"); + keys.remove(&key); + if keys.is_empty() { + self.index.remove(&point); + } + return true; + } + for keys in self.index.values_mut() { + if let Some(key) = self.map.keys().find(|key| !keys.contains(*key)) { + keys.insert(key.clone()); + return true; + } + } + false + } + + /// Puts every touched key back as it was and empties the log. + pub(crate) fn rollback(&mut self) { + for (key, old) in std::mem::take(&mut self.touched) { + match old { + Some(value) => { + self.map.insert(key, value); + } + None => { + self.map.remove(&key); + } + } + } + } + + pub(crate) fn is_clean(&self) -> bool { + self.touched.is_empty() + } +} + +/// One tracked value: the same first-touch rule as a `Docs` key, for the +/// world's own fields. +#[derive(Clone, Debug)] +pub(crate) struct Tracked { + value: T, + /// `None` untouched; `Some(None)` logged as absent (genesis), so `finish` + /// reports it as added. + old: Option>, +} + +impl PartialEq for Tracked { + fn eq(&self, other: &Self) -> bool { + self.value == other.value + } +} + +impl Eq for Tracked {} + +impl Deref for Tracked { + type Target = T; + fn deref(&self) -> &T { + &self.value + } +} + +impl Tracked { + /// A value that did not exist before this transaction. + pub(crate) fn absent(value: T) -> Self { + Self { + value, + old: Some(None), + } + } + + pub(crate) fn get_mut(&mut self) -> &mut T { + if self.old.is_none() { + self.old = Some(Some(self.value.clone())); + } + &mut self.value + } + + /// The old value when the value changed (`Some(None)`: it was absent). + pub(crate) fn finish(&mut self) -> Option> { + match self.old.take() { + Some(old) if old.as_ref() != Some(&self.value) => Some(old), + _ => None, + } + } + + /// (old, new) when the value changed in the open transaction. + pub(crate) fn change(&self) -> Option<(Option<&T>, &T)> { + match &self.old { + Some(old) if old.as_ref() != Some(&self.value) => Some((old.as_ref(), &self.value)), + _ => None, + } + } + + pub(crate) fn rollback(&mut self) { + if let Some(Some(old)) = self.old.take() { + self.value = old; + } + } + + pub(crate) fn is_clean(&self) -> bool { + self.old.is_none() + } +} + +/// The text a document is keyed by in its digest: stable, canonical, one per +/// key. An id is its uuid as `Display` prints it. +pub(crate) trait DocKey { + fn key_text(&self) -> String; +} + +impl DocKey for (A, B) { + fn key_text(&self) -> String { + format!("{}/{}", self.0.key_text(), self.1.key_text()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + type Rows = Docs; + + fn rows(held: &[(u8, u8)]) -> Rows { + let mut docs = Rows::default(); + for (key, value) in held { + docs.insert(*key, *value); + } + docs.finish(); + docs + } + + /// A value sits at its tens digit and its units digit (one point when they + /// agree), so a document has several points and two documents can share one. + #[derive(Clone, Debug)] + struct Digits; + + impl Projection for Digits { + type Point = u8; + fn points(value: &u8, out: &mut Vec) { + out.push(value / 10); + out.push(value % 10); + } + } + + type Spread = Docs; + + fn spread(held: &[(u8, u8)]) -> Spread { + let mut docs = Spread::default(); + for (key, value) in held { + docs.insert(*key, *value); + } + docs.finish(); + docs + } + + /// The projection of the map, computed from scratch: what `indexed(..)` must + /// return at every moment. + fn truth(docs: &Spread) -> Vec<(u8, u8)> { + let mut out = Vec::new(); + for (key, value) in docs.iter() { + out.push((value / 10, *key)); + out.push((value % 10, *key)); + } + out.sort(); + out.dedup(); + out + } + + #[test] + fn a_committed_index_is_the_projection_and_follows_every_finish() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + assert!(docs.index_is_derived()); + assert_eq!(docs.indexed(..), truth(&docs)); + assert_eq!(docs.indexed(1..=1), vec![(1, 1), (1, 2)]); + + docs.insert(1, 32); + docs.remove(&2); + docs.insert(4, 44); + docs.finish(); + assert!(docs.index_is_derived(), "old points leave, new points arrive"); + assert_eq!(docs.indexed(..), truth(&docs)); + assert!(docs.indexed(0..=0).is_empty() && docs.indexed(1..=1).is_empty()); + } + + #[test] + fn a_read_inside_a_transaction_sees_the_log_and_the_index_does_not() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + docs.insert(1, 55); + docs.remove(&2); + docs.insert(7, 12); + assert_eq!(docs.indexed(..), truth(&docs), "the read is true mid-transaction"); + assert!(!docs.indexed(0..=0).iter().any(|(_, key)| *key == 1), "an overwritten value leaves its old points"); + assert!(docs.indexed(5..=5).contains(&(5, 1)), "a new value is seen at once"); + assert!(docs.indexed(..).iter().all(|(_, key)| *key != 2), "a removed document is gone"); + for point in 0..=9 { + assert_eq!( + docs.indexed(point..=point), + truth(&docs).into_iter().filter(|(p, _)| *p == point).collect::>() + ); + } + assert!(!docs.index_is_derived(), "the open log has not reached the index"); + + docs.insert(1, 10); + docs.insert(7, 12); + docs.remove(&7); + assert_eq!(docs.indexed(..), truth(&docs), "a key written back or added and removed adds nothing"); + } + + #[test] + fn rollback_leaves_the_index_as_it_was_because_it_never_saw_the_transaction() { + let mut docs = spread(&[(1, 10), (2, 21)]); + let before = docs.indexed(..); + docs.insert(1, 99); + docs.insert(5, 35); + docs.remove(&2); + docs.rollback(); + assert!(docs.index_is_derived()); + assert_eq!(docs.indexed(..), before); + assert_eq!(docs.indexed(..), truth(&docs)); + } + + #[test] + fn an_index_read_counts_the_entries_it_returns() { + let docs = spread(&[(1, 10), (2, 21), (3, 33)]); + let before = rows_read(); + let found = docs.indexed(..); + assert_eq!(rows_read() - before, found.len() as u64); + let before = rows_read(); + assert_eq!(docs.indexed(1..=1).len(), 2); + assert_eq!(rows_read() - before, 2); + } + + /// Arbitrary interleavings of every write, finish and rollback, read back + /// over arbitrary ranges: `indexed` equals the projection computed from the + /// map at every step, and the index is the rebuild after each close. + #[test] + fn indexed_equals_truth_over_a_random_walk_of_writes_and_ranges() { + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut next = move |bound: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % bound + }; + let mut docs = spread(&[(0, 5), (1, 17), (2, 17)]); + for step in 0..4000 { + let key = next(12) as u8; + match next(8) { + 0 | 1 => { + docs.insert(key, next(100) as u8); + } + 2 => { + docs.remove(&key); + } + 3 => { + if let Some(value) = docs.get_mut(&key) { + *value = (next(100)) as u8; + } + } + 4 => { + let fresh = next(100) as u8; + docs.entry(key).or_insert(fresh); + } + 5 => { + docs.finish(); + assert!(docs.index_is_derived(), "step {step}: after finish"); + } + 6 => { + docs.rollback(); + assert!(docs.index_is_derived(), "step {step}: after rollback"); + } + _ => {} + } + let (a, b) = (next(11) as u8, next(11) as u8); + let (lo, hi) = (a.min(b), a.max(b)); + let all = truth(&docs); + assert_eq!(docs.indexed(..), all, "step {step}: full range"); + let within = |keep: &dyn Fn(u8) -> bool| -> Vec<(u8, u8)> { + all.iter().copied().filter(|(point, _)| keep(*point)).collect() + }; + assert_eq!(docs.indexed(lo..=hi), within(&|p| (lo..=hi).contains(&p)), "step {step}: {lo}..={hi}"); + assert_eq!(docs.indexed(..hi), within(&|p| p < hi), "step {step}: ..{hi}"); + } + } + + #[test] + fn indexed_unchanged_names_the_committed_entries_of_keys_the_log_did_not_change() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33), (4, 11)]); + docs.insert(1, 55); // changed + docs.remove(&2); // removed + docs.insert(3, 33); // touched, written back: unchanged + docs.insert(9, 11); // added: not in the committed index + let before = rows_read(); + let found = docs.indexed_unchanged(1..=1); + assert_eq!(found, vec![(1, 4)], "only the committed entries of unchanged keys"); + assert_eq!(rows_read() - before, 1, "no walk of the log, only the entries returned"); + assert_eq!(docs.indexed_unchanged(..), vec![(1, 4), (3, 3)], "key 3 written back counts as unchanged"); + } + + #[test] + fn walking_the_open_log_is_counted_even_when_nothing_matches() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + docs.insert(1, 11); + docs.insert(9, 99); + let before = rows_read(); + assert!(docs.indexed(5..=5).is_empty()); + assert_eq!(rows_read() - before, 2, "two logged keys were walked"); + } + + #[test] + fn a_damaged_index_is_seen_as_not_derived() { + for stray in [true, false] { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + assert!(docs.corrupt_index_for_test(stray)); + assert!(!docs.index_is_derived(), "stray={stray}"); + } + let mut empty = Spread::default(); + assert!(!empty.corrupt_index_for_test(true) && !empty.corrupt_index_for_test(false)); + } + + fn contents(docs: &Rows) -> Vec<(u8, u8)> { + docs.iter().map(|(key, value)| (*key, *value)).collect() + } + + #[test] + fn a_write_is_reported_with_the_value_the_transaction_began_with() { + let mut docs = rows(&[(1, 10), (2, 20)]); + docs.insert(1, 11); + docs.insert(1, 12); + docs.insert(3, 30); + docs.remove(&2); + let mut changed = docs.finish(); + changed.sort(); + assert_eq!(changed, vec![(1, Some(10)), (2, Some(20)), (3, None)]); + assert!(docs.finish().is_empty(), "finish empties the log"); + assert!(docs.is_clean()); + } + + #[test] + fn a_key_written_back_to_what_it_was_is_not_a_change() { + let mut docs = rows(&[(1, 10), (2, 20)]); + docs.insert(1, 11); + docs.insert(1, 10); + docs.insert(3, 30); + docs.remove(&3); + *docs.get_mut(&2).unwrap() = 20; + *docs.entry(2).or_insert(0) = 20; + assert!(docs.changes().next().is_none()); + assert!(docs.finish().is_empty()); + } + + #[test] + fn a_get_mut_that_misses_touches_nothing() { + let mut docs = rows(&[(1, 10)]); + assert!(docs.get_mut(&9).is_none()); + assert!(docs.is_clean()); + *docs.get_mut(&1).unwrap() += 1; + assert!(!docs.is_clean()); + assert_eq!(docs.finish(), vec![(1, Some(10))]); + } + + #[test] + fn an_entry_that_adds_a_row_is_a_change_and_one_that_finds_it_is_not() { + let mut docs = rows(&[(1, 10)]); + docs.entry(1).or_insert(99); + docs.entry(2).or_insert(20); + assert_eq!(docs.finish(), vec![(2, None)]); + assert_eq!(contents(&docs), vec![(1, 10), (2, 20)]); + } + + #[test] + fn rollback_restores_every_touched_key_and_empties_the_log() { + let mut docs = rows(&[(1, 10), (2, 20), (3, 30)]); + docs.insert(1, 11); + docs.insert(4, 40); + docs.remove(&2); + *docs.get_mut(&3).unwrap() = 31; + *docs.entry(5).or_insert(0) = 50; + docs.rollback(); + assert_eq!(contents(&docs), vec![(1, 10), (2, 20), (3, 30)]); + assert!(docs.is_clean()); + } + + #[test] + fn every_row_an_iterator_yields_is_counted_and_point_reads_are_not() { + let docs = rows(&[(1, 10), (2, 20), (3, 30), (4, 40)]); + let before = rows_read(); + assert_eq!(docs.iter().count(), 4); + assert_eq!(rows_read() - before, 4); + assert_eq!(docs.keys().count() + docs.values().count(), 8); + assert_eq!(docs.range(2..4).count(), 2); + assert_eq!((&docs).into_iter().rev().take(1).count(), 1); + assert_eq!(rows_read() - before, 4 + 8 + 2 + 1); + let before = rows_read(); + assert_eq!(docs.get(&2), Some(&20)); + assert!(docs.contains_key(&3) && docs[&4] == 40); + assert_eq!(docs.len(), 4); + assert_eq!(rows_read(), before); + } + + #[test] + fn equality_is_the_documents_and_not_the_log() { + let mut open = rows(&[(1, 10)]); + open.insert(1, 11); + open.insert(1, 10); + assert_eq!(open, rows(&[(1, 10)])); + } + + #[test] + fn the_header_is_logged_once_and_a_genesis_value_is_an_addition() { + let mut header = Tracked::absent(5u8); + assert_eq!(header.finish(), Some(None), "genesis adds the header"); + + *header.get_mut() = 6; + *header.get_mut() = 7; + assert_eq!(header.finish(), Some(Some(5))); + assert!(header.is_clean()); + + *header.get_mut() = 8; + *header.get_mut() = 7; + assert_eq!(header.finish(), None, "written back is not a change"); + + *header.get_mut() = 9; + header.rollback(); + assert_eq!(*header, 7); + assert!(header.is_clean()); + } +} diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs new file mode 100644 index 000000000..bba7e99a1 --- /dev/null +++ b/native/aetherlight/src/golden_tests.rs @@ -0,0 +1,2405 @@ +//! The pinned replay of one scripted session, and the commit-cost harness. +//! +//! The golden file is the determinism contract in its smallest form: every +//! committed revision's state digest and commit digest, and the digest of the +//! export, for a session that touches speech, display, a routine and a refusal. +//! A change to any id derivation, schema, encoding or reducer arm moves a line. + +use crate::tests::{ + affordance_named, auth_principal, command, creation, first_grant, operations, owner, + play_caller, play_command, speak, subject_by_label, submit_play, tick_body, +}; +use crate::patch::{ + AffordanceDeclaration, AffordanceKindName, AudienceSpec, Declaration, DraftHandle, + OutcomeBand, Precondition, +}; +use crate::{ + AuthenticatedCaller, CommandBody, CommitmentKind, ComponentOp, DecisionInvocation, + FictionalMinutes, KernelError, KnowledgeSource, Ref, Statement, TickMinutes, WorldEffect, + WorldKernel, WorldPatch, +}; +use sha2::{Digest, Sha256}; +use std::time::Instant; + +/// The script: The Human speaks to The Witness, The Human shows a gesture, a +/// two-band `toss` is declared, granted to The Human and used three times (so +/// the band draw is recorded), a Routine is placed on The Witness, thirty minutes roll it, and The Human +/// invokes `convene`, which it does not hold. +pub(super) fn golden_session() -> (WorldKernel, String) { + let (mut kernel, _) = WorldKernel::create(creation("Golden"), &auth_principal(owner())) + .expect("the fixture world is created"); + let human = subject_by_label(&kernel.state, "The Human"); + let witness = subject_by_label(&kernel.state, "The Witness"); + + let snapshot = kernel.snapshot().unwrap(); + let speak_entry = first_grant(&snapshot, human); + submit_play( + &mut kernel, + &snapshot, + CommandBody::Act { + actor: human, + invocation: speak(speak_entry, "The vote carries."), + }, + ); + let heard = kernel.snapshot().unwrap(); + let witness_knowledge = &heard + .subjects + .iter() + .find(|subject| subject.id == witness) + .expect("the witness is a subject") + .knowledge; + assert!( + witness_knowledge.iter().any(|held| matches!( + held.source, + KnowledgeSource::Told { by, .. } if by == human + )), + "the witness holds what the human said as Told" + ); + + submit_play( + &mut kernel, + &heard, + CommandBody::Act { + actor: human, + invocation: DecisionInvocation { + affordance: speak_entry, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + display: Some(Statement::new("The Human raises one finger.").unwrap()), + }, + }, + ); + + // A two-band entry: the one place the golden records a band draw. + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("toss"), + kind: AffordanceKindName("toss".into()), + roles: Vec::new(), + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![ + OutcomeBand { weight: 1, effects: Vec::new() }, + OutcomeBand { weight: 1, effects: Vec::new() }, + ], + carries_speech: true, + })], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(human), + affordance: Ref::Draft(DraftHandle::new("toss")), + }], + evidence: Vec::new(), + }, + }, + ); + for _ in 0..3 { + let snapshot = kernel.snapshot().unwrap(); + let toss = affordance_named(&snapshot, "toss"); + submit_play( + &mut kernel, + &snapshot, + CommandBody::Act { + actor: human, + invocation: DecisionInvocation { + affordance: toss, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Heads or tails.").unwrap()), + display: None, + }, + }, + ); + } + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(witness), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(10), + period: Some(TickMinutes::new(10).unwrap()), + checks: Vec::new(), + statement: Statement::new("The Witness keeps the lamp.").unwrap(), + }]), + ); + + let snapshot = kernel.snapshot().unwrap(); + submit_play(&mut kernel, &snapshot, tick_body(30)); + let ticked = kernel.journal.commits_for_test(); + let WorldEffect::TimeAdvanced { motion, .. } = + &ticked.last().expect("the tick committed").effect + else { + panic!("the last commit is the tick"); + }; + assert!(!motion.fulfilled.is_empty(), "the routine rolled"); + + // The refusal changes nothing: not the revision, not either digest. + let before = kernel.snapshot().unwrap(); + let convene = affordance_named(&before, "convene"); + let refused = kernel.submit( + command( + &before, + play_caller(), + CommandBody::Act { + actor: human, + invocation: speak(convene, "A meeting is called."), + }, + ), + &AuthenticatedCaller::verified_play(), + ); + assert!(matches!(refused, Err(KernelError::AffordanceDenied)), "{refused:?}"); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.journal.commit_count(), 9); + + let mut file = String::new(); + for commit in kernel.journal.commits_for_test() { + file.push_str(&format!( + "{} {} {}\n", + commit.resulting_revision, commit.resulting_state_digest, commit.digest + )); + } + let export = kernel.export().unwrap(); + file.push_str(&format!("export sha256:{:x}\n", Sha256::digest(&export))); + (kernel, file) +} + +#[test] +fn golden_session_digests_are_fixed() { + let (_, computed) = golden_session(); + let (_, again) = golden_session(); + assert_eq!(computed, again, "one session, two runs, one file"); + let fixture: Vec<&str> = include_str!("../fixtures/golden.digests").lines().collect(); + let computed_lines: Vec<&str> = computed.lines().collect(); + assert!( + fixture == computed_lines, + "the golden digests moved; the computed file is:\n{computed}" + ); +} + +#[test] +fn export_open_round_trip_is_exact() { + let (mut original, _) = golden_session(); + let exported = original.export().unwrap(); + let mut reopened = WorldKernel::open(&exported).expect("the golden export opens"); + assert_eq!(reopened.state, original.state); + assert_eq!(reopened.snapshot().unwrap(), original.snapshot().unwrap()); + assert_eq!(reopened.export().unwrap(), exported); + + let human = subject_by_label(&original.state, "The Human"); + let snapshot = original.snapshot().unwrap(); + let next = play_command( + &snapshot, + CommandBody::Act { + actor: human, + invocation: speak(first_grant(&snapshot, human), "Order, please."), + }, + ); + let play = AuthenticatedCaller::verified_play(); + let original_receipt = original.submit(next.clone(), &play).unwrap(); + let reopened_receipt = reopened.submit(next, &play).unwrap(); + assert_eq!(original_receipt, reopened_receipt); + assert_eq!(original.export().unwrap(), reopened.export().unwrap()); +} + +/// The digest is what a replay or a fresh recompute would derive, at every +/// revision of the golden session and after reopening it, and also across a +/// removal, which the session itself never makes. +#[test] +fn incremental_digest_equals_full_recompute() { + let (mut kernel, _) = golden_session(); + let commits = kernel.journal.commits_for_test(); + for (index, commit) in commits.iter().enumerate() { + let replayed = crate::journal::verify_history(&commits[..=index]).unwrap(); + assert_eq!( + replayed.full_state_digest().unwrap(), + commit.resulting_state_digest, + "revision {index}: the incremental digest left the full recompute" + ); + } + assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); + + // A removal: the witness forgets what it was told. + let witness = subject_by_label(&kernel.state, "The Witness"); + let (fact, _) = kernel + .state + .knowledge_of(witness) + .next() + .expect("the witness knows something"); + let fact = *fact; + let rows = kernel.state.knowledge.len(); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(witness), + fact: Ref::Existing(fact), + }]), + ); + assert_eq!(kernel.state.knowledge.len(), rows - 1, "a row was removed"); + assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); + + let reopened = WorldKernel::open(&kernel.export().unwrap()).unwrap(); + assert_eq!(reopened.state.full_state_digest().unwrap(), reopened.state.state_digest); + assert_eq!(reopened.state.accumulator, kernel.state.accumulator); +} + +/// The clockwork world: `persons` persons, ten to a place, one Routine each +/// with period `persons / 2`, due `1 + i mod (persons / 2)`, so a one-minute +/// tick rolls two routines at every size and a speech reaches the same nine +/// listeners. Every partition a read index serves is populated, because an +/// empty one hides its scan: one route between consecutive places, one +/// `Reach::Place` channel per place controlled by its first person, one +/// institution per place with a warden office held by that person and a forum +/// for the place's grievances, and two Obligations past due from the first +/// minute, so a tick presses two sources at every size. +/// +/// Dependencies, retirement and checks grow with the world too, because +/// a partition that stays small hides the walk of it. Every person binds to the +/// previous live person (a satisfied dependency), and persons 0 and 1 also to +/// the last place's grain, which they do not hold: two failing dependencies at +/// every size. Every tenth person from the 35th retires (never a controller or +/// incumbent, who are place * 10), and every routine checks that its person +/// holds their place's grain. The clock then moves one period, so every +/// routine is past due: the live ones roll once, a retired person's stays due +/// for good, and a one-minute tick from there rolls two routines at every size. +fn clockwork_world(persons: usize) -> (WorldKernel, Vec, crate::AffordanceId) { + use crate::patch::kernel_speak_grant; + use crate::patch::{ + AccessKind, AuthoredSource, AuthorityGrantRef, AuthorityTargetRef, ChannelDeclaration, + DependencyRef, EntityDeclaration, EvidenceRef, FactDeclaration, FactStandingRef, + GrievanceKindName, PreconditionRef, Quantity, ReachRef, RouteDeclaration, + SubjectDeclaration, + }; + use crate::tests::{LEVY_KIND, TITHE_RECEIPT, WARDEN_OFFICE, authority_kind, office}; + use crate::Confidence; + use crate::{CallerId, CommandEnvelope, CreateWorld, Cost, EntityKind, SubjectKind}; + use std::collections::BTreeSet; + + let places = persons / 10; + let draft_place = |place: usize| Ref::Draft(DraftHandle::new(format!("place-{place}"))); + let draft_person = |person: usize| Ref::Draft(DraftHandle::new(format!("person-{person}"))); + let mut declarations = Vec::new(); + let mut offices = Vec::new(); + for place in 0..places { + declarations.push(Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(format!("place-{place}")), + label: format!("Place {place}"), + kind: EntityKind::Place, + container: None, + })); + if place + 1 < places { + declarations.push(Declaration::Route(RouteDeclaration { + handle: DraftHandle::new(format!("route-{place}")), + label: format!("Route {place}"), + from: draft_place(place), + to: draft_place(place + 1), + access: AccessKind::Public, + cost: Cost(1), + })); + } + declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new(format!("channel-{place}")), + label: format!("Channel {place}"), + reach: ReachRef::Place(draft_place(place)), + controller: Some(draft_person(place * 10)), + })); + declarations.push(Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(format!("grain-{place}")), + label: format!("Grain {place}"), + kind: EntityKind::Resource, + container: None, + })); + declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(format!("fact-{place}")), + label: format!("Fact {place}"), + statement: Statement::new("The place keeps its hour.").unwrap(), + standing: FactStandingRef::Canonical { evidence: EvidenceRef::new(TITHE_RECEIPT) }, + })); + let institution = DraftHandle::new(format!("institution-{place}")); + declarations.push(Declaration::Subject(SubjectDeclaration { + handle: institution.clone(), + label: format!("Institution {place}"), + kind: SubjectKind::Institution, + affordances: BTreeSet::new(), + position: None, + import_key: None, + })); + offices.push(ComponentOp::GrantAuthority { + holder: Ref::Draft(institution.clone()), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::PlaceSubtree(draft_place(place)), + }, + }); + offices.push(ComponentOp::OpenOffice { + institution: Ref::Draft(institution.clone()), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }); + offices.push(ComponentOp::InstallIncumbent { + institution: Ref::Draft(institution.clone()), + office: office(WARDEN_OFFICE), + incumbent: draft_person(place * 10), + }); + offices.push(ComponentOp::OpenForum { + grievance: GrievanceKindName(format!("grievance_{place}")), + forum: Ref::Draft(institution), + standing: AuthorityTargetRef::PlaceSubtree(draft_place(place)), + }); + } + for person in 0..persons { + let place = person / 10; + // One holding and one known fact per person, so `holdings`, `facts` and + // `knowledge` grow with the world and a scan of them breaks the gate. + offices.push(ComponentOp::Admit { + holder: draft_person(person), + resource: Ref::Draft(DraftHandle::new(format!("grain-{place}"))), + qty: Quantity(1), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }); + offices.push(ComponentOp::AcquireKnowledge { + subject: draft_person(person), + fact: Ref::Draft(DraftHandle::new(format!("fact-{place}"))), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }); + declarations.push(Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(format!("person-{person}")), + label: format!("Person {person}"), + kind: SubjectKind::Person, + affordances: kernel_speak_grant(), + position: Some(Ref::Draft(DraftHandle::new(format!("place-{}", person / 10)))), + import_key: None, + })); + } + let retires = |person: usize| person >= 35 && (person - 35) % 10 == 0; + for person in 0..persons { + if person > 0 { + // The previous person, or the one before when that one retires and + // so leaves the topology: the dependency stays satisfied. + let previous = if retires(person - 1) { person - 2 } else { person - 1 }; + offices.push(ComponentOp::Bind { + subject: draft_person(person), + target: DependencyRef::Subject(draft_person(previous)), + }); + } + if person < 2 { + offices.push(ComponentOp::Bind { + subject: draft_person(person), + target: DependencyRef::Resource(Ref::Draft(DraftHandle::new(format!( + "grain-{}", + places - 1 + )))), + }); + } + } + let (mut kernel, _) = WorldKernel::create( + CreateWorld { + owner: owner(), + title: "Clockwork".into(), + patch: WorldPatch { + declarations, + operations: offices, + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + grammar: None, + }, + &auth_principal(owner()), + ) + .expect("the clockwork world is created"); + let people: Vec<_> = (0..persons) + .map(|person| subject_by_label(&kernel.state, &format!("Person {person}"))) + .collect(); + let period = (persons / 2) as u64; + let grain_of_place: std::collections::BTreeMap = kernel + .state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Resource) + .map(|(id, record)| (record.label.clone(), *id)) + .collect(); + let mut routines: Vec = people + .iter() + .enumerate() + .map(|(index, subject)| ComponentOp::CreateCommitment { + subject: Ref::Existing(*subject), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(1 + index as u64 % period), + period: Some(TickMinutes::new(period as u32).unwrap()), + checks: vec![PreconditionRef::Holds { + resource: Ref::Existing(grain_of_place[&format!("Grain {}", index / 10)]), + at_least: Quantity(1), + }], + statement: Statement::new("Keeps the hour.").unwrap(), + }) + .collect(); + routines.extend(people[..2].iter().map(|subject| ComponentOp::CreateCommitment { + subject: Ref::Existing(*subject), + counterparty: Some(Ref::Existing(people[2])), + kind: CommitmentKind::Obligation, + due: FictionalMinutes(1), + period: None, + checks: Vec::new(), + statement: Statement::new("Owes the tithe.").unwrap(), + })); + let placing = CommandEnvelope { + world_id: kernel.state.header.world_id, + expected_revision: kernel.state.revision, + caller: CallerId::Play, + body: operations(routines), + }; + kernel + .submit(placing, &AuthenticatedCaller::verified_play()) + .expect("the routines are placed"); + let retired: Vec = (0..persons) + .filter(|person| retires(*person)) + .map(|person| ComponentOp::Retire { subject: Ref::Existing(people[person]) }) + .collect(); + if !retired.is_empty() { + let envelope = clockwork_envelope(&kernel, operations(retired)); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the retirements land"); + } + // One period on: every routine is past due, the live ones roll once. + let envelope = clockwork_envelope(&kernel, tick_body(period as u32)); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the clock moves one period"); + let speak_entry = *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "speak") + .map(|(id, _)| id) + .expect("genesis admits Speak"); + (kernel, people, speak_entry) +} + +fn clockwork_envelope(kernel: &WorldKernel, body: CommandBody) -> crate::CommandEnvelope { + crate::CommandEnvelope { + world_id: kernel.state.header.world_id, + expected_revision: kernel.state.revision, + caller: crate::CallerId::Play, + body, + } +} + +/// Submits and reports the document digests the commit computed beside the +/// ones its change set implies: added + removed + 2 x updated, counted by +/// enumerating every document before and after. +fn submit_counting_digests(kernel: &mut WorldKernel, body: CommandBody) -> (usize, usize) { + let before = kernel.state.documents().unwrap(); + let envelope = clockwork_envelope(kernel, body); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the commit lands"); + let computed = crate::digest::DOC_DIGESTS.with(|count| count.get()); + let after = kernel.state.documents().unwrap(); + let added = after.keys().filter(|key| !before.contains_key(*key)).count(); + let removed = before.keys().filter(|key| !after.contains_key(*key)).count(); + let updated = after + .iter() + .filter(|(key, digest)| before.get(*key).is_some_and(|old| old != *digest)) + .count(); + (computed, added + removed + 2 * updated) +} + +/// A commit's digest work is what it changed, not what the world holds: a tick +/// and a speech cost the same number of document digests at 100 persons and at +/// 1600, and exactly Added + Removed + 2 x Updated of that commit. +#[test] +fn digest_work_is_equal_at_100_and_1600() { + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, speak_entry) = clockwork_world(persons); + let mut counts = Vec::new(); + for _ in 0..3 { + counts.push(submit_counting_digests(&mut kernel, tick_body(1))); + } + for index in 0..3 { + let speech = CommandBody::Act { + actor: people[index], + invocation: speak(speak_entry, &format!("Speech {index}.")), + }; + counts.push(submit_counting_digests(&mut kernel, speech)); + } + for (computed, implied) in &counts { + assert!(*computed > 0, "a commit changed documents and digested none"); + assert_eq!( + computed, implied, + "{persons} persons: digests != Added + Removed + 2 x Updated" + ); + } + worked.push(counts); + } + assert_eq!(worked[0], worked[1], "digest work grew with the world"); +} + +/// The ways a failed apply is injected: the revision overflow a tick meets after +/// it has written its documents, and the failure after the digest is folded and +/// the commit sealed, the last point before the world is kept. +#[derive(Clone, Copy, Debug)] +enum Failure { + RevisionOverflow, + AfterDigest, +} + +/// One command to fail, and the world to fail it in. +struct FailureCase { + name: &'static str, + kernel: WorldKernel, + body: CommandBody, +} + +/// Each case writes what its name says: the two ticks are checked against the +/// motion the clock derives for them, so a case cannot quietly stop writing. +fn failure_cases() -> Vec { + let mut cases = Vec::new(); + + let (kernel, _, _) = clockwork_world(20); + let to = kernel.state.header.now.checked_add(TickMinutes::new(1).unwrap()).unwrap(); + assert!(!crate::clock::derive_motion(&kernel.state, to).fulfilled.is_empty()); + cases.push(FailureCase { name: "a tick that rolls routines", kernel, body: tick_body(1) }); + + let (kernel, _, _) = crate::clock_tests::clock_kernel("Pressure"); + let to = kernel.state.header.now.checked_add(TickMinutes::new(200).unwrap()).unwrap(); + assert!(!crate::clock::derive_motion(&kernel.state, to).pressed.is_empty()); + cases.push(FailureCase { name: "a tick that writes pressure rows", kernel, body: tick_body(200) }); + + let (kernel, _) = golden_session(); + let human = subject_by_label(&kernel.state, "The Human"); + let snapshot = kernel.snapshot().unwrap(); + let body = CommandBody::Act { + actor: human, + invocation: speak(first_grant(&snapshot, human), "Order, please."), + }; + cases.push(FailureCase { name: "a speech", kernel, body }); + + let (kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let (fact, _) = kernel.state.knowledge_of(witness).next().expect("the witness knows"); + let body = operations(vec![ComponentOp::Forget { + subject: Ref::Existing(witness), + fact: Ref::Existing(*fact), + }]); + cases.push(FailureCase { name: "a forget", kernel, body }); + cases +} + +/// A failed apply leaves nothing behind: state, accumulator, digest, every +/// partition's bytes, every log and the journal as before, and the next honest +/// command commits. Each case is failed twice: by the revision overflow a tick +/// meets after it has written its documents, and by a failure after the digest +/// is folded and the commit sealed, the last point before the world is kept. +#[test] +fn a_failed_apply_rolls_back() { + for failure in [Failure::RevisionOverflow, Failure::AfterDigest] { + for FailureCase { name, mut kernel, body } in failure_cases() { + let label = format!("{name}, {failure:?}"); + let honest_revision = kernel.state.revision; + let before = kernel.state.clone(); + let bytes = before.encoded_documents(); + let commits = kernel.journal.commit_count(); + match failure { + Failure::RevisionOverflow => kernel.state.revision = u64::MAX, + Failure::AfterDigest => crate::INJECT_FAILURE_AFTER_DIGEST.set(true), + } + let envelope = clockwork_envelope(&kernel, body.clone()); + let error = kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap_err(); + crate::INJECT_FAILURE_AFTER_DIGEST.set(false); + match failure { + Failure::RevisionOverflow => { + assert!(matches!(error, KernelError::Serialization(_)), "{label}: {error:?}"); + } + Failure::AfterDigest => { + assert!(matches!(error, KernelError::Invariant(_)), "{label}: {error:?}"); + } + } + kernel.state.revision = honest_revision; + assert_eq!(kernel.state, before, "{label}: the failure left writes behind"); + assert_eq!(kernel.state.encoded_documents(), bytes, "{label}"); + assert_eq!(kernel.journal.commit_count(), commits, "{label}"); + assert!(kernel.state.header.is_clean(), "{label}: header log open"); + for (schema, docs) in kernel.state.partitions() { + assert!(docs.is_clean(), "{label}: {schema} log open"); + } + assert_eq!( + kernel.state.full_state_digest().unwrap(), + kernel.state.state_digest, + "{label}: the accumulator no longer matches the documents" + ); + assert_indexes_derived(&kernel.state, &format!("{label}, after the failure")); + assert!( + kernel.state.views.same_as(&crate::views::Views::rebuild(&kernel.state)), + "{label}: the failure left the views behind" + ); + + let envelope = clockwork_envelope(&kernel, body); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap_or_else(|error| panic!("{label}: the next honest command: {error:?}")); + assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); + assert_indexes_derived(&kernel.state, &format!("{label}, after the honest command")); + assert!( + kernel.state.views.same_as(&crate::views::Views::rebuild(&kernel.state)), + "{label}: the views left their documents" + ); + } + } +} + +/// Worlds that between them hold a document in every partition: the golden +/// session, the civic, custody and speech benches and the ticked clock bench. +pub(crate) fn populated_worlds() -> Vec { + use crate::tests::{auth_principal, civic_world, creation, custody_world, owner, speech_world}; + let created = |title: &str| { + WorldKernel::create(creation(title), &auth_principal(owner())).unwrap().0 + }; + let mut worlds = vec![golden_session().0.state]; + // Two subjects holding import keys, so the subjects' `ByImportKey` index has + // points to read and to damage. + let mut keyed = crate::tests::creation("Keyed"); + for declaration in &mut keyed.patch.declarations { + if let Declaration::Subject(subject) = declaration { + let record = subject.label.clone(); + subject.import_key = Some(crate::ImportKey::new("aetherlight.fixture", record)); + } + } + worlds.push(WorldKernel::create(keyed, &auth_principal(owner())).unwrap().0.state); + let mut kernel = created("Civic"); + civic_world(&mut kernel); + worlds.push(kernel.state); + let mut kernel = created("Custody"); + custody_world(&mut kernel); + worlds.push(kernel.state); + let mut kernel = created("Speech"); + speech_world(&mut kernel); + worlds.push(kernel.state); + let (mut kernel, _, _) = crate::clock_tests::clock_kernel("Pressure"); + let tick = clockwork_envelope(&kernel, tick_body(200)); + kernel.submit(tick, &AuthenticatedCaller::verified_play()).unwrap(); + worlds.push(kernel.state); + worlds +} + +/// Membership of the partition table is behaviour: for every partition the +/// declaration names, one written document is in the folded digest and agrees +/// with the full recompute, is put back by a rollback, and leaves the log empty +/// and the accumulator at the full recompute when the transaction finishes. The +/// loop runs over the declaration, so a partition added to it is covered, and a +/// partition no fixture populates fails here rather than going untested. +#[test] +fn every_partition_is_digested_undone_and_finished() { + let worlds = populated_worlds(); + for index in 0..crate::WorldState::PARTITIONS { + let schema = worlds[0].partitions()[index].0; + let base = worlds + .iter() + .find(|world| world.partitions()[index].1.rows() > 0) + .unwrap_or_else(|| panic!("no fixture world holds a document in {schema}")); + let written = |state: &mut crate::WorldState| { + state.begin(); + assert!(state.partitions_mut()[index].1.remove_first(), "{schema}: nothing to write"); + let folded = state.folded().unwrap(); + assert_ne!(folded, state.accumulator, "{schema}: the write is not in the digest"); + assert_eq!( + folded.state_digest(state.revision), + state.full_state_digest().unwrap(), + "{schema}: the folded digest left the full recompute" + ); + folded + }; + let clean = |state: &crate::WorldState| { + state.header.is_clean() && state.partitions().iter().all(|(_, docs)| docs.is_clean()) + }; + + let mut state = base.clone(); + written(&mut state); + assert!(!state.partitions()[index].1.is_clean(), "{schema}: the write is not logged"); + state.rollback(); + assert_eq!(&state, base, "{schema}: rollback left the write behind"); + assert_eq!(state.encoded_documents(), base.encoded_documents(), "{schema}"); + assert!(clean(&state), "{schema}: rollback left a log open"); + + let mut state = base.clone(); + let folded = written(&mut state); + state.finish(folded); + assert!(clean(&state), "{schema}: finish left a log open"); + assert_ne!(&state, base, "{schema}: finish dropped the write"); + assert_eq!( + state.accumulator.state_digest(state.revision), + state.full_state_digest().unwrap(), + "{schema}: the finished accumulator left the full recompute" + ); + } +} + +/// What one tick and one speech cost to commit as the world grows, by the +/// clockwork world above: time, document digests and rows read (Docs rows plus +/// index entries) per commit, and the 1600/100 ratios. Run on its own, in +/// release, to read the numbers; nothing is asserted here. Wall time is noise +/// at this scale (a 30-sample mean ratio of speech ran 2.1 to 4.2 over runs +/// whose rows were flat), so each figure is the median of 200 commits, ticks +/// and speeches interleaved so drift and cache state fall on both, and the +/// gate is `read_work_is_equal_at_100_and_1600`, which counts the rows each +/// commit reads and fails when one grows with the world, and +/// `digest_work_is_equal_at_100_and_1600` for what a commit digests. +/// +/// `cargo test --release --lib clockwork_commit_cost -- --ignored --nocapture` +#[test] +#[ignore] +fn clockwork_commit_cost() { + const SAMPLES: usize = 200; + fn median(mut values: Vec) -> f64 { + values.sort_by(|a, b| a.partial_cmp(b).expect("a time")); + values[values.len() / 2] + } + println!( + "persons create_ms tick_ms tick_digests tick_rows speech_ms speech_digests speech_rows" + ); + let mut ticks_ms = Vec::new(); + let mut speeches_ms = Vec::new(); + for persons in [100usize, 400, 1600] { + let started = Instant::now(); + let (mut kernel, people, speak_entry) = clockwork_world(persons); + let create_ms = started.elapsed().as_secs_f64() * 1e3; + let play = AuthenticatedCaller::verified_play(); + + let (mut ticks, mut speeches) = (Vec::new(), Vec::new()); + let (mut tick_digests, mut tick_rows, mut speech_digests, mut speech_rows) = (0, 0, 0, 0); + for index in 0..SAMPLES { + let body = if index % 2 == 0 { + CommandBody::AdvanceTime { minutes: TickMinutes::new(1).unwrap() } + } else { + CommandBody::Act { + actor: people[index % 30], + invocation: speak(speak_entry, &format!("Speech {index}.")), + } + }; + let is_tick = index % 2 == 0; + let envelope = clockwork_envelope(&kernel, body); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + let rows = crate::docs::rows_read(); + let started = Instant::now(); + kernel.submit(envelope, &play).expect("the commit lands"); + let elapsed = started.elapsed().as_secs_f64() * 1e3; + let digests = crate::digest::DOC_DIGESTS.with(|count| count.get()); + let rows = crate::docs::rows_read() - rows; + if is_tick { + ticks.push(elapsed); + (tick_digests, tick_rows) = (digests, rows); + } else { + speeches.push(elapsed); + (speech_digests, speech_rows) = (digests, rows); + } + } + let (tick, speech) = (median(ticks), median(speeches)); + println!( + "{persons:>7} {create_ms:>9.1} {tick:>7.3} {tick_digests:>12} {tick_rows:>9} {speech:>9.3} {speech_digests:>14} {speech_rows:>11}", + ); + ticks_ms.push(tick); + speeches_ms.push(speech); + } + println!( + "ratio of medians 1600/100: tick {:.2} speech {:.2}", + ticks_ms[2] / ticks_ms[0], + speeches_ms[2] / speeches_ms[0] + ); +} + +/// What opening a world costs as it grows: `WorldKernel::open` of the clockwork +/// world's export replays genesis and every commit as bulk commits, which the +/// per-commit gate does not see. Median of five opens per size; nothing asserted +/// (rows are pinned by `folding_a_bulk_commit_reads_rows_in_proportion_to_the_change`). +/// +/// `cargo test --release --lib open_cost -- --ignored --nocapture` +#[test] +#[ignore] +fn open_cost() { + println!("persons open_ms"); + for persons in [200usize, 400, 800, 1600, 3200] { + let (kernel, _, _) = clockwork_world(persons); + let exported = kernel.export().unwrap(); + let mut times: Vec = (0..5) + .map(|_| { + let started = Instant::now(); + WorldKernel::open(&exported).expect("the world opens"); + started.elapsed().as_secs_f64() * 1e3 + }) + .collect(); + times.sort_by(|a, b| a.partial_cmp(b).expect("a time")); + println!("{persons:>7} {:>7.1}", times[2]); + } +} + +/// A document written back to what it was costs no digest: the transaction +/// logged it, and folding finds nothing changed. A real change costs two (the +/// old, subtracted, and the new, added) and moves the accumulator. +#[test] +fn a_touched_document_written_back_costs_no_digest() { + let (mut kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let before = kernel.state.accumulator.clone(); + let digests = || crate::digest::DOC_DIGESTS.with(|count| count.get()); + + kernel.state.begin(); + let now = kernel.state.header.now; + kernel.state.header.get_mut().now = now; + kernel.state.commitments.get_mut(&witness).expect("the witness holds a routine"); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + assert_eq!(kernel.state.folded().unwrap(), before); + assert_eq!(digests(), 0, "an unchanged document was digested"); + + kernel.state.header.get_mut().now = FictionalMinutes(now.0 + 1); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + assert_ne!(kernel.state.folded().unwrap(), before); + assert_eq!(digests(), 2, "an updated document is its old digest and its new"); + kernel.state.rollback(); + assert_eq!(kernel.state.header.now, now); +} + +/// A transaction is never opened over an open one, nor over a stray write. +#[cfg(debug_assertions)] +#[test] +#[should_panic(expected = "a transaction is open")] +fn begin_refuses_an_open_header_log() { + let (mut kernel, _) = golden_session(); + kernel.state.header.get_mut(); + kernel.state.begin(); +} + +#[cfg(debug_assertions)] +#[test] +#[should_panic] +fn begin_refuses_an_open_partition_log() { + let (mut kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + kernel.state.commitments.get_mut(&witness); + kernel.state.begin(); +} + +/// The snapshot's `known_by` is the knowledge partition read the other way: +/// exactly the subjects holding a row for the fact. +#[test] +fn a_fact_is_known_by_exactly_the_subjects_holding_a_row() { + let (kernel, _) = golden_session(); + let snapshot = kernel.snapshot().unwrap(); + assert!(snapshot.facts.iter().any(|fact| !fact.known_by.is_empty())); + for fact in &snapshot.facts { + let holders: Vec<_> = kernel + .state + .subjects + .keys() + .filter(|subject| kernel.state.knowledge.contains_key(&(**subject, fact.id))) + .copied() + .collect(); + assert_eq!(fact.known_by, holders); + } +} + +/// A knowledge row names a live subject and a canonical fact, each judged on +/// its own. +#[test] +fn a_knowledge_row_without_a_subject_or_a_fact_is_corrupt() { + use crate::tests::subject_by_label; + let (kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let (fact, held) = kernel + .state + .knowledge_of(witness) + .next() + .map(|(fact, held)| (*fact, *held)) + .expect("the witness knows something"); + crate::journal::verify_state_shape(&kernel.state).expect("the honest state passes"); + + let mut no_subject = kernel.state.clone(); + no_subject.knowledge.insert((crate::SubjectId::issue(), fact), held); + assert!(crate::journal::verify_state_shape(&no_subject).is_err()); + + let mut no_fact = kernel.state.clone(); + no_fact.knowledge.insert((witness, crate::EntityId::issue()), held); + assert!(crate::journal::verify_state_shape(&no_fact).is_err()); +} + +/// The text a document is keyed by is the contract the digest hashes: an id's +/// uuid, a pair's two joined by a slash, a grievance kind's name. +#[test] +fn document_keys_are_canonical_text() { + use crate::docs::DocKey; + let subject = crate::SubjectId::issue(); + let fact = crate::EntityId::issue(); + assert_eq!(subject.key_text(), subject.0.to_string()); + assert_eq!((subject, fact).key_text(), format!("{}/{}", subject.0, fact.0)); + assert_eq!(crate::patch::GrievanceKindName("theft".into()).key_text(), "theft"); +} + +/// The snapshot says a commitment is past due exactly when its due minute has +/// been reached: the golden's routine rolled once by a thirty-minute tick and +/// is due again at or before the clock. +#[test] +fn a_commitment_due_at_or_before_the_clock_reads_past_due() { + let (kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let snapshot = kernel.snapshot().unwrap(); + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == witness) + .expect("the witness is a subject"); + assert!(!subject.commitments.is_empty()); + for commitment in &subject.commitments { + assert_eq!(commitment.past_due, commitment.due <= kernel.state.header.now); + } + assert!( + subject.commitments.iter().any(|commitment| commitment.past_due), + "the routine fell due behind the clock" + ); +} + +/// Rows (Docs rows and index entries) one submit read. +fn submit_counting_rows(kernel: &mut WorldKernel, body: CommandBody) -> u64 { + let envelope = clockwork_envelope(kernel, body); + let before = crate::docs::rows_read(); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the commit lands"); + crate::docs::rows_read() - before +} + +/// A commit's read work is what it touches, not what the world holds: a tick +/// that rolls two routines and presses two obligations, and a colocated speech, +/// read the same number of rows at 100 persons and at 1600. The count is taken +/// where reads are owned (`Docs`), so a reader that scans a partition cannot +/// hide from it. Wall time is not asserted anywhere: it is noise at this scale. +#[test] +fn read_work_is_equal_at_100_and_1600() { + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, speak_entry) = clockwork_world(persons); + // The gate holds only if the partitions are populated at scale: an empty + // one hides a scan of it. + let state = &kernel.state; + assert!(state.holdings.len() >= persons && state.knowledge.len() >= persons); + assert!(state.facts.len() >= persons / 10 && state.channels.len() == persons / 10); + let retired: Vec<_> = + people.iter().copied().filter(|person| crate::is_retired(state, *person)).collect(); + assert!(retired.len() >= persons / 20, "{persons} persons: too few retired subjects"); + assert_eq!(state.positions.len() + retired.len(), persons, "a retired subject has no position"); + assert!(state.commitments.len() >= persons); + for person in &retired { + assert!( + state.commitments[person].values().any(|commitment| { + commitment.kind == CommitmentKind::Routine && commitment.due <= state.header.now + }), + "{persons} persons: a retired subject holds no past-due routine" + ); + } + for held in state.commitments.values() { + for commitment in held.values().filter(|c| c.kind == CommitmentKind::Routine) { + assert!( + matches!(commitment.checks.as_slice(), [crate::patch::BoundPrecondition::Holds { .. }]), + "{persons} persons: a routine without its Holds check" + ); + } + } + assert!(state.edges.len() + 1 == persons / 10 && state.selection.len() == persons / 10); + // A dependency per person and a forum per place, so a walk of either + // is seen; the clock reads only the two that fail. + assert!(state.dependencies.len() >= persons); + assert_eq!(state.redress.len(), persons / 10); + let mut counts = Vec::new(); + for _ in 0..3 { + counts.push(submit_counting_rows(&mut kernel, tick_body(1))); + } + for index in 0..3 { + let speech = CommandBody::Act { + actor: people[index], + invocation: speak(speak_entry, &format!("Speech {index}.")), + }; + counts.push(submit_counting_rows(&mut kernel, speech)); + } + assert!(counts.iter().all(|rows| *rows > 0), "{persons} persons: a commit read nothing"); + worked.push(counts); + } + assert_eq!(worked[0], worked[1], "read work grew with the world"); +} + +/// What a patch reads is what it touches, not what the world holds: ten patch +/// shapes, each submitted through `AdmitPatch` (resolution against the +/// candidate graph, the reducer, and the commit's own checks), read the same +/// number of rows at 100, 400 and 1600 persons (some read none: point reads are +/// not rows). The count is taken where reads +/// are owned (`Docs`), so a resolver arm that copies a partition, collects keys +/// from every subject, sums a resource over every holder, or judges every holder +/// for overlap cannot hide from it. The shapes run in order on one world, so +/// each leaves the world the next one reads. +#[test] +fn patch_read_work_is_equal_at_100_and_1600() { + use crate::patch::{ + AuthorityGrantRef, AuthorityTargetRef, AuthoredSource, DependencyRef, FactDeclaration, + FactStandingRef, PressureMagnitude, PressureSourceRef, Quantity, SubjectDeclaration, + }; + use crate::tests::{LEVY_KIND, WARDEN_OFFICE, authority_kind, office}; + use crate::{Confidence, ImportKey, SubjectKind}; + use std::collections::BTreeSet; + + let mut shapes: Vec<&'static str> = Vec::new(); + let mut worked: Vec> = Vec::new(); + for persons in [100usize, 400, 1600] { + let (mut kernel, people, _) = clockwork_world(persons); + let label = |kernel: &WorldKernel, label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .unwrap_or_else(|| panic!("{label} is declared")) + .0 + }; + let (place_zero, grain, fact_one) = ( + label(&kernel, "Place 0"), + label(&kernel, "Grain 0"), + label(&kernel, "Fact 1"), + ); + let route = *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "Route 0") + .expect("the first route is declared") + .0; + let institution = subject_by_label(&kernel.state, "Institution 0"); + + // The tick presses the two obligations; then every other person is + // pressed by one source, so the pressure partition holds a row for each. + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick presses the obligations"); + let pressing: Vec = people[1..] + .iter() + .map(|person| ComponentOp::AdvancePressure { + source: PressureSourceRef::Subject(Ref::Existing(people[0])), + target: Ref::Existing(*person), + by: PressureMagnitude(1), + }) + .collect(); + kernel + .submit( + clockwork_envelope(&kernel, operations(pressing)), + &AuthenticatedCaller::verified_play(), + ) + .expect("the pressure rows land"); + assert!(kernel.state.pressures.len() >= persons, "the pressure partition is at scale"); + let obligation = kernel.state.commitments[&people[0]] + .iter() + .find(|(_, commitment)| commitment.kind == CommitmentKind::Obligation) + .map(|(key, _)| *key) + .expect("the first person owes an obligation"); + + let patch = |declarations: Vec, operations: Vec| { + CommandBody::AdmitPatch { + patch: WorldPatch { declarations, operations, evidence: Vec::new() }, + } + }; + let bodies: Vec<(&'static str, CommandBody)> = vec![ + ( + "discharge a past-due obligation", + patch( + Vec::new(), + vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(people[0]), + key: obligation, + }], + ), + ), + ( + "relocate along a route", + patch( + Vec::new(), + vec![ComponentOp::Relocate { subject: Ref::Existing(people[5]), via: Ref::Existing(route) }], + ), + ), + ( + "declare a subject with an import key", + patch( + vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("newcomer"), + label: "The Newcomer".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::new(), + position: Some(Ref::Existing(place_zero)), + import_key: Some(ImportKey::new("aetherlight.gate", "newcomer")), + })], + Vec::new(), + ), + ), + ( + "transfer grain", + patch( + Vec::new(), + vec![ComponentOp::Transfer { + from: Ref::Existing(people[0]), + to: Ref::Existing(people[1]), + resource: Ref::Existing(grain), + qty: Quantity(1), + }], + ), + ), + ( + "witness a fact declared in the same patch", + patch( + vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("omen"), + label: "The Omen".into(), + statement: Statement::new("The lamp gutters.").unwrap(), + standing: FactStandingRef::Ruled, + })], + vec![ComponentOp::Witness { + fact: Ref::Draft(DraftHandle::new("omen")), + place: Ref::Existing(place_zero), + confidence: Confidence::Believed, + }], + ), + ), + ( + "grant authority", + patch( + Vec::new(), + vec![ComponentOp::GrantAuthority { + holder: Ref::Existing(people[7]), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::Subject(Ref::Existing(people[8])), + }, + }], + ), + ), + ( + "install an incumbent", + patch( + Vec::new(), + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(institution), + office: office(WARDEN_OFFICE), + incumbent: Ref::Existing(people[3]), + }], + ), + ), + ( + "acquire knowledge", + patch( + Vec::new(), + vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(people[2]), + fact: Ref::Existing(fact_one), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }], + ), + ), + ( + "bind a dependency", + patch( + Vec::new(), + vec![ComponentOp::Bind { + subject: Ref::Existing(people[4]), + target: DependencyRef::Subject(Ref::Existing(people[2])), + }], + ), + ), + ( + "retire a subject", + patch(Vec::new(), vec![ComponentOp::Retire { subject: Ref::Existing(people[9]) }]), + ), + ]; + let mut counts = Vec::new(); + for (shape, body) in bodies { + let rows = submit_counting_rows(&mut kernel, body); + if persons == 100 { + shapes.push(shape); + } + counts.push(rows); + } + eprintln!("{persons:>5} persons, rows per shape: {counts:?}"); + worked.push(counts); + } + for (index, shape) in shapes.iter().enumerate() { + let rows: Vec = worked.iter().map(|counts| counts[index]).collect(); + assert!( + rows.windows(2).all(|pair| pair[0] == pair[1]), + "{shape}: rows read grew with the world (100, 400, 1600): {rows:?}" + ); + } + // A shape that is point reads all the way down reads no rows at all; the + // counter must still be live, or equality proves nothing. + assert!(worked[0].iter().sum::() > 0, "no shape read a row: the counter is dead"); +} + +/// The pure reads no submit shape isolates, inside one open transaction each: +/// who stands under a two-level subtree, one incumbent's delegated authority, and +/// a path of three routes. (What a patch reads is gated through `AdmitPatch` by +/// `patch_read_work_is_equal_at_100_and_1600`.) +#[test] +fn operation_reads_are_equal_at_100_and_1600() { + use crate::Cost; + use std::collections::BTreeSet; + + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, _) = clockwork_world(persons); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick presses the obligations"); + let place = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared place") + .0 + }; + let (zero, one, two, three) = + (place("Place 0"), place("Place 1"), place("Place 2"), place("Place 3")); + + let state = &mut kernel.state; + state.begin(); + // Place 1 inside place 0, place 2 inside place 1. + state.entities.get_mut(&one).unwrap().container = Some(zero); + state.entities.get_mut(&two).unwrap().container = Some(one); + + let mut counts = Vec::new(); + let mut measure = |read: &mut dyn FnMut()| { + let before = crate::docs::rows_read(); + read(); + let rows = crate::docs::rows_read() - before; + assert!(rows > 0, "a read counted nothing"); + counts.push(rows); + }; + let mut under = BTreeSet::new(); + measure(&mut || under = crate::under_place(state, zero)); + assert_eq!(under.len(), 30, "places 0, 1 and 2 hold ten persons each"); + let mut delegated = Default::default(); + measure(&mut || delegated = crate::delegated_authority(state, people[0])); + assert_eq!(delegated.len(), 1, "the first person holds one office"); + let authority = BTreeSet::new(); + let mut reached = false; + measure(&mut || reached = crate::action::reachable(state, people[0], &authority, three, Cost(3))); + assert!(reached, "three routes of cost one reach place 3"); + state.rollback(); + worked.push(counts); + } + assert_eq!(worked[0], worked[1], "an operation's read work grew with the world"); +} + +/// The commit lane's checks read what the transaction wrote, not the world: +/// conservation sums the holders that were written, disjointness judges the +/// holders whose authority was written, and both cost the same rows at 100 and +/// 1600 persons. Each shape also has to be answered right: a holder already +/// written when the operations begin is measured from where it stood then, and +/// an overlap made by installing an incumbent, or by a grant, is refused with +/// every other holder untouched. +#[test] +fn apply_checks_read_the_log() { + use crate::patch::{AuthorityGrant, AuthorityTarget, ResolvedOp}; + use crate::tests::{LEVY_KIND, WARDEN_OFFICE, authority_kind, office}; + use crate::{Quantity, apply_operations}; + + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, _) = clockwork_world(persons); + let place = |label: &str| { + *kernel.state.entities.iter().find(|(_, record)| record.label == label).expect("declared").0 + }; + let (zero, one, grain) = (place("Place 0"), place("Place 1"), place("Grain 0")); + let institution = subject_by_label(&kernel.state, "Institution 0"); + let level = AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(one), + }; + let revision = kernel.state.revision + 1; + let transfer = ResolvedOp::Transfer { from: people[0], to: people[1], resource: grain, qty: Quantity(1) }; + let mut counts = Vec::new(); + let state = &mut kernel.state; + + // A transfer between two of ten holders: nothing else is read. + state.begin(); + let before = crate::docs::rows_read(); + apply_operations(state, std::slice::from_ref(&transfer), &[], revision) + .expect("a conserving transfer applies"); + counts.push(crate::docs::rows_read() - before); + state.rollback(); + + // A holder written before the operations begin is measured from there. + state.begin(); + crate::set_held(state, people[0], grain, 5); + let before = crate::docs::rows_read(); + apply_operations(state, std::slice::from_ref(&transfer), &[], revision) + .expect("the entry value is the before, not the value the transaction began with"); + counts.push(crate::docs::rows_read() - before); + state.rollback(); + + // Place 1 inside place 0, committed, with person 5's own grant over place 1. + state.begin(); + state.entities.get_mut(&one).unwrap().container = Some(zero); + state.authority.insert(people[5], std::collections::BTreeSet::from([level.clone()])); + let folded = state.folded().unwrap(); + state.finish(folded); + crate::journal::verify_state_shape(state).expect("the world is still disjoint"); + + // A grant that overlaps the warden's lent ground is refused. + state.begin(); + let overlap = ResolvedOp::GrantAuthority { holder: people[0], grant: level.clone() }; + let before = crate::docs::rows_read(); + let refused = apply_operations(state, &[overlap], &[], revision).unwrap_err(); + counts.push(crate::docs::rows_read() - before); + assert!( + matches!(&refused, crate::KernelError::Invariant(m) if m.contains("overlapping")), + "{persons}: {refused:?}" + ); + state.rollback(); + + // Seating a holder of overlapping ground in the office is refused too. + state.begin(); + let install = ResolvedOp::InstallIncumbent { + institution, + office: office(WARDEN_OFFICE), + incumbent: people[5], + }; + let before = crate::docs::rows_read(); + let refused = apply_operations(state, &[install], &[], revision).unwrap_err(); + counts.push(crate::docs::rows_read() - before); + assert!( + matches!(&refused, crate::KernelError::Invariant(m) if m.contains("overlapping")), + "{persons}: {refused:?}" + ); + state.rollback(); + + // Custody is point reads, which are free; the disjointness judgments read + // the office index. A refusal stops at the first overlapping holder, and + // which holder that is depends on id order, so its reads are bounded + // rather than equal: a few rows, where a scan of the world reads thousands. + assert!(counts[2..].iter().all(|rows| (1..=8).contains(rows)), "{persons}: {counts:?}"); + worked.push(counts[..2].to_vec()); + } + assert_eq!(worked[0], worked[1], "a commit check's read work grew with the world"); +} + +fn assert_indexes_derived(state: &crate::WorldState, label: &str) { + for (schema, docs) in state.partitions() { + assert!(docs.index_is_derived(), "{label}: the read index of {schema} left its documents"); + } +} + +/// The states a test walks: every revision of the golden session as replay +/// derives it, the live and reopened golden world, each populated world, and +/// forty commits of the clockwork world. +fn walked_states() -> Vec<(String, crate::WorldState)> { + let mut states = Vec::new(); + let (kernel, _) = golden_session(); + let commits = kernel.journal.commits_for_test(); + for index in 0..commits.len() { + let replayed = crate::journal::verify_history(&commits[..=index]).unwrap(); + states.push((format!("golden revision {index}"), replayed)); + } + let reopened = WorldKernel::open(&kernel.export().unwrap()).unwrap(); + states.push(("golden reopened".into(), reopened.state)); + states.push(("golden live".into(), kernel.state)); + for (index, world) in populated_worlds().into_iter().enumerate() { + states.push((format!("populated world {index}"), world)); + } + let (mut kernel, people, speak_entry) = clockwork_world(100); + states.push(("clockwork created".into(), kernel.state.clone())); + for step in 0..40 { + let body = if step % 2 == 0 { + tick_body(1) + } else { + CommandBody::Act { + actor: people[step % 30], + invocation: speak(speak_entry, &format!("Speech {step}.")), + } + }; + let envelope = clockwork_envelope(&kernel, body); + kernel.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(); + states.push((format!("clockwork commit {step}"), kernel.state.clone())); + } + let reopened = WorldKernel::open(&kernel.export().unwrap()).unwrap(); + states.push(("clockwork reopened".into(), reopened.state)); + states.push(("multivalue world".into(), multivalue_world())); + states.extend(view_scenario()); + states +} + +/// The commands that move what the views join, one at a time, each state kept: +/// dependencies bound on a route, a resource and a subject; the route closed +/// and reopened; the resource's holding emptied and refilled; a depended-on +/// subject loses its position; a dependent released; and a subject that holds +/// past-due routines and a failing dependency retires. +fn view_scenario() -> Vec<(String, crate::WorldState)> { + use crate::patch::{DependencyRef, EvidenceRef, Quantity}; + use crate::tests::TITHE_RECEIPT; + let (mut kernel, people, _) = clockwork_world(20); + let route = *kernel.state.edges.keys().next().expect("a route"); + let grain = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared resource") + .0 + }; + let (grain_0, grain_1) = (grain("Grain 0"), grain("Grain 1")); + let bind = |subject: usize, target: DependencyRef| ComponentOp::Bind { + subject: Ref::Existing(people[subject]), + target, + }; + let steps: Vec<(&str, CommandBody)> = vec![ + ( + "binds", + operations(vec![ + bind(5, DependencyRef::Route(Ref::Existing(route))), + bind(6, DependencyRef::Resource(Ref::Existing(grain_1))), + bind(7, DependencyRef::Subject(Ref::Existing(people[8]))), + bind(7, DependencyRef::Resource(Ref::Existing(grain_0))), + bind(3, DependencyRef::Subject(Ref::Existing(people[4]))), + ]), + ), + ("the route closes", operations(vec![ComponentOp::CloseRoute { route: Ref::Existing(route) }])), + ("the route reopens", operations(vec![ComponentOp::OpenRoute { route: Ref::Existing(route) }])), + ( + "a holding empties", + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(people[7]), + resource: Ref::Existing(grain_0), + qty: Quantity(1), + }]), + ), + ( + "the holding refills", + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(people[7]), + resource: Ref::Existing(grain_0), + qty: Quantity(1), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ), + // A retired dependent never fails: closing the route it names must leave no row. + ("a dependent on the route retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[5]) }])), + ("the route closes again", operations(vec![ComponentOp::CloseRoute { route: Ref::Existing(route) }])), + ("a long tick", tick_body(30)), + ("a depended-on subject retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[8]) }])), + ( + "a dependent is released", + operations(vec![ComponentOp::Release { + subject: Ref::Existing(people[3]), + target: DependencyRef::Subject(Ref::Existing(people[4])), + }]), + ), + ("a failing, past-due subject retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[6]) }])), + ("the route reopens after the retirement", operations(vec![ComponentOp::OpenRoute { route: Ref::Existing(route) }])), + ("a last tick", tick_body(30)), + ]; + let mut states = vec![("scenario created".to_owned(), kernel.state.clone())]; + for (name, body) in steps { + let envelope = clockwork_envelope(&kernel, body); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap_or_else(|error| panic!("{name}: {error:?}")); + states.push((format!("scenario: {name}"), kernel.state.clone())); + } + states +} + +/// A world where one document sits at several points: a pressure target fed by +/// three sources, and an institution whose offices have three distinct +/// incumbents, one of them in two offices. A projection that keeps only the +/// first or last of a document's points loses a row here and nowhere else. +fn multivalue_world() -> crate::WorldState { + use crate::patch::{Office, PressureMagnitude}; + use crate::tests::{LEVY_KIND, authority_kind, office}; + use crate::PressureSource; + let (mut kernel, people, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick commits"); + let mut state = kernel.state; + let institution = *state.selection.keys().next().expect("an institution holds offices"); + state.begin(); + for source in [people[1], people[2], people[3]] { + state + .pressures + .entry(people[5]) + .or_default() + .insert(PressureSource::Subject(source), PressureMagnitude(1)); + } + let delegated = std::collections::BTreeSet::from([authority_kind(LEVY_KIND)]); + let offices = state.selection.get_mut(&institution).unwrap(); + for (name, incumbent) in [("bailiff", people[3]), ("steward", people[3]), ("reeve", people[4])] { + offices.insert(office(name), Office { incumbent: Some(incumbent), delegated: delegated.clone() }); + } + let folded = state.folded().unwrap(); + state.finish(folded); + state +} + +/// Every read index is the projection of its partition and nothing else, after +/// every commit the walked worlds make, however the world was reached. +#[test] +fn indexes_are_derived() { + for (label, state) in walked_states() { + assert_indexes_derived(&state, &label); + // The rebuild above uses the projection itself, so a wrong projection + // agrees with its own index; the scans it replaced do not. + assert_eq!(reference_scan_disagreement(&state), None, "{label}"); + } +} + +/// The first place an index read and the scan it replaced disagree, if any. +fn reference_scan_disagreement(state: &crate::WorldState) -> Option { + use crate::{Audience, Cost, PressureSource}; + let subjects: Vec<_> = state.subjects.keys().copied().collect(); + let places: Vec<_> = state + .entities + .iter() + .filter(|(_, record)| record.kind == crate::EntityKind::Place) + .map(|(id, _)| *id) + .collect(); + for subject in &subjects { + if crate::audience(state, *subject, &Audience::Colocated) + != crate::audience_by_scan(state, *subject, &Audience::Colocated) + { + return Some(format!("colocated audience of {subject:?}")); + } + if crate::delegated_authority(state, *subject) + != crate::delegated_authority_by_scan(state, *subject) + { + return Some(format!("delegated authority of {subject:?}")); + } + if crate::channels_controlled_by(state, *subject) + != crate::channels_controlled_by_by_scan(state, *subject) + { + return Some(format!("channels controlled by {subject:?}")); + } + let authority = crate::subject_authority(state, *subject); + for place in &places { + if crate::action::reachable(state, *subject, &authority, *place, Cost(3)) + != crate::action::reachable_by_scan(state, *subject, &authority, *place, Cost(3)) + { + return Some(format!("reachable {place:?} from {subject:?}")); + } + } + } + let targets: std::collections::BTreeSet<_> = + state.dependencies.values().flat_map(|held| held.iter().copied()).collect(); + for target in targets { + let mut by_index = crate::views::Views::dependents_of(state, target); + by_index.sort(); + if by_index != crate::views::Views::dependents_by_scan(state, target) { + return Some(format!("dependents of {target:?}")); + } + } + let strange = crate::ImportKey::new("aetherlight.fixture", "held by nobody"); + for key in state + .subjects + .values() + .filter_map(|subject| subject.import_key.as_ref()) + .chain(std::iter::once(&strange)) + { + if state.import_key_held(key) != crate::import_key_held_by_scan(state, key) { + return Some(format!("import key {key:?} held")); + } + } + let unnamed = crate::patch::AffordanceKindName("no such kind".into()); + for kind in state + .affordance_catalog + .values() + .map(|entry| &entry.kind) + .chain(std::iter::once(&unnamed)) + { + if state.kind_taken(kind) != crate::kind_taken_by_scan(state, kind) { + return Some(format!("affordance kind {kind:?} taken")); + } + } + for place in &places { + if crate::under_place(state, *place) != crate::under_place_by_scan(state, *place) { + return Some(format!("under_place {place:?}")); + } + if crate::routes_at(state, *place) != crate::routes_at_by_scan(state, *place) { + return Some(format!("routes at {place:?}")); + } + } + for (channel, _) in state.channels.iter() { + let actor = subjects.first().copied()?; + if crate::audience(state, actor, &Audience::Channel(*channel)) + != crate::audience_by_scan(state, actor, &Audience::Channel(*channel)) + { + return Some(format!("audience of channel {channel:?}")); + } + } + let mut sources: Vec = state + .pressures + .iter() + .flat_map(|(_, held)| held.keys().copied()) + .collect(); + sources.extend(subjects.first().map(|first| PressureSource::Subject(*first))); + for source in sources { + if crate::pressure_holders(state, source) != crate::pressure_holders_by_scan(state, source) { + return Some(format!("holders of {source:?}")); + } + } + None +} + +/// Each read an index answers equals the scan it replaced, at every walked state. +#[test] +fn index_reads_equal_reference_scans() { + for (label, state) in walked_states() { + assert_eq!(reference_scan_disagreement(&state), None, "{label}"); + } +} + +/// A read inside an open transaction sees what the transaction wrote, though +/// the index has not: a subject moved through `positions` leaves its old room +/// and joins the new one, a removed pressure row no longer lists its source, and +/// after the rollback the reads are what they were. +#[test] +fn an_index_read_mid_transaction_sees_the_log() { + use crate::patch::Position; + use crate::{Audience, PressureSource}; + let (mut kernel, people, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick presses the obligations"); + let state = &mut kernel.state; + let (mover, in_old, in_new) = (people[1], people[2], people[11]); + let new_place = state.positions[&in_new].place; + assert_ne!(state.positions[&mover].place, new_place); + let obligation = state.commitments[&people[0]] + .iter() + .find(|(_, commitment)| commitment.kind == CommitmentKind::Obligation) + .map(|(key, _)| *key) + .expect("the first person owes an obligation"); + let source = PressureSource::Commitment { subject: people[0], key: obligation }; + let reads = |state: &crate::WorldState| { + ( + crate::audience(state, in_old, &Audience::Colocated), + crate::audience(state, in_new, &Audience::Colocated), + crate::pressure_holders(state, source), + ) + }; + let before = reads(state); + assert!(before.0.contains(&mover) && !before.1.contains(&mover)); + assert!(before.2.contains(&people[0])); + + state.begin(); + state.positions.insert(mover, Position { place: new_place }); + state.pressures.remove(&people[0]); + let during = reads(state); + assert!(!during.0.contains(&mover), "the old room still lists the mover"); + assert!(during.1.contains(&mover), "the new room does not list the mover"); + assert!(!during.2.contains(&people[0]), "a removed pressure row still lists its source"); + assert_eq!(reference_scan_disagreement(state), None, "mid-transaction reads equal the scans"); + state.rollback(); + + assert_indexes_derived(state, "after the rollback"); + assert_eq!(reads(state), before); +} + +/// The oracle can see an index that disagrees with its documents: damaged one +/// way (a document listed where it is not) or the other (a document left out), +/// every indexed partition reports it, and the reads the index serves then +/// differ from the scans they replaced. +#[test] +fn a_corrupted_index_is_detected() { + use std::collections::BTreeSet; + let mut worlds = populated_worlds(); + let (mut kernel, _, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .unwrap(); + worlds.push(kernel.state); + let mut reported = BTreeSet::new(); + let mut misread = BTreeSet::new(); + for world in &worlds { + for index in 0..crate::WorldState::PARTITIONS { + for stray in [true, false] { + let mut damaged = world.clone(); + if !damaged.partitions_mut()[index].1.corrupt_index_first(stray) { + continue; + } + let schema = damaged.partitions()[index].0; + assert!( + !damaged.partitions()[index].1.index_is_derived(), + "{schema}: damage (stray {stray}) went unseen" + ); + reported.insert(schema); + if reference_scan_disagreement(&damaged).is_some() { + misread.insert(schema); + } + } + } + } + let indexed: BTreeSet<&str> = [ + "aetherlight.subject.v1", + "aetherlight.affordance.v1", + "aetherlight.entity.v1", + "aetherlight.edge.v1", + "aetherlight.position.v1", + "aetherlight.channel.v1", + "aetherlight.selection.v1", + "aetherlight.dependencies.v1", + "aetherlight.pressures.v1", + ] + .into(); + assert_eq!(reported, indexed, "exactly the indexed partitions can be damaged"); + assert_eq!(misread, indexed, "a damaged index must change what a reader answers"); +} + +/// A view is derived from the documents and nothing else: after every commit of +/// the walked worlds, however each was reached, it is what a scan of the +/// committed documents builds. +#[test] +fn views_are_derived() { + for (label, state) in walked_states() { + assert!( + state.views.same_as(&crate::views::Views::rebuild(&state)), + "{label}: the views left their documents" + ); + } +} + +/// The motion the views derive is the motion the scans derive: every live +/// subject's due commitments and failing dependencies, over short and long +/// spans, in every walked state (which holds routes that close and reopen, +/// holdings that empty, subjects that lose a position, and subjects that retire +/// holding past-due routines and failing dependencies). +#[test] +fn view_reads_equal_reference_scans() { + let mut pressed_dependency = false; + for (label, state) in walked_states() { + for minutes in [1, 30, 5_000] { + let to = FictionalMinutes(state.header.now.0 + minutes); + let motion = crate::clock::derive_motion(&state, to); + assert_eq!(motion, crate::clock::derive_motion_by_scan(&state, to), "{label}, {minutes} minutes"); + pressed_dependency |= motion + .pressed + .iter() + .any(|written| matches!(written.source, crate::PressureSource::Dependency(_))); + } + } + assert!(pressed_dependency, "no walked state had a failing dependency to compare"); +} + +/// A damaged view is seen by the oracle and changes what the clock derives: a +/// stray failing row presses a dependency nobody holds, and a missing due +/// point leaves its subjects unmoved. +#[test] +fn a_corrupted_view_is_detected() { + let (mut kernel, _, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .unwrap(); + let state = kernel.state; + let to = FictionalMinutes(state.header.now.0 + 30); + assert!(state.views.same_as(&crate::views::Views::rebuild(&state))); + for stray in [true, false] { + let mut damaged = state.clone(); + assert!(damaged.views.corrupt_for_test(stray), "stray {stray}"); + assert!( + !damaged.views.same_as(&crate::views::Views::rebuild(&damaged)), + "stray {stray}: the oracle did not see the damage" + ); + assert_ne!( + crate::clock::derive_motion(&damaged, to), + crate::clock::derive_motion_by_scan(&damaged, to), + "stray {stray}: the damage changed no read" + ); + } +} + +/// A view is read only with clean logs: reading one while a partition it joins +/// has an open write is refused, not answered from a stale fold. +#[test] +#[should_panic(expected = "open log")] +fn a_view_read_with_an_open_log_is_refused() { + let (mut kernel, people, _) = clockwork_world(20); + kernel.state.begin(); + kernel.state.positions.remove(&people[3]); + crate::clock::derive_motion(&kernel.state, FictionalMinutes(1)); +} + +/// A dependency's pressure ends with the dependency: bind to a resource the +/// subject does not hold, let a tick press it, release it, and the row is gone +/// and the world still reopens from its export. +#[test] +fn releasing_a_dependency_removes_the_pressure_it_raised() { + use crate::patch::DependencyRef; + use crate::{DependencyTarget, PressureSource}; + let (mut kernel, people, _) = clockwork_world(20); + let grain_1 = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "Grain 1") + .expect("a declared resource") + .0; + let target = DependencyTarget::Resource(grain_1); + let pressed = PressureSource::Dependency(target); + let submit = |kernel: &mut WorldKernel, body| { + let envelope = clockwork_envelope(kernel, body); + kernel.submit(envelope, &AuthenticatedCaller::verified_play()).expect("the command lands"); + }; + submit( + &mut kernel, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(people[6]), + target: DependencyRef::Resource(Ref::Existing(grain_1)), + }]), + ); + submit(&mut kernel, tick_body(1)); + assert!( + kernel.state.pressures.get(&people[6]).is_some_and(|held| held.contains_key(&pressed)), + "the tick pressed the failing dependency" + ); + submit( + &mut kernel, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(people[6]), + target: DependencyRef::Resource(Ref::Existing(grain_1)), + }]), + ); + assert!( + kernel.state.pressures.get(&people[6]).is_none_or(|held| !held.contains_key(&pressed)), + "the released dependency's pressure row stayed" + ); + let reopened = WorldKernel::open(&kernel.export().unwrap()).expect("the world reopens"); + assert_eq!(reopened.state, kernel.state); +} + +/// A bulk commit (genesis, a large patch, every replayed commit at open) moves +/// many placements and touches many dependencies at once. Folding the views +/// for it reads rows in proportion to what the commit changed, not to changed +/// targets times touched dependencies: every person moves and binds a route in +/// one transaction, and 1600 persons read under six times the rows of 400. +#[test] +fn folding_a_bulk_commit_reads_rows_in_proportion_to_the_change() { + use crate::patch::Position; + use crate::DependencyTarget; + let mut rows = Vec::new(); + for persons in [400usize, 1600] { + let (kernel, people, _) = clockwork_world(persons); + let mut state = kernel.state; + let route = *state.edges.keys().next().expect("a route"); + let place = state.positions[&people[0]].place; + state.begin(); + for person in people.iter().filter(|person| state.positions.contains_key(person)).copied().collect::>() { + state.positions.insert(person, Position { place }); + state.dependencies.entry(person).or_default().insert(DependencyTarget::Route(route)); + } + let mut views = std::mem::take(&mut state.views); + let before = crate::docs::rows_read(); + views.fold(&state); + rows.push(crate::docs::rows_read() - before); + state.views = views; + state.rollback(); + } + assert!(rows[1] > rows[0], "{rows:?}: a bigger commit read no more"); + assert!(rows[1] < rows[0] * 6, "the fold read {} rows at 400 persons and {} at 1600", rows[0], rows[1]); +} + +/// Every kind of command that moves what the views join, drawn at random from a +/// seeded stream over the clockwork world (bind and release on a subject, a +/// route and a resource; routes closed and opened; holdings emptied and filled; +/// subjects relocated and retired; ticks and speech; refused commands), with the +/// world reopened from its export every 50 commits. After every commit, kept or +/// refused, the views are what a scan of the documents builds and the motion +/// they derive is the motion the scans derive, over short and long spans; each +/// reopened world holds the live views. Seeds are fixed, so a failure replays. +#[test] +fn views_equal_their_rebuild_and_the_scans_over_random_commands() { + use crate::patch::{DependencyRef, EvidenceRef, Quantity}; + use crate::tests::TITHE_RECEIPT; + use crate::DependencyTarget; + use std::collections::BTreeMap; + + let mut kept: BTreeMap<&'static str, usize> = BTreeMap::new(); + for seed in [1u64, 2, 3] { + let (mut kernel, people, speak_entry) = clockwork_world(40); + let routes: Vec<_> = kernel.state.edges.keys().copied().collect(); + let grains: Vec<_> = (0..4) + .map(|place| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == format!("Grain {place}")) + .expect("a declared resource") + .0 + }) + .collect(); + let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + let mut next = move |bound: usize| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state % bound as u64) as usize + }; + for step in 0..150 { + let person = people[next(people.len())]; + let route = routes[next(routes.len())]; + let grain = grains[next(grains.len())]; + let target = match next(3) { + 0 => DependencyRef::Subject(Ref::Existing(people[next(people.len())])), + 1 => DependencyRef::Route(Ref::Existing(route)), + _ => DependencyRef::Resource(Ref::Existing(grain)), + }; + let ops = |op| operations(vec![op]); + let (name, body) = match next(16) { + 0 | 1 => ("bind", ops(ComponentOp::Bind { subject: Ref::Existing(person), target })), + 2 | 3 => { + // Release something that is bound, so releases succeed. + let bound: Vec<_> = kernel + .state + .dependencies + .iter() + .flat_map(|(subject, held)| held.iter().map(|target| (*subject, *target))) + .collect(); + if bound.is_empty() { + ("tick", tick_body(1)) + } else { + let (subject, held) = bound[next(bound.len())]; + let target = match held { + DependencyTarget::Subject(other) => DependencyRef::Subject(Ref::Existing(other)), + DependencyTarget::Route(edge) => DependencyRef::Route(Ref::Existing(edge)), + DependencyTarget::Resource(entity) => DependencyRef::Resource(Ref::Existing(entity)), + }; + ("release", ops(ComponentOp::Release { subject: Ref::Existing(subject), target })) + } + } + 4 => ("close", ops(ComponentOp::CloseRoute { route: Ref::Existing(route) })), + 5 => ("open", ops(ComponentOp::OpenRoute { route: Ref::Existing(route) })), + 6 => ( + "consume", + ops(ComponentOp::Consume { + holder: Ref::Existing(person), + resource: Ref::Existing(grain), + qty: Quantity(1), + }), + ), + 7 => ( + "admit", + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(person), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ), + 8 => { + // Along a route that touches where the subject stands. + let here = kernel.state.positions.get(&person).map(|position| position.place); + let via = kernel + .state + .edges + .iter() + .find(|(_, edge)| { + let (from, to) = edge.endpoints(); + here.is_some_and(|place| place == from || place == to) + }) + .map(|(edge, _)| *edge) + .unwrap_or(route); + ("relocate", ops(ComponentOp::Relocate { subject: Ref::Existing(person), via: Ref::Existing(via) })) + } + 9 if next(5) == 0 => ("retire", ops(ComponentOp::Retire { subject: Ref::Existing(person) })), + 13 => ( + "speech", + CommandBody::Act { + actor: person, + invocation: speak(speak_entry, &format!("Speech {step}.")), + }, + ), + 14 => ( + "refused", + ops(ComponentOp::Bind { + subject: Ref::Existing(person), + target: DependencyRef::Subject(Ref::Existing(person)), + }), + ), + _ => ("tick", tick_body(1 + next(25) as u32)), + }; + let envelope = clockwork_envelope(&kernel, body); + if kernel.submit(envelope, &AuthenticatedCaller::verified_play()).is_ok() { + *kept.entry(name).or_default() += 1; + } + let label = format!("seed {seed}, commit {step} ({name})"); + assert!( + kernel.state.views.same_as(&crate::views::Views::rebuild(&kernel.state)), + "{label}: the views left their documents" + ); + for minutes in [1, 30, 5_000] { + let to = FictionalMinutes(kernel.state.header.now.0 + minutes); + assert_eq!( + crate::clock::derive_motion(&kernel.state, to), + crate::clock::derive_motion_by_scan(&kernel.state, to), + "{label}: motion over {minutes} minutes" + ); + } + if step % 50 == 49 { + let reopened = WorldKernel::open(&kernel.export().unwrap()) + .unwrap_or_else(|error| panic!("{label}: the world does not reopen: {error:?}")); + assert_eq!(reopened.state, kernel.state, "{label}: reopened state"); + assert!(reopened.state.views.same_as(&kernel.state.views), "{label}: reopened views"); + } + } + } + for name in ["bind", "release", "close", "open", "consume", "admit", "relocate", "retire", "speech", "tick"] { + assert!(kept.get(name).copied().unwrap_or(0) > 0, "no {name} ever landed: {kept:?}"); + } +} + +/// A holder written before the operations begin and returned by them to the +/// value it had when the transaction opened is no longer in the log, yet it +/// moved: conservation reads it from the entry record, so the transfer that +/// restores it is judged as conserving. +#[test] +fn apply_conserves_a_holder_restored_to_its_start_value() { + use crate::patch::ResolvedOp; + use crate::{Quantity, apply_operations}; + + let (mut kernel, people, _) = clockwork_world(20); + let grain = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "Grain 1") + .expect("declared") + .0; + let revision = kernel.state.revision + 1; + let state = &mut kernel.state; + state.begin(); + crate::set_held(state, people[0], grain, 5); + let transfer = ResolvedOp::Transfer { from: people[0], to: people[1], resource: grain, qty: Quantity(5) }; + apply_operations(state, std::slice::from_ref(&transfer), &[], revision) + .expect("moving the pre-written five on conserves it"); + state.rollback(); +} + +/// Patches whose later operations read what earlier ones wrote, judged by the +/// resolver and committed: each is a legal sequence and must be accepted, or, +/// where the sequence changes nothing, refused cleanly by the resolver with the +/// commit never reached. +mod within_one_patch { + use super::{clockwork_envelope, clockwork_world}; + use crate::patch::{ + AuthorityGrantRef, AuthorityTargetRef, Declaration, DraftHandle, Mismatch, + PressureMagnitude, PressureSourceRef, SubjectDeclaration, + }; + use crate::tests::{LEVY_KIND, authority_kind}; + use crate::{ + AuthenticatedCaller, CommandBody, ComponentOp, KernelError, Ref, SubjectKind, SubjectId, + WorldKernel, WorldPatch, + }; + use std::collections::BTreeSet; + + fn submit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<(), KernelError> { + let envelope = clockwork_envelope(kernel, CommandBody::AdmitPatch { patch }); + kernel.submit(envelope, &AuthenticatedCaller::verified_play()).map(|_| ()) + } + + fn ops(operations: Vec) -> WorldPatch { + WorldPatch { declarations: vec![], operations, evidence: vec![] } + } + + fn levy_over(holder: SubjectId, over: SubjectId) -> ComponentOp { + ComponentOp::GrantAuthority { + holder: Ref::Existing(holder), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::Subject(Ref::Existing(over)), + }, + } + } + + /// Two jurisdictions of one kind over different subjects are disjoint, so + /// one holder may hold both. + #[test] + fn one_holder_may_hold_one_kind_over_two_subjects() { + let (mut kernel, p, _) = clockwork_world(30); + submit(&mut kernel, ops(vec![levy_over(p[0], p[5]), levy_over(p[0], p[6])])) + .expect("levy over two different subjects does not overlap"); + } + + fn source(subject: SubjectId) -> PressureSourceRef { + PressureSourceRef::Subject(Ref::Existing(subject)) + } + + /// A pressure advanced by one operation is there for the next to resolve, + /// and one reduced to nothing is gone for the next to advance afresh. + #[test] + fn a_pressure_advanced_in_a_patch_is_read_by_the_next_operation() { + let (mut kernel, p, _) = clockwork_world(30); + submit(&mut kernel, ops(vec![ + ComponentOp::AdvancePressure { source: source(p[0]), target: Ref::Existing(p[12]), by: PressureMagnitude(2) }, + ComponentOp::ResolvePressure { source: source(p[0]), target: Ref::Existing(p[12]) }, + ])) + .expect("advance then resolve the same slot"); + + submit(&mut kernel, ops(vec![ + ComponentOp::AdvancePressure { source: source(p[0]), target: Ref::Existing(p[13]), by: PressureMagnitude(2) }, + ComponentOp::ReducePressure { source: source(p[0]), target: Ref::Existing(p[13]), by: PressureMagnitude(2) }, + ComponentOp::AdvancePressure { source: source(p[0]), target: Ref::Existing(p[13]), by: PressureMagnitude(1) }, + ])) + .expect("advance, reduce to nothing, advance again"); + } + + fn declared(name: &str, affordance: crate::AffordanceId) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(name), + label: name.into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([Ref::Existing(affordance)]), + position: None, + import_key: None, + }) + } + + /// A subject declared with an affordance already has it: granting it is no + /// change, and the resolver says so itself, rather than admitting what the + /// commit then refuses. Revoking it first makes the grant a change. + #[test] + fn a_declared_affordance_is_known_to_the_operations_that_follow() { + let (mut kernel, _, speak) = clockwork_world(30); + let draft = |name: &str| Ref::Draft(DraftHandle::new(name)); + + let refused = submit(&mut kernel, WorldPatch { + declarations: vec![declared("scribe", speak)], + operations: vec![ComponentOp::GrantAffordance { subject: draft("scribe"), affordance: Ref::Existing(speak) }], + evidence: vec![], + }) + .unwrap_err(); + assert!( + matches!(&refused, KernelError::PatchRejected(m) + if m == &[Mismatch::NoOperationEffect { operation: 0 }]), + "{refused:?}" + ); + + submit(&mut kernel, WorldPatch { + declarations: vec![declared("scribe2", speak)], + operations: vec![ + ComponentOp::RevokeAffordance { subject: draft("scribe2"), affordance: Ref::Existing(speak) }, + ComponentOp::GrantAffordance { subject: draft("scribe2"), affordance: Ref::Existing(speak) }, + ], + evidence: vec![], + }) + .expect("revoke then grant is a change"); + } +} + +/// Seeded random patch sequences through the real kernel. The resolver judges +/// each patch against its overlay, `apply_operations` re-derives conservation +/// and disjointness from the transaction log, and the full-scan references +/// judge the committed world: the three must agree after every step. +/// +/// Per step, in a world of grain holders, institutions with a warden office, +/// pressures and a speak affordance: +/// - the outcome is an accepted commit or a `PatchRejected` mismatch set, never +/// a kernel `Invariant` error (the resolver admitted what apply refuses); +/// - a refused patch changes no document, and the same patch refused again +/// gives the same mismatches; +/// - after an accepted one every index equals its scan, no subject holds two +/// overlapping jurisdictions of one kind, and the grain total is unchanged +/// (the generator transfers and never mints). +#[test] +fn random_patch_sequences_agree_with_the_scan_references() { + use crate::patch::{ + AuthorityGrantRef, AuthorityTargetRef, PressureMagnitude, PressureSourceRef, Quantity, + }; + use crate::tests::{LEVY_KIND, WARDEN_OFFICE, authority_kind, office}; + use crate::{EntityKind, SubjectKind}; + + struct Rng(u64); + impl Rng { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % n as u64) as usize + } + } + + let (mut accepted, mut refused, mut multi) = (0usize, 0usize, 0usize); + for seed in 1..=10u64 { + let (mut kernel, people, speak) = clockwork_world(30); + let labelled = |kernel: &WorldKernel, kind: EntityKind| -> Vec { + let mut found: Vec<_> = kernel + .state + .entities + .iter() + .filter(|(_, record)| record.kind == kind) + .map(|(id, record)| (record.label.clone(), *id)) + .collect(); + found.sort(); + found.into_iter().map(|(_, id)| id).collect() + }; + let places = labelled(&kernel, EntityKind::Place); + let grains = labelled(&kernel, EntityKind::Resource); + let institutions: Vec<_> = (0..places.len()) + .map(|place| subject_by_label(&kernel.state, &format!("Institution {place}"))) + .collect(); + let grain_total = |kernel: &WorldKernel| -> u128 { + grains.iter().map(|grain| crate::resource_total_by_scan(&kernel.state, *grain)).sum() + }; + let total = grain_total(&kernel); + let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + + for step in 0..30 { + // A small pool of subjects, so patches collide often. + let person = |rng: &mut Rng| Ref::Existing(people[rng.below(6)]); + let levy_target = |rng: &mut Rng| { + if rng.below(2) == 0 { + AuthorityTargetRef::Subject(Ref::Existing(people[rng.below(6)])) + } else { + AuthorityTargetRef::PlaceSubtree(Ref::Existing(places[rng.below(3)])) + } + }; + let mut declarations = Vec::new(); + let mut operations = Vec::new(); + for index in 0..1 + rng.below(4) { + let op = match rng.below(14) { + 0..=2 => { + let holder = if rng.below(4) == 0 { + Ref::Existing(institutions[rng.below(3)]) + } else { + person(&mut rng) + }; + ComponentOp::GrantAuthority { + holder, + grant: AuthorityGrantRef { kind: authority_kind(LEVY_KIND), over: levy_target(&mut rng) }, + } + } + 3 => ComponentOp::RevokeAuthority { + holder: person(&mut rng), + grant: AuthorityGrantRef { kind: authority_kind(LEVY_KIND), over: levy_target(&mut rng) }, + }, + 4 => ComponentOp::InstallIncumbent { + institution: Ref::Existing(institutions[rng.below(3)]), + office: office(WARDEN_OFFICE), + incumbent: person(&mut rng), + }, + 5 => ComponentOp::VacateOffice { + institution: Ref::Existing(institutions[rng.below(3)]), + office: office(WARDEN_OFFICE), + }, + 6 => ComponentOp::AdvancePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + by: PressureMagnitude(1 + rng.below(3) as u32), + }, + 7 => ComponentOp::ReducePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + by: PressureMagnitude(1 + rng.below(3) as u32), + }, + 8 => ComponentOp::ResolvePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + }, + 9 => ComponentOp::GrantAffordance { subject: person(&mut rng), affordance: Ref::Existing(speak) }, + 10 => ComponentOp::RevokeAffordance { subject: person(&mut rng), affordance: Ref::Existing(speak) }, + 11 => ComponentOp::Transfer { + from: person(&mut rng), + to: person(&mut rng), + resource: Ref::Existing(grains[rng.below(3)]), + qty: Quantity(1), + }, + 12 => { + let name = format!("s{step}-{index}"); + declarations.push(Declaration::Subject(crate::patch::SubjectDeclaration { + handle: DraftHandle::new(&name), + label: format!("Drafted {seed}-{name}"), + kind: SubjectKind::Person, + affordances: std::collections::BTreeSet::from([Ref::Existing(speak)]), + position: None, + import_key: None, + })); + ComponentOp::GrantAffordance { + subject: Ref::Draft(DraftHandle::new(&name)), + affordance: Ref::Existing(speak), + } + } + _ if rng.below(8) == 0 => ComponentOp::Retire { subject: person(&mut rng) }, + _ => ComponentOp::ResolvePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + }, + }; + operations.push(op); + } + let patch = WorldPatch { declarations, operations, evidence: vec![] }; + let documents = kernel.state.documents().unwrap(); + let again = clockwork_envelope(&kernel, CommandBody::AdmitPatch { patch: patch.clone() }); + let outcome = kernel.submit( + clockwork_envelope(&kernel, CommandBody::AdmitPatch { patch }), + &AuthenticatedCaller::verified_play(), + ); + match outcome { + Ok(_) => { + accepted += 1; + assert_eq!(reference_scan_disagreement(&kernel.state), None, "seed {seed} step {step}"); + assert_indexes_derived(&kernel.state, &format!("seed {seed} step {step}")); + for subject in kernel.state.subjects.keys() { + assert!( + !crate::holder_overlaps(&kernel.state, *subject), + "seed {seed} step {step}: {subject:?} holds overlapping jurisdictions" + ); + } + assert_eq!(grain_total(&kernel), total, "seed {seed} step {step}: custody"); + } + Err(KernelError::PatchRejected(mismatches)) => { + refused += 1; + multi += usize::from(mismatches.len() > 1); + assert_eq!(kernel.state.documents().unwrap(), documents, "seed {seed} step {step}: a refusal wrote"); + // The same patch against the same world: the same refusal. + let repeat = kernel.submit(again, &AuthenticatedCaller::verified_play()); + assert!( + matches!(&repeat, Err(KernelError::PatchRejected(m)) if *m == mismatches), + "seed {seed} step {step}: {repeat:?}" + ); + } + Err(other) => panic!("seed {seed} step {step}: resolver and apply disagree: {other:?}"), + } + } + } + // The generator must reach both sides, or the loop proves nothing. + assert!(accepted >= 40 && refused >= 40 && multi >= 1, "{accepted} accepted, {refused} refused, {multi} multi"); +} diff --git a/native/aetherlight/src/grammar.rs b/native/aetherlight/src/grammar.rs new file mode 100644 index 000000000..a11cd691a --- /dev/null +++ b/native/aetherlight/src/grammar.rs @@ -0,0 +1,209 @@ +//! The action grammar a world is bound to at creation. +//! +//! A grammar is the closed set of affordance kinds a world may declare, each +//! with its role signature and the one render path its acts take. The grammar's +//! home is the Aetheria repo; the kernel holds only this binding: the verbs it +//! enforces, and a content digest that names exactly which grammar that was. +//! The digest is derived here and nowhere else, so a binding cannot claim a +//! digest its verbs do not have. + +use crate::SubjectKind; +use crate::patch::{AffordanceKindName, EntityKind, RefKind, Role, RoleSpec, kernel_speak_entry}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; + +/// How an act of one verb reaches the player: filmed in the engine as a ship +/// action, or shown as Aetheria's portrait-and-choices conversation. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum RenderPath { + ShipAction, + Conversation, +} + +/// What a grammar role may be bound to, in the grammar's own vocabulary. Each +/// lowers to exactly one kernel `RefKind`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum GrammarReferentKind { + Person, + Faction, + Population, + Place, + Cargo, +} + +impl GrammarReferentKind { + fn ref_kind(self) -> RefKind { + match self { + Self::Person => RefKind::Subject(Some(SubjectKind::Person)), + Self::Faction => RefKind::Subject(Some(SubjectKind::Institution)), + Self::Population => RefKind::Subject(Some(SubjectKind::Population)), + Self::Place => RefKind::Entity(EntityKind::Place), + Self::Cargo => RefKind::Entity(EntityKind::Resource), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +pub struct GrammarRole { + pub role: String, + pub referent: GrammarReferentKind, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +pub struct GrammarVerb { + pub render_path: RenderPath, + /// In signature order: the order is part of the verb. + pub roles: Vec, +} + +impl GrammarVerb { + /// Whether a declared role list is this verb's signature: same names, same + /// referent kinds, same order. + pub(crate) fn admits_roles(&self, roles: &[RoleSpec]) -> bool { + self.role_specs() == roles + } + + /// This verb's signature as the kernel declares it: the one lowering of a + /// grammar role, so declaring a verb and admitting a declaration cannot + /// disagree. + pub(crate) fn role_specs(&self) -> Vec { + self.roles + .iter() + .map(|role| RoleSpec { + role: Role(role.role.clone()), + kind: role.referent.ref_kind(), + }) + .collect() + } +} + +/// Why a bound grammar refuses an affordance entry. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GrammarRefusal { + KindNotInGrammar, + RolesDisagree, + SpeakNotConversation, +} + +#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)] +pub enum GrammarError { + #[error("grammar schema id is empty")] + EmptySchemaId, + #[error("grammar declares one verb kind twice")] + DuplicateVerb, + #[error("grammar digest does not match its verbs")] + DigestMismatch, +} + +/// Which grammar a world is bound to: its schema id, revision and content +/// digest. What a consumer reads; the verb table stays in the binding. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GrammarIdentity { + pub schema_id: String, + pub revision: u32, + pub digest: String, +} + +/// The grammar a world was created under. Immutable: the only constructor +/// derives the digest, and deserialisation re-derives it and refuses a mismatch. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(try_from = "RawBinding")] +pub struct GrammarBinding { + schema_id: String, + revision: u32, + digest: String, + verbs: BTreeMap, +} + +#[derive(Deserialize)] +struct RawBinding { + schema_id: String, + revision: u32, + digest: String, + verbs: BTreeMap, +} + +impl TryFrom for GrammarBinding { + type Error = GrammarError; + + fn try_from(raw: RawBinding) -> Result { + let bound = Self::new(raw.schema_id, raw.revision, raw.verbs)?; + if bound.digest != raw.digest { + return Err(GrammarError::DigestMismatch); + } + Ok(bound) + } +} + +impl GrammarBinding { + /// The one constructor. Verbs arrive in any order and are keyed by kind; + /// the digest is the sha256 of the canonical encoding of the kind-sorted + /// verbs, so the same verbs bind to the same digest however they were listed. + pub fn new( + schema_id: impl Into, + revision: u32, + verbs: impl IntoIterator, + ) -> Result { + let schema_id = schema_id.into(); + if schema_id.is_empty() { + return Err(GrammarError::EmptySchemaId); + } + let mut table = BTreeMap::new(); + for (kind, verb) in verbs { + if table.insert(kind, verb).is_some() { + return Err(GrammarError::DuplicateVerb); + } + } + let encoded = rmp_serde::to_vec_named(&table).expect("a verb table encodes"); + let digest = format!("sha256:{:x}", Sha256::digest(encoded)); + Ok(Self { + schema_id, + revision, + digest, + verbs: table, + }) + } + + pub fn identity(&self) -> GrammarIdentity { + GrammarIdentity { + schema_id: self.schema_id.clone(), + revision: self.revision, + digest: self.digest.clone(), + } + } + + /// Every verb, in kind order. + pub(crate) fn verbs(&self) -> impl Iterator { + self.verbs.iter().map(|(kind, verb)| (kind.as_str(), verb)) + } + + pub(crate) fn verb(&self, kind: &str) -> Option<&GrammarVerb> { + self.verbs.get(kind) + } + + /// The one grammar check. The resolver turns a refusal into a mismatch and + /// `admit_resolved`, the only writer of the affordance catalog, into an + /// invariant error, so no path adds an entry without passing it. + pub(crate) fn refusal( + &self, + kind: &AffordanceKindName, + roles: &[RoleSpec], + ) -> Option { + let Some(verb) = self.verb(&kind.0) else { + return Some(GrammarRefusal::KindNotInGrammar); + }; + if !verb.admits_roles(roles) { + return Some(GrammarRefusal::RolesDisagree); + } + if *kind == kernel_speak_entry().kind && verb.render_path != RenderPath::Conversation { + return Some(GrammarRefusal::SpeakNotConversation); + } + None + } +} + +#[cfg(test)] +mod tests; diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs new file mode 100644 index 000000000..817668d73 --- /dev/null +++ b/native/aetherlight/src/grammar/tests.rs @@ -0,0 +1,659 @@ +use super::*; +use crate::patch::{ + AffordanceDeclaration, AffordanceKindName, AudienceSpec, Declaration, DraftHandle, EntityKind, + Mismatch, OutcomeBand, Precondition, Role, RoleSpec, +}; +use crate::tests::{auth_principal, command, creation, owner}; +use crate::{ + CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, CommitReceipt, + WorldKernel, WorldPatch, +}; + +fn verb(path: RenderPath, roles: &[(&str, GrammarReferentKind)]) -> GrammarVerb { + GrammarVerb { + render_path: path, + roles: roles + .iter() + .map(|(role, referent)| GrammarRole { + role: (*role).into(), + referent: *referent, + }) + .collect(), + } +} + +/// What the fixture world's genesis needs: the kernel speak entry and the +/// fixture's own `convene`. Anything else a test wants is added to it. +fn grammar_with(extra: &[(&str, GrammarVerb)]) -> GrammarBinding { + let mut verbs = vec![ + ("speak".to_owned(), verb(RenderPath::Conversation, &[])), + ("convene".to_owned(), verb(RenderPath::Conversation, &[])), + ]; + verbs.extend( + extra + .iter() + .map(|(kind, v)| ((*kind).to_owned(), v.clone())), + ); + GrammarBinding::new("aetheria.grammar", 3, verbs).unwrap() +} + +fn bound(grammar: Option, title: &str) -> CreateWorld { + let mut world = creation(title); + world.grammar = grammar; + world +} + +fn declare(handle: &str, kind: &str, roles: &[(&str, RefKind)]) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles: roles + .iter() + .map(|(role, kind)| RoleSpec { + role: Role((*role).into()), + kind: *kind, + }) + .collect(), + // Speech with one audience is the smallest entry the resolver does + // not refuse as inert; the grammar check does not read it. + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }) +} + +fn patch_of(declarations: Vec) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } +} + +fn rejected(result: Result) -> Vec { + match result { + Err(KernelError::PatchRejected(set)) => set, + Err(other) => panic!("expected a patch refusal, got {other:?}"), + Ok(_) => panic!("expected a patch refusal, the command was admitted"), + } +} + +fn create(world: CreateWorld) -> Result { + WorldKernel::create(world, &auth_principal(owner())).map(|(kernel, _)| kernel) +} + +fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + CallerId::Play, + CommandBody::AdmitPatch { + patch, + }, + ), + &crate::AuthenticatedCaller::verified_play(), + ) +} + +fn person() -> RefKind { + RefKind::Subject(Some(SubjectKind::Person)) +} + +fn place() -> RefKind { + RefKind::Entity(EntityKind::Place) +} + +fn not_in_grammar(handle: &str) -> Vec { + vec![Mismatch::AffordanceKindNotInGrammar { + handle: DraftHandle::new(handle), + }] +} + +fn disagrees(handle: &str) -> Vec { + vec![Mismatch::AffordanceRolesDisagreeWithGrammar { + handle: DraftHandle::new(handle), + }] +} + +#[test] +fn grammar_world_refuses_an_affordance_kind_outside_the_grammar() { + // Genesis: a declared kind the binding lacks is refused. + let mut world = bound(Some(grammar_with(&[])), "Outside"); + world.patch.declarations.push(declare("wave", "wave", &[])); + assert_eq!(rejected(create(world)), not_in_grammar("wave")); + + // A later AdmitPatch: the same kind is refused, and a verb the grammar + // does carry is admitted by the same path. + let extra = [("hail", verb(RenderPath::Conversation, &[]))]; + let kernel = create(bound(Some(grammar_with(&extra)), "Outside")); + let mut kernel = kernel.unwrap(); + assert_eq!( + rejected(admit( + &mut kernel, + patch_of(vec![declare("wave", "wave", &[])]) + )), + not_in_grammar("wave") + ); + let receipt = admit(&mut kernel, patch_of(vec![declare("hail", "hail", &[])])).unwrap(); + assert!(receipt.resulting_revision > 0); +} + +#[test] +fn grammar_world_refuses_a_role_signature_the_grammar_does_not_carry() { + let extra = [ + ( + "meet", + verb( + RenderPath::ShipAction, + &[ + ("who", GrammarReferentKind::Person), + ("where_", GrammarReferentKind::Place), + ], + ), + ), + ("hail", verb(RenderPath::Conversation, &[])), + ]; + let kernel = create(bound(Some(grammar_with(&extra)), "Signatures")); + let mut kernel = kernel.unwrap(); + for (label, roles) in [ + ("renamed", vec![("whom", person()), ("where_", place())]), + ("rekinded", vec![("who", person()), ("where_", person())]), + ("swapped", vec![("where_", place()), ("who", person())]), + ("short", vec![("who", person())]), + ( + "long", + vec![("who", person()), ("where_", place()), ("why", person())], + ), + ] { + let set = rejected(admit( + &mut kernel, + patch_of(vec![declare(label, "meet", &roles)]), + )); + assert_eq!(set, disagrees(label), "{label}"); + } + // A role on a verb the grammar declares with none. + let set = rejected(admit( + &mut kernel, + patch_of(vec![declare("hail", "hail", &[("who", person())])]), + )); + assert_eq!(set, disagrees("hail")); + // The exact signature is admitted. + let receipt = admit( + &mut kernel, + patch_of(vec![declare( + "meet", + "meet", + &[("who", person()), ("where_", place())], + )]), + ) + .unwrap(); + assert!(receipt.resulting_revision > 0); +} + +#[test] +fn each_grammar_referent_kind_admits_exactly_its_own_kernel_kind() { + let kinds = [ + (GrammarReferentKind::Person, person()), + ( + GrammarReferentKind::Faction, + RefKind::Subject(Some(SubjectKind::Institution)), + ), + ( + GrammarReferentKind::Population, + RefKind::Subject(Some(SubjectKind::Population)), + ), + (GrammarReferentKind::Place, place()), + ( + GrammarReferentKind::Cargo, + RefKind::Entity(EntityKind::Resource), + ), + ]; + for (referent, own) in &kinds { + let extra = [("act", verb(RenderPath::ShipAction, &[("with", *referent)]))]; + for (_, offered) in &kinds { + let kernel = create(bound(Some(grammar_with(&extra)), "Referents")); + let mut kernel = kernel.unwrap(); + let result = admit( + &mut kernel, + patch_of(vec![declare("act", "act", &[("with", *offered)])]), + ); + if offered == own { + assert!( + matches!(result, Ok(_)), + "{referent:?} refused its own kind" + ); + } else { + assert_eq!( + rejected(result), + disagrees("act"), + "{referent:?} admitted {offered:?}" + ); + } + } + } +} + +#[test] +fn grammar_world_without_speak_refuses_the_kernel_speak_grant() { + let no_speak = GrammarBinding::new( + "aetheria.grammar", + 1, + [("convene".to_owned(), verb(RenderPath::Conversation, &[]))], + ) + .unwrap(); + assert_eq!( + rejected(create(bound(Some(no_speak), "Mute"))), + not_in_grammar(crate::patch::KERNEL_SPEAK_HANDLE) + ); + + // The kernel entry is held to the signature as well as the kind. + let loud = GrammarBinding::new( + "aetheria.grammar", + 1, + [ + ( + "speak".to_owned(), + verb( + RenderPath::Conversation, + &[("to", GrammarReferentKind::Person)], + ), + ), + ("convene".to_owned(), verb(RenderPath::Conversation, &[])), + ], + ) + .unwrap(); + assert_eq!( + rejected(create(bound(Some(loud), "Loud"))), + disagrees(crate::patch::KERNEL_SPEAK_HANDLE) + ); +} + +#[test] +fn unbound_world_keeps_the_open_catalog() { + let mut world = bound(None, "Open"); + world + .patch + .declarations + .push(declare("wave", "wave", &[("at", person())])); + let kernel = create(world); + let mut kernel = kernel.unwrap(); + let receipt = admit( + &mut kernel, + patch_of(vec![declare("beacon", "beacon", &[])]), + ) + .unwrap(); + assert!(receipt.resulting_revision > 0); + let snapshot = kernel.snapshot().unwrap(); + assert!(snapshot.grammar.is_none()); + assert!(snapshot.affordances.len() >= 4); + assert!(snapshot.affordances.iter().all(|a| a.render_path.is_none())); + + // The state row of a world with no grammar carries no grammar key, so its + // bytes and digests are those of a world written before grammars existed. + let encoded = rmp_serde::to_vec_named(&*kernel.state.header).unwrap(); + let keys: std::collections::BTreeMap = + rmp_serde::from_slice(&encoded).unwrap(); + assert!(!keys.contains_key("grammar")); + assert!(keys.contains_key("title")); +} + +#[test] +fn a_bound_world_reports_its_grammar_and_derives_render_paths_from_it() { + let extra = [("dock", verb(RenderPath::ShipAction, &[]))]; + let grammar = grammar_with(&extra); + let identity = grammar.identity(); + let kernel = create(bound(Some(grammar), "Reports")); + let mut kernel = kernel.unwrap(); + admit(&mut kernel, patch_of(vec![declare("dock", "dock", &[])])).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!(snapshot.grammar, Some(identity)); + let path_of = |kind: &str| { + snapshot + .affordances + .iter() + .find(|a| a.entry.kind.0 == kind) + .unwrap_or_else(|| panic!("{kind} is in the catalog")) + .render_path + }; + assert_eq!(path_of("dock"), Some(RenderPath::ShipAction)); + assert_eq!(path_of("convene"), Some(RenderPath::Conversation)); + assert_eq!(path_of("speak"), Some(RenderPath::Conversation)); +} + +#[test] +fn a_reopened_grammar_world_still_holds_its_grammar() { + let grammar = grammar_with(&[]); + let identity = grammar.identity(); + let kernel = create(bound(Some(grammar), "Reopened")); + let kernel = kernel.unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap().grammar, Some(identity)); + assert_eq!( + rejected(admit( + &mut reopened, + patch_of(vec![declare("wave", "wave", &[])]) + )), + not_in_grammar("wave") + ); +} + +#[test] +fn the_bound_grammar_is_part_of_the_world_state_digest() { + let kernel = create(bound(Some(grammar_with(&[])), "Digested")); + let kernel = kernel.unwrap(); + let bound_digest = kernel.state.full_state_digest().unwrap(); + let mut state = kernel.state.clone(); + state.header.get_mut().grammar = None; + let open_digest = state.full_state_digest().unwrap(); + state.header.get_mut().grammar = Some(grammar_with(&[("dock", verb(RenderPath::ShipAction, &[]))])); + let other_digest = state.full_state_digest().unwrap(); + assert_ne!(bound_digest, open_digest); + assert_ne!(bound_digest, other_digest); +} + +#[test] +fn grammar_digest_is_derived_and_order_free() { + let forward = [ + ("alpha".to_owned(), verb(RenderPath::ShipAction, &[])), + ( + "beta".to_owned(), + verb( + RenderPath::Conversation, + &[("to", GrammarReferentKind::Person)], + ), + ), + ("gamma".to_owned(), verb(RenderPath::Conversation, &[])), + ]; + let mut reversed = forward.clone(); + reversed.reverse(); + let a = GrammarBinding::new("aetheria.grammar", 1, forward.clone()).unwrap(); + let b = GrammarBinding::new("aetheria.grammar", 1, reversed).unwrap(); + assert_eq!(a.digest, b.digest); + assert_eq!(a, b); + + // Content-derived: each part of a verb moves the digest. + let changed = |edit: &dyn Fn(&mut Vec<(String, GrammarVerb)>)| { + let mut verbs = forward.to_vec(); + edit(&mut verbs); + GrammarBinding::new("aetheria.grammar", 1, verbs) + .unwrap() + .digest + }; + assert_ne!( + a.digest, + changed(&|v| v[0].1.render_path = RenderPath::Conversation) + ); + assert_ne!(a.digest, changed(&|v| v[1].1.roles[0].role = "from".into())); + assert_ne!( + a.digest, + changed(&|v| v[1].1.roles[0].referent = GrammarReferentKind::Faction) + ); + assert_ne!(a.digest, changed(&|v| v[2].0 = "delta".into())); + assert_ne!( + a.digest, + changed(&|v| { + v.pop(); + }) + ); + // Role order is part of a verb. + let ordered = |roles: &[(&str, GrammarReferentKind)]| { + GrammarBinding::new( + "g", + 1, + [("meet".to_owned(), verb(RenderPath::ShipAction, roles))], + ) + .unwrap() + .digest + }; + assert_ne!( + ordered(&[ + ("a", GrammarReferentKind::Person), + ("b", GrammarReferentKind::Place) + ]), + ordered(&[ + ("b", GrammarReferentKind::Place), + ("a", GrammarReferentKind::Person) + ]) + ); + // The identity reads the same fields back. + let identity = a.identity(); + assert_eq!(identity.schema_id, "aetheria.grammar"); + assert_eq!(identity.revision, 1); + assert_eq!(identity.digest, a.digest); +} + +#[test] +fn a_tampered_grammar_digest_fails_to_deserialise() { + let binding = grammar_with(&[]); + let value = serde_json::to_value(&binding).unwrap(); + // Untouched: the round trip holds. + let back: GrammarBinding = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(back, binding); + + // A digest the verbs do not have. + let mut forged = value.clone(); + forged["digest"] = "sha256:00".into(); + assert!(serde_json::from_value::(forged.clone()).is_err()); + + // A verb edited under the digest it already had. + let mut edited = value; + edited["verbs"]["convene"]["render_path"] = "ship_action".into(); + assert!(serde_json::from_value::(edited).is_err()); + + // The named encoding a state row uses refuses it the same way. + let bytes = rmp_serde::to_vec_named(&forged).unwrap(); + assert!(rmp_serde::from_slice::(&bytes).is_err()); +} + +#[test] +fn a_grammar_names_each_verb_once_and_has_a_schema() { + assert_eq!( + GrammarBinding::new("", 1, Vec::new()).unwrap_err(), + GrammarError::EmptySchemaId + ); + assert_eq!( + GrammarBinding::new( + "g", + 1, + [ + ("hail".to_owned(), verb(RenderPath::Conversation, &[])), + ("hail".to_owned(), verb(RenderPath::ShipAction, &[])), + ] + ) + .unwrap_err(), + GrammarError::DuplicateVerb + ); +} + +fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + patch: WorldPatch, +) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + caller.clone(), + CommandBody::AdmitPatch { patch }, + ), + &crate::AuthenticatedCaller::fixture(caller), + ) +} + +/// A bound world whose revision has moved past genesis: one Play patch +/// that adds a dead-end place. +fn advanced_grammar_world() -> (WorldKernel, crate::EntityId) { + let extra = [("hail", verb(RenderPath::Conversation, &[]))]; + let kernel = create(bound(Some(grammar_with(&extra)), "Advanced")); + let mut kernel = kernel.unwrap(); + let commons = *kernel.state.entities.keys().next().unwrap(); + admit( + &mut kernel, + patch_of(vec![ + Declaration::Entity(crate::patch::EntityDeclaration { + handle: DraftHandle::new("dead-end"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(crate::patch::RouteDeclaration { + handle: DraftHandle::new("gate"), + label: "The Field Gate".into(), + from: crate::patch::Ref::Existing(commons), + to: crate::patch::Ref::Draft(DraftHandle::new("dead-end")), + access: crate::patch::AccessKind::Public, + cost: crate::patch::Cost(1), + }), + ]), + ) + .unwrap(); + let dead_end = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Unwalked Road") + .map(|(id, _)| id) + .unwrap(); + (kernel, dead_end) +} + +type Door = (&'static str, CallerId); + +/// Each door refuses an outside kind and a wrong role signature, typed, and the +/// refusal leaves the revision where it was. +fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec) { + for (door, caller) in doors { + let revision = kernel.state.revision; + let kind = submit_as( + kernel, + caller.clone(), + patch_of(vec![declare("wave", "wave", &[])]), + ); + assert_eq!(rejected(kind), not_in_grammar("wave"), "{door}"); + let roles = submit_as( + kernel, + caller, + patch_of(vec![declare("hail", "hail", &[("who", person())])]), + ); + assert_eq!(rejected(roles), disagrees("hail"), "{door}"); + assert_eq!( + kernel.state.revision, revision, + "{door} refusal moved the world" + ); + } +} + +#[test] +fn play_refuses_outside_the_grammar_after_the_revision_has_moved() { + let (mut kernel, _) = advanced_grammar_world(); + assert_eq!(kernel.state.revision, 1); + refuse_at_each_door(&mut kernel, vec![("play", CallerId::Play)]); + // The same path admits what the grammar carries, so the refusals above are + // the grammar's and not a closed door. + let receipt = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![declare("hail", "hail", &[])]), + ) + .unwrap(); + assert!(receipt.resulting_revision > 0); +} + +#[test] +fn a_grammar_that_binds_speak_as_anything_but_conversation_is_refused_at_bind() { + let ship = |roles: &[(&str, GrammarReferentKind)]| { + GrammarBinding::new( + "aetheria.grammar", + 1, + [ + ("speak".to_owned(), verb(RenderPath::ShipAction, roles)), + ("convene".to_owned(), verb(RenderPath::Conversation, &[])), + ], + ) + .unwrap() + }; + assert_eq!( + rejected(create(bound(Some(ship(&[])), "Filmed speech"))), + vec![Mismatch::SpeakRenderPathDisagreesWithGrammar { + handle: DraftHandle::new(crate::patch::KERNEL_SPEAK_HANDLE), + }] + ); + // A ShipAction speak with a role fails on the signature first and is still + // refused: no variant of speak but zero roles, Conversation, is admitted. + assert_eq!( + rejected( + create(bound( + Some(ship(&[("to", GrammarReferentKind::Person)])), + "Loud" + )) + ), + disagrees(crate::patch::KERNEL_SPEAK_HANDLE) + ); + // The control: Conversation speak binds. + assert!(create(bound(Some(grammar_with(&[])), "Spoken")).is_ok()); +} + +/// `apply_effect` re-decides an effect it is handed. An effect resolved against +/// a world with no grammar must not install an entry the bound grammar lacks: +/// the catalog's only writer holds the grammar check itself. +#[test] +fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { + let extra = [ + ( + "meet", + verb( + RenderPath::ShipAction, + &[("who", GrammarReferentKind::Person)], + ), + ), + ("hail", verb(RenderPath::Conversation, &[])), + ]; + let kernel = create(bound(Some(grammar_with(&extra)), "Forged")); + let kernel = kernel.unwrap(); + let mut twin = kernel.state.clone(); + twin.header.get_mut().grammar = None; + let resolve = |kind: &str, roles: &[(&str, RefKind)]| { + crate::patch::resolve_patch( + &twin, + CommandId::issue(), + &patch_of(vec![declare("probe", kind, roles)]), + ) + .expect("the unbound twin admits any canonical kind") + }; + for (label, resolved, admitted) in [ + ("outside kind", resolve("wave", &[]), false), + ("wrong roles", resolve("meet", &[("whom", person())]), false), + ("carried verb", resolve("hail", &[]), true), + ] { + let mut state = kernel.state.clone(); + let catalog = state.affordance_catalog.len(); + let result = crate::apply_effect( + &mut state, + CommandId::issue(), + &CallerId::Play, + &crate::WorldEffect::PatchAdmitted { + resolved, + }, + ); + if admitted { + result.unwrap_or_else(|error| panic!("{label}: {error:?}")); + assert_eq!(state.affordance_catalog.len(), catalog + 1, "{label}"); + } else { + assert!( + matches!(result, Err(KernelError::Invariant(_))), + "{label}: {result:?}" + ); + assert_eq!(state.affordance_catalog.len(), catalog, "{label}"); + } + } +} diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs new file mode 100644 index 000000000..150da6960 --- /dev/null +++ b/native/aetherlight/src/import_key_tests.rs @@ -0,0 +1,692 @@ +//! One record, one subject: admission keeps the import-key mapping injective at +//! every door and at every revision, and a world nobody imported into is +//! byte-for-byte what it was before keys existed. + +use crate::patch::{ + AccessKind, ComponentOp, Cost, Declaration, DraftHandle, EntityDeclaration, EntityKind, + ImportKey, Mismatch, Ref, RouteDeclaration, +}; +use crate::tests::{auth_principal, command, creation, owner}; +use crate::{ + CallerId, CommandBody, CommandId, CreateWorld, EntityId, KernelError, + SubjectDeclaration, SubjectKind, CommitReceipt, + WorldKernel, WorldPatch, +}; +use std::collections::BTreeSet; + +fn key(schema: &str, record: &str) -> ImportKey { + ImportKey::new(schema, record) +} + +fn alpha() -> ImportKey { + key("aetheria.ship", "Alpha") +} + +/// The fixture genesis with its witness imported from `alpha()`. +fn keyed_creation(title: &str) -> CreateWorld { + let mut world = creation(title); + for declaration in &mut world.patch.declarations { + if let Declaration::Subject(subject) = declaration + && subject.handle == DraftHandle::new("persona") + { + subject.import_key = Some(alpha()); + } + } + world +} + +fn create(world: CreateWorld) -> Result { + WorldKernel::create(world, &auth_principal(owner())).map(|(kernel, _)| kernel) +} + +fn keyed_world() -> WorldKernel { + create(keyed_creation("Keyed")).unwrap() +} + +fn rejected(result: Result) -> Vec { + match result { + Err(KernelError::PatchRejected(set)) => set, + Err(other) => panic!("expected a patch refusal, got {other:?}"), + Ok(_) => panic!("expected a patch refusal, the command was admitted"), + } +} + +fn patch_of(declarations: Vec) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } +} + +fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + patch: WorldPatch, +) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + caller.clone(), + CommandBody::AdmitPatch { patch }, + ), + &crate::AuthenticatedCaller::fixture(caller), + ) +} + +fn commons(kernel: &WorldKernel) -> EntityId { + *kernel.state.entities.keys().next().unwrap() +} + +/// A keyed subject that holds no verbs: legal, since a subject may be declared +/// with none, and the lightest declaration an import can make. +fn keyed(handle: &str, import_key: Option, place: EntityId) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: SubjectKind::Person, + affordances: BTreeSet::new(), + position: Some(Ref::Existing(place)), + import_key, + }) +} + +fn held(handle: &str) -> Mismatch { + Mismatch::ImportKeyHeld { + handle: DraftHandle::new(handle), + } +} + +fn duplicate(handle: &str) -> Mismatch { + Mismatch::DuplicateImportKey { + handle: DraftHandle::new(handle), + } +} + +fn malformed(handle: &str) -> Mismatch { + Mismatch::MalformedImportKey { + handle: DraftHandle::new(handle), + } +} + +fn keys_in(kernel: &WorldKernel) -> Vec { + kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .filter_map(|subject| subject.import_key) + .collect() +} + +#[test] +fn one_patch_cannot_declare_two_subjects_with_one_import_key() { + // At genesis. + let mut world = creation("Twins"); + for declaration in &mut world.patch.declarations { + if let Declaration::Subject(subject) = declaration + && (subject.handle == DraftHandle::new("persona") + || subject.handle == DraftHandle::new("operator")) + { + subject.import_key = Some(alpha()); + } + } + let result = create(world); + assert_eq!(rejected(result), vec![duplicate("operator")]); + + // In a later patch, with the key unheld. + let mut kernel = keyed_world(); + let place = commons(&kernel); + let revision = kernel.state.revision; + let beta = Some(key("aetheria.ship", "Beta")); + let error = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![ + keyed("first", beta.clone(), place), + keyed("second", beta, place), + ]), + ); + assert_eq!(rejected(error), vec![duplicate("second")]); + assert_eq!(kernel.state.revision, revision, "a refusal moved the world"); +} + +/// The fixture world past genesis: Play has added an unwalked place. +fn advanced_keyed_world() -> (WorldKernel, EntityId) { + let mut kernel = keyed_world(); + let place = commons(&kernel); + submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("dead-end"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("gate"), + label: "The Field Gate".into(), + from: Ref::Existing(place), + to: Ref::Draft(DraftHandle::new("dead-end")), + access: AccessKind::Public, + cost: Cost(1), + }), + ]), + ) + .unwrap(); + let dead_end = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Unwalked Road") + .map(|(id, _)| id) + .unwrap(); + (kernel, dead_end) +} + +/// Each door names the held key, typed, and the refusal leaves the revision +/// where it was. +fn refuse_held_key_at_each_door( + kernel: &mut WorldKernel, + place: EntityId, + doors: Vec<(&str, CallerId)>, +) { + for (door, caller) in doors { + let revision = kernel.state.revision; + let result = submit_as( + kernel, + caller, + patch_of(vec![keyed("copy", Some(alpha()), place)]), + ); + assert_eq!(rejected(result), vec![held("copy")], "{door}"); + assert_eq!( + kernel.state.revision, revision, + "{door} refusal moved the world" + ); + } +} + +#[test] +fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { + let (mut kernel, dead_end) = advanced_keyed_world(); + assert!(kernel.state.revision > 0, "the world has moved past genesis"); + refuse_held_key_at_each_door( + &mut kernel, + dead_end, + vec![("play", CallerId::Play)], + ); + // The same doors admit an unheld key, so the refusals are the key's; and + // what a door admitted is held against every later door. + let fresh = key("aetheria.ship", "Gamma"); + let receipt = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("fresh", Some(fresh.clone()), dead_end)]), + ) + .unwrap(); + assert!(receipt.resulting_revision > 0); + let again = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("fresh-again", Some(fresh), dead_end)]), + ); + assert_eq!(rejected(again), vec![held("fresh-again")]); +} + +#[test] +fn a_held_import_key_is_refused_in_a_later_patch() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("again", Some(alpha()), place)]), + ); + assert_eq!(rejected(error), vec![held("again")]); + assert_eq!(kernel.state.revision, revision); + assert_eq!(keys_in(&kernel), vec![alpha()]); +} + +#[test] +fn a_retired_subjects_import_key_is_never_reissued() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let witness = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.import_key.is_some()) + .unwrap() + .id; + submit_as( + &mut kernel, + CallerId::Play, + WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Retire { + subject: Ref::Existing(witness), + }], + evidence: Vec::new(), + }, + ) + .unwrap(); + let retired = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == witness) + .unwrap(); + assert!(retired.retired, "the witness is retired"); + assert_eq!( + retired.import_key, + Some(alpha()), + "a retired subject keeps its key" + ); + let error = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("reborn", Some(alpha()), place)]), + ); + assert_eq!(rejected(error), vec![held("reborn")]); +} + +#[test] +fn keys_that_differ_in_any_way_are_distinct_records() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + // Same length, case, prefix, the same concatenation split elsewhere, and + // the parts swapped: none is the held key. + let forgeries = [ + key("aetheria.ship", "Alphb"), + key("aetheria.ship", "alpha"), + key("aetheria.ship", "Alph"), + key("aetheria.ship", "Alpha2"), + key("aetheria.shipA", "lpha"), + key("aetheria.sh", "ipAlpha"), + key("Aetheria.ship", "Alpha"), + key("Alpha", "aetheria.ship"), + key("aetheria.ship2", "Alpha"), + ]; + let declarations = forgeries + .iter() + .enumerate() + .map(|(index, forged)| keyed(&format!("forged-{index}"), Some(forged.clone()), place)) + .collect(); + submit_as( + &mut kernel, + CallerId::Play, + patch_of(declarations), + ) + .expect("nine distinct keys beside the held one are admitted together"); + let held_now: BTreeSet = keys_in(&kernel).into_iter().collect(); + assert_eq!(held_now.len(), forgeries.len() + 1); + // And each is then held exactly: repeating any one is refused. + for (index, forged) in forgeries.iter().enumerate() { + let again = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("repeat", Some(forged.clone()), place)]), + ); + assert_eq!(rejected(again), vec![held("repeat")], "forgery {index}"); + } +} + +#[test] +fn a_malformed_import_key_is_refused_without_echoing_it() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let long = "x".repeat(201); + let wide = "é".repeat(101); + let cases = [ + key("", "Delta"), + key("aetheria.ship", ""), + key("aetheria ship", "Delta"), + key("aetheria.ship", "Del\tta"), + key("aetheria.ship", "Del\u{a0}ta"), + key("aetheria.ship", " Delta"), + key("aetheria.ship", "Delta\n"), + key(&long, "Delta"), + key("aetheria.ship", &long), + key("aetheria.ship", &wide), + key(&wide, "Delta"), + ]; + for (index, bad) in cases.iter().enumerate() { + let set = rejected(submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("bad", Some(bad.clone()), place)]), + )); + assert_eq!(set, vec![malformed("bad")], "case {index}"); + let spelled = format!("{set:?}"); + assert!( + !spelled.contains("Delta") && !spelled.contains("aetheria"), + "case {index} echoed the key" + ); + } + // The limit is 200 bytes per part, counted in bytes. + let edge = "é".repeat(100); + let at_limit = [ + key(&"x".repeat(200), &edge), + key("aetheria.ship", &"y".repeat(200)), + ]; + let declarations = at_limit + .iter() + .enumerate() + .map(|(index, limit)| keyed(&format!("edge-{index}"), Some(limit.clone()), place)) + .collect(); + submit_as( + &mut kernel, + CallerId::Play, + patch_of(declarations), + ) + .expect("keys of exactly 200 bytes per part are admitted"); +} + +#[test] +fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_elsewhere() { + let kernel = keyed_world(); + let place = commons(&kernel); + let resolve = |handle: &str| { + crate::patch::resolve_patch( + &kernel.state, + CommandId::issue(), + &patch_of(vec![keyed( + handle, + Some(key("aetheria.ship", "Omega")), + place, + )]), + ) + .expect("the key is unheld at the revision both were resolved against") + }; + let (first, second) = (resolve("first"), resolve("second")); + let mut state = kernel.state.clone(); + let before = state.subjects.len(); + let effect = |resolved| crate::WorldEffect::PatchAdmitted { + resolved, + }; + crate::apply_effect( + &mut state, + CommandId::issue(), + &CallerId::Play, + &effect(first), + ) + .unwrap(); + assert_eq!(state.subjects.len(), before + 1); + let result = crate::apply_effect( + &mut state, + CommandId::issue(), + &CallerId::Play, + &effect(second), + ); + assert!( + matches!(result, Err(KernelError::Invariant(_))), + "{result:?}" + ); + assert_eq!( + state.subjects.len(), + before + 1, + "the second subject was installed" + ); +} + +fn contains(haystack: &[u8], needle: &[u8]) -> bool { + haystack.windows(needle.len()).any(|window| window == needle) +} + +#[test] +fn keyless_world_digests_unchanged() { + // A subject nobody imported serialises without the field at all, so every + // digest written before keys existed is the digest of the same bytes. + let kernel = create(creation("Keyless")); + let kernel = kernel.unwrap(); + let state = kernel.state.encoded_documents(); + assert!( + !contains(&state, b"import_key"), + "a keyless world grew a field" + ); + // A keyed world carries it and digests differently. + let keyed = keyed_world(); + let keyed_state = keyed.state.encoded_documents(); + assert!(contains(&keyed_state, b"import_key")); + assert_ne!( + keyed.state.full_state_digest().unwrap(), + kernel.state.full_state_digest().unwrap() + ); + // And a world nobody imported into holds every key absent. + assert!(kernel.state.subjects.values().all(|s| s.import_key.is_none())); +} + +#[test] +fn a_keyed_world_reopens_with_its_keys_and_digests() { + let kernel = keyed_world(); + let snapshot = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).unwrap(); + let again = reopened.snapshot().unwrap(); + assert_eq!(again.state_digest, snapshot.state_digest); + let keys = keys_in(&reopened); + assert_eq!(keys, vec![alpha()]); + // A reader of the snapshot gets both parts back, separately. + assert_eq!(keys[0].schema(), "aetheria.ship"); + assert_eq!(keys[0].record(), "Alpha"); +} + + +#[test] +fn a_record_key_is_one_canonical_spelling() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let nfc = "Caf\u{e9}"; + let nfd = "Cafe\u{301}"; + let submit = |kernel: &mut WorldKernel, handle: &str, record: &str| { + submit_as( + kernel, + CallerId::Play, + patch_of(vec![keyed( + handle, + Some(key("aetheria.ship", record)), + place, + )]), + ) + }; + submit(&mut kernel, "nfc", nfc).expect("the NFC spelling is admitted"); + let refused = [ + nfd, + "Alpha\u{200b}", + "Alpha\u{0}", + "\u{feff}Alpha", + "Alpha\u{202e}", + "Alpha\u{7}", + "Del ta", + "Del\tta", + "Del\u{a0}ta", + "Del\u{2003}ta", + "Del\nta", + // The violation sits deep in a long, real-shaped path, past any prefix. + "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Cafe\u{301}", + "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan\u{200b}Hart", + ]; + for (index, record) in refused.iter().enumerate() { + let set = rejected(submit(&mut kernel, "bad", record)); + assert_eq!(set, vec![malformed("bad")], "spelling {index}"); + assert!( + !format!("{set:?}").contains("Alpha"), + "spelling {index} echoed the key" + ); + } + assert_eq!( + keys_in(&kernel).len(), + 2, + "only the genesis key and the NFC key are held" + ); +} + +#[test] +fn a_lore_page_path_with_spaces_is_a_record_key() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let record = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart"; + let declare = |kernel: &mut WorldKernel, handle: &str| { + submit_as( + kernel, + CallerId::Play, + patch_of(vec![keyed( + handle, + Some(key("aetheria.lore", record)), + place, + )]), + ) + }; + declare(&mut kernel, "ewan").expect("a path with interior spaces is admitted"); + assert_eq!(rejected(declare(&mut kernel, "again")), vec![held("again")]); +} + +#[test] +fn a_loaded_state_with_a_bad_import_key_is_refused() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed( + "beta", + Some(key("aetheria.ship", "Beta")), + place, + )]), + ) + .unwrap(); + assert!(crate::journal::verify_state_shape(&kernel.state).is_ok()); + let corrupt = |edit: &dyn Fn(&mut ImportKey)| { + let mut state = kernel.state.clone(); + let ids: Vec<_> = state.subjects.keys().copied().collect(); + for id in ids { + if let Some(held) = state.subjects.get_mut(&id).and_then(|s| s.import_key.as_mut()) { + edit(held); + } + } + crate::journal::verify_state_shape(&state) + }; + let shared = corrupt(&|held| *held = alpha()); + assert!( + matches!(&shared, Err(crate::journal::JournalError::Corrupt(why)) if why.contains("import key")), + "two subjects sharing one key: {shared:?}" + ); + assert!( + corrupt(&|held| *held = key("aetheria.ship", " Beta ")).is_err(), + "a key with edge spaces must not load" + ); + assert!( + corrupt(&|held| *held = key("", "")).is_err(), + "an empty key must not load" + ); + assert!( + corrupt(&|held| *held = key("aetheria.ship", "Be\u{200b}ta")).is_err(), + "a key with a format character must not load" + ); +} + +/// The admission backstop, reached with an effect resolution never produced: a +/// resolved patch whose two subjects carry one key. The control is the same +/// effect with distinct keys, admitted by the same function. +#[test] +fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() { + let kernel = keyed_world(); + let place = commons(&kernel); + let resolve = || { + crate::patch::resolve_patch( + &kernel.state, + CommandId::issue(), + &patch_of(vec![ + keyed("first", Some(key("aetheria.ship", "Beta")), place), + keyed("second", Some(key("aetheria.ship", "Gamma")), place), + ]), + ) + .expect("two distinct keys resolve") + }; + let resolves_to = crate::resolution_revision(&kernel.state).unwrap(); + let mut control = kernel.state.clone(); + crate::admit_resolved(&mut control, &resolve(), resolves_to) + .expect("distinct keys are admitted"); + + let mut twinned = resolve(); + assert_eq!(twinned.subjects.len(), 2); + twinned.subjects[1].subject.import_key = twinned.subjects[0].subject.import_key.clone(); + let mut state = kernel.state.clone(); + let error = crate::admit_resolved(&mut state, &twinned, resolves_to) + .expect_err("one key on two resolved subjects is refused"); + assert!( + matches!(&error, KernelError::Invariant(why) if why.contains("import key")), + "{error:?}" + ); + assert!(!format!("{error:?}").contains("Beta"), "the refusal echoed the key"); +} + +/// A decomposable character at every position of a real-shaped key: the NFD +/// spelling is refused wherever it sits, the NFC spelling is admitted, so the +/// rule cannot be a prefix, suffix or first-character check. +#[test] +fn a_decomposable_character_is_refused_in_nfd_at_every_position() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let template: Vec = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart" + .chars() + .collect(); + let submit = |kernel: &mut WorldKernel, handle: &str, record: String| { + submit_as( + kernel, + CallerId::Play, + patch_of(vec![keyed( + handle, + Some(key("aetheria.lore", &record)), + place, + )]), + ) + }; + let spelled = |position: usize, inserted: &str| { + let mut record: String = template[..position].iter().collect(); + record.push_str(inserted); + record.extend(&template[position..]); + record + }; + for position in 0..=template.len() { + let nfd = spelled(position, "e\u{301}"); + assert!( + !unicode_normalization::is_nfc(&nfd), + "position {position} is not NFD" + ); + let set = rejected(submit(&mut kernel, "bad", nfd)); + assert_eq!(set, vec![malformed("bad")], "NFD at position {position}"); + } + for position in 0..=template.len() { + let nfc = spelled(position, "\u{e9}"); + submit(&mut kernel, &format!("good{position}"), nfc) + .unwrap_or_else(|_| panic!("NFC at position {position} was refused")); + } + assert_eq!( + keys_in(&kernel).len(), + 1 + template.len() + 1, + "the genesis key and one NFC key per position are held, no NFD key" + ); +} + +#[test] +fn the_owner_door_is_closed_to_a_keyed_declaration() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + CallerId::Principal(owner()), + patch_of(vec![keyed("fresh", Some(key("aetheria.ship", "Gamma")), place)]), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + assert_eq!(kernel.state.revision, revision); +} diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs new file mode 100644 index 000000000..929ce057c --- /dev/null +++ b/native/aetherlight/src/journal.rs @@ -0,0 +1,2329 @@ +use super::{ + COMMIT_SCHEMA, CommittedCommand, KernelError, WorldCommit, WorldEffect, + WorldId, WorldState, apply_effect, commit_digest, reduce, +}; +use crate::docs::Changed; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use std::collections::{BTreeMap, BTreeSet}; +use thiserror::Error; + +pub(super) const JOURNAL_SCHEMA: &str = "aetherlight.journal.v1"; + +#[derive(Debug, Error)] +pub(super) enum JournalError { + #[error("world journal is corrupt: {0}")] + Corrupt(String), + /// A well-formed commit of another schema generation: not damage, a world + /// this build cannot read. Named apart so a store can tell an old save from + /// a corrupt one. + #[error("commit schema {found} is not the supported {supported}")] + UnsupportedSchema { found: String, supported: &'static str }, +} + +/// The one judge of the schema generation, asked of every commit before any of +/// its other fields is believed. +fn require_commit_schema(commit: &WorldCommit) -> Result<(), JournalError> { + if commit.schema == COMMIT_SCHEMA { + return Ok(()); + } + Err(JournalError::UnsupportedSchema { + found: commit.schema.clone(), + supported: COMMIT_SCHEMA, + }) +} + +/// What an export carries: the schema that names the format, and the commits in +/// revision order. Nothing else is stored, because nothing else is truth: the +/// head state is the replay of these commits. +#[derive(Serialize)] +struct ExportRef<'a> { + schema: &'a str, + commits: &'a [WorldCommit], +} + +#[derive(Serialize, Deserialize)] +struct Export { + schema: String, + commits: Vec, +} + +/// The only record of a world: its commits in revision order, genesis first. +pub(super) struct WorldJournal { + commits: Vec, +} + +impl WorldJournal { + pub(super) fn genesis(genesis: WorldCommit) -> Self { + Self { + commits: vec![genesis], + } + } + + pub(super) fn append(&mut self, commit: WorldCommit) { + self.commits.push(commit); + } + + /// Every decision the world has acted on, oldest first: the one place an + /// event lives, in the commit that applied it. + pub(super) fn acted_events(&self) -> impl Iterator { + self.commits.iter().filter_map(|commit| match &commit.effect { + WorldEffect::Acted { event, .. } => Some(event), + _ => None, + }) + } + + pub(super) fn export(&self) -> Result, KernelError> { + rmp_serde::to_vec_named(&ExportRef { + schema: JOURNAL_SCHEMA, + commits: &self.commits, + }) + .map_err(|error| KernelError::Serialization(error.to_string())) + } + + /// Decode canonically, then replay: the head state is whatever the chain + /// derives, and a chain that does not verify is not a world. + /// + /// A chain verifies as a prefix, so an export with its tail dropped, or an + /// older export, opens as a valid shorter world. The holder of the bytes + /// owns the head: it keeps the revision and state digest from `snapshot()` + /// at export time and compares them after `open` (AL5's C# store). + pub(super) fn open(bytes: &[u8]) -> Result<(Self, WorldState), JournalError> { + let export: Export = decode(bytes)?; + if export.schema != JOURNAL_SCHEMA { + return Err(JournalError::Corrupt(format!( + "export schema {} is not {JOURNAL_SCHEMA}", + export.schema + ))); + } + let state = verify_history(&export.commits)?; + Ok(( + Self { + commits: export.commits, + }, + state, + )) + } + + #[cfg(test)] + pub(super) fn commit_count(&self) -> usize { + self.commits.len() + } + + #[cfg(test)] + pub(super) fn commits_for_test(&self) -> Vec { + self.commits.clone() + } +} + +/// The one judge of a stored chain, `pub(super)` so a forgery test outside this +/// module routes through the same function that `open` does. It replays the +/// commits in revision order from genesis and returns the head state they +/// derive; position `i` must hold resulting revision `i`. +pub(super) fn verify_history(commits: &[WorldCommit]) -> Result { + let genesis = commits + .first() + .ok_or_else(|| JournalError::Corrupt("world has no genesis commit".into()))?; + require_commit_schema(genesis)?; + let CommittedCommand::CreateWorld(genesis_command) = &genesis.command else { + return Err(JournalError::Corrupt( + "first commit does not contain the immutable creation command".into(), + )); + }; + let WorldEffect::WorldCreated { .. } = &genesis.effect else { + return Err(JournalError::Corrupt( + "first commit is not immutable world genesis".into(), + )); + }; + if genesis.previous_revision.is_some() + || genesis.resulting_revision != 0 + || genesis.world_id != WorldId::of(genesis_command.id()) + || genesis.previous_state_digest.is_some() + || genesis.previous_commit_digest.is_some() + || commit_digest(genesis).map_err(kernel_error)? != genesis.digest + { + return Err(JournalError::Corrupt( + "genesis commit is not canonical or verifiable".into(), + )); + } + let mut replay = WorldState::genesis(genesis.world_id, genesis_command, &genesis.effect) + .map_err(kernel_error)?; + verify_state_shape(&replay)?; + let born: Vec<_> = replay.commitments.keys().map(|subject| (*subject, None)).collect(); + verify_commitments_are_future(&replay, &born)?; + if replay.state_digest != genesis.resulting_state_digest { + return Err(JournalError::Corrupt( + "genesis resulting state digest is invalid".into(), + )); + } + replay.last_commit_digest = Some(genesis.digest.clone()); + + for commit in &commits[1..] { + require_commit_schema(commit)?; + if commit.world_id != replay.header.world_id + || commit.previous_revision != Some(replay.revision) + || commit.resulting_revision != replay.revision.saturating_add(1) + || commit.previous_state_digest.as_deref() != Some(replay.state_digest.as_str()) + || commit.previous_commit_digest != replay.last_commit_digest + || commit_digest(commit).map_err(kernel_error)? != commit.digest + { + return Err(JournalError::Corrupt( + "commit chain is not contiguous or verifiable".into(), + )); + } + // Authority is re-decided here for free: `apply_committed_command` + // re-runs `reduce` against the pre-commit state and requires effect + // equality, then `apply_effect`, and both of those call + // `require_play`. A forged commit recording the owner as the caller of + // a post-genesis command fails replay rather than being admitted by a + // reducer that trusts the recorded caller. A third statement of the same rule here would be a + // third owner of one decision. + replay.begin(); + apply_committed_command(&mut replay, commit)?; + // The clock needs no chain check of its own: only `TimeAdvanced` writes + // it, `apply_effect` re-derives `to` from a `TickMinutes` that cannot + // be read outside `1..=MAX_ROUTE_COST`, so every tick moves it forward + // and nothing else moves it. + replay.revision = commit.resulting_revision; + let accumulator = replay.folded().map_err(kernel_error)?; + replay.state_digest = accumulator.state_digest(replay.revision); + if replay.state_digest != commit.resulting_state_digest { + return Err(JournalError::Corrupt( + "commit resulting state digest is invalid".into(), + )); + } + let touched = replay.finish(accumulator); + verify_commitments_are_future(&replay, &touched)?; + replay.last_commit_digest = Some(commit.digest.clone()); + } + verify_state_shape(&replay)?; + Ok(replay) +} + +/// The replay-side twin of `Mismatch::CommitmentDueInThePast`: every commitment +/// key this commit introduced is due after the post-commit clock. Replay already +/// reconstructs both sides, and the transaction's change set names the only subjects +/// that can hold a new key, with what each held before. +fn verify_commitments_are_future( + state: &WorldState, + touched: &[Changed>], +) -> Result<(), JournalError> { + for (subject_id, before) in touched { + let Some(held) = state.commitments.get(subject_id) else { + continue; + }; + for (key, commitment) in held { + let existed = before + .as_ref() + .is_some_and(|previous| previous.contains_key(key)); + if !existed && commitment.due <= state.header.now { + return Err(JournalError::Corrupt( + "a commitment was born at or after its own due date".into(), + )); + } + } + } + Ok(()) +} + +pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { + if state.header.title.trim().is_empty() || state.header.title.trim() != state.header.title { + return Err(JournalError::Corrupt( + "world title is empty or noncanonical".into(), + )); + } + super::validate_principal(&state.header.owner).map_err(kernel_error)?; + if state.subjects.is_empty() { + return Err(JournalError::Corrupt("world ontology is empty".into())); + } + let is_place = |entity_id: &super::EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == super::EntityKind::Place) + }; + for (entity_id, entity) in &state.entities { + if !super::patch::is_canonical_text(&entity.label) { + return Err(JournalError::Corrupt( + "entity label is empty or noncanonical".into(), + )); + } + if let Some(container) = entity.container + && (entity.kind != super::EntityKind::Place || !is_place(&container)) + { + return Err(JournalError::Corrupt( + "entity container does not name a canonical place".into(), + )); + } + if !super::patch::containment_terminates(*entity_id, &state.entities) { + return Err(JournalError::Corrupt("place contains itself".into())); + } + } + for edge in state.edges.values() { + let (from, to) = edge.endpoints(); + if !is_place(&from) + || !is_place(&to) + || from == to + || !super::patch::is_valid_cost(edge.cost()) + { + return Err(JournalError::Corrupt( + "route does not join two distinct places at a valid cost".into(), + )); + } + } + for (subject_id, position) in &state.positions { + if !state.subjects.contains_key(subject_id) || !is_place(&position.place) { + return Err(JournalError::Corrupt( + "position does not name a canonical subject and place".into(), + )); + } + } + let is_resource = |entity_id: &super::EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == super::EntityKind::Resource) + }; + // Absence is zero and one slot holds one pair, so a store satisfying these + // clauses cannot carry a zero, an empty holder, a duplicate, or a dangling + // holding — with no scan for any of them. + for (subject_id, held) in &state.holdings { + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || held + .iter() + .any(|(resource, quantity)| !is_resource(resource) || quantity.0 == 0) + { + return Err(JournalError::Corrupt( + "holding does not name a canonical subject and resource at a nonzero quantity" + .into(), + )); + } + } + for (subject_id, targets) in &state.dependencies { + let target_is_canonical = |target: &super::DependencyTarget| match target { + super::DependencyTarget::Resource(entity_id) => is_resource(entity_id), + super::DependencyTarget::Route(edge_id) => state.edges.contains_key(edge_id), + super::DependencyTarget::Subject(other) => { + other != subject_id && state.subjects.contains_key(other) + } + }; + if !state.subjects.contains_key(subject_id) + || targets.is_empty() + || !targets.iter().all(target_is_canonical) + { + return Err(JournalError::Corrupt( + "dependency does not name a canonical subject and a distinct canonical target" + .into(), + )); + } + } + // Facts, channels, and knowledge. The `facts`/`channels` bijections run both + // ways: a payload row without its entity, or an entity of that kind without + // its payload, is a referenceable half-thing. + for (entity_id, record) in &state.facts { + let standing_is_live = match &record.standing { + super::FactStanding::Canonical { evidence } => { + super::patch::is_canonical_text(evidence.text()) + } + super::FactStanding::Claimed { by } => state.subjects.contains_key(by), + super::FactStanding::Ruled => true, + }; + if !state + .entities + .get(entity_id) + .is_some_and(|entity| entity.kind == super::EntityKind::Fact) + || !super::patch::is_canonical_text(record.statement.as_str()) + || !standing_is_live + { + return Err(JournalError::Corrupt( + "a fact names no canonical entity, statement, or standing".into(), + )); + } + } + for (entity_id, record) in &state.channels { + let reach_is_live = match &record.reach { + super::Reach::Subjects(members) => members + .iter() + .all(|subject_id| state.subjects.contains_key(subject_id)), + super::Reach::Place(place) => is_place(place), + }; + if !state + .entities + .get(entity_id) + .is_some_and(|entity| entity.kind == super::EntityKind::Channel) + || !reach_is_live + || !record + .controller + .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) + { + return Err(JournalError::Corrupt( + "a channel names no canonical entity, reach, or controller".into(), + )); + } + } + for (entity_id, entity) in &state.entities { + let paired = match entity.kind { + super::EntityKind::Fact => state.facts.contains_key(entity_id), + super::EntityKind::Channel => state.channels.contains_key(entity_id), + super::EntityKind::Place | super::EntityKind::Resource => true, + }; + if !paired { + return Err(JournalError::Corrupt( + "a fact or channel entity carries no payload row".into(), + )); + } + } + for ((subject_id, fact), entry) in &state.knowledge { + let entry_is_live = |entry: &super::Knowledge| { + entry.acquired_at <= state.revision + && match entry.source { + super::KnowledgeSource::Told { by, via } => { + state.subjects.contains_key(&by) + && via.is_none_or(|channel| state.channels.contains_key(&channel)) + } + super::KnowledgeSource::Seen { by } => state.subjects.contains_key(&by), + super::KnowledgeSource::Witnessed | super::KnowledgeSource::Evidenced => true, + } + }; + if !state.subjects.contains_key(subject_id) + || !state.facts.contains_key(fact) + || !entry_is_live(entry) + { + return Err(JournalError::Corrupt( + "knowledge does not name a canonical subject, fact, and source, or was acquired ahead of the world's revision" + .into(), + )); + } + } + // Commitments, pressures, and the authored scale target. + // Absence is the only spelling of nothing at every level, so a store + // satisfying these clauses carries no empty inner map, no zero magnitude, + // and no dangling row — with no scan for any of them. + for (subject_id, held) in &state.commitments { + let commitment_is_canonical = |commitment: &super::Commitment| { + (commitment.kind == super::CommitmentKind::Routine) == commitment.period.is_some() + && (commitment.kind == super::CommitmentKind::Routine + || commitment.checks.is_empty()) + && match commitment.counterparty { + Some(counterparty) => { + counterparty != *subject_id + && state.subjects.contains_key(&counterparty) + && commitment.kind != super::CommitmentKind::Goal + } + None => true, + } + && commitment + .checks + .iter() + .all(|check| super::bound_precondition_is_live(state, check)) + }; + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || !held.values().all(commitment_is_canonical) + { + return Err(JournalError::Corrupt( + "a commitment does not name a canonical promisor, counterparty, shape, or check" + .into(), + )); + } + } + for (target, held) in &state.pressures { + let source_is_live = |source: &super::PressureSource| match source { + super::PressureSource::Commitment { subject, key } => state + .commitments + .get(subject) + .is_some_and(|commitments| commitments.contains_key(key)), + super::PressureSource::Dependency(dependency) => state + .dependencies + .get(target) + .is_some_and(|targets| targets.contains(dependency)), + super::PressureSource::Subject(subject_id) => state.subjects.contains_key(subject_id), + }; + if !state.subjects.contains_key(target) + || held.is_empty() + || held + .iter() + .any(|(source, magnitude)| magnitude.0 == 0 || !source_is_live(source)) + { + return Err(JournalError::Corrupt( + "a pressure row does not name a canonical target, live source, and nonzero \ + magnitude" + .into(), + )); + } + } + // The civic subgraph, in the slot the deleted `authority_scope` check + // occupied: a jurisdiction names live ground under a canonical kind, an + // office sits on an institution and lends something to a person who holds + // no other office there, and a forum names a live subject. + let target_is_canonical = |target: &super::AuthorityTarget| match target { + super::AuthorityTarget::Subject(subject_id) => state.subjects.contains_key(subject_id), + super::AuthorityTarget::PlaceSubtree(entity_id) => is_place(entity_id), + }; + for (subject_id, grants) in &state.authority { + if !state.subjects.contains_key(subject_id) + || grants.is_empty() + || !grants.iter().all(|grant| { + super::patch::is_civic_name(&grant.kind.0) && target_is_canonical(&grant.over) + }) + { + return Err(JournalError::Corrupt( + "authority does not name a canonical subject and live ground under a canonical kind" + .into(), + )); + } + } + for (institution, offices) in &state.selection { + let mut incumbents = BTreeSet::new(); + if state.subjects.get(institution).map(|subject| subject.kind) + != Some(super::SubjectKind::Institution) + || offices.is_empty() + { + return Err(JournalError::Corrupt( + "an office register does not name a canonical institution".into(), + )); + } + for (name, office) in offices { + let incumbent_is_person = office.incumbent.is_none_or(|incumbent| { + state.subjects.get(&incumbent).map(|subject| subject.kind) + == Some(super::SubjectKind::Person) + && incumbents.insert(incumbent) + }); + if !super::patch::is_civic_name(&name.0) + || office.delegated.is_empty() + || !office + .delegated + .iter() + .all(|kind| super::patch::is_civic_name(&kind.0)) + || !incumbent_is_person + { + return Err(JournalError::Corrupt( + "an office lends nothing, is misnamed, or is held twice or by a non-person" + .into(), + )); + } + } + } + for (grievance, forum) in &state.redress { + if !super::patch::is_civic_name(&grievance.0) + || !state.subjects.contains_key(&forum.forum) + || !target_is_canonical(&forum.standing) + { + return Err(JournalError::Corrupt( + "a forum does not name a canonical grievance, subject, and standing".into(), + )); + } + } + if super::overlapping_holder(state).is_some() { + return Err(JournalError::Corrupt( + "one subject holds two overlapping jurisdictions of one kind".into(), + )); + } + let mut declared_keys = BTreeSet::new(); + for subject in state.subjects.values() { + if let Some(key) = &subject.import_key + && super::patch::import_key_fault(key, |_| false, &mut declared_keys).is_some() + { + return Err(JournalError::Corrupt( + "subject import key is malformed or held by two subjects".into(), + )); + } + } + for subject in state.subjects.values() { + if !super::patch::is_canonical_text(&subject.label) { + return Err(JournalError::Corrupt( + "subject label is empty or noncanonical".into(), + )); + } + } + // A grant row is a verb list: non-empty, for a live subject, catalog + // entries only. A subject holding no verb holds no row. + for (subject_id, granted) in &state.affordance_grants { + if !state.subjects.contains_key(subject_id) + || super::is_retired(state, *subject_id) + || granted.is_empty() + || granted + .iter() + .any(|affordance_id| !state.affordance_catalog.contains_key(affordance_id)) + { + return Err(JournalError::Corrupt( + "affordance grant is empty, unscoped, retired, or names no catalog entry".into(), + )); + } + } + // Every stored entry still passes the declaration validator, so a forged + // catalog row cannot install an entry the resolver would have refused. + for entry in state.affordance_catalog.values() { + if !super::patch::entry_is_admissible(entry) { + return Err(JournalError::Corrupt( + "stored affordance entry is not admissible".into(), + )); + } + } + Ok(()) +} + +fn apply_committed_command( + state: &mut WorldState, + commit: &WorldCommit, +) -> Result<(), JournalError> { + let CommittedCommand::WorldCommand(command) = &commit.command else { + return Err(JournalError::Corrupt( + "creation command appears after world genesis".into(), + )); + }; + if command.world_id != state.header.world_id || command.expected_revision != state.revision { + return Err(JournalError::Corrupt( + "committed command does not target the exact replay state".into(), + )); + } + let expected_effect = reduce(state, command).map_err(kernel_error)?; + if expected_effect != commit.effect { + return Err(JournalError::Corrupt( + "committed effect is not the deterministic reduction of its command".into(), + )); + } + apply_effect( + state, + command.id(), + &commit.command.caller(), + &expected_effect, + ) + .map_err(kernel_error) +} + +fn decode(bytes: &[u8]) -> Result { + let value: T = rmp_serde::from_slice(bytes) + .map_err(|error| JournalError::Corrupt(format!("could not decode the export: {error}")))?; + let canonical = rmp_serde::to_vec_named(&value) + .map_err(|error| JournalError::Corrupt(error.to_string()))?; + if canonical != bytes { + return Err(JournalError::Corrupt("the export is not canonical".into())); + } + Ok(value) +} + +fn kernel_error(error: KernelError) -> JournalError { + JournalError::Corrupt(error.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::patch::kernel_speak_grant; + use crate::tests::speak_entry; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CreateWorld, Declaration, + DraftHandle, EntityDeclaration, EntityId, EntityKind, Position, PrincipalId, + Ref, SubjectDeclaration, SubjectKind, WorldKernel, WorldPatch, + }; + + #[derive(serde::Serialize, serde::Deserialize)] + struct CanonicalFixture { + value: u8, + } + + /// The bytes an honest exporter writes for `commits`, whatever they claim. + pub(super) fn export_of(commits: &[WorldCommit]) -> Vec { + WorldJournal { + commits: commits.to_vec(), + } + .export() + .unwrap() + } + + /// Open a world from forged commits through the door a real export takes: + /// canonical decode, then the one replay judge. + pub(super) fn reopen(commits: &[WorldCommit]) -> Result { + WorldJournal::open(&export_of(commits)).map(|(_, state)| state) + } + + #[test] + fn decode_rejects_an_alternate_messagepack_shape() { + let bytes = rmp_serde::to_vec(&CanonicalFixture { value: 7 }).unwrap(); + assert!(decode::(&bytes).is_err()); + let canonical = rmp_serde::to_vec_named(&CanonicalFixture { value: 7 }).unwrap(); + assert!(decode::(&canonical).is_ok()); + } + + /// The commit a forgery test rewrites: the one the test just committed. + pub(super) fn last_commit(commits: &mut [WorldCommit]) -> &mut WorldCommit { + commits.iter_mut().max_by_key(|commit| commit.resulting_revision).unwrap() + } + + pub(super) fn genesis_commit(commits: &mut [WorldCommit]) -> &mut WorldCommit { + commits.iter_mut().min_by_key(|commit| commit.resulting_revision).unwrap() + } + + fn owner_patch(subject: SubjectDeclaration) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Subject(subject)], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + #[test] + fn replay_rejects_a_forged_command_or_effect_even_with_valid_hashes() { + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation = CreateWorld { + owner: owner.clone(), + title: "Before".into(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + grammar: None, + }; + let (mut kernel, _) = WorldKernel::create(creation, &authenticated).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + CommandEnvelope { + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Play, + body: CommandBody::AdvanceTime { + minutes: crate::TickMinutes::new(1).unwrap(), + }, + }, + &AuthenticatedCaller::verified_play(), + ) + .unwrap(); + + let mut command_forged_commits = kernel.journal.commits.clone(); + let command_forged = last_commit(&mut command_forged_commits); + let CommittedCommand::WorldCommand(command) = &mut command_forged.command else { + panic!("expected a world command"); + }; + command.body = CommandBody::AdvanceTime { + minutes: crate::TickMinutes::new(2).unwrap(), + }; + command_forged.digest = commit_digest(command_forged).unwrap(); + + assert!(matches!( + reopen(&command_forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut caller_forged_commits = kernel.journal.commits.clone(); + let caller_forged = last_commit(&mut caller_forged_commits); + let CommittedCommand::WorldCommand(command) = &mut caller_forged.command else { + panic!("expected a world command"); + }; + command.caller = CallerId::Principal(PrincipalId::new("attacker@example.test")); + caller_forged.digest = commit_digest(caller_forged).unwrap(); + + assert!(matches!( + reopen(&caller_forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut effect_forged_commits = kernel.journal.commits.clone(); + let effect_forged = last_commit(&mut effect_forged_commits); + let WorldEffect::TimeAdvanced { to, .. } = &mut effect_forged.effect else { + panic!("expected a time effect"); + }; + *to = crate::FictionalMinutes(99); + effect_forged.digest = commit_digest(effect_forged).unwrap(); + + assert!(matches!( + reopen(&effect_forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + #[test] + fn a_forged_patch_effect_does_not_apply() { + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation = CreateWorld { + owner: owner.clone(), + title: "Kharad".into(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + grammar: None, + }; + let (mut kernel, _) = WorldKernel::create(creation, &authenticated).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + CommandEnvelope { + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Play, + body: CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("rhythm-road"), + label: "The Rhythm Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("rhythm-authority"), + label: "The Rhythm Authority".into(), + kind: SubjectKind::Institution, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + }, + &AuthenticatedCaller::verified_play(), + ) + .unwrap(); + + let mut forged_commits = kernel.journal.commits.clone(); + let forged = last_commit(&mut forged_commits); + let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { + panic!("expected an admitted patch effect"); + }; + resolved.subjects[0].position = Some(Position { + place: EntityId::issue(), + }); + forged.digest = commit_digest(forged).unwrap(); + + assert!(matches!( + reopen(&forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// A world whose history includes a patch and a clock advance, both Play's, + /// reopened from its own export. + fn clock_history() -> WorldKernel { + use crate::tests::{auth_principal, creation, owner, submit_play}; + use crate::TickMinutes; + + let (mut kernel, _) = WorldKernel::create(creation("Clock History"), + &auth_principal(owner()), + ) + .unwrap(); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + patch: crate::WorldPatch { + declarations: vec![crate::patch::Declaration::Entity( + crate::patch::EntityDeclaration { + handle: crate::patch::DraftHandle::new("annex"), + label: "The Annex".into(), + kind: crate::patch::EntityKind::Place, + container: None, + }, + )], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + CommandBody::AdvanceTime { + minutes: TickMinutes::new(30).unwrap(), + }, + ); + kernel + } + + /// Replay re-derives Play's patch and clock advance: the honest history + /// reopens to the same state digest and reading, and the exported bytes do too. + #[test] + fn a_history_with_a_patch_and_a_clock_advance_replays_exactly() { + let kernel = clock_history(); + let replayed = reopen(&kernel.journal.commits).expect("the honest history replays"); + assert_eq!(replayed.state_digest, kernel.state.state_digest); + assert_eq!(replayed.header.now, kernel.state.header.now); + + let (digest, now) = (kernel.state.state_digest.clone(), kernel.state.header.now); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.state.state_digest, digest); + assert_eq!(reopened.state.header.now, now); + } + + /// An export is a claim about a chain, and `open` believes none of it that + /// replay does not derive: a chain with a commit missing, repeated or out of + /// order, a Ghostlight commit or export schema, and a non-canonical + /// encoding of an honest chain are each refused. + #[test] + fn forged_exports_are_refused() { + let kernel = clock_history(); + let honest = kernel.journal.commits.clone(); + assert_eq!(honest.len(), 3, "genesis, a patch and a tick"); + reopen(&honest).expect("the honest chain opens"); + let refused = |what: &str, commits: &[WorldCommit]| { + assert!( + reopen(commits).is_err(), + "{what} was admitted" + ); + }; + + refused("a missing middle commit", &[honest[0].clone(), honest[2].clone()]); + refused("a world without genesis", &honest[1..]); + refused("a repeated commit", &[honest[0].clone(), honest[1].clone(), honest[1].clone(), honest[2].clone()]); + refused("reordered commits", &[honest[0].clone(), honest[2].clone(), honest[1].clone()]); + refused("no commits", &[]); + + // Re-sealed down the chain, so the schema is the only thing wrong. + let mut ghostlight = honest.clone(); + ghostlight[1].schema = "ghostlight.world_commit.consumer.v10".into(); + for index in 1..ghostlight.len() { + if index > 1 { + ghostlight[index].previous_commit_digest = Some(ghostlight[index - 1].digest.clone()); + } + ghostlight[index].digest = commit_digest(&ghostlight[index]).unwrap(); + } + refused("a ghostlight commit schema", &ghostlight); + + let foreign = rmp_serde::to_vec_named(&ExportRef { + schema: "ghostlight.world_state.consumer.v10", + commits: &honest, + }) + .unwrap(); + assert!(matches!( + WorldJournal::open(&foreign), + Err(JournalError::Corrupt(_)) + )); + + let positional = rmp_serde::to_vec(&ExportRef { + schema: JOURNAL_SCHEMA, + commits: &honest, + }) + .unwrap(); + assert!(matches!( + WorldJournal::open(&positional), + Err(JournalError::Corrupt(_)) + )); + assert!(matches!( + WorldJournal::open(&[0xc1]), + Err(JournalError::Corrupt(_)) + )); + } + + /// A chain written under the whole-state digest is refused: its commits carry + /// the v1 schema, re-sealed end to end so the schema is the only thing wrong. + #[test] + fn a_v1_commit_is_refused() { + let kernel = clock_history(); + let mut v1 = kernel.journal.commits.clone(); + reopen(&v1).expect("the honest chain opens"); + for index in 0..v1.len() { + v1[index].schema = "aetherlight.world_commit.v1".into(); + if index > 0 { + v1[index].previous_commit_digest = Some(v1[index - 1].digest.clone()); + } + v1[index].digest = commit_digest(&v1[index]).unwrap(); + } + match reopen(&v1) { + Err(JournalError::UnsupportedSchema { found, supported }) => { + assert_eq!(found, "aetherlight.world_commit.v1"); + assert_eq!(supported, COMMIT_SCHEMA); + } + other => panic!("a v1 chain must be refused by name, got {other:?}"), + } + // A later commit of another generation is refused the same way. + let mut mixed = kernel.journal.commits.clone(); + last_commit(&mut mixed).schema = "aetherlight.world_commit.v3".into(); + assert!(matches!( + reopen(&mixed), + Err(JournalError::UnsupportedSchema { .. }) + )); + } + + /// A stored tick whose span is zero or above the bound is not a world: the + /// export does not decode. This is the door the clock needs no check behind: + /// a zero-minute tick would be a commit that moves nothing, and an oversize + /// one a commit no `submit` could have built. + #[test] + fn a_stored_tick_with_a_span_outside_the_bound_does_not_open() { + let kernel = clock_history(); + let honest = export_of(&kernel.journal.commits); + // MessagePack names the span `minutes` and encodes the honest ones + // (1, 2, 30) as a single positive fixint byte, so each is rewritten in + // place, in the command and again in the effect. + let key = b"\xa7minutes"; + let at: Vec = (0..honest.len() - key.len()) + .filter(|&at| &honest[at..at + key.len()] == key) + .collect(); + assert!(at.len() >= 2, "a tick carries its span in the command and its effect"); + for forged_span in [vec![0x00], [&[0xce][..], &(crate::patch::MAX_ROUTE_COST + 1).to_be_bytes()].concat()] { + let mut bytes = honest.clone(); + for &start in at.iter().rev() { + let value = start + key.len(); + assert!(honest[value] < 0x80, "an honest span is a fixint"); + bytes.splice(value..=value, forged_span.iter().copied()); + } + let error = WorldJournal::open(&bytes).err().expect("a forged span opened"); + assert!( + error.to_string().contains("could not decode the export") + && error.to_string().contains("tick span"), + "{forged_span:?}: {error}" + ); + } + } + + /// The replay-side future check reads only the subjects the transaction + /// touched, and a key a subject already held is not newly born. + #[test] + fn a_commitment_born_due_is_corrupt_only_for_a_touched_new_key() { + use crate::tests::subject_by_label; + let (kernel, _) = crate::golden_tests::golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let held = kernel + .state + .commitments + .get(&witness) + .cloned() + .expect("the witness holds a routine"); + let mut early = kernel.state.clone(); + early.header.get_mut().now = crate::FictionalMinutes(0); + let mut late = kernel.state.clone(); + late.header.get_mut().now = crate::FictionalMinutes(u64::MAX); + + assert!(verify_commitments_are_future(&early, &[(witness, None)]).is_ok()); + assert!(matches!( + verify_commitments_are_future(&late, &[(witness, None)]), + Err(JournalError::Corrupt(_)) + )); + assert!(verify_commitments_are_future(&late, &[(witness, Some(held))]).is_ok()); + assert!(verify_commitments_are_future(&late, &[]).is_ok()); + } + + /// A committed command names the exact world and revision it applies to; + /// each is judged on its own. + #[test] + fn a_command_aimed_at_another_world_or_revision_is_corrupt() { + let kernel = clock_history(); + for aim_at_world in [true, false] { + let mut forged = kernel.journal.commits.clone(); + let last = forged.last_mut().unwrap(); + let CommittedCommand::WorldCommand(command) = &mut last.command else { + panic!("the last commit is a world command"); + }; + if aim_at_world { + command.world_id = WorldId::nil_for_test(); + } else { + command.expected_revision += 1; + } + last.digest = commit_digest(last).unwrap(); + assert!( + matches!(reopen(&forged), Err(JournalError::Corrupt(_))), + "a command aimed at another {} was admitted", + if aim_at_world { "world" } else { "revision" } + ); + } + } + + /// A stored digest is checked against the commit it seals, on its own: + /// flipping one character of any commit's digest, with nothing re-sealed, + /// leaves only the digest clause to refuse it (the last commit and a lone + /// genesis have no successor whose previous-digest could). + #[test] + fn a_stored_digest_flipped_without_resealing_is_refused() { + let kernel = clock_history(); + let honest = kernel.journal.commits.clone(); + let flip = |digest: &str| { + let mut flipped = digest.to_owned(); + let last = flipped.pop().unwrap(); + flipped.push(if last == '0' { '1' } else { '0' }); + flipped + }; + for upto in 1..=honest.len() { + let mut chain = honest[..upto].to_vec(); + let tail = chain.last_mut().unwrap(); + tail.digest = flip(&tail.digest); + assert!( + matches!(reopen(&chain), Err(JournalError::Corrupt(_))), + "a flipped digest on commit {} of {upto} was admitted", + upto - 1 + ); + } + } + + /// Each clause of the genesis condition refuses alone: a lone genesis, + /// re-sealed after one field is rewritten, so nothing else can object. + #[test] + fn each_genesis_clause_refuses_on_its_own() { + let kernel = clock_history(); + let genesis = kernel.journal.commits[0].clone(); + let forgeries: [(&str, &dyn Fn(&mut WorldCommit)); 5] = [ + ("schema", &|commit| commit.schema = "ghostlight.world_commit.consumer.v10".into()), + ("a previous revision", &|commit| commit.previous_revision = Some(0)), + ("a nonzero revision", &|commit| commit.resulting_revision = 1), + ("a previous state digest", &|commit| { + commit.previous_state_digest = Some("sha256:00".into()) + }), + ("a previous commit digest", &|commit| { + commit.previous_commit_digest = Some("sha256:00".into()) + }), + ]; + reopen(std::slice::from_ref(&genesis)).expect("a lone honest genesis opens"); + for (what, forge) in forgeries { + let mut forged = genesis.clone(); + forge(&mut forged); + forged.digest = commit_digest(&forged).unwrap(); + assert!( + reopen(&[forged]).is_err(), + "a genesis with {what} was admitted" + ); + } + } + + /// Position `i` holds resulting revision `i`: a commit that names a later + /// revision than its place, with a state digest honestly computed for that + /// revision, is still not the chain's next commit. + #[test] + fn a_chain_that_skips_a_revision_is_refused() { + let kernel = clock_history(); + let honest = kernel.journal.commits.clone(); + let mut state = reopen(&honest[..2]).expect("genesis and the patch open"); + state.revision = 7; + let mut forged = vec![honest[0].clone(), honest[1].clone()]; + forged[1].resulting_revision = 7; + forged[1].resulting_state_digest = state.full_state_digest().unwrap(); + forged[1].digest = commit_digest(&forged[1]).unwrap(); + assert!(matches!(reopen(&forged), Err(JournalError::Corrupt(_)))); + } + + /// A world is named by its creation: a genesis whose world id is any other + /// is refused, however consistently every id under it was derived. + #[test] + fn a_world_id_not_derived_from_its_creation_is_refused() { + use crate::patch::resolve_patch; + use crate::tests::{auth_principal, creation, owner}; + use crate::{CommandId, PreparedCreation}; + + let input = creation("Misnamed"); + let honest = crate::prepare_creation(input.clone(), &auth_principal(owner())).unwrap(); + let other = WorldId::of(CommandId::issue()); + assert_ne!(other, honest.world_id); + let resolved = resolve_patch( + &WorldState::empty(other, input.owner.clone(), honest.title.clone(), None), + input.id(), + &input.patch, + ) + .unwrap(); + let (kernel, _) = WorldKernel::initialize(PreparedCreation { + command: input, + world_id: other, + owner: honest.owner, + title: honest.title, + resolved, + }) + .unwrap(); + assert!(matches!( + reopen(&kernel.journal.commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// A stored command is not believed about who made it. The forgery re-seals + /// the commit around its rewrite and the head's last commit digest names the + /// re-sealed commit, so no digest can answer for the check; the control, the + /// same re-sealing around the honest caller, replays. Both Play's doors are + /// forged: a patch row and a clock row recorded as the owner's. + #[test] + fn a_commit_forged_to_the_owner_fails_replay() { + use crate::tests::owner; + + let kernel = clock_history(); + let honest: Vec = kernel.journal.commits.clone(); + // Re-seals the rewritten commit and every later one around it, so the + // chain of previous-commit digests agrees and only the caller check is + // left to refuse the history. + let forge = |is_row: &dyn Fn(&WorldEffect) -> bool, + rewrite: &dyn Fn(&mut WorldCommit)| + -> Vec { + let mut forged: Vec = honest.clone(); + forged.sort_by_key(|commit| commit.resulting_revision); + let rows: Vec = (0..forged.len()) + .filter(|index| is_row(&forged[*index].effect)) + .collect(); + let [at] = <[usize; 1]>::try_from(rows) + .expect("the history holds exactly one such row"); + rewrite(&mut forged[at]); + for index in at..forged.len() { + if index > at { + forged[index].previous_commit_digest = Some(forged[index - 1].digest.clone()); + } + forged[index].digest = commit_digest(&forged[index]).unwrap(); + } + forged + }; + let patch_row = |effect: &WorldEffect| matches!(effect, WorldEffect::PatchAdmitted { .. }); + let clock_row = |effect: &WorldEffect| matches!(effect, WorldEffect::TimeAdvanced { .. }); + + for is_row in [&patch_row as &dyn Fn(&WorldEffect) -> bool, &clock_row] { + let control = forge(is_row, &|_| {}); + reopen(&control) + .expect("a consistent re-sealed store replays"); + + let forged = forge(is_row, &|commit| { + if let CommittedCommand::WorldCommand(command) = &mut commit.command { + command.caller = CallerId::Principal(owner()); + } + }); + let error = reopen(&forged) + .expect_err("a commit forged to the owner replayed"); + assert!(matches!(error, JournalError::Corrupt(_)), "{error:?}"); + } + } + + /// The tick is re-derived at replay by the same function that produced it, + /// so a committed motion rewritten after the fact no longer reduces from + /// its command. The clock chain refuses a rewritten reading the same way. + #[test] + fn a_forged_motion_does_not_replay() { + use crate::tests::{auth_principal, command, owner}; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, FictionalMinutes, + TickMinutes, + }; + + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Chronicle"), + &authenticated, + ) + .unwrap(); + let active = kernel.snapshot().unwrap(); + let caller = CallerId::Play; + kernel + .submit( + command( + &active, + caller.clone(), + CommandBody::AdvanceTime { + minutes: TickMinutes::new(30).unwrap(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + let mut forged_commits = kernel.journal.commits.clone(); + let forged = last_commit(&mut forged_commits); + let WorldEffect::TimeAdvanced { to, .. } = &mut forged.effect else { + panic!("expected a time-advanced effect"); + }; + *to = FictionalMinutes(31); + forged.digest = commit_digest(forged).unwrap(); + + assert!(matches!( + reopen(&forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Replay re-derives the operation half too: a committed relocation rewritten + /// to move a different subject no longer reduces from its command. + #[test] + fn a_forged_relocate_effect_does_not_apply() { + use crate::tests::{admit_topology, auth_principal, command, owner}; + + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Kharad"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &active, + CallerId::Play, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![crate::ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }], + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap(); + + let mut forged_commits = kernel.journal.commits.clone(); + let forged = last_commit(&mut forged_commits); + let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { + panic!("expected an admitted patch effect"); + }; + let crate::ResolvedOp::Relocate { subject_id, .. } = &mut resolved.operations[0] + else { + panic!("expected a lowered relocation"); + }; + *subject_id = crate::SubjectId::issue(); + forged.digest = commit_digest(forged).unwrap(); + + assert!(matches!( + reopen(&forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul: `a_forged_band_or_forged_effect_does_not_apply` proves the live + /// `apply_effect` arm re-derives. `verify_state_shape` does not re-derive a + /// band — it only bounds the index and refuses effects under an empty band — + /// so the layer that kills a persisted forgery is replay effect-equality. + /// This forges a committed decision inside the journal, re-digests it into a + /// contiguous chain, and asserts recovery refuses it. + #[test] + fn soul_a_forged_band_or_effect_in_the_journal_dies_at_replay() { + use crate::tests::{ + admit_custody, admit_topology, affordance_named, auth_principal, command, + owner, play_caller, + }; + use crate::{ + AuthenticatedCaller, DecisionInvocation, Magnitude, ProposedEffect, Quantity, + RoleBinding, Target, + }; + + let forge = |kind: &str, mutate: &dyn Fn(&mut crate::DecisionEvent)| { + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("ForgedDecision"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = kernel.snapshot().unwrap(); + let entry = affordance_named(&active, kind); + let caller = play_caller(); + let role = |name: &str, target| RoleBinding { + role: crate::Role(name.into()), + target, + }; + kernel + .submit( + command( + &active, + caller.clone(), + CommandBody::Act { + actor: custody.holder, + invocation: DecisionInvocation { + affordance: entry, + bindings: vec![ + role("from", Target::Subject(custody.holder)), + role("recipient", Target::Subject(custody.counterparty)), + role("place", Target::Entity(topology.yard)), + role("resource", Target::Entity(custody.tithe)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + // The honest journal recovers. + assert!(reopen(&kernel.journal.commits).is_ok()); + + let mut forged_commits = kernel.journal.commits.clone(); + let forged = last_commit(&mut forged_commits); + let WorldEffect::Acted { event, .. } = &mut forged.effect else { + panic!("expected an acted effect"); + }; + mutate(event); + forged.digest = commit_digest(forged).unwrap(); + forged_commits + }; + + // A band the seed did not draw, held inside a chain that verifies. + let commits = forge("carry_chance", &|event| { + event.band = (event.band + 1) % 3; + }); + assert!(matches!( + reopen(&commits), + Err(JournalError::Corrupt(_)) + )); + + // A magnitude the ceiling admitted but the lowering never produced. + let commits = forge("carry", &|event| { + let Some(crate::ResolvedOp::Transfer { qty, .. }) = event.effects.first_mut() + else { + panic!("expected a lowered transfer"); + }; + *qty = Quantity(1); + }); + assert!(matches!( + reopen(&commits), + Err(JournalError::Corrupt(_)) + )); + } + + #[test] + fn replay_rejects_genesis_that_does_not_derive_from_its_creation_command() { + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation = CreateWorld { + owner: owner.clone(), + title: "Admitted".into(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + grammar: None, + }; + let (kernel, _) = WorldKernel::create(creation, &authenticated).unwrap(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = genesis_commit(&mut forged_commits); + let CommittedCommand::CreateWorld(command) = &mut forged.command else { + panic!("expected genesis creation command"); + }; + command.title = "Different command".into(); + forged.digest = commit_digest(forged).unwrap(); + + assert!(matches!( + reopen(&forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut binding_forged_commits = kernel.journal.commits.clone(); + let binding_forged = genesis_commit(&mut binding_forged_commits); + let WorldEffect::WorldCreated { resolved, .. } = &mut binding_forged.effect else { + panic!("expected genesis effect"); + }; + resolved.subjects[0].subject.label = "Not the creation subject".into(); + binding_forged.digest = commit_digest(binding_forged).unwrap(); + + assert!(matches!( + reopen(&binding_forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul falsification: the extended replay shape check is not decoration. + /// A forged state carrying a self-loop, a cost out of range, a + /// non-place endpoint, or a position on a non-place is refused by + /// `verify_state_shape`, which `WorldJournal::open` runs on the replayed head. + #[test] + fn soul_forged_topology_states_are_refused_by_the_shape_check() { + use crate::patch::{AccessKind, Cost, EdgeRecord, MAX_ROUTE_COST}; + use crate::tests::{admit_topology, auth_principal, owner}; + + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Forged Rows"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + // The honest state recovers. + assert!(verify_state_shape(&kernel.state).is_ok()); + assert!(reopen(&kernel.journal.commits).is_ok()); + + let self_loop = { + let mut state = kernel.state.clone(); + state.edges.insert( + topology.ramp, + EdgeRecord::Route { + label: "The Yard Ramp".into(), + from: topology.yard, + to: topology.yard, + access: AccessKind::Public, + cost: Cost(12), + open: true, + }, + ); + state + }; + let bad_cost = { + let mut state = kernel.state.clone(); + state + .edges + .get_mut(&topology.ramp) + .unwrap() + .set_cost(Cost(MAX_ROUTE_COST + 1)); + state + }; + let non_place_endpoint = { + let mut state = kernel.state.clone(); + state.entities.get_mut(&topology.road).unwrap().kind = + crate::EntityKind::Resource; + state + }; + let stray_position = { + let mut state = kernel.state.clone(); + state.positions.insert( + topology.walker, + Position { + place: EntityId::issue(), + }, + ); + state + }; + for forged in [self_loop, bad_cost, non_place_endpoint, stray_position] { + let error = verify_state_shape(&forged).unwrap_err(); + assert!( + matches!(error, JournalError::Corrupt(_)), + "a forged topology row recovered: {error:?}" + ); + } + } + + /// A committed levy survives a restart exactly: the snapshot, the band, the + /// lowered effects, and the re-derived authority verdict all come back, and + /// the same envelope is already applied. + #[test] + fn restart_replay_after_a_levy_is_exact() { + use crate::tests::{affordance_named, civic_world, command, owner, play_caller}; + use crate::{ + DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, + Target, + }; + + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Replayed Levy"), + &crate::tests::auth_principal(owner()), + ) + .unwrap(); + let (_, civic, active) = civic_world(&mut kernel); + let caller = play_caller(); + let envelope = command( + &active, + caller.clone(), + CommandBody::Act { + actor: civic.treasury, + invocation: DecisionInvocation { + affordance: affordance_named(&active, "levy"), + bindings: vec![ + RoleBinding { + role: Role("payer".into()), + target: Target::Subject(civic.farmer), + }, + RoleBinding { + role: Role("resource".into()), + target: Target::Entity(civic.grain), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(3)), + }], + speech: None, + display: None, + }, + }, + ); + kernel + .submit( + envelope.clone(), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let events = kernel.events(); + let event = events.last().expect("the levy event").clone(); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + let events = reopened.events(); + let replayed = events.last().expect("the replayed event"); + assert_eq!(replayed.band, event.band); + assert_eq!(replayed.effects, event.effects); + assert!(matches!( + reopened.submit(envelope, &AuthenticatedCaller::fixture(caller)), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// Soul falsification: the civic shape checks are not decoration. A forged + /// state that widens a jurisdiction, doubles an incumbency, seats an + /// institution, or empties a delegation is refused by the shape check. + #[test] + fn a_forged_authority_or_incumbency_is_corrupt() { + use crate::tests::{ + BAILIFF_OFFICE, LEVY_KIND, WARDEN_OFFICE, auth_principal, authority_kind, civic_world, + office, owner, + }; + use crate::{AuthorityGrant, AuthorityTarget, Office}; + use std::collections::BTreeSet; + + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Forged Civics"), + &auth_principal(owner()), + ) + .unwrap(); + let (topology, civic, _) = civic_world(&mut kernel); + assert!(verify_state_shape(&kernel.state).is_ok()); + assert!(reopen(&kernel.journal.commits).is_ok()); + + let widened = { + let mut state = kernel.state.clone(); + state.authority.insert( + civic.reeve, + BTreeSet::from([AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.chamber), + }]), + ); + state + }; + let dangling = { + let mut state = kernel.state.clone(); + state.authority.insert( + civic.outsider, + BTreeSet::from([AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(EntityId::issue()), + }]), + ); + state + }; + let doubled = { + let mut state = kernel.state.clone(); + state + .selection + .get_mut(&civic.treasury) + .unwrap() + .get_mut(&office(BAILIFF_OFFICE)) + .unwrap() + .incumbent = Some(civic.reeve); + state + }; + let seated_institution = { + let mut state = kernel.state.clone(); + state + .selection + .get_mut(&civic.treasury) + .unwrap() + .get_mut(&office(WARDEN_OFFICE)) + .unwrap() + .incumbent = Some(civic.treasury); + state + }; + let inert_office = { + let mut state = kernel.state.clone(); + state.selection.get_mut(&civic.treasury).unwrap().insert( + office(WARDEN_OFFICE), + Office { + incumbent: Some(civic.reeve), + delegated: BTreeSet::new(), + }, + ); + state + }; + let office_on_person = { + let mut state = kernel.state.clone(); + state + .selection + .insert(topology.walker, state.selection[&civic.treasury].clone()); + state + }; + for forged in [ + widened, + dangling, + doubled, + seated_institution, + inert_office, + office_on_person, + ] { + let error = verify_state_shape(&forged).unwrap_err(); + assert!( + matches!(error, JournalError::Corrupt(_)), + "a forged civic row recovered: {error:?}" + ); + } + } + + /// Soul falsification of the structural-overlap decision, updated for the + /// admission-time covering check: a `Subject` grant naming ground a + /// `PlaceSubtree` grant already covers is refused on arrival, but nothing + /// re-derives that check off of live position. Once the farmer walks out + /// from under the hall, the identical grant is unremarkable, and no + /// `Relocate` — in either direction — is ever asked to keep a shape + /// decision current. + #[test] + fn a_relocation_never_corrupts_a_civic_store() { + use crate::tests::{ + LEVY_KIND, auth_principal, civic_world, operations, over_subject, owner, reject_play, + submit_play, + }; + use crate::{ComponentOp, Mismatch}; + + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Moving Civics"), + &auth_principal(owner()), + ) + .unwrap(); + let (_, civic, _) = civic_world(&mut kernel); + + let admit = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + assert!(submit_play(kernel, &before, operations(ops)).resulting_revision > 0); + verify_state_shape(&kernel.state).expect("the committed store keeps its shape"); + assert!( + crate::overlapping_holder(&kernel.state).is_none(), + "a committed store never holds two overlapping jurisdictions" + ); + }; + let place_covers = |kernel: &WorldKernel| { + crate::covers( + &kernel.state, + crate::AuthorityTarget::PlaceSubtree(civic.hall), + crate::Target::Subject(civic.farmer), + ) + }; + let name_farmer = || { + vec![crate::tests::grant_to( + civic.treasury, + LEVY_KIND, + over_subject(civic.farmer), + )] + }; + + // The treasury's hall grant already covers the farmer standing in the + // chamber underneath it, so naming him directly is a second source + // for the same kind of act, and admission refuses it while he stands + // there. + assert!(place_covers(&kernel)); + let before = kernel.snapshot().unwrap(); + assert_eq!( + reject_play(&mut kernel, &before, operations(name_farmer())), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // Out of the subtree, one route at a time. + for edge in [civic.passage, civic.causeway] { + admit( + &mut kernel, + vec![ComponentOp::Relocate { + subject: Ref::Existing(civic.farmer), + via: Ref::Existing(edge), + }], + ); + } + // The move dissolved the cover without any operation naming it, which + // is why the disjointness rule cannot be occupancy-sensitive: nothing + // reruns the covering check on a `Relocate`, in or out. + assert!(!place_covers(&kernel)); + + // Now that he stands outside it, the identical grant is unremarkable. + admit(&mut kernel, name_farmer()); + assert!(kernel.state.authority[&civic.treasury].len() >= 3); + + // The whole history replays, and the reopened world is identical. + let committed = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + } +} + +#[cfg(test)] +mod custody_tests { + use super::*; + use super::tests::{last_commit, reopen}; + use crate::{ + CallerId, CommandBody, ComponentOp, DependencyRef, EntityKind, Quantity, Ref, + WorldKernel, WorldPatch, + tests::{admit_custody, admit_topology, auth_principal, command, creation, owner}, + }; + + /// Replay re-derives the custody partitions from the commit log alone: a + /// world reopened after a transfer is byte-identical, and the transfer's own + /// envelope is idempotent. + #[test] + fn restart_replay_after_a_transfer_is_exact() { + let authenticated = auth_principal(owner()); + let (mut kernel, _) = + WorldKernel::create(creation("Replay"), &authenticated) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = kernel.snapshot().unwrap(); + + let envelope = command( + &active, + CallerId::Play, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }], + evidence: Vec::new(), + }, + }, + ); + kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap(); + let accepted = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert!(matches!( + reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// Replay recomputes `reduce`, so the band and the lowered operations are + /// re-derived rather than trusted: a stored event whose band or effects the + /// seed does not reproduce fails effect equality on the way back in. + #[test] + fn restart_replay_after_an_action_is_exact() { + use crate::tests::{affordance_named, play_caller}; + use crate::{AuthenticatedCaller, Magnitude, ProposedEffect, RoleBinding, Target}; + + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(creation("ActionReplay"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = kernel.snapshot().unwrap(); + let carry = affordance_named(&active, "carry"); + let caller = play_caller(); + + let role = |name: &str, target| RoleBinding { + role: crate::Role(name.into()), + target, + }; + let envelope = command( + &active, + caller.clone(), + CommandBody::Act { + actor: custody.holder, + invocation: crate::DecisionInvocation { + affordance: carry, + bindings: vec![ + role("from", Target::Subject(custody.holder)), + role("recipient", Target::Subject(custody.counterparty)), + role("place", Target::Entity(topology.yard)), + role("resource", Target::Entity(custody.tithe)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }], + speech: None, + display: None, + }, + }, + ); + let authenticated_controller = AuthenticatedCaller::fixture(caller); + kernel + .submit(envelope.clone(), &authenticated_controller) + .unwrap(); + let accepted = kernel.snapshot().unwrap(); + let committed = kernel + .events() + .last() + .expect("the committed event") + .clone(); + assert!(!committed.effects.is_empty()); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!( + reopened.events().last().expect("the replayed event"), + &committed + ); + assert!(matches!( + reopened.submit(envelope, &authenticated_controller), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// The title clause of the shape check refuses an empty title and a + /// noncanonical one, each on its own. + #[test] + fn a_forged_empty_or_padded_title_is_corrupt() { + use crate::tests::{auth_principal, creation, owner}; + + let (kernel, _) = WorldKernel::create(creation("Titled"), + &auth_principal(owner()), + ) + .unwrap(); + verify_state_shape(&kernel.state).expect("a canonical title passes"); + for title in ["", " ", " Titled", "Titled "] { + let mut forged = kernel.state.clone(); + forged.header.get_mut().title = title.into(); + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "title {title:?} passed the shape check" + ); + } + } + + /// A grant row is a verb list for a live subject: each clause of the shape + /// check is pinned on `verify_state_shape` directly, one forged state per + /// clause, so deleting any one of them fails a case. + #[test] + fn a_malformed_grant_row_is_corrupt() { + use crate::tests::{auth_principal, creation, owner}; + use crate::{AffordanceId, SubjectId}; + + let (kernel, _) = WorldKernel::create(creation("GrantRows"), + &auth_principal(owner()), + ) + .unwrap(); + verify_state_shape(&kernel.state).expect("a fresh world has canonical grant rows"); + let held = *kernel.state.affordance_grants.keys().next().unwrap(); + + let corrupt = |name: &str, forge: &dyn Fn(&mut WorldState)| { + let mut forged = kernel.state.clone(); + forge(&mut forged); + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "{name} passed the shape check" + ); + }; + corrupt("a grant row for a retired subject", &|state| { + state.subjects.get_mut(&held).unwrap().retired = true; + }); + corrupt("an empty grant row", &|state| { + state.affordance_grants.get_mut(&held).unwrap().clear(); + }); + corrupt("a grant row for no subject", &|state| { + let verbs = state.affordance_grants[&held].clone(); + state.affordance_grants.insert(SubjectId::issue(), verbs); + }); + corrupt("a grant row naming an uncataloged verb", &|state| { + state + .affordance_grants + .get_mut(&held) + .unwrap() + .insert(AffordanceId::issue()); + }); + } + + /// A chain holding `Acted` commits recovers and verifies on reopen. + #[test] + fn an_acted_chain_reopens() { + use crate::tests::{ + act, auth_principal, creation, first_grant, owner, speak, + }; + + let (mut kernel, _) = WorldKernel::create(creation("ActedChain"), + &auth_principal(owner()), + ) + .unwrap(); + let active = kernel.snapshot().unwrap(); + let actor = *active.subjects.first().map(|subject| &subject.id).unwrap(); + act( + &mut kernel, + actor, + speak(first_grant(&active, actor), "The chain holds."), + ) + .unwrap(); + act( + &mut kernel, + actor, + speak(first_grant(&active, actor), "And again."), + ) + .unwrap(); + let accepted = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).expect("the acted chain recovers"); + assert_eq!(reopened.snapshot().unwrap(), accepted); + verify_state_shape(&reopened.state).expect("an honest event passes the shape check"); + } + + /// Absence is zero and one slot holds one pair, so a stored zero, an empty + /// holder, and a holding on something that is not a resource are each + /// corrupt at replay. + /// + /// Deviation from the spec's wording, decided here: the assertion is against + /// `verify_state_shape`, which owns these clauses. Routing through + /// `verify_history` would also fail on replay-equality, so it would pass + /// even if the shape clauses were deleted — which is the opposite of a + /// falsification. + #[test] + fn a_zero_or_dangling_holding_is_corrupt() { + let authenticated = auth_principal(owner()); + let (mut kernel, _) = + WorldKernel::create(creation("Shape"), &authenticated) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape"); + + let mut zero = kernel.state.clone(); + zero.holdings + .get_mut(&custody.holder) + .unwrap() + .insert(custody.tithe, Quantity(0)); + assert!(matches!( + verify_state_shape(&zero), + Err(JournalError::Corrupt(_)) + )); + + let mut emptied = kernel.state.clone(); + emptied.holdings.get_mut(&custody.holder).unwrap().clear(); + assert!(matches!( + verify_state_shape(&emptied), + Err(JournalError::Corrupt(_)) + )); + + let mut not_a_resource = kernel.state.clone(); + assert_eq!( + not_a_resource.entities[&topology.yard].kind, + EntityKind::Place + ); + not_a_resource + .holdings + .get_mut(&custody.holder) + .unwrap() + .insert(topology.yard, Quantity(1)); + assert!(matches!( + verify_state_shape(¬_a_resource), + Err(JournalError::Corrupt(_)) + )); + + let mut dangling = kernel.state.clone(); + dangling.dependencies.insert( + custody.holder, + BTreeSet::from([crate::DependencyTarget::Subject(custody.holder)]), + ); + assert!(matches!( + verify_state_shape(&dangling), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul: replay is exact after *every* custody and dependency operation, not + /// only after a transfer. The reopened world is byte-identical, the last + /// envelope is idempotent, and the whole chain still verifies. + #[test] + fn soul_replay_is_exact_after_every_custody_operation() { + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(creation("EveryOperation"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + // `Admit` and its evidence are Draft-only, so the opening balance is + // already on the log before activation. + let custody = admit_custody(&mut kernel, &topology); + let active = kernel.snapshot().unwrap(); + + let envelope = command( + &active, + CallerId::Play, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(2), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }, + ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Route(Ref::Existing(topology.shutter)), + }, + ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Subject(Ref::Existing(custody.counterparty)), + }, + ], + evidence: Vec::new(), + }, + }, + ); + kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap(); + let accepted = kernel.snapshot().unwrap(); + let holdings = kernel.state.holdings.clone(); + let dependencies = kernel.state.dependencies.clone(); + let digest = kernel.state.state_digest.clone(); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!(reopened.state.holdings, holdings); + assert_eq!(reopened.state.dependencies, dependencies); + assert_eq!(reopened.state.state_digest, digest); + assert!(matches!( + reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// Soul: a dependency naming a target of the wrong kind, or no canonical + /// target at all, is refused at replay. The shape clauses carry the + /// referential integrity the operation arm enforces at admission. + #[test] + fn soul_a_dependency_on_an_absent_or_wrong_kind_target_is_corrupt() { + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(creation("DependencyShape"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape"); + + // A place is not a resource, so a resource dependency naming one dangles. + let mut wrong_kind = kernel.state.clone(); + wrong_kind.dependencies.insert( + custody.holder, + BTreeSet::from([crate::DependencyTarget::Resource(topology.yard)]), + ); + assert!(matches!( + verify_state_shape(&wrong_kind), + Err(JournalError::Corrupt(_)) + )); + + // An empty target set is the second representation of nothing, and there + // is only supposed to be one. + let mut emptied = kernel.state.clone(); + emptied.dependencies.insert(custody.holder, BTreeSet::new()); + assert!(matches!( + verify_state_shape(&emptied), + Err(JournalError::Corrupt(_)) + )); + + // A holder key that names no canonical subject. + let mut orphan = kernel.state.clone(); + let absent = *orphan.subjects.keys().next().unwrap(); + orphan.dependencies.insert( + absent, + BTreeSet::from([crate::DependencyTarget::Resource(custody.tithe)]), + ); + orphan.subjects.remove(&absent); + assert!(matches!( + verify_state_shape(&orphan), + Err(JournalError::Corrupt(_)) + )); + } + + /// A world with one routine, one past-due goal, and a commit chain that + /// reaches them: the fixture the two clock-forgery checks below need. + fn ticking_world() -> (WorldKernel, super::super::SubjectId) { + use crate::tests::{auth_principal, command, operations, owner}; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, CommitmentKind, ComponentOp, + FictionalMinutes, Ref, TickMinutes, + }; + + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + crate::tests::creation("Ticking"), + &authenticated, + ) + .unwrap(); + let active = kernel.snapshot().unwrap(); + let subject = active.subjects.first().expect("a seeded subject").id; + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + CallerId::Play, + operations(vec![ + ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(10), + period: Some(TickMinutes::new(10).unwrap()), + checks: Vec::new(), + statement: crate::Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(20), + period: None, + checks: Vec::new(), + statement: crate::Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ]), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap(); + + let caller = CallerId::Play; + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + caller.clone(), + CommandBody::AdvanceTime { + minutes: TickMinutes::new(30).unwrap(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + (kernel, subject) + } + + /// Soul falsification: the replay gate and the `apply_effect` gate are two + /// independent re-derivations. This one exercises the replay side over a + /// motion that actually moved commitments and pressure — a rewritten + /// magnitude, a rewritten roll, and a fabricated row each stop replaying. + #[test] + fn soul_a_forged_tick_motion_does_not_replay() { + use crate::{FictionalMinutes, PressureMagnitude, PressureSource}; + + let (kernel, subject) = ticking_world(); + let WorldEffect::TimeAdvanced { motion, .. } = &kernel + .journal + .commits + .iter() + .max_by_key(|commit| commit.resulting_revision) + .expect("the tick's commit") + .effect + else { + panic!("expected a time-advanced effect"); + }; + assert!(!motion.fulfilled.is_empty(), "the routine rolled"); + assert!(!motion.pressed.is_empty(), "the past-due goal pressed"); + + let forge = |rewrite: fn(&mut crate::Motion)| { + let mut forged_commits = kernel.journal.commits.clone(); + let forged = last_commit(&mut forged_commits); + let WorldEffect::TimeAdvanced { motion, .. } = &mut forged.effect else { + panic!("expected a time-advanced effect"); + }; + rewrite(motion); + forged.digest = commit_digest(forged).unwrap(); + reopen(&forged_commits) + }; + + let rewrites: [fn(&mut crate::Motion); 4] = [ + // A magnitude the tick never wrote. + |motion| motion.pressed[0].magnitude = PressureMagnitude(42), + // A roll to a date the period does not reach. + |motion| motion.fulfilled[0].next_due = FictionalMinutes(9_999), + // A row for a source nothing derived. + |motion| { + let mut row = motion.pressed[0].clone(); + row.source = PressureSource::Subject(row.target); + motion.pressed.push(row); + }, + // A fulfilment dropped on the floor. + |motion| motion.fulfilled.clear(), + ]; + for rewrite in rewrites { + assert!( + matches!(forge(rewrite), Err(JournalError::Corrupt(_))), + "a forged motion replayed" + ); + } + let _ = subject; + } + + /// A commitment that is not a Routine and carries a check is not canonical: + /// nothing would ever evaluate the check. The check is a live one, taken + /// from a Routine, so no other clause can be what refuses it; the control + /// is the honest world. + #[test] + fn a_non_routine_commitment_carrying_a_check_is_corrupt() { + let (kernel, _, _) = crate::clock_tests::clock_kernel("Checks"); + verify_state_shape(&kernel.state).expect("the honest world is canonical"); + let check = kernel + .state + .commitments + .values() + .flat_map(|held| held.values()) + .find_map(|commitment| commitment.checks.first().cloned()) + .expect("the clock bench's routine carries a check"); + let (subject, key) = kernel + .state + .commitments + .iter() + .flat_map(|(subject, held)| held.iter().map(move |(key, c)| (*subject, *key, c))) + .find(|(_, _, commitment)| commitment.kind != crate::CommitmentKind::Routine) + .map(|(subject, key, _)| (subject, key)) + .expect("the clock bench holds an obligation or a goal"); + + let mut forged = kernel.state.clone(); + forged + .commitments + .get_mut(&subject) + .unwrap() + .get_mut(&key) + .unwrap() + .checks = vec![check]; + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "a non-routine commitment with a check was admitted" + ); + } + + /// `TickMinutes` owns its bound at decode, so a span outside + /// `1..=MAX_ROUTE_COST` cannot be read in any position: a routine's period, + /// a command, or a tick's own effect. + #[test] + fn a_span_outside_the_bound_cannot_be_decoded() { + for minutes in [0u32, crate::patch::MAX_ROUTE_COST + 1, u32::MAX] { + let raw = rmp_serde::to_vec(&minutes).unwrap(); + assert!( + rmp_serde::from_slice::(&raw).is_err(), + "{minutes} decoded as a span" + ); + assert!(serde_json::from_value::(minutes.into()).is_err()); + } + for minutes in [1u32, crate::patch::MAX_ROUTE_COST] { + let raw = rmp_serde::to_vec(&minutes).unwrap(); + assert_eq!( + rmp_serde::from_slice::(&raw).unwrap().minutes(), + minutes + ); + } + } + +} diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs new file mode 100644 index 000000000..892a8e34f --- /dev/null +++ b/native/aetherlight/src/lib.rs @@ -0,0 +1,12840 @@ +//! The Aetherlight world library, a fork of Ghostlight c43eb54 (see `PROVENANCE.md`). +//! +//! The world owner is one deterministic authority: authenticated commands enter, +//! one reducer decides, and the journal, an in-memory list of commits, records +//! each result. The journal exports as bytes, and opening those bytes replays +//! the chain from genesis: the head state is whatever the replay derives. +//! The fork keeps only that single-threaded kernel: no async runtime, no network, no +//! model controllers and no ports. A decision arrives as an invocation the caller +//! built, a player or a brain; nothing in this crate composes one. +//! +//! The crate has no entry point yet: the ABI that creates, opens and drives a +//! world arrives in AL4. Until then the kernel itself is sealed: there is no +//! mutable state, no canonical ID allocator, no reducer entry, no journal writer, +//! and no authenticated-caller constructor on the public surface, under every +//! configuration. This crate declares no cargo features, so no build can lift +//! the seal. +//! +//! The negative proofs are doc-tests, which compile as an external crate and so +//! stand exactly where a consumer stands. Stable rustdoc does not check the error +//! code of a `compile_fail` test, so none is claimed: each test passes only +//! because its item is not public, and fails once the item is made public. +//! +//! ```compile_fail +//! use aetherlight::WorldKernel; +//! ``` +//! +//! ```compile_fail +//! use aetherlight::reduce; +//! ``` +//! +//! ```compile_fail +//! use aetherlight::WorldState; +//! ``` +//! +//! ```compile_fail +//! use aetherlight::CommandEnvelope; +//! ``` +//! +//! ```compile_fail +//! use aetherlight::AuthenticatedCaller; +//! ``` +//! +//! ```compile_fail +//! use aetherlight::journal::WorldJournal; +//! ``` +//! +//! ```compile_fail +//! let _ = aetherlight::SubjectId::issue(); +//! ``` +//! +//! ```compile_fail +//! use aetherlight::DecisionEvent; +//! ``` + +// The kernel has no entry point until AL4 adds the ABI, so most of it is unreachable +// from the public surface. AL4 removes this attribute. +#![allow(dead_code)] + +mod action; +mod clock; +mod digest; +mod docs; +#[cfg(test)] +mod golden_tests; +mod grammar; +#[cfg(test)] +mod import_key_tests; +mod journal; +mod patch; +mod views; + +pub(crate) use action::ActionMismatch; +pub(crate) use clock::Motion; +pub use clock::{FictionalMinutes, TickMinutes}; +pub use grammar::{ + GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb, + RenderPath, +}; +pub use patch::{ + CommitmentKey, DraftHandle, Mismatch, Ref, RefKind, RefName, Role, Site, Statement, WorldPatch, +}; +pub(crate) use patch::{ + AccessKind, Affordance, Audience, AuthoredSource, AuthorityGrant, AuthorityTarget, + BoundPrecondition, ChannelRecord, Commitment, CommitmentKind, Confidence, Cost, + DependencyTarget, EntityKind, EvidenceRef, FactRecord, + FactStanding, Forum, GrievanceKindName, Knowledge, KnowledgeSource, Office, OfficeName, + Position, PressureMagnitude, PressureSource, Quantity, Reach, +}; +pub use patch::ImportKey; +#[cfg(test)] +pub(crate) use patch::{Bounds, Declaration, EntityDeclaration, SubjectDeclaration}; +#[cfg(test)] +use patch::{ + AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp, + DependencyRef, FactDeclaration, FactStandingRef, ReachRef, RouteDeclaration, +}; +#[cfg(test)] +pub(crate) use patch::{ + AuthorityGrantRef, AuthorityKindName, AuthorityTargetRef, ComponentOpKind, + EffectSlot, OutcomeBand, Precondition, RoleSpec, +}; +use patch::{ + AffordanceKindName, EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch, +}; + +use digest::{LtHash16, Partition}; +use docs::{Changed, DocKey, Docs, Tracked}; +use views::Views; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use thiserror::Error; +use uuid::Uuid; + +pub const STATE_SCHEMA: &str = "aetherlight.world_state.v2"; +pub(crate) const COMMIT_SCHEMA: &str = "aetherlight.world_commit.v2"; + +/// Domain strings of the three content-derived identities. A command is named +/// by what it says, so no caller draws an id and no retry needs one. +const COMMAND_DOMAIN: &[u8] = b"aetherlight.command.v1"; +const CREATE_DOMAIN: &[u8] = b"aetherlight.create.v1"; +const WORLD_DOMAIN: &[u8] = b"aetherlight.world.v1"; + +/// The first 16 bytes of a digest as a `Uuid`, as `patch::derive_id` truncates. +fn truncated_uuid(hasher: Sha256) -> Uuid { + let mut bytes = [0u8; 16]; + bytes.copy_from_slice(&hasher.finalize()[..16]); + Uuid::from_bytes(bytes) +} + +/// The visibility argument is the whole boundary decision for an ID type: the +/// ones a consumer names by value are `pub`, the rest stay `pub(crate)`, and no +/// `issue()` impl is emitted here at all — issuance is private in every case. +macro_rules! opaque_uuid { + ($name:ident, $vis:vis) => { + #[derive( + Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, + )] + #[serde(transparent)] + $vis struct $name(Uuid); + + impl DocKey for $name { + fn key_text(&self) -> String { + self.0.to_string() + } + } + }; + ($name:ident) => { + opaque_uuid!($name, pub(crate)); + }; +} + +opaque_uuid!(WorldId, pub); +opaque_uuid!(CommandId, pub); +opaque_uuid!(SubjectId, pub); +opaque_uuid!(EntityId, pub); +opaque_uuid!(EdgeId, pub); +opaque_uuid!(AffordanceId, pub); +opaque_uuid!(EventId); + +impl CommandId { + fn key(self) -> String { + self.0.to_string() + } + + /// A named random id for tests that need a command id and no command. + #[cfg(test)] + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +impl WorldId { + /// Canonical text, for the key derivations that hash a world identity. + pub(crate) fn text(self) -> String { + self.0.to_string() + } + + /// A named zero for tests that need a world identity and no world. + #[cfg(test)] + pub(crate) fn nil_for_test() -> Self { + Self(Uuid::nil()) + } + + /// The world is named by the creation that made it. + fn of(creation: CommandId) -> Self { + let mut hasher = Sha256::new(); + hasher.update(WORLD_DOMAIN); + hasher.update(creation.0.as_bytes()); + Self(truncated_uuid(hasher)) + } + + fn key(self) -> String { + self.0.to_string() + } +} + +// Subject, entity, controller, and affordance IDs are derived, never drawn. +// `patch::derive_id` is the only allocator, and it is called from exactly two +// sites: `patch::resolve_patch` and `action::exercise`. The action lane mints +// exactly one referent per invocation — always an `EntityKind::Fact`, always +// `Claimed` by the acting subject, never caller-named, never any other kind. +// These fixtures exist so tests can name an ID that no partition holds. +#[cfg(test)] +impl SubjectId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +#[cfg(test)] +impl EntityId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +#[cfg(test)] +impl AffordanceId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +impl EventId { + fn for_command(command_id: CommandId) -> Self { + Self(command_id.0) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct PrincipalId(String); + +impl PrincipalId { + pub fn new(value: impl Into) -> Self { + Self(value.into()) + } +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum SubjectKind { + Person, + Institution, + Population, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct CreateWorld { + owner: PrincipalId, + title: String, + patch: WorldPatch, + /// The grammar the world is bound to for its whole life, or none for an + /// open-catalog world. Authored here and nowhere else: genesis installs it. + #[serde(default, skip_serializing_if = "Option::is_none")] + grammar: Option, +} + +impl CreateWorld { + /// The creation is named by its own bytes: equal creations are one command. + /// Host contract: two byte-equal creations share a `WorldId` and every id + /// derived under it, so a host that wants distinct worlds salts each run or + /// profile into the creation (for example a run seed in the patch). + fn id(&self) -> CommandId { + let mut hasher = Sha256::new(); + hasher.update(CREATE_DOMAIN); + hasher.update(rmp_serde::to_vec_named(self).expect("a creation command serializes")); + CommandId(truncated_uuid(hasher)) + } +} + +/// Who wrote a command. The owner principal authors genesis and nothing after +/// it; after genesis `Play` is the only caller any command body admits. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", content = "id", rename_all = "snake_case")] +enum CallerId { + Principal(PrincipalId), + /// The play table, minted only by `PlayPort`. + Play, +} + +#[derive(Clone, Debug)] +struct AuthenticatedCaller { + caller: CallerId, +} + +impl AuthenticatedCaller { + fn verified_principal(principal: PrincipalId) -> Self { + Self { + caller: CallerId::Principal(principal), + } + } + + /// Visible only inside the `world` subtree. Runtime ingress cannot reach it. + fn verified_play() -> Self { + Self { + caller: CallerId::Play, + } + } + + #[cfg(test)] + fn fixture(caller: CallerId) -> Self { + Self { caller } + } +} + +/// The referent a role is bound to. Canonical IDs only: an invocation happens +/// in Active, where no declaration exists, so a draft reference is +/// unrepresentable here and the action lane runs no draft resolution. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "id", rename_all = "snake_case")] +pub(crate) enum Target { + Subject(SubjectId), + Entity(EntityId), + Edge(EdgeId), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct RoleBinding { + pub(crate) role: Role, + pub(crate) target: Target, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "magnitude", content = "value", rename_all = "snake_case")] +pub(crate) enum Magnitude { + None, + Quantity(Quantity), + Cost(Cost), +} + +/// One proposal against one effect slot. It carries no referents: they all come +/// from the slot's roles resolved through the invocation's bindings, so an +/// invocation cannot name a target its affordance declared no role for and the +/// ceiling check is a comparison rather than a graph walk. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ProposedEffect { + pub(crate) slot: usize, + pub(crate) magnitude: Magnitude, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct DecisionInvocation { + pub affordance: AffordanceId, + pub bindings: Vec, + /// Exactly one entry per slot in the entry, in any order. + pub proposed: Vec, + /// Command input, and the only place an utterance's text enters the kernel. + /// The committed home of those bytes is `facts[fact].statement`. + pub speech: Option, + /// A visible act in the actor's own words, and the only place it enters + /// the kernel. It accompanies any invocation: a body is visible whatever + /// it is doing. Its audience is the actor's place, never the entry's. + pub display: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct CommandEnvelope { + world_id: WorldId, + expected_revision: u64, + caller: CallerId, + body: CommandBody, +} + +impl CommandEnvelope { + /// A command is named by the world, revision, caller and body it carries. + /// The revision is in the preimage so the same body at two revisions is + /// two commands, and every id derived from it is distinct. + fn id(&self) -> CommandId { + let mut hasher = Sha256::new(); + hasher.update(COMMAND_DOMAIN); + hasher.update(self.world_id.0.as_bytes()); + hasher.update(self.expected_revision.to_be_bytes()); + hasher.update(rmp_serde::to_vec_named(&self.caller).expect("a caller serializes")); + hasher.update(rmp_serde::to_vec_named(&self.body).expect("a command body serializes")); + CommandId(truncated_uuid(hasher)) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum CommandBody { + /// One subject's act. Play's alone: the actor's grants decide whether the + /// affordance is its to use. + Act { + actor: SubjectId, + invocation: DecisionInvocation, + }, + /// A patch to the world. Play's alone. + AdmitPatch { + patch: WorldPatch, + }, + /// The world's only clock advance. Play's alone. + AdvanceTime { + minutes: TickMinutes, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct SubjectState { + label: String, + kind: SubjectKind, + /// Written only when a subject declaration is resolved; absent from a + /// subject nobody imported, so its digests are unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + import_key: Option, + /// Set once by `Retire`; the one place retirement is stored. A live + /// subject's row serializes without it. + #[serde(default, skip_serializing_if = "is_false")] + retired: bool, +} + +fn is_false(value: &bool) -> bool { + !*value +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(crate) struct DecisionEvent { + pub(crate) id: EventId, + pub(crate) revision: u64, + pub(crate) actor: SubjectId, + /// The entry exercised. The invocation itself lives on the effect: the + /// invocation is what the caller said, the event is what the world recorded. + pub(crate) affordance: AffordanceId, + /// The claim this act asserted, if it carried speech. Never the text: the + /// event is the world's record and every reader reads it, so it carries the + /// fact id and the statement lives in `facts` alone. + pub(crate) speech: Option, + /// The claim this act displayed, if it carried a visible act. Same rule. + pub(crate) display: Option, + /// Index into the entry's `outcome_bands`. Re-derived and compared at apply + /// and at replay, never trusted. + pub(crate) band: usize, + /// The selected band's slots, lowered through the invocation's bindings. + /// Empty when the selected band names no effects. + pub(crate) effects: Vec, +} + +/// The world's own fields: the one document that is not a map row. Tracked like +/// a partition key, so a tick that advances the clock is one changed document. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +struct WorldHeader { + world_id: WorldId, + owner: PrincipalId, + title: String, + /// Bound by genesis and never written again; absent from a world with no + /// grammar, so such a world's state and digests are what they were before + /// grammars existed. + #[serde(skip_serializing_if = "Option::is_none")] + grammar: Option, + /// Minutes since genesis. The world's only clock, advanced by exactly one + /// command body and read by no wall clock. It is world truth, and it is + /// read by no precondition. + now: FictionalMinutes, +} + +/// The world's partitions, declared once. Each row names a partition, its +/// key and value types and the schema its documents are digested with; the +/// struct, the table `begin`, `folded`, `finish`, `rollback` and the test +/// oracle walk, and the empty world are all generated from these rows, so a +/// partition is in the digest and under the undo log because it exists, and +/// there is no second list to forget it from. +/// +/// Every partition is a `Docs`: reads see the map, every write is logged, and +/// `submit` applies in place and either finishes or rolls the log back. A row +/// may name a [`docs::Projection`] as a third type: that partition then keeps a +/// read index, and the projections sit just above this macro. +macro_rules! world_state { + ($($(#[$meta:meta])* $field:ident: Docs<$key:ty, $value:ty $(, $proj:ty)?> = $schema:literal;)*) => { + #[derive(Clone, Debug, PartialEq, Eq)] + struct WorldState { + header: Tracked, + revision: u64, + $($(#[$meta])* $field: Docs<$key, $value $(, $proj)?>,)* + /// Derived from the partitions at every `finish`: outside every + /// document, so neither digested nor encoded, and equal whatever + /// it holds (see `views`). + views: Views, + // The chain head: outside every document. + accumulator: LtHash16, + state_digest: String, + last_commit_digest: Option, + } + + impl WorldState { + /// The number of partitions. + const PARTITIONS: usize = [$($schema),*].len(); + + /// Every partition under the schema its documents are digested with. + fn partitions(&self) -> [(&'static str, &dyn Partition); Self::PARTITIONS] { + [$(($schema, &self.$field as &dyn Partition)),*] + } + + fn partitions_mut(&mut self) -> [(&'static str, &mut dyn Partition); Self::PARTITIONS] { + [$(($schema, &mut self.$field as &mut dyn Partition)),*] + } + + /// A world with this header, revision 0 and no documents. + fn with_header(header: Tracked) -> Self { + Self { + header, + revision: 0, + $($field: Docs::default(),)* + views: Views::default(), + accumulator: LtHash16::default(), + state_digest: String::new(), + last_commit_digest: None, + } + } + } + }; +} + +/// The read indexes. Each is a pure function of one document's value, held by +/// its partition's `Docs` and read only through `Docs::indexed`; none is state +/// of its own, so none is digested or encoded. +/// +/// `ChildOf`: the places directly inside a place. +#[derive(Clone, Debug)] +struct ChildOf; + +impl docs::Projection for ChildOf { + type Point = EntityId; + fn points(value: &EntityRecord, out: &mut Vec) { + out.extend(value.container); + } +} + +/// `StandsAt`: who stands in a place. A position holds only its place, so two +/// positions are equal exactly when their places are. +#[derive(Clone, Debug)] +struct StandsAt; + +impl docs::Projection for StandsAt { + type Point = EntityId; + fn points(value: &Position, out: &mut Vec) { + out.push(value.place); + } +} + +/// `DependsOn`: who depends on a target. `Views` reads it to re-judge the +/// dependents of a route or a placement that changed. +#[derive(Clone, Debug)] +struct DependsOn; + +impl docs::Projection> for DependsOn { + type Point = DependencyTarget; + fn points(value: &BTreeSet, out: &mut Vec) { + out.extend(value.iter().copied()); + } +} + +/// `BySource`: which pressure sources press on a subject. +#[derive(Clone, Debug)] +struct BySource; + +impl docs::Projection> for BySource { + type Point = PressureSource; + fn points( + value: &BTreeMap, + out: &mut Vec, + ) { + out.extend(value.keys().copied()); + } +} + +/// `ByEndpoint`: the routes touching a place, at either end. +#[derive(Clone, Debug)] +struct ByEndpoint; + +impl docs::Projection for ByEndpoint { + type Point = EntityId; + fn points(value: &EdgeRecord, out: &mut Vec) { + let (from, to) = value.endpoints(); + out.push(from); + if to != from { + out.push(to); + } + } +} + +/// `ByController`: the channels a subject controls. +#[derive(Clone, Debug)] +struct ByController; + +impl docs::Projection for ByController { + type Point = SubjectId; + fn points(value: &ChannelRecord, out: &mut Vec) { + out.extend(value.controller); + } +} + +/// `ByIncumbent`: the institutions in which a subject holds an office. +#[derive(Clone, Debug)] +struct ByIncumbent; + +impl docs::Projection> for ByIncumbent { + type Point = SubjectId; + fn points(value: &BTreeMap, out: &mut Vec) { + let first = out.len(); + out.extend(value.values().filter_map(|office| office.incumbent)); + out[first..].sort(); + out.dedup(); + } +} + +/// `ByImportKey`: the subject that holds an import key. Retired subjects keep +/// theirs, so a key is never reissued. +#[derive(Clone, Debug)] +struct ByImportKey; + +impl docs::Projection for ByImportKey { + type Point = ImportKey; + fn points(value: &SubjectState, out: &mut Vec) { + out.extend(value.import_key.clone()); + } +} + +/// `ByKind`: the catalog entry that names an affordance kind, so a kind is +/// taken exactly when a point holds an entry. +#[derive(Clone, Debug)] +struct ByKind; + +impl docs::Projection for ByKind { + type Point = AffordanceKindName; + fn points(value: &Affordance, out: &mut Vec) { + out.push(value.kind.clone()); + } +} + +world_state! { + subjects: Docs = "aetherlight.subject.v1"; + entities: Docs = "aetherlight.entity.v1"; + edges: Docs = "aetherlight.edge.v1"; + positions: Docs = "aetherlight.position.v1"; + /// What each subject holds. Absence is zero at both levels: no stored + /// `Quantity(0)` and no empty inner map, so a duplicate holding is + /// unrepresentable and "nothing" has one shape. + holdings: Docs> = "aetherlight.holdings.v1"; + /// What each subject depends on. Never empty for a present key. + dependencies: Docs, DependsOn> = "aetherlight.dependencies.v1"; + /// One row per `EntityKind::Fact` entity, and no orphan either way. Facts + /// are write-once: declaration and `AssertClaim` are the only writers, and + /// standing never changes after admission. + facts: Docs = "aetherlight.fact.v1"; + /// One row per `EntityKind::Channel` entity, and no orphan either way. + channels: Docs = "aetherlight.channel.v1"; + /// What each subject knows. The sole owner of who-heard-what: `events` + /// records what was done, and this decides what a subject may act on and + /// what its projection may contain. One document per (subject, fact), and + /// absence is "knows nothing of it" — forgetting removes the key. + knowledge: Docs<(SubjectId, EntityId), Knowledge> = "aetherlight.knowledge.v1"; + /// What ground each subject has jurisdiction over, and under which + /// world-declared kind. Never empty for a present key. No subject holds two + /// grants of one kind over overlapping ground, so nothing ever arbitrates + /// between two sources of one permission. + authority: Docs> = "aetherlight.authority.v1"; + /// The offices each institution constitutes, and who sits in them. An + /// incumbent never acts as its institution: an office answers what its + /// incumbent has jurisdiction over, not who the actor is. + selection: Docs, ByIncumbent> = "aetherlight.selection.v1"; + /// Where each kind of grievance goes, and who may bring it. Keyed by + /// neither a subject nor a referent, so it enters no scope components and + /// is admission-only state. + redress: Docs = "aetherlight.redress.v1"; + /// What each subject has promised. Never empty for a present key. + commitments: Docs> = "aetherlight.commitments.v1"; + /// Pressure *on* each subject, keyed target-major then source. Never empty + /// for a present key; no stored zero magnitude. Lived meaning: read by + /// projection and by nothing that decides. + pressures: Docs, BySource> = "aetherlight.pressures.v1"; + /// What an affordance *is*. World-authored and written by `admit_resolved` + /// alone. + affordance_catalog: Docs = "aetherlight.affordance.v1"; + /// Who may exercise which entry: a row exists if and only if the subject + /// holds at least one verb. A grant carries no payload, so a duplicate + /// grant is unrepresentable rather than checked. + affordance_grants: Docs> = "aetherlight.affordance_grants.v1"; +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +enum WorldEffect { + WorldCreated { + owner: PrincipalId, + title: String, + resolved: ResolvedPatch, + }, + PatchAdmitted { + resolved: ResolvedPatch, + }, + Acted { + /// The command's own input, kept beside the event rather than inside it: + /// the invocation is what the caller said, the event is what the world + /// recorded, and only the first carries text. + invocation: DecisionInvocation, + event: DecisionEvent, + }, + /// The first effect that mutates state for subjects other than one scope. + /// Play's alone, and `apply_effect` + /// re-derives the whole motion, so a forged fulfilment, magnitude, row, or + /// target is one comparison rather than a clause apiece. + TimeAdvanced { + minutes: TickMinutes, + to: FictionalMinutes, + motion: Motion, + }, +} + +/// The exact raw command admitted by the kernel. This is the sole +/// persistent command authority: IDs, callers, and effects are +/// derived from this value rather than copied into independently forgeable +/// commit fields. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", content = "command", rename_all = "snake_case")] +enum CommittedCommand { + CreateWorld(CreateWorld), + WorldCommand(CommandEnvelope), +} + +impl CommittedCommand { + fn id(&self) -> CommandId { + match self { + Self::CreateWorld(command) => command.id(), + Self::WorldCommand(command) => command.id(), + } + } + + fn caller(&self) -> CallerId { + match self { + Self::CreateWorld(command) => CallerId::Principal(command.owner.clone()), + Self::WorldCommand(command) => command.caller.clone(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct WorldCommit { + schema: String, + world_id: WorldId, + command: CommittedCommand, + previous_revision: Option, + resulting_revision: u64, + previous_state_digest: Option, + resulting_state_digest: String, + previous_commit_digest: Option, + effect: WorldEffect, + digest: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SubjectSnapshot { + pub id: SubjectId, + pub label: String, + pub kind: SubjectKind, + /// The Aetheria record this subject was imported from, if it was. + pub import_key: Option, + pub affordances: BTreeSet, + pub(crate) position: Option, + /// Set for a subject `Retire` ended: no grants, no position, no + /// audience, its history kept. The agent's view and the surface read this + /// rather than inferring retirement from an absent position, which a + /// merely unplaced live subject also has. + pub retired: bool, + /// Exactly what a verification reads for this subject, carried whole + /// rather than lowered into projections that then have to be diffed back + /// together: its own position, incident routes, holdings, dependencies, + /// grants, delegated offices, known fact keys, controlled channels, and + /// commitments. A counterparty's components never enter. The narrative lane + /// persists this as the "before" an interruption is measured against. + pub(crate) components: ScopeComponents, + pub(crate) offices_held: Vec, + /// View-only, and covered by no digest: an institution's own offices, so + /// its controller can see what it lends and to whom. No precondition reads + /// it, and installing a warden therefore does not reject the institution's + /// in-flight proposals — what an institution lends is not what it may do. + pub(crate) offices_granted: Vec, + /// View-only: the forums whose standing covers this subject, through the + /// same covering predicate `HasStanding` uses. + pub(crate) redress: Vec, + /// Every fact this subject holds, with the statement resolved. The sole + /// perception surface: a subject perceives a speech act if and only if it + /// holds `Knowledge` of that act's fact. Ordered by `minted_at` then `fact`. + pub(crate) knowledge: Vec, + /// Digest-bound, lowered from the one `scope_components` call `snapshot` + /// already makes, so view and digest cannot drift. Carries `past_due`, + /// which the components do not. + pub(crate) commitments: Vec, + /// Pressure on self. View-only: read by no precondition, so covered by no + /// digest. Pressure this subject *sources* is excluded — it is another + /// subject's state, and the actor already sees the commitment that produced + /// it. + pub(crate) pressures: Vec, + /// This subject's own dependencies, lowered from `components.dependencies` + /// (private to this module) so the play table's omniscient view can print + /// what a `release` may name without reaching into `ScopeComponents` + /// itself. View-only: it is already carried by `components`. + pub(crate) dependencies: Vec, + /// The greatest `DecisionEvent.revision` whose actor is this subject, or + /// `None` if the subject never acted. Derived from the journal's acted events alone: + /// no new state, no schema change. The recency marker `projector_knowledge` + /// stamps onto each knowledge row is `acquired_at > last_acted_at`. + pub(crate) last_acted_at: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct CommitmentSnapshot { + pub(crate) key: CommitmentKey, + pub(crate) kind: CommitmentKind, + pub(crate) counterparty: Option, + pub(crate) due: FictionalMinutes, + pub(crate) period: Option, + pub(crate) statement: Statement, + /// Derived in `snapshot` so a controller does not recompute it against a + /// clock it must be handed anyway. + pub(crate) past_due: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PressureSnapshot { + pub(crate) source: PressureSource, + pub(crate) magnitude: PressureMagnitude, +} + +/// What a subject knows of one fact. `standing` carries no `EvidenceRef`: a +/// receipt is non-fictional provenance and never enters a subject-facing +/// surface, so a subject learns *that* a fact is canonical and never which +/// receipt admitted it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct KnowledgeSnapshot { + pub(crate) fact: EntityId, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingView, + pub(crate) confidence: Confidence, + /// The speaker a subject sees is `Told { by }`. A subject holding a fact it + /// was never told sees the statement with no speaker, which is correct: it + /// knows the thing, not the telling. + pub(crate) source: KnowledgeSource, + /// The revision of the act that minted this claim, spoken or displayed, + /// when some committed event asserted it. + pub(crate) minted_at: Option, + /// The revision at which this subject acquired this row, from `Knowledge` + /// directly: always present, unlike `minted_at`, so the recency marker can + /// see a row a patch, a seed, or a ruling landed with no minting event. + pub(crate) acquired_at: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FactStandingView { + Canonical, + Claimed { by: SubjectId }, + /// Stated by the play table. Never produced for a subject-facing knowledge + /// row (`snapshot`'s per-subject projection still collapses it into + /// `Canonical`, because a subject's own perception cannot tell a ruled + /// fact from an ordinarily canonical one); produced only for the + /// omniscient `WorldSnapshot::facts` row the play table's own `table_view` + /// reads. + Ruled, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct OfficeSnapshot { + pub(crate) institution: SubjectId, + pub(crate) office: OfficeName, + pub(crate) incumbent: Option, + /// What the office actually lends: the institution's live grants whose kind + /// the office delegates. + pub(crate) authority: BTreeSet, +} + +/// A forum a subject may petition. It carries no standing: a subject learns +/// that it may bring a grievance, not the boundary of everyone else's standing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ForumSnapshot { + pub(crate) grievance: GrievanceKindName, + pub(crate) forum: SubjectId, +} + +/// One catalog entry as consumers read it. The whole entry, because every +/// derived surface — tool schemas, signature prose, the typed view's permission +/// block — is a projection of it and a narrower snapshot would be a second +/// vocabulary to keep in step. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct AffordanceSnapshot { + pub id: AffordanceId, + pub entry: Affordance, + /// Derived from the world's grammar by this entry's kind; none when the + /// world has no grammar. + pub render_path: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ResourceSnapshot { + pub(crate) id: EntityId, + pub(crate) label: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PlaceSnapshot { + pub id: EntityId, + pub label: String, + pub(crate) container: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct RouteSnapshot { + pub(crate) id: EdgeId, + pub(crate) label: String, + pub(crate) from: EntityId, + pub(crate) to: EntityId, + pub(crate) access: AccessKind, + pub(crate) cost: Cost, + pub(crate) open: bool, +} + +/// A declared channel, standing rather than per-subject: `ChannelRecord` +/// carries no label (only `reach` and `controller`), so this is exactly that +/// record plus the canonical id, an omniscient row for the play table's own +/// view. No subject-facing surface reads it; a subject sees only the channels +/// it controls, through its own `components`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ChannelSnapshot { + pub(crate) id: EntityId, + pub(crate) reach: Reach, + pub(crate) controller: Option, +} + +/// Every fact the world holds, canonical or not, with its real standing — +/// including `Ruled`, which every subject-facing knowledge row collapses to +/// `Canonical` — and who currently holds it. Built straight from +/// `state.facts` and `state.knowledge`, not from any subject's own knowledge +/// projection, so a fact nobody has been told or shown is still a row here: +/// `mint`, `transfer`, `witness`, and `acquire_knowledge` all take a fact id, +/// and the play table's omniscient view must be able to name one nobody +/// perceives yet. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct FactSnapshot { + pub(crate) id: EntityId, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingView, + pub(crate) known_by: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WorldSnapshot { + pub world_id: WorldId, + pub revision: u64, + pub owner: PrincipalId, + pub title: String, + /// The bound grammar's identity; none for a world with an open catalog. + pub grammar: Option, + pub subjects: Vec, + pub affordances: Vec, + pub places: Vec, + pub(crate) resources: Vec, + pub(crate) routes: Vec, + /// Every declared channel, omniscient: no subject-facing surface reads + /// this field. `communicate`'s audience may name one by id. + pub(crate) channels: Vec, + /// Every fact the world holds, omniscient and including facts nobody + /// currently perceives: no subject-facing surface reads this field, which + /// exists for the play table's own `table_view` alone. + pub(crate) facts: Vec, + /// Everyone in a world shares the clock, and no controller can read a `due` + /// without it. + pub now: FictionalMinutes, + pub state_digest: String, + pub last_commit_digest: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CommitReceipt { + pub command_id: CommandId, + pub resulting_revision: u64, + pub resulting_state_digest: String, + pub commit_digest: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CreationReceipt { + pub command_id: CommandId, + pub world_id: WorldId, + pub resulting_state_digest: String, + pub commit_digest: String, +} + +impl CreationReceipt { + fn from_commit(commit: &WorldCommit) -> Result { + let CommittedCommand::CreateWorld(command) = &commit.command else { + return Err(KernelError::Invariant( + "world genesis receipt does not point to a creation command".into(), + )); + }; + let WorldEffect::WorldCreated { .. } = &commit.effect else { + return Err(KernelError::Invariant( + "world genesis receipt does not point to genesis".into(), + )); + }; + Ok(Self { + command_id: command.id(), + world_id: commit.world_id, + resulting_state_digest: commit.resulting_state_digest.clone(), + commit_digest: commit.digest.clone(), + }) + } +} + +impl From<&WorldCommit> for CommitReceipt { + fn from(commit: &WorldCommit) -> Self { + Self { + command_id: commit.command.id(), + resulting_revision: commit.resulting_revision, + resulting_state_digest: commit.resulting_state_digest.clone(), + commit_digest: commit.digest.clone(), + } + } +} + +#[derive(Debug, Error)] +pub enum KernelError { + #[error("world title must not be empty")] + EmptyTitle, + #[error("world owner principal must be canonical and nonempty")] + EmptyPrincipal, + #[error("patch rejected: {0:?}")] + PatchRejected(Vec), + #[error("action rejected: {0:?}")] + ActionRejected(Vec), + #[error("command targets another world")] + WorldMismatch, + #[error("authenticated caller does not match the command")] + AuthenticationMismatch, + #[error("caller does not own this world")] + Unauthorized, + #[error("decision affordance is not granted to the actor")] + AffordanceDenied, + #[error("expected revision {expected}, current revision {actual}")] + RevisionMismatch { expected: u64, actual: u64 }, + #[error("canonical serialization failed: {0}")] + Serialization(String), + #[error("world journal is corrupt: {0}")] + CorruptJournal(String), + /// A well-formed export written under another commit schema generation + /// (a v1 save): not corrupt, but not readable by this build. + #[error("export commit schema {found} is not the supported {supported}")] + UnsupportedSchema { found: String, supported: &'static str }, + #[error("private reducer invariant failed: {0}")] + Invariant(String), +} + +impl From for KernelError { + fn from(error: journal::JournalError) -> Self { + match error { + journal::JournalError::Corrupt(detail) => Self::CorruptJournal(detail), + journal::JournalError::UnsupportedSchema { found, supported } => { + Self::UnsupportedSchema { found, supported } + } + } + } +} + +// Test seam: when set on this thread, `submit` fails after it has folded the +// digest and sealed the commit, the last point before the world is kept. +#[cfg(test)] +thread_local! { + static INJECT_FAILURE_AFTER_DIGEST: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +struct WorldKernel { + state: WorldState, + journal: journal::WorldJournal, +} + +struct PreparedCreation { + command: CreateWorld, + world_id: WorldId, + owner: PrincipalId, + title: String, + resolved: ResolvedPatch, +} + +fn prepare_creation( + input: CreateWorld, + authenticated: &AuthenticatedCaller, +) -> Result { + let CallerId::Principal(authenticated_principal) = &authenticated.caller else { + return Err(KernelError::AuthenticationMismatch); + }; + validate_principal(&input.owner)?; + if &input.owner != authenticated_principal { + return Err(KernelError::AuthenticationMismatch); + } + let title = normalize_title(&input.title)?; + // The world's own identity is not world structure, and it feeds every + // derived ID, so it is minted before resolution rather than by it. + let world_id = WorldId::of(input.id()); + let resolved = patch::resolve_patch( + &WorldState::empty( + world_id, + input.owner.clone(), + title.clone(), + input.grammar.clone(), + ), + input.id(), + &input.patch, + ) + .map_err(KernelError::PatchRejected)?; + forbid_rulings_at_genesis(&resolved).map_err(KernelError::PatchRejected)?; + Ok(PreparedCreation { + world_id, + owner: input.owner.clone(), + title, + resolved, + command: input, + }) +} + +impl WorldKernel { + fn initialize(prepared: PreparedCreation) -> Result<(Self, CreationReceipt), KernelError> { + let world_id = prepared.world_id; + let effect = WorldEffect::WorldCreated { + owner: prepared.owner, + title: prepared.title, + resolved: prepared.resolved, + }; + let mut state = WorldState::genesis(world_id, &prepared.command, &effect)?; + let mut genesis = WorldCommit { + schema: COMMIT_SCHEMA.into(), + world_id, + command: CommittedCommand::CreateWorld(prepared.command), + previous_revision: None, + resulting_revision: 0, + previous_state_digest: None, + resulting_state_digest: state.state_digest.clone(), + previous_commit_digest: None, + effect, + digest: String::new(), + }; + genesis.digest = commit_digest(&genesis)?; + state.last_commit_digest = Some(genesis.digest.clone()); + let receipt = CreationReceipt::from_commit(&genesis)?; + let journal = journal::WorldJournal::genesis(genesis); + Ok((Self { state, journal }, receipt)) + } + + fn create( + input: CreateWorld, + authenticated: &AuthenticatedCaller, + ) -> Result<(Self, CreationReceipt), KernelError> { + Self::initialize(prepare_creation(input, authenticated)?) + } + + /// The world an export derives: its head state is the replay of its commits. + fn open(bytes: &[u8]) -> Result { + let (journal, state) = journal::WorldJournal::open(bytes)?; + Ok(Self { state, journal }) + } + + fn export(&self) -> Result, KernelError> { + self.journal.export() + } + + fn snapshot(&self) -> Result { + snapshot(&self.state, &self.journal) + } + + /// The decisions the world has acted on, for the tests that read them. + #[cfg(test)] + fn events(&self) -> Vec { + self.journal.acted_events().cloned().collect() + } + + fn submit( + &mut self, + command: CommandEnvelope, + authenticated: &AuthenticatedCaller, + ) -> Result { + let command_id = command.id(); + if command.world_id != self.state.header.world_id { + return Err(KernelError::WorldMismatch); + } + if command.caller != authenticated.caller { + return Err(KernelError::AuthenticationMismatch); + } + if command.expected_revision != self.state.revision { + return Err(KernelError::RevisionMismatch { + expected: command.expected_revision, + actual: self.state.revision, + }); + } + + let effect = reduce(&self.state, &command)?; + let previous_revision = self.state.revision; + let previous_state_digest = self.state.state_digest.clone(); + let previous_commit_digest = self.state.last_commit_digest.clone(); + // Applied in place under the partitions' undo logs: the world is never + // cloned, and any failure up to the sealed commit puts it back. + self.state.begin(); + let sealed = (|| -> Result<(WorldCommit, LtHash16), KernelError> { + apply_effect(&mut self.state, command_id, &command.caller, &effect)?; + self.state.revision = previous_revision + .checked_add(1) + .ok_or_else(|| KernelError::Serialization("world revision overflow".into()))?; + let accumulator = self.state.folded()?; + self.state.state_digest = accumulator.state_digest(self.state.revision); + let mut commit = WorldCommit { + schema: COMMIT_SCHEMA.into(), + world_id: self.state.header.world_id, + command: CommittedCommand::WorldCommand(command), + previous_revision: Some(previous_revision), + resulting_revision: self.state.revision, + previous_state_digest: Some(previous_state_digest.clone()), + resulting_state_digest: self.state.state_digest.clone(), + previous_commit_digest, + effect, + digest: String::new(), + }; + commit.digest = commit_digest(&commit)?; + #[cfg(test)] + if INJECT_FAILURE_AFTER_DIGEST.get() { + return Err(KernelError::Invariant("injected failure after the digest".into())); + } + Ok((commit, accumulator)) + })(); + let (commit, accumulator) = match sealed { + Ok(sealed) => sealed, + Err(error) => { + self.state.rollback(); + self.state.revision = previous_revision; + self.state.state_digest = previous_state_digest; + return Err(error); + } + }; + self.state.finish(accumulator); + self.state.last_commit_digest = Some(commit.digest.clone()); + + let receipt = CommitReceipt::from(&commit); + self.journal.append(commit); + Ok(receipt) + } + +} + +fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result { + // The one admission rule, stated here and again at the top of + // `apply_effect`: `reduce` decides and `apply_effect` re-decides, which is + // how every gate in this file is written. + require_play(&command.caller)?; + let command_id = command.id(); + match &command.body { + CommandBody::Act { actor, invocation } => { + let granted = require_granted(state, *actor, invocation.affordance)?; + let event = action::exercise(state, command_id, *actor, &granted, invocation)?; + Ok(WorldEffect::Acted { + invocation: invocation.clone(), + event, + }) + } + CommandBody::AdvanceTime { minutes } => { + let to = state + .header.now + .checked_add(*minutes) + .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; + // A tick with an empty motion is still a commit: the clock moved, + // which is a canonical change. That is why the clock is a state + // field rather than a patch operation. + Ok(WorldEffect::TimeAdvanced { + minutes: *minutes, + to, + motion: clock::derive_motion(state, to), + }) + } + CommandBody::AdmitPatch { patch } => { + let resolved = patch::resolve_patch(state, command_id, patch) + .map_err(KernelError::PatchRejected)?; + Ok(WorldEffect::PatchAdmitted { resolved }) + } + } +} + +/// The one admission rule: after genesis Play is the only caller any command +/// body admits. Stated once here, reached by `reduce` and by `apply_effect`. +fn require_play(caller: &CallerId) -> Result<(), KernelError> { + match caller { + CallerId::Play => Ok(()), + CallerId::Principal(_) => Err(KernelError::Unauthorized), + } +} + +/// The genesis predicate: the world is being built from nothing, so the one +/// lane that builds revision 0 may build the kernel Speak entry and the first +/// subjects. It reads state, never the caller. It takes the two fields it inspects rather than a whole +/// `WorldState` so the genesis lane, which resolves declarations before any +/// `WorldState` exists, can call the same owner instead of hand-copying the +/// literal it would otherwise always evaluate to. +fn is_genesis(revision: u64, subjects: &Docs) -> bool { + revision == 0 && subjects.is_empty() +} + +const WORLD_DOC_SCHEMA: &str = "aetherlight.world.v1"; + +impl WorldState { + /// Opens a transaction. Every log must be empty: a write outside a + /// transaction, or a transaction left open, is a bug here and not state. + fn begin(&self) { + debug_assert!(self.header.is_clean(), "a transaction is open"); + debug_assert!(self.partitions().iter().all(|(_, docs)| docs.is_clean())); + } + + /// What `subject` knows: its rows of the flat knowledge partition, by fact. + fn knowledge_of(&self, subject: SubjectId) -> impl Iterator { + self.knowledge + .range((subject, EntityId(Uuid::nil()))..=(subject, EntityId(Uuid::max()))) + .map(|((_, fact), held)| (fact, held)) + } + + /// The accumulator the open transaction's writes lead to. Reads the logs and + /// changes nothing, so a failure after it can still roll back. + fn folded(&self) -> Result { + let mut acc = self.accumulator.clone(); + digest::fold_header(&mut acc, WORLD_DOC_SCHEMA, &self.header.world_id.key(), &self.header)?; + for (schema, docs) in self.partitions() { + docs.fold_changes(schema, &mut acc)?; + } + Ok(acc) + } + + /// Closes the transaction, keeping its writes and the accumulator `folded` + /// computed for them. Returns the commitments subjects that changed, with + /// their old promises, for replay's check that every commitment stays in the + /// future. + fn finish( + &mut self, + accumulator: LtHash16, + ) -> Vec>> { + self.accumulator = accumulator; + self.header.finish(); + // The views fold from the open logs, so they come before the logs close. + let mut views = std::mem::take(&mut self.views); + views.fold(self); + self.views = views; + let commitments = self.commitments.finish(); + for (_, docs) in self.partitions_mut() { + docs.finish_log(); + } + commitments + } + + /// Closes the transaction, undoing every write in it. + fn rollback(&mut self) { + self.header.rollback(); + for (_, docs) in self.partitions_mut() { + docs.rollback(); + } + } + + /// Every document's digest by (schema, key), enumerated from the maps and + /// ignoring the logs. + #[cfg(test)] + fn documents( + &self, + ) -> Result, KernelError> { + let mut out = std::collections::BTreeMap::new(); + let header = &*self.header; + let key = header.world_id.key(); + out.insert( + (WORLD_DOC_SCHEMA.to_owned(), key.clone()), + digest::doc_digest(WORLD_DOC_SCHEMA, &key, header)?, + ); + for (schema, docs) in self.partitions() { + docs.documents(schema, &mut out)?; + } + Ok(out) + } + + /// The accumulator recomputed from every document: the oracle the + /// incremental digest is checked against. + #[cfg(test)] + fn full_state_digest(&self) -> Result { + let mut acc = LtHash16::default(); + for doc in self.documents()?.values() { + acc.add(doc); + } + Ok(acc.state_digest(self.revision)) + } + + /// Every document as encoded, header first: the bytes a test scans. + #[cfg(test)] + fn encoded_documents(&self) -> Vec { + let mut bytes = rmp_serde::to_vec_named(&*self.header).expect("the header encodes"); + for (_, docs) in self.partitions() { + bytes.extend(docs.encoded()); + } + bytes + } +} + +impl WorldState { + /// The world before any structure. Genesis resolves its own patch against + /// this value, so the genesis lane and `AdmitPatch` share one resolver + /// signature instead of hand-passing empty partitions. + fn empty( + world_id: WorldId, + owner: PrincipalId, + title: String, + grammar: Option, + ) -> Self { + Self::with_header(Tracked::absent(WorldHeader { + world_id, + owner, + title, + grammar, + now: FictionalMinutes::default(), + })) + } + + fn genesis( + world_id: WorldId, + command: &CreateWorld, + effect: &WorldEffect, + ) -> Result { + let WorldEffect::WorldCreated { + owner, + title, + resolved, + } = effect + else { + return Err(KernelError::Invariant( + "genesis state requires a world-created effect".into(), + )); + }; + validate_principal(&command.owner)?; + let expected_title = normalize_title(&command.title)?; + if owner != &command.owner || title != &expected_title { + return Err(KernelError::Invariant( + "genesis effect does not match the admitted creation command".into(), + )); + } + // The same re-derive-and-compare that `apply_committed_command` runs for + // every other command. Deterministic allocation is what lets one + // equality replace a field-by-field binding zip. + let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone()); + let expected = patch::resolve_patch( + &state, + command.id(), + &command.patch, + ) + .map_err(KernelError::PatchRejected)?; + if &expected != resolved { + return Err(KernelError::Invariant( + "genesis effect does not derive from its creation command".into(), + )); + } + forbid_rulings_at_genesis(resolved).map_err(|_| { + KernelError::Invariant("genesis effect rules or mints without the play authority".into()) + })?; + // Genesis resolves to revision 0 itself: `state.revision` never + // advances past 0 for the creating commit (`resulting_revision: 0`), + // unlike every later commit, which resolves to `state.revision + 1`. + let genesis_revision = state.revision; + admit_resolved(&mut state, resolved, genesis_revision)?; + let accumulator = state.folded()?; + state.state_digest = accumulator.state_digest(state.revision); + state.finish(accumulator); + Ok(state) + } +} + +/// The only writer of every ontology partition. Both admission lanes mutate +/// through it in one fixed order — entities, routes, subjects, operations — so a +/// patch may relocate along a route it declares. It re-derives every structural +/// claim from `state`, so an effect that skipped resolution dies here. +fn admit_resolved( + state: &mut WorldState, + resolved: &ResolvedPatch, + resolves_to: u64, +) -> Result<(), KernelError> { + if resolved.declares_nothing() && resolved.operations.is_empty() { + return Err(KernelError::Invariant( + "admitted patch carries no canonical change".into(), + )); + } + for entity in &resolved.entities { + if !patch::is_canonical_text(&entity.entity.label) { + return Err(KernelError::Invariant( + "admitted entity label is not canonical".into(), + )); + } + if let Some(container) = entity.entity.container + && (entity.entity.kind != EntityKind::Place + || state + .entities + .get(&container) + .is_none_or(|record| record.kind != EntityKind::Place)) + { + return Err(KernelError::Invariant( + "admitted container does not name a canonical place".into(), + )); + } + if state + .entities + .insert(entity.entity_id, entity.entity.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted entity ID collision".into(), + )); + } + if !patch::containment_terminates(entity.entity_id, &state.entities) { + return Err(KernelError::Invariant( + "admitted place contains itself".into(), + )); + } + } + for route in &resolved.routes { + let (from, to) = route.edge.endpoints(); + let endpoint_is_place = |entity_id: &EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == EntityKind::Place) + }; + if !patch::is_canonical_text(route.edge.label()) + || !endpoint_is_place(&from) + || !endpoint_is_place(&to) + || from == to + || !patch::is_valid_cost(route.edge.cost()) + { + return Err(KernelError::Invariant( + "admitted route is noncanonical or does not join two places".into(), + )); + } + if state + .edges + .insert(route.edge_id, route.edge.clone()) + .is_some() + { + return Err(KernelError::Invariant("admitted route ID collision".into())); + } + } + for entry in &resolved.affordances { + // The catalog's only writer holds the same grammar check the resolver + // runs, so an effect resolved elsewhere cannot install an entry the + // bound grammar refuses. + if state.header.grammar.as_ref().is_some_and(|grammar| { + grammar + .refusal(&entry.affordance.kind, &entry.affordance.roles) + .is_some() + }) { + return Err(KernelError::Invariant( + "admitted affordance is outside the bound grammar".into(), + )); + } + if state + .affordance_catalog + .insert(entry.affordance_id, entry.affordance.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted affordance ID collision".into(), + )); + } + } + // The subjects map's only writer holds the same injectivity the resolver + // checks, decided by the same function. + { + let mut declared = BTreeSet::new(); + for subject in &resolved.subjects { + if let Some(key) = &subject.subject.import_key + && patch::import_key_fault(key, |key| state.import_key_held(key), &mut declared) + .is_some() + { + return Err(KernelError::Invariant( + "admitted subject's import key is malformed, held or repeated".into(), + )); + } + } + } + for subject in &resolved.subjects { + if !patch::is_canonical_text(&subject.subject.label) { + return Err(KernelError::Invariant( + "admitted subject label is not canonical".into(), + )); + } + if let Some(position) = subject.position + && state + .entities + .get(&position.place) + .is_none_or(|entity| entity.kind != EntityKind::Place) + { + return Err(KernelError::Invariant( + "admitted position does not name a canonical place".into(), + )); + } + if state + .subjects + .insert(subject.subject_id, subject.subject.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted subject ID collision".into(), + )); + } + if let Some(position) = subject.position + && state + .positions + .insert(subject.subject_id, position) + .is_some() + { + return Err(KernelError::Invariant( + "admitted position collides with an existing one".into(), + )); + } + for affordance_id in &subject.affordances { + if !state.affordance_catalog.contains_key(affordance_id) { + return Err(KernelError::Invariant( + "admitted grant names no catalog entry".into(), + )); + } + state + .affordance_grants + .entry(subject.subject_id) + .or_default() + .insert(*affordance_id); + } + } + // Facts and channels: one `entities` row and one payload row per + // declaration, written together so the bijection has one writer. + for declared in &resolved.facts { + let claimed_by_a_stranger = match &declared.fact.standing { + FactStanding::Canonical { evidence } => { + !(patch::is_canonical_text(evidence.text()) && resolved.evidence.contains(evidence)) + } + FactStanding::Claimed { by } => !state.subjects.contains_key(by), + FactStanding::Ruled => false, + }; + if !patch::is_canonical_text(&declared.entity.label) + || !patch::is_canonical_text(declared.fact.statement.as_str()) + || declared.entity.kind != EntityKind::Fact + || claimed_by_a_stranger + { + return Err(KernelError::Invariant( + "admitted fact is noncanonical, unevidenced, or asserted by no live subject".into(), + )); + } + if state + .entities + .insert(declared.entity_id, declared.entity.clone()) + .is_some() + || state + .facts + .insert(declared.entity_id, declared.fact.clone()) + .is_some() + { + return Err(KernelError::Invariant("admitted fact ID collision".into())); + } + } + for declared in &resolved.channels { + if !patch::is_canonical_text(&declared.entity.label) + || declared.entity.kind != EntityKind::Channel + || !channel_referents_exist(state, &declared.channel) + { + return Err(KernelError::Invariant( + "admitted channel is noncanonical or names no live reach".into(), + )); + } + if state + .entities + .insert(declared.entity_id, declared.entity.clone()) + .is_some() + || state + .channels + .insert(declared.entity_id, declared.channel.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted channel ID collision".into(), + )); + } + } + apply_operations(state, &resolved.operations, &resolved.evidence, resolves_to) +} + +/// The component writer for every lane: apply each operation, accumulate the +/// ledger deltas, and prove conservation once. Declaration admission calls it +/// after its declaration loops; an exercised affordance's lowered effects call +/// it directly. One writer, one conservation statement. +/// +/// A forged effect reaches this function without ever passing the resolver, so +/// conservation and disjointness are re-derived here, from the transaction's own +/// log: only a holder the operations wrote can change either answer, because +/// every other holder appears on both sides of the equation and no other +/// jurisdiction moved. `before` is what each written holder held when this +/// function was entered, never anything the effect asserts. +fn apply_operations( + state: &mut WorldState, + operations: &[ResolvedOp], + evidence: &[EvidenceRef], + resolves_to: u64, +) -> Result<(), KernelError> { + let mut deltas: BTreeMap = BTreeMap::new(); + for operation in operations { + for resource in operation_resources(operation) { + deltas.entry(resource).or_default(); + } + } + // Holders already written when the operations begin (the declarations + // above, normally none): what they hold now is their `before`. + let at_entry: BTreeMap>> = state + .holdings + .changes() + .map(|(holder, _, now)| (*holder, now.cloned())) + .collect(); + for operation in operations { + apply_operation(state, operation, evidence, resolves_to)?; + match operation { + ResolvedOp::Transform { + from_resource, + into_resource, + qty, + .. + } => { + deltas.entry(*from_resource).or_default().spent += u128::from(qty.0); + deltas.entry(*into_resource).or_default().gained += u128::from(qty.0); + } + ResolvedOp::Consume { resource, qty, .. } => { + deltas.entry(*resource).or_default().consumed += u128::from(qty.0); + } + ResolvedOp::Admit { resource, qty, .. } => { + deltas.entry(*resource).or_default().admitted += u128::from(qty.0); + } + ResolvedOp::Mint { resource, qty, .. } => { + deltas.entry(*resource).or_default().admitted += u128::from(qty.0); + } + _ => {} + } + } + let held_of = |held: Option<&BTreeMap>, resource: &EntityId| { + held.and_then(|held| held.get(resource)).map_or(0, |quantity| u128::from(quantity.0)) + }; + // The holders judged are the union of those written at entry and those the + // log now reports: a holder written before the operations and returned to + // its transaction-start value is absent from `changes()` but still moved. + type Held<'a> = Option<&'a BTreeMap>; + let mut judged: BTreeMap, Held<'_>)> = BTreeMap::new(); + for (holder, logged, now) in state.holdings.changes() { + let before = match at_entry.get(holder) { + Some(recorded) => recorded.as_ref(), + None => logged, + }; + judged.insert(*holder, (before, now)); + } + for (holder, recorded) in &at_entry { + judged + .entry(*holder) + .or_insert_with(|| (recorded.as_ref(), state.holdings.get(holder))); + } + for (before, now) in judged.values() { + for (resource, delta) in &mut deltas { + delta.before += held_of(*before, resource); + delta.after += held_of(*now, resource); + } + } + if patch::check_ledger(&deltas).is_some() { + return Err(KernelError::Invariant("custody does not conserve".into())); + } + // Disjointness, re-derived for the same reason conservation is: a forged + // effect reaches this function without passing the resolver. Only a holder + // the transaction touched can have gained an overlap. + if operations.iter().any(|operation| { + matches!( + operation, + ResolvedOp::GrantAuthority { .. } + | ResolvedOp::OpenOffice { .. } + | ResolvedOp::InstallIncumbent { .. } + ) + }) && touched_holders(state).into_iter().any(|holder| holder_overlaps(state, holder)) + { + return Err(KernelError::Invariant( + "one subject holds two overlapping jurisdictions of one kind".into(), + )); + } + Ok(()) +} + +/// Every subject whose effective authority the open transaction may have +/// changed: whose own grants were written, whose offices were written (old +/// incumbent and new), and the incumbents of an institution whose grants were +/// written, because an office lends what its institution holds. A retirement +/// only removes lent authority, so it cannot add an overlap and is not read. +fn touched_holders(state: &WorldState) -> BTreeSet { + let mut touched = BTreeSet::new(); + let mut institutions = BTreeSet::new(); + for (holder, _, _) in state.authority.changes() { + touched.insert(*holder); + institutions.insert(*holder); + } + for (institution, old, new) in state.selection.changes() { + for offices in [old, new].into_iter().flatten() { + touched.extend(offices.values().filter_map(|office| office.incumbent)); + } + institutions.insert(*institution); + } + for institution in institutions { + if let Some(offices) = state.selection.get(&institution) { + touched.extend(offices.values().filter_map(|office| office.incumbent)); + } + } + touched +} + +/// Every resource an operation names, so `admit_resolved` can read its committed +/// total before touching it. +fn operation_resources(operation: &ResolvedOp) -> Vec { + match operation { + ResolvedOp::Transfer { resource, .. } + | ResolvedOp::Consume { resource, .. } + | ResolvedOp::Admit { resource, .. } + | ResolvedOp::Mint { resource, .. } => vec![*resource], + ResolvedOp::Transform { + from_resource, + into_resource, + .. + } => vec![*from_resource, *into_resource], + _ => Vec::new(), + } +} + +/// What `apply_operations` sums before and after: every holder. Conservation +/// reads only the holders a transaction wrote, and this is the reference. +#[cfg(test)] +fn resource_total_by_scan(state: &WorldState, resource: EntityId) -> u128 { + state + .holdings + .values() + .filter_map(|held| held.get(&resource)) + .map(|quantity| u128::from(quantity.0)) + .sum() +} + +/// What a holder holds. Absence is zero. +fn held(state: &WorldState, holder: SubjectId, resource: EntityId) -> u64 { + state + .holdings + .get(&holder) + .and_then(|held| held.get(&resource)) + .map_or(0, |quantity| quantity.0) +} + +/// Zero removes the resource key, and an emptied holder removes the holder key, +/// so `holdings` has exactly one representation of nothing. +fn set_held(state: &mut WorldState, holder: SubjectId, resource: EntityId, value: u64) { + if value == 0 { + let empty = if let Some(held) = state.holdings.get_mut(&holder) { + held.remove(&resource); + held.is_empty() + } else { + false + }; + if empty { + state.holdings.remove(&holder); + } + } else { + state + .holdings + .entry(holder) + .or_default() + .insert(resource, Quantity(value)); + } +} + +/// Whether a subject and a resource are both canonical and of the right kind. +fn custody_referents_exist(state: &WorldState, holder: SubjectId, resource: EntityId) -> bool { + state.subjects.contains_key(&holder) + && state + .entities + .get(&resource) + .is_some_and(|record| record.kind == EntityKind::Resource) +} + +fn dependency_target_exists(state: &WorldState, target: DependencyTarget) -> bool { + match target { + DependencyTarget::Resource(entity_id) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Resource), + DependencyTarget::Route(edge_id) => state.edges.contains_key(&edge_id), + DependencyTarget::Subject(subject_id) => state.subjects.contains_key(&subject_id), + } +} + +/// The component half of admission. Every precondition is re-derived from the +/// partitions, so a forged operation cannot assert a move the topology refuses. +fn apply_operation( + state: &mut WorldState, + operation: &ResolvedOp, + evidence: &[EvidenceRef], + resolves_to: u64, +) -> Result<(), KernelError> { + let insufficient = || KernelError::Invariant("holder does not hold enough".into()); + let overflow = || KernelError::Invariant("holding would overflow".into()); + let unknown = || KernelError::Invariant("custody operation names no canonical referent".into()); + let zero = || KernelError::Invariant("custody operation moves nothing".into()); + match operation { + ResolvedOp::Relocate { + subject_id, + edge_id, + } => { + let route = state + .edges + .get(edge_id) + .ok_or_else(|| KernelError::Invariant("relocation names no route".into()))?; + let (from, to) = route.endpoints(); + let open = route.is_open(); + let access = route.access().clone(); + if !open + || state.positions.get(subject_id) != Some(&Position { place: from }) + || !patch::route_admits(state, &subject_authority(state, *subject_id), &access, to) + { + return Err(KernelError::Invariant( + "relocation does not traverse an open route the subject may take from its place" + .into(), + )); + } + state.positions.insert(*subject_id, Position { place: to }); + } + ResolvedOp::OpenRoute { edge_id } | ResolvedOp::CloseRoute { edge_id } => { + let open = matches!(operation, ResolvedOp::OpenRoute { .. }); + let route = state + .edges + .get_mut(edge_id) + .ok_or_else(|| KernelError::Invariant("route operation names no route".into()))?; + if route.is_open() == open { + return Err(KernelError::Invariant( + "route operation changes nothing".into(), + )); + } + route.set_open(open); + } + ResolvedOp::AlterCost { edge_id, cost } => { + if !patch::is_valid_cost(*cost) { + return Err(KernelError::Invariant( + "admitted cost is out of range".into(), + )); + } + let route = state + .edges + .get_mut(edge_id) + .ok_or_else(|| KernelError::Invariant("route operation names no route".into()))?; + if route.cost() == *cost { + return Err(KernelError::Invariant( + "route operation changes nothing".into(), + )); + } + route.set_cost(*cost); + } + ResolvedOp::Transfer { + from, + to, + resource, + qty, + } => { + if !custody_referents_exist(state, *from, *resource) || !state.subjects.contains_key(to) + { + return Err(unknown()); + } + if qty.0 == 0 || from == to { + return Err(zero()); + } + let remaining = held(state, *from, *resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + let credited = held(state, *to, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *from, *resource, remaining); + set_held(state, *to, *resource, credited); + } + ResolvedOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *from_resource) + || !custody_referents_exist(state, *holder, *into_resource) + { + return Err(unknown()); + } + if qty.0 == 0 || from_resource == into_resource { + return Err(zero()); + } + let remaining = held(state, *holder, *from_resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + let gained = held(state, *holder, *into_resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *from_resource, remaining); + set_held(state, *holder, *into_resource, gained); + } + ResolvedOp::Consume { + holder, + resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + let remaining = held(state, *holder, *resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + set_held(state, *holder, *resource, remaining); + } + ResolvedOp::Admit { + holder, + resource, + qty, + evidence: cited, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + if !evidence.contains(cited) { + return Err(KernelError::Invariant( + "admitted quantity cites no evidence in its patch".into(), + )); + } + let admitted = held(state, *holder, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *resource, admitted); + } + ResolvedOp::Mint { + holder, + resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + let minted = held(state, *holder, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *resource, minted); + } + ResolvedOp::Bind { subject, target } | ResolvedOp::Release { subject, target } => { + let bind = matches!(operation, ResolvedOp::Bind { .. }); + if !state.subjects.contains_key(subject) || !dependency_target_exists(state, *target) { + return Err(unknown()); + } + if *target == DependencyTarget::Subject(*subject) { + return Err(KernelError::Invariant( + "a subject cannot depend on itself".into(), + )); + } + let bound = state + .dependencies + .get(subject) + .is_some_and(|targets| targets.contains(target)); + if bound == bind { + return Err(KernelError::Invariant( + "dependency operation changes nothing".into(), + )); + } + if bind { + state + .dependencies + .entry(*subject) + .or_default() + .insert(*target); + } else { + let empty = if let Some(targets) = state.dependencies.get_mut(subject) { + targets.remove(target); + targets.is_empty() + } else { + false + }; + if empty { + state.dependencies.remove(subject); + } + // The pressure a failing dependency raised is that dependency's + // own: it ends with it, or the world fails its shape check at open. + set_pressure(state, *subject, PressureSource::Dependency(*target), 0); + } + } + ResolvedOp::GrantAuthority { holder, grant } + | ResolvedOp::RevokeAuthority { holder, grant } => { + let granting = matches!(operation, ResolvedOp::GrantAuthority { .. }); + if !state.subjects.contains_key(holder) + || !authority_referent_exists(state, grant.over) + || !patch::is_civic_name(&grant.kind.0) + { + return Err(unknown()); + } + let held = state + .authority + .get(holder) + .is_some_and(|grants| grants.contains(grant)); + if held == granting { + return Err(KernelError::Invariant( + "authority operation changes nothing".into(), + )); + } + if granting { + state + .authority + .entry(*holder) + .or_default() + .insert(grant.clone()); + } else { + let empty = if let Some(grants) = state.authority.get_mut(holder) { + grants.remove(grant); + grants.is_empty() + } else { + false + }; + if empty { + state.authority.remove(holder); + } + } + } + ResolvedOp::OpenOffice { + institution, + office, + delegated, + } => { + require_institution(state, *institution, office)?; + if delegated.is_empty() || delegated.iter().any(|kind| !patch::is_civic_name(&kind.0)) { + return Err(KernelError::Invariant( + "an office lends no canonical authority kind".into(), + )); + } + let current = state + .selection + .get(institution) + .and_then(|offices| offices.get(office)); + if current.is_some_and(|seat| &seat.delegated == delegated) { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } + // A sitting incumbent survives a reconstitution: clipping an + // office's powers under its holder is a political act, not a + // vacancy. + let incumbent = current.and_then(|seat| seat.incumbent); + state.selection.entry(*institution).or_default().insert( + office.clone(), + Office { + incumbent, + delegated: delegated.clone(), + }, + ); + } + ResolvedOp::CloseOffice { + institution, + office, + } + | ResolvedOp::VacateOffice { + institution, + office, + } => { + let closing = matches!(operation, ResolvedOp::CloseOffice { .. }); + require_institution(state, *institution, office)?; + let no_office = || KernelError::Invariant("office operation names no office".into()); + let offices = state.selection.get_mut(institution).ok_or_else(no_office)?; + let occupied = offices + .get(office) + .map(|seat| seat.incumbent.is_some()) + .ok_or_else(no_office)?; + if closing { + offices.remove(office); + let empty = offices.is_empty(); + if empty { + state.selection.remove(institution); + } + } else if !occupied { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } else { + offices.get_mut(office).ok_or_else(no_office)?.incumbent = None; + } + } + ResolvedOp::InstallIncumbent { + institution, + office, + incumbent, + } => { + require_institution(state, *institution, office)?; + if state.subjects.get(incumbent).map(|subject| subject.kind) + != Some(SubjectKind::Person) + { + return Err(KernelError::Invariant( + "an office holder is not a person subject".into(), + )); + } + let offices = state + .selection + .get_mut(institution) + .ok_or_else(|| KernelError::Invariant("office operation names no office".into()))?; + if offices + .iter() + .any(|(name, seat)| name != office && seat.incumbent == Some(*incumbent)) + { + return Err(KernelError::Invariant( + "one person holds two offices of one institution".into(), + )); + } + let seat = offices + .get_mut(office) + .ok_or_else(|| KernelError::Invariant("office operation names no office".into()))?; + if seat.incumbent == Some(*incumbent) { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } + seat.incumbent = Some(*incumbent); + } + ResolvedOp::OpenForum { + grievance, + forum, + standing, + } => { + if !state.subjects.contains_key(forum) + || !authority_referent_exists(state, *standing) + || !patch::is_civic_name(&grievance.0) + { + return Err(unknown()); + } + let seat = Forum { + forum: *forum, + standing: *standing, + }; + if state.redress.get(grievance) == Some(&seat) { + return Err(KernelError::Invariant( + "forum operation changes nothing".into(), + )); + } + state.redress.insert(grievance.clone(), seat); + } + ResolvedOp::CloseForum { grievance } => { + if state.redress.remove(grievance).is_none() { + return Err(KernelError::Invariant( + "forum operation names no forum".into(), + )); + } + } + ResolvedOp::AssertClaim { + fact, + statement, + by, + } => { + if !state.subjects.contains_key(by) || !patch::is_canonical_text(statement.as_str()) { + return Err(KernelError::Invariant( + "a claim names no live asserter or no canonical statement".into(), + )); + } + if state + .entities + .insert( + *fact, + EntityRecord { + label: CLAIM_LABEL.into(), + kind: EntityKind::Fact, + container: None, + }, + ) + .is_some() + || state + .facts + .insert( + *fact, + FactRecord { + statement: statement.clone(), + standing: FactStanding::Claimed { by: *by }, + }, + ) + .is_some() + { + return Err(KernelError::Invariant("minted claim ID collision".into())); + } + } + ResolvedOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => { + let Some(record) = state.facts.get(fact) else { + return Err(KernelError::Invariant( + "knowledge operation names no canonical fact".into(), + )); + }; + if !state.subjects.contains_key(subject) + || (*source == AuthoredSource::Evidenced + && !matches!(record.standing, FactStanding::Canonical { .. })) + { + return Err(KernelError::Invariant( + "knowledge operation names no live subject, or evidences a claim".into(), + )); + } + let source = match source { + AuthoredSource::Witnessed => KnowledgeSource::Witnessed, + AuthoredSource::Evidenced => KnowledgeSource::Evidenced, + }; + // Compared on `confidence` and `source` alone: `acquired_at` is + // this write's own revision, not part of what the author asserts, + // so a re-assertion identical in everything the author controls + // still refuses as a no-op even though it would land a later + // `acquired_at`. + if state + .knowledge + .get(&(*subject, *fact)) + .is_some_and(|held| held.confidence == *confidence && held.source == source) + { + return Err(KernelError::Invariant( + "knowledge operation changes nothing".into(), + )); + } + // Matches `DecisionEvent.revision` and the `minted_at` scan built + // from it (`action::exercise`, `snapshot`): both name the revision + // this commit resolves to. `resolves_to` is `state.revision` itself + // at genesis, which never advances past 0, and `state.revision + 1` + // everywhere else, since `state` still holds the *previous* + // revision until `submit` bumps it. One value, one caller-computed + // source, so a genesis-seeded row cannot land one revision ahead of + // the state it was written into. + let acquired_at = resolves_to; + let entry = Knowledge { + confidence: *confidence, + source, + acquired_at, + }; + state.knowledge.insert((*subject, *fact), entry); + } + ResolvedOp::Forget { subject, fact } => { + if state.knowledge.remove(&(*subject, *fact)).is_none() { + return Err(KernelError::Invariant( + "knowledge operation changes nothing".into(), + )); + } + } + ResolvedOp::Communicate { speaker, fact, to } => { + if !state.subjects.contains_key(speaker) || !state.facts.contains_key(fact) { + return Err(KernelError::Invariant( + "a telling names no live speaker or fact".into(), + )); + } + if !can_broadcast(state, *speaker, to) { + return Err(KernelError::Invariant( + "a speaker is outside its own audience".into(), + )); + } + // An empty fan-out is legal: the delta of a telling is a property of + // the world — an empty room, a silenced channel — not a defect in + // the proposal. Speaking alone commits the claim and lands nothing. + // `acquired_at` matches `minted_at` (PA.f44): both name the + // revision this commit resolves to, `resolves_to` (PA.f49) — + // `state.revision` itself at genesis, `state.revision + 1` + // otherwise. + let acquired_at = resolves_to; + for listener in fan_out(state, *speaker, *fact, to) { + state.knowledge.insert( + (listener, *fact), + Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: *speaker, + via: to.channel(), + }, + acquired_at, + }, + ); + } + } + ResolvedOp::Display { actor, fact } => { + if !state.subjects.contains_key(actor) || !state.facts.contains_key(fact) { + return Err(KernelError::Invariant( + "a display names no live actor or fact".into(), + )); + } + // The room is the audience, re-derived here: the same derivation + // co-located speech uses, so a body and a voice cannot disagree + // about who is in the room. A placeless actor is refused as a + // placeless speaker is; an empty room is a legal no-op, as + // speaking alone is. `Believed` is fixed by the kernel: a + // displayer cannot choose how much a viewer believes its body. + let room = Audience::Colocated; + if !can_broadcast(state, *actor, &room) { + return Err(KernelError::Invariant( + "an actor displays from no place".into(), + )); + } + // The revision the caller's own commit resolves to: `state.revision` + // itself at genesis, which never advances past 0, and + // `state.revision + 1` everywhere else, since `state` still holds + // the *previous* revision until `submit` bumps it. One value, one + // caller-computed source, so a genesis-seeded row cannot land one + // revision ahead of the state it was written into. + let acquired_at = resolves_to; + for viewer in fan_out(state, *actor, *fact, &room) { + state.knowledge.insert( + (viewer, *fact), + Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Seen { by: *actor }, + acquired_at, + }, + ); + } + } + ResolvedOp::Witness { + fact, + place, + confidence, + } => { + if !state.facts.contains_key(fact) + || !state + .entities + .get(place) + .is_some_and(|record| record.kind == EntityKind::Place) + { + return Err(KernelError::Invariant( + "a witness names no live fact or place".into(), + )); + } + // Recipients are derived here and never stored: everyone standing + // under the place, less everyone who already holds the fact. A + // witness that reaches nobody is refused, because a witnessed event + // is only its reception — `resolve_patch` refuses the same case over + // the candidate graph, so the two layers cannot disagree. + let recipients = unheld(state, *fact, under_place(state, *place)); + if recipients.is_empty() { + return Err(KernelError::Invariant( + "a witness reaches nobody who does not already hold the fact".into(), + )); + } + // The revision the caller's own commit resolves to: `state.revision` + // itself at genesis, which never advances past 0, and + // `state.revision + 1` everywhere else, since `state` still holds + // the *previous* revision until `submit` bumps it. One value, one + // caller-computed source, so a genesis-seeded row cannot land one + // revision ahead of the state it was written into. + let acquired_at = resolves_to; + for witness in recipients { + state.knowledge.insert( + (witness, *fact), + Knowledge { + confidence: *confidence, + source: KnowledgeSource::Witnessed, + acquired_at, + }, + ); + } + } + ResolvedOp::SetReach { channel, reach } => { + let current = state + .channels + .get(channel) + .ok_or_else(|| KernelError::Invariant("channel operation names no channel".into()))? + .clone(); + let record = ChannelRecord { + reach: reach.clone(), + controller: current.controller, + }; + if !channel_referents_exist(state, &record) { + return Err(KernelError::Invariant( + "a reach names no live subject or place".into(), + )); + } + if current.reach == *reach { + return Err(KernelError::Invariant( + "channel operation changes nothing".into(), + )); + } + state.channels.insert(*channel, record); + } + ResolvedOp::SetController { + channel, + controller, + } => { + if controller.is_some_and(|subject_id| !state.subjects.contains_key(&subject_id)) { + return Err(unknown()); + } + let seat = state.channels.get_mut(channel).ok_or_else(|| { + KernelError::Invariant("channel operation names no channel".into()) + })?; + if seat.controller == *controller { + return Err(KernelError::Invariant( + "channel operation changes nothing".into(), + )); + } + seat.controller = *controller; + } + ResolvedOp::CreateCommitment { + subject, + key, + commitment, + } => { + if !state.subjects.contains_key(subject) + || !commitment_is_live(state, *subject, commitment) + { + return Err(KernelError::Invariant( + "a commitment names no live promisor, counterparty, or check".into(), + )); + } + if state + .commitments + .entry(*subject) + .or_default() + .insert(*key, commitment.clone()) + .is_some() + { + return Err(KernelError::Invariant("commitment key collision".into())); + } + } + ResolvedOp::DischargeCommitment { subject, key } => { + // One removal, two writes, one owner: the commitment and every + // pressure row it sourced. + let discharged = || KernelError::Invariant("discharge names no live commitment".into()); + let held = state.commitments.get_mut(subject).ok_or_else(discharged)?; + held.remove(key).ok_or_else(discharged)?; + let empty = held.is_empty(); + if empty { + state.commitments.remove(subject); + } + let sourced = PressureSource::Commitment { + subject: *subject, + key: *key, + }; + for target in pressure_holders(state, sourced) { + let emptied = state.pressures.get_mut(&target).is_some_and(|held| { + held.remove(&sourced); + held.is_empty() + }); + if emptied { + state.pressures.remove(&target); + } + } + } + ResolvedOp::AdvancePressure { source, target, by } + | ResolvedOp::ReducePressure { source, target, by } => { + let advancing = matches!(operation, ResolvedOp::AdvancePressure { .. }); + if !state.subjects.contains_key(target) || !pressure_source_is_live(state, source) { + return Err(unknown()); + } + let current = state + .pressures + .get(target) + .and_then(|held| held.get(source)) + .map_or(0, |magnitude| magnitude.0); + let next = if advancing { + current.saturating_add(by.0) + } else { + current.saturating_sub(by.0) + }; + if next == current { + return Err(KernelError::Invariant( + "pressure operation changes nothing".into(), + )); + } + set_pressure(state, *target, *source, next); + } + ResolvedOp::ResolvePressure { source, target } => { + if state + .pressures + .get(target) + .is_none_or(|held| !held.contains_key(source)) + { + return Err(KernelError::Invariant( + "pressure operation changes nothing".into(), + )); + } + set_pressure(state, *target, *source, 0); + } + ResolvedOp::Retire { subject } => { + let held = state.subjects.get_mut(subject).ok_or_else(unknown)?; + if held.retired { + return Err(KernelError::Invariant( + "retire operation names an already retired subject".into(), + )); + } + held.retired = true; + state.positions.remove(subject); + state.affordance_grants.remove(subject); + } + ResolvedOp::GrantAffordance { subject, affordance } + | ResolvedOp::RevokeAffordance { subject, affordance } => { + let granting = matches!(operation, ResolvedOp::GrantAffordance { .. }); + if !state.subjects.contains_key(subject) + || is_retired(state, *subject) + || !state.affordance_catalog.contains_key(affordance) + { + return Err(unknown()); + } + if granting { + if !state + .affordance_grants + .entry(*subject) + .or_default() + .insert(*affordance) + { + return Err(KernelError::Invariant( + "affordance grant operation changes nothing".into(), + )); + } + } else { + let granted = state + .affordance_grants + .get_mut(subject) + .ok_or_else(unknown)?; + if !granted.remove(affordance) { + return Err(KernelError::Invariant( + "affordance grant operation changes nothing".into(), + )); + } + if granted.is_empty() { + state.affordance_grants.remove(subject); + } + } + } + } + Ok(()) +} + +/// Zero removes the source key, and an emptied target removes the target key, +/// so `pressures` has exactly one representation of nothing. +fn set_pressure(state: &mut WorldState, target: SubjectId, source: PressureSource, value: u32) { + if value == 0 { + let empty = if let Some(held) = state.pressures.get_mut(&target) { + held.remove(&source); + held.is_empty() + } else { + false + }; + if empty { + state.pressures.remove(&target); + } + } else { + state + .pressures + .entry(target) + .or_default() + .insert(source, PressureMagnitude(value)); + } +} + +/// Whether every referent a commitment names is live and its shape holds. +/// Re-derived over the committed partitions, because a forged effect reaches +/// `apply_operation` without ever passing the resolver. +fn commitment_is_live(state: &WorldState, subject: SubjectId, commitment: &Commitment) -> bool { + let counterparty_is_live = match commitment.counterparty { + Some(counterparty) => { + counterparty != subject + && state.subjects.contains_key(&counterparty) + && commitment.kind != CommitmentKind::Goal + } + None => true, + }; + counterparty_is_live + && (commitment.kind == CommitmentKind::Routine) == commitment.period.is_some() + && (commitment.kind == CommitmentKind::Routine || commitment.checks.is_empty()) + && commitment.due > state.header.now + && commitment + .checks + .iter() + .all(|check| bound_precondition_is_live(state, check)) +} + +fn bound_precondition_is_live(state: &WorldState, check: &BoundPrecondition) -> bool { + let is_kind = |entity_id: &EntityId, kind: EntityKind| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == kind) + }; + let audience_is_live = |via: &Audience| match via { + Audience::Colocated => true, + Audience::Channel(entity_id) => state.channels.contains_key(entity_id), + }; + match check { + BoundPrecondition::Present { at } => is_kind(at, EntityKind::Place), + BoundPrecondition::Reachable { to, within } => { + is_kind(to, EntityKind::Place) && patch::is_valid_cost(*within) + } + BoundPrecondition::Holds { resource, .. } => is_kind(resource, EntityKind::Resource), + BoundPrecondition::Authorized { over, kind } => { + patch::is_civic_name(&kind.0) + && match over { + Target::Subject(subject_id) => state.subjects.contains_key(subject_id), + Target::Entity(entity_id) => is_kind(entity_id, EntityKind::Place), + Target::Edge(edge_id) => state.edges.contains_key(edge_id), + } + } + BoundPrecondition::HasStanding { grievance } => patch::is_civic_name(&grievance.0), + BoundPrecondition::Knows { fact, .. } => is_kind(fact, EntityKind::Fact), + BoundPrecondition::CanBroadcast { via } => audience_is_live(via), + BoundPrecondition::CanReach { subject, via } => { + state.subjects.contains_key(subject) && audience_is_live(via) + } + BoundPrecondition::Committed { to, .. } => state.subjects.contains_key(to), + } +} + +fn pressure_source_is_live(state: &WorldState, source: &PressureSource) -> bool { + match source { + PressureSource::Commitment { subject, key } => state + .commitments + .get(subject) + .is_some_and(|held| held.contains_key(key)), + PressureSource::Dependency(target) => dependency_target_exists(state, *target), + PressureSource::Subject(subject_id) => state.subjects.contains_key(subject_id), + } +} + +/// The label every minted claim carries. A label is a name, not a transcript: +/// the statement is never copied into it and the label is never derived from +/// it. Labels resolve no references, so identical labels across every claim +/// are unremarkable. The statement itself lives in `facts[fact].statement` +/// and is also carried inside the committed `AssertClaim` effect on the +/// event that minted it; `facts` is the one readable home a projection may +/// consult, and the event copy is the replay witness, never a second read +/// surface. +const CLAIM_LABEL: &str = "claim"; + +/// Whether a channel's reach and controller name live structure. +fn channel_referents_exist(state: &WorldState, record: &ChannelRecord) -> bool { + let reach = match &record.reach { + Reach::Subjects(members) => members + .iter() + .all(|subject_id| state.subjects.contains_key(subject_id)), + Reach::Place(place) => state + .entities + .get(place) + .is_some_and(|entity| entity.kind == EntityKind::Place), + }; + reach + && record + .controller + .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) +} + +impl WorldState { + /// Whether a subject, retired or not, holds this import key. One point read + /// of `ByImportKey`. + fn import_key_held(&self, key: &ImportKey) -> bool { + !self.subjects.indexed(key.clone()..=key.clone()).is_empty() + } + + /// Whether a catalog entry already names this affordance kind. + fn kind_taken(&self, kind: &AffordanceKindName) -> bool { + !self.affordance_catalog.indexed(kind.clone()..=kind.clone()).is_empty() + } +} + +/// What `import_key_held` and `kind_taken` were before their indexes: every +/// subject, every catalog entry. The index reads must equal them. +#[cfg(test)] +fn import_key_held_by_scan(state: &WorldState, key: &ImportKey) -> bool { + state.subjects.values().any(|subject| subject.import_key.as_ref() == Some(key)) +} + +#[cfg(test)] +fn kind_taken_by_scan(state: &WorldState, kind: &AffordanceKindName) -> bool { + state.affordance_catalog.values().any(|entry| &entry.kind == kind) +} + +/// Whether a subject is retired: the one statement of retirement, read by +/// audience derivation, preconditions and resolvers. Only an actual `Retire` +/// sets `SubjectState.retired`. +pub(crate) fn is_retired(state: &WorldState, subject_id: SubjectId) -> bool { + state + .subjects + .get(&subject_id) + .is_some_and(|subject| subject.retired) +} + +/// Everyone standing anywhere under one place. The one downward-facing read of +/// `positions`: `audience`'s `Reach::Place` arm and `ResolvedOp::Witness` are +/// its two callers, so what "under a place" means cannot drift between a +/// declared broadcast area and a witnessed event. A subject with no position is +/// under nothing. +fn under_place(state: &WorldState, root: EntityId) -> BTreeSet { + // The subtree by `ChildOf`, collecting who stands in each place. Containment + // is acyclic (`admit_resolved` refuses a chain that does not terminate); the + // visited set keeps the walk total regardless. + let mut under = BTreeSet::new(); + let mut seen = BTreeSet::new(); + let mut frontier = vec![root]; + while let Some(place) = frontier.pop() { + if !seen.insert(place) { + continue; + } + under.extend( + state + .positions + .indexed(place..=place) + .into_iter() + .map(|(_, subject_id)| subject_id), + ); + frontier.extend( + state + .entities + .indexed(place..=place) + .into_iter() + .map(|(_, child)| child), + ); + } + under +} + +/// What `under_place` was before the index: every position, asked whether its +/// place is covered. The index read must equal it. +#[cfg(test)] +fn under_place_by_scan(state: &WorldState, root: EntityId) -> BTreeSet { + state + .positions + .iter() + .filter(|(_, position)| patch::covers_place(&state.entities, root, position.place)) + .map(|(subject_id, _)| *subject_id) + .collect() +} + +/// The one statement of reach. Called by both speech preconditions, by a +/// `Communicate`'s admission, and by its apply. Nothing else computes an +/// audience. +/// +/// Co-location is the actor's exact place, not its subtree: a voice fills a +/// room, not the district containing it. A channel's `Reach::Place` is +/// deliberately wider, because a declared broadcast area is a declared choice. +fn audience(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet { + match of { + Audience::Colocated => { + let Some(here) = state.positions.get(&actor).copied() else { + return BTreeSet::new(); + }; + state + .positions + .indexed(here.place..=here.place) + .into_iter() + .map(|(_, subject_id)| subject_id) + .collect() + } + Audience::Channel(channel) => { + let Some(record) = state.channels.get(channel) else { + return BTreeSet::new(); + }; + match &record.reach { + // Audience derivation is the one owner of who is reachable, so + // a channel may still *declare* a retired member (PA.f33); + // retirement is filtered here, at the single read site, not at + // declaration time. + Reach::Subjects(members) => members + .iter() + .copied() + .filter(|member| !is_retired(state, *member)) + .collect(), + Reach::Place(root) => under_place(state, *root), + } + } + } +} + +/// What `audience` was before the index: every position compared with the +/// actor's, and `under_place_by_scan` for a channel's place. The index read +/// must equal it. +#[cfg(test)] +fn audience_by_scan(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet { + match of { + Audience::Colocated => { + let Some(here) = state.positions.get(&actor).copied() else { + return BTreeSet::new(); + }; + state + .positions + .iter() + .filter(|(_, position)| **position == here) + .map(|(subject_id, _)| *subject_id) + .collect() + } + Audience::Channel(channel) => match state.channels.get(channel).map(|record| &record.reach) { + Some(Reach::Place(root)) => under_place_by_scan(state, *root), + _ => audience(state, actor, of), + }, + } +} + +/// Whether an actor may broadcast into an audience: either the actor stands +/// inside the declared reach, or — for a channel — the actor is that +/// channel's controller. The controller's privilege is narrow: it lets the +/// horn sound from outside the room, but it does not admit the controller to +/// the audience itself. A controller outside its channel's reach gains no +/// knowledge from its own telling and is not a target another actor can +/// reach through that channel; `audience()` stays the one statement of who is +/// inside, and this is the one statement of who may speak. +fn can_broadcast(state: &WorldState, actor: SubjectId, of: &Audience) -> bool { + if audience(state, actor, of).contains(&actor) { + return true; + } + match of { + Audience::Channel(channel) => state + .channels + .get(channel) + .is_some_and(|record| record.controller == Some(actor)), + Audience::Colocated => false, + } +} + +/// A knowledge landing never overwrites and never downgrades a holder: whoever +/// already holds the fact is dropped, whatever it holds and however it came by +/// it. The knower owns its own credence, and a landing that could reset it by +/// repeating itself would own another subject's mind through an effect nobody +/// checked. `fan_out` and `ResolvedOp::Witness` are the two callers, so a +/// telling and a witnessed event cannot disagree about who is already a knower. +fn unheld( + state: &WorldState, + fact: EntityId, + listeners: BTreeSet, +) -> BTreeSet { + listeners + .into_iter() + .filter(|listener| { + !state.knowledge.contains_key(&(*listener, fact)) + }) + .collect() +} + +/// Who gains knowledge from one telling: the audience, less the speaker, less +/// anyone who already holds the fact. `Believed` is fixed by the kernel and is +/// not a field on the operation, so a speaker cannot choose how much a listener +/// believes it. +fn fan_out( + state: &WorldState, + speaker: SubjectId, + fact: EntityId, + to: &Audience, +) -> BTreeSet { + let mut listeners = audience(state, speaker, to); + listeners.remove(&speaker); + unheld(state, fact, listeners) +} + +/// Whether an authority target names a live subject or a live place. +fn authority_referent_exists(state: &WorldState, target: AuthorityTarget) -> bool { + match target { + AuthorityTarget::Subject(subject_id) => state.subjects.contains_key(&subject_id), + AuthorityTarget::PlaceSubtree(entity_id) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Place), + } +} + +/// The shared half of every office operation: a canonical office name on a live +/// institution subject. +fn require_institution( + state: &WorldState, + institution: SubjectId, + office: &OfficeName, +) -> Result<(), KernelError> { + if !patch::is_civic_name(&office.0) { + return Err(KernelError::Invariant( + "office name is not canonical".into(), + )); + } + if state.subjects.get(&institution).map(|subject| subject.kind) + != Some(SubjectKind::Institution) + { + return Err(KernelError::Invariant( + "an office was opened on a subject that is not an institution".into(), + )); + } + Ok(()) +} + +/// The subject, if any, whose effective authority holds two grants of one kind +/// over overlapping ground. Re-derived over the committed partitions after every +/// batch that could widen a jurisdiction, so a forged effect cannot install the +/// split-brained state the resolver refuses. +fn overlapping_holder(state: &WorldState) -> Option { + let holders: BTreeSet = state + .authority + .keys() + .copied() + .chain( + state + .selection + .values() + .flat_map(|offices| offices.values()) + .filter_map(|office| office.incumbent), + ) + .collect(); + holders.into_iter().find(|holder| holder_overlaps(state, *holder)) +} + +/// Whether one subject's effective authority holds two grants of one kind over +/// overlapping ground. The pairwise check `overlapping_holder` runs over every +/// holder, and `apply_operations` over the holders a transaction touched. +fn holder_overlaps(state: &WorldState, holder: SubjectId) -> bool { + let effective: Vec = subject_authority(state, holder).into_iter().collect(); + effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind && patch::targets_overlap(&state.entities, one.over, other.over) + }) + }) +} + +/// Exactly the components a subject's verification reads. One owner, consumed by +/// `action::exercise` and by the snapshot, so the two cannot drift. `routes` is +/// every edge whose `from` or `to` is the subject's place: an inbound route +/// decides who can arrive, and reading too little is a correctness hole while +/// reading too much only costs an extra rejection. `holdings` and `dependencies` +/// are the acting subject's own; a counterparty's holdings do not enter, because +/// a transfer changes both subjects' components. +/// It also holds what the actor *is* authorized over, and nothing about the +/// world the actor reaches: the target's position, the target's container +/// chain, the forum's state, and any subordinate's components stay out. A +/// target that walks out of a jurisdiction mid-flight fails at `Authorized` +/// at commit, and a revoked grant fails the same way. +/// +/// `Deserialize` is here so the narrative lane can persist a subject's own +/// components as the "before" an interruption is measured against. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ScopeComponents { + position: Option, + routes: BTreeMap, + holdings: BTreeMap, + dependencies: BTreeSet, + /// This subject's own grants. + authority: BTreeSet, + /// What each held office lends: for every office whose incumbent is this + /// subject, the institution's live grants whose kind that office delegates. + /// The institution's authority is copied in through the office link, so one + /// scope covers the grant, the office, and the institution's jurisdiction, + /// and only delegated kinds enter — an institution's `judge` jurisdiction + /// never reaches a `levy`-only incumbent. + delegated: BTreeMap>>, + /// The keys of this subject's own knowledge. Keys, not payloads: a statement + /// is immutable, so it cannot change without the key changing, and + /// confidence is admission-only — a re-appraisal that lowers a subject's own + /// confidence does not reject its own in-flight proposal, because `Knows` + /// re-checks at commit and fails closed with `FactUnknown`. + knows: BTreeSet, + /// The channels this subject controls, with their records. Membership of a + /// channel it merely hears never enters: a 1,000-member channel would churn + /// a thousand scopes per membership change. + controls: BTreeMap, + /// This subject's own commitments. `Precondition::Committed` reads them, so + /// they are in scope. Pressure and the clock stay out: no precondition reads + /// either. + commitments: BTreeMap, +} + +/// Whether an authority target covers a referent. The one statement of +/// jurisdictional membership, reached by `Authorized`, `HasStanding`, +/// `route_admits`, the delegation monotonicity rule, and the snapshot's redress +/// projection. +/// +/// A place subtree covers a subject standing anywhere under it, a place under +/// it, and a route with either endpoint under it — a city must be able to close +/// its own gate, and a gate's far end is outside the city by construction. A +/// resource, fact, or channel is covered by nothing; `RoleKindUnfit` refuses an +/// `Authorized` over such a role at declaration. +fn covers(state: &WorldState, target: AuthorityTarget, of: Target) -> bool { + let under = |place: EntityId, root: EntityId| patch::covers_place(&state.entities, root, place); + match (target, of) { + (AuthorityTarget::Subject(holder), Target::Subject(subject_id)) => holder == subject_id, + (AuthorityTarget::Subject(_), _) => false, + (AuthorityTarget::PlaceSubtree(root), Target::Subject(subject_id)) => state + .positions + .get(&subject_id) + .is_some_and(|position| under(position.place, root)), + (AuthorityTarget::PlaceSubtree(root), Target::Entity(entity_id)) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Place && under(entity_id, root)), + (AuthorityTarget::PlaceSubtree(root), Target::Edge(edge_id)) => { + state.edges.get(&edge_id).is_some_and(|record| { + let (from, to) = record.endpoints(); + under(from, root) || under(to, root) + }) + } + } +} + +/// Own grants plus what every held office lends. The single statement of what a +/// subject may invoke authority over. There is no precedence between a direct +/// grant and a delegated one, because `OverlappingJurisdiction` makes it +/// impossible for both to answer for one kind over overlapping ground. +fn effective_authority( + own: &BTreeSet, + delegated: &BTreeMap>>, +) -> BTreeSet { + let mut effective = own.clone(); + for lent in delegated.values().flat_map(|offices| offices.values()) { + effective.extend(lent.iter().cloned()); + } + effective +} + +/// Every office this subject occupies, keyed by institution, with what each one +/// lends of that institution's live grants. +fn delegated_authority( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap>> { + let mut held: BTreeMap>> = + BTreeMap::new(); + for (_, institution) in state.selection.indexed(subject_id..=subject_id) { + lend_offices(state, subject_id, institution, &state.selection[&institution], &mut held); + } + held +} + +/// What one institution's offices lend `subject_id`, added to `held`. +fn lend_offices( + state: &WorldState, + subject_id: SubjectId, + institution: SubjectId, + offices: &BTreeMap, + held: &mut BTreeMap>>, +) { + // A retired institution lends nothing: `Retire` does not vacate + // offices, so the incumbency stays on record, but a dissolved + // institution's grants stop reaching its office-holders here, the one + // site that turns an office into effective authority. + if is_retired(state, institution) { + return; + } + for (name, office) in offices { + if office.incumbent != Some(subject_id) { + continue; + } + let lent: BTreeSet = state + .authority + .get(&institution) + .into_iter() + .flatten() + .filter(|grant| office.delegated.contains(&grant.kind)) + .cloned() + .collect(); + held.entry(institution) + .or_default() + .insert(name.clone(), lent); + } +} + +/// What `delegated_authority` was before the index: every institution. +#[cfg(test)] +fn delegated_authority_by_scan( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap>> { + let mut held = BTreeMap::new(); + for (institution, offices) in &state.selection { + lend_offices(state, subject_id, *institution, offices, &mut held); + } + held +} + +/// The effective authority of one subject read straight from the partitions, +/// for the reducer paths that do not already hold a `ScopeComponents`. +fn subject_authority(state: &WorldState, subject_id: SubjectId) -> BTreeSet { + let empty = BTreeSet::new(); + effective_authority( + state.authority.get(&subject_id).unwrap_or(&empty), + &delegated_authority(state, subject_id), + ) +} + +/// The routes with an end at `place`, keyed by edge. +fn routes_at(state: &WorldState, place: EntityId) -> BTreeMap { + state + .edges + .indexed(place..=place) + .into_iter() + .map(|(_, edge_id)| (edge_id, state.edges[&edge_id].clone())) + .collect() +} + +#[cfg(test)] +fn routes_at_by_scan(state: &WorldState, place: EntityId) -> BTreeMap { + state + .edges + .iter() + .filter(|(_, record)| { + let (from, to) = record.endpoints(); + from == place || to == place + }) + .map(|(edge_id, record)| (*edge_id, record.clone())) + .collect() +} + +/// The channels `subject_id` controls, with their records. +fn channels_controlled_by( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap { + state + .channels + .indexed(subject_id..=subject_id) + .into_iter() + .map(|(_, entity_id)| (entity_id, state.channels[&entity_id].clone())) + .collect() +} + +#[cfg(test)] +fn channels_controlled_by_by_scan( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap { + state + .channels + .iter() + .filter(|(_, record)| record.controller == Some(subject_id)) + .map(|(entity_id, record)| (*entity_id, record.clone())) + .collect() +} + +/// The subjects with a pressure row from `source`. +fn pressure_holders(state: &WorldState, source: PressureSource) -> Vec { + state + .pressures + .indexed(source..=source) + .into_iter() + .map(|(_, target)| target) + .collect() +} + +#[cfg(test)] +fn pressure_holders_by_scan(state: &WorldState, source: PressureSource) -> Vec { + state + .pressures + .iter() + .filter(|(_, held)| held.contains_key(&source)) + .map(|(target, _)| *target) + .collect() +} + +fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponents { + let position = state.positions.get(&subject_id).copied(); + let routes = position + .map(|position| routes_at(state, position.place)) + .unwrap_or_default(); + ScopeComponents { + position, + routes, + holdings: state.holdings.get(&subject_id).cloned().unwrap_or_default(), + dependencies: state + .dependencies + .get(&subject_id) + .cloned() + .unwrap_or_default(), + authority: state + .authority + .get(&subject_id) + .cloned() + .unwrap_or_default(), + delegated: delegated_authority(state, subject_id), + knows: state + .knowledge_of(subject_id) + .map(|(fact, _)| *fact) + .collect(), + controls: channels_controlled_by(state, subject_id), + commitments: state + .commitments + .get(&subject_id) + .cloned() + .unwrap_or_default(), + } +} + +fn snapshot( + state: &WorldState, + journal: &journal::WorldJournal, +) -> Result { + // One pass over the causal record so each subject's own knowledge map can be + // stamped with the revision that minted each claim it holds. + let minted_at: BTreeMap = journal + .acted_events() + .flat_map(|event| { + event + .speech + .into_iter() + .chain(event.display) + .map(move |fact| (fact, event.revision)) + }) + .collect(); + // One pass over the causal record so each subject can be stamped with the + // revision of its own last exercised decision. `None` for a subject that + // never acted. + let last_acted_at: BTreeMap = + journal + .acted_events() + .fold(BTreeMap::new(), |mut acc, event| { + let entry = acc.entry(event.actor).or_insert(event.revision); + if event.revision > *entry { + *entry = event.revision; + } + acc + }); + let subjects = state + .subjects + .iter() + .map(|(subject_id, subject)| { + let affordances = state + .affordance_grants + .get(subject_id) + .cloned() + .unwrap_or_default(); + let components = scope_components(state, *subject_id); + let offices_held = components + .delegated + .iter() + .flat_map(|(institution, offices)| { + offices + .iter() + .map(move |(office, authority)| OfficeSnapshot { + institution: *institution, + office: office.clone(), + incumbent: Some(*subject_id), + authority: authority.clone(), + }) + }) + .collect(); + let offices_granted = state + .selection + .get(subject_id) + .into_iter() + .flatten() + .map(|(office, seat)| OfficeSnapshot { + institution: *subject_id, + office: office.clone(), + incumbent: seat.incumbent, + authority: state + .authority + .get(subject_id) + .into_iter() + .flatten() + .filter(|grant| seat.delegated.contains(&grant.kind)) + .cloned() + .collect(), + }) + .collect(); + let redress = state + .redress + .iter() + .filter(|(_, forum)| covers(state, forum.standing, Target::Subject(*subject_id))) + .map(|(grievance, forum)| ForumSnapshot { + grievance: grievance.clone(), + forum: forum.forum, + }) + .collect(); + // The sole perception surface, derived here rather than in a + // controller: a controller that recomputed perception would be a + // second answer to who heard what. + let mut knowledge: Vec = state + .knowledge_of(*subject_id) + .map(|(fact, held)| { + let record = state.facts.get(fact).ok_or_else(|| { + KernelError::Invariant("knowledge names no canonical fact".into()) + })?; + Ok(KnowledgeSnapshot { + fact: *fact, + statement: record.statement.clone(), + standing: match &record.standing { + FactStanding::Canonical { .. } => FactStandingView::Canonical, + FactStanding::Claimed { by } => FactStandingView::Claimed { by: *by }, + FactStanding::Ruled => FactStandingView::Canonical, + }, + confidence: held.confidence, + source: held.source, + minted_at: minted_at.get(fact).copied(), + acquired_at: held.acquired_at, + }) + }) + .collect::, KernelError>>()?; + knowledge.sort_by_key(|entry| (entry.minted_at, entry.fact)); + Ok(SubjectSnapshot { + id: *subject_id, + label: subject.label.clone(), + kind: subject.kind, + import_key: subject.import_key.clone(), + affordances, + position: components.position.map(|position| position.place), + retired: subject.retired, + offices_held, + offices_granted, + redress, + knowledge, + commitments: components + .commitments + .iter() + .map(|(key, commitment)| CommitmentSnapshot { + key: *key, + kind: commitment.kind, + counterparty: commitment.counterparty, + due: commitment.due, + period: commitment.period, + statement: commitment.statement.clone(), + past_due: commitment.due <= state.header.now, + }) + .collect(), + dependencies: components.dependencies.iter().copied().collect(), + components, + pressures: state + .pressures + .get(subject_id) + .into_iter() + .flatten() + .map(|(source, magnitude)| PressureSnapshot { + source: *source, + magnitude: *magnitude, + }) + .collect(), + last_acted_at: last_acted_at.get(subject_id).copied(), + }) + }) + .collect::, KernelError>>()?; + let places = state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Place) + .map(|(entity_id, record)| PlaceSnapshot { + id: *entity_id, + label: record.label.clone(), + container: record.container, + }) + .collect(); + let resources = state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Resource) + .map(|(entity_id, record)| ResourceSnapshot { + id: *entity_id, + label: record.label.clone(), + }) + .collect(); + let routes = state + .edges + .iter() + .map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + RouteSnapshot { + id: *edge_id, + label: record.label().to_owned(), + from, + to, + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + } + }) + .collect(); + let channels = state + .channels + .iter() + .map(|(entity_id, record)| ChannelSnapshot { + id: *entity_id, + reach: record.reach.clone(), + controller: record.controller, + }) + .collect(); + // Omniscient and independent of any subject's own knowledge projection: + // a fact nobody has been told or shown is still a row here, and a + // `Ruled` fact keeps its real standing rather than the `Canonical` + // collapse every subject-facing knowledge row applies. + let facts = state + .facts + .iter() + .map(|(fact_id, record)| FactSnapshot { + id: *fact_id, + statement: record.statement.clone(), + standing: match &record.standing { + FactStanding::Canonical { .. } => FactStandingView::Canonical, + FactStanding::Claimed { by } => FactStandingView::Claimed { by: *by }, + FactStanding::Ruled => FactStandingView::Ruled, + }, + known_by: state + .knowledge + .keys() + .filter(|(_, fact)| fact == fact_id) + .map(|(subject_id, _)| *subject_id) + .collect(), + }) + .collect(); + Ok(WorldSnapshot { + world_id: state.header.world_id, + revision: state.revision, + owner: state.header.owner.clone(), + title: state.header.title.clone(), + grammar: state.header.grammar.as_ref().map(GrammarBinding::identity), + subjects, + affordances: state + .affordance_catalog + .iter() + .map(|(affordance_id, entry)| AffordanceSnapshot { + id: *affordance_id, + entry: entry.clone(), + render_path: state + .header.grammar + .as_ref() + .and_then(|grammar| grammar.verb(&entry.kind.0)) + .map(|verb| verb.render_path), + }) + .collect(), + places, + resources, + routes, + channels, + facts, + now: state.header.now, + state_digest: state.state_digest.clone(), + last_commit_digest: state.last_commit_digest.clone(), + }) +} + +/// One affordance the kernel has already gated: the actor holds this entry, and `entry` is its catalog definition. It is the +/// only way to name an affordance to `action::exercise`, so a caller cannot +/// reach the invocation pipeline without passing the grant check first. +pub(crate) struct GrantedAffordance<'a> { + pub(crate) id: AffordanceId, + pub(crate) entry: &'a Affordance, +} + +/// The grant check, shared by `reduce` and `apply_effect`: the actor's own +/// entry set holds the affordance and the catalog defines it. It returns the +/// entry rather than a unit, so the gate and the lookup are one act, and it is +/// the only constructor of `GrantedAffordance`. Retire removes a subject's +/// grants, so a retired actor holds nothing. +fn require_granted<'a>( + state: &'a WorldState, + actor: SubjectId, + affordance: AffordanceId, +) -> Result, KernelError> { + if !state + .affordance_grants + .get(&actor) + .is_some_and(|granted| granted.contains(&affordance)) + { + return Err(KernelError::AffordanceDenied); + } + let entry = state + .affordance_catalog + .get(&affordance) + .ok_or_else(|| KernelError::Invariant("granted affordance has no entry".into()))?; + Ok(GrantedAffordance { + id: affordance, + entry, + }) +} + +/// Genesis may not rule or mint: only Play authors a `Ruled` fact or a `Mint`, +/// and Play only writes after genesis. One `Mismatch::RuledWithoutAuthority` +/// per `Ruled` fact and per `Mint`, and `Ok` if there are none. Called by +/// `prepare_creation` and by `WorldState::genesis` at replay. The resolver +/// stays actor-blind: this runs after resolution, never inside it. +fn forbid_rulings_at_genesis(resolved: &ResolvedPatch) -> Result<(), Vec> { + let mut mismatches = Vec::new(); + for declared in &resolved.facts { + if matches!(declared.fact.standing, FactStanding::Ruled) { + mismatches.push(Mismatch::RuledWithoutAuthority { + site: Site::Declaration(declared.handle.clone()), + }); + } + } + for (index, operation) in resolved.operations.iter().enumerate() { + if matches!(operation, ResolvedOp::Mint { .. }) { + mismatches.push(Mismatch::RuledWithoutAuthority { + site: Site::Operation(index), + }); + } + } + if mismatches.is_empty() { + Ok(()) + } else { + Err(mismatches) + } +} + +fn normalize_title(value: &str) -> Result { + let value = value.trim(); + if value.is_empty() { + Err(KernelError::EmptyTitle) + } else { + Ok(value.to_owned()) + } +} + +fn validate_principal(value: &PrincipalId) -> Result<(), KernelError> { + if value.0.trim().is_empty() || value.0.trim() != value.0 { + Err(KernelError::EmptyPrincipal) + } else { + Ok(()) + } +} + +/// The revision a non-genesis commit resolves to: one past `state.revision`, +/// which still holds the *previous* revision here, since `submit` only bumps +/// it after `apply_effect` returns. Genesis is not a caller: it resolves to +/// `state.revision` itself and computes that directly (PA.f49). +fn resolution_revision(state: &WorldState) -> Result { + state + .revision + .checked_add(1) + .ok_or_else(|| KernelError::Serialization("world revision overflow".into())) +} + +/// `command_id` is the band draw's only per-command term, so the arm that +/// re-derives an exercised decision needs the same one `reduce` drew from. +fn apply_effect( + state: &mut WorldState, + command_id: CommandId, + caller: &CallerId, + effect: &WorldEffect, +) -> Result<(), KernelError> { + // The admission rule `reduce` decided, re-decided here. + require_play(caller)?; + match effect { + WorldEffect::WorldCreated { .. } => { + return Err(KernelError::Invariant( + "world genesis cannot be applied as a mutable effect".into(), + )); + } + WorldEffect::PatchAdmitted { resolved } => { + let resolves_to = resolution_revision(state)?; + admit_resolved(state, resolved, resolves_to)?; + } + WorldEffect::Acted { invocation, event } => { + let granted = require_granted(state, event.actor, invocation.affordance)?; + // The whole event is re-derived by the function that produced the + // honest one, so a forged band, operation, magnitude, minted claim, + // or utterance is one comparison rather than a clause apiece. + let derived = + action::exercise(state, command_id, event.actor, &granted, invocation)?; + if derived != *event { + return Err(KernelError::Invariant( + "acted effect does not derive from the actor's grants".into(), + )); + } + if !event.effects.is_empty() { + // `derived != *event` above already proved `event.revision` is + // exactly what `resolution_revision(state)` would compute right + // now; read it back rather than computing it a second time. + apply_operations(state, &event.effects, &[], event.revision)?; + } + } + WorldEffect::TimeAdvanced { + minutes, + to, + motion, + } => { + let derived_to = state + .header.now + .checked_add(*minutes) + .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; + // The whole motion is re-derived rather than trusted field by + // field, so a forged fulfilment, magnitude, row, and target are one + // comparison. + if derived_to != *to || clock::derive_motion(state, derived_to) != *motion { + return Err(KernelError::Invariant( + "time effect does not derive from the world clock".into(), + )); + } + state.header.get_mut().now = *to; + for rolled in &motion.fulfilled { + let commitment = state + .commitments + .get_mut(&rolled.subject) + .and_then(|held| held.get_mut(&rolled.key)) + .ok_or_else(|| { + KernelError::Invariant("a fulfilled routine has no commitment".into()) + })?; + commitment.due = rolled.next_due; + } + // No inner map is ever left empty, because `derive_motion` emits no + // zero magnitude. + for written in &motion.pressed { + state + .pressures + .entry(written.target) + .or_default() + .insert(written.source, written.magnitude); + } + } + } + Ok(()) +} + +fn digest(value: &T) -> Result { + let bytes = rmp_serde::to_vec_named(value) + .map_err(|error| KernelError::Serialization(error.to_string()))?; + Ok(format!("sha256:{:x}", Sha256::digest(bytes))) +} + +fn commit_digest(commit: &WorldCommit) -> Result { + let mut value = commit.clone(); + value.digest.clear(); + digest(&value) +} + +#[cfg(test)] +mod tests { + use super::patch::kernel_speak_grant; + use super::*; + + /// What a committed event actually asserted, read from the one readable + /// home of an utterance: `facts[fact].statement`. The committed event's + /// own `AssertClaim` effect carries the same bytes as the replay witness, + /// but no projection reads that copy; `facts` is the surface. + pub(crate) fn spoken<'a>(state: &'a WorldState, event: &DecisionEvent) -> Option<&'a str> { + event + .speech + .and_then(|fact| state.facts.get(&fact)) + .map(|record| record.statement.as_str()) + } + + pub(crate) fn owner() -> PrincipalId { + PrincipalId::new("owner@example.test") + } + + pub(crate) fn human_principal() -> PrincipalId { + PrincipalId::new("human@example.test") + } + + pub(crate) fn auth_principal(principal: PrincipalId) -> AuthenticatedCaller { + AuthenticatedCaller::fixture(CallerId::Principal(principal)) + } + + pub(crate) fn subject( + handle: &str, + label: &str, + kind: SubjectKind, + ) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + affordances: kernel_speak_grant(), + // The fixture world is one room. Co-located speech needs a place to + // fill, so every fixture subject stands in the commons. + position: Some(Ref::Draft(DraftHandle::new(COMMONS))), + import_key: None, + }) + } + + /// The one place the base fixture world declares. + pub(crate) const COMMONS: &str = "commons"; + + /// How many entities the base fixture world admits at genesis: the commons + /// and nothing else. A patch-lane test that proves a rejection allocated + /// nothing compares against this rather than against zero. + pub(crate) const FIXTURE_ENTITIES: usize = 1; + + /// The committed Speak entry. A post-genesis declaration grants it by + /// canonical reference, like every other structure a previous commit + /// allocated: the kernel synthesizes the entry once, at genesis. + pub(crate) fn speak_entry(kernel: &WorldKernel) -> Ref { + Ref::Existing( + *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "speak") + .map(|(affordance_id, _)| affordance_id) + .expect("genesis admits the kernel Speak entry"), + ) + } + + /// A catalog entry by kind name. An affordance id names an entry, not a + /// subject's copy of one, so a test that needs an entry a scope does not + /// hold asks for it by name rather than by list position. + pub(crate) fn affordance_named(snapshot: &WorldSnapshot, kind: &str) -> AffordanceId { + snapshot + .affordances + .iter() + .find(|entry| entry.entry.kind.0 == kind) + .map(|entry| entry.id) + .expect("the fixture world declares this affordance") + } + + pub(crate) fn creation(title: &str) -> CreateWorld { + CreateWorld { + owner: owner(), + title: title.into(), + patch: WorldPatch { + operations: Vec::new(), + evidence: Vec::new(), + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(COMMONS), + label: "The Commons".into(), + kind: EntityKind::Place, + container: None, + }), + // A second, world-declared entry granted to exactly one + // subject, so the fixture world has more than one verb and + // grant sets differ between scopes. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("convene"), + kind: AffordanceKindName("convene".into()), + roles: Vec::new(), + // A speech-carrying entry must name exactly one + // audience for the lowering to read. + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + subject( + "human", + "The Human", + SubjectKind::Person, + ), + subject( + "persona", + "The Witness", + SubjectKind::Person, + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("operator"), + label: "The Council".into(), + kind: SubjectKind::Institution, + affordances: kernel_speak_grant() + .into_iter() + .chain(std::iter::once(Ref::Draft(DraftHandle::new("convene")))) + .collect(), + position: Some(Ref::Draft(DraftHandle::new(COMMONS))), + import_key: None, + }), + ], + }, + grammar: None, + } + } + + pub(crate) fn command( + snapshot: &WorldSnapshot, + caller: CallerId, + body: CommandBody, + ) -> CommandEnvelope { + CommandEnvelope { + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller, + body, + } + } + + /// The smallest Play command that commits: a one-minute clock advance. + pub(crate) fn tick_body(minutes: u32) -> CommandBody { + CommandBody::AdvanceTime { + minutes: TickMinutes::new(minutes).expect("a valid span"), + } + } + + pub(crate) fn play_command(snapshot: &WorldSnapshot, body: CommandBody) -> CommandEnvelope { + command(snapshot, CallerId::Play, body) + } + + pub(crate) fn submit_play( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + body: CommandBody, + ) -> CommitReceipt { + kernel + .submit( + command( + snapshot, + CallerId::Play, + body, + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap() + } + + /// The canonical IDs of the shared topology fixture: three places, four + /// routes with every access and open combination the operations read, and one + /// subject standing in the yard. + pub(crate) struct Topology { + pub(crate) yard: EntityId, + pub(crate) road: EntityId, + pub(crate) gate: EntityId, + pub(crate) ramp: EdgeId, + pub(crate) shutter: EdgeId, + pub(crate) toll: EdgeId, + pub(crate) span: EdgeId, + pub(crate) walker: SubjectId, + } + + fn place(handle: &str, label: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: None, + }) + } + + fn way( + handle: &str, + label: &str, + from: &str, + to: &str, + access: AccessKind, + cost: u32, + ) -> Declaration { + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + from: Ref::Draft(DraftHandle::new(from)), + to: Ref::Draft(DraftHandle::new(to)), + access, + cost: Cost(cost), + }) + } + + pub(crate) fn topology_patch(speak: Ref) -> WorldPatch { + WorldPatch { + declarations: vec![ + place("yard", "The Cavity Yard"), + place("road", "The Rhythm Road"), + place("gate", "The Rain Gate"), + way( + "ramp", + "The Yard Ramp", + "yard", + "road", + AccessKind::Public, + 12, + ), + way( + "shutter", + "The Yard Shutter", + "yard", + "gate", + AccessKind::Public, + 5, + ), + way( + "toll", + "The Toll Stair", + "yard", + "gate", + AccessKind::Restricted { + requires: AuthorityKindName(ADMIT_KIND.into()), + }, + 4, + ), + way( + "span", + "The Western Span", + "road", + "gate", + AccessKind::Public, + 7, + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("walker"), + label: "The Walker".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Draft(DraftHandle::new("yard"))), + import_key: None, + }), + ], + // A route that should start closed is declared and closed in one + // patch, so `open` keeps a single writer family. + operations: vec![ComponentOp::CloseRoute { + route: Ref::Draft(DraftHandle::new("shutter")), + }], + evidence: Vec::new(), + } + } + + pub(crate) fn admit_topology(kernel: &mut WorldKernel) -> Topology { + let before = kernel.snapshot().unwrap(); + let receipt = submit_play( + kernel, + &before, + CommandBody::AdmitPatch { + patch: topology_patch(speak_entry(kernel)), + }, + ); + assert!(receipt.resulting_revision > 0); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared place") + .0 + }; + let edge = |label: &str| { + *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == label) + .expect("a declared route") + .0 + }; + Topology { + yard: entity("The Cavity Yard"), + road: entity("The Rhythm Road"), + gate: entity("The Rain Gate"), + ramp: edge("The Yard Ramp"), + shutter: edge("The Yard Shutter"), + toll: edge("The Toll Stair"), + span: edge("The Western Span"), + walker: *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Walker") + .expect("the walker is admitted") + .0, + } + } + + /// The canonical IDs of the custody fixture: two resources and two holder + /// subjects standing in the topology, with the first holder carrying an + /// evidenced opening balance. + pub(crate) struct Custody { + pub(crate) tithe: EntityId, + pub(crate) ingot: EntityId, + pub(crate) holder: SubjectId, + pub(crate) counterparty: SubjectId, + } + + /// The seed world's authority kinds, offices, and grievance. They are world + /// data: the kernel compares these strings and reads them no other way. + pub(crate) const LEVY_KIND: &str = "levy"; + pub(crate) const ADMIT_KIND: &str = "admit"; + pub(crate) const COMMAND_KIND: &str = "command"; + pub(crate) const JUDGE_KIND: &str = "judge"; + pub(crate) const WARDEN_OFFICE: &str = "warden"; + pub(crate) const BAILIFF_OFFICE: &str = "bailiff"; + pub(crate) const SEIZURE_GRIEVANCE: &str = "seizure"; + + pub(crate) const TITHE_RECEIPT: &str = "receipt:rhythm-tithe-census"; + pub(crate) const OPENING_BALANCE: u64 = 7; + + pub(crate) fn resource(handle: &str, label: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Resource, + container: None, + }) + } + + fn holder(handle: &str, label: &str, place: EntityId, speak: Ref) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Institution, + affordances: std::iter::once(speak) + .chain(carry_affordances().into_iter().map(|declaration| { + let Declaration::Affordance(entry) = declaration else { + unreachable!("carry_affordances declares only affordances") + }; + Ref::Draft(entry.handle) + })) + .collect(), + position: Some(Ref::Existing(place)), + import_key: None, + }) + } + + pub(crate) const CARRY_HANDLE: &str = "carry"; + + /// The worked affordances for the action lane. Every one carries the same + /// four roles and the same bounded `Transfer` slot, so a test varies exactly + /// one thing — a precondition or a band table — by naming a different entry + /// rather than by reaching into a committed catalog. The catalog is + /// Draft-only, so authoring it is how a world gets a verb. + fn carry_roles() -> Vec { + vec![ + RoleSpec { + role: Role("from".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("recipient".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("place".into()), + kind: RefKind::Entity(EntityKind::Place), + }, + RoleSpec { + role: Role("resource".into()), + kind: RefKind::Entity(EntityKind::Resource), + }, + ] + } + + /// Two slots on disjoint bands: band 0 names only the transfer, band 1 only + /// the consume. Both slots are proposed on every invocation, so the entry + /// separates what a proposer offered from what a draw admitted. + fn split_variant() -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("carry-split"), + kind: AffordanceKindName("carry_split".into()), + roles: carry_roles(), + preconditions: Vec::new(), + effect_slots: vec![ + EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: vec![ + Role("from".into()), + Role("recipient".into()), + Role("resource".into()), + ], + bounds: Bounds::Quantity(Quantity(3)), + }, + EffectSlot { + op_kind: ComponentOpKind::Consume, + roles: vec![Role("from".into()), Role("resource".into())], + bounds: Bounds::Quantity(Quantity(3)), + }, + ], + outcome_bands: vec![ + OutcomeBand { + weight: 1, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: vec![1], + }, + ], + carries_speech: false, + }) + } + + fn carry_variant( + handle: &str, + kind: &str, + preconditions: Vec, + outcome_bands: Vec, + ) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles: carry_roles(), + preconditions, + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: vec![ + Role("from".into()), + Role("recipient".into()), + Role("resource".into()), + ], + bounds: Bounds::Quantity(Quantity(3)), + }], + outcome_bands, + carries_speech: false, + }) + } + + fn certain_band() -> Vec { + vec![OutcomeBand { + weight: 1, + effects: vec![0], + }] + } + + fn place_role() -> Role { + Role("place".into()) + } + + /// Carry, and five variants that each move one dial: a holding demand above + /// the opening balance, a reach budget short of the two-hop path, one that + /// covers it, a band that names no effect, and three equally weighted bands. + pub(crate) fn carry_affordances() -> Vec { + vec![ + carry_variant( + CARRY_HANDLE, + "carry", + vec![ + Precondition::Present { at: place_role() }, + Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(1), + }, + ], + certain_band(), + ), + carry_variant( + "carry-greedy", + "carry_greedy", + vec![ + Precondition::Present { at: place_role() }, + Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(OPENING_BALANCE + 1), + }, + ], + certain_band(), + ), + carry_variant( + "carry-holds", + "carry_holds", + vec![Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(1), + }], + certain_band(), + ), + carry_variant( + "carry-near", + "carry_near", + vec![Precondition::Reachable { + to: place_role(), + within: Cost(NEAR_REACH), + }], + certain_band(), + ), + carry_variant( + "carry-far", + "carry_far", + vec![Precondition::Reachable { + to: place_role(), + within: Cost(FAR_REACH), + }], + certain_band(), + ), + carry_variant( + "carry-idle", + "carry_idle", + Vec::new(), + vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + ), + carry_variant( + "carry-chance", + "carry_chance", + Vec::new(), + vec![ + OutcomeBand { + weight: 1, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + ], + ), + split_variant(), + ] + } + + /// Yard to gate over the open shutter alone. + pub(crate) const NEAR_REACH: u32 = 5; + /// Yard to gate over the ramp and the span, which is the only open public + /// path while the shutter is closed. + pub(crate) const FAR_REACH: u32 = 19; + + /// Declarations and evidence are Draft-only, so the resources, the holders, + /// and the one evidenced `Admit` that creates the opening balance all land + /// before activation. There is no holdings declaration field: quantity is + /// created by `Admit` and by nothing else, in this lane as in every other. + pub(crate) fn custody_patch(topology: &Topology, speak: Ref) -> WorldPatch { + WorldPatch { + declarations: carry_affordances() + .into_iter() + .chain([ + resource("tithe", "The Rhythm Tithe"), + resource("ingot", "The Cut Ingot"), + holder("clerk", "The Ledger Clerk", topology.yard, speak.clone()), + holder("keeper", "The Gate Keeper", topology.gate, speak), + ]) + .collect(), + operations: vec![ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + } + } + + pub(crate) fn admit_custody(kernel: &mut WorldKernel, topology: &Topology) -> Custody { + let before = kernel.snapshot().unwrap(); + let receipt = submit_play( + kernel, + &before, + CommandBody::AdmitPatch { + patch: custody_patch(topology, speak_entry(kernel)), + }, + ); + assert!(receipt.resulting_revision > 0); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared resource") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared holder") + .0 + }; + Custody { + tithe: entity("The Rhythm Tithe"), + ingot: entity("The Cut Ingot"), + holder: subject("The Ledger Clerk"), + counterparty: subject("The Gate Keeper"), + } + } + + /// Topology, custody, then activation: everything a custody test needs, in + /// the one order the phase rules allow. + pub(crate) fn custody_world(kernel: &mut WorldKernel) -> (Topology, Custody, WorldSnapshot) { + let topology = admit_topology(kernel); + let custody = admit_custody(kernel, &topology); + let active = kernel.snapshot().unwrap(); + (topology, custody, active) + } + + /// The canonical IDs of the civic fixture: a hall containing a chamber, an + /// institution holding jurisdiction over the hall, a person who holds that + /// jurisdiction only through an office, a person and a resource inside the + /// hall, and a person standing outside it. + pub(crate) struct Civic { + pub(crate) hall: EntityId, + pub(crate) chamber: EntityId, + pub(crate) passage: EdgeId, + pub(crate) causeway: EdgeId, + pub(crate) postern: EdgeId, + pub(crate) treasury: SubjectId, + pub(crate) reeve: SubjectId, + pub(crate) farmer: SubjectId, + pub(crate) outsider: SubjectId, + pub(crate) grain: EntityId, + } + + pub(crate) fn authority_kind(name: &str) -> AuthorityKindName { + AuthorityKindName(name.into()) + } + + pub(crate) fn office(name: &str) -> OfficeName { + OfficeName(name.into()) + } + + pub(crate) fn grievance(name: &str) -> GrievanceKindName { + GrievanceKindName(name.into()) + } + + pub(crate) fn over_place(place: EntityId) -> AuthorityTargetRef { + AuthorityTargetRef::PlaceSubtree(Ref::Existing(place)) + } + + pub(crate) fn over_subject(subject_id: SubjectId) -> AuthorityTargetRef { + AuthorityTargetRef::Subject(Ref::Existing(subject_id)) + } + + pub(crate) fn grant_of(kind: &str, over: AuthorityTargetRef) -> AuthorityGrantRef { + AuthorityGrantRef { + kind: authority_kind(kind), + over, + } + } + + pub(crate) fn grant_to(holder: SubjectId, kind: &str, over: AuthorityTargetRef) -> ComponentOp { + ComponentOp::GrantAuthority { + holder: Ref::Existing(holder), + grant: grant_of(kind, over), + } + } + + /// Seven world-authored civic entries. The kernel builds none of them; + /// each is a worked example of what a seed author writes to make the + /// political layer playable rather than administratively imposed. + fn civic_affordances() -> Vec { + let entry = |handle: &str, + kind: &str, + roles: Vec, + preconditions: Vec, + effect_slots: Vec, + outcome_bands: Vec, + carries_speech: bool| { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles, + preconditions, + effect_slots, + outcome_bands, + carries_speech, + }) + }; + let role = |name: &str, kind: RefKind| RoleSpec { + role: Role(name.into()), + kind, + }; + let slot = |op_kind: ComponentOpKind, roles: Vec<&str>, bounds: Bounds| EffectSlot { + op_kind, + roles: roles.into_iter().map(|name| Role(name.into())).collect(), + bounds, + }; + let authorized = |over: &str, kind: &str| Precondition::Authorized { + over: Role(over.into()), + kind: authority_kind(kind), + }; + vec![ + // The payee is the reserved `actor` role, so an authorized + // collector cannot lawfully take a tax and send it to a friend. + entry( + "levy", + "levy", + vec![ + role("payer", RefKind::Subject(None)), + role("resource", RefKind::Entity(EntityKind::Resource)), + ], + vec![authorized("payer", LEVY_KIND)], + vec![slot( + ComponentOpKind::Transfer, + vec!["payer", "actor", "resource"], + Bounds::Quantity(Quantity(10)), + )], + certain_band(), + false, + ), + entry( + "delegate", + "delegate", + vec![ + role("deputy", RefKind::Subject(None)), + role("ground", RefKind::Entity(EntityKind::Place)), + ], + // The precondition names one kind and the slot grants another, + // so the monotonicity rule is the check that decides whether + // the granted authority is one the granter holds. + vec![authorized("ground", COMMAND_KIND)], + vec![slot( + ComponentOpKind::GrantAuthority { + kind: authority_kind(LEVY_KIND), + }, + vec!["deputy", "ground"], + Bounds::None, + )], + certain_band(), + false, + ), + // Isolates the action-lane's revocation envelope: no separate + // precondition, so a rejection here can only be + // `DelegationNotMonotone`. + entry( + "revoke", + "revoke", + vec![ + role("holder", RefKind::Subject(None)), + role("ground", RefKind::Entity(EntityKind::Place)), + ], + Vec::new(), + vec![slot( + ComponentOpKind::RevokeAuthority { + kind: authority_kind(LEVY_KIND), + }, + vec!["holder", "ground"], + Bounds::None, + )], + certain_band(), + false, + ), + entry( + "deploy", + "deploy", + vec![ + role("subordinate", RefKind::Subject(None)), + role("via", RefKind::Edge(patch::EdgeKind::Route)), + ], + vec![authorized("subordinate", COMMAND_KIND)], + vec![slot( + ComponentOpKind::Relocate, + vec!["subordinate", "via"], + Bounds::None, + )], + certain_band(), + false, + ), + // The first affordance whose effect changes shared topology under a + // legitimacy check; the second band is the interdiction that fails. + entry( + "sanction", + "sanction", + vec![role("road", RefKind::Edge(patch::EdgeKind::Route))], + vec![authorized("road", COMMAND_KIND)], + vec![slot( + ComponentOpKind::CloseRoute, + vec!["road"], + Bounds::None, + )], + vec![ + OutcomeBand { + weight: 3, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + ], + false, + ), + // Succession is an act someone performs under authority, not a + // declared method string. + entry( + "appoint", + "appoint", + vec![ + role("institution", RefKind::Subject(None)), + role("candidate", RefKind::Subject(None)), + ], + vec![authorized("institution", COMMAND_KIND)], + vec![slot( + ComponentOpKind::InstallIncumbent { + office: office(BAILIFF_OFFICE), + }, + vec!["institution", "candidate"], + Bounds::None, + )], + certain_band(), + false, + ), + // The reader that keeps `Redress` from being decorative. + entry( + "petition", + "petition", + Vec::new(), + vec![ + Precondition::HasStanding { + grievance: grievance(SEIZURE_GRIEVANCE), + }, + // A petition is spoken, so the entry names where it lands. + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + ], + Vec::new(), + vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + true, + ), + ] + } + + fn civic_grants(handles: &[&str], speak: &Ref) -> BTreeSet> { + std::iter::once(speak.clone()) + .chain( + handles + .iter() + .map(|handle| Ref::Draft(DraftHandle::new(*handle))), + ) + .collect() + } + + pub(crate) fn civic_patch(topology: &Topology, speak: Ref) -> WorldPatch { + let person = |handle: &str, label: &str, place: Ref, handles: &[&str]| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + affordances: civic_grants(handles, &speak), + position: Some(place), + import_key: None, + }) + }; + let declarations = civic_affordances() + .into_iter() + .chain([ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Tithe Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("chamber"), + label: "The Counting Chamber".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + resource("grain", "The Winter Grain"), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("passage"), + label: "The Hall Passage".into(), + from: Ref::Draft(DraftHandle::new("chamber")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(3), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("causeway"), + label: "The Hall Causeway".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Existing(topology.road), + access: AccessKind::Public, + cost: Cost(6), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("postern"), + label: "The Hall Postern".into(), + from: Ref::Existing(topology.yard), + to: Ref::Draft(DraftHandle::new("chamber")), + access: AccessKind::Restricted { + requires: authority_kind(ADMIT_KIND), + }, + cost: Cost(2), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("treasury"), + label: "The Tithe Treasury".into(), + kind: SubjectKind::Institution, + affordances: civic_grants( + &[ + "levy", "delegate", "deploy", "sanction", "appoint", "revoke", + ], + &speak, + ), + position: Some(Ref::Draft(DraftHandle::new("hall"))), + import_key: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("reeve"), + label: "The Hall Reeve".into(), + kind: SubjectKind::Person, + affordances: civic_grants( + &["levy", "delegate", "petition", "sanction"], + &speak, + ), + position: Some(Ref::Draft(DraftHandle::new("chamber"))), + import_key: None, + }), + person( + "farmer", + "The Winter Farmer", + Ref::Draft(DraftHandle::new("chamber")), + &["levy", "petition", "revoke"], + ), + person( + "outsider", + "The Road Pedlar", + Ref::Existing(topology.road), + &["levy", "petition"], + ), + // Deliberately unplaced: a place-subtree jurisdiction covers a + // subject through its position, so a subject with none is + // covered by nothing. + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("nowhere"), + label: "The Unhoused".into(), + kind: SubjectKind::Person, + affordances: civic_grants(&["levy", "petition"], &speak), + position: None, + import_key: None, + }), + ]) + .collect(); + WorldPatch { + declarations, + operations: vec![ + ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("farmer")), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }, + ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("outsider")), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }, + ComponentOp::GrantAuthority { + holder: Ref::Draft(DraftHandle::new("treasury")), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "hall", + ))), + }, + }, + ComponentOp::GrantAuthority { + holder: Ref::Draft(DraftHandle::new("treasury")), + grant: AuthorityGrantRef { + kind: authority_kind(COMMAND_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "hall", + ))), + }, + }, + ComponentOp::OpenOffice { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }, + ComponentOp::OpenOffice { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(BAILIFF_OFFICE), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(WARDEN_OFFICE), + incumbent: Ref::Draft(DraftHandle::new("reeve")), + }, + ComponentOp::OpenForum { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: Ref::Draft(DraftHandle::new("treasury")), + standing: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "chamber", + ))), + }, + ], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + } + } + + pub(crate) fn admit_civic(kernel: &mut WorldKernel, topology: &Topology) -> Civic { + let before = kernel.snapshot().unwrap(); + let receipt = submit_play( + kernel, + &before, + CommandBody::AdmitPatch { + patch: civic_patch(topology, speak_entry(kernel)), + }, + ); + assert!(receipt.resulting_revision > 0); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared entity") + .0 + }; + let edge = |label: &str| { + *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == label) + .expect("a declared route") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared subject") + .0 + }; + Civic { + hall: entity("The Tithe Hall"), + chamber: entity("The Counting Chamber"), + grain: entity("The Winter Grain"), + passage: edge("The Hall Passage"), + causeway: edge("The Hall Causeway"), + postern: edge("The Hall Postern"), + treasury: subject("The Tithe Treasury"), + reeve: subject("The Hall Reeve"), + farmer: subject("The Winter Farmer"), + outsider: subject("The Road Pedlar"), + } + } + + /// Topology, the civic subgraph, then activation. + pub(crate) fn civic_world(kernel: &mut WorldKernel) -> (Topology, Civic, WorldSnapshot) { + let topology = admit_topology(kernel); + let civic = admit_civic(kernel, &topology); + let active = kernel.snapshot().unwrap(); + (topology, civic, active) + } + + /// The speech bench: a hall containing a yard, a speaker and a listener in + /// the hall, a bystander in the yard, a stranger nowhere, one evidenced + /// canonical fact, and a horn that carries over the hall subtree. + pub(crate) struct Speech { + pub(crate) hall: EntityId, + pub(crate) yard: EntityId, + pub(crate) speaker: SubjectId, + pub(crate) listener: SubjectId, + pub(crate) bystander: SubjectId, + pub(crate) stranger: SubjectId, + pub(crate) flood: EntityId, + pub(crate) horn: EntityId, + pub(crate) whisper: AffordanceId, + pub(crate) proclaim: AffordanceId, + pub(crate) recant: AffordanceId, + pub(crate) stair: EdgeId, + } + + pub(crate) const FLOOD_STATEMENT: &str = "The lower hinge is flooding."; + pub(crate) const FLOOD_EVIDENCE: &str = "vault:flood-survey"; + + /// A world with one room inside another, four subjects, a fact, and a + /// channel. Two world-declared speaking entries exercise both audiences: an + /// addressed co-located `whisper` and a channel-bound `proclaim`. + pub(crate) fn speech_world(kernel: &mut WorldKernel) -> (Speech, WorldSnapshot) { + let before = kernel.snapshot().unwrap(); + let speak = speak_entry(kernel); + let person = |handle: &str, label: &str, place: Option<&str>| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([ + speak.clone(), + Ref::Draft(DraftHandle::new("whisper")), + Ref::Draft(DraftHandle::new("proclaim")), + Ref::Draft(DraftHandle::new("recant")), + ]), + position: place.map(|place| Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + }; + submit_play( + kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + evidence: vec![EvidenceRef::new(FLOOD_EVIDENCE)], + operations: Vec::new(), + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Long Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("yard"), + label: "The Cavity Yard".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("stair"), + label: "The Yard Stair".into(), + from: Ref::Draft(DraftHandle::new("yard")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("flood"), + label: "the flooding of the lower hinge".into(), + statement: Statement::new(FLOOD_STATEMENT).unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(FLOOD_EVIDENCE), + }, + }), + // Addressed speech: the audience is still the room. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("whisper"), + kind: AffordanceKindName("whisper".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::CanReach { + subject: Role("target".into()), + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("proclaim"), + kind: AffordanceKindName("proclaim".into()), + roles: vec![RoleSpec { + role: Role("channel".into()), + kind: RefKind::Entity(EntityKind::Channel), + }], + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Channel(Role("channel".into())), + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + // `Knows` plus the one knowledge operation an affordance + // may propose: a subject may only unremember what it + // holds with certainty. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("recant"), + kind: AffordanceKindName("recant".into()), + roles: vec![RoleSpec { + role: Role("fact".into()), + kind: RefKind::Entity(EntityKind::Fact), + }], + preconditions: vec![Precondition::Knows { + fact: Role("fact".into()), + at_least: Confidence::Certain, + }], + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Forget, + roles: vec![Role("actor".into()), Role("fact".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + person("speaker", "The Hall Speaker", Some("hall")), + person("listener", "The Hall Listener", Some("hall")), + person("bystander", "The Yard Bystander", Some("yard")), + person("stranger", "The Placeless Stranger", None), + Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("horn"), + label: "The Temple Horn".into(), + reach: ReachRef::Place(Ref::Draft(DraftHandle::new("hall"))), + controller: Some(Ref::Draft(DraftHandle::new("speaker"))), + }), + ], + }, + }, + ); + let active = kernel.snapshot().unwrap(); + let place = |label: &str| { + active + .places + .iter() + .find(|place| place.label == label) + .expect("the declared place") + .id + }; + let who = |label: &str| { + active + .subjects + .iter() + .find(|subject| subject.label == label) + .expect("the declared subject") + .id + }; + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == FLOOD_STATEMENT) + .expect("the declared fact") + .0; + let horn = *kernel + .state + .channels + .keys() + .next() + .expect("the declared channel"); + ( + Speech { + hall: place("The Long Hall"), + yard: place("The Cavity Yard"), + speaker: who("The Hall Speaker"), + listener: who("The Hall Listener"), + bystander: who("The Yard Bystander"), + stranger: who("The Placeless Stranger"), + flood: fact, + horn, + whisper: affordance_named(&active, "whisper"), + proclaim: affordance_named(&active, "proclaim"), + recant: affordance_named(&active, "recant"), + stair: active.routes[0].id, + }, + active, + ) + } + + /// Submits as Play and returns the complete mismatch set. + pub(crate) fn reject_play( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + body: CommandBody, + ) -> Vec { + let error = kernel + .submit( + command( + snapshot, + CallerId::Play, + body, + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + mismatches + } + + pub(crate) fn operations(operations: Vec) -> CommandBody { + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + }, + } + } + + /// The first entry the subject holds, in id order. + pub(crate) fn first_grant(snapshot: &WorldSnapshot, subject_id: SubjectId) -> AffordanceId { + *snapshot + .subjects + .iter() + .find(|subject| subject.id == subject_id) + .expect("the subject exists") + .affordances + .first() + .expect("the subject holds an affordance") + } + + /// The one subject with this label; the fixture's three are The Human, + /// The Witness and The Council. + pub(crate) fn subject_by_label(state: &WorldState, label: &str) -> SubjectId { + state + .subjects + .iter() + .find(|(_, subject)| subject.label == label) + .map(|(subject_id, _)| *subject_id) + .expect("a subject has this label") + } + + pub(crate) fn speak(affordance: AffordanceId, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + /// The one door for an act in tests: Play submits `Act` for the actor. + pub(crate) fn act_as( + kernel: &mut WorldKernel, + caller: CallerId, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + caller.clone(), + CommandBody::Act { actor, invocation }, + ), + &AuthenticatedCaller::fixture(caller), + ) + } + + pub(crate) fn play_caller() -> CallerId { + CallerId::Play + } + + pub(crate) fn act( + kernel: &mut WorldKernel, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + act_as( + kernel, + CallerId::Play, + actor, + invocation, + ) + } + + #[test] + fn create_submit_restart_and_replay_are_exact() { + let creation = creation("First"); + let (mut kernel, creation_receipt) = + WorldKernel::create(creation.clone(), &auth_principal(owner())).unwrap(); + let active = kernel.snapshot().unwrap(); + let operator = subject_by_label(&kernel.state, "The Council"); + let command = command( + &active, + play_caller(), + CommandBody::Act { + actor: operator, + invocation: speak(first_grant(&active, operator), "The vote carries."), + }, + ); + kernel + .submit(command.clone(), &AuthenticatedCaller::verified_play()) + .unwrap(); + let accepted = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + + // The same creation names the same world, with the same receipt. + let (_, retried) = WorldKernel::create(creation, &auth_principal(owner())).unwrap(); + assert_eq!(retried, creation_receipt); + + // The export is the whole world: its reopening is equal, re-exports + // byte for byte, and the applied command is stale in it. + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!(reopened.export().unwrap(), exported); + assert!(matches!( + reopened.submit(command, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + + // The next command gives equal receipts and equal worlds on both. + let next = play_command(&accepted, tick_body(1)); + let original_receipt = kernel + .submit(next.clone(), &AuthenticatedCaller::verified_play()) + .unwrap(); + let reopened_receipt = reopened + .submit(next, &AuthenticatedCaller::verified_play()) + .unwrap(); + assert_eq!(original_receipt, reopened_receipt); + assert_eq!(kernel.snapshot().unwrap(), reopened.snapshot().unwrap()); + assert_eq!(kernel.export().unwrap(), reopened.export().unwrap()); + } + + #[test] + fn a_stale_command_is_a_revision_mismatch() { + let (mut kernel, _) = WorldKernel::create(creation("Still"), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + assert!(submit_play(&mut kernel, &genesis, tick_body(1)).resulting_revision > 0); + let after = kernel.snapshot().unwrap(); + // The very command that was applied, resubmitted: there is no retry + // identity, so it is stale like any other. + let stale = play_command(&genesis, tick_body(1)); + assert!(matches!( + kernel.submit(stale, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + assert_eq!(kernel.snapshot().unwrap(), after); + assert_eq!(kernel.journal.commit_count(), 2); + } + + #[test] + fn ids_are_derived_from_the_command() { + let create = |title: &str| { + WorldKernel::create(creation(title), &auth_principal(owner())).unwrap() + }; + let (mut kernel, receipt) = create("Same"); + let (twin, twin_receipt) = create("Same"); + assert_eq!(receipt, twin_receipt); + assert_eq!(kernel.state.header.world_id, twin.state.header.world_id); + assert_eq!(receipt.world_id, WorldId::of(receipt.command_id)); + let (other, _) = create("Other"); + assert_ne!(kernel.state.header.world_id, other.state.header.world_id); + + // The same patch at two revisions is two commands, so the entity it + // declares is minted twice under two ids. + let patch = WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cairn"), + label: "A Cairn".into(), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }; + let mut ids = BTreeSet::new(); + for _ in 0..2 { + let snapshot = kernel.snapshot().unwrap(); + let envelope = play_command(&snapshot, CommandBody::AdmitPatch { patch: patch.clone() }); + let expected = envelope.id(); + let receipt = kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap(); + assert_eq!(receipt.command_id, expected); + assert!(ids.insert(receipt.command_id), "two commands share an id"); + } + let cairns = kernel + .state + .entities + .values() + .filter(|entity| entity.label == "A Cairn") + .count(); + assert_eq!(cairns, 2); + } + + #[test] + fn invalid_seed_never_allocates_a_world() { + let mut invalid = creation("Nope"); + invalid.patch.declarations[3] = invalid.patch.declarations[2].clone(); + let Err(KernelError::PatchRejected(rejected)) = + WorldKernel::create(invalid, &auth_principal(owner())) + else { + panic!("expected a rejected creation patch"); + }; + assert_eq!( + rejected, + vec![Mismatch::DuplicateHandle { + handle: DraftHandle::new("human") + }] + ); + assert!( + WorldKernel::create(creation("Valid"), + &auth_principal(owner()) + ) + .is_ok() + ); + } + + #[test] + fn sealed_authentication_cannot_be_replaced_by_a_command_claim() { + let (mut kernel, _) = WorldKernel::create(creation("Owned"), + &auth_principal(owner()), + ) + .unwrap(); + let snapshot = kernel.snapshot().unwrap(); + let forged = command( + &snapshot, + CallerId::Principal(human_principal()), + tick_body(1), + ); + assert!(matches!( + kernel.submit(forged, &auth_principal(owner())), + Err(KernelError::AuthenticationMismatch) + )); + assert_eq!(kernel.snapshot().unwrap(), snapshot); + } + + /// Soul falsification: the preimage must exclude the revision + /// and every component outside the scope. Each step below is a real commit + /// that moves the world, not a hand-edited state. + #[test] + fn soul_scope_components_exclude_revision_and_everything_outside_the_scope() { + let (mut kernel, _) = WorldKernel::create(creation("Preimage"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let scope = topology.walker; + let base = scope_components(&kernel.state, scope); + let start_revision = kernel.state.revision; + + // A new place elsewhere, a route that touches neither the walker's + // place nor it, and a second placed subject: all outside the scope. + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("annex"), + label: "The Annex".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("annexway"), + label: "The Annex Way".into(), + from: Ref::Existing(topology.road), + to: Ref::Draft(DraftHandle::new("annex")), + access: AccessKind::Public, + cost: Cost(3), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("runner"), + label: "The Runner".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.road)), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert_ne!(kernel.state.revision, start_revision); + assert_eq!(scope_components(&kernel.state, scope), base); + + // Another subject's Position moving is not this scope's business. + let annexway = *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "The Annex Way") + .expect("the declared route") + .0; + let runner = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Runner") + .expect("the declared subject") + .0; + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Relocate { + subject: Ref::Existing(runner), + via: Ref::Existing(annexway), + }], + evidence: Vec::new(), + }, + }, + ); + assert_eq!( + kernel.state.positions.get(&runner), + Some(&Position { + place: kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Annex") + .map(|(id, _)| *id) + .unwrap() + }) + ); + assert_eq!(scope_components(&kernel.state, scope), base); + + // A route incident to the walker's own place is inside the scope. + let moved = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &moved, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::CloseRoute { + route: Ref::Existing(topology.ramp), + }], + evidence: Vec::new(), + }, + }, + ); + assert_ne!(scope_components(&kernel.state, scope), base); + } + + /// Soul: an `AffordanceId` now names a catalog entry, not a subject's copy + /// of one — the three genesis subjects share Speak's single id. So the id + /// cannot be what gates: grant membership for the invoking scope is. The + /// same `convene` id commits for the scope that holds it and is denied for + /// one that does not. + #[test] + fn act_needs_the_actors_grant() { + let (mut kernel, _) = WorldKernel::create(creation("SharedCatalogIds"), + &auth_principal(owner()), + ) + .unwrap(); + let active = kernel.snapshot().unwrap(); + let speak = affordance_named(&active, "speak"); + let convened = affordance_named(&active, "convene"); + + // One entry, one id, every genesis subject a grantee. + assert_eq!(active.subjects.len(), 3); + assert!( + active + .subjects + .iter() + .all(|subject| subject.affordances.contains(&speak)) + ); + let holders: Vec = active + .subjects + .iter() + .filter(|subject| subject.affordances.contains(&convened)) + .map(|subject| subject.id) + .collect(); + assert_eq!(holders.len(), 1); + + let invoke = |kernel: &mut WorldKernel, subject: SubjectId| { + act( + kernel, + subject, + DecisionInvocation { + affordance: convened, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("The council convenes.").unwrap()), + display: None, + }, + ) + }; + + // The grantee's scope commits with that id. + assert!(invoke(&mut kernel, holders[0]).unwrap().resulting_revision > 0); + + // A scope that does not hold the entry is denied the very same id, and + // nothing commits. + let after = kernel.snapshot().unwrap(); + let stranger = after + .subjects + .iter() + .find(|subject| !subject.affordances.contains(&convened)) + .expect("a subject without the grant") + .id; + assert!(matches!( + invoke(&mut kernel, stranger).unwrap_err(), + KernelError::AffordanceDenied + )); + assert_eq!(kernel.snapshot().unwrap(), after); + } + + #[test] + fn a_distant_route_closing_leaves_the_actors_scope_alone_and_its_act_commits() { + let (mut kernel, _) = WorldKernel::create(creation("BindingAndAdmission"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = kernel.snapshot().unwrap(); + let speak = affordance_named(&active, "speak"); + + // A route the actor does not stand beside is outside its scope. + // Admission re-reads the live graph at commit, so nothing commits on + // stale topology. + let before_components = scope_components(&kernel.state, topology.walker); + let before = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &before, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(topology.span), + }]), + ); + assert_eq!( + scope_components(&kernel.state, topology.walker), + before_components, + "a route outside the actor's incident set is not in its scope" + ); + + let receipt = act( + &mut kernel, + topology.walker, + DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Still here.").unwrap()), + display: None, + }, + ) + .expect("a distant route closing does not stop this act"); + assert!(receipt.resulting_revision > 0); + } + + /// The mvp doc's disjointness requirement: an institution with an + /// operational organ and a person-shaped voice is two subjects joined by an + /// office, not one subject with two controllers. + #[test] + fn an_institution_and_its_voice_are_two_subjects_joined_by_an_office() { + let mut kernel = crate::custody_tests::custody_kernel("Two"); + let (_, civic, _) = civic_world(&mut kernel); + + + // Both are authorized over the hall — one directly, one by delegation — + // and neither appears in the other's components. + let over_hall = AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }; + assert!(subject_authority(&kernel.state, civic.treasury).contains(&over_hall)); + assert!(subject_authority(&kernel.state, civic.reeve).contains(&over_hall)); + assert!(kernel.state.authority.get(&civic.reeve).is_none()); + assert!( + scope_components(&kernel.state, civic.treasury) + .delegated + .is_empty() + ); + assert!( + scope_components(&kernel.state, civic.reeve) + .authority + .is_empty() + ); + } + + /// A levy from catalog to conservation: one lowered `Transfer`, the ledger + /// total unchanged, and no other partition touched. + #[test] + fn a_levy_round_trips_from_catalog_to_conservation() { + let mut kernel = crate::custody_tests::custody_kernel("Levy"); + let (_, civic, active) = civic_world(&mut kernel); + let before_total: u64 = kernel + .state + .holdings + .values() + .filter_map(|held| held.get(&civic.grain)) + .map(|quantity| quantity.0) + .sum(); + let positions = kernel.state.positions.clone(); + let edges = kernel.state.edges.clone(); + let entities = kernel.state.entities.clone(); + + let caller = play_caller(); + let receipt = kernel + .submit( + command( + &active, + caller.clone(), + CommandBody::Act { + actor: civic.treasury, + invocation: DecisionInvocation { + affordance: affordance_named(&active, "levy"), + bindings: vec![ + RoleBinding { + role: Role("payer".into()), + target: Target::Subject(civic.farmer), + }, + RoleBinding { + role: Role("resource".into()), + target: Target::Entity(civic.grain), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(3)), + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + assert!(receipt.resulting_revision > 0); + + let held = |holder: SubjectId| { + kernel + .state + .holdings + .get(&holder) + .and_then(|held| held.get(&civic.grain)) + .map_or(0, |quantity| quantity.0) + }; + assert_eq!(held(civic.farmer), OPENING_BALANCE - 3); + assert_eq!(held(civic.treasury), 3); + let after_total: u64 = kernel + .state + .holdings + .values() + .filter_map(|held| held.get(&civic.grain)) + .map(|quantity| quantity.0) + .sum(); + assert_eq!(before_total, after_total); + assert_eq!( + kernel.events().last().unwrap().effects, + vec![ResolvedOp::Transfer { + from: civic.farmer, + to: civic.treasury, + resource: civic.grain, + qty: Quantity(3), + }] + ); + assert_eq!(kernel.state.positions, positions); + assert_eq!(kernel.state.edges, edges); + assert_eq!(kernel.state.entities, entities); + } + + /// Representation is person-and-institution shaped, and that is the check + /// that stops the two-subject shape from collapsing back into one. + #[test] + fn office_admission_is_person_and_institution_shaped() { + let mut kernel = crate::custody_tests::custody_kernel("Offices"); + let (_, civic, _) = civic_world(&mut kernel); + let refuse = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + reject_play(kernel, &before, operations(ops)) + }; + + // An institution cannot occupy its own office. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.treasury), + }] + ), + vec![Mismatch::OfficeHolderNotPerson { operation: 0 }] + ); + // An office cannot be opened on a person. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::OpenOffice { + institution: Ref::Existing(civic.reeve), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }] + ), + vec![Mismatch::OfficeOnNonInstitution { operation: 0 }] + ); + // One person, at most one office per institution. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.reeve), + }] + ), + vec![Mismatch::DuplicateIncumbency { operation: 0 }] + ); + } + + /// Disjointness in both directions: overlap inside one subject's effective + /// authority is refused, overlap between subjects is layered government. + #[test] + fn overlapping_jurisdiction_within_one_subject_is_rejected() { + let mut kernel = crate::custody_tests::custody_kernel("Overlap"); + let (_, civic, _) = civic_world(&mut kernel); + let refuse = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + reject_play(kernel, &before, operations(ops)) + }; + let admit = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + submit_play(kernel, &before, operations(ops)) + }; + + // A direct grant under what the reeve's office already lends. + assert_eq!( + refuse( + &mut kernel, + vec![grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber))] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + // Two direct grants of one kind, nested, in one patch. + assert_eq!( + refuse( + &mut kernel, + vec![ + grant_to(civic.farmer, LEVY_KIND, over_place(civic.hall)), + grant_to(civic.farmer, LEVY_KIND, over_place(civic.chamber)), + ] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 1 }] + ); + // An incumbency that would lend the farmer ground it already holds. + admit( + &mut kernel, + vec![grant_to(civic.farmer, LEVY_KIND, over_place(civic.chamber))], + ); + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + incumbent: Ref::Existing(civic.farmer), + }] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // A different kind over the same ground commits, and so does the same + // kind held by a different subject: two holders authorized over one + // target is not a contradiction, because nothing arbitrates. + assert!(admit( &mut kernel, vec![ grant_to(civic.reeve, JUDGE_KIND, over_place(civic.chamber)), grant_to(civic.outsider, LEVY_KIND, over_place(civic.chamber)), ] ).resulting_revision > 0); + } + + /// Contract 6 on the civic surface: one patch, the complete sorted set, no + /// allocation, and repairing exactly those failures commits. + #[test] + fn civic_operations_are_rejected_with_the_complete_set() { + let mut kernel = crate::custody_tests::custody_kernel("CivicSet"); + let (_, civic, _) = civic_world(&mut kernel); + let before = kernel.snapshot().unwrap(); + let broken = vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + delegated: BTreeSet::new(), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("provost"), + incumbent: Ref::Existing(civic.farmer), + }, + ComponentOp::CloseForum { + grievance: grievance("eviction"), + }, + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("Chief Steward"), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.treasury), + }, + grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber)), + ]; + let mut expected = vec![ + Mismatch::EmptyDelegation { operation: 0 }, + Mismatch::UnknownOffice { operation: 1 }, + Mismatch::UnknownForum { operation: 2 }, + Mismatch::InvalidCivicName { + site: patch::Site::Operation(3), + }, + Mismatch::OfficeHolderNotPerson { operation: 4 }, + Mismatch::OverlappingJurisdiction { operation: 5 }, + ]; + expected.sort(); + assert_eq!( + reject_play(&mut kernel, &before, operations(broken)), + expected + ); + assert_eq!(kernel.snapshot().unwrap(), before); + + let repaired = vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + incumbent: Ref::Existing(civic.farmer), + }, + ComponentOp::OpenForum { + grievance: grievance("eviction"), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.hall), + }, + ]; + assert!(submit_play(&mut kernel, &before, operations(repaired)).resulting_revision > 0); + } + + /// A civic operation that changes nothing is not a canonical change. + #[test] + fn an_idempotent_civic_operation_is_no_change() { + let mut kernel = + crate::custody_tests::custody_kernel("Idempotent"); + let (_, civic, _) = civic_world(&mut kernel); + for operation in [ + grant_to(civic.treasury, LEVY_KIND, over_place(civic.hall)), + ComponentOp::RevokeAuthority { + holder: Ref::Existing(civic.treasury), + grant: grant_of(JUDGE_KIND, over_place(civic.hall)), + }, + ComponentOp::VacateOffice { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + }, + ComponentOp::OpenForum { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.chamber), + }, + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }, + ] { + let before = kernel.snapshot().unwrap(); + assert_eq!( + reject_play(&mut kernel, &before, operations(vec![operation])), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + } + + /// The digest reads what the actor is authorized over and nothing about the + /// world the actor reaches. + #[test] + fn scope_components_read_authority_and_delegation_but_not_occupancy() { + let mut kernel = crate::custody_tests::custody_kernel("Digest"); + let (topology, civic, _) = civic_world(&mut kernel); + let digest_of = |kernel: &WorldKernel, subject_id| { + scope_components(&kernel.state, subject_id) + }; + let admit = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + submit_play(kernel, &before, operations(ops)); + }; + + // Moving an unrelated subject into and out of the jurisdiction, and + // opening a forum, leave every digest alone. + let reeve_before = digest_of(&kernel, civic.reeve); + let treasury_before = digest_of(&kernel, civic.treasury); + admit( + &mut kernel, + vec![ + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }, + ComponentOp::OpenForum { + grievance: grievance("eviction"), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.hall), + }, + ], + ); + assert_eq!(digest_of(&kernel, civic.reeve), reeve_before); + assert_eq!(digest_of(&kernel, civic.treasury), treasury_before); + + // Installing an office the subject does not hold leaves it alone too. + admit( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.farmer), + }], + ); + assert_eq!(digest_of(&kernel, civic.reeve), reeve_before); + assert_eq!(digest_of(&kernel, civic.treasury), treasury_before); + + // Revoking the institution's grant for a lent kind moves the + // incumbent's digest, because the office copies it in. + admit( + &mut kernel, + vec![ComponentOp::RevokeAuthority { + holder: Ref::Existing(civic.treasury), + grant: grant_of(LEVY_KIND, over_place(civic.hall)), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + assert_ne!(digest_of(&kernel, civic.treasury), treasury_before); + + // Granting the actor's own, and narrowing a held office, move it too. + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber))], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(COMMAND_KIND)]), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![ComponentOp::VacateOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + } + + /// The snapshot carries a subject's own civic state and no gazetteer: a + /// forum is visible only to its standing, and no subject sees another's + /// grants. + #[test] + fn a_forum_is_visible_only_to_its_standing() { + let mut kernel = crate::custody_tests::custody_kernel("Redress"); + let (_, civic, active) = civic_world(&mut kernel); + let of = |subject_id: SubjectId| { + active + .subjects + .iter() + .find(|subject| subject.id == subject_id) + .expect("a declared subject") + }; + + // The farmer stands in the chamber, which is the forum's standing. + assert_eq!( + of(civic.farmer).redress, + vec![ForumSnapshot { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: civic.treasury, + }] + ); + assert!(of(civic.outsider).redress.is_empty()); + + // Grants are the subject's own; offices held and offices granted are + // the two ends of one link and never merge. + assert!(of(civic.reeve).components.authority.is_empty()); + assert_eq!(of(civic.reeve).offices_held.len(), 1); + assert!(of(civic.reeve).offices_granted.is_empty()); + assert_eq!(of(civic.treasury).offices_granted.len(), 2); + assert!(of(civic.treasury).offices_held.is_empty()); + assert!(of(civic.farmer).components.authority.is_empty()); + assert_eq!( + of(civic.treasury).components.authority, + BTreeSet::from([ + AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }, + AuthorityGrant { + kind: authority_kind(COMMAND_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }, + ]) + ); + } + + /// Soul falsification of the candidate authority shadow's reach: a grant + /// minted in the same patch resolves, but a *destination* declared in the + /// same patch does not, because the shadow is projected to canonical + /// referents before the covering predicate runs. A genesis patch therefore + /// cannot declare a restricted room and walk anyone into it in one batch. + #[test] + fn a_same_patch_destination_is_covered_by_no_grant() { + let mut kernel = crate::custody_tests::custody_kernel("DraftDoor"); + let topology = admit_topology(&mut kernel); + let before = kernel.snapshot().unwrap(); + let patch = WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("keep"), + label: "The Inner Keep".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("keepgate"), + label: "The Keep Gate".into(), + from: Ref::Existing(topology.yard), + to: Ref::Draft(DraftHandle::new("keep")), + access: AccessKind::Restricted { + requires: authority_kind(ADMIT_KIND), + }, + cost: Cost(2), + }), + ], + operations: vec![ + ComponentOp::GrantAuthority { + holder: Ref::Existing(topology.walker), + grant: AuthorityGrantRef { + kind: authority_kind(ADMIT_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "keep", + ))), + }, + }, + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Draft(DraftHandle::new("keepgate")), + }, + ], + evidence: Vec::new(), + }; + assert_eq!( + reject_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch + } + ), + vec![Mismatch::RouteAccessRestricted { operation: 1 }], + "the key covers the door, but the door's far side is still a draft" + ); + } + + /// PA.f38: a retired institution lends nothing. `Retire` does not vacate + /// the office the reeve holds — the incumbency stays on the ledger — but + /// `delegated_authority` stops reading a dissolved institution's grants, + /// the one site that turns an office into effective authority. + #[test] + fn a_retired_institution_lends_no_authority_to_its_office_holder() { + let mut kernel = crate::custody_tests::custody_kernel("RetiredLends"); + let (_, civic, before) = civic_world(&mut kernel); + let over_hall = AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }; + assert!( + subject_authority(&kernel.state, civic.reeve).contains(&over_hall), + "the reeve holds levy only through the warden office before retirement" + ); + + submit_play( + &mut kernel, + &before, + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }]), + ); + + let warden = kernel + .state + .selection + .get(&civic.treasury) + .and_then(|offices| offices.get(&office(WARDEN_OFFICE))) + .expect("retire did not vacate the office"); + assert_eq!( + warden.incumbent, + Some(civic.reeve), + "the reeve still holds the office after the institution retires" + ); + assert!( + !subject_authority(&kernel.state, civic.reeve).contains(&over_hall), + "a retired institution still lent authority through its office" + ); + } +} + +#[cfg(test)] +mod custody_tests { + use super::tests::{ + OPENING_BALANCE, TITHE_RECEIPT, act, admit_custody, admit_topology, + auth_principal, creation, custody_world, first_grant, operations, owner, reject_play, + speak, speak_entry, submit_play, + }; + use super::*; + + pub(crate) fn custody_kernel(title: &str) -> WorldKernel { + WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .expect("a created world") + .0 + } + + fn holding(kernel: &WorldKernel, holder: SubjectId, resource: EntityId) -> u64 { + held(&kernel.state, holder, resource) + } + + /// A forged `PatchAdmitted` never passes the resolver, so `admit_resolved` + /// re-derives every custody precondition from the committed partitions and + /// commits nothing when one fails. + /// + /// Deviation from the spec's wording, decided here: `ResolvedOp::Transfer` + /// carries one `qty`, so "a transfer whose debit and credit differ" is + /// unrepresentable — which is the stronger outcome that shape was chosen + /// for. The reachable forgery is a transfer the holder cannot cover, and + /// the conservation equation itself is falsified directly beside it. + #[test] + fn a_non_conserving_transfer_effect_does_not_apply() { + let mut kernel = custody_kernel("Forged"); + let (_, custody, _) = custody_world(&mut kernel); + let before = kernel.state.holdings.clone(); + + let mut candidate = kernel.state.clone(); + let forged = WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![ResolvedOp::Transfer { + from: custody.holder, + to: custody.counterparty, + resource: custody.tithe, + qty: Quantity(OPENING_BALANCE + 1), + }], + evidence: Vec::new(), + }, + }; + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &forged, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate.holdings, before); + + // The conservation equation is the one owner, and it refuses a ledger + // that does not balance regardless of which operation produced it. + let unbalanced = BTreeMap::from([( + custody.tithe, + LedgerDelta { + before: 7, + after: 9, + admitted: 1, + ..LedgerDelta::default() + }, + )]); + assert_eq!(patch::check_ledger(&unbalanced), Some(custody.tithe)); + let balanced = BTreeMap::from([( + custody.tithe, + LedgerDelta { + before: 7, + after: 8, + admitted: 1, + ..LedgerDelta::default() + }, + )]); + assert_eq!(patch::check_ledger(&balanced), None); + } + + /// Creation of quantity is attributable: an `Admit` whose ref is not in the + /// patch's own evidence list mints nothing and allocates no ID. + #[test] + fn an_admit_without_evidence_is_rejected() { + let mut kernel = custody_kernel("Unevidenced"); + let topology = admit_topology(&mut kernel); + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + + let mismatches = reject_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("tithe"), + label: "The Rhythm Tithe".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("clerk"), + label: "The Ledger Clerk".into(), + kind: SubjectKind::Institution, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.yard)), + import_key: None, + }), + ], + operations: vec![ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(4), + evidence: EvidenceRef::new("receipt:never-listed"), + }], + evidence: Vec::new(), + }, + }, + ); + + assert_eq!( + mismatches, + vec![Mismatch::AdmitWithoutEvidence { operation: 0 }] + ); + assert!(kernel.state.holdings.is_empty()); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + #[test] + fn a_transfer_moves_the_exact_quantity_and_nothing_else() { + let mut kernel = custody_kernel("Transfer"); + let (_, custody, active) = custody_world(&mut kernel); + let entities = kernel.state.entities.clone(); + let edges = kernel.state.edges.clone(); + let positions = kernel.state.positions.clone(); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); + assert_eq!(holding(&kernel, custody.counterparty, custody.tithe), 3); + assert_eq!(resource_total_by_scan(&kernel.state, custody.tithe), 7); + assert_eq!(kernel.state.entities, entities); + assert_eq!(kernel.state.edges, edges); + assert_eq!(kernel.state.positions, positions); + } + + /// Absence is zero at both levels, so emptying a holding removes the + /// resource key and emptying a holder removes the holder key. + #[test] + fn consume_reduces_the_holding_and_emptying_removes_the_key() { + let mut kernel = custody_kernel("Consume"); + let (_, custody, active) = custody_world(&mut kernel); + + let after_three = submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + assert!(after_three.resulting_revision > 0); + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(4), + }]), + ); + assert!(!kernel.state.holdings.contains_key(&custody.holder)); + let subject = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.holder) + .expect("the holder is in the snapshot"); + assert!(subject.components.holdings.is_empty()); + } + + #[test] + fn a_transform_conserves_one_for_one() { + let mut kernel = custody_kernel("Transform"); + let (_, custody, active) = custody_world(&mut kernel); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(5), + }]), + ); + + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 2); + assert_eq!(holding(&kernel, custody.holder, custody.ingot), 5); + assert_eq!(resource_total_by_scan(&kernel.state, custody.tithe), 2); + assert_eq!(resource_total_by_scan(&kernel.state, custody.ingot), 5); + } + + #[test] + fn spending_more_than_held_is_rejected_with_insufficient_custody() { + let mut kernel = custody_kernel("Insufficient"); + let (_, custody, _) = custody_world(&mut kernel); + let too_much = Quantity(OPENING_BALANCE + 1); + let attempts = [ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: too_much, + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: too_much, + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: too_much, + }, + ]; + + for attempt in attempts { + let snapshot = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + let mismatches = reject_play(&mut kernel, &snapshot, operations(vec![attempt])); + assert_eq!( + mismatches, + vec![Mismatch::InsufficientCustody { operation: 0 }] + ); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), snapshot); + } + } + + /// A holder with no entry holds zero: there is no second name for it and no + /// zero entry anywhere in the snapshot. + #[test] + fn an_absent_holding_is_zero() { + let mut kernel = custody_kernel("Absent"); + let (_, custody, active) = custody_world(&mut kernel); + + let mismatches = reject_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }]), + ); + assert_eq!( + mismatches, + vec![Mismatch::InsufficientCustody { operation: 0 }] + ); + let counterparty = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.counterparty) + .expect("the counterparty is in the snapshot"); + assert!(counterparty.components.holdings.is_empty()); + } + + #[test] + fn a_zero_quantity_operation_is_rejected() { + let mut kernel = custody_kernel("Zero"); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + + // `Admit` is Draft-only, because Active refuses a patch carrying + // evidence, so its zero case is proven before activation. + let draft = kernel.snapshot().unwrap(); + let mismatches = reject_play( + &mut kernel, + &draft, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ); + assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); + + let active = kernel.snapshot().unwrap(); + for attempt in [ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + }, + ] { + let snapshot = kernel.snapshot().unwrap(); + let mismatches = reject_play(&mut kernel, &snapshot, operations(vec![attempt])); + assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); + } + assert_eq!(kernel.snapshot().unwrap(), active); + } + + #[test] + fn dependency_bind_and_release_round_trip() { + let mut kernel = custody_kernel("Dependency"); + let (_, custody, active) = custody_world(&mut kernel); + let before = kernel.state.dependencies.clone(); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }]), + ); + assert_eq!( + kernel.state.dependencies.get(&custody.holder), + Some(&BTreeSet::from([DependencyTarget::Resource(custody.tithe)])) + ); + + let bound = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &bound, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }]), + ); + assert_eq!(kernel.state.dependencies, before); + assert!(!kernel.state.dependencies.contains_key(&custody.holder)); + } + + /// A bind that changes nothing is `NoOperationEffect`, the name pass 2 + /// already owns; a subject bound to itself is `SelfDependency`. + #[test] + fn a_duplicate_dependency_bind_is_rejected_as_no_effect() { + let mut kernel = custody_kernel("Duplicate"); + let (_, custody, active) = custody_world(&mut kernel); + + let bind = ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }; + submit_play(&mut kernel, &active, operations(vec![bind.clone()])); + + let bound = kernel.snapshot().unwrap(); + assert_eq!( + reject_play(&mut kernel, &bound, operations(vec![bind])), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert_eq!( + reject_play( + &mut kernel, + &bound, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.ingot)), + }]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert_eq!( + reject_play( + &mut kernel, + &bound, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Subject(Ref::Existing(custody.holder)), + }]), + ), + vec![Mismatch::SelfDependency { operation: 0 }] + ); + } + + /// Pass 3 owns the representation of a dependency, not its consequence. A + /// dependency on a closed route commits and shows up in the subject's + /// components; nothing rejects it and nothing fires from it. + #[test] + fn a_dependency_on_a_closed_route_is_representable_and_visible() { + let mut kernel = custody_kernel("Closed"); + let (topology, custody, active) = custody_world(&mut kernel); + assert!(!kernel.state.edges[&topology.shutter].is_open()); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Route(Ref::Existing(topology.shutter)), + }]), + ); + + let subject = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.holder) + .expect("the holder is in the snapshot"); + assert_eq!( + subject.components.dependencies, + BTreeSet::from([DependencyTarget::Route(topology.shutter)]) + ); + } + + /// The digest reads the acting subject's own holdings and dependencies, and + /// only its own: a counterparty's churn does not move it. + #[test] + fn scope_components_read_holdings_and_dependencies() { + let mut kernel = custody_kernel("ScopeCustody"); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let scope = custody.holder; + let base = scope_components(&kernel.state, scope); + + let mut spent = kernel.state.clone(); + set_held(&mut spent, custody.holder, custody.tithe, 1); + assert_ne!(scope_components(&spent, scope), base); + + let mut gained = kernel.state.clone(); + set_held(&mut gained, custody.holder, custody.ingot, 1); + assert_ne!(scope_components(&gained, scope), base); + + let mut bound = kernel.state.clone(); + bound + .dependencies + .entry(custody.holder) + .or_default() + .insert(DependencyTarget::Resource(custody.tithe)); + assert_ne!(scope_components(&bound, scope), base); + + let mut elsewhere = kernel.state.clone(); + set_held(&mut elsewhere, custody.counterparty, custody.tithe, 9); + elsewhere + .dependencies + .entry(custody.counterparty) + .or_default() + .insert(DependencyTarget::Resource(custody.ingot)); + assert_eq!(scope_components(&elsewhere, scope), base); + } + + /// Soul, proof 4: the ledger equation stated as arithmetic over the + /// committed partitions, across one patch that exercises every conserving + /// operation at once. Per resource, `after == before + admitted + gained - + /// consumed - spent`, and no third resource moves. + #[test] + fn soul_a_mixed_patch_conserves_every_resource_it_touches() { + let mut kernel = custody_kernel("MixedLedger"); + let (_, custody, active) = custody_world(&mut kernel); + + // The opening balance was created by `Admit` alone: before is zero, + // admitted is the balance, and the total equals the sum of the two. + assert_eq!( + resource_total_by_scan(&kernel.state, custody.tithe), + u128::from(OPENING_BALANCE) + ); + assert_eq!(resource_total_by_scan(&kernel.state, custody.ingot), 0); + + let tithe_before = resource_total_by_scan(&kernel.state, custody.tithe); + let ingot_before = resource_total_by_scan(&kernel.state, custody.ingot); + + let receipt = submit_play( + &mut kernel, + &active, + operations(vec![ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(2), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }, + ]), + ); + assert!(receipt.resulting_revision > 0); + + // Transfer contributes to no term; transform contributes one spent and + // one gained; consume contributes one consumed. Nothing was admitted. + assert_eq!( + resource_total_by_scan(&kernel.state, custody.tithe), + tithe_before - 1 - 2 + ); + assert_eq!( + resource_total_by_scan(&kernel.state, custody.ingot), + ingot_before + 2 + ); + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 2); + assert_eq!(holding(&kernel, custody.holder, custody.ingot), 2); + assert_eq!(holding(&kernel, custody.counterparty, custody.tithe), 2); + // Absence is zero: the counterparty never held an ingot, so there is no + // row for one rather than a row holding nothing. + assert!(!kernel.state.holdings[&custody.counterparty].contains_key(&custody.ingot)); + } + + /// Soul: is the apply-side `check_ledger` reachable? + /// + /// A forged `PatchAdmitted` can carry a *sequence* whose second operation + /// exceeds what the first left. It dies at `apply_operation`'s own + /// re-derived precondition, one operation early, so the ledger never speaks. + /// A sequence in which every operation applies cannot break the equation, + /// because every `ResolvedOp` arm debits and credits the same `qty` it + /// records: the apply-side call is unreachable from the current closed set. + #[test] + fn soul_a_forged_sequence_dies_at_the_per_operation_check_not_the_ledger() { + let mut kernel = custody_kernel("ForgedSequence"); + let (_, custody, _) = custody_world(&mut kernel); + let before = kernel.state.holdings.clone(); + + let forge = |operations: Vec| WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations, + evidence: Vec::new(), + }, + }; + let transfer = |qty: u64| ResolvedOp::Transfer { + from: custody.holder, + to: custody.counterparty, + resource: custody.tithe, + qty: Quantity(qty), + }; + + // Two transfers of five out of a balance of seven: the first leaves two, + // the second cannot cover five. + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &forge(vec![transfer(5), transfer(5)]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "holder does not hold enough"), + "the per-operation precondition speaks first, not the ledger: {error:?}" + ); + // The candidate is a throwaway clone; the live state never moved. + assert_eq!(kernel.state.holdings, before); + + // Every operation applying means the equation balances, so the same + // forged lane commits a conserving sequence with no ledger complaint. + let mut conserving = kernel.state.clone(); + apply_effect( + &mut conserving, + CommandId::issue(), + &CallerId::Play, + &forge(vec![ + transfer(5), + ResolvedOp::Transfer { + from: custody.counterparty, + to: custody.holder, + resource: custody.tithe, + qty: Quantity(5), + }, + ]), + ) + .expect("a conserving forged sequence applies"); + assert_eq!(conserving.holdings, before); + + // The degenerate shapes a forgery could otherwise use to mint or burn + // are refused by the arms themselves, not by the equation. + for degenerate in [ + ResolvedOp::Transfer { + from: custody.holder, + to: custody.holder, + resource: custody.tithe, + qty: Quantity(1), + }, + ResolvedOp::Transform { + holder: custody.holder, + from_resource: custody.tithe, + into_resource: custody.tithe, + qty: Quantity(1), + }, + ] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &forge(vec![degenerate]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "custody operation moves nothing"), + "unexpected refusal: {error:?}" + ); + } + + // An `Admit` in a forged effect still needs its receipt in the same + // patch, so the apply lane mints no unattributable quantity either. + let mut unevidenced = kernel.state.clone(); + let error = apply_effect( + &mut unevidenced, + CommandId::issue(), + &CallerId::Play, + &forge(vec![ResolvedOp::Admit { + holder: custody.holder, + resource: custody.tithe, + qty: Quantity(4), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "admitted quantity cites no evidence in its patch"), + "unexpected refusal: {error:?}" + ); + assert_eq!(kernel.state.holdings, before); + } + + /// Soul: `QuantityOverflow` is reachable, and the arithmetic that reaches it + /// is `checked_add` rather than a silent clamp. Two admissions in one patch + /// whose sum exceeds `u64::MAX` mint nothing and allocate no ID. + #[test] + fn soul_a_holding_cannot_overflow_silently() { + let mut kernel = custody_kernel("Overflow"); + let topology = admit_topology(&mut kernel); + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + + let admit = |qty: u64| ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(qty), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }; + let mismatches = reject_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("tithe"), + label: "The Rhythm Tithe".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("clerk"), + label: "The Ledger Clerk".into(), + kind: SubjectKind::Institution, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.yard)), + import_key: None, + }), + ], + operations: vec![admit(u64::MAX), admit(1)], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ); + + assert_eq!( + mismatches, + vec![Mismatch::QuantityOverflow { operation: 1 }], + "the overflow is the complete verdict: no clamp, no second name" + ); + assert!(kernel.state.holdings.is_empty()); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Soul, scope: a transfer changes the *receiver's* components too, and + /// no unrelated subject's, whose act still commits at the later revision. + #[test] + fn soul_an_incoming_transfer_changes_only_the_counterpartys_scope() { + let mut kernel = custody_kernel("IncomingScope"); + let (topology, custody, active) = custody_world(&mut kernel); + let receiver_before = scope_components(&kernel.state, custody.counterparty); + let bystander_before = scope_components(&kernel.state, topology.walker); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + let moved = kernel.snapshot().unwrap(); + + assert_ne!( + scope_components(&kernel.state, custody.counterparty), + receiver_before, + "the receiver's holdings moved" + ); + assert_eq!( + scope_components(&kernel.state, topology.walker), + bystander_before, + "an unrelated subject's scope is untouched by the transfer" + ); + + let receipt = act( + &mut kernel, + topology.walker, + speak(first_grant(&moved, topology.walker), "Unmoved."), + ) + .expect("an unrelated subject acts at the later revision"); + assert!(receipt.resulting_revision > 0); + } +} + +/// Pass 6: `Knowledge`, `Channel`, `Fact` standing, and the non-leakage rule. +/// A subject perceives a speech act if and only if it holds `Knowledge` of that +/// act's fact — the knowledge partition is the sole owner of who-heard-what. +#[cfg(test)] +mod knowledge_tests { + use super::patch::{RefName, Site}; + use super::tests::{ + act, play_caller, affordance_named, + FLOOD_EVIDENCE, FLOOD_STATEMENT, Speech, auth_principal, command, creation, operations, + owner, reject_play, speech_world, spoken, submit_play, + }; + use super::*; + + fn speech_kernel(title: &str) -> (WorldKernel, Speech, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + (kernel, speech, active) + } + + fn utter( + kernel: &mut WorldKernel, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + act(kernel, actor, invocation) + } + + fn say(affordance: AffordanceId, bindings: Vec, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn rejected(result: Result) -> Vec { + match result { + Err(KernelError::ActionRejected(mismatches)) => mismatches, + other => panic!("expected a rejected invocation, got {other:?}"), + } + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option { + kernel + .state + .knowledge + .get(&(subject, fact)) + .copied() + } + + fn acquire(subject: SubjectId, fact: EntityId, source: AuthoredSource) -> ComponentOp { + ComponentOp::AcquireKnowledge { + subject: Ref::Existing(subject), + fact: Ref::Existing(fact), + source, + confidence: Confidence::Certain, + } + } + + fn minted_claim(kernel: &WorldKernel) -> EntityId { + kernel + .events() + .last() + .expect("the committed event") + .speech + .expect("a speech act names its claim") + } + + /// Verification 5, first half: a patch adds knowledge only by citing an + /// accessible fact, and a rejected citation allocates nothing. + #[test] + fn knowledge_citing_an_inaccessible_fact_is_rejected() { + let (mut kernel, speech, active) = speech_kernel("Inaccessible"); + let before = kernel.state.clone(); + + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + EntityId::issue(), + AuthoredSource::Witnessed + )]), + ), + vec![Mismatch::UnknownCanonical { + site: Site::Operation(0), + expected: RefKind::Entity(EntityKind::Fact), + }] + ); + // A live referent of the wrong kind names the kind it actually is. + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.hall, + AuthoredSource::Witnessed + )]), + ), + vec![Mismatch::WrongKind { + site: Site::Operation(0), + referent: RefName::Entity(Ref::Existing(speech.hall)), + expected: RefKind::Entity(EntityKind::Fact), + actual: RefKind::Entity(EntityKind::Place), + }] + ); + assert_eq!(kernel.state, before); + + submit_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + assert_eq!( + knows(&kernel, speech.listener, speech.flood).map(|held| held.source), + Some(KnowledgeSource::Witnessed) + ); + } + + /// Standing is what a fact *is*, so both halves are checked at declaration: + /// canon needs its receipt in the same patch, a claim needs a live asserter. + #[test] + fn a_canonical_fact_needs_evidence_and_a_claim_needs_an_asserter() { + let mut draft = WorldKernel::create(creation("Standing"), + &auth_principal(owner()), + ) + .expect("a draft world") + .0; + let start = draft.snapshot().unwrap(); + let declare = + |standing: FactStandingRef, evidence: Vec| CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rumour"), + label: "a rumour".into(), + statement: Statement::new("The reeve took two tithes.").unwrap(), + standing, + })], + operations: Vec::new(), + evidence, + }, + }; + + assert_eq!( + reject_play( + &mut draft, + &start, + declare( + FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:absent"), + }, + Vec::new(), + ), + ), + vec![Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("rumour"), + }] + ); + assert_eq!( + reject_play( + &mut draft, + &start, + declare( + FactStandingRef::Claimed { + by: Ref::Draft(DraftHandle::new("nobody")), + }, + Vec::new(), + ), + ), + vec![Mismatch::UnresolvedDraft { + site: Site::Declaration(DraftHandle::new("rumour")), + referent: DraftHandle::new("nobody"), + expected: RefKind::Subject(None), + }] + ); + assert!(draft.state.facts.is_empty()); + + submit_play( + &mut draft, + &start, + declare( + FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:rumour"), + }, + vec![EvidenceRef::new("vault:rumour")], + ), + ); + assert_eq!(draft.state.facts.len(), 1); + // The bijection holds in both directions. + let fact = *draft.state.facts.keys().next().unwrap(); + assert_eq!(draft.state.entities[&fact].kind, EntityKind::Fact); + } + + /// A receipt vouches for canon. It cannot vouch for an assertion the kernel + /// never evaluated. + #[test] + fn evidenced_knowledge_of_a_claim_is_rejected() { + let (mut kernel, speech, _) = speech_kernel("Evidenced"); + utter(&mut kernel, speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The gate was left open.", + ), + ) + .expect("the proclamation commits"); + let claim = minted_claim(&kernel); + let active = kernel.snapshot().unwrap(); + + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.stranger, + claim, + AuthoredSource::Evidenced + )]), + ), + vec![Mismatch::EvidencedKnowledgeOfClaim { operation: 0 }] + ); + submit_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.stranger, + speech.flood, + AuthoredSource::Evidenced, + )]), + ); + assert_eq!( + knows(&kernel, speech.stranger, speech.flood).map(|held| held.source), + Some(KnowledgeSource::Evidenced) + ); + assert_eq!( + kernel.state.facts[&speech.flood].standing, + FactStanding::Canonical { + evidence: EvidenceRef::new(FLOOD_EVIDENCE), + } + ); + } + + /// The fan-out is the audience, less the speaker: co-located speech fills + /// the exact room, and the utterance lands in `facts` and nowhere else. + #[test] + fn speak_fans_out_to_the_audience_and_not_beyond() { + let (mut kernel, speech, active) = speech_kernel("FanOut"); + utter(&mut kernel, speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Mind the hinge.", + ), + ) + .expect("the whisper commits"); + + let events = kernel.events(); + let event = events.last().expect("the committed event"); + let claim = event.speech.expect("a speech act names its claim"); + assert_eq!(spoken(&kernel.state, event), Some("Mind the hinge.")); + assert_eq!( + knows(&kernel, speech.listener, claim), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: None, + }, + acquired_at: active.revision + 1, + }) + ); + // The yard is inside the hall, but a voice fills a room and not the + // district containing it. The speaker's own claim is not implied. + for outside in [speech.bystander, speech.stranger, speech.speaker] { + assert_eq!(knows(&kernel, outside, claim), None); + } + assert_eq!( + kernel.state.facts[&claim].standing, + FactStanding::Claimed { by: speech.speaker } + ); + // The utterance has exactly one home: a label is a name, not a + // transcript. + assert_ne!(kernel.state.entities[&claim].label, "Mind the hinge."); + } + + /// Co-location is the exact place; a channel's `Reach::Place` is the + /// subtree, through the same containment walk a jurisdiction uses. + #[test] + fn co_location_reach_is_the_exact_place_and_a_channel_place_is_the_subtree() { + let (mut kernel, speech, _) = speech_kernel("Reach"); + utter(&mut kernel, speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn carries.", + ), + ) + .expect("the proclamation commits"); + let broadcast = minted_claim(&kernel); + assert!(knows(&kernel, speech.listener, broadcast).is_some()); + assert!(knows(&kernel, speech.bystander, broadcast).is_some()); + assert_eq!(knows(&kernel, speech.stranger, broadcast), None); + + // The same speaker's voice reaches only the hall. + utter(&mut kernel, speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "A voice does not.", + ), + ) + .expect("the whisper commits"); + let voiced = minted_claim(&kernel); + assert!(knows(&kernel, speech.listener, voiced).is_some()); + assert_eq!(knows(&kernel, speech.bystander, voiced), None); + + // Moving the bystander up the stair puts it in both audiences. + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(speech.bystander), + via: Ref::Existing(speech.stair), + }]), + ); + utter(&mut kernel, speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Now you hear it.", + ), + ) + .expect("the whisper commits"); + assert!(knows(&kernel, speech.bystander, minted_claim(&kernel)).is_some()); + } + + /// The delta of a telling is a property of the world, not a defect in the + /// proposal: speaking alone commits the claim and the event and lands + /// nothing. + #[test] + fn speaking_into_an_empty_room_commits_the_claim_and_lands_nothing() { + let (mut kernel, speech, _) = speech_kernel("EmptyRoom"); + let knowledge_before = kernel.state.knowledge.clone(); + utter(&mut kernel, speech.bystander, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Nobody is here.", + ), + ) + .expect("speech into an empty room commits"); + + assert_eq!(kernel.state.knowledge, knowledge_before); + assert_eq!(kernel.events().len(), 1); + assert_eq!( + spoken(&kernel.state, kernel.events().last().unwrap()), + Some("Nobody is here.") + ); + assert_eq!( + kernel + .state + .facts + .values() + .filter(|record| matches!(record.standing, FactStanding::Claimed { .. })) + .count(), + 1 + ); + } + + + fn show( + affordance: AffordanceId, + bindings: Vec, + speech: Option<&str>, + display: &str, + ) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: speech.map(|text| Statement::new(text).unwrap()), + display: Some(Statement::new(display).unwrap()), + } + } + + /// A visible act is the room's to see and nobody else's: everyone standing + /// in the actor's place holds it as `Seen { by }`; the actor, the yard + /// below, and the placeless hold nothing. The entry's own audience is not + /// consulted: a proclamation down the horn carries its words to the yard + /// and still folds its arms only before the hall. + #[test] + fn a_display_is_seen_by_the_room_and_by_no_one_else() { + let (mut kernel, speech, active) = speech_kernel("Display"); + utter(&mut kernel, speech.speaker, + show( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + Some("The horn carries."), + "I fold my arms.", + ), + ) + .expect("the proclamation with a display commits"); + + let events = kernel.events(); + let event = events.last().expect("the committed event"); + let said = event.speech.expect("the utterance names its claim"); + let seen = event.display.expect("the display names its claim"); + assert_ne!(said, seen); + assert_eq!(kernel.state.facts[&seen].statement.as_str(), "I fold my arms."); + assert_eq!( + kernel.state.facts[&seen].standing, + FactStanding::Claimed { by: speech.speaker } + ); + assert!(knows(&kernel, speech.bystander, said).is_some()); + assert_eq!( + knows(&kernel, speech.listener, seen), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Seen { by: speech.speaker }, + acquired_at: active.revision + 1, + }) + ); + for blind in [speech.bystander, speech.stranger, speech.speaker] { + assert_eq!(knows(&kernel, blind, seen), None); + } + // One act minted both claims, so the listener's snapshot stamps both + // rows with the one revision. + let snapshot = kernel.snapshot().unwrap(); + let listener = snapshot + .subjects + .iter() + .find(|subject| subject.id == speech.listener) + .unwrap(); + let stamps: BTreeSet> = listener + .knowledge + .iter() + .filter(|row| row.fact == said || row.fact == seen) + .map(|row| row.minted_at) + .collect(); + assert_eq!(stamps, BTreeSet::from([Some(event.revision)])); + } + + /// A silent turn: the kernel `speak` entry invoked with no utterance and a + /// display is an address, not `SpeechRequired`. The act lands, no speech + /// claim is minted, and alone in the yard the same act commits its claim + /// and lands nothing, as speaking alone does. + #[test] + fn a_silent_display_addresses_the_room_through_the_speak_entry() { + let (mut kernel, speech, active) = speech_kernel("Silent"); + let speak = affordance_named(&active, "speak"); + utter(&mut kernel, speech.speaker, + show(speak, Vec::new(), None, "I nod toward the stair."), + ) + .expect("a silent act commits"); + let events = kernel.events(); + let event = events.last().unwrap(); + assert!(event.speech.is_none()); + let seen = event.display.expect("the display names its claim"); + assert_eq!( + knows(&kernel, speech.listener, seen).map(|held| held.source), + Some(KnowledgeSource::Seen { by: speech.speaker }) + ); + assert_eq!(claimed(&kernel), 1); + + let knowledge_before = kernel.state.knowledge.clone(); + utter(&mut kernel, speech.bystander, + show(speak, Vec::new(), None, "I sit on the step."), + ) + .expect("a display into an empty room commits"); + assert_eq!(kernel.state.knowledge, knowledge_before); + assert_eq!(kernel.events().len(), 2); + assert_eq!(claimed(&kernel), 2); + } + + /// The refusals, each at its own layer: a padded act is `EmptyDisplay` at + /// the check; a speech-carrying entry given neither words nor act is + /// `SpeechRequired`; the placeless stranger has no room to be seen in and + /// fails the entry's own `NoAudience`. None of them mints anything. + #[test] + fn a_display_is_refused_when_empty_placeless_or_when_nothing_is_addressed() { + let (mut kernel, speech, active) = speech_kernel("Refused"); + let speak = affordance_named(&active, "speak"); + let mut padded = show(speak, Vec::new(), None, "placeholder"); + padded.display = Some(serde_json::from_str::("\" \"").unwrap()); + assert_eq!( + rejected(utter(&mut kernel, speech.speaker, padded)), + vec![ActionMismatch::EmptyDisplay] + ); + let mute = DecisionInvocation { + affordance: speech.whisper, + bindings: vec![binding("target", Target::Subject(speech.listener))], + proposed: Vec::new(), + speech: None, + display: None, + }; + assert_eq!( + rejected(utter(&mut kernel, speech.speaker, mute)), + vec![ActionMismatch::SpeechRequired] + ); + assert_eq!( + rejected(utter(&mut kernel, speech.stranger, + show(speak, Vec::new(), None, "I shrug."), + )), + vec![ActionMismatch::NoAudience { precondition: 0 }] + ); + assert!(kernel.events().is_empty()); + assert_eq!(claimed(&kernel), 0); + } + + /// The claims a display minted, its `Seen` rows, and its event replay from + /// the journal exactly, through the same path as speech. + #[test] + fn restart_replay_after_a_display_is_exact() { + let (speech, exported, expected) = { + let mut kernel = WorldKernel::create(creation("ReplayDisplay"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + let speak = affordance_named(&active, "speak"); + utter(&mut kernel, speech.speaker, + show(speak, Vec::new(), Some("One."), "I raise one finger."), + ) + .expect("the act commits"); + utter(&mut kernel, speech.listener, + show(speak, Vec::new(), None, "I look away."), + ) + .expect("the silent act commits"); + (speech, kernel.export().unwrap(), kernel.state.clone()) + }; + let reopened = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(reopened.state, expected); + assert!(reopened + .state + .knowledge_of(speech.listener) + .any(|(_, held)| held.source == KnowledgeSource::Seen { by: speech.speaker })); + assert!(reopened + .state + .knowledge_of(speech.speaker) + .any(|(_, held)| held.source == KnowledgeSource::Seen { by: speech.listener })); + } + + fn claimed(kernel: &WorldKernel) -> usize { + kernel + .state + .facts + .values() + .filter(|record| matches!(record.standing, FactStanding::Claimed { .. })) + .count() + } + + /// The horn belongs to the temple: its controller may speak on it whether + /// or not it stands inside its reach, and removing the controller flips the + /// same invocation to exactly one named failure. + #[test] + fn a_channel_controller_may_speak_outside_its_own_reach() { + let (mut kernel, speech, active) = speech_kernel("Controller"); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.listener)])), + }]), + ); + let proclaim = || { + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn still carries.", + ) + }; + utter(&mut kernel, speech.speaker, proclaim()) + .expect("the controller may speak on its own channel"); + + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::SetController { + channel: Ref::Existing(speech.horn), + controller: None, + }]), + ); + assert_eq!( + rejected(utter(&mut kernel, speech.speaker, proclaim())), + vec![ActionMismatch::NoAudience { precondition: 0 }] + ); + } + + /// Addressing does not narrow the audience, and a target outside it names + /// itself. A target that walked in mid-flight commits, and the whole + /// audience receives the telling, not only the addressed subject. + #[test] + fn an_addressed_subject_outside_the_audience_names_itself() { + let (mut kernel, speech, active) = speech_kernel("Addressing"); + let whisper = || { + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Come inside.", + ) + }; + assert_eq!( + rejected(utter(&mut kernel, speech.speaker, whisper())), + vec![ActionMismatch::CannotReach { precondition: 0 }] + ); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(speech.bystander), + via: Ref::Existing(speech.stair), + }]), + ); + utter(&mut kernel, speech.speaker, whisper()) + .expect("the addressed subject is now in the room"); + let claim = minted_claim(&kernel); + assert!(knows(&kernel, speech.bystander, claim).is_some()); + assert!( + knows(&kernel, speech.listener, claim).is_some(), + "speaking to someone in a room is heard by the room" + ); + } + + /// `Knows` compares confidence with one `>=`, and `Forget` removes the key + /// rather than storing a zero. + #[test] + fn knows_fails_below_its_confidence_and_forget_removes() { + let (mut kernel, speech, active) = speech_kernel("Knows"); + let recant = || DecisionInvocation { + affordance: speech.recant, + bindings: vec![binding("fact", Target::Entity(speech.flood))], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }; + assert_eq!( + rejected(utter(&mut kernel, speech.listener, recant())), + vec![ActionMismatch::FactUnknown { precondition: 0 }] + ); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + rejected(utter(&mut kernel, speech.listener, recant())), + vec![ActionMismatch::FactUnknown { precondition: 0 }], + "Believed falls short of Certain" + ); + + submit_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + utter(&mut kernel, speech.listener, recant()) + .expect("certainty admits the recant"); + // Absence is the one shape of knowing nothing: no row. + assert!(kernel.state.knowledge_of(speech.listener).next().is_none()); + + let active = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + }]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + + /// A telling never overwrites and never downgrades: the knower owns its own + /// credence. + #[test] + fn a_telling_never_overwrites_a_holder() { + let (mut kernel, speech, active) = speech_kernel("NoOverwrite"); + submit_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + let before = knows(&kernel, speech.listener, speech.flood); + let active = kernel.snapshot().unwrap(); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ); + assert_eq!(knows(&kernel, speech.listener, speech.flood), before); + assert_eq!( + knows(&kernel, speech.bystander, speech.flood), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: Some(speech.horn), + }, + acquired_at: active.revision + 1, + }) + ); + } + + /// Ontology admission: communication reaches only subjects inside the + /// channel's reach, and a speaker outside it is not speaking. + #[test] + fn communicating_from_outside_the_audience_is_rejected() { + let (mut kernel, speech, active) = speech_kernel("OutsideAudience"); + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }]), + ), + vec![Mismatch::SpeakerOutsideAudience { operation: 0 }] + ); + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ), + vec![Mismatch::SpeakerOutsideAudience { operation: 0 }] + ); + assert!(kernel.state.knowledge.is_empty()); + } + + /// The two allocation sites, asserted: only `derive_id` allocates, and the + /// action lane's one referent per invocation is reproduced by calling it + /// directly with the recorded world, command, handle, and discriminator. + #[test] + fn every_canonical_id_comes_from_one_of_two_sites() { + let (mut kernel, speech, active) = speech_kernel("Allocation"); + let world_id = kernel.state.header.world_id; + let caller = play_caller(); + let entities_before = kernel.state.entities.len(); + let whisper = command( + &active, + caller.clone(), + CommandBody::Act { + actor: speech.speaker, + invocation: say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Counted.", + ), + }, + ); + let command_id = whisper.id(); + kernel + .submit(whisper, &AuthenticatedCaller::fixture(caller)) + .expect("the whisper commits"); + + let claim = minted_claim(&kernel); + assert_eq!( + claim, + EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("ghostlight.speech"), + Some("0"), + )) + ); + // Exactly one referent, always a fact, always claimed by the actor. + assert_eq!(kernel.state.entities.len(), entities_before + 1); + assert_eq!(kernel.state.entities[&claim].kind, EntityKind::Fact); + assert_eq!( + kernel.state.facts[&claim].standing, + FactStanding::Claimed { by: speech.speaker } + ); + } + + /// Replay is exact because every allocation derives from committed inputs + /// and every fan-out is re-derived at apply from the audience plus live + /// state. + #[test] + fn restart_replay_after_speech_is_exact() { + let (speech, exported, expected, expected_events) = { + let mut kernel = WorldKernel::create(creation("ReplaySpeech"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, _) = speech_world(&mut kernel); + utter(&mut kernel, speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "One.", + ), + ) + .expect("the first proclamation commits"); + utter(&mut kernel, speech.listener, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.speaker))], + "Two.", + ), + ) + .expect("the whisper commits"); + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ); + let exported = kernel.export().unwrap(); + (speech, exported, kernel.state.clone(), kernel.events()) + }; + + let reopened = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(reopened.state.facts, expected.facts); + assert_eq!(reopened.state.channels, expected.channels); + assert_eq!(reopened.state.knowledge, expected.knowledge); + assert_eq!(reopened.events(), expected_events); + assert_eq!(reopened.state, expected); + assert!(reopened.state.knowledge_of(speech.bystander).next().is_some()); + } + + /// A forged claim does not apply, and a forged recipient list is + /// unrepresentable: `ResolvedOp::Communicate` stores an audience, never + /// recipients. + #[test] + fn a_forged_claim_or_forged_recipient_does_not_apply() { + let (kernel, speech, _) = speech_kernel("Forgery"); + let command_id = CommandId::issue(); + let caller = play_caller(); + let invocation = say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "Honest.", + ); + let granted = require_granted(&kernel.state, speech.speaker, invocation.affordance).unwrap(); + let honest = action::exercise( + &kernel.state, + command_id, + speech.speaker, + &granted, + &invocation, + ) + .expect("the honest event derives"); + let fact = honest.speech.expect("the honest claim"); + + let mut forged_claim = honest.clone(); + forged_claim.speech = Some(speech.flood); + let mut forged_statement = honest.clone(); + forged_statement.effects[0] = ResolvedOp::AssertClaim { + fact, + statement: Statement::new("Forged.").unwrap(), + by: speech.speaker, + }; + let mut forged_asserter = honest.clone(); + forged_asserter.effects[0] = ResolvedOp::AssertClaim { + fact, + statement: Statement::new("Honest.").unwrap(), + by: speech.listener, + }; + for forged in [forged_claim, forged_statement, forged_asserter] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + + // A recipient list cannot be forged because none is stored. + assert!(matches!( + honest.effects[1], + ResolvedOp::Communicate { + to: Audience::Channel(_), + .. + } + )); + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation, + event: honest, + }, + ) + .expect("the honest event applies"); + assert!(candidate.knowledge_of(speech.listener).next().is_some()); + } + + /// The scope table: a telling moves its listener's scope and leaves a bystander + /// alone, and a reach change moves only the controller's scope. + #[test] + fn a_telling_moves_only_the_listeners_scope() { + let (mut kernel, speech, _) = speech_kernel("ScopeMove"); + let digest = |kernel: &WorldKernel, subject: SubjectId| { + scope_components(&kernel.state, subject) + }; + let listener_before = digest(&kernel, speech.listener); + let bystander_before = digest(&kernel, speech.bystander); + + utter(&mut kernel, speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Only you.", + ), + ) + .expect("the whisper commits"); + assert_ne!(digest(&kernel, speech.listener), listener_before); + assert_eq!(digest(&kernel, speech.bystander), bystander_before); + + // Reach membership is admission-only: adding a hearer moves the + // controller's digest and nobody else's. + let active = kernel.snapshot().unwrap(); + let hearer_before = digest(&kernel, speech.listener); + let speaker_before = digest(&kernel, speech.speaker); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.stranger)])), + }]), + ); + assert_eq!(digest(&kernel, speech.listener), hearer_before); + assert_ne!(digest(&kernel, speech.speaker), speaker_before); + } + + /// A speech-carrying entry names exactly one audience: none is unlowerable + /// and two is unchoosable. Each rejection allocates no `AffordanceId`. + #[test] + fn a_speech_carrying_entry_must_declare_exactly_one_audience() { + let mut kernel = WorldKernel::create(creation("SpeechAudience"), + &auth_principal(owner()), + ) + .expect("a draft world") + .0; + let before = kernel.snapshot().unwrap(); + let catalog_before = kernel.state.affordance_catalog.len(); + let declare = |preconditions: Vec| CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("herald"), + kind: AffordanceKindName("herald".into()), + roles: Vec::new(), + preconditions, + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }; + assert_eq!( + reject_play(&mut kernel, &before, declare(Vec::new())), + vec![Mismatch::SpeechWithoutAudience { + handle: DraftHandle::new("herald"), + }] + ); + assert_eq!( + reject_play( + &mut kernel, + &before, + declare(vec![ + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + ]), + ), + vec![Mismatch::AmbiguousSpeechAudience { + handle: DraftHandle::new("herald"), + }] + ); + assert_eq!(kernel.state.affordance_catalog.len(), catalog_before); + } + + /// The kernel does not compare two statements: no dedup, no interning, no + /// contradiction check, no similarity. A claim byte-identical to a + /// canonical fact and one that plainly negates it commit identically. + #[test] + fn the_kernel_never_compares_two_statements() { + let run = |name: &str, text: &str| { + let (mut kernel, speech, _) = speech_kernel(name); + let receipt = utter(&mut kernel, speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + text, + ), + ) + .expect("both statements commit identically"); + assert!(receipt.resulting_revision > 0); + let events = kernel.events(); + let event = events.last().unwrap().clone(); + (kernel, speech, event) + }; + let (agreeing, agreeing_speech, agreeing_event) = run("agree", FLOOD_STATEMENT); + let (negating, _, negating_event) = run("negate", "The lower hinge is dry."); + + assert_eq!(agreeing_event.band, negating_event.band); + assert_eq!(agreeing_event.effects.len(), negating_event.effects.len()); + assert_eq!(agreeing.state.facts.len(), negating.state.facts.len()); + // Two facts with byte-identical statements are two facts: the claim is + // not the canonical fact it repeats, and neither run learned anything + // about the other's meaning. + let claim = agreeing_event.speech.unwrap(); + assert_ne!(claim, agreeing_speech.flood); + assert_eq!( + agreeing.state.facts[&claim].statement, + agreeing.state.facts[&agreeing_speech.flood].statement + ); + assert_ne!( + agreeing.state.facts[&claim].standing, + agreeing.state.facts[&agreeing_speech.flood].standing + ); + } +} + +/// Soul's pass-6 falsification set. Each test names the claim it attacks and, +/// where the landed behaviour differs from the specified one, pins the actual +/// behaviour so the difference is visible rather than assumed. +#[cfg(test)] +mod soul_knowledge_tests { + use super::tests::{ + act, play_caller, FLOOD_STATEMENT, Speech, affordance_named, auth_principal, command, creation, operations, + owner, speech_world, submit_play, + }; + use super::*; + + fn speech_kernel(title: &str) -> (WorldKernel, Speech, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + (kernel, speech, active) + } + + fn say(affordance: AffordanceId, bindings: Vec, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn utter( + kernel: &mut WorldKernel, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + act(kernel, actor, invocation) + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option { + kernel + .state + .knowledge + .get(&(subject, fact)) + .copied() + } + + fn digest_of(kernel: &WorldKernel, subject_id: SubjectId) -> ScopeComponents { + scope_components(&kernel.state, subject_id) + } + + fn minted_claim(kernel: &WorldKernel) -> EntityId { + kernel + .events() + .last() + .expect("the committed event") + .speech + .expect("a speech act names its claim") + } + + /// A channel's controller carries exactly one privilege: `can_broadcast` + /// lets it sound the horn from outside the declared reach. `audience` + /// itself never folds the controller in, so the controller is not a + /// recipient of a telling it did not stand inside, whether the telling is + /// its own or another subject's. + #[test] + fn soul_a_channel_controller_hears_what_it_is_out_of_reach_of() { + let (mut kernel, speech, active) = speech_kernel("ControllerHears"); + // The horn now reaches exactly one subject. The speaker controls it and + // is not in that set. + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.listener)])), + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + kernel.state.channels[&speech.horn].reach, + Reach::Subjects(BTreeSet::from([speech.listener])) + ); + + // The controller may still speak from outside its own reach — the horn + // belongs to the temple — and the listener, who stands inside the + // reach, hears it. + utter(&mut kernel, speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn is mine to sound.", + ), + ) + .expect("the controller may speak on its own channel"); + let controllers_claim = minted_claim(&kernel); + assert_eq!( + knows(&kernel, speech.listener, controllers_claim), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: Some(speech.horn), + }, + acquired_at: active.revision + 1, + }) + ); + // The controller gains no knowledge of its own claim: it is outside + // the reach, and speaking privilege is not audience membership. + assert_eq!(knows(&kernel, speech.speaker, controllers_claim), None); + + // Now the listener speaks on the same channel. + utter(&mut kernel, speech.listener, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn is mine tonight.", + ), + ) + .expect("a subject inside the reach may broadcast"); + let claim = minted_claim(&kernel); + + // The declared reach names the listener alone, and the listener spoke, + // so the declared fan-out is empty. The controller — outside the + // reach, and not the speaker this time either — learns nothing. + assert_eq!( + knows(&kernel, speech.speaker, claim), + None, + "the controller does not gain knowledge through fan-out" + ); + assert_eq!(knows(&kernel, speech.bystander, claim), None); + assert_eq!(knows(&kernel, speech.stranger, claim), None); + assert_eq!(knows(&kernel, speech.listener, claim), None); + } + + /// Every speech precondition fails at `exercise`, before the band draw and + /// before the speech lowering, so a refused utterance mints no claim and + /// leaves the whole committed state byte-identical. Nothing here reaches + /// replay to be caught later. + #[test] + fn soul_a_refused_utterance_dies_at_the_gate_and_allocates_nothing() { + let (mut kernel, speech, active) = speech_kernel("GateNotReplay"); + let speak = affordance_named(&active, "speak"); + let before = kernel.state.clone(); + + let cases: Vec<(SubjectId, DecisionInvocation, Vec)> = vec![ + // Unplaced: no co-location audience at all. + ( + speech.stranger, + say(speak, Vec::new(), "Anyone?"), + vec![ActionMismatch::NoAudience { precondition: 0 }], + ), + // Addressed at a subject one containment level down. + ( + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Down there.", + ), + vec![ActionMismatch::CannotReach { precondition: 0 }], + ), + // `recant` requires `Knows { at_least: Certain }` of the bound fact. + // Its unproposed slot names itself beside the precondition; the + // point is that the complete set lands at the gate, in one pass. + ( + speech.speaker, + DecisionInvocation { + affordance: speech.recant, + bindings: vec![binding("fact", Target::Entity(speech.flood))], + proposed: Vec::new(), + speech: None, + display: None, + }, + vec![ + ActionMismatch::SlotNotProposed { slot: 0 }, + ActionMismatch::FactUnknown { precondition: 0 }, + ], + ), + ]; + + for (actor, invocation, expected) in cases { + let error = utter(&mut kernel, actor, invocation).unwrap_err(); + let KernelError::ActionRejected(mismatches) = error else { + panic!("expected an action rejection, got {error:?}"); + }; + assert_eq!(mismatches, expected); + // No claim, no entity row, no event, no revision: the gate ran + // before anything was drawn or lowered. + assert_eq!(kernel.state, before); + } + } + + /// Fan-out is the sole way knowledge enters another subject from speech, and + /// it is not carried by the effect. A forged `Acted` that widens + /// the audience, appends a second telling, or tells a foreign fact is refused + /// by `apply_effect` itself, so replay is never the first reader to notice. + #[test] + fn soul_a_forged_wider_audience_does_not_apply() { + let (kernel, speech, _) = speech_kernel("WiderAudience"); + let command_id = CommandId::issue(); + let caller = play_caller(); + let invocation = say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Only the hall.", + ); + let granted = require_granted(&kernel.state, speech.speaker, invocation.affordance).unwrap(); + let honest = action::exercise( + &kernel.state, + command_id, + speech.speaker, + &granted, + &invocation, + ) + .expect("the honest event derives"); + let fact = honest.speech.expect("the honest claim"); + assert_eq!( + honest.effects[1], + ResolvedOp::Communicate { + speaker: speech.speaker, + fact, + to: Audience::Colocated, + } + ); + + // Widened to the horn, which covers the yard through `covers_place`. + let mut widened = honest.clone(); + widened.effects[1] = ResolvedOp::Communicate { + speaker: speech.speaker, + fact, + to: Audience::Channel(speech.horn), + }; + // A second telling appended to the same event. + let mut doubled = honest.clone(); + doubled.effects.push(ResolvedOp::Communicate { + speaker: speech.speaker, + fact: speech.flood, + to: Audience::Colocated, + }); + // A telling of a fact this act did not mint. + let mut foreign = honest.clone(); + foreign.effects[1] = ResolvedOp::Communicate { + speaker: speech.speaker, + fact: speech.flood, + to: Audience::Colocated, + }; + + for forged in [widened, doubled, foreign] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + } + + /// The reducer re-derives the audience gate from committed state, so a forged + /// `Communicate` for a speaker with no standing in the room is refused even + /// when the fact is live and the event carries no mismatch. The same telling + /// by a speaker who is in the room applies. + #[test] + fn a_telling_by_a_speaker_outside_its_audience_does_not_apply() { + let (kernel, speech, _) = speech_kernel("OutsideAudience"); + let resolves_to = kernel.state.revision + 1; + + let mut candidate = kernel.state.clone(); + let error = apply_operation( + &mut candidate, + &ResolvedOp::Communicate { + speaker: speech.stranger, + fact: speech.flood, + to: Audience::Colocated, + }, + &[], + resolves_to, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + + let mut candidate = kernel.state.clone(); + apply_operation( + &mut candidate, + &ResolvedOp::Communicate { + speaker: speech.speaker, + fact: speech.flood, + to: Audience::Colocated, + }, + &[], + resolves_to, + ) + .expect("a speaker inside its audience tells"); + } + + /// A speech act that lands nothing moves no digest at all, the speaker's own + /// included. `AssertClaim` writes `entities` and `facts`, and neither is a + /// scope component, so an in-flight proposal held by anyone in the world + /// survives an utterance nobody heard. + #[test] + fn soul_speech_that_lands_nothing_moves_no_digest_including_the_speakers() { + let (mut kernel, speech, active) = speech_kernel("NoDigestMove"); + let speak = affordance_named(&active, "speak"); + let everyone = [ + speech.speaker, + speech.listener, + speech.bystander, + speech.stranger, + ]; + let before: Vec = everyone + .iter() + .map(|subject| digest_of(&kernel, *subject)) + .collect(); + let facts_before = kernel.state.facts.len(); + + // The bystander stands alone in the yard. + utter(&mut kernel, speech.bystander, + say(speak, Vec::new(), "Nobody is here."), + ) + .expect("speaking into an empty room commits"); + + assert_eq!(kernel.state.facts.len(), facts_before + 1); + assert_eq!(kernel.events().len(), 1); + assert!(kernel.state.knowledge.is_empty()); + for (subject, digest) in everyone.iter().zip(before) { + assert_eq!( + digest_of(&kernel, *subject), + digest, + "an utterance nobody heard moved a scope" + ); + } + } + + /// The resolver does not model a `Communicate`'s fan-out, so a same-patch + /// telling followed by a `Forget` of what that telling would have landed is + /// refused at resolve although apply would accept it. The asymmetry is + /// fail-closed, and it does not refuse the order that must work: forgetting + /// first and being told again in the same patch commits, and the telling is + /// what the subject ends up holding. + #[test] + fn soul_a_same_patch_telling_then_forget_fails_closed_only() { + let (mut kernel, speech, active) = speech_kernel("SamePatchOrder"); + let tell = ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }; + let forget = ComponentOp::Forget { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + }; + + let error = kernel + .submit( + command( + &active, + CallerId::Play, + operations(vec![tell.clone(), forget.clone()]), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + assert_eq!( + mismatches, + vec![Mismatch::NoOperationEffect { operation: 1 }] + ); + + // The legitimate order. The listener holds the fact first, forgets it, + // and the telling in the same patch lands it again as a telling, which + // is what the committed state carries. + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }]), + ); + let active = kernel.snapshot().unwrap(); + submit_play(&mut kernel, &active, operations(vec![forget, tell])); + assert_eq!( + knows(&kernel, speech.listener, speech.flood), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: None, + }, + acquired_at: active.revision + 1, + }) + ); + } + + /// `verify_state_shape` checks the forward speech direction only: an event's + /// claim is asserted by the acting subject and named by no other event. The + /// reverse, that every claim is named by some event, is deliberately absent, + /// because a world may declare a claim with no event behind it, in Draft + /// or, by the play table, in Active. Such a + /// claim is a valid shape and its store reopens. + #[test] + fn an_orphan_claim_is_a_valid_shape_and_reopens() { + let (mut kernel, speech, active) = speech_kernel("OrphanClaim"); + // The Draft-declared fact is an orphan by construction: no event names + // it. Reopening runs the shape verifier over the replayed state. + assert!(kernel.state.facts.contains_key(&speech.flood)); + assert!( + kernel + .events() + .iter() + .all(|event| event.speech.is_none()) + ); + + let before = kernel.state.clone(); + let receipt = kernel + .submit( + command( + &active, + CallerId::Play, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rumour"), + label: "a rumour".into(), + statement: Statement::new("The gate is unguarded.").unwrap(), + standing: FactStandingRef::Claimed { + by: Ref::Existing(speech.speaker), + }, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::fixture(CallerId::Play), + ) + .expect("the play table declares a claim in Active"); + assert!(receipt.resulting_revision > 0); + assert_eq!(kernel.state.facts.len(), before.facts.len() + 1); + let facts = kernel.state.facts.clone(); + let exported = kernel.export().unwrap(); + drop(kernel); + let replayed = WorldKernel::open(&exported).expect("the orphan store is healthy"); + assert_eq!(replayed.state.facts, facts); + } + + /// Replay equality across every new arm, twice, with no RNG and no clock in + /// any of them: a speech act, a telling, an authored acquisition, a forget, + /// a reach change, and a controller change all reproduce byte-identically + /// from the journal, and reopening again reproduces the same state. + #[test] + fn soul_replay_is_exact_across_every_new_arm() { + let (exported, expected, expected_events) = { + let (mut kernel, speech, _) = speech_kernel("ReplayArms"); + utter(&mut kernel, speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The hinge is flooding.", + ), + ) + .expect("the proclamation commits"); + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + operations(vec![ + ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }, + ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }, + ComponentOp::SetController { + channel: Ref::Existing(speech.horn), + controller: Some(Ref::Existing(speech.listener)), + }, + ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Place(Ref::Existing(speech.yard)), + }, + ]), + ); + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + }]), + ); + assert!(!kernel.state.knowledge.is_empty()); + assert!(!kernel.state.facts.is_empty()); + (kernel.export().unwrap(), kernel.state.clone(), kernel.events()) + }; + + for _ in 0..2 { + let replayed = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(replayed.state.facts, expected.facts); + assert_eq!(replayed.state.channels, expected.channels); + assert_eq!(replayed.state.knowledge, expected.knowledge); + assert_eq!(replayed.state.entities, expected.entities); + assert_eq!(replayed.events(), expected_events); + assert_eq!(replayed.state, expected); + } + } + + /// The statement's bytes are stored twice, and only one of the two copies + /// is a read surface. `facts[fact].statement` is the readable home: + /// `spoken()` and every projection consult it. The committed event's own + /// `AssertClaim` effect carries the same bytes as the replay witness — + /// required so `apply_effect` can re-derive the identical event on replay + /// without re-deriving the statement from elsewhere — but nothing reads + /// that copy back out. Those two are the whole of it, and neither reaches + /// a subject-facing surface. + #[test] + fn soul_the_utterance_is_stored_in_facts_and_in_the_committed_effect() { + let (mut kernel, speech, active) = speech_kernel("OneHome"); + let speak = affordance_named(&active, "speak"); + let text = "A statement that appears nowhere else."; + utter(&mut kernel, speech.speaker, + say(speak, Vec::new(), text), + ) + .expect("the kernel speak commits"); + let claim = minted_claim(&kernel); + + assert_eq!(kernel.state.facts[&claim].statement.as_str(), text); + assert_eq!( + kernel.state.entities[&claim].label, CLAIM_LABEL, + "the label is a name, not a transcript" + ); + // The event no longer embeds the invocation, and its `speech` field is + // the fact id. The bytes still appear in the event, inside the committed + // `AssertClaim` effect. + let events = kernel.events(); + let event = events.last().unwrap(); + assert_eq!(event.speech, Some(claim)); + assert_eq!( + event.effects[0], + ResolvedOp::AssertClaim { + fact: claim, + statement: Statement::new(text).unwrap(), + by: speech.speaker, + }, + "the event carries the statement as a replay witness, not a second read surface" + ); + // The facts are the whole of it: strip them and the + // rest of the state is silent. + let mut stripped = kernel.state.clone(); + let facts: Vec<_> = stripped.facts.keys().copied().collect(); + for fact in facts { + stripped.facts.remove(&fact); + } + let encoded = stripped.encoded_documents(); + assert!( + !encoded + .windows(text.len()) + .any(|window| window == text.as_bytes()) + ); + // The statement declared in Draft is untouched by any of it. + assert_eq!( + kernel.state.facts[&speech.flood].statement.as_str(), + FLOOD_STATEMENT + ); + } +} + +/// One witnessed event over a place subtree: who it reaches, who it leaves +/// alone, where it is refused, and what it costs an in-flight binding. +#[cfg(test)] +mod witness_tests { + use super::tests::{ + play_caller, auth_principal, command, creation, operations, owner, + reject_play, submit_play, + }; + use super::*; + + /// Nesting, because "under a place" is the whole question. A hemisphere + /// holds a region and a far coast; the region holds a village and one + /// unwalked hollow; subjects stand in the village, on the coast, and in the + /// hemisphere under neither. The hollow is empty so a witness has a place + /// that reaches nobody. + struct Nesting { + hemisphere: EntityId, + region: EntityId, + village: EntityId, + coast: EntityId, + hollow: EntityId, + villager: SubjectId, + neighbour: SubjectId, + coaster: SubjectId, + drifter: SubjectId, + asteroid: EntityId, + moon: EntityId, + ferry: EdgeId, + } + + fn place(handle: &str, label: &str, container: Option<&str>) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: container.map(|value| Ref::Draft(DraftHandle::new(value))), + }) + } + + fn stander(handle: &str, label: &str, place: &str, speak: &Ref) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak.clone(), Ref::Draft(DraftHandle::new("beacon"))]), + position: Some(Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + } + + fn sky_fact(handle: &str, label: &str, statement: &str, evidence: &str) -> Declaration { + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + statement: Statement::new(statement).unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(evidence), + }, + }) + } + + fn witness(fact: EntityId, place: EntityId, confidence: Confidence) -> ComponentOp { + ComponentOp::Witness { + fact: Ref::Existing(fact), + place: Ref::Existing(place), + confidence, + } + } + + fn nesting_kernel(title: &str) -> (WorldKernel, Nesting, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let before = kernel.snapshot().unwrap(); + let speak = super::tests::speak_entry(&kernel); + submit_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + place("hemisphere", "The Lit Hemisphere", None), + place("region", "The Rhythm Region", Some("hemisphere")), + place("village", "The Anchor Village", Some("region")), + place("hollow", "The Unwalked Hollow", Some("region")), + place("coast", "The Far Coast", Some("hemisphere")), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("ferry"), + label: "The Coast Ferry".into(), + from: Ref::Draft(DraftHandle::new("coast")), + to: Ref::Draft(DraftHandle::new("village")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("path"), + label: "The Hollow Path".into(), + from: Ref::Draft(DraftHandle::new("village")), + to: Ref::Draft(DraftHandle::new("hollow")), + access: AccessKind::Public, + cost: Cost(1), + }), + // A world-authored verb with no speaker in it: the + // proposer chooses which declared place the entry + // binds and nothing else. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("beacon"), + kind: AffordanceKindName("beacon".into()), + roles: vec![ + RoleSpec { + role: Role("fact".into()), + kind: RefKind::Entity(EntityKind::Fact), + }, + RoleSpec { + role: Role("place".into()), + kind: RefKind::Entity(EntityKind::Place), + }, + ], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Witness { + confidence: Confidence::Believed, + }, + roles: vec![Role("fact".into()), Role("place".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + stander("villager", "The Anchor Villager", "village", &speak), + stander("neighbour", "The Anchor Neighbour", "village", &speak), + stander("coaster", "The Coast Watcher", "coast", &speak), + stander("drifter", "The Open Drifter", "hemisphere", &speak), + sky_fact( + "asteroid", + "the asteroid over the region", + "An asteroid crossed the sky above the region.", + "vault:asteroid", + ), + sky_fact( + "moon", + "the second moon", + "A second moon rose over the hemisphere.", + "vault:moon", + ), + ], + operations: Vec::new(), + evidence: vec![ + EvidenceRef::new("vault:asteroid"), + EvidenceRef::new("vault:moon"), + ], + }, + }, + ); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared entity") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared subject") + .0 + }; + let nesting = Nesting { + hemisphere: entity("The Lit Hemisphere"), + region: entity("The Rhythm Region"), + village: entity("The Anchor Village"), + coast: entity("The Far Coast"), + hollow: entity("The Unwalked Hollow"), + villager: subject("The Anchor Villager"), + neighbour: subject("The Anchor Neighbour"), + coaster: subject("The Coast Watcher"), + drifter: subject("The Open Drifter"), + asteroid: entity("the asteroid over the region"), + moon: entity("the second moon"), + ferry: *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "The Coast Ferry") + .expect("a declared route") + .0, + }; + let active = kernel.snapshot().unwrap(); + (kernel, nesting, active) + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option { + kernel + .state + .knowledge + .get(&(subject, fact)) + .copied() + } + + fn seen(confidence: Confidence, acquired_at: u64) -> Option { + Some(Knowledge { + confidence, + source: KnowledgeSource::Witnessed, + acquired_at, + }) + } + + /// The subtree is the whole reach: everyone under the named place, nobody + /// beside it, and a wider place reaches the wider set. + #[test] + fn a_witness_reaches_every_subject_under_the_place_and_no_other() { + let (mut kernel, world, active) = nesting_kernel("Reach"); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Believed, + )]), + ); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!(knows(&kernel, world.coaster, world.asteroid), None); + assert_eq!(knows(&kernel, world.drifter, world.asteroid), None); + + let after = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &after, + operations(vec![witness( + world.moon, + world.hemisphere, + Confidence::Certain, + )]), + ); + for subject in [ + world.villager, + world.neighbour, + world.coaster, + world.drifter, + ] { + assert_eq!( + knows(&kernel, subject, world.moon), + seen(Confidence::Certain, after.revision + 1) + ); + } + + // No witness names a teller, so nothing in the world was told. + assert!( + kernel + .state + .knowledge + .values() + .all(|entry| !matches!(entry.source, KnowledgeSource::Told { .. })), + "a witness wrote a told row" + ); + } + + /// The knower owns its credence. A holder is dropped from the landing + /// whatever it holds and however it came by it, so a witness cannot reset a + /// mind by repeating itself. + #[test] + fn a_witness_never_overwrites_a_holder() { + let (kernel, world, _) = nesting_kernel("Holder"); + // `Told` has exactly one writer, so the holder's row is planted at the + // layer that can hold one and the witness is applied beside it. + let held = Knowledge { + confidence: Confidence::Doubted, + source: KnowledgeSource::Told { + by: world.coaster, + via: None, + }, + acquired_at: 0, + }; + let mut state = kernel.state.clone(); + let state_revision = state.revision; + state.knowledge.insert((world.villager, world.asteroid), held); + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place: world.region, + confidence: Confidence::Certain, + }, + &[], + state_revision + 1, + ) + .expect("the witness lands"); + assert_eq!(state.knowledge[&(world.villager, world.asteroid)], held); + assert_eq!( + state.knowledge[&(world.neighbour, world.asteroid)], + Knowledge { + confidence: Confidence::Certain, + source: KnowledgeSource::Witnessed, + acquired_at: state_revision + 1, + } + ); + } + + /// A witnessed event is only its reception, so a landing that reaches + /// nobody is not an event the world recorded. Both layers refuse it, and + /// they refuse the same two cases: an empty subtree, and a subtree whose + /// every stander already holds the fact. + #[test] + fn a_witness_over_nobody_is_refused_at_resolve_and_at_apply() { + let (mut kernel, world, active) = nesting_kernel("Nobody"); + let forged = |place: EntityId, state: &WorldState| { + let resolves_to = state.revision + 1; + let mut state = state.clone(); + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place, + confidence: Confidence::Certain, + }, + &[], + resolves_to, + ) + .unwrap_err() + }; + + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.hollow, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert!(matches!( + forged(world.hollow, &kernel.state), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + + // Every stander already holds it, which is the same refusal. + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain, + )]), + ); + let after = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &after, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert!(matches!( + forged(world.village, &kernel.state), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + + // A forged effect naming a place that is not one, or no live fact, is + // refused by the arm's own kind check before any of that. + let mut state = kernel.state.clone(); + let resolves_to = state.revision + 1; + assert!(matches!( + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place: world.asteroid, + confidence: Confidence::Certain, + }, + &[], + resolves_to, + ) + .unwrap_err(), + KernelError::Invariant(message) if message == "a witness names no live fact or place" + )); + } + + /// The candidate map models the fan-out, so a subject this patch moved into + /// the subtree is a recipient and a subject it moved out is not. The resolve + /// layer and the apply layer agree on both. + #[test] + fn a_mid_patch_relocation_into_the_subtree_counts() { + let (mut kernel, world, active) = nesting_kernel("Relocation"); + // The village's own standers already hold it, so the relocated coaster + // is the only candidate recipient left. + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + let seeded = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &seeded, + operations(vec![ + ComponentOp::Relocate { + subject: Ref::Existing(world.coaster), + via: Ref::Existing(world.ferry), + }, + witness(world.asteroid, world.village, Confidence::Certain), + ]), + ); + assert_eq!( + kernel.state.positions[&world.coaster], + Position { + place: world.village + } + ); + assert_eq!( + knows(&kernel, world.coaster, world.asteroid), + seen(Confidence::Certain, seeded.revision + 1) + ); + + // The inverse: the coast's only stander leaves before the witness, so + // the coast reaches nobody. Both layers say so. + let moved = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &moved, + operations(vec![witness(world.moon, world.coast, Confidence::Certain)]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + let mut state = kernel.state.clone(); + let resolves_to = state.revision + 1; + assert!(matches!( + apply_operations( + &mut state, + &[ResolvedOp::Witness { + fact: world.moon, + place: world.coast, + confidence: Confidence::Certain, + }], + &[], + resolves_to, + ) + .unwrap_err(), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + } + + /// The components carry the keys of a subject's own knowledge, so a witness + /// moves exactly the components of the subjects that learned something. + #[test] + fn a_witness_moves_every_recipients_scope_components_and_nobody_elses() { + let (mut kernel, world, active) = nesting_kernel("Digest"); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(world.neighbour), + fact: Ref::Existing(world.asteroid), + source: AuthoredSource::Witnessed, + confidence: Confidence::Doubted, + }]), + ); + let digest = |kernel: &WorldKernel, subject_id: SubjectId| { + scope_components(&kernel.state, subject_id) + }; + let learner = digest(&kernel, world.villager); + let holder = digest(&kernel, world.neighbour); + let outsider = digest(&kernel, world.coaster); + + let seeded = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &seeded, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert_ne!(digest(&kernel, world.villager), learner); + assert_eq!(digest(&kernel, world.neighbour), holder); + assert_eq!(digest(&kernel, world.coaster), outsider); + } + + /// The slot names a fact and a place, never a subject, so an exercised + /// witness lands the subtree with no teller anywhere in it. A slot whose + /// place position binds a subject is refused before it is ever declared. + #[test] + fn a_witness_affordance_lowers_with_no_speaker() { + let (mut kernel, world, active) = nesting_kernel("Affordance"); + let beacon = *active + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .expect("the villager exists") + .affordances + .iter() + .find(|id| { + active + .affordances + .iter() + .any(|entry| entry.id == **id && entry.entry.kind.0 == "beacon") + }) + .expect("the villager holds the beacon entry"); + let caller = play_caller(); + kernel + .submit( + command( + &active, + caller.clone(), + CommandBody::Act { + actor: world.villager, + invocation: DecisionInvocation { + affordance: beacon, + bindings: vec![ + RoleBinding { + role: Role("fact".into()), + target: Target::Entity(world.asteroid), + }, + RoleBinding { + role: Role("place".into()), + target: Target::Entity(world.region), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the beacon lands"); + assert_eq!( + kernel + .events() + .last() + .expect("a committed event") + .effects, + vec![ResolvedOp::Witness { + fact: world.asteroid, + place: world.region, + confidence: Confidence::Believed, + }] + ); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!(knows(&kernel, world.coaster, world.asteroid), None); + + // The second role is a place, and a subject cannot serve it, so a slot + // that named one is refused at affordance declaration. + let rules = ComponentOpKind::Witness { + confidence: Confidence::Believed, + } + .arity(); + assert_eq!(rules.len(), 2); + assert!(patch::role_kind_fits( + &rules[0], + RefKind::Entity(EntityKind::Fact) + )); + assert!(patch::role_kind_fits( + &rules[1], + RefKind::Entity(EntityKind::Place) + )); + assert!(!patch::role_kind_fits(&rules[1], RefKind::Subject(None))); + } + + /// A journal carrying a witness replays to digest equality, and the rows it + /// wrote pass the shape check with no clause of their own. + #[test] + fn a_world_with_a_witness_replays() { + let (mut kernel, world, active) = nesting_kernel("Replay"); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + let committed = kernel.state.clone(); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = + WorldKernel::open(&exported).expect("it replays"); + assert_eq!(reopened.state, committed); + assert_eq!( + knows(&reopened, world.villager, world.asteroid), + seen(Confidence::Certain, active.revision + 1) + ); + } + + /// PA.f49: `acquired_at` stamps the revision the write's own commit + /// resolves to on every path, genesis included. Genesis resolves to + /// revision 0 itself — `state.revision` never advances past 0 for the + /// creating commit — so a fact a genesis patch both declares and grants + /// knowledge of lands at `acquired_at: 0`, not one revision ahead of the + /// state it was written into. + #[test] + fn a_genesis_seeded_knowledge_row_is_acquired_at_revision_zero() { + let mut creation = creation("PAf49Genesis"); + creation.patch.declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("founding"), + label: "The Founding Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Claimed { + by: Ref::Draft(DraftHandle::new("human")), + }, + })); + creation.patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Draft(DraftHandle::new("human")), + fact: Ref::Draft(DraftHandle::new("founding")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + let (kernel, _) = WorldKernel::create(creation, &auth_principal(owner())).unwrap(); + assert_eq!(kernel.state.revision, 0); + let human = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Human") + .expect("genesis admits the declared human") + .0; + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == "Stated by the table.") + .expect("genesis admits the declared fact") + .0; + assert_eq!( + kernel.state.knowledge[&(human, fact)].acquired_at, + 0, + "a genesis-seeded row landed one revision ahead of the state it was written into" + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + } + + /// PA.f49: every commit after genesis still stamps the revision it + /// resolves to, one past the state it was applied against. + #[test] + fn a_later_commits_knowledge_row_is_acquired_at_that_commits_revision() { + let (mut kernel, world, active) = nesting_kernel("PAf49Later"); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(world.villager), + fact: Ref::Existing(world.asteroid), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }]), + ); + assert_eq!(kernel.state.revision, active.revision + 1); + assert_eq!( + kernel.state.knowledge[&(world.villager, world.asteroid)].acquired_at, + active.revision + 1 + ); + } + + /// PA.f49: the shape check refuses a knowledge row forged ahead of the + /// world's own revision — the check `verify_state_shape` gained alongside + /// the genesis fix, so a corrupt or forged `acquired_at` cannot pass + /// replay silently. + #[test] + fn a_shape_check_refuses_a_knowledge_row_forged_ahead_of_the_world_revision() { + let (mut kernel, world, active) = nesting_kernel("PAf49Shape"); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + let mut forged = kernel.state.clone(); + let entry = forged + .knowledge + .get_mut(&(world.villager, world.asteroid)) + .expect("the witness landed on the villager"); + entry.acquired_at = forged.revision + 1; + assert!(journal::verify_state_shape(&forged).is_err()); + } + + /// The two callers of the shared owners answer the same question. A + /// `Reach::Place` channel's fan-out and a witness over the same place select + /// the same subjects over the same state, so "under a place" and "already a + /// knower" cannot drift between a declared broadcast area and a witnessed + /// event. A grep proves there is one body; this proves the two lanes reach + /// it. + #[test] + fn soul_a_place_reach_fan_out_and_a_witness_select_the_same_subjects() { + let (kernel, world, _) = nesting_kernel("One owner"); + let mut state = kernel.state.clone(); + // One holder, so the already-holds half of the selection is exercised + // and not merely the subtree half. + state.knowledge.insert( + (world.neighbour, world.asteroid), + Knowledge { + confidence: Confidence::Doubted, + source: KnowledgeSource::Witnessed, + acquired_at: 0, + }, + ); + for root in [world.hemisphere, world.region, world.village, world.coast] { + let horn = state + .entities + .keys() + .copied() + .find(|id| !state.channels.contains_key(id)) + .expect("an unused key for the horn"); + state.channels.insert( + horn, + patch::ChannelRecord { + reach: patch::Reach::Place(root), + controller: None, + }, + ); + for speaker in [world.coaster, world.drifter, world.villager] { + // `fan_out` is exactly the shared pair with the speaker taken + // out; the speaker clause is the only thing it owns itself. + let mut expected = under_place(&state, root); + expected.remove(&speaker); + assert_eq!( + fan_out( + &state, + speaker, + world.asteroid, + &patch::Audience::Channel(horn), + ), + unheld(&state, world.asteroid, expected), + "the two lanes disagreed about {root:?} for {speaker:?}" + ); + } + state.channels.remove(&horn); + } + } + + /// Presence in the subtree is read from `positions` alone. A place covers + /// itself, covers its children transitively, and covers nothing beside it; + /// a subject standing nowhere is under nothing, at every root including the + /// world's widest. + #[test] + fn soul_under_place_covers_itself_and_below_and_never_the_placeless() { + let (kernel, world, _) = nesting_kernel("Nesting"); + let under = |root: EntityId| under_place(&kernel.state, root); + // The village holds its two standers and nobody else. + assert_eq!( + under(world.village), + BTreeSet::from([world.villager, world.neighbour]) + ); + // The region covers the village transitively and the drifter standing + // one level above it is not swept in. + assert_eq!( + under(world.region), + BTreeSet::from([world.villager, world.neighbour]) + ); + // The hemisphere covers everything below it and the drifter standing + // exactly at it, not merely below. + assert_eq!( + under(world.hemisphere), + BTreeSet::from([ + world.villager, + world.neighbour, + world.coaster, + world.drifter, + ]) + ); + assert_eq!(under(world.coast), BTreeSet::from([world.coaster])); + assert!(under(world.hollow).is_empty()); + + // A subject with no position is under nothing, at every root including + // the world's widest, and the widest witness in the world does not + // reach it. Presence is read from `positions` alone: there is no second + // notion of being somewhere for a placeless subject to fall back on. + let mut adrift = kernel.state.clone(); + let adrift_revision = adrift.revision; + adrift.positions.remove(&world.drifter); + for root in [ + world.hemisphere, + world.region, + world.village, + world.coast, + world.hollow, + ] { + assert!( + !under_place(&adrift, root).contains(&world.drifter), + "a placeless subject was under {root:?}" + ); + } + apply_operation( + &mut adrift, + &ResolvedOp::Witness { + fact: world.moon, + place: world.hemisphere, + confidence: Confidence::Certain, + }, + &[], + adrift_revision + 1, + ) + .expect("the hemisphere still reaches the standers"); + assert!( + !adrift + .knowledge + .contains_key(&(world.drifter, world.moon)), + "a placeless subject witnessed the widest event in the world" + ); + for subject in [world.villager, world.neighbour, world.coaster] { + assert_eq!( + adrift.knowledge[&(subject, world.moon)], + Knowledge { + confidence: Confidence::Certain, + source: KnowledgeSource::Witnessed, + acquired_at: adrift_revision + 1, + } + ); + } + } + + /// The candidate model and the apply arm are handed a patch built so they + /// could disagree: the only subject the witness can reach is one this same + /// patch declares and places, and every subject already standing there + /// already holds the fact. If the resolver did not see the draft stander it + /// would refuse a landing the apply pass performs; if the apply pass did + /// not see it, it would refuse a landing the resolver admitted. Both see + /// it. The inverse — a draft subject declared with no position — is refused + /// by both. + #[test] + fn soul_a_subject_declared_and_placed_in_one_patch_is_a_recipient_at_both_layers() { + let (mut kernel, world, active) = nesting_kernel("Draft stander"); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + let beacon = *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "beacon") + .expect("the beacon entry is declared") + .0; + let arrival = + |kernel: &mut WorldKernel, handle: &str, label: &str, position: Option| { + let snapshot = kernel.snapshot().unwrap(); + let caller = CallerId::Play; + kernel.submit( + command( + &snapshot, + caller.clone(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: format!("The Hollow Shed for {handle}"), + kind: EntityKind::Place, + container: Some(Ref::Existing(world.hollow)), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([Ref::Existing(beacon)]), + position: position.map(Ref::Existing), + import_key: None, + }), + ], + operations: vec![witness( + world.asteroid, + world.village, + Confidence::Certain, + )], + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + }; + + // Declared with no position: under nothing, so the witness still + // reaches nobody and the resolver says so. + match arrival(&mut kernel, "ghost", "The Unplaced Arrival", None) { + Err(KernelError::PatchRejected(set)) => assert_eq!( + set, + vec![Mismatch::NoOperationEffect { operation: 0 }], + "a placeless draft subject was counted as a recipient" + ), + other => panic!("expected a refusal, got {other:?}"), + } + + // Declared and placed under the witnessed place: the resolver's + // candidate map carries the draft position, and the apply pass derives + // the same subject from live state. + let before_arrival = kernel.state.revision; + let receipt = arrival( + &mut kernel, + "arrival", + "The Village Arrival", + Some(world.village), + ); + assert!( + matches!(receipt, Ok(_)), + "{receipt:?}" + ); + let arrived = *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == "The Village Arrival") + .expect("the arrival is declared") + .0; + assert_eq!( + knows(&kernel, arrived, world.asteroid), + seen(Confidence::Certain, before_arrival + 1) + ); + // The standers who already held it kept their own rows, from the + // earlier witness, and this landing did not touch them. + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + } + + /// The other way the two layers could disagree about who already holds the + /// fact: an earlier operation in the same patch takes it away. The + /// resolver's candidate map drops the row and the apply pass drops the + /// stored one, so a forget-then-witness lands rather than being refused as + /// reaching nobody. + #[test] + fn soul_a_forget_before_a_witness_agrees_at_both_layers() { + let (mut kernel, world, active) = nesting_kernel("Forget first"); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + // Everyone under the village holds it, so the witness alone is refused. + let seeded = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &seeded, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + + let seeded = kernel.snapshot().unwrap(); + let receipt = submit_play( + &mut kernel, + &seeded, + operations(vec![ + ComponentOp::Forget { + subject: Ref::Existing(world.villager), + fact: Ref::Existing(world.asteroid), + }, + witness(world.asteroid, world.village, Confidence::Certain), + ]), + ); + assert!(receipt.resulting_revision > 0, "{receipt:?}"); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Certain, seeded.revision + 1), + "the forgotten subject was not re-reached" + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1), + "a holder the patch did not touch was overwritten" + ); + } + + /// What a witness hands the narrative lane's interruption renderer. The + /// renderer takes a subject's own `ScopeComponents` and its own knowledge + /// rows and nothing else, so both of its inputs are pinned here rather than + /// in the lane that owns the prose: exactly one component moved, `knows`, + /// which is the anonymous line and names no author; and the row the witness + /// wrote carries no `minted_at`, which is the sole gate on an `Overheard` + /// row, so no attributable line can be built from it. + #[test] + fn soul_a_witness_moves_only_knows_and_writes_no_spoken_row() { + let (mut kernel, world, active) = nesting_kernel("Anonymous"); + let before = scope_components(&kernel.state, world.villager); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + let after = scope_components(&kernel.state, world.villager); + assert_ne!(before.knows, after.knows); + assert_eq!( + after, + ScopeComponents { + knows: after.knows.clone(), + ..before + }, + "a witness moved a component other than what this person knows" + ); + + let snapshot = kernel.snapshot().unwrap(); + let held = snapshot + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .expect("the learner is snapshotted"); + assert!( + held.knowledge + .iter() + .filter(|row| row.fact == world.asteroid) + .all(|row| row.minted_at.is_none() && row.source == KnowledgeSource::Witnessed), + "a witnessed row carried a speech act" + ); + } +} + +/// The clock, commitments, pressure, boundaries, and scale. +#[cfg(test)] +mod clock_tests { + use super::patch::{PreconditionRef, PressureSourceRef}; + use super::tests::{ + act, affordance_named, auth_principal, authority_kind, command, creation, + human_principal, office, operations, owner, play_caller, reject_play, + speech_world, submit_play, + }; + use super::*; + + /// The canonical IDs of the clock fixture: a hall containing a yard, a + /// dead end reached by exactly one route, three subjects, a resource, and + /// one commitment of each kind. + pub(crate) struct Clockwork { + yard: EntityId, + dead_end: EntityId, + gate: EdgeId, + reeve: SubjectId, + farmer: SubjectId, + treasury: SubjectId, + routine: CommitmentKey, + obligation: CommitmentKey, + goal: CommitmentKey, + deliver: AffordanceId, + threaten: AffordanceId, + } + + const ROUTINE_DUE: u64 = 60; + const LATE_DUE: u64 = 100; + + fn minutes(value: u32) -> TickMinutes { + TickMinutes::new(value).expect("a valid span") + } + + pub(crate) fn clock_kernel(title: &str) -> (WorldKernel, Clockwork, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (clockwork, active) = clock_world(&mut kernel); + (kernel, clockwork, active) + } + + fn clock_world(kernel: &mut WorldKernel) -> (Clockwork, WorldSnapshot) { + let before = kernel.snapshot().unwrap(); + let speak = super::tests::speak_entry(kernel); + let person = |handle: &str, label: &str, kind: SubjectKind, place: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + affordances: BTreeSet::from([ + speak.clone(), + Ref::Draft(DraftHandle::new("deliver")), + Ref::Draft(DraftHandle::new("threaten")), + ]), + position: Some(Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + }; + let subject = |handle: &str| Ref::Draft(DraftHandle::new(handle)); + submit_play( + kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + evidence: vec![EvidenceRef::new("vault:harvest")], + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Long Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("yard"), + label: "The Cavity Yard".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + // Nothing inside it, nobody in it, and one route out: + // the world has not grown into it yet. + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("dead-end"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("grain"), + label: "Winter Grain".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("stair"), + label: "The Yard Stair".into(), + from: Ref::Draft(DraftHandle::new("yard")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("back"), + label: "The Hall Steps".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Draft(DraftHandle::new("yard")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("gate"), + label: "The Field Gate".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Draft(DraftHandle::new("dead-end")), + access: AccessKind::Public, + cost: Cost(1), + }), + // An affordance whose legitimacy is a promise rather + // than a jurisdiction, and one that presses directly. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("deliver"), + kind: AffordanceKindName("deliver".into()), + roles: vec![RoleSpec { + role: Role("creditor".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::Committed { + to: Role("creditor".into()), + kind: CommitmentKind::Obligation, + }], + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::CreateCommitment { + kind: CommitmentKind::Obligation, + horizon: minutes(1440), + period: None, + }, + roles: vec![Role("actor".into()), Role("creditor".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("threaten"), + kind: AffordanceKindName("threaten".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AdvancePressure { + by: PressureMagnitude(3), + }, + roles: vec![Role("target".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + person("reeve", "The Yard Reeve", SubjectKind::Person, "yard"), + person("farmer", "The Yard Farmer", SubjectKind::Person, "yard"), + person( + "treasury", + "The Hall Treasury", + SubjectKind::Institution, + "hall", + ), + ], + operations: vec![ + ComponentOp::Admit { + holder: subject("farmer"), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(4), + evidence: EvidenceRef::new("vault:harvest"), + }, + // 0: the routine, whose check is where its subject stands. + ComponentOp::CreateCommitment { + subject: subject("farmer"), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(ROUTINE_DUE), + period: Some(minutes(10)), + checks: vec![PreconditionRef::Present { + at: Ref::Draft(DraftHandle::new("yard")), + }], + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: subject("farmer"), + counterparty: Some(subject("treasury")), + kind: CommitmentKind::Obligation, + due: FictionalMinutes(LATE_DUE), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: subject("reeve"), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(LATE_DUE), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::Bind { + subject: subject("reeve"), + target: DependencyRef::Route(Ref::Draft(DraftHandle::new("gate"))), + }, + ], + }, + }, + ); + let active = kernel.snapshot().unwrap(); + let place = |label: &str| { + active + .places + .iter() + .find(|place| place.label == label) + .expect("the declared place") + .id + }; + let who = |label: &str| { + active + .subjects + .iter() + .find(|subject| subject.label == label) + .expect("the declared subject") + .id + }; + let reeve = who("The Yard Reeve"); + let farmer = who("The Yard Farmer"); + let key_of = |subject: SubjectId, kind: CommitmentKind| { + *kernel + .state + .commitments + .get(&subject) + .expect("the subject holds commitments") + .iter() + .find(|(_, commitment)| commitment.kind == kind) + .expect("the declared commitment") + .0 + }; + let gate = active + .routes + .iter() + .find(|route| route.label == "The Field Gate") + .expect("the declared route") + .id; + ( + Clockwork { + yard: place("The Cavity Yard"), + dead_end: place("The Unwalked Road"), + gate, + reeve, + farmer, + treasury: who("The Hall Treasury"), + routine: key_of(farmer, CommitmentKind::Routine), + obligation: key_of(farmer, CommitmentKind::Obligation), + goal: key_of(reeve, CommitmentKind::Goal), + deliver: affordance_named(&active, "deliver"), + threaten: affordance_named(&active, "threaten"), + }, + active, + ) + } + + fn tick(kernel: &mut WorldKernel, span: u32) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + CallerId::Play, + CommandBody::AdvanceTime { + minutes: minutes(span), + }, + ), + &AuthenticatedCaller::fixture(CallerId::Play), + ) + } + + fn exercise( + kernel: &mut WorldKernel, + actor: SubjectId, + affordance: AffordanceId, + bindings: Vec, + ) -> Result { + act( + kernel, + actor, + DecisionInvocation { + affordance, + bindings, + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + ) + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn pressure(kernel: &WorldKernel, target: SubjectId, source: PressureSource) -> u32 { + kernel + .state + .pressures + .get(&target) + .and_then(|held| held.get(&source)) + .map_or(0, |magnitude| magnitude.0) + } + + fn due(kernel: &WorldKernel, subject: SubjectId, key: CommitmentKey) -> FictionalMinutes { + kernel + .state + .commitments + .get(&subject) + .and_then(|held| held.get(&key)) + .expect("the live commitment") + .due + } + + /// Verification 12: a defaulted commitment advances pressure on + /// its subject, and the pressure grows with the next tick. + #[test] + fn a_defaulted_commitment_advances_pressure_one_step_per_tick() { + let (mut kernel, clockwork, _) = clock_kernel("Default"); + let sourced = PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + }; + + tick(&mut kernel, 120).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 1); + assert_eq!( + kernel.state.pressures[&clockwork.farmer].len(), + 1, + "only the past-due obligation pressed the farmer" + ); + + tick(&mut kernel, 1).expect("the second tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 2); + } + + /// Verification 19: a due routine fulfils with no inference and no pressure, + /// and a blocked one neither rolls nor presses. + #[test] + fn a_due_routine_auto_fulfils_and_a_blocked_one_does_not() { + let (mut kernel, clockwork, active) = clock_kernel("Routine"); + let holdings = kernel.state.holdings.clone(); + let positions = kernel.state.positions.clone(); + let edges = kernel.state.edges.clone(); + + tick(&mut kernel, ROUTINE_DUE as u32).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 10) + ); + assert!( + kernel.state.pressures.is_empty(), + "a routine raises nothing" + ); + assert_eq!(kernel.state.holdings, holdings); + assert_eq!(kernel.state.positions, positions); + assert_eq!(kernel.state.edges, edges); + + // Out of the yard: the check fails, so the routine neither rolls nor + // presses, and it retries on the next tick. + let route = |label: &str| { + active + .routes + .iter() + .find(|route| route.label == label) + .expect("the declared route") + .id + }; + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(clockwork.farmer), + via: Ref::Existing(route("The Yard Stair")), + }]), + ); + tick(&mut kernel, 10).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 10) + ); + assert!( + kernel.state.pressures.is_empty(), + "a blocked routine neither rolls nor presses" + ); + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(clockwork.farmer), + via: Ref::Existing(route("The Hall Steps")), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 20) + ); + } + + /// A tick with nothing due is still a commit: the clock moved, which is a + /// canonical change. + #[test] + fn a_tick_with_nothing_due_moves_only_the_clock() { + let (mut kernel, _, _) = clock_kernel("Quiet"); + let before = kernel.state.clone(); + let before_events = kernel.events(); + + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(kernel.state.header.now, FictionalMinutes(1)); + assert_eq!(kernel.state.revision, before.revision + 1); + assert!(kernel.state.pressures.is_empty()); + assert_eq!(kernel.state.commitments, before.commitments); + assert_eq!(kernel.state.holdings, before.holdings); + assert_eq!(kernel.state.positions, before.positions); + assert_eq!(kernel.events(), before_events); + + tick(&mut kernel, 2).expect("the tick commits"); + assert_eq!(kernel.state.header.now, FictionalMinutes(3)); + } + + /// A closed route in one place becomes political pressure in another without + /// anyone deciding that it should. The tick never reduces; only an operation + /// does. + #[test] + fn an_unavailable_dependency_presses_its_depender() { + let (mut kernel, clockwork, _) = clock_kernel("Dependency"); + let sourced = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 0); + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 1); + + // Repair stops the pressing but never unwrites what accrued. + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::OpenRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 1); + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ResolvePressure { + source: PressureSourceRef::Dependency(DependencyRef::Route(Ref::Existing( + clockwork.gate, + ))), + target: Ref::Existing(clockwork.reeve), + }]), + ); + assert!( + !kernel.state.pressures.contains_key(&clockwork.reeve), + "an emptied target removes its key rather than storing an empty map" + ); + } + + /// The clock moves through exactly one command body. + #[test] + fn time_advances_only_through_advance_time() { + let (mut kernel, clockwork, _) = clock_kernel("OnlyTick"); + tick(&mut kernel, 5).expect("the tick commits"); + let now = kernel.state.header.now; + + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + assert_eq!(kernel.state.header.now, now); + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + assert_eq!(kernel.state.header.now, now); + } + + /// Who may tick, when, and how far. + #[test] + fn advance_time_negatives() { + let mut kernel = WorldKernel::create(creation("Negatives"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + + let active = kernel.snapshot().unwrap(); + // A span is constructor-checked, so a malformed one never reaches a + // command at all. + assert!(TickMinutes::new(0).is_none()); + assert!(TickMinutes::new(super::patch::MAX_ROUTE_COST + 1).is_none()); + + for caller in [ + CallerId::Principal(human_principal()), + CallerId::Principal(owner()), + ] { + let error = kernel + .submit( + command( + &active, + caller.clone(), + CommandBody::AdvanceTime { + minutes: minutes(1), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + + // Play ticks. + submit_play( + &mut kernel, + &active, + CommandBody::AdvanceTime { + minutes: minutes(7), + }, + ); + assert_eq!(kernel.state.header.now, FictionalMinutes(7)); + + // And a span that would overflow the clock is refused rather than + // wrapping. + kernel.state.header.get_mut().now = FictionalMinutes(u64::MAX); + let snapshot = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &snapshot, + CallerId::Play, + CommandBody::AdvanceTime { + minutes: minutes(1), + }, + ), + &AuthenticatedCaller::fixture(CallerId::Play), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Serialization(_)), "{error:?}"); + } + + /// The whole motion is re-derived at apply, so a forged fulfilment, target, + /// magnitude, or clock reading is one comparison. + #[test] + fn a_forged_motion_does_not_apply() { + let (kernel, clockwork, _) = clock_kernel("Forged"); + let to = FictionalMinutes(120); + let honest = clock::derive_motion(&kernel.state, to); + assert!(!honest.fulfilled.is_empty() || !honest.pressed.is_empty()); + + let forgeries = [ + // A forged clock reading. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to: FictionalMinutes(121), + motion: honest.clone(), + }, + // A fulfilment nothing derived. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: vec![clock::RoutineFulfilled { + subject: clockwork.farmer, + key: clockwork.routine, + next_due: FictionalMinutes(9_999), + }], + pressed: honest.pressed.clone(), + }, + }, + // A forged magnitude. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: honest.fulfilled.clone(), + pressed: honest + .pressed + .iter() + .map(|written| clock::PressureWritten { + magnitude: PressureMagnitude(written.magnitude.0 + 9), + ..written.clone() + }) + .collect(), + }, + }, + // A pressure row for an untouched subject. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: honest.fulfilled.clone(), + pressed: honest + .pressed + .iter() + .cloned() + .chain(std::iter::once(clock::PressureWritten { + target: clockwork.treasury, + source: PressureSource::Subject(clockwork.reeve), + magnitude: PressureMagnitude(5), + })) + .collect(), + }, + }, + ]; + for forged in forgeries { + let mut candidate = kernel.state.clone(); + let error = apply_effect(&mut candidate, CommandId::issue(), &CallerId::Play, &forged) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + } + + // The honest one applies. + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: honest, + }, + ) + .expect("the honest motion applies"); + assert_eq!(candidate.header.now, to); + } + + /// Replay across a tick is exact, and every envelope is idempotent. + #[test] + fn restart_replay_across_a_tick_is_exact() { + let (mut kernel, clockwork, _) = clock_kernel("Replay"); + + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + tick(&mut kernel, 60).expect("the routine tick commits"); + tick(&mut kernel, 60).expect("the obligation tick commits"); + let snapshot = kernel.snapshot().unwrap(); + let repeat = command( + &snapshot, + CallerId::Play, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + kernel + .submit(repeat.clone(), &AuthenticatedCaller::verified_play()) + .expect("the discharge commits"); + // Discharge removes every pressure row it sourced. + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 0 + ); + + let before = kernel.state.clone(); + let before_snapshot = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + let mut replayed = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(replayed.state, before); + assert_eq!(replayed.snapshot().unwrap(), before_snapshot); + assert!(matches!( + replayed.submit(repeat, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// Every commitment shape check, in one complete sorted set. + #[test] + fn commitment_declaration_negatives() { + let (mut kernel, clockwork, active) = clock_kernel("Shapes"); + let before = kernel.state.clone(); + let create = |kind: CommitmentKind, + counterparty: Option, + due: u64, + period: Option, + checks: Vec| { + ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.farmer), + counterparty: counterparty.map(Ref::Existing), + kind, + due: FictionalMinutes(due), + period, + checks, + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + } + }; + + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![ + // 0: a routine with no period. + create(CommitmentKind::Routine, None, 500, None, Vec::new()), + // 1: a goal with a period. + create( + CommitmentKind::Goal, + None, + 500, + Some(minutes(10)), + Vec::new() + ), + // 2: checks on a non-routine. + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 500, + None, + vec![PreconditionRef::Present { + at: Ref::Existing(clockwork.yard), + }], + ), + // 3: born past due. + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 0, + None, + Vec::new() + ), + // 4: a promise to oneself with a counterparty. + create( + CommitmentKind::Obligation, + Some(clockwork.farmer), + 500, + None, + Vec::new() + ), + // 5: a goal with a counterparty. + create( + CommitmentKind::Goal, + Some(clockwork.treasury), + 500, + None, + Vec::new() + ), + // 6: a discharge of a key nobody holds. + ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: CommitmentKey { + command: CommandId::issue(), + index: 0, + }, + }, + ]), + ), + { + let mut expected = vec![ + Mismatch::CommitmentPeriodMismatch { operation: 0 }, + Mismatch::CommitmentPeriodMismatch { operation: 1 }, + Mismatch::ChecksOnNonRoutine { operation: 2 }, + Mismatch::CommitmentDueInThePast { operation: 3 }, + Mismatch::SelfCommitment { operation: 4 }, + Mismatch::GoalWithCounterparty { operation: 5 }, + Mismatch::UnknownCommitment { operation: 6 }, + ]; + expected.sort(); + expected + } + ); + assert_eq!(kernel.state, before); + + // Repairing exactly those commits. + submit_play( + &mut kernel, + &active, + operations(vec![ + create( + CommitmentKind::Routine, + None, + 500, + Some(minutes(10)), + Vec::new(), + ), + create(CommitmentKind::Goal, None, 500, None, Vec::new()), + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 500, + None, + Vec::new(), + ), + ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.routine, + }, + ]), + ); + assert!( + !kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.routine), + "the discharge removed the routine" + ); + } + + /// `Committed` reads the actor's own commitments: the farmer promised the + /// treasury and the reeve did not. + #[test] + fn committed_reads_the_actors_own_commitments() { + let (mut kernel, clockwork, _) = clock_kernel("Committed"); + + // The reeve promised the treasury nothing. + let error = exercise( + &mut kernel, + clockwork.reeve, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + )); + + // The farmer did, so the entry commits and mints a second obligation + // whose due date the kernel computed. + let before = kernel.state.commitments[&clockwork.farmer].len(); + exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .expect("the delivery commits"); + assert_eq!( + kernel.state.commitments[&clockwork.farmer].len(), + before + 1 + ); + } + + /// `Committed` reads the actor's commitments at Act time: once the + /// obligation to the treasury is discharged, the promisor's act that needs + /// it is refused and nothing commits. + #[test] + fn a_discharged_commitment_refuses_the_act_that_needs_it() { + let (mut kernel, clockwork, _) = clock_kernel("DischargeThenAct"); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + let events = kernel.events().len(); + let error = exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .unwrap_err(); + assert!( + matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + ), + "{error:?}" + ); + assert_eq!(kernel.events().len(), events); + } + + /// `Committed` is a conjunction: the actor holds a commitment to this very + /// counterparty and of this very kind. The farmer owes the treasury an + /// obligation and nobody else, so naming the reeve fails the counterparty + /// half while the kind half holds. + #[test] + fn committed_requires_the_named_counterparty() { + let (mut kernel, clockwork, _) = clock_kernel("CommittedCounterparty"); + let error = exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.reeve))], + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + )); + } + + /// The other half: the reeve holds a routine toward the treasury, a kind + /// `deliver` does not ask for, so the counterparty half holds and the kind + /// half fails. The farmer's own obligation to the same treasury still passes. + #[test] + fn committed_requires_the_named_kind() { + let (mut kernel, clockwork, _) = clock_kernel("CommittedKind"); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.reeve), + counterparty: Some(Ref::Existing(clockwork.treasury)), + kind: CommitmentKind::Routine, + due: FictionalMinutes(ROUTINE_DUE), + period: Some(minutes(10)), + checks: vec![PreconditionRef::Present { + at: Ref::Existing(clockwork.yard), + }], + statement: Statement::new("A routine held toward the treasury.").unwrap(), + }]), + ); + assert!( + kernel.state.commitments[&clockwork.reeve] + .values() + .any(|held| held.kind == CommitmentKind::Routine + && held.counterparty == Some(clockwork.treasury)), + "the fixture reeve holds a routine to the treasury" + ); + let error = exercise( + &mut kernel, + clockwork.reeve, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + )); + exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .expect("an obligation to the same counterparty passes"); + } + + /// A tick that only advances pressure moves nobody's scope components; a tick + /// that fulfils a routine moves exactly that subject's. + #[test] + fn a_pressure_tick_moves_no_scope_components_and_a_routine_tick_moves_one() { + let (mut kernel, clockwork, _) = clock_kernel("Digests"); + let digests = |kernel: &WorldKernel| -> BTreeMap { + kernel + .state + .subjects + .keys() + .map(|subject_id| (*subject_id, scope_components(&kernel.state, *subject_id))) + .collect() + }; + + // Past the obligation and the goal, but the routine is blocked out of + // the yard first so only pressure moves. + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.routine, + }]), + ); + let before = digests(&kernel); + tick(&mut kernel, 200).expect("the tick commits"); + assert!(!kernel.state.pressures.is_empty(), "the tick pressed"); + assert_eq!(digests(&kernel), before, "pressure binds no proposal"); + + // A routine fulfilment moves exactly its own subject's digest. + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.reeve), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(500), + period: Some(minutes(60)), + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]), + ); + let before = digests(&kernel); + tick(&mut kernel, 400).expect("the tick commits"); + let after = digests(&kernel); + for (subject, digest) in &before { + if *subject == clockwork.reeve { + assert_ne!(after[subject], *digest, "the fulfilling subject's scope moved"); + } else { + assert_eq!(after[subject], *digest, "everyone else's scope is untouched"); + } + } + } + + /// Soul falsification: pressure magnitude cannot overflow or go negative, + /// and zero is spelled by absence at both ends. + #[test] + fn soul_pressure_saturates_and_never_underflows() { + let (mut kernel, clockwork, _) = clock_kernel("Saturate"); + let sourced = PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + }; + + // A tick over a magnitude already at the ceiling saturates rather than + // wrapping. + let mut brimming = kernel.state.clone(); + brimming.pressures.insert( + clockwork.farmer, + BTreeMap::from([(sourced, PressureMagnitude(u32::MAX))]), + ); + let motion = clock::derive_motion(&brimming, FictionalMinutes(LATE_DUE)); + let written = motion + .pressed + .iter() + .find(|written| written.source == sourced) + .expect("the past-due obligation pressed"); + assert_eq!(written.magnitude, PressureMagnitude(u32::MAX)); + + // Reducing by more than the row holds removes it instead of wrapping. + tick(&mut kernel, u32::try_from(LATE_DUE).unwrap()).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 1); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ReducePressure { + source: PressureSourceRef::Commitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }, + target: Ref::Existing(clockwork.farmer), + by: PressureMagnitude(9), + }]), + ); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 0); + assert!( + !kernel.state.pressures.contains_key(&clockwork.farmer), + "an emptied target keeps no empty inner map" + ); + + // Resolving an absent row changes nothing and is refused. + let snapshot = kernel.snapshot().unwrap(); + let mismatches = reject_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ResolvePressure { + source: PressureSourceRef::Commitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }, + target: Ref::Existing(clockwork.farmer), + }]), + ); + assert_eq!( + mismatches, + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + + /// Soul falsification: `now` is in no scope. A tick with nothing due moves + /// the clock and not one subject's components. + #[test] + fn soul_a_clock_only_tick_moves_no_scope_components() { + let (mut kernel, _, _) = clock_kernel("ClockOnly"); + let digests = |kernel: &WorldKernel| -> BTreeMap { + kernel + .state + .subjects + .keys() + .map(|subject_id| (*subject_id, scope_components(&kernel.state, *subject_id))) + .collect() + }; + let before = digests(&kernel); + let before_now = kernel.state.header.now; + + // Short of every due date in the fixture. + tick(&mut kernel, 10).expect("the tick commits"); + assert_eq!(kernel.state.header.now, FictionalMinutes(before_now.0 + 10)); + assert!(kernel.state.pressures.is_empty()); + assert_eq!(digests(&kernel), before, "the clock entered a scope"); + } + + // ---- genesis may not rule or mint ---------------------------------- + + /// Only Play rules or mints, and Play writes only after genesis: the + /// check reports every offender, not the first, so a scan narrowed to one + /// fact or one operation fails here. + #[test] + fn genesis_may_not_rule_or_mint() { + let mut input = creation("RulesAndMints"); + for handle in ["first-rule", "second-rule"] { + input + .patch + .declarations + .push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })); + } + input + .patch + .declarations + .push(super::tests::resource("loot", "Roadside Loot")); + for _ in 0..2 { + input.patch.operations.push(ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("human")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }); + } + let Err(error) = WorldKernel::create(input, &auth_principal(owner())) else { + panic!("a genesis patch that rules and mints was admitted"); + }; + let KernelError::PatchRejected(set) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + let offender = |site| Mismatch::RuledWithoutAuthority { site }; + assert_eq!( + set, + vec![ + offender(patch::Site::Declaration(DraftHandle::new("first-rule"))), + offender(patch::Site::Declaration(DraftHandle::new("second-rule"))), + offender(patch::Site::Operation(0)), + offender(patch::Site::Operation(1)), + ] + ); + } + + /// `prepare_creation` and `WorldState::genesis` both forbid rulings at + /// genesis. A creation patch that carries a `Ruled` fact is refused before + /// a world is ever written. + #[test] + fn a_genesis_patch_carrying_a_ruled_fact_is_refused() { + let mut input = creation("RuledGenesis"); + input + .patch + .declarations + .push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rule"), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })); + let Err(error) = WorldKernel::create(input, &auth_principal(owner())) else { + panic!("a genesis patch carrying a Ruled fact was admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Declaration(DraftHandle::new("rule")), + })), + "{error:?}" + ); + } + + /// The `Mint` half: a creation patch that carries a `Mint` is refused the + /// same way. + #[test] + fn a_genesis_patch_carrying_a_mint_is_refused() { + let mut input = creation("MintGenesis"); + input + .patch + .declarations + .push(super::tests::resource("loot", "Roadside Loot")); + input.patch.operations.push(ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("human")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }); + let Err(error) = WorldKernel::create(input, &auth_principal(owner())) else { + panic!("a genesis patch carrying a Mint was admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Operation(0), + })), + "{error:?}" + ); + } + + /// `WorldState::genesis` re-decides `forbid_rulings_at_genesis` on its own + /// terms, independent of `prepare_creation` — that is what protects + /// journal replay of a stored genesis commit, not only a freshly + /// admitted one. Called directly, bypassing `prepare_creation` entirely, + /// so this cannot be satisfied by `prepare_creation`'s own check. + #[test] + fn genesis_itself_refuses_a_ruled_fact_and_a_mint() { + let mut input = creation("GenesisRuleDirect"); + let world_id = WorldId::of(input.id()); + input + .patch + .declarations + .push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rule"), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })); + let title = normalize_title(&input.title).unwrap(); + let resolved = patch::resolve_patch( + &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), + input.id(), + &input.patch, + ) + .expect("the resolver is actor-blind and accepts a Ruled fact"); + let effect = WorldEffect::WorldCreated { + owner: input.owner.clone(), + title, + resolved, + }; + let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + + let mut input = creation("GenesisMintDirect"); + let world_id = WorldId::of(input.id()); + input + .patch + .declarations + .push(super::tests::resource("loot", "Roadside Loot")); + input.patch.operations.push(ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("human")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }); + let title = normalize_title(&input.title).unwrap(); + let resolved = patch::resolve_patch( + &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), + input.id(), + &input.patch, + ) + .expect("the resolver is actor-blind and accepts a Mint"); + let effect = WorldEffect::WorldCreated { + owner: input.owner.clone(), + title, + resolved, + }; + let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + } + + /// Soul falsification: a discharge names one subject's own live key. + #[test] + fn soul_discharging_a_foreign_or_already_discharged_commitment_is_refused() { + let (mut kernel, clockwork, _) = clock_kernel("Discharge"); + + // The farmer's obligation, claimed by the reeve. + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.reeve), + key: clockwork.obligation, + }]), + ), + vec![Mismatch::UnknownCommitment { operation: 0 }] + ); + + // Discharged once, and then not again. + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ), + vec![Mismatch::UnknownCommitment { operation: 0 }] + ); + } + + /// Soul falsification: a routine re-arms by exactly one period per command, + /// whatever the span, and a non-routine cannot carry checks. + #[test] + fn soul_a_routine_re_arms_exactly_one_period_per_command() { + let (mut kernel, clockwork, _) = clock_kernel("Rearm"); + let period = u64::from( + kernel.state.commitments[&clockwork.farmer][&clockwork.routine] + .period + .expect("a routine carries a period") + .minutes(), + ); + let start = due(&kernel, clockwork.farmer, clockwork.routine); + + // One roll per command, even for a span that clears many periods. + tick(&mut kernel, u32::try_from(period * 10).unwrap()).expect("the long tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(start.0 + period) + ); + tick(&mut kernel, 1).expect("the short tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(start.0 + 2 * period) + ); + + // Checks belong to routines alone. + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.reeve), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(100_000), + period: None, + checks: vec![PreconditionRef::Present { + at: Ref::Existing(clockwork.yard), + }], + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]), + ), + vec![Mismatch::ChecksOnNonRoutine { operation: 0 }] + ); + } + + /// Soul falsification: `derive_motion` is a function of state and span + /// alone, and the committed effect is exactly what `reduce` re-derives for + /// a tick that fulfils a routine, presses past-due promises, and presses a + /// failing dependency at once. + #[test] + fn soul_derive_motion_is_pure_and_the_tick_replays_exactly() { + let (mut kernel, clockwork, _) = clock_kernel("Pure"); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + + // The same state and the same span, twenty times: one answer. + let span = u32::try_from(LATE_DUE + 10).unwrap(); + let to = FictionalMinutes(LATE_DUE + 10); + let first = clock::derive_motion(&kernel.state, to); + assert!(!first.fulfilled.is_empty(), "the routine is due"); + assert!( + first.pressed.len() >= 2, + "past-due promises and the closed route all press" + ); + for _ in 0..20 { + assert_eq!(clock::derive_motion(&kernel.state, to), first); + } + + // And the commit carries exactly that motion. + let snapshot = kernel.snapshot().unwrap(); + let ticking = command( + &snapshot, + CallerId::Play, + CommandBody::AdvanceTime { + minutes: minutes(span), + }, + ); + let expected = reduce(&kernel.state, &ticking).expect("the tick reduces"); + assert_eq!( + expected, + WorldEffect::TimeAdvanced { + minutes: minutes(span), + to, + motion: first, + } + ); + // Applying the re-derived effect to a copy reproduces the committed + // state exactly, which is the replay identity the journal relies on. + let mut replayed = kernel.state.clone(); + apply_effect(&mut replayed, ticking.id(), &CallerId::Play, &expected) + .expect("the re-derived effect applies"); + kernel + .submit(ticking, &AuthenticatedCaller::fixture(CallerId::Play)) + .expect("the tick commits"); + assert_eq!(replayed.header.now, kernel.state.header.now); + assert_eq!(replayed.commitments, kernel.state.commitments); + assert_eq!(replayed.pressures, kernel.state.pressures); + } + + // ---- system capabilities ------------------------------------------ + + fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + body: CommandBody, + ) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command(&snapshot, caller.clone(), body), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn shed_under(container: EntityId, handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: EntityKind::Place, + container: Some(Ref::Existing(container)), + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + /// The mismatch vocabulary is kernel-internal plus controller telemetry. It + /// never enters a commit, and `verify_state_shape` never grows a clause for + /// it because no partition holds one. + #[test] + fn mismatch_never_appears_in_a_world_commit() { + let (mut kernel, clockwork, _) = clock_kernel("Separation"); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .expect("the play table's patch commits"); + + let bytes = kernel.state.encoded_documents(); + let text = String::from_utf8_lossy(&bytes); + for tag in [ + "outside_jurisdiction", + "unresolved_draft", + "no_canonical_change", + "mismatch", + ] { + assert!(!text.contains(tag), "{tag} reached world state"); + } + } + + // ---- Soul: the confinement predicate past its declaration lane ------ + + // ---- Cut 3: the play authority, `Ruled` facts and `Mint` ----------- + + fn ruled_fact_patch(handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(handle), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + fn resource_named(kernel: &WorldKernel, label: &str) -> EntityId { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .map(|(id, _)| id) + .expect("the declared resource") + } + + /// Invariant 5, first half, and P3.1: the play authority declares in + /// Active with no answer. + #[test] + fn the_play_authority_declares_in_active_without_an_answer() { + let (mut kernel, clockwork, _) = clock_kernel("PlayDeclares"); + let receipt = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: shed_under(clockwork.dead_end, "play-shed"), + }, + ) + .expect("the play authority declares unanswered in Active"); + assert!(receipt.resulting_revision > 0); + } + + /// Invariant 5: the play authority reaches the whole world, unconfined to + /// a ground. Writing under a place no jurisdiction covers is exactly what + /// a confined author cannot do. + #[test] + fn the_play_authority_is_unconfined() { + let (mut kernel, clockwork, _) = clock_kernel("PlayUnconfined"); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: shed_under(clockwork.dead_end, "unconfined-shed"), + }, + ) + .expect("the play authority is confined to no ground"); + } + + /// Invariant 5: the play authority advances time, the clock's precedent. + #[test] + fn the_play_authority_advances_time() { + let (mut kernel, _clockwork, active) = clock_kernel("PlayClock"); + let receipt = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdvanceTime { + minutes: minutes(30), + }, + ) + .expect("the play authority advances time"); + assert!(receipt.resulting_revision > 0); + assert!(kernel.state.header.now > active.now); + } + + /// P3.4: a ruled fact is world truth to every subject that knows it. + #[test] + fn the_play_authority_rules_a_fact_and_a_witness_knows_it_as_canon() { + let (mut kernel, clockwork, _) = clock_kernel("PlayRules"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("verdict")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch, + }, + ) + .expect("the play authority rules a fact and grants it as knowledge"); + + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == "Stated by the table.") + .map(|(id, _)| id) + .expect("the ruled fact"); + assert_eq!(kernel.state.facts[&fact].standing, FactStanding::Ruled); + + let snapshot = kernel.snapshot().unwrap(); + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .expect("the reeve's snapshot"); + let known = subject + .knowledge + .iter() + .find(|held| held.fact == fact) + .expect("the reeve knows the ruled fact"); + assert_eq!(known.standing, FactStandingView::Canonical); + } + + /// P3.5: minted quantity balances the ledger, and replay reproduces it. + #[test] + fn the_play_authority_mints_and_the_ledger_balances() { + let (exported, reeve, grain) = { + let (mut kernel, clockwork, _) = clock_kernel("PlayMints"); + let grain = resource_named(&kernel, "Winter Grain"); + let before = held(&kernel.state, clockwork.reeve, grain); + assert_eq!(before, 0); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Mint { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(7), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority mints"); + let after = held(&kernel.state, clockwork.reeve, grain); + assert_eq!(before + 7, after); + (kernel.export().unwrap(), clockwork.reeve, grain) + }; + let replayed = WorldKernel::open(&exported).expect("the minted export replays"); + assert_eq!(held(&replayed.state, reeve, grain), 7); + } + + /// The evidenced-knowledge clause is unchanged: a receipt cannot vouch for + /// an assertion the kernel never evaluated, and a `Ruled` fact is exactly + /// such an assertion. + #[test] + fn a_ruled_fact_cannot_be_known_evidenced() { + let (mut kernel, clockwork, _) = clock_kernel("PlayEvidenced"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("verdict")), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }); + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::EvidencedKnowledgeOfClaim { operation: 0 })), + "{error:?}" + ); + } + + /// The evidence gate on `Canonical` facts and `Admit` is one predicate at + /// the same sites for genesis and for Play (P3.3). `Play` carries no + /// receipts, so its `Admit` is refused without one. + #[test] + fn the_evidence_gate_holds_for_play() { + let (mut kernel, clockwork, _) = clock_kernel("PlayEvidenceGate"); + let grain = resource_named(&kernel, "Winter Grain"); + + // Without a receipt: `Play`'s `Admit` is refused exactly as anyone's. + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:uncited"), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::AdmitWithoutEvidence { operation: 0 })), + "{error:?}" + ); + + // With the receipt cited in the same patch, `Play`'s `Admit` is + // admitted like anyone unconfined's. + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:cited"), + }], + evidence: vec![EvidenceRef::new("vault:cited")], + }, + }, + ) + .expect("an evidenced admit is admitted for the play authority too"); + } + + /// P3.5, replay half, folded with a ruled fact: reopening the journal + /// reproduces both across the digest. + #[test] + fn a_journal_holding_a_ruled_fact_and_a_mint_replays() { + let (exported, expected) = { + let (mut kernel, clockwork, _) = clock_kernel("PlayReplay"); + let grain = resource_named(&kernel, "Winter Grain"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::Mint { + holder: Ref::Existing(clockwork.farmer), + resource: Ref::Existing(grain), + qty: Quantity(2), + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch, + }, + ) + .expect("the play authority rules and mints in one patch"); + (kernel.export().unwrap(), kernel.snapshot().unwrap()) + }; + let replayed = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(replayed.snapshot().unwrap(), expected); + let exported = replayed.export().unwrap(); + drop(replayed); + let replayed_again = + WorldKernel::open(&exported).expect("the export replays a second time"); + assert_eq!(replayed_again.snapshot().unwrap(), expected); + } + + // ---- Cut 4: retirement ------------------------------------------- + + fn retire_patch(subject: SubjectId) -> WorldPatch { + WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Retire { + subject: Ref::Existing(subject), + }], + evidence: Vec::new(), + } + } + + /// Play retires a subject. + fn play_retires(kernel: &mut WorldKernel, subject: SubjectId) -> Result { + submit_as( + kernel, + CallerId::Play, + CommandBody::AdmitPatch { + patch: retire_patch(subject), + }, + ) + } + + /// P4.1, replay half: reopening the journal reproduces a retirement — no + /// grants and `retired` both survive the round trip. + #[test] + fn a_retired_subject_holds_no_grants_across_a_replay() { + let (exported, reeve) = { + let (mut kernel, clockwork, active) = clock_kernel("RetireReplay"); + assert!( + !active + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap() + .affordances + .is_empty(), + "the reeve holds grants before retirement" + ); + play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); + (kernel.export().unwrap(), clockwork.reeve) + }; + let replayed = WorldKernel::open(&exported).expect("the export replays"); + let snapshot = replayed.snapshot().unwrap(); + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == reeve) + .expect("the retired subject's own row"); + assert!(subject.retired); + assert!(subject.affordances.is_empty(), "a retired subject holds no grants"); + } + + /// P4.1: Play's `Act` for a retired subject is denied, because `Retire` + /// removed its grants. + #[test] + fn a_retired_subject_cannot_act() { + let (mut kernel, clockwork, _) = clock_kernel("RetireCannotAct"); + play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); + let error = exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied), "{error:?}"); + } + + /// P4.1: no position, so a witness at the retired subject's former place + /// never reaches it, while a still-present subject at the same place + /// does. + #[test] + fn a_retired_subject_hears_nothing() { + let (mut kernel, clockwork, _) = clock_kernel("RetireHearsNothing"); + play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::Witness { + fact: Ref::Draft(DraftHandle::new("news")), + place: Ref::Existing(clockwork.yard), + confidence: Confidence::Certain, + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch, + }, + ) + .expect("the play authority witnesses at the yard"); + let snapshot = kernel.snapshot().unwrap(); + let reeve = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .expect("the retired reeve's own row"); + assert!(reeve.knowledge.is_empty(), "{:?}", reeve.knowledge); + let farmer = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.farmer) + .expect("the farmer's own row"); + assert!(!farmer.knowledge.is_empty(), "the farmer still hears it"); + } + + /// P4.2: events, knowledge, holdings, and commitments all survive + /// retirement untouched. + #[test] + fn a_retired_subject_keeps_its_history() { + let (mut kernel, clockwork, _) = clock_kernel("RetireKeepsHistory"); + let before_holdings = kernel.state.holdings.get(&clockwork.farmer).cloned(); + let before_commitments = kernel.state.commitments.get(&clockwork.farmer).cloned(); + assert!(before_holdings.is_some()); + assert!(before_commitments.is_some()); + play_retires(&mut kernel, clockwork.farmer).expect("play retires the farmer"); + assert_eq!( + kernel.state.holdings.get(&clockwork.farmer).cloned(), + before_holdings + ); + assert_eq!( + kernel.state.commitments.get(&clockwork.farmer).cloned(), + before_commitments + ); + assert!(kernel.state.subjects.contains_key(&clockwork.farmer)); + } + + /// P4.1: retiring twice is `NoOperationEffect`, not a second retirement. + #[test] + fn retiring_twice_is_no_effect() { + let (mut kernel, clockwork, _) = clock_kernel("RetireTwice"); + play_retires(&mut kernel, clockwork.reeve).expect("the first retirement commits"); + let error = play_retires(&mut kernel, clockwork.reeve).unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::NoOperationEffect { operation: 0 })), + "{error:?}" + ); + } + + // ---- Cut 5: granting and revoking affordances --------------------- + + fn wave_affordance() -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("wave"), + kind: AffordanceKindName("wave".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AdvancePressure { + by: PressureMagnitude(1), + }, + roles: vec![Role("target".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }) + } + + /// P5.1: the seed lane is the owner in Draft, and it grants the player a + /// verb the same way any owner-authored `GrantAffordance` does. + #[test] + fn the_seed_grants_the_player_a_verb_in_draft() { + let mut kernel = WorldKernel::create(creation("SeedGrantsDraft"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let before = kernel.snapshot().unwrap(); + let commons = before.places[0].id; + let speak = super::tests::speak_entry(&kernel); + submit_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + wave_affordance(), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("player"), + label: "The Player".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(commons)), + import_key: None, + }), + ], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Draft(DraftHandle::new("player")), + affordance: Ref::Draft(DraftHandle::new("wave")), + }], + evidence: Vec::new(), + }, + }, + ); + let snapshot = kernel.snapshot().unwrap(); + let player = snapshot + .subjects + .iter() + .find(|subject| subject.label == "The Player") + .expect("the declared player"); + assert_eq!(player.affordances.len(), 2); + } + + /// P5.1: Play grants and revokes a verb in Active. + #[test] + fn the_play_authority_grants_and_revokes_in_active() { + let (mut kernel, clockwork, _) = clock_kernel("PlayGrantRevoke"); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![wave_affordance()], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Draft(DraftHandle::new("wave")), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority grants a new verb"); + let after_grant = kernel.snapshot().unwrap(); + assert_eq!( + after_grant + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap() + .affordances + .len(), + 4 + ); + + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.threaten), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority revokes a held verb"); + let after_revoke = kernel.snapshot().unwrap(); + let reeve = after_revoke + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap(); + assert_eq!(reeve.affordances.len(), 3); + assert!(!reeve.affordances.contains(&clockwork.threaten)); + } + + // ---- Retirement fix batch (PA.f31-PA.f35) ------------------------------ + + fn human_subject(snapshot: &WorldSnapshot) -> SubjectId { + snapshot + .subjects + .iter() + .find(|subject| subject.label == "The Human") + .expect("the genesis human") + .id + } + + /// PA.f31: `verify_state_shape` no longer judges a `DecisionEvent` against + /// the subject's *present* controller identity. Retiring a subject that + /// has acted commits, and the history survives a full reopen-and-replay + /// (`open` -> `verify_history` -> `verify_state_shape` for every + /// commit, per the caller census in the report). + #[test] + fn retiring_a_subject_that_acted_survives_reopen_and_replay() { + let exported = { + let (mut kernel, clockwork, _) = clock_kernel("PAf31RetireActed"); + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + play_retires(&mut kernel, clockwork.reeve) + .expect("a subject with history can be retired"); + kernel.export().unwrap() + }; + let reopened = WorldKernel::open(&exported).expect("the export replays"); + let retired = reopened + .snapshot() + .unwrap() + .subjects + .iter() + .find(|subject| subject.label == "The Yard Reeve") + .expect("the reeve survives replay") + .retired; + assert!(retired); + } + + /// PA.f31: revoking a verb a subject has already used commits, and the + /// event that used it survives reopen-and-replay for the same reason: the + /// grant a `DecisionEvent` rode is judged once, at commit, not re-judged + /// against the present-day grant set. + #[test] + fn revoking_a_used_verb_survives_reopen_and_replay() { + let exported = { + let (mut kernel, clockwork, _) = clock_kernel("PAf31RevokeUsed"); + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + let before = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &before, + operations(vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.threaten), + }]), + ); + kernel.export().unwrap() + }; + let reopened = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(reopened.events().len(), 1); + } + + /// PA.f32(b, c): once the world is Active, the human's Draft approval is + /// frozen history, so the owner may retire the human — the player's + /// subject may die — and the retire survives reopen-and-replay because + /// the journal's approval-shape check no longer re-reads the present-day + /// controller roster in Active. + #[test] + fn retiring_the_human_in_active_survives_reopen_and_replay() { + let (exported, human) = { + let (mut kernel, clockwork, active) = clock_kernel("PAf32ActiveRetire"); + let _ = &clockwork; + let human = human_subject(&active); + play_retires(&mut kernel, human).expect("play retires the human subject"); + (kernel.export().unwrap(), human) + }; + let reopened = WorldKernel::open(&exported).expect("the export replays"); + let retired = reopened + .snapshot() + .unwrap() + .subjects + .iter() + .find(|subject| subject.id == human) + .expect("the human survives replay") + .retired; + assert!(retired); + } + + /// PA.f33: audience derivation (`audience()`) is the one owner of who a + /// channel reaches, so a channel may still *declare* a retired member, + /// but that member is filtered out at the one read site — it gains no + /// knowledge from a telling into that channel. + #[test] + fn channel_audience_excludes_a_retired_member() { + let (mut kernel, clockwork, _) = clock_kernel("PAf33Audience"); + play_retires(&mut kernel, clockwork.reeve).expect("retire"); + let mut patch = ruled_fact_patch("news"); + patch.declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Existing(clockwork.reeve), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + })); + patch.operations.push(ComponentOp::Communicate { + speaker: Ref::Existing(clockwork.farmer), + fact: Ref::Draft(DraftHandle::new("news")), + to: AudienceRef::Channel(Ref::Draft(DraftHandle::new("wire"))), + }); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch }) + .expect("admitted"); + let reeve_knows = kernel.state.knowledge_of(clockwork.reeve).count(); + assert_eq!(reeve_knows, 0, "a retired subject was an audience"); + } + + /// PA.f33: `Communicate` resolves and refuses a retired speaker with + /// `RetiredSubjectActed`, whether or not it is also that channel's + /// controller. + #[test] + fn a_retired_subject_cannot_speak_through_a_channel() { + let (mut kernel, clockwork, _) = clock_kernel("PAf33RetiredSpeaks"); + let mut declare = ruled_fact_patch("wire-decl"); + declare.declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Existing(clockwork.reeve), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + })); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch: declare }) + .expect("declare"); + play_retires(&mut kernel, clockwork.reeve).expect("retire"); + let wire = *kernel.state.channels.keys().next().unwrap(); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::Communicate { + speaker: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + to: AudienceRef::Channel(Ref::Existing(wire)), + }); + let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch }) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f33: `CanReach` is `audience().contains(target)`, so a retired + /// target fails the same precondition every other reach check now + /// respects — one statement of reach, one fix. + #[test] + fn a_retired_subject_is_unreachable_through_can_reach() { + let mut kernel = WorldKernel::create(creation("PAf33CanReach"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, _) = speech_world(&mut kernel); + play_retires(&mut kernel, speech.listener).expect("play retires the listener"); + let invocation = DecisionInvocation { + affordance: speech.whisper, + bindings: vec![binding("target", Target::Subject(speech.listener))], + proposed: Vec::new(), + speech: Some(Statement::new("Are you still there?").unwrap()), + display: None, + }; + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::Act { + actor: speech.speaker, + invocation, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::ActionRejected(set) + if set.contains(&ActionMismatch::CannotReach { precondition: 0 })), + "{error:?}" + ); + } + + /// PA.f34: `AcquireKnowledge` refuses a retired subject. + #[test] + fn a_retired_subject_cannot_acquire_knowledge() { + let (mut kernel, clockwork, _) = clock_kernel("PAf34Acquire"); + play_retires(&mut kernel, clockwork.reeve).expect("retire"); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch }) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f34: `Forget` refuses a retired subject. + #[test] + fn a_retired_subject_cannot_forget() { + let (mut kernel, clockwork, _) = clock_kernel("PAf34Forget"); + let mut declare = ruled_fact_patch("news"); + declare.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch: declare }) + .expect("the reeve learns the fact"); + let fact = *kernel.state.knowledge_of(clockwork.reeve).next().unwrap().0; + play_retires(&mut kernel, clockwork.reeve).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_play( + &mut kernel, + &before, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Existing(fact), + }]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 0 }]); + } + + /// PA.f34: `InstallIncumbent` refuses a retired subject as incumbent. + #[test] + fn a_retired_subject_cannot_take_office() { + let (mut kernel, clockwork, _) = clock_kernel("PAf34Office"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_play( + &mut kernel, + &before, + operations(vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(clockwork.treasury), + office: office("warden"), + delegated: BTreeSet::from([authority_kind("levy")]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(clockwork.treasury), + office: office("warden"), + incumbent: Ref::Existing(clockwork.farmer), + }, + ]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 1 }]); + } + + /// PA.f34: a retired subject's holdings remain transferable — a body may + /// still be looted after it stops acting. + #[test] + fn holdings_are_still_transferable_from_a_retired_holder() { + let (mut kernel, clockwork, _) = clock_kernel("PAf34Loot"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let grain = *kernel + .state + .holdings + .get(&clockwork.farmer) + .expect("the retired farmer still holds grain") + .keys() + .next() + .expect("at least one resource"); + submit_play( + &mut kernel, + &before, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(clockwork.farmer), + to: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(2), + }]), + ); + assert_eq!( + kernel.state.holdings[&clockwork.reeve][&grain], + Quantity(2) + ); + } + + /// PA.f35, MuA: the resolver's `Retire` arm removes the subject's + /// Position (`positions.remove`) in the same candidate pass a later + /// `Relocate` in the same patch reads, so retire-then-relocate in one + /// patch is rejected as `UnplacedSubject` rather than silently placing a + /// retired subject. + #[test] + fn retiring_then_relocating_in_one_patch_is_rejected() { + let (mut kernel, clockwork, _) = clock_kernel("PAf35RetireRelocate"); + let stair = *kernel + .state + .edges + .iter() + .find(|(_, edge)| edge.endpoints().0 == clockwork.yard) + .unwrap() + .0; + let before = kernel.snapshot().unwrap(); + let error = reject_play( + &mut kernel, + &before, + operations(vec![ + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ComponentOp::Relocate { + subject: Ref::Existing(clockwork.reeve), + via: Ref::Existing(stair), + }, + ]), + ); + assert_eq!(error, vec![Mismatch::UnplacedSubject { operation: 1 }]); + } + + /// PA.f35, MuE: the resolver's `Retire` arm inserts the subject into its + /// own-patch `retired` candidate set, so a second `Retire` of the same + /// subject in one patch is caught as a no-op rather than silently + /// re-resolving. + #[test] + fn retiring_the_same_subject_twice_in_one_patch_is_a_noop_the_second_time() { + let (mut kernel, clockwork, _) = clock_kernel("PAf35DoubleRetire"); + let before = kernel.snapshot().unwrap(); + let error = reject_play( + &mut kernel, + &before, + operations(vec![ + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ]), + ); + assert_eq!(error, vec![Mismatch::NoOperationEffect { operation: 1 }]); + } + + // ---- Retirement fix batch (PA.f36-PA.f38) ------------------------------ + + /// PA.f37: a retired subject cannot become a promisor. `CreateCommitment` + /// refuses it with `RetiredSubjectActed`, the same mismatch a retired + /// office incumbent draws. + #[test] + fn a_retired_subject_cannot_be_a_promisor() { + let (mut kernel, clockwork, _) = clock_kernel("PAf37Promisor"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_play( + &mut kernel, + &before, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.farmer), + counterparty: None, + kind: CommitmentKind::Obligation, + due: FictionalMinutes(LATE_DUE + 1), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.") + .unwrap(), + }]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 0 }]); + } + + /// PA.f37: once a subject is retired, the clock stops moving what it + /// holds — its routine no longer rolls and its obligation no longer + /// presses — while a live subject's goal and dependency still move on the + /// same tick. Nothing is discharged or deleted; the retired subject's + /// commitments stay on record, un-fulfilled and un-pressed, exactly as + /// they were the moment it retired. + #[test] + fn after_retirement_a_tick_moves_none_of_the_retired_subjects_commitments() { + let (mut kernel, clockwork, _) = clock_kernel("PAf37Frozen"); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + play_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); + let routine_before = due(&kernel, clockwork.farmer, clockwork.routine); + let dependency_source = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + routine_before, + "a retired subject's routine still rolled" + ); + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 0, + "a retired subject's obligation still pressed" + ); + assert_eq!( + pressure( + &kernel, + clockwork.reeve, + PressureSource::Commitment { + subject: clockwork.reeve, + key: clockwork.goal, + } + ), + 1, + "the live subject's goal did not press" + ); + assert_eq!( + pressure(&kernel, clockwork.reeve, dependency_source), + 1, + "the live subject's dependency did not press" + ); + + assert!( + kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.routine), + "the frozen routine was discharged or deleted rather than left as history" + ); + assert!( + kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.obligation), + "the frozen obligation was discharged or deleted rather than left as history" + ); + } + + /// PA.f37, the other half: retiring the subject that holds the goal and + /// the dependency freezes those instead, while the still-live farmer's + /// routine and obligation keep moving. Soul's probe retired a subject + /// whose routine rolled and whose goal and dependency kept pressing; this + /// pins the dependency loop in `derive_motion` the first test above never + /// exercises, since the farmer it retires holds no dependency. + #[test] + fn after_retirement_a_tick_moves_none_of_the_retired_subjects_goal_or_dependency() { + let (mut kernel, clockwork, _) = clock_kernel("PAf37FrozenDep"); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + play_retires(&mut kernel, clockwork.reeve).expect("retire the reeve"); + let routine_before = due(&kernel, clockwork.farmer, clockwork.routine); + let dependency_source = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + + assert_eq!( + pressure( + &kernel, + clockwork.reeve, + PressureSource::Commitment { + subject: clockwork.reeve, + key: clockwork.goal, + } + ), + 0, + "a retired subject's goal still pressed" + ); + assert_eq!( + pressure(&kernel, clockwork.reeve, dependency_source), + 0, + "a retired subject's dependency still pressed" + ); + assert_ne!( + due(&kernel, clockwork.farmer, clockwork.routine), + routine_before, + "the live subject's routine did not roll" + ); + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 1, + "the live subject's obligation did not press" + ); + } + + /// PA.f37: the freeze survives a full reopen-and-replay, the same way + /// every other retirement effect in this batch does. + #[test] + fn a_retired_subjects_frozen_commitments_survive_reopen_and_replay() { + let (exported, farmer, routine, obligation) = { + let (mut kernel, clockwork, _) = clock_kernel("PAf37Replay"); + play_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + ( + kernel.export().unwrap(), + clockwork.farmer, + clockwork.routine, + clockwork.obligation, + ) + }; + let reopened = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!( + due(&reopened, farmer, routine), + FictionalMinutes(ROUTINE_DUE), + "the routine rolled somewhere along the replayed path" + ); + assert_eq!( + pressure( + &reopened, + farmer, + PressureSource::Commitment { + subject: farmer, + key: obligation, + } + ), + 0, + "the obligation pressed somewhere along the replayed path" + ); + } + + // ---- Retirement fix batch, test gaps (PA.f39) -------------------------- + + /// PA.f39, M2: `AcquireKnowledge` refuses a retired subject regardless of + /// source. `Evidenced` already carries its own provenance guard + /// (`EvidencedKnowledgeOfClaim`), which makes it plausible for a future + /// edit to narrow the retirement check to `source != Evidenced`; this + /// proves the retirement check still fires for an `Evidenced` acquire + /// too. + #[test] + fn a_retired_subject_cannot_acquire_evidenced_knowledge() { + let (mut kernel, clockwork, _) = clock_kernel("PAf39Evidenced"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); + let patch = WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("news"), + label: "The Harvest Report".into(), + statement: Statement::new("The winter grain is counted.").unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:count"), + }, + })], + operations: vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.farmer), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }], + evidence: vec![EvidenceRef::new("vault:count")], + }; + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { patch }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f39, Soul's probe S2: `CanReach` to a placeless target reachable + /// only through a `Reach::Subjects` channel — no co-location is possible + /// — is refused once the target retires. This exercises `audience()`'s + /// channel side, which PA.f33's Colocated-only `CanReach` test + /// (`a_retired_subject_is_unreachable_through_can_reach`) never reaches, + /// and kills a mutation that removes `audience()`'s retired filter. + #[test] + fn a_retired_placeless_subject_is_unreachable_through_a_subjects_channel() { + let (mut kernel, clockwork, _) = clock_kernel("PAf39S2"); + let speak = super::tests::speak_entry(&kernel); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("outcast"), + label: "The Placeless Outcast".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak.clone()]), + position: None, + import_key: None, + }), + Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Outcast Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Draft(DraftHandle::new("outcast")), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("hail"), + kind: AffordanceKindName("hail".into()), + roles: vec![ + RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("channel".into()), + kind: RefKind::Entity(EntityKind::Channel), + }, + ], + preconditions: vec![Precondition::CanReach { + subject: Role("target".into()), + via: AudienceSpec::Channel(Role("channel".into())), + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + ], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(clockwork.farmer), + affordance: Ref::Draft(DraftHandle::new("hail")), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority declares the placeless outcast and its channel"); + + let positions = kernel.state.positions.clone(); + let outcast = *kernel + .state + .subjects + .keys() + .find(|id| !positions.contains_key(id)) + .expect("the declared placeless outcast"); + let wire = *kernel.state.channels.keys().next().expect("the declared channel"); + let snapshot = kernel.snapshot().unwrap(); + let hail = affordance_named(&snapshot, "hail"); + let invocation = DecisionInvocation { + affordance: hail, + bindings: vec![ + binding("target", Target::Subject(outcast)), + binding("channel", Target::Entity(wire)), + ], + proposed: Vec::new(), + speech: Some(Statement::new("Hail!").unwrap()), + display: None, + }; + submit_as( + &mut kernel, + play_caller(), + CommandBody::Act { + actor: clockwork.farmer, + invocation: invocation.clone(), + }, + ) + .expect("the live outcast is reachable through the channel"); + + play_retires(&mut kernel, outcast).expect("retire the outcast"); + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::Act { + actor: clockwork.farmer, + invocation, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::ActionRejected(set) + if set.contains(&ActionMismatch::CannotReach { precondition: 0 })), + "{error:?}" + ); + } +} + +/// After genesis only Play writes, and a world is born Active. Each rule here +/// is the one the reducer's single admission gate decides, on commit and at +/// the commit-time re-decision. +#[cfg(test)] +mod agency_tests { + use super::tests::{ + act, affordance_named, auth_principal, command, creation, first_grant, human_principal, + operations, owner, play_command, reject_play, speak, subject_by_label, submit_play, + tick_body, + }; + use super::*; + + fn world(title: &str) -> WorldKernel { + let (kernel, _) = WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .unwrap(); + kernel + } + + fn declare_place_patch(handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + #[test] + fn after_genesis_only_play_writes() { + let mut kernel = world("PlayOnly"); + let snapshot = kernel.snapshot().unwrap(); + let human = subject_by_label(&kernel.state, "The Human"); + let persona = subject_by_label(&kernel.state, "The Witness"); + let operator = subject_by_label(&kernel.state, "The Council"); + let convene = affordance_named(&snapshot, "convene"); + let bodies = vec![ + ( + "declare", + CommandBody::AdmitPatch { + patch: declare_place_patch("annex"), + }, + ), + ( + "retire", + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(persona), + }]), + ), + ( + "grant", + operations(vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(human), + affordance: Ref::Existing(convene), + }]), + ), + ( + "revoke", + operations(vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(operator), + affordance: Ref::Existing(convene), + }]), + ), + ("advance", tick_body(5)), + ( + "act", + CommandBody::Act { + actor: human, + invocation: speak(first_grant(&snapshot, human), "Hello."), + }, + ), + ]; + + for (name, body) in &bodies { + for caller in [ + CallerId::Principal(owner()), + CallerId::Principal(human_principal()), + ] { + let commits = kernel.journal.commit_count(); + let error = kernel + .submit( + command(&snapshot, caller.clone(), body.clone()), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::Unauthorized), + "{name} as {caller:?}: {error:?}" + ); + assert_eq!(kernel.journal.commit_count(), commits, "{name} committed"); + assert_eq!(kernel.snapshot().unwrap(), snapshot, "{name} moved the world"); + } + } + for (name, body) in bodies { + let before = kernel.snapshot().unwrap(); + let receipt = kernel + .submit( + play_command(&before, body), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_or_else(|error| panic!("Play {name}: {error:?}")); + assert!(receipt.resulting_revision > 0, "Play {name}"); + } + } + + #[test] + fn apply_effect_re_decides_play() { + let kernel = world("ReDecide"); + let state = &kernel.state; + let command_id = CommandId::issue(); + let human = subject_by_label(state, "The Human"); + let affordance = first_grant(&kernel.snapshot().unwrap(), human); + let invocation = speak(affordance, "Spoken."); + let granted = require_granted(state, human, affordance).unwrap(); + let event = action::exercise(state, command_id, human, &granted, &invocation).unwrap(); + let minutes = TickMinutes::new(9).unwrap(); + let to = state.header.now.checked_add(minutes).unwrap(); + let effects = [ + ( + "patch", + WorldEffect::PatchAdmitted { + resolved: patch::resolve_patch( + state, + command_id, + &declare_place_patch("annex"), + ) + .unwrap(), + }, + ), + ("act", WorldEffect::Acted { invocation, event }), + ( + "tick", + WorldEffect::TimeAdvanced { + minutes, + to, + motion: clock::derive_motion(state, to), + }, + ), + ]; + for (name, effect) in &effects { + for caller in [ + CallerId::Principal(owner()), + CallerId::Principal(human_principal()), + ] { + let mut candidate = state.clone(); + let error = apply_effect(&mut candidate, command_id, &caller, effect).unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{name}: {error:?}"); + assert_eq!(&candidate, state, "{name} mutated before refusing"); + } + let mut candidate = state.clone(); + apply_effect(&mut candidate, command_id, &CallerId::Play, effect) + .unwrap_or_else(|error| panic!("Play {name}: {error:?}")); + assert_ne!(&candidate, state, "Play {name} changed nothing"); + } + } + + /// The gate sits at the top of `reduce`, so a non-Play caller learns + /// nothing about the world through a refusal: a patch that would be + /// rejected for naming an unknown subject, and an act the actor has no + /// grant for, both come back Unauthorized. + #[test] + fn a_non_play_caller_is_refused_before_the_world_is_read() { + let mut kernel = world("Blind"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_label(&kernel.state, "The Witness"); + let ungranted = affordance_named(&snapshot, "convene"); + let broken = operations(vec![ComponentOp::Retire { + subject: Ref::Existing(SubjectId::issue()), + }]); + let denied = CommandBody::Act { + actor: persona, + invocation: speak(ungranted, "Not mine."), + }; + for caller in [ + CallerId::Principal(owner()), + CallerId::Principal(human_principal()), + ] { + for body in [broken.clone(), denied.clone()] { + let error = kernel + .submit( + command(&snapshot, caller.clone(), body), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + } + // The same commands from Play are refused for what they are. + let error = reject_play(&mut kernel, &snapshot, broken); + assert!(!error.is_empty()); + let error = act(&mut kernel, persona, speak(ungranted, "Not mine.")).unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied), "{error:?}"); + } + + #[test] + fn a_world_is_born_active() { + let mut kernel = world("BornActive"); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!(snapshot.revision, 0); + let human = subject_by_label(&kernel.state, "The Human"); + act(&mut kernel, human, speak(first_grant(&snapshot, human), "At once.")).unwrap(); + let accepted = kernel.snapshot().unwrap(); + assert_eq!(accepted.revision, 1); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + + let mut kernel = world("BornActiveClock"); + let genesis = kernel.snapshot().unwrap(); + submit_play(&mut kernel, &genesis, tick_body(1)); + assert_eq!(kernel.snapshot().unwrap().revision, 1); + } + + /// Retirement is stored once, on the subject, and a live subject's row is + /// the shape it had before the flag existed. + #[test] + fn a_live_subjects_row_is_unchanged_by_the_flag() { + let live = SubjectState { + label: "Walker".into(), + kind: SubjectKind::Person, + import_key: None, + retired: false, + }; + let live_json = serde_json::to_value(&live).unwrap(); + assert!(live_json.get("retired").is_none()); + let retired = SubjectState { retired: true, ..live.clone() }; + let retired_json = serde_json::to_value(&retired).unwrap(); + assert_eq!(retired_json["retired"], true); + assert_eq!(serde_json::from_value::(live_json).unwrap(), live); + assert_eq!(serde_json::from_value::(retired_json).unwrap(), retired); + } + + #[test] + fn a_patch_carrying_a_controller_does_not_decode() { + let Declaration::Subject(declared) = crate::tests::subject("walker", "Walker", SubjectKind::Person) + else { + unreachable!() + }; + let mut json = serde_json::to_value(&declared).unwrap(); + serde_json::from_value::(json.clone()) + .expect("the declaration decodes as built"); + json["controller"] = serde_json::json!({"type": "operational_agent"}); + assert!(serde_json::from_value::(json).is_err()); + } + + /// Retire sets the flag `is_retired` reads, and nothing else retires. + #[test] + fn retirement_lives_on_the_subject() { + let mut kernel = world("RetireFlag"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_label(&kernel.state, "The Witness"); + assert!(!is_retired(&kernel.state, persona)); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(persona), + }]), + ); + assert!(kernel.state.subjects[&persona].retired); + assert!(is_retired(&kernel.state, persona)); + assert!(!kernel.state.positions.contains_key(&persona)); + assert!(!kernel.state.affordance_grants.contains_key(&persona)); + let after = kernel.snapshot().unwrap(); + assert!(after.subjects.iter().find(|s| s.id == persona).unwrap().retired); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).unwrap(); + assert!(is_retired(&reopened.state, persona)); + assert_eq!(reopened.snapshot().unwrap(), after); + } + + #[test] + fn retired_tags_do_not_decode() { + fn refused(json: &str) { + assert!(serde_json::from_str::(json).is_err(), "{json} decoded"); + } + let id = "\"00000000-0000-4000-8000-000000000000\""; + refused::(r#"{"type":"approve_draft"}"#); + refused::(r#"{"type":"activate_world"}"#); + refused::(&format!(r#"{{"type":"controller","id":{id}}}"#)); + refused::(r#"{"type":"system","id":{"capability":"clock"}}"#); + refused::(r#"{"type":"system","id":{"capability":"play"}}"#); + refused::(&format!( + r#"{{"type":"system","id":{{"capability":"consumer","consumer":{id}}}}}"# + )); + refused::(r#"{"type":"draft_approved","principal":"p"}"#); + refused::(r#"{"type":"world_activated"}"#); + assert_eq!( + serde_json::from_str::(r#"{"type":"play"}"#).unwrap(), + CallerId::Play + ); + } + + #[test] + fn a_revoke_may_leave_a_subject_with_no_verbs() { + let mut kernel = world("Mute"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_label(&kernel.state, "The Witness"); + let only = first_grant(&snapshot, persona); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(persona), + affordance: Ref::Existing(only), + }]), + ); + assert!( + !kernel + .state + .affordance_grants + .contains_key(&persona), + "the emptied row was kept" + ); + let error = act(&mut kernel, persona, speak(only, "Silent.")).unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied), "{error:?}"); + journal::verify_state_shape(&kernel.state).expect("a mute subject is a legal shape"); + let accepted = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + assert_eq!( + WorldKernel::open(&exported) + .unwrap() + .snapshot() + .unwrap(), + accepted + ); + } + + #[test] + fn a_subject_may_be_declared_with_no_verbs() { + let mute = |handle: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: SubjectKind::Person, + affordances: BTreeSet::new(), + position: Some(Ref::Draft(DraftHandle::new(super::tests::COMMONS))), + import_key: None, + }) + }; + let mut input = creation("Mutes"); + input.patch.declarations.push(mute("born-mute")); + let (mut kernel, _) = WorldKernel::create(input, + &auth_principal(owner()), + ) + .unwrap(); + let snapshot = kernel.snapshot().unwrap(); + let speaking = first_grant(&snapshot, subject_by_label(&kernel.state, "The Human")); + submit_play( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + position: None, + ..match mute("declared-mute") { + Declaration::Subject(subject) => subject, + _ => unreachable!(), + } + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + let snapshot = kernel.snapshot().unwrap(); + for label in ["The born-mute", "The declared-mute"] { + let found = snapshot + .subjects + .iter() + .find(|subject| subject.label == label) + .unwrap(); + assert!(found.affordances.is_empty(), "{label}"); + assert!( + !kernel + .state + .affordance_grants + .contains_key(&found.id), + "{label} holds a grant row" + ); + let error = act(&mut kernel, found.id, speak(speaking, "Mute.")).unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied), "{label}: {error:?}"); + } + } + + #[test] + fn a_retired_subject_takes_no_grant() { + let mut kernel = world("RetiredGrants"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_label(&kernel.state, "The Witness"); + let convene = affordance_named(&snapshot, "convene"); + let grant = ComponentOp::GrantAffordance { + subject: Ref::Existing(persona), + affordance: Ref::Existing(convene), + }; + let revoke = ComponentOp::RevokeAffordance { + subject: Ref::Existing(persona), + affordance: Ref::Existing(first_grant(&snapshot, persona)), + }; + let retire = ComponentOp::Retire { + subject: Ref::Existing(persona), + }; + for op in [grant.clone(), revoke.clone()] { + let mismatches = reject_play( + &mut kernel, + &snapshot, + operations(vec![retire.clone(), op]), + ); + assert_eq!( + mismatches, + vec![Mismatch::GrantsToRetired { operation: 1 }], + "same patch" + ); + } + submit_play(&mut kernel, &snapshot, operations(vec![retire])); + let snapshot = kernel.snapshot().unwrap(); + for op in [grant, revoke] { + let mismatches = reject_play(&mut kernel, &snapshot, operations(vec![op])); + assert_eq!(mismatches, vec![Mismatch::GrantsToRetired { operation: 0 }]); + } + } + + #[test] + fn retire_applies_to_every_subject() { + let mut kernel = world("RetireAll"); + let snapshot = kernel.snapshot().unwrap(); + let everyone = ["The Human", "The Witness", "The Council"] + .map(|label| subject_by_label(&kernel.state, label)); + submit_play( + &mut kernel, + &snapshot, + operations( + everyone + .iter() + .map(|subject| ComponentOp::Retire { + subject: Ref::Existing(*subject), + }) + .collect(), + ), + ); + let after = kernel.snapshot().unwrap(); + assert_eq!(after.subjects.len(), everyone.len()); + for subject in &after.subjects { + assert!(subject.retired, "{} was not retired", subject.label); + assert!(subject.affordances.is_empty()); + assert!(subject.position.is_none()); + } + assert!(kernel.state.affordance_grants.is_empty()); + let exported = kernel.export().unwrap(); + drop(kernel); + assert_eq!( + WorldKernel::open(&exported) + .unwrap() + .snapshot() + .unwrap(), + after + ); + } + + /// `apply_operation` re-decides the retired guard the resolver also holds: + /// a forged `PatchAdmitted` that grants a retired subject a verb is refused + /// at apply rather than leaving a grant row the shape check calls corrupt. + #[test] + fn apply_refuses_a_grant_to_a_retired_subject() { + let mut kernel = world("ForgedGrant"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_label(&kernel.state, "The Witness"); + let convene = affordance_named(&snapshot, "convene"); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(persona), + }]), + ); + let forged = WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![ResolvedOp::GrantAffordance { + subject: persona, + affordance: convene, + }], + evidence: Vec::new(), + }, + }; + let mut candidate = kernel.state.clone(); + let error = + apply_effect(&mut candidate, CommandId::issue(), &CallerId::Play, &forged).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert!( + !candidate + .affordance_grants + .contains_key(&persona), + "a retired subject was granted a verb" + ); + } +} diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs new file mode 100644 index 000000000..b01de3373 --- /dev/null +++ b/native/aetherlight/src/patch.rs @@ -0,0 +1,6699 @@ +//! Closed-patch resolution: the one owner of draft handles, reference kinds, and +//! declaration-lane ID allocation. +//! +//! Only [`derive_id`] allocates a canonical ID, and it is called from exactly +//! two sites: [`resolve_patch`] here, and `action::exercise`, which mints one +//! referent per speech-carrying invocation — always a `Claimed` fact asserted by +//! the acting subject. +//! +//! A patch names structure two ways and no other way: an exact canonical ID that +//! already keys a partition, or a draft handle declared in the same patch. +//! Resolution accumulates the complete mismatch set first and allocates only +//! after that set is empty, so a rejected patch never mints an ID. + +use super::clock::{FictionalMinutes, TickMinutes}; +use super::docs::Docs; +use super::grammar::GrammarRefusal; +use super::{ + AffordanceId, ByEndpoint, ChildOf, CommandId, EdgeId, EntityId, SubjectId, SubjectKind, + SubjectState, WorldId, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet, btree_map::Entry}; +use unicode_properties::{GeneralCategory, UnicodeGeneralCategory}; +use uuid::Uuid; + +mod candidate; +use candidate::{Candidate, Overlay}; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum EntityKind { + Place, + Resource, + Fact, + Channel, +} + +/// Exactly the edge kinds that have a record shape. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum EdgeKind { + Route, +} + +/// Traversal rule. A `Restricted` route names the authority kind that opens it: +/// the door names its own key, and the kernel reads neither the door nor the key +/// beyond comparing the name. [`route_admits`] is the sole statement of who gets +/// through, reached identically by `resolve_patch`'s `Relocate` arm and by +/// `Precondition::Reachable`'s edge admission. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "access", rename_all = "snake_case")] +pub(crate) enum AccessKind { + Public, + Restricted { requires: AuthorityKindName }, +} + +/// A world-declared authority name: canonical text, `[a-z][a-z0-9_]{0,47}`. The +/// kernel carries it, compares it for equality, and reads it no other way. A +/// closed enum here would make "conscript" or "audit" a kernel change and put a +/// world's political vocabulary in the reducer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct AuthorityKindName(pub(crate) String); + +/// What an authority covers. Distinct from a subject, which says *whose* +/// authority it is and stays one field. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "over", content = "id", rename_all = "snake_case")] +pub(crate) enum AuthorityTarget { + Subject(SubjectId), + /// That place and everything contained in it, by `EntityRecord.container`. + PlaceSubtree(EntityId), +} + +impl AuthorityTarget { + /// The referent this target names, so "does grant A cover grant B's ground" + /// is the one covering predicate rather than a second one. + pub(super) fn as_referent(self) -> super::Target { + match self { + Self::Subject(subject_id) => super::Target::Subject(subject_id), + Self::PlaceSubtree(entity_id) => super::Target::Entity(entity_id), + } + } +} + +/// The proposal-time twin of [`AuthorityTarget`], carrying references. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "over", content = "ref", rename_all = "snake_case")] +pub(crate) enum AuthorityTargetRef { + Subject(Ref), + PlaceSubtree(Ref), +} + +/// One jurisdiction: a kind and the ground it runs over. Ordered `(kind, over)` +/// so a subject's grant set has one canonical order. A jurisdiction is a set of +/// these, so revoking one place is not a restatement of the whole scope. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct AuthorityGrant { + pub(crate) kind: AuthorityKindName, + pub(crate) over: AuthorityTarget, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct AuthorityGrantRef { + pub(crate) kind: AuthorityKindName, + pub(crate) over: AuthorityTargetRef, +} + +/// Canonical text, scoped to its institution: the pair (institution, name) is +/// the identity, the same discipline a `Role` gets inside one affordance. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct OfficeName(pub(crate) String); + +/// A seat inside one institution. It carries no term and no selection method: +/// there is no clock, so nothing can expire, and a field nothing reads is a +/// decoration the next pass has to delete. `delegated` is the field that earns +/// its keep — `scope_components` reads it and `Authorized` resolves through it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Office { + /// A person subject, or vacant. A vacancy is an ordinary state. + pub(crate) incumbent: Option, + /// Which of the institution's authority kinds this office lends its + /// incumbent. Non-empty: an office lending nothing is inert. + pub(crate) delegated: BTreeSet, +} + +/// World-declared canonical text, kernel-opaque, `[a-z][a-z0-9_]{0,47}`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct GrievanceKindName(pub(crate) String); + + +impl crate::docs::DocKey for GrievanceKindName { + fn key_text(&self) -> String { + self.0.clone() + } +} + +/// Where one kind of grievance goes, and who may bring it. One forum per +/// grievance kind, world-wide; per-jurisdiction forums would key this on +/// `(GrievanceKindName, AuthorityTarget)`, and that key has no consumer yet. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Forum { + /// Any subject. A one-person magistrate is a legitimate forum, so the + /// kernel branches on `SubjectKind` here as it does everywhere else: not at + /// all. + pub(crate) forum: SubjectId, + /// Who may bring this grievance. It reuses `AuthorityTarget`'s type and its + /// covering predicate and is emphatically not stored in the `authority` + /// partition, so `RevokeAuthority` cannot strip standing. + pub(crate) standing: AuthorityTarget, +} + +/// Whole minutes: the kernel's only time unit, so route cost adds and compares +/// with no converter. The valid range is checked, not typed, so a bad cost joins +/// the complete mismatch set instead of failing deserialization. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct Cost(pub(crate) u32); + +/// One year of minutes; bounds path sums. +pub(super) const MAX_ROUTE_COST: u32 = 525_600; + +/// A conserved count. Unsigned because a holding can never be negative: a signed +/// type would make "owes 3 iron" representable and push the real check to runtime +/// anyway. Subtraction is `checked_sub` and its failure is `InsufficientCustody`; +/// addition is `checked_add` and its failure is `QuantityOverflow`. No saturating +/// arithmetic anywhere, because a silent clamp is a silent conservation break. +/// There is no maximum: nothing sums quantities across resources, so the honest +/// bound is the type's. There is no unit, because a unit is where prices enter. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct Quantity(pub(crate) u64); + +/// What a subject depends on. A dependency is a bare relation: no magnitude, no +/// kind beyond its target namespace, no clock, no cost. The variant selects the +/// resolver, so the target kind is carried by the type rather than checked after +/// the fact. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "id", rename_all = "snake_case")] +pub(crate) enum DependencyTarget { + Resource(EntityId), + Route(EdgeId), + Subject(SubjectId), +} + +/// The proposal-time twin of [`DependencyTarget`], carrying references rather +/// than canonical IDs. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "ref", rename_all = "snake_case")] +pub(crate) enum DependencyRef { + Resource(Ref), + Route(Ref), + Subject(Ref), +} + +/// Where a subject stands. One place, derived from nothing else. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct Position { + pub(crate) place: EntityId, +} + +/// Namespace plus declared kind of a draft handle. A reference states the kind it +/// expects; resolution refuses a handle that answers with another one. A subject +/// expectation carries `None` where the referring position constrains the +/// namespace but not the kind. +/// +/// It is one predicate serving three readers: the resolution index, `Mismatch`, +/// and an affordance's `RoleSpec`, which persists inside the catalog and so +/// requires the serde derives. `Affordance` names the catalog namespace, which +/// carries no components and can never be a role's target. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "namespace", content = "kind", rename_all = "snake_case")] +pub enum RefKind { + Subject(Option), + Entity(EntityKind), + Edge(EdgeKind), + Affordance, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct DraftHandle(String); + +impl DraftHandle { + pub(super) fn new(value: impl Into) -> Self { + Self(value.into()) + } +} + +/// A reference is an exact canonical ID or a handle resolved in the same patch. +/// There is no third form and no `From`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "ref", content = "value", rename_all = "snake_case")] +pub enum Ref { + Existing(Id), + Draft(DraftHandle), +} + +/// A referent in any of the three referent namespaces, or in the catalog. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "namespace", content = "ref", rename_all = "snake_case")] +pub enum RefName { + Subject(Ref), + Entity(Ref), + Edge(Ref), + Affordance(Ref), +} + +/// A world-declared affordance name. Canonical text, `[a-z][a-z0-9_]{0,47}`, +/// because it becomes a generated tool name and a tool name must be stable, +/// unique, and safe. The kernel carries it and branches on it nowhere; that is +/// what keeps genre out of the reducer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct AffordanceKindName(pub String); + +/// A named slot in one affordance, bound to a referent at invocation time. +/// Canonical text, `[a-z][a-z0-9_]{0,31}` — it becomes a tool parameter name. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct Role(pub(crate) String); + +/// What a role must be bound to. `RefKind` is reused rather than restated: it +/// already spells subject, entity kind, and edge kind, so the binding kind-check +/// and the declaration kind-check are one predicate. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct RoleSpec { + pub(crate) role: Role, + pub(crate) kind: RefKind, +} + +/// Committed world text: canonical, non-empty. The kernel stores it, hands it to +/// a projection, and reads it no other way. Nothing compares two `Statement`s: +/// no dedup, no interning, no contradiction check, no similarity. Two facts with +/// byte-identical statements are two facts. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct Statement(String); + +impl Statement { + pub fn new(value: impl Into) -> Option { + let value = value.into(); + is_canonical_text(&value).then_some(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// How a fact stands. Immutable after admission: there is no `SetStanding`. A +/// claim never becomes canon and canon never degrades to a claim, so nothing +/// ever has to decide which of two facts wins. A world in which a court rules on +/// a rumour declares a *new* `Canonical` fact; the rumour survives beside it, +/// which is what makes a later `Redress` reading possible at all. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "standing", rename_all = "snake_case")] +pub(crate) enum FactStanding { + /// Admitted with a receipt, through the same evidence gate `Admit` uses. + Canonical { evidence: EvidenceRef }, + /// Asserted by a subject. The kernel does not evaluate the assertion. + Claimed { by: SubjectId }, + /// Stated by the play table. The kernel does not evaluate it; only `Play` + /// may write it. + Ruled, +} + +/// The proposal-time twin of [`FactStanding`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "standing", rename_all = "snake_case")] +pub(crate) enum FactStandingRef { + Canonical { evidence: EvidenceRef }, + Claimed { by: Ref }, + Ruled, +} + +/// One `EntityKind::Fact` row's payload. Write-once: only declaration and +/// `AssertClaim` ever write `facts`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct FactRecord { + pub(crate) statement: Statement, + pub(crate) standing: FactStanding, +} + +/// Where a channel carries. A place reach is the subtree, through the same +/// [`covers_place`] walk a `PlaceSubtree` jurisdiction uses. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "reach", content = "of", rename_all = "snake_case")] +pub(crate) enum Reach { + /// Exactly these subjects. May be empty: an empty reach is the named + /// silenced state, which is the outcome this component exists to hold. + Subjects(BTreeSet), + /// Everyone positioned at that place or anywhere inside it. + Place(EntityId), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "reach", content = "of", rename_all = "snake_case")] +pub(crate) enum ReachRef { + Subjects(BTreeSet>), + Place(Ref), +} + +/// One `EntityKind::Channel` row's payload. It carries no latency: there is no +/// clock, so a latency field would be read by nothing and bound by nothing. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChannelRecord { + pub(crate) reach: Reach, + /// Who may speak on it besides those inside its reach, and whose scope + /// components carry it. The horn belongs to the temple, not to whoever happens + /// to be within earshot of it. + pub(crate) controller: Option, +} + +/// A small closed ordinal. Ordered ascending by declaration order, so derived +/// `Ord` *is* the semantics and `Knows { at_least }` is one `>=`. Three levels: +/// two cannot express "I heard it but I doubt it", which is the state deception +/// produces; four or more is a scale nothing in the vocabulary distinguishes. +/// There is no zero — forgetting is a removed key, exactly as `Quantity(0)` is +/// unstorable. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Confidence { + Doubted, + Believed, + Certain, +} + +/// Three sources with named writers: `Witnessed` is written by +/// `AcquireKnowledge` and by `Witness`, `Evidenced` by `AcquireKnowledge`, and +/// `Told` only by `Communicate`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "source", rename_all = "snake_case")] +pub(crate) enum KnowledgeSource { + Witnessed, + /// `via: None` is co-location. + Told { + by: SubjectId, + via: Option, + }, + /// A visible act of `by`, perceived in the same place. Written only by + /// `ResolvedOp::Display`, which the kernel alone lowers. + Seen { + by: SubjectId, + }, + Evidenced, +} + +/// What one subject holds of one fact. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Knowledge { + pub(crate) confidence: Confidence, + pub(crate) source: KnowledgeSource, + /// The revision at which this subject acquired this row: witnessed, + /// told, shown, or seeded by an author. Written by every writer of this + /// map (PA.f44), so the Projector's recency marker can tell a row minted + /// with no `minted_at` — a patch, a seed, a ruled fact — from one the + /// subject already held before its last act. + pub(crate) acquired_at: u64, +} + +/// The source an author may write. `Told` is unrepresentable here: only +/// `Communicate` writes it, so no author can forge a teller. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "source", rename_all = "snake_case")] +pub(crate) enum AuthoredSource { + Witnessed, + Evidenced, +} + +/// Where a telling lands. `Colocated` is derived from `positions` at check and +/// at apply; it is never a stored channel, so no entity is minted per place and +/// no world must enumerate a village to let people talk in a room. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Audience { + Colocated, + Channel(EntityId), +} + +impl Audience { + pub(super) fn channel(self) -> Option { + match self { + Self::Colocated => None, + Self::Channel(entity_id) => Some(entity_id), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum AudienceRef { + Colocated, + Channel(Ref), +} + +/// The catalog form: a declared affordance names a role, the invoker binds a +/// channel to it, and `exercise` lowers this plus the bindings into the +/// canonical [`Audience`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum AudienceSpec { + Colocated, + Channel(Role), +} + +/// What a subject has promised. The kernel branches on this twice — the tick +/// behaves differently per kind and the scale count reads `Goal` — so it is a +/// closed enum rather than a world-declared name. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum CommitmentKind { + Routine, + Obligation, + Goal, +} + +/// Deterministic from the creating command and the operation's index within +/// that command's lowered operations. No `EdgeId`: nothing references a +/// commitment by identity, so a structural key is the whole answer. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct CommitmentKey { + pub(crate) command: CommandId, + pub(crate) index: u32, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Commitment { + pub(crate) kind: CommitmentKind, + /// `None` is a promise to oneself: a personal `Goal`. A counterparty equal + /// to the subject is refused. + pub(crate) counterparty: Option, + /// Absolute. "Past due" is `due <= now`: one comparison, no countdown + /// fanned across the partition. + pub(crate) due: FictionalMinutes, + /// Required for `Routine` — that is what makes it recur — and forbidden + /// otherwise. On auto-fulfilment `due` rolls forward by this. + pub(crate) period: Option, + /// What must hold for a `Routine` to auto-fulfil. Role-free canonical + /// checks. Empty for `Obligation` and `Goal`. + pub(crate) checks: Vec, + /// What is promised, as the promisor would state it. Without it a promise + /// is a clock and a name, and on the road both parties invented the rest. + pub(crate) statement: Statement, +} + +/// Nonzero by construction; saturating in both directions. A separate newtype +/// from [`super::Magnitude`], which is an effect ceiling and shares nothing with +/// this but a word. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct PressureMagnitude(pub(crate) u32); + +/// Target-major, because every reader is: the typed view shows pressure on +/// self. Source-major has no reader. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "from", content = "of", rename_all = "snake_case")] +pub(crate) enum PressureSource { + /// A past-due commitment. Carries the promisor and the structural key. + Commitment { + subject: SubjectId, + key: CommitmentKey, + }, + /// An unavailable dependency of the pressed subject. This is how a closed + /// route in one realm becomes a political problem in another without anyone + /// deciding that it should be. + Dependency(DependencyTarget), + /// Another subject, pressing directly through an affordance effect. + Subject(SubjectId), +} + +/// The proposal-time twin of [`PressureSource`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "from", content = "of", rename_all = "snake_case")] +pub(crate) enum PressureSourceRef { + Commitment { + subject: Ref, + key: CommitmentKey, + }, + Dependency(DependencyRef), + Subject(Ref), +} + +/// The role-free canonical twin of [`Precondition`]. A `Precondition` names +/// roles; a `BoundPrecondition` names referents, so a commitment's checks are +/// storable with no second binding path and one evaluator serves both the +/// invocation pipeline and the tick. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum BoundPrecondition { + Present { + at: EntityId, + }, + Reachable { + to: EntityId, + within: Cost, + }, + Holds { + resource: EntityId, + at_least: Quantity, + }, + Authorized { + over: super::Target, + kind: AuthorityKindName, + }, + HasStanding { + grievance: GrievanceKindName, + }, + Knows { + fact: EntityId, + at_least: Confidence, + }, + CanBroadcast { + via: Audience, + }, + CanReach { + subject: SubjectId, + via: Audience, + }, + Committed { + to: SubjectId, + kind: CommitmentKind, + }, +} + +/// The proposal-time twin of [`BoundPrecondition`], carried by +/// `CreateCommitment` so a patch may name a check over structure it declares. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum PreconditionRef { + Present { + at: Ref, + }, + Reachable { + to: Ref, + within: Cost, + }, + Holds { + resource: Ref, + at_least: Quantity, + }, + Authorized { + over: AuthorityTargetRef, + kind: AuthorityKindName, + }, + HasStanding { + grievance: GrievanceKindName, + }, + Knows { + fact: Ref, + at_least: Confidence, + }, + CanBroadcast { + via: AudienceRef, + }, + CanReach { + subject: Ref, + via: AudienceRef, + }, + Committed { + to: Ref, + kind: CommitmentKind, + }, +} + +/// What must already be true of committed state before an invocation is +/// admitted. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum Precondition { + /// The acting subject's Position names the place bound to `at`. + Present { at: Role }, + /// A path exists from the actor's place to the place bound to `to`, over + /// open routes this subject may traverse, with summed cost at most `within`. + Reachable { to: Role, within: Cost }, + /// The acting subject's own holding of the resource bound to `resource` is + /// at least `at_least`. + Holds { resource: Role, at_least: Quantity }, + /// The acting subject's effective authority — its own grants plus what + /// every office it occupies lends — holds a grant of `kind` whose target + /// covers the referent bound to `over`. + Authorized { over: Role, kind: AuthorityKindName }, + /// A forum takes `grievance` and the acting subject is inside its standing. + HasStanding { grievance: GrievanceKindName }, + /// The acting subject holds the fact bound to `fact` at `at_least` or + /// better. + Knows { fact: Role, at_least: Confidence }, + /// The acting subject has an audience at all: it is positioned, for + /// co-location, or it is inside the bound channel's reach or is its + /// controller. + CanBroadcast { via: AudienceSpec }, + /// The referent bound to `subject` is inside that audience. Addressing does + /// not narrow the audience: a telling still lands on everyone in it. + CanReach { subject: Role, via: AudienceSpec }, + /// The acting subject holds a commitment of `kind` to the referent bound to + /// `to`. This is what lets a world author an affordance whose legitimacy is + /// a promise rather than a jurisdiction. + Committed { to: Role, kind: CommitmentKind }, +} + +/// Exactly the operations an affordance may propose. `Admit` is absent because +/// minting quantity requires an `EvidenceRef` and an invocation carries no +/// evidence list, so admitting it here would be a second creation path beside +/// the single evidenced one. `OpenOffice`, `CloseOffice`, `OpenForum`, and +/// `CloseForum` are absent because constituting an office or a forum has no +/// live in-play reader an affordance would serve; they stay patch-lane only. +/// +/// `Witness` is a slot and `Communicate` is not, because a witnessed event is +/// world-caused and names no speaker, while speech is the actor's own act and +/// reaches an invocation only through the kernel-owned `carries_speech` +/// lowering: a proposer that could `Communicate` would choose a speaker, and a +/// proposer that `Witness`es chooses only where. +/// +/// The four civic variants carry their payload on the variant rather than on +/// the slot or the invocation: an authority kind and an office name are not +/// referents, so they cannot be roles, and a proposer's only degree of freedom +/// stays magnitude. The world fixes the kind when it authors the entry. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ComponentOpKind { + Relocate, + OpenRoute, + CloseRoute, + AlterCost, + Transfer, + Transform, + Consume, + Bind, + Release, + GrantAuthority { + kind: AuthorityKindName, + }, + RevokeAuthority { + kind: AuthorityKindName, + }, + InstallIncumbent { + office: OfficeName, + }, + VacateOffice { + office: OfficeName, + }, + /// Source is fixed to `Witnessed`: only `Communicate` writes a teller, and + /// `Evidenced` needs a patch's evidence list, which an invocation has not. + AcquireKnowledge { + confidence: Confidence, + }, + /// A world-authored event with no speaker: a beacon, a bell, a blast. The + /// slot names a fact and a place, never a subject, so a proposer's only + /// degree of freedom is which declared place the entry binds. The source is + /// `Witnessed` by construction — `ComponentOp::Witness` has no field a + /// teller could enter — so this lowering cannot forge one however it is + /// bound. + Witness { + confidence: Confidence, + }, + Forget, + /// The kind, the horizon, and the period are fixed on the variant, so a + /// proposer's only degree of freedom stays magnitude. `due` is + /// `now + horizon`, computed by the kernel at lowering: an absolute due on + /// a catalog entry would be a fixed date the world outgrows. + CreateCommitment { + kind: CommitmentKind, + horizon: TickMinutes, + period: Option, + }, + /// The source is fixed to the acting subject, so it cannot be forged. A + /// world authoring `threaten`, `reassure`, or `forgive` needs these three. + AdvancePressure { + by: PressureMagnitude, + }, + ReducePressure { + by: PressureMagnitude, + }, + ResolvePressure, +} + +/// The referent shape of one operation: the single source of both the +/// declaration check and the lowering. +pub(super) enum RoleKindRule { + Exact(RefKind), + AnyDependencyTarget, + AnyAuthorityTarget, +} + +/// Which magnitude, if any, an operation carries. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum BoundsDimension { + None, + Quantity, + Cost, +} + +impl ComponentOpKind { + pub(super) fn arity(&self) -> Vec { + let subject = || RoleKindRule::Exact(ANY_SUBJECT); + let route = || RoleKindRule::Exact(ROUTE); + let resource = || RoleKindRule::Exact(RefKind::Entity(EntityKind::Resource)); + match self { + Self::Relocate => vec![subject(), route()], + Self::OpenRoute | Self::CloseRoute | Self::AlterCost => vec![route()], + Self::Transfer => vec![subject(), subject(), resource()], + Self::Transform => vec![subject(), resource(), resource()], + Self::Consume => vec![subject(), resource()], + Self::Bind | Self::Release => vec![subject(), RoleKindRule::AnyDependencyTarget], + Self::GrantAuthority { .. } | Self::RevokeAuthority { .. } => { + vec![subject(), RoleKindRule::AnyAuthorityTarget] + } + Self::InstallIncumbent { .. } => vec![subject(), subject()], + Self::VacateOffice { .. } => vec![subject()], + Self::AcquireKnowledge { .. } | Self::Forget => { + vec![subject(), RoleKindRule::Exact(FACT)] + } + Self::Witness { .. } => vec![RoleKindRule::Exact(FACT), RoleKindRule::Exact(PLACE)], + // Promisor and counterparty. A `Goal` slot is refused at admission + // with `GoalWithCounterparty`: a promise to oneself has no second + // referent to bind, so the action lane authors `Routine` and + // `Obligation` and the patch lane authors goals. + Self::CreateCommitment { .. } => vec![subject(), subject()], + Self::AdvancePressure { .. } | Self::ReducePressure { .. } | Self::ResolvePressure => { + vec![subject()] + } + } + } + + pub(super) fn dimension(&self) -> BoundsDimension { + match self { + Self::Transfer | Self::Transform | Self::Consume => BoundsDimension::Quantity, + Self::AlterCost => BoundsDimension::Cost, + _ => BoundsDimension::None, + } + } + + /// The civic names this variant carries, so one validator checks them all. + fn payload_names(&self) -> Vec<&str> { + match self { + Self::GrantAuthority { kind } | Self::RevokeAuthority { kind } => vec![&kind.0], + Self::InstallIncumbent { office } | Self::VacateOffice { office } => vec![&office.0], + _ => Vec::new(), + } + } +} + +/// Whether a declared role kind can serve a position governed by this rule. +pub(super) fn role_kind_fits(rule: &RoleKindRule, declared: RefKind) -> bool { + match rule { + RoleKindRule::Exact(RefKind::Subject(_)) => matches!(declared, RefKind::Subject(_)), + RoleKindRule::Exact(expected) => *expected == declared, + RoleKindRule::AnyDependencyTarget => matches!( + declared, + RefKind::Subject(_) | RefKind::Entity(EntityKind::Resource) | RefKind::Edge(_) + ), + RoleKindRule::AnyAuthorityTarget => { + matches!(declared, RefKind::Subject(_) | PLACE) + } + } +} + +/// The magnitude ceiling for one slot. A closed enum matched to the operation's +/// dimension rather than a struct of optional ceilings: an `Option` ceiling that +/// is `None` is not a ceiling, and a struct admits the nonsense of a cost +/// ceiling on a `Transfer`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "bound", content = "max", rename_all = "snake_case")] +pub(crate) enum Bounds { + None, + Quantity(Quantity), + Cost(Cost), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct EffectSlot { + pub(crate) op_kind: ComponentOpKind, + /// Positional: exactly the referents `op_kind` takes, in `arity()` order. + pub(crate) roles: Vec, + pub(crate) bounds: Bounds, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct OutcomeBand { + /// At least 1. A zero-weight band is a branch that can never be selected. + pub(crate) weight: u32, + /// Indices into `effect_slots`, strictly increasing. Empty is legal and is + /// how a world expresses "the attempt does nothing". + pub(crate) effects: Vec, +} + +/// One catalog entry: what an affordance *is*. Who may use it is +/// `affordance_grants` and nothing else, so an entry carries no audience. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Affordance { + pub kind: AffordanceKindName, + /// Ordered, so the generated tool's parameters are stable across builds. + pub(crate) roles: Vec, + pub(crate) preconditions: Vec, + pub(crate) effect_slots: Vec, + pub(crate) outcome_bands: Vec, + /// Every invocation of this entry carries exactly one utterance. The + /// kernel's only behaviour is to record it in the event; any world may + /// declare a speaking affordance, so this is not a Speak special case. + pub(crate) carries_speech: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct AffordanceDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) kind: AffordanceKindName, + pub(crate) roles: Vec, + pub(crate) preconditions: Vec, + pub(crate) effect_slots: Vec, + pub(crate) outcome_bands: Vec, + pub(crate) carries_speech: bool, +} + +/// Where a failed check appeared. One way to say it, for declarations and +/// operations alike. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "site", content = "at", rename_all = "snake_case")] +pub enum Site { + Declaration(DraftHandle), + Operation(usize), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct EvidenceRef(String); + +impl EvidenceRef { + /// An author's evidence receipts are built here, and `Deserialize` + /// already mints one from any string, so this constructor gates nothing. + /// Canonical text is checked by the resolver, in the complete mismatch set. + pub(super) fn new(value: impl Into) -> Self { + Self(value.into()) + } + + pub(super) fn text(&self) -> &str { + &self.0 + } +} + +/// The Aetheria record a subject was imported from: the CultCache schema id and +/// the record key, compared exactly as two separate texts so no pair of +/// distinct records can spell one key. Admission keeps the mapping injective; +/// a key is never matched by prefix, case or normalisation. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct ImportKey { + schema: String, + record: String, +} + +/// The longest either part of an import key may be, in bytes. +const MAX_IMPORT_KEY_PART_BYTES: usize = 200; + +impl ImportKey { + pub fn new(schema: impl Into, record: impl Into) -> Self { + Self { + schema: schema.into(), + record: record.into(), + } + } + + pub fn schema(&self) -> &str { + &self.schema + } + + pub fn record(&self) -> &str { + &self.record + } + + /// The one predicate for an import key, called by the resolver and by the + /// load-time state gate alike. The record part is canonical free text: not + /// empty, at most 200 bytes, no leading, trailing or doubled space, already NFC + /// (refused, never normalised, so the kernel derives no second spelling), + /// no control or format character, and no whitespace but U+0020. The schema + /// part is a schema id: the same text with no space at all. + pub(super) fn is_canonical(&self) -> bool { + is_canonical_key_text(&self.record) + && is_canonical_key_text(&self.schema) + && !self.schema.contains(' ') + } +} + +fn is_canonical_key_text(part: &str) -> bool { + !part.is_empty() + && part.len() <= MAX_IMPORT_KEY_PART_BYTES + && !part.starts_with(' ') + && !part.ends_with(' ') + && !part.contains(" ") + && unicode_normalization::is_nfc(part) + && part.chars().all(|c| { + !c.is_control() + && c.general_category() != GeneralCategory::Format + && (c == ' ' || !c.is_whitespace()) + }) +} + +/// Why an import key cannot join a world: the resolver names these by draft +/// handle, the state gates by invariant text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ImportKeyFault { + Malformed, + Held, + Duplicate, +} + +/// The one decision on a key: malformed, held by a subject already in the +/// world (`held` asks the subjects' `ByImportKey` index, retired ones +/// included, so a key is never reissued), or already claimed in `declared` +/// (which it joins). Every door that admits or loads subjects calls this, so +/// none can decide otherwise. +pub(super) fn import_key_fault<'a>( + key: &'a ImportKey, + held: impl Fn(&ImportKey) -> bool, + declared: &mut BTreeSet<&'a ImportKey>, +) -> Option { + if !key.is_canonical() { + Some(ImportKeyFault::Malformed) + } else if held(key) { + Some(ImportKeyFault::Held) + } else if !declared.insert(key) { + Some(ImportKeyFault::Duplicate) + } else { + None + } +} + +/// `position` is the subject's presence: one place it stands in. A subject +/// declared without one is unplaced until a later pass gives placement an owner. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct SubjectDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) kind: SubjectKind, + /// The catalog entries this subject may exercise. Every entry is a + /// reference, so a genesis patch declares a catalog and grants from it + /// atomically. + pub(crate) affordances: BTreeSet>, + pub(crate) position: Option>, + /// The record this subject was imported from, if any. Absent from a + /// subject nobody imported, so such a world's state and digests are what + /// they were before import keys existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) import_key: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct EntityDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) kind: EntityKind, + /// Legal only for `EntityKind::Place`, and only ever names a place. + pub(crate) container: Option>, +} + +/// A declared route is open. A route that should start closed is `declare` plus +/// `CloseRoute` in the same patch, so `open` has one writer family. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct RouteDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) from: Ref, + pub(crate) to: Ref, + pub(crate) access: AccessKind, + pub(crate) cost: Cost, +} + +/// A fact's label is a short authored name ("the flooding of the lower hinge"), +/// never a transcript: the statement is never copied into the label and the +/// label is never derived from the statement, so the utterance has exactly one +/// home in state. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct FactDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingRef, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChannelDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) reach: ReachRef, + pub(crate) controller: Option>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(crate) enum Declaration { + Subject(SubjectDeclaration), + /// Places and resources only. `Fact` and `Channel` carry a payload and have + /// their own declarations, so a referenceable empty one is unrepresentable. + Entity(EntityDeclaration), + Route(RouteDeclaration), + Affordance(AffordanceDeclaration), + Fact(FactDeclaration), + Channel(ChannelDeclaration), +} + +/// The operations that change a component of an already canonical structure. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ComponentOp { + Relocate { + subject: Ref, + via: Ref, + }, + OpenRoute { + route: Ref, + }, + CloseRoute { + route: Ref, + }, + AlterCost { + route: Ref, + cost: Cost, + }, + Transfer { + from: Ref, + to: Ref, + resource: Ref, + qty: Quantity, + }, + /// One-for-one relabel: the same `qty` leaves `from_resource` and arrives in + /// `into_resource`, held by the same subject. A ratio would be a recipe, and + /// recipes belong to the consumer that owns production; the op shape makes a + /// non-conserving transform unrepresentable rather than merely checkable. A + /// world that needs lossy conversion writes `Transform` plus `Consume`, and + /// both terms then appear in the ledger. + Transform { + holder: Ref, + from_resource: Ref, + into_resource: Ref, + qty: Quantity, + }, + Consume { + holder: Ref, + resource: Ref, + qty: Quantity, + }, + /// The only creation path for quantity, in every lane including genesis. Its + /// `evidence` must appear in the same patch's `evidence` list, which makes + /// creation attributable; the commit chain then makes it tamper-evident. + Admit { + holder: Ref, + resource: Ref, + qty: Quantity, + evidence: EvidenceRef, + }, + /// Creates quantity with no receipt. Only `Play` may write it; every other + /// author creates quantity through `Admit` and its evidence. + Mint { + holder: Ref, + resource: Ref, + qty: Quantity, + }, + Bind { + subject: Ref, + target: DependencyRef, + }, + Release { + subject: Ref, + target: DependencyRef, + }, + /// Adds one grant. An identical grant is `NoOperationEffect`; one that + /// overlaps another the holder already has is `OverlappingJurisdiction`. + GrantAuthority { + holder: Ref, + grant: AuthorityGrantRef, + }, + RevokeAuthority { + holder: Ref, + grant: AuthorityGrantRef, + }, + /// Creates or reconstitutes an office, preserving any sitting incumbent. + /// Clipping an office's powers under a sitting incumbent is a political + /// act, and this is how it is written. + OpenOffice { + institution: Ref, + office: OfficeName, + delegated: BTreeSet, + }, + CloseOffice { + institution: Ref, + office: OfficeName, + }, + InstallIncumbent { + institution: Ref, + office: OfficeName, + incumbent: Ref, + }, + VacateOffice { + institution: Ref, + office: OfficeName, + }, + OpenForum { + grievance: GrievanceKindName, + forum: Ref, + standing: AuthorityTargetRef, + }, + CloseForum { + grievance: GrievanceKindName, + }, + /// Source is authored: `Witnessed` by an author or an affordance, + /// `Evidenced` only over a `Canonical` fact. + AcquireKnowledge { + subject: Ref, + fact: Ref, + source: AuthoredSource, + confidence: Confidence, + }, + /// One telling. It stores the audience, never the recipients: the fan-out is + /// re-derived at apply from live `positions` and `channels`. + Communicate { + speaker: Ref, + fact: Ref, + to: AudienceRef, + }, + /// One witnessed event over a place subtree: a beacon, a bell, a blast, an + /// asteroid. It names no speaker, because the row it lands is + /// `KnowledgeSource::Witnessed` — there is no teller to forge and none is + /// implied. It stores the place, never the recipients: the subtree is + /// re-derived at apply from live `positions`. Everyone already holding the + /// fact is untouched, and a witness that reaches nobody is refused. + Witness { + fact: Ref, + place: Ref, + confidence: Confidence, + }, + Forget { + subject: Ref, + fact: Ref, + }, + SetReach { + channel: Ref, + reach: ReachRef, + }, + SetController { + channel: Ref, + controller: Option>, + }, + /// Two identical creations are two commitments, not `NoOperationEffect`: + /// the key is command-derived so they cannot collide, and two promises of + /// the same thing to the same counterparty are two promises. This is where + /// a commitment differs from a grant, a holding, and a dependency, all of + /// which are set-shaped. + CreateCommitment { + subject: Ref, + counterparty: Option>, + kind: CommitmentKind, + due: FictionalMinutes, + period: Option, + checks: Vec, + statement: Statement, + }, + /// Removes the commitment and every pressure row sourced by it. Fulfilment, + /// default, and release are one write: the kernel never learns who invoked + /// an operation, so three names would be three spellings of one removal + /// with a distinction only a consumer can read. + DischargeCommitment { + subject: Ref, + key: CommitmentKey, + }, + /// Insert-or-add, saturating. With absence meaning zero, creation and + /// advance are the same write. + AdvancePressure { + source: PressureSourceRef, + target: Ref, + by: PressureMagnitude, + }, + /// Saturating subtract; removal at zero. + ReducePressure { + source: PressureSourceRef, + target: Ref, + by: PressureMagnitude, + }, + ResolvePressure { + source: PressureSourceRef, + target: Ref, + }, + /// Ends a subject for good: no grants, no position, no audience, its + /// history kept. Play's alone, like every post-genesis patch. + Retire { + subject: Ref, + }, + /// Grants one more standing catalog entry to an existing subject. Play's + /// alone. + GrantAffordance { + subject: Ref, + affordance: Ref, + }, + /// Revokes a grant. A subject left with no verb holds no grant row and + /// simply cannot act. + RevokeAffordance { + subject: Ref, + affordance: Ref, + }, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct WorldPatch { + pub(crate) declarations: Vec, + pub(crate) operations: Vec, + pub(crate) evidence: Vec, +} + +/// The one byte bound on a `WorldPatch` frame from any external source, and +/// the three item bounds on a `WorldPatch` as a value. One owner, two +/// consumers: the consumer ingress decodes against them through +/// `decode_patch`, and `check_patch_caps` applies the same three item caps to +/// an assembled value before submission. +pub(crate) const MAX_PATCH_BYTES: usize = 256 * 1024; +pub(crate) const MAX_PATCH_DECLARATIONS: usize = 64; +pub(crate) const MAX_PATCH_OPERATIONS: usize = 128; +pub(crate) const MAX_PATCH_EVIDENCE: usize = 64; + +/// Why a patch was refused before the resolver ever saw it. Not a second +/// structural vocabulary: nothing here reads world state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PatchDecodeError { + TooLarge { bytes: usize }, + NotCanonical, + Malformed, + TooManyDeclarations { count: usize }, + TooManyOperations { count: usize }, + TooManyEvidence { count: usize }, +} + +/// The one decode owner for a `WorldPatch` from a byte source. The byte cap is +/// applied to the frame before `rmp_serde` sees it, so no item is deserialized +/// out of a frame the world would not accept; the item caps are checked on the +/// decoded value before `resolve_patch`, which is the first thing that costs +/// `state ∪ patch`. +pub(crate) fn decode_patch(bytes: &[u8]) -> Result { + if bytes.len() > MAX_PATCH_BYTES { + return Err(PatchDecodeError::TooLarge { bytes: bytes.len() }); + } + let patch: WorldPatch = + rmp_serde::from_slice(bytes).map_err(|_| PatchDecodeError::Malformed)?; + // The canonical round-trip the journal and the presence route already + // require, so one frame has one encoding. + if rmp_serde::to_vec_named(&patch).map_err(|_| PatchDecodeError::Malformed)? != bytes { + return Err(PatchDecodeError::NotCanonical); + } + check_patch_caps(&patch)?; + Ok(patch) +} + +/// The same three item caps against an in-memory draft, for the lane that +/// builds rather than decodes. +pub(crate) fn check_patch_caps(patch: &WorldPatch) -> Result<(), PatchDecodeError> { + if patch.declarations.len() > MAX_PATCH_DECLARATIONS { + return Err(PatchDecodeError::TooManyDeclarations { + count: patch.declarations.len(), + }); + } + if patch.operations.len() > MAX_PATCH_OPERATIONS { + return Err(PatchDecodeError::TooManyOperations { + count: patch.operations.len(), + }); + } + if patch.evidence.len() > MAX_PATCH_EVIDENCE { + return Err(PatchDecodeError::TooManyEvidence { + count: patch.evidence.len(), + }); + } + Ok(()) +} + +/// One named structural check that a patch failed. A rejection carries the +/// complete set, never the first failure. It never enters `WorldState`, +/// `WorldEffect`, `CommandEnvelope`, or `WorldCommit`; the serde derives exist +/// for telemetry readers outside the kernel, under their own row type and +/// schema. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "mismatch", rename_all = "snake_case")] +pub enum Mismatch { + EmptyHandle { + position: usize, + }, + DuplicateHandle { + handle: DraftHandle, + }, + EmptyLabel { + handle: DraftHandle, + }, + /// The world is bound to a grammar and this affordance's kind is not one of + /// its verbs. + AffordanceKindNotInGrammar { + handle: DraftHandle, + }, + /// The kind is a verb of the bound grammar, but the declared roles are not + /// its signature (name, referent kind or order). + AffordanceRolesDisagreeWithGrammar { + handle: DraftHandle, + }, + /// The grammar binds the kernel's speak verb as anything but a Conversation. + SpeakRenderPathDisagreesWithGrammar { + handle: DraftHandle, + }, + /// An import key is empty, has whitespace, or is longer than 200 bytes in + /// either part. + MalformedImportKey { + handle: DraftHandle, + }, + /// Two subjects in one patch declare the same import key. + DuplicateImportKey { + handle: DraftHandle, + }, + /// A subject already in the world, retired or not, holds this import key. + ImportKeyHeld { + handle: DraftHandle, + }, + UnresolvedDraft { + site: Site, + referent: DraftHandle, + expected: RefKind, + }, + WrongKind { + site: Site, + referent: RefName, + expected: RefKind, + actual: RefKind, + }, + UnknownCanonical { + site: Site, + expected: RefKind, + }, + EmptyEvidence { + position: usize, + }, + CanonicalCollision { + handle: DraftHandle, + }, + NoCanonicalChange, + /// A genesis-lane resolution (the same empty-state case `is_genesis` + /// tests) declared no subject, so the world would have nobody to act. This + /// is a rejected patch, not a corrupt journal: the kernel must survive it. + NoDecisionSubject, + /// A declared place contains itself through its container chain. + ContainmentCycle { + referent: DraftHandle, + }, + RouteSelfLoop { + referent: DraftHandle, + }, + InvalidCost { + site: Site, + }, + SubjectNotAtOrigin { + operation: usize, + }, + RouteClosed { + operation: usize, + }, + RouteAccessRestricted { + operation: usize, + }, + UnplacedSubject { + operation: usize, + }, + /// An operation that changes nothing is not a canonical change. + NoOperationEffect { + operation: usize, + }, + /// The holder does not hold enough. Absence is zero, so "holds none at all" + /// is this variant at the boundary rather than a second name. + InsufficientCustody { + operation: usize, + }, + /// A custody operation naming `Quantity(0)`: it moves nothing. + ZeroQuantity { + operation: usize, + }, + /// A credit that would leave a holding above `u64::MAX`. + QuantityOverflow { + operation: usize, + }, + /// An `Admit` whose `EvidenceRef` is not listed in this patch's `evidence`. + AdmitWithoutEvidence { + operation: usize, + }, + /// A `Bind` or `Release` naming the acting subject as its own target. + SelfDependency { + operation: usize, + }, + /// The candidate ledger does not balance for this resource: the total after + /// the patch is not the total before plus what was admitted and gained, less + /// what was consumed and spent. + CustodyNotConserved { + resource: RefName, + }, + /// `kind` is not `[a-z][a-z0-9_]{0,47}`, or a `Role` is not + /// `[a-z][a-z0-9_]{0,31}`. Tool and parameter names must be safe. + InvalidAffordanceName { + handle: DraftHandle, + }, + /// Two entries in the candidate graph share one kind name; the generated + /// tool catalog would have two tools with one name. + DuplicateAffordanceKind { + handle: DraftHandle, + }, + DuplicateRole { + handle: DraftHandle, + role: Role, + }, + /// A precondition or a slot names a role the entry does not declare. + UnknownRole { + handle: DraftHandle, + role: Role, + }, + /// A declared role's `RefKind` cannot serve the position that reads it, or + /// names a namespace no invocation target can bind. + RoleKindUnfit { + handle: DraftHandle, + role: Role, + }, + SlotRoleArity { + handle: DraftHandle, + slot: usize, + }, + /// The slot's `Bounds` variant does not match its `op_kind`'s dimension, or + /// the ceiling is zero, or a cost ceiling is outside `1..=MAX_ROUTE_COST`. + SlotBoundMismatch { + handle: DraftHandle, + slot: usize, + }, + NoOutcomeBand { + handle: DraftHandle, + }, + ZeroBandWeight { + handle: DraftHandle, + band: usize, + }, + /// A band names a slot index the entry does not have. + DanglingBandEffect { + handle: DraftHandle, + band: usize, + }, + /// A band's `effects` are not strictly increasing. + BandEffectsNotCanonical { + handle: DraftHandle, + band: usize, + }, + /// No effect slots and no speech: the entry can never change anything. + InertAffordance { + handle: DraftHandle, + }, + /// An `OfficeName`, `AuthorityKindName`, or `GrievanceKindName` that is not + /// `[a-z][a-z0-9_]{0,47}`. + InvalidCivicName { + site: Site, + }, + /// `OpenOffice` lending no authority kind. + EmptyDelegation { + operation: usize, + }, + /// The institution named by an office operation is not + /// `SubjectKind::Institution`. + OfficeOnNonInstitution { + operation: usize, + }, + /// An incumbent that is not `SubjectKind::Person`. This is the check that + /// keeps an institution's operational organ and its person-shaped voice two + /// subjects joined by an office. + OfficeHolderNotPerson { + operation: usize, + }, + /// This person already occupies another office of this institution. + DuplicateIncumbency { + operation: usize, + }, + /// `InstallIncumbent`, `VacateOffice`, or `CloseOffice` naming an office the + /// institution does not have. + UnknownOffice { + operation: usize, + }, + /// `CloseForum` naming a grievance no forum takes. + UnknownForum { + operation: usize, + }, + /// One subject would hold two grants of the same kind over overlapping + /// targets, from any combination of direct grant and office delegation. + /// Overlap between *different* subjects is layered government and legal: + /// `Authorized` is a permission predicate, not an exclusivity claim, and + /// this rule exists so nothing ever has to arbitrate between two sources. + OverlappingJurisdiction { + operation: usize, + }, + /// A catalog entry declares a role named `actor`, which the kernel binds. + ReservedRole { + handle: DraftHandle, + }, + /// An `EntityDeclaration` naming `Fact` or `Channel`. Those kinds carry a + /// payload and have their own declaration; a payload-less one would make a + /// referenceable, empty fact a legal state. + PayloadEntityKind { + handle: DraftHandle, + }, + /// A `Canonical` fact declaration whose `EvidenceRef` is not listed in this + /// patch's `evidence`. + FactWithoutEvidence { + handle: DraftHandle, + }, + EmptyStatement { + handle: DraftHandle, + }, + /// A commitment statement that is empty, padded, or spans lines. + NoncanonicalText { + operation: usize, + }, + /// `AcquireKnowledge { source: Evidenced }` over a `Claimed` fact. + EvidencedKnowledgeOfClaim { + operation: usize, + }, + /// A `Communicate` whose speaker is neither inside the audience nor the + /// channel's controller. + SpeakerOutsideAudience { + operation: usize, + }, + /// A catalog entry with `carries_speech` and no `CanBroadcast` or + /// `CanReach`: its speech would have no audience to lower. + SpeechWithoutAudience { + handle: DraftHandle, + }, + /// More than one, so the lowering could not choose. + AmbiguousSpeechAudience { + handle: DraftHandle, + }, + /// A `Routine` with no period, or a non-`Routine` with one. + CommitmentPeriodMismatch { + operation: usize, + }, + /// A non-`Routine` carrying checks. Nothing would ever evaluate them. + ChecksOnNonRoutine { + operation: usize, + }, + /// `due <= now` at creation. A promise cannot be born past due; it would + /// press on its subject on the very next tick with no chance to act. + CommitmentDueInThePast { + operation: usize, + }, + /// `counterparty == subject`. + SelfCommitment { + operation: usize, + }, + /// A goal is a promise to oneself, and a promise to another is an + /// obligation. This keeps the scale count's `Goal` clause meaning one thing. + GoalWithCounterparty { + operation: usize, + }, + /// `DischargeCommitment` naming a key the subject does not hold. + UnknownCommitment { + operation: usize, + }, + /// A `Ruled` fact or a `Mint` was written by a caller other than the play + /// authority. + RuledWithoutAuthority { + site: Site, + }, + /// `Communicate`, `AcquireKnowledge`, `Forget`, or `InstallIncumbent` + /// named a retired subject as the one acting, learning, forgetting, or + /// taking office. A retired subject is a body, not an actor: it may still + /// be a holdings source (looted), a channel member, or a route endpoint, + /// but it cannot be the one who speaks, knows, or holds office. + RetiredSubjectActed { + operation: usize, + }, + /// `GrantAffordance` or `RevokeAffordance` named a retired subject: it + /// holds no grant this patch may touch. + GrantsToRetired { + operation: usize, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct EntityRecord { + pub(super) label: String, + pub(super) kind: EntityKind, + /// `Some` only for `EntityKind::Place`, and only ever a place. + pub(super) container: Option, +} + +/// One variant per edge kind that has a shape, so no record carries fields that +/// are meaningless for its discriminator. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(super) enum EdgeRecord { + Route { + label: String, + from: EntityId, + to: EntityId, + access: AccessKind, + cost: Cost, + open: bool, + }, +} + +impl EdgeRecord { + pub(super) fn endpoints(&self) -> (EntityId, EntityId) { + match self { + Self::Route { from, to, .. } => (*from, *to), + } + } + + pub(super) fn label(&self) -> &str { + match self { + Self::Route { label, .. } => label, + } + } + + pub(super) fn cost(&self) -> Cost { + match self { + Self::Route { cost, .. } => *cost, + } + } + + pub(super) fn access(&self) -> &AccessKind { + match self { + Self::Route { access, .. } => access, + } + } + + pub(super) fn is_open(&self) -> bool { + match self { + Self::Route { open, .. } => *open, + } + } + + pub(super) fn set_open(&mut self, value: bool) { + match self { + Self::Route { open, .. } => *open = value, + } + } + + pub(super) fn set_cost(&mut self, value: Cost) { + match self { + Self::Route { cost, .. } => *cost = value, + } + } +} + +/// The handle-to-ID binding table for one subject. The handle is commit-scoped +/// provenance; it never enters `WorldState`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedSubject { + pub(super) handle: DraftHandle, + pub(super) subject_id: SubjectId, + pub(super) subject: SubjectState, + pub(super) affordances: BTreeSet, + pub(super) position: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedEntity { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, +} + +/// The handle-to-ID binding for one catalog entry. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedAffordance { + pub(super) handle: DraftHandle, + pub(super) affordance_id: AffordanceId, + pub(super) affordance: Affordance, +} + +/// A declared fact: one `entities` row and one `facts` row, allocated together +/// so the bijection has one writer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedFact { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, + pub(super) fact: FactRecord, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedChannel { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, + pub(super) channel: ChannelRecord, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedRoute { + pub(super) handle: DraftHandle, + pub(super) edge_id: EdgeId, + pub(super) edge: EdgeRecord, +} + +/// A lowered operation. `Relocate` carries no endpoints: they are read from the +/// route at apply time, so a forged effect cannot assert a destination the route +/// does not have. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ResolvedOp { + Relocate { + subject_id: SubjectId, + edge_id: EdgeId, + }, + OpenRoute { + edge_id: EdgeId, + }, + CloseRoute { + edge_id: EdgeId, + }, + AlterCost { + edge_id: EdgeId, + cost: Cost, + }, + Transfer { + from: SubjectId, + to: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Transform { + holder: SubjectId, + from_resource: EntityId, + into_resource: EntityId, + qty: Quantity, + }, + Consume { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Admit { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + evidence: EvidenceRef, + }, + Mint { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Bind { + subject: SubjectId, + target: DependencyTarget, + }, + Release { + subject: SubjectId, + target: DependencyTarget, + }, + GrantAuthority { + holder: SubjectId, + grant: AuthorityGrant, + }, + RevokeAuthority { + holder: SubjectId, + grant: AuthorityGrant, + }, + OpenOffice { + institution: SubjectId, + office: OfficeName, + delegated: BTreeSet, + }, + CloseOffice { + institution: SubjectId, + office: OfficeName, + }, + InstallIncumbent { + institution: SubjectId, + office: OfficeName, + incumbent: SubjectId, + }, + VacateOffice { + institution: SubjectId, + office: OfficeName, + }, + OpenForum { + grievance: GrievanceKindName, + forum: SubjectId, + standing: AuthorityTarget, + }, + CloseForum { + grievance: GrievanceKindName, + }, + AcquireKnowledge { + subject: SubjectId, + fact: EntityId, + source: AuthoredSource, + confidence: Confidence, + }, + /// Stores the audience, never the recipients. `apply_operation` re-derives + /// the fan-out from live `positions`/`channels`, exactly as `Relocate` + /// stores `edge_id` and re-derives the destination, so a forged effect + /// cannot assert a landing the world does not have. + Communicate { + speaker: SubjectId, + fact: EntityId, + to: Audience, + }, + /// A visible act: the actor's own sentence, seen by everyone standing in + /// the actor's place. Lowered only by the kernel's speech path beside + /// `AssertClaim`, never by a patch, so no author can move a + /// person's body from outside the person. There is no audience field: a + /// display cannot go down a channel, and the room is re-derived from live + /// `positions` at apply, so a forged effect cannot assert a landing the + /// world does not have. + Display { + actor: SubjectId, + fact: EntityId, + }, + /// Stores the place, never the recipients. `apply_operation` re-derives the + /// subtree from live `positions`, so a forged effect cannot assert a + /// landing the world does not have. There is no speaker field, so this + /// operation cannot write `KnowledgeSource::Told` however it is forged. + Witness { + fact: EntityId, + place: EntityId, + confidence: Confidence, + }, + Forget { + subject: SubjectId, + fact: EntityId, + }, + SetReach { + channel: EntityId, + reach: Reach, + }, + SetController { + channel: EntityId, + controller: Option, + }, + /// Kernel-only: no [`ComponentOp`] twin, because no proposer may author one. + /// Synthesized by `action::exercise` for a speech-carrying invocation and by + /// nothing else. Inserts the entity row and the `facts` row; it writes no + /// knowledge, because a speaker's own knowledge of its claim is not implied. + AssertClaim { + fact: EntityId, + statement: Statement, + by: SubjectId, + }, + CreateCommitment { + subject: SubjectId, + key: CommitmentKey, + commitment: Commitment, + }, + DischargeCommitment { + subject: SubjectId, + key: CommitmentKey, + }, + AdvancePressure { + source: PressureSource, + target: SubjectId, + by: PressureMagnitude, + }, + ReducePressure { + source: PressureSource, + target: SubjectId, + by: PressureMagnitude, + }, + ResolvePressure { + source: PressureSource, + target: SubjectId, + }, + Retire { + subject: SubjectId, + }, + GrantAffordance { + subject: SubjectId, + affordance: AffordanceId, + }, + RevokeAffordance { + subject: SubjectId, + affordance: AffordanceId, + }, +} + +/// One resource's movement across a whole patch. Accumulators are `u128` so an +/// intermediate total cannot overflow while a stored per-holder `Quantity` stays +/// `u64`. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub(super) struct LedgerDelta { + pub(super) before: u128, + pub(super) after: u128, + pub(super) admitted: u128, + pub(super) consumed: u128, + pub(super) gained: u128, + pub(super) spent: u128, +} + +/// The only statement of custody conservation, called by the resolver over the +/// candidate map and again by `admit_resolved` over the committed partitions. +/// Returns the first resource whose ledger does not balance, in key order, so +/// the verdict is deterministic. +/// +/// `Transfer` contributes to no term: its correctness is *proven by* this +/// equation, because a transfer that moved a different amount out than in breaks +/// the total for that resource. `Transform` contributes the same `qty` to one +/// `spent` and one `gained`, so the one-for-one rule is this equation restricted +/// to a single operation. Nothing else states conservation anywhere. +pub(super) fn check_ledger(deltas: &BTreeMap) -> Option { + deltas + .iter() + .find(|(_, delta)| { + let credited = delta + .before + .checked_add(delta.admitted) + .and_then(|total| total.checked_add(delta.gained)); + let expected = credited + .and_then(|total| total.checked_sub(delta.consumed)) + .and_then(|total| total.checked_sub(delta.spent)); + expected != Some(delta.after) + }) + .map(|(resource, _)| resource.clone()) +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedPatch { + pub(super) subjects: Vec, + pub(super) entities: Vec, + pub(super) routes: Vec, + pub(super) affordances: Vec, + pub(super) facts: Vec, + pub(super) channels: Vec, + pub(super) operations: Vec, + pub(super) evidence: Vec, +} + +impl ResolvedPatch { + pub(super) fn declares_nothing(&self) -> bool { + self.subjects.is_empty() + && self.entities.is_empty() + && self.routes.is_empty() + && self.affordances.is_empty() + && self.facts.is_empty() + && self.channels.is_empty() + && self.evidence.is_empty() + } +} + +const SUBJECT_NAMESPACE: &str = "ghostlight.id.subject.v1"; +pub(super) const ENTITY_NAMESPACE: &str = "ghostlight.id.entity.v1"; +const EDGE_NAMESPACE: &str = "ghostlight.id.edge.v1"; +const AFFORDANCE_NAMESPACE: &str = "ghostlight.id.affordance.v1"; + +const PLACE: RefKind = RefKind::Entity(EntityKind::Place); +const FACT: RefKind = RefKind::Entity(EntityKind::Fact); +const CHANNEL: RefKind = RefKind::Entity(EntityKind::Channel); +const ROUTE: RefKind = RefKind::Edge(EdgeKind::Route); +const ANY_SUBJECT: RefKind = RefKind::Subject(None); + +/// A candidate-graph key: a structure this patch declares, or one the world +/// already holds. Candidate topology is checked before any ID is minted, so it +/// is keyed by reference rather than by canonical ID. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Key { + Existing(Id), + Draft(DraftHandle), +} + +fn key_of(reference: &Ref) -> Key { + match reference { + Ref::Existing(id) => Key::Existing(*id), + Ref::Draft(handle) => Key::Draft(handle.clone()), + } +} + +/// [`DependencyTarget`] over candidate keys, so a dependency on a structure this +/// patch declares is checked before any ID is minted. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum TargetKey { + Resource(Key), + Route(Key), + Subject(Key), +} + +/// [`PressureSource`] over candidate keys. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum PressureSourceKey { + Commitment { + subject: Key, + key: CommitmentKey, + }, + Dependency(TargetKey), + Subject(Key), +} + +/// [`AuthorityTarget`] over candidate keys, so a grant over a place this patch +/// declares is checked before any ID is minted. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum AuthorityTargetKey { + Subject(Key), + PlaceSubtree(Key), +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct GrantKey { + kind: AuthorityKindName, + over: AuthorityTargetKey, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct OfficeCandidate { + incumbent: Option>, + delegated: BTreeSet, +} + +/// Whether a candidate `Subject` grant target and a candidate `PlaceSubtree` +/// grant target of one kind name overlapping ground: a `PlaceSubtree` grant +/// covers a `Subject` grant's target when the subject's committed position +/// sits under that subtree. Checked live against `state` rather than the +/// candidate graph, because `covers` reads committed position and +/// containment, not anything a patch declares; a target still in this +/// patch's drafts has no committed position and so cannot overlap here. This +/// is the one cross-shape case `Candidate::targets_overlap` leaves alone by +/// construction — same-shape overlap is its job, not this one's. +fn grant_targets_nest( + state: &super::WorldState, + left: &AuthorityTargetKey, + right: &AuthorityTargetKey, +) -> bool { + let place_and_subject = |a: &AuthorityTargetKey, b: &AuthorityTargetKey| match (a, b) { + ( + AuthorityTargetKey::PlaceSubtree(Key::Existing(place)), + AuthorityTargetKey::Subject(Key::Existing(subject_id)), + ) => Some((*place, *subject_id)), + _ => None, + }; + place_and_subject(left, right) + .or_else(|| place_and_subject(right, left)) + .is_some_and(|(place, subject_id)| { + super::covers( + state, + AuthorityTarget::PlaceSubtree(place), + super::Target::Subject(subject_id), + ) + }) +} + +fn target_key_of(target: AuthorityTarget) -> AuthorityTargetKey { + match target { + AuthorityTarget::Subject(subject_id) => { + AuthorityTargetKey::Subject(Key::Existing(subject_id)) + } + AuthorityTarget::PlaceSubtree(entity_id) => { + AuthorityTargetKey::PlaceSubtree(Key::Existing(entity_id)) + } + } +} + +fn grant_key_of(grant: &AuthorityGrant) -> GrantKey { + GrantKey { + kind: grant.kind.clone(), + over: target_key_of(grant.over), + } +} + +/// The candidate authority of one subject, projected to the canonical referents +/// [`covers`](super::covers) reads. A grant naming structure this patch declares +/// cannot cover a place an already-canonical route reaches, so the projection +/// loses nothing the `Restricted` rule asks about. +fn canonical_grants(grants: &BTreeSet) -> BTreeSet { + grants + .iter() + .filter_map(|grant| { + let over = match &grant.over { + AuthorityTargetKey::Subject(Key::Existing(subject_id)) => { + AuthorityTarget::Subject(*subject_id) + } + AuthorityTargetKey::PlaceSubtree(Key::Existing(entity_id)) => { + AuthorityTarget::PlaceSubtree(*entity_id) + } + _ => return None, + }; + Some(AuthorityGrant { + kind: grant.kind.clone(), + over, + }) + }) + .collect() +} + +/// A fact in the candidate graph. Only its standing matters to resolution: the +/// statement is never read and never compared. +#[derive(Clone, Debug, PartialEq, Eq)] +enum FactCandidate { + Canonical, + Claimed(Key), + Ruled, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum ReachKey { + Subjects(BTreeSet>), + Place(Key), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct ChannelCandidate { + reach: ReachKey, + controller: Option>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum KnowledgeSourceKey { + Witnessed, + Told { + by: Key, + via: Option>, + }, + Seen { + by: Key, + }, + Evidenced, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct KnowledgeCandidate { + confidence: Confidence, + source: KnowledgeSourceKey, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum AudienceKey { + Colocated, + Channel(Key), +} + +#[derive(Clone, Debug)] +struct RouteCandidate { + from: Key, + to: Key, + access: AccessKind, + cost: Cost, + open: bool, +} + +/// The only canonical ID allocator, called from exactly two sites: +/// [`resolve_patch`] and `action::exercise`. Deterministic on purpose: journal +/// replay recomputes `reduce` and requires effect equality, so a reduce arm can +/// never draw a `Uuid::new_v4`. Preimage fields are length-prefixed where they +/// are variable-width, so the concatenation is unambiguous — `discriminator` +/// included: a bare presence byte followed by a length prefix means +/// `Some("")` and `None` write different bytes, where an unprefixed +/// `Some("")` would have written nothing, same as `None`. +pub(super) fn derive_id( + namespace: &str, + world_id: WorldId, + command_id: CommandId, + handle: &DraftHandle, + discriminator: Option<&str>, +) -> Uuid { + let mut hasher = Sha256::new(); + hasher.update(namespace.as_bytes()); + hasher.update(world_id.0.as_bytes()); + hasher.update(command_id.0.as_bytes()); + hasher.update((handle.0.len() as u64).to_be_bytes()); + hasher.update(handle.0.as_bytes()); + match discriminator { + Some(discriminator) => { + hasher.update([1u8]); + hasher.update((discriminator.len() as u64).to_be_bytes()); + hasher.update(discriminator.as_bytes()); + } + None => hasher.update([0u8]), + } + let mut bytes = [0u8; 16]; + bytes.copy_from_slice(&hasher.finalize()[..16]); + Uuid::from_bytes(bytes) +} + +pub(super) fn is_canonical_text(value: &str) -> bool { + !value.trim().is_empty() && value.trim() == value +} + +pub(super) fn is_valid_cost(cost: Cost) -> bool { + (1..=MAX_ROUTE_COST).contains(&cost.0) +} + +/// The one role name the kernel owns. A catalog entry may not declare it and an +/// invocation may not bind it: stage 2 binds it to the acting subject, so a slot +/// that must land on the actor — the payee of a levy, say — says so instead of +/// letting the proposer point it at a friend. +pub(super) const ACTOR_ROLE: &str = "actor"; + +/// Authority kinds, office names, and grievance kinds share the affordance +/// alphabet: world-declared, kernel-opaque, and safe to surface in a generated +/// tool description. +pub(super) fn is_civic_name(value: &str) -> bool { + is_tool_name(value, 48) +} + +/// `[a-z][a-z0-9_]{0,max-1}`. Affordance kinds and roles become generated tool +/// and parameter names, so the alphabet is the safe one and the bound is stated +/// rather than assumed. +fn is_tool_name(value: &str, max: usize) -> bool { + let mut characters = value.chars(); + characters + .next() + .is_some_and(|first| first.is_ascii_lowercase()) + && value.len() <= max + && value.chars().all(|character| { + character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_' + }) +} + +/// The handle of the kernel-built Speak entry. It is indexed in the same draft +/// index as world-declared entries, so a genesis subject grants it with an +/// ordinary `Ref::Draft` and there is no second grant path. +pub(super) const KERNEL_SPEAK_HANDLE: &str = "ghostlight.affordance.speak"; + +/// The grant every genesis subject carries: a draft reference to the +/// kernel-built entry, resolved by the ordinary handle index. World ingress and +/// every fixture name this rather than repeating the handle literal. +pub(super) fn kernel_speak_grant() -> BTreeSet> { + BTreeSet::from([Ref::Draft(DraftHandle::new(KERNEL_SPEAK_HANDLE))]) +} + +/// Zero roles, zero slots, one empty band, one utterance, and one audience: a +/// voice fills the room it is standing in. Zero roles is load-bearing — the +/// Interpreter lane submits no bindings and a consumer's speak payload carries +/// only +/// text. The precondition is not vacuous: an unplaced subject has no +/// co-location audience and fails with `NoAudience`. +pub(super) fn kernel_speak_entry() -> Affordance { + Affordance { + kind: AffordanceKindName("speak".into()), + roles: Vec::new(), + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + } +} + +/// Whether a stored catalog entry would still be admitted by the declaration +/// validator. One validator, two readers: the resolver rejects a bad entry, and +/// opening an export refuses a chain that already holds one. +pub(super) fn entry_is_admissible(entry: &Affordance) -> bool { + let mut mismatches = Vec::new(); + validate_affordance( + &DraftHandle::new(""), + &entry.kind, + &entry.roles, + &entry.preconditions, + &entry.effect_slots, + &entry.outcome_bands, + entry.carries_speech, + &mut mismatches, + ); + mismatches.is_empty() +} + +/// The catalog-entry resolver, beside `resolve_entity`/`_subject`/`_route`. An +/// entry carries no components, so there is nothing to check past namespace +/// agreement. +fn resolve_affordance( + site: Site, + reference: &Ref, + index: &BTreeMap, + catalog: &Docs, + mismatches: &mut Vec, +) -> Option> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: RefKind::Affordance, + }); + None + } + Some(kind) if *kind != RefKind::Affordance => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Affordance(reference.clone()), + expected: RefKind::Affordance, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(affordance_id) => { + if catalog.contains_key(affordance_id) { + Some(Key::Existing(*affordance_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: RefKind::Affordance, + }); + None + } + } + } +} + +/// The one validator of a catalog entry, run per declared entry in declaration +/// order inside the resolver's accumulate-then-gate loop. +fn validate_affordance( + handle: &DraftHandle, + kind: &AffordanceKindName, + roles: &[RoleSpec], + preconditions: &[Precondition], + effect_slots: &[EffectSlot], + outcome_bands: &[OutcomeBand], + carries_speech: bool, + mismatches: &mut Vec, +) { + let site = || Site::Declaration(handle.clone()); + if !is_tool_name(&kind.0, 48) || roles.iter().any(|spec| !is_tool_name(&spec.role.0, 32)) { + mismatches.push(Mismatch::InvalidAffordanceName { + handle: handle.clone(), + }); + } + let mut declared: BTreeMap = BTreeMap::new(); + for spec in roles { + if spec.role.0 == ACTOR_ROLE { + mismatches.push(Mismatch::ReservedRole { + handle: handle.clone(), + }); + } + match declared.entry(spec.role.clone()) { + Entry::Vacant(slot) => { + slot.insert(spec.kind); + } + Entry::Occupied(_) => mismatches.push(Mismatch::DuplicateRole { + handle: handle.clone(), + role: spec.role.clone(), + }), + } + // No `Target` names the catalog namespace, so a role of that kind could + // never be bound. + if spec.kind == RefKind::Affordance { + mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: spec.role.clone(), + }); + } + } + // The kernel binds `actor` to the acting subject, so preconditions and + // slots may name it like any role. + declared.insert(Role(ACTOR_ROLE.into()), ANY_SUBJECT); + let require = + |role: &Role, expected: RefKind, mismatches: &mut Vec| match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(actual) if *actual != expected => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }), + Some(_) => {} + }; + let require_subject = |role: &Role, mismatches: &mut Vec| match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(RefKind::Subject(_)) => {} + Some(_) => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }), + }; + let require_audience = |via: &AudienceSpec, mismatches: &mut Vec| match via { + AudienceSpec::Colocated => {} + AudienceSpec::Channel(role) => require(role, CHANNEL, mismatches), + }; + for precondition in preconditions { + match precondition { + Precondition::Present { at } => { + require(at, RefKind::Entity(EntityKind::Place), mismatches); + } + Precondition::Reachable { to, within } => { + require(to, RefKind::Entity(EntityKind::Place), mismatches); + if !is_valid_cost(*within) { + mismatches.push(Mismatch::InvalidCost { site: site() }); + } + } + Precondition::Holds { resource, .. } => { + require(resource, RefKind::Entity(EntityKind::Resource), mismatches); + } + Precondition::Authorized { over, kind } => { + // Jurisdiction runs over subjects, places, and routes. A + // resource, fact, or channel is covered by nothing, so a role + // of that kind is refused at declaration rather than always + // failing at invocation. + match declared.get(over) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: over.clone(), + }), + Some(RefKind::Subject(_)) | Some(&PLACE) | Some(&ROUTE) => {} + Some(_) => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: over.clone(), + }), + } + if !is_civic_name(&kind.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + } + Precondition::HasStanding { grievance } => { + if !is_civic_name(&grievance.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + } + Precondition::Knows { fact, .. } => require(fact, FACT, mismatches), + Precondition::CanBroadcast { via } => require_audience(via, mismatches), + Precondition::CanReach { subject, via } => { + require_subject(subject, mismatches); + require_audience(via, mismatches); + } + Precondition::Committed { to, .. } => require_subject(to, mismatches), + } + } + // A speech-carrying entry must name exactly one audience: the lowering reads + // it, so none is unlowerable and two is unchoosable. + if carries_speech { + let audiences = preconditions + .iter() + .filter(|precondition| { + matches!( + precondition, + Precondition::CanBroadcast { .. } | Precondition::CanReach { .. } + ) + }) + .count(); + if audiences == 0 { + mismatches.push(Mismatch::SpeechWithoutAudience { + handle: handle.clone(), + }); + } else if audiences > 1 { + mismatches.push(Mismatch::AmbiguousSpeechAudience { + handle: handle.clone(), + }); + } + } + for (index, slot) in effect_slots.iter().enumerate() { + let arity = slot.op_kind.arity(); + if slot + .op_kind + .payload_names() + .iter() + .any(|name| !is_civic_name(name)) + { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + if slot.roles.len() != arity.len() { + mismatches.push(Mismatch::SlotRoleArity { + handle: handle.clone(), + slot: index, + }); + } + for (role, rule) in slot.roles.iter().zip(arity.iter()) { + match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(declared_kind) if !role_kind_fits(rule, *declared_kind) => { + mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }); + } + Some(_) => {} + } + } + let fits = match (slot.op_kind.dimension(), slot.bounds) { + (BoundsDimension::None, Bounds::None) => true, + (BoundsDimension::Quantity, Bounds::Quantity(ceiling)) => ceiling.0 >= 1, + (BoundsDimension::Cost, Bounds::Cost(ceiling)) => is_valid_cost(ceiling), + _ => false, + }; + if !fits { + mismatches.push(Mismatch::SlotBoundMismatch { + handle: handle.clone(), + slot: index, + }); + } + } + if outcome_bands.is_empty() { + mismatches.push(Mismatch::NoOutcomeBand { + handle: handle.clone(), + }); + } + for (index, band) in outcome_bands.iter().enumerate() { + if band.weight == 0 { + mismatches.push(Mismatch::ZeroBandWeight { + handle: handle.clone(), + band: index, + }); + } + if band.effects.iter().any(|slot| *slot >= effect_slots.len()) { + mismatches.push(Mismatch::DanglingBandEffect { + handle: handle.clone(), + band: index, + }); + } + if band.effects.windows(2).any(|pair| pair[0] >= pair[1]) { + mismatches.push(Mismatch::BandEffectsNotCanonical { + handle: handle.clone(), + band: index, + }); + } + } + if effect_slots.is_empty() && !carries_speech { + mismatches.push(Mismatch::InertAffordance { + handle: handle.clone(), + }); + } +} + +/// The one entity resolver. `expected` names the kind the referring site +/// requires; a handle or ID that answers with another kind is `WrongKind`. +fn resolve_entity( + site: Site, + expected_kind: EntityKind, + reference: &Ref, + index: &BTreeMap, + entities: &Docs, + mismatches: &mut Vec, +) -> Option> { + let expected = RefKind::Entity(expected_kind); + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected, + }); + None + } + Some(kind) if *kind != expected => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Entity(reference.clone()), + expected, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(entity_id) => match entities.get(entity_id) { + None => { + mismatches.push(Mismatch::UnknownCanonical { site, expected }); + None + } + Some(record) if record.kind != expected_kind => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Entity(reference.clone()), + expected, + actual: RefKind::Entity(record.kind), + }); + None + } + Some(_) => Some(Key::Existing(*entity_id)), + }, + } +} + +fn resolve_subject( + site: Site, + reference: &Ref, + index: &BTreeMap, + subjects: &Docs, + mismatches: &mut Vec, +) -> Option> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: ANY_SUBJECT, + }); + None + } + Some(RefKind::Subject(_)) => Some(Key::Draft(named.clone())), + Some(kind) => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Subject(reference.clone()), + expected: ANY_SUBJECT, + actual: *kind, + }); + None + } + }, + Ref::Existing(subject_id) => { + if subjects.contains_key(subject_id) { + Some(Key::Existing(*subject_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: ANY_SUBJECT, + }); + None + } + } + } +} + +fn resolve_route( + site: Site, + reference: &Ref, + index: &BTreeMap, + edges: &Docs, + mismatches: &mut Vec, +) -> Option> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: ROUTE, + }); + None + } + Some(kind) if *kind != ROUTE => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Edge(reference.clone()), + expected: ROUTE, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(edge_id) => { + if edges.contains_key(edge_id) { + Some(Key::Existing(*edge_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: ROUTE, + }); + None + } + } + } +} + +fn resolve_dependency_target( + site: Site, + target: &DependencyRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match target { + DependencyRef::Resource(reference) => resolve_entity( + site, + EntityKind::Resource, + reference, + index, + &state.entities, + mismatches, + ) + .map(TargetKey::Resource), + DependencyRef::Route(reference) => { + resolve_route(site, reference, index, &state.edges, mismatches).map(TargetKey::Route) + } + DependencyRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(TargetKey::Subject) + } + } +} + +/// The candidate kind of a subject reference: the declared kind for a handle +/// this patch introduces, the committed kind otherwise. +fn subject_kind_of( + key: &Key, + index: &BTreeMap, + state: &super::WorldState, +) -> Option { + match key { + Key::Existing(subject_id) => state.subjects.get(subject_id).map(|subject| subject.kind), + Key::Draft(handle) => match index.get(handle) { + Some(RefKind::Subject(kind)) => *kind, + _ => None, + }, + } +} + +/// The institution half of every office operation: one subject reference, one +/// canonical office name, and the kind check that keeps an institution's +/// operational organ and its person-shaped voice two subjects. +fn resolve_office_institution( + position: usize, + institution: &Ref, + office: &OfficeName, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option> { + let named = is_civic_name(&office.0); + if !named { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let key = resolve_subject( + Site::Operation(position), + institution, + index, + &state.subjects, + mismatches, + )?; + if subject_kind_of(&key, index, state) != Some(SubjectKind::Institution) { + mismatches.push(Mismatch::OfficeOnNonInstitution { + operation: position, + }); + return None; + } + named.then_some(key) +} + +/// The one reach resolver: every member of a subject set, or one place. +fn resolve_reach( + site: Site, + reach: &ReachRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match reach { + ReachRef::Subjects(members) => { + let mut resolved = BTreeSet::new(); + let mut complete = true; + for reference in members { + match resolve_subject(site.clone(), reference, index, &state.subjects, mismatches) { + Some(key) => { + resolved.insert(key); + } + None => complete = false, + } + } + complete.then_some(ReachKey::Subjects(resolved)) + } + ReachRef::Place(reference) => resolve_entity( + site, + EntityKind::Place, + reference, + index, + &state.entities, + mismatches, + ) + .map(ReachKey::Place), + } +} + +/// A channel controller is optional, so "declared none" and "named one that did +/// not resolve" are two answers, not one. +fn resolve_controller( + site: Site, + controller: &Option>, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option>> { + match controller { + None => Some(None), + Some(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches).map(Some) + } + } +} + +fn resolve_audience( + site: Site, + audience: &AudienceRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match audience { + AudienceRef::Colocated => Some(AudienceKey::Colocated), + AudienceRef::Channel(reference) => resolve_entity( + site, + EntityKind::Channel, + reference, + index, + &state.entities, + mismatches, + ) + .map(AudienceKey::Channel), + } +} + +fn resolve_authority_target( + site: Site, + target: &AuthorityTargetRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match target { + AuthorityTargetRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(AuthorityTargetKey::Subject) + } + AuthorityTargetRef::PlaceSubtree(reference) => resolve_entity( + site, + EntityKind::Place, + reference, + index, + &state.entities, + mismatches, + ) + .map(AuthorityTargetKey::PlaceSubtree), + } +} + +/// What a holder holds in the candidate map. Absence is zero, at both levels. +fn candidate_held( + holdings: &Overlay<'_, (Key, Key), Quantity>, + holder: &Key, + resource: &Key, +) -> u64 { + holdings + .get(&(holder.clone(), resource.clone())) + .map_or(0, |quantity| quantity.0) +} + +/// Zero removes the slot, so one representation of nothing survives the patch. +fn candidate_set( + holdings: &mut Overlay<'_, (Key, Key), Quantity>, + holder: &Key, + resource: &Key, + value: u64, +) { + let slot = (holder.clone(), resource.clone()); + if value == 0 { + holdings.remove(&slot); + } else { + holdings.insert(slot, Quantity(value)); + } +} + +/// A bound grammar is the whole catalog: a kind it lacks, or a role signature +/// it does not carry, is refused. A world with no grammar is not checked. +fn check_against_grammar( + state: &super::WorldState, + handle: &DraftHandle, + kind: &AffordanceKindName, + roles: &[RoleSpec], + mismatches: &mut Vec, +) { + let Some(grammar) = &state.header.grammar else { + return; + }; + let handle = handle.clone(); + mismatches.extend(grammar.refusal(kind, roles).map(|refusal| match refusal { + GrammarRefusal::KindNotInGrammar => Mismatch::AffordanceKindNotInGrammar { handle }, + GrammarRefusal::RolesDisagree => Mismatch::AffordanceRolesDisagreeWithGrammar { handle }, + GrammarRefusal::SpeakNotConversation => { + Mismatch::SpeakRenderPathDisagreesWithGrammar { handle } + } + })); +} + +/// The one resolution owner for every admission lane: declarations, references, +/// topology admission, and operation preconditions. Every check runs against the +/// complete candidate graph — what the world already holds plus what this patch +/// declares — and the whole mismatch set closes before the first ID is minted. +pub(super) fn resolve_patch( + state: &super::WorldState, + command_id: CommandId, + patch: &WorldPatch, +) -> Result> { + let world_id = state.header.world_id; + let genesis = super::is_genesis(state.revision, &state.subjects); + let mut mismatches = Vec::new(); + let mut index: BTreeMap = BTreeMap::new(); + + // The kernel-built Speak entry enters the same index as a world-declared + // one, before the declaration loop, so a world reusing its handle collides + // as a duplicate handle rather than through a reserved-name check. + let speak_handle = DraftHandle::new(KERNEL_SPEAK_HANDLE); + if genesis { + index.insert(speak_handle.clone(), RefKind::Affordance); + } + if genesis { + // The kernel-built entry is held to the grammar like any declaration. + let speak = kernel_speak_entry(); + check_against_grammar(state, &speak_handle, &speak.kind, &speak.roles, &mut mismatches); + } + let mut graph = Candidate::new(state); + if genesis { + graph.declare_kind(kernel_speak_entry().kind); + } + + let mut declared_keys: BTreeSet<&ImportKey> = BTreeSet::new(); + for (position, declaration) in patch.declarations.iter().enumerate() { + let (handle, label, kind) = match declaration { + Declaration::Subject(subject) => ( + &subject.handle, + Some(&subject.label), + RefKind::Subject(Some(subject.kind)), + ), + Declaration::Entity(entity) => ( + &entity.handle, + Some(&entity.label), + RefKind::Entity(entity.kind), + ), + Declaration::Route(route) => (&route.handle, Some(&route.label), ROUTE), + // A catalog entry's name is its `kind`, checked by the entry + // validator against the tool-name alphabet rather than against the + // label rule. + Declaration::Affordance(affordance) => (&affordance.handle, None, RefKind::Affordance), + Declaration::Fact(fact) => (&fact.handle, Some(&fact.label), FACT), + Declaration::Channel(channel) => (&channel.handle, Some(&channel.label), CHANNEL), + }; + let named = is_canonical_text(&handle.0); + if !named { + mismatches.push(Mismatch::EmptyHandle { position }); + } + if label.is_some_and(|label| !is_canonical_text(label)) { + mismatches.push(Mismatch::EmptyLabel { + handle: handle.clone(), + }); + } + if named { + match index.entry(handle.clone()) { + Entry::Vacant(slot) => { + slot.insert(kind); + } + Entry::Occupied(_) => mismatches.push(Mismatch::DuplicateHandle { + handle: handle.clone(), + }), + } + } + if let Declaration::Subject(subject) = declaration + && let Some(key) = &subject.import_key + { + let handle = subject.handle.clone(); + match import_key_fault(key, |key| graph.import_key_held(key), &mut declared_keys) { + Some(ImportKeyFault::Malformed) => { + mismatches.push(Mismatch::MalformedImportKey { handle }); + } + Some(ImportKeyFault::Held) => mismatches.push(Mismatch::ImportKeyHeld { handle }), + Some(ImportKeyFault::Duplicate) => { + mismatches.push(Mismatch::DuplicateImportKey { handle }); + } + None => {} + } + } + if let Declaration::Affordance(affordance) = declaration { + validate_affordance( + &affordance.handle, + &affordance.kind, + &affordance.roles, + &affordance.preconditions, + &affordance.effect_slots, + &affordance.outcome_bands, + affordance.carries_speech, + &mut mismatches, + ); + check_against_grammar( + state, + &affordance.handle, + &affordance.kind, + &affordance.roles, + &mut mismatches, + ); + if graph.declare_kind(affordance.kind.clone()) { + mismatches.push(Mismatch::DuplicateAffordanceKind { + handle: affordance.handle.clone(), + }); + } + } + if let Declaration::Entity(entity) = declaration + && matches!(entity.kind, EntityKind::Fact | EntityKind::Channel) + { + mismatches.push(Mismatch::PayloadEntityKind { + handle: handle.clone(), + }); + } + if let Declaration::Fact(fact) = declaration { + if !is_canonical_text(fact.statement.as_str()) { + mismatches.push(Mismatch::EmptyStatement { + handle: handle.clone(), + }); + } + // The same predicate `Admit` uses, moved into the declaration loop so + // one rule serves evidenced quantity and evidenced canon alike. + if let FactStandingRef::Canonical { evidence } = &fact.standing + && !(is_canonical_text(&evidence.0) && patch.evidence.contains(evidence)) + { + mismatches.push(Mismatch::FactWithoutEvidence { + handle: handle.clone(), + }); + } + } + } + + for (position, evidence) in patch.evidence.iter().enumerate() { + if !is_canonical_text(&evidence.0) { + mismatches.push(Mismatch::EmptyEvidence { position }); + } + } + + let mut deltas: BTreeMap, LedgerDelta> = BTreeMap::new(); + let mut declared_places: Vec<(DraftHandle, Key)> = Vec::new(); + + for declaration in &patch.declarations { + match declaration { + Declaration::Entity(entity) => { + if entity.kind == EntityKind::Place { + declared_places + .push((entity.handle.clone(), Key::Draft(entity.handle.clone()))); + } + if let Some(reference) = &entity.container { + if entity.kind != EntityKind::Place { + mismatches.push(Mismatch::WrongKind { + site: Site::Declaration(entity.handle.clone()), + referent: RefName::Entity(reference.clone()), + expected: PLACE, + actual: RefKind::Entity(entity.kind), + }); + } else if let Some(parent) = resolve_entity( + Site::Declaration(entity.handle.clone()), + EntityKind::Place, + reference, + &index, + &state.entities, + &mut mismatches, + ) { + graph.containers.insert(Key::Draft(entity.handle.clone()), parent); + } + } + } + Declaration::Affordance(_) => {} + Declaration::Fact(fact) => { + let standing = match &fact.standing { + FactStandingRef::Canonical { .. } => Some(FactCandidate::Canonical), + FactStandingRef::Claimed { by } => resolve_subject( + Site::Declaration(fact.handle.clone()), + by, + &index, + &state.subjects, + &mut mismatches, + ) + .map(FactCandidate::Claimed), + FactStandingRef::Ruled => Some(FactCandidate::Ruled), + }; + if let Some(standing) = standing { + graph.facts.insert(Key::Draft(fact.handle.clone()), standing); + } + } + Declaration::Channel(channel) => { + let reach = resolve_reach( + Site::Declaration(channel.handle.clone()), + &channel.reach, + &index, + state, + &mut mismatches, + ); + let controller = resolve_controller( + Site::Declaration(channel.handle.clone()), + &channel.controller, + &index, + state, + &mut mismatches, + ); + if let (Some(reach), Some(controller)) = (reach, controller) { + graph.channels.insert( + Key::Draft(channel.handle.clone()), + ChannelCandidate { reach, controller }, + ); + } + } + Declaration::Subject(subject) => { + let mut granted = BTreeSet::new(); + for reference in &subject.affordances { + if let Some(affordance_key) = resolve_affordance( + Site::Declaration(subject.handle.clone()), + reference, + &index, + &state.affordance_catalog, + &mut mismatches, + ) { + granted.insert(affordance_key); + } + } + if !granted.is_empty() { + graph.affordance_holdings.insert(Key::Draft(subject.handle.clone()), granted); + } + if let Some(reference) = &subject.position + && let Some(place) = resolve_entity( + Site::Declaration(subject.handle.clone()), + EntityKind::Place, + reference, + &index, + &state.entities, + &mut mismatches, + ) + { + graph.positions.insert(Key::Draft(subject.handle.clone()), place); + } + } + Declaration::Route(route) => { + let from = resolve_entity( + Site::Declaration(route.handle.clone()), + EntityKind::Place, + &route.from, + &index, + &state.entities, + &mut mismatches, + ); + let to = resolve_entity( + Site::Declaration(route.handle.clone()), + EntityKind::Place, + &route.to, + &index, + &state.entities, + &mut mismatches, + ); + if !is_valid_cost(route.cost) { + mismatches.push(Mismatch::InvalidCost { + site: Site::Declaration(route.handle.clone()), + }); + } + if let (Some(from), Some(to)) = (from, to) { + if from == to { + mismatches.push(Mismatch::RouteSelfLoop { + referent: route.handle.clone(), + }); + } + graph.routes.insert( + Key::Draft(route.handle.clone()), + RouteCandidate { + from, + to, + access: route.access.clone(), + cost: route.cost, + open: true, + }, + ); + } + } + } + } + + // Containment acyclicity. Containment is immutable after admission and + // admission already refused cycles, so every cycle contains a declared + // place; walking from each declared place names them all. + for (handle, start) in &declared_places { + if graph.contains_itself(start) { + mismatches.push(Mismatch::ContainmentCycle { + referent: handle.clone(), + }); + } + } + + for (position, operation) in patch.operations.iter().enumerate() { + let site = Site::Operation(position); + match operation { + ComponentOp::CreateCommitment { + subject, + counterparty, + kind, + due, + period, + checks, + statement, + } => { + if !is_canonical_text(statement.as_str()) { + mismatches.push(Mismatch::NoncanonicalText { + operation: position, + }); + } + let subject_key = resolve_subject( + site.clone(), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let counterparty_key = counterparty.as_ref().map(|reference| { + resolve_subject( + site.clone(), + reference, + &index, + &state.subjects, + &mut mismatches, + ) + }); + let mut checks_resolve = true; + for check in checks { + checks_resolve &= + resolve_check(site.clone(), check, &index, state, &mut mismatches); + } + if (*kind == CommitmentKind::Routine) != period.is_some() { + mismatches.push(Mismatch::CommitmentPeriodMismatch { + operation: position, + }); + } + if let Some(period) = period + && !is_valid_cost(Cost(period.minutes())) + { + mismatches.push(Mismatch::InvalidCost { site: site.clone() }); + } + if *kind != CommitmentKind::Routine && !checks.is_empty() { + mismatches.push(Mismatch::ChecksOnNonRoutine { + operation: position, + }); + } + // A promise cannot be born past due: it would press on its + // subject on the very next tick with no chance to act. + if *due <= state.header.now { + mismatches.push(Mismatch::CommitmentDueInThePast { + operation: position, + }); + } + if counterparty.is_some() && *kind == CommitmentKind::Goal { + mismatches.push(Mismatch::GoalWithCounterparty { + operation: position, + }); + } + let Some(subject_key) = subject_key else { + continue; + }; + // A retired subject cannot act, and making a promise is + // acting: refused here the same way `RetiredSubjectActed` + // refuses a retired office incumbent below. + if graph.is_retired(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + if let Some(counterparty_key) = &counterparty_key { + match counterparty_key { + None => continue, + Some(counterparty_key) if *counterparty_key == subject_key => { + mismatches.push(Mismatch::SelfCommitment { + operation: position, + }); + continue; + } + Some(_) => {} + } + } + if !checks_resolve { + continue; + } + graph.commitments.insert( + ( + subject_key, + CommitmentKey { + command: command_id, + index: position as u32, + }, + ), + (), + ); + } + ComponentOp::DischargeCommitment { subject, key } => { + let Some(subject_key) = resolve_subject( + site.clone(), + subject, + &index, + &state.subjects, + &mut mismatches, + ) else { + continue; + }; + if graph.commitments.remove(&(subject_key, *key)).is_none() { + mismatches.push(Mismatch::UnknownCommitment { + operation: position, + }); + } + } + ComponentOp::AdvancePressure { source, target, by } + | ComponentOp::ReducePressure { source, target, by } => { + let advancing = matches!(operation, ComponentOp::AdvancePressure { .. }); + let target_key = resolve_subject( + site.clone(), + target, + &index, + &state.subjects, + &mut mismatches, + ); + let source_key = + resolve_pressure_source(site.clone(), source, &index, state, &mut mismatches); + let (Some(target_key), Some(source_key)) = (target_key, source_key) else { + continue; + }; + let slot = (target_key, source_key); + let current = graph.pressures.get(&slot).unwrap_or_default(); + let next = if advancing { + current.saturating_add(by.0) + } else { + current.saturating_sub(by.0) + }; + // A zero step and a subtraction that hits a floor both change + // nothing, which is one name and not three. + if next == current { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if next == 0 { + graph.pressures.remove(&slot); + } else { + graph.pressures.insert(slot, next); + } + } + ComponentOp::ResolvePressure { source, target } => { + let target_key = resolve_subject( + site.clone(), + target, + &index, + &state.subjects, + &mut mismatches, + ); + let source_key = + resolve_pressure_source(site.clone(), source, &index, state, &mut mismatches); + let (Some(target_key), Some(source_key)) = (target_key, source_key) else { + continue; + }; + if graph.pressures.remove(&(target_key, source_key)).is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } + ComponentOp::Relocate { subject, via } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let route_key = resolve_route( + Site::Operation(position), + via, + &index, + &state.edges, + &mut mismatches, + ); + let (Some(subject_key), Some(route_key)) = (subject_key, route_key) else { + continue; + }; + let Some(route) = graph.routes.get(&route_key) else { + continue; + }; + let mut admitted = true; + match graph.positions.get(&subject_key) { + None => { + mismatches.push(Mismatch::UnplacedSubject { + operation: position, + }); + admitted = false; + } + Some(place) if place != route.from => { + mismatches.push(Mismatch::SubjectNotAtOrigin { + operation: position, + }); + admitted = false; + } + Some(_) => {} + } + if !route.open { + mismatches.push(Mismatch::RouteClosed { + operation: position, + }); + admitted = false; + } + // The resolver reads authority for the subject being moved, not + // for whoever proposed the patch, which is what keeps it + // actor-blind: the patch lane and the action lane get + // the same answer for the same move. A destination this patch + // declares is canonically unknown, so only a `Public` route + // reaches it. + let opened = match &route.to { + Key::Existing(destination) => route_admits( + state, + &canonical_grants(&graph.effective_authority(&subject_key)), + &route.access, + *destination, + ), + Key::Draft(_) => route.access == AccessKind::Public, + }; + if !opened { + mismatches.push(Mismatch::RouteAccessRestricted { + operation: position, + }); + admitted = false; + } + if admitted { + graph.positions.insert(subject_key, route.to); + } + } + ComponentOp::Retire { subject } => { + let Some(subject_key) = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ) else { + continue; + }; + if graph.is_retired(&subject_key) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + graph.retire(subject_key.clone()); + graph.positions.remove(&subject_key); + graph.affordance_holdings.remove(&subject_key); + } + ComponentOp::OpenRoute { route } | ComponentOp::CloseRoute { route } => { + let open = matches!(operation, ComponentOp::OpenRoute { .. }); + let Some(route_key) = resolve_route( + Site::Operation(position), + route, + &index, + &state.edges, + &mut mismatches, + ) else { + continue; + }; + let Some(candidate) = graph.routes.get_mut(&route_key) else { + continue; + }; + if candidate.open == open { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.open = open; + } + } + ComponentOp::AlterCost { route, cost } => { + let route_key = resolve_route( + Site::Operation(position), + route, + &index, + &state.edges, + &mut mismatches, + ); + if !is_valid_cost(*cost) { + mismatches.push(Mismatch::InvalidCost { + site: Site::Operation(position), + }); + continue; + } + let Some(route_key) = route_key else { continue }; + let Some(candidate) = graph.routes.get_mut(&route_key) else { + continue; + }; + if candidate.cost == *cost { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.cost = *cost; + } + } + ComponentOp::Transfer { + from, + to, + resource, + qty, + } => { + let from_key = resolve_subject( + Site::Operation(position), + from, + &index, + &state.subjects, + &mut mismatches, + ); + let to_key = resolve_subject( + Site::Operation(position), + to, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(from_key), Some(to_key), Some(resource_key)) = + (from_key, to_key, resource_key) + else { + continue; + }; + if from_key == to_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if qty.0 == 0 { + continue; + } + let held = candidate_held(&graph.holdings, &from_key, &resource_key); + let Some(remaining) = held.checked_sub(qty.0) else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + let Some(credited) = + candidate_held(&graph.holdings, &to_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut graph.holdings, &from_key, &resource_key, remaining); + candidate_set(&mut graph.holdings, &to_key, &resource_key, credited); + // A transfer contributes to no ledger term: the equation proves + // it, because moving a different amount out than in breaks the + // resource's total. + deltas.entry(resource_key).or_default(); + } + ComponentOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let from_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + from_resource, + &index, + &state.entities, + &mut mismatches, + ); + let into_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + into_resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(from_key), Some(into_key)) = + (holder_key, from_key, into_key) + else { + continue; + }; + if from_key == into_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if qty.0 == 0 { + continue; + } + let Some(remaining) = + candidate_held(&graph.holdings, &holder_key, &from_key).checked_sub(qty.0) + else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + let Some(gained) = + candidate_held(&graph.holdings, &holder_key, &into_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut graph.holdings, &holder_key, &from_key, remaining); + candidate_set(&mut graph.holdings, &holder_key, &into_key, gained); + deltas.entry(from_key).or_default().spent += u128::from(qty.0); + deltas.entry(into_key).or_default().gained += u128::from(qty.0); + } + ComponentOp::Consume { + holder, + resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 { + continue; + } + let Some(remaining) = + candidate_held(&graph.holdings, &holder_key, &resource_key).checked_sub(qty.0) + else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + candidate_set(&mut graph.holdings, &holder_key, &resource_key, remaining); + deltas.entry(resource_key).or_default().consumed += u128::from(qty.0); + } + ComponentOp::Admit { + holder, + resource, + qty, + evidence, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let evidenced = is_canonical_text(&evidence.0) && patch.evidence.contains(evidence); + if !evidenced { + mismatches.push(Mismatch::AdmitWithoutEvidence { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 || !evidenced { + continue; + } + let Some(admitted) = + candidate_held(&graph.holdings, &holder_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut graph.holdings, &holder_key, &resource_key, admitted); + deltas.entry(resource_key).or_default().admitted += u128::from(qty.0); + } + ComponentOp::Mint { + holder, + resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 { + continue; + } + let Some(minted) = + candidate_held(&graph.holdings, &holder_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut graph.holdings, &holder_key, &resource_key, minted); + deltas.entry(resource_key).or_default().admitted += u128::from(qty.0); + } + ComponentOp::Bind { subject, target } | ComponentOp::Release { subject, target } => { + let bind = matches!(operation, ComponentOp::Bind { .. }); + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let target_key = resolve_dependency_target( + Site::Operation(position), + target, + &index, + state, + &mut mismatches, + ); + let (Some(subject_key), Some(target_key)) = (subject_key, target_key) else { + continue; + }; + if target_key == TargetKey::Subject(subject_key.clone()) { + mismatches.push(Mismatch::SelfDependency { + operation: position, + }); + continue; + } + let slot = (subject_key, target_key); + if graph.dependencies.contains_key(&slot) == bind { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if bind { + graph.dependencies.insert(slot, ()); + } else { + graph.dependencies.remove(&slot); + } + } + ComponentOp::GrantAuthority { holder, grant } + | ComponentOp::RevokeAuthority { holder, grant } => { + let granting = matches!(operation, ComponentOp::GrantAuthority { .. }); + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + if !is_civic_name(&grant.kind.0) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let over = resolve_authority_target( + Site::Operation(position), + &grant.over, + &index, + state, + &mut mismatches, + ); + let (Some(holder_key), Some(over)) = (holder_key, over) else { + continue; + }; + let entry = GrantKey { + kind: grant.kind.clone(), + over, + }; + // Admission-time only: a `Subject` grant landing inside a + // `PlaceSubtree` grant the holder already has, or the reverse, + // is a second source for the same kind of act. This does not + // reach `targets_overlap`/`verify_state_shape`, which stay + // structural and position-independent; a later `Relocate` + // that creates this shape is not re-derived as a violation. + let mut grants = graph.grants_of(&holder_key); + if granting + && grants.iter().any(|other| { + other.kind == entry.kind + && grant_targets_nest(state, &entry.over, &other.over) + }) + { + mismatches.push(Mismatch::OverlappingJurisdiction { + operation: position, + }); + continue; + } + if grants.contains(&entry) == granting { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + if granting { + grants.insert(entry); + } else { + grants.remove(&entry); + } + graph.set_grants(holder_key, grants); + } + } + ComponentOp::GrantAffordance { subject, affordance } + | ComponentOp::RevokeAffordance { subject, affordance } => { + let granting = matches!(operation, ComponentOp::GrantAffordance { .. }); + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let affordance_key = resolve_affordance( + Site::Operation(position), + affordance, + &index, + &state.affordance_catalog, + &mut mismatches, + ); + let (Some(subject_key), Some(affordance_key)) = (subject_key, affordance_key) + else { + continue; + }; + // A retired subject holds no grant a patch may touch. + if graph.is_retired(&subject_key) { + mismatches.push(Mismatch::GrantsToRetired { + operation: position, + }); + continue; + } + let mut granted = graph.affordance_holdings.get(&subject_key).unwrap_or_default(); + if granted.contains(&affordance_key) == granting { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if granting { + granted.insert(affordance_key); + } else { + granted.remove(&affordance_key); + } + if granted.is_empty() { + graph.affordance_holdings.remove(&subject_key); + } else { + graph.affordance_holdings.insert(subject_key, granted); + } + } + ComponentOp::OpenOffice { + institution, + office, + delegated, + } => { + let institution_key = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ); + if delegated.is_empty() { + mismatches.push(Mismatch::EmptyDelegation { + operation: position, + }); + } + if delegated.iter().any(|kind| !is_civic_name(&kind.0)) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let Some(institution_key) = institution_key else { + continue; + }; + if delegated.is_empty() { + continue; + } + let slot = (institution_key, office.clone()); + let current = graph.office(&slot); + if current + .as_ref() + .is_some_and(|current| ¤t.delegated == delegated) + { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + graph.set_office( + slot, + Some(OfficeCandidate { + incumbent: current.and_then(|current| current.incumbent), + delegated: delegated.clone(), + }), + ); + } + } + ComponentOp::CloseOffice { + institution, + office, + } + | ComponentOp::VacateOffice { + institution, + office, + } => { + let closing = matches!(operation, ComponentOp::CloseOffice { .. }); + let Some(institution_key) = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ) else { + continue; + }; + let slot = (institution_key, office.clone()); + let Some(current) = graph.office(&slot) else { + mismatches.push(Mismatch::UnknownOffice { + operation: position, + }); + continue; + }; + if closing { + graph.set_office(slot, None); + } else if current.incumbent.is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + graph.set_office( + slot, + Some(OfficeCandidate { + incumbent: None, + ..current + }), + ); + } + } + ComponentOp::InstallIncumbent { + institution, + office, + incumbent, + } => { + let institution_key = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ); + let incumbent_key = resolve_subject( + Site::Operation(position), + incumbent, + &index, + &state.subjects, + &mut mismatches, + ); + if let Some(incumbent_key) = &incumbent_key + && subject_kind_of(incumbent_key, &index, state) != Some(SubjectKind::Person) + { + mismatches.push(Mismatch::OfficeHolderNotPerson { + operation: position, + }); + continue; + } + let (Some(institution_key), Some(incumbent_key)) = (institution_key, incumbent_key) + else { + continue; + }; + if graph.is_retired(&incumbent_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + let slot = (institution_key.clone(), office.clone()); + let Some(current) = graph.office(&slot) else { + mismatches.push(Mismatch::UnknownOffice { + operation: position, + }); + continue; + }; + if graph.offices_of(&institution_key).iter().any(|(name, other)| { + name != office && other.incumbent.as_ref() == Some(&incumbent_key) + }) { + mismatches.push(Mismatch::DuplicateIncumbency { + operation: position, + }); + continue; + } + if current.incumbent.as_ref() == Some(&incumbent_key) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + graph.set_office( + slot, + Some(OfficeCandidate { + incumbent: Some(incumbent_key), + ..current + }), + ); + } + } + ComponentOp::OpenForum { + grievance, + forum, + standing, + } => { + if !is_civic_name(&grievance.0) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let forum_key = resolve_subject( + Site::Operation(position), + forum, + &index, + &state.subjects, + &mut mismatches, + ); + let standing_key = resolve_authority_target( + Site::Operation(position), + standing, + &index, + state, + &mut mismatches, + ); + let (Some(forum_key), Some(standing_key)) = (forum_key, standing_key) else { + continue; + }; + if graph.redress.get(grievance) == Some((forum_key.clone(), standing_key.clone())) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + graph.redress.insert(grievance.clone(), (forum_key, standing_key)); + } + } + ComponentOp::CloseForum { grievance } => { + if graph.redress.remove(grievance).is_none() { + mismatches.push(Mismatch::UnknownForum { + operation: position, + }); + } + } + ComponentOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { + continue; + }; + if graph.is_retired(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + // Evidenced knowledge is knowledge of canon. A receipt cannot + // vouch for an assertion the kernel never evaluated. + if *source == AuthoredSource::Evidenced + && graph.facts.get(&fact_key) != Some(FactCandidate::Canonical) + { + mismatches.push(Mismatch::EvidencedKnowledgeOfClaim { + operation: position, + }); + continue; + } + let entry = KnowledgeCandidate { + confidence: *confidence, + source: match source { + AuthoredSource::Witnessed => KnowledgeSourceKey::Witnessed, + AuthoredSource::Evidenced => KnowledgeSourceKey::Evidenced, + }, + }; + let slot = (subject_key, fact_key); + if graph.knowledge.get(&slot) == Some(entry.clone()) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + graph.knowledge.insert(slot, entry); + } + } + ComponentOp::Forget { subject, fact } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { + continue; + }; + if graph.is_retired(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + if graph.knowledge.remove(&(subject_key, fact_key)).is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } + ComponentOp::Communicate { speaker, fact, to } => { + let speaker_key = resolve_subject( + Site::Operation(position), + speaker, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let audience = resolve_audience( + Site::Operation(position), + to, + &index, + state, + &mut mismatches, + ); + let (Some(speaker_key), Some(_), Some(audience)) = + (speaker_key, fact_key, audience) + else { + continue; + }; + if graph.is_retired(&speaker_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + // Ontology admission: communication reaches only subjects inside + // the channel's reach, and a speaker outside it is not speaking. + if !graph.in_audience(&speaker_key, &audience, &speaker_key) { + mismatches.push(Mismatch::SpeakerOutsideAudience { + operation: position, + }); + } + } + ComponentOp::Witness { + fact, + place, + confidence, + } => { + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let place_key = resolve_entity( + Site::Operation(position), + EntityKind::Place, + place, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(fact_key), Some(place_key)) = (fact_key, place_key) else { + continue; + }; + // The apply-time fan-out, modelled: every candidate subject + // standing under the place — canonical positions plus this + // patch's own declarations and its own relocations, which + // earlier arms have already written into `positions` — less + // everyone this map already has holding the fact, which is the + // same "already a knower" test `unheld` applies over committed + // state. + let entry = KnowledgeCandidate { + confidence: *confidence, + source: KnowledgeSourceKey::Witnessed, + }; + let recipients: Vec> = graph + .occupants_under(&place_key) + .into_iter() + .filter(|subject_key| { + !graph.knowledge.contains_key(&(subject_key.clone(), fact_key.clone())) + }) + .collect(); + if recipients.is_empty() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + for subject_key in recipients { + graph.knowledge.insert((subject_key, fact_key.clone()), entry.clone()); + } + } + } + ComponentOp::SetReach { channel, reach } => { + let channel_key = resolve_entity( + Site::Operation(position), + EntityKind::Channel, + channel, + &index, + &state.entities, + &mut mismatches, + ); + let reach_key = resolve_reach( + Site::Operation(position), + reach, + &index, + state, + &mut mismatches, + ); + let (Some(channel_key), Some(reach_key)) = (channel_key, reach_key) else { + continue; + }; + let Some(candidate) = graph.channels.get_mut(&channel_key) else { + continue; + }; + if candidate.reach == reach_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.reach = reach_key; + } + } + ComponentOp::SetController { + channel, + controller, + } => { + let channel_key = resolve_entity( + Site::Operation(position), + EntityKind::Channel, + channel, + &index, + &state.entities, + &mut mismatches, + ); + let controller_key = resolve_controller( + Site::Operation(position), + controller, + &index, + state, + &mut mismatches, + ); + let (Some(channel_key), Some(controller_key)) = (channel_key, controller_key) + else { + continue; + }; + let Some(candidate) = graph.channels.get_mut(&channel_key) else { + continue; + }; + if candidate.controller == controller_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.controller = controller_key; + } + } + } + // Disjointness, checked against the complete candidate graph after each + // operation that could widen someone's jurisdiction, so two operations + // in one patch collide with each other and the failure names the one + // that created the collision. Only three operations can: a new grant, a + // widened office, and a new incumbency. + if matches!( + operation, + ComponentOp::GrantAuthority { .. } + | ComponentOp::OpenOffice { .. } + | ComponentOp::InstallIncumbent { .. } + ) && graph.overlapping() + { + mismatches.push(Mismatch::OverlappingJurisdiction { + operation: position, + }); + } + } + + // Conservation, over the complete candidate after every operation has been + // applied in order. Never per operation: a patch whose operations + // individually balance but whose net does not is impossible, and an + // intermediate negative was already caught above as `InsufficientCustody`. + for (resource_key, delta) in &mut deltas { + (delta.before, delta.after) = graph.custody(resource_key); + } + if let Some(resource) = check_ledger(&deltas) { + mismatches.push(Mismatch::CustodyNotConserved { + resource: RefName::Entity(match resource { + Key::Existing(entity_id) => Ref::Existing(entity_id), + Key::Draft(handle) => Ref::Draft(handle), + }), + }); + } + + if patch.declarations.is_empty() && patch.operations.is_empty() { + mismatches.push(Mismatch::NoCanonicalChange); + } + + if genesis + && !patch + .declarations + .iter() + .any(|declaration| matches!(declaration, Declaration::Subject(_))) + { + mismatches.push(Mismatch::NoDecisionSubject); + } + + if !mismatches.is_empty() { + mismatches.sort(); + return Err(mismatches); + } + + // No canonical ID exists above this line. Allocation starts only now. + let mut collisions = Vec::new(); + let mut entities = Vec::new(); + let mut allocated_entities: BTreeMap = BTreeMap::new(); + for declaration in &patch.declarations { + let Declaration::Entity(entity) = declaration else { + continue; + }; + let entity_id = EntityId(derive_id( + ENTITY_NAMESPACE, + world_id, + command_id, + &entity.handle, + None, + )); + if state.entities.contains_key(&entity_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: entity.handle.clone(), + }); + } + allocated_entities.insert(entity.handle.clone(), entity_id); + entities.push(ResolvedEntity { + handle: entity.handle.clone(), + entity_id, + entity: EntityRecord { + label: entity.label.clone(), + kind: entity.kind, + container: None, + }, + }); + } + // Facts and channels allocate through the same entity namespace and the same + // `derive_id`, so no namespace is added and `RefKind::Entity` types every + // reference to one. They stay out of `entities` above so that vector remains + // a zip over the place and resource declarations. + for declaration in &patch.declarations { + let handle = match declaration { + Declaration::Fact(fact) => &fact.handle, + Declaration::Channel(channel) => &channel.handle, + _ => continue, + }; + let entity_id = EntityId(derive_id( + ENTITY_NAMESPACE, + world_id, + command_id, + handle, + None, + )); + if state.entities.contains_key(&entity_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: handle.clone(), + }); + } + allocated_entities.insert(handle.clone(), entity_id); + } + let entity_id_of = |key: &Key| -> EntityId { + match key { + Key::Existing(entity_id) => *entity_id, + Key::Draft(handle) => *allocated_entities + .get(handle) + .expect("a draft entity reference resolved above"), + } + }; + for (resolved, declaration) in entities + .iter_mut() + .zip( + patch + .declarations + .iter() + .filter_map(|declaration| match declaration { + Declaration::Entity(entity) => Some(entity), + _ => None, + }), + ) + { + resolved.entity.container = declaration + .container + .as_ref() + .map(|reference| entity_id_of(&key_of(reference))); + } + + let mut allocated_routes: BTreeMap = BTreeMap::new(); + let mut routes = Vec::new(); + for declaration in &patch.declarations { + let Declaration::Route(route) = declaration else { + continue; + }; + let edge_id = EdgeId(derive_id( + EDGE_NAMESPACE, + world_id, + command_id, + &route.handle, + None, + )); + if state.edges.contains_key(&edge_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: route.handle.clone(), + }); + } + allocated_routes.insert(route.handle.clone(), edge_id); + routes.push(ResolvedRoute { + handle: route.handle.clone(), + edge_id, + edge: EdgeRecord::Route { + label: route.label.clone(), + from: entity_id_of(&key_of(&route.from)), + to: entity_id_of(&key_of(&route.to)), + access: route.access.clone(), + cost: route.cost, + open: true, + }, + }); + } + + let mut allocated_affordances: BTreeMap = BTreeMap::new(); + let mut affordances = Vec::new(); + let allocate_affordance = |handle: &DraftHandle, + entry: Affordance, + affordances: &mut Vec, + allocated: &mut BTreeMap, + collisions: &mut Vec| { + let affordance_id = AffordanceId(derive_id( + AFFORDANCE_NAMESPACE, + world_id, + command_id, + handle, + None, + )); + if state.affordance_catalog.contains_key(&affordance_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: handle.clone(), + }); + } + allocated.insert(handle.clone(), affordance_id); + affordances.push(ResolvedAffordance { + handle: handle.clone(), + affordance_id, + affordance: entry, + }); + }; + if genesis { + allocate_affordance( + &speak_handle, + kernel_speak_entry(), + &mut affordances, + &mut allocated_affordances, + &mut collisions, + ); + } + for declaration in &patch.declarations { + let Declaration::Affordance(input) = declaration else { + continue; + }; + allocate_affordance( + &input.handle, + Affordance { + kind: input.kind.clone(), + roles: input.roles.clone(), + preconditions: input.preconditions.clone(), + effect_slots: input.effect_slots.clone(), + outcome_bands: input.outcome_bands.clone(), + carries_speech: input.carries_speech, + }, + &mut affordances, + &mut allocated_affordances, + &mut collisions, + ); + } + let affordance_id_of = |key: &Key| -> AffordanceId { + match key { + Key::Existing(affordance_id) => *affordance_id, + Key::Draft(handle) => *allocated_affordances + .get(handle) + .expect("a draft affordance reference resolved above"), + } + }; + + let mut allocated_subjects: BTreeMap = BTreeMap::new(); + let mut subjects = Vec::new(); + for declaration in &patch.declarations { + let Declaration::Subject(input) = declaration else { + continue; + }; + let subject_id = SubjectId(derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &input.handle, + None, + )); + if state.subjects.contains_key(&subject_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: input.handle.clone(), + }); + } + allocated_subjects.insert(input.handle.clone(), subject_id); + let granted = input + .affordances + .iter() + .map(|reference| affordance_id_of(&key_of(reference))) + .collect(); + subjects.push(ResolvedSubject { + handle: input.handle.clone(), + subject_id, + subject: SubjectState { + label: input.label.clone(), + kind: input.kind, + import_key: input.import_key.clone(), + retired: false, + }, + affordances: granted, + position: input.position.as_ref().map(|reference| Position { + place: entity_id_of(&key_of(reference)), + }), + }); + } + + let subject_id_of = |key: &Key| -> SubjectId { + match key { + Key::Existing(subject_id) => *subject_id, + Key::Draft(handle) => *allocated_subjects + .get(handle) + .expect("a draft subject reference resolved above"), + } + }; + let edge_id_of = |key: &Key| -> EdgeId { + match key { + Key::Existing(edge_id) => *edge_id, + Key::Draft(handle) => *allocated_routes + .get(handle) + .expect("a draft route reference resolved above"), + } + }; + let target_of = |target: &DependencyRef| -> DependencyTarget { + match target { + DependencyRef::Resource(reference) => { + DependencyTarget::Resource(entity_id_of(&key_of(reference))) + } + DependencyRef::Route(reference) => { + DependencyTarget::Route(edge_id_of(&key_of(reference))) + } + DependencyRef::Subject(reference) => { + DependencyTarget::Subject(subject_id_of(&key_of(reference))) + } + } + }; + let authority_target_of = |target: &AuthorityTargetRef| -> AuthorityTarget { + match target { + AuthorityTargetRef::Subject(reference) => { + AuthorityTarget::Subject(subject_id_of(&key_of(reference))) + } + AuthorityTargetRef::PlaceSubtree(reference) => { + AuthorityTarget::PlaceSubtree(entity_id_of(&key_of(reference))) + } + } + }; + let reach_of = |reach: &ReachRef| -> Reach { + match reach { + ReachRef::Subjects(members) => Reach::Subjects( + members + .iter() + .map(|reference| subject_id_of(&key_of(reference))) + .collect(), + ), + ReachRef::Place(reference) => Reach::Place(entity_id_of(&key_of(reference))), + } + }; + let controller_of = |controller: &Option>| -> Option { + controller + .as_ref() + .map(|reference| subject_id_of(&key_of(reference))) + }; + let audience_of = |audience: &AudienceRef| -> Audience { + match audience { + AudienceRef::Colocated => Audience::Colocated, + AudienceRef::Channel(reference) => Audience::Channel(entity_id_of(&key_of(reference))), + } + }; + let mut declared_facts = Vec::new(); + let mut declared_channels = Vec::new(); + for declaration in &patch.declarations { + match declaration { + Declaration::Fact(fact) => declared_facts.push(ResolvedFact { + handle: fact.handle.clone(), + entity_id: entity_id_of(&Key::Draft(fact.handle.clone())), + entity: EntityRecord { + label: fact.label.clone(), + kind: EntityKind::Fact, + container: None, + }, + fact: FactRecord { + statement: fact.statement.clone(), + standing: match &fact.standing { + FactStandingRef::Canonical { evidence } => FactStanding::Canonical { + evidence: evidence.clone(), + }, + FactStandingRef::Claimed { by } => FactStanding::Claimed { + by: subject_id_of(&key_of(by)), + }, + FactStandingRef::Ruled => FactStanding::Ruled, + }, + }, + }), + Declaration::Channel(channel) => declared_channels.push(ResolvedChannel { + handle: channel.handle.clone(), + entity_id: entity_id_of(&Key::Draft(channel.handle.clone())), + entity: EntityRecord { + label: channel.label.clone(), + kind: EntityKind::Channel, + container: None, + }, + channel: ChannelRecord { + reach: reach_of(&channel.reach), + controller: controller_of(&channel.controller), + }, + }), + _ => {} + } + } + let grant_of = |grant: &AuthorityGrantRef| -> AuthorityGrant { + AuthorityGrant { + kind: grant.kind.clone(), + over: authority_target_of(&grant.over), + } + }; + let precondition_of = |check: &PreconditionRef| -> BoundPrecondition { + match check { + PreconditionRef::Present { at } => BoundPrecondition::Present { + at: entity_id_of(&key_of(at)), + }, + PreconditionRef::Reachable { to, within } => BoundPrecondition::Reachable { + to: entity_id_of(&key_of(to)), + within: *within, + }, + PreconditionRef::Holds { resource, at_least } => BoundPrecondition::Holds { + resource: entity_id_of(&key_of(resource)), + at_least: *at_least, + }, + PreconditionRef::Authorized { over, kind } => BoundPrecondition::Authorized { + over: authority_target_of(over).as_referent(), + kind: kind.clone(), + }, + PreconditionRef::HasStanding { grievance } => BoundPrecondition::HasStanding { + grievance: grievance.clone(), + }, + PreconditionRef::Knows { fact, at_least } => BoundPrecondition::Knows { + fact: entity_id_of(&key_of(fact)), + at_least: *at_least, + }, + PreconditionRef::CanBroadcast { via } => BoundPrecondition::CanBroadcast { + via: audience_of(via), + }, + PreconditionRef::CanReach { subject, via } => BoundPrecondition::CanReach { + subject: subject_id_of(&key_of(subject)), + via: audience_of(via), + }, + PreconditionRef::Committed { to, kind } => BoundPrecondition::Committed { + to: subject_id_of(&key_of(to)), + kind: *kind, + }, + } + }; + let pressure_source_of = |source: &PressureSourceRef| -> PressureSource { + match source { + PressureSourceRef::Commitment { subject, key } => PressureSource::Commitment { + subject: subject_id_of(&key_of(subject)), + key: *key, + }, + PressureSourceRef::Dependency(target) => PressureSource::Dependency(target_of(target)), + PressureSourceRef::Subject(reference) => { + PressureSource::Subject(subject_id_of(&key_of(reference))) + } + } + }; + let operations = patch + .operations + .iter() + .enumerate() + .map(|(position, operation)| match operation { + ComponentOp::CreateCommitment { + subject, + counterparty, + kind, + due, + period, + checks, + statement, + } => ResolvedOp::CreateCommitment { + subject: subject_id_of(&key_of(subject)), + key: CommitmentKey { + command: command_id, + index: position as u32, + }, + commitment: Commitment { + kind: *kind, + counterparty: counterparty + .as_ref() + .map(|reference| subject_id_of(&key_of(reference))), + due: *due, + period: *period, + checks: checks.iter().map(precondition_of).collect(), + statement: statement.clone(), + }, + }, + ComponentOp::DischargeCommitment { subject, key } => ResolvedOp::DischargeCommitment { + subject: subject_id_of(&key_of(subject)), + key: *key, + }, + ComponentOp::AdvancePressure { source, target, by } => ResolvedOp::AdvancePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + by: *by, + }, + ComponentOp::ReducePressure { source, target, by } => ResolvedOp::ReducePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + by: *by, + }, + ComponentOp::ResolvePressure { source, target } => ResolvedOp::ResolvePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + }, + ComponentOp::Retire { subject } => ResolvedOp::Retire { + subject: subject_id_of(&key_of(subject)), + }, + ComponentOp::GrantAffordance { + subject, + affordance, + } => ResolvedOp::GrantAffordance { + subject: subject_id_of(&key_of(subject)), + affordance: affordance_id_of(&key_of(affordance)), + }, + ComponentOp::RevokeAffordance { + subject, + affordance, + } => ResolvedOp::RevokeAffordance { + subject: subject_id_of(&key_of(subject)), + affordance: affordance_id_of(&key_of(affordance)), + }, + ComponentOp::Relocate { subject, via } => ResolvedOp::Relocate { + subject_id: subject_id_of(&key_of(subject)), + edge_id: edge_id_of(&key_of(via)), + }, + ComponentOp::OpenRoute { route } => ResolvedOp::OpenRoute { + edge_id: edge_id_of(&key_of(route)), + }, + ComponentOp::CloseRoute { route } => ResolvedOp::CloseRoute { + edge_id: edge_id_of(&key_of(route)), + }, + ComponentOp::AlterCost { route, cost } => ResolvedOp::AlterCost { + edge_id: edge_id_of(&key_of(route)), + cost: *cost, + }, + ComponentOp::Transfer { + from, + to, + resource, + qty, + } => ResolvedOp::Transfer { + from: subject_id_of(&key_of(from)), + to: subject_id_of(&key_of(to)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => ResolvedOp::Transform { + holder: subject_id_of(&key_of(holder)), + from_resource: entity_id_of(&key_of(from_resource)), + into_resource: entity_id_of(&key_of(into_resource)), + qty: *qty, + }, + ComponentOp::Consume { + holder, + resource, + qty, + } => ResolvedOp::Consume { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Admit { + holder, + resource, + qty, + evidence, + } => ResolvedOp::Admit { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + evidence: evidence.clone(), + }, + ComponentOp::Mint { + holder, + resource, + qty, + } => ResolvedOp::Mint { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Bind { subject, target } => ResolvedOp::Bind { + subject: subject_id_of(&key_of(subject)), + target: target_of(target), + }, + ComponentOp::Release { subject, target } => ResolvedOp::Release { + subject: subject_id_of(&key_of(subject)), + target: target_of(target), + }, + ComponentOp::GrantAuthority { holder, grant } => ResolvedOp::GrantAuthority { + holder: subject_id_of(&key_of(holder)), + grant: grant_of(grant), + }, + ComponentOp::RevokeAuthority { holder, grant } => ResolvedOp::RevokeAuthority { + holder: subject_id_of(&key_of(holder)), + grant: grant_of(grant), + }, + ComponentOp::OpenOffice { + institution, + office, + delegated, + } => ResolvedOp::OpenOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + delegated: delegated.clone(), + }, + ComponentOp::CloseOffice { + institution, + office, + } => ResolvedOp::CloseOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + }, + ComponentOp::InstallIncumbent { + institution, + office, + incumbent, + } => ResolvedOp::InstallIncumbent { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + incumbent: subject_id_of(&key_of(incumbent)), + }, + ComponentOp::VacateOffice { + institution, + office, + } => ResolvedOp::VacateOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + }, + ComponentOp::OpenForum { + grievance, + forum, + standing, + } => ResolvedOp::OpenForum { + grievance: grievance.clone(), + forum: subject_id_of(&key_of(forum)), + standing: authority_target_of(standing), + }, + ComponentOp::CloseForum { grievance } => ResolvedOp::CloseForum { + grievance: grievance.clone(), + }, + ComponentOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => ResolvedOp::AcquireKnowledge { + subject: subject_id_of(&key_of(subject)), + fact: entity_id_of(&key_of(fact)), + source: *source, + confidence: *confidence, + }, + ComponentOp::Communicate { speaker, fact, to } => ResolvedOp::Communicate { + speaker: subject_id_of(&key_of(speaker)), + fact: entity_id_of(&key_of(fact)), + to: audience_of(to), + }, + ComponentOp::Witness { + fact, + place, + confidence, + } => ResolvedOp::Witness { + fact: entity_id_of(&key_of(fact)), + place: entity_id_of(&key_of(place)), + confidence: *confidence, + }, + ComponentOp::Forget { subject, fact } => ResolvedOp::Forget { + subject: subject_id_of(&key_of(subject)), + fact: entity_id_of(&key_of(fact)), + }, + ComponentOp::SetReach { channel, reach } => ResolvedOp::SetReach { + channel: entity_id_of(&key_of(channel)), + reach: reach_of(reach), + }, + ComponentOp::SetController { + channel, + controller, + } => ResolvedOp::SetController { + channel: entity_id_of(&key_of(channel)), + controller: controller_of(controller), + }, + }) + .collect(); + + if !collisions.is_empty() { + collisions.sort(); + return Err(collisions); + } + + Ok(ResolvedPatch { + subjects, + entities, + routes, + affordances, + facts: declared_facts, + channels: declared_channels, + operations, + evidence: patch.evidence.clone(), + }) +} + +/// Whether every referent one stored check names resolves. The canonical +/// lowering runs after allocation, so a check that does not resolve here would +/// have nothing to lower to. +fn resolve_check( + site: Site, + check: &PreconditionRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> bool { + let entity = |kind: EntityKind, reference: &Ref, mismatches: &mut Vec| { + resolve_entity( + site.clone(), + kind, + reference, + index, + &state.entities, + mismatches, + ) + .is_some() + }; + let audience = |via: &AudienceRef, mismatches: &mut Vec| { + resolve_audience(site.clone(), via, index, state, mismatches).is_some() + }; + let subject = |reference: &Ref, mismatches: &mut Vec| { + resolve_subject(site.clone(), reference, index, &state.subjects, mismatches).is_some() + }; + match check { + PreconditionRef::Present { at } => entity(EntityKind::Place, at, mismatches), + PreconditionRef::Reachable { to, within } => { + let resolved = entity(EntityKind::Place, to, mismatches); + if !is_valid_cost(*within) { + mismatches.push(Mismatch::InvalidCost { site: site.clone() }); + return false; + } + resolved + } + PreconditionRef::Holds { resource, .. } => { + entity(EntityKind::Resource, resource, mismatches) + } + PreconditionRef::Authorized { over, kind } => { + let resolved = + resolve_authority_target(site.clone(), over, index, state, mismatches).is_some(); + if !is_civic_name(&kind.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site.clone() }); + return false; + } + resolved + } + PreconditionRef::HasStanding { grievance } => { + if is_civic_name(&grievance.0) { + true + } else { + mismatches.push(Mismatch::InvalidCivicName { site: site.clone() }); + false + } + } + PreconditionRef::Knows { fact, .. } => entity(EntityKind::Fact, fact, mismatches), + PreconditionRef::CanBroadcast { via } => audience(via, mismatches), + PreconditionRef::CanReach { + subject: named, + via, + } => subject(named, mismatches) & audience(via, mismatches), + PreconditionRef::Committed { to, .. } => subject(to, mismatches), + } +} + +fn resolve_pressure_source( + site: Site, + source: &PressureSourceRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match source { + PressureSourceRef::Commitment { subject, key } => { + resolve_subject(site, subject, index, &state.subjects, mismatches) + .map(|subject| PressureSourceKey::Commitment { subject, key: *key }) + } + PressureSourceRef::Dependency(target) => { + resolve_dependency_target(site, target, index, state, mismatches) + .map(PressureSourceKey::Dependency) + } + PressureSourceRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(PressureSourceKey::Subject) + } + } +} + +/// Whether `place` is `root` or is contained in it, over canonical state: one +/// upward walk in the shape of [`containment_terminates`], bounded by the graph +/// size. It is total because `admit_resolved` refuses a non-terminating chain, +/// so the bound is belt-and-braces rather than a repair loop. The question it +/// answers is "is this target inside my ground". Enumerating who stands under a +/// place is the other direction and has its own owner: `under_place` walks the +/// subtree by the entities partition's `ChildOf` index. +pub(super) fn covers_place( + entities: &Docs, + root: EntityId, + place: EntityId, +) -> bool { + let mut current = Some(place); + for _ in 0..=entities.len() { + match current { + None => return false, + Some(node) if node == root => return true, + Some(node) => current = entities.get(&node).and_then(|record| record.container), + } + } + false +} + +/// The canonical twin of the candidate graph's `Candidate::targets_overlap`: whether two +/// jurisdictions of one kind cover common ground. +pub(super) fn targets_overlap( + entities: &Docs, + left: AuthorityTarget, + right: AuthorityTarget, +) -> bool { + match (left, right) { + (AuthorityTarget::Subject(one), AuthorityTarget::Subject(other)) => one == other, + (AuthorityTarget::PlaceSubtree(one), AuthorityTarget::PlaceSubtree(other)) => { + covers_place(entities, one, other) || covers_place(entities, other, one) + } + _ => false, + } +} + +/// Whether a subject holding `grants` may traverse a route with this access +/// rule toward `destination`. The sole statement of the `Restricted` rule, +/// called by `resolve_patch`'s `Relocate` arm, by `apply_operation`'s, and by +/// `Precondition::Reachable`'s edge admission — one rule, three callers, no +/// drift. Openness is a separate claim with its own name, so it is not folded +/// in here. +pub(super) fn route_admits( + state: &super::WorldState, + grants: &BTreeSet, + access: &AccessKind, + destination: EntityId, +) -> bool { + match access { + AccessKind::Public => true, + AccessKind::Restricted { requires } => grants.iter().any(|grant| { + &grant.kind == requires + && super::covers(state, grant.over, super::Target::Entity(destination)) + }), + } +} + +/// The same containment walk over canonical state, for the admission and replay +/// invariants. `admit_resolved` runs it after inserting a place, so a container +/// chain that never terminates dies before the partition keeps it. +pub(super) fn containment_terminates( + start: EntityId, + entities: &Docs, +) -> bool { + let mut current = entities.get(&start).and_then(|record| record.container); + for _ in 0..=entities.len() { + match current { + None => return true, + Some(node) if node == start => return false, + Some(node) => current = entities.get(&node).and_then(|record| record.container), + } + } + false +} +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{ + ADMIT_KIND, FIXTURE_ENTITIES, LEVY_KIND, admit_topology, authority_kind, + auth_principal, civic_world, command, creation, grant_to, human_principal, office, + over_place, owner, reject_play, speak_entry, submit_play, + }; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, CommandId, KernelError, WorldKernel, + }; + + fn entity(handle: &str, label: &str, kind: EntityKind) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + container: None, + }) + } + + fn contained(handle: &str, label: &str, container: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new(container))), + }) + } + + fn route(handle: &str, label: &str, from: &str, to: &str, cost: u32) -> Declaration { + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + from: Ref::Draft(DraftHandle::new(from)), + to: Ref::Draft(DraftHandle::new(to)), + access: AccessKind::Public, + cost: Cost(cost), + }) + } + + /// Every fixture institution is declared by a post-genesis `AdmitPatch`, so + /// it grants the committed Speak entry by canonical reference: the kernel + /// synthesizes that entry once, at genesis, and a later patch names it like + /// any other structure a previous commit allocated. + fn institution( + kernel: &WorldKernel, + handle: &str, + label: &str, + position: Option>, + ) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Institution, + affordances: BTreeSet::from([speak_entry(kernel)]), + position, + import_key: None, + }) + } + + fn patch_of(declarations: Vec) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } + } + + fn operations_of(operations: Vec) -> WorldPatch { + WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + } + } + + fn draft(handle: &str) -> DraftHandle { + DraftHandle::new(handle) + } + + fn at(handle: &str) -> Site { + Site::Declaration(DraftHandle::new(handle)) + } + + fn admit(patch: WorldPatch) -> CommandBody { + CommandBody::AdmitPatch { + patch, + } + } + + /// A minimal admissible entry, so a validation test changes exactly one + /// thing and names exactly one rejection. + fn catalog_entry( + handle: &str, + kind: &str, + roles: Vec, + effect_slots: Vec, + outcome_bands: Vec, + ) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles, + preconditions: Vec::new(), + effect_slots, + outcome_bands, + carries_speech: false, + }) + } + + fn role_spec(role: &str, kind: RefKind) -> RoleSpec { + RoleSpec { + role: Role(role.into()), + kind, + } + } + + fn transfer_slot(roles: Vec<&str>, bounds: Bounds) -> EffectSlot { + EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: roles.into_iter().map(|role| Role(role.into())).collect(), + bounds, + } + } + + fn transfer_roles() -> Vec { + vec![ + role_spec("from", RefKind::Subject(None)), + role_spec("to", RefKind::Subject(None)), + role_spec("goods", RefKind::Entity(EntityKind::Resource)), + ] + } + + fn band(effects: Vec) -> OutcomeBand { + OutcomeBand { weight: 1, effects } + } + + #[test] + fn a_catalog_entry_with_a_dangling_or_noncanonical_band_is_rejected() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let slots = vec![ + transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))), + transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))), + ]; + let handle = DraftHandle::new("verb"); + + for (bands, expected) in [ + ( + vec![band(vec![2])], + Mismatch::DanglingBandEffect { + handle: handle.clone(), + band: 0, + }, + ), + ( + vec![band(vec![1, 0])], + Mismatch::BandEffectsNotCanonical { + handle: handle.clone(), + band: 0, + }, + ), + ( + vec![OutcomeBand { + weight: 0, + effects: vec![0], + }], + Mismatch::ZeroBandWeight { + handle: handle.clone(), + band: 0, + }, + ), + ( + Vec::new(), + Mismatch::NoOutcomeBand { + handle: handle.clone(), + }, + ), + ] { + let rejected = reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + slots.clone(), + bands, + )])), + ); + assert_eq!(rejected, vec![expected]); + assert!(kernel.state.affordance_catalog.len() == before.affordances.len()); + } + + // No effect slots and no speech: the entry could never change anything. + let rejected = reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + Vec::new(), + Vec::new(), + vec![band(Vec::new())], + )])), + ); + assert_eq!(rejected, vec![Mismatch::InertAffordance { handle }]); + } + + #[test] + fn a_slot_whose_roles_do_not_match_its_operation_is_rejected() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let handle = DraftHandle::new("verb"); + + // A `Transfer` takes three referents, not two. + assert_eq!( + reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::SlotRoleArity { + handle: handle.clone(), + slot: 0 + }] + ); + + // Its third referent is a resource, not a place. + assert_eq!( + reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + vec![ + role_spec("from", RefKind::Subject(None)), + role_spec("to", RefKind::Subject(None)), + role_spec("goods", RefKind::Entity(EntityKind::Place)), + ], + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: Role("goods".into()) + }] + ); + + // A `Transfer` carries a quantity, so an unbounded slot has no ceiling. + assert_eq!( + reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot(vec!["from", "to", "goods"], Bounds::None)], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::SlotBoundMismatch { + handle: handle.clone(), + slot: 0 + }] + ); + + // A slot naming a role the entry does not declare. + assert_eq!( + reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "cargo"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::UnknownRole { + handle, + role: Role("cargo".into()) + }] + ); + } + + #[test] + fn a_grant_naming_an_undeclared_affordance_is_rejected_and_the_same_patch_commits() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let entries_before = kernel.state.affordance_catalog.len(); + let subjects_before = kernel.state.subjects.len(); + + let granting = |handle: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("late-arrival"), + label: "A Late Arrival".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([Ref::Draft(DraftHandle::new(handle))]), + position: None, + import_key: None, + }) + }; + + assert_eq!( + reject_play( + &mut kernel, + &before, + admit(patch_of(vec![granting("verb")])) + ), + vec![Mismatch::UnresolvedDraft { + site: Site::Declaration(DraftHandle::new("late-arrival")), + referent: DraftHandle::new("verb"), + expected: RefKind::Affordance, + }] + ); + assert_eq!(kernel.state.affordance_catalog.len(), entries_before); + assert_eq!(kernel.state.subjects.len(), subjects_before); + + // Declaring the entry in the same patch commits both atomically. + let receipt = submit_play( + &mut kernel, + &before, + admit(patch_of(vec![ + catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)), + )], + vec![band(vec![0])], + ), + granting("verb"), + ])), + ); + assert!(receipt.resulting_revision > 0); + assert_eq!(kernel.state.affordance_catalog.len(), entries_before + 1); + assert_eq!(kernel.state.subjects.len(), subjects_before + 1); + let granted = kernel + .state + .affordance_grants + .values() + .find(|entries| entries.len() == 1) + .expect("the new subject's grant set"); + assert!( + granted + .iter() + .all(|id| kernel.state.affordance_catalog.contains_key(id)) + ); + } + + #[test] + fn two_entries_cannot_share_one_kind_name() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let slot = transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))); + let rejected = reject_play( + &mut kernel, + &before, + admit(patch_of(vec![ + catalog_entry( + "first", + "haul", + transfer_roles(), + vec![slot.clone()], + vec![band(vec![0])], + ), + catalog_entry( + "second", + "haul", + transfer_roles(), + vec![slot], + vec![band(vec![0])], + ), + ])), + ); + assert_eq!( + rejected, + vec![Mismatch::DuplicateAffordanceKind { + handle: DraftHandle::new("second") + }] + ); + + // A kind name outside the tool-name alphabet is refused for the same + // reason: it becomes a generated tool name. + let rejected = reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "loud", + "Haul It", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)), + )], + vec![band(vec![0])], + )])), + ); + assert_eq!( + rejected, + vec![Mismatch::InvalidAffordanceName { + handle: DraftHandle::new("loud") + }] + ); + } + + fn draft_world() -> WorldKernel { + WorldKernel::create(creation("Kharad"), + &auth_principal(owner()), + ) + .expect("draft world") + .0 + } + + /// The position reference names a place that no declaration and no partition + /// provides. Nothing commits and nothing is allocated. + #[test] + fn a_subject_declared_at_an_undeclared_place_is_rejected_and_allocates_nothing() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(vec![institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), + )])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::UnresolvedDraft { + site: at("rhythm-authority"), + referent: draft("kharad-rhythm-road"), + expected: PLACE, + }] + ); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); + assert_eq!(kernel.state.subjects.len(), before.subjects.len()); + } + + /// A place, a route into it, and a subject standing there are one atomic + /// commit: every reference resolves to an ID the same patch allocated. + #[test] + fn a_declared_place_and_its_dependents_commit_atomically() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let patch = patch_of(vec![ + entity("cavity-yard", "The Cavity Yard", EntityKind::Place), + entity("kharad-rhythm-road", "The Rhythm Road", EntityKind::Place), + route( + "yard-road", + "The Yard Ramp", + "cavity-yard", + "kharad-rhythm-road", + 12, + ), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(draft("kharad-rhythm-road"))), + ), + ]); + let receipt = submit_play(&mut kernel, &before, admit(patch)); + assert!(receipt.resulting_revision > 0); + + let after = kernel.snapshot().unwrap(); + assert_eq!(after.revision, before.revision + 1); + assert_eq!(kernel.journal.commit_count(), commits_before + 1); + assert_eq!(kernel.state.entities.len(), 3); + let road = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Rhythm Road") + .expect("the road is admitted") + .0; + let yard = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Cavity Yard") + .expect("the yard is admitted") + .0; + let (_, edge) = kernel.state.edges.iter().next().expect("the route lands"); + assert_eq!(edge.endpoints(), (yard, road)); + assert_eq!(edge.cost(), Cost(12)); + assert!(edge.is_open()); + let admitted = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Rhythm Authority") + .expect("the institution is admitted") + .0; + assert_eq!( + kernel.state.positions.get(&admitted), + Some(&Position { place: road }) + ); + } + + /// A handle of the wrong namespace kind is a runtime mismatch. The + /// cross-namespace canonical case is a compile error instead: + /// `Ref::::Existing(subject_id)` does not compile, because + /// `SubjectId`, `EntityId`, and `EdgeId` are distinct newtypes with no + /// conversion between them and no public `Uuid` constructor. + #[test] + fn a_draft_handle_of_the_wrong_kind_is_rejected() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(vec![ + entity("rhythm-tithe", "The Rhythm Tithe", EntityKind::Resource), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-tithe"))), + ), + ])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::WrongKind { + site: at("rhythm-authority"), + referent: RefName::Entity(Ref::Draft(draft("rhythm-tithe"))), + expected: PLACE, + actual: RefKind::Entity(EntityKind::Resource), + }] + ); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Rejection carries the complete failed-check set, not the first failure, + /// and repairing exactly that set is enough to commit. + #[test] + fn rejection_returns_every_failed_check_and_repairing_exactly_those_commits() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + + let broken = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + entity("rhythm-road", " ", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("cavity-yard"))), + ), + ]); + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(broken), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::DuplicateHandle { + handle: DraftHandle::new("rhythm-road"), + }, + Mismatch::EmptyLabel { + handle: DraftHandle::new("rhythm-road"), + }, + Mismatch::UnresolvedDraft { + site: at("rhythm-authority"), + referent: draft("cavity-yard"), + expected: PLACE, + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.journal.commit_count(), 1); + + let repaired = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + entity("cavity-yard", "The Cavity Yard", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("cavity-yard"))), + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("late-arrival"), + label: "A Late Arrival".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: None, + import_key: None, + }), + ]); + let receipt = submit_play(&mut kernel, &before, admit(repaired)); + assert!(receipt.resulting_revision > 0); + assert_eq!(kernel.state.entities.len(), 3); + } + + #[test] + fn an_empty_patch_is_no_canonical_change() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(Vec::new())), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![Mismatch::NoCanonicalChange]); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.journal.commit_count(), 1); + } + + /// Three places whose containers form a cycle name themselves, and the + /// unrelated empty label joins the same complete set. + #[test] + fn a_containment_cycle_is_rejected_with_the_complete_set() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(vec![ + contained("yard", "The Cavity Yard", "road"), + contained("road", "The Rhythm Road", "gate"), + contained("gate", "The Rain Gate", "yard"), + entity("orphan", " ", EntityKind::Place), + ])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::ContainmentCycle { + referent: draft("yard"), + }, + Mismatch::ContainmentCycle { + referent: draft("road"), + }, + Mismatch::ContainmentCycle { + referent: draft("gate"), + }, + Mismatch::EmptyLabel { + handle: draft("orphan"), + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); + } + + #[test] + fn a_route_endpoint_that_is_not_a_place_is_rejected() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(vec![ + entity("yard", "The Cavity Yard", EntityKind::Place), + entity("tithe", "The Rhythm Tithe", EntityKind::Resource), + route("ramp", "The Yard Ramp", "yard", "tithe", 12), + ])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::WrongKind { + site: at("ramp"), + referent: RefName::Entity(Ref::Draft(draft("tithe"))), + expected: PLACE, + actual: RefKind::Entity(EntityKind::Resource), + }] + ); + assert!(kernel.state.edges.is_empty()); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// One name for one failed check, whether the cost arrives in a declaration + /// or in an operation. + #[test] + fn an_invalid_route_cost_is_rejected_from_declaration_and_from_alter_cost() { + let mut kernel = draft_world(); + let topology = admit_topology(&mut kernel); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(WorldPatch { + declarations: vec![Declaration::Route(RouteDeclaration { + handle: draft("free-ride"), + label: "The Free Ride".into(), + from: Ref::Existing(topology.yard), + to: Ref::Existing(topology.road), + access: AccessKind::Public, + cost: Cost(0), + })], + operations: vec![ComponentOp::AlterCost { + route: Ref::Existing(topology.ramp), + cost: Cost(MAX_ROUTE_COST + 1), + }], + evidence: Vec::new(), + }), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::InvalidCost { + site: at("free-ride"), + }, + Mismatch::InvalidCost { + site: Site::Operation(0), + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Each refusal has exactly one name: a closed route, a restricted one, and + /// a route that does not start where the subject stands. + #[test] + fn relocate_without_an_open_public_route_is_rejected() { + let mut kernel = draft_world(); + let topology = admit_topology(&mut kernel); + let active = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + for (edge_id, expected) in [ + (topology.shutter, Mismatch::RouteClosed { operation: 0 }), + ( + topology.toll, + Mismatch::RouteAccessRestricted { operation: 0 }, + ), + (topology.span, Mismatch::SubjectNotAtOrigin { operation: 0 }), + ] { + let error = kernel + .submit( + command( + &active, + CallerId::Play, + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(edge_id), + }])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![expected]); + } + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), active); + assert_eq!( + kernel.state.positions.get(&topology.walker), + Some(&Position { + place: topology.yard + }) + ); + } + + /// PA.f48: `Candidate::effective_authority` is the resolver's twin of + /// `delegated_authority`, and must share its predicate for "is this + /// institution live". Retiring the lending institution and granting the + /// same ground directly to its former office-holder, in one patch, must + /// not be read as an overlap with a lend the retirement already killed. + #[test] + fn a_grant_after_retiring_the_lending_institution_is_admitted() { + let mut kernel = draft_world(); + let (_, civic, before) = civic_world(&mut kernel); + + // The office lends levy over the whole hall; grant the reeve levy + // directly over the chamber the hall contains, so a resolver that + // still counted the dead lend would see two distinct, overlapping + // `GrantKey`s (not one collapsed duplicate) and refuse. + let receipt = submit_play( + &mut kernel, + &before, + admit(operations_of(vec![ + ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }, + grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber)), + ])), + ); + assert!( + receipt.resulting_revision > 0, + "a dead institution's lend must not collide with a fresh direct grant over the same ground" + ); + } + + /// PA.f48: a `Relocate` through a restricted route open only through a + /// dead institution's delegated authority is refused by the resolver + /// itself, as an ordinary `RouteAccessRestricted` mismatch — not + /// admitted by the resolver and then blown up as a `KernelError::Invariant` + /// when canonical apply recomputes the same authority, correctly finds it + /// gone, and refuses the already-applied `Retire`'s sibling operation. + #[test] + fn a_relocate_relying_only_on_a_retiring_institutions_authority_is_refused_by_the_resolver() { + let mut kernel = draft_world(); + let (topology, civic, before) = civic_world(&mut kernel); + + // `topology.walker` already exists and already stands at `yard`, so + // this delegation patch is operations-only: no declaration. + let delegated = submit_play( + &mut kernel, + &before, + admit(operations_of(vec![ + grant_to(civic.treasury, ADMIT_KIND, over_place(civic.chamber)), + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("portal"), + delegated: BTreeSet::from([authority_kind(ADMIT_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("portal"), + incumbent: Ref::Existing(topology.walker), + }, + ])), + ); + assert!( + delegated.resulting_revision > 0, + "expected the delegation patch to apply, got {delegated:?}" + ); + let after_delegation = kernel.snapshot().unwrap(); + + let commits_before = kernel.journal.commit_count(); + let mismatches = reject_play( + &mut kernel, + &after_delegation, + admit(operations_of(vec![ + ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }, + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(civic.postern), + }, + ])), + ); + assert_eq!( + mismatches, + vec![Mismatch::RouteAccessRestricted { operation: 1 }], + "the resolver must refuse the dead institution's lend itself, not let apply blow up" + ); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), after_delegation); + } + + #[test] + fn relocate_moves_the_subject_and_nothing_else() { + let mut kernel = draft_world(); + let topology = admit_topology(&mut kernel); + let active = kernel.snapshot().unwrap(); + let entities_before = kernel.state.entities.clone(); + let edges_before = kernel.state.edges.clone(); + + let receipt = submit_play( + &mut kernel, + &active, + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }])), + ); + assert!(receipt.resulting_revision > 0); + assert_eq!( + kernel.state.positions.get(&topology.walker), + Some(&Position { + place: topology.road + }) + ); + assert_eq!(kernel.state.entities, entities_before); + assert_eq!(kernel.state.edges, edges_before); + let after = kernel.snapshot().unwrap(); + assert_eq!( + after + .subjects + .iter() + .find(|subject| subject.id == topology.walker) + .expect("the walker is in the snapshot") + .position, + Some(topology.road) + ); + } + + #[test] + fn restart_replay_after_a_relocate_is_exact() { + let (mut kernel, _) = WorldKernel::create(creation("Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = kernel.snapshot().unwrap(); + let envelope = command( + &active, + CallerId::Play, + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }])), + ); + kernel + .submit(envelope.clone(), &AuthenticatedCaller::verified_play()) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + assert_eq!( + reopened.state.positions.get(&topology.walker), + Some(&Position { + place: topology.road + }) + ); + assert!(matches!( + reopened.submit(envelope, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + #[test] + fn the_snapshot_exposes_places_routes_and_positions_deterministically() { + let mut kernel = draft_world(); + let topology = admit_topology(&mut kernel); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!(snapshot, kernel.snapshot().unwrap()); + + assert_eq!(snapshot.places.len(), 4); + let place_ids: Vec<_> = snapshot.places.iter().map(|place| place.id).collect(); + let mut sorted_places = place_ids.clone(); + sorted_places.sort(); + assert_eq!(place_ids, sorted_places); + assert!(place_ids.contains(&topology.gate)); + + assert_eq!(snapshot.routes.len(), 4); + let route_ids: Vec<_> = snapshot.routes.iter().map(|route| route.id).collect(); + let mut sorted_routes = route_ids.clone(); + sorted_routes.sort(); + assert_eq!(route_ids, sorted_routes); + let shutter = snapshot + .routes + .iter() + .find(|route| route.id == topology.shutter) + .expect("the shutter is in the snapshot"); + assert!(!shutter.open); + assert_eq!(shutter.cost, Cost(5)); + assert_eq!(shutter.from, topology.yard); + + for subject in &snapshot.subjects { + assert_eq!( + subject.position, + kernel + .state + .positions + .get(&subject.id) + .map(|position| position.place) + ); + } + } + + #[test] + fn restart_replay_after_a_committed_patch_is_exact() { + let (mut kernel, _) = WorldKernel::create(creation("Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let before = kernel.snapshot().unwrap(); + let envelope = command( + &before, + CallerId::Play, + admit(patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + ), + ])), + ); + kernel + .submit(envelope.clone(), &AuthenticatedCaller::verified_play()) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + assert!(matches!( + reopened.submit(envelope, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// One allocator, a pure function of `(world_id, command_id, handle)`: the + /// same handle text under two commands gets two IDs, and the same command + /// re-resolved gets the same ones. + #[test] + fn genesis_and_admit_patch_share_one_allocator() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let genesis_human = before + .subjects + .iter() + .find(|subject| subject.label == "The Human") + .expect("the genesis human subject") + .id; + + let patch = patch_of(vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("human"), + label: "Another Human".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: None, + import_key: None, + })]); + submit_play(&mut kernel, &before, admit(patch.clone())); + let admitted = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "Another Human") + .expect("the admitted subject") + .0; + assert_ne!(admitted, genesis_human); + + let command_id = CommandId::issue(); + let first = resolve_patch(&kernel.state, command_id, &patch).unwrap(); + let second = resolve_patch(&kernel.state, command_id, &patch).unwrap(); + assert_eq!(first, second); + } + + /// The durable half of "a rejected patch mints nothing": the export, not + /// just the in-memory head, carries no commit and no byte of any ID the + /// rejected patch would have allocated. + #[test] + fn a_rejected_patch_leaves_no_commit_and_no_id_in_the_export() { + let (mut kernel, _) = WorldKernel::create(creation("Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let before = kernel.snapshot().unwrap(); + let handle = DraftHandle::new("rhythm-authority"); + let envelope = command( + &before, + CallerId::Play, + admit(patch_of(vec![institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), + )])), + ); + let command_id = envelope.id(); + + let error = kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap_err(); + assert!(matches!(error, KernelError::PatchRejected(_))); + + // Every ID the patch would have allocated, had resolution closed. + let would_be = [ + derive_id( + SUBJECT_NAMESPACE, + before.world_id, + command_id, + &handle, + None, + ), + derive_id( + AFFORDANCE_NAMESPACE, + before.world_id, + command_id, + &handle, + Some("speak"), + ), + ]; + + let exported = kernel.export().unwrap(); + drop(kernel); + let raw = &exported; + for id in would_be { + assert!( + !raw.windows(16).any(|window| window == id.as_bytes()), + "a rejected patch left {id} in the export" + ); + } + + let reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), before); + assert_eq!(reopened.journal.commit_count(), 1); + assert_eq!(reopened.state.entities.len(), FIXTURE_ENTITIES); + assert!( + !reopened + .state + .subjects + .contains_key(&SubjectId(would_be[0])) + ); + } + + /// `discriminator` is length-prefixed like `handle`, so `Some("")` and + /// `None` write different bytes into the preimage and cannot collide — + /// and neither can any other pair of discriminators whose bytes would + /// otherwise concatenate to the same string. + #[test] + fn derive_id_does_not_collide_some_empty_discriminator_with_none() { + let (kernel, _) = WorldKernel::create( + creation("DeriveId"), + &auth_principal(owner()), + ) + .unwrap(); + let world_id = kernel.state.header.world_id; + let command_id = CommandId::issue(); + let handle = DraftHandle::new("a-handle"); + assert_ne!( + derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, None), + derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, Some("")), + ); + // A concatenation-style collision across the handle/discriminator + // boundary: without a length prefix on the discriminator, "ab" + "" + // and "a" + "b" would hash identically. + assert_ne!( + derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("ab"), + Some(""), + ), + derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("a"), + Some("b"), + ), + ); + } + + /// The `PatchAdmitted` arm is not a trusting applier. A forged effect, a + /// replayed one and a non-owner caller each die inside `apply_effect`, + /// without the journal's reduce-equality check running. + #[test] + fn apply_effect_rejects_a_forged_stale_or_unauthorized_patch_effect() { + let kernel = draft_world(); + let patch = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + ), + ]); + let resolved = resolve_patch(&kernel.state, CommandId::issue(), &patch).unwrap(); + let honest = super::super::WorldEffect::PatchAdmitted { + resolved: resolved.clone(), + }; + + // Forged: the position names a place no partition holds, and the effect + // no longer carries the entity that would have created it. + let mut forged = resolved.clone(); + forged.entities.clear(); + forged.subjects[0].position = Some(Position { + place: super::super::EntityId::issue(), + }); + let mut candidate = kernel.state.clone(); + let forged_error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &super::super::WorldEffect::PatchAdmitted { + resolved: forged, + }, + ) + .unwrap_err(); + assert!(matches!(forged_error, KernelError::Invariant(_))); + + // Stale: the honest effect applied twice collides on its own IDs. + let mut candidate = kernel.state.clone(); + super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &honest, + ) + .unwrap(); + let stale_error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &honest, + ) + .unwrap_err(); + assert!(matches!(stale_error, KernelError::Invariant(_))); + + // A non-Play caller never reaches admission. + let mut candidate = kernel.state.clone(); + let unauthorized = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(human_principal()), + &honest, + ) + .unwrap_err(); + assert!(matches!(unauthorized, KernelError::Unauthorized)); + assert_eq!(candidate, kernel.state); + } + + /// Soul falsification: the three pass-2 `Mismatch` variants that no landed + /// test names are each reachable from a real patch. + #[test] + fn soul_self_loop_unplaced_subject_and_no_effect_are_each_reachable() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + + // A route whose two endpoints resolve to one place. + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(vec![ + entity("hollow", "The Hollow", EntityKind::Place), + route("noose", "The Noose", "hollow", "hollow", 4), + ])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::RouteSelfLoop { + referent: draft("noose") + }] + ); + + let topology = admit_topology(&mut kernel); + // Every fixture subject stands somewhere now, so the unplaced case is + // declared here rather than borrowed from a genesis accident. + let before = kernel.snapshot().unwrap(); + let speak = speak_entry(&kernel); + submit_play( + &mut kernel, + &before, + admit(patch_of(vec![Declaration::Subject(SubjectDeclaration { + handle: draft("nowhere"), + label: "The Unplaced".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak]), + position: None, + import_key: None, + })])), + ); + let active = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + let unplaced = *kernel + .state + .subjects + .iter() + .find(|(subject_id, _)| !kernel.state.positions.contains_key(*subject_id)) + .expect("the unplaced subject this test declared") + .0; + + // Relocating a subject that stands nowhere. + let error = kernel + .submit( + command( + &active, + CallerId::Play, + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(unplaced), + via: Ref::Existing(topology.ramp), + }])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![Mismatch::UnplacedSubject { operation: 0 }]); + + // Three operations that each change nothing: the ramp is already open, + // the shutter already closed, and the ramp already costs twelve. + let error = kernel + .submit( + command( + &active, + CallerId::Play, + admit(operations_of(vec![ + ComponentOp::OpenRoute { + route: Ref::Existing(topology.ramp), + }, + ComponentOp::CloseRoute { + route: Ref::Existing(topology.shutter), + }, + ComponentOp::AlterCost { + route: Ref::Existing(topology.ramp), + cost: Cost(12), + }, + ])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![ + Mismatch::NoOperationEffect { operation: 0 }, + Mismatch::NoOperationEffect { operation: 1 }, + Mismatch::NoOperationEffect { operation: 2 }, + ] + ); + assert_eq!(kernel.snapshot().unwrap(), active); + assert_eq!(kernel.journal.commit_count(), commits_before); + } + + /// Soul falsification: `admit_resolved` re-derives every relocate + /// precondition, so a forged effect naming a route the subject does not + /// stand on, a closed route, or a restricted one dies at apply time. + #[test] + fn soul_a_forged_relocate_effect_is_refused_at_apply_time() { + let mut kernel = draft_world(); + let topology = admit_topology(&mut kernel); + for edge_id in [topology.span, topology.shutter, topology.toll] { + let forged = super::super::WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![ResolvedOp::Relocate { + subject_id: topology.walker, + edge_id, + }], + evidence: Vec::new(), + }, + }; + let mut candidate = kernel.state.clone(); + let error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &forged, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + } +} diff --git a/native/aetherlight/src/patch/candidate.rs b/native/aetherlight/src/patch/candidate.rs new file mode 100644 index 000000000..1934f0048 --- /dev/null +++ b/native/aetherlight/src/patch/candidate.rs @@ -0,0 +1,1294 @@ +//! The candidate graph of one resolution: what the world holds plus what the +//! patch writes, without copying the world. +//! +//! Every candidate map is an [`Overlay`]: the committed partition read through a +//! base function, and the patch's own writes in a local map. Nothing here +//! iterates a committed partition; each scale-sensitive read is a named method +//! of [`Candidate`] whose cost is bounded by what the patch wrote plus what the +//! read returns, through the partitions' point reads and `indexed`. A +//! `Candidate` lives for one `resolve_patch` call and is never written back: +//! `admit_resolved` stays the only writer of the ontology partitions. + +use super::{ + AffordanceKindName, AudienceKey, AuthorityTargetKey, ChannelCandidate, CommitmentKey, + DependencyTarget, FactCandidate, GrantKey, GrievanceKindName, ImportKey, Key, + KnowledgeCandidate, KnowledgeSource, KnowledgeSourceKey, OfficeCandidate, OfficeName, + PressureSource, PressureSourceKey, Quantity, Reach, ReachKey, RouteCandidate, TargetKey, + grant_key_of, target_key_of, +}; +use crate::{AffordanceId, EdgeId, EntityId, SubjectId, WorldState}; +use std::collections::{BTreeMap, BTreeSet}; + +/// One committed partition seen through a patch: reads fall through to the +/// partition by point get, writes land in `local`, and a removal is a `None` +/// there. A `Key::Draft` key has no committed value, so its base is `None`. +pub(super) struct Overlay<'s, K: Ord + Clone, V: Clone> { + state: &'s WorldState, + base: fn(&WorldState, &K) -> Option, + local: BTreeMap>, +} + +impl<'s, K: Ord + Clone, V: Clone> Overlay<'s, K, V> { + fn new(state: &'s WorldState, base: fn(&WorldState, &K) -> Option) -> Self { + Self { state, base, local: BTreeMap::new() } + } + + pub(super) fn get(&self, key: &K) -> Option { + match self.local.get(key) { + Some(written) => written.clone(), + None => (self.base)(self.state, key), + } + } + + pub(super) fn contains_key(&self, key: &K) -> bool { + match self.local.get(key) { + Some(written) => written.is_some(), + None => (self.base)(self.state, key).is_some(), + } + } + + pub(super) fn insert(&mut self, key: K, value: V) { + self.local.insert(key, Some(value)); + } + + /// The value the key held, if any. + pub(super) fn remove(&mut self, key: &K) -> Option { + let held = self.get(key); + if held.is_some() { + self.local.insert(key.clone(), None); + } + held + } + + /// Copies the committed value into `local` on first mutable touch; a miss + /// writes nothing. + pub(super) fn get_mut(&mut self, key: &K) -> Option<&mut V> { + if !self.local.contains_key(key) { + let committed = (self.base)(self.state, key)?; + self.local.insert(key.clone(), Some(committed)); + } + self.local.get_mut(key)?.as_mut() + } + + /// The entries the patch has touched, removals as `None`. + pub(super) fn local(&self) -> &BTreeMap> { + &self.local + } +} + +fn existing(key: &Key) -> Option { + match key { + Key::Existing(id) => Some(*id), + Key::Draft(_) => None, + } +} + +fn target_of(key: &TargetKey) -> Option { + Some(match key { + TargetKey::Resource(id) => DependencyTarget::Resource(existing(id)?), + TargetKey::Route(id) => DependencyTarget::Route(existing(id)?), + TargetKey::Subject(id) => DependencyTarget::Subject(existing(id)?), + }) +} + +fn source_of(key: &PressureSourceKey) -> Option { + Some(match key { + PressureSourceKey::Commitment { subject, key } => { + PressureSource::Commitment { subject: existing(subject)?, key: *key } + } + PressureSourceKey::Dependency(target) => PressureSource::Dependency(target_of(target)?), + PressureSourceKey::Subject(subject) => PressureSource::Subject(existing(subject)?), + }) +} + +fn office_candidate(office: &crate::Office) -> OfficeCandidate { + OfficeCandidate { + incumbent: office.incumbent.map(Key::Existing), + delegated: office.delegated.clone(), + } +} + +fn base_container(state: &WorldState, key: &Key) -> Option> { + state.entities.get(&existing(key)?)?.container.map(Key::Existing) +} + +fn base_route(state: &WorldState, key: &Key) -> Option { + let record = state.edges.get(&existing(key)?)?; + let (from, to) = record.endpoints(); + Some(RouteCandidate { + from: Key::Existing(from), + to: Key::Existing(to), + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + }) +} + +fn base_position(state: &WorldState, key: &Key) -> Option> { + state.positions.get(&existing(key)?).map(|position| Key::Existing(position.place)) +} + +fn base_holding(state: &WorldState, key: &(Key, Key)) -> Option { + let (holder, resource) = (existing(&key.0)?, existing(&key.1)?); + state.holdings.get(&holder)?.get(&resource).copied() +} + +fn base_dependency(state: &WorldState, key: &(Key, TargetKey)) -> Option<()> { + let (subject, target) = (existing(&key.0)?, target_of(&key.1)?); + state.dependencies.get(&subject)?.contains(&target).then_some(()) +} + +fn base_grants(state: &WorldState, key: &Key) -> Option> { + state.authority.get(&existing(key)?).map(|grants| grants.iter().map(grant_key_of).collect()) +} + +fn base_office(state: &WorldState, key: &(Key, OfficeName)) -> Option { + state.selection.get(&existing(&key.0)?)?.get(&key.1).map(office_candidate) +} + +fn base_forum( + state: &WorldState, + key: &GrievanceKindName, +) -> Option<(Key, AuthorityTargetKey)> { + state + .redress + .get(key) + .map(|forum| (Key::Existing(forum.forum), target_key_of(forum.standing))) +} + +fn base_fact(state: &WorldState, key: &Key) -> Option { + state.facts.get(&existing(key)?).map(|record| match &record.standing { + crate::FactStanding::Canonical { .. } => FactCandidate::Canonical, + crate::FactStanding::Claimed { by } => FactCandidate::Claimed(Key::Existing(*by)), + crate::FactStanding::Ruled => FactCandidate::Ruled, + }) +} + +fn base_retired(state: &WorldState, key: &Key) -> Option<()> { + crate::is_retired(state, existing(key)?).then_some(()) +} + +fn base_affordances( + state: &WorldState, + key: &Key, +) -> Option>> { + state + .affordance_grants + .get(&existing(key)?) + .map(|granted| granted.iter().map(|id| Key::Existing(*id)).collect()) +} + +fn base_channel(state: &WorldState, key: &Key) -> Option { + state.channels.get(&existing(key)?).map(|record| ChannelCandidate { + reach: match &record.reach { + Reach::Subjects(members) => { + ReachKey::Subjects(members.iter().copied().map(Key::Existing).collect()) + } + Reach::Place(place) => ReachKey::Place(Key::Existing(*place)), + }, + controller: record.controller.map(Key::Existing), + }) +} + +fn base_knowledge( + state: &WorldState, + key: &(Key, Key), +) -> Option { + let (subject, fact) = (existing(&key.0)?, existing(&key.1)?); + state.knowledge.get(&(subject, fact)).map(|entry| KnowledgeCandidate { + confidence: entry.confidence, + source: match entry.source { + KnowledgeSource::Witnessed => KnowledgeSourceKey::Witnessed, + KnowledgeSource::Evidenced => KnowledgeSourceKey::Evidenced, + KnowledgeSource::Told { by, via } => KnowledgeSourceKey::Told { + by: Key::Existing(by), + via: via.map(Key::Existing), + }, + KnowledgeSource::Seen { by } => KnowledgeSourceKey::Seen { by: Key::Existing(by) }, + }, + }) +} + +fn base_commitment(state: &WorldState, key: &(Key, CommitmentKey)) -> Option<()> { + state.commitments.get(&existing(&key.0)?)?.contains_key(&key.1).then_some(()) +} + +fn base_pressure(state: &WorldState, key: &(Key, PressureSourceKey)) -> Option { + let (target, source) = (existing(&key.0)?, source_of(&key.1)?); + state.pressures.get(&target)?.get(&source).map(|magnitude| magnitude.0) +} + +/// The candidate graph: canonical topology plus everything this patch declares +/// and operates. Containment, endpoints, and preconditions all read it. +/// +/// `authority`, `selection` and `retired` are private: a write to any of them +/// goes through a method that re-judges the holders whose candidate effective +/// authority it can change, so `overlapping` is always the set of holders that +/// hold two grants of one kind over overlapping ground, exactly what a scan of +/// every holder would answer. That equality holds because the committed world is +/// disjoint (every commit checks it, and opening a world verifies it), so only +/// a holder the patch touched can enter the set. +pub(super) struct Candidate<'s> { + state: &'s WorldState, + pub(super) containers: Overlay<'s, Key, Key>, + pub(super) routes: Overlay<'s, Key, RouteCandidate>, + pub(super) positions: Overlay<'s, Key, Key>, + pub(super) holdings: Overlay<'s, (Key, Key), Quantity>, + pub(super) dependencies: Overlay<'s, (Key, TargetKey), ()>, + authority: Overlay<'s, Key, BTreeSet>, + selection: Overlay<'s, (Key, OfficeName), OfficeCandidate>, + pub(super) redress: Overlay<'s, GrievanceKindName, (Key, AuthorityTargetKey)>, + pub(super) facts: Overlay<'s, Key, FactCandidate>, + retired: Overlay<'s, Key, ()>, + pub(super) affordance_holdings: Overlay<'s, Key, BTreeSet>>, + pub(super) channels: Overlay<'s, Key, ChannelCandidate>, + pub(super) knowledge: Overlay<'s, (Key, Key), KnowledgeCandidate>, + pub(super) commitments: Overlay<'s, (Key, CommitmentKey), ()>, + pub(super) pressures: Overlay<'s, (Key, PressureSourceKey), u32>, + /// The affordance kinds this patch declares. + kinds: BTreeSet, + overlapping: BTreeSet>, +} + +impl<'s> Candidate<'s> { + pub(super) fn new(state: &'s WorldState) -> Self { + Self { + state, + containers: Overlay::new(state, base_container), + routes: Overlay::new(state, base_route), + positions: Overlay::new(state, base_position), + holdings: Overlay::new(state, base_holding), + dependencies: Overlay::new(state, base_dependency), + authority: Overlay::new(state, base_grants), + selection: Overlay::new(state, base_office), + redress: Overlay::new(state, base_forum), + facts: Overlay::new(state, base_fact), + retired: Overlay::new(state, base_retired), + affordance_holdings: Overlay::new(state, base_affordances), + channels: Overlay::new(state, base_channel), + knowledge: Overlay::new(state, base_knowledge), + commitments: Overlay::new(state, base_commitment), + pressures: Overlay::new(state, base_pressure), + kinds: BTreeSet::new(), + overlapping: BTreeSet::new(), + } + } + + // ---- Named reads ------------------------------------------------------- + + /// Whether the affordance kind is already named: by the catalog (its + /// `ByKind` index) or by this patch. + pub(super) fn kind_taken(&self, kind: &AffordanceKindName) -> bool { + self.kinds.contains(kind) || self.state.kind_taken(kind) + } + + /// Names a kind for this patch, reporting whether it was already taken. + pub(super) fn declare_kind(&mut self, kind: AffordanceKindName) -> bool { + let taken = self.kind_taken(&kind); + self.kinds.insert(kind); + taken + } + + /// Whether a subject in the world, retired or not, holds this import key + /// (the subjects' `ByImportKey` index). + pub(super) fn import_key_held(&self, key: &ImportKey) -> bool { + self.state.import_key_held(key) + } + + /// Every subject standing at or under a place: the committed subtree's + /// occupants (`under_place`) less every subject this patch gave a position + /// or took one from, plus the subjects whose written position the candidate + /// containment places under it. A written position can only be a draft + /// place's or a relocation's, so the committed subtree cannot hold it. + pub(super) fn occupants_under(&self, place: &Key) -> BTreeSet> { + let mut occupants: BTreeSet> = match place { + Key::Existing(root) => { + crate::under_place(self.state, *root).into_iter().map(Key::Existing).collect() + } + Key::Draft(_) => BTreeSet::new(), + }; + let written = self.positions.local(); + occupants.retain(|subject| !written.contains_key(subject)); + for (subject, standing) in written { + if let Some(standing) = standing + && self.covers(place, standing) + { + occupants.insert(subject.clone()); + } + } + occupants + } + + /// The offices of one institution: the committed row merged with the + /// patch's writes to its offices. + pub(super) fn offices_of( + &self, + institution: &Key, + ) -> BTreeMap { + let mut offices = BTreeMap::new(); + if let Some(id) = existing(institution) + && let Some(committed) = self.state.selection.get(&id) + { + offices.extend( + committed.iter().map(|(name, office)| (name.clone(), office_candidate(office))), + ); + } + let from = (institution.clone(), OfficeName(String::new())); + for ((held_by, name), written) in self.selection.local().range(from..) { + if held_by != institution { + break; + } + match written { + Some(office) => { + offices.insert(name.clone(), office.clone()); + } + None => { + offices.remove(name); + } + } + } + offices + } + + /// Every office a subject holds, by (institution, name): the committed + /// offices it holds (`ByIncumbent`) unless the patch rewrote them, plus the + /// written offices that name it. + pub(super) fn offices_held_by( + &self, + holder: &Key, + ) -> BTreeMap<(Key, OfficeName), OfficeCandidate> { + let mut held = BTreeMap::new(); + let written = self.selection.local(); + if let Some(id) = existing(holder) { + for (_, institution) in self.state.selection.indexed(id..=id) { + for (name, office) in &self.state.selection[&institution] { + let slot = (Key::Existing(institution), name.clone()); + if office.incumbent == Some(id) && !written.contains_key(&slot) { + held.insert(slot, office_candidate(office)); + } + } + } + } + for (slot, office) in written { + if let Some(office) = office + && office.incumbent.as_ref() == Some(holder) + { + held.insert(slot.clone(), office.clone()); + } + } + held + } + + /// What a resource's total was and is: the sum over the holders the patch + /// wrote, before and after. Every other holder is on both sides of the + /// equation and cancels. + pub(super) fn custody(&self, resource: &Key) -> (u128, u128) { + let (mut before, mut after) = (0u128, 0u128); + for ((holder, held), written) in self.holdings.local() { + if held != resource { + continue; + } + let committed = base_holding(self.state, &(holder.clone(), held.clone())); + before += committed.map_or(0, |quantity| u128::from(quantity.0)); + after += written.map_or(0, |quantity| u128::from(quantity.0)); + } + (before, after) + } + + /// Whether `place` is `root`, or reaches it through the candidate container + /// chain. The walk is bounded by the graph size, so a cycle that does not + /// include either end still terminates. + pub(super) fn covers(&self, root: &Key, place: &Key) -> bool { + let bound = self.state.entities.len() + self.containers.local().len(); + let mut current = Some(place.clone()); + for _ in 0..=bound { + match current { + None => return false, + Some(node) if node == *root => return true, + Some(node) => current = self.containers.get(&node), + } + } + false + } + + /// Whether a place reaches itself through its container chain: the same + /// walk, started one link up so a place is not its own ancestor by + /// definition. + pub(super) fn contains_itself(&self, start: &Key) -> bool { + self.containers.get(start).is_some_and(|parent| self.covers(start, &parent)) + } + + /// Whether two jurisdictions of one kind cover common ground. Structural on + /// purpose: identity for named subordinates, containment for territory, and + /// never across the two, so the answer cannot decay when a subject walks + /// somewhere. Containment is fixed at declaration, so every way of creating + /// an overlap is a checked operation. + fn targets_overlap(&self, left: &AuthorityTargetKey, right: &AuthorityTargetKey) -> bool { + match (left, right) { + (AuthorityTargetKey::Subject(one), AuthorityTargetKey::Subject(other)) => one == other, + (AuthorityTargetKey::PlaceSubtree(one), AuthorityTargetKey::PlaceSubtree(other)) => { + self.covers(one, other) || self.covers(other, one) + } + _ => false, + } + } + + // ---- Authority, offices and retirement ---------------------------------- + + pub(super) fn grants_of(&self, holder: &Key) -> BTreeSet { + self.authority.get(holder).unwrap_or_default() + } + + pub(super) fn office(&self, slot: &(Key, OfficeName)) -> Option { + self.selection.get(slot) + } + + pub(super) fn is_retired(&self, subject: &Key) -> bool { + self.retired.contains_key(subject) + } + + /// Own grants plus what every held office lends, over the candidate graph. + /// A retired institution lends nothing, the same predicate + /// `delegated_authority` reads canonically: `Retire` does not vacate + /// offices, so the resolver and the kernel must not disagree about whether + /// a dead institution's grants still reach its office-holders. + pub(super) fn effective_authority(&self, holder: &Key) -> BTreeSet { + let mut effective = self.grants_of(holder); + for ((institution, _), office) in self.offices_held_by(holder) { + if self.is_retired(&institution) { + continue; + } + for grant in self.grants_of(&institution) { + if office.delegated.contains(&grant.kind) { + effective.insert(grant); + } + } + } + effective + } + + /// Whether any holder in the candidate graph holds two grants of one kind + /// over overlapping ground, from any combination of direct grant and office + /// delegation. + pub(super) fn overlapping(&self) -> bool { + !self.overlapping.is_empty() + } + + /// Replaces a subject's own grants; an empty set removes the row. + pub(super) fn set_grants(&mut self, holder: Key, grants: BTreeSet) { + if grants.is_empty() { + self.authority.remove(&holder); + } else { + self.authority.insert(holder.clone(), grants); + } + // An institution's grants reach its office-holders. + let mut affected = self.incumbents_of(&holder); + affected.insert(holder); + self.rejudge(affected); + } + + /// Writes one office, or closes it (`None`). + pub(super) fn set_office( + &mut self, + slot: (Key, OfficeName), + office: Option, + ) { + let mut affected = BTreeSet::new(); + affected.extend(self.selection.get(&slot).and_then(|old| old.incumbent)); + affected.extend(office.iter().filter_map(|new| new.incumbent.clone())); + match office { + Some(office) => self.selection.insert(slot, office), + None => { + self.selection.remove(&slot); + } + } + self.rejudge(affected); + } + + /// Marks a subject retired. A retired institution lends nothing, so its + /// office-holders are judged again. + pub(super) fn retire(&mut self, subject: Key) { + self.retired.insert(subject.clone(), ()); + let affected = self.incumbents_of(&subject); + self.rejudge(affected); + } + + fn incumbents_of(&self, institution: &Key) -> BTreeSet> { + self.offices_of(institution).into_values().filter_map(|office| office.incumbent).collect() + } + + fn rejudge(&mut self, holders: BTreeSet>) { + for holder in holders { + let effective: Vec = self.effective_authority(&holder).into_iter().collect(); + let overlaps = effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind && self.targets_overlap(&one.over, &other.over) + }) + }); + if overlaps { + self.overlapping.insert(holder); + } else { + self.overlapping.remove(&holder); + } + } + } + + /// Whether `subject` stands in the audience, over the candidate graph: the + /// same question `audience()` answers over committed state, asked before + /// any ID is minted. A controller is inside its own channel's audience for + /// the purpose of speaking on it: the horn belongs to the temple. + pub(super) fn in_audience( + &self, + subject: &Key, + audience: &AudienceKey, + speaker: &Key, + ) -> bool { + match audience { + AudienceKey::Colocated => { + match (self.positions.get(speaker), self.positions.get(subject)) { + (Some(here), Some(there)) => here == there, + _ => false, + } + } + AudienceKey::Channel(channel) => { + let Some(record) = self.channels.get(channel) else { + return false; + }; + if record.controller.as_ref() == Some(subject) { + return true; + } + match &record.reach { + ReachKey::Subjects(members) => members.contains(subject), + ReachKey::Place(root) => self + .positions + .get(subject) + .is_some_and(|place| self.covers(root, &place)), + } + } + } + } +} + +/// The reference the overlays are measured against, in test builds only: the +/// candidate graph as it was before overlays, every partition copied into a map +/// and every read a scan of those maps. +#[cfg(test)] +pub(super) struct Materialized { + pub(super) containers: BTreeMap, Key>, + pub(super) routes: BTreeMap, RouteCandidate>, + pub(super) positions: BTreeMap, Key>, + pub(super) holdings: BTreeMap<(Key, Key), Quantity>, + pub(super) dependencies: BTreeSet<(Key, TargetKey)>, + pub(super) authority: BTreeMap, BTreeSet>, + pub(super) selection: BTreeMap<(Key, OfficeName), OfficeCandidate>, + pub(super) redress: BTreeMap, AuthorityTargetKey)>, + pub(super) facts: BTreeMap, FactCandidate>, + pub(super) retired: BTreeSet>, + pub(super) affordance_holdings: BTreeMap, BTreeSet>>, + pub(super) channels: BTreeMap, ChannelCandidate>, + pub(super) knowledge: BTreeMap<(Key, Key), KnowledgeCandidate>, + pub(super) commitments: BTreeSet<(Key, CommitmentKey)>, + pub(super) pressures: BTreeMap<(Key, PressureSourceKey), u32>, +} + +#[cfg(test)] +fn apply_written(map: &mut BTreeMap, local: &BTreeMap>) { + for (key, written) in local { + match written { + Some(value) => { + map.insert(key.clone(), value.clone()); + } + None => { + map.remove(key); + } + } + } +} + +#[cfg(test)] +fn apply_written_set(set: &mut BTreeSet, local: &BTreeMap>) { + for (key, written) in local { + if written.is_some() { + set.insert(key.clone()); + } else { + set.remove(key); + } + } +} + +#[cfg(test)] +impl Materialized { + /// The committed world copied whole: what the resolver seeded its candidate + /// maps with, moved here as the reference. + pub(super) fn seeded(state: &WorldState) -> Self { + let containers: BTreeMap, Key> = state + .entities + .iter() + .filter_map(|(entity_id, record)| { + record + .container + .map(|container| (Key::Existing(*entity_id), Key::Existing(container))) + }) + .collect(); + let routes: BTreeMap, RouteCandidate> = state + .edges + .iter() + .map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + ( + Key::Existing(*edge_id), + RouteCandidate { + from: Key::Existing(from), + to: Key::Existing(to), + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + }, + ) + }) + .collect(); + let positions: BTreeMap, Key> = state + .positions + .iter() + .map(|(subject_id, position)| (Key::Existing(*subject_id), Key::Existing(position.place))) + .collect(); + let holdings: BTreeMap<(Key, Key), Quantity> = state + .holdings + .iter() + .flat_map(|(subject_id, held)| { + held.iter().map(move |(entity_id, quantity)| { + ( + (Key::Existing(*subject_id), Key::Existing(*entity_id)), + *quantity, + ) + }) + }) + .collect(); + let dependencies: BTreeSet<(Key, TargetKey)> = state + .dependencies + .iter() + .flat_map(|(subject_id, bound)| { + bound.iter().map(move |target| { + ( + Key::Existing(*subject_id), + match target { + DependencyTarget::Resource(id) => TargetKey::Resource(Key::Existing(*id)), + DependencyTarget::Route(id) => TargetKey::Route(Key::Existing(*id)), + DependencyTarget::Subject(id) => TargetKey::Subject(Key::Existing(*id)), + }, + ) + }) + }) + .collect(); + let authority: BTreeMap, BTreeSet> = state + .authority + .iter() + .map(|(subject_id, grants)| { + ( + Key::Existing(*subject_id), + grants.iter().map(grant_key_of).collect(), + ) + }) + .collect(); + let selection: BTreeMap<(Key, OfficeName), OfficeCandidate> = state + .selection + .iter() + .flat_map(|(institution, offices)| { + offices.iter().map(move |(name, office)| { + ( + (Key::Existing(*institution), name.clone()), + OfficeCandidate { + incumbent: office.incumbent.map(Key::Existing), + delegated: office.delegated.clone(), + }, + ) + }) + }) + .collect(); + let redress: BTreeMap, AuthorityTargetKey)> = state + .redress + .iter() + .map(|(grievance, forum)| { + ( + grievance.clone(), + (Key::Existing(forum.forum), target_key_of(forum.standing)), + ) + }) + .collect(); + let facts: BTreeMap, FactCandidate> = state + .facts + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + match &record.standing { + crate::FactStanding::Canonical { .. } => FactCandidate::Canonical, + crate::FactStanding::Claimed { by } => FactCandidate::Claimed(Key::Existing(*by)), + crate::FactStanding::Ruled => FactCandidate::Ruled, + }, + ) + }) + .collect(); + // `Retire` and the affordance grant operations read and write these + // candidates. `retired` seeds from the committed subject rows: a declared subject is always + // fresh and unretired, so drafts start out of the set. `affordance_holdings` + // seeds from committed `affordance_grants` and is extended below for a + // subject this same patch declares. + let retired: BTreeSet> = state + .subjects + .keys() + .filter(|subject_id| crate::is_retired(state, **subject_id)) + .map(|subject_id| Key::Existing(*subject_id)) + .collect(); + let affordance_holdings: BTreeMap, BTreeSet>> = state + .affordance_grants + .iter() + .map(|(subject_id, granted)| { + ( + Key::Existing(*subject_id), + granted.iter().map(|id| Key::Existing(*id)).collect(), + ) + }) + .collect(); + let channels: BTreeMap, ChannelCandidate> = state + .channels + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + ChannelCandidate { + reach: match &record.reach { + Reach::Subjects(members) => { + ReachKey::Subjects(members.iter().copied().map(Key::Existing).collect()) + } + Reach::Place(place) => ReachKey::Place(Key::Existing(*place)), + }, + controller: record.controller.map(Key::Existing), + }, + ) + }) + .collect(); + // Keys and payload, so an `AcquireKnowledge` that changes nothing is + // `NoOperationEffect` before any ID is minted. `Witness` is modelled here + // too: its landing is a subtree of `positions`, both maps are candidate + // maps, and so the fan-out it will perform at apply is derivable now — a + // subject this patch relocated into the subtree counts, and a witness that + // reaches nobody is refused at resolve exactly as `apply_operation` + // refuses it. + // + // `Communicate` never enters, and the difference is not scale. A telling is + // an act whose occurrence does not depend on its reception: its empty + // fan-out is legal, so there is nothing for this map to refuse and no + // refusal for it to predict. A witnessed event is only its reception, so + // its landing is its legality. + // + // Neither operation can write `Told`. This map can represent a `Told` + // entry, but no `ComponentOp` can construct one: `AcquireKnowledge` takes + // an `AuthoredSource`, `Witness` takes no source at all, and neither type + // has a `Told` variant — + // `action::no_component_op_kind_lowers_to_a_told_knowledge_write` pins both + // lowering sites that could otherwise drift. If a future operation is ever + // given the power to write `Told` directly — bypassing `Communicate`'s own + // apply-time fan-out — it must model that fan-out into this candidate graph + // first, or `resolve_patch` will silently reason about a knowledge state + // the apply pass will not produce. + let knowledge: BTreeMap<(Key, Key), KnowledgeCandidate> = state + .knowledge + .iter() + .map(|((subject_id, fact), entry)| { + ( + (Key::Existing(*subject_id), Key::Existing(*fact)), + KnowledgeCandidate { + confidence: entry.confidence, + source: match entry.source { + KnowledgeSource::Witnessed => KnowledgeSourceKey::Witnessed, + KnowledgeSource::Evidenced => KnowledgeSourceKey::Evidenced, + KnowledgeSource::Told { by, via } => KnowledgeSourceKey::Told { + by: Key::Existing(by), + via: via.map(Key::Existing), + }, + KnowledgeSource::Seen { by } => KnowledgeSourceKey::Seen { + by: Key::Existing(by), + }, + }, + }, + ) + }) + .collect(); + // Presence is all a discharge asks, and a create cannot collide: the key is + // command-derived and the index is unique within one patch. + let commitments: BTreeSet<(Key, CommitmentKey)> = state + .commitments + .iter() + .flat_map(|(subject_id, held)| { + held.keys() + .map(move |key| (Key::Existing(*subject_id), *key)) + }) + .collect(); + let pressures: BTreeMap<(Key, PressureSourceKey), u32> = state + .pressures + .iter() + .flat_map(|(target, held)| { + held.iter().map(move |(source, magnitude)| { + ( + ( + Key::Existing(*target), + match source { + PressureSource::Commitment { subject, key } => { + PressureSourceKey::Commitment { + subject: Key::Existing(*subject), + key: *key, + } + } + PressureSource::Dependency(DependencyTarget::Resource(entity_id)) => { + PressureSourceKey::Dependency(TargetKey::Resource(Key::Existing( + *entity_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Route(edge_id)) => { + PressureSourceKey::Dependency(TargetKey::Route(Key::Existing( + *edge_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Subject(subject_id)) => { + PressureSourceKey::Dependency(TargetKey::Subject(Key::Existing( + *subject_id, + ))) + } + PressureSource::Subject(subject_id) => { + PressureSourceKey::Subject(Key::Existing(*subject_id)) + } + }, + ), + magnitude.0, + ) + }) + }) + .collect(); + Self { + containers, + routes, + positions, + holdings, + dependencies, + authority, + selection, + redress, + facts, + retired, + affordance_holdings, + channels, + knowledge, + commitments, + pressures, + } + } + + /// Whether `place` is `root`, or reaches it through the container chain. + pub(super) fn covers(&self, root: &Key, place: &Key) -> bool { + let mut current = Some(place); + for _ in 0..=self.containers.len() { + match current { + None => return false, + Some(node) if node == root => return true, + Some(node) => current = self.containers.get(node), + } + } + false + } + + fn targets_overlap(&self, left: &AuthorityTargetKey, right: &AuthorityTargetKey) -> bool { + match (left, right) { + (AuthorityTargetKey::Subject(one), AuthorityTargetKey::Subject(other)) => one == other, + (AuthorityTargetKey::PlaceSubtree(one), AuthorityTargetKey::PlaceSubtree(other)) => { + self.covers(one, other) || self.covers(other, one) + } + _ => false, + } + } + + /// Every subject whose position the container chain puts under `place`. + pub(super) fn occupants_under(&self, place: &Key) -> BTreeSet> { + self.positions + .iter() + .filter(|(_, standing)| self.covers(place, standing)) + .map(|(subject, _)| subject.clone()) + .collect() + } + + pub(super) fn offices_of( + &self, + institution: &Key, + ) -> BTreeMap { + self.selection + .iter() + .filter(|((held_by, _), _)| held_by == institution) + .map(|((_, name), office)| (name.clone(), office.clone())) + .collect() + } + + pub(super) fn offices_held_by( + &self, + holder: &Key, + ) -> BTreeMap<(Key, OfficeName), OfficeCandidate> { + self.selection + .iter() + .filter(|(_, office)| office.incumbent.as_ref() == Some(holder)) + .map(|(slot, office)| (slot.clone(), office.clone())) + .collect() + } + + /// Own grants plus what every held office lends, walking every office. + pub(super) fn effective_authority(&self, holder: &Key) -> BTreeSet { + let mut effective = self.authority.get(holder).cloned().unwrap_or_default(); + for ((institution, _), office) in &self.selection { + if office.incumbent.as_ref() != Some(holder) || self.retired.contains(institution) { + continue; + } + for grant in self.authority.get(institution).into_iter().flatten() { + if office.delegated.contains(&grant.kind) { + effective.insert(grant.clone()); + } + } + } + effective + } + + /// Every holder in the graph with two grants of one kind over overlapping + /// ground, from any combination of direct grant and office delegation. + pub(super) fn overlapping_holders(&self) -> BTreeSet> { + let holders: BTreeSet<&Key> = self + .authority + .keys() + .chain(self.selection.values().filter_map(|office| office.incumbent.as_ref())) + .collect(); + holders + .into_iter() + .filter(|holder| { + let effective: Vec = + self.effective_authority(holder).into_iter().collect(); + effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind && self.targets_overlap(&one.over, &other.over) + }) + }) + }) + .cloned() + .collect() + } + + /// What a resource's holders hold in all. + pub(super) fn total(&self, resource: &Key) -> u128 { + self.holdings + .iter() + .filter(|((_, held), _)| held == resource) + .map(|(_, quantity)| u128::from(quantity.0)) + .sum() + } +} + +#[cfg(test)] +impl Candidate<'_> { + /// Every candidate map, in full: the committed world with the patch's writes + /// applied. The named reads must equal scans of it. + pub(super) fn materialized(&self) -> Materialized { + let mut all = Materialized::seeded(self.state); + apply_written(&mut all.containers, self.containers.local()); + apply_written(&mut all.routes, self.routes.local()); + apply_written(&mut all.positions, self.positions.local()); + apply_written(&mut all.holdings, self.holdings.local()); + apply_written_set(&mut all.dependencies, self.dependencies.local()); + apply_written(&mut all.authority, self.authority.local()); + apply_written(&mut all.selection, self.selection.local()); + apply_written(&mut all.redress, self.redress.local()); + apply_written(&mut all.facts, self.facts.local()); + apply_written_set(&mut all.retired, self.retired.local()); + apply_written(&mut all.affordance_holdings, self.affordance_holdings.local()); + apply_written(&mut all.channels, self.channels.local()); + apply_written(&mut all.knowledge, self.knowledge.local()); + apply_written_set(&mut all.commitments, self.commitments.local()); + apply_written(&mut all.pressures, self.pressures.local()); + all + } + + /// The holders the running judgement holds as overlapping. + pub(super) fn overlapping_holders(&self) -> &BTreeSet> { + &self.overlapping + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::patch::DraftHandle; + use crate::tests::{ + BAILIFF_OFFICE, LEVY_KIND, WARDEN_OFFICE, auth_principal, authority_kind, civic_world, + creation, office, operations, owner, reject_play, + }; + use crate::{Mismatch, WorldKernel}; + + fn civic_kernel(title: &str) -> (WorldKernel, crate::tests::Topology, crate::tests::Civic) { + let (mut kernel, _) = WorldKernel::create(creation(title), &auth_principal(owner())).unwrap(); + let (topology, civic, _) = civic_world(&mut kernel); + (kernel, topology, civic) + } + + fn levy_over(place: Key) -> GrantKey { + GrantKey { kind: authority_kind(LEVY_KIND), over: AuthorityTargetKey::PlaceSubtree(place) } + } + + /// Every named read, asked of the overlay and of a scan of the materialized + /// maps, must agree. + fn agrees( + graph: &Candidate<'_>, + label: &str, + places: &[Key], + holders: &[Key], + resource: &Key, + ) { + let all = graph.materialized(); + for place in places { + assert_eq!(graph.occupants_under(place), all.occupants_under(place), "{label}: under {place:?}"); + } + for holder in holders { + assert_eq!(graph.offices_of(holder), all.offices_of(holder), "{label}: offices of {holder:?}"); + assert_eq!( + graph.offices_held_by(holder), + all.offices_held_by(holder), + "{label}: offices held by {holder:?}" + ); + assert_eq!( + graph.effective_authority(holder), + all.effective_authority(holder), + "{label}: authority of {holder:?}" + ); + } + let overlapping = all.overlapping_holders(); + assert_eq!(graph.overlapping_holders(), &overlapping, "{label}: who overlaps"); + assert_eq!(graph.overlapping(), !overlapping.is_empty(), "{label}: whether anyone overlaps"); + // The written holders' sums stand in for the totals: every other holder + // is on both sides, so the two differ by the same amount. + let (before, after) = graph.custody(resource); + let seeded = Materialized::seeded(graph.state).total(resource); + assert_eq!( + after as i128 - before as i128, + all.total(resource) as i128 - seeded as i128, + "{label}: custody" + ); + for kind in ["speak", "levy", "novel"] { + let kind = AffordanceKindName(kind.into()); + assert_eq!( + graph.kind_taken(&kind), + crate::kind_taken_by_scan(graph.state, &kind) || graph.kinds.contains(&kind), + "{label}: kind {kind:?}" + ); + } + } + + /// The patch walks the places the clockwork rules care about: a subject + /// leaving and entering a subtree, a declared place and a declared subject + /// in it, a retirement, a vacated and refilled office, a grant that + /// overlaps what an office lends and its revocation, the retirement of the + /// lending institution, a declared institution, and custody written both + /// ways. After every step each named read equals a scan of the maps the + /// patch would have copied. + #[test] + fn candidate_reads_equal_materialized_scans() { + let (kernel, topology, civic) = civic_kernel("Candidate"); + let state = &kernel.state; + let (hall, chamber, road) = + (Key::Existing(civic.hall), Key::Existing(civic.chamber), Key::Existing(topology.road)); + let (treasury, reeve, farmer, outsider) = ( + Key::Existing(civic.treasury), + Key::Existing(civic.reeve), + Key::Existing(civic.farmer), + Key::Existing(civic.outsider), + ); + let grain = Key::Existing(civic.grain); + let annex: Key = Key::Draft(DraftHandle::new("annex")); + let scribe: Key = Key::Draft(DraftHandle::new("scribe")); + let ministry: Key = Key::Draft(DraftHandle::new("ministry")); + let places = [hall.clone(), chamber.clone(), road.clone(), annex.clone()]; + let holders = + [treasury.clone(), reeve.clone(), farmer.clone(), outsider.clone(), scribe.clone(), ministry.clone()]; + let check = |graph: &Candidate<'_>, label: &str| agrees(graph, label, &places, &holders, &grain); + + let mut graph = Candidate::new(state); + check(&graph, "untouched"); + assert!(!graph.overlapping() && graph.offices_held_by(&reeve).len() == 1); + assert_eq!( + graph.occupants_under(&hall).len(), + 3, + "the treasury, the reeve and the farmer stand under the hall" + ); + + graph.positions.insert(farmer.clone(), road.clone()); + check(&graph, "a subject leaves the subtree"); + assert!(!graph.occupants_under(&hall).contains(&farmer)); + + graph.positions.insert(outsider.clone(), chamber.clone()); + check(&graph, "a subject enters the subtree"); + assert!(graph.occupants_under(&hall).contains(&outsider)); + + graph.containers.insert(annex.clone(), chamber.clone()); + graph.positions.insert(scribe.clone(), annex.clone()); + check(&graph, "a declared place holds a declared subject"); + assert!(graph.occupants_under(&hall).contains(&scribe)); + assert_eq!(graph.occupants_under(&annex), BTreeSet::from([scribe.clone()])); + + graph.retire(farmer.clone()); + graph.positions.remove(&farmer); + check(&graph, "a subject is retired"); + assert!(!graph.occupants_under(&road).contains(&farmer)); + + let warden = (treasury.clone(), office(WARDEN_OFFICE)); + let seat = graph.office(&warden).expect("the treasury opens a warden office"); + graph.set_office(warden.clone(), Some(OfficeCandidate { incumbent: None, ..seat.clone() })); + check(&graph, "the warden office is vacated"); + assert!(graph.offices_held_by(&reeve).is_empty()); + graph.set_office(warden.clone(), Some(OfficeCandidate { incumbent: Some(outsider.clone()), ..seat })); + check(&graph, "the warden office is refilled"); + assert_eq!(graph.offices_held_by(&outsider).len(), 1); + assert_eq!(graph.offices_of(&treasury).len(), 2); + + // The outsider now holds levy over the hall through the office; a levy + // over the chamber of their own overlaps it. + graph.set_grants(outsider.clone(), BTreeSet::from([levy_over(chamber.clone())])); + check(&graph, "an overlapping grant"); + assert_eq!(graph.overlapping_holders(), &BTreeSet::from([outsider.clone()])); + graph.set_grants(outsider.clone(), BTreeSet::new()); + check(&graph, "the grant is revoked"); + assert!(!graph.overlapping()); + graph.set_grants(outsider.clone(), BTreeSet::from([levy_over(chamber.clone())])); + assert!(graph.overlapping()); + graph.retire(treasury.clone()); + check(&graph, "the lending institution is retired"); + assert!(!graph.overlapping(), "a retired institution lends nothing"); + + // A declared institution lends a declared place to a declared subject. + graph.set_grants(ministry.clone(), BTreeSet::from([levy_over(annex.clone())])); + let seat = (ministry.clone(), office("reeve")); + graph.set_office( + seat.clone(), + Some(OfficeCandidate { + incumbent: Some(scribe.clone()), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }), + ); + check(&graph, "a declared institution seats a declared subject"); + assert_eq!(graph.effective_authority(&scribe), BTreeSet::from([levy_over(annex.clone())])); + graph.set_grants(scribe.clone(), BTreeSet::from([levy_over(chamber.clone())])); + check(&graph, "the declared subject's own grant covers the lent place"); + assert_eq!(graph.overlapping_holders(), &BTreeSet::from([scribe.clone()])); + graph.set_office(seat, None); + check(&graph, "the office is closed"); + assert!(!graph.overlapping()); + + // Custody, written both ways: the farmer's grain goes, the scribe's comes. + graph.holdings.insert((farmer.clone(), grain.clone()), Quantity(2)); + graph.holdings.insert((scribe.clone(), grain.clone()), Quantity(5)); + graph.holdings.remove(&(outsider.clone(), grain.clone())); + check(&graph, "custody is rewritten"); + assert_eq!(graph.custody(&grain), (14, 7), "two of seven, five of none, and none of seven"); + + assert!(!graph.declare_kind(AffordanceKindName("novel".into()))); + assert!(graph.declare_kind(AffordanceKindName("novel".into())), "a kind is named once"); + assert!(graph.declare_kind(AffordanceKindName("speak".into())), "the catalog names speak"); + check(&graph, "kinds"); + } + + /// An overlay nobody has written reads exactly the partition the old seeding + /// copied, key for key, in every world that holds a document in some + /// partition; and a draft key, or an id nothing holds, reads as absent. + #[test] + fn an_untouched_overlay_reads_what_the_seeding_copied() { + let worlds = crate::golden_tests::populated_worlds(); + for state in &worlds { + let graph = Candidate::new(state); + let all = Materialized::seeded(state); + macro_rules! same { + ($($map:ident),*) => {$( + for (key, value) in &all.$map { + assert_eq!( + format!("{:?}", graph.$map.get(key)), + format!("{:?}", Some(value)), + stringify!($map) + ); + } + )*}; + } + macro_rules! same_set { + ($($map:ident),*) => {$( + for key in &all.$map { + assert!(graph.$map.contains_key(key), stringify!($map)); + } + )*}; + } + same!(containers, routes, positions, holdings, redress, facts, affordance_holdings, channels, knowledge, pressures); + same_set!(dependencies, commitments); + for (key, value) in &all.authority { + assert_eq!(&graph.grants_of(key), value); + } + for (slot, value) in &all.selection { + assert_eq!(graph.office(slot).as_ref(), Some(value)); + } + for key in &all.retired { + assert!(graph.is_retired(key)); + } + let nobody: Key = Key::Existing(SubjectId::issue()); + let nowhere: Key = Key::Existing(EntityId::issue()); + let drafted: Key = Key::Draft(DraftHandle::new("drafted")); + assert!(graph.positions.get(&nobody).is_none() && graph.positions.get(&drafted).is_none()); + assert!(graph.containers.get(&nowhere).is_none()); + assert!(graph.grants_of(&nobody).is_empty() && !graph.is_retired(&drafted)); + assert!(graph.office(&(nobody, office(WARDEN_OFFICE))).is_none()); + assert!(graph.occupants_under(&nowhere).is_empty()); + assert_eq!(graph.effective_authority(&drafted), BTreeSet::new()); + } + } + + /// The first overlap of a patch is named at the operation that made it, and + /// every later widening operation is named too while it stands; a revoke + /// that clears it makes the later widening operation clean. + #[test] + fn overlap_mismatches_are_unchanged() { + let (mut kernel, _, civic) = civic_kernel("Overlaps"); + let snapshot = kernel.snapshot().unwrap(); + let grant = |holder: SubjectId| crate::ComponentOp::GrantAuthority { + holder: crate::Ref::Existing(holder), + grant: crate::AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: crate::AuthorityTargetRef::PlaceSubtree(crate::Ref::Existing(civic.chamber)), + }, + }; + let revoke = |holder: SubjectId| match grant(holder) { + crate::ComponentOp::GrantAuthority { holder, grant } => { + crate::ComponentOp::RevokeAuthority { holder, grant } + } + other => other, + }; + let seat = crate::ComponentOp::InstallIncumbent { + institution: crate::Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: crate::Ref::Existing(civic.farmer), + }; + let at = |operation: usize| Mismatch::OverlappingJurisdiction { operation }; + + // The reeve holds the warden's levy over the hall, so a levy over the + // chamber of the reeve's own overlaps it, and the seating that follows + // still sees an overlap standing. + let both = reject_play( + &mut kernel, + &snapshot, + operations(vec![grant(civic.reeve), seat.clone()]), + ); + assert_eq!(both, vec![at(0), at(1)]); + + let cleared = reject_play( + &mut kernel, + &snapshot, + operations(vec![grant(civic.reeve), revoke(civic.reeve), seat]), + ); + assert_eq!(cleared, vec![at(0)]); + } +} diff --git a/native/aetherlight/src/views.rs b/native/aetherlight/src/views.rs new file mode 100644 index 000000000..ac3de4a3d --- /dev/null +++ b/native/aetherlight/src/views.rs @@ -0,0 +1,230 @@ +//! Cross-partition views: what a read needs that no one partition's index can +//! answer. +//! +//! A `Docs` projection is a pure function of one document. Two questions the +//! clock asks are joins: "is this dependency failing" reads dependencies with +//! edges, holdings and positions (two of its arms are anti-joins: a resource +//! not held, a subject not placed), and "is this due commitment live" reads +//! commitments with `subjects.retired`. [`Views`] answers them as state derived +//! from those partitions' change lists, so a tick reads the work due and the +//! rows failing instead of every dependency or every dead pledge in the world. +//! +//! `Views` is derived, never state: not digested, not encoded, never exported, +//! and ignored by `WorldState`'s equality (its `PartialEq` is always true, as a +//! `Docs` index is ignored). The one writer is [`Views::fold`], called by +//! `WorldState::finish` from the open logs before they close, so replay (genesis +//! and every replayed commit close through `finish`) rebuilds it on open and a +//! rollback has nothing to undo: the view never saw the transaction. It is read +//! only with clean logs, which `derive_motion` asserts. + +use super::clock::dependency_unavailable; +#[cfg(test)] +use super::docs; +use super::patch::DependencyTarget; +use super::{EntityId, FictionalMinutes, SubjectId, WorldState, is_retired}; +use std::collections::{BTreeMap, BTreeSet}; +use uuid::Uuid; + +#[derive(Clone, Debug, Default)] +pub(crate) struct Views { + /// When live subjects' commitments fall due: a point for each distinct + /// due, holding the subjects that have a commitment due then. A retired + /// subject has no point. + live_due: BTreeMap>, + /// The (dependent, target) pairs failing a live dependent: a closed route, + /// a resource the dependent does not hold, a subject nobody places. + failing: BTreeSet<(SubjectId, DependencyTarget)>, +} + +/// A view is derived and carries no content of its own, so two worlds with the +/// same documents are equal whatever their views hold. +impl PartialEq for Views { + fn eq(&self, _: &Self) -> bool { + true + } +} + +impl Eq for Views {} + +/// Whether the six partitions the views read have no open log: the only time a +/// view is true. +pub(crate) fn readable(state: &WorldState) -> bool { + state.commitments.is_clean() + && state.subjects.is_clean() + && state.dependencies.is_clean() + && state.edges.is_clean() + && state.holdings.is_clean() + && state.positions.is_clean() +} + +impl Views { + /// Subjects with a live commitment due at or before `to`. + pub(crate) fn due_by(&self, to: FictionalMinutes) -> BTreeSet { + #[cfg(test)] + docs::count_rows(self.live_due.range(..=to).map(|(_, held)| held.len() as u64).sum()); + self.live_due + .range(..=to) + .flat_map(|(_, held)| held.iter().copied()) + .collect() + } + + /// Every failing (dependent, target), in order. + pub(crate) fn failing(&self) -> impl Iterator { + #[cfg(test)] + docs::count_rows(self.failing.len() as u64); + self.failing.iter() + } + + /// Brings the views up to the open logs of the six partitions. Called by + /// `WorldState::finish` before the logs close; nothing else writes a view. + pub(crate) fn fold(&mut self, state: &WorldState) { + // Dues. A subject whose commitments or retirement changed loses the + // points its commitments held before and regains them if it is live. + let mut before: BTreeMap> = BTreeMap::new(); + for (subject, old, _) in state.commitments.changes() { + before.insert(*subject, old); + } + for (subject, _, _) in state.subjects.changes() { + before.entry(*subject).or_insert_with(|| state.commitments.get(subject)); + } + for (subject, old) in &before { + for commitment in old.into_iter().flat_map(|held| held.values()) { + if let Some(due) = self.live_due.get_mut(&commitment.due) { + due.remove(subject); + if due.is_empty() { + self.live_due.remove(&commitment.due); + } + } + } + if is_retired(state, *subject) { + continue; + } + for commitment in state.commitments.get(subject).into_iter().flat_map(|held| held.values()) { + self.live_due.entry(commitment.due).or_default().insert(*subject); + } + } + + // Failing dependencies. A subject whose dependencies, holdings or + // retirement changed has every row re-judged; a route or a placement + // that changed re-judges its dependents. + let rejudged: BTreeSet = state + .dependencies + .changes() + .map(|(subject, _, _)| *subject) + .chain(state.holdings.changes().map(|(subject, _, _)| *subject)) + .chain(state.subjects.changes().map(|(subject, _, _)| *subject)) + .collect(); + for subject in &rejudged { + let rows: Vec<_> = self + .failing + .range( + (*subject, DependencyTarget::Resource(EntityId(Uuid::nil()))) + ..=(*subject, DependencyTarget::Subject(SubjectId(Uuid::max()))), + ) + .copied() + .collect(); + for row in rows { + self.failing.remove(&row); + } + if is_retired(state, *subject) { + continue; + } + for target in state.dependencies.get(subject).into_iter().flatten() { + if dependency_unavailable(state, *subject, *target) { + self.failing.insert((*subject, *target)); + } + } + } + let moved: BTreeSet = state + .edges + .changes() + .map(|(edge, _, _)| DependencyTarget::Route(*edge)) + .chain(state.positions.changes().map(|(subject, _, _)| DependencyTarget::Subject(*subject))) + .collect(); + // A changed dependencies key is already in `rejudged`, so the dependents + // left to judge are the unchanged ones, which the committed index names + // without walking the log once per target. + for target in moved { + for (_, dependent) in state.dependencies.indexed_unchanged(target..=target) { + if rejudged.contains(&dependent) { + continue; + } + let row = (dependent, target); + if !is_retired(state, dependent) && dependency_unavailable(state, dependent, target) { + self.failing.insert(row); + } else { + self.failing.remove(&row); + } + } + } + } +} + +/// The views as a scan of the committed documents derives them, and the +/// oracle's other tools (test builds). +#[cfg(test)] +impl Views { + pub(crate) fn rebuild(state: &WorldState) -> Self { + let mut views = Self::default(); + for (subject, held) in state.commitments.iter() { + if is_retired(state, *subject) { + continue; + } + for commitment in held.values() { + views.live_due.entry(commitment.due).or_default().insert(*subject); + } + } + for (subject, targets) in state.dependencies.iter() { + if is_retired(state, *subject) { + continue; + } + for target in targets { + if dependency_unavailable(state, *subject, *target) { + views.failing.insert((*subject, *target)); + } + } + } + views + } + + /// Content equality, which `PartialEq` deliberately is not. + pub(crate) fn same_as(&self, other: &Self) -> bool { + self.live_due == other.live_due && self.failing == other.failing + } + + /// Damages the view in one place: a stray failing row, else a missing + /// due point (the latest, which only its own subjects sit at). False when there + /// is nothing to damage that way. + pub(crate) fn corrupt_for_test(&mut self, stray: bool) -> bool { + if stray { + let row = (SubjectId(Uuid::from_u128(1)), DependencyTarget::Subject(SubjectId(Uuid::from_u128(2)))); + return self.failing.insert(row); + } + let Some(due) = self.live_due.keys().next_back().copied() else { + return false; + }; + self.live_due.remove(&due); + true + } + + /// The subjects with a dependency on `target`, by a scan of every row. + pub(crate) fn dependents_by_scan(state: &WorldState, target: DependencyTarget) -> Vec { + state + .dependencies + .iter() + .filter(|(_, held)| held.contains(&target)) + .map(|(subject, _)| *subject) + .collect() + } + + /// The subjects with a dependency on `target`, from the dependencies + /// partition's `DependsOn` index (true mid-transaction). + pub(crate) fn dependents_of(state: &WorldState, target: DependencyTarget) -> Vec { + state + .dependencies + .indexed(target..=target) + .into_iter() + .map(|(_, subject)| subject) + .collect() + } +} diff --git a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs index dfdb9d040..8381d325d 100644 --- a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs +++ b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs @@ -104,6 +104,27 @@ public sealed partial class RunStartTests Assert.Equal(LoadoutGenerator.AmmunitionCrates, weapon.Reserve); } + // A ship summoned into a running zone is stocked like one a run start stages: a fed fit carries the crates its weapon draws, + // and one whose scenario authored its cargo keeps exactly that. Kills: Summon skipping StockUnauthoredAmmunition. + [Fact] + public void ASummonedFedShipCarriesItsCrates() + { + var (hull, slots) = FedFit(bay: true); + var (_, arena, staged, failures) = Launch(new Scripted(false, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0))), Inputs(() => GalaxySeed)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + + var summoned = ZoneStage.Summon(_items, arena, stage => + { + stage.Place(stage.Fit(hull, slots), float2(300, 0)); + var authored = stage.Place(stage.Fit(hull, slots), float2(-300, 0)); + stage.Cargo(authored); + }, failures); + + Assert.True(failures.Count == 0, string.Join("; ", failures)); + Assert.Equal(LoadoutGenerator.AmmunitionCrates, Assert.Single(summoned[0].Weapons).Reserve); + Assert.Equal(0, Assert.Single(summoned[1].Weapons).Reserve); + } + // The Loadout path with the DEFAULT stocking argument (what the boss in ZoneGenerator and the console `fly` call): a ship built from a // Loadout holds the crates its fed weapon draws, and one whose only weapon draws nothing holds none. Kills: Materialize // dropping its default StockAmmunition (every Loadout-built armed ship fires one magazine). diff --git a/tests/Aetheria.Shared.Tests/BootedCatalogReadToolsTests.cs b/tests/Aetheria.Shared.Tests/BootedCatalogReadToolsTests.cs new file mode 100644 index 000000000..6c9aef1f3 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/BootedCatalogReadToolsTests.cs @@ -0,0 +1,120 @@ +using System; +using System.IO; +using Xunit; + +// Every AetherDb read tool answers for the catalog the game boots (campaign aetheria-living-world, follow-up aetherdb-booted-catalog): +// the shipped GameData/Aetheria.cc with the first-party packages in GameData/Mods composed, through the one AetherDb.ComposeBooted. +// The station hulls besides Zenith are packages', so a tool that opened the shipped file alone answered wrong with exit 0. +[Collection("process working directory")] +public sealed class BootedCatalogReadToolsTests : IDisposable +{ + private readonly string _previous = Environment.CurrentDirectory; + private readonly TempDirectory _broken = new TempDirectory(); + private readonly string _repo = AetherDb.FindRoot(); + + public void Dispose() + { + Environment.CurrentDirectory = _previous; + _broken.Dispose(); + } + + // The Seized Refinery's hull, read from its package: a hull the shipped catalog does not hold. + private string SeizedRefineryHull() + { + var (hull, _, _) = ShipAuthoringStore.Load(Path.Combine(_repo, "GameData", "Mods", "aetheria.seized-refinery", "ship.cc")); + return hull.Name; + } + + private string Run(params string[] args) + { + Environment.CurrentDirectory = _repo; + // The exit code counts the tool's own findings (loadout's hulls with no loadout), not whether it ran; the answer is the text. + return ConsoleProbe.WrittenBy(() => Program.Main(args)); + } + + // A game folder with the shipped catalog and one package the compose refuses. + private string BrokenRoot() + { + Directory.CreateDirectory(Path.Combine(_broken.Path, "GameData", "Mods", "mod.broken")); + File.Copy(Path.Combine(_repo, "GameData", "Aetheria.cc"), Path.Combine(_broken.Path, "GameData", "Aetheria.cc")); + File.WriteAllBytes(Path.Combine(_broken.Path, "GameData", "Mods", "mod.broken", "ship.cc"), new byte[] { 1, 2, 3 }); + // The save viewer returns early without a run store, so the fixture holds one; the compose throws before it is read. + File.WriteAllBytes(Path.Combine(_broken.Path, "GameData", "run.cc"), Array.Empty()); + return _broken.Path; + } + + // Zenith, plus the Pirates' and Zhestokost's package hulls: three station hulls, not the shipped one. + [Fact] + public void CensusCountsThePackageStationHulls() => Assert.Matches(@"Hull/Station\s+3\b", Run("census")); + + [Fact] + public void StationFitChecksThePackageHulls() + { + var output = Run("station-fit"); + Assert.Contains("Arsenal Depot:", output); + Assert.Contains(SeizedRefineryHull() + ":", output); + } + + [Fact] + public void LoadoutListsThePackageStationHulls() + { + var output = Run("loadout", "2"); + Assert.Contains("Arsenal Depot", output); + Assert.Contains(SeizedRefineryHull(), output); + } + + // economy report and economy balance print no hull, so the pin is the compose itself: a package the game would skip is a throw + // that names it, and only a tool that composes the packages can throw it. The same holds for every other read tool. + [Theory] + [InlineData("census")] + [InlineData("station-fit")] + [InlineData("loadout", "2")] + [InlineData("hardpoint-fit")] + [InlineData("factions")] + [InlineData("weapon-ammo")] + [InlineData("save")] + [InlineData("economy", "report")] + [InlineData("economy", "balance")] + public void AReadToolThrowsNamingAnExcludedPackage(params string[] args) + { + Environment.CurrentDirectory = BrokenRoot(); + var error = Assert.Throws(() => ConsoleProbe.WrittenBy(() => Program.Main(args))); + Assert.Contains("mod.broken", error.Message); + } + + // A read tool's composed scratch (aetherdb-mods-*) is removed when the tool returns or throws. This class runs alone (its collection + // disables parallelization), so no other test is making one meanwhile. + [Theory] + [InlineData("census")] + [InlineData("station-fit")] + [InlineData("loadout", "2")] + [InlineData("hardpoint-fit")] + [InlineData("factions")] + [InlineData("weapon-ammo")] + [InlineData("economy", "report")] + public void AReadToolLeavesNoScratchBehind(params string[] args) + { + var before = Scratches(); + Run(args); + Assert.Equal(before, Scratches()); + } + + [Fact] + public void TheSaveViewerLeavesNoScratchBehindWhenItThrows() + { + var before = Scratches(); + Environment.CurrentDirectory = BrokenRoot(); + Assert.Throws(() => ConsoleProbe.WrittenBy(() => Program.Main(new[] { "save" }))); + Assert.Equal(before, Scratches()); + } + + private static string[] Scratches() => Directory.GetDirectories(Path.GetTempPath(), "aetherdb-mods-*"); + + [Fact] + public void ComposeBootedThrowsNamingAnExcludedPackage() + { + var scratch = Directory.CreateDirectory(Path.Combine(_broken.Path, "scratch")).FullName; + var error = Assert.Throws(() => AetherDb.ComposeBooted(BrokenRoot(), scratch)); + Assert.Contains("mod.broken", error.Message); + } +} diff --git a/tests/Aetheria.Shared.Tests/CatalogResaveTests.cs b/tests/Aetheria.Shared.Tests/CatalogResaveTests.cs new file mode 100644 index 000000000..df520f5fa --- /dev/null +++ b/tests/Aetheria.Shared.Tests/CatalogResaveTests.cs @@ -0,0 +1,87 @@ +using System; +using System.IO; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using Xunit; + +// AetherDb catalog resave (follow-up aetherdb-catalog-resave): a record stored under an older schema id is re-saved under the +// current one, a dry run writes nothing, and a second apply writes nothing. The fixture tests/fixtures/catalog-resave/probe-v1.cc +// holds two records of schema aetheria.test.resaveprobe as written by a type with one member; Probe appends a second, which is +// how a real schema change restamps a record. +public sealed class CatalogResaveTests : IDisposable +{ + [MessagePackObject] + [CultDocument("aetheria.test.resaveprobe", "1")] + public sealed class Probe + { + [Key(0)] public string Name = ""; + [Key(1)] public int Appended = 7; + } + + private readonly TempDirectory _directory = new TempDirectory(); + private string Stored => System.IO.Path.Combine(_directory.Path, "probe.cc"); + + public CatalogResaveTests() => + File.Copy(System.IO.Path.Combine(RunStartTests.FindRepoRoot(), "tests", "fixtures", "catalog-resave", "probe-v1.cc"), Stored); + + public void Dispose() => _directory.Dispose(); + + private CultCache Open() + { + var cache = new CultCache(CultDocumentRegistry.ForTypes(new[] { typeof(Probe) })); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(Stored), new[] { typeof(Probe) }); + return cache; + } + + private string[] StoredIds() => + CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(Stored)).Records.Select(r => r.SchemaId).ToArray(); + + [Fact] + public void ADryRunListsAndWritesNothing() + { + var before = File.ReadAllBytes(Stored); + using (var cache = Open()) + { + var output = new StringWriter(); + Assert.Equal(0, CatalogResaveCommand.Run(cache, apply: false, output)); + Assert.Contains("2 record(s) would be re-saved", output.ToString()); + } + Assert.Equal(before, File.ReadAllBytes(Stored)); + } + + [Fact] + public void ApplyRestampsEveryRecordAndASecondApplyWritesNothing() + { + var oldIds = StoredIds(); + using (var cache = Open()) + Assert.Equal(0, CatalogResaveCommand.Run(cache, apply: true, new StringWriter())); + var newIds = StoredIds(); + Assert.Equal(2, newIds.Length); + Assert.All(newIds, id => Assert.DoesNotContain(id, oldIds)); + var written = File.ReadAllBytes(Stored); + + using (var cache = Open()) + { + Assert.Equal(new[] { "a", "b" }, cache.GetAll().Select(p => p.Name).OrderBy(n => n)); + Assert.All(cache.GetAll(), p => Assert.Equal(7, p.Appended)); + var output = new StringWriter(); + Assert.Equal(0, CatalogResaveCommand.Run(cache, apply: true, output)); + Assert.Contains("0 record(s) would be re-saved", output.ToString()); + } + Assert.Equal(written, File.ReadAllBytes(Stored)); + } + + // The catalog the game ships is current: resaving it changes nothing. + [Fact] + public void TheShippedCatalogIsAlreadyCurrent() + { + var copy = System.IO.Path.Combine(_directory.Path, "Aetheria.cc"); + File.Copy(System.IO.Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Aetheria.cc"), copy); + using var cache = AetheriaStores.Open(copy, catalogWritable: true, registry: TestCatalog.Registry()); + var output = new StringWriter(); + Assert.Equal(0, CatalogResaveCommand.Run(cache, apply: true, output)); + Assert.Contains("0 record(s) would be re-saved", output.ToString()); + } +} diff --git a/tests/Aetheria.Shared.Tests/CatalogRoleTests.cs b/tests/Aetheria.Shared.Tests/CatalogRoleTests.cs index 10056b421..ce181f03e 100644 --- a/tests/Aetheria.Shared.Tests/CatalogRoleTests.cs +++ b/tests/Aetheria.Shared.Tests/CatalogRoleTests.cs @@ -219,10 +219,10 @@ public sealed class CatalogRoleTests string[] Roles(EquippableItemData d) => d.Roles.Select(r => r.Name).OrderBy(r => r, StringComparer.Ordinal).ToArray(); var autocannon = Design("Autocannon"); - Assert.Equal(new[] { "barrel", "feed mechanism" }, Roles(autocannon)); - AssertRange(autocannon, "Damage", false, "barrel"); - AssertRange(autocannon, "Range", false, "barrel"); - AssertRange(autocannon, "Penetration", false, "barrel"); + Assert.Equal(new[] { "feed mechanism", "lined barrel" }, Roles(autocannon)); + AssertRange(autocannon, "Damage", false, "lined barrel"); + AssertRange(autocannon, "Range", false, "lined barrel"); + AssertRange(autocannon, "Penetration", false, "lined barrel"); var lrm = Design("Long-Range Missile Rack"); Assert.Equal(new[] { "guidance system", "thruster", "warhead" }, Roles(lrm)); @@ -256,7 +256,7 @@ public sealed class CatalogRoleTests // Designs whose non-flat stats named no role are pointed at the role their kind's map gives them. AssertNamed(Design("Cluster Cannon"), "Count", "feed mechanism"); - AssertNamed(Design("Flak Gun"), "Count", "feed mechanism"); + AssertNamed(Design("Flak Gun"), "Count", "tracking feed"); AssertNamed(Design("Guided Missile Launcher"), "MinRange", "guidance system"); AssertNamed(Design("Lightning Projector"), "DamageSpread", "focusing array"); AssertNamed(Design("Muon Fusion Reactor"), "Modifier", "core"); diff --git a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs index ccf3fae29..17255e703 100644 --- a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs +++ b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs @@ -40,10 +40,9 @@ public sealed class ChildrenWithinReachTests : IClassFixture("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); var planetSettings = authored.Read("PlanetSettings"); foreach (var galaxyZone in galaxy.Zones) @@ -51,7 +50,7 @@ public sealed class ChildrenWithinReachTests : IClassFixture("ZoneSettings"); tune?.Invoke(Settings); var pack = ZoneGenerator.GenerateZone(items, Settings, planetSettings, galaxy, galaxyZone, - galaxyZone == galaxy.Entrance && galaxy.IsPrelude, false); + EntranceStationOrder.Any, false); foreach (var belt in pack.Planets.Select(cache.Get).OfType()) { Belts++; diff --git a/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs b/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs index b59885c26..4579fdc5d 100644 --- a/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs +++ b/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs @@ -13,8 +13,8 @@ public sealed class CommodityRecordsTests public void ShippedCatalogOpensWithTheRetiredKeysGone() { using var cache = RestoredHullsTests.OpenCatalog(); - Assert.Equal(24, cache.GetAll().Count()); - Assert.Equal(63, cache.GetAll().Count()); + Assert.Equal(50, cache.GetAll().Count()); + Assert.Equal(67, cache.GetAll().Count()); Assert.Contains(cache.GetAll(), c => c.Name == "Ammo"); Assert.All(cache.GetAll(), c => Assert.False(string.IsNullOrEmpty(c.Name))); } @@ -26,7 +26,7 @@ public sealed class CommodityRecordsTests int[] KeysOf(Type type) => type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Select(f => f.GetCustomAttribute()?.IntKey).Where(k => k.HasValue).Select(k => k.Value).ToArray(); Assert.Equal(new[] { 9 }, KeysOf(typeof(SimpleCommodityData))); - Assert.Empty(KeysOf(typeof(CompoundCommodityData))); + Assert.Equal(new[] { 12 }, KeysOf(typeof(CompoundCommodityData))); // MaxStack, added by cut compound-commodity-stacks; 10 and 11 stay unused Assert.Null(typeof(SimpleCommodityData).GetField("Category")); Assert.Null(typeof(CompoundCommodityData).GetField("Category")); Assert.Null(typeof(CompoundCommodityData).GetField("DemandProfile")); diff --git a/tests/Aetheria.Shared.Tests/CommodityShapeTests.cs b/tests/Aetheria.Shared.Tests/CommodityShapeTests.cs new file mode 100644 index 000000000..413155a2a --- /dev/null +++ b/tests/Aetheria.Shared.Tests/CommodityShapeTests.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; + +// A commodity holds a Shape (aetheria-living-world, cut commodity-shapes): one cell by the type default, refused as an L-shape fault +// when a stored commodity has none, and held by a cargo bay in the shipped catalog. +public sealed class CommodityShapeTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-commodityshape-" + Guid.NewGuid().ToString("N")); + + public CommodityShapeTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + private sealed class Lambda : EconomyBatch + { + private readonly Action _author; + public Lambda(Action author) => _author = author; + public override void Author(EconomyAuthor author) => _author(author); + } + + // Kills: the default dropped from either commodity type. + [Fact] + public void ANewCommodityIsOneCell() + { + Assert.Single(new SimpleCommodityData().Shape.Coordinates); + Assert.Single(new CompoundCommodityData().Shape.Coordinates); + } + + // Kills: a check that reads only simple commodities, or one that treats a restored shape as a fault. + [Fact] + public void AShapelessCommodityIsAnLShapeFault() + { + using var f = EconomyFixture.Healthy(); + Assert.Empty(EconomyChecks.Shapes(f.Cache)); + var key = new CultRecordKey(EconomyFixture.Key("plate")); + var plate = f.Cache.Get(key); + plate.Shape = null; + f.Cache.Upsert(typeof(CompoundCommodityData), plate, key); + var fault = Assert.Single(EconomyChecks.Shapes(f.Cache)); + Assert.Equal(EconomyChecks.LShape, fault.Invariant); + Assert.Equal(key.Value, fault.Record); + Assert.Single(EconomyChecks.Check(f.Cache).Faults, x => x.Invariant == EconomyChecks.LShape); + plate.Shape = new Shape(); + f.Cache.Upsert(typeof(CompoundCommodityData), plate, key); + Assert.Empty(EconomyChecks.Shapes(f.Cache)); + } + + // Kills: LShape missing from the refusing set in EconomyCommand. + [Fact] + public void ABatchThatWritesAShapelessCommodityIsRefused() + { + using var f = EconomyFixture.Healthy(); + f.Cache.FlushAsync().GetAwaiter().GetResult(); + var bytes = File.ReadAllBytes(f.CatalogPath); + var output = new StringWriter(); + var batch = new Lambda(a => a.Put(new SimpleCommodityData { Name = "void", Shape = null }, new CultRecordKey(EconomyFixture.Key("void")))); + var code = EconomyCommand.Author(f.CatalogPath, new List { batch }, true, output, TestCatalog.Registry(), _root); + Assert.Equal(1, code); + Assert.Contains("The batch is refused", output.ToString()); + Assert.Contains("L-shape commodity:void", output.ToString()); + Assert.Equal(bytes, File.ReadAllBytes(f.CatalogPath)); + } + + private CultCache Shipped() + { + var path = Path.Combine(_root, "Aetheria.cc"); + File.Copy(TestCatalog.Repo, path, true); + return AetheriaStores.Open(path, catalogWritable: true, registry: TestCatalog.Registry()); + } + + // Kills: the data pass skipping compound or raw goods. + [Fact] + public void EveryShippedCommodityHasAShape() + { + using var cache = Shipped(); + var commodities = cache.GetAll().Where(Recipes.IsCommodity).ToArray(); + Assert.True(commodities.Length > 100); + Assert.All(commodities, item => Assert.NotEmpty(item.Shape?.Coordinates ?? Array.Empty())); + Assert.Empty(EconomyChecks.Shapes(cache)); + } + + // Kills: a zero-cell shape and the null crash on the way into a hold. + [Fact] + public void EveryShippedSimpleCommodityFitsAnEmptyHold() + { + using var cache = Shipped(); + var shape = new Shape(5, 5); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var bay = new Shape(4, 4); + foreach (var cell in bay.AllCoordinates) bay[cell] = true; + cache.Upsert(new VerseGrammar { Revision = 1 }); + cache.Upsert(new HullData { Name = "ShapeSkiff", HullType = HullType.Ship, Shape = shape, Price = 1000, Durability = 10, Armor = 10 }); + cache.Upsert(new CargoBayData { Name = "ShapeBay", Shape = new Shape(), InteriorShape = bay, Price = 20, Durability = 4 }); + cache.FlushAsync().GetAwaiter().GetResult(); + var items = new ItemManager(1u, cache, new ProvenanceLedger(), AuthoredSettings.Load(RestoredHullsTests.FindRepoRoot()).Read("GameplaySettings"), _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + EquippableItem Mint(string design) + { + var data = cache.GetByName(design); + return new EquippableItem + { + Data = cache.RefOf(data), Durability = data.Durability, + Lot = items.Lots.Add(new Lot { Design = cache.RefOf(data), Origin = new Attributed(), Quality = .5f, Roles = new List() }) + }; + } + var ship = new Ship(items, zone, Mint("ShapeSkiff"), new EntitySettings()); + Assert.True(ship.TryEquip(Mint("ShapeBay"), new int2(1, 1))); + var simple = cache.GetAll().ToArray(); + Assert.NotEmpty(simple); + foreach (var data in simple) + { + var hold = ship.CargoBays.Single(); + Assert.True(hold.TryStore(new SimpleCommodity { Data = cache.RefOf(data), Quantity = 1 }), data.Name); + foreach (var held in hold.Cargo.Keys.ToArray()) hold.Remove(held); + } + } +} diff --git a/tests/Aetheria.Shared.Tests/CompoundStackTests.cs b/tests/Aetheria.Shared.Tests/CompoundStackTests.cs new file mode 100644 index 000000000..c2f38c613 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/CompoundStackTests.cs @@ -0,0 +1,575 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using UniRx; +using Xunit; + +// Ruling aetheria-living-world:ruling:compound-commodities-stack-by-lot: units of one lot of a compound commodity stack up to +// the design's MaxStack, two lots never merge, a split carries its lot, and a save from before stacks reads one unit. One bay +// rule serves every stack (ICommodityStack.StacksWith), so these tests go through the bay's public entries only. The fixture +// is StationServicesTests's: a skiff, a station, a crate, plus one compound design (MaxStack 4) and two lots of it. +public sealed class CompoundStackTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-compoundstacks-" + Guid.NewGuid().ToString("N")); + private readonly CultCache _cache; + private readonly ItemManager _items; + private readonly Zone _zone; + private readonly CompoundCommodityData _gem; + private readonly CompoundCommodityData _rod; + private readonly SimpleCommodityData _ore; + private readonly int _lotA; + private readonly int _lotB; + private const float Dt = .1f; + + public CompoundStackTests() + { + Directory.CreateDirectory(_root); + _cache = AetheriaStores.Open(Path.Combine(_root, "Aetheria.cc"), catalogWritable: true); + _cache.Upsert(new VerseGrammar { Revision = 1 }); + var shape = new Shape(5, 5); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + _cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = shape, Price = 1000, Durability = 10, Armor = 10 }); + _cache.Commit(batch => batch.Upsert(typeof(StationKindData), new StationKindData { Name = "Trade Hub" }, StationKindData.KeyOf("trade-hub"))); + _cache.Upsert(new HullData { Name = "Hub", HullType = HullType.Station, Kind = TestStationKinds.TradeHub, Shape = shape, Price = 5000, Durability = 10, + Hardpoints = { new HardpointData { Type = HardpointType.Facility, Position = new int2(0, 0), Shape = new Shape() } } }); + _cache.Upsert(new GearData { Name = "Smelter", Hardpoint = HardpointType.Facility, Shape = new Shape(), Price = 1, Durability = 4, Behaviors = { new FacilityData() } }); + _cache.Upsert(new GearData { Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 400, Durability = 8 }); + var bay = new Shape(4, 4); + foreach (var cell in bay.AllCoordinates) bay[cell] = true; + _cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = bay, Price = 20, Durability = 4 }); + var pocket = new Shape(1, 1); + foreach (var cell in pocket.AllCoordinates) pocket[cell] = true; + _cache.Upsert(new CargoBayData { Name = "Pocket", Shape = new Shape(), InteriorShape = pocket, Price = 5, Durability = 4 }); + _ore = new SimpleCommodityData { Name = "Ore", Shape = new Shape(), Price = 7, MaxStack = 10 }; + _cache.Upsert(_ore); + _gem = new CompoundCommodityData { Name = "Gem", Shape = new Shape(), Price = 10, Mass = 2f, SpecificHeat = 3f, MaxStack = 4 }; + _cache.Upsert(_gem); + var rodShape = new Shape(2, 1); + foreach (var cell in rodShape.AllCoordinates) rodShape[cell] = true; + _rod = new CompoundCommodityData { Name = "Rod", Shape = rodShape, Price = 4, Mass = 1f, SpecificHeat = 1f, MaxStack = 4 }; + _cache.Upsert(_rod); + // The fixture station wants what its facility draws: the Smelter's one recipe takes any filler of the role the gem fills, so + // the station wants Gem and not Rod. + var bar = new SimpleCommodityData { Name = "Bar", Shape = new Shape(), Price = 1, MaxStack = 10 }; + _cache.Upsert(bar); + _cache.Upsert(typeof(RecipeData), new RecipeData { Output = _cache.RefOf(_gem), Fills = { "gemmed" } }, RecipeData.KeyOf(_cache.RefOf(_gem).Key)); + _cache.Upsert(typeof(RecipeData), new RecipeData + { + Output = _cache.RefOf(bar), Facility = _cache.RefOf(_cache.GetByName("Smelter")), + RoleInputs = { new ItemRole { Name = "gemmed", Count = 1 } } + }, RecipeData.KeyOf(_cache.RefOf(bar).Key)); + _cache.FlushAsync().Wait(); + + var settings = AuthoredSettings.Load(RestoredHullsTests.FindRepoRoot()).Read("GameplaySettings"); + _items = new ItemManager(1u, _cache, new ProvenanceLedger(), settings, _ => { }); + _zone = new Zone(_items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + _lotA = _items.CreateLot(_gem, default, .9f); + _lotB = _items.CreateLot(_gem, default, .6f); + } + + public void Dispose() + { + _cache.Dispose(); + Directory.Delete(_root, true); + } + + private EquippableItem Mint(string design) + { + var data = _cache.GetByName(design); + return new EquippableItem + { + Data = _cache.RefOf(data), Durability = data.Durability, + Lot = _items.Lots.Add(new Lot { Design = _cache.RefOf(data), Origin = new Attributed(), Quality = .5f, Roles = new List() }) + }; + } + + // Units of a lot as ItemManager mints them (one), then set to the stack the test wants. + private CompoundCommodity Gem(int lot, int quantity) + { + var stack = Assert.IsType(_items.CreateInstance(lot)); + stack.Quantity = quantity; + return stack; + } + + private SimpleCommodity Ore(int quantity) => + new SimpleCommodity { Data = _cache.RefOf(_ore), Quantity = quantity }; + + private Ship ShipWithBays(params string[] bays) + { + var ship = new Ship(_items, _zone, Mint("Skiff"), new EntitySettings()); + for (var i = 0; i < bays.Length; i++) + ship.CargoBays.Add(new EquippedCargoBay(_items, Mint(bays[i]), new int2(1 + i, 1), ship, $"bay{i}")); + return ship; + } + + // A ship whose bay is equipped the way a save knows it. + private Ship ShipWith(string bay) + { + var ship = new Ship(_items, _zone, Mint("Skiff"), new EntitySettings()); + Assert.True(ship.TryEquip(Mint(bay), new int2(1, 1))); + return ship; + } + + private OrbitalEntity Station(bool wants = true) + { + var station = new OrbitalEntity(_items, _zone, Mint("Hub"), default, new EntitySettings()); + Assert.True(station.TryEquip(Mint("Crate"), new int2(1, 1))); + if (wants) Assert.True(station.TryEquip(Mint("Smelter"), new int2(0, 0))); + return station; + } + + private static CompoundCommodity[] Stacks(EquippedCargoBay bay) => + bay.Cargo.Keys.OfType().OrderBy(s => bay.Cargo[s].y).ThenBy(s => bay.Cargo[s].x).ToArray(); + + private float Weight(EquippedCargoBay bay) => bay.Data.Mass + bay.Cargo.Keys.Sum(item => _items.GetMass(item)); + + private float ThermalWeight(EquippedCargoBay bay) => bay.Data.Mass * bay.Data.SpecificHeat + bay.Cargo.Keys.Sum(item => _items.GetThermalMass(item)); + + [Fact] + public void UnitsOfOneLotMergeUpToMaxStack() + { + var bay = ShipWithBays("Crate").CargoBays[0]; + Assert.True(bay.TryStore(Gem(_lotA, 3))); + Assert.True(bay.TryStore(Gem(_lotA, 2))); + Assert.Equal(new[] { 1, 4 }, Stacks(bay).Select(s => s.Quantity).OrderBy(q => q)); + Assert.Equal(2, Stacks(bay).Length); + Assert.All(Stacks(bay), s => Assert.Equal(_lotA, s.Lot)); + Assert.Equal(Weight(bay), bay.Mass, 3); + } + + [Fact] + public void TwoLotsOfOneDesignNeverMerge() + { + var pocket = ShipWithBays("Pocket").CargoBays[0]; + var a = Gem(_lotA, 2); + Assert.True(pocket.TryStore(a)); + var b = Gem(_lotB, 1); + Assert.False(pocket.TryFindSpace(b)); + Assert.False(pocket.TryStore(b)); + Assert.False(pocket.TryStore(b, new int2(0, 0))); + Assert.Equal(2, a.Quantity); + Assert.Equal(1, b.Quantity); + + var crate = ShipWithBays("Crate").CargoBays[0]; + Assert.True(crate.TryStore(Gem(_lotA, 2))); + Assert.True(crate.TryStore(Gem(_lotB, 2))); + Assert.Equal(new[] { _lotA, _lotB }, Stacks(crate).Select(s => s.Lot).OrderBy(l => l)); + } + + [Fact] + public void ACompoundStackNeverMergesWithAnotherKind() + { + var pocket = ShipWithBays("Pocket").CargoBays[0]; + Assert.True(pocket.TryStore(Ore(3))); + var gem = Gem(_lotA, 1); + Assert.False(pocket.TryFindSpace(gem)); + Assert.False(pocket.TryStore(gem, new int2(0, 0))); + + var other = ShipWithBays("Pocket").CargoBays[0]; + Assert.True(other.TryStore(gem)); + Assert.False(other.TryFindSpace(Ore(1))); + Assert.False(other.TryStore(Ore(1), new int2(0, 0))); + Assert.False(other.TryStore(Mint("Gun"), new int2(0, 0))); + Assert.False(gem.StacksWith(Mint("Gun"))); + Assert.False(gem.StacksWith(Ore(1))); + Assert.False(Ore(1).StacksWith(gem)); + Assert.Equal(1, gem.Quantity); + } + + [Fact] + public void ASplitKeepsItsLotAndConservesMass() + { + var from = ShipWithBays("Crate").CargoBays[0]; + var to = ShipWithBays("Crate").CargoBays[0]; + var stack = Gem(_lotA, 4); + Assert.True(from.TryStore(stack)); + var total = from.Mass + to.Mass; + + var part = Assert.IsType(from.Remove(stack, 2)); + Assert.Equal((_lotA, 2, 2), (part.Lot, part.Quantity, stack.Quantity)); + Assert.Equal(stack.Data.Key, part.Data.Key); + Assert.Equal(Weight(from), from.Mass, 3); + Assert.Equal(ThermalWeight(from), from.ThermalMass, 3); + + Assert.True(to.TryStore(part)); + Assert.Equal(Weight(to), to.Mass, 3); + Assert.Equal(total, from.Mass + to.Mass, 3); + Assert.Equal(4, from.Count(stack.Data.Key) + to.Count(stack.Data.Key)); + } + + private (Ship giver, Ship receiver) Alongside() + { + var giver = ShipWith("Crate"); + var receiver = ShipWith("Crate"); + giver.Position = new float3(-50, 0, 10); + receiver.Position = giver.Position + new float3(5, 0, 0); + _zone.Admit(giver, piloted: false); + _zone.Admit(receiver, piloted: false); + return (giver, receiver); + } + + [Fact] + public void AGiveMovesUnitsOfTheOrderedLotOnly() + { + var (giver, receiver) = Alongside(); + var a = Gem(_lotA, 3); + var b = Gem(_lotB, 3); + Assert.True(giver.CargoBays[0].TryStore(b)); + Assert.True(giver.CargoBays[0].TryStore(a)); + giver.Command.Give(receiver, Gem(_lotA, 1), 3); + + for (var i = 0; i < 40; i++) _zone.Update(Dt); + + var held = receiver.CargoBays[0]; + Assert.Equal(3, held.Cargo.Keys.OfType().Where(s => s.Lot == _lotA).Sum(s => s.Quantity)); + Assert.DoesNotContain(held.Cargo.Keys.OfType(), s => s.Lot == _lotB); + Assert.Equal(3, giver.CargoBays[0].Cargo.Keys.OfType().Where(s => s.Lot == _lotB).Sum(s => s.Quantity)); + Assert.DoesNotContain(giver.CargoBays[0].Cargo.Keys.OfType(), s => s.Lot == _lotA); + } + + [Fact] + public void AStackIsPricedPerUnitAndSellsOnlyWhatTheStationCanHold() + { + var unit = Gem(_lotA, 1); + var unitPrice = _items.GetPrice(unit); + Assert.True(unitPrice > 0); + Assert.Equal(unitPrice * 3, StationServices.BuyPrice(_items, unit, 3)); + var fraction = (double) _items.GameplaySettings.SellFraction; + int Pays(int units) => (int) Math.Floor(unitPrice * units * fraction); + Assert.Equal(Pays(3), StationServices.SellPrice(_items, Gem(_lotA, 3))); + Assert.True(Pays(3) > 0); + + // Empty bay: the whole stack goes and is paid in full. + var from = ShipWith("Crate").CargoBays[0]; + var stack = Gem(_lotA, 3); + Assert.True(from.TryStore(stack)); + var station = Station(); + var credits = 100; + Assert.Equal(3, StationServices.TrySellPart(from, station, stack, ref credits).Sold); + Assert.Equal(100 + Pays(3), credits); + Assert.Empty(from.Cargo); + Assert.Equal(3, station.CargoBays[0].Count(_cache.RefOf(_gem).Key)); + + // Part-full bay: the station's stack of the lot has room for one unit and every other cell holds a gun, so one unit + // sells, is paid for alone, and two stay in the seller's hold. + var second = Gem(_lotA, 3); + Assert.True(from.TryStore(second)); + var hold = station.CargoBays[0]; + while (hold.TryStore(Mint("Gun"))) { } + credits = 0; + Assert.Equal(1, StationServices.TrySellPart(from, station, second, ref credits).Sold); + Assert.Equal(Pays(1), credits); + Assert.Equal(2, second.Quantity); + Assert.Contains(second, from.Cargo.Keys); + Assert.Equal(4, hold.Count(_cache.RefOf(_gem).Key)); + Assert.Equal(Weight(hold), hold.Mass, 3); + Assert.Equal(Weight(from), from.Mass, 3); + + // Full bay: nothing moves and nothing is paid. + credits = 0; + Assert.Equal(0, StationServices.TrySellPart(from, station, second, ref credits).Sold); + Assert.Throws(() => StationServices.TrySell(from, station, second, ref credits)); + Assert.Equal(0, credits); + Assert.Equal(2, second.Quantity); + Assert.Equal(4, hold.Count(_cache.RefOf(_gem).Key)); + } + + private byte[] PreCutUnit(int lot, MessagePackSerializerOptions options) + { + var buffer = new System.Buffers.ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteArrayHeader(2); + writer.Write(1); // Union(1, CompoundCommodity) + writer.WriteArrayHeader(12); + MessagePackSerializer.Serialize(ref writer, new CultRecordRef(_cache.RefOf(_gem).Key), options); + MessagePackSerializer.Serialize(ref writer, ItemRotation.None, options); + for (var slot = 2; slot < 11; slot++) writer.WriteNil(); + writer.Write(lot); // slot 11: Lot + writer.Flush(); + return buffer.WrittenSpan.ToArray(); + } + + // The hull's lot and the ship pack a one-ship save is made of, as FungibleCommodityTests builds them. + private int _hullLot; + + // The fixture holds the catalog open, so a save reads its own copy of it. + private CultCache Open(string tag) + { + var catalog = Path.Combine(_root, $"catalog-{tag}.cc"); + if (!File.Exists(catalog)) File.Copy(Path.Combine(_root, "Aetheria.cc"), catalog); + return AetheriaStores.Open(catalog, Path.Combine(_root, $"run-{tag}.cc"), Path.Combine(_root, $"player-{tag}.cc")); + } + + private ProvenanceLedger SaveAndReload(ProvenanceLedger live, string tag, params ItemInstance[] held) + { + _hullLot = live.Add(new Lot { Design = default, Origin = new Attributed(), Quality = 1f, Roles = new List() }); + using (var cache = Open(tag)) + { + var game = new SavedGame + { + InfluenceScale = 1, + Factions = new CultRecordRef[0], Relationships = new FactionRelationship[0], + HomeZones = new Dictionary(), BossZones = new Dictionary(), DiscoveredZones = new[] { 0 }, + ActionBarBindings = new SavedActionBarBinding[0], Exit = -1 + }; + var pack = new ShipPack + { + Name = "ship", Hull = new EquippableItem { Lot = _hullLot }, + Equipment = Array.Empty<(int2, EquippableItem)>(), CargoBays = Array.Empty<(int2, EquippableItem)>(), + DockingBays = Array.Empty<(int2, EquippableItem)>(), + CargoContents = new[] { held.Select((s, i) => (new int2(i, 0), s)).ToArray() }, + DockingBayContents = Array.Empty<(int2, ItemInstance)[]>(), Children = Array.Empty(), + Temperature = new float[0, 0], Armor = new float[0, 0], Conductivity = new bool2[0, 0], + DockingBayAssignments = Array.Empty(), Settings = new EntitySettings(), WeaponGroups = Array.Empty() + }; + var zone = new SavedZone + { + Name = "Zone 0", AdjacentZones = Array.Empty(), Factions = Array.Empty(), Owner = -1, + Contents = new ZonePack { Entities = new List { pack } } + }; + RunSave.Commit(cache, game, new[] { zone }, live); + } + using (var cache = Open(tag)) return RunSave.Lots(cache); + } + + [Fact] + public void APreCutCompoundUnitReadsAsOneAndSavesItsLot() + { + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ItemInstance).Assembly); + var old = Assert.IsType(MessagePackSerializer.Deserialize(PreCutUnit(_lotA, options), options)); + Assert.Equal((_lotA, 1), (old.Lot, old.Quantity)); + + var bay = ShipWithBays("Pocket").CargoBays[0]; + Assert.True(bay.TryStore(old)); + Assert.True(bay.TryStore(Gem(_lotA, 1))); + Assert.Equal(2, Assert.Single(Stacks(bay)).Quantity); + + // A new stack keeps its quantity and lot across the wire. + var fresh = Gem(_lotB, 3); + var again = Assert.IsType(MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(fresh, options), options)); + Assert.Equal((_lotB, 3), (again.Lot, again.Quantity)); + + // The run save roots the lot of a stack once. + var saved = SaveAndReload(_items.Lots, "precut", old); + Assert.Contains(_lotA, saved.Lots.Keys); + Assert.DoesNotContain(_lotB, saved.Lots.Keys); + } + + [Fact] + public void RestoreSplitsAnOversizeCompoundStackKeepingItsLot() + { + var ship = ShipWith("Crate"); + Assert.True(ship.CargoBays[0].TryStore(Gem(_lotA, 4))); + var pack = EntitySerializer.Pack(ship); + _gem.MaxStack = 3; + var restored = EntitySerializer.Unpack(_items, _zone, pack); + + var stacks = restored.CargoBays.SelectMany(Stacks).ToArray(); + Assert.Equal(4, stacks.Sum(s => s.Quantity)); + Assert.True(stacks.Length >= 2); + Assert.All(stacks, s => Assert.Equal(_lotA, s.Lot)); + Assert.All(stacks, s => Assert.True(s.Quantity <= 3)); + } + + [Fact] + public void RestoreConsolidatesFragments() + { + var ship = ShipWith("Crate"); + var bay = ship.CargoBays[0]; + // Fragments of one design at four cells: the bay merges nothing at an empty cell, as a pre-merge save held them. + var cell = 0; + foreach (var quantity in new[] { 4, 4, 4, 5 }) Assert.True(bay.TryStore(Ore(quantity), new int2(cell++, 0))); + // Two pre-cut units of lot A, and one of lot B. + Assert.True(bay.TryStore(Gem(_lotA, 1), new int2(0, 1))); + Assert.True(bay.TryStore(Gem(_lotA, 1), new int2(1, 1))); + Assert.True(bay.TryStore(Gem(_lotB, 1), new int2(2, 1))); + var mass = bay.Mass; + var thermal = bay.ThermalMass; + + var restored = EntitySerializer.Unpack(_items, _zone, EntitySerializer.Pack(ship)).CargoBays[0]; + + Assert.Equal(new[] { 7, 10 }, restored.Cargo.Keys.OfType().Select(s => s.Quantity).OrderBy(q => q)); + var gems = restored.Cargo.Keys.OfType().OrderBy(s => s.Lot).ToArray(); + Assert.Equal(new[] { (_lotA, 2), (_lotB, 1) }, gems.Select(s => (s.Lot, s.Quantity))); + Assert.Equal(mass, restored.Mass, 3); + Assert.Equal(thermal, restored.ThermalMass, 3); + Assert.Equal(Weight(restored), restored.Mass, 3); + } + + [Fact] + public void CountCountsUnits() + { + var ship = ShipWithBays("Crate", "Pocket"); + Assert.True(ship.CargoBays[0].TryStore(Gem(_lotA, 3))); + Assert.True(ship.CargoBays[0].TryStore(Gem(_lotB, 2))); + Assert.True(ship.CargoBays[1].TryStore(Gem(_lotA, 1))); + var gun = Mint("Gun"); + Assert.True(ship.CargoBays[0].TryStore(gun)); + var gem = _cache.RefOf(_gem).Key; + + Assert.Equal(5, ship.CargoBays[0].Count(gem)); + Assert.Equal(1, ship.CargoBays[1].Count(gem)); + Assert.Equal(6, ship.CountItemsInCargo(gem)); + Assert.Equal(1, ship.CountItemsInCargo(gun.Data.Key)); + Assert.Equal(0, ship.CountItemsInCargo(_cache.RefOf(_ore).Key)); + } + + // One compound sale path: TrySell would pay a whole stack's price for one unit, so it refuses a compound outright. + [Fact] + public void TrySellRefusesACompoundStack() + { + var from = ShipWith("Crate").CargoBays[0]; + var stack = Gem(_lotA, 3); + Assert.True(from.TryStore(stack)); + var credits = 0; + Assert.Throws(() => StationServices.TrySell(from, Station(), stack, ref credits)); + Assert.Equal(0, credits); + Assert.Equal(3, stack.Quantity); + Assert.Contains(stack, from.Cargo.Keys); + } + + // Units moved are units paid, across bays: the station's crate has room for two units and its pocket for one. + [Fact] + public void ASaleAcrossTwoBaysPaysForExactlyWhatMoved() + { + var unitPrice = _items.GetPrice(Gem(_lotA, 1)); + var fraction = (double) _items.GameplaySettings.SellFraction; + int Pays(int units) => (int) Math.Floor(unitPrice * units * fraction); + var key = _cache.RefOf(_gem).Key; + + var station = Station(); + Assert.True(station.TryEquip(Mint("Pocket"), new int2(2, 2))); + var crate = station.CargoBays[0]; + var pocket = station.CargoBays[1]; + var inCrate = Gem(_lotA, 2); + var inPocket = Gem(_lotA, 3); + Assert.True(crate.TryStore(inCrate)); + Assert.True(pocket.TryStore(inPocket)); + while (crate.TryStore(Mint("Gun"))) { } + + var from = ShipWith("Crate").CargoBays[0]; + var stack = Gem(_lotA, 4); + Assert.True(from.TryStore(stack)); + var units = crate.Count(key) + pocket.Count(key) + from.Count(key); + var credits = 0; + + Assert.Equal(3, StationServices.TrySellPart(from, station, stack, ref credits).Sold); + + Assert.Equal(Pays(2) + Pays(1), credits); + Assert.Equal((4, 4, 1), (inCrate.Quantity, inPocket.Quantity, stack.Quantity)); + Assert.Equal(units, crate.Count(key) + pocket.Count(key) + from.Count(key)); + Assert.Equal(Weight(from), from.Mass, 3); + Assert.Equal(Weight(crate), crate.Mass, 3); + } + + // A station whose gear draws no gem does not buy one: nothing moves and nothing is paid. + [Fact] + public void AStationThatDoesNotWantTheGemRefusesItNotWanted() + { + var from = ShipWith("Crate").CargoBays[0]; + var stack = Gem(_lotA, 3); + Assert.True(from.TryStore(stack)); + var station = Station(wants: false); + var credits = 0; + var result = StationServices.TrySellPart(from, station, stack, ref credits); + Assert.Equal((0, 3, SaleRefusal.NotWanted), (result.Sold, result.Offered, result.Refusal)); + Assert.Equal(0, credits); + Assert.Equal(3, stack.Quantity); + Assert.Empty(station.CargoBays[0].Cargo); + } + + [Fact] + public void AStackNotInTheHoldSellsNothing() + { + var from = ShipWith("Crate").CargoBays[0]; + var station = Station(); + var elsewhere = Gem(_lotA, 3); + var credits = 5; + Assert.Equal(0, StationServices.TrySellPart(from, station, elsewhere, ref credits).Sold); + Assert.Equal(5, credits); + Assert.Equal(3, elsewhere.Quantity); + Assert.Empty(station.CargoBays[0].Cargo); + } + + // A floor, not a round: a half credit is not paid. + [Fact] + public void ASaleFloorsAHalfCredit() + { + // A lot whose unit price is odd, so one unit at half is a half credit. + var lot = Enumerable.Range(1, 99).Select(q => _items.CreateLot(_gem, default, q / 100f)) + .First(l => _items.GetPrice(Gem(l, 1)) % 2 == 1); + var unitPrice = _items.GetPrice(Gem(lot, 1)); + Assert.Equal(.5f, _items.GameplaySettings.SellFraction); + Assert.Equal(unitPrice / 2, StationServices.SellPrice(_items, Gem(lot, 1))); + Assert.Equal(unitPrice * 3 / 2, StationServices.SellPrice(_items, Gem(lot, 3))); + } + + // Exactly two fragments fold into one: the fold starts at the second stack. + [Fact] + public void ConsolidateFoldsExactlyTwoFragments() + { + var bay = ShipWithBays("Crate").CargoBays[0]; + Assert.True(bay.TryStore(Gem(_lotA, 1), new int2(0, 0))); + Assert.True(bay.TryStore(Gem(_lotA, 2), new int2(1, 0))); + var mass = bay.Mass; + + bay.Consolidate(); + + Assert.Equal(3, Assert.Single(Stacks(bay)).Quantity); + Assert.Equal(mass, bay.Mass, 3); + Assert.Equal(Weight(bay), bay.Mass, 3); + } + + // A design that fills two cells is one stack, met once in the bay's cell order, not once per cell. + [Fact] + public void ConsolidateFoldsAMultiCellCompoundOnce() + { + var bay = ShipWithBays("Crate").CargoBays[0]; + var lot = _items.CreateLot(_rod, default, .8f); + var rods = new[] { new int2(0, 0), new int2(0, 1), new int2(0, 2) }; + foreach (var at in rods) + { + var rod = Assert.IsType(_items.CreateInstance(lot)); + Assert.True(bay.TryStore(rod, at)); + } + Assert.Equal(3, Stacks(bay).Length); + var mass = bay.Mass; + + bay.Consolidate(); + + Assert.Equal(3, Assert.Single(Stacks(bay)).Quantity); + Assert.Equal(mass, bay.Mass, 3); + Assert.Equal(Weight(bay), bay.Mass, 3); + Assert.Equal(3, bay.Count(_cache.RefOf(_rod).Key)); + } + + [Fact] + public void APickupReportsTheWholeCompoundStackStored() + { + var ship = ShipWith("Crate"); + _zone.Admit(ship, piloted: false); + var stored = -1; + using (_zone.CargoGained.Subscribe(gain => stored = gain.Stored)) + { + var floating = _zone.Release(Gem(_lotA, 3), new float2(0, 0), new float2(0, 0)); + Assert.True(_zone.TryPickUp(ship, floating.Id)); + } + Assert.Equal(3, stored); + Assert.Equal(3, ship.CountItemsInCargo(_cache.RefOf(_gem).Key)); + } + + [Fact] + public void ASplitKeepsItsRotation() + { + var bay = ShipWithBays("Crate").CargoBays[0]; + var stack = Gem(_lotA, 4); + stack.Rotation = ItemRotation.Clockwise; + Assert.True(bay.TryStore(stack)); + Assert.Equal(ItemRotation.Clockwise, bay.Remove(stack, 1).Rotation); + } +} diff --git a/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs b/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs index 9878d95c6..083f7ac0f 100644 --- a/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs @@ -139,6 +139,7 @@ public sealed class ConsumableSupplyTests : IDisposable _caches.Add(cache); var game = new SavedGame { + InfluenceScale = 1, Factions = new[] { maker }, Relationships = new[] { FactionRelationship.Neutral }, HomeZones = new Dictionary { { 0, 0 } }, @@ -282,8 +283,8 @@ public sealed class ConsumableSupplyTests : IDisposable cache.Upsert(new FactionProductData { Name = "Overdrive by Maker", Design = new CultRecordRef(overdrive.Key), Manufacturer = maker }); var authored = AuthoredSettings.Load(repo); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), cache, new PlayerSettings(), Directory.CreateDirectory(Path.Combine(_root, "Narrative")), _ => { }, null, 1); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), cache, _ => { }, null, 1); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); int stations = 0, ships = 0; diff --git a/tests/Aetheria.Shared.Tests/ConsumablesFirstSetCommandTests.cs b/tests/Aetheria.Shared.Tests/ConsumablesFirstSetCommandTests.cs index 96010e26a..7fbfb3a2c 100644 --- a/tests/Aetheria.Shared.Tests/ConsumablesFirstSetCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumablesFirstSetCommandTests.cs @@ -37,7 +37,7 @@ public sealed class ConsumablesFirstSetCommandTests : IDisposable private (ConsumableItemData[] Designs, FactionProductData[] Products) Read() { - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); try { var designs = db.Cache.GetAll().Where(c => DesignNames.Contains(c.Name)).ToArray(); diff --git a/tests/Aetheria.Shared.Tests/ConsumablesFirstSetTests.cs b/tests/Aetheria.Shared.Tests/ConsumablesFirstSetTests.cs index a3858a407..840f1a1e7 100644 --- a/tests/Aetheria.Shared.Tests/ConsumablesFirstSetTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumablesFirstSetTests.cs @@ -53,7 +53,7 @@ public sealed class ConsumablesFirstSetTests Assert.Equal(1, overdrive.Shape.Width); Assert.Equal(1, overdrive.Shape.Height); Assert.Equal(10f, overdrive.Mass); - Assert.Equal(18000, overdrive.Price); + Assert.Equal(180, overdrive.Price); Assert.False(overdrive.Stackable); Assert.Equal(6f, overdrive.Duration); Assert.Equal(new[] { "propellant", "regulator" }, overdrive.Roles.Select(r => r.Name).ToArray()); @@ -68,7 +68,7 @@ public sealed class ConsumablesFirstSetTests Assert.Equal(1, vent.Shape.Width); Assert.Equal(1, vent.Shape.Height); Assert.Equal(15f, vent.Mass); - Assert.Equal(12000, vent.Price); + Assert.Equal(120, vent.Price); Assert.False(vent.Stackable); Assert.Equal(15f, vent.Duration); Assert.Equal(new[] { "nozzle", "coolant" }, vent.Roles.Select(r => r.Name).ToArray()); diff --git a/tests/Aetheria.Shared.Tests/ContactRevealTests.cs b/tests/Aetheria.Shared.Tests/ContactRevealTests.cs index b7d1b88ab..65c69d21b 100644 --- a/tests/Aetheria.Shared.Tests/ContactRevealTests.cs +++ b/tests/Aetheria.Shared.Tests/ContactRevealTests.cs @@ -1991,4 +1991,33 @@ public sealed partial class ContactRevealTests : IDisposable Assert.False(bystander.IsHostileTo(intruder)); Assert.DoesNotContain(intruder, bystander.VisibleEnemies); } + + // The owner's own map decides whom it permits in its Critical area: with a Friendly entry for the visitor's faction she is + // permitted and the patrol holds her no enemy once tracked; with no entry she trespasses and the patrol does (base behaviour). + // Kills: the NPC arm of GetFactionRelationship left constant. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void RelationsDecidePresenceInOwnedSpace(bool friendly) + { + var patrol = Add(float3(0, 0, 0), new[] { "Eye", "Gun" }); + var visitor = Visitor(float3(0, 0, 60), player: false); + var owner = patrol.Faction; + _openCache.Upsert(owner); + var visitorRef = _openCache.Upsert(visitor.Faction); + if (friendly) + { + owner.Relations[visitorRef] = FactionRelationship.Friendly; + _openCache.Upsert(owner); + } + OwnedGalaxy(owner); + Tick(.05f); + Assert.Equal(friendly, visitor.PresencePermitted.Value); + + patrol.EntityInfoGathered[visitor] = 1f; + Tick(.05f); + + Assert.True(patrol.VisibleEntities.Contains(visitor)); + Assert.Equal(!friendly, patrol.IsHostileTo(visitor)); + } } diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs index 9479e31e3..72c54d442 100644 --- a/tests/Aetheria.Shared.Tests/CreditsTests.cs +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -285,7 +285,7 @@ namespace Aetheria.Shared.Tests var notice = credits.Single(credit => credit.LicenceFile == creditFile).Notice; var licenceText = Read(creditFile); Assert.Contains(creditFile.Contains("UFL") ? "UBUNTU FONT LICENCE Version 1.0" : "SIL OPEN FONT LICENSE Version 1.1", licenceText); - Assert.True(Path.GetDirectoryName(creditFile) == Path.GetDirectoryName(fonts[0]).Replace('\\', '/'), "licence text sits beside its fonts"); + Assert.True(Path.GetDirectoryName(creditFile).Replace('\\', '/') == Path.GetDirectoryName(fonts[0]).Replace('\\', '/'), "licence text sits beside its fonts"); if (creditFile.Contains("OFL")) Assert.Contains(embedded, licenceText); Assert.Contains(embedded, notice); foreach (var font in fonts) diff --git a/tests/Aetheria.Shared.Tests/DelaunayTests.cs b/tests/Aetheria.Shared.Tests/DelaunayTests.cs new file mode 100644 index 000000000..e471555a8 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/DelaunayTests.cs @@ -0,0 +1,301 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using System.Threading.Tasks; +using CultMath; +using Xunit; +using static CultMath.math; + +// Delaunay.Edges is exact: it agrees with an empty-circumcircle oracle evaluated in BigInteger, and degenerate input +// either links correctly or throws. +public sealed class DelaunayTests +{ + // Every edge of a triangle whose circumcircle holds no other point strictly inside, evaluated exactly. When no + // empty circle has a point on it the triangulation is unique and these are its edges; otherwise they are a superset. + internal static (SortedSet<(int a, int b)> Edges, bool Unique) Oracle(IReadOnlyList points) + { + var n = points.Count; + var (px, py) = ExactCoordinates(points); + + var edges = new SortedSet<(int a, int b)>(); + var unique = true; + for (var i = 0; i < n; i++) + for (var j = i + 1; j < n; j++) + for (var k = j + 1; k < n; k++) + { + var orient = (px[i] - px[k]) * (py[j] - py[k]) - (py[i] - py[k]) * (px[j] - px[k]); + if (orient.IsZero) continue; + var inside = false; + var onCircle = false; + for (var m = 0; m < n && !inside; m++) + { + if (m == i || m == j || m == k) continue; + BigInteger adx = px[i] - px[m], ady = py[i] - py[m], bdx = px[j] - px[m], bdy = py[j] - py[m], cdx = px[k] - px[m], cdy = py[k] - py[m]; + var det = (adx * adx + ady * ady) * (bdx * cdy - cdx * bdy) + (bdx * bdx + bdy * bdy) * (cdx * ady - adx * cdy) + + (cdx * cdx + cdy * cdy) * (adx * bdy - bdx * ady); + var sign = det.Sign * orient.Sign; + inside = sign > 0; + onCircle |= sign == 0; + } + if (inside) continue; + unique &= !onCircle; + edges.Add((i, j)); + edges.Add((j, k)); + edges.Add((i, k)); + } + return (edges, unique); + } + + // Every coordinate as an integer in one shared unit, so differences and products are exact. + private static (BigInteger[] X, BigInteger[] Y) ExactCoordinates(IReadOnlyList points) + { + var n = points.Count; + var raw = new (BigInteger m, int e)[n, 2]; + var lowest = int.MaxValue; + for (var i = 0; i < n; i++) + for (var axis = 0; axis < 2; axis++) + { + var bits = BitConverter.SingleToInt32Bits(axis == 0 ? points[i].x : points[i].y); + var biased = (bits >> 23) & 0xFF; + var m = biased == 0 ? bits & 0x7FFFFF : (bits & 0x7FFFFF) | 0x800000; + raw[i, axis] = (bits < 0 ? -m : m, biased == 0 ? -149 : biased - 150); + if (m != 0) lowest = Math.Min(lowest, raw[i, axis].e); + } + var px = new BigInteger[n]; + var py = new BigInteger[n]; + for (var i = 0; i < n; i++) + { + px[i] = raw[i, 0].m << Math.Max(0, raw[i, 0].e - lowest); + py[i] = raw[i, 1].m << Math.Max(0, raw[i, 1].e - lowest); + } + return (px, py); + } + + private static int Turn(BigInteger[] x, BigInteger[] y, int a, int b, int c) => + ((x[b] - x[a]) * (y[c] - y[a]) - (y[b] - y[a]) * (x[c] - x[a])).Sign; + + // The edges are a triangulation of the points' convex hull: no two cross, and their count is 3n - 3 - b, b being the + // points on the hull's boundary (a planar graph with that many edges has no face but triangles and the outer one). + // Cocircular input has several Delaunay triangulations; this pins that the one returned is a whole triangulation. + internal static void AssertTriangulatesTheHull(IReadOnlyList points, IReadOnlyList<(int a, int b)> edges, string context) + { + var n = points.Count; + var (x, y) = ExactCoordinates(points); + var order = Enumerable.Range(0, n).OrderBy(i => x[i]).ThenBy(i => y[i]).ToArray(); + var hull = new List(); + foreach (var pass in new[] { order, order.Reverse().ToArray() }) + { + var start = hull.Count; + foreach (var i in pass) + { + while (hull.Count >= start + 2 && Turn(x, y, hull[^2], hull[^1], i) <= 0) hull.RemoveAt(hull.Count - 1); + hull.Add(i); + } + hull.RemoveAt(hull.Count - 1); + } + var boundary = 0; + for (var p = 0; p < n; p++) + for (var h = 0; h < hull.Count; h++) + { + int u = hull[h], v = hull[(h + 1) % hull.Count]; + if (Turn(x, y, u, v, p) != 0) continue; + if (BigInteger.Min(x[u], x[v]) <= x[p] && x[p] <= BigInteger.Max(x[u], x[v]) && BigInteger.Min(y[u], y[v]) <= y[p] && y[p] <= BigInteger.Max(y[u], y[v])) + { + boundary++; + break; + } + } + if (hull.Count == 2) boundary = n; // collinear input: every point is on the boundary + for (var i = 0; i < edges.Count; i++) + for (var j = i + 1; j < edges.Count; j++) + { + var (a, b) = edges[i]; + var (c, d) = edges[j]; + if (a == c || a == d || b == c || b == d) continue; + Assert.False(Turn(x, y, a, b, c) * Turn(x, y, a, b, d) < 0 && Turn(x, y, c, d, a) * Turn(x, y, c, d, b) < 0, + $"{context}: edges ({a},{b}) and ({c},{d}) cross"); + } + Assert.True(edges.Count == 3 * n - 3 - boundary, $"{context}: {edges.Count} edges, a triangulation of the hull has {3 * n - 3 - boundary}"); + } + + // The triangulation lies within the oracle's edges, and equals them when the oracle's answer is unique. + internal static void AssertDelaunay(IReadOnlyList points, string context) + { + var edges = Delaunay.Edges(points); + var (oracle, unique) = Oracle(points); + Assert.True(edges.All(oracle.Contains), $"{context}: edge outside the Delaunay set: {string.Join(" ", edges.Where(e => !oracle.Contains(e)))}"); + if (unique) + Assert.True(oracle.SetEquals(edges), $"{context}: missed Delaunay edges: {string.Join(" ", oracle.Where(e => !edges.Contains(e)))}"); + if (!unique) AssertTriangulatesTheHull(points, edges, context); + Assert.Equal(points.Count, edges.SelectMany(e => new[] { e.a, e.b }).Distinct().Count()); + } + + // Distinct points on a 1/1024 lattice inside [0, 1024), then lifted by offset. + private static float2[] RandomPoints(int seed, int count, float offset = 0) + { + var random = new System.Random(seed); + var seen = new HashSet<(int, int)>(); + var points = new List(); + while (points.Count < count) + { + (int, int) cell = (random.Next(1 << 20), random.Next(1 << 20)); + if (seen.Add(cell)) points.Add(float2(cell.Item1 / 1024f + offset, cell.Item2 / 1024f + offset)); + } + return points.ToArray(); + } + + // Kills: the plain double-precision in-circle (a seed in 0..400 that missed a true edge), the filter bound too small. + [Fact] + public void TwoHundredRandomSetsOf64PointsAreExactlyDelaunay() + { + Parallel.For(0, 200, seed => AssertDelaunay(RandomPoints(seed, 64), $"seed {seed}")); + } + + // The seeds the double-precision predicate got wrong (found sweeping 0..400 on the old code: 42 and 184), by name. + // Kills: the plain double-precision in-circle. + [Theory] + [InlineData(42)] + [InlineData(184)] + public void SeedsTheDoublePredicateMissedStayExact(int seed) => AssertDelaunay(RandomPoints(seed, 64), $"seed {seed}"); + + // Kills: the filter bound too small (it answers wrongly where the double determinant is within rounding of zero). + [Fact] + public void NearlyCocircularPointsChooseTheTrueDiagonal() + { + // Eight lattice points exactly on a circle, then one nudged by an ulp inward and outward. + var circle = new[] { (5f, 0f), (-5f, 0f), (0f, 5f), (0f, -5f), (3f, 4f), (-3f, 4f), (3f, -4f), (-3f, -4f), (4f, 3f), (-4f, 3f), (4f, -3f), (-4f, -3f) }; + foreach (var nudge in new[] { 0, 1, -1 }) + foreach (var scale in new[] { 1f, 1e4f, 1e-3f }) + for (var which = 0; which < circle.Length; which++) + { + var points = circle.Select(p => float2(p.Item1 * scale, p.Item2 * scale)).ToArray(); + if (nudge != 0 && points[which].x != 0) + points[which] = float2(BitConverter.Int32BitsToSingle(BitConverter.SingleToInt32Bits(points[which].x) + nudge), points[which].y); + AssertDelaunay(points, $"nudge {nudge} scale {scale} point {which}"); + } + } + + // Kills: no offset-safe predicate (squares of 1e6-sized coordinates drown the differences in double precision). + [Fact] + public void LargeCoordinateOffsetsStayExact() + { + Parallel.For(0, 40, seed => + { + AssertDelaunay(RandomPoints(seed, 64, 1e6f), $"offset 1e6 seed {seed}"); + AssertDelaunay(RandomPoints(seed, 32, -3e7f), $"offset -3e7 seed {seed}"); + }); + } + + // A lattice is cocircular everywhere: every edge is a true one and every point is linked. + [Fact] + public void ALatticeLinksEveryPointAlongTrueEdges() + { + var grid = new List(); + for (var i = 0; i < 6; i++) + for (var j = 0; j < 6; j++) + grid.Add(float2(i * 100 + 1e6f, j * 100 + 1e6f)); + AssertDelaunay(grid, "lattice"); + var linked = Delaunay.Edges(grid).SelectMany(e => new[] { e.a, e.b }).ToHashSet(); + Assert.Equal(grid.Count, linked.Count); + } + + // Kills: the guard on fewer than two points, the collinear branch dropped (every triangle then holds a super-vertex + // and nothing links). + [Fact] + public void DegenerateInputGivesTheSpecifiedOutcome() + { + Assert.Empty(Delaunay.Edges(new float2[0])); + Assert.Empty(Delaunay.Edges(new[] { float2(3, 4) })); + Assert.Equal(new[] { (0, 1) }, Delaunay.Edges(new[] { float2(3, 4), float2(-1, 2) })); + + // Collinear: each point links to its neighbour along the line, whatever the index order and slope. + var line = new[] { float2(30, 15), float2(0, 0), float2(20, 10), float2(10, 5), float2(-10, -5) }; + Assert.Equal(new[] { (0, 2), (1, 3), (1, 4), (2, 3) }, Delaunay.Edges(line)); + var vertical = new[] { float2(7, 2), float2(7, -9), float2(7, 40) }; + Assert.Equal(new[] { (0, 1), (0, 2) }, Delaunay.Edges(vertical)); + // Exactly collinear off the axes, where a double cross product need not be zero. + var slanted = Enumerable.Range(0, 20).Select(i => float2(1e6f + i, 3e6f + 3 * i)).ToArray(); + Assert.Equal(19, Delaunay.Edges(slanted).Count); + } + + // Kills: the orientation exact path replaced by the plain double sign. Each triple is far from collinear in + // exact arithmetic, yet its double cross product is 0 (the coordinate differences span more than 53 bits and round), + // so the plain sign calls the three points collinear and links only two of the three edges. + [Theory] + [InlineData(66144f, -196608f, 480f, 384f, -70368744177664f, 211106232532992f)] + [InlineData(1.9075232557952404e-05f, 6.62929865148937e+18f, 1.9073442672379315e-05f, 6.62929865148937e+18f, 844424930131968f, 6.629861601442791e+18f)] + [InlineData(-0.00018310546875f, 1759218604441600f, -1610612736f, 1759220215054336f, -2.8823037615171174e+18f, 2.884062980121559e+18f)] + [InlineData(-1536f, -0.0361328125f, 162304f, 81919.9609375f, -1.8014398509481984e+17f, -9.007199254740992e+16f)] + public void WideExponentTrianglesAreNotCalledCollinear(float ax, float ay, float bx, float by, float cx, float cy) + { + var points = new[] { float2(ax, ay), float2(bx, by), float2(cx, cy) }; + Assert.Equal(new[] { (0, 1), (0, 2), (1, 2) }, Delaunay.Edges(points)); + } + + // Kills: OrientationBound loosened to 1e-30 or 0. The first three points are a wide-exponent triple whose plain double + // orientation has the wrong sign, so only the true Shewchuk bound sends it to the exact path; d makes the wrong sign + // corrupt a cavity. + [Fact] + public void AWrongSignedDoubleOrientationIsSentToTheExactPath() + { + var points = new[] + { + float2(-6.848652894797524e-11f, 6.064014568263332e-11f), + float2(2.7171004335357907e-10f, -1.0525675470107743e-10f), + float2(15966.099609375f, -7785.87060546875f), + float2(0f, 1f), + }; + AssertDelaunay(points, "wrong-signed double orientation"); + } + + // Kills: the collinear detector skipping the last sorted point. One point off the line sorts last, so a detector + // that never tests it reads the set as a line and drops the hull edges to it. + [Fact] + public void ALoneOffLinePointThatSortsLastStillTriangulates() + { + var points = new[] { float2(4, 1), float2(0, 0), float2(2, 0), float2(1, 0), float2(3, 0) }; + // The apex fans to every point on the base: the only triangulation of this hull. + Assert.Equal(new[] { (0, 1), (0, 2), (0, 3), (0, 4), (1, 3), (2, 4), (3, 2) }.Select(e => (Math.Min(e.Item1, e.Item2), Math.Max(e.Item1, e.Item2))).OrderBy(e => e).ToArray(), + Delaunay.Edges(points)); + AssertDelaunay(points, "off-line point last"); + } + + // Kills: the super-triangle too small to keep its vertices out of a thin triangle's circumcircle. A triangle of + // height h on a base of 1 has a circumradius near 1/(8h); the super vertices must stay outside that circle, or + // they cut the triangle's hull edges. + [Theory] + [InlineData(-10)] + [InlineData(-30)] + [InlineData(-60)] + [InlineData(-100)] + [InlineData(-140)] + public void ThinTrianglesKeepTheirHullEdges(int exponent) + { + var h = (float) Math.Pow(2, exponent); + AssertDelaunay(new[] { float2(0, 0), float2(1, 0), float2(0.5f, h) }, $"3 points, h 2^{exponent}"); + AssertDelaunay(new[] { float2(0, 0), float2(1, 0), float2(0.25f, h), float2(0.5f, h), float2(0.75f, h) }, $"5 points, h 2^{exponent}"); + Assert.Equal(new[] { (0, 1), (0, 2), (1, 2) }, Delaunay.Edges(new[] { float2(0, 0), float2(1, 0), float2(0.5f, h) })); + } + + // Kills: the duplicate check. + [Fact] + public void DuplicatePointsAreRefusedByIndex() + { + var exception = Assert.Throws(() => Delaunay.Edges(new[] { float2(0, 0), float2(5, 5), float2(9, 1), float2(5, 5) })); + Assert.Contains("points 1 and 3", exception.Message); + Assert.Throws(() => Delaunay.Edges(new[] { float2(1, 1), float2(1, 1) })); + Assert.Throws(() => Delaunay.Edges(new[] { float2(0, 0), float2(float.NaN, 1), float2(2, 2) })); + } + + // Kills: the Galaxy guard removed. + [Fact] + public void GalaxyRefusesAZoneNoLinkReaches() + { + var zones = new[] { new GalaxyZone { Position = float2(0, 0) }, new GalaxyZone { Position = float2(1, 0) }, new GalaxyZone { Position = float2(2, 5) } }; + var exception = Assert.Throws(() => Galaxy.RequireEveryZoneLinked(zones, new[] { (zones[0], zones[1]) })); + Assert.Contains("1 of 3 zones", exception.Message); + Galaxy.RequireEveryZoneLinked(zones, new[] { (zones[0], zones[1]), (zones[1], zones[2]) }); + Galaxy.RequireEveryZoneLinked(new[] { zones[0] }, new (GalaxyZone, GalaxyZone)[0]); + } +} diff --git a/tests/Aetheria.Shared.Tests/DemoLoopTests.cs b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs index a2daf444a..9b2b990b8 100644 --- a/tests/Aetheria.Shared.Tests/DemoLoopTests.cs +++ b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs @@ -1,3 +1,4 @@ +using System; /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ @@ -5,11 +6,12 @@ using System.Linq; using System.Collections.Generic; using CultMath; +using GameCult.Caching; using UniRx; using Xunit; -// The demo loop on the shipped catalog (aetheria-release, mining 5a and the ore sheet): the player's own gun breaks a rock -// through the trigger, the ore lands in the hold, the Pirates station Zenith buys it, repairs the hull and sells a unit back. +// The demo loop on the shipped catalog (aetheria-release, mining 5a): the player's own gun breaks a rock +// through the trigger, the ore lands in the hold, the Pirates' refinery buys it and repairs the hull, and Zenith, Aeronautics Unlimited's trade hub, sells a unit back. public sealed partial class RunStartTests { [Fact] @@ -45,7 +47,7 @@ public sealed partial class RunStartTests var info = player.ChunkInfo(rock); Assert.False(arena.ChunkExists(rock), $"the laser broke the rock: designated {FireControl.Designated(laser, player, rock, out var range)} range {range} info {info} target {player.Target} pos {player.Position} rockpos {arena.ChunkPose(rock.Field, rock.Index)} hp {arena.Settings.AsteroidHitpoints.Evaluate(arena.AsteroidBelts[rock.Field].Data.Asteroids[0].Size)}"); - var ores = new[] { "Rock", "New Metals", "Gold" }; + var ores = FieldKinds.Yield(((AsteroidBeltData) belt.Value).Kind, default, _cache).Select(yield => _cache.Get(yield.Commodity).Name).ToArray(); var held = player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType().Select(stack => (bay, stack))) .Where(h => ores.Contains(_items.GetData(h.stack).Name)).ToArray(); Assert.NotEmpty(held); @@ -55,14 +57,33 @@ public sealed partial class RunStartTests Assert.All(gains, gain => Assert.Equal((GainKind.Mined, 0), (gain.Kind, gain.Adrift))); Assert.Equal(held.Sum(h => h.stack.Quantity), gains.Sum(gain => gain.Stored)); - var zenith = arena.Entities.Single(entity => entity.HullData.Name == "Zenith"); + var refinery = StationOfKind(arena, "processing"); + var zenith = StationOfKind(arena, "trade-hub"); var credits = 0; - // Every mined stack goes in one sale: the market takes it all, whatever the full hold of Zenith has room for. - var value = StationServices.OreValue(_items, player.CargoBays); + // The refinery buys the mined ore as far as its bays hold it (ruling no-market-absorption): the units it took are paid for, and + // what did not fit stays in the hold. + var value = StationServices.OreValue(_items, player.CargoBays, refinery); Assert.True(value > 0); - Assert.Equal(gains.Sum(gain => gain.Stored), StationServices.TrySellOre(player.CargoBays, zenith, ref credits)); - Assert.Equal(value, credits); - Assert.DoesNotContain(player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()), c => ores.Contains(_items.GetData(c).Name)); + var mined = gains.Sum(gain => gain.Stored); + var sale = StationServices.TrySellOre(player.CargoBays, refinery, ref credits); + Assert.Equal(mined, sale.Offered); + Assert.True(sale.Sold > 0, "the refinery has room for some of the ore"); + var left = player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()).Where(c => ores.Contains(_items.GetData(c).Name)).Sum(c => c.Quantity); + Assert.Equal(mined - sale.Sold, left); + if (left == 0) Assert.Equal(value, credits); + else Assert.True(credits > 0 && credits < value); + + // Zenith's silo wants the ores of the haul order to the refinery: it buys what the hold still carries, and a fresh stack too. + var zenithWants = StationWants.Of(zenith); + Assert.NotEmpty(zenithWants); + Assert.All(zenithWants, good => Assert.True(FieldKinds.IsOre(_cache, _cache.Get(new CultRecordRef(good))))); + var silo = zenith.CargoBays.Single(bay => bay.Data is SiloData); + var oreGood = zenithWants.OrderBy(good => good.Value, StringComparer.Ordinal).First(); + var fresh = new SimpleCommodity { Data = new CultRecordRef(oreGood), Quantity = 5 }; + Assert.True(player.CargoBays[0].TryStore(fresh)); + var atZenith = StationServices.TrySellPart(player.CargoBays[0], zenith, fresh, ref credits); + Assert.Equal((5, SaleRefusal.None), (atZenith.Sold, atZenith.Refusal)); + Assert.Equal(5, silo.Count(oreGood)); var cell = Enumerable.Range(0, player.MaxArmor.GetLength(0)).SelectMany(x => Enumerable.Range(0, player.MaxArmor.GetLength(1)).Select(y => (x, y))) .First(c => player.MaxArmor[c.x, c.y] > 0); @@ -75,15 +96,56 @@ public sealed partial class RunStartTests Assert.Equal(paid, credits); Assert.Equal(player.MaxArmor[cell.x, cell.y], player.Armor[cell.x, cell.y]); - // Zenith's whole stock is one 16-cell reactor, which fits only an empty 4x4: the player jettisons what the hold - // still carries, then buys it. + // Zenith's smallest piece may need an empty hold: the player jettisons what the hold still carries, then buys it. var hold = player.CargoBays[0]; foreach (var leftover in hold.Cargo.Keys.ToArray()) hold.Remove(leftover); - var stock = zenith.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType().Select(piece => (bay, piece))).Single(); + var stock = zenith.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType().Select(piece => (bay, piece))) + .MinBy(held => _items.GetData(held.piece).Shape.Cells.Cast().Count(occupied => occupied)); credits = StationServices.BuyPrice(_items, stock.piece); Assert.Equal(BuyResult.Bought, StationServices.TryBuy(_items, stock.piece, 1, ref credits, - () => stock.bay.TryTransferItem(hold, stock.piece))); + () => stock.bay.TryTransferItem(hold, stock.piece, 1))); Assert.Equal(0, credits); Assert.Contains(stock.piece, hold.Cargo.Keys); } + + // What a hold of belt ore earns against what the loop spends it on, on the shipped catalog (aetheria-living-world, ruling + // economy-numbers-are-sim-tuned-knobs: the prices are balance knobs tuned from simulation, so this pins only the scale). V is the + // belt kind's hold-cell value: a unit is drawn by abundance, a cell takes MaxStack units, so a cell's value is + // sum(abundance x price) / sum(abundance / MaxStack), over every yield of the kind. It is set against the repair of the player's hull + // with all its armour lost and against the authored Price of the cheapest piece Zenith stocks (ruling demo-loop-reads-authored-price: + // the rolled BuyPrice moves with any catalog change that shifts the stock draw, 47053 against 36806 for the same Ring Station Reactor + // across design-bills, which is not what this test is about). Margin rule: the anchors are the readings the shipped catalog gives at + // design-bills (V 282.149, repair 55404, cheapest authored price 15500; the price re-read at station-sale-by-wants as 2500, since generated stock stops at half the bay and the smaller, cheaper pieces then fit where the full bay refused them), and the band is 1/sqrt(10) to sqrt(10) of each, the + // geometric midpoint between the shipped reading and the least mutant this test claims to catch (a divisor of ten on either side, a + // ratio of 10 or 0.1): the shipped reading and that mutant each sit 3.16x from a bound. + // The one station of a kind in the arena: the demo's two stations are told apart by what they are for, never by hull. + private static OrbitalEntity StationOfKind(Zone arena, string kind) => + arena.Entities.OfType().Single(entity => entity.Kind.Key.Equals(StationKindData.KeyOf(kind))); + + private const double BaseRepairRatio = 0.0050925, BaseBuyRatio = 0.11286; + private static readonly double Margin = Math.Sqrt(10); + + [Fact] + public void DemoLoopIncomeToCostClosesAfterRescale() + { + var (_, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var player = staged.Player; + var belt = arena.Planets.Single(body => body.Value is AsteroidBeltData); + var kind = _cache.Get(((AsteroidBeltData) belt.Value).Kind); + var yields = kind.Yields.Select(y => (data: _cache.Get(y.Commodity), weight: (double) y.Abundance)).ToArray(); + var value = yields.Sum(y => y.weight * y.data.Price) / yields.Sum(y => y.weight / y.data.MaxStack); + + for (var x = 0; x < player.MaxArmor.GetLength(0); x++) + for (var y = 0; y < player.MaxArmor.GetLength(1); y++) + player.Armor[x, y] = 0; + var repair = StationServices.RepairCost(_items, player); + var zenith = StationOfKind(arena, "trade-hub"); + var cheapest = zenith.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()).Min(piece => _items.GetData(piece).Price); + Assert.True(repair > 0 && cheapest > 0); + + var measured = $"belt {kind.Name}: V {value:0.###} per cell, repair {repair}, cheapest authored price {cheapest}, V/repair {value / repair:0.######}, V/buy {value / cheapest:0.######}"; + Assert.True(value / repair >= BaseRepairRatio / Margin && value / repair <= BaseRepairRatio * Margin, measured); + Assert.True(value / cheapest >= BaseBuyRatio / Margin && value / cheapest <= BaseBuyRatio * Margin, measured); + } } diff --git a/tests/Aetheria.Shared.Tests/DemoOreSheetTests.cs b/tests/Aetheria.Shared.Tests/DemoOreSheetTests.cs deleted file mode 100644 index 24ef521eb..000000000 --- a/tests/Aetheria.Shared.Tests/DemoOreSheetTests.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using CultMath; -using GameCult.Caching; -using Xunit; - -// The interim ore sheet (rulings mining-demo-ore-minimal-yields-now, mining-demo-ore-prices-gear-scale): what the shipped catalog's -// Asteroid belt holds can be carried and sold, so mine, sell, repair closes on the existing stations. -public sealed class DemoOreSheetTests : IDisposable -{ - private static readonly string[] Ores = { "Rock", "New Metals", "Gold" }; - private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-demoore-" + Guid.NewGuid().ToString("N")); - - public DemoOreSheetTests() => Directory.CreateDirectory(_root); - public void Dispose() => Directory.Delete(_root, true); - - private CultCache Shipped() - { - var path = Path.Combine(_root, "Aetheria.cc"); - File.Copy(TestCatalog.Repo, path, true); - return AetheriaStores.Open(path, catalogWritable: true, registry: TestCatalog.Registry()); - } - - private static CultRecordRef Asteroid(CultCache cache) => - cache.RefOf(cache.GetAll().Single(k => k.Name == "Asteroid")); - - [Fact] - public void AsteroidYieldsThreeOresInKeyOrder() - { - using var cache = Shipped(); - var yield = FieldKinds.Yield(Asteroid(cache), default, cache); - var amounts = yield.ToDictionary(y => cache.Get(y.Commodity).Name, y => y.Amount); - Assert.Equal(Ores.OrderBy(n => n).ToArray(), amounts.Keys.OrderBy(n => n).ToArray()); - Assert.Equal(6f, amounts["Rock"]); - Assert.Equal(3f, amounts["New Metals"]); - Assert.Equal(1f, amounts["Gold"]); - Assert.Equal(yield.Select(y => y.Commodity.Key.Value).OrderBy(k => k, StringComparer.Ordinal), yield.Select(y => y.Commodity.Key.Value)); - } - - [Fact] - public void EveryYieldedOreCanBeHeldAndSold() - { - using var cache = Shipped(); - var shape = new Shape(5, 5); - foreach (var cell in shape.AllCoordinates) shape[cell] = true; - var bay = new Shape(4, 4); - foreach (var cell in bay.AllCoordinates) bay[cell] = true; - cache.Upsert(new VerseGrammar { Revision = 1 }); - cache.Upsert(new HullData { Name = "OreSkiff", HullType = HullType.Ship, Shape = shape, Price = 1000, Durability = 10, Armor = 10 }); - cache.Upsert(new CargoBayData { Name = "OreBay", Shape = new Shape(), InteriorShape = bay, Price = 20, Durability = 4 }); - cache.FlushAsync().GetAwaiter().GetResult(); - var items = new ItemManager(1u, cache, new ProvenanceLedger(), AuthoredSettings.Load(RestoredHullsTests.FindRepoRoot()).Read("GameplaySettings"), _ => { }); - var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); - EquippableItem Mint(string design) - { - var data = cache.GetByName(design); - return new EquippableItem - { - Data = cache.RefOf(data), Durability = data.Durability, - Lot = items.Lots.Add(new Lot { Design = cache.RefOf(data), Origin = new Attributed(), Quality = .5f, Roles = new List() }) - }; - } - var ship = new Ship(items, zone, Mint("OreSkiff"), new EntitySettings()); - Assert.True(ship.TryEquip(Mint("OreBay"), new int2(1, 1))); - - foreach (var (commodity, _) in FieldKinds.Yield(Asteroid(cache), default, cache)) - { - var data = cache.Get(commodity); - Assert.NotNull(data.Shape); - Assert.True(data.Price > 0, data.Name); - Assert.True(data.Mass > 0, data.Name); - Assert.True(ship.CargoBays.Single().TryStore(new SimpleCommodity { Data = cache.RefOf(data), Quantity = 1 }), data.Name); - } - } - - [Fact] - public void TheSheetConverges() - { - var path = Path.Combine(_root, "Converge.cc"); - File.Copy(Path.Combine(RestoredHullsTests.FindRepoRoot(), "GameData", "Aetheria.cc"), path); - var before = File.ReadAllBytes(path); - var output = new StringWriter(); - Assert.Equal(0, EconomyCommand.Author(path, new List { new DemoOre() }, true, output, TestCatalog.Registry(), _root)); - Assert.Equal(before, File.ReadAllBytes(path)); - - using var cache = AetheriaStores.Open(path, registry: TestCatalog.Registry()); - var ids = cache.GetAll().Single(k => k.Name == "Asteroid").Yields.Select(y => y.Id).ToArray(); - Assert.Equal(new[] { "a57e0c000001", "a57e0c000002", "a57e0c000003" }, ids); - } -} diff --git a/tests/Aetheria.Shared.Tests/DemoPressureTests.cs b/tests/Aetheria.Shared.Tests/DemoPressureTests.cs new file mode 100644 index 000000000..850e19b36 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/DemoPressureTests.cs @@ -0,0 +1,372 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; + +// The demo's pressure curve (aetheria-release, cut demo-pressure-curve): how many hostiles of what hull tier a zone of +// the demo galaxy holds, as one function of its depth toward the gate. The fixture is RunStartTests'. +public sealed partial class RunStartTests +{ + private sealed record ZoneRow(int Index, int Jumps, double Depth, DemoPressure.Pressure Asked, int Hostiles, int Friendly, string[] HostileHulls, int[] HostilePrices); + + // The demo's own declaration, as RunStart.GenerateArena passes it: the entrance zone gets its station. + private static IReadOnlyList DemoEntranceStations => new DemoTerminus().EntranceStations; + + // Every zone of the demo galaxy as the generator builds it. Hostile means the antagonist's ships, the one cast faction + // the player is Hated by. + private ZoneRow[] DemoZones(uint seed) + { + var (galaxy, _, _, failures) = Launch(new DemoTerminus(), Inputs(() => seed)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var antagonist = galaxy.Antagonist; + return galaxy.Zones.Select((zone, index) => + { + var pack = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, galaxy, zone, DemoEntranceStations); + var ships = pack.Entities.OfType().ToArray(); + // The boss is the run's goal, placed apart from the pressure. + var hostile = ships.Where(ship => _cache.Get(ship.Faction) == antagonist && !ship.Boss).ToArray(); + return new ZoneRow(index, galaxy.Entrance.Distance[zone], + DemoPressure.Depth(galaxy, zone), DemoPressure.Of(galaxy, zone), + hostile.Length, ships.Count(ship => _cache.Get(ship.Faction) != antagonist), + hostile.Select(ship => _items.GetData(ship.Hull).Name).ToArray(), + hostile.Select(ship => _items.GetData(ship.Hull).Price).ToArray()); + }).ToArray(); + } + + // The measured table the operator tunes against (not an assertion): set DEMO_PRESSURE_TABLE to a path to write it. + [Fact] + public void DemoGalaxy_pressure_table() + { + var path = Environment.GetEnvironmentVariable("DEMO_PRESSURE_TABLE"); + if (string.IsNullOrEmpty(path)) return; + var lines = new List { "seed zone jumps depth hostiles other hull-prices" }; + foreach (var seed in DemoSeeds) + foreach (var row in DemoZones(seed).OrderBy(r => r.Jumps)) + lines.Add($"{seed} {row.Index,3} {row.Jumps,2} {row.Depth:0.00} {row.Hostiles,2} {row.Friendly,2} [{string.Join(",", row.HostilePrices)}]"); + File.WriteAllLines(path, lines); + } + + private static IEnumerable DepthGrid() => Enumerable.Range(0, 1001).Select(step => step / 1000f); + + // The curve only rises with depth, and rises somewhere in both its counts and its tiers. + [Fact] + public void DemoPressure_monotone() + { + var grid = DepthGrid().Select(depth => DemoPressure.At(depth)).ToArray(); + for (var i = 1; i < grid.Length; i++) + { + Assert.True(grid[i - 1].Hostiles <= grid[i].Hostiles, $"hostiles fall at step {i}"); + Assert.True(grid[i - 1].Tier <= grid[i].Tier, $"tier falls at step {i}"); + } + Assert.True(grid.First().Hostiles < grid.Last().Hostiles); + Assert.True(grid.First().Tier < grid.Last().Tier); + } + + [Fact] + public void DemoPressure_grace_at_entrance() + { + Assert.Equal(0, DemoPressure.At(0f).Hostiles); + // The bound is the literal quarter, not DemoPressure.GraceDepth, so a grace that shrinks to nothing fails here. + foreach (var depth in DepthGrid().Where(depth => depth <= 0.25f)) + Assert.Equal(0, DemoPressure.At(depth).Hostiles); + } + + [Fact] + public void DemoPressure_boss_zone_is_ceiling() + { + var ceiling = DemoPressure.At(1f); + Assert.Equal(DemoPressure.MaxHostiles, ceiling.Hostiles); + foreach (var depth in DepthGrid()) + { + Assert.True(DemoPressure.At(depth).Hostiles <= ceiling.Hostiles); + Assert.True(DemoPressure.At(depth).Tier <= ceiling.Tier); + } + } + + // However low the tier, the ceiling admits at least the cheapest hull offered, and the top tier admits them all. + [Fact] + public void DemoPressure_price_ceiling_never_empty() + { + var prices = new[] { 10_000_000, 7_500_000, 60_000_000, 10_000_000 }; + foreach (var tier in DepthGrid()) + Assert.Contains(prices, price => price <= DemoPressure.PriceCeiling(prices, tier)); + Assert.Equal(prices.Min(), DemoPressure.PriceCeiling(prices, 0f)); + Assert.Equal(prices.Max(), DemoPressure.PriceCeiling(prices, 1f)); + } + + // The generator draws the function's numbers, not a parallel formula: every zone of the demo galaxy holds exactly the + // hostiles the curve asks of its depth, none dearer than its tier admits, and the mean count rises from the near third + // of the way to the far third. + [Fact] + public void DemoGalaxy_generated_pressure_follows_curve() + { + var byThird = new List[3] { new List(), new List(), new List() }; + foreach (var seed in DemoSeeds) + foreach (var row in DemoZones(seed)) + { + Assert.True(row.Hostiles == row.Asked.Hostiles, $"seed {seed} zone {row.Index}: {row.Hostiles} hostiles at depth {row.Depth:0.00}, the curve asks {row.Asked.Hostiles}"); + byThird[Math.Min(2, (int)(row.Depth * 3))].Add(row.Hostiles); + } + var means = byThird.Select(bucket => bucket.Average()).ToArray(); + Assert.True(means[0] <= means[1] && means[1] < means[2], string.Join(" ", means)); + } + + [Fact] + public void DemoGalaxy_hostile_hulls_stay_inside_the_tier() + { + foreach (var seed in DemoSeeds) + { + var (galaxy, _, _, _) = Launch(new DemoTerminus(), Inputs(() => seed)); + var antagonist = galaxy.Antagonist; + var offered = new LoadoutGenerator(ref _items.Random, _items, galaxy, galaxy.Exit, antagonist, .5f) + .OfferedShipHulls().Select(hull => hull.Price).ToArray(); + Assert.NotEmpty(offered); + foreach (var row in DemoZones(seed).Where(row => row.Hostiles > 0)) + { + var ceiling = DemoPressure.PriceCeiling(offered, row.Asked.Tier); + Assert.All(row.HostilePrices, price => Assert.True(price <= ceiling, $"seed {seed} zone {row.Index}: a {price} hull above the {ceiling} ceiling")); + } + } + } + + private static readonly uint[] RingSeeds = Enumerable.Range(1, 100).Select(seed => (uint)seed).ToArray(); + + private static GalaxyZone[] Ring(Galaxy galaxy) => galaxy.Entrance.AdjacentZones.Prepend(galaxy.Entrance).ToArray(); + + // Hated by the player: the antagonist's faction, by the standing the demo stages. + private bool IsHated(Galaxy galaxy, CultRecordRef faction) => + faction.IsSet() && galaxy.FactionRelationships[_cache.Get(faction)] == FactionRelationship.Hated; + + // The quiet start, pinned by its own literal and not by GraceDepth: the entrance and its jump-1 neighbours carry no hostile + // ship and no hostile station or turret, on a hundred seeds, and the guaranteed entrance station is there. + [Fact] + public void DemoGalaxy_entrance_ring_has_no_hostiles() + { + foreach (var seed in RingSeeds) + { + var (galaxy, _, _, _) = Launch(new DemoTerminus(), Inputs(() => seed)); + foreach (var zone in Ring(galaxy)) + { + var pack = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, galaxy, zone, DemoEntranceStations); + var hostile = pack.Entities.Where(entity => IsHated(galaxy, entity.Faction)).Select(entity => entity.GetType().Name + ":" + _items.GetData(entity.Hull).Name).ToArray(); + Assert.True(hostile.Length == 0, $"seed {seed} zone {Array.IndexOf(galaxy.Zones, zone)} (jump {galaxy.Entrance.Distance[zone]}): {string.Join(", ", hostile)}"); + } + var entrance = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, galaxy, galaxy.Entrance, DemoEntranceStations); + Assert.Contains(entrance.Entities.OfType(), entity => entity.Kind.IsSet()); + } + } + + // Every zone at jump >= 2 whose depth, derived here as e / (e + x) from the zone's own distances, is at most a quarter holds + // no ship, station or turret of a Hated faction: the grace as the literal 0.25, not as DemoPressure.GraceDepth or its depth term. + [Fact] + public void DemoGalaxy_grace_depth_by_literal() + { + var graced = 0; + foreach (var seed in RingSeeds) + { + var (galaxy, _, _, _) = Launch(new DemoTerminus(), Inputs(() => seed)); + foreach (var zone in galaxy.Zones) + { + float e = galaxy.Entrance.Distance[zone], x = galaxy.Exit.Distance[zone]; + if (e < 2 || e / (e + x) > 0.25f) continue; + graced++; + // The depth term itself: where no hostile would be drawn anyway (the curve's own ramp is 0 there), grace is + // what moves the antagonist's stations and turrets away, so it is asserted, not left to the generated zone. + Assert.True(DemoPressure.InGrace(galaxy, zone), $"seed {seed} zone {Array.IndexOf(galaxy.Zones, zone)} (jump {e}, depth {e / (e + x):0.00}) is not in grace"); + var pack = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, galaxy, zone, DemoEntranceStations); + var hostile = pack.Entities.Where(entity => IsHated(galaxy, entity.Faction)).Select(entity => entity.GetType().Name + ":" + _items.GetData(entity.Hull).Name).ToArray(); + Assert.True(hostile.Length == 0, $"seed {seed} zone {Array.IndexOf(galaxy.Zones, zone)} (jump {e}, depth {e / (e + x):0.00}): {string.Join(", ", hostile)}"); + } + } + Assert.True(graced > 0, "no zone at jump >= 2 has depth <= 0.25 on seeds 1-100"); + } + + // Depth runs from the entrance to the gate and nowhere outside them: 0 only at the entrance, 1 only at the exit, every other + // zone strictly between, including those behind the entrance (a clamped depth read them as 0). + [Fact] + public void DemoGalaxy_depth_spans_entrance_to_gate() + { + foreach (var seed in Enumerable.Range(1, 20).Select(seed => (uint)seed)) + { + var (galaxy, _, _, _) = Launch(new DemoTerminus(), Inputs(() => seed)); + foreach (var zone in galaxy.Zones) + { + var depth = DemoPressure.Depth(galaxy, zone); + if (zone == galaxy.Entrance) Assert.Equal(0f, depth); + else if (zone == galaxy.Exit) Assert.Equal(1f, depth); + else Assert.True(depth > 0f && depth < 1f, $"seed {seed} zone {Array.IndexOf(galaxy.Zones, zone)}: depth {depth}"); + } + } + } + + // The demo's galaxy raids with the faction whose gate it has, whatever else BossZones holds: a second boss zone for another + // faction nearer the entrance changes neither the antagonist nor the raiders of a mid-depth zone, and generates without refusing. + [Fact] + public void DemoGalaxy_antagonist_is_the_gate_faction() + { + var (galaxy, _, _, _) = Launch(new DemoTerminus(), Inputs(() => 1)); + var zhestokost = galaxy.Factions.Single(faction => faction.Name == "Zhestokost"); + Assert.Same(zhestokost, galaxy.Antagonist); + Assert.Contains(zhestokost, galaxy.BossZones.Keys); + + var near = galaxy.Entrance.AdjacentZones[0]; + galaxy.BossZones[galaxy.Factions.First(faction => faction != zhestokost)] = near; + Assert.Same(zhestokost, galaxy.Antagonist); + var mid = galaxy.Zones.Where(zone => zone != near && zone != galaxy.Exit && DemoPressure.Of(galaxy, zone).Hostiles > 0) + .MinBy(zone => Math.Abs(DemoPressure.Depth(galaxy, zone) - .5f)); + Assert.NotNull(mid); + var raiders = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, galaxy, mid, DemoEntranceStations) + .Entities.OfType().Where(ship => !ship.Boss && _cache.Get(ship.Faction) == zhestokost).ToArray(); + Assert.Equal(DemoPressure.Of(galaxy, mid).Hostiles, raiders.Length); + ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, galaxy, galaxy.Exit, DemoEntranceStations); + } + + // A galaxy with no gate antagonist keeps the nearest faction's patrol even where BossZones is filled (Main Galaxy's bosses): + // a zone's facts are the same with BossZones intact and cleared, which a scope keyed on BossZones would break. LongHaul has no gate. + [Fact] + public void MainGalaxy_patrol_ignores_boss_zones() + { + foreach (var seed in new uint[] { 1, 2, 3 }) + { + var (galaxy, _, _, _) = Launch(new MainGalaxy(), Inputs(() => seed)); + Assert.Null(galaxy.Antagonist); + Assert.NotEmpty(galaxy.BossZones); + var zone = galaxy.Zones.First(z => z != galaxy.Entrance && !galaxy.BossZones.ContainsValue(z)); + + var intactItems = LoggingItems(new List()); + var intact = ZoneFacts(intactItems, BossZonePack(galaxy, intactItems, zone)); + galaxy.BossZones.Clear(); + var clearedItems = LoggingItems(new List()); + var cleared = ZoneFacts(clearedItems, BossZonePack(galaxy, clearedItems, zone)); + Assert.True(intact == cleared, $"seed {seed}: BossZones changed an ambient zone\nintact:\n{intact}\ncleared:\n{cleared}"); + } + Assert.Null(Launch(new LongHaul(), Inputs(() => 1)).galaxy.Antagonist); + } + + // A save committed with key 18 unset (one from before it) restores no antagonist and generates the patrol, not raids. + [Fact] + public void SavedGame_without_antagonist_continues_unraided() + { + var (galaxy, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.Empty(failures); + galaxy.Entrance.Contents = arena; + var (game, zones) = RunSave.Capture(_cache, galaxy, arena, staged.Player, new SavedActionBarBinding[0], 0); + game.Antagonist = default; + RunSave.Commit(_cache, game, zones, _items.Lots); + var restored = new Galaxy(_cache, _cache.GetGlobal(), _ => { }); + Assert.Null(restored.Antagonist); + + string[] Hulls(Galaxy g, int index) => ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, g, g.Zones[index], DemoEntranceStations) + .Entities.OfType().Select(ship => _items.GetData(ship.Hull).Name).ToArray(); + var deep = DemoZones(1).Where(row => row.Asked.Hostiles >= 3).ToArray(); + Assert.NotEmpty(deep); + Assert.Contains(deep, row => !Hulls(galaxy, row.Index).SequenceEqual(Hulls(restored, row.Index))); + } + + // A zone as the player meets it: generated, with the demo's player staged into it and the generated ships' standing in force. + // adjust edits the generated pack before the arena is built. + private (Zone arena, Ship player) EnterZone(Galaxy galaxy, GalaxyZone zone, Action adjust = null) + { + var pack = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, galaxy, zone, DemoEntranceStations); + adjust?.Invoke(pack); + var arena = new Zone(_items, _planetSettings, pack, zone, galaxy); + var failures = new List(); + // The demo's player and stances, without its entrance's haul order: a ring arena holds no Zenith or refinery to order between. + var staged = RunStart.Stage(_items, arena, new Scripted(false, stage => + { + stage.Galaxy.FactionRelationships[stage.Galaxy.ResolveFaction(DemoTerminus.Cast.ProtagonistFaction)] = FactionRelationship.Friendly; + stage.Galaxy.FactionRelationships[stage.Galaxy.ResolveFaction(DemoTerminus.Cast.AntagonistFaction)] = FactionRelationship.Hated; + stage.Galaxy.FactionRelationships[stage.Galaxy.ResolveFaction(DemoTerminus.Cast.BufferFaction)] = FactionRelationship.Neutral; + foreach (var neutral in DemoTerminus.Cast.NeutralFactions) + stage.Galaxy.FactionRelationships[stage.Galaxy.ResolveFaction(neutral)] = FactionRelationship.Neutral; + stage.Player(stage.Generated("Longinus"), float2.zero); + }), _startingHull, failures); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + arena.Update(0); + return (arena, staged.Player); + } + + // No ship or structure of a Hated faction is in any ring arena at arrival, on the seeds where the generator once put one + // there. It claims no survival: whether the player lives is DemoGalaxy_pursuit_measure's printout and the operator's ruling. + [Fact] + public void DemoGalaxy_ring_arrival_has_no_hated_entity() + { + foreach (var seed in new uint[] { 1, 2, 3, 69, 97 }) + { + var (galaxy, _, _, _) = Launch(new DemoTerminus(), Inputs(() => seed)); + foreach (var zone in Ring(galaxy)) + { + var (arena, player) = EnterZone(galaxy, zone); + var hostile = arena.Entities.Where(entity => entity != player && entity.Faction != null && galaxy.FactionRelationships[entity.Faction] == FactionRelationship.Hated).Select(entity => entity.Name).ToArray(); + Assert.True(hostile.Length == 0, $"seed {seed} zone {Array.IndexOf(galaxy.Zones, zone)}: hostile to the player at arrival: {string.Join(", ", hostile)}"); + } + } + } + + // The pursuit measure, not an assertion of survival: set DEMO_PRESSURE_PURSUIT to a path to write it. In each seed's raided + // zone nearest the entrance (the smallest jump whose curve asks for hostiles), the staged default fit, AI-flown as the proxy for + // a played one, meets one antagonist raider of that zone's tier astern for 120 simulated seconds, the zone's own raiders removed + // so one pursuer is what is measured. Only that an engagement happened (some hull changed in some arena) is asserted: the + // outcome is a balance number for the operator (question demo-raider-balance), and no threshold here is a ruling. + [Fact] + public void DemoGalaxy_pursuit_measure() + { + const float Seconds = 120f; + var path = Environment.GetEnvironmentVariable("DEMO_PRESSURE_PURSUIT"); + if (string.IsNullOrEmpty(path)) return; + var lines = new List { "seed zone jump tier player-hull-start player-hull-end raider-hull-start raider-hull-end" }; + var engaged = false; + foreach (var seed in new uint[] { 1, 2, 3, 69, 97 }) + { + var (galaxy, _, _, _) = Launch(new DemoTerminus(), Inputs(() => seed)); + var antagonist = galaxy.Antagonist; + var zone = galaxy.Zones.Where(z => DemoPressure.Of(galaxy, z).Hostiles > 0).MinBy(z => galaxy.Entrance.Distance[z]); + var tier = DemoPressure.Of(galaxy, zone).Tier; + var (arena, player) = EnterZone(galaxy, zone, pack => pack.Entities.RemoveAll(entity => entity is ShipPack ship && !ship.Boss && _cache.Get(ship.Faction) == antagonist)); + + var generator = new LoadoutGenerator(ref _items.Random, _items, galaxy, zone, antagonist, .5f); + var ceiling = DemoPressure.PriceCeiling(generator.OfferedShipHulls().Select(hull => hull.Price).ToArray(), tier); + var pursuer = EntitySerializer.Unpack(_items, arena, generator.GenerateShipLoadout(hull => hull.Price <= ceiling)); + pursuer.Position = player.Position + CultMath.math.float3(0, 0, -300); + pursuer.SetIff(player, true); + player.SetIff(pursuer, true); + arena.Admit(pursuer, true); + Assert.True(arena.Remove(player)); + player.Deactivate(); + arena.Admit(player, true); + var (playerStart, raiderStart) = (player.Hull.Durability, pursuer.Hull.Durability); + for (var tick = 0; tick < MathF.Round(Seconds / SimClock.GameStep); tick++) arena.Update(SimClock.GameStep); + engaged |= player.Hull.Durability != playerStart || pursuer.Hull.Durability != raiderStart; + lines.Add($"{seed} {Array.IndexOf(galaxy.Zones, zone)} {galaxy.Entrance.Distance[zone]} {tier:0.00} {playerStart:0} {player.Hull.Durability:0} {raiderStart:0} {pursuer.Hull.Durability:0}"); + } + File.WriteAllLines(path, lines); + Assert.True(engaged, "no hull changed in any pursuit arena"); + } + + // Continue regenerates the same zone: the curve reads only the persisted Entrance, Exit and Antagonist, so a galaxy + // restored from the save draws the same hostile hulls as before it. + [Fact] + public void DemoGalaxy_continue_regenerates_same_zone() + { + var (galaxy, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.Empty(failures); + galaxy.Entrance.Contents = arena; + var (game, zones) = RunSave.Capture(_cache, galaxy, arena, staged.Player, new SavedActionBarBinding[0], 0); + RunSave.Commit(_cache, game, zones, _items.Lots); + var restored = new Galaxy(_cache, _cache.GetGlobal(), _ => { }); + + string[] Hulls(Galaxy g, int index) => ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, g, g.Zones[index], DemoEntranceStations) + .Entities.OfType().Select(ship => _items.GetData(ship.Hull).Name).ToArray(); + var deep = DemoZones(1).Where(row => row.Hostiles >= 3).ToArray(); + Assert.NotEmpty(deep); + foreach (var row in deep) + Assert.Equal(Hulls(galaxy, row.Index), Hulls(restored, row.Index)); + } +} diff --git a/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs b/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs index 54f46a57c..ec36ebb68 100644 --- a/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs +++ b/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs @@ -8,7 +8,7 @@ using System.Linq; using CultMath; using Xunit; -// The demo scenario (aetheria-release, cut demo-galaxy): a prelude galaxy of a fixed cast whose antagonist's home is the +// The demo scenario (aetheria-release, cut demo-galaxy): a galaxy of a fixed cast whose antagonist's home is the // boss zone and the exit. The cast, the Pirates included, is in the shipped catalog. public sealed partial class RunStartTests { @@ -24,6 +24,30 @@ public sealed partial class RunStartTests DemoGalaxy(seed).Factions.Select(faction => faction.Name)); } + // The entrance declares its stations as orders (ruling demo-zenith-ore-depot, demo-processing-station-buys-ore): on every seed, + // Aeronautics Unlimited's trade hub on Zenith and the Pirates' processing station with its Refinery, apart by at least their reaches. + [Fact] + public void DemoEntranceHoldsZenithAndTheRefinery() + { + var cellSize = _items.GameplaySettings.SchematicCellSize; + foreach (var seed in Enumerable.Range(1, 40).Select(s => (uint) s).Concat(new uint[] { 69, 97 })) + { + var (_, arena, _, failures) = Launch(new DemoTerminus(), Inputs(() => seed)); + Assert.True(failures.Count == 0, $"seed {seed}: " + string.Join("; ", failures)); + arena.Update(.02f); // the stations take their places on their orbits + var stations = arena.Entities.OfType().Where(entity => entity.HullData.HullType == HullType.Station).ToArray(); + Assert.True(stations.Length == 2, $"seed {seed}: {stations.Length} stations"); + var hub = stations.Single(station => station.Kind.Key.Equals(StationKindData.KeyOf("trade-hub"))); + var refinery = stations.Single(station => station.Kind.Key.Equals(StationKindData.KeyOf("processing"))); + Assert.Equal("Aeronautics Unlimited", hub.Faction.Name); + Assert.Equal("Pirates", refinery.Faction.Name); + Assert.Contains(refinery.Equipment, equipped => equipped.Behaviors.OfType().Any() && _items.GetData(equipped.EquippableItem).Name == "Refinery"); + var apart = math.length(hub.Position.xz - refinery.Position.xz); + var reaches = hub.HullData.Reach(cellSize) + refinery.HullData.Reach(cellSize); + Assert.True(apart >= reaches, $"seed {seed}: stations {apart} apart against a reach sum of {reaches}"); + } + } + [Fact] public void DemoTerminus_gate_at_antagonist_home() { @@ -64,6 +88,8 @@ public sealed partial class RunStartTests }, Standing(restored)); Assert.Equal(Standing(galaxy), Standing(restored)); Assert.Equal(Array.IndexOf(galaxy.Zones, galaxy.Exit), Array.IndexOf(restored.Zones, restored.Exit)); + Assert.Equal("Zhestokost", restored.Antagonist.Name); + Assert.Equal(_cache.RefOf(galaxy.Antagonist), _cache.RefOf(restored.Antagonist)); Assert.Equal( galaxy.BossZones.Select(boss => (boss.Key.Name, Array.IndexOf(galaxy.Zones, boss.Value))), restored.BossZones.Select(boss => (boss.Key.Name, Array.IndexOf(restored.Zones, boss.Value)))); @@ -82,16 +108,15 @@ public sealed partial class RunStartTests Assert.DoesNotContain(_cache.GetAll(), faction => faction.Name.StartsWith("Pirates", StringComparison.Ordinal)); var refusal = Assert.Throws(() => DemoGalaxy(1)); Assert.Contains("Pirates", refusal.Message); - Assert.Contains(nameof(TutorialGenerationSettings.ProtagonistFaction), refusal.Message); + Assert.Contains(nameof(GalaxyCast.ProtagonistFaction), refusal.Message); } - // The operator's ruling is that the first release is a demo: the one scenario a release build lists says so by name. + // The operator's ruling is that the first release is a demo: the run the simulation's exit launches says so by name. [Fact] public void DemoTerminus_is_named_a_demo() { - var listed = Assert.Single(Scenarios.Modes); - Assert.IsType(listed); - Assert.Equal("Terminus (Demo)", listed.Name); + Assert.IsType(Scenarios.Terminus); + Assert.Equal("Terminus (Demo)", Scenarios.Terminus.Name); } // The run start as New Game runs it: the player is not a Pirate, so the hull is the base Longinus, made by Alakrita, @@ -144,12 +169,12 @@ public sealed partial class RunStartTests string.Join(",", zone.AdjacentZones.Select(adjacent => Array.IndexOf(g.Zones, adjacent)).OrderBy(index => index)))); Galaxy Reference(uint seed, float density) { - var cast = new TutorialGenerationSettings + var cast = new GalaxyCast { ProtagonistFaction = "Pirates", AntagonistFaction = "Zhe", BufferFaction = "Luc", - NeutralFactions = new[] { "Aero" }, QuestFaction = null, ZoneCount = 64, LinkDensity = density + NeutralFactions = new[] { "Aero" }, QuestFaction = null, ZoneCount = 64, LinkDensity = density, InfluenceScale = .5f }; - return RunStart.Generate(new Scripted(false, _ => { }, seed, galaxy => galaxy.Prelude(cast)), Inputs()); + return RunStart.Generate(new Scripted(false, _ => { }, seed, stage => stage.Cast(cast)), Inputs()); } foreach (var seed in DemoSeeds) @@ -172,50 +197,43 @@ public sealed partial class RunStartTests // A name that resolves to nothing refuses the galaxy whichever cast field names it, and the refusal names the field. [Theory] - [InlineData(nameof(TutorialGenerationSettings.ProtagonistFaction))] - [InlineData(nameof(TutorialGenerationSettings.AntagonistFaction))] - [InlineData(nameof(TutorialGenerationSettings.BufferFaction))] - [InlineData(nameof(TutorialGenerationSettings.QuestFaction))] - [InlineData(nameof(TutorialGenerationSettings.NeutralFactions))] + [InlineData(nameof(GalaxyCast.ProtagonistFaction))] + [InlineData(nameof(GalaxyCast.AntagonistFaction))] + [InlineData(nameof(GalaxyCast.BufferFaction))] + [InlineData(nameof(GalaxyCast.QuestFaction))] + [InlineData(nameof(GalaxyCast.NeutralFactions))] public void AnUnresolvedCastNameRefusesTheGalaxyNamingItsField(string field) { - var cast = new TutorialGenerationSettings - { - ProtagonistFaction = _tutorialSettings.ProtagonistFaction, - AntagonistFaction = _tutorialSettings.AntagonistFaction, - BufferFaction = _tutorialSettings.BufferFaction, - QuestFaction = _tutorialSettings.QuestFaction, - NeutralFactions = _tutorialSettings.NeutralFactions, - ZoneCount = _tutorialSettings.ZoneCount, - LinkDensity = _tutorialSettings.LinkDensity - }; - typeof(TutorialGenerationSettings).GetField(field).SetValue(cast, field == nameof(cast.NeutralFactions) ? new[] { "Nonesuch" } : "Nonesuch"); - var scenario = new Scripted(false, _ => { }, generate: galaxy => galaxy.Prelude(cast)); + var cast = TestCasts.Wide; + typeof(GalaxyCast).GetField(field).SetValue(cast, field == nameof(cast.NeutralFactions) ? new[] { "Nonesuch" } : "Nonesuch"); + var scenario = new Scripted(false, _ => { }, generate: stage => stage.Cast(cast)); var refusal = Assert.Throws(() => RunStart.Generate(scenario, Inputs())); Assert.Contains(field, refusal.Message); } - // What a release build lists under New Game is the demo alone; the tutorial and the main galaxy are listed only in - // editor and development builds (MainMenu.ShowScenarios), beside the test arenas. + // What a release build lists under New Game is the simulation alone (ruling ifl-wormhole-exit-standin): the demo run + // is reached through its exit, and the main galaxy is listed only in editor and development builds + // (MainMenu.ShowScenarios), with the demo and the test arenas. [Fact] - public void ReleaseBuildsListOnlyTheDemo() + public void ReleaseBuildsListOnlyTheSimulation() { - Assert.Equal(new[] { typeof(DemoTerminus) }, Scenarios.Modes.Select(scenario => scenario.GetType())); - Assert.Equal(new[] { typeof(TutorialGalaxy), typeof(MainGalaxy) }, Scenarios.Development.Select(scenario => scenario.GetType())); + Assert.Equal(new[] { typeof(InfiniteFunLand) }, Scenarios.Modes.Select(scenario => scenario.GetType())); + Assert.Equal(new[] { typeof(MainGalaxy), typeof(DemoTerminus) }, Scenarios.Development.Select(scenario => scenario.GetType())); } - // The tutorial is the galaxy it was before the demo: its cast, homes, entrance and ownership at a fixed seed, with - // no exit and no boss zone. + // The wide test cast at half influence is the galaxy it was before the prelude was retired: its cast, homes, entrance + // and ownership at a fixed seed, with no exit and no boss zone. Homes, entrance and owners depend on InfluenceOf, so + // an InfluenceScale of 1 or a lost halving fails it. [Fact] - public void TutorialGalaxy_unchanged() + public void CastGalaxyAtHalfInfluenceIsUnchanged() { - var galaxy = RunStart.Generate(new TutorialGalaxy(), Inputs(() => GalaxySeed)); - Assert.Equal(TutorialSeed1, TutorialShape(galaxy)); - Assert.True(galaxy.Exit == null, "the tutorial has no exit"); - Assert.True(galaxy.BossZones.Count == 0, $"the tutorial has {galaxy.BossZones.Count} boss zones"); + var galaxy = RunStart.Generate(new Scripted(false, _ => { }, generate: stage => stage.Cast(TestCasts.Wide)), Inputs(() => GalaxySeed)); + Assert.Equal(WideCastSeed1, CastShape(galaxy)); + Assert.True(galaxy.Exit == null, "a cast galaxy has no exit until its scenario places the gate"); + Assert.True(galaxy.BossZones.Count == 0, $"the cast galaxy has {galaxy.BossZones.Count} boss zones"); } - private static string TutorialShape(Galaxy g) => + private static string CastShape(Galaxy g) => string.Join(",", g.Factions.Select(f => f.Name)) + " | homes " + string.Join(",", g.Factions.Select(f => g.HomeZones.TryGetValue(f, out var z) ? Array.IndexOf(g.Zones, z) : -2)) + " | entrance " + Array.IndexOf(g.Zones, g.Entrance) + @@ -223,6 +241,6 @@ public sealed partial class RunStartTests " | owners " + string.Join(",", g.Zones.Select(z => z.Owner == null ? "-" : z.Owner.ShortName)); // Measured at seed 1 under CultMath 0.3.0 (cultmath-unity-v0.3.0); the noise kernel changed there, which re-rolled the galaxy. - private const string TutorialSeed1 = + private const string WideCastSeed1 = "Miss Terri’s Sugariffic Snack Company,Zhestokost,Lucent Media,Adrasteia,Aeronautics Unlimited,Finch Cybernetics | homes 3,44,40,19,0,30 | entrance 12 | zones 64 | owners AU,AU,Finch,Miss Terri's,Lucent,Zhestokost,-,Lucent,AU,AU,Lucent,Adrasteia,-,Finch,Zhestokost,-,Adrasteia,-,AU,Adrasteia,AU,Zhestokost,Miss Terri's,-,AU,Finch,Miss Terri's,-,Zhestokost,-,Finch,-,-,AU,-,-,-,-,Miss Terri's,AU,Lucent,-,Finch,-,Zhestokost,AU,-,Zhestokost,Adrasteia,Adrasteia,AU,Miss Terri's,Finch,AU,Finch,-,Lucent,Zhestokost,-,AU,Miss Terri's,Zhestokost,-,Lucent"; } diff --git a/tests/Aetheria.Shared.Tests/DerivedPriceTests.cs b/tests/Aetheria.Shared.Tests/DerivedPriceTests.cs new file mode 100644 index 000000000..64a0564ea --- /dev/null +++ b/tests/Aetheria.Shared.Tests/DerivedPriceTests.cs @@ -0,0 +1,282 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// Made goods (commodities, and designs with a recipe) are priced from their chain at the raw wage (EconomyBalance.Prices); economy author writes the price and L-price +// refuses drift. Fixture chains are hand-solved. +public sealed class DerivedPriceTests +{ + private sealed class Lambda : EconomyBatch + { + private readonly Action _author; + public Lambda(Action author) => _author = author; + public override void Author(EconomyAuthor author) => _author(author); + } + + private static void Price(EconomyFixture f, string key, int price) => + f.EditItem(key, item => item.Price = price); + + // ore (raw, labour 20, price 50), salt (raw, labour 10, price 100) -> raw wages 2.5 and 10, wage 6.25; + // bar (2 per cycle from 3 ore, labour 10), part (2 bars, labour 4). Authored made prices are deliberately wrong. + private static EconomyFixture Chain(int scale = 1) + { + var f = new EconomyFixture(); + f.Good("ore", workforce: 2, cycle: 10); + f.Good("salt", workforce: 1, cycle: 10); + f.Good("bar", inputs: new[] { ("ore", 3) }, outputCount: 2, workforce: 2, cycle: 5); + f.Good("part", inputs: new[] { ("bar", 2) }, workforce: 1, cycle: 4); + Price(f, "commodity:ore", 50 * scale); + Price(f, "commodity:salt", 100 * scale); + Price(f, "commodity:bar", 1); + Price(f, "commodity:part", 1); + return f; + } + + private static int Author(EconomyFixture f, bool apply, out string output, params Action[] batches) + { + f.Cache.FlushAsync().GetAwaiter().GetResult(); + var writer = new StringWriter(); + var code = EconomyCommand.Author(f.CatalogPath, batches.Select(b => (EconomyBatch) new Lambda(b)).ToList(), apply, writer, TestCatalog.Registry()); + output = writer.ToString(); + return code; + } + + private static CultCache Read(EconomyFixture f) => AetheriaStores.Open(f.CatalogPath, registry: TestCatalog.Registry()); + + [Fact] + public void AMadeGoodIsPricedAtItsInputsPlusTheRawWage() + { + using var f = Chain(); + Assert.Equal(6.25, EconomyBalance.Wage(f.Cache), 9); + var prices = EconomyBalance.Prices(f.Cache, out _); + // bar = (3 x 50 + 6.25 x 10) / 2; the ore stays at its authored 50, not its labour cost 125. + Assert.Equal(106.25, prices["commodity:bar"], 9); + Assert.Equal(2 * 106.25 + 6.25 * 4, prices["commodity:part"], 9); + Assert.DoesNotContain("commodity:ore", prices.Keys); + } + + [Fact] + public void TheWageIsTheMedianOfRawLinks() + { + using var f = new EconomyFixture(); + f.Good("a", workforce: 1, cycle: 1); + f.Good("b", workforce: 1, cycle: 1); + f.Good("c", workforce: 1, cycle: 1); + f.Good("bar", inputs: new[] { ("a", 1) }, workforce: 1, cycle: 1); + Price(f, "commodity:a", 1); + Price(f, "commodity:b", 2); + Price(f, "commodity:c", 10); + Price(f, "commodity:bar", 100000); + Assert.Equal(2, EconomyBalance.Wage(f.Cache), 9); + } + + [Fact] + public void RawAndRecipelessPricesAreNotRepricedButADesignWithARecipeIs() + { + using var f = Chain(); + f.Cache.Upsert(typeof(SimpleCommodityData), new SimpleCommodityData { Name = "tin", Price = 7 }, new CultRecordKey("commodity:tin")); + var gear = f.Gear("laser", new[] { ("Plate", 1) }); + f.Good("plate", inputs: new[] { ("bar", 1) }, fills: new[] { "Plate" }, workforce: 1, cycle: 1); + f.EditItem(gear, g => g.Price = 12345); + var bare = f.Gear("bare", new (string, int)[0], recipe: false); + f.EditItem(bare, g => g.Price = 777); + Assert.Equal(0, Author(f, true, out _)); + using var after = Read(f); + Assert.Equal(50, after.Get(new CultRecordKey("commodity:ore")).Price); + Assert.Equal(100, after.Get(new CultRecordKey("commodity:salt")).Price); + Assert.Equal(7, after.Get(new CultRecordKey("commodity:tin")).Price); + Assert.Equal(777, after.Get(new CultRecordKey(bare)).Price); + // The laser takes one plate: a bar (106.25) and a worker-second of the 6.25 wage, 112.5 rounded half away from zero. + Assert.Equal(113, after.Get(new CultRecordKey(gear)).Price); + Assert.Equal(106, after.Get(new CultRecordKey("commodity:bar")).Price); + } + + // Kills: PriceCheck skipping designs, so a chained design's drift passes unseen. + [Fact] + public void AStaleDesignPriceIsAnLPriceFault() + { + using var f = Chain(); + f.Good("plate", inputs: new[] { ("bar", 1) }, fills: new[] { "Plate" }, workforce: 1, cycle: 1); + var gear = f.Gear("laser", new[] { ("Plate", 1) }); + f.Settle(); + f.EditItem(gear, g => g.Price = 5); + var stale = Assert.Single(EconomyChecks.PriceCheck(f.Cache)); + Assert.Equal(gear, stale.Record); + Assert.Equal(0, Author(f, true, out _)); + using var after = Read(f); + Assert.Empty(EconomyChecks.PriceCheck(after)); + } + + // Kills: repricing every design, whether or not it has a chain. + [Fact] + public void ADesignWithoutARecipeKeepsItsAuthoredPrice() + { + using var f = Chain(); + var bare = f.Gear("bare", new (string, int)[0], recipe: false); + f.EditItem(bare, g => g.Price = 777); + f.Settle(); + Assert.DoesNotContain(EconomyChecks.PriceCheck(f.Cache), x => x.Record == bare); + Assert.Equal(0, Author(f, true, out _)); + using var after = Read(f); + Assert.Equal(777, after.Get(new CultRecordKey(bare)).Price); + } + + [Fact] + public void AuthorRepricesAfterTheBatchesAndConverges() + { + using var f = Chain(); + // The batch sets a made good's price to 1; author runs after it and lists bar as changed, to the derived value. + Assert.Equal(0, Author(f, false, out var dry, a => a.SetPrice("commodity:bar", 1))); + Assert.Contains("changed commodity:bar", dry); + Assert.Contains("Dry run", dry); + Assert.Equal(0, Author(f, true, out _, a => a.SetPrice("commodity:bar", 1))); + using (var after = Read(f)) + { + Assert.Equal(106, after.Get(new CultRecordKey("commodity:bar")).Price); + Assert.Equal(238, after.Get(new CultRecordKey("commodity:part")).Price); + } + f.Reopen(); + Assert.Equal(0, Author(f, true, out var again)); + Assert.Contains("Nothing to write", again); + } + + [Fact] + public void AnAuthorBatchCannotKeepAMadePriceItChose() + { + using var f = Chain(); + Assert.Equal(0, Author(f, true, out _, a => a.SetPrice("commodity:part", 999999))); + using var after = Read(f); + Assert.Equal(238, after.Get(new CultRecordKey("commodity:part")).Price); + } + + [Fact] + public void AStaleMadePriceIsAnLPriceFault() + { + using var f = Chain(); + var stale = EconomyChecks.PriceCheck(f.Cache); + Assert.Equal(new[] { "commodity:bar", "commodity:part" }, stale.Select(x => x.Record).ToArray()); + Assert.All(stale, x => Assert.Equal(EconomyChecks.LPrice, x.Invariant)); + f.Settle(); + Assert.Empty(EconomyChecks.PriceCheck(f.Cache)); + // 106.25 rounds to 106 and 237.5 to 238 (half away from zero): a comparison without rounding would fault both. + Assert.Equal(106, f.Cache.Get(new CultRecordKey("commodity:bar")).Price); + Assert.Equal(238, f.Cache.Get(new CultRecordKey("commodity:part")).Price); + } + + [Fact] + public void ScalingRawPricesScalesMadePrices() + { + using var one = Chain(); + using var hundred = Chain(100); + var a = EconomyBalance.Prices(one.Cache, out _); + var b = EconomyBalance.Prices(hundred.Cache, out _); + foreach (var (key, price) in a) Assert.Equal(price * 100, b[key], 7); + } + + [Fact] + public void ShippedCatalogHasNoPriceFault() + { + using var cache = RestoredHullsTests.OpenCatalog(); + Assert.Empty(EconomyChecks.PriceCheck(cache)); + var prices = EconomyBalance.Prices(cache, out _); + Assert.NotEmpty(prices); + Assert.All(prices.Keys, key => Assert.True(cache.Get(new CultRecordKey(key)).Price >= 1)); + foreach (var name in new[] { "Water", "Methane", "Diamond" }) + Assert.True(cache.GetAll().Concat(cache.GetAll()).Single(i => i.Name == name).Price > 0, name); + } + + // ore (raw, price 50) feeds a, a feeds b, b feeds a again: the cycle's radius is sqrt(ratio), so 1 and 1.0005 are the edge cases. + private static EconomyFixture Cycle(int bPerA, int perBatch) + { + var f = new EconomyFixture(); + f.Good("ore", workforce: 1, cycle: 1); + Price(f, "commodity:ore", 50); + f.Good("a", inputs: new[] { ("ore", 1), ("b", 1) }); + f.Good("b", inputs: new[] { ("a", bPerA) }, outputCount: perBatch); + return f; + } + + [Theory] + [InlineData(4, 1)] + [InlineData(1001, 1000)] + [InlineData(1, 1)] + public void AChainThatDoesNotSettleHasNoPriceAndAuthorRefusesIt(int bPerA, int perBatch) + { + using var f = Cycle(bPerA, perBatch); + EconomyBalance.Prices(f.Cache, out var unsettled); + Assert.Equal(new[] { "commodity:a", "commodity:b" }, unsettled); + var fault = Assert.Single(EconomyChecks.Check(f.Cache).Faults, x => x.Invariant == EconomyChecks.LPrice); + Assert.Contains("a, b", fault.Message); + f.Cache.FlushAsync().GetAwaiter().GetResult(); + var bytes = File.ReadAllBytes(f.CatalogPath); + var code = Author(f, true, out var output); + Assert.Equal(1, code); + Assert.Contains("No price settles", output); + Assert.Contains("a, b", output); + Assert.Equal(bytes, File.ReadAllBytes(f.CatalogPath)); + } + + [Fact] + public void ACycleThatShrinksSettlesAndIsPriced() + { + using var f = Cycle(1, 2); + var prices = EconomyBalance.Prices(f.Cache, out var unsettled); + Assert.Empty(unsettled); + // a = 50 + b, b = a / 2: a = 100, b = 50. + Assert.Equal(100, prices["commodity:a"], 6); + Assert.Equal(50, prices["commodity:b"], 6); + } + + [Fact] + public void ADriftedMadePriceIsInTheReportAndAnIntroducedOneRefusesAuthor() + { + using var f = Chain(); + Assert.Equal(2, EconomyChecks.Check(f.Cache).Faults.Count(x => x.Invariant == EconomyChecks.LPrice)); + // Tool upkeep is a made good: pricing it moves the raw wage the made price reads, so the repriced catalog is itself off its derived price. + using var g = new EconomyFixture(); + g.Good("crude", workforce: 1, cycle: 1); + g.Good("fuel", inputs: new[] { ("crude", 1) }, workforce: 1, cycle: 1); + g.Good("ore", workforce: 1, cycle: 1, upkeep: new[] { ("fuel", 5) }); + Price(g, "commodity:ore", 300); + Price(g, "commodity:fuel", 1); + Price(g, "commodity:crude", 100); + g.Cache.FlushAsync().GetAwaiter().GetResult(); + var bytes = File.ReadAllBytes(g.CatalogPath); + Assert.Equal(1, Author(g, true, out var output)); + Assert.Contains("L-price", output); + Assert.Equal(bytes, File.ReadAllBytes(g.CatalogPath)); + } + + [Fact] + public void AMadePriceIsWholeCreditsAtLeastOneRoundedHalfAwayFromZero() + { + Assert.Equal(1, EconomyBalance.Rounded(0.2)); + Assert.Equal(1, EconomyBalance.Rounded(0)); + Assert.Equal(3, EconomyBalance.Rounded(2.5)); + Assert.Equal(4, EconomyBalance.Rounded(3.5)); + using var f = new EconomyFixture(); + f.Good("ore", workforce: 1, cycle: 1); + f.Good("dust", inputs: new[] { ("ore", 1) }, outputCount: 10, workforce: 1, cycle: 1); + Price(f, "commodity:ore", 1); + Assert.Equal(0.2, EconomyBalance.Prices(f.Cache, out _)["commodity:dust"], 9); + Assert.Equal(0, Author(f, true, out _)); + using var after = Read(f); + Assert.Equal(1, after.Get(new CultRecordKey("commodity:dust")).Price); + } + + [Fact] + public void UpkeepIsPartOfAMadeGoodsPrice() + { + using var f = new EconomyFixture(); + f.Good("ore", workforce: 1, cycle: 1); + f.Good("tool", workforce: 1, cycle: 1); + f.Good("bar", inputs: new[] { ("ore", 1) }, upkeep: new[] { ("tool", 2) }, workforce: 2, cycle: 1); + Price(f, "commodity:ore", 10); + Price(f, "commodity:tool", 5); + // Raw wages 10 and 5: wage 7.5. bar = 10 + 2 x 5 + 7.5 x 2. + Assert.Equal(35, EconomyBalance.Prices(f.Cache, out _)["commodity:bar"], 9); + } +} diff --git a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs index 7b7182400..eb21bf606 100644 --- a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs +++ b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs @@ -23,7 +23,6 @@ public sealed partial class RunStartTests { // The two-AI fight's digest, captured on Yggdrasil. Replays are trusted only on the host class that recorded them // (ruling replays-per-host-class), and arenas run on Linux. - private const string TwoAiPinnedHostClass = "linux-x64"; // Repinned twice, and the second repin has two causes (Soul measured the steps: group 1 + seed = f19b9992, + the Follow // gate = ce81a426; group 2 without the seed = bf586806). // First for the side split: the two fighters are unaffiliated, were one side and each followed itself (1b2ffe51). @@ -58,7 +57,20 @@ public sealed partial class RunStartTests // spread (station-reactor-spread), and that blob alone moved the digest (the same tree with the old catalog measured 52fbb10d; // traced: only Notorious Station moves it, because the zone's station Zenith carries a Notorious Station reactor lot whose // minted quality changes with the role spread, and Snapshot hashes every zone entity's heat and shield). - private const string TwoAiPinnedDigest = "9c70a3ee234fb3b879f721a4a4abf13dd83bf56fd8733690d356b89b8a392258"; + // Repinned a tenth time (hardpoint-fit-1): the Zenith's (11,6) radiator mount was rotation None and is now Clockwise, so the + // zone's generated station Zenith can fit a radiator there and Snapshot hashes its heat. windows-x64 133e5d76 -> e4a3d6e5, + // linux-x64 9c70a3ee -> 6b8b31ad (measured on Yggdrasil). The fight itself stages hand-fitted Longinus ships and a Bare Djinni, + // so the shields now on sale do not move it: the same catalog with only the Zenith rotation put back to None measures the old digest. + // Station packages: the Arsenal Depot (a station hull in the zone the fight runs in) moved both digests; linux-x64 6b8b31ad -> 99e358a0 + // measured on Yggdrasil, windows-x64 e4a3d6e5 -> 5201ca08 measured on Starfire. + // Station facility fit (cut station-facility-fit): the zone's station Zenith seats its kind's facilities before its docking bay and heater, + // which moves its gear; linux-x64 99e358a0 -> d80cc78c (Yggdrasil), windows-x64 5201ca08 -> 77e8a2f3 (Starfire). + private static readonly System.Collections.Generic.Dictionary TwoAiPinnedDigests = new() + { + ["linux-x64"] = "d80cc78c8ebf209c880a073db4294b9df57e5ab829da8b2dd3208e4654c9d1f8", + // Measured on windows-x64 at the commit that added this pin (the fight is one history there: TwoAiFightIsOneHistory). + ["windows-x64"] = "77e8a2f385b036b72ee75c69d1b86091190e48251af4e34c8b12481f34c5149e", + }; private const float TwoAiSeconds = 60f; [Fact] @@ -276,8 +288,8 @@ public sealed partial class RunStartTests { var host = HostClass(); var digest = TwoAiFight().digest; - Assert.True(host == TwoAiPinnedHostClass, - $"TWO-AI-DIGEST host class {host} has no pin (pinned: {TwoAiPinnedHostClass}); measured digest {digest}"); - Assert.True(digest == TwoAiPinnedDigest, $"TWO-AI-DIGEST {host} measured {digest}, pinned {TwoAiPinnedDigest}"); + Assert.True(TwoAiPinnedDigests.TryGetValue(host, out var pinned), + $"TWO-AI-DIGEST host class {host} has no pin (pinned: {string.Join(",", TwoAiPinnedDigests.Keys)}); measured digest {digest}"); + Assert.True(digest == pinned, $"TWO-AI-DIGEST {host} measured {digest}, pinned {pinned}"); } } diff --git a/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs b/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs index e7254fac6..7497e2e81 100644 --- a/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs +++ b/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs @@ -530,6 +530,26 @@ public sealed class DrawnPoseTests : IDisposable Assert.Equal(candidates.Select(c => c.Name).ToArray(), Kept("belt-0", 20)); } + // The mesh choice reads the belt's Site: whatever key the caller passes, a belt with a Site draws the same meshes, and without + // one the key decides (so a belt from before sites draws as it did). + [Fact] + public void TheDrawFollowsTheSite() + { + var w = Build(); + var belt = w.Zone.AsteroidBelts[w.Belt]; + var candidates = Enumerable.Range(0, 8).Select(i => new Candidate("c" + i, 1f + i)).ToArray(); + string Drawn(string key) + { + var list = DrawAhead.DrawListOf(belt, w.Zone.Settings, candidates, c => c.Radius, 3, new CultRecordKey(key)); + return string.Join(",", MeshOf(list, w.Asteroids.Length).Select(m => list.Meshes[m].Name)); + } + var keys = Enumerable.Range(0, 40).Select(i => "belt-" + i).ToArray(); + Assert.True(keys.Select(Drawn).Distinct().Count() > 1, "with no Site the key decides"); + belt.Data.Site = "7:belt:2"; + var first = Drawn(keys[0]); + foreach (var key in keys) Assert.Equal(first, Drawn(key)); + } + // A mined rock keeps its mesh and only shrinks: the assignment reads the unworn size. [Fact] public void AMinedRockKeepsItsMesh() diff --git a/tests/Aetheria.Shared.Tests/EconomyBalanceTests.cs b/tests/Aetheria.Shared.Tests/EconomyBalanceTests.cs new file mode 100644 index 000000000..a90cdbd8f --- /dev/null +++ b/tests/Aetheria.Shared.Tests/EconomyBalanceTests.cs @@ -0,0 +1,181 @@ +using System; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// The static economy balance (EconomyBalance): implied wage per chain link, prices derived from inputs and labour, the report-only +// health faults. Fixture chains are hand-solved; the shipped catalog test asserts reach, never a fault count (faults are tuning state). +public sealed class EconomyBalanceTests +{ + private static void Price(EconomyFixture f, string key, int price) + { + var item = f.Cache.Get(new CultRecordKey(key)); + item.Price = price; + f.Cache.Upsert(item.GetType(), item, new CultRecordKey(key)); + } + + private static void Labour(EconomyFixture f, string key, int workforce, float cycle) => + f.EditRecipe(key, r => { r.Workforce = workforce; r.Cycle = cycle; r.OutputCount = Math.Max(1, r.OutputCount); }); + + // ore (labour 20, price 50) -> bar (2 per cycle from 3 ore, labour 10, price 80) -> part (2 bars, labour 4, price 200), all times scale. + // Wages 2.5, 1, 10: median 2.5. Derived cost at 2.5: ore 50, bar (3 x 50 + 2.5 x 10) / 2 = 87.5, part 2 x 87.5 + 2.5 x 4 = 185. + private static EconomyFixture Chain(int scale = 1) + { + var f = new EconomyFixture(); + f.Good("ore", workforce: 2, cycle: 10); + f.Good("bar", inputs: new[] { ("ore", 3) }, outputCount: 2, workforce: 2, cycle: 5); + f.Good("part", inputs: new[] { ("bar", 2) }, workforce: 1, cycle: 4); + Price(f, "commodity:ore", 50 * scale); + Price(f, "commodity:bar", 80 * scale); + Price(f, "commodity:part", 200 * scale); + return f; + } + + private static BalanceLink Link(BalanceReport r, string key) => r.Links.Single(l => l.Output == key); + + [Fact] + public void ALinkSellingBelowItsInputsIsAMarginFault() + { + using var f = new EconomyFixture(); + f.Good("ore", workforce: 1, cycle: 1); + f.Good("bar", inputs: new[] { ("ore", 2) }, workforce: 1, cycle: 1); + Price(f, "commodity:ore", 10); + Price(f, "commodity:bar", 5); + var report = EconomyBalance.Balance(f.Cache); + var fault = Assert.Single(report.Faults, x => x.Invariant == EconomyBalance.HMargin); + Assert.Equal("commodity:bar", fault.Record); + Assert.Equal(-15, Link(report, "commodity:bar").Wage.Value, 9); + } + + [Fact] + public void TheCheaperFillerSetsTheDerivedCost() + { + using var f = new EconomyFixture(); + f.Good("ore", workforce: 1, cycle: 1); + // The dearer filler sorts first, so a first-filler pick and a max both read it. + f.Good("a-dear", inputs: new[] { ("ore", 3) }, fills: new[] { "Plate" }, workforce: 1, cycle: 1); + f.Good("z-cheap", inputs: new[] { ("ore", 1) }, fills: new[] { "Plate" }, workforce: 1, cycle: 1); + var gear = f.Gear("laser", new[] { ("Plate", 1) }); + Labour(f, gear, 1, 1); + Price(f, "commodity:ore", 10); + Price(f, "commodity:a-dear", 40); + Price(f, "commodity:z-cheap", 30); + f.EditItem(gear, g => g.Price = 100); + // The one raw link, the ore, earns 10: that is the wage. Cost: ore 10, a-dear 3 x 10 + 10 = 40, z-cheap 10 + 10 = 20, laser min(40, 20) + 10 = 30. + var report = EconomyBalance.Balance(f.Cache); + Assert.Equal(10, report.WageReference, 9); + Assert.Equal(30, Link(report, gear).Cost, 9); + } + + [Fact] + public void DerivedCostMatchesTheHandSolvedChain() + { + using var f = Chain(); + var report = EconomyBalance.Balance(f.Cache); + Assert.Equal(2.5, report.WageReference, 9); + Assert.Equal(50, Link(report, "commodity:ore").Cost, 9); + Assert.Equal(87.5, Link(report, "commodity:bar").Cost, 9); + Assert.Equal(185, Link(report, "commodity:part").Cost, 9); + } + + [Fact] + public void ScalingEveryPriceScalesTheWageAndNoFault() + { + using var one = Chain(); + using var hundred = Chain(100); + var a = EconomyBalance.Balance(one.Cache); + var b = EconomyBalance.Balance(hundred.Cache); + Assert.NotEmpty(a.Faults); + Assert.Equal(a.WageReference * 100, b.WageReference, 7); + Assert.Equal(a.Faults.Select(x => x.Invariant + x.Record), b.Faults.Select(x => x.Invariant + x.Record)); + foreach (var link in a.Links) Assert.Equal(link.WageRatio.Value, Link(b, link.Output).WageRatio.Value, 9); + } + + [Fact] + public void AnUnpricedLinkHasNoWage() + { + using var f = new EconomyFixture(); + f.Good("ore", workforce: 1, cycle: 1); + f.Good("bar", inputs: new[] { ("ore", 1) }, workforce: 1, cycle: 1); + f.Good("tin", workforce: 1, cycle: 1); + Price(f, "commodity:bar", 80); + Price(f, "commodity:tin", 7); + var report = EconomyBalance.Balance(f.Cache); + Assert.Null(Link(report, "commodity:ore").Wage); + Assert.Null(Link(report, "commodity:bar").Wage); + Assert.Equal(7, report.WageReference, 9); + Assert.Empty(report.Faults); + } + + [Fact] + public void AnUnpricedLinkNamesWhetherItsOutputOrAnInputIsFree() + { + using var f = new EconomyFixture(); + f.Good("ore", workforce: 1, cycle: 1); + f.Good("bar", inputs: new[] { ("ore", 1) }, workforce: 1, cycle: 1); + f.Good("tin", workforce: 1, cycle: 1); + Price(f, "commodity:bar", 80); + Price(f, "commodity:tin", 7); + var report = EconomyBalance.Balance(f.Cache); + Assert.Equal("output", Link(report, "commodity:ore").Unpriced); + Assert.Equal("input", Link(report, "commodity:bar").Unpriced); + Assert.Null(Link(report, "commodity:tin").Unpriced); + } + + [Fact] + public void AFreeFillerLeavesTheRoleUnpricedEvenWithAPricedOneBesideIt() + { + using var f = new EconomyFixture(); + f.Good("ore", workforce: 1, cycle: 1); + f.Good("a-free", inputs: new[] { ("ore", 1) }, fills: new[] { "Plate" }, workforce: 1, cycle: 1); + f.Good("z-priced", inputs: new[] { ("ore", 1) }, fills: new[] { "Plate" }, workforce: 1, cycle: 1); + var gear = f.Gear("laser", new[] { ("Plate", 1) }); + Labour(f, gear, 1, 1); + Price(f, "commodity:ore", 10); + Price(f, "commodity:z-priced", 30); + f.EditItem(gear, g => g.Price = 100); + var link = Link(EconomyBalance.Balance(f.Cache), gear); + Assert.Null(link.Wage); + Assert.Equal("input", link.Unpriced); + } + + [Fact] + public void TwoRecipesForOneOutputTakeTheCheaperDerivedCostInEitherOrder() + { + foreach (var cheapFirst in new[] { true, false }) + { + using var f = new EconomyFixture(); + f.Good("ore", workforce: 1, cycle: 1); + f.Good("bar", inputs: new[] { ("ore", cheapFirst ? 1 : 3) }, workforce: 1, cycle: 1); + f.Good("tin", workforce: 1, cycle: 1); + Price(f, "commodity:ore", 10); + Price(f, "commodity:bar", 80); + Price(f, "commodity:tin", 7); + // A second recipe for bar under its own key, written after the first, from a different input count. + var first = f.Cache.Get(RecipeData.KeyOf(new CultRecordKey("commodity:bar"))); + f.Cache.Upsert(typeof(RecipeData), new RecipeData + { + Output = first.Output, OutputCount = 1, Cycle = 1, Workforce = 1, StationKind = first.StationKind, Facility = first.Facility, LoreHook = "a good", + Inputs = new System.Collections.Generic.List { new CommodityCount { Commodity = EconomyFixture.Item("commodity:ore"), Count = cheapFirst ? 3 : 1 } } + }, new CultRecordKey("recipe:commodity:bar-alt")); + var report = EconomyBalance.Balance(f.Cache); + // Cost of one bar from one ore: ore cost plus the wage reference for one worker-second. + var ore = Link(report, "commodity:ore").Cost; + var cheap = ore + report.WageReference; + Assert.All(report.Links.Where(l => l.Output == "commodity:bar"), l => Assert.Equal(cheap, l.Cost, 9)); + } + } + + [Fact] + public void ShippedCatalogBalanceListsTheMaterializedChain() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var report = EconomyBalance.Balance(cache); + var expected = cache.GetAll().Count(r => cache.Get(r.Output) != null && r.OutputCount > 0 && float.IsFinite(r.Cycle)); + Assert.Equal(expected, report.Links.Count); + Assert.Contains(report.Links, l => l.Output == "commodity:steel"); + var guns = cache.GetAll().Where(r => Recipes.IsRoleRecipe(cache, r) && !Recipes.IsCommodity(cache.Get(r.Output))).Select(r => r.Output.Key.Value).ToArray(); + Assert.True(guns.Length >= 9); + Assert.All(guns, g => Assert.Contains(report.Links, l => l.Output == g)); + } +} diff --git a/tests/Aetheria.Shared.Tests/EconomyChecksTests.cs b/tests/Aetheria.Shared.Tests/EconomyChecksTests.cs index a9e0db99f..ae367846b 100644 --- a/tests/Aetheria.Shared.Tests/EconomyChecksTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyChecksTests.cs @@ -69,6 +69,26 @@ public sealed class EconomyChecksTests var ghost = f.Station("ghost", "Ghost"); f.EditRecipe(Ore, r => r.StationKind = ghost); }, "recipe:" + Ore, EconomyChecks.LOneKindList); + // L-facility: each clause fails its own case (ruling demand-consumed-inputs-processed-by-facilities). + const string Facility = EconomyChecks.LFacility; + yield return Case("an unset facility", f => f.EditRecipe(Ore, r => r.Facility = default), "recipe:" + Ore, Facility, "Facility is unset"); + yield return Case("a facility naming nothing", f => f.EditRecipe(Ore, r => r.Facility = EconomyFixture.Item("commodity:ghost")), "recipe:" + Ore, Facility, "names no item"); + yield return Case("a facility that is not facility gear", f => f.EditRecipe(Ore, r => r.Facility = EconomyFixture.Item("gear:laser")), "recipe:" + Ore, Facility, "not a recipe facility"); + yield return Case("a facility no kind lists", f => + { + // With no kind set the kind-mirror clause has nothing to say, so only the listing clause speaks. + var orphan = f.FacilityGear("orphan-works"); + f.EditRecipe(Ore, r => { r.Facility = orphan; r.StationKind = default; }); + }, "recipe:" + Ore, Facility, "No station kind lists"); + yield return Case("a kind that does not list its recipe's facility", f => + { + var forge = f.Station("forge", "Forge"); + f.EditItem(forge.Key.Value, kind => kind.Facilities = new List> { f.FacilityGear("forge-works") }); + f.EditRecipe(Ore, r => r.StationKind = forge); + }, "recipe:" + Ore, Facility, "Station kind 'Forge' does not list"); + yield return Case("a kind listing gear that is not a facility", f => f.EditItem("station-kind:mill", kind => kind.Facilities.Add(EconomyFixture.Item("gear:laser"))), "station-kind:mill", Facility, "Facilities[1]"); + yield return Case("facility gear on a Tool hardpoint", f => f.EditItem("gear:laser", gear => gear.Behaviors.Add(new FacilityData())), "gear:laser", Facility, "holds a FacilityData"); + yield return Case("a served kind whose hull has no Facility row", f => f.EditItem("hull:yard", hull => hull.Hardpoints.Clear()), "station-facilities", Facility, "Yard"); } [Theory] @@ -86,6 +106,83 @@ public sealed class EconomyChecksTests if (invariant == EconomyChecks.LOneKindList) Assert.DoesNotContain(faults, x => x.Invariant == EconomyChecks.LRecipe); } + private static readonly CultRecordKey StonyKey = new CultRecordKey("field-kind:stony"); + private static readonly CultRecordKey PlainKey = new CultRecordKey("province:plain"); + + // The Healthy catalog with one field kind yielding the ore and one province that draws the kind and the ore. + private static EconomyFixture WithGround() + { + var f = EconomyFixture.Healthy(); + var ore = new CultRecordRef(new CultRecordKey(Ore)); + f.Cache.Upsert(typeof(FieldKindData), new FieldKindData + { + Name = "Stony", CrossSection = 5, GenerationWeight = 1, + Yields = new List { new FieldYield { Commodity = ore, Abundance = 2 } } + }, StonyKey); + f.Cache.Upsert(typeof(ProvinceData), new ProvinceData + { + Name = "Plain", GenerationWeight = 1, + Kinds = new List { new ProvinceKindWeight { Kind = new CultRecordRef(StonyKey), Weight = 1 } }, + Ores = new List { new ProvinceOre { Commodity = ore, Weight = 1 } } + }, PlainKey); + return f; + } + + private static void EditKind(EconomyFixture f, Action edit) + { + var kind = f.Cache.Get(StonyKey); + edit(kind); + f.Cache.Upsert(typeof(FieldKindData), kind, StonyKey); + } + + private static void EditProvince(EconomyFixture f, Action edit) + { + var province = f.Cache.Get(PlainKey); + edit(province); + f.Cache.Upsert(typeof(ProvinceData), province, PlainKey); + } + + public static IEnumerable BadWeights() + { + object[] Case(string name, Action mutate, string record, string says) => new object[] { name, mutate, record, says }; + var ghost = new CultRecordKey("commodity:ghost"); + yield return Case("negative kind weight", f => EditKind(f, k => k.GenerationWeight = -1), StonyKey.Value, "GenerationWeight"); + yield return Case("NaN kind weight", f => EditKind(f, k => k.GenerationWeight = float.NaN), StonyKey.Value, "GenerationWeight"); + yield return Case("infinite kind weight", f => EditKind(f, k => k.GenerationWeight = float.PositiveInfinity), StonyKey.Value, "GenerationWeight"); + yield return Case("negative abundance", f => EditKind(f, k => k.Yields[0].Abundance = -0.5f), StonyKey.Value, "Yields[0].Abundance"); + yield return Case("a yield naming nothing", f => EditKind(f, k => k.Yields.Add(new FieldYield { Commodity = new CultRecordRef(ghost), Abundance = 1 })), StonyKey.Value, "Yields[1].Commodity"); + yield return Case("an unset yield", f => EditKind(f, k => k.Yields.Add(new FieldYield { Abundance = 1 })), StonyKey.Value, "Yields[1].Commodity"); + yield return Case("negative province cards", f => EditProvince(f, p => p.GenerationWeight = -1), PlainKey.Value, "GenerationWeight"); + yield return Case("negative kind factor", f => EditProvince(f, p => p.Kinds[0].Weight = -1), PlainKey.Value, "Kinds[0].Weight"); + yield return Case("a province kind naming nothing", f => EditProvince(f, p => p.Kinds.Add(new ProvinceKindWeight { Kind = new CultRecordRef(new CultRecordKey("field-kind:ghost")), Weight = 1 })), PlainKey.Value, "Kinds[1].Kind"); + yield return Case("negative ore factor", f => EditProvince(f, p => p.Ores[0].Weight = -1), PlainKey.Value, "Ores[0].Weight"); + yield return Case("a province ore naming nothing", f => EditProvince(f, p => p.Ores.Add(new ProvinceOre { Commodity = new CultRecordRef(ghost), Weight = 1 })), PlainKey.Value, "Ores[1].Commodity"); + } + + [Theory] + [MemberData(nameof(BadWeights))] + public void WeightsRefuseBadGround(string name, Action mutate, string record, string says) + { + using var f = WithGround(); + Assert.Empty(EconomyChecks.Weights(f.Cache)); + mutate(f); + var faults = EconomyChecks.Weights(f.Cache); + var matched = faults.Where(x => x.Invariant == EconomyChecks.LWeights && x.Record == record && x.Message.Contains(says)).ToArray(); + Assert.True(matched.Length > 0, name + ": " + string.Join(" | ", faults)); + // The rule is part of Check, and EconomyCommand refuses on it. + Assert.Contains(EconomyChecks.Check(f.Cache).Faults, x => x.Invariant == EconomyChecks.LWeights && x.Record == record); + } + + // A zero weight is a legal 'never drawn', not a fault. + [Fact] + public void WeightsAllowZero() + { + using var f = WithGround(); + EditKind(f, k => { k.GenerationWeight = 0; k.Yields[0].Abundance = 0; }); + EditProvince(f, p => { p.GenerationWeight = 0; p.Kinds[0].Weight = 0; p.Ores[0].Weight = 0; }); + Assert.Empty(EconomyChecks.Weights(f.Cache)); + } + [Fact] public void RecipeRefusesARecipeUnderTheWrongKey() { diff --git a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs index 9557f27a1..eef44b82c 100644 --- a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs @@ -81,7 +81,7 @@ public sealed class EconomyCommandTests else a.Put(new CompoundCommodityData { Name = id }, key); a.Put(new RecipeData { - Output = EconomyFixture.Item(key.Value), StationKind = kind ?? f.Mill, LoreHook = lore, + Output = EconomyFixture.Item(key.Value), StationKind = kind ?? f.Mill, Facility = f.MillWorks, LoreHook = lore, Inputs = (inputs ?? Array.Empty<(string, int)>()).Select(i => new CommodityCount { Commodity = EconomyFixture.Item(EconomyFixture.Key(i.Id)), Count = i.Count }).ToList(), Fills = (fills ?? Array.Empty()).ToList() }, RecipeData.KeyOf(key)); @@ -334,10 +334,25 @@ public sealed class EconomyCommandTests Assert.Contains("economy report | author", output.ToString()); } + [Fact] + public void BalanceOnTheShippedCatalogPrintsEveryLinkAndBeltRow() + { + using var db = AetherDb.OpenShipped(); + var report = EconomyBalance.Balance(db.Cache); + var output = new StringWriter(); + EconomyCommand.Balance(db.Cache, 2, output); + var text = output.ToString(); + Assert.Contains("Links by wage over the median", text); + Assert.Contains("Belts (", text); + foreach (var l in report.Links) Assert.Contains($" {l.Output} ({l.Name}) | ", text); + foreach (var belt in report.Belts) Assert.Contains($" {belt.Kind}: price ", text); + foreach (var l in report.Links.Where(l => l.Wage == null)) Assert.Contains($"unpriced {l.Unpriced}", text); + } + [Fact] public void ReportOnTheShippedCatalogGoesToTheGivenWriterAndNeverToConsole() { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenShipped(); var expected = new StringWriter(); var expectedCode = EconomyCommand.Report(db.Cache, expected); var output = new StringWriter(); @@ -502,6 +517,7 @@ public sealed class EconomyCommandTests var f = EconomyFixture.Healthy(); f.Good("loopa", inputs: new[] { ("loopb", 1) }); f.Good("loopb", inputs: new[] { ("loopa", 2) }); + f.Settle(); return f; } @@ -595,7 +611,7 @@ public sealed class EconomyCommandTests { var key = new CultRecordKey(EconomyFixture.Key(id)); f.Cache.Upsert(typeof(SimpleCommodityData), new SimpleCommodityData { Name = id }, key); - f.Cache.Upsert(typeof(RecipeData), new RecipeData { Output = EconomyFixture.Item(key.Value), StationKind = f.Mill, LoreHook = "a good", Inputs = new List() }, RecipeData.KeyOf(key)); + f.Cache.Upsert(typeof(RecipeData), new RecipeData { Output = EconomyFixture.Item(key.Value), StationKind = f.Mill, Facility = f.MillWorks, LoreHook = "a good", Inputs = new List() }, RecipeData.KeyOf(key)); } [Fact] diff --git a/tests/Aetheria.Shared.Tests/EconomyDrainTests.cs b/tests/Aetheria.Shared.Tests/EconomyDrainTests.cs new file mode 100644 index 000000000..418224f07 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/EconomyDrainTests.cs @@ -0,0 +1,191 @@ +using System; +using System.IO; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// The station-drain stage of `economy balance --drain` (EconomyDrain) on the demo run of seed 1: the shipped refinery stalls Room the +// moment a sale fills it, the trade hub's silo and stock bay take ore apart, and the window by steps agrees with the window by spans. +public sealed class EconomyDrainTests +{ + private static string Root => RunStartTests.FindRepoRoot(); + + // The base loop's sorties of seed 1, mined once: the one belt of the seed, capped, 131 units of mixed ore. + private static readonly Lazy Seed1 = new Lazy(() => EconomyLoop.Sorties(RunStartTests.FindRepoRoot(), 1, 150).ToArray()); + + private static string Printed(DrainSample sample) + { + var text = new StringWriter(); + EconomyDrain.Print(sample, text); + return text.ToString(); + } + + private static StationDrain Station(DrainSample sample, string role) => sample.Stations.Single(station => station.Role == role); + + // Room for outputs: the refinery's starting gear put away once the sale has filled the bay. + private static void PutGearAway(DemoArena demo) + { + foreach (var bay in demo.Processing.CargoBays) + foreach (var gear in bay.Cargo.Keys.Where(item => !(item is ICommodityStack)).ToList()) bay.Remove(gear); + } + + [Fact] + public void DrainIsDeterministic() + { + var first = Printed(EconomyDrain.Run(Root, 1, 30, 2, Seed1.Value)); + var second = Printed(EconomyDrain.Run(Root, 1, 30, 2, Seed1.Value)); + Assert.Equal(first, second); + Assert.Contains("Station drain, seed 1", first); + } + + // The sortie rig after Boot was lifted out of it, on the shipped catalog, read at the commit before the extraction. + [Fact] + public void SortieOutputUnchangedByBoot() + { + var sample = Seed1.Value.Single(); + Assert.Equal((131, 73, 58), (sample.Units, sample.UnitsSold, sample.UnitsRefused)); + Assert.Equal(1295, sample.SellValue); + Assert.Equal(150, sample.SimSeconds, 3); + Assert.Equal(131, sample.Mined.Sum(m => m.Units)); + } + + // A drain copy shares no object with the live station: EntitySerializer.Pack alone puts the live stacks in the pack, so a copy + // made from it would move the original's units when it sells or takes (Soul s1, copy-isolation-unpinned). + [Fact] + public void ACopyNeverSharesObjectsWithTheLiveStation() + { + using var demo = EconomyLoop.Boot(Root, 1); + var ore = demo.Cache.GetAll().First(design => FieldKinds.IsOre(demo.Cache, design)); + Assert.True(demo.Zenith.CargoBays.Any(bay => bay.TryStore(new SimpleCommodity { Data = new CultRecordRef(demo.Cache.RefOf(ore).Key), Quantity = 5 }))); + var live = demo.Zenith.CargoBays.SelectMany(bay => bay.Cargo.Keys).ToList(); + Assert.Contains(live, item => item is ICommodityStack); + + var copy = EconomyDrain.Copy(demo, demo.Zenith); + var copied = copy.CargoBays.SelectMany(bay => bay.Cargo.Keys).ToList(); + Assert.Equal(live.Count, copied.Count); + Assert.DoesNotContain(copied, item => live.Any(held => ReferenceEquals(held, item))); + + long Units(Entity entity) => entity.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()).Sum(stack => (long) stack.Quantity); + var before = Units(demo.Zenith); + foreach (var bay in copy.CargoBays) + foreach (var stack in bay.Cargo.Keys.OfType().ToList()) bay.Remove((ItemInstance) stack); + Assert.Equal(before, Units(demo.Zenith)); + Assert.Equal(0, Units(copy)); + } + + [Fact] + public void WindowAgreesWithSpans() + { + // Long enough for the first cycle to end: Room is inside the window, not only the horizon (Soul s1, window-stall-vacuous). + var sample = EconomyDrain.Run(Root, 1, 700, 1, Seed1.Value); + Assert.All(sample.Stations, station => Assert.Empty(station.WindowDisagreements)); + Assert.DoesNotContain(EconomyDrain.Report(new[] { sample }), fault => fault.Invariant == EconomyDrain.HSim); + Assert.True(Station(sample, "processing").Facilities.Single().WindowSteps.TryGetValue(Stall.Room, out var roomSteps) && roomSteps > 0); + + // A facility that does not run on screen while the spans run it: the held counts and the run part. + var off = EconomyDrain.Run(Root, 1, 120, 1, Seed1.Value, beforeWindow: demo => + { + foreach (var unit in demo.Processing.Equipment.Where(item => item.Behaviors.OfType().Any())) unit.Enabled.Value = false; + }); + Assert.NotEmpty(Station(off, "processing").WindowDisagreements); + Assert.Contains(EconomyDrain.Report(new[] { off }), fault => fault.Invariant == EconomyDrain.HSim && fault.Record == "seed 1 processing"); + } + + // The screen one step ahead of the span path, which no held count sees: a facility with room has the same units held and a run + // 0.02 s further on (Soul s1, hsim-blind-to-time-skew). + [Fact] + public void WindowSeesATimeSkew() + { + var even = EconomyDrain.Run(Root, 1, 120, 1, Seed1.Value, beforeWindow: PutGearAway); + Assert.Empty(Station(even, "processing").WindowDisagreements); + + var skewed = EconomyDrain.Run(Root, 1, 120, 1, Seed1.Value, beforeWindow: PutGearAway, onStep: (demo, step) => + { + if (step == 0) demo.Arena.Update(EconomyLoop.Step); + }); + var parted = Station(skewed, "processing").WindowDisagreements; + Assert.Single(parted); + Assert.Contains("run", parted[0]); + Assert.Contains(EconomyDrain.Report(new[] { skewed }), fault => fault.Invariant == EconomyDrain.HSim); + } + + [Fact] + public void AFullRefineryIsAStallFault() + { + var shipped = EconomyDrain.Run(Root, 1, 30, 4, Seed1.Value); + var refinery = Station(shipped, "processing"); + Assert.True(refinery.Filled); + Assert.Equal(Stall.Room, refinery.Facilities.Single().HorizonEnd); + Assert.NotNull(refinery.FirstRoomStall); + var fault = Assert.Single(EconomyDrain.Report(new[] { shipped }), f => f.Invariant == EconomyDrain.HStall); + Assert.Contains("Room", fault.Message); + + // The sale fills every cell: a bay emptied before the fill is filled again by the next sortie. With the starting gear put + // away after the fill (eight cells) there is room for outputs: the ore drains to nothing, the block reports how long that + // takes, and the stall is Inputs, not a fault. + var made = EconomyDrain.Run(Root, 1, 30, 24, Seed1.Value, beforeWindow: PutGearAway); + var roomy = Station(made, "processing"); + Assert.Contains(roomy.Outputs, pile => pile.Hourly.Any(units => units > 0)); + Assert.NotNull(roomy.Ores[0].EmptyAt); + Assert.Null(roomy.FirstRoomStall); + Assert.Equal(Stall.Inputs, roomy.Facilities.Single().HorizonEnd); + Assert.DoesNotContain(EconomyDrain.Report(new[] { made }), f => f.Invariant == EconomyDrain.HStall); + } + + // A sortie the base loop faults is a fault of its own and no sortie of the fill count (Soul s1, fill-count-artifact). + [Fact] + public void AFaultedSortieIsReportedAndLeftOutOfTheFill() + { + var mined = Seed1.Value.Single().Mined; + var ammoOut = new LoopSample { Seed = 1, Belt = 0, Belts = 2, BeltKind = "Carbonaceous", Outcome = LoopOutcome.AmmoOut, SimSeconds = 12.4, Units = 18, Mined = mined }; + var rig = new LoopSample { Seed = 1, Belt = 1, Belts = 2, BeltKind = "Metallic", Outcome = LoopOutcome.RigFault, Note = "no rock of the belt could be targeted" }; + + var none = EconomyDrain.Run(Root, 1, 20, 1, new[] { ammoOut, rig }); + Assert.Equal(0, none.Usable); + Assert.Equal(2, none.Excluded.Count); + Assert.All(none.Stations, station => Assert.Empty(station.Sorties)); + Assert.Equal(2, EconomyDrain.Report(new[] { none }).Count(fault => fault.Invariant == EconomyDrain.HSortie)); + Assert.Contains("sorties usable 0 of 2", Printed(none)); + + var some = EconomyDrain.Run(Root, 1, 20, 1, new[] { ammoOut }.Concat(Seed1.Value).ToArray()); + Assert.Equal(1, some.Usable); + Assert.Single(EconomyDrain.Report(new[] { some }), fault => fault.Invariant == EconomyDrain.HSortie); + Assert.Equal(EconomyDrain.Run(Root, 1, 20, 1, Seed1.Value).Stations[1].Sorties.Count, some.Stations[1].Sorties.Count); + } + + [Fact] + public void DrainRefusesLoopAndStrayOptions() + { + var refused = new[] + { + new[] { "balance", "--drain", "--loop" }, + new[] { "balance", "--loop", "1", "--window", "5" }, + new[] { "balance", "--drain", "--cap", "5" }, + new[] { "balance", "--drain", "--horizon", "0" }, + new[] { "balance", "--drain", "--window" }, + new[] { "balance", "--loop", "1", "--cap", "1e39" } + }; + foreach (var args in refused) + { + var output = new StringWriter(); + Assert.Equal(1, EconomyCommand.Run(args, output)); + Assert.Contains("balance --drain [...]", output.ToString()); + } + } + + [Fact] + public void IntakeSplitsSiloAndStock() + { + var sample = EconomyDrain.Run(Root, 1, 20, 1, Seed1.Value); + var zenith = Station(sample, "trade-hub"); + var silo = zenith.Bays.Single(bay => bay.Silo); + var stock = zenith.Bays.Single(bay => !bay.Silo); + Assert.Equal(("Nickel-Iron", 640), silo.Capacity.First(c => c.Ore == "Nickel-Iron")); + Assert.Equal(("Nickel-Iron", 80), stock.Capacity.First(c => c.Ore == "Nickel-Iron")); + // Onward-haul ore goes to the silo only (ore-haul-run): the stock bay holds room for it but takes none. + Assert.True(silo.Taken > 0); + Assert.Equal(0, stock.Taken); + Assert.Equal(zenith.Sorties.Sum(sale => sale.Sold), silo.Taken); + Assert.Equal(1, sample.Parked); + } +} diff --git a/tests/Aetheria.Shared.Tests/EconomyFixture.cs b/tests/Aetheria.Shared.Tests/EconomyFixture.cs index 3aba1fe05..8cb77212d 100644 --- a/tests/Aetheria.Shared.Tests/EconomyFixture.cs +++ b/tests/Aetheria.Shared.Tests/EconomyFixture.cs @@ -13,6 +13,8 @@ public sealed class EconomyFixture : IDisposable public CultCache Cache { get; private set; } public CultRecordRef Maker { get; private set; } public CultRecordRef Mill { get; private set; } + // The facility design Mill's recipes name: facility gear no faction offers (NotOffered), 2x2, on a Facility row. + public CultRecordRef MillWorks { get; private set; } public EconomyFixture() { @@ -22,7 +24,11 @@ public sealed class EconomyFixture : IDisposable Cache.Upsert(new InputLayout { Rows = new InputLayoutRow[] { new InputLayoutRowSpacer { Height = 1 } } }); Maker = new CultRecordRef(Cache.Upsert(new Faction { Name = "Maker", ShortName = "MKR" }).Key); Mill = Station("mill", "Mill"); - Sell(Cache.Upsert(typeof(HullData), new HullData { Name = "Yard", HullType = HullType.Station, Kind = Mill, Shape = new Shape(), Price = 1 }, new CultRecordKey("hull:yard"))); + MillWorks = FacilityGear("mill-works"); + var mill = Cache.Get(Mill.Key); + mill.Facilities = new List> { MillWorks }; + Cache.Upsert(typeof(StationKindData), mill, Mill.Key); + Sell(Cache.Upsert(typeof(HullData), new HullData { Name = "Yard", HullType = HullType.Station, Kind = Mill, Shape = new Shape(), Price = 1, Hardpoints = { FacilityRow() } }, new CultRecordKey("hull:yard"))); } public void Dispose() @@ -42,6 +48,28 @@ public sealed class EconomyFixture : IDisposable public static CultRecordRef Item(string key) => new CultRecordRef(new CultRecordKey(key)); public static string Key(string id) => "commodity:" + id; + private static Shape Solid(int width, int height) + { + var shape = new Shape(width, height); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + return shape; + } + + // A 2x2 Facility row, which takes any 2x2 facility design. + public static HardpointData FacilityRow() => new HardpointData { Type = HardpointType.Facility, Position = new CultMath.int2(0, 0), Shape = Solid(2, 2), Transform = "Fa.1" }; + + // A recipe facility design: Facility gear, 2x2, sold by the maker NotOffered (a design with no product is an unsold design). + public CultRecordRef FacilityGear(string id) + { + var key = new CultRecordKey("gear:" + id); + Cache.Upsert(typeof(GearData), new GearData + { + Name = id, Hardpoint = HardpointType.Facility, Shape = Solid(2, 2), Price = 1, Behaviors = new List { new FacilityData() } + }, key); + Cache.Upsert(new FactionProductData { Name = key.Value, Design = new CultRecordRef(key), Manufacturer = Maker, NotOffered = true }); + return Item(key.Value); + } + public CultRecordRef Station(string id, string name) { var key = StationKindData.KeyOf(id); @@ -56,7 +84,7 @@ public sealed class EconomyFixture : IDisposable // the roles its recipe takes, any filler will do. public string Good(string id, (string Id, int Count)[] inputs = null, string[] fills = null, int outputCount = 1, float cycle = 1, int workforce = 0, (string Id, int Count)[] upkeep = null, string lore = "a good", (string Role, int Count)[] roles = null, CultRecordRef? kind = null, - (string Role, int Count)[] roleInputs = null) + (string Role, int Count)[] roleInputs = null, CultRecordRef? facility = null) { var key = new CultRecordKey(Key(id)); var roleList = (roles ?? Array.Empty<(string, int)>()).Select(r => new ItemRole { Name = r.Role, Count = r.Count }).ToList(); @@ -71,6 +99,7 @@ public sealed class EconomyFixture : IDisposable Inputs = (inputs ?? Array.Empty<(string, int)>()).Select(i => new CommodityCount { Commodity = Item(Key(i.Id)), Count = i.Count }).ToList(), Upkeep = (upkeep ?? Array.Empty<(string, int)>()).Select(i => new CommodityCount { Commodity = Item(Key(i.Id)), Count = i.Count }).ToList(), StationKind = kind ?? Mill, + Facility = facility ?? MillWorks, LoreHook = lore, Fills = (fills ?? Array.Empty()).ToList(), RoleInputs = (roleInputs ?? Array.Empty<(string, int)>()).Select(r => new ItemRole { Name = r.Role, Count = r.Count }).ToList() @@ -99,6 +128,7 @@ public sealed class EconomyFixture : IDisposable Name = id, HullType = type, Shape = new Shape(), Price = 1, Kind = type == HullType.Station ? Mill : default, Roles = roles.Select(r => new ItemRole { Name = r.Role, Count = r.Count }).ToList() }, key); + if (type == HullType.Station) EditItem(key.Value, hull => hull.Hardpoints.Add(FacilityRow())); Design(key, offered, recipe); return key.Value; } @@ -110,7 +140,7 @@ public sealed class EconomyFixture : IDisposable Name = key.Value, Design = new CultRecordRef(key), Manufacturer = Maker, NotOffered = !offered }); if (recipe) - Cache.Upsert(typeof(RecipeData), new RecipeData { Output = Item(key.Value), StationKind = Mill }, RecipeData.KeyOf(key)); + Cache.Upsert(typeof(RecipeData), new RecipeData { Output = Item(key.Value), StationKind = Mill, Facility = MillWorks }, RecipeData.KeyOf(key)); } public void EditRecipe(string outputKey, Action edit) @@ -135,6 +165,18 @@ public sealed class EconomyFixture : IDisposable Rows = rows.Select(r => new OutsideMarketRow { Commodity = Item(r.Commodity), Price = 10, Buys = r.Buys, Sells = r.Sells, RatePerHour = 5 }).ToList() }, OutsideMarketData.KeyOf("gate")); + // Every made good (a commodity, or a design with a recipe) at the price its chain derives, as economy author leaves it. A test that + // needs an off-chain design price sets it after Settle. + public void Settle() + { + foreach (var (key, derived) in EconomyBalance.Prices(Cache, out _)) + { + var item = Cache.Get(new CultRecordKey(key)); + item.Price = EconomyBalance.Rounded(derived); + Cache.Upsert(item.GetType(), item, new CultRecordKey(key)); + } + } + // ore (raw) -> plate (fills Plate) -> a laser and a skiff that each take two plates: no fault anywhere. public static EconomyFixture Healthy() { @@ -143,6 +185,7 @@ public sealed class EconomyFixture : IDisposable f.Good("plate", inputs: new[] { ("ore", 2) }, fills: new[] { "Plate" }); f.Gear("laser", new[] { ("Plate", 2) }); f.Hull("skiff", HullType.Ship, new[] { ("Plate", 1) }); + f.Settle(); return f; } } diff --git a/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs b/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs new file mode 100644 index 000000000..8ade9b7f4 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs @@ -0,0 +1,350 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Xunit; + +// The player-loop section of `economy balance --loop` (EconomyLoop): rates from hand samples, minutes to afford, the ladder band and +// the H faults, on fixture catalogs whose numbers are solved by hand. The sortie itself runs on the shipped catalog. +public sealed class EconomyLoopTests +{ + private static LoopSample Sample(uint seed, int sell, int ammo, int repair, double seconds, LoopOutcome outcome = LoopOutcome.Capped) => + new LoopSample { Seed = seed, Belts = 1, BeltKind = "belt", Weapons = "gun", SimSeconds = seconds, SellValue = sell, AmmoSpent = ammo, Repair = repair, Outcome = outcome, Note = "why" }; + + private static GameplaySettings Settings(float min = 0, float max = 0, int purse = 100000, float sortiesMin = 0, float sortiesMax = 0) => + new GameplaySettings { StartingCredits = purse, EconomyLadderMin = min, EconomyLadderMax = max, EconomySortiesMin = sortiesMin, EconomySortiesMax = sortiesMax }; + + // A gear in `hardpoint` offered at `price`, with a recipe so it is an offered design. + private static void Offer(EconomyFixture f, string id, HardpointType hardpoint, int price, int plates = 1) + { + var key = f.Gear(id, new[] { ("Plate", plates) }); + f.EditItem(key, g => { g.Hardpoint = hardpoint; g.Price = price; }); + } + + private static LoopLadder Ladder(LoopReport report, string category) => report.Ladders.Single(l => l.Category == category); + + [Fact] + public void MinutesToAffordIsPriceOverRate() + { + using var f = EconomyFixture.Healthy(); + Offer(f, "cannon", HardpointType.Tool, 600); + // Gross 1000 a minute, and net 150 a minute once ammunition and repair are paid: the rate is net, per sim-minute. + var report = EconomyLoop.Report(f.Cache, Settings(), new[] { Sample(1, 1000, 0, 0, 60), Sample(2, 500, 100, 100, 120) }); + Assert.Equal(575, report.Median, 9); + Assert.Equal(1000, report.Best, 9); + var cannon = Ladder(report, "Gear/Tool").Designs.Single(d => d.Key == "gear:cannon"); + Assert.Equal(600 / 575.0, cannon.MinutesAtMedian.Value, 9); + Assert.Equal(0.6, cannon.MinutesAtBest.Value, 9); + Assert.True(cannon.Covered); + } + + [Fact] + public void ADesignDearerThanThePurseIsNotCovered() + { + using var f = EconomyFixture.Healthy(); + Offer(f, "cannon", HardpointType.Tool, 600); + var report = EconomyLoop.Report(f.Cache, Settings(purse: 599), new[] { Sample(1, 1000, 0, 0, 60) }); + Assert.False(Ladder(report, "Gear/Tool").Designs.Single(d => d.Key == "gear:cannon").Covered); + // A design priced exactly at the purse is covered. + report = EconomyLoop.Report(f.Cache, Settings(purse: 600), new[] { Sample(1, 1000, 0, 0, 60) }); + Assert.True(Ladder(report, "Gear/Tool").Designs.Single(d => d.Key == "gear:cannon").Covered); + } + + [Fact] + public void ABandWithOnlyOneSideFaultsOnlyThatSide() + { + using var f = EconomyFixture.Healthy(); + Offer(f, "cheap", HardpointType.Reactor, 10); + Offer(f, "dear", HardpointType.Reactor, 1000); + var samples = new[] { Sample(1, 1000, 0, 0, 60) }; + // 100x against a floor of 10 alone, and against a ceiling of 30 alone. + Assert.DoesNotContain(EconomyLoop.Report(f.Cache, Settings(10, 0), samples).Faults, x => x.Record == "Gear/Reactor"); + Assert.Contains(EconomyLoop.Report(f.Cache, Settings(0, 30), samples).Faults, x => x.Record == "Gear/Reactor"); + Assert.Contains(EconomyLoop.Report(f.Cache, Settings(200, 0), samples).Faults, x => x.Record == "Gear/Reactor"); + Assert.DoesNotContain(EconomyLoop.Report(f.Cache, Settings(0, 200), samples).Faults, x => x.Record == "Gear/Reactor"); + } + + // Ruling ladder-band-weapons-and-gear: hulls, bays, consumables and control modules carry no tier band. + [Fact] + public void TheLadderBandCoversWeaponsAndGearOnly() + { + using var f = EconomyFixture.Healthy(); + Offer(f, "cheap", HardpointType.Reactor, 10); + Offer(f, "dear", HardpointType.Reactor, 1000); + var hull = f.Hull("big", HullType.Ship, new[] { ("Plate", 1) }); + f.EditItem(hull, h => h.Price = 100000); + var report = EconomyLoop.Report(f.Cache, Settings(10, 30), new[] { Sample(1, 1000, 0, 0, 60) }); + Assert.True(Ladder(report, "Hull/Ship").Width > 30); + Assert.Equal(new[] { "Gear/Reactor" }, report.Faults.Where(x => x.Invariant == EconomyLoop.HLadder).Select(x => x.Record).ToArray()); + } + + // Rulings top-tier-per-item and top-gear-within-one-region-run: about 10-20 sorties at the median net buys the dearest item. + [Fact] + public void TheAffordBandFaultsADearestDesignOutsideTenToTwentySorties() + { + using var f = EconomyFixture.Healthy(); + Offer(f, "cheap", HardpointType.Reactor, 10); + Offer(f, "top", HardpointType.Reactor, 1500); + // One sortie nets 100: the top design takes 15 sorties. + var samples = new[] { Sample(1, 100, 0, 0, 60) }; + var report = EconomyLoop.Report(f.Cache, Settings(sortiesMin: 10, sortiesMax: 20), samples); + Assert.Equal(15, Ladder(report, "Gear/Reactor").TopSorties.Value, 9); + Assert.DoesNotContain(report.Faults, x => x.Invariant == EconomyLoop.HAfford); + Assert.Contains(EconomyLoop.Report(f.Cache, Settings(sortiesMin: 16, sortiesMax: 20), samples).Faults, x => x.Invariant == EconomyLoop.HAfford && x.Record == "Gear/Reactor"); + var low = Assert.Single(EconomyLoop.Report(f.Cache, Settings(sortiesMin: 10, sortiesMax: 14), samples).Faults, x => x.Invariant == EconomyLoop.HAfford); + Assert.Contains("1 measured sortie", low.Message); + Assert.DoesNotContain(EconomyLoop.Report(f.Cache, Settings(), samples).Faults, x => x.Invariant == EconomyLoop.HAfford); + } + + // The shipped bands on the shipped catalog: the ballistic ladder and its top gun sit inside them, on the one measured sortie + // (seed 1, Metallic belt: sell 1734, repair 183, 150 s) the harness has. Kills a bill trimmed out of the ruled band. + [Fact] + public void TheBallisticLadderAndItsTopGunSitInsideTheShippedBands() + { + using var db = AetherDb.OpenShipped(); + var settings = new GameplaySettings(); + Assert.Equal((10f, 30f, 10f, 20f), (settings.EconomyLadderMin, settings.EconomyLadderMax, settings.EconomySortiesMin, settings.EconomySortiesMax)); + var report = EconomyLoop.Report(db.Cache, settings, new[] { Sample(1, 1734, 0, 183, 150) }); + var ladder = Ladder(report, "Weapon/ExplosivelyPropelled"); + Assert.InRange(ladder.Width.Value, 10, 30); + Assert.InRange(ladder.TopSorties.Value, 10, 20); + Assert.DoesNotContain(report.Faults, x => x.Record == "Weapon/ExplosivelyPropelled"); + } + + [Fact] + public void UnsetLadderBandRaisesNoLadderFault() + { + using var f = EconomyFixture.Healthy(); + Offer(f, "cheap", HardpointType.Reactor, 10); + Offer(f, "dear", HardpointType.Reactor, 1000); + // A settings object nobody tuned: its band is what the field defaults to. + var report = EconomyLoop.Report(f.Cache, Settings(), new[] { Sample(1, 1000, 0, 0, 60) }); + Assert.Equal(100, Ladder(report, "Gear/Reactor").Width.Value, 9); + Assert.DoesNotContain(report.Faults, x => x.Invariant == EconomyLoop.HLadder); + } + + [Fact] + public void LadderOutsideBandIsAFault() + { + using var f = EconomyFixture.Healthy(); + // 2x, 40x, 20x, and the two edges of the band, 10x and 30x; Sensors holds one design alone. + foreach (var (hardpoint, low, high) in new[] { (HardpointType.Tool, 100, 200), (HardpointType.Thruster, 50, 2000), (HardpointType.Reactor, 100, 2000), + (HardpointType.Radiator, 100, 1000), (HardpointType.Ballistic, 100, 3000) }) + { + Offer(f, hardpoint + "-low", hardpoint, low); + Offer(f, hardpoint + "-high", hardpoint, high); + } + Offer(f, "Sensors-only", HardpointType.Sensors, 5000); + // The fixture's own laser is a Tool at price 1: move it into the ladder it should not narrow. + f.EditItem("gear:laser", g => { g.Hardpoint = HardpointType.Energy; g.Price = 7; }); + var report = EconomyLoop.Report(f.Cache, Settings(10, 30), new[] { Sample(1, 1000, 0, 0, 60) }); + var faulted = report.Faults.Where(x => x.Invariant == EconomyLoop.HLadder).Select(x => x.Record).OrderBy(x => x, StringComparer.Ordinal).ToArray(); + Assert.Equal(new[] { "Gear/Thruster", "Gear/Tool" }, faulted); + Assert.Null(Ladder(report, "Gear/Sensors").Width); + Assert.Null(Ladder(report, "Gear/Energy").Width); + } + + [Fact] + public void ACategoryIsTheHullTypeTheWeaponTypeTheHardpointOrTheRecordType() + { + using var f = EconomyFixture.Healthy(); + Offer(f, "beam", HardpointType.Energy, 100); + var gun = f.Cache.Get(new GameCult.Caching.CultRecordKey("gear:beam")); + Assert.Equal("Gear/Energy", EconomyLoop.Category(gun)); + Assert.Equal("Hull/Ship", EconomyLoop.Category(f.Cache.Get(new GameCult.Caching.CultRecordKey("hull:skiff")))); + Assert.Equal("Weapon/Laser", EconomyLoop.Category(new WeaponItemData { WeaponType = WeaponType.Laser, Hardpoint = HardpointType.Energy })); + Assert.Equal("CargoBayData", EconomyLoop.Category(new CargoBayData())); + } + + [Fact] + public void NetLossSortieIsHLoop() + { + using var f = EconomyFixture.Healthy(); + // Gross positive in all three; net 0, -1 and 1: only the last earns anything. + var report = EconomyLoop.Report(f.Cache, Settings(), new[] { Sample(1, 100, 60, 40, 60), Sample(2, 100, 60, 41, 60), Sample(3, 100, 60, 39, 60) }); + var faults = report.Faults.Where(x => x.Invariant == EconomyLoop.HLoop).Select(x => x.Record).OrderBy(x => x, StringComparer.Ordinal).ToArray(); + Assert.Equal(new[] { "seed 1 belt 1 of 1", "seed 2 belt 1 of 1" }, faults); + } + + [Fact] + public void AmmoOutAndRigFaultSortiesAreOutcomesNotIdleIncome() + { + using var f = EconomyFixture.Healthy(); + var report = EconomyLoop.Report(f.Cache, Settings(), new[] + { + Sample(1, 1000, 0, 0, 60), Sample(2, 3000, 0, 0, 60), + // Strongly negative if they were folded in; neither is a rate. + Sample(3, 10, 500, 0, 12, LoopOutcome.AmmoOut), Sample(4, 0, 0, 4, 1, LoopOutcome.RigFault) + }); + Assert.Equal(2000, report.Median, 9); + Assert.Equal(3000, report.Best, 9); + Assert.Equal(new[] { "H-ammo", "H-rig" }, report.Faults.Select(x => x.Invariant).OrderBy(x => x, StringComparer.Ordinal).ToArray()); + Assert.DoesNotContain(report.Faults, x => x.Invariant == EconomyLoop.HLoop); + } + + [Fact] + public void WithNoMeasuredSortieThereIsNoRateAndNoMinutes() + { + using var f = EconomyFixture.Healthy(); + var report = EconomyLoop.Report(f.Cache, Settings(), new[] { Sample(3, 10, 500, 0, 12, LoopOutcome.AmmoOut) }); + Assert.Equal(0, report.Median); + Assert.All(report.Ladders.SelectMany(l => l.Designs), d => Assert.Null(d.MinutesAtMedian)); + } + + // Kills: Prices leaving out a design that has a recipe, or pricing one that has none. + [Fact] + public void PricesCoverEveryDesignWithARecipe() + { + using var f = EconomyFixture.Healthy(); + var prices = EconomyBalance.Prices(f.Cache, out _); + Assert.Equal(new[] { "commodity:plate", "gear:laser", "hull:skiff" }, prices.Keys.OrderBy(k => k, StringComparer.Ordinal).ToArray()); + // Laser takes two plates and skiff one, with no labour on either recipe. + Assert.Equal(2 * prices["commodity:plate"], prices["gear:laser"], 9); + Assert.Equal(prices["commodity:plate"], prices["hull:skiff"], 9); + f.Gear("bare", new (string, int)[0], recipe: false); + Assert.DoesNotContain("gear:bare", EconomyBalance.Prices(f.Cache, out _).Keys); + } + + private static string Root => RunStartTests.FindRepoRoot(); + + // The price the catalog authors for a simple commodity of that name. + private static int PriceOf(string name) + { + using var db = AetherDb.OpenShipped(); + return db.Cache.GetAll().Single(c => c.Name == name).Price; + } + + [Fact] + public void SortieLeavesTheCatalogAndMinesSomething() + { + var catalog = Path.Combine(Root, "GameData", "Aetheria.cc"); + var before = System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(catalog)); + var sample = EconomyLoop.Sortie(Root, 1, 0, 60); + Assert.True(sample.Units > 0); + Assert.True(sample.Rocks > 0); + Assert.Equal(60, sample.SimSeconds, 1); + Assert.Equal(LoopOutcome.Capped, sample.Outcome); + Assert.Equal(before, System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(catalog))); + } + + // Follow-up sortie-determinism-pin: a seed fixes the sortie. Each call generates its own run store, so the keys the cache + // mints differ between the two; ore, target order and rock meshes must not read them (zone-body-sites). + [Fact] + public void ASortieIsAFunctionOfItsSeed() + { + var first = EconomyLoop.Sortie(Root, 1, 0, 60); + var second = EconomyLoop.Sortie(Root, 1, 0, 60); + Assert.Equal(first.BeltKind, second.BeltKind); + Assert.Equal(first.Weapons, second.Weapons); + Assert.Equal(first.Outcome, second.Outcome); + Assert.Equal(first.Rocks, second.Rocks); + Assert.Equal(first.Units, second.Units); + Assert.Equal(first.HoldFullAt, second.HoldFullAt); + Assert.Equal(first.SellValue, second.SellValue); + Assert.Equal(first.AmmoSpent, second.AmmoSpent); + Assert.Equal(first.Repair, second.Repair); + Assert.Equal(first.SimSeconds, second.SimSeconds); + } + + [Fact] + public void AFullHoldSortieIsPricedFromTheShipItEndedWith() + { + int ore = -1, repair = -1; + var sample = EconomyLoop.Sortie(Root, 1, 0, 300, (ship, items, processing) => + { + ore = StationServices.OreValue(items, ship.CargoBays, processing); + repair = StationServices.RepairCost(items, ship); + }); + Assert.Equal(LoopOutcome.Full, sample.Outcome); + Assert.True(sample.HoldFullAt > 0 && sample.HoldFullAt <= sample.SimSeconds); + Assert.True(sample.SellValue > 0); + // The station pays for the units its bays took: what it would pay for all of them, less what it refused for want of room. + Assert.Equal(ore, sample.OfferedValue); + Assert.True(sample.SellValue <= sample.OfferedValue); + Assert.Equal(sample.Units, sample.UnitsSold + sample.UnitsRefused); + if (sample.UnitsRefused == 0) Assert.Equal(sample.OfferedValue, sample.SellValue); + Assert.True(sample.Repair > 0); + Assert.Equal(repair, sample.Repair); + // Laser fit: no ammunition is spent. + Assert.Equal(0, sample.AmmoSpent); + } + + [Fact] + public void ASortieThatSpendsItsStarterAmmunitionEndsAmmoOutAndPaysForIt() + { + var ammoLeft = -1; + var sample = EconomyLoop.Sortie(Root, 2, 0, 150, (ship, items, _) => + ammoLeft = ship.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()).Where(c => items.GetData(c).Name == "Ammo").Sum(c => c.Quantity)); + Assert.Equal(LoopOutcome.AmmoOut, sample.Outcome); + Assert.Equal(0, ammoLeft); + // The Cell Blaster fit starts with 3 Ammo, bought back at the catalog's price. + Assert.Equal(3 * PriceOf("Ammo"), sample.AmmoSpent); + Assert.True(sample.SimSeconds < 150); + } + + [Fact] + public void EveryBeltOfTheZoneIsItsOwnSampleAndAnUnlitOneIsARigFault() + { + var samples = EconomyLoop.Sorties(Root, 2, 5); + Assert.Equal(2, samples.Count); + Assert.All(samples, x => Assert.Equal(2, x.Belts)); + Assert.Equal(new[] { 0, 1 }, samples.Select(x => x.Belt).ToArray()); + Assert.NotEqual(samples[0].BeltKind, samples[1].BeltKind); + // Seed 2's second belt is in darkness: no rock can be targeted, and that is not income. + Assert.Equal(LoopOutcome.RigFault, samples[1].Outcome); + Assert.Equal(0, samples[1].Units); + } + + [Fact] + public void ANonFiniteOrNonPositiveCapIsRefused() + { + foreach (var cap in new[] { float.NaN, 0f, -1f, float.PositiveInfinity }) + Assert.Throws(() => EconomyLoop.Sortie(Root, 1, 0, cap)); + foreach (var word in new[] { "NaN", "0", "-1", "Infinity" }) + { + var output = new StringWriter(); + Assert.Equal(1, EconomyCommand.Run(new[] { "balance", "--loop", "1", "--cap", word }, output)); + Assert.Contains("balance [--loop", output.ToString()); + } + } + + [Fact] + public void BalanceWithoutLoopIsUnchanged() + { + // The committed output of economy balance at the commit before --loop existed, on the shipped catalog. + var golden = File.ReadAllText(Path.Combine(Root, "tests", "Aetheria.Shared.Tests", "Golden", "economy-balance-base.txt")).Replace("\r\n", "\n"); + var output = new StringWriter(); + EconomyCommand.Run(new[] { "balance" }, output); + Assert.Equal(golden, output.ToString().Replace("\r\n", "\n")); + } + + [Fact] + public void BalanceLoopPrintsTheLoopAndTheLaddersAndLetsTheirFaultsFailTheCommand() + { + using var db = AetherDb.OpenShipped(); + var settings = AuthoredSettings.Load(db.Root).Read("GameplaySettings"); + var report = EconomyLoop.Report(db.Cache, settings, new[] { Sample(7, 100, 100, 0, 60) }); + var plain = new StringWriter(); + EconomyCommand.Balance(db.Cache, settings.EconomyWageSpread, plain); + var output = new StringWriter(); + Assert.Equal(1, EconomyCommand.Balance(db.Cache, settings.EconomyWageSpread, output, report)); + var text = output.ToString(); + Assert.StartsWith(plain.ToString().Split('\n')[0], text); + Assert.Contains("H-loop (1)", text); + Assert.Contains("Player loop (", text); + Assert.Contains("Ladders (", text); + Assert.Contains(" Gear/Reactor: ", text); + } + + [Theory] + [InlineData("--cap", "5")] + [InlineData("--loop", "x")] + [InlineData("--loop", "--cap")] + [InlineData("--bogus")] + public void BalanceRefusesWhatItCannotRead(params string[] words) + { + var output = new StringWriter(); + Assert.Equal(1, EconomyCommand.Run(new[] { "balance" }.Concat(words).ToArray(), output)); + Assert.Contains("balance [--loop", output.ToString()); + } +} diff --git a/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs b/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs index d94222635..682b20409 100644 --- a/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs +++ b/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs @@ -107,7 +107,7 @@ public class ElementIdUpgradeTests { using var directory = new TempDirectory(); var copy = Path.Combine(directory.Path, "ship.cc"); - File.Copy(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Mods", "aetheria.wren", "ship.cc"), copy); + File.Copy(Path.Combine(RunStartTests.FindRepoRoot(), "tests", "fixtures", "mods", "aetheria.wren", "ship.cc"), copy); var bytes = File.ReadAllBytes(copy); var (hull, visual, products) = ShipAuthoringStore.Load(copy); diff --git a/tests/Aetheria.Shared.Tests/EvasionTrackingTests.cs b/tests/Aetheria.Shared.Tests/EvasionTrackingTests.cs index f6c461aab..06550e9f0 100644 --- a/tests/Aetheria.Shared.Tests/EvasionTrackingTests.cs +++ b/tests/Aetheria.Shared.Tests/EvasionTrackingTests.cs @@ -356,6 +356,8 @@ public sealed partial class RunStartTests // Data check: the authored numbers of the three designs, read from the shipped catalog through the production load path // (addenda "Catalog growth: generic designs, branded products", the Derivation of the PD stats). Each is a lever the // operator tunes, so each is pinned; the ammunition is the commodity Autocannon's rounds are. + // The Point Defense Gun and Flak Gun prices are what their chains derive (MunitionsBills; L-price holds them to it), so a retune of the + // parts moves them and this pin with them. [Fact] public void PdGearStatsAreAuthored() { @@ -365,11 +367,11 @@ public sealed partial class RunStartTests (float min, float max) velocity, (float min, float max) energy, (float min, float max) heat, (float min, float max) visibility, bool ammo, int magazine, float reload)[] { - ("Point Defense Gun", 40f, 80000, 60f, WeaponModifiers.RapidFire, (1.5f, 4f), (1f, 1f), (300f, 550f), (.06f, .025f), (1f, .3f), + ("Point Defense Gun", 40f, 4890, 60f, WeaponModifiers.RapidFire, (1.5f, 4f), (1f, 1f), (300f, 550f), (.06f, .025f), (1f, .3f), (1100f, 1600f), (.4f, .2f), (40f, 15f), (400f, 150f), true, 250, 3f), - ("Point Defense Laser", 30f, 110000, 30f, PdDesign("Light Laser").WeaponModifiers, (5f, 12f), (1f, 1f), (400f, 750f), (.2f, .1f), (.05f, 0f), + ("Point Defense Laser", 30f, 1100, 30f, PdDesign("Light Laser").WeaponModifiers, (5f, 12f), (1f, 1f), (400f, 750f), (.2f, .1f), (.05f, 0f), (0f, 0f), (6f, 10f), (300f, 150f), (300f, 100f), false, PdDesign("Light Laser").Behaviors.OfType().Single().MagazineSize, PdDesign("Light Laser").Behaviors.OfType().Single().ReloadTime), - ("Flak Gun", 120f, 180000, 80f, WeaponModifiers.Cluster, (30f, 70f), (6f, 8f), (350f, 800f), (.6f, .35f), (4f, 2f), + ("Flak Gun", 120f, 6022, 80f, WeaponModifiers.Cluster, (30f, 70f), (6f, 8f), (350f, 800f), (.6f, .35f), (4f, 2f), (900f, 1300f), (1f, .5f), (300f, 150f), (800f, 300f), true, 40, 4f), }; foreach (var e in expected) diff --git a/tests/Aetheria.Shared.Tests/FacilitiesBatchTests.cs b/tests/Aetheria.Shared.Tests/FacilitiesBatchTests.cs new file mode 100644 index 000000000..07b102423 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/FacilitiesBatchTests.cs @@ -0,0 +1,107 @@ +using System; +using System.IO; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// The Facilities economy batch (aetheria-living-world, cut recipe-facilities): over a copy of the shipped catalog stripped of its +// facilities, it gives every kind a recipe names one facility design, and every recipe its kind's. +public sealed class FacilitiesBatchTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-facilities-" + Guid.NewGuid().ToString("N")); + + public FacilitiesBatchTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + // The shipped Aetheria.cc on its own (the batch's catalog: no packages), as it stood before the batch: no facility design, no + // kind's Facilities, no recipe's Facility. + private CultCache Stripped() + { + var path = Path.Combine(_root, Guid.NewGuid().ToString("N") + ".cc"); + File.Copy(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Aetheria.cc"), path); + var cache = AetheriaStores.Open(path, catalogWritable: true, registry: TestCatalog.Registry()); + foreach (var recipe in cache.GetAll().ToArray()) + { + recipe.Facility = default; + cache.Upsert(typeof(RecipeData), recipe, cache.RefOf(recipe).Key); + } + foreach (var kind in cache.GetAll().ToArray()) + { + kind.Facilities.Clear(); + cache.Upsert(typeof(StationKindData), kind, cache.RefOf(kind).Key); + } + foreach (var key in cache.GetAll().Where(StationKinds.IsRecipeFacility).Select(gear => cache.RefOf(gear).Key).ToArray()) cache.Remove(key); + foreach (var product in cache.GetAll().Where(p => cache.Get(p.Design) == null).ToArray()) cache.Remove(cache.RefOf(product).Key); + Assert.Empty(cache.GetAll().SelectMany(kind => kind.Facilities)); + return cache; + } + + [Fact] + public void EveryRecipeNamesItsKindsFacility() + { + using var cache = Stripped(); + new Facilities().Author(new EconomyAuthor(cache)); + var recipes = cache.GetAll().ToArray(); + Assert.NotEmpty(recipes); + foreach (var recipe in recipes) + { + var kind = cache.Get(recipe.StationKind); + var facility = Assert.Single(kind.Facilities); + Assert.Equal(facility.Key.Value, recipe.Facility.Key.Value); + Assert.True(StationKinds.IsRecipeFacility(cache.Get(facility))); + } + Assert.Equal(recipes.Select(r => r.StationKind.Key.Value).Distinct().Count(), recipes.Select(r => r.Facility.Key.Value).Distinct().Count()); + Assert.DoesNotContain(EconomyChecks.Recipe(cache), fault => fault.Invariant == EconomyChecks.LFacility && fault.Record != "station-facilities"); + } + + [Fact] + public void RerunConverges() + { + using var cache = Stripped(); + new Facilities().Author(new EconomyAuthor(cache)); + var again = new EconomyAuthor(cache); + new Facilities().Author(again); + Assert.Empty(again.Touched); + } + + [Fact] + public void EachFacilityHasOneUnofferedProduct() + { + using var cache = Stripped(); + new Facilities().Author(new EconomyAuthor(cache)); + var facilities = cache.GetAll().SelectMany(kind => kind.Facilities).Select(facility => facility.Key).ToArray(); + Assert.NotEmpty(facilities); + foreach (var facility in facilities) + { + var product = Assert.Single(cache.GetAll(), p => p.Design.Key.Equals(facility)); + Assert.True(product.NotOffered); + Assert.False(LoadoutGenerator.IsOffered(cache, product)); + Assert.True(cache.Get(product.Manufacturer) != null); + } + } + + [Fact] + public void AKindWithoutARowThrows() + { + using var cache = Stripped(); + var recipe = cache.GetAll().First(); + recipe.StationKind = new CultRecordRef(StationKindData.KeyOf("shipyard")); + cache.Upsert(typeof(RecipeData), recipe, cache.RefOf(recipe).Key); + var refusal = Assert.Throws(() => new Facilities().Author(new EconomyAuthor(cache))); + Assert.Contains("station-kind:shipyard", refusal.Message); + } + + // The munitions batch rewrites its kind whole; the facilities the catalog already holds for it survive, and so does every recipe's. + [Fact] + public void MunitionsRewriteKeepsAKindsFacilities() + { + var path = Path.Combine(_root, "munitions.cc"); + File.Copy(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Aetheria.cc"), path); + using var cache = AetheriaStores.Open(path, catalogWritable: true, registry: TestCatalog.Registry()); + var works = StationKindData.KeyOf("munitions-works"); + var held = Assert.Single(cache.Get(works).Facilities).Key.Value; + new Munitions().Author(new EconomyAuthor(cache)); + Assert.Equal(held, Assert.Single(cache.Get(works).Facilities).Key.Value); + Assert.DoesNotContain(EconomyChecks.Recipe(cache), fault => fault.Invariant == EconomyChecks.LFacility); + } +} diff --git a/tests/Aetheria.Shared.Tests/FacilityProductionTests.cs b/tests/Aetheria.Shared.Tests/FacilityProductionTests.cs new file mode 100644 index 000000000..a96788091 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/FacilityProductionTests.cs @@ -0,0 +1,562 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using Xunit; + +// Installed facilities run their recipes on screen (aetheria-living-world, cut facility-production): one cycle rule, +// Production.Advance; the inputs of a cycle are taken when it starts and a simple output is stored when it ends. The fixture seats +// a shipped facility design by hand on a station of its own, over the booted catalog (the recipes are the shipped ones), and steps +// Zone.Update by SimClock.GameStep, the on-screen clock. +public sealed class FacilityProductionTests : IDisposable +{ + private const double IronCycle = 600; + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-facilityproduction-" + Guid.NewGuid().ToString("N")); + private readonly CultCache _cache; + + public FacilityProductionTests() + { + Directory.CreateDirectory(_root); + _cache = Open("catalog.cc"); + Add(_cache); + } + + public void Dispose() + { + _cache.Dispose(); + Directory.Delete(_root, true); + } + + private CultCache Open(string name) + { + var path = Path.Combine(_root, name); + File.Copy(TestCatalog.Repo, path); + var cache = new CultCache(TestCatalog.Registry()); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(path), AetheriaStores.CatalogTypes); + return cache; + } + + private static Shape Solid(int width, int height) + { + var shape = new Shape(width, height); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + return shape; + } + + // A hull with one 2x2 Facility row, a bay the size of one cell (a Pocket) and a bay of sixteen (a Crate), and goods to fill them. + private static void Add(CultCache cache) + { + cache.Upsert(new HullData + { + Name = "Test Yard", HullType = HullType.Station, Shape = Solid(8, 8), Price = 1, Durability = 10, Mass = 1000, + Hardpoints = { new HardpointData { Type = HardpointType.Facility, Position = new int2(0, 0), Shape = Solid(2, 2), Transform = "Fa.1" } } + }); + cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = Solid(4, 4), Price = 20, Durability = 4 }); + cache.Upsert(new CargoBayData { Name = "Pocket", Shape = new Shape(), InteriorShape = Solid(1, 1), Price = 5, Durability = 4 }); + cache.Upsert(new SimpleCommodityData { Name = "Slag", Shape = new Shape(), Price = 1, MaxStack = 100 }); + cache.Upsert(new ConsumableItemData { Name = "Facility Pill", Shape = new Shape(), Price = 1, Behaviors = { new FacilityData() } }); + } + + private sealed class World + { + public ItemManager Items; + public Zone Zone; + public OrbitalEntity Station; + public Facility Facility; + public EquippableItem Unit; + public EntityHold Hold; + } + + private EquippableItem Mint(ItemManager items, CultCache cache, string design) + { + var data = cache.GetByName(design); + return new EquippableItem + { + Data = cache.RefOf(data), + Durability = data.Durability, + Lot = items.Lots.Add(new Lot { Design = cache.RefOf(data), Origin = new Attributed(), Quality = .5f, Roles = new List() }) + }; + } + + // A station of Test Yard with the named facility on its row and the named bay. + private World Build(string facility = "Refinery", string bay = "Crate") + { + var items = new ItemManager(1u, _cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + var station = new OrbitalEntity(items, zone, Mint(items, _cache, "Test Yard"), default, new EntitySettings()); + Assert.True(station.TryEquip(Mint(items, _cache, facility), new int2(0, 0))); + Assert.True(station.TryEquip(Mint(items, _cache, bay), new int2(4, 4))); + zone.Admit(station, piloted: false); + return Wrap(items, zone, station); + } + + private static World Wrap(ItemManager items, Zone zone, OrbitalEntity station) + { + var item = station.Equipment.Single(equipped => equipped.Behaviors.Any(behavior => behavior is Facility)); + return new World + { + Items = items, Zone = zone, Station = station, Facility = item.Behaviors.OfType().Single(), + Unit = item.EquippableItem, Hold = new EntityHold(station) + }; + } + + private SimpleCommodity Goods(string design, int units) => + new SimpleCommodity { Data = new CultRecordRef(_cache.RefOf(_cache.GetByName(design)).Key), Quantity = units }; + + private static SimpleCommodity Goods(CultRecordKey design, int units) => + new SimpleCommodity { Data = new CultRecordRef(design), Quantity = units }; + + private static void Stock(World world, CultRecordKey design, int units) => + Assert.True(world.Station.CargoBays[0].TryStore(Goods(design, units))); + + private static void Step(World world, int steps) + { + for (var at = 0; at < steps; at++) world.Zone.Update(SimClock.GameStep); + } + + // The steps whose sum of GameStep first reaches the cycle: the first of them also starts it. + private static int StepsOf(double seconds) => (int) Math.Round(seconds / SimClock.GameStep); + + private CultRecordKey[] IronFillers => Recipes.Fillers(_cache, "iron ore"); + private CultRecordKey Iron => new CultRecordKey("commodity:iron"); + + // What the station's bays hold and its facilities run, as bytes: nothing else of the entity is read. + private static byte[] Contents(World world) + { + var pack = EntitySerializer.Pack(world.Station); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + return MessagePackSerializer.Serialize((pack.Equipment, pack.CargoBays, pack.CargoContents), options); + } + + private static int Held(World world, CultRecordKey design) => world.Hold.Held(design); + + [Fact] + public void ARefineryTurnsOreIntoIron() + { + var world = Build(); + Stock(world, IronFillers[0], 3); + Step(world, 1); + Assert.Equal(0, Held(world, IronFillers[0])); + Assert.Equal(RecipeData.KeyOf(Iron), world.Unit.Run.Recipe.Key); + Assert.Equal(0, Held(world, Iron)); + + Step(world, StepsOf(IronCycle) - 1); + Assert.Equal(2, Held(world, Iron)); + Assert.Equal(0, Held(world, IronFillers[0])); + Assert.Equal(0, world.Unit.Run.Progress); + Assert.Equal(Stall.Inputs, world.Facility.Stall); + Assert.Equal(1, world.Station.CargoBays[0].Cargo.Count); + } + + [Fact] + public void TakenInputsStayTaken() + { + var world = Build(); + Stock(world, IronFillers[0], 6); + Step(world, 1); + Assert.True(world.Hold.TryTake(new[] { (IronFillers[0], 3) })); + Assert.Equal(0, Held(world, IronFillers[0])); + + Step(world, StepsOf(IronCycle) - 1); + Assert.Equal(2, Held(world, Iron)); + } + + [Fact] + public void ShortHoldWritesNothing() + { + var world = Build(); + Stock(world, IronFillers[0], 2); + var before = Contents(world); + Step(world, StepsOf(100)); + Assert.Null(world.Unit.Run); + Assert.Equal(before, Contents(world)); + Assert.Equal(Stall.Inputs, world.Facility.Stall); + } + + [Fact] + public void FullHoldHoldsTheBatch() + { + var world = Build(bay: "Pocket"); + Stock(world, IronFillers[0], 3); + Step(world, 1); + Assert.Equal(0, Held(world, IronFillers[0])); + var slag = Goods("Slag", 1); + Assert.True(world.Station.CargoBays[0].TryStore(slag)); + + Step(world, StepsOf(IronCycle) + 100); + Assert.Equal(Stall.Room, world.Facility.Stall); + Assert.Equal(IronCycle, world.Unit.Run.Progress); + Assert.Equal(0, Held(world, Iron)); + Assert.Equal(0, Held(world, IronFillers[0])); + + world.Station.CargoBays[0].Remove(slag); + Step(world, 1); + Assert.Equal(2, Held(world, Iron)); + Assert.Equal(0, world.Unit.Run.Progress); + Assert.Equal(Stall.Inputs, world.Facility.Stall); + } + + [Fact] + public void RoundRobinFromTheCursor() + { + var world = Build(); + var copperOre = Recipes.Fillers(_cache, "copper ore").Except(IronFillers).First(); + Stock(world, copperOre, 8); + Stock(world, IronFillers[0], 6); + var runList = Production.RunList(_cache, _cache.RefOf(_cache.GetByName("Refinery")).Key); + var copper = new CultRecordKey("commodity:copper"); + var cycles = new[] { 900.0, 600.0, 900.0, 600.0 }; + var produced = new List<(int copper, int iron)>(); + FacilityRun run = null; + foreach (var span in cycles) + { + (run, _) = Production.Advance(_cache, runList, run, span, world.Hold); + produced.Add((Held(world, copper), Held(world, Iron))); + } + Assert.Equal(new[] { (1, 0), (1, 2), (2, 2), (2, 4) }, produced); + } + + [Fact] + public void RolesFillInFillerOrder() + { + var world = Build(); + var fillers = IronFillers; + var recipe = _cache.Get(RecipeData.KeyOf(Iron)); + Stock(world, fillers[0], 4); + Stock(world, fillers[1], 4); + Assert.Equal(new[] { (fillers[0], 3) }, Production.Take(_cache, recipe, world.Hold)); + + Assert.True(world.Hold.TryTake(new[] { (fillers[0], 2) })); + Assert.Equal(new[] { (fillers[0], 2), (fillers[1], 1) }, Production.Take(_cache, recipe, world.Hold)); + } + + [Fact] + public void RunListIsTheRule() + { + var expected = new Dictionary { ["Refinery"] = 18, ["Munitions Line"] = 5, ["Algae Vats"] = 1, + ["Fabrication Line"] = 0, ["Extraction Rig"] = 0, ["Volatiles Skimmer"] = 0 }; + foreach (var design in _cache.GetAll().Where(StationKinds.IsRecipeFacility)) + { + var key = _cache.RefOf(design).Key; + var rule = _cache.GetAll() + .Where(recipe => recipe.Facility.IsSet() && recipe.Facility.Key.Equals(key)) + .Where(recipe => !Recipes.IsRaw(_cache, recipe) && _cache.Get(recipe.Output) is SimpleCommodityData) + .OrderBy(recipe => RecipeData.KeyOf(recipe.Output.Key).Value, StringComparer.Ordinal) + .ToArray(); + Assert.Equal(rule, Production.RunList(_cache, key)); + Assert.Equal(expected[design.Name], rule.Length); + } + + foreach (var name in new[] { "Extraction Rig", "Volatiles Skimmer", "Fabrication Line" }) + { + var world = Build(name); + Step(world, 2); + Assert.Equal(Stall.Unrunnable, world.Facility.Stall); + Assert.Null(world.Unit.Run); + } + } + + [Fact] + public void OneSpanEqualsManySteps() + { + var span = Build(); + var steps = Build(); + foreach (var world in new[] { span, steps }) Stock(world, IronFillers[0], 6); + var runList = Production.RunList(_cache, _cache.RefOf(_cache.GetByName("Refinery")).Key); + + var (run, _) = Production.Advance(_cache, runList, null, 2 * IronCycle, span.Hold); + FacilityRun stepped = null; + for (var at = 0; at < StepsOf(2 * IronCycle); at++) + (stepped, _) = Production.Advance(_cache, runList, stepped, SimClock.GameStep, steps.Hold); + + Assert.Equal(4, Held(span, Iron)); + Assert.Equal(Held(span, Iron), Held(steps, Iron)); + Assert.Equal(Held(span, IronFillers[0]), Held(steps, IronFillers[0])); + Assert.Equal((run.Recipe.Key, run.Progress), (stepped.Recipe.Key, stepped.Progress)); + } + + [Fact] + public void RunSurvivesThePack() + { + var broken = Build(); + var whole = Build(); + foreach (var world in new[] { broken, whole }) Stock(world, IronFillers[0], 3); + Step(broken, StepsOf(IronCycle) / 2); + Step(whole, StepsOf(IronCycle) / 2); + Assert.InRange(broken.Unit.Run.Progress, 1, IronCycle - 1); + + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + var bytes = MessagePackSerializer.Serialize(EntitySerializer.Pack(broken.Station), options); + var items = broken.Items; + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + var station = (OrbitalEntity) EntitySerializer.Unpack(items, zone, MessagePackSerializer.Deserialize(bytes, options)); + if (!zone.Entities.Contains(station)) zone.Admit(station, piloted: false); + var restored = Wrap(items, zone, station); + Assert.Equal(whole.Unit.Run.Progress, restored.Unit.Run.Progress); + + Step(restored, StepsOf(IronCycle) - StepsOf(IronCycle) / 2); + Step(whole, StepsOf(IronCycle) - StepsOf(IronCycle) / 2); + Assert.Equal(2, Held(restored, Iron)); + Assert.Equal((Held(whole, Iron), whole.Unit.Run.Progress), (Held(restored, Iron), restored.Unit.Run.Progress)); + } + + [Fact] + public void TwoHistoriesAgree() + { + var first = Build(); + var second = Build(); + foreach (var world in new[] { first, second }) Stock(world, IronFillers[0], 6); + foreach (var world in new[] { first, second }) Step(world, StepsOf(2 * IronCycle)); + Assert.Equal(4, Held(first, Iron)); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + Assert.Equal(MessagePackSerializer.Serialize(EntitySerializer.Pack(first.Station), options), + MessagePackSerializer.Serialize(EntitySerializer.Pack(second.Station), options)); + } + + [Fact] + public void NoFacilityOnAConsumable() + { + var world = Build(); + var pill = new ConsumableItem + { + Data = _cache.RefOf(_cache.GetByName("Facility Pill")), + Lot = world.Items.Lots.Add(new Lot { Design = _cache.RefOf(_cache.GetByName("Facility Pill")), + Origin = new Attributed(), Quality = .5f, Roles = new List() }) + }; + var error = Assert.Throws(() => new ConsumableItemEffect(pill, world.Station)); + Assert.Contains("Facility Pill", error.Message); + } + + // The shipped catalog as it boots, a shipped station hull with no heater, the shipped Refinery on its Facility row: an hour of sim + // time (the station's cells cool toward 0 meanwhile) turns 15 ore into 5 cycles of iron, one cycle fewer than the hour holds. + [Fact] + public void TheShippedRefineryRunsAnHourOnAHeaterlessShippedStation() + { + using var shipped = Open("shipped.cc"); + var items = new ItemManager(1u, shipped, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + var station = new OrbitalEntity(items, zone, Mint(items, shipped, "Zenith"), default, new EntitySettings()); + Assert.True(station.TryEquip(Mint(items, shipped, "Refinery"))); + var bay = shipped.GetAll().Where(data => !(data is DockingBayData)).OrderByDescending(data => data.InteriorShape.Coordinates.Length).ThenBy(data => data.Name, StringComparer.Ordinal).First(); + Assert.True(station.TryEquip(Mint(items, shipped, bay.Name))); + Assert.DoesNotContain(station.Equipment.Select(equipped => equipped.Data), data => data is GearData gear && gear.Behaviors.Any(behavior => behavior is HeatData)); + zone.Admit(station, piloted: false); + var world = Wrap(items, zone, station); + // An ore only iron takes, so no other recipe competes for it in the round robin. + var others = shipped.GetAll().SelectMany(recipe => Recipes.RoleInputsOf(shipped, recipe)).Select(role => role.Name).Where(role => role != "iron ore").Distinct(); + var ore = Recipes.Fillers(shipped, "iron ore").Except(others.SelectMany(role => Recipes.Fillers(shipped, role))).First(); + var maxStack = items.MaxStack(Goods(ore, 1)); + for (var left = 15; left > 0; left -= maxStack) Assert.True(station.CargoBays[0].TryStore(Goods(ore, Math.Min(left, maxStack)))); + + Step(world, StepsOf(3600)); + Assert.Equal(10, world.Hold.Held(new CultRecordKey("commodity:iron"))); + Assert.Equal(0, world.Hold.Held(ore)); + Assert.True(world.Station.Equipment.Single(equipped => equipped.Behaviors.Any(behavior => behavior is Facility)).Active.Value); + } + + [Fact] + public void AnIdleFacilityTriesAgainWhenTheHoldChanges() + { + var world = Build(); + Stock(world, IronFillers[0], 2); + Step(world, 3); + Assert.Equal(Stall.Inputs, world.Facility.Stall); + Assert.Null(world.Unit.Run); + + Stock(world, IronFillers[0], 1); + Step(world, 1); + Assert.Equal(RecipeData.KeyOf(Iron), world.Unit.Run.Recipe.Key); + Assert.Equal(0, Held(world, IronFillers[0])); + } + + // The entity's cargo revision moves on every kind of change to what its bays hold (a stack stored, merged, split or removed, a unit + // stored or removed, a bay seated or removed) and on nothing else. + [Fact] + public void TheCargoRevisionCountsEveryChangeToWhatTheBaysHold() + { + var world = Build(); + var bay = world.Station.CargoBays[0]; + var at = world.Station.CargoRevision; + Assert.Equal(at, world.Hold.Revision); + void Moved() { Assert.True(world.Station.CargoRevision > at); at = world.Station.CargoRevision; } + Assert.True(bay.TryStore(Goods("Slag", 5))); + Moved(); + Assert.True(bay.TryStore(Goods("Slag", 5))); + Moved(); + var stack = bay.Cargo.Keys.Single(); + Assert.NotNull(bay.Remove(stack, 3)); + Moved(); + Assert.Equal(7, bay.Count(stack.Data.Key)); + Assert.Equal(at, world.Station.CargoRevision); + bay.Remove(stack); + Moved(); + var unit = Mint(world.Items, _cache, "Pocket"); + Assert.True(bay.TryStore(unit)); + Moved(); + bay.Remove(unit); + Moved(); + world.Station.Deactivate(); + var pocket = world.Station.TryEquip(Mint(world.Items, _cache, "Pocket"), new int2(6, 6)); + Assert.True(pocket); + Moved(); + Assert.NotNull(world.Station.TryUnequip(world.Station.CargoBays[1])); + Moved(); + } + + // Soul's sequence: a take fails with 2 ore held; the station is deactivated, its empty second bay removed, one ore stored, and it + // is activated again. The hold's revision is never the one the failure recorded, so the facility takes the 3 ore. + [Fact] + public void AFacilityTakesWhatIsStockedAfterABayLeaves() + { + var world = Build(); + world.Station.Deactivate(); + Assert.True(world.Station.TryEquip(Mint(world.Items, _cache, "Pocket"), new int2(6, 6))); + world.Station.Activate(); + Stock(world, IronFillers[0], 2); + Step(world, 3); + Assert.Equal(Stall.Inputs, world.Facility.Stall); + + world.Station.Deactivate(); + Assert.NotNull(world.Station.TryUnequip(world.Station.CargoBays[1])); + Stock(world, IronFillers[0], 1); + world.Station.Activate(); + Step(world, 3); + Assert.NotNull(world.Unit.Run); + Assert.Equal(0, Held(world, IronFillers[0])); + } + + // An idle facility whose take failed does not try again until the hold changes: the failed take is recorded. + [Fact] + public void AnIdleFacilityDoesNotRetryUntilTheHoldChanges() + { + var world = Build(); + Stock(world, IronFillers[0], 2); + Step(world, 20); + Assert.Equal(1, world.Facility.Attempts); + Stock(world, IronFillers[0], 1); + Step(world, 1); + Assert.Equal(2, world.Facility.Attempts); + Assert.NotNull(world.Unit.Run); + } + + // A save written mid-cycle, then a catalog that no longer has the recipe: the run is dropped, the inputs it took stay consumed, and + // the facility starts its next recipe. Nothing throws on any step. + [Fact] + public void ASaveNamingADeletedRecipeIsDroppedNotThrown() + { + var world = Build(); + var copperOre = Recipes.Fillers(_cache, "copper ore").Except(IronFillers).First(); + Stock(world, IronFillers[0], 3); + Step(world, 101); + Assert.Equal(RecipeData.KeyOf(Iron), world.Unit.Run.Recipe.Key); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + var bytes = MessagePackSerializer.Serialize(EntitySerializer.Pack(world.Station), options); + + _cache.Remove(RecipeData.KeyOf(Iron)); + var zone = new Zone(world.Items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + var station = (OrbitalEntity) EntitySerializer.Unpack(world.Items, zone, MessagePackSerializer.Deserialize(bytes, options)); + if (!zone.Entities.Contains(station)) zone.Admit(station, piloted: false); + var restored = Wrap(world.Items, zone, station); + Assert.Equal(RecipeData.KeyOf(Iron), restored.Unit.Run.Recipe.Key); + + Stock(restored, copperOre, 4); + Step(restored, 2); + Assert.Equal(RecipeData.KeyOf(new CultRecordKey("commodity:copper")), restored.Unit.Run.Recipe.Key); + Assert.Equal(0, Held(restored, copperOre)); + Assert.Equal(0, Held(restored, Iron)); + Assert.Equal(0, Held(restored, IronFillers[0])); + } + + private void Edit(CultRecordKey recipe, Action change) + { + var held = _cache.Get(recipe); + change(held); + _cache.Upsert(typeof(RecipeData), held, recipe); + } + + private static T Within(Func work) + { + var task = System.Threading.Tasks.Task.Run(work); + Assert.True(task.Wait(TimeSpan.FromSeconds(20)), "Advance did not return: it spins on a stale run list"); + return task.Result; + } + + // A run list built before the catalog changed names a recipe the catalog no longer holds, or holds as a raw one: nothing starts + // from it, the stock is untouched, the call returns, and the recipes that still run still start. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AStaleRunListStartsNothingAndReturns(bool removed) + { + var world = Build(); + var runList = Production.RunList(_cache, _cache.RefOf(_cache.GetByName("Refinery")).Key); + Assert.Contains(runList, recipe => recipe.Output.Key.Equals(Iron)); + var ironKey = RecipeData.KeyOf(Iron); + if (removed) _cache.Remove(ironKey); + else Edit(ironKey, recipe => recipe.RoleInputs.Clear()); + Stock(world, IronFillers[0], 3); + + var (run, stall) = Within(() => Production.Advance(_cache, runList, null, 1200, world.Hold)); + Assert.Null(run); + Assert.Equal(Stall.Inputs, stall); + Assert.Equal(3, Held(world, IronFillers[0])); + Assert.Equal(0, Held(world, Iron)); + + var copperOre = Recipes.Fillers(_cache, "copper ore").Except(IronFillers).First(); + Stock(world, copperOre, 4); + (run, _) = Within(() => Production.Advance(_cache, runList, null, 10, world.Hold)); + Assert.Equal(RecipeData.KeyOf(new CultRecordKey("commodity:copper")), run.Recipe.Key); + } + + // A running cycle whose recipe the catalog changed under it is dropped, whatever the change: the recipe removed, made raw (it takes + // nothing now) or given a compound output (a graded output needs a lot). The facility's list is rebuilt and it moves on. + [Theory] + [InlineData("removed")] + [InlineData("raw")] + [InlineData("compound")] + public void ARunningCycleWhoseRecipeStoppedRunningIsDropped(string change) + { + var world = Build(); + Stock(world, IronFillers[0], 3); + Step(world, 101); + Assert.Equal(RecipeData.KeyOf(Iron), world.Unit.Run.Recipe.Key); + var ironKey = RecipeData.KeyOf(Iron); + if (change == "removed") _cache.Remove(ironKey); + else if (change == "raw") Edit(ironKey, recipe => recipe.RoleInputs.Clear()); + else Edit(ironKey, recipe => recipe.Output = new CultRecordRef(_cache.RefOf(_cache.GetAll().First()).Key)); + + Step(world, 2); + Assert.Null(world.Unit.Run); + Assert.Equal(0, Held(world, Iron)); + Assert.Equal(0, Held(world, IronFillers[0])); + Stock(world, IronFillers[0], 3); + Step(world, 2); + Assert.Null(world.Unit.Run); + } + + // Recipes.Fillers reads an index built once per catalog; it is rebuilt when a recipe changes. + [Fact] + public void FillersFollowTheCatalogThroughAChange() + { + var roles = _cache.GetAll().SelectMany(recipe => recipe.Fills).Distinct().ToArray(); + foreach (var role in roles) + { + var scan = _cache.GetAll() + .Where(recipe => recipe.Fills.Contains(role) && Recipes.IsCommodity(_cache.Get(recipe.Output))) + .Select(recipe => recipe.Output.Key).OrderBy(key => key.Value, StringComparer.Ordinal).ToArray(); + Assert.Equal(scan, Recipes.Fillers(_cache, role)); + } + + var slag = _cache.RefOf(_cache.GetByName("Slag")); + Assert.DoesNotContain(slag.Key, Recipes.Fillers(_cache, "iron ore")); + _cache.Upsert(typeof(RecipeData), new RecipeData { Output = slag, Fills = { "iron ore" } }, RecipeData.KeyOf(slag.Key)); + Assert.Contains(slag.Key, Recipes.Fillers(_cache, "iron ore")); + _cache.Remove(RecipeData.KeyOf(slag.Key)); + Assert.DoesNotContain(slag.Key, Recipes.Fillers(_cache, "iron ore")); + Assert.Empty(Recipes.Fillers(_cache, "no such role")); + } +} diff --git a/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs b/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs index 991af3b44..7ec6abaf5 100644 --- a/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs +++ b/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs @@ -234,6 +234,7 @@ public sealed class FireControlCut6cTests : IDisposable // Targeting Maker, so IsAvailable rejects Targeting Maker's products by allegiance. var game = new SavedGame { + InfluenceScale = 1, Factions = new[] { maker }, Relationships = new[] { FactionRelationship.Neutral }, HomeZones = new Dictionary { { 0, 0 } }, diff --git a/tests/Aetheria.Shared.Tests/FlightTests.cs b/tests/Aetheria.Shared.Tests/FlightTests.cs index 1cb2f9c48..a50b02d13 100644 --- a/tests/Aetheria.Shared.Tests/FlightTests.cs +++ b/tests/Aetheria.Shared.Tests/FlightTests.cs @@ -941,8 +941,8 @@ public sealed class FlightTests : IDisposable Assert.Equal(turns, turn != 0f); } - // Faction.Doctrine rides at wire slot 17; slot 16 is reserved for Relations; BossLoadout rides at 22, which sets the array's length. - // Kills: the key moved. + // Faction.Relations rides at wire slot 16 and Faction.Doctrine at 17; BossLoadout rides at 22, which sets the array's length. + // Kills: either key moved. [Fact] public void TheFactionDoctrineRidesAtWireSlot17() { @@ -952,11 +952,25 @@ public sealed class FlightTests : IDisposable CultDocumentMessagePackSerialization.OptionsFor(typeof(Faction).Assembly))); Assert.Equal(23, slots.Length); // 19 is Assembly, 21 is Places, 22 is BossLoadout - Assert.Null(slots[16]); + Assert.Empty(Assert.IsAssignableFrom(slots[16])); // 16 is Relations, none authored here var doctrine = Assert.IsType(slots[17]); Assert.Equal(6f, Convert.ToSingle(doctrine[1])); } + // A faction's relations survive the wire with the regarded faction and the stance. Kills: a wrong key or a field the wire leaves out. + [Fact] + public void ARelationsMapRoundTrips() + { + var regarded = new CultRecordRef(new CultRecordKey("faction:regarded")); + var faction = new Faction { Name = "Grudging", Relations = { [regarded] = FactionRelationship.Hated } }; + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(Faction).Assembly); + + var back = MessagePack.MessagePackSerializer.Deserialize(MessagePack.MessagePackSerializer.Serialize(faction, options), options); + + Assert.Equal(FactionRelationship.Hated, Assert.Single(back.Relations).Value); + Assert.Equal(regarded.Key, Assert.Single(back.Relations).Key.Key); + } + // A cast faction that already has a doctrine keeps it, whatever it holds: one that differs in its engagement and one // that differs only below it. Kills: the keep tested on the engagement alone, or on any one field. [Fact] diff --git a/tests/Aetheria.Shared.Tests/FormationTests.cs b/tests/Aetheria.Shared.Tests/FormationTests.cs new file mode 100644 index 000000000..dd926caed --- /dev/null +++ b/tests/Aetheria.Shared.Tests/FormationTests.cs @@ -0,0 +1,107 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using Xunit; +using float2 = CultMath.float2; +using static CultMath.math; + +// Formations (compiled groups a summon places, with a stable id and a cast faction) into a running arena. +public sealed partial class RunStartTests +{ + private sealed class FormationOf : Formation + { + private readonly string _faction; + public FormationOf(string faction) => _faction = faction; + public override string Id => "test-formation"; + public override string Name => "Test Formation"; + public override string Faction => _faction; + public override void Place(ZoneStage stage, Faction faction, float2 at, float2 facing) => + stage.Place(stage.Generated("", faction), at, facing, piloted: true); + } + + // The cast and size each formation is authored with: a literal, so a miscast formation cannot vouch for itself. + private static readonly (string Id, string Faction, int Ships)[] Authored = + { + ("sparring-target", null, 1), + ("zhestokost-pair", "Zhestokost", 2), + ("pirates-pair", "Pirates", 2), + ("lucent-pair", "Lucent Media", 2), + ("aeronautics-pair", "Aeronautics Unlimited", 2) + }; + + // Every formation summons into a running zone: no failure, each placed entity is a member with one agent and carries the + // faction the formation is authored for (a literal, resolved through the catalog as the game does), the ships stand 60 m + // apart centred on the summon point. Kills: a formation that drops or miscasts its faction, places nothing, or collapses + // its spacing. + [Fact] + public void EveryFormationSummons() + { + Assert.Equal(Authored.Select(a => a.Id), Formations.All.Select(formation => formation.Id)); + foreach (var formation in Formations.All) + { + var (_, factionName, ships) = Authored.Single(a => a.Id == formation.Id); + var zone = Arena(true); + Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))); + for (var tick = 0; tick < 5; tick++) zone.Update(.1f); + + var failures = new List(); + var summoned = formation.Summon(_items, zone, float2(400, 0), float2(-1, 0), failures); + + Assert.True(failures.Count == 0, $"{formation.Id}: {string.Join("; ", failures)}"); + Assert.NotNull(summoned); + Assert.NotEmpty(summoned); + var expected = factionName == null ? null : _galaxy.ResolveFaction(factionName); + if (factionName != null) + { + Assert.NotNull(expected); + Assert.Equal(factionName, expected.Name); + } + Assert.Equal(ships, summoned.Count); + foreach (var entity in summoned) + { + SafeAssert.In(zone, entity, $"{formation.Id}: the summoned ship is admitted"); + Assert.Equal(1, AgentsOf(zone, entity)); + Assert.Same(expected, entity.Faction); + } + if (ships == 2) + { + var a = summoned[0].Position.xz; + var b = summoned[1].Position.xz; + Assert.Equal(60f, length(a - b), 1e-3f); + Assert.Equal(400f, (a.x + b.x) / 2, 1e-3f); + Assert.Equal(0f, (a.y + b.y) / 2, 1e-3f); + } + } + } + + // Ids are the stable handle: unique, kebab-case, and found by ById. Kills: duplicate or display-text ids. + [Fact] + public void FormationIdsAreStable() + { + var ids = Formations.All.Select(formation => formation.Id).ToList(); + Assert.Equal(ids.Count, ids.Distinct().Count()); + foreach (var formation in Formations.All) + { + Assert.Matches(new Regex("^[a-z0-9]+(-[a-z0-9]+)*$"), formation.Id); + Assert.Same(formation, Formations.ById(formation.Id)); + } + Assert.Null(Formations.ById("no-such-formation")); + } + + // A faction the catalog does not hold refuses the summon rather than arriving factionless. Kills: resolving to null and + // summoning factionless ships. + [Fact] + public void AnUnknownFormationFactionSummonsNothing() + { + var zone = Arena(true); + Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))); + var entities = zone.Entities.ToList(); + var agents = zone.Agents.ToList(); + var failures = new List(); + + Assert.Null(new FormationOf("No Such Faction").Summon(_items, zone, float2(400, 0), float2(-1, 0), failures)); + + Assert.Contains(failures, failure => failure.Contains("No Such Faction")); + SafeAssert.Unchanged(zone, entities, agents); + } +} diff --git a/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs b/tests/Aetheria.Shared.Tests/FungibleCommodityTests.cs similarity index 53% rename from tests/Aetheria.Shared.Tests/MiningCut5bTests.cs rename to tests/Aetheria.Shared.Tests/FungibleCommodityTests.cs index 9ad960a77..6bcf65c8a 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs +++ b/tests/Aetheria.Shared.Tests/FungibleCommodityTests.cs @@ -12,15 +12,16 @@ using GameCult.Caching.MessagePack; using MessagePack; using Xunit; -// Mining Cut 5b (docs/mining-cut-refresh.md, Cut 5, Q6b = A): a mined unit carries an Extracted lot naming the zone, the belt -// and the ore; stacks merge, split, restore and save by lot. Fixtures are Cut 3's belt scene and Cut 5a's bay and stock helpers. -public sealed class MiningCut5bTests : IDisposable +// Ruling aetheria-living-world:ruling:simple-commodities-fungible (supersedes Mining Cut 5b, Q6b A): a simple commodity carries +// no lot, so units of one design merge whatever their source, Extract mints nothing, and a save from before the ruling still +// reads. Fixtures are Cut 3's belt scene and Cut 5a's bay and stock helpers. +public sealed class FungibleCommodityTests : IDisposable { private readonly MiningCut3Tests _scenes = new MiningCut3Tests(); private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-mining5b-" + Guid.NewGuid().ToString("N")); private uint _ordinal; - public MiningCut5bTests() => Directory.CreateDirectory(_root); + public FungibleCommodityTests() => Directory.CreateDirectory(_root); public void Dispose() { @@ -46,6 +47,7 @@ public sealed class MiningCut5bTests : IDisposable MiningCut5aTests.Stock(scene, kind, (ore, 1f)); var game = new SavedGame { + InfluenceScale = 1, Seed = 5, Factions = new CultRecordRef[0], Relationships = new FactionRelationship[0], HomeZones = new Dictionary(), BossZones = new Dictionary(), DiscoveredZones = new[] { 0 }, ActionBarBindings = new SavedActionBarBinding[0], Entrance = 0, Exit = -1 @@ -78,86 +80,86 @@ public sealed class MiningCut5bTests : IDisposable FireControl.Extract(zone, chunk, zone.Wear(chunk, 1e6f), ship, SimulationDice.For(zone.DropSeed, SimulationDice.OreStream, ++_ordinal)); } - private static SimpleCommodity[] Stacks(EquippedCargoBay bay) => bay.Cargo.Keys.OfType().OrderBy(s => s.Lot).ToArray(); + private static SimpleCommodity[] Stacks(EquippedCargoBay bay) => bay.Cargo.Keys.OfType().OrderBy(s => s.Quantity).ToArray(); + + private static SimpleCommodity Units(Field f, SimpleCommodityData design, int quantity) => + new SimpleCommodity { Data = new CultRecordRef(f.Scene.Cache.RefOf(design).Key), Quantity = quantity }; [Fact] - public void MinedUnitsCarryAnExtractedLotNamingZoneBeltAndOre() - { - var f = Build(); - var zone = ZoneOf(f, 2); - var ship = Shooter(f, zone); - var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); - Mine(f, zone, ship, 1, 0); - - var stack = Assert.Single(Stacks(bay)); - Assert.Equal(4, stack.Quantity); - Assert.NotEqual(0, stack.Lot); - var lot = f.Scene.Items.GetLot(stack); - var origin = Assert.IsType(lot.Origin); - Assert.Equal(2, origin.Zone); - Assert.Equal(f.Scene.Belts[1], origin.Body.Key); - Assert.Equal(stack.Data.Key, origin.Commodity.Key); - Assert.Equal(stack.Data.Key, lot.Design.Key); - Assert.Equal(1f, lot.Quality); - Assert.Equal(default, lot.Product); - } - - [Fact] - public void AZoneWithNoGalaxyIsMinus1() - { - var f = Build(); - var zone = ZoneOf(f, -1); - var ship = Shooter(f, zone); - var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); - Mine(f, zone, ship, 0, 0); - Assert.Equal(-1, Assert.IsType(f.Scene.Items.GetLot(Assert.Single(Stacks(bay))).Origin).Zone); - } - - [Fact] - public void UnitsFromOneSourceStack_UnitsFromTwoSourcesDoNot() + public void UnitsMinedFromTwoBeltsAndTwoZonesMergeIntoOneStack() { var f = Build(); var zone = ZoneOf(f, 1); var ship = Shooter(f, zone); var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); Mine(f, zone, ship, 0, 0); - Mine(f, zone, ship, 0, 1); - var one = Assert.Single(Stacks(bay)); - Assert.Equal(8, one.Quantity); - Mine(f, zone, ship, 1, 0); - var stacks = Stacks(bay); - Assert.Equal(new[] { 8, 4 }, stacks.Select(s => s.Quantity)); - Assert.NotEqual(stacks[0].Lot, stacks[1].Lot); - Assert.Equal(2, f.Scene.Items.Lots.Lots.Values.Count(l => l.Origin is Extracted)); - // Two lots of one ore still total one commodity for the market and the hold. - Assert.Equal(12, MiningCut5aTests.Units(bay, "Rock", f.Scene)); + Assert.Equal(8, Assert.Single(Stacks(bay)).Quantity); + + var otherZone = ZoneOf(f, 2); + var other = Shooter(f, otherZone); + var otherBay = MiningCut5aTests.Bay(f.Scene, other, 4, 4, "Hold"); + Mine(f, otherZone, other, 0, 1); + Assert.True(bay.TryStore(otherBay.Remove(Assert.Single(Stacks(otherBay)), 4))); + Assert.Equal(12, Assert.Single(Stacks(bay)).Quantity); } - // TryFindSpace and the at-coordinate store both look for a stack to top up: a stack of another lot is not one. [Fact] - public void ASearchAndAStoreIgnoreAStackOfAnotherLot() + public void BoughtAndMinedUnitsOfOneDesignMerge() { var f = Build(); var zone = ZoneOf(f, 0); var ship = Shooter(f, zone); - var bay = MiningCut5aTests.Bay(f.Scene, ship, 1, 1, "Hold"); - var key = new CultRecordRef(f.Scene.Cache.RefOf(f.Ore).Key); - SimpleCommodity Units(int lot, int quantity) => new SimpleCommodity { Data = key, Lot = lot, Quantity = quantity }; + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Assert.True(bay.TryStore(Units(f, f.Ore, 5))); + Mine(f, zone, ship, 0, 0); + Assert.Equal(9, Assert.Single(Stacks(bay)).Quantity); - Assert.True(bay.TryStore(Units(7, 90))); - Assert.False(bay.TryFindSpace(Units(8, 5), out _)); - Assert.True(bay.TryFindSpace(Units(7, 5), out _)); - var other = Units(8, 5); - Assert.False(bay.TryStore(other, new int2(0, 0))); - Assert.Equal(90, Assert.Single(bay.Cargo.Keys.OfType()).Quantity); - Assert.Equal(5, other.Quantity); - Assert.True(bay.TryStore(Units(7, 5), new int2(0, 0))); - Assert.Equal(95, Assert.Single(bay.Cargo.Keys.OfType()).Quantity); + var floating = zone.Release(Units(f, f.Ore, 4), new float2(0, 0), new float2(0, 0)); + Assert.True(zone.TryPickUp(ship, floating.Id)); + Assert.Equal(13, Assert.Single(Stacks(bay)).Quantity); } [Fact] - public void ASplitStackKeepsItsLot() + public void TwoDesignsNeverMerge() + { + var f = Build(); + var zone = ZoneOf(f, 0); + var ship = Shooter(f, zone); + var shells = MiningCut5aTests.Commodity("Shells"); + f.Scene.Cache.Upsert(shells); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Assert.True(bay.TryStore(Units(f, f.Ore, 5))); + Assert.True(bay.TryStore(Units(f, shells, 5))); + Assert.Equal(2, Stacks(bay).Length); + + var small = MiningCut5aTests.Bay(f.Scene, ship, 1, 1, "Small"); + Assert.True(small.TryStore(Units(f, f.Ore, 90))); + Assert.False(small.TryFindSpace(Units(f, shells, 5))); + Assert.True(small.TryFindSpace(Units(f, f.Ore, 5))); + var other = Units(f, shells, 5); + Assert.False(small.TryStore(other, new int2(0, 0))); + Assert.Equal(90, Assert.Single(Stacks(small)).Quantity); + Assert.True(small.TryStore(Units(f, f.Ore, 5), new int2(0, 0))); + Assert.Equal(95, Assert.Single(Stacks(small)).Quantity); + } + + [Fact] + public void ExtractAddsNothingToTheLedger() + { + var f = Build(); + var zone = ZoneOf(f, 0); + var ship = Shooter(f, zone); + MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + var lots = f.Scene.Items.Lots; + var (count, next) = (lots.Lots.Count, lots.NextLot); + Mine(f, zone, ship, 0, 0); + Mine(f, zone, ship, 1, 0); + Assert.Equal((count, next), (lots.Lots.Count, lots.NextLot)); + } + + [Fact] + public void ASplitStackIsTheSameDesign() { var f = Build(); var zone = ZoneOf(f, 0); @@ -165,24 +167,20 @@ public sealed class MiningCut5bTests : IDisposable var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); Mine(f, zone, ship, 0, 0); var stack = Assert.Single(Stacks(bay)); - var part = bay.Remove(stack, 3); - Assert.Equal(3, part.Quantity); - Assert.Equal(stack.Lot, part.Lot); - Assert.NotEqual(0, part.Lot); - Assert.Equal(1, stack.Quantity); + Assert.Equal((3, 1), (((ICommodityStack) part).Quantity, stack.Quantity)); + Assert.Equal(stack.Data.Key, part.Data.Key); } - // A saved stack above its design's MaxStack comes back as several stacks, every one of the saved lot. + // A saved stack above its design's MaxStack comes back as several stacks of the one design. [Fact] - public void ARestoredOversizeStackKeepsItsLot() + public void ARestoredOversizeStackSplitsByDesign() { var f = Build(); var zone = ZoneOf(f, 0); var ship = Shooter(f, zone); var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); for (var rock = 0; rock < 2; rock++) Mine(f, zone, ship, 0, rock); - var lot = Assert.Single(Stacks(bay)).Lot; var pack = EntitySerializer.Pack(ship); f.Ore.MaxStack = 3; @@ -191,7 +189,7 @@ public sealed class MiningCut5bTests : IDisposable var stacks = restored.CargoBays.SelectMany(Stacks).ToArray(); Assert.Equal(8, stacks.Sum(s => s.Quantity)); Assert.True(stacks.Length >= 3); - Assert.All(stacks, s => Assert.Equal(lot, s.Lot)); + Assert.All(stacks, s => Assert.Equal(f.Scene.Cache.RefOf(f.Ore).Key, s.Data.Key)); } private CultCache Open() => AetheriaStores.Open(Path.Combine(_root, "Aetheria.cc"), Path.Combine(_root, "run.cc"), Path.Combine(_root, "player.cc")); @@ -222,6 +220,7 @@ public sealed class MiningCut5bTests : IDisposable { var game = new SavedGame { + InfluenceScale = 1, Factions = new CultRecordRef[0], Relationships = new FactionRelationship[0], HomeZones = new Dictionary(), BossZones = new Dictionary(), DiscoveredZones = new[] { 0 }, ActionBarBindings = new SavedActionBarBinding[0], Exit = -1 @@ -236,26 +235,7 @@ public sealed class MiningCut5bTests : IDisposable using (var cache = Open()) return RunSave.Lots(cache); } - // An ore the draw never picks mints no lot: the ledger gains nothing for it, only for the ore that was drawn. - [Fact] - public void AnOreThatDrawsZeroUnitsMintsNoLot() - { - var f = Build(); - var dud = MiningCut5aTests.Commodity("Dud"); - MiningCut5aTests.Stock(f.Scene, f.Scene.Kinds[0], (f.Ore, 1f), (dud, 1e-12f)); - var zone = ZoneOf(f, 0); - var ship = Shooter(f, zone); - var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); - var before = f.Scene.Items.Lots.Lots.Count; - Mine(f, zone, ship, 0, 0); - - Assert.Equal(4, MiningCut5aTests.Units(bay, "Rock", f.Scene)); - Assert.Equal(0, MiningCut5aTests.Units(bay, "Dud", f.Scene)); - Assert.Equal(before + 1, f.Scene.Items.Lots.Lots.Count); - Assert.Equal(1, f.Scene.Items.Lots.Lots.Values.Count(l => l.Origin is Extracted)); - } - - // A crafted item with no lot is corruption and the save says so; a SimpleCommodity at Lot 0 is ordinary stock. + // A crafted item with no lot is corruption and the save says so; a simple commodity has no lot and roots nothing. [Fact] public void ACraftedItemAtLotZeroFailsTheSaveLoudly() { @@ -264,59 +244,31 @@ public sealed class MiningCut5bTests : IDisposable var thrown = Assert.Throws(() => SaveAndReload(new ProvenanceLedger(), crafted)); Assert.Contains("Lot 0 is not in the provenance ledger", thrown.Message); - var stock = new SimpleCommodity { Data = new CultRecordRef(f.Scene.Cache.RefOf(f.Ore).Key), Quantity = 3, Lot = 0 }; + var stock = new SimpleCommodity { Data = new CultRecordRef(f.Scene.Cache.RefOf(f.Ore).Key), Quantity = 3 }; var savedStock = SaveAndReload(new ProvenanceLedger(), stock); Assert.Equal(new[] { _hullLot }, savedStock.Lots.Keys); } - [Fact] - public void AMinedStackSurvivesSaveGc() + private static byte[] PreRulingStack(CultRecordRef key, MessagePackSerializerOptions options) { - var f = Build(); - var zone = ZoneOf(f, 1); - var ship = Shooter(f, zone); - var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); - Mine(f, zone, ship, 0, 0); - Mine(f, zone, ship, 1, 0); - var held = Stacks(bay); - Assert.Equal(2, held.Length); - // A third lot nobody holds: floated and gone, or never collected. - var orphan = f.Scene.Items.ExtractedLot(1, new CultRecordKey("elsewhere"), f.Ore); - - var saved = SaveAndReload(f.Scene.Items.Lots, held); - - Assert.Equal(held.Select(s => s.Lot).Append(_hullLot).OrderBy(i => i), saved.Lots.Keys.OrderBy(i => i)); - Assert.DoesNotContain(orphan, saved.Lots.Keys); - var origin = Assert.IsType(saved[held[0].Lot].Origin); - Assert.Equal(1, origin.Zone); - Assert.Equal(f.Scene.Belts[0], origin.Body.Key); + var buffer = new System.Buffers.ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteArrayHeader(2); + writer.Write(0); // Union(0, SimpleCommodity) + writer.WriteArrayHeader(12); + MessagePackSerializer.Serialize(ref writer, key, options); + MessagePackSerializer.Serialize(ref writer, ItemRotation.None, options); + writer.Write(7); // Quantity + for (var slot = 3; slot < 11; slot++) writer.WriteNil(); + writer.Write(9); // slot 11: the lot a pre-ruling mined stack named + writer.Flush(); + return buffer.WrittenSpan.ToArray(); } + // A save from before the ruling: a three-slot stack from before SimpleCommodity had a lot, and a twelve-slot stack + // whose slot 11 names one. Both read as a plain stack, and merge with a fresh stack of their design. [Fact] - public void TheLotIndexIsRebuiltOnContinue() - { - var f = Build(); - var zone = ZoneOf(f, 1); - var ship = Shooter(f, zone); - var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); - Mine(f, zone, ship, 0, 0); - var held = Assert.Single(Stacks(bay)); - - var saved = SaveAndReload(f.Scene.Items.Lots, held); - var continued = new ItemManager(1u, f.Scene.Cache, saved, RunSaveTests.TestSettings(), _ => { }); - - Assert.Equal(held.Lot, continued.ExtractedLot(1, f.Scene.Belts[0], f.Ore)); - Assert.Equal(2, saved.Lots.Count); // the mined lot and the hull - var next = continued.ExtractedLot(1, f.Scene.Belts[1], f.Ore); - Assert.NotEqual(held.Lot, next); - Assert.Equal(3, saved.Lots.Count); - // Zone and ore tell lots apart as the belt does. - Assert.NotEqual(next, continued.ExtractedLot(2, f.Scene.Belts[1], f.Ore)); - } - - // A save from before the field reached SimpleCommodity: Data, Rotation, Quantity and nothing else. - [Fact] - public void OldSavesReadLotZero() + public void APreRulingStackReadsAndMerges() { var f = Build(); var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ItemInstance).Assembly); @@ -330,17 +282,71 @@ public sealed class MiningCut5bTests : IDisposable MessagePackSerializer.Serialize(ref writer, ItemRotation.None, options); writer.Write(7); writer.Flush(); - var old = Assert.IsType(MessagePackSerializer.Deserialize(buffer.WrittenMemory, options)); - Assert.Equal(7, old.Quantity); - Assert.Equal(0, old.Lot); - Assert.Equal(key.Key, old.Data.Key); + Assert.Equal((7, key.Key), (old.Quantity, old.Data.Key)); - // A lot rides the wire; a Lot-0 stack is no root, so the old stack saves no lot. - var back = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize( - new SimpleCommodity { Data = key, Quantity = 2, Lot = 9 }, options), options); - Assert.Equal(9, back.Lot); - var savedOld = SaveAndReload(new ProvenanceLedger(), old); - Assert.Equal(new[] { _hullLot }, savedOld.Lots.Keys); // the hull only + var lotted = Assert.IsType(MessagePackSerializer.Deserialize(PreRulingStack(key, options), options)); + Assert.Equal((7, key.Key), (lotted.Quantity, lotted.Data.Key)); + + var zone = ZoneOf(f, 0); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 1, 1, "Hold"); + Assert.True(bay.TryStore(Units(f, f.Ore, 5))); + Assert.True(bay.TryStore(lotted)); + Assert.Equal(12, Assert.Single(Stacks(bay)).Quantity); + } + + // A run ledger saved before the ruling holds mined-source lots (Provenance arm 2: zone, commodity, belt). They read as + // RetiredExtracted, and a save drops them: no item roots them. + [Fact] + public void APreRulingExtractedLotLoadsAndCommitDropsIt() + { + var f = Build(); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ItemInstance).Assembly); + var buffer = new System.Buffers.ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteArrayHeader(2); + writer.Write(2); + writer.WriteArrayHeader(3); + writer.Write(1); + MessagePackSerializer.Serialize(ref writer, new CultRecordRef(f.Scene.Cache.RefOf(f.Ore).Key), options); + MessagePackSerializer.Serialize(ref writer, new CultRecordRef(f.Scene.Belts[0]), options); + writer.Flush(); + var origin = Assert.IsType(MessagePackSerializer.Deserialize(buffer.WrittenMemory, options)); + + var ledger = new ProvenanceLedger(); + var retired = ledger.Add(new Lot { Design = default, Origin = origin, Quality = 1f, Roles = new List() }); + var saved = SaveAndReload(ledger); + Assert.DoesNotContain(retired, saved.Lots.Keys); + Assert.Equal(new[] { _hullLot }, saved.Lots.Keys); + } + + // A produced lot that named a mined input keeps its place in a save and loses the input: the input's lot is dropped + // (no item roots it), and a ledger that named it would fail the next save (finding input-keeps-retired-lot). + [Fact] + public void ReachableDropsARetiredInputAndKeepsTheProducedLot() + { + var f = Build(); + var ledger = new ProvenanceLedger(); + var facility = ledger.Add(new Lot { Design = default, Origin = new Attributed(), Quality = 1f, Roles = new List() }); + var retired = ledger.Add(new Lot { Design = default, Origin = new RetiredExtracted(), Quality = 1f, Roles = new List() }); + var kept = ledger.Add(new Lot { Design = default, Origin = new Attributed(), Quality = 1f, Roles = new List() }); + var produced = ledger.Add(new Lot + { + Design = default, Quality = 1f, Roles = new List(), + Origin = new Produced { Station = facility, Facility = facility, Inputs = new[] { retired, kept } } + }); + var item = new EquippableItem { Data = f.Scene.Cache.RefOf(f.Scene.Hull), Lot = produced }; + + var saved = SaveAndReload(ledger, item); + Assert.Contains(produced, saved.Lots.Keys); + Assert.DoesNotContain(retired, saved.Lots.Keys); + Assert.Equal(new[] { kept }, Assert.IsType(saved[produced].Origin).Inputs); + // The live ledger is not mutated by a save. + Assert.Equal(new[] { retired, kept }, ((Produced) ledger[produced].Origin).Inputs); + + // The saved ledger names only lots it holds, so a second save does not throw. + var again = SaveAndReload(saved, item); + Assert.Contains(produced, again.Lots.Keys); } } diff --git a/tests/Aetheria.Shared.Tests/GearPrices.cs b/tests/Aetheria.Shared.Tests/GearPrices.cs new file mode 100644 index 000000000..1cfb97d9d --- /dev/null +++ b/tests/Aetheria.Shared.Tests/GearPrices.cs @@ -0,0 +1,12 @@ +using System; + +// The one-shot catalog commands (pd-gear, launch-suppressor, inspection-scanner, ...) author gear at the prices they were written +// with, a hundred times the shipped catalog's (cut gear-money-rescale: Equippable and Consumable prices were divided by 100 once and +// the commands keep their literals). A test that sets a command's landed design against the shipped record compares the price +// through this, the transform the rescale applied: half away from zero, never below 1. +internal static class GearPrices +{ + public const int Divisor = 100; + + public static int Rescaled(int price) => Math.Max(1, (int) Math.Round(price / (double) Divisor, MidpointRounding.AwayFromZero)); +} diff --git a/tests/Aetheria.Shared.Tests/GenericDesignsCommandTests.cs b/tests/Aetheria.Shared.Tests/GenericDesignsCommandTests.cs index 87d5ed74c..23c7149c8 100644 --- a/tests/Aetheria.Shared.Tests/GenericDesignsCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/GenericDesignsCommandTests.cs @@ -26,14 +26,14 @@ public sealed class GenericDesignsCommandTests : IDisposable private void Edit(Action edit) { - var db = AetherDb.Open(catalogWritable: true, root: _root); + var db = AetherDb.OpenShipped(catalogWritable: true, root: _root); try { edit(db); } finally { db.Cache.Dispose(); } } private T Read(Func read) { - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); try { return read(db); } finally { db.Cache.Dispose(); } } diff --git a/tests/Aetheria.Shared.Tests/Golden/economy-balance-base.txt b/tests/Aetheria.Shared.Tests/Golden/economy-balance-base.txt new file mode 100644 index 000000000..a3b2a267c --- /dev/null +++ b/tests/Aetheria.Shared.Tests/Golden/economy-balance-base.txt @@ -0,0 +1,124 @@ +median implied wage 0.00722 per worker-second, spread 2, 74 links, 0 unpriced +14 faults +H-wage (14) + 043997a8-0661-4206-ab8a-10215ecf4efc: Regolith: implied wage 0.00071 is 0.1x the median 0.00722, outside the spread of 2. + commodity:ammonia: Ammonia: implied wage 0.025 is 3.46x the median 0.00722, outside the spread of 2. + commodity:anorthite: Anorthite: implied wage 0.00333 is 0.46x the median 0.00722, outside the spread of 2. + commodity:brannerite: Brannerite: implied wage 0.015 is 2.08x the median 0.00722, outside the spread of 2. + commodity:columbite: Columbite: implied wage 0.03333 is 4.62x the median 0.00722, outside the spread of 2. + commodity:isoferroplatinum: Isoferroplatinum: implied wage 0.18056 is 25x the median 0.00722, outside the spread of 2. + commodity:monazite: Monazite: implied wage 0.02667 is 3.69x the median 0.00722, outside the spread of 2. + commodity:native-gold: Native Gold: implied wage 0.09722 is 13.46x the median 0.00722, outside the spread of 2. + commodity:orthoclase: Orthoclase: implied wage 0.00067 is 0.09x the median 0.00722, outside the spread of 2. + commodity:sperrylite: Sperrylite: implied wage 0.09375 is 12.98x the median 0.00722, outside the spread of 2. + commodity:sylvite: Sylvite: implied wage 0.00167 is 0.23x the median 0.00722, outside the spread of 2. + commodity:troilite: Troilite: implied wage 0.00267 is 0.37x the median 0.00722, outside the spread of 2. + commodity:uraninite: Uraninite: implied wage 0.02 is 2.77x the median 0.00722, outside the spread of 2. + commodity:wolframite: Wolframite: implied wage 0.02 is 2.77x the median 0.00722, outside the spread of 2. + +Links by wage over the median (output | station kind | labour | price | derived cost | wage | ratio) + commodity:orthoclase (Orthoclase) | Mining Station | 6000 | 1 | 10.83 | 0.00067 | 0.09x + 043997a8-0661-4206-ab8a-10215ecf4efc (Regolith) | Mining Station | 8400 | 1 | 10.11 | 0.00071 | 0.1x + commodity:sylvite (Sylvite) | Mining Station | 4800 | 2 | 8.67 | 0.00167 | 0.23x + commodity:troilite (Troilite) | Mining Station | 6000 | 4 | 10.83 | 0.00267 | 0.37x + commodity:anorthite (Anorthite) | Mining Station | 7200 | 6 | 13 | 0.00333 | 0.46x + commodity:magnetite (Magnetite) | Mining Station | 6000 | 6 | 10.83 | 0.004 | 0.55x + commodity:native-copper (Native Copper) | Mining Station | 6000 | 16 | 21.67 | 0.00533 | 0.74x + commodity:primer (Primer) | Munitions Works | 4800 | 9 | 10.17 | 0.00646 | 0.89x + 00b5b3b2-2fc5-4adb-a1d7-c1a35d19afd3 (Nickel-Iron) | Mining Station | 6000 | 10 | 10.83 | 0.00667 | 0.92x + 214fe497-cda4-4cdb-a7c4-fe656e5ff61c (Methane) | Volatiles Station | 2400 | 4 | 4.33 | 0.00667 | 0.92x + commodity:chalcopyrite (Chalcopyrite) | Mining Station | 7200 | 12 | 13 | 0.00667 | 0.92x + commodity:pentlandite (Pentlandite) | Mining Station | 7200 | 12 | 13 | 0.00667 | 0.92x + 2e08445d-c130-497c-9fb3-8d752a24e654 (Algae) | Agriculture Station | 7200 | 12 | 14.69 | 0.00708 | 0.98x + commodity:steel (Steel) | Processing Station | 12000 | 29 | 32.32 | 0.00708 | 0.98x + 3c8b2b3d-ca1a-405f-966f-c64662a64418 (Circuit Board) | Fabrication Station | 8400 | 394 | 79.44 | 0.00714 | 0.99x + commodity:iron (Iron) | Processing Station | 8400 | 36 | 46.58 | 0.00714 | 0.99x + commodity:nitrocellulose (Nitrocellulose) | Munitions Works | 12000 | 103 | 101.47 | 0.00717 | 0.99x + commodity:he-warhead (High-Explosive Warhead) | Munitions Works | 21600 | 693 | 587.08 | 0.00718 | 0.99x + commodity:coil-barrel (Coil Barrel) | Fabrication Station | 72000 | 6363 | 3582.94 | 0.00719 | 1x + commodity:titanium (Titanium) | Processing Station | 16800 | 191 | 186.33 | 0.0072 | 1x + commodity:tungsten (Tungsten) | Processing Station | 16800 | 301 | 186.33 | 0.0072 | 1x + 8ac84e31-f0cf-43b2-8611-3316adfa4010 (Cluster Cannon) | Fabrication Station | 108000 | 9942 | 7844.06 | 0.0072 | 1x + 13116166-f0c8-43cf-a35f-8fd448bc630c (Autocannon) | Fabrication Station | 72000 | 4856 | 3413.22 | 0.00721 | 1x + 0271bb97-4ce8-4d64-97c3-8bfd3f76b2c6 (Light Machine Gun) | Fabrication Station | 54000 | 2756 | 2154.75 | 0.00722 | 1x + 08c07793-bc06-48dc-adc2-c7e61ef2cb2b (Uranium) | Processing Station | 9000 | 155 | 108.33 | 0.00722 | 1x + 1b4a2bb358eb432eb1cfc0ccf3317303 (Mine Launcher) | Fabrication Station | 43200 | 1716 | 1307.13 | 0.00722 | 1x + 2fd0d88b-f565-4021-85b4-02d9eae7be58 (Long Slug Rifle) | Fabrication Station | 72000 | 3268 | 2657.42 | 0.00722 | 1x + 3085fc8a-ec0d-4f6f-a339-ea43edb573e6 (Ammo) | Munitions Works | 18000 | 181 | 183.67 | 0.00722 | 1x + 36746041-a5bd-4b95-aa18-294acaaeae62 (Gold) | Processing Station | 3600 | 726 | 78 | 0.00722 | 1x + 679fb6a1-cefb-4adc-a49c-71942602196b (Slug Rifle) | Fabrication Station | 54000 | 3138 | 2527.42 | 0.00722 | 1x + 6af6446e40cb4cdd90d7a3fee04394d4 (Flak Gun) | Fabrication Station | 72000 | 6022 | 3845.47 | 0.00722 | 1x + 8776c2fd-45f6-4ca6-8ef0-5214be830182 (Diamond) | Mining Station | 14400 | 104 | 104 | 0.00722 | 1x + a8e259fc-fbf1-477a-8248-0277611f1859 (Potassium) | Processing Station | 1800 | 15 | 30.33 | 0.00722 | 1x + commodity:aluminium (Aluminium) | Processing Station | 10800 | 108 | 143 | 0.00722 | 1x + commodity:autoloader (Autoloader Mechanism) | Fabrication Station | 36000 | 1364 | 751.47 | 0.00722 | 1x + commodity:copper (Copper) | Processing Station | 14400 | 152 | 156 | 0.00722 | 1x + commodity:explosive-fill (Explosive Fill) | Munitions Works | 27000 | 160 | 146.25 | 0.00722 | 1x + commodity:fuze (Fuze) | Munitions Works | 10800 | 158 | 75.92 | 0.00722 | 1x + commodity:gun-barrel (Gun Barrel) | Fabrication Station | 36000 | 1002 | 1013.28 | 0.00722 | 1x + commodity:mine-dispenser (Mine Dispenser) | Fabrication Station | 18000 | 711 | 408.06 | 0.00722 | 1x + commodity:missiles (Missiles) | Munitions Works | 28800 | 678 | 626.42 | 0.00722 | 1x + commodity:nickel (Nickel) | Processing Station | 12600 | 131 | 134.33 | 0.00722 | 1x + commodity:nitric-acid (Nitric Acid) | Processing Station | 3600 | 31 | 25.28 | 0.00722 | 1x + commodity:platinum-group-metals (Platinum Group Metals) | Processing Station | 18000 | 1480 | 208 | 0.00722 | 1x + commodity:rare-earth-oxides (Rare Earth Oxides) | Processing Station | 32400 | 474 | 299 | 0.00722 | 1x + commodity:rifled-barrel (Rifled Barrel) | Fabrication Station | 36000 | 1384 | 1385.94 | 0.00722 | 1x + commodity:rocket-motor (Rocket Motor) | Munitions Works | 18000 | 455 | 457.76 | 0.00722 | 1x + commodity:tracking-feed (Tracking Feed) | Fabrication Station | 36000 | 3498 | 1298.92 | 0.00722 | 1x + d02bcf71f2c8420b878f036cd1a33bea (Point Defense Gun) | Fabrication Station | 54000 | 4890 | 2702.19 | 0.00722 | 1x + 3aa1ac05-6d55-4569-8a4b-e1c3c6e07c61 (Charged Scattergun) | Fabrication Station | 144000 | 29221 | 16874.72 | 0.00723 | 1x + commodity:lined-barrel (Lined Barrel) | Fabrication Station | 51000 | 1609 | 1390.28 | 0.00724 | 1x + commodity:niobium (Niobium) | Processing Station | 21000 | 452 | 216.67 | 0.00724 | 1x + commodity:gun-forging (Gun Forging) | Processing Station | 72000 | 638 | 649.28 | 0.00725 | 1x + commodity:mines (Mines) | Munitions Works | 18000 | 441 | 390.86 | 0.00728 | 1.01x + 0b449ae1-7eab-47e8-ac3c-2b6f6ff01f00 (Ballistic Powder) | Munitions Works | 14400 | 148 | 147.72 | 0.00729 | 1.01x + commodity:potassium-nitrate (Potassium Nitrate) | Processing Station | 1920 | 30 | 34.74 | 0.00729 | 1.01x + commodity:cellulose-pulp (Cellulose Pulp) | Processing Station | 3000 | 29 | 32.86 | 0.00733 | 1.02x + commodity:hexamine (Hexamine) | Processing Station | 3000 | 32 | 21.67 | 0.00733 | 1.02x + commodity:fragmentation-case (Fragmentation Case) | Fabrication Station | 8400 | 60 | 62.65 | 0.00738 | 1.02x + commodity:actuator (Actuator) | Fabrication Station | 9600 | 523 | 213.42 | 0.0074 | 1.02x + 3acbb2bf-19fb-4591-bef1-dc9d5dde7e7a (Water) | Volatiles Station | 2400 | 3 | 2.89 | 0.0075 | 1.04x + commodity:oxygen (Oxygen) | Processing Station | 2400 | 9 | 8.67 | 0.0075 | 1.04x + commodity:projectile (Projectile) | Fabrication Station | 2880 | 20 | 21.36 | 0.00764 | 1.06x + commodity:ilmenite (Ilmenite) | Mining Station | 7200 | 14 | 13 | 0.00778 | 1.08x + commodity:shell-casing (Shell Casing) | Fabrication Station | 2880 | 13 | 13.28 | 0.00799 | 1.11x + commodity:brannerite (Brannerite) | Mining Station | 6000 | 45 | 21.67 | 0.015 | 2.08x + commodity:uraninite (Uraninite) | Mining Station | 6000 | 60 | 21.67 | 0.02 | 2.77x + commodity:wolframite (Wolframite) | Mining Station | 6000 | 60 | 21.67 | 0.02 | 2.77x + commodity:ammonia (Ammonia) | Volatiles Station | 2400 | 15 | 4.33 | 0.025 | 3.46x + commodity:monazite (Monazite) | Mining Station | 6000 | 80 | 21.67 | 0.02667 | 3.69x + commodity:columbite (Columbite) | Mining Station | 6000 | 100 | 21.67 | 0.03333 | 4.62x + commodity:sperrylite (Sperrylite) | Mining Station | 4800 | 450 | 34.67 | 0.09375 | 12.98x + commodity:native-gold (Native Gold) | Mining Station | 3600 | 350 | 26 | 0.09722 | 13.46x + commodity:isoferroplatinum (Isoferroplatinum) | Mining Station | 3600 | 650 | 26 | 0.18056 | 25x + +Belts (kind: abundance-weighted price and derived cost per unit; each ore: share, extraction wage ratio, price, cost) + Basaltic: price 9.37, cost 12.35 + 043997a8-0661-4206-ab8a-10215ecf4efc 47 % | wage 0.1x | price 1 | cost 10.11 + commodity:ilmenite 14 % | wage 1.08x | price 14 | cost 13 + commodity:anorthite 19 % | wage 0.46x | price 6 | cost 13 + commodity:native-copper 3 % | wage 0.74x | price 16 | cost 21.67 + commodity:chalcopyrite 3 % | wage 0.92x | price 12 | cost 13 + commodity:orthoclase 7 % | wage 0.09x | price 1 | cost 10.83 + commodity:uraninite 1 % | wage 2.77x | price 60 | cost 21.67 + commodity:brannerite 1 % | wage 2.08x | price 45 | cost 21.67 + commodity:monazite 2 % | wage 3.69x | price 80 | cost 21.67 + commodity:columbite 1 % | wage 4.62x | price 100 | cost 21.67 + commodity:wolframite 1 % | wage 2.77x | price 60 | cost 21.67 + Carbonaceous: price 2.75, cost 10.25 + 043997a8-0661-4206-ab8a-10215ecf4efc 62 % | wage 0.1x | price 1 | cost 10.11 + commodity:magnetite 19 % | wage 0.55x | price 6 | cost 10.83 + commodity:pentlandite 6 % | wage 0.92x | price 12 | cost 13 + commodity:sylvite 12 % | wage 0.23x | price 2 | cost 8.67 + Metallic: price 28.21, cost 11.46 + 00b5b3b2-2fc5-4adb-a1d7-c1a35d19afd3 83 % | wage 0.92x | price 10 | cost 10.83 + commodity:troilite 13 % | wage 0.37x | price 4 | cost 10.83 + commodity:native-gold 2 % | wage 13.46x | price 350 | cost 26 + commodity:isoferroplatinum 2 % | wage 25x | price 650 | cost 26 + Stony: price 8.23, cost 10.88 + 043997a8-0661-4206-ab8a-10215ecf4efc 63 % | wage 0.1x | price 1 | cost 10.11 + commodity:troilite 16 % | wage 0.37x | price 4 | cost 10.83 + 00b5b3b2-2fc5-4adb-a1d7-c1a35d19afd3 8 % | wage 0.92x | price 10 | cost 10.83 + commodity:pentlandite 6 % | wage 0.92x | price 12 | cost 13 + commodity:chalcopyrite 5 % | wage 0.92x | price 12 | cost 13 + commodity:sperrylite 1 % | wage 12.98x | price 450 | cost 34.67 diff --git a/tests/Aetheria.Shared.Tests/HardpointFitTests.cs b/tests/Aetheria.Shared.Tests/HardpointFitTests.cs new file mode 100644 index 000000000..26657ee00 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/HardpointFitTests.cs @@ -0,0 +1,38 @@ +using System; +using System.Linq; +using Xunit; + +// The hardpoint census (campaign aetheria-release, cut hardpoint-fit-1): every hardpoint on every hull the game boots takes a +// design some product sells. Program.UnfillableHardpoints is the one census, over HardpointData.Takes, the one fit rule. +public sealed class HardpointFitTests +{ + // Every hardpoint on every hull the game boots (shipped catalog plus GameData/Mods) takes a design some product sells. + [Fact] + public void EveryHardpointTheGameBootsTakesASoldDesign() + { + using var cache = RestoredHullsTests.OpenCatalog(); + Assert.Empty(Program.UnfillableHardpoints(cache)); + } + + // Positive control: the census is not a tautology. The Zenith's (11,6) mount put back to rotation None (its authoring slip, in + // memory on a read-only catalog) is the one mount no sold design takes, and the census names it. + [Fact] + public void TheCensusNamesAMountNoSoldDesignTakes() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var mount = Assert.Single(Assert.Single(cache.GetAll(), h => h.Name == "Zenith").Hardpoints, + h => h.Position.x == 11 && h.Position.y == 6); + Assert.Equal(ItemRotation.Clockwise, mount.Rotation); + mount.Rotation = ItemRotation.None; + Assert.Equal(new[] { "Zenith (Station) Radiator 1x4 at (11,6)" }, Program.UnfillableHardpoints(cache)); + } + + // The census is over the catalog the game boots, packages included: a package hull's mount is as fillable as a shipped one. + [Fact] + public void TheCensusReadsThePackagesTheGameBoots() + { + var root = RunStartTests.FindRepoRoot(); + using (var db = AetherDb.OpenBooted(root: root)) + Assert.Contains(db.Cache.GetAll(), hull => hull.Name == "Nakovalnya"); + } +} diff --git a/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs new file mode 100644 index 000000000..6d5341ae9 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs @@ -0,0 +1,163 @@ +using System.Collections.Generic; +using System.Linq; +using CultMath; +using Xunit; +using static CultMath.math; + +// Hardpoint gear holds the hardpoint it was seated in across save and reload: an origin two hardpoints accept is +// resolved by the item's saved Rotation (HardpointData.Rotation), not by hardpoint declaration order. +public sealed partial class RunStartTests +{ + // Two disjoint ballistic hardpoints, A (None, cell (6,5)) and B (Reversed, cell (5,5)). The edge gun's single cell is + // (1,0): origin (5,5) puts it at (6,5) unturned and at (5,5) turned 180 degrees, so both hardpoints take it there. + private (HullData hull, HardpointData a, HardpointData b) TwinMountHull(string name) + { + var a = Mount(HardpointType.Ballistic, 6, 5, rotation: ItemRotation.None); + var b = Mount(HardpointType.Ballistic, 5, 5, rotation: ItemRotation.Reversed); + return (ScratchHull(name, 12, a, b), a, b); + } + + [Fact] + public void AnOriginTwoHardpointsAcceptReloadsIntoTheHardpointItHeld() + { + var (hull, _, b) = TwinMountHull("Origin Twin Mounts"); + var filler = ScratchGear("Origin Filler", HardpointType.Ballistic, 1, 1); + var edge = ScratchGear("Origin Edge Gun", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + Assert.True(entity.TryEquip(Instance(filler), int2(6, 5))); + Assert.True(entity.TryEquip(Instance(edge), int2(5, 5))); + var held = entity.Equipment.Single(i => i.Data == edge); + Assert.Same(b, held.Hardpoint); + Assert.Equal(ItemRotation.Reversed, held.EquippableItem.Rotation); + // Un-equip the filler as a player would, then save and reload. + entity.TryUnequip(entity.Equipment.Single(i => i.Data == filler)); + + var reloaded = EntitySerializer.Unpack(_items, null, EntitySerializer.Pack(entity)); + var after = reloaded.Equipment.Single(i => i.Data == edge); + Assert.Equal(1, reloaded.HullData.Hardpoints.IndexOf(after.Hardpoint)); + } + + [Fact] + public void ReloadKeepsTheFirstHardpointToo() + { + var (hull, _, _) = TwinMountHull("Origin Twin Mounts First"); + var edge = ScratchGear("Origin Edge Gun First", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + Assert.True(entity.TryEquip(Instance(edge), int2(5, 5))); + Assert.Equal(ItemRotation.None, entity.Equipment.Single(i => i.Data == edge).EquippableItem.Rotation); + + var reloaded = EntitySerializer.Unpack(_items, null, EntitySerializer.Pack(entity)); + var after = reloaded.Equipment.Single(i => i.Data == edge); + Assert.Equal(0, reloaded.HullData.Hardpoints.IndexOf(after.Hardpoint)); + } + + [Fact] + public void AnItemWhoseRotationNamesNoAcceptingHardpointStillSeats() + { + var (hull, a, _) = TwinMountHull("Origin Twin Mounts Stray"); + var edge = ScratchGear("Origin Edge Gun Stray", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + var item = Instance(edge); + item.Rotation = ItemRotation.Clockwise; + Assert.True(entity.ItemFits(item, int2(5, 5))); + Assert.True(entity.TryEquip(item, int2(5, 5))); + var held = entity.Equipment.Single(i => i.Data == edge); + Assert.Same(a, held.Hardpoint); + Assert.Equal(ItemRotation.None, held.EquippableItem.Rotation); + } + + // A probe reports; only TryEquip seats. The probe used to turn the item to the hardpoint it found, so the same item + // probed twice could resolve differently, and a failed or merely previewed placement left it turned. + [Fact] + public void AProbeLeavesTheItemsRotationAlone() + { + var (hull, a, b) = TwinMountHull("Origin Twin Mounts Probe"); + var edge = ScratchGear("Origin Edge Gun Probe", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + var item = Instance(edge); + item.Rotation = ItemRotation.Clockwise; + + Assert.True(entity.ItemFits(item, int2(5, 5))); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + Assert.True(entity.ItemFits(item, int2(5, 5), out var seated)); + Assert.Equal(ItemRotation.None, seated); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + Assert.True(entity.TryFindSpace(item, out _)); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + Assert.False(entity.ItemFits(item, int2(0, 0), out var unseated)); + Assert.Equal(ItemRotation.Clockwise, unseated); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + + Assert.True(entity.TryEquip(item, int2(5, 5))); + var held = entity.Equipment.Single(i => i.Data == edge); + Assert.Same(a, held.Hardpoint); + Assert.Equal(ItemRotation.None, held.EquippableItem.Rotation); + + var reversed = Instance(edge); + reversed.Rotation = ItemRotation.Reversed; + var fresh = BareHull(hull); + Assert.True(fresh.ItemFits(reversed, int2(5, 5), out var first)); + Assert.True(fresh.ItemFits(reversed, int2(5, 5), out var second)); + Assert.Equal(ItemRotation.Reversed, first); + Assert.Equal(first, second); + Assert.Equal(b.Rotation, first); + } + + // A deployed entity takes no gear, so no probe reports a fit or a seat on one (the out overload's own guard). + // Kills: a probe that ignores the deployed state and offers a placement TryEquip would then refuse. + [Fact] + public void ADeployedEntityTakesNoProbe() + { + var (hull, _, _) = TwinMountHull("Origin Twin Mounts Deployed"); + var edge = ScratchGear("Origin Edge Gun Deployed", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + var item = Instance(edge); + item.Rotation = ItemRotation.Clockwise; + Assert.True(entity.ItemFits(item, int2(5, 5), out _)); + + var zone = Arena(false); + entity.Zone = zone; + zone.Admit(entity, piloted: false); + Assert.False(entity.ItemFits(item, int2(5, 5), out var seated)); + Assert.Equal(ItemRotation.Clockwise, seated); + Assert.False(entity.ItemFits(item, int2(5, 5))); + Assert.False(entity.TryEquip(item, int2(5, 5))); + } +} + +// The shipped catalog authors no origin that two differently turned hardpoints of one type both take. The fit rule alone +// over-approximates what Entity.HardpointAt sees (occupancy only removes candidates), so zero here is stricter than needed. +public sealed class ShippedHardpointOriginTests +{ + [Fact] + public void TheShippedCatalogHasNoAmbiguousOrigin() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var designs = cache.GetAll().Where(d => !(d is HullData) && d.HardpointType != HardpointType.Tool).ToArray(); + var ambiguous = new List(); + var pairs = 0; + var probes = 0; + foreach (var hull in cache.GetAll()) + for (var i = 0; i < hull.Hardpoints.Count; i++) + for (var j = i + 1; j < hull.Hardpoints.Count; j++) + { + var a = hull.Hardpoints[i]; + var b = hull.Hardpoints[j]; + if (a.Type != b.Type || a.Rotation == b.Rotation) continue; + pairs++; + foreach (var design in designs.Where(d => d.HardpointType == a.Type)) + for (var x = -20; x < hull.Shape.Width; x++) + for (var y = -20; y < hull.Shape.Height; y++) + { + var origin = int2(x, y); + probes++; + if (a.TakesAt(design, origin - a.Position) && b.TakesAt(design, origin - b.Position)) + ambiguous.Add($"{hull.Name} {design.Name} at ({x},{y}): hardpoints {i} and {j}"); + } + } + System.Console.WriteLine($"ShippedHardpointOriginTests visited {pairs} same-type different-rotation pairs"); + // A scan that visits nothing would pass; the catalog has such pairs today, so losing them must fail loudly. + Assert.True(pairs > 0 && probes > 0, $"the scan visited {pairs} pairs and {probes} origins"); + Assert.True(ambiguous.Count == 0, $"{ambiguous.Count} ambiguous origins: " + string.Join("; ", ambiguous.Take(10))); + } +} diff --git a/tests/Aetheria.Shared.Tests/HaulFeedTests.cs b/tests/Aetheria.Shared.Tests/HaulFeedTests.cs index 34eb8a3db..531f6a109 100644 --- a/tests/Aetheria.Shared.Tests/HaulFeedTests.cs +++ b/tests/Aetheria.Shared.Tests/HaulFeedTests.cs @@ -53,7 +53,6 @@ public sealed class HaulFeedTests : IDisposable Assert.Equal((GainKind.Mined, 4, 0), (gain.Kind, gain.Stored, gain.Adrift)); Assert.Same(rig.Shooter, gain.Taker); Assert.Equal(4, MiningCut5aTests.Units(bay, "Rock", rig.Scene)); - Assert.NotEqual(0, gain.Lot); // A full hold: everything floats. var (full, fullBay, fullGains) = Mining(1, 1, (MiningCut5aTests.Commodity("Grit", maxStack: 1), 1f)); @@ -99,11 +98,10 @@ public sealed class HaulFeedTests : IDisposable var chunk = rig.Rock; FireControl.Extract(rig.Zone, chunk, rig.Zone.Wear(chunk, 1e6f), rig.Shooter, Dice(rig, 1)); var keys = bay.Cargo.Keys.ToArray(); - // Same rock field and index, same ore, so the same lot: the second extraction merges and writes no Cargo key. + // Same rock field and index, same ore, so the same design: the second extraction merges and writes no Cargo key. FireControl.Extract(rig.Zone, chunk, 40f, rig.Shooter, Dice(rig, 2)); Assert.Equal(keys, bay.Cargo.Keys.ToArray()); Assert.Equal(2, gains.Count); - Assert.Equal(gains[0].Lot, gains[1].Lot); Assert.True(gains[1].Stored > 0); } @@ -114,7 +112,7 @@ public sealed class HaulFeedTests : IDisposable rig.Zone.Settings.AsteroidYield = new ExponentialLerp { Minimum = 400f, Maximum = 400f, Exponent = 1f }; FireControl.Extract(rig.Zone, rig.Rock, rig.Zone.Wear(rig.Rock, 1e6f), rig.Shooter, Dice(rig, 3)); Assert.Equal(2, gains.Count); - Assert.Equal(2, gains.Select(g => g.Lot).Distinct().Count()); + Assert.Equal(2, gains.Select(g => g.Design.Key).Distinct().Count()); Assert.All(gains, g => Assert.True(g.Stored + g.Adrift > 0)); } @@ -152,9 +150,9 @@ public sealed class HaulFeedTests : IDisposable rig.Zone.Admit(taker, piloted: false); var bay = MiningCut5aTests.Bay(rig.Scene, taker, 2, 1, "Taker"); var design = rig.Scene.Cache.RefOf(grit); - Assert.True(bay.TryStore(new SimpleCommodity { Data = design, Lot = 7, Quantity = 3 })); + Assert.True(bay.TryStore(new SimpleCommodity { Data = design, Quantity = 3 })); gains.Clear(); - var floating = rig.Zone.Release(new SimpleCommodity { Data = design, Lot = 7, Quantity = 4 }, new float2(0, 0), new float2(0, 0)); + var floating = rig.Zone.Release(new SimpleCommodity { Data = design, Quantity = 4 }, new float2(0, 0), new float2(0, 0)); Assert.True(rig.Zone.TryPickUp(taker, floating.Id)); Assert.Equal(7, MiningCut5aTests.Units(bay, "Grit", rig.Scene)); Assert.Equal((GainKind.Collected, 4, 0), (Assert.Single(gains).Kind, gains[0].Stored, gains[0].Adrift)); diff --git a/tests/Aetheria.Shared.Tests/HaulRunTests.cs b/tests/Aetheria.Shared.Tests/HaulRunTests.cs new file mode 100644 index 000000000..36c67e85a --- /dev/null +++ b/tests/Aetheria.Shared.Tests/HaulRunTests.cs @@ -0,0 +1,263 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using UniRx; +using Xunit; +using float2 = CultMath.float2; + +// The demo's ore haul (aetheria-living-world, cut ore-haul-run; rulings transit-depots-buy-for-onward-haul, demo-zenith-ore-depot, +// no-market-absorption, comms-cells-are-zones, docking-is-enclosed-bays): a depot buys only into its silo, and a real hauler ship +// carries the silo's ore to the refinery under the standing haul order. +public sealed partial class RunStartTests +{ + // Finding zenith-keeps-buying-past-its-silo: with the silo full, a sale of order ore sells nothing and the stock bay does not + // take it; the refinery still takes drawn ore into its one bay. + [Fact] + public void ZenithBuysOnlyIntoItsSilo() + { + var (_, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var zenith = StationOfKind(arena, "trade-hub"); + var refinery = StationOfKind(arena, "processing"); + var player = staged.Player; + var silo = zenith.CargoBays.Single(bay => bay.Data is SiloData); + var stock = zenith.CargoBays.Single(bay => !(bay.Data is SiloData)); + var good = StationWants.Of(zenith).OrderBy(key => key.Value, StringComparer.Ordinal).First(); + Assert.Equal(new[] { silo }, StationWants.Bays(zenith, good)); + Assert.Empty(StationWants.Bays(zenith, new CultRecordKey("commodity:not-wanted"))); + + while (silo.TryStore(new SimpleCommodity { Data = new CultRecordRef(good), Quantity = 10 })) { } + var before = stock.Cargo.Select(held => (held.Key, held.Value)).ToArray(); + var hold = player.CargoBays[0]; + var offered = new SimpleCommodity { Data = new CultRecordRef(good), Quantity = 5 }; + Assert.True(hold.TryStore(offered)); + var credits = 0; + var sale = StationServices.TrySellPart(hold, zenith, offered, ref credits); + Assert.Equal((0, 5, SaleRefusal.NoRoom), (sale.Sold, sale.Offered, sale.Refusal)); + Assert.Equal(0, credits); + Assert.Equal(5, hold.Count(good)); + Assert.Equal(before, stock.Cargo.Select(held => (held.Key, held.Value)).ToArray()); + Assert.Equal(0, stock.Count(good)); + + var drawn = StationWants.Of(refinery).First(key => FieldKinds.IsOre(_cache, _cache.Get(new CultRecordRef(key)))); + Assert.Equal(refinery.CargoBays, StationWants.Bays(refinery, drawn)); + var ore = new SimpleCommodity { Data = new CultRecordRef(drawn), Quantity = 5 }; + Assert.True(hold.TryStore(ore)); + var taken = StationServices.TrySellPart(hold, refinery, ore, ref credits); + Assert.Equal((5, SaleRefusal.None), (taken.Sold, taken.Refusal)); + Assert.True(credits > 0); + } + + private sealed class HaulWorld + { + public Zone Arena; + public OrbitalEntity Zenith, Refinery; + public Ship Player, Hauler; + public EquippedCargoBay Silo; + public HaulOrderData Order; + public CultRecordKey Good; + public RunStart.Staged Started; + } + + // The demo entrance on a seed, with `silo` units of the order's ore sold into Zenith's silo. + private HaulWorld HaulStage(uint seed = 1, int silo = 40) + { + var (_, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => seed)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var world = new HaulWorld + { + Arena = arena, Started = staged, Player = staged.Player, + Zenith = StationOfKind(arena, "trade-hub"), Refinery = StationOfKind(arena, "processing"), + Order = Assert.Single(_cache.GetAll()) + }; + world.Hauler = Assert.Single(arena.Entities.OfType(), ship => ship.Haul.Key.IsSet()); + world.Silo = world.Zenith.CargoBays.Single(bay => bay.Data is SiloData); + world.Good = world.Order.Goods.Select(good => good.Key).OrderBy(key => key.Value, StringComparer.Ordinal).First(); + for (var left = silo; left > 0; left -= 10) + Assert.True(world.Silo.TryStore(new SimpleCommodity { Data = new CultRecordRef(world.Good), Quantity = Math.Min(10, left) })); + return world; + } + + private static int Units(IEnumerable bays, CultRecordKey good) => bays.Sum(bay => bay.Count(good)); + + private static void Fly(Zone arena, float seconds, Action each = null) + { + for (var elapsed = 0f; elapsed < seconds; elapsed += .02f) + { + arena.Update(.02f); + each?.Invoke(); + } + } + + private static void Emptied(Ship ship) + { + foreach (var bay in ship.CargoBays) + foreach (var stack in bay.Cargo.Keys.ToArray()) + bay.Remove(stack); + } + + // The hauler's own pilot: the agent that flies it now (a dock call gives it a fresh one). + private static Agent PilotOf(Zone arena, Ship ship) => arena.Agents.Single(agent => ReferenceEquals(agent.Ship, ship)); + + // A real hauler carries Zenith's silo ore to the refinery under the standing order, docking to load and to unload; units of the + // order's good are never minted (the refinery's facility only takes them), the silo falls and the refinery's bays gain. + [Fact] + public void AHaulerCarriesSiloOreToTheRefinery() + { + var world = HaulStage(); + var dockings = 0; + world.Hauler.Docked.Subscribe(_ => dockings++); + var start = Units(world.Zenith.CargoBays, world.Good) + Units(world.Refinery.CargoBays, world.Good); + var refineryAtStart = Units(world.Refinery.CargoBays, world.Good); + var refineryPeak = refineryAtStart; + var stepped = 0; + Fly(world.Arena, 240, () => + { + var held = Units(world.Zenith.CargoBays, world.Good) + Units(world.Hauler.CargoBays, world.Good) + Units(world.Refinery.CargoBays, world.Good); + Assert.True(held <= start, $"step {stepped}: {held} units of the good, {start} at the start: a unit was minted"); + refineryPeak = Math.Max(refineryPeak, Units(world.Refinery.CargoBays, world.Good)); + stepped++; + }); + Assert.True(Units(new[] { world.Silo }, world.Good) < 40, "the silo gave up ore"); + Assert.True(refineryPeak > refineryAtStart, "the refinery's bays took delivered ore"); + Assert.True(dockings >= 2, $"the hauler docked {dockings} times: once to load and once to unload at least"); + Assert.Contains(world.Hauler, world.Arena.Entities); + Assert.IsType(PilotOf(world.Arena, world.Hauler).Task); + } + + // No field stores the leg: the order key is the task's only state, and the leg follows the hold as it is now. + [Fact] + public void TheLegIsTheHold() + { + var flags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly; + Assert.Equal(new[] { "Order" }, typeof(HaulingTask).GetFields(flags).Select(field => field.Name)); + var world = HaulStage(silo: 0); + var hold = world.Hauler.CargoBays[0]; + Assert.Equal(world.Order.From.Key, HaulRun.Leg(world.Hauler, world.Order)); + Assert.True(hold.TryStore(new SimpleCommodity { Data = new CultRecordRef(world.Good), Quantity = 5 })); + Assert.Equal(world.Order.To.Key, HaulRun.Leg(world.Hauler, world.Order)); + + // Steering follows it: from midway, a loaded hauler closes on the refinery and the same hauler with its hold hand-emptied turns for Zenith. + float2 Toward(OrbitalEntity station) => CultMath.math.normalize(world.Arena.GetOrbitPosition(station.OrbitData) - world.Hauler.Position.xz); + void Midway() + { + var between = (world.Arena.GetOrbitPosition(world.Zenith.OrbitData) + world.Arena.GetOrbitPosition(world.Refinery.OrbitData)) * .5f; + world.Hauler.Position = new CultMath.float3(between.x, world.Hauler.Position.y, between.y); + world.Hauler.Velocity = float2.zero; + } + Midway(); + Fly(world.Arena, 3); + Assert.True(CultMath.math.dot(CultMath.math.normalize(world.Hauler.Velocity), Toward(world.Refinery)) > .5f, "a loaded hauler heads for the refinery"); + Emptied(world.Hauler); + Midway(); + Fly(world.Arena, 3); + Assert.True(CultMath.math.dot(CultMath.math.normalize(world.Hauler.Velocity), Toward(world.Zenith)) > .5f, "an emptied hauler heads for Zenith"); + } + + // A hauler docks only when the call would move a unit: with the silo empty it never docks and keeps its pilot; with the refinery's + // bays full of something else, a loaded hauler keeps its cargo. + [Fact] + public void AHaulerDocksOnlyToMoveSomething() + { + var world = HaulStage(silo: 0); + var dockings = 0; + world.Hauler.Docked.Subscribe(_ => dockings++); + var pilot = PilotOf(world.Arena, world.Hauler); + Fly(world.Arena, 60); + Assert.Equal(0, dockings); + Assert.Same(pilot, PilotOf(world.Arena, world.Hauler)); + + var wants = StationWants.Of(world.Refinery); + var filler = _cache.GetAll().First(data => !wants.Contains(_cache.RefOf(data).Key)); + foreach (var bay in world.Refinery.CargoBays) + while (bay.TryStore(new SimpleCommodity { Data = new CultRecordRef(_cache.RefOf(filler).Key), Quantity = 1 })) { } + Assert.Equal(0, Units(world.Refinery.CargoBays, world.Good)); + Assert.True(world.Hauler.CargoBays[0].TryStore(new SimpleCommodity { Data = new CultRecordRef(world.Good), Quantity = 5 })); + Fly(world.Arena, 60); + Assert.Equal(0, dockings); + Assert.Equal(5, Units(world.Hauler.CargoBays, world.Good)); + Assert.Equal(0, Units(world.Refinery.CargoBays, world.Good)); + } + + // Delivery moves units and pays nobody: what the refinery gains is what the hauler loses, and a call that loads moves what the silo gives. + [Fact] + public void DeliveryPaysNobody() + { + var world = HaulStage(silo: 20); + Emptied(world.Hauler); + var credits = world.Started.Credits; + HaulRun.Call(world.Hauler, world.Zenith); + var carried = Units(world.Hauler.CargoBays, world.Good); + Assert.True(carried > 0, "the call at the From station loaded the hauler"); + Assert.Equal(20 - carried, Units(new[] { world.Silo }, world.Good)); + Assert.Contains(world.Hauler, world.Arena.Entities); + + var before = Units(world.Refinery.CargoBays, world.Good); + HaulRun.Call(world.Hauler, world.Refinery); + var delivered = Units(world.Refinery.CargoBays, world.Good) - before; + Assert.True(delivered > 0); + Assert.Equal(carried - delivered, Units(world.Hauler.CargoBays, world.Good)); + Assert.Equal(credits, world.Started.Credits); + } + + // Kill the loaded hauler: its stacks float, the stations are untouched, and nothing replaces it. + [Fact] + public void ALostHaulerLosesItsCargo() + { + var world = HaulStage(silo: 0); + Assert.True(world.Hauler.CargoBays[0].TryStore(new SimpleCommodity { Data = new CultRecordRef(world.Good), Quantity = 7 })); + var refinery = Units(world.Refinery.CargoBays, world.Good); + world.Hauler.HeatstrokeDeath.OnNext(UniRx.Unit.Default); + Assert.DoesNotContain(world.Hauler, world.Arena.Entities); + Assert.Equal(7, world.Arena.FloatingItems.Where(floating => floating.Item is SimpleCommodity stack && stack.Data.Key.Equals(world.Good)).Sum(floating => ((SimpleCommodity) floating.Item).Quantity)); + Assert.Equal(0, Units(new[] { world.Silo }, world.Good)); + Assert.Equal(refinery, Units(world.Refinery.CargoBays, world.Good)); + Fly(world.Arena, 30); + Assert.DoesNotContain(world.Arena.Entities.OfType(), ship => ship.Haul.Key.IsSet()); + } + + // The order rides the pack: a restored ship carries it and gets the haul task at admission; a ship with no order patrols. + [Fact] + public void TheHaulSurvivesThePack() + { + var world = HaulStage(silo: 0); + var pack = EntitySerializer.Pack(world.Hauler); + Assert.Equal(HaulOrderData.KeyOf("demo-terminus-ore"), pack.Haul.Key); + world.Hauler.HeatstrokeDeath.OnNext(UniRx.Unit.Default); + var restored = (Ship) EntitySerializer.Unpack(_items, world.Arena, pack); + Assert.Equal(pack.Haul.Key, restored.Haul.Key); + world.Arena.Admit(restored, piloted: true); + Assert.IsType(PilotOf(world.Arena, restored).Task); + + restored.Haul = default; + var plain = (Ship) EntitySerializer.Unpack(_items, world.Arena, EntitySerializer.Pack(restored)); + Assert.Null(HaulRun.TaskOf(plain)); + world.Arena.Admit(plain, piloted: true); + Assert.IsType(PilotOf(world.Arena, plain).Task); + } + + // A grudge on the hauler moves it off its leg; when the track is gone its task is the same HaulingTask object, and it flies on. + [Fact] + public void AHaulerFightsAndResumes() + { + var world = HaulStage(silo: 0); + var pilot = PilotOf(world.Arena, world.Hauler); + var task = pilot.Task; + Assert.IsType(task); + world.Player.Position = new CultMath.float3(world.Hauler.Position.x + 60, world.Hauler.Position.y, world.Hauler.Position.z); + world.Hauler.EntityInfoGathered[world.Player] = (_items.GameplaySettings.TargetDetectionInfoThreshold + 1f) / 2f; + world.Hauler.Provoke(world.Player); + var left = false; + Fly(world.Arena, 10, () => left |= !ReferenceEquals(pilot.Task, task) || pilot.View.TargetOf(world.Hauler) != null); + Assert.True(left, "the grudge moved the hauler off its haul task"); + world.Player.HeatstrokeDeath.OnNext(UniRx.Unit.Default); + Fly(world.Arena, 30); + Assert.Same(task, pilot.Task); + Assert.Null(pilot.View.TargetOf(world.Hauler)); + } +} diff --git a/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs b/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs index b2a01e356..2d44b8ebb 100644 --- a/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs +++ b/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs @@ -444,4 +444,112 @@ public sealed class IffAndCombatTests : IDisposable Assert.Empty(eligible); } + + // Two cached factions (Relations are read through the catalog's keys), with A regarding B as given when it is given, and a + // ship of each in the world's one ownerless zone. + private (Ship a, Ship b) Rivals(ItemManager items, Zone zone, FactionRelationship? aRegardsB) + { + var a = new Faction { Name = "A" }; + var b = new Faction { Name = "B" }; + items.ItemData.Upsert(a); + var bRef = items.ItemData.Upsert(b); + if (aRegardsB.HasValue) + { + a.Relations[bRef] = aRegardsB.Value; + items.ItemData.Upsert(a); + } + return (NewShip(items, zone, a), NewShip(items, zone, b)); + } + + // Hated is kill on sight in any zone, owned or not, once the claim is received with the track; it is directed, so B's stance + // toward A reads B's map. Kills: no Hated branch; reading the regarded side's map. + [Fact] + public void HatedIsKillOnSightInAnOwnerlessZone() + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, FactionRelationship.Hated); + + Assert.False(a.IsHostileTo(b)); // untracked: no claim to hate + + Detect(a, b); + Detect(b, a); + + Assert.True(a.IsHostileTo(b)); + Assert.True(a.EntityHostility[b]); + Assert.False(b.IsHostileTo(a)); + Assert.False(b.EntityHostility[a]); + } + + // The ladder below Hated governs presence in owned space, not fire. Kills: treating Hostile or worse as kill on sight. + [Theory] + [InlineData(FactionRelationship.Hostile)] + [InlineData(FactionRelationship.Neutral)] + [InlineData(FactionRelationship.Beloved)] + public void ARelationShortOfHatedIsNotKillOnSight(FactionRelationship relationship) + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, relationship); + + Detect(a, b); + Detect(b, a); + + Assert.False(a.IsHostileTo(b)); + Assert.False(b.IsHostileTo(a)); + } + + // An IFF override is the observer's own word and outranks what its faction holds. Kills: the relation branch placed before the override. + [Fact] + public void AnOverrideOutranksARelation() + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, FactionRelationship.Hated); + Detect(a, b); + Assert.True(a.IsHostileTo(b)); + + a.SetIff(b, false); + + Assert.False(a.IsHostileTo(b)); + Assert.False(a.EntityHostility[b]); + } + + // A faction the catalog does not hold has no key, so it is regarded Neutral and nothing throws. Kills: RefOf in the lookup. + [Fact] + public void AFactionOutsideTheCacheIsRegardedNeutral() + { + var (items, zone) = BuildWorld(); + var a = new Faction { Name = "A" }; + items.ItemData.Upsert(a); + a.Relations[items.ItemData.Upsert(new Faction { Name = "Elsewhere" })] = FactionRelationship.Hated; + items.ItemData.Upsert(a); + var ship = NewShip(items, zone, a); + var stranger = NewShip(items, zone, new Faction { Name = "Stranger" }); + + Detect(ship, stranger); + + Assert.False(ship.IsHostileTo(stranger)); + } + + // Stance follows the faction the contact claimed when it was tracked, not the faction it flies now. Kills: reading other.Faction + // instead of the telemetry claim. + [Fact] + public void StanceFollowsTheClaimNotTheLiveFaction() + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, FactionRelationship.Hated); + var other = new Faction { Name = "C" }; + items.ItemData.Upsert(other); + var neutral = NewShip(items, zone, other); + + Detect(a, b); + Detect(a, neutral); + Assert.True(a.IsHostileTo(b)); + Assert.False(a.IsHostileTo(neutral)); + + var hated = b.Faction; + b.Faction = other; // each keeps what it claimed when tracked, until it is claimed again + neutral.Faction = hated; + + Assert.True(a.IsHostileTo(b)); + Assert.False(a.IsHostileTo(neutral)); + } } diff --git a/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs b/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs index 8dbc47873..cc87e061c 100644 --- a/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs @@ -19,6 +19,7 @@ public sealed class InspectionScannerCommandTests : IDisposable // The design and products as the shipped catalog holds them, taken before they are removed from the scratch copy. private readonly byte[] _shippedDesign; + private readonly int _shippedPrice; private readonly string[] _shippedProducts; private static byte[] Pack(GearData design) => @@ -39,6 +40,7 @@ public sealed class InspectionScannerCommandTests : IDisposable cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes); var design = Assert.Single(cache.GetAll(), g => g.Name == DesignName); _shippedDesign = Pack(design); + _shippedPrice = design.Price; var key = cache.RefOf(design).Key; var products = cache.GetAll().Where(p => p.Design.Key.Equals(key)).ToArray(); _shippedProducts = products.Select(p => Describe(cache, p)).OrderBy(x => x, StringComparer.Ordinal).ToArray(); @@ -52,7 +54,7 @@ public sealed class InspectionScannerCommandTests : IDisposable private (GearData[] Designs, string[] Products) Read() { - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); try { var designs = db.Cache.GetAll().Where(g => g.Name == DesignName).ToArray(); @@ -88,7 +90,11 @@ public sealed class InspectionScannerCommandTests : IDisposable Assert.NotEqual(before, landed); var (designs, products) = Read(); // The record keys are CultCache's to mint and differ run to run; the design and products do not. - Assert.True(_shippedDesign.AsSpan().SequenceEqual(Pack(Assert.Single(designs))), "the design differs from the shipped catalog's record"); + // The command authors at its own literal price, a hundred times the shipped (GearPrices); everything else is the shipped record. + var landedDesign = Assert.Single(designs); + Assert.Equal(_shippedPrice, GearPrices.Rescaled(landedDesign.Price)); + landedDesign.Price = _shippedPrice; + Assert.True(_shippedDesign.AsSpan().SequenceEqual(Pack(landedDesign)), "the design differs from the shipped catalog's record"); Assert.Equal(_shippedProducts, products); // A second apply finds everything authored and writes nothing; so does a dry run. diff --git a/tests/Aetheria.Shared.Tests/ItemTitleTests.cs b/tests/Aetheria.Shared.Tests/ItemTitleTests.cs index b2b083b41..dd381472d 100644 --- a/tests/Aetheria.Shared.Tests/ItemTitleTests.cs +++ b/tests/Aetheria.Shared.Tests/ItemTitleTests.cs @@ -110,12 +110,6 @@ public sealed class ItemTitleTests : IDisposable var given = _items.CreateInstance(_items.CreateLot(_array, default, .5f)); Assert.Equal("Array", _items.Title(given)); - var extractedLot = _items.Lots.Add(new Lot - { - Design = _cache.RefOf(_array), Origin = new Extracted(), Quality = .5f, Roles = new List() - }); - Assert.Equal("Array", _items.Title(_items.CreateInstance(extractedLot))); - var ore = new SimpleCommodity { Data = _cache.RefOf(_cache.GetByName("Ore")), Quantity = 3 }; Assert.Equal("Ore", _items.Title(ore)); } diff --git a/tests/Aetheria.Shared.Tests/LaunchSuppressorCatalogTests.cs b/tests/Aetheria.Shared.Tests/LaunchSuppressorCatalogTests.cs index 7a1481670..8e1392359 100644 --- a/tests/Aetheria.Shared.Tests/LaunchSuppressorCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/LaunchSuppressorCatalogTests.cs @@ -42,8 +42,8 @@ public sealed class LaunchSuppressorCatalogTests var computer = Design(cache, "Targeting Computer"); var designs = new[] { - (Design: Design(cache, StrongName), Price: 40000, Factor: (.08f, .03f), Heat: (1.4f, .8f), Rated: (310f, 330f)), - (Design: Design(cache, MildName), Price: 25000, Factor: (.4f, .2f), Heat: (.8f, .5f), Rated: (310f, 330f)), + (Design: Design(cache, StrongName), Price: 400, Factor: (.08f, .03f), Heat: (1.4f, .8f), Rated: (310f, 330f)), + (Design: Design(cache, MildName), Price: 250, Factor: (.4f, .2f), Heat: (.8f, .5f), Rated: (310f, 330f)), }; foreach (var (design, price, factor, heat, rated) in designs) { diff --git a/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs b/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs index 47cc9a29e..2f7d41863 100644 --- a/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs @@ -18,7 +18,7 @@ public sealed class LaunchSuppressorCommandTests : IDisposable private string CatalogPath => Path.Combine(_root, "GameData", "Aetheria.cc"); // The designs and products as the shipped catalog holds them, taken before they are removed from the scratch copy. - private readonly (string Name, byte[] Bytes)[] _shippedDesigns; + private readonly (string Name, int Price, byte[] Bytes)[] _shippedDesigns; private readonly string[] _shippedProducts; private static byte[] Pack(GearData design) => @@ -39,7 +39,7 @@ public sealed class LaunchSuppressorCommandTests : IDisposable cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes); var designs = cache.GetAll().Where(g => DesignNames.Contains(g.Name)).ToArray(); Assert.Equal(DesignNames.Length, designs.Length); - _shippedDesigns = designs.Select(d => (d.Name, Pack(d))).ToArray(); + _shippedDesigns = designs.Select(d => (d.Name, d.Price, Pack(d))).ToArray(); var keys = designs.Select(d => cache.RefOf(d).Key).ToArray(); var products = cache.GetAll().Where(p => keys.Any(k => p.Design.Key.Equals(k))).ToArray(); _shippedProducts = products.Select(p => Describe(cache, p)).OrderBy(x => x, StringComparer.Ordinal).ToArray(); @@ -53,7 +53,7 @@ public sealed class LaunchSuppressorCommandTests : IDisposable private (GearData[] Designs, string[] Products) Read() { - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); try { var designs = db.Cache.GetAll().Where(g => DesignNames.Contains(g.Name)).ToArray(); @@ -89,8 +89,14 @@ public sealed class LaunchSuppressorCommandTests : IDisposable Assert.NotEqual(before, landed); var (designs, products) = Read(); // The record keys are CultCache's to mint and differ run to run; the designs and products do not. - foreach (var (name, bytes) in _shippedDesigns) - Assert.True(bytes.AsSpan().SequenceEqual(Pack(designs.Single(d => d.Name == name))), $"{name} differs from the shipped catalog's record"); + // The command authors at its own literal price, a hundred times the shipped (GearPrices); everything else is the shipped record. + foreach (var (name, price, bytes) in _shippedDesigns) + { + var landedDesign = designs.Single(d => d.Name == name); + Assert.Equal(price, GearPrices.Rescaled(landedDesign.Price)); + landedDesign.Price = price; + Assert.True(bytes.AsSpan().SequenceEqual(Pack(landedDesign)), $"{name} differs from the shipped catalog's record"); + } Assert.Equal(_shippedProducts, products); // A second apply finds everything authored and writes nothing; so does a dry run. diff --git a/tests/Aetheria.Shared.Tests/LauncherAmmunitionCatalogTests.cs b/tests/Aetheria.Shared.Tests/LauncherAmmunitionCatalogTests.cs index 209a0caa9..f57a648b1 100644 --- a/tests/Aetheria.Shared.Tests/LauncherAmmunitionCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/LauncherAmmunitionCatalogTests.cs @@ -13,7 +13,7 @@ public sealed class LauncherAmmunitionCatalogTests [Fact] public void EveryShippedLauncherReloadsFromMissilesAndMissilesCanBeMade() { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenShipped(); var missiles = db.Cache.GetAll().Single(c => c.Name == "Missiles"); var key = db.Cache.RefOf(missiles).Key; var launchers = db.Cache.GetAll().SelectMany(i => i.Behaviors.OfType().Where(IsLauncher).Select(d => (i.Name, d))).ToArray(); diff --git a/tests/Aetheria.Shared.Tests/LoadoutTests.cs b/tests/Aetheria.Shared.Tests/LoadoutTests.cs index 3697d7345..4a114637e 100644 --- a/tests/Aetheria.Shared.Tests/LoadoutTests.cs +++ b/tests/Aetheria.Shared.Tests/LoadoutTests.cs @@ -494,6 +494,7 @@ public sealed class LoadoutTests : IDisposable var game = new SavedGame { + InfluenceScale = 1, Factions = Array.Empty>(), Relationships = Array.Empty(), HomeZones = new Dictionary(), diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index 95dbacd1f..fdaeaceb6 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -320,9 +320,12 @@ public sealed partial class MiningCut3Tests : IDisposable // are trusted only on the host class that recorded them (ruling replays-per-host-class). windows-x64 is the recording the // test was written with; linux-x64 is base 12dfcef5 run on Linux, which gives 1039274088 where Windows gave 1039274086 for // the second observer, and the current code gives the same bits as that base. + // The windows-x64 value for the second observer was 1039274086 when recorded (2026-10-11) and reads 1039274088 now, the + // linux bits; at the recording commit c86f28e93, with its own CultLib and CultMath pins, today's Windows host also gives + // ...088, and so does the 10.0.6 runtime, so the change is the host (OS or CPU libm), not this repository. private static readonly System.Collections.Generic.Dictionary ChunkInfoAtBase = new() { - ["windows-x64"] = new uint[] { 1045120030u, 1039274086u, 1030543422u, 1029120970u, 1036363351u, 1035122917u }, + ["windows-x64"] = new uint[] { 1045120030u, 1039274088u, 1030543422u, 1029120970u, 1036363351u, 1035122917u }, ["linux-x64"] = new uint[] { 1045120030u, 1039274088u, 1030543422u, 1029120970u, 1036363351u, 1035122917u }, }; @@ -482,6 +485,29 @@ public sealed partial class MiningCut3Tests : IDisposable Assert.Contains(farther, offered); } + // Chunks of equal index are offered in the order of their belts' Sites, then keys: the minted key's text decides nothing + // when a Site exists. The Sites are set against the keys' ordinal order, so a key comparison would offer the other way. + [Fact] + public void ChunkTieBreakFollowsSiteNotKey() + { + var kind = Kind("Asteroid", 4f); + var s = BuildScene(new[] { kind }, Belt(kind, Rock(150f)), Belt(kind, Rock(150f))); + var byKey = s.Belts.OrderBy(key => key.Value, StringComparer.Ordinal).ToArray(); + s.Zone.AsteroidBelts[byKey[0]].Data.Site = "site-b"; + s.Zone.AsteroidBelts[byKey[1]].Data.Site = "site-a"; + var eyeAt = float2(150, -100); + var observer = SpawnShip(s, eyeAt, sensor: true, weaponRanges: new[] { 400f }); + Tick((observer, eyeAt)); + var offered = new List(); + observer.VisibleChunksInReach(offered); + Assert.Equal(new[] { new ChunkId(byKey[1], 0), new ChunkId(byKey[0], 0) }, offered); + + s.Zone.AsteroidBelts[byKey[0]].Data.Site = "site-a"; + s.Zone.AsteroidBelts[byKey[1]].Data.Site = "site-b"; + observer.VisibleChunksInReach(offered); + Assert.Equal(new[] { new ChunkId(byKey[0], 0), new ChunkId(byKey[1], 0) }, offered); + } + // The chunk query returns exactly the chunks within range, from inside the belt's hole, from within the // annulus and from outside it -- the belt skip never drops a chunk the brute-force answer would keep -- and it // leaves out a broken chunk. @@ -830,14 +856,14 @@ public sealed partial class MiningCut3Tests : IDisposable Galaxy galaxy; try { - galaxy = new Galaxy(RestoredHullsTests.TutorialGalaxySettings(), RestoredHullsTests.TutorialBackgroundSettings(), - cache, new PlayerSettings(), new DirectoryInfo(dir), _ => { }, null, seed); + galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, + cache, _ => { }, null, seed); } catch (Exception) { continue; } // Galaxy's own seed-dependent flakiness (RestoredHullsTests) var items = new ItemManager(1u, cache, new ProvenanceLedger(), GameSettings(), _ => { }); foreach (var zone in galaxy.Zones.Take(4)) { - var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance); + var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, entranceStations: EntranceStationOrder.Any); foreach (var body in pack.Planets) { if (!(cache.Get(body) is AsteroidBeltData belt)) continue; @@ -874,13 +900,13 @@ public sealed partial class MiningCut3Tests : IDisposable Galaxy galaxy; try { - galaxy = new Galaxy(RestoredHullsTests.TutorialGalaxySettings(), RestoredHullsTests.TutorialBackgroundSettings(), - cache, new PlayerSettings(), new DirectoryInfo(dir), _ => { }, null, seed); + galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, + cache, _ => { }, null, seed); } catch (Exception) { return null; } var items = new ItemManager(1u, cache, new ProvenanceLedger(), GameSettings(), _ => { }); return galaxy.Zones.Take(6).SelectMany(zone => - ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance) + ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, entranceStations: EntranceStationOrder.Any) .Planets.Select(body => cache.Get(body)).OfType().Select(belt => cache.Get(belt.Kind).Name)) .ToArray(); } diff --git a/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs index 04f02164d..301ae1f3b 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs @@ -209,10 +209,10 @@ public sealed class MiningCut5aTests : IDisposable } // Every rock broken once; the shooter is not in the zone, so everything floats and the floats are the record. - private static (int Rock, int Gold)[] Break(MiningCut3Tests.Scene scene, Zone zone, Ship ship, int rocks, uint seed) => + private static (int Rock, int Gold)[] Break(MiningCut3Tests.Scene scene, Zone zone, Ship ship, int rocks, uint seed, int belt = 0) => Enumerable.Range(0, rocks).Select(rock => { - var chunk = new ChunkId(scene.Belts[0], rock); + var chunk = new ChunkId(scene.Belts[belt], rock); var before = zone.FloatingItems.Select(f => f.Item).ToArray(); FireControl.Extract(zone, chunk, zone.Wear(chunk, 1e6f), ship, SimulationDice.For(seed, SimulationDice.OreStream, (uint) rock)); var added = zone.FloatingItems.Select(f => f.Item).Except(before).ToArray(); @@ -228,6 +228,31 @@ public sealed class MiningCut5aTests : IDisposable Assert.NotEqual(first, Break(scene, newZone(), ship, 20, 12)); } + // Ore reads the body's Site, not the key the cache minted for it: two belts of one scene (one set of commodities) wear the + // same ore under one seed when they share a Site, and with no Site (a save from before sites, or a hand-built belt) the key + // stands in and they differ. + [Fact] + public void TwoBeltsOfOneSiteGiveTheSameOre() + { + const int rocks = 20; + var kind = MiningCut3Tests.Kind("Asteroid", 4f); + MiningCut3Tests.BeltSpec Belt() => MiningCut3Tests.Belt(kind, + Enumerable.Range(0, rocks).Select(i => MiningCut3Tests.Rock(150f + i, i / (float) rocks, .5f)).ToArray()); + var scene = _scenes.BuildScene(new[] { kind }, Belt(), Belt()); + Stock(scene, kind, (Commodity("Rock"), 1f), (Commodity("Gold"), 1f)); + var settings = MiningCut3Tests.PlanetSettings(); + settings.ChunkCompositionVariance = 2f; + settings.AsteroidYield = new ExponentialLerp { Minimum = 40f, Maximum = 40f, Exponent = 1f }; + var ship = new Ship(scene.Items, scene.Zone, MiningCut3Tests.Mint(scene, scene.Hull), new EntitySettings()); + Zone NewZone() => new Zone(scene.Items, settings, scene.Pack, new GalaxyZone { Name = "MiningCut3", Owner = null }, null); + + Assert.NotEqual(Break(scene, NewZone(), ship, rocks, 11, belt: 0), Break(scene, NewZone(), ship, rocks, 11, belt: 1)); + + var zone = NewZone(); + foreach (var key in scene.Belts) zone.AsteroidBelts[key].Data.Site = "7:belt:3"; + Assert.Equal(Break(scene, zone, ship, rocks, 11, belt: 0), Break(scene, NewZone(), ship, rocks, 11, belt: 1)); + } + // Composition is derived from the rock's identity every call: variance 0 reads the kind's ratio, variance above 0 gives // rocks different mixes, and nothing stores it (a second zone of the pack reads the same mixes from the dice and keys). [Fact] diff --git a/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs b/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs index 374f9292e..e492b5835 100644 --- a/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs @@ -546,4 +546,130 @@ public sealed partial class MiningCut3Tests Assert.Equal(order[i % order.Count], observer.Target.Value); } } + + private static float2 Polar(float2 at, float distance, float angle) => at + distance * float2(cos(angle), sin(angle)); + + // Both presses, from nothing and from every target, visit `order` and wrap. + private static void AssertPressesWalk(Ship observer, List order) + { + observer.SetTarget(TargetRef.None); + for (var i = 0; i <= order.Count; i++) + { + Assert.True(observer.TargetNext()); + Assert.Equal(order[i % order.Count], observer.Target.Value); + } + observer.SetTarget(TargetRef.None); + for (var i = 0; i <= order.Count; i++) + { + Assert.True(observer.TargetPrevious()); + Assert.Equal(order[order.Count - 1 - i % order.Count], observer.Target.Value); + } + for (var i = 0; i < order.Count; i++) + { + observer.SetTarget(order[i]); + Assert.True(observer.TargetNext()); + Assert.Equal(order[(i + 1) % order.Count], observer.Target.Value); + observer.SetTarget(order[i]); + Assert.True(observer.TargetPrevious()); + Assert.Equal(order[(i + order.Count - 1) % order.Count], observer.Target.Value); + } + } + + // Ships keep their distance order for both presses at every range: the key is the distance itself past 1000 too, + // not a function that clamps or bends there. Ships stand on both sides of 1000, many thousand units out, each a + // distinct distance and admitted in an order unlike the distance order, so a key that ties or inverts any two + // falls back on zone order and shows. + [Fact] + public void ShipsPastAThousandUnitsAreOrderedByDistanceBothWays() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + var distances = new[] { 1800f, 700f, 2400f, 1200f, 400f, 4000f, 999f, 1500f, 1001f, 150f, 3100f, 1100f }; + for (var i = 0; i < distances.Length; i++) Sight(s, observer, Polar(at, distances[i], i * 1.9f)); + var order = ByDistance(s, observer, 120f); + Assert.True(order.Count(t => t.Chunk.HasValue) >= 8 && order.Count(t => t.Entity != null) == distances.Length, $"degenerate: {order.Count} candidates"); + var ships = order.Where(t => t.Entity != null).Select(t => length(t.Entity.Position.xz - at)).ToList(); + Assert.Equal(ships.OrderBy(d => d).ToList(), ships); + Assert.Equal(ships.Distinct().Count(), ships.Count); + AssertPressesWalk(observer, order); + } + + // The pilot's instruments bound the pick at every range: undetected ships stand from a few units out to well + // past the farthest seen one, on every bearing, among the seen ships, so a press that offers undetected ships + // within any window of distance (or only once the zone is crowded) offers one here. Every press walks the + // detected order, and the reticle aimed straight at each hidden ship still takes a detected target. + [Fact] + public void ShipsTheObserverHasNotDetectedAreNeverPickedAtAnyDistance() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + foreach (var (distance, i) in new[] { 60f, 300f, 800f, 1300f, 2000f }.Select((d, i) => (d, i))) Sight(s, observer, Polar(at, distance, i * 1.3f + .4f)); + var hidden = new List(); + for (var i = 0; i < 48; i++) + hidden.Add(Unseen(s, Polar(at, 2f * MathF.Pow(1.18f, i), i * 2.4f))); + var order = ByDistance(s, observer, 120f); + Assert.True(order.Count > 5 && order.Count(t => t.Entity != null) == 5, $"degenerate: {order.Count} candidates"); + Assert.All(hidden, h => Assert.DoesNotContain(h, order)); + var farthest = hidden.Max(h => length(h.Entity.Position.xz - at)); + Assert.True(farthest > 4000f && hidden.Count(h => length(h.Entity.Position.xz - at) is > 100f and < 2500f) > 10, "the hidden ships do not sweep the window"); + + AssertPressesWalk(observer, order); + foreach (var h in hidden) + { + var to = h.Entity.Position.xz - at; + observer.Aim = float3(to.x, 0, to.y); + observer.SetTarget(TargetRef.None); + Assert.True(observer.TargetUnderReticle()); + Assert.DoesNotContain(observer.Target.Value, hidden); + Assert.Contains(observer.Target.Value, order); + } + } + + // The distance key stays the distance far beyond the clamps a fixture reaching 4000 can see: ships stand out to + // 8000 units, several within any one quantum or round-number cap (4600 and 4900, 5200 and 5300, 7960, 7975 and 7990), + // and are admitted farthest first, so zone order is the exact reverse of distance order and any tie (a clamp, a + // coarse bucket, a cap on either key) shows as a swapped pair. + [Fact] + public void ShipsOutToEightThousandUnitsAreOrderedByDistanceBothWaysWhenAdmittedFarthestFirst() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + var distances = new[] { 7990f, 7975f, 7960f, 7900f, 7000f, 6100f, 5300f, 5200f, 4900f, 4600f, 4000f, 3600f, 3100f, 2900f, 1500f, 700f }; + for (var i = 0; i < distances.Length; i++) Sight(s, observer, Polar(at, distances[i], i * 1.9f)); + var order = ByDistance(s, observer, 120f); + Assert.True(order.Count(t => t.Chunk.HasValue) >= 8 && order.Count(t => t.Entity != null) == distances.Length, $"degenerate: {order.Count} candidates"); + var ships = order.Where(t => t.Entity != null).Select(t => length(t.Entity.Position.xz - at)).ToList(); + Assert.Equal(ships.OrderBy(d => d).ToList(), ships); + Assert.Equal(ships.Distinct().Count(), ships.Count); + Assert.True(ships.Last() > 7900f); + AssertPressesWalk(observer, order); + } + + // The same pins in a crowded zone: far more than 60 entities stand in it, ships the observer has not detected + // among them out to 8000 units, so a leak or a bent key gated on the zone's size shows here. + [Fact] + public void ShipsTheObserverHasNotDetectedAreNeverPickedInACrowdedZone() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + var seen = new[] { 6200f, 4700f, 2500f, 900f, 120f, 5400f }; + for (var i = 0; i < seen.Length; i++) Sight(s, observer, Polar(at, seen[i], i * 1.3f + .4f)); + var hidden = new List(); + for (var i = 0; i < 110; i++) + hidden.Add(Unseen(s, Polar(at, 3f * MathF.Pow(1.0885f, i), i * 2.4f))); + var order = ByDistance(s, observer, 120f); + Assert.True(s.Zone.Entities.Count > 100, $"zone holds {s.Zone.Entities.Count}"); + Assert.True(order.Count > seen.Length && order.Count(t => t.Entity != null) == seen.Length, $"degenerate: {order.Count} candidates"); + Assert.All(hidden, h => Assert.DoesNotContain(h, order)); + Assert.True(hidden.Max(h => length(h.Entity.Position.xz - at)) > 7500f, "the hidden ships do not reach the far window"); + AssertPressesWalk(observer, order); + foreach (var h in hidden.Where((_, i) => i % 3 == 0)) + { + var to = h.Entity.Position.xz - at; + observer.Aim = float3(to.x, 0, to.y); + observer.SetTarget(TargetRef.None); + Assert.True(observer.TargetUnderReticle()); + Assert.DoesNotContain(observer.Target.Value, hidden); + } + } } diff --git a/tests/Aetheria.Shared.Tests/MinorPowersTests.cs b/tests/Aetheria.Shared.Tests/MinorPowersTests.cs index 1988a033e..14d7622bc 100644 --- a/tests/Aetheria.Shared.Tests/MinorPowersTests.cs +++ b/tests/Aetheria.Shared.Tests/MinorPowersTests.cs @@ -38,6 +38,7 @@ public sealed class MinorPowersTests : IDisposable Assert.Equal(3, gone.Length); foreach (var product in cache.GetAll().Where(p => gone.Any(g => g.Key.Equals(p.Manufacturer.Key))).ToArray()) Assert.True(cache.Remove(cache.RefOf(product).Key)); + TestStationKinds.DropStandInsOf(cache, gone.Select(g => g.Key).ToArray()); foreach (var reference in gone) Assert.True(cache.Remove(reference.Key)); foreach (var faction in cache.GetAll()) foreach (var key in faction.Allegiance.Keys.Where(k => gone.Any(g => g.Key.Equals(k.Key))).ToArray()) @@ -80,7 +81,7 @@ public sealed class MinorPowersTests : IDisposable Assert.Equal(0, MinorPowerFactionsCommand.Run(new[] { "apply" }, _root)); var landed = File.ReadAllBytes(CatalogPath); Assert.NotEqual(before, landed); - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); try { var factions = db.Cache.GetAll().ToArray(); @@ -107,7 +108,7 @@ public sealed class MinorPowersTests : IDisposable public void ANameHeldUnderAnotherKeyIsRefusedWithNothingWritten() { StripTheMinorPowers(); - var squatter = AetherDb.Open(catalogWritable: true, root: _root); + var squatter = AetherDb.OpenShipped(catalogWritable: true, root: _root); squatter.Cache.Commit(batch => batch.Upsert(typeof(Faction), new Faction { Name = "Megiddo", ShortName = "Megiddo" })); squatter.Cache.Dispose(); var before = File.ReadAllBytes(CatalogPath); @@ -139,8 +140,9 @@ public sealed partial class RunStartTests Assert.Contains(Enumerable.Range(1, 64), seed => For("AU", unchecked((uint) seed * 2654435761u)).ChooseProduct(autocannon)?.Name == pattern30.Name); var terri = For("Miss Terri's", 1); - var theirs = _cache.GetAll().Where(p => new[] { "Aya", "Megiddo", "Forge" }.Contains(_cache.Get(p.Manufacturer).ShortName)).ToArray(); - Assert.Equal(10, theirs.Length); + var theirs = _cache.GetAll().Where(p => LoadoutGenerator.IsOffered(_cache, p) && new[] { "Aya", "Megiddo", "Forge" }.Contains(_cache.Get(p.Manufacturer).ShortName)).ToArray(); + // 10 until the shield projectors: Awning (Aya) and Migdal (Megiddo) join their makers' lines. + Assert.Equal(12, theirs.Length); Assert.All(theirs, product => Assert.False(terri.IsAvailable(product), product.Name)); } } diff --git a/tests/Aetheria.Shared.Tests/MunitionsBillsTests.cs b/tests/Aetheria.Shared.Tests/MunitionsBillsTests.cs new file mode 100644 index 000000000..a3bd6c027 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MunitionsBillsTests.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// The munitions chain's design bills (aetheria-living-world, cut design-bills-of-materials): tier role names, the four tier parts +// and the role recipes, owned by the MunitionsBills batch and not by Munitions. +public sealed class MunitionsBillsTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-bills-" + Guid.NewGuid().ToString("N")); + + public MunitionsBillsTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + private string ShippedCopy(string name) + { + var path = Path.Combine(_root, name); + File.Copy(TestCatalog.Repo, path, true); + return path; + } + + private static string[] Reach(CultCache catalog, ItemData item) + { + var seen = new HashSet(StringComparer.Ordinal); + void Walk(ItemData good) + { + var recipe = Recipes.RecipeOf(catalog, good); + if (recipe == null) return; + foreach (var input in recipe.Inputs) Visit(catalog.Get(input.Commodity)); + foreach (var role in Recipes.RoleInputsOf(catalog, recipe)) + foreach (var filler in Recipes.Fillers(catalog, role.Name)) Visit(catalog.Get(filler)); + } + void Visit(ItemData good) + { + if (good != null && seen.Add(catalog.RefOf(good).Key.Value)) Walk(good); + } + Walk(item); + return seen.OrderBy(k => k, StringComparer.Ordinal).ToArray(); + } + + // Kills: a bill that drops the rare inputs, or a starter whose chain reaches them. + [Fact] + public void TheTopBallisticBillReachesTheScarceMetalsAndTheStarterDoesNot() + { + using var cache = AetheriaStores.Open(TestCatalog.Repo, registry: TestCatalog.Registry()); + ItemData Gun(string name) => Assert.Single(cache.GetAll(), w => w.Name == name); + var scarce = new[] { "commodity:niobium", "commodity:rare-earth-oxides", "commodity:platinum-group-metals" }; + Assert.All(scarce, key => Assert.Contains(key, Reach(cache, Gun("Charged Scattergun")))); + Assert.All(scarce, key => Assert.DoesNotContain(key, Reach(cache, Gun("Light Machine Gun")))); + var guns = new[] { "Light Machine Gun", "Point Defense Gun", "Slug Rifle", "Long Slug Rifle", "Flak Gun", "Autocannon", "Cluster Cannon", "Charged Scattergun" }.Select(Gun).ToArray(); + Assert.Equal("Light Machine Gun", guns.OrderBy(g => g.Price).First().Name); + Assert.Equal("Charged Scattergun", guns.OrderBy(g => g.Price).Last().Name); + } + + // Kills: a rename that misses a stat term, a seller's profile or a bin, or one that does not converge. + [Fact] + public void RenamingARoleReachesEveryReaderAndConverges() + { + using var cache = AetheriaStores.Open(ShippedCopy("Rename.cc"), catalogWritable: true, registry: TestCatalog.Registry()); + var author = new EconomyAuthor(cache); + var rifle = Assert.Single(cache.GetAll(), w => w.Name == "Slug Rifle"); + var key = cache.RefOf(rifle).Key; + + IEnumerable TermRoles() => rifle.Behaviors.SelectMany(b => b.GetType().GetFields().Where(f => f.FieldType == typeof(PerformanceStat)) + .SelectMany(f => ((PerformanceStat) f.GetValue(b)).Terms.Where(t => t.Source == StatSource.Quality && !string.IsNullOrEmpty(t.Role)).Select(t => t.Role))); + var sellers = cache.GetAll().Where(p => p.Design.Key.Equals(key)).ToArray(); + Assert.Contains(sellers, p => p.Bin != null); + Assert.True(sellers.Count(p => p.Bin == null) >= 2); + Assert.Contains("rifled barrel", TermRoles()); + + MunitionsBills.RenameRole(author, "Slug Rifle", "rifled barrel", "barrel"); + Assert.DoesNotContain("rifled barrel", TermRoles()); + Assert.Contains("barrel", TermRoles()); + Assert.Contains("barrel", rifle.Roles.Select(r => r.Name)); + Assert.All(sellers.Where(p => p.Bin == null), p => Assert.Contains(p.Roles, r => r.Role == "barrel")); + Assert.All(sellers.Where(p => p.Bin != null), p => Assert.Empty(p.Roles)); + + MunitionsBills.RenameRole(author, "Slug Rifle", "rifled barrel", "barrel"); + MunitionsBills.RenameRole(author, "Slug Rifle", "barrel", "rifled barrel"); + Assert.DoesNotContain("barrel", TermRoles()); + Assert.All(sellers.Where(p => p.Bin == null), p => Assert.Contains(p.Roles, r => r.Role == "rifled barrel")); + } + + private sealed class DifferentGunRecipe : EconomyBatch + { + public override void Author(EconomyAuthor author) + { + var gun = author.Catalog.GetAll().Single(w => w.Name == "Autocannon"); + var key = RecipeData.KeyOf(author.Catalog.RefOf(gun).Key); + var recipe = author.Catalog.Get(key); + recipe.Workforce = 99; + author.Put(recipe, key); + } + } + + // Kills: the design-recipe block surviving in Munitions beside the bills. + [Fact] + public void MunitionsWritesNoDesignRecipe() + { + var path = ShippedCopy("Munitions.cc"); + Assert.Equal(0, EconomyCommand.Author(path, new EconomyBatch[] { new DifferentGunRecipe(), new Munitions() }, true, TextWriter.Null, TestCatalog.Registry(), _root)); + using var cache = AetheriaStores.Open(path, registry: TestCatalog.Registry()); + var gun = Assert.Single(cache.GetAll(), w => w.Name == "Autocannon"); + Assert.Equal(99, cache.Get(RecipeData.KeyOf(cache.RefOf(gun).Key)).Workforce); + } + + // What the shipped catalog holds of the bills: every part and design with its price, role counts and recipe, as text. + private static string[] Bills(CultCache cache) + { + var keys = new[] { "rifled-barrel", "lined-barrel", "coil-barrel", "tracking-feed" }.Select(id => new CultRecordKey("commodity:" + id)).ToList(); + var designs = new[] { "Light Machine Gun", "Point Defense Gun", "Slug Rifle", "Long Slug Rifle", "Flak Gun", "Autocannon", "Cluster Cannon", "Charged Scattergun", "Mine Launcher" }; + keys.AddRange(designs.Select(name => cache.RefOf(Assert.Single(cache.GetAll(), w => w.Name == name)).Key)); + return keys.Select(key => + { + var item = cache.Get(key); + var recipe = cache.Get(RecipeData.KeyOf(key)); + var roles = string.Join(",", Recipes.RolesOf(item).OrderBy(r => r.Name, StringComparer.Ordinal).Select(r => r.Name + "x" + r.Count)); + var inputs = string.Join(",", recipe.Inputs.OrderBy(i => i.Commodity.Key.Value, StringComparer.Ordinal).Select(i => i.Commodity.Key.Value + "x" + i.Count)); + return $"{item.Name}|price {item.Price}|roles {roles}|inputs {inputs}|fills {string.Join(",", recipe.Fills)}|cycle {recipe.Cycle} wf {recipe.Workforce} out {recipe.OutputCount}"; + }).ToArray(); + } + + // Kills: an edit to the batch (a bill count, a part input, a workforce) that the shipped catalog does not carry, or a catalog edit the + // batch would silently undo on its next apply. Byte equality is out of reach (element ids are minted on every write), so the batch is + // applied to a copy and the records it owns are compared as text, prices included. + [Fact] + public void TheBatchWritesWhatTheShippedCatalogHolds() + { + var path = ShippedCopy("Bills.cc"); + using (var shipped = AetheriaStores.Open(TestCatalog.Repo, registry: TestCatalog.Registry())) + { + var output = new StringWriter(); + Assert.True(EconomyCommand.Author(path, new EconomyBatch[] { new MunitionsBills() }, true, output, TestCatalog.Registry(), _root) == 0, output.ToString()); + using var applied = AetheriaStores.Open(path, registry: TestCatalog.Registry()); + Assert.Equal(Bills(shipped), Bills(applied)); + } + } +} diff --git a/tests/Aetheria.Shared.Tests/MunitionsSourcingCatalogTests.cs b/tests/Aetheria.Shared.Tests/MunitionsSourcingCatalogTests.cs index 45c8db147..7100eddbc 100644 --- a/tests/Aetheria.Shared.Tests/MunitionsSourcingCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/MunitionsSourcingCatalogTests.cs @@ -17,7 +17,7 @@ public sealed class MunitionsSourcingCatalogTests [Fact] public void EveryRoundFiringGunNamesAnAmmunitionCommodityAndHoldsARealMagazine() { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenShipped(); var guns = db.Cache.GetAll() .SelectMany(i => i.Behaviors.OfType().Where(d => FiresRounds(i, d)).Select(d => (i.Name, d))).ToArray(); Assert.True(guns.Length >= 14, $"fixture: the catalog holds its round-firing guns ({guns.Length})"); @@ -34,7 +34,7 @@ public sealed class MunitionsSourcingCatalogTests [Fact] public void EveryDrawnAmmunitionHasAFiniteProductionDepth() { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenShipped(); var depth = EconomyChecks.Deep(db.Cache); var drawn = db.Cache.GetAll().SelectMany(i => i.Behaviors.OfType()).Where(d => d.AmmoType.IsSet()) .Select(d => d.AmmoType.Key.Value).Distinct().ToArray(); @@ -47,7 +47,7 @@ public sealed class MunitionsSourcingCatalogTests [Fact] public void TheMunitionsChainHasNoSourceSinkFault() { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenShipped(); var chain = new HashSet(ChainOf(db.Cache), System.StringComparer.Ordinal); Assert.True(chain.Count >= 25, $"fixture: the chain is walked ({chain.Count} goods)"); var faults = EconomyChecks.SourceSink(db.Cache).Where(f => chain.Contains(KeyOfRecipe(f.Record))).ToArray(); diff --git a/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs b/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs index 7a399587f..9ed9a32cd 100644 --- a/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs +++ b/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs @@ -251,13 +251,12 @@ public sealed class OrbitsFromFieldTests : IDisposable cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(catalog), AetheriaStores.CatalogTypes); cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var tutorial = authored.Read("TutorialGenerationSettings"); - var galaxy = new Galaxy(tutorial, authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var tutorial = TestCasts.Wide; + var galaxy = new Galaxy(tutorial, authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, - galaxy.IsPrelude, false); + EntranceStationOrder.Any, false); var zone = new Zone(items, authored.Read("PlanetSettings"), pack, galaxy.Entrance, galaxy); var hosting = zone.Planets.Values.Select(body => body.Orbit.Key).ToHashSet(); diff --git a/tests/Aetheria.Shared.Tests/OreGeographyTests.cs b/tests/Aetheria.Shared.Tests/OreGeographyTests.cs index 20c1e9043..dadd29448 100644 --- a/tests/Aetheria.Shared.Tests/OreGeographyTests.cs +++ b/tests/Aetheria.Shared.Tests/OreGeographyTests.cs @@ -128,14 +128,14 @@ public sealed class OreGeographyTests : IDisposable return reached; } - private static Galaxy Build(CultCache cache, bool prelude, uint seed, TutorialGenerationSettings cast = null) => prelude - ? new Galaxy(cast ?? Authored.Read("TutorialGenerationSettings"), Authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed) + private static Galaxy Build(CultCache cache, bool prelude, uint seed, GalaxyCast cast = null) => prelude + ? new Galaxy(cast ?? TestCasts.Wide, Authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed) : new Galaxy(Authored.Read("SectorGenerationSettings"), Authored.Read("SectorBackgroundSettings"), cache, _ => { }, null, seed); // Galaxy refuses some seeds (RestoredHullsTests calls it seed-dependent flakiness); those are skipped. - private static Galaxy TryBuild(CultCache cache, bool prelude, uint seed, TutorialGenerationSettings cast = null) + private static Galaxy TryBuild(CultCache cache, bool prelude, uint seed, GalaxyCast cast = null) { try { return Build(cache, prelude, seed, cast); } catch (Exception) { return null; } @@ -151,14 +151,14 @@ public sealed class OreGeographyTests : IDisposable Enumerable.Range(1, (int) last).Select(seed => SharedGalaxy(prelude, (uint) seed)).Where(galaxy => galaxy != null); // The demo's cast: the same fixed cast, with the province size chosen. - private static TutorialGenerationSettings Cast(int provinceZones) + private static GalaxyCast Cast(int provinceZones) { var cast = DemoTerminus.Cast; - return new TutorialGenerationSettings + return new GalaxyCast { ProtagonistFaction = cast.ProtagonistFaction, AntagonistFaction = cast.AntagonistFaction, BufferFaction = cast.BufferFaction, NeutralFactions = cast.NeutralFactions, QuestFaction = cast.QuestFaction, ZoneCount = cast.ZoneCount, LinkDensity = cast.LinkDensity, - ProvinceZones = provinceZones + ProvinceZones = provinceZones, InfluenceScale = cast.InfluenceScale }; } @@ -754,13 +754,16 @@ public sealed class OreGeographyTests : IDisposable }).ToArray(); var (cache, _, _) = Shipped(); + var (bare, _, _) = Shipped(); + StripShippedProvinces(cache); + StripShippedProvinces(bare); Province(cache, "one", 2); Province(cache, "two", 1); var compared = 0; foreach (var prelude in new[] {false, true}) for (uint seed = 1; seed <= 4; seed++) { - var without = SharedGalaxy(prelude, seed); + var without = TryBuild(bare, prelude, seed); var with = TryBuild(cache, prelude, seed); Assert.Equal(without == null, with == null); if (without == null) continue; @@ -929,7 +932,7 @@ public sealed class OreGeographyTests : IDisposable { foreach (var zone in galaxy.Zones.Take(zones)) { - var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance); + var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, entranceStations: EntranceStationOrder.Any); foreach (var belt in pack.Planets.Select(body => cache.Get(body)).OfType()) yield return (belt, zone, pack); } @@ -937,6 +940,13 @@ public sealed class OreGeographyTests : IDisposable private ItemManager Items(CultCache cache) => new ItemManager(1u, cache, new ProvenanceLedger(), Authored.Read("GameplaySettings"), _ => { }); + // The shipped catalog deals six province types (batch OresAndProvinces); a test that draws by provinces it adds, or compares a galaxy dealt + // none with one dealt some, takes the shipped ones out first. + private static void StripShippedProvinces(CultCache cache) + { + foreach (var existing in cache.GetAll().ToArray()) Assert.True(cache.Remove(cache.RefOf(existing).Key)); + } + private static void SilenceShippedKinds(CultCache cache) { foreach (var existing in cache.GetAll().ToArray()) @@ -955,6 +965,7 @@ public sealed class OreGeographyTests : IDisposable { var (cache, _, _) = Shipped(); SilenceShippedKinds(cache); + StripShippedProvinces(cache); var a = Kind(cache, "a", 1f); var b = Kind(cache, "b", 1f); Province(cache, "no-a", 1, new[] {KindFactor(a, 0f)}); @@ -1004,7 +1015,7 @@ public sealed class OreGeographyTests : IDisposable var settings = RestoredHullsTests.AuthoredPlanetSettings(); var loaded = new Zone(items, settings, packs[0].Key, inProvince, galaxy); foreach (var key in packs[0].Select(g => cache.RefOf(g.Belt).Key)) - Assert.Equal(FieldKinds.Assign(key.Value, cache, noA).Key.Value, ((AsteroidBeltData) loaded.Planets[key]).Kind.Key.Value); + Assert.Equal(FieldKinds.Assign(((AsteroidBeltData) loaded.Planets[key]).SiteOr(key), cache, noA).Key.Value, ((AsteroidBeltData) loaded.Planets[key]).Kind.Key.Value); Assert.All(packs[0].Select(g => cache.RefOf(g.Belt).Key), key => Assert.Equal("field-kind:b", ((AsteroidBeltData) loaded.Planets[key]).Kind.Key.Value)); // No GalaxyZone: the unweighted pick. @@ -1015,7 +1026,7 @@ public sealed class OreGeographyTests : IDisposable foreach (var key in pack.Select(g => cache.RefOf(g.Belt).Key)) { var kind = ((AsteroidBeltData) bare.Planets[key]).Kind.Key.Value; - Assert.Equal(FieldKinds.Assign(key.Value, cache, default).Key.Value, kind); + Assert.Equal(FieldKinds.Assign(((AsteroidBeltData) bare.Planets[key]).SiteOr(key), cache, default).Key.Value, kind); if (kind == "field-kind:a") unweighted++; } } diff --git a/tests/Aetheria.Shared.Tests/OresAndProvincesTests.cs b/tests/Aetheria.Shared.Tests/OresAndProvincesTests.cs new file mode 100644 index 000000000..d89c39ba7 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/OresAndProvincesTests.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; + +// Batch OresAndProvinces on the shipped catalog (aetheria-living-world, cut ore-batch-apply): every ore a belt can yield is held, +// priced and sold, and MunitionsFeed leaves the recipes the batch owns. +public sealed class OresAndProvincesTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-ores-" + Guid.NewGuid().ToString("N")); + + public OresAndProvincesTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + private CultCache Shipped() + { + var path = Path.Combine(_root, "Aetheria.cc"); + File.Copy(TestCatalog.Repo, path, true); + return AetheriaStores.Open(path, catalogWritable: true, registry: TestCatalog.Registry()); + } + + // Kills: an ore written without a Shape (ItemData.Shape has no default and a cargo bay reads it to store the good). + [Fact] + public void EveryYieldedOreCanBeHeldAndSold() + { + using var cache = Shipped(); + var shape = new Shape(5, 5); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var bay = new Shape(4, 4); + foreach (var cell in bay.AllCoordinates) bay[cell] = true; + cache.Upsert(new VerseGrammar { Revision = 1 }); + cache.Upsert(new HullData { Name = "OreSkiff", HullType = HullType.Ship, Shape = shape, Price = 1000, Durability = 10, Armor = 10 }); + cache.Upsert(new CargoBayData { Name = "OreBay", Shape = new Shape(), InteriorShape = bay, Price = 20, Durability = 4 }); + cache.FlushAsync().GetAwaiter().GetResult(); + var items = new ItemManager(1u, cache, new ProvenanceLedger(), AuthoredSettings.Load(RestoredHullsTests.FindRepoRoot()).Read("GameplaySettings"), _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + EquippableItem Mint(string design) + { + var data = cache.GetByName(design); + return new EquippableItem + { + Data = cache.RefOf(data), Durability = data.Durability, + Lot = items.Lots.Add(new Lot { Design = cache.RefOf(data), Origin = new Attributed(), Quality = .5f, Roles = new List() }) + }; + } + var ship = new Ship(items, zone, Mint("OreSkiff"), new EntitySettings()); + Assert.True(ship.TryEquip(Mint("OreBay"), new int2(1, 1))); + + var kinds = cache.GetAll().ToArray(); + Assert.NotEmpty(kinds); + var yielded = kinds.SelectMany(kind => kind.Yields).Select(yield => yield.Commodity).GroupBy(commodity => commodity.Key.Value).Select(group => group.First()).ToArray(); + Assert.NotEmpty(yielded); + foreach (var commodity in yielded) + { + var data = cache.Get(commodity); + Assert.NotNull(data); + Assert.NotNull(data.Shape); + Assert.True(data.Price > 0, data.Name); + Assert.True(data.Mass > 0, data.Name); + var hold = ship.CargoBays.Single(); + Assert.True(hold.TryStore(new SimpleCommodity { Data = cache.RefOf(data), Quantity = 1 }), data.Name); + // One ore at a time: the bay has fewer cells than the ores there are. + foreach (var held in hold.Cargo.Keys.ToArray()) hold.Remove(held); + } + } + + // MunitionsFeed finds the ores it takes as inputs by key (Regolith, Nickel-Iron) or by name (Gold): a name lookup refused at head + // ("0 items are named 'Rock'"). A dry run at the shipped catalog succeeds and changes nothing. + [Fact] + public void MunitionsFeedDryRunSucceedsAtHeadAndChangesNothing() + { + var path = Path.Combine(_root, "Feed.cc"); + File.Copy(Path.Combine(RestoredHullsTests.FindRepoRoot(), "GameData", "Aetheria.cc"), path); + var before = File.ReadAllBytes(path); + var output = new StringWriter(); + Assert.Equal(0, EconomyCommand.Author(path, new List { new MunitionsFeed() }, false, output, TestCatalog.Registry(), _root)); + Assert.Equal(before, File.ReadAllBytes(path)); + Assert.DoesNotContain("are named", output.ToString()); + } + + // The batch is the one writer of the four recipes MunitionsFeed once wrote (Regolith, Nickel-Iron, Gold, Potassium): applying the feed + // to the applied catalog leaves each as the batch wrote it. Kills: a surviving Make for any of the four (mining without RoleInputs + // for Gold and Potassium, the feed's lore for any). + [Fact] + public void MunitionsFeedLeavesTheBatchRecipes() + { + var path = Path.Combine(_root, "Leaves.cc"); + File.Copy(Path.Combine(RestoredHullsTests.FindRepoRoot(), "GameData", "Aetheria.cc"), path); + string[] Names = { "Regolith", "Nickel-Iron", "Gold", "Potassium" }; + + List Read() + { + using var cache = AetheriaStores.Open(path, registry: TestCatalog.Registry()); + return Names.Select(name => + { + var item = cache.GetAll().Single(c => c.Name == name); + var recipe = cache.Get(RecipeData.KeyOf(cache.RefOf(item).Key)); + Assert.NotNull(recipe); + return $"{name}|{cache.Get(recipe.StationKind).Name}|inputs {recipe.Inputs.Count}|roles {string.Join(",", recipe.RoleInputs.Select(r => r.Name + "x" + r.Count))}|fills {string.Join(",", recipe.Fills)}|{recipe.LoreHook}"; + }).ToList(); + } + + var batch = Read(); + Assert.Contains(batch, line => line.StartsWith("Regolith|Mining Station|inputs 0|roles |")); + Assert.Contains(batch, line => line.StartsWith("Nickel-Iron|Mining Station|inputs 0|roles |")); + Assert.Contains(batch, line => line.StartsWith("Gold|Processing Station|inputs 0|roles gold orex")); + Assert.Contains(batch, line => line.StartsWith("Potassium|Processing Station|inputs 0|roles potassium orex")); + + Assert.Equal(0, EconomyCommand.Author(path, new List { new MunitionsFeed() }, true, new StringWriter(), TestCatalog.Registry(), _root)); + Assert.Equal(batch, Read()); + } +} diff --git a/tests/Aetheria.Shared.Tests/PackageMountCensusTests.cs b/tests/Aetheria.Shared.Tests/PackageMountCensusTests.cs new file mode 100644 index 000000000..8e1512378 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/PackageMountCensusTests.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using Xunit; + +// A census over every ship package the repo composes: each hardpoint of a package hull takes at least one catalog item of its +// type under the one fit rule (HardpointData.Takes). The bug class is nakovalnya-package s2: flank flak and radiators that +// took nothing. A type with no item in the catalog at all is skipped (follow-up no-shield-item), because no package can fix +// that. Packages are enumerated through the composed catalog (ShipModCatalog's mod keys), as the game boots them +// (ruling census-tests-read-the-owners). +public sealed class PackageMountCensusTests +{ + private static CultCache Open(string catalog) + { + var cache = new CultCache(TestCatalog.Registry()); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalog, true), AetheriaStores.CatalogTypes); + return cache; + } + + // Every package hull of a composed catalog, named by ship id. The key format is ShipModCatalog's: a hull record with a mod + // key is a package's, and the id is what follows the prefix HullKey puts on it. + private static (string Package, HullData Hull)[] Packages(CultCache cache) + { + var prefix = ShipModCatalog.HullKey("").Value; + return cache.GetAll() + .Select(hull => (Key: cache.RefOf(hull).Key, Hull: hull)) + .Where(entry => ShipModCatalog.IsModKey(entry.Key)) + .Select(entry => (entry.Key.Value.Substring(prefix.Length), entry.Hull)) + .ToArray(); + } + + // One line per hardpoint no catalog item of its type fits, naming package, row and type. + private static string[] Unfilled(IEnumerable<(string Package, HullData Hull)> packages, IReadOnlyCollection items) => + packages.SelectMany(package => package.Hull.Hardpoints + .Where(row => items.Any(item => item.HardpointType == row.Type) && !items.Any(row.Takes)) + .Select(row => $"{package.Package}: row {row.Transform} ({row.Type}) takes no catalog item")) + .ToArray(); + + [Fact] + public void EveryPackageMountTakesSomeGear() + { + using var cache = Open(TestCatalog.Repo); + var packages = Packages(cache); + Assert.NotEmpty(packages); + Assert.Empty(Unfilled(packages, cache.GetAll().ToArray())); + } + + private static HullData StarterHull(string root, string id, HullData like) => + ShipModCatalog.ReadPackage(ShipStarterCommand.Write(Path.Combine(root, "GameData", "Mods"), id, "Probe " + id, like)).Hull; + + private static HullData Like() => new HullData { Name = "Like", HullType = HullType.Ship, Mass = 1234, Behaviors = { new VelocityLimitData() } }; + + // The census cannot pass vacuously. The starter package passes; the same package with any one row's Shape cut to a single + // cell, that row first or last in the list, fails naming that row and no other. (Widening a mount only lets it take more + // gear under Takes, so the pin narrows.) Every row the pin can narrow is tried, so a census that skips a row fails here. + [Fact] + public void TheCensusNamesAMountNothingFits() + { + using var cache = Open(TestCatalog.Repo); + var items = cache.GetAll().ToArray(); + using var work = new TempDirectory(); + var hull = StarterHull(work.Path, "probe.census", Like()); + Assert.Empty(Unfilled(new[] { ("probe.census", hull) }, items)); + + var original = hull.Hardpoints.ToList(); + var narrowable = original.Where(row => items.Any(item => item.HardpointType == row.Type && item.Shape.Coordinates.Length > 1)).ToArray(); + Assert.True(narrowable.Length >= 2, "the pin needs at least two rows that a one-cell shape starves"); + foreach (var row in narrowable) + foreach (var first in new[] { true, false }) + { + var shape = row.Shape; + row.Shape = new Shape(1, 1); + var others = original.Where(other => other != row); + hull.Hardpoints = first ? new[] { row }.Concat(others).ToList() : others.Append(row).ToList(); + Assert.Equal(new[] { $"probe.census: row {row.Transform} ({row.Type}) takes no catalog item" }, Unfilled(new[] { ("probe.census", hull) }, items)); + row.Shape = shape; + } + } + + // Enumeration reads every package of the composed catalog, not the first: two packages compose, and both are censused. + [Fact] + public void TheCensusEnumeratesEveryPackage() + { + using var work = new TempDirectory(); + var mods = Path.Combine(work.Path, "GameData", "Mods"); + foreach (var id in new[] { "probe.alpha", "probe.omega" }) + ShipStarterCommand.Write(mods, id, "Probe " + id, Like()); + var catalog = TestCatalog.Resolve(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Aetheria.cc"), mods, work.Path); + using var cache = Open(catalog); + Assert.Equal(new[] { "probe.alpha", "probe.omega" }, Packages(cache).Select(package => package.Package).OrderBy(id => id, StringComparer.Ordinal).ToArray()); + } +} diff --git a/tests/Aetheria.Shared.Tests/PiratesFactionCommandTests.cs b/tests/Aetheria.Shared.Tests/PiratesFactionCommandTests.cs index 99ec92249..7b83c8525 100644 --- a/tests/Aetheria.Shared.Tests/PiratesFactionCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/PiratesFactionCommandTests.cs @@ -32,6 +32,7 @@ public sealed class PiratesFactionCommandTests : IDisposable var ours = cache.RefOf(pirates); foreach (var product in cache.GetAll().Where(product => product.Manufacturer.Equals(ours)).ToArray()) Assert.True(cache.Remove(cache.RefOf(product).Key)); + TestStationKinds.DropStandInsOf(cache, ours.Key); Assert.True(cache.Remove(ours.Key)); cache.FlushAsync().Wait(); } @@ -41,14 +42,14 @@ public sealed class PiratesFactionCommandTests : IDisposable private int AllFactionsButThePirates() { - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); try { return db.Cache.GetAll().Count(f => f.Name != "Pirates"); } finally { db.Cache.Dispose(); } } private (Faction[] Pirates, FactionProductData[] Products) Read() { - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); try { var pirates = db.Cache.GetAll().Where(faction => faction.Name == "Pirates").ToArray(); @@ -79,7 +80,7 @@ public sealed class PiratesFactionCommandTests : IDisposable Assert.Equal(AllFactionsButThePirates(), faction.Allegiance.Count); Assert.All(faction.Allegiance.Values, value => Assert.Equal(1f, value)); - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); try { var expected = new (string Design, string Name, string Description)[] @@ -117,7 +118,7 @@ public sealed class PiratesFactionCommandTests : IDisposable [Fact] public void An_existing_Pirates_faction_is_topped_up_with_allegiance_and_nothing_else() { - var db = AetherDb.Open(catalogWritable: true, root: _root); + var db = AetherDb.OpenShipped(catalogWritable: true, root: _root); db.Cache.Commit(batch => batch.Upsert(typeof(Faction), new Faction { Name = "Pirates", ShortName = "Mine", Description = "authored by hand" })); var key = db.Cache.RefOf(db.Cache.GetAll().Single(f => f.Name == "Pirates")).Key; db.Cache.Dispose(); @@ -134,14 +135,14 @@ public sealed class PiratesFactionCommandTests : IDisposable Assert.Empty(products); var topped = File.ReadAllBytes(CatalogPath); - var late = AetherDb.Open(catalogWritable: true, root: _root); + var late = AetherDb.OpenShipped(catalogWritable: true, root: _root); late.Cache.Commit(batch => batch.Upsert(typeof(Faction), new Faction { Name = "Latecomer", ShortName = "Late" })); var lateRef = late.Cache.RefOf(late.Cache.GetAll().Single(f => f.Name == "Latecomer")); var others = late.Cache.GetAll().Count(f => f.Name != "Pirates"); late.Cache.Dispose(); Assert.Equal(0, Program.PiratesFaction(apply: true, root: _root)); - var check = AetherDb.Open(root: _root); + var check = AetherDb.OpenShipped(root: _root); try { var after = check.Cache.GetAll().Single(f => f.Name == "Pirates"); @@ -162,7 +163,7 @@ public sealed class PiratesFactionCommandTests : IDisposable [Fact] public void A_missing_design_refuses_and_lands_nothing() { - var db = AetherDb.Open(catalogWritable: true, root: _root); + var db = AetherDb.OpenShipped(catalogWritable: true, root: _root); var autocannon = db.Cache.GetAll().Single(weapon => weapon.Name == "Autocannon"); autocannon.Name = "Autocannon (renamed)"; db.Cache.Commit(batch => batch.Upsert(typeof(WeaponItemData), autocannon, db.Cache.RefOf(autocannon).Key)); diff --git a/tests/Aetheria.Shared.Tests/PiratesRecordTests.cs b/tests/Aetheria.Shared.Tests/PiratesRecordTests.cs index 8b8367701..f6088cdb4 100644 --- a/tests/Aetheria.Shared.Tests/PiratesRecordTests.cs +++ b/tests/Aetheria.Shared.Tests/PiratesRecordTests.cs @@ -27,7 +27,8 @@ public sealed partial class RunStartTests Assert.All(others, other => Assert.True(pirates.Allegiance.ContainsKey(other))); Assert.NotEmpty(pirates.Places); - var products = PiratesProducts(); + // The Seized Refinery is the Pirates' own station package (cut station-package-processing), not a rebrand of another maker's design. + var products = PiratesProducts().Where(product => !product.Design.Key.Equals(ShipModCatalog.HullKey("aetheria.seized-refinery"))).ToArray(); Assert.Equal(8, products.Length); var hulls = LoadoutGenerator.SoldHulls(_cache); foreach (var product in products) diff --git a/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs b/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs index 9490d049b..6856b6eb9 100644 --- a/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs +++ b/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs @@ -30,8 +30,8 @@ public sealed class PlaceNamesTests : IDisposable } private static Galaxy Build(CultCache cache, bool prelude, uint seed) => prelude - ? new Galaxy(Authored.Read("TutorialGenerationSettings"), Authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed) + ? new Galaxy(TestCasts.Wide, Authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed) : new Galaxy(Authored.Read("SectorGenerationSettings"), Authored.Read("SectorBackgroundSettings"), cache, _ => { }, null, seed); @@ -297,7 +297,7 @@ public sealed class PlaceNamesTests : IDisposable Assert.Equal(0, PlaceNamesCommand.Run(new[] { "apply" }, root)); var landed = File.ReadAllBytes(CatalogOf(root)); Assert.NotEqual(before, landed); - var db = AetherDb.Open(root: root); + var db = AetherDb.OpenShipped(root: root); try { foreach (var row in PlaceNamesCommand.Table) @@ -308,7 +308,7 @@ public sealed class PlaceNamesTests : IDisposable Assert.Equal(landed, File.ReadAllBytes(CatalogOf(root))); // Aya's ShortName changed under its key: identity is the key, so the row no longer describes that faction. - var squatter = AetherDb.Open(catalogWritable: true, root: root); + var squatter = AetherDb.OpenShipped(catalogWritable: true, root: root); var aya = squatter.Cache.GetAll().Single(f => f.ShortName == "Aya"); aya.ShortName = "Ayx"; squatter.Cache.Commit(batch => batch.Upsert(typeof(Faction), aya, squatter.Cache.RefOf(aya).Key)); @@ -325,7 +325,7 @@ public sealed class PlaceNamesTests : IDisposable var root = ScratchWithoutLists(); Assert.Equal(0, PlaceNamesCommand.Run(new[] { "apply" }, root)); var row = PlaceNamesCommand.Table.First(); - var edited = AetherDb.Open(catalogWritable: true, root: root); + var edited = AetherDb.OpenShipped(catalogWritable: true, root: root); var faction = edited.Cache.GetAll().Single(f => edited.Cache.RefOf(f).Key.Value == row.RecordKey); faction.Places = row.Names.Reverse().Select(n => new FactionPlace { Name = n }).ToArray(); edited.Cache.Commit(batch => batch.Upsert(typeof(Faction), faction, edited.Cache.RefOf(faction).Key)); @@ -333,7 +333,7 @@ public sealed class PlaceNamesTests : IDisposable Assert.Equal(0, PlaceNamesCommand.Run(new[] { "apply" }, root)); - var db = AetherDb.Open(root: root); + var db = AetherDb.OpenShipped(root: root); try { Assert.Equal(row.Names, db.Cache.GetAll().Single(f => db.Cache.RefOf(f).Key.Value == row.RecordKey).Places.Select(p => p.Name)); } finally { db.Cache.Dispose(); } } diff --git a/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs b/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs index 76ad7c2f8..768bc8a14 100644 --- a/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs +++ b/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs @@ -128,6 +128,7 @@ public sealed class ProductChoiceTests : IDisposable var outZ = cache.GetByName("OutZ"); var game = new SavedGame { + InfluenceScale = 1, // Alpha's headquarters are in zone 0 and Zeta's in zone 1. Factions = new[] { cache.RefOf(outA), cache.RefOf(outZ), cache.RefOf(cache.GetByName("Alpha")), cache.RefOf(cache.GetByName("Zeta")) }, Relationships = new[] { FactionRelationship.Neutral, FactionRelationship.Neutral, FactionRelationship.Neutral, FactionRelationship.Neutral }, diff --git a/tests/Aetheria.Shared.Tests/RecipeRoleInputTests.cs b/tests/Aetheria.Shared.Tests/RecipeRoleInputTests.cs index fdf387130..6d2731452 100644 --- a/tests/Aetheria.Shared.Tests/RecipeRoleInputTests.cs +++ b/tests/Aetheria.Shared.Tests/RecipeRoleInputTests.cs @@ -29,7 +29,9 @@ public sealed class RecipeRoleInputTests using var cache = AetheriaStores.Open(TestCatalog.Repo, registry: TestCatalog.Registry()); var recipes = cache.GetAll().ToArray(); Assert.NotEmpty(recipes); - Assert.All(recipes, r => { Assert.NotNull(r.RoleInputs); Assert.Empty(r.RoleInputs); }); + Assert.All(recipes, r => Assert.NotNull(r.RoleInputs)); + // Only the batch's first smelting step takes a role instead of a commodity: every recipe with Inputs reads an empty list. + Assert.All(recipes.Where(r => r.Inputs.Count > 0), r => Assert.Empty(r.RoleInputs)); } [Fact] @@ -59,6 +61,7 @@ public sealed class RecipeRoleInputTests public void ANullListElsewhereInARecipeLeavesItsRoleInputsToTheRules() { using var f = Smelter(); + f.Settle(); Assert.Empty(EconomyChecks.Check(f.Cache).Faults.Where(x => x.Invariant != EconomyChecks.LRecipe)); f.EditRecipe(Iron, r => r.Upkeep = null); Assert.Empty(EconomyChecks.Check(f.Cache).Faults.Where(x => x.Invariant != EconomyChecks.LRecipe)); diff --git a/tests/Aetheria.Shared.Tests/RecipeSchemaTests.cs b/tests/Aetheria.Shared.Tests/RecipeSchemaTests.cs index 62b311d22..2fb3009b2 100644 --- a/tests/Aetheria.Shared.Tests/RecipeSchemaTests.cs +++ b/tests/Aetheria.Shared.Tests/RecipeSchemaTests.cs @@ -32,6 +32,40 @@ public sealed class RecipeSchemaTests Assert.Equal(4, counted.Count); } + // A record keeps the slots it was written with: one cut short of a later key reads that member as it starts out. + private static byte[] CutShort(byte[] record, int slots) + { + var reader = new MessagePackReader(record); + var count = reader.ReadArrayHeader(); + Assert.True(count > slots); + var start = reader.Consumed; + for (var i = 0; i < slots; i++) reader.Skip(); + var writer = new System.Buffers.ArrayBufferWriter(); + var write = new MessagePackWriter(writer); + write.WriteArrayHeader(slots); + write.Flush(); + return writer.WrittenSpan.ToArray().Concat(record.Skip((int) start).Take((int) (reader.Consumed - start))).ToArray(); + } + + [Fact] + public void RecordsWrittenBeforeFacilityKeysReadUnsetAndEmpty() + { + var options = GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.OptionsFor(typeof(RecipeData).Assembly); + var item = new CultRecordRef(new CultRecordKey("gear:mill-works")); + var recipe = new RecipeData { Output = item, Facility = item }; + var kind = new StationKindData { Name = "Mill", Facilities = new System.Collections.Generic.List> { item } }; + var current = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(recipe, options), options); + Assert.Equal("gear:mill-works", current.Facility.Key.Value); + Assert.Equal("gear:mill-works", MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(kind, options), options).Facilities.Single().Key.Value); + + var oldRecipe = MessagePackSerializer.Deserialize(CutShort(MessagePackSerializer.Serialize(recipe, options), 10), options); + Assert.False(oldRecipe.Facility.IsSet()); + Assert.Equal("gear:mill-works", oldRecipe.Output.Key.Value); + var oldKind = MessagePackSerializer.Deserialize(CutShort(MessagePackSerializer.Serialize(kind, options), 3), options); + Assert.Empty(oldKind.Facilities); + Assert.Equal("Mill", oldKind.Name); + } + [Fact] public void RoleCountSurvivesTheStore() { diff --git a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs index 121d468b3..f1251b606 100644 --- a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs +++ b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs @@ -61,9 +61,10 @@ public sealed class RestoredHullsTests } internal static CultCache OpenCatalog() => OpenReadOnlyRealCatalog(TestCatalog.Repo); + internal static CultCache OpenCatalogWithFixtures() => OpenReadOnlyRealCatalog(TestCatalog.RepoWithFixtures); - // Shared tutorial-galaxy construction settings (Assets/Resources/Settings.asset's own values), factored out - // so every test that needs a real tutorial Galaxy -- not just EntranceZoneAlwaysGetsADockedStationAcrossSeeds + // Shared cast-galaxy construction settings (Assets/Resources/Settings.asset's own values), factored out + // so every test that needs a real cast Galaxy -- not just EntranceZoneAlwaysGetsADockedStationAcrossSeeds // -- builds it the same way instead of re-inlining the same ~20 fields. internal static PlanetSettings AuthoredPlanetSettings() => AuthoredSettings.Load(RunStartTests.FindRepoRoot()).Read("PlanetSettings"); @@ -87,18 +88,6 @@ public sealed class RestoredHullsTests NameData = new string[0], }; - internal static TutorialGenerationSettings TutorialGalaxySettings() => new TutorialGenerationSettings - { - ProtagonistFaction = "Miss", AntagonistFaction = "Zhe", BufferFaction = "Luc", - NeutralFactions = new[] { "Aero", "Finch" }, QuestFaction = "Adras", LinkDensity = .5f, ZoneCount = 64, - }; - - internal static SectorBackgroundSettings TutorialBackgroundSettings() => new SectorBackgroundSettings - { - NoiseAmplitude = 1, NoiseOffset = .3f, NoiseGain = .7f, NoiseLacunarity = 2, NoiseFrequency = .1f, - NoisePosition = 536.5106f, CloudExponent = 10, CloudAmplitude = .01f, - }; - // A station's orbit is a copy of its source planet's own (Parent, Distance) (ZoneGenerator.CreateLagrangeOrbit), // so it always matches that one planet. It matches MORE than one planet only when the source planet shares its // distance with a sibling under the same parent -- exactly what ZoneGenerator's potentialLagrangePoints filter @@ -158,10 +147,10 @@ public sealed class RestoredHullsTests var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); for (var seed = 1u; seed <= 64u; seed++) { - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed); foreach (var zone in galaxy.Zones.Where(z => !ReferenceEquals(z, galaxy.Entrance))) { - var orbits = ParentedPlanetOrbits(cache, ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial: false, ambient: false)); + var orbits = ParentedPlanetOrbits(cache, ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, entranceStations: EntranceStationOrder.None, ambient: false)); if (orbits.Length > 0 && !HasGenuineLagrangeCandidate(orbits)) return (seed, zone.Name); } } @@ -379,8 +368,8 @@ public sealed class RestoredHullsTests public void EntranceZoneAlwaysGetsADockedStationAcrossSeeds() { var zoneSettings = TutorialZoneSettings(); - var tutorialSettings = TutorialGalaxySettings(); - var background = TutorialBackgroundSettings(); + var tutorialSettings = TestCasts.Wide; + var background = TestCasts.Background; var gameData = TestCatalog.Repo; var sawGenuineLagrangeOrbit = false; for (uint seed = 1; seed <= 25; seed++) @@ -389,10 +378,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(tutorialSettings, background, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(tutorialSettings, background, cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStations: EntranceStationOrder.Any); var dockedStation = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -412,15 +401,15 @@ public sealed class RestoredHullsTests // Cut 1 fix batch 3 (F6, N1): a per-seed strengthening of the "across seeds" test above. That test only // requires a genuine Lagrange orbit at least once in 25 seeds; it says nothing about a seed where a genuine // candidate DID exist but the station landed on the widened fallback anyway (which the widening condition's - // own isTutorialEntrance-and-empty-candidates guard should make impossible). This pins the normal case + // own entranceStationEntrance-and-empty-candidates guard should make impossible). This pins the normal case // directly, seed by seed: whenever the entrance zone actually has a genuine (non-rosette) Lagrange candidate, // its station must be seated on one. [Fact] public void EntranceStationSitsOnAGenuineLagrangeOrbitWheneverOneExists() { var zoneSettings = TutorialZoneSettings(); - var tutorialSettings = TutorialGalaxySettings(); - var background = TutorialBackgroundSettings(); + var tutorialSettings = TestCasts.Wide; + var background = TestCasts.Background; var gameData = TestCatalog.Repo; var sawGenuineCandidate = false; for (uint seed = 1; seed <= 25; seed++) @@ -429,10 +418,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(tutorialSettings, background, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(tutorialSettings, background, cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStations: EntranceStationOrder.Any); var planetOrbits = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Where(o => o.Parent.IsSet()).ToArray(); var hasGenuineCandidate = planetOrbits.Any(o => planetOrbits.Count(c => c.Parent.Key.Equals(o.Parent.Key) && abs(c.Distance - o.Distance) < .1f) == 1); @@ -467,7 +456,7 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); var zoneSettings = TutorialZoneSettings(); @@ -477,7 +466,7 @@ public sealed class RestoredHullsTests zoneSettings.SubZoneCount = new ExponentialLerp { Exponent = 1, Minimum = 0, Maximum = 0 }; Assert.Throws(() => - ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true)); + ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStations: EntranceStationOrder.Any)); } finally { @@ -502,7 +491,7 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); var zoneSettings = TutorialZoneSettings(); @@ -511,7 +500,7 @@ public sealed class RestoredHullsTests zoneSettings.SatelliteCreationProbability = 0; zoneSettings.BinaryCreationProbability = 0; - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStations: EntranceStationOrder.Any); var roots = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Count(o => !o.Parent.IsSet()); Assert.True(roots > 1, $"this fixture no longer produces a multi-root entrance (only {roots} root); it no longer tests the fragmented-topology case."); @@ -541,8 +530,8 @@ public sealed class RestoredHullsTests public void EntranceStationPhaseDiffersFromEveryPlanetAtItsOwnDistanceAcrossSeeds() { var zoneSettings = TutorialZoneSettings(); - var tutorialSettings = TutorialGalaxySettings(); - var background = TutorialBackgroundSettings(); + var tutorialSettings = TestCasts.Wide; + var background = TestCasts.Background; var gameData = TestCatalog.Repo; var checkedAny = false; @@ -552,10 +541,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(tutorialSettings, background, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(tutorialSettings, background, cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStations: EntranceStationOrder.Any); var dockedStation = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -687,7 +676,7 @@ public sealed class RestoredHullsTests // real zone from a real galaxy (e.g. one already known to have no Lagrange candidate) and make it the Entrance. private static Galaxy BuildGalaxyWithForcedEntrance(CultCache cache, uint seed, string entranceZoneName) { - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed); var target = galaxy.Zones.Single(z => z.Name == entranceZoneName); var factions = galaxy.Factions; @@ -714,7 +703,7 @@ public sealed class RestoredHullsTests Relationships = factions.Select(f => galaxy.FactionRelationships[f]).ToArray(), DiscoveredZones = Array.Empty(), Background = galaxy.Background, - IsTutorial = true, + InfluenceScale = .5f, }; return new Galaxy(cache, game, _ => { }); } @@ -749,7 +738,7 @@ public sealed class RestoredHullsTests var galaxy = BuildGalaxyWithForcedEntrance(cache, seed, zoneName); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStations: EntranceStationOrder.Any); var station = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -798,24 +787,24 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - int StationCount(GalaxyZone zone, bool isTutorial) => - ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial) + int StationCount(GalaxyZone zone, IReadOnlyList entranceStations) => + ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, entranceStations) .Entities.OfType() .Count(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station); // (a) A non-entrance tutorial zone that naturally rolls zero stations keeps that roll under - // isTutorial: true -- the floor must not leak past the galaxy.Entrance reference check. - // The zone is chosen by its natural roll: zero stations without the tutorial floor (isTutorial: false). - var otherZone = galaxy.Zones.First(z => !ReferenceEquals(z, galaxy.Entrance) && StationCount(z, isTutorial: false) == 0); + // a default order -- the floor must not leak past the galaxy.Entrance reference check. + // The zone is chosen by its natural roll: zero stations without the tutorial floor (no orders). + var otherZone = galaxy.Zones.First(z => !ReferenceEquals(z, galaxy.Entrance) && StationCount(z, entranceStations: EntranceStationOrder.None) == 0); Assert.NotSame(galaxy.Entrance, otherZone); - Assert.Equal(0, StationCount(otherZone, isTutorial: true)); + Assert.Equal(0, StationCount(otherZone, entranceStations: EntranceStationOrder.Any)); - // (b) The entrance zone itself, generated for a non-tutorial game (isTutorial: false), keeps its - // natural roll too -- the floor must not leak past the isTutorial flag either. - Assert.Equal(0, StationCount(galaxy.Entrance, isTutorial: false)); + // (b) The entrance zone itself, generated for a non-tutorial game (no orders), keeps its + // natural roll too -- the floor must not leak past the declaration either. + Assert.Equal(0, StationCount(galaxy.Entrance, entranceStations: EntranceStationOrder.None)); } finally { @@ -826,7 +815,7 @@ public sealed class RestoredHullsTests // Cut 1 fix batch 2 (Soul's finding #2, baseStationCount): the entrance override raises stationCount (the // orbit-selection floor) but must not also raise the enemyCount roll, which is keyed to baseStationCount // (the pre-override value) precisely so the forced station doesn't buy the zone an extra enemy. Seed 1's - // entrance zone rolls baseStationCount 0 (confirmed via the isTutorial: false StationCount == 0 above) and + // entrance zone rolls baseStationCount 0 (confirmed via the entranceStations: EntranceStationOrder.None StationCount == 0 above) and // the override raises stationCount to 1; this pins the resulting ship count at the value baseStationCount // produces. It must fail if the enemy-count formula is changed to add stationCount instead (it would add a // ship instead of zero). @@ -838,10 +827,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStations: EntranceStationOrder.Any); var stationCount = pack.Entities.OfType().Count(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station); // Soul's finding (this cut's fix batch 3): pack.Entities.OfType().Count() also counts the // zone's neutral wanderers (ZoneGenerator.cs's own EligibleWandererFactions spawn, keyed to @@ -868,12 +857,12 @@ public sealed class RestoredHullsTests // here by boosting one faction's presence there (HomeZone distance 0, InfluenceDistance 50, so the roll's // floor(rand * (factionPresence+1)) is overwhelmingly likely nonzero) via the same public SavedGame round // trip BuildGalaxyWithForcedEntrance uses, not by touching ZoneGenerator's private roll. Verified directly: - // temporarily widening every zone (dropping ZoneGenerator's isTutorialEntrance guard) turns this fixture's + // temporarily widening every zone (dropping ZoneGenerator's entranceStationEntrance guard) turns this fixture's // station count from 0 into 2, so a natural nonzero roll really is hiding behind the empty candidate set. // Must fail if that guard is dropped for real. private static Galaxy BuildGalaxyWithBoostedPresence(CultCache cache, uint seed, string zoneName) { - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed); var target = galaxy.Zones.Single(z => z.Name == zoneName); var factions = galaxy.Factions; @@ -905,7 +894,7 @@ public sealed class RestoredHullsTests Relationships = factions.Select(f => galaxy.FactionRelationships[f]).ToArray(), DiscoveredZones = Array.Empty(), Background = galaxy.Background, - IsTutorial = true, + InfluenceScale = .5f, }; return new Galaxy(cache, game, _ => { }); } @@ -924,7 +913,7 @@ public sealed class RestoredHullsTests Assert.NotSame(galaxy.Entrance, zone); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, entranceStations: EntranceStationOrder.Any); // Confirms this fixture still has no genuine (non-rosette) Lagrange candidate -- a regression here // would mean the fixture no longer probes what this test claims to probe. diff --git a/tests/Aetheria.Shared.Tests/RolesBackfillCommandTests.cs b/tests/Aetheria.Shared.Tests/RolesBackfillCommandTests.cs index 58c823af4..64dc7ac33 100644 --- a/tests/Aetheria.Shared.Tests/RolesBackfillCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/RolesBackfillCommandTests.cs @@ -68,12 +68,19 @@ public sealed class RolesBackfillCommandTests : IDisposable } } if (unnamed) + { + // Cluster Cannon and Flak Gun shipped before their tier roles (MunitionsBills came after the backfill). + var author = new EconomyAuthor(cache); + MunitionsBills.RenameRole(author, "Cluster Cannon", "lined barrel", "barrel"); + MunitionsBills.RenameRole(author, "Flak Gun", "tracking feed", "feed mechanism"); + designs = cache.GetAll().ToArray(); foreach (var (name, field) in Unnamed) { var design = designs.Single(d => d.Name == name); foreach (var term in Stat(design, field).Terms.Where(t => t.Source == StatSource.Quality)) term.Role = null; changed.Add(design); } + } if (changed.Count > 0) cache.Commit(batch => { @@ -107,9 +114,16 @@ public sealed class RolesBackfillCommandTests : IDisposable return string.Join("\n", new[] { roles }.Concat(stats).Concat(sellers)); } + // The tiers are history that came after the backfill, so a replay is the backfill, then the bills. + private void ApplyBills() + { + var output = new StringWriter(); + Assert.True(EconomyCommand.Author(CatalogPath, new EconomyBatch[] { new MunitionsBills() }, true, output, TestCatalog.Registry(), _root) == 0, output.ToString()); + } + private Dictionary Read() { - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); try { var products = db.Cache.GetAll().ToArray(); @@ -131,8 +145,9 @@ public sealed class RolesBackfillCommandTests : IDisposable Assert.Equal(before, File.ReadAllBytes(CatalogPath)); Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root)); + Assert.NotEqual(before, File.ReadAllBytes(CatalogPath)); + ApplyBills(); var landed = File.ReadAllBytes(CatalogPath); - Assert.NotEqual(before, landed); var after = Read(); foreach (var name in _shipped.Keys.OrderBy(n => n, StringComparer.Ordinal)) Assert.Equal(_shipped[name], after[name]); @@ -153,6 +168,7 @@ public sealed class RolesBackfillCommandTests : IDisposable Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root)); Assert.NotEqual(before, File.ReadAllBytes(CatalogPath)); + ApplyBills(); var after = Read(); foreach (var (name, _) in Unnamed) Assert.Equal(_shipped[name], after[name]); } @@ -173,7 +189,7 @@ public sealed class RolesBackfillCommandTests : IDisposable Reset(flattened: true, unnamed: true); Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root)); - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); Dictionary> after; try { after = Read(db.Cache.GetAll().ToArray()); } finally { db.Cache.Dispose(); } @@ -185,7 +201,7 @@ public sealed class RolesBackfillCommandTests : IDisposable public void A_seller_with_one_of_two_roles_authored_gains_only_the_missing_role() { Reset(flattened: false, unnamed: false); - var db = AetherDb.Open(catalogWritable: true, root: _root); + var db = AetherDb.OpenShipped(catalogWritable: true, root: _root); var autocannon = db.Cache.GetAll().Single(weapon => weapon.Name == "Autocannon"); var seller = db.Cache.GetAll().OrderBy(p => p.Name, StringComparer.Ordinal).First(p => p.Design.Key.Equals(db.Cache.RefOf(autocannon).Key) && p.Roles.Count == 2); var kept = seller.Roles.OrderBy(r => r.Role, StringComparer.Ordinal).First(); @@ -197,11 +213,11 @@ public sealed class RolesBackfillCommandTests : IDisposable db.Cache.Dispose(); Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root)); - db = AetherDb.Open(root: _root); + db = AetherDb.OpenShipped(root: _root); try { var after = db.Cache.GetAll().Single(p => p.Name == sellerName); - Assert.Equal(new[] { "barrel", "feed mechanism" }, after.Roles.Select(r => r.Role).OrderBy(r => r, StringComparer.Ordinal).ToArray()); + Assert.Equal(autocannon.Roles.Select(r => r.Name).OrderBy(r => r, StringComparer.Ordinal).ToArray(), after.Roles.Select(r => r.Role).OrderBy(r => r, StringComparer.Ordinal).ToArray()); Assert.Equal(.91f, after.Roles.Single(r => r.Role == keptRole).Mean, 3); } finally { db.Cache.Dispose(); } @@ -212,7 +228,7 @@ public sealed class RolesBackfillCommandTests : IDisposable public void A_binned_seller_gains_no_roles() { Reset(flattened: false, unnamed: false); - var db = AetherDb.Open(catalogWritable: true, root: _root); + var db = AetherDb.OpenShipped(catalogWritable: true, root: _root); var autocannon = db.Cache.GetAll().Single(weapon => weapon.Name == "Autocannon"); var seller = db.Cache.GetAll().OrderBy(p => p.Name, StringComparer.Ordinal).First(p => p.Design.Key.Equals(db.Cache.RefOf(autocannon).Key) && p.Roles.Count == 2); var sellerName = seller.Name; @@ -230,7 +246,7 @@ public sealed class RolesBackfillCommandTests : IDisposable db.Cache.Dispose(); Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root)); - db = AetherDb.Open(root: _root); + db = AetherDb.OpenShipped(root: _root); try { Assert.Equal(2, db.Cache.GetAll().Single(p => p.Name == sellerName).Roles.Count); @@ -243,7 +259,7 @@ public sealed class RolesBackfillCommandTests : IDisposable [Fact] public void The_census_reports_a_roleless_seller_and_never_a_bin() { - var db = AetherDb.Open(catalogWritable: true, root: _root); + var db = AetherDb.OpenShipped(catalogWritable: true, root: _root); var autocannon = db.Cache.GetAll().Single(weapon => weapon.Name == "Autocannon"); var seller = db.Cache.GetAll().OrderBy(p => p.Name, StringComparer.Ordinal).First(p => p.Design.Key.Equals(db.Cache.RefOf(autocannon).Key)); var sellerName = seller.Name; @@ -259,7 +275,7 @@ public sealed class RolesBackfillCommandTests : IDisposable }); db.Cache.Dispose(); - db = AetherDb.Open(root: _root); + db = AetherDb.OpenShipped(root: _root); try { var gaps = Program.RoleGaps(db.Cache, db.Cache.GetAll().ToArray(), db.Cache.GetAll().ToArray()).ToArray(); @@ -273,7 +289,7 @@ public sealed class RolesBackfillCommandTests : IDisposable [Fact] public void A_binned_seller_gains_no_roles_from_roles_migrate() { - var db = AetherDb.Open(catalogWritable: true, root: _root); + var db = AetherDb.OpenShipped(catalogWritable: true, root: _root); var autocannon = db.Cache.GetAll().Single(weapon => weapon.Name == "Autocannon"); var seller = db.Cache.GetAll().OrderBy(p => p.Name, StringComparer.Ordinal).First(p => p.Design.Key.Equals(db.Cache.RefOf(autocannon).Key)); var bin = new FactionProductData @@ -285,7 +301,7 @@ public sealed class RolesBackfillCommandTests : IDisposable db.Cache.Dispose(); Assert.Equal(0, Program.RolesMigrate(apply: true, root: _root)); - db = AetherDb.Open(root: _root); + db = AetherDb.OpenShipped(root: _root); try { Assert.Empty(db.Cache.GetAll().Single(p => p.Name == "Binned " + seller.Name).Roles); } finally { db.Cache.Dispose(); } } @@ -294,7 +310,7 @@ public sealed class RolesBackfillCommandTests : IDisposable [Fact] public void A_binned_seller_gains_no_roles_from_sensor_stat_set() { - var db = AetherDb.Open(catalogWritable: true, root: _root); + var db = AetherDb.OpenShipped(catalogWritable: true, root: _root); var sensor = db.Cache.GetAll().Where(d => d.Behaviors != null && d.Behaviors.OfType().Any()).OrderBy(d => d.Name, StringComparer.Ordinal).First(); var seller = db.Cache.GetAll().OrderBy(p => p.Name, StringComparer.Ordinal).First(p => p.Bin == null && p.Design.Key.Equals(db.Cache.RefOf(sensor).Key)); var bin = new FactionProductData @@ -306,7 +322,7 @@ public sealed class RolesBackfillCommandTests : IDisposable db.Cache.Dispose(); Assert.Equal(0, Program.SensorStatSet(apply: true, root: _root)); - db = AetherDb.Open(root: _root); + db = AetherDb.OpenShipped(root: _root); try { Assert.Empty(db.Cache.GetAll().Single(p => p.Name == "Binned " + seller.Name).Roles); } finally { db.Cache.Dispose(); } } @@ -315,7 +331,7 @@ public sealed class RolesBackfillCommandTests : IDisposable public void A_design_the_catalog_does_not_hold_refuses_and_lands_nothing() { Reset(flattened: false, unnamed: false); - var db = AetherDb.Open(catalogWritable: true, root: _root); + var db = AetherDb.OpenShipped(catalogWritable: true, root: _root); var autocannon = db.Cache.GetAll().Single(weapon => weapon.Name == "Autocannon"); autocannon.Name = "Autocannon (renamed)"; db.Cache.Commit(batch => batch.Upsert(typeof(WeaponItemData), autocannon, db.Cache.RefOf(autocannon).Key)); diff --git a/tests/Aetheria.Shared.Tests/RunGoalTests.cs b/tests/Aetheria.Shared.Tests/RunGoalTests.cs index cfdbdb158..c23ffef59 100644 --- a/tests/Aetheria.Shared.Tests/RunGoalTests.cs +++ b/tests/Aetheria.Shared.Tests/RunGoalTests.cs @@ -21,7 +21,7 @@ public sealed partial class RunStartTests private ZonePack BossZonePack(Galaxy galaxy, ItemManager items, GalaxyZone zone, bool ambient = true, uint seed = 7) { items.Random = new CultMath.Random(seed); - return ZoneGenerator.GenerateZone(items, _zoneSettings, _planetSettings, galaxy, zone, galaxy.IsPrelude, ambient); + return ZoneGenerator.GenerateZone(items, _zoneSettings, _planetSettings, galaxy, zone, entranceStations: EntranceStationOrder.Any, ambient); } private Zone ZoneOf(Galaxy galaxy, GalaxyZone zone) => @@ -414,6 +414,54 @@ public sealed partial class RunStartTests Assert.False(RunGoal.ExitOpen(ZoneOf(galaxy, zone))); } + // The gate belongs to the exit zone alone. A boss zone that is not the exit spawns its boss and loses it, and that zone's gate + // stays sealed: the exit check, not the boss mark, decides where a gate can open (a MainGalaxy choke-point boss zone is such a zone). + [Fact] + public void Exit_stays_sealed_in_a_non_exit_zone_whose_boss_died() + { + var galaxy = DemoGalaxy(1); + GiveAntagonistABoss(galaxy); + var other = galaxy.Zones.First(zone => zone != galaxy.Exit); + galaxy.BossZones[Zhestokost(galaxy)] = other; + + var zone = ZoneOf(galaxy, other); + Assert.True(zone.Pack.BossSpawned, "the fixture must spawn a boss outside the exit"); + var boss = Assert.Single(zone.Entities, entity => entity.IsBoss); + Assert.False(RunGoal.ExitOpen(zone)); + boss.HeatstrokeDeath.OnNext(Unit.Default); + Assert.False(RunGoal.BossAlive(zone)); + Assert.False(RunGoal.ExitOpen(zone), "a dead boss outside the exit zone opens no gate"); + } + + // The null-boss path through the real spawn loop: the boss zone is the exit, the faction's Loadout resolves, and + // Materialize cannot build it, so no boss is produced and the gate must not read as open. + // Both refusals (no Loadout, unbuildable Loadout) leave BossSpawned false. + [Fact] + public void A_refused_boss_leaves_the_exit_sealed_through_the_spawn_loop() + { + var galaxy = DemoGalaxy(1); + var loadout = GiveAntagonistABoss(galaxy); + var antagonist = Zhestokost(galaxy); + var exitZone = galaxy.Exit; + Assert.Equal(exitZone, galaxy.BossZones[antagonist]); + + // Unbuildable: the Loadout resolves and the entity is null. + loadout.Slots[0].Position = new int2(999, 999); + loadout.Slots[1].Position = new int2(998, 998); + StoreLoadout(loadout); + var unbuildable = ZoneOf(galaxy, exitZone); + Assert.False(unbuildable.Pack.BossSpawned); + Assert.DoesNotContain(unbuildable.Entities, entity => entity.IsBoss); + Assert.False(RunGoal.ExitOpen(unbuildable)); + + // Unresolved: the faction's Loadout is gone, so BossOf returns null. + antagonist.BossLoadout = new CultRecordRef(Loadouts.KeyOf("No Such Loadout")); + var unresolved = ZoneOf(galaxy, exitZone); + Assert.False(unresolved.Pack.BossSpawned); + Assert.DoesNotContain(unresolved.Entities, entity => entity.IsBoss); + Assert.False(RunGoal.ExitOpen(unresolved)); + } + // Continue: the mark is saved with the zone and restored, so a boss alive when the run was saved is alive after. [Fact] public void Boss_mark_survives_continue() diff --git a/tests/Aetheria.Shared.Tests/RunLaunchTests.cs b/tests/Aetheria.Shared.Tests/RunLaunchTests.cs new file mode 100644 index 000000000..1c8b0e380 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/RunLaunchTests.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using Xunit; + +// RunStart.Launch decides whether a start produced a run; the game scene halts on its answer (a failed start clears the +// galaxy, and a scene with no galaxy steps nothing). Kills: a start that throws or returns nothing reading as a run, a +// failure with no reason to show on the menu, a thrown exception that is neither logged nor listed, and a start that +// worked being reported failed. +public sealed class RunLaunchTests +{ + [Fact] + public void AStartThatThrowsIsNoRunAndSaysWhy() + { + var failures = new List(); + var logged = new List(); + var staged = RunStart.Launch(() => throw new InvalidOperationException("the arena would not generate"), failures, logged.Add); + Assert.Null(staged); + Assert.Equal(new[] { "the arena would not generate" }, failures); + Assert.Single(logged); + } + + [Fact] + public void AStartThatReturnsNothingIsNoRunAndKeepsItsOwnReasons() + { + var failures = new List(); + Assert.Null(RunStart.Launch(() => { failures.Add("player: the scenario places no player"); return null; }, failures)); + Assert.Equal(new[] { "player: the scenario places no player" }, failures); + } + + [Fact] + public void AStartThatReturnsNothingAndSaysNothingStillGivesAReason() + { + var failures = new List(); + Assert.Null(RunStart.Launch(() => null, failures)); + Assert.Single(failures); + } + + [Fact] + public void AStartThatStagedIsARunWithNoFailures() + { + var failures = new List(); + var made = new RunStart.Staged(); + Assert.Same(made, RunStart.Launch(() => made, failures)); + Assert.Empty(failures); + } +} diff --git a/tests/Aetheria.Shared.Tests/RunSaveTests.cs b/tests/Aetheria.Shared.Tests/RunSaveTests.cs index 545c1681a..3e7622fde 100644 --- a/tests/Aetheria.Shared.Tests/RunSaveTests.cs +++ b/tests/Aetheria.Shared.Tests/RunSaveTests.cs @@ -328,6 +328,95 @@ public sealed class RunSaveTests : IDisposable } } + // A simulation starts beside the saved run: while it lives the store holds the saved run and what the simulation + // wrote, and discarding it leaves exactly the saved run, which the next open still resumes. + [Fact] + public void ASimulationNeverTouchesTheSavedRun() + { + using (var cache = Open()) + RunSave.Commit(cache, Game(cache), Zones(3, StageZoneContents(cache), 0), new ProvenanceLedger()); + string[] saved; + using (var cache = Open()) + saved = RunKeys(cache); + + using (var cache = Open()) + { + var (started, simulation) = RunSave.Beside(cache, () => + { + WriteAnOrbitTheSavedRunLacks(cache); + return StageZoneContents(cache); + }); + Assert.NotNull(started); + Assert.Equal(saved.Length + 4, RunKeys(cache).Length); + Assert.All(saved, key => Assert.Contains(key, RunKeys(cache))); + simulation.Discard(cache); + Assert.Equal(saved, RunKeys(cache)); + } + using (var cache = Open()) + { + Assert.Equal(saved, RunKeys(cache)); + Assert.NotNull(cache.GetGlobal()); + } + } + + // A simulation that does not start, by returning nothing or by throwing, takes away only what it wrote. + [Fact] + public void AFailedSimulationTakesAwayOnlyWhatItWrote() + { + using (var cache = Open()) + RunSave.Commit(cache, Game(cache), Zones(3, StageZoneContents(cache), 0), new ProvenanceLedger()); + string[] saved; + using (var cache = Open()) + saved = RunKeys(cache); + + using (var cache = Open()) + { + var (started, simulation) = RunSave.Beside(cache, () => + { + WriteAnOrbitTheSavedRunLacks(cache); + return null; + }); + Assert.Null(started); + Assert.Null(simulation); + Assert.Equal(saved, RunKeys(cache)); + } + using (var cache = Open()) + { + Assert.Throws(() => RunSave.Beside(cache, () => + { + WriteAnOrbitTheSavedRunLacks(cache); + throw new InvalidOperationException("the arena would not generate"); + })); + Assert.Equal(saved, RunKeys(cache)); + } + using (var cache = Open()) + { + Assert.Equal(saved, RunKeys(cache)); + Assert.NotNull(cache.GetGlobal()); + } + } + + // A run started after a discarded simulation replaces the saved run and leaves nothing of the simulation behind. + [Fact] + public void ARunStartedAfterADiscardedSimulationReplacesOnlyTheSave() + { + using (var cache = Open()) + RunSave.Commit(cache, Game(cache), Zones(3, StageZoneContents(cache), 0), new ProvenanceLedger()); + + ZonePack started; + using (var cache = Open()) + { + RunSave.Beside(cache, () => StageZoneContents(cache)).simulation.Discard(cache); + started = RunSave.Replace(cache, () => StageZoneContents(cache)); + } + using (var cache = Open()) + { + Assert.Null(cache.GetGlobal()); + Assert.Equal(started.Orbits.Select(orbit => orbit.Key.Value).Concat(started.Planets.Select(body => body.Key.Value)) + .OrderBy(key => key, StringComparer.Ordinal), RunKeys(cache)); + } + } + private static string[] RunKeys(CultCache cache) => cache.AllStoredDocuments .Where(stored => RunSave.IsRunRecord(stored.Descriptor.DocumentType)) .Select(stored => stored.Key.Value) @@ -347,7 +436,7 @@ public sealed class RunSaveTests : IDisposable lots.Lots[2] = new Lot { Origin = new Attributed() }; lots.Lots[3] = new Lot { Origin = new Produced { Facility = 4, Inputs = new[] { 5 } } }; lots.Lots[4] = new Lot { Origin = new Attributed() }; - lots.Lots[5] = new Lot { Origin = new Extracted() }; + lots.Lots[5] = new Lot { Origin = new Attributed() }; lots.Lots[6] = new Lot { Origin = new Attributed() }; var child = BarePack(hull: null, dockingBayContents: new (int2, ItemInstance)[][] @@ -458,6 +547,7 @@ public sealed class RunSaveTests : IDisposable var game = new SavedGame { + InfluenceScale = 1, Factions = Array.Empty>(), Relationships = Array.Empty(), HomeZones = new Dictionary(), @@ -841,6 +931,7 @@ public sealed class RunSaveTests : IDisposable // HomeZones lists the factions in reverse of their saved order. private static SavedGame Game(CultCache cache, params Faction[] factions) => new SavedGame { + InfluenceScale = 1, Factions = factions.Select(f => cache.RefOf(f)).ToArray(), Relationships = factions.Select(_ => FactionRelationship.Neutral).ToArray(), HomeZones = factions.Select((_, i) => factions.Length - 1 - i).ToDictionary(i => i, _ => 0), diff --git a/tests/Aetheria.Shared.Tests/RunSeedFixture.cs b/tests/Aetheria.Shared.Tests/RunSeedFixture.cs index 0152584b7..2f4acf413 100644 --- a/tests/Aetheria.Shared.Tests/RunSeedFixture.cs +++ b/tests/Aetheria.Shared.Tests/RunSeedFixture.cs @@ -9,6 +9,7 @@ internal static class RunSeedFixture { var game = new SavedGame { + InfluenceScale = 1, Seed = seed, Factions = new CultRecordRef[0], Relationships = new FactionRelationship[0], diff --git a/tests/Aetheria.Shared.Tests/RunStartGearTests.cs b/tests/Aetheria.Shared.Tests/RunStartGearTests.cs index 2d0e1fb67..9abaae4a6 100644 --- a/tests/Aetheria.Shared.Tests/RunStartGearTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartGearTests.cs @@ -79,9 +79,9 @@ public sealed partial class RunStartTests } [Fact] - public void APreludeNoLongerOffersEverything() + public void ACastGalaxyNoLongerOffersEverything() { - Assert.True(_galaxy.IsPrelude); + Assert.Equal(.5f, _galaxy.InfluenceScale); var (absentProduct, _) = AbsentMaker("AbsentToPrelude"); var generator = GeneratorFor(_galaxy, "PreludeLoner"); Assert.False(generator.IsAvailable(absentProduct)); diff --git a/tests/Aetheria.Shared.Tests/RunStartTests.cs b/tests/Aetheria.Shared.Tests/RunStartTests.cs index efd17eb71..4dbb1cbc2 100644 --- a/tests/Aetheria.Shared.Tests/RunStartTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartTests.cs @@ -17,7 +17,7 @@ using float2 = CultMath.float2; using float3 = CultMath.float3; // RunStart owns what a new run starts with, and Zone.Admit is the one admission into a zone (docs/scenarios-cut.md, -// 2.2 and R). Every test stages into a real arena: the entrance zone of a prelude galaxy at a fixed seed, built from a +// 2.2 and R). Every test stages into a real arena: the entrance zone of a cast galaxy at a fixed seed, built from a // scratch copy of the catalog the game boots (TestCatalog) and the authored settings (Assets/Resources/Settings.asset). public sealed partial class RunStartTests : IDisposable { @@ -31,7 +31,6 @@ public sealed partial class RunStartTests : IDisposable private readonly PlanetSettings _planetSettings; private readonly string _startingHull; private readonly Faction _protagonist; - private readonly TutorialGenerationSettings _tutorialSettings; public RunStartTests() { @@ -49,10 +48,9 @@ public sealed partial class RunStartTests : IDisposable var authored = AuthoredSettings.Load(repo); _zoneSettings = authored.Read("ZoneSettings"); _planetSettings = authored.Read("PlanetSettings"); - var tutorial = _tutorialSettings = authored.Read("TutorialGenerationSettings"); - _galaxy = new Galaxy(tutorial, authored.Read("TutorialBackgroundSettings"), - _cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "Narrative")), _ => { }, null, GalaxySeed); + var tutorial = TestCasts.Wide; + _galaxy = new Galaxy(tutorial, authored.Read("CastBackgroundSettings"), + _cache, _ => { }, null, GalaxySeed); _items = new ItemManager(1u, _cache, new ProvenanceLedger(), RestoredHullsTests.PinnedFlight(authored.Read("GameplaySettings")), _ => { }); _protagonist = _galaxy.ResolveFaction(tutorial.ProtagonistFaction); @@ -125,11 +123,11 @@ public sealed partial class RunStartTests : IDisposable var background = authored.Read("SectorBackgroundSettings"); var sector = authored.Read("SectorGenerationSettings"); sector.ZoneCount = 8; - var tutorial = authored.Read("TutorialGenerationSettings"); + var tutorial = TestCasts.Wide; var main = Assert.Throws(() => new Galaxy(sector, background, _cache, _ => { }, null, 0)); var prelude = Assert.Throws(() => - new Galaxy(tutorial, background, _cache, new PlayerSettings(), new DirectoryInfo(_root), _ => { }, null, 0)); + new Galaxy(tutorial, background, _cache, _ => { }, null, 0)); foreach (var refusal in new[] { main, prelude }) { Assert.Equal("seed", refusal.ParamName); @@ -161,7 +159,7 @@ public sealed partial class RunStartTests : IDisposable public void EveryFactionsStationsCarryOnlyGearItCanReachIncludingAHeaterAndAReactor() { var galaxy = MainSectorGalaxy(); - Assert.False(galaxy.IsPrelude); + Assert.Equal(1f, galaxy.InfluenceScale); var zone = Arena(true); foreach (var faction in galaxy.Factions) { @@ -313,7 +311,10 @@ public sealed partial class RunStartTests : IDisposable .OrderBy(design => design.Shape.Coordinates.Length).ThenBy(design => design.Name, StringComparer.Ordinal).First(); var shape = new Shape(bay.Shape.Width + 2, bay.Shape.Height + 2); foreach (var cell in shape.AllCoordinates) shape[cell] = true; - var cramped = new HullData { Name = "Cramped Station", HullType = HullType.Station, Kind = TestStationKinds.TradeHub, Shape = shape, Durability = 100, Mass = 1000, Price = 1 }; + // A kind with no facilities: the shipped trade hub now seats a silo, which a hull this small has no Facility row for. + var bare = new CultRecordRef(StationKindData.KeyOf("cramped")); + _cache.Commit(batch => batch.Upsert(typeof(StationKindData), new StationKindData { Name = "Cramped" }, bare.Key)); + var cramped = new HullData { Name = "Cramped Station", HullType = HullType.Station, Kind = bare, Shape = shape, Durability = 100, Mass = 1000, Price = 1 }; _cache.Upsert(cramped); _cache.Upsert(new FactionProductData { @@ -323,7 +324,7 @@ public sealed partial class RunStartTests : IDisposable hull.Price = 0; // generation offers no zero-price design, so the cramped hull is the only station var generator = new LoadoutGenerator(ref _items.Random, _items, _galaxy, _galaxy.Entrance, _protagonist, .5f); - var failure = Assert.Throws(() => generator.GenerateStationLoadout(TestStationKinds.TradeHub)); + var failure = Assert.Throws(() => generator.GenerateStationLoadout(bare)); Assert.Contains("heater", failure.Message); } @@ -383,7 +384,8 @@ public sealed partial class RunStartTests : IDisposable public void GenerationOffersExactlyTheSoldGearSomeHullCanFit() { var hulls = LoadoutGenerator.SoldHulls(_cache); - var sold = _cache.GetAll().Where(p => p.Manufacturer.IsSet()).Select(p => p.Design.Key).ToHashSet(); + // Sold means on the market: a facility design's product is NotOffered, which no generation draws. + var sold = _cache.GetAll().Where(p => p.Manufacturer.IsSet() && LoadoutGenerator.IsOffered(_cache, p)).Select(p => p.Design.Key).ToHashSet(); var generator = PreludeGenerator(); var wrong = _cache.GetAll() .Where(design => sold.Contains(_cache.RefOf(design).Key) && design.Price > 0) diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index 7303931f0..dd866a4c8 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -17,7 +17,7 @@ using float2 = CultMath.float2; using float3 = CultMath.float3; // Scenarios S2 (docs/scenarios-cut.md, R): every new run is a scenario. The fixture is RunStartTests': a scratch copy -// of the shipped catalog, the authored settings and a prelude galaxy at a fixed seed. +// of the shipped catalog, the authored settings and a cast galaxy at a fixed seed. public sealed partial class RunStartTests { // A test's own scenario: a script given inline, staged into the fixture's arena or launched whole. @@ -33,7 +33,7 @@ public sealed partial class RunStartTests _ambient = ambient; _stage = stage; _seed = seed; - _generate = generate ?? (galaxy => galaxy.Prelude()); + _generate = generate ?? (stage => stage.Cast(TestCasts.Wide)); } public override string Name => "Scripted"; @@ -54,9 +54,8 @@ public sealed partial class RunStartTests return new GalaxyStage( authored.Read("SectorGenerationSettings"), authored.Read("SectorBackgroundSettings"), - authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), - _cache, new PlayerSettings(), Directory.CreateDirectory(Path.Combine(_root, "Narrative")), _ => { }, null, clock); + authored.Read("CastBackgroundSettings"), + _cache, _ => { }, null, clock); } // What MainMenu.Launch and StartGame do with a scenario: its galaxy, its arena, then staging. beforeStaging stands in @@ -67,14 +66,14 @@ public sealed partial class RunStartTests var arena = new Zone(_items, _planetSettings, RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, galaxy, scenario), galaxy.Entrance, galaxy); beforeStaging?.Invoke(); var failures = new List(); - var staged = RunStart.Stage(_items, arena, scenario, _startingHull, _tutorialSettings, failures); + var staged = RunStart.Stage(_items, arena, scenario, _startingHull, failures); return (galaxy, arena, staged, failures); } private RunStart.Staged Stage(Zone zone, Scenario scenario) { var failures = new List(); - var staged = RunStart.Stage(_items, zone, scenario, _startingHull, _tutorialSettings, failures); + var staged = RunStart.Stage(_items, zone, scenario, _startingHull, failures); Assert.True(failures.Count == 0, string.Join("; ", failures)); Assert.NotNull(staged); return staged; @@ -86,7 +85,7 @@ public sealed partial class RunStartTests var entities = zone.Entities.ToList(); var agents = zone.Agents.ToList(); var failures = new List(); - Assert.Null(RunStart.Stage(_items, zone, scenario, _startingHull, _tutorialSettings, failures)); + Assert.Null(RunStart.Stage(_items, zone, scenario, _startingHull, failures)); SafeAssert.Unchanged(zone, entities, agents); return failures; } @@ -123,32 +122,46 @@ public sealed partial class RunStartTests Assert.Equal(1234, poor.Credits); } - // The two game modes are what New Game did: the tutorial a prelude galaxy and a starting-hull ship of the - // protagonist faction at the entrance's origin; the main galaxy a main galaxy and a starting-hull ship there. Both - // arenas keep their generated ships. + // The two game modes are what New Game did: the demo a cast galaxy at half influence and a starting-hull ship at the + // entrance's origin; the main galaxy a main galaxy at full influence and a starting-hull ship there. Both arenas + // keep their generated ships. [Fact] public void ModesMatchOldNewGame() { Assert.Equal("Longinus", _startingHull); - var tutorial = Launch(new TutorialGalaxy(), Inputs(() => GalaxySeed)); - Assert.Empty(tutorial.failures); - Assert.True(tutorial.galaxy.IsPrelude, "the tutorial is a prelude galaxy"); - Assert.Equal(_startingHull, tutorial.staged.Player.HullData.Name); - Assert.Same(tutorial.galaxy.ResolveFaction(_tutorialSettings.ProtagonistFaction), tutorial.staged.Player.Faction); - Assert.Equal(float3.zero, tutorial.staged.Player.Position); - Assert.Empty(tutorial.staged.Entities); - Assert.Contains(tutorial.arena.Pack.Entities, entity => entity is ShipPack { IsPlayerShip: false }); + var demo = Launch(new DemoTerminus(), Inputs(() => GalaxySeed)); + Assert.Empty(demo.failures); + Assert.Equal(.5f, demo.galaxy.InfluenceScale); + Assert.Equal(_startingHull, demo.staged.Player.HullData.Name); + Assert.Equal(float3.zero, demo.staged.Player.Position); + // The demo places one ship besides the player: Zenith's hauler, which carries the standing haul order (cut ore-haul-run). + Assert.True(Assert.Single(demo.staged.Entities).Haul.Key.IsSet()); + Assert.Contains(demo.arena.Pack.Entities, entity => entity is ShipPack { IsPlayerShip: false }); var main = Launch(new MainGalaxy(), Inputs(() => GalaxySeed)); Assert.Empty(main.failures); - Assert.False(main.galaxy.IsPrelude, "the main galaxy is not a prelude"); + Assert.Equal(1f, main.galaxy.InfluenceScale); Assert.Equal(_startingHull, main.staged.Player.HullData.Name); Assert.Equal(float3.zero, main.staged.Player.Position); Assert.Empty(main.staged.Entities); Assert.Contains(main.arena.Pack.Entities, entity => entity is ShipPack { IsPlayerShip: false }); } + // New Game boots Nibu's simulation, which is never saved; the run its exit launches is a development entry, and + // every other scenario is a run that saves. + [Fact] + public void InfiniteFunLandIsASimulation() + { + Assert.False(Scenarios.Simulation.Saved); + Assert.False(Scenarios.Simulation.Ambient); + Assert.NotEqual(0u, Scenarios.Simulation.Seed); + Assert.Equal(new[] { Scenarios.Simulation }, Scenarios.Modes); + Assert.Contains(Scenarios.Terminus, Scenarios.Development); + Assert.All(Scenarios.Modes.Concat(Scenarios.Development).Concat(Scenarios.Tests).Where(scenario => scenario != Scenarios.Simulation), + scenario => Assert.True(scenario.Saved, scenario.Id)); + } + // Everything a galaxy's layout fixes: each zone's name, position, owner, factions and links, the homes, the // entrance, the exit and the background. private static string Layout(Galaxy galaxy) => @@ -209,12 +222,12 @@ public sealed partial class RunStartTests Assert.NotEqual(Layout(a), Layout(b)); } - // Generating a galaxy writes nothing a later one reads: a prelude leaves the catalog's faction influence as authored. + // Generating a galaxy writes nothing a later one reads: a cast galaxy leaves the catalog's faction influence as authored. [Fact] public void AGalaxyLeavesTheCatalogsFactionsAsAuthored() { var authored = _cache.GetAll().ToDictionary(faction => faction, faction => faction.InfluenceDistance); - RunStart.Generate(new TutorialGalaxy(), Inputs()); + RunStart.Generate(new DemoTerminus(), Inputs()); RunStart.Generate(new MainGalaxy(), Inputs()); Assert.All(authored, pair => Assert.Equal(pair.Value, pair.Key.InfluenceDistance)); } @@ -222,7 +235,7 @@ public sealed partial class RunStartTests // Every zone is linked into one graph. These seeds left zones with no link at all (the vendored float-precision // convex-hull triangulation dropped them), so the constructor threw KeyNotFoundException placing homes (prelude) // or the entrance (main). Each galaxy's links are a subset of its zone positions' Delaunay edges, and the - // triangulation agrees with a brute-force empty-circumcircle oracle. + // triangulation agrees with DelaunayTests' exact empty-circumcircle oracle. [Theory] [InlineData(103u, true)] [InlineData(134u, true)] @@ -233,12 +246,12 @@ public sealed partial class RunStartTests [InlineData(34u, false)] public void EveryZoneIsLinked(uint seed, bool prelude) { - var galaxy = RunStart.Generate(new Scripted(true, _ => { }, seed, stage => prelude ? stage.Prelude() : stage.Main()), Inputs()); + var galaxy = RunStart.Generate(new Scripted(true, _ => { }, seed, stage => prelude ? stage.Cast(TestCasts.Wide) : stage.Main()), Inputs()); Assert.All(galaxy.Zones, zone => Assert.Equal(galaxy.Zones.Length, zone.Distance.Count)); var positions = galaxy.Zones.Select(zone => zone.Position).ToArray(); var edges = Delaunay.Edges(positions); - Assert.Equal(BruteForceDelaunay(positions), edges); + DelaunayTests.AssertDelaunay(positions, $"seed {seed}"); var delaunay = new HashSet<(int, int)>(edges); for (var i = 0; i < galaxy.Zones.Length; i++) foreach (var adjacent in galaxy.Zones[i].AdjacentZones) @@ -248,36 +261,6 @@ public sealed partial class RunStartTests } } - // Every triangle whose circumcircle holds no other point, as sorted edges. - private static List<(int a, int b)> BruteForceDelaunay(float2[] points) - { - var edges = new SortedSet<(int a, int b)>(); - for (var i = 0; i < points.Length; i++) - for (var j = i + 1; j < points.Length; j++) - for (var k = j + 1; k < points.Length; k++) - { - double ax = points[i].x, ay = points[i].y, bx = points[j].x, by = points[j].y, cx = points[k].x, cy = points[k].y; - var d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)); - if (d == 0) continue; - double a2 = ax * ax + ay * ay, b2 = bx * bx + by * by, c2 = cx * cx + cy * cy; - var ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d; - var uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d; - var r2 = (ax - ux) * (ax - ux) + (ay - uy) * (ay - uy); - var empty = true; - for (var m = 0; m < points.Length && empty; m++) - if (m != i && m != j && m != k) - { - double dx = points[m].x - ux, dy = points[m].y - uy; - empty = dx * dx + dy * dy >= r2; - } - if (!empty) continue; - edges.Add((i, j)); - edges.Add((j, k)); - edges.Add((i, k)); - } - return edges.ToList(); - } - // A scenario naming one unknown design admits nothing, not even the parts that built, and names the design. [Fact] public void StagingIsAllOrNothing() @@ -401,6 +384,142 @@ public sealed partial class RunStartTests Assert.Equal(0, AgentsOf(zone, neutral)); } + // A summon places into a running zone through the stage's admission (ruling ifl-ships-in-demo-as-tactical-view): after a run + // has started and stepped, a piloted generated ship that approaches the player is a member with one agent, and its pilot + // knows the player by the sensors' own path. It holds no stance either way (ruling summons-follow-faction-logic: the faction + // rule decides). Kills: a summon that skips the pilot or the knowledge seed, or that writes any override. + [Fact] + public void ASummonJoinsARunningZone() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + for (var tick = 0; tick < 20; tick++) zone.Update(.1f); + + var failures = new List(); + var summoned = ZoneStage.Summon(_items, zone, stage => + { + var placed = stage.Place(stage.Generated("Longinus"), float2(400, 0), piloted: true); + stage.Approach(placed, player); + }, failures); + + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var raider = Assert.Single(summoned); + SafeAssert.In(zone, raider, "the summoned ship is admitted"); + Assert.Equal(1, AgentsOf(zone, raider)); + Assert.Null(raider.IffOverride(player)); + Assert.Null(player.IffOverride(raider)); + Assert.Equal((_items.GameplaySettings.TargetDetectionInfoThreshold + 1f) / 2f, raider.EntityInfoGathered[player]); + for (var tick = 0; tick < 20; tick++) zone.Update(.1f); + Assert.Equal(1, AgentsOf(zone, raider)); + } + + // A summon writes no pin, so the grudge a provocation raises still lands (an override already held is never replaced: + // Entity.Provoke). Kills: any stance written at summon, which blocks the formation from fighting back. + [Fact] + public void ASummonedShipAnswersAProvocation() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var failures = new List(); + var placed = Assert.Single(ZoneStage.Summon(_items, zone, stage => + stage.Place(stage.Generated("Longinus"), float2(400, 0), piloted: true), failures)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + + placed.Provoke(player); + + Assert.True(placed.IsHostileTo(player), "a provoked summon did not turn on its attacker"); + } + + // A run-start script's Hostile is the only authored stance: written both ways with the player. Neutral is the absence of + // an override, not a pin to false. Kills: Neutral writing false; a Hostile written one way only. + [Fact] + public void ANeutralPlacementWritesNoOverride() + { + var staged = Stage(Arena(true), new Scripted(true, stage => + { + stage.Player(stage.Bare("Djinni"), float2(0, 0)); + stage.Place(stage.Generated("Longinus"), float2(300, 0), stance: ScenarioStance.Hostile, piloted: true); + stage.Place(stage.Bare("Longinus"), float2(-300, 0), stance: ScenarioStance.Neutral); + })); + var player = staged.Player; + var hostile = staged.Entities[0]; + var neutral = staged.Entities[1]; + + Assert.Null(neutral.IffOverride(player)); + Assert.Null(player.IffOverride(neutral)); + Assert.True(hostile.IffOverride(player) == true && player.IffOverride(hostile) == true, "hostile both ways"); + } + + // A summon naming a design the catalog lacks admits nothing, and names it. Kills: admitting before the failure check. + [Fact] + public void ARefusedSummonAdmitsNothing() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var entities = zone.Entities.ToList(); + var agents = zone.Agents.ToList(); + var failures = new List(); + + var summoned = ZoneStage.Summon(_items, zone, stage => + { + stage.Place(stage.Generated("Longinus"), float2(400, 0), piloted: true); + stage.Place(stage.Bare("No Such Hull"), float2(-400, 0)); + }, failures); + + Assert.Null(summoned); + Assert.Contains(failures, failure => failure.Contains("No Such Hull")); + SafeAssert.Unchanged(zone, entities, agents); + } + + // A refused summon leaves the item stream and the lot ledger (which a run save persists) where they were, so a refusal is neither + // a draw nor a mint. Kills: a summon that keeps the draws or the lots of the fits it built before refusing. + [Fact] + public void ARefusedSummonLeavesTheItemStream() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var before = _items.Random; + var nextLot = _items.Lots.NextLot; + var lots = _items.Lots.Lots.Keys.ToList(); + var failures = new List(); + + Assert.Null(ZoneStage.Summon(_items, zone, stage => + { + stage.Place(stage.Generated("Longinus"), float2(400, 0)); + stage.Place(stage.Bare("No Such Hull"), float2(-400, 0)); + }, failures)); + + var after = _items.Random; + Assert.Equal(before.NextUInt(), after.NextUInt()); + Assert.Equal(nextLot, _items.Lots.NextLot); + Assert.Equal(lots.OrderBy(id => id), _items.Lots.Lots.Keys.OrderBy(id => id)); + } + + // A faction's boss is the zone generator's to place (boss-hulls-exclusive): a preset naming the loadout Loadouts.BossOf + // returns is refused, through a summon as through a run start. Kills: a Preset that places any catalog loadout. + [Fact] + public void APresetCannotPlaceAFactionsBoss() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var boss = _cache.GetAll().Select(faction => Loadouts.BossOf(_cache, faction, out _)).First(loadout => loadout != null); + var entities = zone.Entities.ToList(); + var agents = zone.Agents.ToList(); + var failures = new List(); + + Assert.Null(ZoneStage.Summon(_items, zone, stage => + stage.Place(stage.Preset(boss.Name), float2(400, 0), piloted: true), failures)); + + Assert.Contains(failures, failure => failure.Contains(boss.Name) && failure.Contains("boss")); + SafeAssert.Unchanged(zone, entities, agents); + var started = Refused(Arena(true), new Scripted(true, stage => + { + stage.Player(stage.Bare("Djinni"), float2(0, 0)); + stage.Place(stage.Preset(boss.Name), float2(400, 0)); + })); + Assert.Contains(started, failure => failure.Contains("boss")); + } + // A stance lasts the sitting: the player docking and undocking leaves it standing both ways. It goes with an entity // gone for good: once an entity is destroyed, the player holds no stance toward it. [Fact] @@ -438,7 +557,7 @@ public sealed partial class RunStartTests public void UndockingAdmitsWithNoAgent() { var zone = Arena(true); - var player = Stage(zone, new TutorialGalaxy()).Player; + var player = Stage(zone, new Scripted(false, stage => stage.Player(stage.Generated(stage.StartingHull), float2(0, 0)))).Player; var station = zone.Entities.First(entity => entity is OrbitalEntity && entity.DockingBays.Count > 0); var agents = zone.Agents.Count; @@ -617,18 +736,81 @@ public sealed partial class RunStartTests Assert.Empty(UnsoldAndUnplaced(runs)); } - // Whether a run is the prelude is the galaxy's fact (Galaxy.IsPrelude); a save records it with no second owner. + // How far influence reaches is the galaxy's fact (Galaxy.InfluenceScale); a save records it with no second owner, and + // a save without one (written before it existed) is refused by name rather than read as full influence. [Fact] - public void SaveReadsPrelude() + public void InfluenceScaleRoundTripsAndOldSavesAreRefused() { var arena = Arena(true); - var (prelude, _) = RunSave.Capture(_cache, _galaxy, arena, null, new SavedActionBarBinding[0], 0); - Assert.True(prelude.IsTutorial); - + var (demo, _) = RunSave.Capture(_cache, _galaxy, arena, null, new SavedActionBarBinding[0], 0); + Assert.Equal(.5f, demo.InfluenceScale); var (main, _) = RunSave.Capture(_cache, MainSectorGalaxy(), arena, null, new SavedActionBarBinding[0], 0); - Assert.False(main.IsTutorial); + Assert.Equal(1f, main.InfluenceScale); + + var old = Assert.Throws(() => new Galaxy(_cache, new SavedGame + { + Zones = demo.Zones, Factions = demo.Factions, HomeZones = demo.HomeZones, BossZones = demo.BossZones, + Entrance = demo.Entrance, Exit = demo.Exit, DiscoveredZones = demo.DiscoveredZones, Background = demo.Background, + Relationships = demo.Relationships, Standings = demo.Standings, Seed = demo.Seed, + InfluenceScale = 0, + }, _ => { })); + Assert.Contains(nameof(SavedGame.InfluenceScale), old.Message); } + // The halving is the cast's: InfluenceOf scales a faction's authored distance by the galaxy's InfluenceScale, rounding up. + [Fact] + public void InfluenceOfMatchesTheHalving() + { + var half = _galaxy; + var full = MainSectorGalaxy(); + var faction = _cache.GetAll().First(); + var authored = faction.InfluenceDistance; + try + { + for (var distance = 0; distance <= 10; distance++) + { + faction.InfluenceDistance = distance; + Assert.Equal((distance + 1) / 2, half.InfluenceOf(faction)); + Assert.Equal(distance, full.InfluenceOf(faction)); + } + } + finally { faction.InfluenceDistance = authored; } + } + + // Whether the arena gets a forced entrance station is the scenario's declaration, not the galaxy's. At a seed whose + // natural roll is zero stations, a scenario declaring one gets a docking station and the same arena generated without + // the declaration gets none. + [Fact] + public void EntranceStationIsTheScenariosDeclaration() + { + Assert.Equal(new[] { ("Aero", "trade-hub"), ("Pirates", "processing") }, + new DemoTerminus().EntranceStations.Select(order => (order.Faction, order.Kind))); + Assert.Empty(new MainGalaxy().EntranceStations); + + var natural = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, _galaxy, _galaxy.Entrance, entranceStations: EntranceStationOrder.None, ambient: false); + var forced = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, _galaxy, _galaxy.Entrance, entranceStations: EntranceStationOrder.Any, ambient: false); + Assert.Equal(0, StationsOf(natural)); + Assert.True(StationsOf(forced) >= 1); + + // Through RunStart, the scenario's declaration is what reaches the generator: the demo, in its own galaxy (the fixture's cast has + // no Pirates), holds both stations. + var (_, demoArena, _, failures) = Launch(new DemoTerminus()); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + Assert.Equal(2, demoArena.Entities.OfType().Count(entity => entity.HullData.HullType == HullType.Station)); + Assert.Equal(0, StationsOf(RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new MainGalaxy()))); + + // An order the galaxy or the catalog cannot meet is refused by name, never placed as something else. + var badFaction = Assert.Throws(() => ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, _galaxy, + _galaxy.Entrance, new[] { new EntranceStationOrder("Nonesuch", null) }, ambient: false)); + Assert.Contains("Nonesuch", badFaction.Message); + var badKind = Assert.Throws(() => ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, _galaxy, + _galaxy.Entrance, new[] { new EntranceStationOrder(null, "nowhere") }, ambient: false)); + Assert.Contains("nowhere", badKind.Message); + } + + private int StationsOf(ZonePack pack) => + pack.Entities.OfType().Count(entity => (_cache.Get(entity.Hull.Data) as HullData)?.HullType == HullType.Station); + // PlayerSettings Key 2, the never-written tutorial flag, is retired: a player.cc written with it still loads, every other field intact. [Fact] public void OldPlayerSettingsLoad() @@ -672,4 +854,39 @@ public sealed partial class RunStartTests stale.Add(scenario.Name + " names " + retired); Assert.True(stale.Count == 0, "scenario briefs naming gear the catalog no longer has: " + string.Join("; ", stale)); } + + // The ruling's played case: nothing but the catalog's Relations makes two NPC factions fight. Two piloted ships of the cast's + // Zhe and Luc sit 400 apart in the arena; with Luc's record Hated toward Zhe the Zhestokost ship is hit or gone inside 60 s, + // and without it both keep full armor. Kills: no Hated branch; the relation read from the wrong side; a scenario stance doing + // the work. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void TwoFactionsFightByRelationAlone(bool hated) + { + var zhe = _galaxy.ResolveFaction("Zhe"); + var luc = _galaxy.ResolveFaction("Luc"); + if (hated) + { + luc.Relations ??= new Dictionary, FactionRelationship>(); + luc.Relations[_cache.RefOf(zhe)] = FactionRelationship.Hated; + } + Entity zheShip = null, lucShip = null; + var (_, arena, _, failures) = Launch(new Scripted(false, stage => + { + stage.Player(stage.Bare("Djinni"), float2(0, 0)); + zheShip = stage.Place(stage.Generated("Longinus", zhe), float2(2000, 0), piloted: true); + lucShip = stage.Place(stage.Generated("Longinus", luc), float2(2000, 400), piloted: true); + })); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + Assert.Same(zhe, zheShip.Faction); + Assert.Same(luc, lucShip.Faction); + + for (var tick = 0; tick < 600; tick++) arena.Update(.1f); + + bool Intact(Entity ship) => arena.Entities.Contains(ship) && + ship.Armor.Cast().Sum() >= ship.MaxArmor.Cast().Sum(); + Assert.Equal(!hated, Intact(zheShip)); + if (!hated) Assert.True(Intact(lucShip)); + } } diff --git a/tests/Aetheria.Shared.Tests/ShieldCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShieldCatalogTests.cs new file mode 100644 index 000000000..de33ec69f --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShieldCatalogTests.cs @@ -0,0 +1,51 @@ +using System.Linq; +using GameCult.Caching; +using Xunit; + +// The shields the catalog sells (campaign aetheria-release, cut hardpoint-fit-1; rulings hardpoint-sizes-are-footprint-palette, +// catalog-grows-generic-designs-branded-products): a light 1x1 and a heavy 2x2 projector, each with a product a maker offers, and +// the fit they give the mounts the game boots. Prices and stats are starting knobs, so none is pinned here. +public sealed class ShieldCatalogTests +{ + private static GearData Design(CultCache cache, string name) => Assert.Single(cache.GetAll(), g => g.Name == name); + + private static FactionProductData[] Offered(CultCache cache, GearData design) => + cache.GetAll().Where(p => p.Design.Key.Equals(cache.RefOf(design).Key) && !p.NotOffered).ToArray(); + + [Theory] + [InlineData(ShieldCatalog.Light, 1)] + [InlineData(ShieldCatalog.Heavy, 2)] + public void EachProjectorIsAShieldOfItsFootprintWithAnOfferedProduct(string name, int size) + { + using var cache = RestoredHullsTests.OpenCatalog(); + var design = Design(cache, name); + Assert.Equal(HardpointType.Shield, design.Hardpoint); + Assert.Equal((size, size), (design.Shape.Width, design.Shape.Height)); + Assert.Equal(size * size, design.Shape.Coordinates.Length); + var shield = Assert.Single(design.Behaviors.OfType()); + Assert.True(shield.Capacity.Min > 0f && shield.Capacity.Max > 0f, "a shield with no capacity breaks on its first hit"); + Assert.NotEmpty(Offered(cache, design)); + } + + [Fact] + public void MegiddoSellsTheHeavyProjector() + { + using var cache = RestoredHullsTests.OpenCatalog(); + Assert.Contains(Offered(cache, Design(cache, ShieldCatalog.Heavy)), p => cache.Get(p.Manufacturer).ShortName == "Megiddo"); + } + + // Loose fit: the light projector serves a 1x1 shield mount, the heavy one fills every 2x2 shield mount of the booted hulls. + [Fact] + public void TheProjectorsFitTheMountsTheGameBoots() + { + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); + var light = Design(cache, ShieldCatalog.Light); + var heavy = Design(cache, ShieldCatalog.Heavy); + var mounts = cache.GetAll().SelectMany(h => h.Hardpoints).Where(m => m.Type == HardpointType.Shield).ToArray(); + Assert.Contains(mounts, m => m.Shape.Coordinates.Length == 1); + Assert.Contains(mounts, m => m.Shape.Coordinates.Length == 4); + Assert.All(mounts, m => Assert.True(m.Takes(light) || m.Takes(heavy))); + Assert.All(mounts.Where(m => m.Shape.Coordinates.Length == 1), m => Assert.True(m.Takes(light) && !m.Takes(heavy))); + Assert.All(mounts.Where(m => m.Shape.Coordinates.Length == 4), m => Assert.True(m.IsFilledBy(heavy) && m.Takes(light))); + } +} diff --git a/tests/Aetheria.Shared.Tests/ShipAuthoringPushTests.cs b/tests/Aetheria.Shared.Tests/ShipAuthoringPushTests.cs new file mode 100644 index 000000000..38ee11501 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipAuthoringPushTests.cs @@ -0,0 +1,674 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using MessagePack; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using Newtonsoft.Json.Linq; +using Xunit; + +// ship-authoring open and push (AetherDb): one request vocabulary, dry run by default, apply under a per-record version +// check that refuses a stale record. These call ShipAuthoringPush directly with readers and writers, as the add-on's pipe does. +[Collection("process working directory")] +public sealed class ShipAuthoringPushTests : IDisposable +{ + private readonly TempDirectory _root = new TempDirectory(); + private readonly string _previous = Environment.CurrentDirectory; + private string Mods => Path.Combine(_root.Path, "GameData", "Mods"); + + public ShipAuthoringPushTests() + { + Directory.CreateDirectory(Mods); + Environment.CurrentDirectory = _root.Path; + } + + public void Dispose() + { + Environment.CurrentDirectory = _previous; + _root.Dispose(); + } + + // A valid package with an element-id-carrying thruster row (Row set), a gun, and the fixture's line. + private string Package(string id = "mod.skiff") => + Path.Combine(ShipFixture.WritePackage(Mods, id, tweak: ship => ship.Hull.Hardpoints[0].Row = "port-row"), "ship.cc"); + + private static string Open(string path) + { + var output = new StringWriter(); + Assert.Equal(0, ShipAuthoringPush.Open(path, output)); + return output.ToString(); + } + + private static (int Code, string[] Lines, JObject Outcome) Push(string path, string request, bool apply = false) + { + var output = new StringWriter(); + var code = ShipAuthoringPush.Push(path, new StringReader(request), apply, output); + var lines = output.ToString().Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(line => line.TrimEnd('\r')).ToArray(); + return (code, lines.Take(lines.Length - 1).ToArray(), Parse(lines.Last())); + } + + // Versions are strings; the default reader would turn them into dates and write them back reformatted. + private static JObject Parse(string text) + { + using var reader = new Newtonsoft.Json.JsonTextReader(new StringReader(text)) { DateParseHandling = Newtonsoft.Json.DateParseHandling.None }; + return JObject.Load(reader); + } + + private static string Edit(string request, Action change) + { + var json = Parse(request); + change(json); + return json.ToString(); + } + + private static string[] Listing(string path) => Directory.GetFiles(Path.GetDirectoryName(path)).Select(Path.GetFileName).OrderBy(name => name, StringComparer.Ordinal).ToArray(); + + private static byte[] Pack(T value) => MessagePackSerializer.Serialize(value, CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly)); + + private static JToken Hardpoint(JObject request, string mount) => request["layout"]["hardpoints"].First(row => (string)row["mount"] == mount); + + // Moves the gun, retargets an anchor and drops the line: the three changes the dry run and the apply must agree on. + private static string ThreeChanges(string request) => Edit(request, json => + { + Hardpoint(json, "gun")["cell"] = new JArray(1, 1); + json["visual"]["anchors"].First(anchor => (string)anchor["id"] == "map")["node"] = "collider"; + json["lines"] = new JArray(); + }); + + [Fact] + public void OpenThenPushIsNoChange() + { + var copy = Path.Combine(_root.Path, "nakovalnya"); + Directory.CreateDirectory(copy); + foreach (var file in Directory.GetFiles(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Mods", "aetheria.nakovalnya"))) + File.Copy(file, Path.Combine(copy, Path.GetFileName(file))); + foreach (var path in new[] { Package(), Path.Combine(copy, "ship.cc") }) + { + var request = Open(path); + var before = File.ReadAllBytes(path); + var files = Listing(path); + foreach (var apply in new[] { false, true }) + { + var (code, changes, outcome) = Push(path, request, apply); + Assert.Equal(0, code); + Assert.Empty(changes); + Assert.Equal(apply ? "applied" : "dry-run", (string)outcome["outcome"]); + Assert.Empty(outcome["changed"]); + Assert.Equal(before, File.ReadAllBytes(path)); + Assert.Equal(files, Listing(path)); + } + } + } + + [Fact] + public void DryRunWritesNothing() + { + var path = Package(); + var request = ThreeChanges(Open(path)); + var before = File.ReadAllBytes(path); + var files = Listing(path); + var (code, changes, outcome) = Push(path, request); + Assert.True(code == 0, outcome.ToString()); + Assert.Equal("dry-run", (string)outcome["outcome"]); + Assert.Equal(3, changes.Length); + Assert.Contains(changes, line => line.StartsWith("mod-hull:mod.skiff hardpoint[") && line.EndsWith("cell: 0,0 -> 1,1")); + Assert.Contains(changes, line => line == "mod-ship:mod.skiff anchor[map] node: map -> collider"); + Assert.Contains(changes, line => line.StartsWith("mod-ship:mod.skiff line[") && line.EndsWith("removed")); + Assert.Equal(before, File.ReadAllBytes(path)); + Assert.Equal(files, Listing(path)); + } + + // An anchor the request adds is a whole anchor: the Id is the one the validator and the node binding read. + [Fact] + public void AnAddedAnchorKeepsItsId() + { + var path = Package(); + var request = Edit(Open(path), json => ((JArray)json["visual"]["anchors"]).Add( + new JObject { ["id"] = "extra", ["role"] = "map-icon", ["node"] = "extra", ["parent"] = null, ["order"] = 0 })); + var (code, changes, outcome) = Push(path, request, apply: true); + Assert.True(code == 0, outcome.ToString()); + Assert.Contains("mod-ship:mod.skiff anchor[extra] added", changes); + Assert.Contains(Parse(Open(path))["visual"]["anchors"], anchor => (string)anchor["id"] == "extra"); + } + + [Fact] + public void ApplyWritesTheDryRunResult() + { + var path = Package(); + var opened = Open(path); + var request = ThreeChanges(opened); + var (_, dryChanges, _) = Push(path, request); + var (code, changes, outcome) = Push(path, request, apply: true); + Assert.Equal(0, code); + Assert.Equal("applied", (string)outcome["outcome"]); + Assert.Equal(dryChanges, changes); + + var reopened = Parse(Open(path)); + var gun = Hardpoint(reopened, "gun"); + Assert.Equal(new[] { 1, 1 }, gun["cell"].Select(cell => (int)cell)); + Assert.Equal((string)Hardpoint(Parse(opened), "gun")["element"], (string)gun["element"]); + Assert.Equal("collider", (string)reopened["visual"]["anchors"].First(anchor => (string)anchor["id"] == "map")["node"]); + Assert.Empty(reopened["lines"]); + // The thruster was not touched: its element id and the Row no section authors survive. + var thruster = ShipAuthoringStore.Load(path).Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "thruster.port"); + Assert.Equal("port-row", thruster.Row); + Assert.Equal((string)Hardpoint(Parse(opened), "thruster.port")["element"], thruster.Id); + Assert.Equal(reopened["versions"].ToString(), outcome["versions"].ToString()); + Assert.Equal(new[] { "mod-hull:mod.skiff", "mod-ship:mod.skiff" }, outcome["changed"].Select(key => (string)key).OrderBy(key => key, StringComparer.Ordinal)); + } + + [Fact] + public void StaleVersionRefused() + { + var path = Package(); + var request = ThreeChanges(Open(path)); + // stats is a builder over the push core: it writes the hull record alone, so the ship record is still current. + var stats = ConsoleProbe.Capture(() => ShipAuthoringCommands.Run(new[] { "stats", path, "--mass", "1" }), out _, out var statsError); + Assert.True(stats == 0, statsError); + var after = File.ReadAllBytes(path); + var (code, _, outcome) = Push(path, request, apply: true); + Assert.Equal(2, code); + Assert.Equal("stale", (string)outcome["outcome"]); + Assert.Equal(new[] { "mod-hull:mod.skiff" }, outcome["stale"].Select(key => (string)key).OrderBy(key => key, StringComparer.Ordinal)); + Assert.Equal(after, File.ReadAllBytes(path)); + } + + [Fact] + public void ElementMatching() + { + var path = Package(); + var request = Open(path); + var thruster = (string)Hardpoint(Parse(request), "thruster.port")["element"]; + + var added = Edit(request, json => + { + var row = (JObject)Hardpoint(json, "gun").DeepClone(); + row["element"] = ""; + row["mount"] = "gun.second"; + row["cell"] = new JArray(1, 1); + ((JArray)json["layout"]["hardpoints"]).Add(row); + // The one with no element is the only change that mints; the gun's own row stays. + }); + Assert.Equal(0, Push(path, added, apply: true).Code); + var hull = ShipAuthoringStore.Load(path).Hull; + Assert.Equal(3, hull.Hardpoints.Count); + var second = hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "gun.second"); + Assert.False(string.IsNullOrEmpty(second.Id)); + Assert.Equal(3, hull.Hardpoints.Select(hardpoint => hardpoint.Id).Distinct().Count()); + + var removed = Edit(Open(path), json => ((JArray)json["layout"]["hardpoints"]).First(row => (string)row["mount"] == "gun.second").Remove()); + Assert.Equal(0, Push(path, removed, apply: true).Code); + Assert.DoesNotContain(ShipAuthoringStore.Load(path).Hull.Hardpoints, hardpoint => hardpoint.Transform == "gun.second"); + + var renamed = Edit(Open(path), json => Hardpoint(json, "thruster.port")["mount"] = "thruster.renamed"); + var (code, changes, _) = Push(path, renamed, apply: true); + Assert.Equal(0, code); + Assert.Equal($"mod-hull:mod.skiff hardpoint[{thruster}] mount: thruster.port -> thruster.renamed", Assert.Single(changes)); + Assert.Equal(thruster, ShipAuthoringStore.Load(path).Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "thruster.renamed").Id); + + var before = File.ReadAllBytes(path); + var unknown = Edit(Open(path), json => Hardpoint(json, "gun")["element"] = "000000000000"); + var refused = Push(path, unknown, apply: true); + Assert.Equal(1, refused.Code); + Assert.Contains("000000000000", (string)refused.Outcome["message"]); + Assert.Equal(before, File.ReadAllBytes(path)); + } + + [Fact] + public void StructuralRefusals() + { + var path = Package(); + var open = Open(path); + var cases = new (string Name, string Request, string Names)[] + { + ("unknown key", Edit(open, json => json["surprise"] = 1), "surprise"), + ("missing version", Edit(open, json => { Hardpoint(json, "gun")["armor"] = 5; ((JObject)json["versions"]).Remove("mod-hull:mod.skiff"); }), "mod-hull:mod.skiff"), + ("missing ship", Edit(open, json => json.Remove("ship")), "ship"), + ("missing hardpoint key", Edit(open, json => ((JObject)Hardpoint(json, "gun")).Remove("arc")), "arc"), + ("grid 33 wide", Edit(open, json => json["layout"]["grid"] = new string('#', 33)), "grid"), + ("grid 33 high", Edit(open, json => json["layout"]["grid"] = string.Join("/", Enumerable.Repeat("#", 33))), "grid"), + ("empty grid", Edit(open, json => json["layout"]["grid"] = ".."), "grid"), + ("ragged grid", Edit(open, json => json["layout"]["grid"] = "##/#"), "grid"), + ("bad footprint", Edit(open, json => Hardpoint(json, "gun")["footprint"] = "#x"), "footprint"), + ("empty footprint", Edit(open, json => Hardpoint(json, "gun")["footprint"] = "."), "footprint"), + ("unknown kind", Edit(open, json => Hardpoint(json, "gun")["kind"] = "Laser"), "kind"), + ("rotation 4", Edit(open, json => Hardpoint(json, "gun")["rotation"] = 4), "rotation"), + ("negative armor", Edit(open, json => Hardpoint(json, "gun")["armor"] = -1), "armor"), + ("arc 361", Edit(open, json => Hardpoint(json, "gun")["arc"] = 361), "arc"), + ("duplicate mount", Edit(open, json => Hardpoint(json, "gun")["mount"] = "thruster.port"), "thruster.port"), + ("duplicate anchor", Edit(open, json => json["visual"]["anchors"][1]["id"] = "map"), "map"), + ("empty anchor id", Edit(open, json => json["visual"]["anchors"][1]["id"] = ""), "anchor"), + ("wrong ship", Edit(open, json => json["ship"] = "mod.other"), "mod.skiff"), + }; + foreach (var (name, request, names) in cases) + { + var before = File.ReadAllBytes(path); + var files = Listing(path); + foreach (var apply in new[] { false, true }) + { + var (code, _, outcome) = Push(path, request, apply); + Assert.True(code == 1, $"{name}: exit {code}"); + Assert.Equal("refused", (string)outcome["outcome"]); + Assert.True(((string)outcome["message"]).Contains(names, StringComparison.Ordinal), $"{name}: {outcome["message"]}"); + Assert.Equal(before, File.ReadAllBytes(path)); + Assert.Equal(files, Listing(path)); + } + } + } + + [Fact] + public void VerdictIsNotAGate() + { + var path = Package(); + // A draft with rows and no anchors: the thruster and the gun are mounts the model cannot bind. + var request = Edit(Open(path), json => json["visual"]["anchors"] = new JArray()); + var (code, _, outcome) = Push(path, request, apply: true); + Assert.Equal(0, code); + Assert.Equal("applied", (string)outcome["outcome"]); + var verdict = (string)outcome["verdict"]; + Assert.StartsWith("refused: ", verdict); + var validated = ConsoleProbe.Capture(() => ShipAuthoringCommands.Run(new[] { "validate", path }), out _, out var error); + Assert.Equal(1, validated); + Assert.Equal(error.Trim(), verdict.Substring("refused: ".Length)); + Assert.Empty(ShipAuthoringStore.Load(path).Visual.Anchors); + } + + [Fact] + public void UnauthoredMembersCarried() + { + var path = Package(); + var (hull, ship, _) = ShipAuthoringStore.Load(path); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + byte[] Pack(T value) => MessagePackSerializer.Serialize(value, options); + var carried = new object[] { hull.Mass, hull.Price, hull.Name, hull.Durability, hull.Armor, hull.Drag, hull.Roles, hull.Behaviors, ship.Joints }; + var before = carried.Select(member => Convert.ToHexString(Pack(member))).ToArray(); + + var request = Edit(Open(path), json => Hardpoint(json, "gun")["armor"] = 5); + Assert.Equal(0, Push(path, request, apply: true).Code); + var (hull2, ship2, _) = ShipAuthoringStore.Load(path); + var after = new object[] { hull2.Mass, hull2.Price, hull2.Name, hull2.Durability, hull2.Armor, hull2.Drag, hull2.Roles, hull2.Behaviors, ship2.Joints } + .Select(member => Convert.ToHexString(Pack(member))).ToArray(); + Assert.Equal(before, after); + Assert.Equal(5f, hull2.Hardpoints.Single(hardpoint => hardpoint.Transform == "gun").Armor); + Assert.Equal("port-row", hull2.Hardpoints.Single(hardpoint => hardpoint.Transform == "thruster.port").Row); + } + + // The Expect half of the compare-exchange: a write that lands between the load and the commit, through whatever + // path, replaces the instance the commit expects. The commit is refused and the concurrent write is what the store holds. + [Fact] + public void ConcurrentWriteBetweenLoadAndCommitIsRefused() + { + var path = Package(); + using (var cache = ShipAuthoringStore.Open(path, writable: true)) + { + var (hull, _, _) = ShipAuthoringStore.Load(cache, path); + var key = ShipModCatalog.HullKey("mod.skiff"); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + HullData Mutated(float mass) + { + var copy = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(hull, options), options); + copy.Mass = mass; + return copy; + } + var mine = Mutated(111); + var concurrent = Mutated(222); + cache.UpsertAsync(typeof(HullData), concurrent, key).GetAwaiter().GetResult(); + var writes = new[] { new ShipAuthoringPush.Write(key, typeof(HullData), hull, mine) }; + Assert.False(ShipAuthoringPush.Land(cache, writes)); + Assert.Same(concurrent, cache.Get(key)); + cache.FlushAsync().Wait(); + } + Assert.Equal(222f, ShipAuthoringStore.Load(path).Hull.Mass); + } + + [Theory] + [InlineData("")] + [InlineData("null")] + [InlineData(" ")] + public void EmptyRequestIsRefusedWithAnOutcome(string body) + { + var path = Package(); + var before = File.ReadAllBytes(path); + var files = Listing(path); + foreach (var apply in new[] { false, true }) + { + var (code, _, outcome) = Push(path, body, apply); + Assert.Equal(1, code); + Assert.Equal("refused", (string)outcome["outcome"]); + Assert.Contains("request", (string)outcome["message"]); + Assert.Equal(before, File.ReadAllBytes(path)); + Assert.Equal(files, Listing(path)); + } + } + + // A model file that does not read as a GLB is the package's fault, not the request's: the verdict reports it, the + // draft still applies, and nothing escapes. + [Theory] + [InlineData("badjson")] + [InlineData("truncated")] + [InlineData("notglb")] + public void CorruptModelIsAVerdictNotACrash(string kind) + { + var path = Path.Combine(ShipFixture.WritePackage(Mods, "mod.skiff", tweak: ship => ship.Hull.Roles = new List { new ItemRole { Name = "frame" } }), "ship.cc"); + var model = Path.Combine(Path.GetDirectoryName(path), "skiff.glb"); + var good = File.ReadAllBytes(model); + // Control: the same request on the intact package is accepted, so the refusal below is the model's. + var intact = Push(path, Edit(Open(path), json => Hardpoint(json, "gun")["armor"] = 6), apply: false); + Assert.True(((string)intact.Outcome["verdict"]).StartsWith("accepted: records and model"), (string)intact.Outcome["verdict"]); + File.WriteAllBytes(model, kind switch + { + "badjson" => ShipFixture.Glb("{not json"), + "truncated" => good.Take(30).ToArray(), + _ => new byte[] { 1, 2, 3 } + }); + var request = Edit(Open(path), json => Hardpoint(json, "gun")["armor"] = 7); + var (code, _, outcome) = Push(path, request, apply: true); + Assert.Equal(0, code); + Assert.Equal("applied", (string)outcome["outcome"]); + Assert.StartsWith("refused: ", (string)outcome["verdict"]); + Assert.Equal(7f, ShipAuthoringStore.Load(path).Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "gun").Armor); + } + + // ---- hull and products -------------------------------------------------------------------------------------------- + + // A shipped catalog the commands find from the working directory: factions to make products for (TWN is ambiguous) + // and one station kind. + private (CultRecordKey Acme, CultRecordKey TwinA) Catalog() + { + var shipped = Path.Combine(_root.Path, "GameData", "Aetheria.cc"); + Directory.CreateDirectory(Path.GetDirectoryName(shipped)); + using var cache = AetheriaStores.Open(shipped, catalogWritable: true); + cache.Upsert(new VerseGrammar { Revision = 1 }); + var acme = cache.Upsert(new Faction { Name = "Acme", ShortName = "ACM" }).Key; + cache.Upsert(new Faction { Name = "Rival", ShortName = "RVL" }); + var twin = cache.Upsert(new Faction { Name = "Twin A", ShortName = "TWN" }).Key; + cache.Upsert(new Faction { Name = "Twin B", ShortName = "TWN" }); + cache.UpsertAsync(typeof(StationKindData), new StationKindData { Name = "Depot" }, StationKindData.KeyOf("depot")).GetAwaiter().GetResult(); + cache.FlushAsync().Wait(); + return (acme, twin); + } + + private static (int Code, string Output, string Error) Command(params string[] args) + { + var code = ConsoleProbe.Capture(() => ShipAuthoringCommands.Run(args), out var output, out var error); + return (code, output, error); + } + + private static JToken Hull(JObject request) => request["hull"]; + + private static void RefusedUntouched(string path, string request, string names) + { + var before = File.ReadAllBytes(path); + var files = Listing(path); + foreach (var apply in new[] { false, true }) + { + var (code, _, outcome) = Push(path, request, apply); + Assert.True(code == 1, $"{names}: exit {code}: {outcome}"); + Assert.Equal("refused", (string)outcome["outcome"]); + Assert.True(((string)outcome["message"]).Contains(names, StringComparison.Ordinal), $"{names}: {outcome["message"]}"); + Assert.Equal(before, File.ReadAllBytes(path)); + Assert.Equal(files, Listing(path)); + } + } + + [Fact] + public void HullFieldsRoundTripAndApply() + { + var path = Package(); + var opened = Open(path); + var request = Edit(opened, json => { Hull(json)["name"] = "Renamed"; Hull(json)["price"] = 777; Hull(json)["mass"] = 4321.5f; }); + var before = File.ReadAllBytes(path); + var (code, changes, outcome) = Push(path, request); + Assert.Equal(0, code); + Assert.Equal(3, changes.Length); + Assert.Contains(changes, line => line == "mod-hull:mod.skiff name: Skiff -> Renamed"); + Assert.Contains(changes, line => line.StartsWith("mod-hull:mod.skiff price: ") && line.EndsWith(" -> 777")); + Assert.Contains(changes, line => line.StartsWith("mod-hull:mod.skiff mass: ") && line.EndsWith(" -> 4321.5")); + Assert.Equal(new[] { "mod-hull:mod.skiff" }, outcome["changed"].Select(key => (string)key)); + Assert.Equal(before, File.ReadAllBytes(path)); + + var (applyCode, applied, applyOutcome) = Push(path, request, apply: true); + Assert.Equal(0, applyCode); + Assert.Equal(changes, applied); + var hull = ShipAuthoringStore.Load(path).Hull; + Assert.Equal(("Renamed", 777, 4321.5f), (hull.Name, hull.Price, hull.Mass)); + var reopened = Parse(Open(path)); + Assert.Equal("Renamed", (string)Hull(reopened)["name"]); + Assert.Equal(777, (int)Hull(reopened)["price"]); + // The ship record was not written: its version token is the one open printed. + Assert.Equal((string)Parse(opened)["versions"]["mod-ship:mod.skiff"], (string)reopened["versions"]["mod-ship:mod.skiff"]); + Assert.NotEqual((string)Parse(opened)["versions"]["mod-hull:mod.skiff"], (string)reopened["versions"]["mod-hull:mod.skiff"]); + + RefusedUntouched(path, Edit(Open(path), json => Hull(json)["name"] = ""), "name"); + RefusedUntouched(path, Edit(Open(path), json => Hull(json)["name"] = " "), "name"); + RefusedUntouched(path, Edit(Open(path), json => Hull(json)["price"] = -1), "price"); + RefusedUntouched(path, Edit(Open(path), json => Hull(json)["price"] = 1.5), "price"); + RefusedUntouched(path, Edit(Open(path), json => Hull(json)["mass"] = -1), "mass"); + RefusedUntouched(path, Edit(Open(path), json => Hull(json)["drag"] = -.5), "drag"); + RefusedUntouched(path, Edit(Open(path), json => Hull(json)["topSpeed"] = -1), "topSpeed"); + RefusedUntouched(path, Edit(Open(path), json => ((JObject)Hull(json)).Remove("armor")), "armor"); + } + + [Fact] + public void TopSpeedRules() + { + var path = Package(); + var behaviors = Pack(ShipAuthoringStore.Load(path).Hull.Behaviors); + var opened = Parse(Open(path)); + Assert.Equal(JTokenType.Float, Hull(opened)["topSpeed"].Type); + + // Null leaves the behaviors byte-equal. + var (code, changes, _) = Push(path, Edit(Open(path), json => { Hull(json)["topSpeed"] = null; Hull(json)["mass"] = 9; }), apply: true); + Assert.Equal(0, code); + Assert.Single(changes); + Assert.Equal(behaviors, Pack(ShipAuthoringStore.Load(path).Hull.Behaviors)); + + // A number sets Min = Max on the one VelocityLimit. + Assert.Equal(0, Push(path, Edit(Open(path), json => Hull(json)["topSpeed"] = 42.5), apply: true).Code); + var limit = ShipAuthoringStore.Load(path).Hull.Behaviors.OfType().Single().TopSpeed; + Assert.Equal((42.5f, 42.5f), (limit.Min, limit.Max)); + Assert.Equal(42.5, (double)Hull(Parse(Open(path)))["topSpeed"]); + + // A hull with no VelocityLimit gets one. + var bare = Path.Combine(ShipFixture.WritePackage(Mods, "mod.bare", tweak: ship => ship.Hull.Behaviors.Clear()), "ship.cc"); + Assert.Equal(JTokenType.Null, Hull(Parse(Open(bare)))["topSpeed"].Type); + Assert.Equal(0, Push(bare, Edit(Open(bare), json => Hull(json)["topSpeed"] = 60), apply: true).Code); + var added = ShipAuthoringStore.Load(bare).Hull.Behaviors.OfType().Single().TopSpeed; + Assert.Equal((60f, 60f), (added.Min, added.Max)); + + // Two leave no one top speed to set; open prints null for them and for a limit whose Min differs from its Max. + var twin = Path.Combine(ShipFixture.WritePackage(Mods, "mod.twin", tweak: ship => ship.Hull.Behaviors.Add(new VelocityLimitData())), "ship.cc"); + Assert.Equal(JTokenType.Null, Hull(Parse(Open(twin)))["topSpeed"].Type); + RefusedUntouched(twin, Edit(Open(twin), json => Hull(json)["topSpeed"] = 50), "at most one VelocityLimit"); + var ranged = Path.Combine(ShipFixture.WritePackage(Mods, "mod.ranged", tweak: ship => + { + var speed = ship.Hull.Behaviors.OfType().Single().TopSpeed; + speed.Min = 1; + speed.Max = 2; + }), "ship.cc"); + Assert.Equal(JTokenType.Null, Hull(Parse(Open(ranged)))["topSpeed"].Type); + } + + [Fact] + public void ProductsAddChangeRemove() + { + var (acme, _) = Catalog(); + var path = Package(); + var opened = Open(path); + Assert.Empty(Parse(opened)["products"]); + var added = Edit(opened, json => ((JArray)json["products"]).Add(new JObject { ["maker"] = "ACM", ["name"] = "Acme Skiff", ["description"] = "Reliable.", ["offered"] = true })); + var productKey = ShipModCatalog.ProductKey("mod.skiff", acme).Value; + var (code, changes, outcome) = Push(path, added, apply: true); + Assert.True(code == 0, outcome.ToString()); + Assert.Equal(new[] { productKey + " added" }, changes); + Assert.Equal(new[] { productKey }, outcome["changed"].Select(key => (string)key)); + Assert.NotNull(outcome["versions"][productKey]); + var (hull, _, products) = ShipAuthoringStore.Load(path); + var product = Assert.Single(products); + Assert.Equal(ShipModCatalog.HullKey("mod.skiff"), product.Design.Key); + Assert.Equal(acme, product.Manufacturer.Key); + Assert.Equal(hull.Roles.Select(role => role.Name), product.Roles.Select(role => role.Role)); + Assert.Equal(("Acme Skiff", "Reliable.", false), (product.Name, product.Description, product.NotOffered)); + + // A changed name keeps the roles and the assembly no section authors. + using (var cache = ShipAuthoringStore.Open(path, writable: true)) + { + var held = Pack(product); + var custom = ShipAuthoringPush.Copy(product); + custom.Roles = new List { new ProductRole { Role = "special", Mean = .9f } }; + custom.Assembly = new AssemblyDistribution { Mean = .8f }; + ShipAuthoringStore.WriteProduct(cache, "mod.skiff", custom); + cache.FlushAsync().Wait(); + Assert.NotEqual(held, Pack(custom)); + } + var opened2 = Open(path); + Assert.Equal(acme.Value, (string)Parse(opened2)["products"][0]["maker"]); + var renamed = Edit(opened2, json => { json["products"][0]["name"] = "Acme Racer"; json["products"][0]["offered"] = false; }); + var (renameCode, renameChanges, _) = Push(path, renamed, apply: true); + Assert.Equal(0, renameCode); + Assert.Equal(new[] { productKey + " name: Acme Skiff -> Acme Racer", productKey + " offered: true -> false" }, renameChanges); + var kept = Assert.Single(ShipAuthoringStore.Load(path).Products); + Assert.Equal(("Acme Racer", true), (kept.Name, kept.NotOffered)); + Assert.Equal("special", Assert.Single(kept.Roles).Role); + Assert.Equal(.8f, kept.Assembly.Mean); + + // A dropped row removes the record, with a hull change in the same commit. + var removed = Edit(Open(path), json => { ((JArray)json["products"]).Clear(); Hull(json)["price"] = 5; }); + var (removeCode, removeChanges, removeOutcome) = Push(path, removed, apply: true); + Assert.Equal(0, removeCode); + Assert.Contains(productKey + " removed", removeChanges); + Assert.Equal(new[] { "mod-hull:mod.skiff", productKey }, removeOutcome["changed"].Select(key => (string)key).OrderBy(key => key, StringComparer.Ordinal)); + Assert.Empty(ShipAuthoringStore.Load(path).Products); + } + + [Fact] + public void ProductMakerResolution() + { + var (_, twinA) = Catalog(); + var path = Package(); + ProductRowEdit(path, "Nobody", "X", "0 factions"); + ProductRowEdit(path, "TWN", "X", "2 factions"); + ProductRowEdit(path, "ACM", " ", "needs a name"); + RefusedUntouched(path, Edit(Open(path), json => + { + ((JArray)json["products"]).Add(new JObject { ["maker"] = "ACM", ["name"] = "A", ["description"] = null, ["offered"] = true }); + ((JArray)json["products"]).Add(new JObject { ["maker"] = "Acme", ["name"] = "B", ["description"] = null, ["offered"] = true }); + }), "Acme"); + + // A stored maker's key names its product with no resolution through the catalog's names (TWN is ambiguous there). + using (var cache = ShipAuthoringStore.Open(path, writable: true)) + { + ShipAuthoringStore.WriteProduct(cache, "mod.skiff", new FactionProductData + { + Name = "Twin Skiff", + Design = new CultRecordRef(ShipModCatalog.HullKey("mod.skiff")), + Manufacturer = new CultRecordRef(twinA) + }); + cache.FlushAsync().Wait(); + } + var request = Edit(Open(path), json => json["products"][0]["name"] = "Twin Racer"); + Assert.Equal(twinA.Value, (string)Parse(request)["products"][0]["maker"]); + Assert.Equal(0, Push(path, request, apply: true).Code); + Assert.Equal("Twin Racer", Assert.Single(ShipAuthoringStore.Load(path).Products).Name); + } + + private void ProductRowEdit(string path, string maker, string name, string message) => + RefusedUntouched(path, Edit(Open(path), json => ((JArray)json["products"]).Add( + new JObject { ["maker"] = maker, ["name"] = name, ["description"] = null, ["offered"] = true })), message); + + // A new product's key is expected absent: one written since the open makes the push stale. + [Fact] + public void NewProductExpectsAbsent() + { + var (acme, _) = Catalog(); + var path = Package(); + var request = Edit(Open(path), json => ((JArray)json["products"]).Add(new JObject { ["maker"] = "ACM", ["name"] = "Mine", ["description"] = null, ["offered"] = true })); + var (code, _, error) = Command("product", path, "ACM", "--name", "Theirs"); + Assert.True(code == 0, error); + var after = File.ReadAllBytes(path); + var (pushCode, _, outcome) = Push(path, request, apply: true); + Assert.Equal(2, pushCode); + Assert.Equal("stale", (string)outcome["outcome"]); + Assert.Equal(new[] { ShipModCatalog.ProductKey("mod.skiff", acme).Value }, outcome["stale"].Select(key => (string)key)); + Assert.Equal(after, File.ReadAllBytes(path)); + } + + [Fact] + public void HullTypeChecked() + { + var path = Package(); + var open = Open(path); + Assert.Equal("Ship", (string)Parse(open)["hullType"]); + RefusedUntouched(path, Edit(open, json => json["hullType"] = "Station"), "hullType"); + var without = Edit(open, json => json.Remove("hullType")); + Assert.Equal(0, Push(path, without, apply: true).Code); + } + + [Fact] + public void KindInHullSection() + { + Catalog(); + var target = Path.Combine(ShipFixture.WritePackage(Mods, "probe.depot", "Probe Depot", tweak: ship => ship.Hull.HullType = HullType.Station), "ship.cc"); + Assert.Equal(JTokenType.Null, Hull(Parse(Open(target)))["kind"].Type); + + // A stats push on a kindless station applies: the kind is only judged when it changes. + Assert.Equal(0, Push(target, Edit(Open(target), json => Hull(json)["mass"] = 11), apply: true).Code); + Assert.Equal(11f, ShipAuthoringStore.Load(target).Hull.Mass); + Assert.Equal(0, Command("price", target, "12").Code); + + RefusedUntouched(target, Edit(Open(target), json => Hull(json)["kind"] = "station-kind:nowhere"), "names no station kind"); + var (code, _, error) = Command("kind", target, "depot"); + Assert.True(code == 0, error); + Assert.Equal("station-kind:depot", (string)Hull(Parse(Open(target)))["kind"]); + // A station with no kind is refused: clearing one is. + RefusedUntouched(target, Edit(Open(target), json => Hull(json)["kind"] = null), "has no Kind"); + + var ship = Package(); + RefusedUntouched(ship, Edit(Open(ship), json => Hull(json)["kind"] = "station-kind:depot"), "only a station hull has one"); + } + + // A stored kind that names no station kind is never passed as fine: it is judged whenever the request or the hull names one, + // by push and by the kind command alike. + [Fact] + public void AnInvalidStoredKindIsNeverAccepted() + { + Catalog(); + var target = Path.Combine(ShipFixture.WritePackage(Mods, "probe.bad", "Probe Bad", tweak: ship => + { + ship.Hull.HullType = HullType.Station; + ship.Hull.Kind = new CultRecordRef(StationKindData.KeyOf("nowhere")); + }), "ship.cc"); + var before = File.ReadAllBytes(target); + var (code, _, error) = Command("kind", target, "nowhere"); + Assert.Equal(1, code); + Assert.Contains("names no station kind", error); + RefusedUntouched(target, Edit(Open(target), json => Hull(json)["mass"] = 11), "names no station kind"); + Assert.Equal(before, File.ReadAllBytes(target)); + } + + // price and stats on a valid product package need no shipped catalog: it is opened only for a product's maker or a kind. + [Fact] + public void PriceAndStatsNeedNoGameData() + { + var path = Path.Combine(ShipFixture.WritePackage(Mods, "probe.sold", "Probe Sold"), "ship.cc"); + using (var cache = ShipAuthoringStore.Open(path, writable: true)) + { + ShipAuthoringStore.WriteProduct(cache, "probe.sold", new FactionProductData + { + Name = "Sold", + Design = new CultRecordRef(ShipModCatalog.HullKey("probe.sold")), + Manufacturer = new CultRecordRef(new CultRecordKey("faction:maker")) + }); + cache.FlushAsync().Wait(); + } + Assert.False(File.Exists(Path.Combine(_root.Path, "GameData", "Aetheria.cc"))); + var (code, _, error) = Command("price", path, "300"); + Assert.True(code == 0, error); + (code, _, error) = Command("stats", path, "--mass", "7", "--top-speed", "33"); + Assert.True(code == 0, error); + var (hull, _, products) = ShipAuthoringStore.Load(path); + Assert.Equal((300, 7f), (hull.Price, hull.Mass)); + Assert.Single(products); + } +} diff --git a/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs b/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs index 7ed2b84be..af531bd6b 100644 --- a/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs @@ -287,7 +287,7 @@ public sealed class ShipAuthoringTests [Theory] [InlineData(HardpointType.Hull), InlineData(HardpointType.Tool), InlineData(HardpointType.Thermal), InlineData(HardpointType.WarpDrive), InlineData(HardpointType.Reactor), InlineData(HardpointType.Shield), InlineData(HardpointType.Sensors), - InlineData(HardpointType.ControlModule)] + InlineData(HardpointType.ControlModule), InlineData(HardpointType.Facility)] public void AnInternalHardpointCarriesNoAnchor(HardpointType type) { WithOnly(type).Validate(); diff --git a/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs new file mode 100644 index 000000000..e3af827dc --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs @@ -0,0 +1,188 @@ +using System; +using System.IO; +using System.Linq; +using Newtonsoft.Json.Linq; +using Xunit; + +// A directional thruster's emitter mesh is the surface its exhaust is born from, along each triangle's normal, so every +// normal must face the exhaust, opposite the push (ShipModCatalog.BindExhaust). A closed box fires both ways: the operator +// saw the same thrusters firing whichever way the ship strafed. A ring thruster is a class of its own with its own rule and +// is not exercised here. +public sealed class ShipEmitterExhaustTests : IDisposable +{ + private readonly TempDirectory _directory = new TempDirectory(); + + public void Dispose() => _directory.Dispose(); + + private string Thruster => Path.Combine(_directory.Path, "mod.skiff", "ship.cc"); + + // The fixture thruster's hardpoint Rotation is None, so its exhaust leaves toward glTF's +Z; its emitter, one quad + // wound to face +Z, is the one-sided emitter the generator writes. + private void Write(Action tweak = null, string from = null, string to = null) + { + ShipFixture.WritePackage(_directory.Path, "mod.skiff", tweak: tweak); + if (from == null) return; + var json = ShipFixture.GlbJson(ShipFixture.Nodes); + Assert.Contains(from, json); + File.WriteAllBytes(Path.Combine(_directory.Path, "mod.skiff", "skiff.glb"), ShipFixture.Glb(json.Replace(from, to), ShipFixture.MeshBytes())); + } + + private static void Reversed(ShipParts ship) => ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "thruster.port").Rotation = ItemRotation.Reversed; + + [Fact] + public void AOneSidedEmitterFacingItsExhaustIsAccepted() + { + Write(); + Assert.Equal("mod.skiff", ShipModCatalog.ReadPackage(Thruster).Visual.Id); + } + + [Fact] + public void AClosedBoxEmitterIsRefusedNamingItsAnchor() + { + Write(from: @"""name"":""thruster-port"",""mesh"":1", to: @"""name"":""thruster-port"",""mesh"":0"); + var message = Assert.Throws(() => ShipModCatalog.ReadPackage(Thruster)).Message; + Assert.Contains("thruster emitter thruster.port", message); + Assert.Contains("one-sided", message); + } + + [Fact] + public void AnEmitterFacingTheWrongWayIsRefused() + { + // The same quad toward +Z under a thruster that now faces aft: its exhaust would leave along the push. + Write(Reversed); + Assert.Contains("thruster emitter thruster.port", Assert.Throws(() => ShipModCatalog.ReadPackage(Thruster)).Message); + } + + [Fact] + public void TheNodesTurnDecidesWhichWayTheEmitterFaces() + { + // Turned half a circle about Y, the quad's +Z becomes -Z: the exhaust of an aft-facing thruster. + Write(Reversed, from: @"""name"":""thruster-port"",""mesh"":1", to: @"""name"":""thruster-port"",""mesh"":1,""rotation"":[0,1,0,0]"); + Assert.Equal("mod.skiff", ShipModCatalog.ReadPackage(Thruster).Visual.Id); + } + + [Fact] + public void TheShippedAndFixturePackagesPass() + { + var root = RunStartTests.FindRepoRoot(); + foreach (var ship in new[] { Path.Combine("GameData", "Mods", "aetheria.nakovalnya"), Path.Combine("tests", "fixtures", "mods", "aetheria.wren") }) + Assert.NotNull(ShipModCatalog.ReadPackage(Path.Combine(root, ship, "ship.cc"))); + } + + // The fixture package whose thruster node carries a mesh of the test's own (a third mesh appended to the BIN chunk), with + // optional vertex normals, an edit to the node, and an edit to the primitive. The thruster's Rotation is None: the exhaust + // leaves toward +Z and the push is -Z. + private string WriteCustom(float[] positions, ushort[] indices, float[] normals = null, Action node = null, Action primitive = null) + { + ShipFixture.WritePackage(_directory.Path, "mod.skiff"); + var json = JObject.Parse(ShipFixture.GlbJson(ShipFixture.Nodes)); + var bin = ShipFixture.MeshBytes().ToList(); + int View(byte[] bytes) + { + while (bin.Count % 4 != 0) bin.Add(0); + ((JArray)json["bufferViews"]).Add(new JObject { ["buffer"] = 0, ["byteOffset"] = bin.Count, ["byteLength"] = bytes.Length }); + bin.AddRange(bytes); + return ((JArray)json["bufferViews"]).Count - 1; + } + int Accessor(int view, int component, int count, string type) + { + ((JArray)json["accessors"]).Add(new JObject { ["bufferView"] = view, ["componentType"] = component, ["count"] = count, ["type"] = type }); + return ((JArray)json["accessors"]).Count - 1; + } + var attributes = new JObject { ["POSITION"] = Accessor(View(positions.SelectMany(BitConverter.GetBytes).ToArray()), 5126, positions.Length / 3, "VEC3") }; + if (normals != null) attributes["NORMAL"] = Accessor(View(normals.SelectMany(BitConverter.GetBytes).ToArray()), 5126, normals.Length / 3, "VEC3"); + var made = new JObject { ["attributes"] = attributes, ["indices"] = Accessor(View(indices.SelectMany(BitConverter.GetBytes).ToArray()), 5123, indices.Length, "SCALAR") }; + primitive?.Invoke(made); + ((JArray)json["meshes"]).Add(new JObject { ["primitives"] = new JArray(made) }); + var thruster = json["nodes"].Single(n => (string)n["name"] == "thruster-port"); + thruster["mesh"] = ((JArray)json["meshes"]).Count - 1; + node?.Invoke((JObject)thruster); + json["buffers"][0]["byteLength"] = bin.Count + (4 - bin.Count % 4) % 4; + File.WriteAllBytes(Path.Combine(_directory.Path, "mod.skiff", "skiff.glb"), ShipFixture.Glb(json.ToString(Newtonsoft.Json.Formatting.None), bin.ToArray())); + return Thruster; + } + + private static readonly ushort[] Quad = { 0, 1, 2, 0, 2, 3 }; + + // A unit quad with counter-clockwise normal n (in the XZ plane's span: n = (sin a, 0, cos a)), a measured from +Z. + private static float[] Plane(double degrees) + { + var (s, c) = (Math.Sin(degrees * Math.PI / 180), Math.Cos(degrees * Math.PI / 180)); + var t = new[] { (float)c, 0f, (float)-s }; + return new[] { 0f, 0f, 0f, t[0], 0f, t[2], t[0], 1f, t[2], 0f, 1f, 0f }; + } + + private static float[] Repeat(float x, float y, float z) => Enumerable.Repeat(new[] { x, y, z }, 4).SelectMany(v => v).ToArray(); + + private bool Accepts(string ship) + { + try { ShipModCatalog.ReadPackage(ship); return true; } + catch (InvalidOperationException error) when (error.Message.Contains("thruster emitter thruster.port")) { return false; } + } + + [Theory] + [InlineData(0, true), InlineData(60, true), InlineData(-60, true), InlineData(89, true), InlineData(-89, true), + InlineData(91, false), InlineData(-91, false), InlineData(120, false), InlineData(180, false)] + public void ATiltedEmitterIsJudgedByItsDotWithThePush(double degrees, bool accepted) => + Assert.Equal(accepted, Accepts(WriteCustom(Plane(degrees), Quad))); + + [Fact] + public void VertexNormalsThatContradictTheWindingAreRefused() + { + // Unity's Mesh Renderer shape emits along the vertex normals, so a face wound toward the exhaust is not enough. + Assert.True(Accepts(WriteCustom(Plane(0), Quad, Repeat(0, 0, 1)))); + Assert.False(Accepts(WriteCustom(Plane(0), Quad, Repeat(0, 0, -1)))); + Assert.False(Accepts(WriteCustom(Plane(0), Quad, Repeat(1, 0, 0)))); + } + + [Fact] + public void AMirroredNodeFlipsTheWindingAndIsJudgedByWhatItDrawsNotWhatItIsWound() + { + // Scaled -1 in X the quad's winding reverses in the world, so glTF's front face is the other one. + Action mirror = node => node["scale"] = new JArray(-1, 1, 1); + Assert.True(Accepts(WriteCustom(Plane(0), Quad, node: mirror))); + Assert.False(Accepts(WriteCustom(Plane(180), Quad, node: mirror))); + } + + [Fact] + public void VertexNormalsFollowTheInverseTransposeUnderNonUniformScale() + { + // A quarter turn's eighth about Y over a stretch of 4 in X: the plane with local normal (1,0,1) keeps a normal toward + // +Z (0.75 of it), where transforming the normal like a position would send it toward -Z. + Action stretched = node => { node["scale"] = new JArray(4, 1, 1); node["rotation"] = new JArray(0, 0.3826834f, 0, 0.9238795f); }; + var tangent = (float)(1 / Math.Sqrt(2)); + var positions = new[] { 0f, 0f, 0f, tangent, 0f, -tangent, tangent, 1f, -tangent, 0f, 1f, 0f }; + Assert.True(Accepts(WriteCustom(positions, Quad, Repeat(tangent, 0, tangent), stretched))); + } + + [Fact] + public void OnlyExtensionsThatHideGeometryAreRefused() + { + Assert.True(Accepts(WriteCustom(Plane(0), Quad, primitive: p => p["extensions"] = JObject.Parse(@"{""KHR_materials_variants"":{""mappings"":[]}}")))); + var compressed = WriteCustom(Plane(0), Quad, primitive: p => p["extensions"] = JObject.Parse(@"{""KHR_draco_mesh_compression"":{""bufferView"":0,""attributes"":{""POSITION"":0}}}")); + Assert.Contains("compressed by KHR_draco_mesh_compression", Assert.Throws(() => ShipModCatalog.ReadPackage(compressed)).Message); + } + + [Fact] + public void ASidewaysEmitterWhoseNormalIsPerpendicularToThePushIsRefused() => + // Normal exactly +X, dot with the push exactly 0: the rule is non-negative, so it fires along the axis it is not meant to. + Assert.False(Accepts(WriteCustom(new[] { 0f, 0f, 0f, 0f, 1f, 0f, 0f, 1f, 1f, 0f, 0f, 1f }, Quad))); + + [Theory] + [InlineData("KHR_draco_mesh_compression"), InlineData("EXT_meshopt_compression")] + public void AnAccessorWhoseBufferViewIsCompressedIsRefused(string extension) + { + // The compression sits on the bufferView, not the primitive: the accessor's bytes are not positions. + var path = WriteCustom(Plane(0), Quad); + var glb = Path.Combine(_directory.Path, "mod.skiff", "skiff.glb"); + var bytes = File.ReadAllBytes(glb); + var length = (int)BitConverter.ToUInt32(bytes, 12); + var json = JObject.Parse(System.Text.Encoding.UTF8.GetString(bytes, 20, length)); + var views = (JArray)json["bufferViews"]; + var positions = (int)json["accessors"][(int)json["meshes"].Last["primitives"][0]["attributes"]["POSITION"]]["bufferView"]; + views[positions]["extensions"] = JObject.Parse("{\"" + extension + "\":{}}"); + var bin = bytes.Skip(28 + length).ToArray(); + File.WriteAllBytes(glb, ShipFixture.Glb(json.ToString(Newtonsoft.Json.Formatting.None), bin)); + Assert.Contains("compressed by " + extension, Assert.Throws(() => ShipModCatalog.ReadPackage(path)).Message); + } +} diff --git a/tests/Aetheria.Shared.Tests/ShipFixture.cs b/tests/Aetheria.Shared.Tests/ShipFixture.cs index 9f2e1c75f..ac41ece2f 100644 --- a/tests/Aetheria.Shared.Tests/ShipFixture.cs +++ b/tests/Aetheria.Shared.Tests/ShipFixture.cs @@ -22,22 +22,33 @@ internal static class ShipFixture 1, 0, 0, 0, 1, 0, 0, 0, 1 }; - public static byte[] MeshBytes() => Tetrahedron.SelectMany(BitConverter.GetBytes).ToArray(); + // One-sided quad in the z = 0 plane, wound counter-clockwise seen from +Z, so its normal is +Z (glTF's nose): the emitter + // of a thruster whose Rotation is None, which faces its exhaust ahead. Four vertices and six 16-bit indices follow the + // tetrahedron in the BIN chunk. + private static readonly float[] Quad = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 }; + private static readonly ushort[] QuadIndices = { 0, 1, 2, 0, 2, 3 }; + + public static byte[] MeshBytes() => + Tetrahedron.SelectMany(BitConverter.GetBytes).Concat(Quad.SelectMany(BitConverter.GetBytes)).Concat(QuadIndices.SelectMany(BitConverter.GetBytes)).ToArray(); + + // The model's geometry as glTF JSON members (meshes, accessors, bufferViews, buffers) over MeshBytes: mesh 0 is the + // tetrahedron, mesh 1 the quad. + public static string Geometry => + @"""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]},{""primitives"":[{""attributes"":{""POSITION"":1},""indices"":2}]}]," + + @"""accessors"":[{""bufferView"":0,""componentType"":5126,""count"":12,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,1]}," + + @"{""bufferView"":1,""componentType"":5126,""count"":4,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,0]}," + + @"{""bufferView"":2,""componentType"":5123,""count"":6,""type"":""SCALAR""}]," + + $@"""bufferViews"":[{{""buffer"":0,""byteLength"":144}},{{""buffer"":0,""byteOffset"":144,""byteLength"":48}},{{""buffer"":0,""byteOffset"":192,""byteLength"":12}}],""buffers"":[{{""byteLength"":{MeshBytes().Length}}}]"; // The GLB carries a glTF scene naming every node: glTFast instantiates a scene, and a scene-less file has none. // Nodes in meshNodes (default MeshNodes) get the shared tetrahedron mesh, whose vertices live in the BIN chunk (MeshBytes). public static string GlbJson(string[] nodes, string[] meshNodes = null) { meshNodes ??= MeshNodes; - var length = MeshBytes().Length; - var mesh = nodes.Any(meshNodes.Contains) - ? @",""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]}]," + - @"""accessors"":[{""bufferView"":0,""componentType"":5126,""count"":12,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,1]}]," + - $@"""bufferViews"":[{{""buffer"":0,""byteLength"":{length}}}],""buffers"":[{{""byteLength"":{length}}}]" - : ""; + var mesh = nodes.Any(meshNodes.Contains) ? "," + Geometry : ""; return @"{""asset"":{""version"":""2.0""},""scene"":0,""scenes"":[{""nodes"":[" + string.Join(",", nodes.Select((_, index) => index)) + @"]}]" + mesh + @",""nodes"":[" + string.Join(",", nodes.Select(node => - $@"{{""name"":""{node}""{(meshNodes.Contains(node) ? @",""mesh"":0" : "")},""extras"":{{""aetheria.id"":""{node}""}}}}")) + "]}"; + $@"{{""name"":""{node}""{(meshNodes.Contains(node) ? node.StartsWith("thruster") ? @",""mesh"":1" : @",""mesh"":0" : "")},""extras"":{{""aetheria.id"":""{node}""}}}}")) + "]}"; } public static byte[] Glb(string json, byte[] bin = null) diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index f439eecc9..0ab632e09 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -49,6 +49,137 @@ public sealed class ShipModCatalogTests : IDisposable AssertOnlyTheDerivedFile(); } + // A maker (by name) the shipped catalog holds, made on first use. + private CultRecordKey Maker(string name) + { + using var cache = AetheriaStores.Open(Shipped, catalogWritable: true); + var existing = cache.GetAll().FirstOrDefault(faction => faction.Name == name); + var key = existing != null ? cache.RefOf(existing).Key : cache.Upsert(new Faction { Name = name, ShortName = name.Substring(0, 3).ToUpperInvariant() }).Key; + cache.FlushAsync().Wait(); + return key; + } + + // A shipped product line a package's product can bin. + private CultRecordKey ShippedLine(string name, bool notOffered) + { + var maker = Maker("Acme"); + using var cache = AetheriaStores.Open(Shipped, catalogWritable: true); + var hull = cache.Upsert(new HullData { Name = name + " hull", Shape = ShipAuthoringTests.Fixture().Hull.Shape, Price = 10 }); + var line = cache.Upsert(new FactionProductData + { + Name = name, + Design = new CultRecordRef(hull.Key), + Manufacturer = new CultRecordRef(maker), + NotOffered = notOffered + }); + cache.FlushAsync().Wait(); + return line.Key; + } + + // One product of a package: its maker, whether it is itself off the market, and the line it bins, if any. + private sealed record Sale(string Maker, bool NotOffered = false, CultRecordKey? Bin = null); + + // A priced package selling the given products through the one product writer, with or without schematic lines + // (`lines` null leaves the record's SchematicLines null). + private void PricedPackage(string id, bool? lines, params Sale[] sales) + { + var makers = sales.Select(sale => Maker(sale.Maker)).ToArray(); + WritePackage(id, id, tweak: ship => + { + ship.Hull.Price = 100; + if (lines == false) ship.Visual.SchematicLines = new List(); + if (lines == null) ship.Visual.SchematicLines = null; + }); + using var cache = ShipAuthoringStore.Open(Path.Combine(Mods, id, "ship.cc"), writable: true); + for (var n = 0; n < sales.Length; n++) + ShipAuthoringStore.WriteProduct(cache, id, new FactionProductData + { + Name = $"{id} product {n}", + Design = new CultRecordRef(ShipModCatalog.HullKey(id)), + Manufacturer = new CultRecordRef(makers[n]), + NotOffered = sales[n].NotOffered, + Bin = sales[n].Bin is { } line ? new ProductBin { Line = new CultRecordRef(line), Floor = 1f } : null + }); + cache.FlushAsync().Wait(); + } + + private static string Excluded(ShipModCatalog.Composition composition, string package) => + composition.Excluded.SingleOrDefault(entry => entry.Package == package)?.Reason; + + // An offered hull is drawn by its schematic lines (ShipModVisual.BuildLineMesh builds nothing from none), so one without any + // is left out of the catalog with its reason; an offered hull with lines and an unoffered stand-in without them both compose. + [Fact] + public void ComposeExcludesAnOfferedHullWithoutSchematicLinesAndKeepsTheRest() + { + PricedPackage("mod.offeredbare", lines: false, new Sale("Acme")); + PricedPackage("mod.offeredlined", lines: true, new Sale("Acme")); + PricedPackage("mod.standin", lines: false, new Sale("Acme", NotOffered: true)); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.offeredlined", "mod.standin" }, composition.Included.OrderBy(id => id, StringComparer.Ordinal)); + var excluded = Assert.Single(composition.Excluded); + Assert.Equal("mod.offeredbare", excluded.Package); + Assert.Contains("mod.offeredbare", excluded.Reason); + Assert.Contains("no schematic", excluded.Reason); + } + + // A hull is offered when any product of it is, and a binned product is offered only if its line is (ruling bin-inherits-line-offered): + // the verdict is IsOffered's, not a read of the product's own NotOffered. + [Fact] + public void OfferedNessComesFromAnyProductAndFromTheBinsLine() + { + var offeredLine = ShippedLine("Offered Line", notOffered: false); + var closedLine = ShippedLine("Closed Line", notOffered: true); + PricedPackage("mod.binoffered", lines: false, new Sale("Acme", Bin: offeredLine)); + PricedPackage("mod.binclosed", lines: false, new Sale("Acme", Bin: closedLine)); + PricedPackage("mod.oneoftwo", lines: false, new Sale("Acme", NotOffered: true), new Sale("Rival")); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Contains("no schematic", Excluded(composition, "mod.binoffered")); + Assert.Null(Excluded(composition, "mod.binclosed")); + Assert.Contains("no schematic", Excluded(composition, "mod.oneoftwo")); + Assert.Equal(new[] { "mod.binclosed" }, composition.Included); + } + + [Fact] + public void ANullSchematicIsNoSchematicWhenOffered() + { + PricedPackage("mod.nulled", lines: null, new Sale("Acme")); + PricedPackage("mod.nulledstandin", lines: null, new Sale("Acme", NotOffered: true)); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Contains("no schematic", Excluded(composition, "mod.nulled")); + Assert.Equal(new[] { "mod.nulledstandin" }, composition.Included); + } + + // A bin's line is a shipped product or one of the package's own, never another package's and never nothing: the catalog read + // refuses such a bin at boot, so compose leaves the package out and the derived catalog opens. + [Fact] + public void ComposeExcludesAPackageWhoseBinNamesNoShippedOrOwnLine() + { + var shipped = ShippedLine("Shipped Line", notOffered: false); + var maker = Maker("Acme"); + PricedPackage("mod.lined", lines: true, new Sale("Acme")); + PricedPackage("mod.cross", lines: false, new Sale("Rival", Bin: ShipModCatalog.ProductKey("mod.lined", maker))); + PricedPackage("mod.nothing", lines: true, new Sale("Acme", Bin: new CultRecordKey("product:nowhere"))); + PricedPackage("mod.shippedbin", lines: true, new Sale("Acme", Bin: shipped)); + PricedPackage("mod.ownbin", lines: true, new Sale("Acme"), new Sale("Rival", Bin: ShipModCatalog.ProductKey("mod.ownbin", maker))); + + PricedPackage("mod.binofbin", lines: true, new Sale("Acme", Bin: shipped), new Sale("Rival", Bin: ShipModCatalog.ProductKey("mod.binofbin", maker))); + + var (catalog, excluded) = ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.binofbin", "mod.cross", "mod.nothing" }, excluded.Select(entry => entry.Package).OrderBy(id => id, StringComparer.Ordinal)); + Assert.All(excluded, entry => Assert.Contains("bins a line", entry.Reason)); + Assert.Equal(Derived, catalog); + using var cache = AetheriaStores.Open(Derived); + Assert.Contains("mod.ownbin product 1", cache.GetAll().Select(product => product.Name)); + Assert.DoesNotContain("mod.cross product 0", cache.GetAll().Select(product => product.Name)); + } + // A package's station kind is checked per package: a bad one is left out, named with its reason, and the derived catalog // still opens. The shipped catalog's own check is unchanged. [Fact] @@ -328,6 +459,54 @@ public sealed class ShipModCatalogTests : IDisposable Assert.Contains("GLB", excluded.Reason); } + // Bind is the one verdict on whether a mod hull exists: a package whose GLB names a node mesh the importer cannot build + // (dangling or negative index, no meshes array, non-integer index, no POSITION on any one primitive, non-triangle mode, skinned node, no primitives) never reaches the boot catalog, so Preload has nothing left to refuse on file facts. + [Fact] + public void ABootCatalogHoldsNoHullTheImporterCannotBuild() + { + WritePackage("mod.good", hullName: "Good"); + var broken = new Dictionary + { + ["mod.dangling"] = (@"{""name"":""collider"",""mesh"":0", @"{""name"":""collider"",""mesh"":7"), + ["mod.nopos"] = (@"""attributes"":{""POSITION"":0}", @"""attributes"":{}"), + ["mod.skinned"] = (@"{""name"":""map"",""mesh"":0", @"{""name"":""map"",""mesh"":0,""skin"":0"), + ["mod.noprims"] = (@"""primitives"":[{""attributes"":{""POSITION"":0}}]", @"""primitives"":[]"), + ["mod.onebad"] = (@"""primitives"":[{""attributes"":{""POSITION"":0}}]", @"""primitives"":[{""attributes"":{""POSITION"":0}},{""attributes"":{}}]"), + ["mod.points"] = (@"""attributes"":{""POSITION"":0}}", @"""attributes"":{""POSITION"":0},""mode"":0}"), + ["mod.negative"] = (@"""mesh"":0", @"""mesh"":-1"), + ["mod.nomeshes"] = (@"""meshes"":", @"""other"":"), + ["mod.fractional"] = (@"""mesh"":0", @"""mesh"":0.0") + }; + foreach (var (package, (from, to)) in broken) + { + WritePackage(package, hullName: package.Substring(4)); + var json = ShipFixture.GlbJson(FixtureNodes); + Assert.Contains(from, json); + File.WriteAllBytes(Path.Combine(Mods, package, "skiff.glb"), ShipFixture.Glb(json.Replace(from, to), ShipFixture.MeshBytes())); + } + + var (catalog, excluded) = ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods); + + Assert.Equal(Derived, catalog); + Assert.Equal(broken.Keys.OrderBy(name => name, StringComparer.Ordinal), excluded.Select(e => e.Package).OrderBy(name => name, StringComparer.Ordinal)); + Assert.All(excluded, e => Assert.Contains("needs a mesh", e.Reason)); + using var cache = AetheriaStores.Open(catalog); + var hulls = cache.GetAll().Where(hull => hull.Visual.IsSet()).ToArray(); + Assert.Equal(new[] { "Good" }, hulls.Select(hull => hull.Name)); + var keys = cache.AllStoredDocuments.Select(record => record.Key.Value).ToHashSet(); + foreach (var package in broken.Keys) + { + Assert.DoesNotContain(ShipModCatalog.HullKey(package).Value, keys); + Assert.DoesNotContain(ShipModCatalog.AuthoringKey(package).Value, keys); + } + // Preload's own two steps over file facts, run headlessly: neither may refuse a hull the catalog holds. + foreach (var hull in hulls) + { + var package = ShipModCatalog.PackageOf(cache, hull, Mods); + ShipModPlan.Build(package.Hull, package.Visual); + } + } + // The game's boot: a bad package is named and the rest boot; with none left, the shipped catalog boots. [Fact] public void TheBootCatalogSurvivesBadPackages() @@ -501,6 +680,59 @@ public sealed class ShipModCatalogTests : IDisposable Assert.True(File.Exists(target), error); } + // A station package: create --like Zenith makes a Station and never copies Zenith's kind; kind is the one writer of it, judged + // by the one kind rule against the shipped catalog; a refusal leaves the file byte-identical. + [Fact] + public void AStationPackageGetsItsKindOnlyFromTheKindCommand() + { + var target = Path.Combine(_directory.Path, "GameData", "Mods", "probe.depot", "ship.cc"); + Assert.Equal(0, Run("create", target, "probe.depot", "Probe Depot", "--like", "Zenith").Code); + var (hull, _, _) = ShipAuthoringStore.Load(target); + Assert.Equal(HullType.Station, hull.HullType); + Assert.False(hull.Kind.IsSet()); + + var before = File.ReadAllBytes(target); + var (code, _, error) = Run("kind", target, "no-such-kind"); + Assert.Equal(1, code); + Assert.Contains("names no station kind", error); + Assert.Equal(before, File.ReadAllBytes(target)); + + (code, _, error) = Run("kind", target, "depot"); + Assert.Equal(0, code); + Assert.Equal("", error); + Assert.Equal("station-kind:depot", ShipAuthoringStore.Load(target).Hull.Kind.Key.Value); + + // A station made like Zenith carries no roles; its product still takes none. + (code, _, error) = Run("product", target, "Zhestokost", "--name", "Probe Depot"); + Assert.Equal((0, ""), (code, error)); + Assert.Empty(ShipAuthoringStore.Load(target).Products.Single().Roles); + } + + // validate judges a finished station package's kind with the rule Compose applies, before compose does. + [Fact] + public void ValidateRefusesAKindlessStationAndAcceptsOneThatNamesAShippedKind() + { + WritePackage("mod.station", tweak: parts => parts.Hull.HullType = HullType.Station); + var path = Path.Combine(Mods, "mod.station", "ship.cc"); + var (code, _, error) = Run("validate", path); + Assert.Equal(1, code); + Assert.Contains("has no Kind", error); + Assert.Equal(0, Run("kind", path, "depot").Code); + Assert.Equal(0, Run("validate", path).Code); + } + + [Fact] + public void TheKindCommandRefusesAShipHullAndLeavesTheFileUntouched() + { + var target = Path.Combine(_directory.Path, "GameData", "Mods", "probe.ship", "ship.cc"); + Assert.Equal(0, Run("create", target, "probe.ship", "Probe Ship", "--like", "Djinni").Code); + var before = File.ReadAllBytes(target); + var (code, _, error) = Run("kind", target, "depot"); + Assert.Equal(1, code); + Assert.Contains("only a station hull has one", error); + Assert.Equal(before, File.ReadAllBytes(target)); + } + // starter: a complete package from nothing but a hull to take stats from. The package must pass the reader the game boots // with (GLB node ids and mesh roles included) and plan a rig, and a second run must not touch the first package. [Fact] @@ -554,8 +786,9 @@ public sealed class ShipModCatalogTests : IDisposable public void NodeIdsMapToTheirGlbNodeIndexSkippingNodesWithoutOne() { var path = Write("nodes.glb", ShipFixture.Glb(@"{""asset"":{""version"":""2.0""},""nodes"":[ - {""name"":""plain""},{""extras"":{""aetheria.id"":""a""}},{""extras"":{}},{""extras"":{""aetheria.id"":""""}},{""mesh"":0,""extras"":{""aetheria.id"":""b""}}]}")); - Assert.Equal(new Dictionary { ["a"] = (1, false, -1, true), ["b"] = (4, true, -1, true) }, ShipModCatalog.ReadNodeIds(path)); + {""name"":""plain""},{""extras"":{""aetheria.id"":""a""}},{""extras"":{}},{""extras"":{""aetheria.id"":""""}},{""mesh"":0,""extras"":{""aetheria.id"":""b""}},{""mesh"":7,""extras"":{""aetheria.id"":""c""}}], + ""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]}]}")); + Assert.Equal(new Dictionary { ["a"] = (1, false, -1, true), ["b"] = (4, true, -1, true), ["c"] = (5, false, -1, true) }, ShipModCatalog.ReadNodeIds(path)); } [Fact] diff --git a/tests/Aetheria.Shared.Tests/ShipProductTests.cs b/tests/Aetheria.Shared.Tests/ShipProductTests.cs index 82f094e88..638f408b6 100644 --- a/tests/Aetheria.Shared.Tests/ShipProductTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipProductTests.cs @@ -99,6 +99,39 @@ public sealed class ShipProductTests : IDisposable } } + // validate gives the verdict compose gives: an offered hull with no schematic lines is refused, an unoffered one is not. + [Fact] + public void ValidateRefusesAnOfferedHullWithoutSchematicLinesAsComposeDoes() + { + Environment.CurrentDirectory = _root.Path; + string Bare(string id, bool offered, bool nullLines = false, CultRecordKey? bin = null) + { + var directory = ShipFixture.WritePackage(Mods, id, id, tweak: ship => { ship.Hull.Price = 100; ship.Visual.SchematicLines = nullLines ? null : new List(); }); + var path = Path.Combine(directory, "ship.cc"); + using var cache = ShipAuthoringStore.Open(path, writable: true); + var product = Product(id + " product", _acme, id); + product.NotOffered = !offered; + if (bin is { } line) product.Bin = new ProductBin { Line = new CultRecordRef(line), Floor = 1f }; + ShipAuthoringStore.WriteProduct(cache, id, product); + cache.FlushAsync().Wait(); + return path; + } + + var (code, _, error) = Run("validate", Bare("mod.offered", offered: true)); + Assert.Equal(1, code); + Assert.Contains("no schematic", error); + Assert.Equal(0, Run("validate", Bare("mod.standin", offered: false)).Item1); + // A null SchematicLines is no schematic, as for compose. + var (nullCode, _, nullError) = Run("validate", Bare("mod.nulled", offered: true, nullLines: true)); + Assert.Equal(1, nullCode); + Assert.Contains("no schematic", nullError); + // A bin naming no shipped product and no product of the package is refused, as compose excludes it. + var (binCode, _, binError) = Run("validate", Bare("mod.badbin", offered: true, bin: new CultRecordKey("product:nowhere"))); + Assert.Equal(1, binCode); + Assert.Contains("bins a line", binError); + Assert.Equal(new[] { "mod.standin" }, ShipModCatalog.Compose(Shipped, Derived, Mods).Included); + } + [Fact] public void APackageWithAnUnknownMakerIsExcluded() { diff --git a/tests/Aetheria.Shared.Tests/ShipRigTests.cs b/tests/Aetheria.Shared.Tests/ShipRigTests.cs index 34581f34a..657a2f03b 100644 --- a/tests/Aetheria.Shared.Tests/ShipRigTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipRigTests.cs @@ -209,13 +209,13 @@ public sealed class ShipRigTests : IDisposable private static string GlbJson(Node[] nodes) { - var text = new StringBuilder(@"{""asset"":{""version"":""2.0""},""meshes"":[{""primitives"":[]}],""nodes"":["); + var text = new StringBuilder(@"{""asset"":{""version"":""2.0""}," + ShipFixture.Geometry + @",""nodes"":["); for (var index = 0; index < nodes.Length; index++) { var node = nodes[index]; var kids = Enumerable.Range(0, nodes.Length).Where(child => nodes[child].Parent == node.Name).ToArray(); text.Append(index > 0 ? "," : "").Append($@"{{""name"":""{node.Name}"""); - if (node.Mesh) text.Append(@",""mesh"":0"); + if (node.Mesh) text.Append(node.Name.StartsWith("thruster") ? @",""mesh"":1" : @",""mesh"":0"); if (node.Id != null) text.Append($@",""extras"":{{""aetheria.id"":""{node.Id}""}}"); if (kids.Length > 0) text.Append(@",""children"":[" + string.Join(",", kids) + "]"); text.Append('}'); @@ -238,7 +238,7 @@ public sealed class ShipRigTests : IDisposable ship.Visual.Anchors.Single(anchor => anchor.Id == "gun").Joint = "wrist"; tweak?.Invoke(ship); }); - File.WriteAllBytes(Path.Combine(directory, "skiff.glb"), ShipFixture.Glb(GlbJson(nodes ?? RigNodes))); + File.WriteAllBytes(Path.Combine(directory, "skiff.glb"), ShipFixture.Glb(GlbJson(nodes ?? RigNodes), ShipFixture.MeshBytes())); return Path.Combine(directory, "ship.cc"); } @@ -348,7 +348,7 @@ public sealed class ShipRigTests : IDisposable public void NodeParentsAreTheNearestTaggedAncestorAndRootsHaveNone() { var path = Path.Combine(_directory.Path, "rig.glb"); - File.WriteAllBytes(path, ShipFixture.Glb(GlbJson(RigNodes))); + File.WriteAllBytes(path, ShipFixture.Glb(GlbJson(RigNodes), ShipFixture.MeshBytes())); var nodes = ShipModCatalog.ReadNodeIds(path); Assert.Equal(-1, nodes["arm"].Parent); Assert.Equal((int)nodes["arm"].Index, nodes["elbow"].Parent); diff --git a/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs b/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs index 760595dcc..9cbc5bb57 100644 --- a/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs @@ -9,34 +9,16 @@ using GameCult.Caching.MessagePack; using MessagePack; using Xunit; -// tools/blender/aetheria_ships/ship_cc.py edits a ship file's HullData and ShipAuthoring records by MessagePack slot -// number and by hardpoint member position. These tests bind that file to the C# types that own the numbers: any renumbered, renamed or -// reordered member, enum value, or nested array shape fails here instead of corrupting a ship the next time Blender saves. +// tools/blender/aetheria_ships/ship_cc.py holds the ship id rule and the enum member names the Blender add-on shares with +// its tools; the ship file itself is read and written only by AetherDb. These tests bind those constants to the C# rule and +// enums that own them: a changed rule, renamed or reordered enum member fails here instead of in a Blender session. public sealed class ShipSchemaPinTests { private static readonly string Source = File.ReadAllText(Locate("tools", "blender", "aetheria_ships", "ship_cc.py")); - [Theory] - [InlineData("MODEL_ASSET_SLOT", typeof(ShipAuthoring), nameof(ShipAuthoring.ModelAsset))] - [InlineData("ANCHORS_SLOT", typeof(ShipAuthoring), nameof(ShipAuthoring.Anchors))] - [InlineData("SCHEMATIC_LINES_SLOT", typeof(ShipAuthoring), nameof(ShipAuthoring.SchematicLines))] - [InlineData("HULL_SHAPE_SLOT", typeof(HullData), nameof(HullData.Shape))] - [InlineData("HULL_HARDPOINTS_SLOT", typeof(HullData), nameof(HullData.Hardpoints))] - [InlineData("HULL_TYPE_SLOT", typeof(HullData), nameof(HullData.HullType))] - [InlineData("PRODUCT_MANUFACTURER_SLOT", typeof(FactionProductData), nameof(FactionProductData.Manufacturer))] - public void PythonSlotConstantsAreTheKeysOfTheMembersTheyNameInTheirComments(string constant, Type owner, string member) - { - Assert.Equal(KeyOf(owner, member), Integer(constant)); - Assert.Matches(new Regex($@"^{constant} = \d+ # \w+\.{member}\r?$", RegexOptions.Multiline), Source); - } - [Fact] - public void PythonSchemaNamesAreTheDocumentsTheyNameAndTheRetiredSlotIsNotReused() + public void RetiredShipKeyOneIsNotReused() { - Assert.Equal(typeof(ShipAuthoring).GetCustomAttribute().SchemaName, Text("SCHEMA")); - Assert.Equal(typeof(HullData).GetCustomAttribute().SchemaName, Text("HULL_SCHEMA")); - Assert.Equal(typeof(FactionProductData).GetCustomAttribute().SchemaName, Text("PRODUCT_SCHEMA")); - Assert.Equal(1, Integer("RETIRED_HULL_SLOT")); // Key 1 held the embedded hull until S1. A later member must not take it, or an old file would decode as it. Assert.DoesNotContain(typeof(ShipAuthoring).GetMembers(BindingFlags.Public | BindingFlags.Instance), member => member.GetCustomAttribute()?.IntKey == 1); @@ -52,33 +34,6 @@ public sealed class ShipSchemaPinTests Assert.Equal(taken.Length, taken.Distinct().Count()); } - [Fact] - public void PythonHardpointMembersAreHardpointDataMembersAtTheirOwnPositions() - { - var members = Strings("HARDPOINT_MEMBERS"); - Assert.Equal(7, members.Length); - for (var slot = 0; slot < members.Length; slot++) - Assert.Equal(slot, KeyOf(typeof(HardpointData), members[slot])); - } - - [Fact] - public void PythonAnchorMembersAreShipAnchorMembersAtTheirPositions() - { - var members = Strings("ANCHOR_MEMBERS"); - Assert.Equal(5, members.Length); - for (var slot = 0; slot < members.Length; slot++) - Assert.Equal(slot, KeyOf(typeof(ShipAnchor), members[slot])); - } - - // ship_cc.py edits slots 2 to 4 of a ship and the first five slots of an anchor row, and carries every later slot (replace_visual - // by anchor Id). The rig lives in those later slots; their numbers are the contract that carry-through keeps. - [Fact] - public void TheRigLivesInTheSlotsPastTheOnesPythonEdits() - { - Assert.Equal(Integer("SCHEMATIC_LINES_SLOT") + 1, KeyOf(typeof(ShipAuthoring), nameof(ShipAuthoring.Joints))); - Assert.Equal(Strings("ANCHOR_MEMBERS").Length, KeyOf(typeof(ShipAnchor), nameof(ShipAnchor.Joint))); - } - // New Ship refuses a bad ship ID before it touches anything, with ship_cc.valid_ship_id; these two constants are that // rule's data, so the C# rule that create and Validate share must agree with them on every character and every stem. [Fact] @@ -117,7 +72,7 @@ public sealed class ShipSchemaPinTests var scad = File.ReadAllText(Locate("tools", "blender", "aetheria_ships", "factions", file)); var literal = Regex.Match(scad, @"^[A-Z]+_LANG = \[[^;]*""([^""]+)""\];", RegexOptions.Multiline); Assert.True(literal.Success, $"{file} has no *_LANG with a maker as its last element"); - var db = AetherDb.Open(root: AetherDb.FindRoot()); + var db = AetherDb.OpenShipped(root: AetherDb.FindRoot()); try { var record = Assert.Single(db.Cache.GetAll().Where(f => f.Name == faction)); @@ -140,34 +95,31 @@ public sealed class ShipSchemaPinTests Assert.Equal(EnumNames(), Strings("HULL_TYPE_NAMES")); } + // The stored number of each HardpointType: a row is stored by value, so an arm inserted mid-enum silently turns every later + // stored row into another type. New arms are appended with the next number. [Fact] - public void SerializedShipHasTheNestedArrayShapesPythonIndexes() + public void HardpointTypeValuesAreTheStoredNumbers() { - var (hull, visual) = ShipAuthoringTests.Fixture(); - var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ShipAuthoring).Assembly); - object[] Body(object document) => Assert.IsType(MessagePackSerializer.Deserialize( - MessagePackSerializer.Serialize(document.GetType(), document, options), MessagePackSerializerOptions.Standard)); + var stored = new[] + { + ("Hull", 0), ("Tool", 1), ("Thermal", 2), ("Thruster", 3), ("WarpDrive", 4), ("Reactor", 5), ("Radiator", 6), ("Shield", 7), + ("Sensors", 8), ("Energy", 9), ("Ballistic", 10), ("Launcher", 11), ("ControlModule", 12), ("Facility", 13) + }; + Assert.Equal(stored, Enum.GetValues().Select(type => (type.ToString(), (int) type)).OrderBy(pair => pair.Item2)); + } - var body = Body(visual); - Assert.Equal("mod.skiff", body[0]); - var lines = Assert.IsType(body[Integer("SCHEMATIC_LINES_SLOT")]); - Assert.Equal("Hull", Assert.IsType(Assert.Single(lines))[0]); - - var hullBody = Body(hull); - // A schematic is [[width, height, cells]] with cells flattened x-major (index x * height + y). - var hullShape = Assert.IsType(Assert.IsType(hullBody[Integer("HULL_SHAPE_SLOT")])[0]); - Assert.Equal(new object[] { 2, 2 }, hullShape.Take(2).Select(value => (object)Convert.ToInt32(value))); - Assert.Equal(new[] { true, false, true, false }, Assert.IsType(hullShape[2]).Cast()); - - var hardpoints = Assert.IsType(hullBody[Integer("HULL_HARDPOINTS_SLOT")]); - var row = Assert.IsType(Assert.Single(hardpoints)); - var members = Strings("HARDPOINT_MEMBERS"); - Assert.True(row.Length >= members.Length); - Assert.Equal("thruster.port", row[Array.IndexOf(members, "Transform")]); - var footprint = Assert.IsType(Assert.IsType(row[Array.IndexOf(members, "Shape")])[0]); - Assert.Equal(3, footprint.Length); - Assert.Equal(new[] { true }, Assert.IsType(footprint[2]).Cast()); - Assert.Equal(new[] { 1, 0 }, Assert.IsType(row[Array.IndexOf(members, "Position")]).Select(value => Convert.ToInt32(value))); + // GameSettings.GetIcon(HardpointType) indexes the Settings asset's ItemIcons by value: one sprite per type, none null. (GameSettings is + // Unity code, so the asset is read as text; the loud failure of a missing entry is for the Unity editor to confirm.) + [Fact] + public void EveryHardpointTypeHasAnIconInTheSettingsAsset() + { + var text = File.ReadAllText(Path.Combine(AetherDb.FindRoot(), "Assets", "Resources", "Settings.asset")); + var lines = text.Split('\n').Select(line => line.TrimEnd('\r')).ToList(); + var start = lines.IndexOf(" ItemIcons:") + 1; + Assert.True(start > 0, "Settings.asset has no ItemIcons"); + var entries = lines.Skip(start).TakeWhile(line => line.StartsWith(" - ")).ToArray(); + Assert.Equal(Enum.GetValues().Length, entries.Length); + Assert.DoesNotContain(entries, entry => entry.Contains("fileID: 0}")); } private static int KeyOf(Type owner, string member) @@ -176,9 +128,6 @@ public sealed class ShipSchemaPinTests return Assert.IsType(found.GetCustomAttribute().IntKey); } - private static int Integer(string constant) => - int.Parse(Regex.Match(Source, $@"^{constant} = (\d+)", RegexOptions.Multiline).Groups[1].Value); - private static string Text(string constant) { var match = Regex.Match(Source, $@"^{constant} = ""([^""]*)""", RegexOptions.Multiline); diff --git a/tests/Aetheria.Shared.Tests/SimClockTests.cs b/tests/Aetheria.Shared.Tests/SimClockTests.cs index 75c2437f5..4ddade80f 100644 --- a/tests/Aetheria.Shared.Tests/SimClockTests.cs +++ b/tests/Aetheria.Shared.Tests/SimClockTests.cs @@ -289,6 +289,62 @@ public sealed partial class RunStartTests Assert.Equal(player.Rotation.w, rotation.w); } + // The screen warp is derived from the wormhole animation: nothing before it, rising through the dive, falling through + // the exit, nothing once the ship has arrived. + [Fact] + public void ShipWormholeWarpFollowsTheAnimation() + { + var (arena, player) = LaunchDuel(); + var wormhole = player.Position.xz + float2(50, 0); + Assert.Equal(0f, player.WormholeWarp); + var arrived = false; + player.OnEnteredWormhole += () => player.ExitWormhole(wormhole, float2(0, 40)); + player.OnExitedWormhole += () => arrived = true; + player.EnterWormhole(wormhole); + + var peak = 0f; + var entering = true; + for (var step = 0; step < 2000 && !arrived; step++) + { + var before = player.WormholeWarp; + arena.Update(ClockFrame); + var after = player.WormholeWarp; + if (arrived) break; + Assert.InRange(after, 0f, 1f); + if (entering && after < before) entering = false; // the hand-over to the exit half + if (entering) Assert.True(after >= before, "the warp rises through the dive"); + else Assert.True(after <= before, "the warp falls through the exit"); + peak = Math.Max(peak, after); + } + Assert.True(arrived, "the ship arrives"); + Assert.False(entering, "the dive hands over to the exit"); + Assert.True(peak > .95f, "the warp reaches nearly full depth between the halves"); + Assert.Equal(0f, player.WormholeWarp); + } + + // The warp centres on the wormhole the ship is at in each half: the one it dives into, then the one it emerges from, + // which is a different place in the new zone. + [Fact] + public void ShipWormholePositionFollowsTheHalf() + { + var (arena, player) = LaunchDuel(); + var entered = player.Position.xz + float2(50, 0); + var emerging = player.Position.xz + float2(-300, 120); + var exiting = false; + var arrived = false; + player.OnEnteredWormhole += () => { player.ExitWormhole(emerging, float2(0, 40)); exiting = true; }; + player.OnExitedWormhole += () => arrived = true; + player.EnterWormhole(entered); + Assert.Equal(entered, player.WormholePosition); + for (var step = 0; step < 2000 && !arrived; step++) + { + arena.Update(ClockFrame); + if (arrived) break; + Assert.Equal(exiting ? emerging : entered, player.WormholePosition); + } + Assert.True(arrived && exiting, "the ship dives and emerges"); + } + // The turn a presenter draws ahead is the turn the next step makes: a ship held in a steady turn, drawn one whole // step ahead of the pose it was last given, is where the sim puts that pose next. [Fact] @@ -354,4 +410,61 @@ public sealed partial class RunStartTests Assert.True(all(Close(Axis(turned, float3(0, 1, 0)), upBefore) < tolerance), "the pose's up does not move"); Assert.True(all(Close(Axis(turned, float3(0, 0, 1)), rodrigues) < tolerance), "the forward axis swings about it by the angle"); } + + // Rate dilates the real seconds fed, never the step: sixteen frames of one period's real time at Rate 1/16 (all exact in + // binary) buy exactly one step, and that step is the same Step. + [Fact] + public void RateIsHeldInsideZeroExclusiveToOneAndRefusesNaN() + { + var clock = new SimClock(1f / 60, 60); + Assert.Equal(1f, clock.Rate); + clock.Rate = .25f; + Assert.Equal(.25f, clock.Rate); + clock.Rate = float.NaN; + Assert.Equal(.25f, clock.Rate); // refused, the last rate stands + clock.Rate = 2f; + Assert.Equal(1f, clock.Rate); + clock.Rate = float.PositiveInfinity; + Assert.Equal(1f, clock.Rate); + clock.Rate = 0f; + Assert.Equal(float.Epsilon, clock.Rate); + clock.Rate = -3f; + Assert.Equal(float.Epsilon, clock.Rate); + clock.Rate = float.NegativeInfinity; + Assert.Equal(float.Epsilon, clock.Rate); + + // A refused NaN leaves the clock stepping: none of the accumulator is poisoned. + clock.Rate = .5f; + clock.Rate = float.NaN; + Assert.True(clock.Advance(1f, _ => { }) > 0); + clock.Rate = 1f; + var before = clock.Steps; + clock.Advance(.1f, _ => { }); + Assert.True(clock.Steps > before); + } + + [Fact] + public void RateDilatesRealTimeWithoutChangingStep() + { + var clock = new SimClock(1f / 32, 32) { Rate = 1f / 16 }; + var passed = new List(); + for (var frame = 0; frame < 15; frame++) clock.Advance(1f / 32, dt => passed.Add(dt)); + Assert.Empty(passed); + clock.Advance(1f / 32, dt => passed.Add(dt)); + Assert.Equal(new[] { 1f / 32 }, passed); + Assert.Equal(1f / 32, clock.Step); + + // The frame clamp comes first: a hitch at Rate .5 pays MaxFrameSeconds x .5, not the hitch. + var hitch = new SimClock(1f / 32, 32) { Rate = .5f }; + Assert.Equal((int) (SimClock.MaxFrameSeconds * .5f * 32), hitch.Advance(10f, _ => { })); + + // The game's own rate over ten real seconds at Rate .01: a tenth of a sim second of steps, every one GameStep. + var game = SimClock.ForGame(); + game.Rate = .01f; + var deltas = new List(); + for (var frame = 0; frame < 600; frame++) game.Advance(1f / 60, dt => deltas.Add(dt)); + Assert.InRange(deltas.Count, 2, 4); + Assert.All(deltas, dt => Assert.Equal(SimClock.GameStep, dt)); + Assert.Equal(1f, new SimClock(1f / 60, 60).Rate); + } } diff --git a/tests/Aetheria.Shared.Tests/SmokeHullCommandTests.cs b/tests/Aetheria.Shared.Tests/SmokeHullCommandTests.cs index 4084f377b..bcef02ce4 100644 --- a/tests/Aetheria.Shared.Tests/SmokeHullCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/SmokeHullCommandTests.cs @@ -31,7 +31,7 @@ public sealed class SmokeHullCommandTests : IDisposable private (HullData[] Hulls, HullData Longinus, EquippableItemData[] Fitted, int Products) Read() { - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); try { var hulls = db.Cache.GetAll().Where(h => h.Name == HullName).ToArray(); diff --git a/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs b/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs index 83013d766..5a1484b69 100644 --- a/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs @@ -45,7 +45,7 @@ public sealed class SmokeRoundsCommandTests : IDisposable private (WeaponItemData[] Smoke, WeaponItemData LightLaser, WeaponItemData ChargedScatterBlaster, int Products) Read() { - var db = AetherDb.Open(root: _root); + var db = AetherDb.OpenShipped(root: _root); try { var smoke = db.Cache.GetAll().Where(w => Names.Contains(w.Name)).ToArray(); diff --git a/tests/Aetheria.Shared.Tests/StationFacilityFitTests.cs b/tests/Aetheria.Shared.Tests/StationFacilityFitTests.cs new file mode 100644 index 000000000..e58fd6de9 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/StationFacilityFitTests.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// Facility rows first (aetheria-living-world, cut station-facility-fit): a generated station installs its kind's Facilities on its +// Facility rows, from LoadoutGenerator.EquipFacilities, before the docking bay, the heater or any interior gear. The tests read the +// owners (ruling census-tests-read-the-owners): StationKinds names the served kinds and each kind's Facilities. +public sealed class StationFacilityFitTests +{ + private static CultRecordRef Kind(string id) => new CultRecordRef(StationKindData.KeyOf(id)); + + // One station of the kind from this maker's generator, seeded; the entity unpacked from its pack. + private static (ItemManager Items, Entity Station) Generate(CultCache cache, Faction maker, CultRecordRef kind, uint seed) + { + var items = new ItemManager(1u, cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }); + var random = new CultMath.Random(seed); + var generator = new LoadoutGenerator(ref random, items, null, null, maker, .5f); + var pack = generator.GenerateStationLoadout(kind); + Assert.NotNull(pack); + return (items, EntitySerializer.Unpack(items, null, pack)); + } + + // Every (faction, fieldable kind) pair of the catalog with the kind's Facilities, over a few seeds so every hull of the kind is drawn. + private static IEnumerable<(Faction Maker, CultRecordRef Kind, uint Seed)> Cases(CultCache cache) => + cache.GetAll().SelectMany(faction => StationKinds.FieldableKindsOf(cache, faction) + .Where(kind => cache.Get(kind).Facilities.Count > 0) + .SelectMany(kind => Enumerable.Range(1, 6).Select(seed => (faction, kind, (uint) seed)))); + + private static string[] FacilityKeys(Entity station) => station.Equipment.Concat(station.CargoBays).Where(item => item.Data.HardpointType == HardpointType.Facility) + .Select(item => item.Data.Name).OrderBy(name => name, StringComparer.Ordinal).ToArray(); + + [Fact] + public void EveryServedKindGetsItsFacilities() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var cases = Cases(cache).ToArray(); + Assert.NotEmpty(cases); + foreach (var (maker, kind, seed) in cases) + { + var (items, station) = Generate(cache, maker, kind, seed); + var wanted = cache.Get(kind).Facilities.Select(facility => cache.Get(facility).Name).OrderBy(name => name, StringComparer.Ordinal).ToArray(); + Assert.Equal(wanted, FacilityKeys(station)); + Assert.All(station.Equipment.Concat(station.CargoBays).Where(item => item.Data.HardpointType == HardpointType.Facility), + item => Assert.Equal(HardpointType.Facility, item.Hardpoint.Type)); + } + } + + [Fact] + public void NoInteriorGearSitsOnAFacilityRow() + { + using var cache = RestoredHullsTests.OpenCatalog(); + foreach (var (maker, kind, seed) in Cases(cache)) + { + var (_, station) = Generate(cache, maker, kind, seed); + foreach (var tool in station.Equipment.Where(item => item.Data.HardpointType == HardpointType.Tool)) + foreach (var cell in tool.Data.Shape.Coordinates) + { + var at = tool.Position + tool.Data.Shape.Rotate(cell, tool.EquippableItem.Rotation); + Assert.NotEqual(HardpointType.Facility, station.Hardpoints[at.x, at.y]?.Type); + } + } + } + + // The hull row of a kind with no second row: an in-memory second facility has nowhere to go and generation names why. + [Fact] + public void AKindWithNoRowFailsByName() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var mining = cache.Get(Kind("mining")); + var extra = cache.Get(Kind("processing")).Facilities.Single(); + mining.Facilities.Add(extra); + var maker = cache.GetAll().First(faction => StationKinds.FieldableKindsOf(cache, faction).Any(kind => kind.Key.Equals(Kind("mining").Key))); + var error = Assert.Throws(() => Generate(cache, maker, Kind("mining"), 1)); + Assert.Contains(mining.Name, error.Message); + Assert.Contains(cache.Get(extra).Name, error.Message); + Assert.Contains("station hull", error.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void FacilitiesSurviveThePack() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var (maker, kind, seed) = Cases(cache).First(); + var items = new ItemManager(1u, cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }); + var random = new CultMath.Random(seed); + var pack = new LoadoutGenerator(ref random, items, null, null, maker, .5f).GenerateStationLoadout(kind); + var before = EntitySerializer.Unpack(items, null, pack); + var again = EntitySerializer.Unpack(items, null, EntitySerializer.Pack(before) as OrbitalEntityPack); + Assert.NotEmpty(FacilityKeys(before)); + Assert.Equal(FacilityKeys(before), FacilityKeys(again)); + Assert.All(again.Equipment.Where(item => item.Data.HardpointType == HardpointType.Facility), + item => Assert.Equal(HardpointType.Facility, item.Hardpoint.Type)); + } + + // The facility step takes nothing from the generator's Random: the same seed with the kind's Facilities emptied draws the same + // station hull, docking bay and heater products. + [Fact] + public void EquipFacilitiesDrawsNothing() + { + using var with = RestoredHullsTests.OpenCatalog(); + using var without = RestoredHullsTests.OpenCatalog(); + foreach (var (maker, kind, seed) in Cases(with).Where(entry => entry.Seed <= 3)) + { + without.Get(kind).Facilities.Clear(); + var makerWithout = without.Get(with.RefOf(maker)); + var (itemsA, a) = Generate(with, maker, kind, seed); + var (itemsB, b) = Generate(without, makerWithout, kind, seed); + Assert.Equal(a.HullData.Name, b.HullData.Name); + string Brand(ItemManager items, Entity station) => string.Join("|", station.Equipment + .Where(item => item.Data is DockingBayData || item.Data is GearData gear && LoadoutGenerator.IsHeater(gear)) + .Select(item => item.Data.Name + ":" + items.ItemData.Get(item.Lot.Product)?.Name).OrderBy(text => text, StringComparer.Ordinal)); + Assert.Equal(Brand(itemsA, a), Brand(itemsB, b)); + } + } +} diff --git a/tests/Aetheria.Shared.Tests/StationFacilityRoomTests.cs b/tests/Aetheria.Shared.Tests/StationFacilityRoomTests.cs new file mode 100644 index 000000000..eaf16a690 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/StationFacilityRoomTests.cs @@ -0,0 +1,101 @@ +using System.IO; +using System.Linq; +using CultMath; +using Newtonsoft.Json.Linq; +using Xunit; + +// Station facilities on typed mounts (aetheria-living-world, cut recipe-facilities; ruling station-facilities-on-typed-mounts): over +// the catalog the game boots, every offered station hull has the Facility rows to take the facility gear of every kind it serves, +// and keeps room for the docking bay and the heater it has always carried. +public sealed class StationFacilityRoomTests +{ + // StationKinds.FacilityRoomFaults over the booted catalog (shipped hulls and station packages): empty. A package merged without + // its Facility row, or a kind given a facility some hull serving it cannot take, fails here by name. + [Fact] + public void EveryServedKindFitsItsHulls() + { + using var cache = RestoredHullsTests.OpenCatalog(); + Assert.Empty(StationKinds.FacilityRoomFaults(cache)); + } + + // The committed manifests under tools/blender/manifests, one per station package (a new directory is checked without editing this test). + public static TheoryData Manifests() + { + var data = new TheoryData(); + foreach (var directory in Directory.GetDirectories(Path.Combine(AetherDb.FindRoot(), "tools", "blender", "manifests")).OrderBy(d => d, System.StringComparer.Ordinal)) + data.Add(Path.GetFileName(directory)); + return data; + } + + // A repackage from a committed manifest reproduces its shipped package in every field the packager writes: hull.scad, name, kind, rows + // (Fa.1 included), stats, price and the product's maker, name, description and whether it is offered. The packager is creation input + // only, so this keeps the two from drifting apart. + [Theory] + [MemberData(nameof(Manifests))] + public void TheCommittedManifestsAreTheShippedPackages(string directory) + { + var root = AetherDb.FindRoot(); + var manifest = JObject.Parse(File.ReadAllText(Path.Combine(root, "tools", "blender", "manifests", directory, "package.json"))); + var id = (string) manifest["id"]; + Assert.Equal(File.ReadAllBytes(Path.Combine(root, "GameData", "Mods", id, "hull.scad")), + File.ReadAllBytes(Path.Combine(root, "tools", "blender", "manifests", directory, "hull.scad"))); + using var cache = RestoredHullsTests.OpenCatalog(); + var key = ShipModCatalog.HullKey(id); + var hull = Assert.Single(cache.GetAll(), candidate => cache.RefOf(candidate).Key.Equals(key)); + Assert.Equal((string) manifest["name"], hull.Name); + if (manifest["kind"] != null) Assert.Equal("station-kind:" + (string) manifest["kind"], hull.Kind.Key.Value); + var shipped = hull.Hardpoints.Select(row => $"{row.Transform}|{row.Type}|{row.Position.x},{row.Position.y}|{ShipAuthoringPush.Footprint(row.Shape)}|{(int) row.Rotation}|{row.Armor}|{row.FiringArc}").OrderBy(x => x); + var written = manifest["rows"].Select(row => $"{(string) row["id"]}|{(string) row["kind"]}|{(int) row["cell"][0]},{(int) row["cell"][1]}|{(string) row["footprint"]}|{(int) row["rotation"]}|{(float) row["armor"]}|{(float) row["arc"]}").OrderBy(x => x); + Assert.Equal(shipped, written); + var stats = manifest["stats"]; + Assert.Equal(((float) stats["mass"], (float) stats["durability"], (float) stats["armor"], (float) stats["drag"]), (hull.Mass, hull.Durability, hull.Armor, hull.Drag)); + Assert.Equal((int) manifest["price"], hull.Price); + var product = Assert.Single(cache.GetAll(), candidate => candidate.Design.Key.Equals(key)); + Assert.Equal(((string) manifest["maker"], (string) manifest["name"], (string) manifest["description"], !(bool) manifest["offered"]), + (cache.Get(product.Manufacturer).Name, product.Name, product.Description, product.NotOffered)); + if (hull.HullType == HullType.Station) Assert.Contains(hull.Hardpoints, row => row.Type == HardpointType.Facility); + } + + // Positive control: Zenith's Facility rows taken away (in memory, on a read-only catalog), the census names the hull, a kind it + // serves and that kind's facility. + [Fact] + public void ARowlessHullIsNamed() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var zenith = Assert.Single(cache.GetAll(), hull => hull.Name == "Zenith"); + Assert.Contains(zenith.Hardpoints, row => row.Type == HardpointType.Facility); + zenith.Hardpoints.RemoveAll(row => row.Type == HardpointType.Facility); + var faults = StationKinds.FacilityRoomFaults(cache); + Assert.Contains(faults, line => line.Contains("Zenith") && line.Contains("Mining Station") && line.Contains("Extraction Rig")); + Assert.All(faults, line => Assert.Contains("Zenith", line)); + } + + // A Facility row must not crowd out what a station has always carried: with every hardpoint's cells taken, each booted station + // hull's interior still fits the Medium Docking Bay and then a heater. + [Fact] + public void EveryStationHullKeepsRoomForDockAndHeater() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var bay = Assert.Single(cache.GetAll(), design => design.Name == "Medium Docking Bay"); + var heater = cache.GetAll().Where(LoadoutGenerator.IsHeater) + .OrderBy(design => design.Shape.Coordinates.Length).ThenBy(design => design.Name, System.StringComparer.Ordinal).First(); + var hulls = cache.GetAll().Where(hull => hull.HullType == HullType.Station).ToArray(); + Assert.NotEmpty(hulls); + foreach (var hull in hulls) + { + var free = new Shape(hull.Shape.Width, hull.Shape.Height); + foreach (var cell in hull.InteriorCells.Coordinates) free[cell] = true; + foreach (var row in hull.Hardpoints) + foreach (var cell in row.Shape.Coordinates) + { + var taken = row.Position + cell; + if (taken.x >= 0 && taken.y >= 0 && taken.x < free.Width && taken.y < free.Height) free[taken] = false; + } + foreach (var design in new ItemData[] { bay, heater }) + { + Assert.True(design.Shape.FitsWithin(free, out var rotation, out var position), $"{hull.Name}: no room left for {design.Name} with every hardpoint's cells taken."); + foreach (var cell in design.Shape.Coordinates) free[design.Shape.Rotate(cell, rotation) + position] = false; + } + } + } +} diff --git a/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs b/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs index 3e00ba91b..5384ab3de 100644 --- a/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs +++ b/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs @@ -6,14 +6,14 @@ using Xunit; // A station kind's description is what a player and a planner read of what it does; the recipes at the kind are what it does. public sealed class StationKindDescriptionTests { - // Every good the shipped catalog extracts at a station kind (a commodity recipe with no inputs; a gear recipe is a design on offer, not raw) is named in that kind's description. + // Every good the shipped catalog extracts at a station kind (a commodity recipe that is raw per Recipes.IsRaw: no inputs, no role inputs; a gear recipe is a design on offer, not raw) is named in that kind's description. // Kills: a kind that gains an extraction recipe (Diamond at mining, Ammonia at volatiles) while its description still lists the old set. [Fact] public void EveryRawGoodAKindExtractsIsNamedInItsDescription() { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenShipped(); var cache = db.Cache; - var unnamed = cache.GetAll().Where(recipe => recipe.Inputs.Count == 0 && recipe.StationKind.IsSet()) + var unnamed = cache.GetAll().Where(recipe => Recipes.IsRaw(cache, recipe) && recipe.StationKind.IsSet()) .Select(recipe => (Kind: cache.Get(recipe.StationKind), Output: cache.Get(recipe.Output))) .Where(pair => pair.Kind != null && (pair.Output is SimpleCommodityData || pair.Output is CompoundCommodityData) && !pair.Kind.Description.Contains(pair.Output.Name)) .Select(pair => $"{pair.Kind.Name} extracts {pair.Output.Name}, which its description omits") @@ -25,13 +25,13 @@ public sealed class StationKindDescriptionTests [Fact] public void MiningExtractsDiamondAndVolatilesAmmonia() { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenShipped(); var cache = db.Cache; - string Extracted(string kindId) => string.Join(",", cache.GetAll() - .Where(recipe => recipe.Inputs.Count == 0 && recipe.StationKind.IsSet() && recipe.StationKind.Key.Equals(StationKindData.KeyOf(kindId))) + string RawAt(string kindId) => string.Join(",", cache.GetAll() + .Where(recipe => Recipes.IsRaw(cache, recipe) && recipe.StationKind.IsSet() && recipe.StationKind.Key.Equals(StationKindData.KeyOf(kindId))) .Select(recipe => cache.Get(recipe.Output).Name)); - Assert.Contains("Diamond", Extracted("mining")); - Assert.Contains("Ammonia", Extracted("volatiles")); + Assert.Contains("Diamond", RawAt("mining")); + Assert.Contains("Ammonia", RawAt("volatiles")); Assert.Contains("Diamond", cache.Get(StationKindData.KeyOf("mining")).Description); Assert.Contains("Ammonia", cache.Get(StationKindData.KeyOf("volatiles")).Description); } @@ -41,7 +41,7 @@ public sealed class StationKindDescriptionTests [Fact] public void EveryCommodityAStationKindNamesIsMadeOrTakenByARecipe() { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenShipped(); var c = db.Cache; var used = c.GetAll().SelectMany(r => r.Inputs.Select(i => i.Commodity.Key.Value).Append(r.Output.Key.Value)).ToHashSet(); var commodities = c.GetAll().ToArray(); @@ -59,7 +59,7 @@ public sealed class StationKindDescriptionTests [Fact] public void TheShippedDescriptionsAreTheAuthoredTable() { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenShipped(); foreach (var id in new[] { "mining", "volatiles", "agriculture", "habitat-support", "power" }) Assert.Equal(StationKindsCatalog.DescriptionOf(id), db.Cache.Get(StationKindData.KeyOf(id)).Description); } diff --git a/tests/Aetheria.Shared.Tests/StationKindTests.cs b/tests/Aetheria.Shared.Tests/StationKindTests.cs index 02db0c081..2f306cf61 100644 --- a/tests/Aetheria.Shared.Tests/StationKindTests.cs +++ b/tests/Aetheria.Shared.Tests/StationKindTests.cs @@ -13,6 +13,17 @@ using Random = CultMath.Random; internal static class TestStationKinds { public static readonly CultRecordRef TradeHub = new CultRecordRef(StationKindData.KeyOf("trade-hub")); + + // A test that takes factions out of a catalog copy takes their stand-ins with them: a stand-in naming a faction the catalog no + // longer holds is a refused catalog (StationKinds.Validate), and the shipped catalog stands every faction in on mining. + public static void DropStandInsOf(CultCache cache, params CultRecordKey[] factions) + { + foreach (var kind in cache.GetAll().Where(k => k.StandIns.Any(s => factions.Contains(s.Faction.Key))).ToArray()) + { + kind.StandIns.RemoveAll(s => factions.Contains(s.Faction.Key)); + cache.Commit(batch => batch.Upsert(typeof(StationKindData), kind, cache.RefOf(kind).Key)); + } + } } // Station kinds (aetheria-living-world, cut station-kind-datum): the one list of kinds in the catalog, a hull's kind, a @@ -53,6 +64,8 @@ public sealed class StationKindTests : IDisposable host._caches.Add(cache); cache.AddBackingStore(new SingleFileMessagePackBackingStore(Path.Combine(dir, "Aetheria.cc")), AetheriaStores.CatalogTypes); cache.AddBackingStore(new SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); + // The shipped catalog stands every faction in on mining (batch OresAndProvinces); these worlds hold only the stand-ins a test adds. + foreach (var kind in cache.GetAll().Where(k => k.StandIns.Count > 0).ToArray()) { kind.StandIns.Clear(); cache.Upsert(kind); } var world = new World { Cache = cache }; world.Items = new ItemManager(1u, cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), world.Log.Add); world.Zh = cache.GetAll().Single(f => f.Name == "Zhestokost"); @@ -60,6 +73,13 @@ public sealed class StationKindTests : IDisposable world.Lucent = cache.GetAll().Single(f => f.ShortName == "Lucent"); world.Zenith = cache.GetAll().Single(h => h.Name == "Zenith"); world._zenithProduct = cache.GetAll().Single(p => cache.Get(p.Design) == world.Zenith); + // Station packages composed into the catalog (the Arsenal Depot) are off the market too: these worlds hold only the station + // hulls a test adds, and the depot's offer would make every depot stand-in live (StationPackageTests owns that). + foreach (var product in cache.GetAll().Where(p => cache.Get(p.Design) is HullData { HullType: HullType.Station } h && h.Visual.IsSet()).ToArray()) + { + product.NotOffered = true; + cache.Upsert(product); + } if (!zenithOffered) { world._zenithProduct.NotOffered = true; @@ -156,6 +176,43 @@ public sealed class StationKindTests : IDisposable Assert.Contains("only a station hull has one", turretWithKind); } + // station-facilities-on-typed-mounts: only a station hull carries a Facility row. + [Fact] + public void OpenRefusesAFacilityRowOnAnythingButAStationHull() + { + HullData WithFacility(HullType type, CultRecordRef kind = default) + { + var hull = Hull(type, kind); + hull.Hardpoints.Add(new HardpointData { Type = HardpointType.Facility, Position = new int2(0, 0), Shape = new Shape(2, 2), Transform = "Fa.1" }); + return hull; + } + foreach (var type in new[] { HullType.Ship, HullType.Turret }) + Assert.Contains("only a station hull takes facilities", OpenRefusal(cache => cache.Upsert(WithFacility(type)))); + SeedAndReopen(cache => + { + var kind = new CultRecordRef(cache.Upsert(new StationKindData { Name = "Hub" }).Key); + cache.Upsert(WithFacility(HullType.Station, kind)); + }, out var path); + using var opened = AetheriaStores.Open(path); + Assert.Contains(opened.GetAll(), hull => hull.Hardpoints.Any(row => row.Type == HardpointType.Facility)); + } + + // The random fill never decides a Facility row (a kind's Facilities fill it, follow-up station-buys-by-installed-gear): Zenith + // generates with no gear of a Facility design and no "No compatible item" log for its row, whatever seed draws it. + [Fact] + public void AStationGeneratesWithItsFacilityRowUnfilledAndUnlogged() + { + var world = World.Make(this, zenithOffered: true); + Assert.Single(world.Zenith.Hardpoints, row => row.Type == HardpointType.Facility); + for (uint seed = 1; seed <= 8; seed++) + { + var pack = world.Generator(world.Au, seed).GenerateStationLoadout(Kind("trade-hub")); + Assert.Equal("Zenith", world.HullName(pack)); + Assert.DoesNotContain(pack.Equipment, entry => entry.item != null && ((EquippableItemData) world.Items.GetData(entry.item)).HardpointType == HardpointType.Facility); + } + Assert.DoesNotContain(world.Log, line => line.Contains("Facility hardpoint")); + } + [Fact] public void OpenRefusesBadStandIn() { @@ -352,11 +409,10 @@ public sealed class StationKindTests : IDisposable stock?.Invoke(w); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); var dir = Path.Combine(_root, "galaxy" + _worlds++); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), w.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, 3); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), w.Cache, _ => { }, null, 3); var pack = ZoneGenerator.GenerateZone(w.Items, authored.Read("ZoneSettings"), - authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, galaxy.IsPrelude, true); + authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, EntranceStationOrder.Any, true); Assert.NotEmpty(pack.Entities.OfType()); return pack.Orbits.Select(orbit => w.Cache.Get(orbit)).Select(orbit => (orbit.Distance, orbit.Phase)).ToArray(); } @@ -376,11 +432,10 @@ public sealed class StationKindTests : IDisposable foreach (var faction in new[] { w.Au, w.Zh, w.Lucent }) foreach (var kind in new[] { "mining", "shipyard", "depot", "power" }) w.Sell(faction, kind); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), w.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "galaxy" + _worlds++, "Narrative")), _ => { }, null, 3); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), w.Cache, _ => { }, null, 3); return galaxy.Zones.Take(8).SelectMany(zone => ZoneGenerator.GenerateZone(w.Items, authored.Read("ZoneSettings"), - authored.Read("PlanetSettings"), galaxy, zone, zone == galaxy.Entrance && galaxy.IsPrelude, true) + authored.Read("PlanetSettings"), galaxy, zone, EntranceStationOrder.Any, true) .Entities.OfType().Where(e => e.Kind.IsSet()).Select(e => e.Kind.Key.Value)).ToArray(); } var first = Kinds(); @@ -397,15 +452,14 @@ public sealed class StationKindTests : IDisposable w.StandIn("depot", w.Lucent, "power"); w.StandIn("depot", w.Zh, "power"); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), w.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "zones", "Narrative")), _ => { }, null, 5); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), w.Cache, _ => { }, null, 5); var stations = 0; var fallbacks = 0; foreach (var galaxyZone in galaxy.Zones.Take(8)) { var pack = ZoneGenerator.GenerateZone(w.Items, authored.Read("ZoneSettings"), - authored.Read("PlanetSettings"), galaxy, galaxyZone, galaxyZone == galaxy.Entrance && galaxy.IsPrelude, true); + authored.Read("PlanetSettings"), galaxy, galaxyZone, EntranceStationOrder.Any, true); foreach (var station in pack.Entities.OfType().Where(e => w.HullOf(e).HullType == HullType.Station)) { stations++; @@ -473,11 +527,10 @@ public sealed class StationKindTests : IDisposable } var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), world.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "galaxy" + _worlds++, "Narrative")), _ => { }, null, 5); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), world.Cache, _ => { }, null, 5); var entrance = ZoneGenerator.GenerateZone(world.Items, authored.Read("ZoneSettings"), - authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, galaxy.IsPrelude, true); + authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, EntranceStationOrder.Any, true); Assert.Contains(entrance.Entities.OfType(), e => world.HullOf(e).HullType == HullType.Station); } diff --git a/tests/Aetheria.Shared.Tests/StationKindsCatalogTests.cs b/tests/Aetheria.Shared.Tests/StationKindsCatalogTests.cs index 517a6ddc6..677545697 100644 --- a/tests/Aetheria.Shared.Tests/StationKindsCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/StationKindsCatalogTests.cs @@ -84,7 +84,7 @@ public sealed class StationKindsCatalogTests : IDisposable var warned = new List(); var applied = new StringWriter(); - using (var db = AetherDb.Open(catalogWritable: true, root: root, warn: warned.Add)) + using (var db = AetherDb.OpenShipped(catalogWritable: true, root: root, warn: warned.Add)) { Assert.Contains(warned, line => line.Contains("Zenith")); Assert.Contains(warned, line => line.Contains("Second Station")); @@ -94,7 +94,7 @@ public sealed class StationKindsCatalogTests : IDisposable } Assert.Throws(() => AetheriaStores.Open(catalog)); - using (var db = AetherDb.Open(catalogWritable: true, root: root, warn: _ => { })) + using (var db = AetherDb.OpenShipped(catalogWritable: true, root: root, warn: _ => { })) { var dry = new StringWriter(); Assert.Equal(0, StationKindsCatalog.SetHullKind(db.Cache, "Second Station", "mining", false, dry)); @@ -112,7 +112,7 @@ public sealed class StationKindsCatalogTests : IDisposable public void SetHullKindRefusesWhatIsNotAStationHullOrAHeldKind() { var root = SeedRoot("Zenith"); - using var db = AetherDb.Open(catalogWritable: true, root: root, warn: _ => { }); + using var db = AetherDb.OpenShipped(catalogWritable: true, root: root, warn: _ => { }); StationKindsCatalog.Run(db.Cache, true, new StringWriter()); string Refusal(string hull, string kind) { @@ -126,6 +126,81 @@ public sealed class StationKindsCatalogTests : IDisposable Assert.False(db.Cache.GetAll().Single(h => h.Name == "Cutter").Kind.IsSet()); } + // A writable catalog holding a solid 6x6 station hull (interior cells 1..4) with one Reactor row, a Ship hull, and a facility design. + private CultCache HubCatalog(out CultRecordKey hubKey) + { + var cache = AetheriaStores.Open(Path.Combine(_root, "hub" + Guid.NewGuid().ToString("N") + ".cc"), catalogWritable: true); + cache.Upsert(new VerseGrammar { Revision = 1 }); + cache.Upsert(new InputLayout { Rows = new InputLayoutRow[] { new InputLayoutRowSpacer { Height = 1 } } }); + var kind = new CultRecordRef(cache.Upsert(new StationKindData { Name = "Hub" }).Key); + var shape = new Shape(6, 6); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var reactor = new Shape(2, 2); + foreach (var cell in reactor.AllCoordinates) reactor[cell] = true; + hubKey = cache.Upsert(new HullData + { + Name = "Hub", HullType = HullType.Station, Kind = kind, Shape = shape, Price = 1, + Hardpoints = { new HardpointData { Type = HardpointType.Reactor, Position = new CultMath.int2(1, 1), Shape = reactor, Transform = "R.1", Armor = 2 } } + }).Key; + cache.Upsert(new HullData { Name = "Cutter", HullType = HullType.Ship, Shape = shape, Price = 1 }); + cache.Upsert(new GearData { Name = "Works", Hardpoint = HardpointType.Facility, Shape = reactor, Price = 1, Behaviors = { new FacilityData() } }); + return cache; + } + + private static string Rows(HullData hull) => + string.Join(" ", hull.Hardpoints.Select(row => $"{row.Transform}:{row.Type}@{row.Position.x},{row.Position.y}:{row.Shape.Width}x{row.Shape.Height}:{row.Armor}")); + + [Fact] + public void SetFacilityRowsSetsRowsAndARerunWritesNothing() + { + using var cache = HubCatalog(out var key); + var before = Rows(cache.Get(key)); + var dry = new StringWriter(); + Assert.Equal(0, StationKindsCatalog.SetFacilityRows(cache, "Hub", new[] { "3,3:##/##", "1,3:#/#" }, false, dry)); + Assert.Contains("Dry run", dry.ToString()); + Assert.Contains("Works", dry.ToString()); + Assert.Equal(before, Rows(cache.Get(key))); + Assert.Equal(0, StationKindsCatalog.SetFacilityRows(cache, "Hub", new[] { "3,3:##/##", "1,3:#/#" }, true, new StringWriter())); + var after = Rows(cache.Get(key)); + Assert.Equal(before + " Fa.1:Facility@3,3:2x2:0 Fa.2:Facility@1,3:1x2:0", after); + // The facility design takes the 2x2 row and no other. + var set = cache.Get(key).Hardpoints.Where(row => row.Type == HardpointType.Facility).ToArray(); + Assert.True(set[0].Takes(cache.GetByName("Works"))); + Assert.False(set[1].Takes(cache.GetByName("Works"))); + var stored = cache.GetStored(key).StoredAt; + var again = new StringWriter(); + Assert.Equal(0, StationKindsCatalog.SetFacilityRows(cache, "Hub", new[] { "3,3:##/##", "1,3:#/#" }, true, again)); + Assert.Contains("No change", again.ToString()); + Assert.Equal(stored, cache.GetStored(key).StoredAt); + // A call with no rows clears the Facility rows and keeps every other row as it was. + Assert.Equal(0, StationKindsCatalog.SetFacilityRows(cache, "Hub", new string[0], true, new StringWriter())); + Assert.Equal(before, Rows(cache.Get(key))); + } + + [Fact] + public void SetFacilityRowsRefusesWhatItCannotPlaceAndLeavesTheRowsEqual() + { + using var cache = HubCatalog(out var key); + Assert.Equal(0, StationKindsCatalog.SetFacilityRows(cache, "Hub", new[] { "3,3:##/##" }, true, new StringWriter())); + var before = Rows(cache.Get(key)); + string Refusal(string hull, params string[] rows) + { + var output = new StringWriter(); + Assert.Equal(1, StationKindsCatalog.SetFacilityRows(cache, hull, rows, true, output)); + Assert.Equal(before, Rows(cache.Get(key))); + return output.ToString(); + } + Assert.Contains("only a station hull", Refusal("Cutter", "1,1:#")); + Assert.Contains("exactly one is required", Refusal("Missing", "1,1:#")); + Assert.Contains("outside Hub's interior", Refusal("Hub", "4,4:##/##")); + Assert.Contains("outside Hub's interior", Refusal("Hub", "0,0:#")); + Assert.Contains("overlaps another row", Refusal("Hub", "2,2:#")); + Assert.Contains("overlaps another row", Refusal("Hub", "3,3:#", "3,3:#")); + Assert.Contains("is not a row", Refusal("Hub", "3,3")); + Assert.Contains("is not a row", Refusal("Hub", "-1,3:#")); + Assert.Contains("rows of # and .", Refusal("Hub", "3,3:#x/##")); + } + [Fact] public void DryRunWritesNothingApplyIsIdempotent() { diff --git a/tests/Aetheria.Shared.Tests/StationPackageTests.cs b/tests/Aetheria.Shared.Tests/StationPackageTests.cs new file mode 100644 index 000000000..19086b960 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/StationPackageTests.cs @@ -0,0 +1,149 @@ +using System; +using System.IO; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using Xunit; + +// Station packages (aetheria-release, cuts station-packages and station-package-processing): a package hull of type Station enters +// the game as data through the one compose path, names its kind (HullData.Kind, written by ship-authoring kind) and is drawn for that +// kind by StationKinds and LoadoutGenerator. The first is GameData/Mods/aetheria.arsenal-depot, the Zhestokost Arsenal Depot, whose +// offer makes every depot stand-in live; the second is aetheria.seized-refinery, the Pirates' Seized Refinery on a Zhestokost donor, +// the processing station. The tests read the owners (ruling census-tests-read-the-owners). +public sealed class StationPackageTests : IDisposable +{ + private const string Id = "aetheria.arsenal-depot"; + private const string RefineryId = "aetheria.seized-refinery"; + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-stationpackage-" + Guid.NewGuid().ToString("N")); + private int _caches; + + public StationPackageTests() => Directory.CreateDirectory(_root); + + public void Dispose() => Directory.Delete(_root, true); + + private static CultRecordRef Kind(string id) => new CultRecordRef(StationKindData.KeyOf(id)); + + // The booted catalog (TestCatalog.Repo: shipped catalog with the first-party packages composed in), a private copy so a test may edit it. + private CultCache Catalog() + { + var path = Path.Combine(_root, $"catalog{_caches++}.cc"); + File.Copy(TestCatalog.Repo, path); + var cache = new CultCache(TestCatalog.Registry()); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(path), AetheriaStores.CatalogTypes); + return cache; + } + + private static HullData Depot(CultCache cache) => cache.Get(new CultRecordRef(ShipModCatalog.HullKey(Id))); + + // What stands in the way of this maker's generator drawing this hull and fitting a docking bay and a heater, or null. + private static string Fault(CultCache cache, Faction maker, HullData hull) + { + var items = new ItemManager(1u, cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }); + var random = new CultMath.Random(1u); + var generator = new LoadoutGenerator(ref random, items, null, null, maker, .5f); + OrbitalEntityPack pack; + try { pack = generator.GenerateStationLoadout(hull.Kind); } + catch (InvalidLoadoutException error) { return $"{hull.Name}: {error.Message}"; } + if (pack == null) return $"{hull.Name}: no station was drawn for its kind."; + var entity = EntitySerializer.Unpack(items, null, pack); + if (!entity.HullData.Kind.Key.Equals(hull.Kind.Key)) return $"{hull.Name}: the draw gave a {entity.HullData.Name}, not a hull of its kind."; + if (pack.DockingBays.Length == 0) return $"{hull.Name}: no docking bay was fitted."; + if (!entity.Equipment.Select(item => item.Data).OfType().Any(gear => gear.Behaviors.Any(behavior => behavior is HeatData))) + return $"{hull.Name}: no heater was fitted."; + return null; + } + + [Fact] + public void TheDepotIsAnOfferedStationOfKindDepot() + { + using var cache = Catalog(); + var hull = Depot(cache); + Assert.NotNull(hull); + Assert.Equal(("Arsenal Depot", HullType.Station), (hull.Name, hull.HullType)); + Assert.Equal(StationKindData.KeyOf("depot"), hull.Kind.Key); + Assert.True(hull.Visual.IsSet()); + var product = Assert.Single(cache.GetAll(), p => p.Design.Key.Equals(ShipModCatalog.HullKey(Id))); + Assert.Equal("Zhestokost", cache.Get(product.Manufacturer).Name); + Assert.True(LoadoutGenerator.IsDrawable(cache, product, hull)); + } + + // The processing station: a Pirate-made, offered Station hull of kind processing whose Facility row takes the Refinery; Pirates, who + // placed only mining before, can now field processing, and the Zhestokost stand-in to depot is unchanged. + [Fact] + public void TheSeizedRefineryIsAnOfferedPirateProcessingStation() + { + using var cache = Catalog(); + var hull = cache.Get(new CultRecordRef(ShipModCatalog.HullKey(RefineryId))); + Assert.NotNull(hull); + Assert.Equal(("🔥🏭", HullType.Station), (hull.Name, hull.HullType)); + Assert.Equal(StationKindData.KeyOf("processing"), hull.Kind.Key); + Assert.True(hull.Visual.IsSet()); + var product = Assert.Single(cache.GetAll(), p => p.Design.Key.Equals(ShipModCatalog.HullKey(RefineryId))); + var pirates = cache.Get(product.Manufacturer); + Assert.Equal("Pirates", pirates.Name); + Assert.True(LoadoutGenerator.IsDrawable(cache, product, hull)); + var refinery = Assert.Single(cache.GetAll(), gear => gear.Name == "Refinery"); + Assert.Contains(hull.Hardpoints, row => row.Type == HardpointType.Facility && row.Takes(refinery)); + var processing = Kind("processing"); + Assert.Equal(processing.Key, StationKinds.HullKindFor(cache, pirates, processing).Key); + Assert.Contains(processing.Key, StationKinds.FieldableKindsOf(cache, pirates).Select(fieldable => fieldable.Key)); + } + + [Fact] + public void EveryDepotStandInIsLive() + { + using var cache = Catalog(); + var depot = Kind("depot"); + var standIns = cache.GetAll() + .SelectMany(kind => kind.StandIns.Where(entry => entry.Kind.Key.Equals(depot.Key)).Select(entry => (kind: cache.RefOf(kind), faction: cache.Get(entry.Faction)))) + .ToArray(); + Assert.NotEmpty(standIns); + foreach (var (kind, faction) in standIns) + { + Assert.Equal(depot.Key, StationKinds.HullKindFor(cache, faction, kind).Key); + Assert.Contains(kind.Key, StationKinds.FieldableKindsOf(cache, faction).Select(fieldable => fieldable.Key)); + } + } + + [Fact] + public void EveryStationPackageGeneratesItsKind() + { + using var cache = Catalog(); + var packages = cache.GetAll().Where(hull => hull.HullType == HullType.Station && hull.Visual.IsSet()).ToArray(); + Assert.Contains(Depot(cache), packages); + Assert.Contains(cache.Get(new CultRecordRef(ShipModCatalog.HullKey(RefineryId))), packages); + foreach (var hull in packages) + { + var makers = cache.GetAll().Where(p => p.Design.Key.Equals(cache.RefOf(hull).Key)).Select(p => cache.Get(p.Manufacturer)); + foreach (var maker in makers) Assert.Null(Fault(cache, maker, hull)); + } + } + + // The generation check is not vacuous: a station package too small to take a docking bay fails it, naming the package. + [Fact] + public void AStationThatTakesNoDockingBayFails() + { + using var cache = Catalog(); + var depot = Depot(cache); + var depotProduct = cache.GetAll().Single(p => p.Design.Key.Equals(cache.RefOf(depot).Key)); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + var tiny = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(depot, options), options); + tiny.Name = "Tiny Depot"; + tiny.Shape = new Shape(3, 3); + foreach (var cell in tiny.Shape.AllCoordinates) tiny.Shape[cell] = true; + tiny.Hardpoints.Clear(); + var tinyRef = cache.Upsert(tiny); + var tinyProduct = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(depotProduct, options), options); + tinyProduct.Name = "Tiny Depot"; + tinyProduct.Design = new CultRecordRef(tinyRef.Key); + cache.Upsert(tinyProduct); + depotProduct.NotOffered = true; + cache.Upsert(depotProduct); + + var fault = Fault(cache, cache.Get(tinyProduct.Manufacturer), tiny); + Assert.NotNull(fault); + Assert.Contains("Tiny Depot", fault); + Assert.Contains("docking bay", fault); + } +} diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index b265ead4d..8eced01ec 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -52,10 +52,9 @@ public sealed class StationPlacementTests : IDisposable cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); var settings = authored.Read("GameplaySettings"); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), settings, _ => { }); stock?.Invoke(items); foreach (var galaxyZone in entranceOnly ? new[] { galaxy.Entrance } : galaxy.Zones.Take(zonesPerSeed)) @@ -65,7 +64,7 @@ public sealed class StationPlacementTests : IDisposable var zoneSettings = authored.Read("ZoneSettings"); tune?.Invoke(zoneSettings); var pack = ZoneGenerator.GenerateZone(items, zoneSettings, authored.Read("PlanetSettings"), galaxy, galaxyZone, - galaxyZone == galaxy.Entrance && galaxy.IsPrelude, true); + EntranceStationOrder.Any, true); var zone = new Zone(items, authored.Read("PlanetSettings"), pack, galaxyZone, galaxy); zone.Update(.02f); yield return new Built(seed, zone, items); diff --git a/tests/Aetheria.Shared.Tests/StationServicesTests.cs b/tests/Aetheria.Shared.Tests/StationServicesTests.cs index 3821a22b4..fd604935a 100644 --- a/tests/Aetheria.Shared.Tests/StationServicesTests.cs +++ b/tests/Aetheria.Shared.Tests/StationServicesTests.cs @@ -24,7 +24,11 @@ public sealed class StationServicesTests : IDisposable foreach (var cell in shape.AllCoordinates) shape[cell] = true; var hardpoint = new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() }; _cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = shape, Price = 1000, Durability = 10, Armor = 10, Hardpoints = { hardpoint } }); - _cache.Upsert(new HullData { Name = "Hub", HullType = HullType.Station, Shape = shape, Price = 5000, Durability = 10 }); + _cache.Upsert(new HullData + { + Name = "Hub", HullType = HullType.Station, Shape = shape, Price = 5000, Durability = 10, + Hardpoints = { new HardpointData { Type = HardpointType.Facility, Position = new int2(0, 0), Shape = new Shape() } } + }); _cache.Upsert(new HullData { Name = "Bare Hub", HullType = HullType.Station, Shape = shape, Price = 5000, Durability = 10 }); _cache.Upsert(new GearData { Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 400, Durability = 8 }); _cache.Upsert(new GearData { Name = "Sweep", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 1, Durability = 20 }); @@ -33,7 +37,24 @@ public sealed class StationServicesTests : IDisposable foreach (var cell in bay.AllCoordinates) bay[cell] = true; _cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = bay, Price = 20, Durability = 4 }); _cache.Upsert(new DockingBayData { Name = "Berth", Shape = new Shape(), InteriorShape = bay, MaxSize = new int2(2, 2), Price = 60, Durability = 6 }); - _cache.Upsert(new SimpleCommodityData { Name = "Ore", Shape = new Shape(), Price = 7, MaxStack = 100 }); + var ore = new SimpleCommodityData { Name = "Ore", Shape = new Shape(), Price = 7, MaxStack = 100 }; + _cache.Upsert(ore); + // A belt yields Ore, so Ore is ore; no field yields Shells, so Shells is not. + _cache.Upsert(new FieldKindData + { + Name = "Asteroid", CrossSection = 4f, GenerationWeight = 1f, + Yields = { new FieldYield { Commodity = _cache.RefOf(ore), Abundance = 1f } } + }); + _cache.Upsert(new SimpleCommodityData { Name = "Shells", Shape = new Shape(), Price = 3, MaxStack = 100 }); + // The fixture station wants what its Smelter's one recipe draws: Ore, and not Shells. + var bar = new SimpleCommodityData { Name = "Bar", Shape = new Shape(), Price = 9, MaxStack = 100 }; + _cache.Upsert(bar); + _cache.Upsert(new GearData { Name = "Smelter", Hardpoint = HardpointType.Facility, Shape = new Shape(), Price = 1, Durability = 4, Behaviors = { new FacilityData() } }); + _cache.Upsert(typeof(RecipeData), new RecipeData + { + Output = _cache.RefOf(bar), Facility = _cache.RefOf(_cache.GetByName("Smelter")), + Inputs = { new CommodityCount { Commodity = _cache.RefOf(ore), Count = 1 } } + }, RecipeData.KeyOf(_cache.RefOf(bar).Key)); _cache.FlushAsync().Wait(); var settings = AuthoredSettings.Load(RestoredHullsTests.FindRepoRoot()).Read("GameplaySettings"); @@ -58,6 +79,8 @@ public sealed class StationServicesTests : IDisposable }; } + private SimpleCommodity Shells(int quantity) => new SimpleCommodity { Data = _cache.RefOf(_cache.GetByName("Shells")), Quantity = quantity }; + private SimpleCommodity Ore(int quantity) => new SimpleCommodity { Data = _cache.RefOf(_cache.GetByName("Ore")), Quantity = quantity }; // A ship with a cargo bay. @@ -69,10 +92,11 @@ public sealed class StationServicesTests : IDisposable } // A station whose one cargo bay can take the goods, or one with no cargo bay at all. - private OrbitalEntity Station(bool withBay = true) + private OrbitalEntity Station(bool withBay = true, bool wants = true) { var station = new OrbitalEntity(_items, _zone, Mint(withBay ? "Hub" : "Bare Hub"), default, new EntitySettings()); if (withBay) Assert.True(station.TryEquip(Mint("Crate"), new int2(1, 1))); + if (withBay && wants) Assert.True(station.TryEquip(Mint("Smelter"), new int2(0, 0))); return station; } @@ -81,7 +105,7 @@ public sealed class StationServicesTests : IDisposable { Assert.Equal(.5f, _items.GameplaySettings.SellFraction); Assert.Equal(.25f, _items.GameplaySettings.RepairFraction); - Assert.Equal(15000000, _items.GameplaySettings.StartingCredits); + Assert.Equal(4000, _items.GameplaySettings.StartingCredits); } [Fact] @@ -124,9 +148,7 @@ public sealed class StationServicesTests : IDisposable var ship = Ship(); var from = ship.CargoBays.Single(); var gun = Mint("Gun", 4); - var ore = Ore(10); Assert.True(from.TryStore(gun)); - Assert.True(from.TryStore(ore)); var station = Station(); var credits = 1000; @@ -135,12 +157,6 @@ public sealed class StationServicesTests : IDisposable Assert.DoesNotContain(gun, from.Cargo.Keys); Assert.Contains(gun, station.CargoBays.Single().Cargo.Keys); - credits = 1000; - Assert.True(StationServices.TrySell(from, station, ore, ref credits)); - Assert.Equal(1035, credits); - Assert.Empty(from.Cargo.Keys.OfType()); - Assert.Equal(10, station.CargoBays.Single().Cargo.Keys.OfType().Sum(c => c.Quantity)); - // A station with nowhere to put it takes nothing and pays nothing. var other = Mint("Gun"); Assert.True(from.TryStore(other)); @@ -150,6 +166,45 @@ public sealed class StationServicesTests : IDisposable Assert.Equal(1000, credits); Assert.Equal(packed, from.Cargo.Count); Assert.Contains(other, from.Cargo.Keys); + + // A commodity stack never sells through TrySell: it has no unit count to say how many sold. + Assert.Throws(() => StationServices.TrySell(from, station, Ore(10), ref credits)); + } + + // A commodity sells by what the station's installed gear draws: the Smelter's recipe takes Ore, so Ore sells whole into room and + // Shells, which no facility draws, are NotWanted with nothing moved (ruling installed-gear-decides-what-a-station-buys). + [Fact] + public void AStationBuysOnlyWhatItsGearWants() + { + var from = Ship().CargoBays.Single(); + var ore = Ore(10); + var shells = Shells(5); + Assert.True(from.TryStore(ore)); + Assert.True(from.TryStore(shells)); + var station = Station(); + Assert.Equal(new[] { _cache.RefOf(_cache.GetByName("Ore")).Key }, StationWants.Of(station)); + + var credits = 1000; + var sold = StationServices.TrySellPart(from, station, ore, ref credits); + Assert.Equal((10, 10, SaleRefusal.None), (sold.Sold, sold.Offered, sold.Refusal)); + Assert.Equal(1035, credits); + Assert.DoesNotContain(ore, from.Cargo.Keys); + Assert.Equal(10, station.CargoBays.Single().Cargo.Keys.OfType().Sum(c => c.Quantity)); + + var refused = StationServices.TrySellPart(from, station, shells, ref credits); + Assert.Equal((0, 5, SaleRefusal.NotWanted), (refused.Sold, refused.Offered, refused.Refusal)); + Assert.Equal(1035, credits); + Assert.Contains(shells, from.Cargo.Keys); + Assert.Equal(5, shells.Quantity); + + // A station with no facility wants nothing, Ore included. + var bare = Station(wants: false); + Assert.Empty(StationWants.Of(bare)); + var held = Ore(1); + Assert.True(from.TryStore(held)); + var none = StationServices.TrySellPart(from, bare, held, ref credits); + Assert.Equal((0, 1, SaleRefusal.NotWanted), (none.Sold, none.Offered, none.Refusal)); + Assert.Equal(1035, credits); } // A station's first bay being full is no reason to refuse: the goods go to whichever bay takes them. @@ -170,26 +225,39 @@ public sealed class StationServicesTests : IDisposable var credits = 0; Assert.True(StationServices.TrySell(from, station, gun, ref credits)); - Assert.True(StationServices.TrySell(from, station, ore, ref credits)); + Assert.Equal(10, StationServices.TrySellPart(from, station, ore, ref credits).Sold); Assert.Contains(gun, open.Cargo.Keys); Assert.Contains(ore, open.Cargo.Keys); } - // The market absorbs a sold commodity (aetheria-release:ruling:station-market-absorbs-sold-commodity): a full hold - // stores what fits, the rest is taken, and the full price is paid; a hold with no room at all still pays. + // Nothing is absorbed (ruling no-market-absorption): a hold with room for some units takes those and pays for those + // alone, the rest stays in the seller's hold, and a hold with no room pays nothing. [Fact] - public void TrySell_commodity_is_paid_in_full_when_the_station_hold_is_full() + public void AFullStationHoldTakesOnlyWhatFits() { var from = Ship().CargoBays.Single(); - var ore = Ore(10); - Assert.True(from.TryStore(ore)); var station = Station(); - while (station.CargoBays[0].TryStore(Mint("Gun"))) { } + var bay = station.CargoBays[0]; + // The station's one ore stack holds 60 of its 100 and every other cell holds a gun: 40 units fit. + var shelf = Ore(60); + Assert.True(bay.TryStore(shelf)); + while (bay.TryStore(Mint("Gun"))) { } + var big = Ore(100); + Assert.True(from.TryStore(big)); var credits = 0; - Assert.True(StationServices.TrySell(from, station, ore, ref credits)); - Assert.Equal(35, credits); - Assert.Empty(from.Cargo.Keys.OfType()); - Assert.Empty(station.CargoBays[0].Cargo.Keys.OfType()); + var result = StationServices.TrySellPart(from, station, big, ref credits); + Assert.Equal((40, 100, SaleRefusal.NoRoom), (result.Sold, result.Offered, result.Refusal)); + Assert.Equal(StationServices.SellPrice(_items, Ore(40)), credits); + Assert.Contains(big, from.Cargo.Keys); + Assert.Equal(60, big.Quantity); + Assert.Equal(100, shelf.Quantity); + + // Now the stack is full and no cell is free: nothing sells, nothing is paid, the stack stays. + credits = 0; + var refused = StationServices.TrySellPart(from, station, big, ref credits); + Assert.Equal((0, 60, SaleRefusal.NoRoom), (refused.Sold, refused.Offered, refused.Refusal)); + Assert.Equal(0, credits); + Assert.Equal(60, big.Quantity); } // A commodity the seller does not hold sells for nothing: not one never stored, and not a stale copy of a stack the sale @@ -203,14 +271,14 @@ public sealed class StationServicesTests : IDisposable var station = Station(); var credits = 500; - Assert.False(StationServices.TrySell(from, station, Ore(10), ref credits)); + Assert.Equal(0, StationServices.TrySellPart(from, station, Ore(10), ref credits).Sold); Assert.Equal(500, credits); Assert.Empty(station.CargoBays.Single().Cargo.Keys.OfType()); Assert.Equal(10, Assert.Single(from.Cargo.Keys.OfType()).Quantity); - Assert.True(StationServices.TrySell(from, station, held, ref credits)); + Assert.Equal(10, StationServices.TrySellPart(from, station, held, ref credits).Sold); var paid = credits; - Assert.False(StationServices.TrySell(from, station, held, ref credits)); + Assert.Equal(0, StationServices.TrySellPart(from, station, held, ref credits).Sold); Assert.Equal(paid, credits); Assert.Equal(10, station.CargoBays.Single().Cargo.Keys.OfType().Sum(c => c.Quantity)); } @@ -506,71 +574,59 @@ public sealed class StationServicesTests : IDisposable Assert.Equal(0, credits); } - private SimpleCommodity Mined(int quantity) - { - var data = _cache.GetByName("Ore"); - return new SimpleCommodity { Data = _cache.RefOf(data), Quantity = quantity, Lot = _items.ExtractedLot(0, default, data) }; - } - [Fact] - public void SellOreSellsOnlyMinedStacks() + public void SellOreSellsEveryOreStackMinedOrBought() { var ship = Ship(); var bay = ship.CargoBays.Single(); - var mined = Mined(10); - var staged = Ore(5); + var bought = Ore(10); + var shells = Shells(5); var gun = Mint("Gun"); - Assert.True(bay.TryStore(mined)); - Assert.True(bay.TryStore(staged)); + Assert.True(bay.TryStore(bought)); + Assert.True(bay.TryStore(shells)); Assert.True(bay.TryStore(gun)); var station = Station(); - var value = StationServices.OreValue(_items, ship.CargoBays); - Assert.Equal(StationServices.SellPrice(_items, mined), value); + var value = StationServices.OreValue(_items, ship.CargoBays, station); + Assert.Equal(StationServices.SellPrice(_items, bought), value); Assert.True(value > 0); var credits = 100; - Assert.Equal(10, StationServices.TrySellOre(ship.CargoBays, station, ref credits)); + Assert.Equal(10, StationServices.TrySellOre(ship.CargoBays, station, ref credits).Sold); Assert.Equal(100 + value, credits); - Assert.DoesNotContain(mined, bay.Cargo.Keys); - Assert.Contains(staged, bay.Cargo.Keys); + Assert.DoesNotContain(bought, bay.Cargo.Keys); + Assert.Contains(shells, bay.Cargo.Keys); Assert.Contains(gun, bay.Cargo.Keys); } - [Fact] - public void SellOreLeavesALottedCommodityThatWasNotExtracted() - { - var ship = Ship(); - var bay = ship.CargoBays.Single(); - var data = _cache.GetByName("Ore"); - var lot = _items.Lots.Add(new Lot { Design = _cache.RefOf(data), Origin = new Attributed(), Quality = 1 }); - Assert.NotEqual(0, lot); - var traded = new SimpleCommodity { Data = _cache.RefOf(data), Quantity = 6, Lot = lot }; - Assert.True(bay.TryStore(traded)); - var credits = 100; - Assert.Equal(0, StationServices.OreValue(_items, ship.CargoBays)); - Assert.Equal(0, StationServices.TrySellOre(ship.CargoBays, Station(), ref credits)); - Assert.Equal(100, credits); - Assert.Contains(traded, bay.Cargo.Keys); - } - [Fact] public void SellOreAcrossBaysAndShips() { var one = Ship(); var two = Ship(); var bays = one.CargoBays.Concat(two.CargoBays).ToArray(); - Assert.True(one.CargoBays.Single().TryStore(Mined(30))); - Assert.True(two.CargoBays.Single().TryStore(Mined(40))); + Assert.True(one.CargoBays.Single().TryStore(Ore(30))); + Assert.True(two.CargoBays.Single().TryStore(Ore(40))); var station = Station(); - // Fill the station's bay so nothing more fits: the market absorbs the sale at full price all the same. - for (var i = 0; i < 20; i++) station.CargoBays.Single().TryStore(Ore(100)); - var value = StationServices.OreValue(_items, bays); + var value = StationServices.OreValue(_items, bays, station); Assert.Equal(StationServices.SellPrice(_items, Ore(70)), value); + // Across bays, a station with room takes all of it and pays for all of it. var credits = 0; - Assert.Equal(70, StationServices.TrySellOre(bays, station, ref credits)); + var roomy = StationServices.TrySellOre(bays, station, ref credits); + Assert.Equal((70, 70), (roomy.Sold, roomy.Offered)); Assert.Equal(value, credits); Assert.All(bays, bay => Assert.Empty(bay.Cargo.Keys.OfType())); + + // The full station takes nothing: credits 0, the 70 units stay. + Assert.True(one.CargoBays.Single().TryStore(Ore(30))); + Assert.True(two.CargoBays.Single().TryStore(Ore(40))); + var full = Station(); + while (full.CargoBays.Single().TryStore(Mint("Gun"))) { } + credits = 0; + var refused = StationServices.TrySellOre(bays, full, ref credits); + Assert.Equal((0, 70, SaleRefusal.NoRoom), (refused.Sold, refused.Offered, refused.Refusal)); + Assert.Equal(0, credits); + Assert.Equal(70, bays.SelectMany(bay => bay.Cargo.Keys.OfType()).Sum(stack => stack.Quantity)); } [Fact] @@ -578,12 +634,12 @@ public sealed class StationServicesTests : IDisposable { var ship = Ship(); var bay = ship.CargoBays.Single(); - Assert.True(bay.TryStore(Ore(5))); + Assert.True(bay.TryStore(Shells(5))); Assert.True(bay.TryStore(Mint("Gun"))); var held = bay.Cargo.Count; var credits = 100; - Assert.Equal(0, StationServices.OreValue(_items, ship.CargoBays)); - Assert.Equal(0, StationServices.TrySellOre(ship.CargoBays, Station(), ref credits)); + Assert.Equal(0, StationServices.OreValue(_items, ship.CargoBays, Station())); + Assert.Equal(0, StationServices.TrySellOre(ship.CargoBays, Station(), ref credits).Sold); Assert.Equal(100, credits); Assert.Equal(held, bay.Cargo.Count); } diff --git a/tests/Aetheria.Shared.Tests/StationWantsTests.cs b/tests/Aetheria.Shared.Tests/StationWantsTests.cs new file mode 100644 index 000000000..b07210b8d --- /dev/null +++ b/tests/Aetheria.Shared.Tests/StationWantsTests.cs @@ -0,0 +1,189 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using Xunit; +using float2 = CultMath.float2; + +// What a station buys on the shipped catalog (aetheria-living-world, cut station-sale-by-wants; rulings +// installed-gear-decides-what-a-station-buys, transit-depots-buy-for-onward-haul, demo-zenith-ore-depot, no-market-absorption): +// a recipe facility's draws, a silo's haul order, the silo as a bay, the order as a run record, and the room generated stock leaves. +public sealed partial class RunStartTests +{ + // A hold that holds `units` of every design but the excluded ones. + private sealed class FullHold : IProductionHold + { + private readonly HashSet _without; + public FullHold(IEnumerable without = null) => _without = new HashSet(without ?? Array.Empty()); + public int Held(CultRecordKey design) => _without.Contains(design) ? 0 : 1000; + public bool TryTake(IReadOnlyList<(CultRecordKey design, int units)> units) => true; + public bool TryPut(CultRecordKey design, int units) => true; + } + + private IEnumerable ShippedFacilityDesigns() => + _cache.GetAll().SelectMany(kind => kind.Facilities).Select(facility => facility.Key).Distinct() + .Where(key => StationKinds.IsRecipeFacility(_cache.Get(new CultRecordRef(key)))); + + // Production.Draws names every design Take can take: with every good in the hold, and with each filler of each role the only one. + [Fact] + public void DrawsNamesEveryDesignTakeTakes() + { + var checkedRecipes = 0; + foreach (var facility in ShippedFacilityDesigns()) + foreach (var recipe in Production.RunList(_cache, facility)) + { + var draws = Production.Draws(_cache, recipe); + var all = Production.Take(_cache, recipe, new FullHold()); + Assert.NotNull(all); + Assert.All(all, entry => Assert.Contains(entry.design, draws)); + foreach (var role in Recipes.RoleInputsOf(_cache, recipe)) + { + var fillers = Recipes.Fillers(_cache, role.Name); + foreach (var only in fillers) + { + var taken = Production.Take(_cache, recipe, new FullHold(fillers.Where(filler => !filler.Equals(only)))); + Assert.NotNull(taken); + Assert.All(taken, entry => Assert.Contains(entry.design, draws)); + Assert.Contains(taken, entry => entry.design.Equals(only)); + } + } + checkedRecipes++; + } + Assert.True(checkedRecipes > 10, $"{checkedRecipes} recipes checked"); + } + + // The wants of the Pirates' refinery are the draws of its run list and nothing else: Gun Forging makes a compound, so it is on the + // facility's RunOn list but not its run list, and what only it draws is not wanted. + [Fact] + public void AFacilityThatRunsNothingWantsNothing() + { + var (_, arena, _, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var refinery = StationOfKind(arena, "processing"); + var design = refinery.Equipment.Select(equipped => _items.GetData(equipped.EquippableItem)).Single(data => StationKinds.IsRecipeFacility(data)); + var key = _cache.RefOf(design).Key; + var run = Production.RunList(_cache, key); + var drawn = new HashSet(run.SelectMany(recipe => Production.Draws(_cache, recipe))); + Assert.Equal(drawn.OrderBy(good => good.Value, StringComparer.Ordinal), StationWants.Of(refinery).OrderBy(good => good.Value, StringComparer.Ordinal)); + + var skipped = Recipes.RunOn(_cache, key).Except(run).ToArray(); + Assert.NotEmpty(skipped); + var onlySkipped = skipped.SelectMany(recipe => Production.Draws(_cache, recipe)).Where(good => !drawn.Contains(good)).ToArray(); + Assert.NotEmpty(onlySkipped); + Assert.Empty(StationWants.Of(refinery).Intersect(onlySkipped)); + } + + private OrbitalEntity DemoStation(string kind, uint seed = 1) + { + var (_, arena, _, failures) = Launch(new DemoTerminus(), Inputs(() => seed)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + return StationOfKind(arena, kind); + } + + // Zenith's silo is a bay on its Facility row, in CargoBays and not in Equipment; it survives a pack and restore, takes ore and + // refuses gear and consumables, and generated gear stock never lands in it. + [Fact] + public void ASiloIsABayOnItsFacilityRowAndHoldsBulkOnly() + { + var (_, arena, _, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var zenith = StationOfKind(arena, "trade-hub"); + var silo = Assert.Single(zenith.CargoBays, bay => bay.Data is SiloData); + Assert.NotNull(silo.Hardpoint); + Assert.Equal(HardpointType.Facility, silo.Hardpoint.Type); + Assert.DoesNotContain(zenith.Equipment, equipped => equipped.Data is SiloData); + Assert.Empty(silo.Cargo); + Assert.Contains(zenith.CargoBays, bay => !(bay.Data is SiloData) && bay.Cargo.Count > 0); + + var ore = StationWants.Of(zenith).OrderBy(good => good.Value, StringComparer.Ordinal).First(); + Assert.True(silo.TryStore(new SimpleCommodity { Data = new CultRecordRef(ore), Quantity = 3 })); + var gear = _cache.GetAll().First(data => data.HardpointType == HardpointType.Sensors); + var instance = _items.CreateInstance(_cache.GetAll().First(product => product.Design.Key.Equals(_cache.RefOf(gear).Key))); + Assert.False(silo.TryStore(instance)); + Assert.False(silo.TryFindSpace(instance)); + + var restored = EntitySerializer.Unpack(_items, arena, EntitySerializer.Pack(zenith)); + var restoredSilo = Assert.Single(restored.CargoBays, bay => bay.Data is SiloData); + Assert.Equal(3, restoredSilo.Count(ore)); + Assert.Equal(zenith.CargoBays.Count, restored.CargoBays.Count); + } + + // Zenith buys ore for its haul order: with the order removed, or the silo removed, it buys none. + [Fact] + public void ZenithBuysOnlyTheHaulOrdersGoods() + { + var zenith = DemoStation("trade-hub"); + var order = Assert.Single(_cache.GetAll()); + Assert.Equal(order.Goods.Select(good => good.Key).OrderBy(good => good.Value, StringComparer.Ordinal), StationWants.Of(zenith).OrderBy(good => good.Value, StringComparer.Ordinal)); + Assert.NotEmpty(order.Goods); + Assert.All(order.Goods, good => Assert.True(FieldKinds.IsOre(_cache, _cache.Get(good)))); + + // The same station without its silo (a copy, since a placed station is active) wants nothing: its goods are its silo's. + var copy = (OrbitalEntity) EntitySerializer.Unpack(_items, zenith.Zone, EntitySerializer.Pack(zenith)); + Assert.Equal(StationWants.Of(zenith).Count, StationWants.Of(copy).Count); + Assert.NotNull(copy.TryUnequip(copy.CargoBays.Single(bay => bay.Data is SiloData))); + Assert.Empty(StationWants.Of(copy)); + + var key = _cache.AllStoredDocuments.Single(stored => stored.Descriptor.DocumentType == typeof(HaulOrderData)).Key; + _cache.Commit(batch => batch.Remove(key)); + Assert.Empty(StationWants.Of(zenith)); + } + + // The staged order is a run record: Clear and a discarded Simulation remove it, and a refused stage writes none. + [Fact] + public void HaulOrderGoesWithTheRun() + { + Assert.True(RunSave.IsRunRecord(typeof(HaulOrderData))); + var (started, simulation) = RunSave.Beside(_cache, () => + { + var (_, _, _, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + return new object(); + }); + Assert.NotNull(started); + Assert.Single(_cache.GetAll()); + simulation.Discard(_cache); + Assert.Empty(_cache.GetAll()); + + Launch(new DemoTerminus(), Inputs(() => 2)); + Assert.Single(_cache.GetAll()); + RunSave.Clear(_cache); + Assert.Empty(_cache.GetAll()); + + // A stage that queues an order and then fails writes nothing. + var (_, _, staged, refused) = Launch(new Scripted(false, stage => + { + var station = stage.Arena.Entities.OfType().First(); + stage.HaulOrder("refused", station, station, new[] { new CultRecordRef(new CultRecordKey("commodity:iron")) }, "scenario:test"); + stage.Station("no-such-kind"); + stage.Player(stage.Generated(""), float2.zero); + }), Inputs()); + Assert.Null(staged); + Assert.Contains(refused, failure => failure.Contains("no-such-kind")); + Assert.DoesNotContain(refused, failure => failure.Contains("orbit")); + Assert.Empty(_cache.GetAll()); + } + + // Generated gear stock stops at half the stock bay: every demo station keeps at least (1 - StationStockShare) of its cells free. + [Fact] + public void GeneratedStockLeavesRoom() + { + foreach (var seed in new uint[] { 1, 2, 3, 4, 5, 69, 97 }) + { + var (_, arena, _, failures) = Launch(new DemoTerminus(), Inputs(() => seed)); + Assert.True(failures.Count == 0, $"seed {seed}: " + string.Join("; ", failures)); + foreach (var station in arena.Entities.OfType().Where(entity => entity.HullData.HullType == HullType.Station)) + { + var bay = station.CargoBays.First(candidate => !(candidate.Data is SiloData)); + var cells = bay.Data.InteriorShape.Coordinates.Length; + var free = bay.Data.InteriorShape.Coordinates.Count(cell => bay.Occupancy[cell.x, cell.y] == null); + var floor = cells - (int) (cells * LoadoutGenerator.StationStockShare); + Assert.True(free >= floor, $"seed {seed} {station.Name}: {free} of {cells} cells free, at least {floor} wanted"); + } + } + } +} diff --git a/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs new file mode 100644 index 000000000..39842e4f0 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs @@ -0,0 +1,253 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using Xunit; + +// Substance clean break (aetheria-release:ruling:clean-break-from-substance, cut remove-sbsar-files). The 41 .sbsar +// files, their importer and the SUBSTANCE_PLUGIN_ENABLED define are gone, and nothing that survives may point into +// them. Headless: no Unity is open, so a dangling GUID is caught here instead of rendering pink in the editor. +public sealed class SubstanceCleanBreakTests +{ + // Every guid the removed tree owned, captured from the .meta files before deletion: the 41 .sbsar.meta, the two + // folder metas (Assets/Materials/Substance.meta, Substance/Metal.meta) and the importer script guid + // (43a8bbf6..., the `script:` line of every .sbsar.meta, whose plugin was already absent). + private static readonly string[] Tombstones = + { + "06833951ebae4cc45ad88d58cb5571de", + "06d6a565d43fba5409712ce9a10bfbef", + "07f679eadba9fb14abac26b1e165f7d5", + "092bdd8d243488141aeab5bb0d72429a", + "09aee558716a08d4c9806b9b4273a209", + "0b5dfc86c0681a3459a57d197804191b", + "0be5fb1df83ac8e499a3f6a060041e49", + "130f566ffa0b2424fbb47de2194c136a", + "180b85899b4b1f848b348230339ce984", + "1c858fec5b74c7c46b1712494192b6b5", + "26a894e543f3ed44893b1620707ca62c", + "2b42584452fe0cc4fa4e8a115230b156", + "2be0f689f5b01be4aa1032bc86f15eab", + "2e9a9dbacde66a446852af882f33e9e2", + "43a8bbf65be290d44ba52b94476242b9", + "4e39297ae4fe9ee4b803c04eabb69da7", + "50192727b92e0af4cbe5c773bec3537f", + "504c7bfe0d50ff64a88b8eac2ceb46f8", + "53adf8e53222e6f4791d7bf2110fb70c", + "58e16b7dbc1c31f4585e11544cdce127", + "6b2eb94965ca27542b8627d3521f5b5b", + "7363fcc4a3c41a349b29de7ec34555be", + "7de1c11cf7591ec48bdb53e9818172f5", + "8249e9ffcbd97c84d8ce73343e156c82", + "885e680924fc12c439a842a2142d4b78", + "9458f33b8e7e51a42aa19686b9779d82", + "9aa51bbe4dd46874a906608c34a739e4", + "9d0963470d3545a4e932ed4ea95b9d62", + "9fc901afb8a434e46b9405eaec2df5a4", + "a1d39ea984432bf44b4a0686afe2bf1a", + "a74970be876d3554ea0f279f39314c9c", + "afbd691d0ea2a5a47b5a43b244593a56", + "b2bec4b400153d745b2915f1c43e5c96", + "b7e648471e9dfc44490bd41973711541", + "c00b5a4f1e4743a4ca59b8030251f900", + "c5f2177e1f35daa499f4d7e0b7f3370a", + "ca8f080ab60226e4097841eee2bfa8db", + "cbc61995a46604441ab9de4f1c68e290", + "d15fc45ed0000934d946b5f271f637ef", + "ddc6970cc883b9845bdadc91983130c2", + "deb7e15e5f95294498d18869d9f11302", + "e7758cad28ae98f478940e55222419a6", + "ea7457b9a4f0bcb43becaa33de541cbd", + "ef9a54b8dacea9f44be70da43472f701", + }; + + private static readonly string[] PrefabsAndMetasEditedByTheCut = + { + "Assets/Content/Prefabs/Turrets/Turret.prefab", "Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab", + "Assets/Prefabs/RPG/Pickups/Hexahedron.prefab", "Assets/Prefabs/RPG/Pickups/Icosahedron.prefab", + "Assets/Prefabs/RPG/Pickups/Octahedron.prefab", "Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab", + "Assets/Models/Zenith_Blender.fbx.meta", + }; + + // A material reference (main object fileID 2100000). Script guids in the same files resolve to Unity packages, + // which have no .meta under Assets/, so only material slots are checked. + private static readonly Regex MaterialRef = new(@"fileID:\s*2100000,\s*guid:\s*([0-9a-f]{32})", RegexOptions.Compiled); + + private static readonly string[] ExcludedDirs = { ".git", "node_modules", ".voidbot" }; + + private static readonly string[] RepointedMaterials = + { + "Assets/Materials/Steel.mat", "Assets/Materials/Aluminium brushed.mat", "Assets/Materials/Silver.mat", + "Assets/Materials/Steel parkerized.mat", "Assets/Materials/Cockpit.mat", "Assets/Materials/Metal 003.mat", + "Assets/Materials/Car Paint Red.mat", "Assets/Materials/Car Paint Magenta.mat", + "Assets/Materials/Car Paint White.mat", "Assets/Materials/Car Paint White Small.mat", + "Assets/Materials/Radiators.mat", "Assets/Materials/Station Lights.mat", "Assets/Materials/Mine Glow.mat", + "Assets/Models/Discobolus/Discobolus Marble.mat", "Assets/Materials/Pickup Trim.mat", + }; + + private static IEnumerable Walk(string dir) + { + foreach (var file in Directory.EnumerateFiles(dir)) yield return file; + foreach (var sub in Directory.EnumerateDirectories(dir)) + if (!ExcludedDirs.Contains(Path.GetFileName(sub))) + foreach (var file in Walk(sub)) yield return file; + } + + // A checkout that holds Git LFS pointers instead of content cannot be scanned. The guards that read LFS-tracked + // files fail loudly here: skipping would pass vacuously, and a failure says "smudge the LFS objects first". + private static bool IsLfsPointer(string path) + { + using var stream = File.OpenRead(path); + var head = new byte[48]; + var n = stream.Read(head, 0, head.Length); + return Encoding.ASCII.GetString(head, 0, n).StartsWith("version https://git-lfs", StringComparison.Ordinal); + } + + private static string ReadTextOrFailOnPointer(string path) + { + Assert.False(IsLfsPointer(path), $"{path} is an LFS pointer, not content: this guard cannot see inside it. Run `git lfs pull`."); + return File.ReadAllText(path, Encoding.Latin1); + } + + // Everything is scanned except known binary media (a denylist, so an unlisted serialized type is still read) and, + // for unlisted extensions, files with a NUL byte in the first 8 KiB. The extension check comes first because an + // LFS pointer for a texture is itself text and says nothing about what the object holds. + private static readonly string[] BinaryExtensions = + { + ".png", ".jpg", ".jpeg", ".tga", ".tif", ".tiff", ".psd", ".bmp", ".gif", ".exr", ".hdr", ".dds", ".wav", ".mp3", + ".ogg", ".mp4", ".fbx", ".glb", ".blend", ".ttf", ".otf", ".dll", ".so", ".pdb", ".msgpack", ".zip", ".bank", + }; + + private static bool LooksBinary(string path) + { + if (BinaryExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase)) return true; + using var stream = File.OpenRead(path); + var buf = new byte[8192]; + var n = stream.Read(buf, 0, buf.Length); + return Array.IndexOf(buf, (byte)0, 0, n) >= 0; + } + + private static Dictionary GuidToMeta(string root) + { + var map = new Dictionary(); + foreach (var meta in Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*.meta", SearchOption.AllDirectories)) + { + var guid = File.ReadLines(meta).FirstOrDefault(l => l.StartsWith("guid: "))?.Substring("guid: ".Length).Trim(); + if (guid == null) continue; + // A .meta whose asset is gone still carries the guid, so resolution must look beside it: the asset is the + // .meta path minus ".meta". Directory metas resolve to a folder. + var asset = meta.Substring(0, meta.Length - ".meta".Length); + if (File.Exists(asset) || Directory.Exists(asset)) map[guid] = Path.GetRelativePath(root, meta).Replace('\\', '/'); + } + return map; + } + + [Fact] + public void NoSbsarFileOrMetaRemains() + { + var root = RestoredHullsTests.FindRepoRoot(); + var stray = Walk(root).Where(f => f.EndsWith(".sbsar", StringComparison.OrdinalIgnoreCase) + || f.EndsWith(".sbsar.meta", StringComparison.OrdinalIgnoreCase)) + .Select(f => Path.GetRelativePath(root, f)).ToList(); + Assert.True(stray.Count == 0, $"{stray.Count} Substance archive files remain, first: {stray.FirstOrDefault()}"); + Assert.False(Directory.Exists(Path.Combine(root, "Assets", "Materials", "Substance"))); + } + + [Fact] + public void NoSurvivingFileNamesARemovedSubstanceGuid() + { + var root = RestoredHullsTests.FindRepoRoot(); + var files = new[] { "Assets", "Packages", "ProjectSettings" } + .Select(d => Path.Combine(root, d)).Where(Directory.Exists) + .SelectMany(Walk) + .Concat(Directory.Exists(Path.Combine(root, "GameData")) + ? Directory.EnumerateFiles(Path.Combine(root, "GameData"), "*.cc") : Enumerable.Empty()) + .Where(f => f.EndsWith(".cc") || !LooksBinary(f)) + .ToList(); + var pointers = files.Where(IsLfsPointer).Select(f => Path.GetRelativePath(root, f)).ToList(); + Assert.True(pointers.Count == 0, + $"{pointers.Count} scanned files are LFS pointers, not content (first: {pointers.FirstOrDefault()}); run `git lfs pull`."); + var hits = new List(); + foreach (var file in files) + { + var lines = File.ReadAllText(file, Encoding.Latin1).Split('\n'); + for (var i = 0; i < lines.Length; i++) + foreach (var guid in Tombstones) + if (lines[i].Contains(guid, StringComparison.Ordinal)) + hits.Add($"{Path.GetRelativePath(root, file)}:{i + 1} names {guid}"); + } + Assert.True(hits.Count == 0, $"{hits.Count} references to removed Substance guids:\n" + string.Join("\n", hits.Take(40))); + } + + [Fact] + public void NoSubstanceBuildSurface() + { + var root = RestoredHullsTests.FindRepoRoot(); + Assert.DoesNotContain("SUBSTANCE", ReadTextOrFailOnPointer(Path.Combine(root, "ProjectSettings", "ProjectSettings.asset")), StringComparison.Ordinal); + foreach (var name in new[] { "manifest.json", "packages-lock.json" }) + { + var text = File.ReadAllText(Path.Combine(root, "Packages", name)); + Assert.DoesNotContain("substance", text, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("allegorithmic", text, StringComparison.OrdinalIgnoreCase); + } + Assert.DoesNotContain("sbsar", File.ReadAllText(Path.Combine(root, ".gitattributes")), StringComparison.OrdinalIgnoreCase); + Assert.False(Directory.Exists(Path.Combine(root, "Assets", "Allegorithmic"))); + } + + [Fact] + public void EveryReplacementTextureResolves() + { + var root = RestoredHullsTests.FindRepoRoot(); + var guidToMeta = GuidToMeta(root); + + var texture = new Regex(@"m_Texture:\s*\{fileID:\s*(-?\d+)(?:,\s*guid:\s*([0-9a-f]{32}))?", RegexOptions.Compiled); + var problems = new List(); + foreach (var rel in RepointedMaterials) + { + var path = Path.Combine(root, rel); + if (!File.Exists(path)) { problems.Add($"{rel} does not exist"); continue; } + var text = File.ReadAllText(path); + var start = text.IndexOf("m_TexEnvs:", StringComparison.Ordinal); + var end = text.IndexOf("m_Floats:", StringComparison.Ordinal); + Assert.True(start >= 0 && end > start, $"{rel} has no m_TexEnvs section"); + foreach (Match m in texture.Matches(text.Substring(start, end - start))) + { + if (m.Groups[1].Value == "0") continue; + if (!m.Groups[2].Success) { problems.Add($"{rel} has a nonzero texture fileID with no guid: {m.Value}"); continue; } + var guid = m.Groups[2].Value; + if (!guidToMeta.TryGetValue(guid, out var meta)) problems.Add($"{rel} names {guid}, which has no .meta and asset under Assets/"); + else if (meta.StartsWith("Assets/Materials/Substance", StringComparison.Ordinal)) problems.Add($"{rel} names {guid} inside the removed Substance tree"); + else if (!File.ReadLines(Path.Combine(root, meta)).Any(l => l.StartsWith("TextureImporter:", StringComparison.Ordinal))) + problems.Add($"{rel} texture slot names {guid} ({meta}), which is not a TextureImporter asset"); + } + } + Assert.True(problems.Count == 0, string.Join("\n", problems)); + } + + [Fact] + public void EveryRepointedPrefabAndFbxSlotResolves() + { + var root = RestoredHullsTests.FindRepoRoot(); + var guidToMeta = GuidToMeta(root); + var problems = new List(); + foreach (var rel in PrefabsAndMetasEditedByTheCut) + { + var path = Path.Combine(root, rel); + if (!File.Exists(path)) { problems.Add($"{rel} does not exist"); continue; } + var lines = ReadTextOrFailOnPointer(path).Split('\n'); + for (var i = 0; i < lines.Length; i++) + foreach (Match m in MaterialRef.Matches(lines[i])) + { + var guid = m.Groups[1].Value; + if (!guidToMeta.TryGetValue(guid, out var meta)) problems.Add($"{rel}:{i + 1} names {guid}, which has no .meta and asset under Assets/"); + else if (!meta.EndsWith(".mat.meta", StringComparison.Ordinal)) problems.Add($"{rel}:{i + 1} material slot names {guid} ({meta}), which is not a .mat"); + } + } + Assert.True(problems.Count == 0, string.Join("\n", problems.Take(40))); + } +} diff --git a/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs b/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs index 37eafc01a..b17248ff4 100644 --- a/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs +++ b/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs @@ -181,17 +181,16 @@ public sealed class SunsNeverGreenTests : IDisposable cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(catalog), AetheriaStores.CatalogTypes); cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var tutorial = authored.Read("TutorialGenerationSettings"); - var galaxy = new Galaxy(tutorial, authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var tutorial = TestCasts.Wide; + var galaxy = new Galaxy(tutorial, authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); var zoneSettings = authored.Read("ZoneSettings"); adjust(zoneSettings); foreach (var zone in galaxy.Zones) { zones++; - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, false, false); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, EntranceStationOrder.None, false); suns.AddRange(pack.Planets.Select(p => cache.Get(p)).OfType()); } } diff --git a/tests/Aetheria.Shared.Tests/TacticalInputTests.cs b/tests/Aetheria.Shared.Tests/TacticalInputTests.cs new file mode 100644 index 000000000..fbd7f40f6 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/TacticalInputTests.cs @@ -0,0 +1,108 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Text.Json; +using CultMath; +using Xunit; + +// Ruling tactical-input-hands-off: ship input pauses in the tactical view, view input stays live, and no action is left out. +public sealed class TacticalInputTests +{ + private static TacticalView Flight() + { + var view = new TacticalView(1.25f, 250, 1000, .01f, 2, .6f, .4f, .15f); + view.Reset(20000, 30, new float2(0, 0)); + return view; + } + + private static TacticalView Tactical() + { + var view = Flight(); + for (var i = 0; i < 30 && !view.Tactical; i++) { view.Tick(.05f); view.Scroll(1); } + Assert.True(view.Tactical); + return view; + } + + private static List Actions() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir != null && !File.Exists(Path.Combine(dir.FullName, "Assets", "Resources", "Aetheria.inputactions"))) + dir = dir.Parent; + Assert.NotNull(dir); + using var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(dir.FullName, "Assets", "Resources", "Aetheria.inputactions"))); + return doc.RootElement.GetProperty("maps").EnumerateArray() + .Where(m => m.GetProperty("name").GetString() is "Player" or "Global") + .SelectMany(m => m.GetProperty("actions").EnumerateArray() + .Select(a => m.GetProperty("name").GetString() + "/" + a.GetProperty("name").GetString())) + .ToList(); + } + + // The one route: every Player and Global action ActionGameManager touches is an argument of Bind, TryRead, Held, ActiveControl or + // Live, and only Bind subscribes. A callback or a read outside them would skip TacticalInput. + [Fact] + public void ActionGameManagerTouchesEveryShipInputActionThroughTheOneHelper() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir != null && !File.Exists(Path.Combine(dir.FullName, "Assets", "Scripts", "Gameplay", "ActionGameManager.cs"))) + dir = dir.Parent; + Assert.NotNull(dir); + var source = File.ReadAllText(Path.Combine(dir.FullName, "Assets", "Scripts", "Gameplay", "ActionGameManager.cs")); + var uses = Regex.Matches(source, @"\bInput\.(Player|Global)\.(?!Enable\b|Disable\b)\w+").Count; + var routed = Regex.Matches(source, @"\b(Bind|TryRead|Held|ActiveControl|Live)(<[^>(]*>)?\(\s*Input\.(Player|Global)\.\w+").Count; + Assert.True(uses > 20); + Assert.Equal(uses, routed); + Assert.Equal(1, Regex.Matches(source, @"\.performed\s*\+=").Count); + } + + [Fact] + public void EveryPlayerAndGlobalActionIsClassifiedAsShipOrViewInput() + { + var actions = Actions(); + Assert.True(actions.Count > 20); + var listed = TacticalInput.Classified.ToList(); + Assert.Empty(actions.Except(listed)); + Assert.Empty(listed.Except(actions)); + Assert.Equal(listed.Count, listed.Distinct().Count()); + } + + [Fact] + public void ShipInputPausesInTacticalAndViewInputStaysLive() + { + var flight = Flight(); + var tactical = Tactical(); + foreach (var action in TacticalInput.Classified) + { + var map = action.Split('/')[0]; + var name = action.Split('/')[1]; + Assert.True(TacticalInput.Live(flight, map, name), action); + Assert.Equal(!TacticalInput.IsShip(map, name), TacticalInput.Live(tactical, map, name)); + } + foreach (var live in new[] { "Zoom", "Pan", "Point", "Minimap Zoom", "Hide UI" }) + Assert.True(TacticalInput.Live(tactical, "Player", live), live); + foreach (var paused in new[] { "Move", "Look", "Turn", "Tractor Beam", "Ping", "Toggle Shield" }) + Assert.False(TacticalInput.Live(tactical, "Player", paused), paused); + Assert.False(TacticalInput.Live(tactical, "Global", "Interact")); + } + + [Fact] + public void AnUnclassifiedActionIsNotLiveEvenInFlight() + { + Assert.False(TacticalInput.Live(Flight(), "Player", "Warp Drive")); + } + + [Fact] + public void ShipInputIsLiveAgainOnReturnToTheFlightView() + { + var view = Tactical(); + Assert.False(TacticalInput.Live(view, "Player", "Move")); + for (var i = 0; i < 40 && view.Tactical; i++) { view.Tick(.05f); view.Scroll(-1); } + Assert.False(view.Tactical); + Assert.True(TacticalInput.Live(view, "Player", "Move")); + } +} diff --git a/tests/Aetheria.Shared.Tests/TacticalViewTests.cs b/tests/Aetheria.Shared.Tests/TacticalViewTests.cs new file mode 100644 index 000000000..cecc698af --- /dev/null +++ b/tests/Aetheria.Shared.Tests/TacticalViewTests.cs @@ -0,0 +1,460 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using CultMath; +using Xunit; + +// TacticalView owns the view: one eased log-distance axis with a detent between flight and tactical. Blend and time rate +// are derived from the eased distance, never stored. The constants are the placeholders GameSettings holds for the operator. +public sealed class TacticalViewTests +{ + private const float Radius = 20000, Fit = 2, Start = 250, End = 1000, Scale = .01f, BaseDistance = 30; + private const float Step = 1.25f, Resistance = .6f, Relax = .4f, Ease = .15f; + private static readonly float LnStep = MathF.Log(Step); + + private static TacticalView Make(float radius = Radius) + { + var view = new TacticalView(Step, Start, End, Scale, Fit, Resistance, Relax, Ease); + view.Reset(radius, BaseDistance, new float2(100, -50)); + return view; + } + + // Notches at a rate: the real time between them is ticked first, so a held scroll feeds the relaxation too. + private static void Flick(TacticalView view, int notches, float perSecond, float direction = 1) + { + for (var i = 0; i < notches; i++) + { + view.Tick(1 / perSecond); + view.Scroll(direction); + } + } + + // A fast scroll, 20 notches a second, until the view changes; the notches it took. + private static int Cross(TacticalView view, float direction = 1) + { + var was = view.Tactical; + var notches = 0; + while (view.Tactical == was && notches < 30) + { + view.Tick(.05f); + view.Scroll(direction); + notches++; + } + return notches; + } + + private static void Settle(TacticalView view) + { + for (var i = 0; i < 200; i++) view.Tick(.02f); + } + + // The flight's farthest edge: ten notches carry it just into the band, and the band relaxes it to the edge. + private static void ToFlightEdge(TacticalView view) + { + view.Scroll(10); + Settle(view); + Assert.Equal(MathF.Log(Start), view.Commanded, 3); + } + + [Fact] + public void ScrollMovesFreelyInsideEachView() + { + var view = Make(); + var lnBase = MathF.Log(BaseDistance); + view.Scroll(-5); + Assert.Equal(lnBase, view.Commanded, 5); + view.Scroll(3); + Assert.Equal(lnBase + 3 * LnStep, view.Commanded, 4); + view.Scroll(-1); + Assert.Equal(lnBase + 2 * LnStep, view.Commanded, 4); + Assert.False(view.Tactical); + + ToFlightEdge(view); + Assert.InRange(Cross(view), 1, 12); + Assert.True(view.Tactical); + Assert.Equal(MathF.Log(End), view.Commanded, 4); + view.Scroll(2); + Assert.Equal(MathF.Log(End) + 2 * LnStep, view.Commanded, 4); + view.Scroll(-1); + Assert.Equal(MathF.Log(End) + LnStep, view.Commanded, 4); + view.Scroll(500); + Assert.Equal(MathF.Log(Radius * Fit), view.Commanded, 4); + // A zone smaller than the band's far edge still reaches that edge and no farther. + var tiny = Make(10); + ToFlightEdge(tiny); + Cross(tiny); + tiny.Scroll(100); + Assert.Equal(MathF.Log(End), tiny.Commanded, 4); + } + + [Fact] + public void DetentHoldsASlowScroll() + { + var view = Make(); + ToFlightEdge(view); + Flick(view, 40, 5); + Assert.False(view.Tactical); + Assert.True(view.Commanded > MathF.Log(Start)); + Settle(view); + Assert.Equal(MathF.Log(Start), view.Commanded, 3); + Assert.False(view.Tactical); + } + + [Fact] + public void DetentYieldsToAFastScroll() + { + var view = Make(); + ToFlightEdge(view); + var notches = 0; + while (!view.Tactical && notches < 10) + { + view.Tick(.05f); + view.Scroll(1); + notches++; + } + Assert.True(view.Tactical); + Assert.Equal(MathF.Log(End), view.Commanded, 5); + } + + [Fact] + public void DetentIsSymmetric() + { + var view = Make(); + ToFlightEdge(view); + Assert.InRange(Cross(view), 1, 12); + Assert.True(view.Tactical); + Settle(view); + Flick(view, 40, 5, -1); + Assert.True(view.Tactical); + Settle(view); + Assert.Equal(MathF.Log(End), view.Commanded, 3); + Assert.InRange(Cross(view, -1), 1, 12); + Assert.False(view.Tactical); + Assert.Equal(MathF.Log(Start), view.Commanded, 5); + } + + [Fact] + public void TickNeverFlipsTactical() + { + // The commanded position sampled across the whole band, from both views, then ticked every which way. + foreach (var fromTactical in new[] { false, true }) + foreach (var notches in new[] { 1, 2, 3, 4, 5, 6 }) + foreach (var dt in new[] { .001f, .05f, .4f, 3f, 100f }) + { + var view = Make(); + ToFlightEdge(view); + if (fromTactical) Assert.InRange(Cross(view), 1, 12); + view.Scroll(fromTactical ? -notches : notches); + var was = view.Tactical; + for (var i = 0; i < 5; i++) + { + view.Tick(dt); + Assert.Equal(was, view.Tactical); + } + } + } + + [Fact] + public void BlendFollowsTheEasedDistance() + { + var view = Make(); + ToFlightEdge(view); + var before = view.Distance; + Cross(view); + Assert.True(view.Tactical); + // The committing scroll moved the commanded position, not the camera: the eased distance is still near flight's edge. + Assert.True(view.Distance < End); + var last = view.Distance; + var lastBlend = view.Blend(last); + Assert.True(last >= before - 1e-3f); + for (var i = 0; i < 600; i++) + { + view.Tick(.005f); + Assert.True(view.Distance >= last - 1e-3f); + Assert.True(view.Distance <= End * 1.0001f); + Assert.True(view.Blend(view.Distance) >= lastBlend - 1e-6f); + last = view.Distance; + lastBlend = view.Blend(last); + } + Assert.Equal(End, view.Distance, 0); + Assert.Equal(1f, view.Blend(view.Distance), 2); + } + + [Fact] + public void RightAfterACommitDistanceAndBlendAreUnchanged() + { + var view = Make(); + ToFlightEdge(view); + var distance = view.Distance; + var blend = view.Blend(distance); + for (var i = 0; i < 8; i++) view.Scroll(1); + Assert.True(view.Tactical); + Assert.Equal(distance, view.Distance, 3); + Assert.Equal(blend, view.Blend(view.Distance), 5); + } + + [Fact] + public void TargetTracksTheShipOnlyInFlight() + { + var view = Make(); + Assert.Equal(new float2(100, -50), view.Target); + view.Pan(new float2(5, 5)); + Assert.Equal(new float2(100, -50), view.Target); + view.Track(new float2(7, 8)); + Assert.Equal(new float2(7, 8), view.Target); + ToFlightEdge(view); + Cross(view); + Assert.True(view.Tactical); + Settle(view); + view.Track(new float2(-900, 900)); + Assert.Equal(new float2(7, 8), view.Target); + view.Pan(new float2(10, -4)); + Assert.Equal(new float2(17, 4), view.Target); + view.Pan(new float2(1e6f, 0)); + Assert.Equal(Radius, MathF.Sqrt(view.Target.x * view.Target.x + view.Target.y * view.Target.y), 1); + view.Reset(Radius, BaseDistance, new float2(3, 4)); + Assert.Equal(new float2(3, 4), view.Target); + Assert.False(view.Tactical); + } + + [Fact] + public void BlendRisesMonotonicallyAcrossTheBand() + { + var view = Make(); + Assert.Equal(0f, view.Blend(BaseDistance)); + Assert.Equal(0f, view.Blend(Start)); + Assert.Equal(1f, view.Blend(End)); + Assert.Equal(1f, view.Blend(Radius * Fit)); + var last = 0f; + for (var distance = Start; distance <= End; distance += 5) + { + var blend = view.Blend(distance); + Assert.InRange(blend, last, 1f); + last = blend; + } + Assert.InRange(view.Blend(Start * 1.01f), 0f, .05f); + Assert.InRange(view.Blend(End / 1.01f), .95f, 1f); + } + + // The band is smoothstep over the logarithm of distance: a quarter, half and three quarters of the way up in ln + // are 250 x 4^t m, and the thresholds themselves are the 250 m and 1000 m the operator tunes by eye (GameSettings). + [Fact] + public void BlendIsSmoothstepOverLogDistanceBetweenTheThresholds() + { + var view = Make(); + Assert.Equal(.15625f, view.Blend(250f * MathF.Pow(4, .25f)), 3); + Assert.Equal(.5f, view.Blend(500f), 3); + Assert.Equal(.84375f, view.Blend(250f * MathF.Pow(4, .75f)), 3); + Assert.Equal(0f, view.Blend(249f)); + Assert.Equal(1f, view.Blend(1001f)); + } + + [Fact] + public void TimeRateIsTheScaleToTheBlendPowerNotLinear() + { + var view = Make(); + Assert.Equal(.1f, view.TimeRate(.5f), 5); + Assert.Equal(MathF.Pow(.01f, .25f), view.TimeRate(.25f), 5); + Assert.Equal(MathF.Pow(.01f, .75f), view.TimeRate(.75f), 5); + Assert.Equal(1f, view.TimeRate(-1)); + Assert.Equal(Scale, view.TimeRate(2), 6); + } + + [Fact] + public void TimeRateIsOneInFlightAndTheScaleInTactical() + { + var view = Make(); + Assert.Equal(1f, view.TimeRate(0)); + Assert.Equal(Scale, view.TimeRate(1), 6); + var last = 1f; + for (var blend = 0f; blend <= 1f; blend += .05f) + { + var rate = view.TimeRate(blend); + Assert.InRange(rate, Scale - 1e-6f, last); + last = rate; + } + // Flying never sees it: every distance at or under the near edge runs at full speed. + Assert.Equal(1f, view.TimeRate(view.Blend(Start))); + } + + // The committed notch count of a held scroll at a rate, ticked between notches; 0 if it never crosses in 200. + private static int HeldCrossing(float perSecond) + { + var view = Make(); + ToFlightEdge(view); + for (var i = 1; i <= 200; i++) + { + view.Tick(1 / perSecond); + view.Scroll(1); + if (view.Tactical) return i; + } + return 0; + } + + [Fact] + public void TenNotchesASecondHoldsAndFifteenCrosses() + { + Assert.Equal(0, HeldCrossing(10)); + Assert.InRange(HeldCrossing(15), 1, 12); + // The ruled claim sits clear of the boundary on both sides, so a softened or stiffened detent is red. + Assert.Equal(0, HeldCrossing(8)); + Assert.InRange(HeldCrossing(20), 1, 10); + } + + [Fact] + public void ACrestAtTheBandsMidpointSplitsATwoNotchPushBothWays() + { + // One notch into the band stays in flight; the commit lands only past the crest, not after a fixed few notches. + var view = Make(); + ToFlightEdge(view); + view.Scroll(1); + Assert.False(view.Tactical); + Assert.True(view.Commanded > MathF.Log(Start)); + Assert.True(view.Commanded < (MathF.Log(Start) + MathF.Log(End)) / 2); + Assert.Equal(MathF.Log(Start) + LnStep * Resistance, view.Commanded, 3); + } + + // Eased from rest, critically damped: ln d(t) = c - offset (1 + wt) e^(-wt), w = 2 / EaseTime. + [Fact] + public void TheEaseIsACriticallyDampedSpringNotASnap() + { + var view = Make(); + var lnBase = MathF.Log(BaseDistance); + view.Scroll(2); + Assert.Equal(BaseDistance, view.Distance, 4); + view.Tick(.05f); + var w = 2 / Ease; + var expected = lnBase + 2 * LnStep * (1 - (1 + w * .05f) * MathF.Exp(-w * .05f)); + Assert.Equal(MathF.Exp(expected), view.Distance, 3); + Assert.True(view.Distance < BaseDistance * 1.25f * 1.25f); + // The same step in two halves lands at the same place: the solution is exact at any dt. + var halves = Make(); + halves.Scroll(2); + halves.Tick(.025f); + halves.Tick(.025f); + Assert.Equal(view.Distance, halves.Distance, 3); + } + + [Fact] + public void ResetClearsTheEasedPositionAndTheVelocity() + { + var view = Make(); + view.Scroll(4); + view.Tick(.05f); + Assert.NotEqual(BaseDistance, view.Distance); + view.Reset(Radius, BaseDistance, new float2(0, 0)); + Assert.Equal(BaseDistance, view.Distance, 4); + Assert.Equal(MathF.Log(BaseDistance), view.Commanded, 5); + view.Tick(.1f); + Assert.Equal(BaseDistance, view.Distance, 4); + } + + [Fact] + public void ANonPositiveTickChangesNothing() + { + var view = Make(); + ToFlightEdge(view); + view.Scroll(1); + view.Tick(.02f); + var commanded = view.Commanded; + var distance = view.Distance; + view.Tick(0); + view.Tick(-1); + Assert.Equal(commanded, view.Commanded, 6); + Assert.Equal(distance, view.Distance, 4); + } + + // The ruling: everything follows the eased distance. Flicking back from a panned tactical view must not move the + // camera's target by the pan offset in one frame; it returns to the ship with the rig's weight. + [Fact] + public void TargetReturnsToTheShipWithTheEasedCameraNotTheCommandedFlip() + { + var view = Make(); + var ship = new float2(100, -50); + ToFlightEdge(view); + Cross(view); + Settle(view); + view.Pan(new float2(12000, 0)); + view.Track(ship); + var panned = view.Target; + Assert.Equal(12100f, panned.x, 2); + view.Track(ship); + Assert.Equal(panned, view.Target); + + var last = view.Target; + var worst = 0f; + // A fast flick back at 20 notches a second, stepped at 5 ms frames, then settled: no frame moves it far. + for (var i = 0; i < 40 && view.Tactical; i++) + { + for (var frame = 0; frame < 10; frame++) + { + view.Tick(.005f); + view.Track(ship); + worst = MathF.Max(worst, MathF.Abs(view.Target.x - last.x)); + last = view.Target; + } + view.Scroll(-1); + worst = MathF.Max(worst, MathF.Abs(view.Target.x - last.x)); + last = view.Target; + } + Assert.False(view.Tactical); + for (var i = 0; i < 600; i++) + { + view.Tick(.005f); + view.Track(ship); + var step = MathF.Abs(view.Target.x - last.x); + worst = MathF.Max(worst, step); + last = view.Target; + } + Assert.True(worst < 12000 * .1f, "target stepped " + worst); + Assert.Equal(ship, view.Target); + } + + [Fact] + public void ThePanStartsFromTheShipOnEntry() + { + var view = Make(); + ToFlightEdge(view); + view.Track(new float2(500, 500)); + Cross(view); + Settle(view); + Assert.Equal(new float2(500, 500), view.Target); + } + + // Ruling tactical-input-hands-off: ActionGameManager takes keyboard flight, toggles, mouse look and fire only while Direct, + // so the ship holds its last commands through the tactical view and takes input again on return. + [Fact] + public void DirectInputIsTakenInFlightPausesInTacticalAndReturnsWithTheFlightView() + { + var view = Make(); + Assert.True(view.Direct); + Assert.False(view.Tactical); + + Cross(view); + Assert.True(view.Tactical); + Assert.False(view.Direct); + for (var i = 0; i < 40; i++) { view.Tick(.05f); Assert.False(view.Direct); } + + Cross(view, -1); + Assert.False(view.Tactical); + Assert.True(view.Direct); + + Cross(view); + view.Reset(Radius, BaseDistance, new float2(0, 0)); + Assert.True(view.Direct); + } + + [Fact] + public void DirectIsPausedExactlyWhereTacticalIsAtEveryNotchOfTheDetent() + { + var view = Make(); + for (var i = 0; i < 80; i++) + { + view.Scroll(i < 40 ? 1 : -1); + view.Tick(.02f); + Assert.Equal(!view.Tactical, view.Direct); + } + } +} diff --git a/tests/Aetheria.Shared.Tests/TestCasts.cs b/tests/Aetheria.Shared.Tests/TestCasts.cs new file mode 100644 index 000000000..05759557c --- /dev/null +++ b/tests/Aetheria.Shared.Tests/TestCasts.cs @@ -0,0 +1,18 @@ +// The two fixtures every cast-galaxy test builds from: the values the retired Settings.asset block held (Miss, Zhe, Luc, +// Aero and Finch, Adras, 64 zones, half influence), so every test galaxy is what it was. A test fixture is not new +// faction material (ruling miss-terris-belongs-to-emily-r3). +internal static class TestCasts +{ + internal static GalaxyCast Wide => new GalaxyCast + { + ProtagonistFaction = "Miss", AntagonistFaction = "Zhe", BufferFaction = "Luc", + NeutralFactions = new[] { "Aero", "Finch" }, QuestFaction = "Adras", LinkDensity = .5f, ZoneCount = 64, + InfluenceScale = .5f, + }; + + internal static SectorBackgroundSettings Background => new SectorBackgroundSettings + { + NoiseAmplitude = 1, NoiseOffset = .3f, NoiseGain = .7f, NoiseLacunarity = 2, NoiseFrequency = .1f, + NoisePosition = 536.5106f, CloudExponent = 10, CloudAmplitude = .01f, + }; +} diff --git a/tests/Aetheria.Shared.Tests/TestCatalog.cs b/tests/Aetheria.Shared.Tests/TestCatalog.cs index 60d41c996..2561406f2 100644 --- a/tests/Aetheria.Shared.Tests/TestCatalog.cs +++ b/tests/Aetheria.Shared.Tests/TestCatalog.cs @@ -18,6 +18,12 @@ internal static class TestCatalog // The repo's catalog with its first-party packages composed in, resolved once per test process. public static string Repo => Shared.Value; + private static readonly Lazy SharedWithFixtures = new Lazy(() => ForRepoWithFixtures(RunStartTests.FindRepoRoot())); + + // The repo's catalog with its first-party packages and the test fixture packages (tests/fixtures/mods) composed in. For a + // test whose subject is a fixture package; Repo is the catalog the game ships. + public static string RepoWithFixtures => SharedWithFixtures.Value; + // The shipped assembly's own [CultDocument] types and nothing the test assembly registers (CultDocumentRegistry.ForTypes // does not re-scan the AppDomain), so this assembly's fixture documents never become catalog globals the real catalog // must hold. The one registry every test that opens a real catalog, and the composition behind Repo, uses. @@ -34,6 +40,21 @@ internal static class TestCatalog return Resolve(Path.Combine(repoRoot, "GameData", "Aetheria.cc"), Path.Combine(repoRoot, "GameData", "Mods"), work); } + // ForRepo over a mods root assembled from GameData/Mods and tests/fixtures/mods, copied into the per-call temp directory. + public static string ForRepoWithFixtures(string repoRoot) + { + var work = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetheria-testcatalog-" + Guid.NewGuid().ToString("N"))).FullName; + AppDomain.CurrentDomain.ProcessExit += (_, _) => { try { Directory.Delete(work, true); } catch (IOException) { } }; + var mods = Path.Combine(work, "Mods"); + foreach (var root in new[] { Path.Combine(repoRoot, "GameData", "Mods"), Path.Combine(repoRoot, "tests", "fixtures", "mods") }) + foreach (var package in Directory.GetDirectories(root)) + { + var target = Directory.CreateDirectory(Path.Combine(mods, Path.GetFileName(package))).FullName; + foreach (var file in Directory.GetFiles(package)) File.Copy(file, Path.Combine(target, Path.GetFileName(file))); + } + return Resolve(Path.Combine(repoRoot, "GameData", "Aetheria.cc"), mods, work); + } + public static string Resolve(string shippedCatalog, string modsRoot, string workDir) { // Every directory under the first-party tree is a package. The game treats a directory without a ship.cc as not a diff --git a/tests/Aetheria.Shared.Tests/TrojanSwarmTests.cs b/tests/Aetheria.Shared.Tests/TrojanSwarmTests.cs index 3da5e77ab..e90184263 100644 --- a/tests/Aetheria.Shared.Tests/TrojanSwarmTests.cs +++ b/tests/Aetheria.Shared.Tests/TrojanSwarmTests.cs @@ -132,7 +132,7 @@ public class TrojanSwarmTests // C1 (one belt extent rule) with swarms off, over the zones of each seed; both samples draw no lane, so the base is the zone // with neither shape: a zone with no swarm is the base zone, and a zone with // swarms is the base zone plus them. The per-zone comparison leaves PopulatedRadius out, since a swarm's outer rock may grow it. - private static readonly Dictionary BaseDigest = new Dictionary + private static readonly Dictionary LinuxBaseDigest = new Dictionary { [1] = "1873400d50d11b27913a67daca460f0829629aa21dacabac2cfc97a66537a700", [2] = "5872680ee91c2019b345925f54c2113303cc2817ee9ea28d26ba839e43d1944e", @@ -142,6 +142,23 @@ public class TrojanSwarmTests [6] = "307dc4b38ff341670a5b5179ab977b6c7c59ba682d529d80dcaf9c4852c21fe2", }; + // The generator's zones come out different on Windows than on Linux (measured; the cause is not traced), so the swarmless zones' digests are + // per host class (ruling replays-per-host-class); the linux table above was computed on Yggdrasil. The windows table is the + // same cut's tree measured on windows-x64 (at d0fc8adb7, where the linux table was set, it measured identically). + private static readonly Dictionary> BaseDigests = new() + { + ["linux-x64"] = LinuxBaseDigest, + ["windows-x64"] = new Dictionary + { + [1] = "8ab09122f6c97cbbd24beebb9fab239302a947e039fa6271c2fec32260eeda2b", + [2] = "c7471235420889fc8267b14c54cfa91940bd53e9f76b289b7a57f31cef2d5504", + [3] = "1b9b7dcf9c4635c0a1efbc2781df4497192fd54488d76bcc312b309b03876e4b", + [4] = "72aea7f038281d7188900ccd7c31df409c62020e0fe2c64be1bde17ed08ca919", + [5] = "679b83ac406c1eee9c9f8a1c1733fa967a53fbbcce206172dce113abe599a90b", + [6] = "5da9181eef4c46a9c41a67936cbb2042e169016e6446477e008ace5ce446d8f0", + }, + }; + [Fact] public void ASwarmMovesNothingElseInTheZone() { @@ -149,12 +166,14 @@ public class TrojanSwarmTests using var live = new ChildrenWithinReachTests.Zones(First, Last, z => z.LaneProbability = 0); Assert.Equal(swarmless.All.Count, live.All.Count); int swarms = 0, grew = 0; - foreach (var seed in BaseDigest.Keys) + var host = RunStartTests.HostClass(); + Assert.True(BaseDigests.TryGetValue(host, out var baseDigest), $"swarmless zone digests: host class {host} has no pin; measured " + string.Join(",", LinuxBaseDigest.Keys.Select(seed => seed + "=" + ZoneFingerprint.Of(swarmless.All.Where(x => x.Seed == seed).Select(x => x.Zone).ToList(), _ => false, _ => false, true)))); + foreach (var seed in baseDigest.Keys) { var a = swarmless.All.Where(x => x.Seed == seed).Select(x => x.Zone).ToList(); var b = live.All.Where(x => x.Seed == seed).Select(x => x.Zone).ToList(); Assert.Empty(a.SelectMany(z => z.AsteroidBelts.Where(x => x.Value.Data.RidesRail))); - Assert.Equal(BaseDigest[seed], ZoneFingerprint.Of(a, _ => false, _ => false, true)); + Assert.Equal(baseDigest[seed], ZoneFingerprint.Of(a, _ => false, _ => false, true)); string Swarmed(Zone z) => ZoneFingerprint.Of(new[] { z }, SwarmRails(z).Contains, IsSwarm, false); for (var n = 0; n < a.Count; n++) { @@ -174,10 +193,12 @@ public class TrojanSwarmTests { var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ZonePack).Assembly); var saved = MessagePackSerializer.Serialize(new AsteroidBeltData { Mass = 5, Asteroids = new[] { new Asteroid { Distance = 3, Phase = .2f } } }, options); - Assert.Equal(0x9C, saved[0]); // a fixarray of 12 slots, keys 0-11 - Assert.Equal(0xC2, saved[^1]); // its last slot, RidesRail, false - var old = saved[..^1]; - old[0] = 0x9B; + // keys 0-11 are the belt's own and key 23 is BodyData.Site, so the array is 24 slots (array16) with keys 12-23 nil + Assert.Equal(0xDC, saved[0]); + Assert.Equal(24, (saved[1] << 8) | saved[2]); + Assert.All(saved[^12..], slot => Assert.Equal(0xC0, slot)); + Assert.Equal(0xC2, saved[^13]); // RidesRail, false + var old = new byte[] { 0x9B }.Concat(saved[3..^13]).ToArray(); var belt = MessagePackSerializer.Deserialize(old, options); Assert.False(belt.RidesRail); Assert.Equal(3f, belt.Asteroids[0].Distance); diff --git a/tests/Aetheria.Shared.Tests/WrenPackageTests.cs b/tests/Aetheria.Shared.Tests/WrenPackageTests.cs index bb95cbb55..7313858d0 100644 --- a/tests/Aetheria.Shared.Tests/WrenPackageTests.cs +++ b/tests/Aetheria.Shared.Tests/WrenPackageTests.cs @@ -5,7 +5,7 @@ using Xunit; using static CultMath.math; using Random = CultMath.Random; -// GameData/Mods/aetheria.wren: a first-party package written by `ship-authoring starter --like Djinni`, then priced and given +// tests/fixtures/mods/aetheria.wren: a test fixture package, not shipped with the game, written by `ship-authoring starter --like Djinni`, then priced and given // an unoffered Aeronautics Unlimited product by `ship-authoring price` and `product`; its model is the starter's boxed // stand-in. It is the pipeline's proof from a hull package on disk to a ship that flies in the headless simulation: the // package composes into the catalog, its mounts take catalog gear, and the fitted ship moves under thrust. `fly` cannot @@ -19,7 +19,7 @@ public sealed class WrenPackageTests [Fact] public void TheStarterPackageIsInTheComposedCatalogWithTheStatsOfItsLike() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var hull = Wren(cache); var like = cache.GetByName("Djinni"); Assert.NotNull(hull); @@ -34,7 +34,7 @@ public sealed class WrenPackageTests [Fact] public void TheStarterIsMadeButNeverOffered() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var hull = Wren(cache); var product = Assert.Single(cache.GetAll(), p => p.Design.Key.Equals(ShipModCatalog.HullKey(Id))); Assert.Equal("Aeronautics Unlimited", cache.Get(product.Manufacturer).Name); @@ -47,17 +47,16 @@ public sealed class WrenPackageTests [Fact] public void EveryMountTakesACatalogDesign() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var designs = cache.GetAll().ToArray(); var bare = Wren(cache).Hardpoints.Where(hardpoint => !designs.Any(hardpoint.Takes)).Select(hardpoint => $"{hardpoint.Transform} ({hardpoint.Type})").ToArray(); - // No shield design fits a 1x1 yet (hardpoint-fit lists Djinni's 4-cell shield with none either); every other mount does. - Assert.Equal(new[] { "internal.shield (Shield)" }, bare); + Assert.Empty(bare); } [Fact] public void TheStarterFliesUnderThrust() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var ship = RestoredHullsTests.BuildThrustedShip(cache, "Wren"); var start = ship.Velocity; ship.MovementDirection = float2(0, 1); diff --git a/tests/Aetheria.Shared.Tests/ZoneSiteTests.cs b/tests/Aetheria.Shared.Tests/ZoneSiteTests.cs new file mode 100644 index 000000000..0956eb65f --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ZoneSiteTests.cs @@ -0,0 +1,51 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// Zone body identity (cut zone-body-sites, ruling zone-body-site-identity): a generated body's key is minted by the cache and +// is identity only; its Site is the generation coordinate (zone seed, kind, place in the pack) that ore, tie-breaks, rock meshes +// and names read. Every input is the production one: the fixture galaxy, GenerateZone, the run store. +public sealed partial class RunStartTests +{ + private BodyData BodyOf(CultRecordRef body) => _cache.Get(body); + + // Replace and Beside generate a scenario of a saved run's seed beside the saved run in one store. + [Fact] + public void ASameSeedBesideItselfTouchesNoneOfTheFirstBodies() + { + var zone = _galaxy.Entrance; + var first = BossZonePack(_galaxy, _items, zone, ambient: false); + var held = first.Planets.Select(body => (body, Doc: BodyOf(body))).ToArray(); + var second = BossZonePack(_galaxy, _items, zone, ambient: false); + + Assert.Equal(first.Planets.Count, second.Planets.Count); + Assert.Empty(first.Planets.Select(body => body.Key).Intersect(second.Planets.Select(body => body.Key))); + Assert.Empty(first.Orbits.Select(orbit => orbit.Key).Intersect(second.Orbits.Select(orbit => orbit.Key))); + Assert.Equal(first.Planets.Select(body => BodyOf(body).Site), second.Planets.Select(body => BodyOf(body).Site)); + Assert.Equal(first.Planets.Select(body => BodyOf(body).Name), second.Planets.Select(body => BodyOf(body).Name)); + foreach (var (body, doc) in held) Assert.Same(doc, BodyOf(body)); + } + + [Fact] + public void EveryGeneratedBodyHasASiteUniqueInItsPack() + { + var swarms = 0; + var lanes = 0; + foreach (var zone in _galaxy.Zones) + { + var bodies = BossZonePack(_galaxy, _items, zone, ambient: false).Planets.Select(BodyOf).ToArray(); + Assert.All(bodies, body => Assert.False(string.IsNullOrEmpty(body.Site), $"{zone.Name} has a body with no Site")); + Assert.Equal(bodies.Length, bodies.Select(body => body.Site).Distinct().Count()); + Assert.All(bodies, body => Assert.Equal(BodyData.NameOf(body.Site), body.Name)); + swarms += bodies.Count(body => body.Site.Contains(":swarm:")); + lanes += bodies.Count(body => body.Site.Contains(":lane:")); + } + Assert.True(swarms > 0, "the fixture galaxy generated no trojan swarm"); + Assert.True(lanes > 0, "the fixture galaxy generated no laned belt"); + } +} diff --git a/tests/fixtures/catalog-resave/probe-v1.cc b/tests/fixtures/catalog-resave/probe-v1.cc new file mode 100644 index 000000000..3c94bd6ad Binary files /dev/null and b/tests/fixtures/catalog-resave/probe-v1.cc differ diff --git a/GameData/Mods/aetheria.wren/ship.cc b/tests/fixtures/mods/aetheria.wren/ship.cc similarity index 100% rename from GameData/Mods/aetheria.wren/ship.cc rename to tests/fixtures/mods/aetheria.wren/ship.cc diff --git a/tests/fixtures/mods/aetheria.wren/ship.glb b/tests/fixtures/mods/aetheria.wren/ship.glb new file mode 100644 index 000000000..08f3e5c7e --- /dev/null +++ b/tests/fixtures/mods/aetheria.wren/ship.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3980ea88075b07bece2f64f315fde34bb7214ae0c9fb40d766556e12bb4b8a5a +size 5872 diff --git a/tools/AetherDb/AetherDb.cs b/tools/AetherDb/AetherDb.cs index c65002d11..319dbecf9 100644 --- a/tools/AetherDb/AetherDb.cs +++ b/tools/AetherDb/AetherDb.cs @@ -1,31 +1,72 @@ using System; using System.IO; +using System.Linq; using GameCult.Caching; -// Opens GameData/Aetheria.cc through AetheriaStores, the game's own store composition. The catalog attaches read-only -// unless a command writes it, so a command that only reads cannot write. A station hull with no kind does not lock the +// Opens the catalog through AetheriaStores, the game's own store composition: OpenBooted for a read tool (the catalog the game boots), +// OpenShipped for the shipped GameData/Aetheria.cc alone, which attaches read-only unless a command writes it, so a command that only reads cannot write. A station hull with no kind does not lock the // catalog: it is named to warn (stderr by default) and the commands that repair it stay reachable. public sealed class AetherDb : IDisposable { public string Root { get; } public CultCache Cache { get; } - public void Dispose() => Cache.Dispose(); + // The compose directory withMods made, owned by this instance: the derived catalog is read from it until Dispose. + private readonly string _composed; - private AetherDb(string root, bool catalogWritable, bool withRun, Action warn) + public void Dispose() + { + Cache.Dispose(); + if (_composed != null) try { Directory.Delete(_composed, true); } catch (IOException) { } + } + + private AetherDb(string root, bool booted, bool withRun, Action warn, bool catalogWritable) { Root = root; var gameData = Path.Combine(root, "GameData"); - Cache = AetheriaStores.Open( - Path.Combine(gameData, "Aetheria.cc"), - runPath: withRun ? Path.Combine(gameData, "run.cc") : null, - catalogWritable: catalogWritable, - kindlessStation: warn ?? Console.Error.WriteLine); + var catalog = Path.Combine(gameData, "Aetheria.cc"); + if (booted) + { + // Derived and read-only, so a write through it would land in a temp file, never in Aetheria.cc: a write opens the shipped file alone. + _composed = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-mods-" + Guid.NewGuid().ToString("N"))).FullName; + try { catalog = ComposeBooted(root, _composed); } + catch { try { Directory.Delete(_composed, true); } catch (IOException) { } throw; } + } + try + { + Cache = AetheriaStores.Open( + catalog, + runPath: withRun ? Path.Combine(gameData, "run.cc") : null, + catalogWritable: catalogWritable, + kindlessStation: warn ?? Console.Error.WriteLine); + } + catch { if (_composed != null) try { Directory.Delete(_composed, true); } catch (IOException) { } throw; } } - // With no root given, walks up from the working directory to the game folder: the first folder whose GameData holds Aetheria.cc - public static AetherDb Open(bool catalogWritable = false, bool withRun = false, string root = null, Action warn = null) => - new AetherDb(root ?? FindRoot(), catalogWritable, withRun, warn); + // The one owner of "the catalog the game boots": the first-party packages in GameData/Mods composed (ShipModCatalog.ResolveCatalog) + // over a scratch copy of GameData/Aetheria.cc, inside the caller's scratch directory, which the caller owns and removes. Returns + // the path of the composed catalog to open read-only; the shipped file is never written. The game skips a broken package so a + // player still boots; a tool reading the catalog does not, so a package left out throws, naming it. + public static string ComposeBooted(string root, string scratch) + { + var copy = Path.Combine(scratch, "Aetheria.cc"); + File.Copy(Path.Combine(root, "GameData", "Aetheria.cc"), copy); + new FileInfo(copy).IsReadOnly = false; + var (composed, excluded) = ShipModCatalog.ResolveCatalog(copy, Path.Combine(scratch, "derived.cc"), Path.Combine(root, "GameData", "Mods")); + if (excluded.Length > 0) + throw new InvalidOperationException("First-party packages were excluded from the catalog: " + + string.Join("; ", excluded.Select(entry => entry.Package + ": " + entry.Reason))); + return composed; + } + + // The shipped GameData/Aetheria.cc alone, which is what an apply path (and its dry run) reads and writes. With no root given, walks up + // from the working directory to the game folder: the first folder whose GameData holds Aetheria.cc. + public static AetherDb OpenShipped(bool catalogWritable = false, bool withRun = false, string root = null, Action warn = null) => + new AetherDb(root ?? FindRoot(), false, withRun, warn, catalogWritable); + + // The catalog the game boots (see ComposeBooted), read-only: every read tool opens this. + public static AetherDb OpenBooted(bool withRun = false, string root = null, Action warn = null) => + new AetherDb(root ?? FindRoot(), true, withRun, warn, false); public static string FindRoot() { diff --git a/tools/AetherDb/CatalogResaveCommand.cs b/tools/AetherDb/CatalogResaveCommand.cs new file mode 100644 index 000000000..3b461defb --- /dev/null +++ b/tools/AetherDb/CatalogResaveCommand.cs @@ -0,0 +1,31 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System.IO; +using System.Linq; +using GameCult.Caching; + +// catalog resave [apply] (aetheria-living-world follow-up aetherdb-catalog-resave): re-saves every record the catalog holds +// under an older schema id through the current schema, so a schema change (an appended field, a restamped id) never needs a +// hand restamp of GameData/Aetheria.cc. The cache loads each record through the game's own types, so a record reads whole +// and an appended field takes its initializer; the write puts it under the current id. A record already under the current +// id is not written, so a second apply writes nothing. Dry run unless apply. +public static class CatalogResaveCommand +{ + public static int Run(CultCache catalog, bool apply, TextWriter output) + { + var stale = catalog.AllStoredDocuments.Where(stored => stored.StoredSchemaId != stored.Descriptor.SchemaId).ToArray(); + foreach (var group in stale.GroupBy(stored => stored.Descriptor.SchemaName).OrderBy(group => group.Key, System.StringComparer.Ordinal)) + output.WriteLine($"{group.Key}: {group.Count()} record(s) under an older schema id"); + output.WriteLine($"{stale.Length} record(s) would be re-saved"); + if (!apply || stale.Length == 0) return 0; + catalog.Commit(batch => + { + foreach (var stored in stale) batch.Upsert(stored.Descriptor.DocumentType, stored.Document, stored.Key); + }); + catalog.FlushAsync().GetAwaiter().GetResult(); + output.WriteLine($"{stale.Length} record(s) re-saved"); + return 0; + } +} diff --git a/tools/AetherDb/Economy/DemoOre.cs b/tools/AetherDb/Economy/DemoOre.cs deleted file mode 100644 index df2a2aff2..000000000 --- a/tools/AetherDb/Economy/DemoOre.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using GameCult.Caching; - -// Interim ore sheet (ruling mining-demo-ore-minimal-yields-now): the Asteroid field kind yields Rock, New Metals and Gold, and those -// three can be held (a 1x1 shape, a mass) and are sold (a price). The economy ores batch may rewrite the yields by element id. -// Prices are ruling mining-demo-ore-prices-gear-scale, gear-scale so the mine, sell, repair loop closes: a retune is an edit here and a rerun. -// Munitions and MunitionsFeed never rewrite these three commodities, so rerunning them does not clobber this sheet. -public sealed class DemoOre : EconomyBatch -{ - private const int RockPrice = 200; - private const int NewMetalsPrice = 1000; - private const int GoldPrice = 5000; - - // Authored element ids (the cache takes a hand-written id only as 12 lowercase hex): asteroid-rock, asteroid-new-metals, asteroid-gold. - private const string RockId = "a57e0c000001"; - private const string NewMetalsId = "a57e0c000002"; - private const string GoldId = "a57e0c000003"; - - public override void Author(EconomyAuthor author) - { - author.Edit("Rock", o => { o.Shape = new Shape(); o.Price = RockPrice; }); - author.Edit("New Metals", o => { o.Shape = new Shape(); o.Price = NewMetalsPrice; o.Mass = 2; }); - author.Edit("Gold", o => { o.Shape = new Shape(); o.Price = GoldPrice; }); - - var kinds = author.Catalog.GetAll().Where(k => k.Name == "Asteroid").ToArray(); - if (kinds.Length != 1) throw new InvalidOperationException($"{kinds.Length} field kinds are named 'Asteroid'; the ore sheet needs exactly one."); - var asteroid = kinds[0]; - asteroid.Yields = new List - { - Yield(author, "Rock", 6, RockId), - Yield(author, "New Metals", 3, NewMetalsId), - Yield(author, "Gold", 1, GoldId) - }; - author.Put(asteroid, author.Catalog.RefOf(asteroid).Key); - } - - private static FieldYield Yield(EconomyAuthor author, string name, float abundance, string id) - { - var item = author.Catalog.GetAll().Single(i => i.Name == name); - return new FieldYield { Commodity = new CultRecordRef(author.Catalog.RefOf(item).Key), Abundance = abundance, Regional = false, Id = id }; - } -} diff --git a/tools/AetherDb/Economy/Facilities.cs b/tools/AetherDb/Economy/Facilities.cs new file mode 100644 index 000000000..af1503738 --- /dev/null +++ b/tools/AetherDb/Economy/Facilities.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; + +// Economy content: the facility gear a station is fitted with to run its recipes (aetheria-living-world, cut recipe-facilities; +// rulings demand-consumed-inputs-processed-by-facilities, installed-gear-decides-what-a-station-buys). One facility design per station +// kind that some recipe names, a 2x2 GearData on a Facility mount holding FacilityData, sold by a NotOffered product (a design no +// product sells is an unsold design; a not-offered product is on no market). Sets each kind's Facilities to its design and every +// recipe's Facility to its kind's. Writes whole values, only where they differ, so a rerun touches nothing. Price is a sim-tuned knob +// (ruling economy-numbers-are-sim-tuned-knobs); names and descriptions are first drafts for the economy content pass. +public sealed class Facilities : EconomyBatch +{ + // The thermal band of every facility design, sim-tuned knobs like the prices (ruling economy-numbers-are-sim-tuned-knobs). A facility + // is Active only while its cells are inside the band, and a station's cells start at 280 and cool toward 0 with no heater, so the + // band holds that whole range: full performance from 0 to 560 around 280, tapering to nothing at 1000, with the floor just below + // 0 so a cell that has cooled all the way is still inside it. Gear that leaves these unauthored gets GearData's 0 to 100. + private const float ThermalMin = -1, ThermalMax = 1000, ThermalOptimal = 280, ThermalPlateau = 560; + + private static readonly (string Kind, string Id, string Name, string Description)[] Table = + { + ("mining", "extraction-rig", "Extraction Rig", "Drills, crushers and loaders that turn a station's miners into a steady flow of ore."), + ("volatiles", "volatiles-skimmer", "Volatiles Skimmer", "Scoops, condensers and tankage that skim gas giants and ice for Methane, Ammonia and Water."), + ("agriculture", "algae-vats", "Algae Vats", "Lit, circulating vats that grow Algae from Water and Potassium."), + ("processing", "refinery", "Refinery", "Furnaces, centrifuges and reactors that refine ore and volatiles into Metals, Alloys and Compounds."), + ("fabrication", "fabrication-line", "Fabrication Line", "Presses, printers and assembly cells that turn Alloys and Compounds into finished goods."), + ("munitions-works", "munitions-line", "Munitions Line", "A sealed line that makes energetics and loads rounds, primers, fuzes, warheads and motors."), + }; + + // The one storage facility: Zenith's ore silo (ruling demo-zenith-ore-depot). Storage, not a recipe facility, so it has no recipe and + // its kind is named here; a silo is bulk storage on a Facility row and holds only commodity stacks (SiloData). + private static readonly (string Kind, string Id, string Name, string Description) Silo = + ("trade-hub", "ore-silo", "Ore Silo", "A sealed bulk store that holds ore waiting for the haul to the refinery."); + + // The kind's first facility design, or unset: the one lookup the recipe-writing batches use. + public static CultRecordRef Of(CultCache catalog, string kindId) + { + return FirstOf(catalog.Get(StationKindData.KeyOf(kindId))); + } + + private static CultRecordRef FirstOf(StationKindData kind) => kind != null && kind.Facilities.Count > 0 ? kind.Facilities[0] : default; + + public override void Author(EconomyAuthor author) + { + var catalog = author.Catalog; + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ItemData).Assembly); + // Writes a record only when its stored value differs from the one wanted, so a rerun converges. + void Put(T wanted, CultRecordKey key) where T : class + { + var held = catalog.Get(key) as T; + if (held == null || !MessagePackSerializer.Serialize(held, options).SequenceEqual(MessagePackSerializer.Serialize(wanted, options))) author.Put(wanted, key); + } + + var kinds = catalog.GetAll().Select(recipe => recipe.StationKind.Key.Value).Distinct(StringComparer.Ordinal).OrderBy(key => key, StringComparer.Ordinal).ToArray(); + foreach (var kindKey in kinds) + { + var (_, id, name, description) = Table.SingleOrDefault(row => StationKindData.KeyOf(row.Kind).Value == kindKey); + if (id == null) throw new InvalidOperationException($"A recipe runs on station kind '{kindKey}', which the facilities batch has no facility for."); + var designKey = new CultRecordKey("facility:" + id); + var shape = new Shape(2, 2); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + // A stored behavior carries a cache-minted element id, so a design is compared by its fields, never by bytes. + if (!(catalog.Get(designKey) is GearData held && held.Name == name && held.Description == description && held.Hardpoint == HardpointType.Facility + && held.Durability == 100 && held.Mass == 250 && held.Price == 1000 && held.Shape.Width == 2 && held.Shape.Height == 2 && held.Shape.Coordinates.Length == 4 + && held.Behaviors.Count == 1 && held.Behaviors[0] is FacilityData + && held.MinimumTemperature == ThermalMin && held.MaximumTemperature == ThermalMax && held.OptimalTemperature == ThermalOptimal && held.PlateauWidth == ThermalPlateau)) + author.Put(new GearData + { + Name = name, Description = description, Hardpoint = HardpointType.Facility, Shape = shape, + Durability = 100, Mass = 250, Price = 1000, Behaviors = { new FacilityData() }, + MinimumTemperature = ThermalMin, MaximumTemperature = ThermalMax, OptimalTemperature = ThermalOptimal, PlateauWidth = ThermalPlateau + }, designKey); + var maker = MakerOf(catalog, kindKey); + // The brand lives in the product (ruling designs-are-tech-nodes): the maker's name before the design's. + Put(new FactionProductData + { + Name = $"{maker.Faction.Name} {name}", Description = description, Design = new CultRecordRef(designKey), + Manufacturer = new CultRecordRef(maker.Key), NotOffered = true + }, new CultRecordKey("product:facility:" + id)); + + var kind = catalog.Get(new CultRecordKey(kindKey)) ?? throw new InvalidOperationException($"A recipe names station kind '{kindKey}', which the catalog does not hold."); + if (kind.Facilities.Count != 1 || !kind.Facilities[0].Key.Equals(designKey)) + { + kind.Facilities = new List> { new CultRecordRef(designKey) }; + author.Put(kind, new CultRecordKey(kindKey)); + } + } + AuthorSilo(author, catalog, (wanted, key) => Put(wanted, key)); + foreach (var recipe in catalog.GetAll().ToArray()) + { + var facility = FirstOf(catalog.Get(recipe.StationKind)); + if (recipe.Facility.IsSet() && recipe.Facility.Key.Equals(facility.Key)) continue; + recipe.Facility = facility; + author.Put(recipe, catalog.RefOf(recipe).Key); + } + } + + // The first faction by key that places the kind, else the first by key: the brand of a facility's product. + private static (CultRecordKey Key, Faction Faction) MakerOf(CultCache catalog, string kindKey) + { + var factions = catalog.GetAll().Select(faction => (Key: catalog.RefOf(faction).Key, Faction: faction)).OrderBy(pair => pair.Key.Value, StringComparer.Ordinal).ToArray(); + var maker = factions.FirstOrDefault(pair => StationKinds.KindsOf(catalog, pair.Faction).Any(kind => kind.Key.Value == kindKey)); + return maker.Faction == null ? factions.First() : maker; + } + + // The silo design, its NotOffered product, and its kind's Facilities holding it: each only where it differs. Compared by fields, as + // the recipe facilities are. + private static void AuthorSilo(EconomyAuthor author, CultCache catalog, Action put) + { + var (kindId, id, name, description) = Silo; + var designKey = new CultRecordKey("facility:" + id); + var shape = new Shape(2, 2); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var interior = new Shape(8, 8); + foreach (var cell in interior.AllCoordinates) interior[cell] = true; + if (!(catalog.Get(designKey) is SiloData held && held.Name == name && held.Description == description + && held.Durability == 100 && held.Mass == 250 && held.Price == 1000 && held.Shape.Width == 2 && held.Shape.Height == 2 && held.Shape.Coordinates.Length == 4 + && held.InteriorShape.Width == 8 && held.InteriorShape.Height == 8 && held.InteriorShape.Coordinates.Length == 64 + && held.MinimumTemperature == ThermalMin && held.MaximumTemperature == ThermalMax && held.OptimalTemperature == ThermalOptimal && held.PlateauWidth == ThermalPlateau)) + author.Put(new SiloData + { + Name = name, Description = description, Shape = shape, InteriorShape = interior, + Durability = 100, Mass = 250, Price = 1000, + MinimumTemperature = ThermalMin, MaximumTemperature = ThermalMax, OptimalTemperature = ThermalOptimal, PlateauWidth = ThermalPlateau + }, designKey); + var kindKey = StationKindData.KeyOf(kindId); + var maker = MakerOf(catalog, kindKey.Value); + put(new FactionProductData + { + Name = $"{maker.Faction.Name} {name}", Description = description, Design = new CultRecordRef(designKey), + Manufacturer = new CultRecordRef(maker.Key), NotOffered = true + }, new CultRecordKey("product:facility:" + id)); + var kind = catalog.Get(kindKey) ?? throw new InvalidOperationException($"The silo's station kind '{kindId}' is not in the catalog."); + if (kind.Facilities.Count != 1 || !kind.Facilities[0].Key.Equals(designKey)) + { + kind.Facilities = new List> { new CultRecordRef(designKey) }; + author.Put(kind, kindKey); + } + } +} diff --git a/tools/AetherDb/Economy/Munitions.cs b/tools/AetherDb/Economy/Munitions.cs index c20165253..8a103704e 100644 --- a/tools/AetherDb/Economy/Munitions.cs +++ b/tools/AetherDb/Economy/Munitions.cs @@ -22,11 +22,13 @@ public sealed class Munitions : EconomyBatch // The kind this chain adds. Energetics and loading are sited apart from other industry because a loading accident must not // take a yard with it; that separation is the reason it is its own kind rather than a line in a fabrication station. + // It keeps the facilities the catalog already holds for the kind (batch Facilities owns them). _a.Put(new StationKindData { Name = "Munitions Works", Description = "Makes energetics (nitrocellulose, propellant, high explosive), loads rounds, primers, fuzes, warheads and rocket motors; sited apart from other industry so an accident takes only itself.", - StandIns = new List() + StandIns = new List(), + Facilities = _a.Catalog.Get(StationKindData.KeyOf("munitions-works"))?.Facilities.ToList() ?? new List>() }, StationKindData.KeyOf("munitions-works")); // Zhestokost has no station model of any kind yet. Its first planned model is the supply depot (ruling faction-station-models), @@ -146,8 +148,8 @@ public sealed class Munitions : EconomyBatch // Missiles: the crate a launcher design reloads from. One crate is one magazine reload (the reload takes one unit of the weapon's // AmmoType), the same convention as Ammo for guns, whatever the magazine holds (2 to 288 rounds across the five designs). A crate is // a warhead and a motor; the guidance package (seeker and fin actuators) waits on the electronics chain, so the recipe does not - // yet draw it. Shape and stack match Ammo's, so a hold takes crates cell for cell. - var missiles = new SimpleCommodityData { Name = "Missiles", Shape = new Shape(), MaxStack = 5, Mass = 8f, Price = 1800, + // yet draw it. Stack matches Ammo's and the type default gives the crate one cell, so a hold takes crates cell for cell. + var missiles = new SimpleCommodityData { Name = "Missiles", MaxStack = 5, Mass = 8f, Price = 1800, Description = "Crated guided munitions: a high-explosive warhead mated to a rocket motor on a launch rail. The crate a launcher reloads from; the rounds are real, only the reactor energy of the launch is not." }; _a.Put(missiles, CommodityKey("missiles")); var missilesRef = new CultRecordRef(CommodityKey("missiles")); @@ -155,8 +157,8 @@ public sealed class Munitions : EconomyBatch "A missile crate is a warhead and a motor in one box, and the box is the arsenal's most counted object: Zhestokost ties each launcher crew's allowance to a serial range, so a cache of loose crates is either a deserter's or a quartermaster's crime.", new string[0], (warhead, 1), (motor, 1)); - // Mines: the crate the mine launcher reloads from, a warhead per mine laid. Shape and stack as Missiles. - var mines = new SimpleCommodityData { Name = "Mines", Shape = new Shape(), MaxStack = 5, Mass = 7f, Price = 1400, + // Mines: the crate the mine launcher reloads from, a warhead per mine laid. Stack as Missiles. + var mines = new SimpleCommodityData { Name = "Mines", MaxStack = 5, Mass = 7f, Price = 1400, Description = "Crated proximity mines: a high-explosive warhead in a steel drum with a fuzed trigger. The crate a mine launcher reloads from." }; _a.Put(mines, CommodityKey("mines")); var minesRef = new CultRecordRef(CommodityKey("mines")); @@ -169,12 +171,6 @@ public sealed class Munitions : EconomyBatch "Little more than steel and actuators, which is why every convoy navy can build one and every blockade starts with one.", new[] { "dispenser" }, (steel, 2), (actuator, 1)); - // The designs whose every role this chain fills. Missile racks and rocket pods also need a guidance system, which the - // electronics chain fills; their recipes wait for it. - foreach (var gun in new[] { "Light Machine Gun", "Autocannon", "Long Slug Rifle", "Charged Scattergun", "Slug Rifle", "Flak Gun", "Cluster Cannon", "Point Defense Gun" }) - Design(gun, 1800, 30, "A ballistic gun is a barrel and a feed; the round brings the energy."); - Design("Mine Launcher", 1800, 24, "A dispenser and the warheads it lays."); - // Launchers draw real rounds (ruling ballistics-real-ammo): the reactor energy per shot stays as authored, and each magazine // reload consumes one Missiles crate. foreach (var launcher in new[] { "Guided Missile Launcher", "Long-Range Missile Rack", "Short-Range Missile Rack", "Incendiary Rocket Pod", "Swarm Rocket Pod" }) @@ -263,12 +259,9 @@ public sealed class Munitions : EconomyBatch Workforce = workforce, Upkeep = new List(), StationKind = new CultRecordRef(StationKindData.KeyOf(kind)), + Facility = Facilities.Of(_a.Catalog, kind), LoreHook = lore, Fills = fills.ToList() }, RecipeData.KeyOf(output.Key)); } - - // A role recipe: its inputs are the design's roles, so it names none. - private void Design(string name, float cycle, int workforce, string lore) => - Recipe(Existing(name), "fabrication", cycle, workforce, 1, lore, new string[0]); } diff --git a/tools/AetherDb/Economy/MunitionsBills.cs b/tools/AetherDb/Economy/MunitionsBills.cs new file mode 100644 index 000000000..72bfbb47d --- /dev/null +++ b/tools/AetherDb/Economy/MunitionsBills.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; + +// Economy content, batch: the bills of the munitions chain's designs. A design recipe names roles, never components (L-roles), and a +// role is priced at its cheapest filler, so a top gun cannot be dearer than a starter by naming a rarer grade of the same role. +// It names a different role instead: a rifled barrel, a lined barrel or a coil barrel where the starter names a barrel, a tracking +// feed where it names a feed mechanism. The same stats read the renamed role, its sellers' maker profiles carry over, and a part +// built from rarer metals fills it, so the design's price climbs the ladder with its chain (rulings gear-ladder-wide-by-rare-inputs, +// top-gear-within-one-region-run). Counts, labour and the parts' metals are sim-tuned knobs (economy-numbers-are-sim-tuned-knobs). +// Missile racks and rocket pods also need a guidance system, which the electronics chain fills; their recipes wait for it. +// +// Owner of the munitions chain's design recipes, their role counts and tier role names, and the four tier parts. Munitions writes +// the parts the starter fills and the rounds; it writes no design recipe, so a Munitions rerun cannot undo a bill. Renames run +// before bills, and a design that already holds the new role name is left alone, so a rerun changes no price, role or count (it does rewrite the four part recipes as new bytes: CommodityCount carries a cache-minted element id). +public sealed class MunitionsBills : EconomyBatch +{ + private EconomyAuthor _a; + + public override void Author(EconomyAuthor author) + { + _a = author; + var forging = Named("Gun Forging"); + var autoloader = Named("Autoloader Mechanism"); + var diamond = Named("Diamond"); + var board = Named("Circuit Board"); + var titanium = Commodity("titanium"); + var tungsten = Commodity("tungsten"); + var niobium = Commodity("niobium"); + var rareEarth = Commodity("rare-earth-oxides"); + var pgm = Commodity("platinum-group-metals"); + + Part("rifled-barrel", "Rifled Barrel", "A forged blank bored, rifled and diamond-lined inside a titanium jacket that keeps a long tube true.", 40f, 1200, 30, "rifled barrel", + "A titanium jacket keeps a long barrel straight when one side of it is in sunlight and the other in shadow. Rifles that hit at range come from regions with a basalt crust, and a rifleman's first question about a new posting is where its titanium comes from.", + (forging, 1), (diamond, 1), (titanium, 2)); + var lined = Part("lined-barrel", "Lined Barrel", "A forged blank with a sintered tungsten liner that takes sustained fire without washing out.", 45f, 1500, 34, "lined barrel", + "Diamond lining is cheap and wears fast; tungsten lasts as long as the gun is fed. Reactors and autocannon draw on the same tungsten, so a region short of it chooses each quarter between its plasma walls and its liners.", + (forging, 1), (tungsten, 2)); + Part("coil-barrel", "Coil Barrel", "A tungsten-lined barrel wound with niobium coils and rare-earth magnets that charge the shot in the bore.", 60f, 1800, 40, "coil barrel", + "A charged scattergun carries a fusion plant's worth of niobium wound round its barrels and platinum on every contact. Only a region that holds columbite and an evolved crust, or pays the gate for them, fields these, and a squadron that does is announcing it.", + (lined, 1), (niobium, 4), (rareEarth, 2), (pgm, 1)); + Part("tracking-feed", "Tracking Feed", "An autoloader slaved to a fire-control board with platinum contacts, cycling rounds on a predicted intercept.", 35f, 1200, 30, "tracking feed", + "Point defence and flak fire on a solution, not a trigger: the feed waits for the board to say now. The platinum is there because a contact that drifts by a millisecond puts the burst behind the missile.", + (autoloader, 1), (board, 1), (pgm, 1)); + + RenameRole(_a, "Point Defense Gun", "feed mechanism", "tracking feed"); + RenameRole(_a, "Slug Rifle", "barrel", "rifled barrel"); + RenameRole(_a, "Long Slug Rifle", "barrel", "rifled barrel"); + RenameRole(_a, "Flak Gun", "feed mechanism", "tracking feed"); + RenameRole(_a, "Autocannon", "barrel", "lined barrel"); + RenameRole(_a, "Cluster Cannon", "barrel", "lined barrel"); + RenameRole(_a, "Charged Scattergun", "barrel", "coil barrel"); + + const string gun = "A ballistic gun is a barrel and a feed; the round brings the energy."; + Bill("Light Machine Gun", 30, gun, ("barrel", 1), ("feed mechanism", 1)); + Bill("Point Defense Gun", 30, gun, ("barrel", 1), ("tracking feed", 1)); + Bill("Slug Rifle", 30, gun, ("rifled barrel", 1), ("feed mechanism", 1)); + Bill("Long Slug Rifle", 40, gun, ("rifled barrel", 1), ("feed mechanism", 1)); + Bill("Flak Gun", 40, gun, ("barrel", 2), ("tracking feed", 1)); + Bill("Autocannon", 40, gun, ("lined barrel", 1), ("feed mechanism", 2)); + Bill("Cluster Cannon", 60, gun, ("lined barrel", 4), ("feed mechanism", 2)); + Bill("Charged Scattergun", 80, gun, ("coil barrel", 4), ("feed mechanism", 2)); + Bill("Mine Launcher", 24, "A dispenser and the warheads it lays.", ("dispenser", 1), ("warhead", 1)); + } + + // An item the catalog holds, by its unique name. + private CultRecordRef Named(string name) + { + var named = _a.Catalog.GetAll().Where(i => i.Name == name).ToArray(); + if (named.Length != 1) throw new InvalidOperationException($"{named.Length} items are named '{name}'; the munitions bills need exactly one."); + return new CultRecordRef(_a.Catalog.RefOf(named[0]).Key); + } + + // A metal the ores batch writes. + private CultRecordRef Commodity(string id) + { + var key = new CultRecordKey("commodity:" + id); + return _a.Catalog.Get(key) != null ? new CultRecordRef(key) : throw new InvalidOperationException($"The catalog holds no '{key.Value}'; the ores batch writes it."); + } + + // A tier part: priced by its chain (author reprices), filling only its own role. + private CultRecordRef Part(string id, string name, string description, float mass, float cycle, int workforce, string fills, string lore, + params (CultRecordRef Commodity, int Count)[] inputs) + { + var key = new CultRecordKey("commodity:" + id); + _a.Put(new CompoundCommodityData { Name = name, Description = description, Mass = mass, Price = 1 }, key); + var output = new CultRecordRef(key); + Recipe(output, cycle, workforce, lore, new[] { fills }, inputs); + return output; + } + + // Renames a role of a design everywhere it is read: the design's roles, every stat term of every behaviour, and every non-bin + // seller's profile. A design that holds the new name and not the old is left alone, so a rerun renames nothing. + public static void RenameRole(EconomyAuthor author, string design, string from, string to) + { + CultRecordKey key = default; + var pending = true; + author.Edit(design, item => + { + key = author.Catalog.RefOf(item).Key; + if (item.Roles.All(r => r.Name != from)) + { + if (item.Roles.Any(r => r.Name == to)) { pending = false; return; } + throw new InvalidOperationException($"'{design}' declares no role '{from}' to rename."); + } + foreach (var role in item.Roles.Where(r => r.Name == from)) role.Name = to; + foreach (var behavior in item.Behaviors.Where(b => b != null)) + foreach (var field in behavior.GetType().GetFields().Where(f => f.FieldType == typeof(PerformanceStat))) + if (field.GetValue(behavior) is PerformanceStat stat && stat.Terms != null) + foreach (var term in stat.Terms.Where(t => t.Source == StatSource.Quality && t.Role == from)) term.Role = to; + }); + if (!pending) return; + foreach (var product in author.Catalog.GetAll().Where(p => p.Bin == null && p.Design.Key.Equals(key)).ToArray()) + { + foreach (var role in product.Roles.Where(r => r.Role == from)) role.Role = to; + author.Put(product, author.Catalog.RefOf(product).Key); + } + } + + // A design's bill: each declared role's count, and the role recipe (its inputs are the roles, so it names none). + private void Bill(string design, int workforce, string lore, params (string Role, int Count)[] counts) + { + CultRecordKey key = default; + _a.Edit(design, item => + { + key = _a.Catalog.RefOf(item).Key; + foreach (var (role, count) in counts) + (item.Roles.SingleOrDefault(r => r.Name == role) ?? throw new InvalidOperationException($"'{design}' declares no role '{role}'.")).Count = count; + }); + Recipe(new CultRecordRef(key), 1800, workforce, lore, new string[0]); + } + + private void Recipe(CultRecordRef output, float cycle, int workforce, string lore, string[] fills, + params (CultRecordRef Commodity, int Count)[] inputs) + { + _a.Put(new RecipeData + { + Output = output, + OutputCount = 1, + Inputs = inputs.Select(i => new CommodityCount { Commodity = i.Commodity, Count = i.Count }).ToList(), + Cycle = cycle, + Workforce = workforce, + Upkeep = new List(), + StationKind = new CultRecordRef(StationKindData.KeyOf("fabrication")), + Facility = Facilities.Of(_a.Catalog, "fabrication"), + LoreHook = lore, + Fills = fills.ToList() + }, RecipeData.KeyOf(output.Key)); + } +} diff --git a/tools/AetherDb/Economy/MunitionsFeed.cs b/tools/AetherDb/Economy/MunitionsFeed.cs index eab9c16cc..e3d54d37b 100644 --- a/tools/AetherDb/Economy/MunitionsFeed.cs +++ b/tools/AetherDb/Economy/MunitionsFeed.cs @@ -5,26 +5,29 @@ using GameCult.Caching; // Economy content, batch 1b: where the munitions chain's raw materials come from. Munitions writes the chain and names its leaves // (Water, Methane, Ammonia, Oxygen, Potassium, Diamond, Steel, Cellulose Pulp, Actuator, Circuit Board) without recipes; this batch -// gives each a source at a station kind whose description already says it does that work: input-free extraction at mining (ore, -// Gold, Potassium, Diamond) and volatiles (Water, Methane, Ammonia), and processing or fabrication from those goods for the rest. +// gives each a source at a station kind whose description already says it does that work: input-free extraction at mining (Diamond) +// and volatiles (Water, Methane, Ammonia), and processing or fabrication from those goods for the rest. Extraction of the ore, +// Gold and Potassium is OresAndProvinces': this batch holds references to them and writes no recipe for them. // Run after Munitions: it edits nothing the other batch writes and every output it names must exist. public sealed class MunitionsFeed : EconomyBatch { private EconomyAuthor _a; + // The records OresAndProvinces owns, held by key (Regolith and Nickel-Iron keep the keys Rock and New Metals had) or by name. + private static readonly CultRecordRef Regolith = new CultRecordRef(new CultRecordKey("043997a8-0661-4206-ab8a-10215ecf4efc")); + private static readonly CultRecordRef NickelIron = new CultRecordRef(new CultRecordKey("00b5b3b2-2fc5-4adb-a1d7-c1a35d19afd3")); + public override void Author(EconomyAuthor author) { _a = author; + // Ores the chain takes as inputs; their recipes are OresAndProvinces'. + var rock = Regolith; + var metals = NickelIron; + var gold = Named("Gold"); + var potassium = Named("Potassium"); + // Extraction: no inputs, so these are the chain's raw goods. - var rock = Make("Rock", "mining", 300, 10, 8, - "Nobody on a mining station calls it rock; it is the overburden, the slag, the thing the real cargo was buried in. It is also what every smelter, board shop and cement yard starts from, so the cheapest hold in the verse is the one that decides who can build."); - var metals = Make("New Metals", "mining", 300, 12, 6, - "The ore that built the cities: whoever holds the claim feeds every foundry downstream, which is why mining rights are the one commodity the garrisons will not leave unguarded."); - var gold = Make("Gold", "mining", 600, 8, 2, - "Gold has a use besides vanity: it does not corrode in a contact. Boards bound for a hull in a cold or wet corridor are gold-plated, and a prospector who finds a seam sells it to the board shops before the jewellers."); - var potassium = Make("Potassium", "mining", 300, 8, 4, - "Potash and saltpetre salts turn up in the same evaporite beds that mark old water. Farms want it for fertiliser and the arsenal wants it for powder; the survey crews tag the beds by which buyer reached them first."); var diamond = Make("Diamond", "mining", 1200, 12, 1, "Industrial stones from the deep kimberlite cores: grit for lining barrels and cutting tools rather than jewellery. A miner who sells one for a ring has wasted a barrel."); var water = Make("Water", "volatiles", 300, 8, 6, @@ -61,12 +64,18 @@ public sealed class MunitionsFeed : EconomyBatch (steel, 2), (board, 1)); } - private CultRecordRef Make(string name, string kind, float cycle, int workforce, int count, string lore, - params (CultRecordRef Commodity, int Count)[] inputs) + // Every item this batch names is found by its unique name. + private CultRecordRef Named(string name) { var named = _a.Catalog.GetAll().Where(i => i.Name == name).ToArray(); if (named.Length != 1) throw new InvalidOperationException($"{named.Length} items are named '{name}'; the munitions feed needs exactly one."); - var output = new CultRecordRef(_a.Catalog.RefOf(named[0]).Key); + return new CultRecordRef(_a.Catalog.RefOf(named[0]).Key); + } + + private CultRecordRef Make(string name, string kind, float cycle, int workforce, int count, string lore, + params (CultRecordRef Commodity, int Count)[] inputs) + { + var output = Named(name); _a.Put(new RecipeData { Output = output, @@ -76,6 +85,7 @@ public sealed class MunitionsFeed : EconomyBatch Workforce = workforce, Upkeep = new List(), StationKind = new CultRecordRef(StationKindData.KeyOf(kind)), + Facility = Facilities.Of(_a.Catalog, kind), LoreHook = lore, Fills = new List() }, RecipeData.KeyOf(output.Key)); diff --git a/tools/AetherDb/Economy/OresAndProvinces.cs b/tools/AetherDb/Economy/OresAndProvinces.cs new file mode 100644 index 000000000..17d9e7251 --- /dev/null +++ b/tools/AetherDb/Economy/OresAndProvinces.cs @@ -0,0 +1,312 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; + +// Economy content: ores and provinces (rulings ores-are-regional, ores-fill-metal-roles, provinces-within-regions, +// province-types-dealt-per-region, everyone-mines, new-metals-is-nickel-iron). It comes before ores-to-alloys, which is +// re-authored on top of it. +// +// The model is Dwarf Fortress's, moved to asteroids (docs/research/2026-10-27-ore-geology-prior-art.md). In DF a rock layer +// decides which ores a site holds and many named ores smelt into a few shared metals. Here a belt's field kind is its body +// class, read from real asteroid taxonomy (carbonaceous C, stony S, metallic M, basaltic V), and a province is the kind of +// ground a region's zones sit on: which body classes its belts draw and which regional ores exist there at all. The ground +// tells one story: the belts are the debris of protoplanets that differentiated and then broke, so a core province is +// metal, a crust province is basalt, and the incompatible elements (uranium, rare earths, niobium, tungsten) sit only in +// the last crust to freeze. Common ground (primitive and chondrite) is dealt most; specialty ground is dealt less, so a region +// holds a spread and the specialty ore it lacks must come by trade. +// +// Ores are named minerals, each a raw good the mining station extracts. A metal's recipe takes that metal's ore role, and an +// ore fills the role of every metal that is at least a tenth of the mineral by mass (ruling ores-fill-metal-roles: whatever else +// the ore holds is slag for that recipe). So ilmenite is both titanium ore and iron ore, and which it becomes is the smelter's +// choice. Grade is not modelled per role, by that ruling; how rich a belt is lives in its yield. +// +// This batch owns extraction and the first smelting step: every ore, the metal each role feeds, the field kinds and the +// province types. It owns nothing downstream of a metal (steel, alloys, mill products are ores-to-alloys). Every faction places +// mining (ruling everyone-mines): a Mega controls territory and the resources in it. A faction with no station model stands in on +// the supply depot (ruling faction-station-models), Aeronautics Unlimited on its trade hub (ruling station-kind-family-stand-in). +public sealed class OresAndProvinces : EconomyBatch +{ + private EconomyAuthor _a; + + // Records this batch renames, found by key so a rerun converges after the rename. + private static readonly CultRecordKey NewMetalsKey = new CultRecordKey("00b5b3b2-2fc5-4adb-a1d7-c1a35d19afd3"); + private static readonly CultRecordKey RockKey = new CultRecordKey("043997a8-0661-4206-ab8a-10215ecf4efc"); + private static readonly CultRecordKey AsteroidKindKey = new CultRecordKey("2b0deb8dd4ca44da9a36581877bf629d"); + + public override void Author(EconomyAuthor author) + { + _a = author; + + foreach (var faction in _a.Catalog.GetAll().OrderBy(f => f.Name, StringComparer.Ordinal).ToArray()) + StandIn("mining", new CultRecordRef(_a.Catalog.RefOf(faction).Key), faction.Name == "Aeronautics Unlimited" ? "trade-hub" : "depot"); + + var miningKey = StationKindData.KeyOf("mining"); + var mining = _a.Catalog.Get(miningKey); + mining.Description = "Extracts ore from belts: Regolith, Nickel-Iron and Troilite in common ground; Magnetite and Pentlandite in carbonaceous rock; Ilmenite and Anorthite in basalt; and only where the ground holds them Sylvite, Orthoclase, Chalcopyrite, Sperrylite, Native Copper, Native Gold, Isoferroplatinum, Uraninite, Brannerite, Monazite, Columbite and Wolframite. Cuts Diamond from deep cores; consumes tools and food."; + _a.Put(mining, miningKey); + + // ---- Ores: the raw goods. Fills are metal roles; abundance is the field kinds' business, below. + + var regolith = Rename(RockKey, "Regolith", "Crushed silicate rubble and dust, the bulk of every belt: what is left when the ore is picked out, and the aggregate cast habitats and berms are made of.", 1f, 1, 14, 6, + "Regolith is what every belt is mostly made of, and nobody fights over it. Orbital Forge casts it into habitat shells on a cage of rebar, so a hauler full of regolith heading for an empty rock means someone means to live there."); + + var nickelIron = Rename(NewMetalsKey, "Nickel-Iron", "Native nickel-iron, kamacite and taenite, cut from metallic asteroids: about nine parts iron to one of nickel, with a trace of cobalt and platinum.", 1f, 10, 10, 4, + "Metallic asteroids are the cores of broken protoplanets, iron that cooled so slowly it crystallised in plates a hand wide. The cut face rings when struck, and crews price it by the cut, not the tonne.", + "iron ore", "nickel ore"); + + var troilite = Ore("troilite", "Troilite", "Iron sulphide (FeS) in grains and nodules through stony asteroids: iron ore, with the sulphur driven off as gas.", 1f, 4, 10, 4, + "Troilite is the bronze fleck in a broken chondrite, and the reason a stony-belt smelter smells of sulphur. It is poor iron, but it is everywhere, and a habitat that cannot buy iron can always roast troilite.", + "iron ore"); + + var magnetite = Ore("magnetite", "Magnetite", "Iron oxide (Fe3O4) grown in the wet clays of carbonaceous asteroids: rich iron ore that a magnet lifts straight out of the crushed rock.", 1f, 6, 10, 4, + "Carbonaceous rocks were once wet, and the water grew magnetite in them as framboids and plates. Crews in the dark belts sweep crushed rock with a magnet drum and keep what sticks; the rest of the rock is somebody else's water.", + "iron ore"); + + var ilmenite = Ore("ilmenite", "Ilmenite", "Iron-titanium oxide (FeTiO3), the black sand of basaltic crust: titanium ore and iron ore at once.", 1f, 14, 12, 4, + "Ilmenite is the dark sand of old basalt flows, and every grain is both titanium and iron. Which one a smelter takes out of it says what its owner is short of this year, so a buyer's choice of ilmenite contract is read like a budget.", + "titanium ore", "iron ore"); + + var anorthite = Ore("anorthite", "Anorthite", "Calcium plagioclase (CaAl2Si2O8), the pale feldspar of anorthosite crust: the aluminium ore that molten-salt cells take apart.", 1f, 6, 12, 4, + "Anorthosite is the pale crust of a body that once had a magma ocean, the feldspar that floated to the top. Aluminium comes out of it only at a great cost in power, so where anorthite is cheap, ask where the power is coming from.", + "aluminium ore"); + + var pentlandite = Ore("pentlandite", "Pentlandite", "Iron-nickel sulphide ((Fe,Ni)9S8), bronze-yellow grains in sulphide melt and carbonaceous rock: the richest nickel ore, and iron ore besides.", 1f, 12, 12, 4, + "Pentlandite settles out of a sulphide melt like cream, so the sulphide provinces where an impact once melted a body are where nickel is cheap. Crews call a good pentlandite seam a cream line.", + "nickel ore", "iron ore"); + + var chalcopyrite = Ore("chalcopyrite", "Chalcopyrite", "Copper-iron sulphide (CuFeS2), brassy and iridescent: the common copper ore, found only where a sulphide melt pooled.", 1f, 12, 12, 4, + "Copper is scarce in the belts, and almost all of it is chalcopyrite in a sulphide province. Every wire, coil and heat pipe draws on it, so the regions that hold one trade copper for everything else, and the regions that do not wait in yards for their wiring.", + "copper ore", "iron ore"); + + var nativeCopper = Ore("native-copper", "Native Copper", "Metallic copper in sheets and wires through the vesicles of basalt, where hot water once carried it.", 1f, 16, 10, 2, + "Native copper lies in the old lava as sheets you can peel; the oldest Belt prospectors' stories are of native copper found in a vent pipe. It is rare, rich and hand-picked, and a find is kept quiet until the claim is filed.", + "copper ore"); + + var sylvite = Ore("sylvite", "Sylvite", "Potassium chloride (KCl) crystallised from the brines of wet carbonaceous bodies: potash ore.", 1f, 2, 8, 4, + "The wet bodies left salt where their brines froze out, the way Ceres wears its white spots. Farms buy sylvite first and arsenals second: the potassium that grows a habitat's algae is the potassium in its primers.", + "potassium ore"); + + var orthoclase = Ore("orthoclase", "Orthoclase", "Potassium feldspar (KAlSi3O8) from evolved granitic crust: a lean potash ore, worked where no brine salt is.", 1f, 1, 10, 4, + "Potassium feldspar is potash the hard way, cooked out of granite. Regions with no salt flats grind it anyway, and a farm co-op that buys orthoclase is a co-op whose neighbours have closed the salt trade to it.", + "potassium ore"); + + var nativeGold = Ore("native-gold", "Native Gold", "Gold, alloyed with a little silver, in grains and nuggets through the metal of core fragments.", 0.2f, 350, 6, 1, + "Gold sank with the iron when the protoplanets melted, so it is found in their broken cores, never in their crust. It wires every contact that must not corrode, and it is still the one metal people hoard without being told to.", + "gold ore"); + + var isoferroplatinum = Ore("isoferroplatinum", "Isoferroplatinum", "Platinum-iron alloy (Pt3Fe) in grains and nuggets, with iridium, osmium and rhodium: the native platinum of core fragments.", 0.2f, 650, 6, 1, + "Platinum came down with the iron, like the gold, and sits in nuggets where a core broke. A single nugget can pay a crew's season; a platinum strike in a contested core province has started more than one war that its history books call a border dispute.", + "platinum ore"); + + var sperrylite = Ore("sperrylite", "Sperrylite", "Platinum arsenide (PtAs2), small tin-white crystals in sulphide ore: a platinum ore that comes out of the same melt as the nickel.", 0.3f, 450, 8, 1, + "Sperrylite is platinum that rode up with the sulphide melt instead of sinking with the core, so a sulphide province holds platinum as well as copper and nickel. The arsenic that comes off in the roaster is why its smelters stand downwind of everything.", + "platinum ore"); + + var uraninite = Ore("uraninite", "Uraninite", "Uranium dioxide (UO2), pitch-black and heavy, in veins through the last crust to freeze: uranium ore.", 1f, 60, 10, 2, + "Uranium is an incompatible element: it would not fit in any early crystal, so it ended up in the last melt to freeze, and only evolved crust holds it. It is mined under licence and shipped under seal, and a broken seal is a crime in every bloc.", + "uranium ore"); + + var brannerite = Ore("brannerite", "Brannerite", "Uranium titanate (UTi2O6), black and glassy: uranium ore and titanium ore in one, worked for both.", 1f, 45, 10, 2, + "Brannerite is uranium locked in titanium oxide, hard to leach and worth it twice. A refinery that buys brannerite and sells only titanium has a uranium stockpile somewhere, and the licensing offices know to ask where.", + "uranium ore", "titanium ore"); + + var monazite = Ore("monazite", "Monazite", "Rare-earth phosphate ((Ce,La,Nd)PO4) with a little thorium, honey-coloured grains in evolved crust: the rare-earth ore.", 1f, 80, 10, 2, + "Neodymium from monazite is in every strong magnet, from an actuator to a drive pump, and the rare earths are in the premium superconductor tape that Cryonix certifies. The monazite crust provinces are few, so whoever holds one has a hand on every motor in the region.", + "rare earth ore"); + + var columbite = Ore("columbite", "Columbite", "Iron niobate (FeNb2O6), black tabular crystals from the pegmatites of evolved crust: niobium ore, with iron besides.", 1f, 100, 10, 2, + "Niobium is the conductor in the coils every yard but Cryonix's can wind: niobium-tin and niobium-titanium, heavier and hungrier for cold than the premium tape, and free of its licence. Columbite is how the gray-market fusion trade stays alive.", + "niobium ore", "iron ore"); + + var wolframite = Ore("wolframite", "Wolframite", "Iron tungstate (FeWO4), dense black blades from the vein ends of evolved crust: tungsten ore, with iron besides.", 1f, 60, 10, 2, + "Tungsten faces the plasma in every reactor and lines the throat of every hot nozzle; Orbital Forge's ugly refractory hardware is mostly tungsten. Wolframite is heavy for its size, so its haulers ride low on thrust and are easy prey.", + "tungsten ore", "iron ore"); + + // ---- Metals: the first smelting step. Each takes its ore role; downstream of a metal is ores-to-alloys. + + Metal("iron", "Iron", "Reduced iron pellet and sponge, smelted from whatever iron ore the furnace was fed; the rest of the ore leaves as slag.", 1f, 22, 3, 2, 600, 14, + "Iron is the one metal every province can make, from nickel-iron, troilite, magnetite or the iron in a copper ore, and the dry-refinery stack TerraCore's patents spread across Luna and the Belt still runs on all of them. A region short of iron is short of something else: power, crews or peace.", + "iron ore"); + + Metal("nickel", "Nickel", "Carbonyl nickel pellets, drawn off as a gas from nickel ore and redeposited almost pure.", 1f, 60, 4, 1, 900, 14, + "Nickel comes off the carbonyl line as a poisonous gas and settles back as pellets: the same carbon monoxide that does it kills a crew that forgets its sensors. Every stainless fitting, hot alloy and battery plate in a habitat starts as one of these pellets.", + "nickel ore"); + + Metal("copper", "Copper", "Cathode copper: sulphide ore roasted and smelted, or native copper melted, then electrorefined.", 1f, 70, 4, 1, 900, 16, + "Copper travels further than any other base metal because so few provinces hold it. A copper smelter in a region without a sulphide province runs on ore that crossed a boss line, and its prices carry the escort's fee.", + "copper ore"); + + Metal("aluminium", "Aluminium", "Aluminium ingot, reduced from anorthite in molten-salt electrolysis cells.", 0.4f, 50, 5, 1, 900, 12, + "Aluminium is electricity made solid: the cells that win it from feldspar draw more power than the habitat beside them. Where a refinery sells aluminium cheap, its power is cheap too, and someone should ask why.", + "aluminium ore"); + + Metal("titanium", "Titanium", "Titanium sponge, reduced from ilmenite or brannerite in molten-salt cells and pressed into billet.", 0.5f, 140, 5, 1, 1200, 14, + "Titanium is reduced a few kilograms at a time in salt baths that run for days, so a sponge shipment is small, heavy with value and always insured. Basalt-crust provinces make most of it; the brannerite crust makes the rest, and pays its licence fees twice.", + "titanium ore"); + + Metal("platinum-group-metals", "Platinum Group Metals", "Platinum with iridium, palladium, rhodium and osmium, refined to sponge from platinum ore.", 0.1f, 2400, 3, 1, 1800, 10, + "Platinum is the catalyst gauze that turns ammonia into nitric acid, the electrode in a fuel cell and the contact in a sensor that must not drift. Every fertiliser plant and every arsenal in a region depends on a few kilograms of it, which is why a platinum province is guarded like a gate.", + "platinum ore"); + + Smelt("Gold", "Gold bullion, melted out of native gold and parted from its silver.", 0.2f, 900, 2, 1, 600, 6, + "Gold is refined where it is mined, under guard, because a tonne of native gold ore is a crew's lifetime of wages. It goes into contacts and connectors, and into bars that nobody uses for anything at all.", + "gold ore"); + + Smelt("Uranium", "Uranium ore concentrate: yellowcake, leached from uranium ore and sealed in drums.", 0.5f, 150, 2, 1, 900, 10, + "Yellowcake is milled at the mine head because nobody wants to haul the waste rock, and sealed there because nobody trusts the haulers. A drum's seal number is its whole history, and an unbroken seal on a drum that never reached its reactor is a better story than a broken one.", + "uranium ore"); + + Smelt("Potassium", "Potash: potassium chloride and carbonate refined from potassium ore, fertiliser and chemical grade.", 1f, 6, 2, 1, 300, 6, + "Potash feeds farms first and arsenals second: the saltpetre in a primer is made from the same salt that grows a habitat's algae. A region with no brine-salt ground grinds feldspar for it, and pays for that in power.", + "potassium ore"); + + Metal("rare-earth-oxides", "Rare Earth Oxides", "Separated neodymium, praseodymium, lanthanum and cerium oxides, cracked from monazite and split by solvent extraction.", 0.5f, 320, 3, 1, 1800, 18, + "Splitting the rare earths takes hundreds of solvent stages, each a little better than the last, and the thorium that comes off is someone's licensing problem. A separation plant is the most valuable building in an evolved-crust province, and the most watched.", + "rare earth ore"); + + Metal("niobium", "Niobium", "Niobium metal, reduced from columbite and electron-beam remelted to conductor grade.", 0.5f, 380, 3, 1, 1500, 14, + "Niobium wire is what a fusion plant without a Cryonix contract runs on. It is heavier and colder to run than the premium tape, but no inspector can take it away, so the regions that hold columbite keep the independent reactors lit.", + "niobium ore"); + + Metal("tungsten", "Tungsten", "Tungsten powder and pressed bar, reduced from wolframite.", 1f, 240, 3, 1, 1200, 14, + "Tungsten is the wall between a reactor's plasma and everything else, and it wears: every plasma-facing tile is replaced on a schedule. A region that cannot buy tungsten has a date when its reactors go dark, and its neighbours know the date.", + "tungsten ore"); + + // ---- Field kinds: a belt's body class. CrossSection is reflectivity per cell, scaled to albedo with stony at the 5 it had. + + var stony = Kind(AsteroidKindKey, "Stony", 5f, 2f, + (regolith, 6f, false), (troilite, 1.5f, false), (nickelIron, 0.8f, false), + (pentlandite, 0.6f, true), (chalcopyrite, 0.5f, true), (sperrylite, 0.1f, true)); + var carbonaceous = Kind(new CultRecordKey("field-kind:carbonaceous"), "Carbonaceous", 1.5f, 4f, + (regolith, 5f, false), (magnetite, 1.5f, false), (pentlandite, 0.5f, false), (sylvite, 1f, true)); + var metallic = Kind(new CultRecordKey("field-kind:metallic"), "Metallic", 4f, 0.5f, + (nickelIron, 5f, false), (troilite, 0.8f, false), (nativeGold, 0.15f, true), (isoferroplatinum, 0.1f, true)); + var basaltic = Kind(new CultRecordKey("field-kind:basaltic"), "Basaltic", 9f, 0.3f, + (regolith, 5f, false), (ilmenite, 1.5f, false), (anorthite, 2f, false), + (nativeCopper, 0.3f, true), (chalcopyrite, 0.3f, true), (orthoclase, 0.8f, true), + (uraninite, 0.15f, true), (brannerite, 0.15f, true), (monazite, 0.2f, true), (columbite, 0.12f, true), (wolframite, 0.15f, true)); + + // ---- Province types: dealt per region from a deck of these card counts (ruling province-types-dealt-per-region). + + Province("primitive-reach", "Primitive Reach", 3, + new[] { (carbonaceous, 2f), (stony, 0.5f), (metallic, 0.2f), (basaltic, 0.1f) }, + new[] { (magnetite, 1.5f), (sylvite, 1f), (pentlandite, 1f) }); + Province("chondrite-plain", "Chondrite Plain", 3, + new[] { (stony, 3f), (carbonaceous, 1f), (metallic, 0.5f), (basaltic, 0.3f) }, + new[] { (troilite, 1.5f), (nickelIron, 1.2f) }); + Province("shattered-core", "Shattered Core", 2, + new[] { (metallic, 12f), (stony, 1f), (carbonaceous, 0.3f), (basaltic, 0.3f) }, + new[] { (nickelIron, 1.5f), (nativeGold, 1f), (isoferroplatinum, 1f) }); + Province("basalt-shards", "Basalt Shards", 2, + new[] { (basaltic, 15f), (stony, 1f), (carbonaceous, 0.3f), (metallic, 0.3f) }, + new[] { (ilmenite, 1.5f), (anorthite, 1.5f), (nativeCopper, 1f) }); + Province("sulphide-melt", "Sulphide Melt", 1, + new[] { (stony, 2f), (metallic, 6f), (basaltic, 10f), (carbonaceous, 0.3f) }, + new[] { (pentlandite, 2f), (chalcopyrite, 1.5f), (sperrylite, 1f), (nativeGold, 0.5f) }); + Province("evolved-crust", "Evolved Crust", 1, + new[] { (basaltic, 12f), (stony, 1f), (carbonaceous, 0.2f), (metallic, 0.2f) }, + new[] { (ilmenite, 1f), (uraninite, 1f), (brannerite, 1f), (monazite, 1f), (columbite, 1f), (wolframite, 1f), (orthoclase, 1f) }); + } + + // Sets this faction's stand-in on a kind, replacing any it had, so a rerun converges. + private void StandIn(string kindId, CultRecordRef faction, string standInKindId) + { + var key = StationKindData.KeyOf(kindId); + var kind = _a.Catalog.Get(key) ?? throw new InvalidOperationException($"The catalog holds no station kind '{kindId}'."); + kind.StandIns = kind.StandIns.Where(s => !s.Faction.Key.Equals(faction.Key)).ToList(); + kind.StandIns.Add(new StationKindStandIn { Faction = faction, Kind = new CultRecordRef(StationKindData.KeyOf(standInKindId)) }); + _a.Put(kind, key); + } + + private static CultRecordKey CommodityKey(string id) => new CultRecordKey("commodity:" + id); + + // A new ore: a raw good with an extraction recipe at the mining station that fills its metal roles. Its Shape is the commodity type's one-cell default. + private CultRecordRef Ore(string id, string name, string description, float mass, int price, int workforce, int perCycle, string lore, params string[] fills) + { + var key = CommodityKey(id); + _a.Put(new SimpleCommodityData { Name = name, Description = description, Mass = mass, Price = price }, key); + Recipe(key, "mining", 600, workforce, perCycle, lore, fills, new List()); + return new CultRecordRef(key); + } + + // An existing raw record given its ore name, a Shape and an extraction recipe; found by key so a rerun after the rename converges. + private CultRecordRef Rename(CultRecordKey key, string name, string description, float mass, int price, int workforce, int perCycle, string lore, params string[] fills) + { + var record = _a.Catalog.Get(key) ?? throw new InvalidOperationException($"The catalog holds no simple commodity {key.Value}."); + record.Name = name; + record.Description = description; + record.Mass = mass; + record.Price = price; + record.Shape = new Shape(); + _a.Put(record, key); + Recipe(key, "mining", 600, workforce, perCycle, lore, fills, new List()); + return new CultRecordRef(key); + } + + // A new metal: a simple commodity whose processing recipe takes its ore role. + private void Metal(string id, string name, string description, float mass, int price, int oreCount, int outputCount, float cycle, int workforce, string lore, string role) + { + var key = CommodityKey(id); + _a.Put(new SimpleCommodityData { Name = name, Description = description, Mass = mass, Price = price }, key); + Recipe(key, "processing", cycle, workforce, outputCount, lore, new string[0], new List { new ItemRole { Name = role, Count = oreCount } }); + } + + // An existing good (Gold, Uranium, Potassium) given what it is and a processing recipe that takes its ore role. + private void Smelt(string name, string description, float mass, int price, int oreCount, int outputCount, float cycle, int workforce, string lore, string role) + { + _a.Edit(name, c => + { + c.Description = description; + c.Mass = mass; + c.Price = price; + }); + var key = _a.Catalog.RefOf(_a.Catalog.GetAll().Single(c => c.Name == name)).Key; + Recipe(key, "processing", cycle, workforce, outputCount, lore, new string[0], new List { new ItemRole { Name = role, Count = oreCount } }); + } + + private void Recipe(CultRecordKey output, string kind, float cycle, int workforce, int outputCount, string lore, string[] fills, List roles) + { + var outputRef = new CultRecordRef(output); + _a.Put(new RecipeData + { + Output = outputRef, + OutputCount = outputCount, + Inputs = new List(), + RoleInputs = roles, + Cycle = cycle, + Workforce = workforce, + Upkeep = new List(), + StationKind = new CultRecordRef(StationKindData.KeyOf(kind)), + Facility = Facilities.Of(_a.Catalog, kind), + LoreHook = lore, + Fills = fills.ToList() + }, RecipeData.KeyOf(output)); + } + + // A field kind under its key, written whole: a rerun converges, and the existing kind keeps its key so saved belts hold. + private CultRecordRef Kind(CultRecordKey key, string name, float crossSection, float weight, + params (CultRecordRef Ore, float Abundance, bool Regional)[] yields) + { + _a.Put(new FieldKindData + { + Name = name, + CrossSection = crossSection, + GenerationWeight = weight, + Yields = yields.Select(y => new FieldYield { Commodity = y.Ore, Abundance = y.Abundance, Regional = y.Regional }).ToList() + }, key); + return new CultRecordRef(key); + } + + private void Province(string id, string name, int cards, (CultRecordRef Kind, float Weight)[] kinds, + (CultRecordRef Ore, float Weight)[] ores) + { + _a.Put(new ProvinceData + { + Name = name, + GenerationWeight = cards, + Kinds = kinds.Select(k => new ProvinceKindWeight { Kind = k.Kind, Weight = k.Weight }).ToList(), + Ores = ores.Select(o => new ProvinceOre { Commodity = o.Ore, Weight = o.Weight }).ToList() + }, new CultRecordKey("province:" + id)); + } +} diff --git a/tools/AetherDb/Economy/OresAndProvinces.dry-run.txt b/tools/AetherDb/Economy/OresAndProvinces.dry-run.txt new file mode 100644 index 000000000..625aec534 --- /dev/null +++ b/tools/AetherDb/Economy/OresAndProvinces.dry-run.txt @@ -0,0 +1,345 @@ +Dry run of economy author OresAndProvinces on the Windows workstation (dotnet 10.0.401), branch nibu/ore-batch-rescale on base d1ff2f78e, before apply. +Aetheria.cc sha256 7bfba1bdf25112c11f8c88a74d9ca53382d5d98245f68a4be9f67065ad5fe6e7, unchanged by the dry run. 62 added, 10 changed. + +===== DRY RUN (exit 0) +changed station-kind:mining +unchanged 043997a8-0661-4206-ab8a-10215ecf4efc +changed recipe:043997a8-0661-4206-ab8a-10215ecf4efc +changed 00b5b3b2-2fc5-4adb-a1d7-c1a35d19afd3 +changed recipe:00b5b3b2-2fc5-4adb-a1d7-c1a35d19afd3 +added commodity:troilite +added recipe:commodity:troilite +added commodity:magnetite +added recipe:commodity:magnetite +added commodity:ilmenite +added recipe:commodity:ilmenite +added commodity:anorthite +added recipe:commodity:anorthite +added commodity:pentlandite +added recipe:commodity:pentlandite +added commodity:chalcopyrite +added recipe:commodity:chalcopyrite +added commodity:native-copper +added recipe:commodity:native-copper +added commodity:sylvite +added recipe:commodity:sylvite +added commodity:orthoclase +added recipe:commodity:orthoclase +added commodity:native-gold +added recipe:commodity:native-gold +added commodity:isoferroplatinum +added recipe:commodity:isoferroplatinum +added commodity:sperrylite +added recipe:commodity:sperrylite +added commodity:uraninite +added recipe:commodity:uraninite +added commodity:brannerite +added recipe:commodity:brannerite +added commodity:monazite +added recipe:commodity:monazite +added commodity:columbite +added recipe:commodity:columbite +added commodity:wolframite +added recipe:commodity:wolframite +added commodity:iron +added recipe:commodity:iron +added commodity:nickel +added recipe:commodity:nickel +added commodity:copper +added recipe:commodity:copper +added commodity:aluminium +added recipe:commodity:aluminium +added commodity:titanium +added recipe:commodity:titanium +added commodity:platinum-group-metals +added recipe:commodity:platinum-group-metals +changed 36746041-a5bd-4b95-aa18-294acaaeae62 +changed recipe:36746041-a5bd-4b95-aa18-294acaaeae62 +changed 08c07793-bc06-48dc-adc2-c7e61ef2cb2b +added recipe:08c07793-bc06-48dc-adc2-c7e61ef2cb2b +changed a8e259fc-fbf1-477a-8248-0277611f1859 +changed recipe:a8e259fc-fbf1-477a-8248-0277611f1859 +added commodity:rare-earth-oxides +added recipe:commodity:rare-earth-oxides +added commodity:niobium +added recipe:commodity:niobium +added commodity:tungsten +added recipe:commodity:tungsten +changed 2b0deb8dd4ca44da9a36581877bf629d +added field-kind:carbonaceous +added field-kind:metallic +added field-kind:basaltic +added province:primitive-reach +added province:chondrite-plain +added province:shattered-core +added province:basalt-shards +added province:sulphide-melt +added province:evolved-crust +62 added, 10 changed, 0 removed, 1 unchanged +137 faults +L-consumer-demand (18) + recipe:0b449ae1-7eab-47e8-ac3c-2b6f6ff01f00: 'Ballistic Powder' leads into thruster, Ammo and Missiles but no use leads into a consumer good. + recipe:2e08445d-c130-497c-9fb3-8d752a24e654: 'Algae' leads into thruster, Ammo and Missiles but no use leads into a consumer good. + recipe:36746041-a5bd-4b95-aa18-294acaaeae62: 'Gold' leads into dispenser, feed mechanism, warhead, Mines and Missiles but no use leads into a consumer good. + recipe:3c8b2b3d-ca1a-405f-966f-c64662a64418: 'Circuit Board' leads into dispenser, feed mechanism, warhead, Mines and Missiles but no use leads into a consumer good. + recipe:a8e259fc-fbf1-477a-8248-0277611f1859: 'Potassium' leads into thruster, Ammo and Missiles but no use leads into a consumer good. + recipe:commodity:actuator: 'Actuator' leads into dispenser and feed mechanism but no use leads into a consumer good. + recipe:commodity:cellulose-pulp: 'Cellulose Pulp' leads into thruster, Ammo and Missiles but no use leads into a consumer good. + recipe:commodity:explosive-fill: 'Explosive Fill' leads into warhead, Mines and Missiles but no use leads into a consumer good. + recipe:commodity:fragmentation-case: 'Fragmentation Case' leads into warhead, Mines and Missiles but no use leads into a consumer good. + recipe:commodity:fuze: 'Fuze' leads into warhead, Mines and Missiles but no use leads into a consumer good. + recipe:commodity:he-warhead: 'High-Explosive Warhead' leads into warhead, Mines and Missiles but no use leads into a consumer good. + recipe:commodity:hexamine: 'Hexamine' leads into warhead, Mines and Missiles but no use leads into a consumer good. + recipe:commodity:nitric-acid: 'Nitric Acid' leads into thruster, warhead, Ammo, Mines and Missiles but no use leads into a consumer good. + recipe:commodity:nitrocellulose: 'Nitrocellulose' leads into thruster, Ammo and Missiles but no use leads into a consumer good. + recipe:commodity:oxygen: 'Oxygen' leads into thruster, warhead, Ammo, Mines and Missiles but no use leads into a consumer good. + recipe:commodity:potassium-nitrate: 'Potassium Nitrate' leads into thruster, Ammo and Missiles but no use leads into a consumer good. + recipe:commodity:rocket-motor: 'Rocket Motor' leads into thruster and Missiles but no use leads into a consumer good. + recipe:commodity:steel: 'Steel' leads into barrel, dispenser, feed mechanism, thruster, warhead, Ammo, Mines and Missiles but no use leads into a consumer good. +L-recipe (109) + 03ff4335-fa65-4a89-8cea-68f70de01d60: Commodity 'Dashboard Ornament' has no recipe. + 0caaa08c-e0b6-4eaf-a9fd-7e03088371ea: Commodity 'Reaction Chamber' has no recipe. + 0d6a518d-24e9-40bf-9861-301de17b5161: Commodity 'Heat Sink Tile' has no recipe. + 11d9fd0c-c0dd-482f-8e2a-f7c289ed6a3d: Commodity 'AI Pilot' has no recipe. + 17032840-c285-4f33-82ae-6b03f1e1e56b: Commodity 'Cargo Pod' has no recipe. + 1af83f0b-11ae-4d03-acc3-c5d478d55f14: Commodity 'Spacesuit' has no recipe. + 1ea0df17-aba1-45bc-8d6e-a430c110e38d: Commodity 'Geiger Counter' has no recipe. + 20376ecd-77fa-4ffe-9be6-185158ee1bfc: Commodity 'All-Surface Stylus' has no recipe. + 2055f611-ef5d-4791-b1ad-f1757c081a99: Commodity 'Holo-desk' has no recipe. + 22917d5e-313a-4470-a91e-0c78f1e08044: Commodity 'Spacewalking Boots' has no recipe. + 2aa99b2d-80ed-4640-9350-9affcfe6d8cd: Commodity 'Construction Rebar' has no recipe. + 32934bf0-d7e9-432f-8863-e07c092b67f6: Commodity 'Inertial Compensating Seatbelt' has no recipe. + 33944941-5bd1-43ca-91a4-348c253f7e8b: Commodity 'Stealth Coating' has no recipe. + 34b16da9-1e5e-4fba-b256-eb8a38274b39: Commodity 'Neural Lace' has no recipe. + 35f02735-1993-4467-b3de-028c2d6e2276: Commodity 'Emergency Personal Life Support System' has no recipe. + 3689a855-9264-40f0-91b3-8b235dac80b6: Commodity 'Sure Bet Sherbet Fountain' has no recipe. + 3987140a-19c3-4b0b-8fa5-528f43a83afb: Commodity 'Magnetic EVA Boots' has no recipe. + 3a33da73-ba06-4574-afec-d529097408b5: Commodity 'Universal Translator' has no recipe. + 3c6bb1cc-70d8-400b-8d69-9c81339758f3: Commodity 'Bacteria' has no recipe. + 3ddbbb28-c166-4ab3-8a0b-c7b77c372f32: Commodity 'Mouth Adapting Gummy Molars' has no recipe. + 40004417-d242-47d2-9f27-1bbcf8548779: Commodity 'Trigger' has no recipe. + 4081eb4c-3376-4912-a230-c43096d90ad1: Commodity 'Travel Permit' has no recipe. + 421e9788-d094-4c17-88cc-0d820e3cfeca: Commodity 'Sheet Metal' has no recipe. + 4486cfad-3063-4667-80ae-5e4d615ee501: Commodity 'Hydrogen' has no recipe. + 452bbd60-11df-449b-a4b7-a4ca22527123: Commodity 'Secret Storage Compartment' has no recipe. + 4681d1af-1a6d-4c7e-b10d-5ee8295b9a79: Commodity 'Ship Fins' has no recipe. + 4810a43b-bbb9-447d-b62e-b723e4d88afc: Commodity 'Antireflective Coating' has no recipe. + 498c664d-05ff-45a0-b3b6-2b98feec8611: Commodity 'Super Tough Toffee' has no recipe. + 4b3fc716-d362-4379-8c65-f2c471647ed1: Commodity 'Crash Test Dummy' has no recipe. + 4c82acfa-b8e4-4601-9465-2fad107b1eff: Commodity 'Insulation' has no recipe. + 4d5929a9-5cb1-470c-a0b7-12f8abaf4497: Commodity 'Ship Decal' has no recipe. + 502a6ed8-73aa-4554-ae89-a50b67cfa9e0: Commodity 'Rope' has no recipe. + 515734e6-4287-470c-bf56-188c4b257420: Commodity 'Trousers' has no recipe. + 51e4dc3b-0107-4ab5-a2c6-02d34a1035b2: Commodity 'Mining Rights' has no recipe. + 5383d6b6-083b-4721-8f6b-426dba0beaeb: Commodity 'Hat' has no recipe. + 5449f7d3-b250-41cd-9e7e-ab2a7037cacb: Commodity 'Knife' has no recipe. + 5837ec5e-036b-4f73-9098-dbe11339909f: Commodity 'Safety Goggles' has no recipe. + 5bcddae5-10fe-4316-9dca-6dc5d53c899e: Commodity 'Local Newscast' has no recipe. + 5e2950d6-02df-461e-a35e-a4123c6a5639: Commodity 'Big Red Button' has no recipe. + 601a345d-6f0b-4bdb-8171-be4befaf9a33: Commodity 'Daily Feed Ad Slot (5ms)' has no recipe. + 63abe46b-ad99-4ac9-b5e4-d83a40465065: Commodity 'Joystick' has no recipe. + 64bccb57-3aa8-4e5f-829d-07e62295b0c7: Commodity 'Fungi' has no recipe. + 6713c2b2-d886-4440-b076-dd206c22848a: Commodity 'SpaceCast' has no recipe. + 675a1ebe-868c-4b27-a2eb-bee2fe5e356b: Commodity 'Paparazzi Drone' has no recipe. + 6821495a-4875-4350-a8e8-e813c3576aa8: Commodity 'Fuel' has no recipe. + 6d20c298-281e-46fc-be33-dbcc575d49d7: Commodity 'Cockpit' has no recipe. + 6d4c9e32-7ffd-45f6-8e08-86d544793774: Commodity 'Dials' has no recipe. + 6dc76b7c-65c3-4cc1-bc2a-eace8e4f58d2: Commodity 'Support Strut' has no recipe. + 6f0ed812-01b0-4767-90c5-0b6857bc2e29: Commodity 'Memory Download' has no recipe. + 7e9783b7-ab6c-4c50-bb99-4f1f3a3e240d: Commodity 'Animal Products' has no recipe. + 86d11f6a-9ddd-478d-8192-f047d38a7c6a: Commodity 'Moo-ed Lighting' has no recipe. + 8b026aea-1d79-49a0-b843-abdfcca31bab: Commodity 'Helmet' has no recipe. + 03740fd6-158d-43e9-b070-9a40e0b9bc45: Offered design 'Secure Cargo Bay' has no recipe. + 03a842b2-295e-4cf7-9faa-ecc4bc54eb76: Offered design 'Heavy Beam Laser' has no recipe. + 04255796-db68-48d2-81e5-8cfdab150706: Offered design 'Burn Drive' has no recipe. + 08226a8cb09844919c9922fbd7b76bef: Offered design 'Station Reactor' has no recipe. + 0d499d62-3b92-454b-9498-37d12616167f: Offered design 'Charged Scatter Blaster' has no recipe. + 106179618b054e8da61650bbec486c18: Offered design 'Fire Control Array' has no recipe. + 1c0cff5d-8668-45ea-9726-8b08c81d0267: Offered design 'Short-Range Missile Rack' has no recipe. + 205efba0-16af-477b-80e9-c9597cead5b4: Offered design 'Ring Reactor' has no recipe. + 20e9f41a-6bd2-4f6c-9740-7b707614509c: Offered design 'Cryogenic Heat Pump' has no recipe. + 291a01746063494fbfcb8c96f82aa8d3: Offered design 'Muon Fusion Station Reactor' has no recipe. + 2933c4ce-bf41-459c-b0d6-9583466b393d: Offered design 'Long Laser' has no recipe. + 2935b4d4-2ad5-4b90-8416-a85bbb38171b: Offered design 'Adaptive Radiator' has no recipe. + 2b2777c0-b756-4e19-9bf6-e5bac3cc385c: Offered design 'Turret Control Module' has no recipe. + 2c911da4-fad0-4a38-be5b-5e327c0c9e43: Offered design 'Industrial Thermostatic Heater' has no recipe. + 2e4c7753e0a24c13849818ac1dcfdba0: Offered design 'Passive Array' has no recipe. + 2e5193aa-3703-4ecc-911d-4d8394ce4c2f: Offered design 'Incendiary Rocket Pod' has no recipe. + 31325c3d-0537-40ec-9e5e-80930ea01496: Offered design 'Cockpit 2x2' has no recipe. + 32157982-b015-461e-ba4e-d321a23c2748: Offered design 'Long-Range Missile Rack' has no recipe. + 34b15c33-c01f-4712-ac75-5fcf779f0685: Offered design 'Capacitor' has no recipe. + 372d23cc-5ef0-42b5-9d96-807f2e412b0d: Offered design 'Muon Fusion Reactor' has no recipe. + 394612a6-9198-4797-a69b-c70cd0ee3273: Offered design 'High-Yield Reactor' has no recipe. + 3baa2c43-b389-4438-94cb-fbb04489cd77: Offered design 'Heavy Reactor' has no recipe. + 3e930a2c-ac72-4385-98aa-1c5b0b90db46: Offered design 'Medium Docking Bay' has no recipe. + 457ac901-aa54-4ba7-9df6-fbacdfb40b3f: Offered design 'Cell Blaster' has no recipe. + 46b66f9a-5c72-4e7a-ac9b-4dd7904cc4a1: Offered design 'Large Cargo Bay' has no recipe. + 480d6cc4-cd8a-49b6-9c89-211033e7c1d5: Offered design 'Compact Sensor' has no recipe. + 499f7891-c5df-4cbe-8431-9db7108102ec: Offered design 'Charged Blaster' has no recipe. + 49b4c15a-c10b-49c0-9dad-31dfb9b3a9b9: Offered design 'Cargo Bay' has no recipe. + 4a41dec8-6b65-46ee-b578-ba805f112c0c: Offered design 'Light Laser' has no recipe. + 4b019503-1865-4bad-a6e9-c85b558aacea: Offered design 'Long Radiator' has no recipe. + 4bc1fe6f-347a-425e-be1b-997920175bee: Offered design 'Compact Reactor' has no recipe. + 542169f2-363c-41f7-8d6d-60a5bd7578bd: Offered design 'Heat Pump' has no recipe. + 5cd802dd-ef0e-4303-bd87-c30988326e4b: Offered design 'Large Drive' has no recipe. + 5ee2ff03-0ac4-4cdd-89bc-81e29223900b: Offered design 'Guided Missile Launcher' has no recipe. + 632420a6-4419-4647-a92b-5e22ea289025: Offered design 'Lightning Projector' has no recipe. + 67111f5b41d5464e958ffc62bb3249da: Offered design 'Coolant Vent' has no recipe. + 726c1403ced34c2497693bf0f269c898: Offered design 'Inspection Scanner' has no recipe. + 72859489-677a-47a4-ae04-550e582ba29e: Offered design 'Sensor Array' has no recipe. + 7d14649c-a3b6-47c5-ab74-201b90072e2c: Offered design 'Tractor Beam' has no recipe. + 88e81a2b-45fd-49de-830f-c896adae8d5b: Offered design 'Racing Drive' has no recipe. + 8d84faaae78c490cb762289fd362bb0a: Offered design 'Launch Suppressor' has no recipe. + 9013c312-f37f-42a8-9efc-3d699759923b: Offered design 'Small Drive' has no recipe. + a0478430-3ec5-445d-94a7-f30e61b2b8d3: Offered design 'Swarm Rocket Pod' has no recipe. + a2ce2da35eff4f4aa6ec220449427a0d: Offered design 'High-Yield Station Reactor' has no recipe. + a828a676cc9e492f86ea7e08d75c4687: Offered design 'Launch Baffle' has no recipe. + ae05f4cb-0dd5-4f37-af96-cc61c9d61e1f: Offered design 'Small Cargo Bay' has no recipe. + b1403776e5fc4bd9bd0ed17d7e2a5e6e: Offered design 'Heavy Station Reactor' has no recipe. + b24ee1740ae04cdf9a07fff4105069f2: Offered design 'Thruster Overdrive' has no recipe. + bb5d9f73-612f-4060-8fb4-f72d6b93b616: Offered design 'Djinni' has no recipe. + bc3870ae-8e31-45ec-99d9-745a4262f78a: Offered design 'Radiator' has no recipe. + c07ea205005d423bb70d3bed899fdedd: Offered design 'Targeting Computer' has no recipe. + c4b20032-8cd3-4206-807f-97b296797425: Offered design 'Longinus' has no recipe. + d6e1b44396494e39a4e0a1b51c92a0ef: Offered design 'Ring Station Reactor' has no recipe. + d706ff66-c98c-4e60-a8e5-5dceb8dc3742: Offered design 'Rugged Drive' has no recipe. + ebfb35b5-3905-4510-a8cf-c09528f27172: Offered design 'High-Thrust Drive' has no recipe. + ef0f782e-9fa8-4059-bb8c-f16e1d3de100: Offered design 'Medium Drive' has no recipe. + fa568d572eec4969aad07599444a3892: Offered design 'Point Defense Laser' has no recipe. +L-source-sink (10) + recipe:08c07793-bc06-48dc-adc2-c7e61ef2cb2b: 'Uranium' has no sink: no recipe takes it or a role it fills, no design names a role it fills, no weapon draws it, no gate buys it. + recipe:commodity:aluminium: 'Aluminium' has no sink: no recipe takes it or a role it fills, no design names a role it fills, no weapon draws it, no gate buys it. + recipe:commodity:copper: 'Copper' has no sink: no recipe takes it or a role it fills, no design names a role it fills, no weapon draws it, no gate buys it. + recipe:commodity:iron: 'Iron' has no sink: no recipe takes it or a role it fills, no design names a role it fills, no weapon draws it, no gate buys it. + recipe:commodity:nickel: 'Nickel' has no sink: no recipe takes it or a role it fills, no design names a role it fills, no weapon draws it, no gate buys it. + recipe:commodity:niobium: 'Niobium' has no sink: no recipe takes it or a role it fills, no design names a role it fills, no weapon draws it, no gate buys it. + recipe:commodity:platinum-group-metals: 'Platinum Group Metals' has no sink: no recipe takes it or a role it fills, no design names a role it fills, no weapon draws it, no gate buys it. + recipe:commodity:rare-earth-oxides: 'Rare Earth Oxides' has no sink: no recipe takes it or a role it fills, no design names a role it fills, no weapon draws it, no gate buys it. + recipe:commodity:titanium: 'Titanium' has no sink: no recipe takes it or a role it fills, no design names a role it fills, no weapon draws it, no gate buys it. + recipe:commodity:tungsten: 'Tungsten' has no sink: no recipe takes it or a role it fills, no design names a role it fills, no weapon draws it, no gate buys it. + +Depth + 00b5b3b2-2fc5-4adb-a1d7-c1a35d19afd3 depth 0 + 0271bb97-4ce8-4d64-97c3-8bfd3f76b2c6 depth 5 + 03ff4335-fa65-4a89-8cea-68f70de01d60 depth none + 043997a8-0661-4206-ab8a-10215ecf4efc depth 0 + 08c07793-bc06-48dc-adc2-c7e61ef2cb2b depth 1 + 0b449ae1-7eab-47e8-ac3c-2b6f6ff01f00 depth 5 + 0caaa08c-e0b6-4eaf-a9fd-7e03088371ea depth none + 0d6a518d-24e9-40bf-9861-301de17b5161 depth none + 11d9fd0c-c0dd-482f-8e2a-f7c289ed6a3d depth none + 13116166-f0c8-43cf-a35f-8fd448bc630c depth 5 + 17032840-c285-4f33-82ae-6b03f1e1e56b depth none + 1af83f0b-11ae-4d03-acc3-c5d478d55f14 depth none + 1b4a2bb358eb432eb1cfc0ccf3317303 depth 6 + 1ea0df17-aba1-45bc-8d6e-a430c110e38d depth none + 20376ecd-77fa-4ffe-9be6-185158ee1bfc depth none + 2055f611-ef5d-4791-b1ad-f1757c081a99 depth none + 214fe497-cda4-4cdb-a7c4-fe656e5ff61c depth 0 + 22917d5e-313a-4470-a91e-0c78f1e08044 depth none + 2aa99b2d-80ed-4640-9350-9affcfe6d8cd depth none + 2e08445d-c130-497c-9fb3-8d752a24e654 depth 2 + 2fd0d88b-f565-4021-85b4-02d9eae7be58 depth 5 + 3085fc8a-ec0d-4f6f-a339-ea43edb573e6 depth 6 + 32934bf0-d7e9-432f-8863-e07c092b67f6 depth none + 33944941-5bd1-43ca-91a4-348c253f7e8b depth none + 34b16da9-1e5e-4fba-b256-eb8a38274b39 depth none + 35f02735-1993-4467-b3de-028c2d6e2276 depth none + 36746041-a5bd-4b95-aa18-294acaaeae62 depth 1 + 3689a855-9264-40f0-91b3-8b235dac80b6 depth none + 3987140a-19c3-4b0b-8fa5-528f43a83afb depth none + 3a33da73-ba06-4574-afec-d529097408b5 depth none + 3aa1ac05-6d55-4569-8a4b-e1c3c6e07c61 depth 5 + 3acbb2bf-19fb-4591-bef1-dc9d5dde7e7a depth 0 + 3c6bb1cc-70d8-400b-8d69-9c81339758f3 depth none + 3c8b2b3d-ca1a-405f-966f-c64662a64418 depth 2 + 3ddbbb28-c166-4ab3-8a0b-c7b77c372f32 depth none + 40004417-d242-47d2-9f27-1bbcf8548779 depth none + 4081eb4c-3376-4912-a230-c43096d90ad1 depth none + 421e9788-d094-4c17-88cc-0d820e3cfeca depth none + 4486cfad-3063-4667-80ae-5e4d615ee501 depth none + 452bbd60-11df-449b-a4b7-a4ca22527123 depth none + 4681d1af-1a6d-4c7e-b10d-5ee8295b9a79 depth none + 4810a43b-bbb9-447d-b62e-b723e4d88afc depth none + 498c664d-05ff-45a0-b3b6-2b98feec8611 depth none + 4b3fc716-d362-4379-8c65-f2c471647ed1 depth none + 4c82acfa-b8e4-4601-9465-2fad107b1eff depth none + 4d5929a9-5cb1-470c-a0b7-12f8abaf4497 depth none + 502a6ed8-73aa-4554-ae89-a50b67cfa9e0 depth none + 515734e6-4287-470c-bf56-188c4b257420 depth none + 51e4dc3b-0107-4ab5-a2c6-02d34a1035b2 depth none + 5383d6b6-083b-4721-8f6b-426dba0beaeb depth none + 5449f7d3-b250-41cd-9e7e-ab2a7037cacb depth none + 5837ec5e-036b-4f73-9098-dbe11339909f depth none + 5bcddae5-10fe-4316-9dca-6dc5d53c899e depth none + 5e2950d6-02df-461e-a35e-a4123c6a5639 depth none + 601a345d-6f0b-4bdb-8171-be4befaf9a33 depth none + 63abe46b-ad99-4ac9-b5e4-d83a40465065 depth none + 64bccb57-3aa8-4e5f-829d-07e62295b0c7 depth none + 6713c2b2-d886-4440-b076-dd206c22848a depth none + 675a1ebe-868c-4b27-a2eb-bee2fe5e356b depth none + 679fb6a1-cefb-4adc-a49c-71942602196b depth 5 + 6821495a-4875-4350-a8e8-e813c3576aa8 depth none + 6af6446e40cb4cdd90d7a3fee04394d4 depth 5 + 6d20c298-281e-46fc-be33-dbcc575d49d7 depth none + 6d4c9e32-7ffd-45f6-8e08-86d544793774 depth none + 6dc76b7c-65c3-4cc1-bc2a-eace8e4f58d2 depth none + 6f0ed812-01b0-4767-90c5-0b6857bc2e29 depth none + 7e9783b7-ab6c-4c50-bb99-4f1f3a3e240d depth none + 86d11f6a-9ddd-478d-8192-f047d38a7c6a depth none + 8776c2fd-45f6-4ca6-8ef0-5214be830182 depth 0 + 8ac84e31-f0cf-43b2-8611-3316adfa4010 depth 5 + 8b026aea-1d79-49a0-b843-abdfcca31bab depth none + a8e259fc-fbf1-477a-8248-0277611f1859 depth 1 + commodity:actuator depth 3 + commodity:aluminium depth 1 + commodity:ammonia depth 0 + commodity:anorthite depth 0 + commodity:autoloader depth 4 + commodity:brannerite depth 0 + commodity:cellulose-pulp depth 3 + commodity:chalcopyrite depth 0 + commodity:columbite depth 0 + commodity:copper depth 1 + commodity:explosive-fill depth 3 + commodity:fragmentation-case depth 2 + commodity:fuze depth 4 + commodity:gun-barrel depth 3 + commodity:gun-forging depth 2 + commodity:he-warhead depth 5 + commodity:hexamine depth 1 + commodity:ilmenite depth 0 + commodity:iron depth 1 + commodity:isoferroplatinum depth 0 + commodity:magnetite depth 0 + commodity:mine-dispenser depth 4 + commodity:mines depth 6 + commodity:missiles depth 7 + commodity:monazite depth 0 + commodity:native-copper depth 0 + commodity:native-gold depth 0 + commodity:nickel depth 1 + commodity:niobium depth 1 + commodity:nitric-acid depth 2 + commodity:nitrocellulose depth 4 + commodity:orthoclase depth 0 + commodity:oxygen depth 1 + commodity:pentlandite depth 0 + commodity:platinum-group-metals depth 1 + commodity:potassium-nitrate depth 3 + commodity:primer depth 4 + commodity:projectile depth 2 + commodity:rare-earth-oxides depth 1 + commodity:rocket-motor depth 6 + commodity:shell-casing depth 2 + commodity:sperrylite depth 0 + commodity:steel depth 1 + commodity:sylvite depth 0 + commodity:titanium depth 1 + commodity:troilite depth 0 + commodity:tungsten depth 1 + commodity:uraninite depth 0 + commodity:wolframite depth 0 + d02bcf71f2c8420b878f036cd1a33bea depth 5 + +Dry run. Pass "apply" to write Aetheria.cc. diff --git a/tools/AetherDb/EconomyCommand.cs b/tools/AetherDb/EconomyCommand.cs index 83349a1c0..90592b2bc 100644 --- a/tools/AetherDb/EconomyCommand.cs +++ b/tools/AetherDb/EconomyCommand.cs @@ -8,7 +8,7 @@ using MessagePack; // One batch of economy content: commodities, recipes, station kinds with stand-ins, outside-market rows and edits to existing // items, written through EconomyAuthor. A batch is a class under tools/AetherDb/Economy/, named on the command line by its class -// name. It writes what it names and nothing else, so a revised batch converges and a rerun writes nothing. +// name. It writes what it names and nothing else, so a revised batch converges to the same records; a rerun rewrites any recipe that has inputs as new bytes (their elements carry cache-minted ids), and only `author` with no batch is certain to print Nothing to write. public abstract class EconomyBatch { public abstract void Author(EconomyAuthor author); @@ -42,6 +42,14 @@ public sealed class EconomyAuthor Write(named[0].GetType(), named[0], _catalog.RefOf(named[0]).Key); } + // Sets one item's price, written under the type it is held as. + public void SetPrice(string key, int price) + { + var item = _catalog.Get(new CultRecordKey(key)); + item.Price = price; + Write(item.GetType(), item, new CultRecordKey(key)); + } + private void Write(Type type, object document, CultRecordKey key) { if (!_touched.Contains(key.Value)) _touched.Add(key.Value); @@ -53,33 +61,91 @@ public sealed class EconomyAuthor } } -// economy report | author ... [apply]: the one writer of economy content and a reader of the catalog's economy report. +// economy report | author ... [apply] | prices: the one writer of economy content and a reader of the catalog's economy report. // EconomyChecks owns every rule; this command only calls it. public static class EconomyCommand { // The invariants whose faults the batches introduce refuse them. The rest (a missing sink, no consumer demand, a commodity // with no recipe yet) are completeness: reported, and settled by the batch that closes the chain. private static readonly string[] Shape = - { EconomyChecks.LRecipe, EconomyChecks.LLore, EconomyChecks.LProductive, EconomyChecks.LOneKindList }; + { EconomyChecks.LRecipe, EconomyChecks.LLore, EconomyChecks.LProductive, EconomyChecks.LOneKindList, EconomyChecks.LWeights, EconomyChecks.LShape, EconomyChecks.LPrice }; // A batch is compiled code under tools/AetherDb/Economy/ and runs with the operator's authority: reviewed code, never an input. - private const string Usage = "economy report | author ... [apply]\nA batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor."; + private const string Usage = "economy report | author [...] [apply] | " + EconomyPrices.Usage + " | balance [--loop [...]] [--cap ] | balance --drain [...] [--window ] [--horizon ]\nbalance reads the chain and changes nothing; --loop adds the player loop (a mining sortie per seed, default seeds 1 2 3 69 97, every belt of each, cap 150 sim seconds a sortie) and the offered gear ladders; --drain, not in the same call, adds a station block per seed: sorties to fill, the window (default 600 sim s) on screen and by spans, and the horizon (default 24 sim h) by spans. A batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor. After the batches, author reprices every made good (a commodity, or a design with a recipe) to the price its chain derives; with no batch it reprices alone."; public static int Run(string[] args, TextWriter output) { if (args.Length > 0 && args[0] == "report") { - using var db = AetherDb.Open(); + using var db = AetherDb.OpenBooted(); return Report(db.Cache, output); } - if (args.Length > 1 && args[0] == "author") + if (args.Length > 0 && args[0] == "prices") return EconomyPrices.Run(args.Skip(1).ToArray(), output); + if (args.Length > 0 && args[0] == "balance") + { + using var db = AetherDb.OpenBooted(); + var settings = AuthoredSettings.Load(db.Root).Read("GameplaySettings"); + var rest = args.Skip(1).ToList(); + bool Option(string name, out double value) + { + value = 0; + var at = rest.IndexOf(name); + if (at < 0) return false; + if (at + 1 >= rest.Count || !double.TryParse(rest[at + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out value) || !double.IsFinite(value) || value <= 0) + throw new FormatException(name); + rest.RemoveRange(at, 2); + return true; + } + double cap, window, horizon; + bool capped, windowed, horizoned; + try { (capped, windowed, horizoned) = (Option("--cap", out cap), Option("--window", out window), Option("--horizon", out horizon)); } + catch (FormatException) + { + output.WriteLine(Usage); + return 1; + } + // A cap the sortie takes as a float: a finite double too big for one is as bad as a word. + if (capped && !float.IsFinite((float) cap)) + { + output.WriteLine(Usage); + return 1; + } + if (!capped) cap = EconomyLoop.DefaultCap; + if (!windowed) window = EconomyDrain.DefaultWindowSeconds; + if (!horizoned) horizon = EconomyDrain.DefaultHorizonHours; + var loopAt = rest.IndexOf("--loop"); + var drainAt = rest.IndexOf("--drain"); + var seeds = new List(); + var flagAt = Math.Max(loopAt, drainAt); + if (flagAt >= 0) + foreach (var word in rest.Skip(flagAt + 1)) + { + if (!uint.TryParse(word, out var seed)) { output.WriteLine(Usage); return 1; } + seeds.Add(seed); + } + // One of the two stages a call, its seeds last; each option belongs to its own stage. + if ((flagAt >= 0 ? rest.Count - 1 - seeds.Count : rest.Count) != 0 || (loopAt >= 0 && drainAt >= 0) || (capped && loopAt < 0) || ((windowed || horizoned) && drainAt < 0)) + { + output.WriteLine(Usage); + return 1; + } + var seedList = seeds.Count == 0 ? EconomyLoop.DefaultSeeds : seeds.ToArray(); + LoopReport loop = null; + if (loopAt >= 0) + loop = EconomyLoop.Report(db.Cache, settings, seedList.SelectMany(seed => EconomyLoop.Sorties(db.Root, seed, (float) cap)).ToList()); + List drain = null; + if (drainAt >= 0) + drain = seedList.Select(seed => EconomyDrain.Run(db.Root, seed, window, horizon, EconomyLoop.Sorties(db.Root, seed, EconomyLoop.DefaultCap))).ToList(); + return Balance(db.Cache, settings.EconomyWageSpread, output, loop, drain); + } + if (args.Length > 0 && args[0] == "author") { var apply = args.Contains("apply"); var names = args.Skip(1).Where(a => a != "apply").ToArray(); var known = typeof(EconomyBatch).Assembly.GetTypes().Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(EconomyBatch))) .OrderBy(t => t.Name, StringComparer.Ordinal).ToArray(); var unknown = names.Where(n => known.All(t => !string.Equals(t.Name, n, StringComparison.OrdinalIgnoreCase))).ToArray(); - if (unknown.Length > 0 || names.Length == 0) + if (unknown.Length > 0) { output.WriteLine($"{unknown.Length} of the names given match no batch. Batches: {string.Join(", ", known.Select(t => t.Name))}"); return 1; @@ -91,6 +157,59 @@ public static class EconomyCommand return 1; } + // The static balance: the median implied wage, the H faults, one line per chain link by wage over the median, then the belts. + // Report-only: nothing here is a Shape invariant. Exit 1 when any fault. + public static int Balance(CultCache catalog, double wageSpread, TextWriter output, LoopReport loop = null, IReadOnlyList drain = null) + { + var report = EconomyBalance.Balance(catalog, wageSpread); + var faults = report.Faults.Concat(loop?.Faults ?? new List()).Concat(drain == null ? new List() : EconomyDrain.Report(drain)).ToList(); + var inv = System.Globalization.CultureInfo.InvariantCulture; + output.WriteLine($"median implied wage {report.WageReference.ToString("0.#####", inv)} per worker-second, spread {wageSpread.ToString(inv)}, {report.Links.Count} links, {report.Links.Count(l => l.Wage == null)} unpriced"); + output.WriteLine($"{faults.Count} faults"); + foreach (var group in faults.GroupBy(f => f.Invariant).OrderBy(g => g.Key, StringComparer.Ordinal)) + { + output.WriteLine($"{group.Key} ({group.Count()})"); + foreach (var fault in group) output.WriteLine($" {fault.Record}: {fault.Message}"); + } + output.WriteLine("\nLinks by wage over the median (output | station kind | labour | price | derived cost | wage | ratio)"); + foreach (var l in report.Links.OrderBy(l => l.WageRatio ?? double.PositiveInfinity).ThenBy(l => l.Output, StringComparer.Ordinal)) + output.WriteLine(string.Format(inv, " {0} ({7}) | {1} | {2:0.#} | {3:0.##} | {4:0.##} | {5} | {6}", l.Output, l.StationKind, l.Labour, l.Price, l.Cost, + l.Wage.HasValue ? l.Wage.Value.ToString("0.#####", inv) : "unpriced " + l.Unpriced, l.WageRatio.HasValue ? l.WageRatio.Value.ToString("0.##", inv) + "x" : "-", l.Name)); + output.WriteLine("\nBelts (kind: abundance-weighted price and derived cost per unit; each ore: share, extraction wage ratio, price, cost)"); + foreach (var belt in report.Belts) + { + output.WriteLine(string.Format(inv, " {0}: price {1:0.##}, cost {2:0.##}", belt.Kind, belt.Price, belt.Cost)); + foreach (var y in belt.Yields) + output.WriteLine(string.Format(inv, " {0} {1:P0} | wage {2} | price {3:0.##} | cost {4:0.##}", y.Ore, y.Share, y.WageRatio.HasValue ? y.WageRatio.Value.ToString("0.##", inv) + "x" : "-", y.Price, y.Cost)); + } + if (loop != null) PrintLoop(loop, output); + if (drain != null) foreach (var sample in drain) EconomyDrain.Print(sample, output); + return faults.Count == 0 ? 0 : 1; + } + + // The player loop and the ladders, as numbers: a line per sortie, the median and best rate and the purse, then each category's + // width and its designs with the minutes of income each takes to afford. No verdict beyond the faults the report raised. + private static void PrintLoop(LoopReport loop, TextWriter output) + { + var inv = System.Globalization.CultureInfo.InvariantCulture; + output.WriteLine("\nPlayer loop (seed belt | kind | weapons | outcome | rocks | sim s | hold full at | units | sold | refused | offered value | sell | ammo | repair | net per minute)"); + foreach (var s in loop.Samples) + output.WriteLine(string.Format(inv, " {0} {11}/{12} | {1} | {2} | {13} | {3} | {4:0.#} | {5} | {6} | {14} | {15} | {16} | {7} | {8} | {9} | {10:0.#}", s.Seed, s.BeltKind, s.Weapons, s.Rocks, s.SimSeconds, + s.HoldFullAt.HasValue ? s.HoldFullAt.Value.ToString("0.#", inv) + " s" : "never", s.Units, s.SellValue, s.AmmoSpent, s.Repair, s.RatePerMinute, s.Belt + 1, s.Belts, s.Outcome, s.UnitsSold, s.UnitsRefused, s.OfferedValue)); + output.WriteLine(string.Format(inv, " median {0:0.#} per minute, best {1:0.#} per minute over the {3} sorties that mined to a full hold or the cap; purse {2}", loop.Median, loop.Best, loop.Purse, loop.Samples.Count(s => s.Measured))); + output.WriteLine(string.Format(inv, " median net per sortie {0:0.#} (the afford band counts sorties of this net, resting on {1} measured sorties)", loop.MedianNet, loop.MeasuredSorties)); + string Minutes(double? m) => m.HasValue ? m.Value.ToString("0.#", inv) : "-"; + string Width(double? w) => w.HasValue ? w.Value.ToString("0.##", inv) + "x" : "-"; + output.WriteLine("\nLadders (category: width; each design: price | priced from | minutes at median | minutes at best | purse covers)"); + foreach (var ladder in loop.Ladders) + { + output.WriteLine($" {ladder.Category}: {Width(ladder.Width)}{(ladder.TopSorties.HasValue ? $", top {ladder.TopSorties.Value.ToString("0.#", inv)} sorties" : "")}"); + foreach (var d in ladder.Designs) + output.WriteLine(string.Format(inv, " {0} ({1}) | {2} | {3} | {4} | {5} | {6}", d.Name, d.Key, d.Price, d.Chained ? "chain" : "authored", + Minutes(d.MinutesAtMedian), Minutes(d.MinutesAtBest), d.Covered ? "yes" : "no")); + } + } + // Faults grouped by invariant, then one line per good with its depth, then one line per recipe. Fails on any fault. public static int Report(CultCache catalog, TextWriter output) { @@ -158,6 +277,7 @@ public static class EconomyCommand batch.Author(author); } running = ""; + Reprice(author); StationKinds.Validate(cache); } catch (Exception e) @@ -224,6 +344,19 @@ public static class EconomyCommand } } + // Every made good (a commodity, or a design with a recipe) takes the price its chain derives. The one writer of a made price: + // batches may set any, this overwrites it. + private static void Reprice(EconomyAuthor author) + { + var prices = EconomyBalance.Prices(author.Catalog, out var unsettled); + if (unsettled.Count > 0) throw new InvalidOperationException(EconomyBalance.Unsettled(author.Catalog, unsettled)); + foreach (var (key, derived) in prices.OrderBy(p => p.Key, StringComparer.Ordinal)) + { + var price = EconomyBalance.Rounded(derived); + if (author.Catalog.Get(new CultRecordKey(key))?.Price is int held && held != price) author.SetPrice(key, price); + } + } + // Something holds Aetheria.cc open: a refusal that names the holder to close, never an exception. private static string Held(string verb, Exception e) => $"The batches are refused: Aetheria.cc could not be {verb} ({e.Message}). Something holds the file: close Unity and any other editor or tool that has it open, then run again. The catalog is unchanged."; diff --git a/tools/AetherDb/EconomyDrain.cs b/tools/AetherDb/EconomyDrain.cs new file mode 100644 index 000000000..1b72c33f9 --- /dev/null +++ b/tools/AetherDb/EconomyDrain.cs @@ -0,0 +1,445 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; + +// What a station's intake and drain look like in the demo run of one seed (ruling station-intake-few-sorties: a station takes ore +// for a few sorties, then fills, and installed facilities work it down). Measurement only: it reads a booted copy of the catalog, +// fills the two demo stations with the holds the base loop's sorties mined (a faulted sortie is reported and left out) through the shipped sale (StationServices.TrySellOre), then reads +// the drain twice. On screen for a bounded window, stepping the arena; and by Production.Advance spans on inactive copies for the +// window (which must agree with the steps: H-drain-sim) and for the long horizon (the same rule, FacilityProductionTests. +// OneSpanEqualsManySteps). Writes no catalog, changes no setting: every record it touches is in the booted scratch. + +// One bay of a station before any sale: its usable cells, the free ones, and the units of each wanted ore it takes at that ore's MaxStack. +public sealed class BayIntake +{ + public string Name; + public bool Silo; + public int Cells, Free; + // Units of wanted ore the bay holds after the fill. + public int Taken; + public List<(string Ore, int Units)> Capacity = new List<(string, int)>(); +} + +// One sortie's hold offered to the station through the shipped sale. +public sealed class SortieSale +{ + // The ores of the hold as mined, with units; Held is what the station wants of them (the offer), Sold what its bays took. + public string Hold; + public int Held, Sold; + public int Refused => Held - Sold; +} + +public sealed class FacilityDrain +{ + public string Name; + // One line per recipe the facility runs: output, cycle, inputs. + public List RunList = new List(); + // Steps of the on-screen window per Stall, and the Stall the last span of the horizon ended in. + public SortedDictionary WindowSteps = new SortedDictionary(); + public Stall HorizonEnd; + // The ores some recipe of this facility draws that the station still holds when the horizon ends. + public List OresLeft = new List(); +} + +public sealed class OreDrain +{ + public string Ore; + // Units held after the fill and after each sim hour of the horizon (index 0 is the fill). + public List Hourly = new List(); + // Sim seconds until none is held, or null with the facilities' last Stall. + public double? EmptyAt; + public string NeverBecause = ""; +} + +public sealed class OutputPile +{ + public string Metal; + public List Hourly = new List(); +} + +public sealed class StationDrain +{ + public string Role, Name, Kind; + public List Bays = new List(); + // The sorties to the first refusal, or all of them when the cap on sorties ended it. + public List Sorties = new List(); + public bool Filled; + public List Facilities = new List(); + public List Ores = new List(); + public List Outputs = new List(); + // Sim seconds into the horizon at the end of the first span any facility ended stalled Room, or null. + public double? FirstRoomStall; + // Where the window by steps and by spans part: units held of a design, a facility's run progress, the sim time of its first Room stall. + public List WindowDisagreements = new List(); +} + +public sealed class DrainSample +{ + public uint Seed; + // The base loop's sorties of this seed: the usable ones fill the stations, the rest are faults and left out of the count. + public int Usable; + public List Excluded = new List(); + // Haulers taken out of the arena before anything else: the harness measures facilities, so no haul moves on screen or in the spans. + public int Parked; + public double WindowSeconds, HorizonHours; + public List Stations = new List(); +} + +public static class EconomyDrain +{ + public const string HStall = "H-drain-stall", HSim = "H-drain-sim", HSortie = "H-drain-sortie"; + public const double DefaultWindowSeconds = 1200, DefaultHorizonHours = 24; + // One span of the off-screen path, in sim seconds: the resolution of every time the horizon reports. + public const double Span = 60; + private const int MaxSorties = 500; + // Stepped and spanned run progress differ by float rounding only; a skew of one step (0.02 s) is far outside this. A cycle that ends on a + // span boundary is met by the steps one or two steps later, as their sum falls just short of it. + private const double ProgressTolerance = 1e-3; + + // sorties are the base loop's samples of this seed (EconomyLoop.Sorties). A measured one that mined something fills the + // stations with the ore it carried as mined; any other (ammunition out, the rig measured nothing) is reported as a fault by + // Report and is not a sortie of the fill count. beforeWindow sees the arena after the fill and before the window is read by steps + // or by spans (a test makes room or switches a facility off there); onStep sees it before each on-screen step (a test skews time). + public static DrainSample Run(string root, uint seed, double windowSeconds, double horizonHours, IReadOnlyList sorties, + Action beforeWindow = null, Action onStep = null) + { + if (!double.IsFinite(windowSeconds) || windowSeconds <= 0) throw new ArgumentOutOfRangeException(nameof(windowSeconds), "the window must be a positive, finite number of sim seconds"); + if (!double.IsFinite(horizonHours) || horizonHours <= 0) throw new ArgumentOutOfRangeException(nameof(horizonHours), "the horizon must be a positive, finite number of sim hours"); + using var demo = EconomyLoop.Boot(root, seed); + var catalog = demo.Cache; + // The demo's hauler flies orders on screen and has no span-side model (follow-up drain-haul-throughput; off-screen hauling is + // region-haul-legs), so it is parked in both paths: taken out of the arena before the fill, the window and the spans. + var haulers = demo.Arena.Entities.OfType().Where(ship => ship.Haul.Key.IsSet()).ToList(); + foreach (var hauler in haulers) + if (demo.Arena.Remove(hauler)) hauler.Deactivate(); + var usable = sorties.Where(s => s.Measured && s.Mined.Count > 0).ToList(); + var sample = new DrainSample { Seed = seed, Parked = haulers.Count, Usable = usable.Count, Excluded = sorties.Except(usable).ToList(), WindowSeconds = windowSeconds, HorizonHours = horizonHours }; + var stations = new[] { ("processing", demo.Processing), ("trade-hub", demo.Zenith) }; + var runs = new List(); + foreach (var (role, station) in stations) + { + var drain = new StationDrain { Role = role, Name = station.Name, Kind = station.Kind.Key.Value }; + var ores = WantedOres(demo, station); + foreach (var bay in station.CargoBays) drain.Bays.Add(Intake(demo, station, bay, ores)); + Fill(demo, station, usable, drain); + for (var at = 0; at < drain.Bays.Count; at++) + drain.Bays[at].Taken = station.CargoBays.ElementAt(at).Cargo.Keys.OfType().Where(stack => ores.Contains(((ItemInstance) stack).Data.Key)).Sum(stack => stack.Quantity); + sample.Stations.Add(drain); + runs.Add(new StationRun(demo, station, drain, ores)); + } + beforeWindow?.Invoke(demo); + foreach (var run in runs) run.Copy(); + + // The window on screen: the arena steps, every facility's Stall is read after each step, and the first Room is timed. + var steps = (int) Math.Round(windowSeconds / EconomyLoop.Step); + foreach (var run in runs) + { + run.Live = run.Station.Equipment.SelectMany(unit => unit.Behaviors.OfType().Select(facility => (unit, facility))).ToArray(); + run.LiveRoom = new double?[run.Live.Length]; + } + for (var step = 0; step < steps; step++) + { + onStep?.Invoke(demo, step); + demo.Arena.Update(EconomyLoop.Step); + foreach (var run in runs) + for (var at = 0; at < run.Live.Length; at++) + { + var tally = run.Drain.Facilities[at].WindowSteps; + var stall = run.Live[at].facility.Stall; + tally[stall] = tally.TryGetValue(stall, out var n) ? n + 1 : 1; + if (stall == Stall.Room && run.LiveRoom[at] == null) run.LiveRoom[at] = (step + 1) * (double) EconomyLoop.Step; + } + } + // The same window by spans on the copy: the units held, each facility's run (recipe and progress) and the time of its first Room + // must read as the steps did, to the span for the time. Held counts alone are blind to a facility that stalls Room. So is the run + // progress: a Room-stalled facility holds at its Cycle whatever the time, so a skew there is caught only through its first-Room + // time, within one span, and not at all after. + foreach (var run in runs) + { + var spanRoom = new double?[run.Live.Length]; + run.Spans(run.WindowCopy, steps * (double) EconomyLoop.Step, (at, stalls) => + { + for (var i = 0; i < stalls.Length; i++) + if (stalls[i] == Stall.Room && spanRoom[i] == null) spanRoom[i] = at; + }); + var onScreen = Held(run.Station); + var spanned = Held(run.WindowCopy); + foreach (var design in onScreen.Keys.Union(spanned.Keys).OrderBy(k => k, StringComparer.Ordinal)) + { + onScreen.TryGetValue(design, out var a); + spanned.TryGetValue(design, out var b); + if (a != b) run.Drain.WindowDisagreements.Add($"{Name(catalog, design)} held {a} by steps against {b} by spans"); + } + var copied = StationRun.Units(run.WindowCopy); + for (var i = 0; i < run.Live.Length; i++) + { + var name = run.Drain.Facilities[i].Name; + var (live, copy) = (run.Live[i].unit.EquippableItem.Run, copied[i].Run); + var (liveRecipe, copyRecipe) = (live?.Recipe.Key.Value, copy?.Recipe.Key.Value); + var (liveProgress, copyProgress) = (live?.Progress ?? 0, copy?.Progress ?? 0); + if (liveRecipe != copyRecipe || Math.Abs(liveProgress - copyProgress) > ProgressTolerance) + run.Drain.WindowDisagreements.Add($"{name} run {liveRecipe ?? "idle"} at {liveProgress:0.###} s by steps against {copyRecipe ?? "idle"} at {copyProgress:0.###} s by spans"); + var (steppedRoom, spannedRoom) = (run.LiveRoom[i], spanRoom[i]); + if (steppedRoom.HasValue != spannedRoom.HasValue || (steppedRoom.HasValue && !(steppedRoom.Value > spannedRoom.Value - Span - ProgressTolerance && steppedRoom.Value <= spannedRoom.Value + 2 * EconomyLoop.Step))) + run.Drain.WindowDisagreements.Add($"{name} first Room at {(steppedRoom.HasValue ? steppedRoom.Value.ToString("0.##", CultureInfo.InvariantCulture) : "never")} s by steps against {(spannedRoom.HasValue ? spannedRoom.Value.ToString("0.##", CultureInfo.InvariantCulture) : "never")} s by spans"); + } + } + + // The horizon by spans on a copy of the filled station, sampled each sim hour. + foreach (var run in runs) run.Horizon(horizonHours); + return sample; + } + + // The faults of a set of samples: a facility that ends the horizon stalled with ore it draws still held, and a window that steps + // and spans read differently. + public static List Report(IReadOnlyList samples) + { + var faults = new List(); + foreach (var sample in samples) + { + foreach (var excluded in sample.Excluded) + faults.Add(new EconomyFault(HSortie, $"seed {sample.Seed} belt {excluded.Belt + 1} of {excluded.Belts}", $"the base sortie is {excluded.Outcome} after {excluded.SimSeconds:0.#} s ({excluded.Units} units mined{(string.IsNullOrEmpty(excluded.Note) ? "" : ", " + excluded.Note)}): it is left out of the fill count.")); + foreach (var station in sample.Stations) + { + var where = $"seed {sample.Seed} {station.Role}"; + foreach (var facility in station.Facilities.Where(f => f.OresLeft.Count > 0 && (f.HorizonEnd == Stall.Room || f.HorizonEnd == Stall.Inputs))) + faults.Add(new EconomyFault(HStall, where, $"{facility.Name} ends the {sample.HorizonHours:0.##} h horizon stalled {facility.HorizonEnd} with {string.Join(", ", facility.OresLeft)} still held: the station does not drain what it took.")); + if (station.WindowDisagreements.Count > 0) + faults.Add(new EconomyFault(HSim, where, $"the {sample.WindowSeconds:0.##} s window by steps and by spans disagree: {string.Join("; ", station.WindowDisagreements)}.")); + } + } + return faults; + } + + public static void Print(DrainSample sample, TextWriter output) + { + var inv = CultureInfo.InvariantCulture; + output.WriteLine(string.Format(inv, "\nStation drain, seed {0} (window {1:0.##} s on screen and by spans; horizon {2:0.##} h by spans of {3:0} s)", sample.Seed, sample.WindowSeconds, sample.HorizonHours, Span)); + output.WriteLine($" haulers parked: {sample.Parked} (no haul moves on screen or in the spans: this block measures facilities; haul throughput is follow-up drain-haul-throughput, off-screen hauling region-haul-legs)"); output.WriteLine(" window compares units held, run progress and first-Room time; a Room-stalled facility holds at its cycle whatever the time, so a skew there shows only as first-Room time within one span"); + output.WriteLine(" window compares units held, run progress and first-Room time; a Room-stalled facility holds at its cycle whatever the time, so a skew there shows only as first-Room time within one span"); + output.WriteLine($" sorties usable {sample.Usable} of {sample.Usable + sample.Excluded.Count}" + string.Concat(sample.Excluded.Select(x => $"; excluded belt {x.Belt + 1}/{x.Belts} {x.BeltKind} {x.Outcome} at {x.SimSeconds:0.#} s"))); + foreach (var station in sample.Stations) + { + output.WriteLine($" {station.Role} {station.Name} ({station.Kind})"); + foreach (var bay in station.Bays) + output.WriteLine($" bay {bay.Name} | {(bay.Silo ? "silo" : "stock")} | cells {bay.Cells} | free {bay.Free} | ore units at MaxStack: {(bay.Capacity.Count == 0 ? "none wanted" : string.Join("; ", bay.Capacity.GroupBy(c => c.Units).Select(g => $"{g.Key} each of {string.Join(", ", g.Select(c => c.Ore))}")))} | wanted ore held after the fill: {bay.Taken}"); + output.WriteLine(station.Sorties.Count == 0 + ? " sorties to fill: none (no usable sortie)" + : $" sorties to fill: {station.Sorties.Count}{(station.Filled ? "" : "+ (the station took the whole hold of the last one or the cap on sorties ended it)")} | per sortie (hold as mined | wanted sold refused): {string.Join("; ", station.Sorties.Select(s => $"{s.Hold} | {s.Held} {s.Sold} {s.Refused}"))}"); + foreach (var facility in station.Facilities) + { + output.WriteLine($" facility {facility.Name}: {facility.RunList.Count} recipes"); + foreach (var line in facility.RunList) output.WriteLine(" " + line); + var total = facility.WindowSteps.Values.Sum(); + output.WriteLine($" window stalls: {(total == 0 ? "no steps" : string.Join(", ", facility.WindowSteps.Select(kv => string.Format(inv, "{0} {1:0.#}%", kv.Key, 100.0 * kv.Value / total))))} | horizon ends {facility.HorizonEnd}"); + } + output.WriteLine(station.WindowDisagreements.Count == 0 + ? " window by steps and by spans: units held, run progress and first Room time agree" + : $" window by steps and by spans: DISAGREE: {string.Join("; ", station.WindowDisagreements)}"); + foreach (var ore in station.Ores) + { + var drained = ore.Hourly[0] - ore.Hourly[ore.Hourly.Count - 1]; + var hours = (ore.EmptyAt ?? sample.HorizonHours * 3600) / 3600; + output.WriteLine(string.Format(inv, " ore {0}: {1} held after the fill, {2:0.##} per sim hour drained, full to empty {3} | per hour {4}", ore.Ore, ore.Hourly[0], hours > 0 ? drained / hours : 0, + ore.EmptyAt.HasValue ? ore.EmptyAt.Value.ToString("0", inv) + " sim s (" + (ore.EmptyAt.Value / 3600).ToString("0.##", inv) + " h)" : "never (" + ore.NeverBecause + ")", string.Join(" ", ore.Hourly))); + } + foreach (var pile in station.Outputs.Where(p => p.Hourly.Any(units => units > 0))) + output.WriteLine($" output {pile.Metal}: units held per hour {string.Join(" ", pile.Hourly)}"); + var empty = station.Outputs.Where(p => p.Hourly.All(units => units == 0)).Select(p => p.Metal).ToList(); + if (empty.Count > 0) output.WriteLine($" outputs held at 0 all horizon: {string.Join(", ", empty)}"); + if (station.Outputs.Count > 0) + output.WriteLine(station.FirstRoomStall.HasValue + ? string.Format(inv, " first Room stall at {0:0} sim s ({1:0.##} h)", station.FirstRoomStall.Value, station.FirstRoomStall.Value / 3600) + : " no Room stall in the horizon"); + } + } + + // The ores the station wants, in key order: what a sortie can bring that it will take. + private static List WantedOres(DemoArena demo, Entity station) => + StationWants.Of(station).Where(key => FieldKinds.IsOre(demo.Cache, demo.Cache.Get(key))).OrderBy(key => key.Value, StringComparer.Ordinal).ToList(); + + private static string Name(CultCache catalog, string key) => catalog.Get(new CultRecordKey(key))?.Name ?? key; + + // One bay as it is booted: capacity for each wanted ore is measured on an inactive copy of the station, so the sale below + // never moves it. + private static BayIntake Intake(DemoArena demo, Entity station, EquippedCargoBay bay, List ores) + { + var shape = bay.Data.InteriorShape; + var cells = shape.AllCoordinates.Count(v => shape[v]); + var used = shape.AllCoordinates.Count(v => shape[v] && bay.Occupancy[v.x, v.y] != null); + var intake = new BayIntake { Name = bay.Name, Silo = bay.Data is SiloData, Cells = cells, Free = cells - used }; + var at = station.CargoBays.ToList().IndexOf(bay); + foreach (var ore in ores) + { + var copy = Copy(demo, station).CargoBays.ElementAt(at); + var maxStack = demo.Cache.Get(ore).MaxStack; + var units = 0; + while (copy.TryStore(new SimpleCommodity { Data = new CultRecordRef(ore), Quantity = maxStack })) units += maxStack; + // The last, partial stack: halve the quantity until one fits. + for (var quantity = maxStack / 2; quantity >= 1; quantity /= 2) + while (copy.TryStore(new SimpleCommodity { Data = new CultRecordRef(ore), Quantity = quantity })) units += quantity; + intake.Capacity.Add((demo.Cache.Get(ore).Name, units)); + } + return intake; + } + + // Sorties to fill: the usable sorties of the seed in turn, each hold as it was mined, sold through the shipped sale until a sortie + // sells less than the station wanted of it. The hold is the player's own; what the sale leaves aboard is put away. + private static void Fill(DemoArena demo, Entity station, List usable, StationDrain drain) + { + if (usable.Count == 0) return; + var player = demo.Player; + for (var sortie = 0; sortie < MaxSorties; sortie++) + { + var mined = usable[sortie % usable.Count]; + foreach (var (ore, units) in mined.Mined) + { + var maxStack = demo.Cache.Get(ore).MaxStack; + for (var left = units; left > 0;) + { + var quantity = Math.Min(left, maxStack); + if (!player.CargoBays.Any(bay => bay.TryStore(new SimpleCommodity { Data = new CultRecordRef(ore), Quantity = quantity }))) + throw new InvalidOperationException($"seed {drain.Name}: the player's hold cannot take back the {units} units of {ore.Value} its sortie mined"); + left -= quantity; + } + } + var credits = 0; + var result = StationServices.TrySellOre(player.CargoBays, station, ref credits); + drain.Sorties.Add(new SortieSale { Hold = string.Join(", ", mined.Mined.Select(m => $"{m.Units} {demo.Cache.Get(m.Ore).Name}")), Held = result.Offered, Sold = result.Sold }); + foreach (var bay in player.CargoBays) + foreach (var stack in bay.Cargo.Keys.OfType().Where(s => mined.Mined.Any(m => m.Ore.Equals(s.Data.Key))).ToList()) + bay.Remove(stack); + if (result.Offered == 0) return; + if (result.Sold < result.Offered) { drain.Filled = true; return; } + } + } + + // An inactive copy of a station as it stands, through the bytes a save would hold: Pack alone shares the stack objects with the + // live station, so a copy's sale or take would move the original's units. + public static Entity Copy(DemoArena demo, Entity station) + { + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + var bytes = MessagePackSerializer.Serialize(EntitySerializer.Pack(station), options); + return EntitySerializer.Unpack(demo.Items, demo.Arena, MessagePackSerializer.Deserialize(bytes, options)); + } + + private static Dictionary Held(Entity entity) + { + var held = new Dictionary(StringComparer.Ordinal); + foreach (var bay in entity.CargoBays) + foreach (var stack in bay.Cargo.Keys.OfType()) + { + var key = ((ItemInstance) stack).Data.Key.Value; + held[key] = held.TryGetValue(key, out var n) ? n + stack.Quantity : stack.Quantity; + } + return held; + } + + // One station through the window and the horizon: the live one on screen, and inactive copies of it as it stood after the fill. + private sealed class StationRun + { + public readonly DemoArena Demo; + public readonly Entity Station; + public readonly StationDrain Drain; + public readonly List Ores; + public Entity WindowCopy, HorizonCopy; + public (EquippedItem unit, Facility facility)[] Live = Array.Empty<(EquippedItem, Facility)>(); + // The sim second each live facility first stalled Room on screen, null while it has not. + public double?[] LiveRoom = Array.Empty(); + + public StationRun(DemoArena demo, Entity station, StationDrain drain, List ores) + { + Demo = demo; + Station = station; + Drain = drain; + Ores = ores; + } + + public void Copy() + { + WindowCopy = EconomyDrain.Copy(Demo, Station); + HorizonCopy = EconomyDrain.Copy(Demo, Station); + foreach (var (unit, facility) in Facilities(Station)) + { + var design = Demo.Items.GetData(unit.EquippableItem); + var drain = new FacilityDrain { Name = design.Name }; + foreach (var recipe in Production.RunList(Demo.Cache, Demo.Cache.RefOf(design).Key)) + drain.RunList.Add($"{Demo.Cache.Get(recipe.Output).Name} x{recipe.OutputCount} | cycle {recipe.Cycle:0.##} s | takes {string.Join(", ", Production.Draws(Demo.Cache, recipe).Select(key => Name(Demo.Cache, key.Value)))}"); + Drain.Facilities.Add(drain); + } + } + + // The facility gear of an entity, in equipment order: the order every per-facility list here is indexed in. + public static EquippableItem[] Units(Entity entity) => + entity.Equipment.Where(unit => unit.Behaviors.OfType().Any()).Select(unit => unit.EquippableItem).ToArray(); + + private static IEnumerable<(EquippedItem unit, Facility facility)> Facilities(Entity entity) => + entity.Equipment.SelectMany(unit => unit.Behaviors.OfType().Select(facility => (unit, facility))); + + // The copy's facilities, each advanced through `seconds` of sim time in spans of Span, in equipment order. Returns the Stall + // each ended in; each sees the sim time and the stalls after every span. + public Stall[] Spans(Entity copy, double seconds, Action each = null) + { + var catalog = Demo.Cache; + var hold = new EntityHold(copy); + var units = Units(copy); + var last = new Stall[units.Length]; + for (var at = 0.0; at < seconds - 1e-9;) + { + var span = Math.Min(Span, seconds - at); + for (var i = 0; i < units.Length; i++) + { + var (run, stall) = Production.Advance(catalog, Production.RunList(catalog, units[i].Data.Key), units[i].Run, span, hold); + units[i].Run = run; + last[i] = stall; + } + at += span; + each?.Invoke(at, last); + } + return last; + } + + public void Horizon(double hours) + { + var catalog = Demo.Cache; + var hold = new EntityHold(HorizonCopy); + var facilities = Facilities(HorizonCopy).Select(f => f.unit).ToArray(); + var outputs = facilities.SelectMany(unit => Production.RunList(catalog, unit.EquippableItem.Data.Key)).Select(r => r.Output.Key).Distinct().OrderBy(k => k.Value, StringComparer.Ordinal).ToList(); + var oreKeys = Ores.Where(ore => hold.Held(ore) > 0).ToList(); + foreach (var ore in oreKeys) Drain.Ores.Add(new OreDrain { Ore = Name(catalog, ore.Value) }); + foreach (var metal in outputs) Drain.Outputs.Add(new OutputPile { Metal = Name(catalog, metal.Value) }); + void Sample() + { + for (var i = 0; i < oreKeys.Count; i++) Drain.Ores[i].Hourly.Add(hold.Held(oreKeys[i])); + for (var i = 0; i < outputs.Count; i++) Drain.Outputs[i].Hourly.Add(hold.Held(outputs[i])); + } + Sample(); + var nextHour = 3600.0; + var ends = Spans(HorizonCopy, hours * 3600, (at, stalls) => + { + if (!Drain.FirstRoomStall.HasValue && stalls.Any(stall => stall == Stall.Room)) Drain.FirstRoomStall = at; + for (var i = 0; i < oreKeys.Count; i++) + if (!Drain.Ores[i].EmptyAt.HasValue && hold.Held(oreKeys[i]) == 0) Drain.Ores[i].EmptyAt = at; + if (at >= nextHour - 1e-9) { Sample(); nextHour += 3600; } + }); + HashSet Draws(EquippedItem unit) => Production.RunList(catalog, unit.EquippableItem.Data.Key).SelectMany(recipe => Production.Draws(catalog, recipe)).ToHashSet(); + for (var i = 0; i < ends.Length; i++) + { + var draws = Draws(facilities[i]); + Drain.Facilities[i].HorizonEnd = ends[i]; + Drain.Facilities[i].OresLeft = oreKeys.Where(ore => draws.Contains(ore) && hold.Held(ore) > 0).Select(ore => Name(catalog, ore.Value)).ToList(); + } + for (var i = 0; i < oreKeys.Count; i++) + { + if (Drain.Ores[i].EmptyAt.HasValue) continue; + var drawers = Enumerable.Range(0, facilities.Length).Where(f => Draws(facilities[f]).Contains(oreKeys[i])).ToList(); + Drain.Ores[i].NeverBecause = drawers.Count == 0 ? "no facility draws it" : string.Join("/", drawers.Select(f => ends[f]).Distinct()); + } + } + } +} diff --git a/tools/AetherDb/EconomyLoop.cs b/tools/AetherDb/EconomyLoop.cs new file mode 100644 index 000000000..4d4ee1dd8 --- /dev/null +++ b/tools/AetherDb/EconomyLoop.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using CultMath; +using GameCult.Caching; +using UniRx; + +// The player loop of `economy balance --loop`: a measured mining sortie per seed, the income it implies, the minutes that income +// takes to afford each offered design, and the width of each offered gear ladder against a band. It measures and reports; it changes +// no price, yield or purse (rulings economy-numbers-are-sim-tuned-knobs, economy-tuned-by-systemic-health). Faults are report-only. +// The sortie driver teleports the ship, so it is a measuring rig that lives here and never in ServerShared. +public enum LoopOutcome +{ + // The hold filled (the first unit floated): the sortie measured what a full trip pays. + Full, + // The cap ended it with the ship still mining. + Capped, + // A stock the ship started with ran out: it cannot sustain mining. The rate is measured up to there and never enters the median. + AmmoOut, + // The rig measured nothing (no rock could be targeted, or it ran out of rocks early): never income. + RigFault +} + +public sealed class LoopSample +{ + public uint Seed; + // This sample's belt in the zone's generation order, and how many belts the zone holds. + public int Belt; + public int Belts; + public string BeltKind; + public string Weapons; + public LoopOutcome Outcome; + public string Note; + public int Rocks; + public double SimSeconds; + public int Units; + // The ore the hold carried when the sortie ended, as mined, in key order: what a station is offered. Not printed. + public List<(CultRecordKey Ore, int Units)> Mined = new List<(CultRecordKey, int)>(); + // The sim second the first unit floated, i.e. the hold was full; null if it never filled. + public double? HoldFullAt; + // What the arena's processing station paid for the hold at sortie end (TrySellOre), and what it would have paid for every ore + // stack it wants had its bays had room (OreValue); the units it took and the units it refused for want of room. + public int SellValue; + public int OfferedValue; + public int UnitsSold; + public int UnitsRefused; + public int AmmoSpent; + public int Repair; + + public int Net => SellValue - AmmoSpent - Repair; + public double RatePerMinute => SimSeconds > 0 ? Net * 60.0 / SimSeconds : 0; + // Only a sortie that mined to a full hold or to the cap says what the loop pays. + public bool Measured => Outcome == LoopOutcome.Full || Outcome == LoopOutcome.Capped; +} + +public sealed class LoopDesign +{ + public string Key; + public string Name; + public int Price; + // The design has a recipe, so its price is derived from its chain; otherwise the authored price stands. + public bool Chained; + public double? MinutesAtMedian; + public double? MinutesAtBest; + public bool Covered; +} + +public sealed class LoopLadder +{ + public string Category; + public List Designs; + // Dearest over cheapest, for a category of two or more priced designs; null otherwise. + public double? Width; + // Sorties at the median net it takes to afford the dearest design here; null for a category of one design or with no measured sortie. + public double? TopSorties; +} + +public sealed class LoopReport +{ + public IReadOnlyList Samples; + // Over the measured samples only. + public double Median; + public double Best; + // The median net of a measured sortie, and how many sorties it rests on. + public double MedianNet; + public int MeasuredSorties; + public int Purse; + public List Ladders; + public List Faults; +} + +public static class EconomyLoop +{ + public const string HLoop = "H-loop", HLadder = "H-ladder", HAfford = "H-afford", HAmmo = "H-ammo", HRig = "H-rig"; + // The ladder band and the afford band are rulings about weapons and gear only (ladder-band-weapons-and-gear). + private static bool Banded(string category) => category.StartsWith("Weapon/", StringComparison.Ordinal) || category.StartsWith("Gear/", StringComparison.Ordinal); + public static readonly uint[] DefaultSeeds = { 1, 2, 3, 69, 97 }; + // Every belt of every default seed is a sample (11 of them), so the cap is what bounds wall time. + public const float DefaultCap = 150f; + + internal const float Step = .02f; + private const float RockSeconds = 60f; + private const int AmmoCheckTicks = 10; + + // One sortie per belt of the demo run of this seed, each its own sample. + public static List Sorties(string root, uint seed, float capSeconds) + { + var first = Sortie(root, seed, 0, capSeconds); + var samples = new List { first }; + for (var belt = 1; belt < first.Belts; belt++) samples.Add(Sortie(root, seed, belt, capSeconds)); + return samples; + } + + // The demo run of one seed booted in a scratch of its own, with the two stations found by what they are for. Everything it + // touches is its own: a scratch copy of the catalog, its own run store and its own ItemManager (a shared one advances its + // Random and gave the same seed different results). Dispose closes the store and deletes the scratch. + public static DemoArena Boot(string root, uint seed) + { + var scratch = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-loop-" + Guid.NewGuid().ToString("N"))).FullName; + var demo = new DemoArena(scratch); + try + { + // The catalog the game boots (the Pirates' station hulls are a package's), composed in the scratch, never written back. + var composed = AetherDb.ComposeBooted(root, scratch); + var cache = demo.Cache = AetheriaStores.Open(composed, runPath: Path.Combine(scratch, "run.cc")); + var authored = AuthoredSettings.Load(root); + var items = demo.Items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); + var zoneSettings = authored.Read("ZoneSettings"); + var planetSettings = authored.Read("PlanetSettings"); + var startingHull = File.ReadLines(Path.Combine(root, "Assets", "Resources", "Settings.asset")) + .Select(line => Regex.Match(line, @"^ StartingHullName: (.+)$")).First(match => match.Success).Groups[1].Value.Trim(); + + var scenario = new DemoTerminus(); + var stage = new GalaxyStage(authored.Read("SectorGenerationSettings"), + authored.Read("SectorBackgroundSettings"), authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, () => seed); + var galaxy = RunStart.Generate(scenario, stage); + var arena = demo.Arena = new Zone(items, planetSettings, RunStart.GenerateArena(items, zoneSettings, planetSettings, galaxy, scenario), galaxy.Entrance, galaxy); + var failures = new List(); + demo.Player = RunStart.Stage(items, arena, scenario, startingHull, failures).Player; + if (failures.Count > 0) throw new InvalidOperationException($"seed {seed}: staging failed: {string.Join("; ", failures)}"); + // The station that buys a sortie's ore and the one that holds it for onward haul, found by what they are for. + OrbitalEntity OfKind(string kind) => arena.Entities.OfType().Single(entity => entity.Kind.Key.Equals(StationKindData.KeyOf(kind))); + demo.Processing = OfKind("processing"); + demo.Zenith = OfKind("trade-hub"); + return demo; + } + catch + { + demo.Dispose(); + throw; + } + } + + // One sortie in the demo run of this seed on one belt: the staged ship is held forty units off each rock of the belt in index + // order, fires every weapon at it, and stops when the first unit floats (the hold is full), when a starting stock runs out, or + // at the cap. Everything it touches is its own: a scratch copy of the catalog, its own run store and its own ItemManager (a + // shared one advances its Random and gave the same seed different results). atEnd, if given, sees the ship, items and the processing station as the + // sample is taken, so a test can read the same state the sample was priced from. + public static LoopSample Sortie(string root, uint seed, int beltIndex, float capSeconds, Action atEnd = null) + { + if (!float.IsFinite(capSeconds) || capSeconds <= 0) throw new ArgumentOutOfRangeException(nameof(capSeconds), "the cap must be a positive, finite number of sim seconds"); + using var demo = Boot(root, seed); + var (cache, items, arena, player, processing) = (demo.Cache, demo.Items, demo.Arena, demo.Player, demo.Processing); + + var belts = arena.Planets.Where(body => body.Value is AsteroidBeltData).ToList(); + if (beltIndex < 0 || beltIndex >= Math.Max(belts.Count, 1)) throw new ArgumentOutOfRangeException(nameof(beltIndex), $"seed {seed} has {belts.Count} belts"); + var weapons = player.Equipment.SelectMany(item => item.Behaviors.OfType()).ToArray(); + var sample = new LoopSample + { + Seed = seed, Belt = beltIndex, Belts = belts.Count, BeltKind = "none", + Weapons = string.Join(", ", weapons.Select(w => items.GetData(w.Item.EquippableItem).Name).GroupBy(n => n).Select(g => g.Count() + "x " + g.Key)) + }; + if (belts.Count == 0) + { + sample.Outcome = LoopOutcome.RigFault; + sample.Note = "the zone holds no belt"; + return sample; + } + var belt = belts[beltIndex]; + var beltData = (AsteroidBeltData) belt.Value; + sample.BeltKind = cache.Get(beltData.Kind)?.Name ?? beltData.Kind.Key.Value; + var ammoBefore = Ammunition(items, player); + var units = 0; + arena.CargoGained.Subscribe(gain => units += gain.Stored); + + for (var tick = 0; tick < 50; tick++) arena.Update(Step); + var ticks = 0; + var capTicks = (int) Math.Round(capSeconds / Step); + var broken = 0; + var targeted = 0; + var ammoOut = false; + int? fullTick = null; + bool Stopped() => fullTick != null || ammoOut || ticks >= capTicks; + void Tick(Action hold) + { + hold(); + arena.Update(Step); + ticks++; + if (fullTick == null && arena.FloatingItems.Count > 0) fullTick = ticks; + if (ticks % AmmoCheckTicks == 0 && !ammoOut) + { + var now = Ammunition(items, player); + ammoOut = ammoBefore.Keys.Any(data => !now.ContainsKey(data)); + } + } + + for (var index = 0; index < beltData.Asteroids.Length && !Stopped(); index++) + { + var rock = new ChunkId(belt.Key, index); + if (!arena.ChunkExists(rock)) continue; + void Hold() + { + var at = arena.ChunkPose(rock.Field, rock.Index).xy; + player.Position = new float3(at.x, player.Position.y, at.y - 40f); + player.Velocity = float2.zero; + player.Direction = new float2(0, 1); + player.Aim = new float3(0, 0, 1); + } + Tick(Hold); + Tick(Hold); + if (!player.SetTarget(rock)) continue; + targeted++; + foreach (var weapon in weapons) weapon.Activate(); + for (var spent = 0; spent < (int) Math.Round(RockSeconds / Step) && arena.ChunkExists(rock) && !Stopped(); spent++) Tick(Hold); + if (!arena.ChunkExists(rock)) broken++; + } + foreach (var weapon in weapons) weapon.Deactivate(); + + var ammoAfter = Ammunition(items, player); + var spentOnAmmo = 0L; + foreach (var (data, (quantity, stack)) in ammoBefore) + { + var left = ammoAfter.TryGetValue(data, out var held) ? held.Quantity : 0; + if (quantity > left) spentOnAmmo += StationServices.BuyPrice(items, stack, quantity - left); + } + sample.Rocks = broken; + sample.SimSeconds = ticks * (double) Step; + sample.Units = units; + sample.HoldFullAt = fullTick == null ? null : fullTick * (double) Step; + sample.OfferedValue = StationServices.OreValue(items, player.CargoBays, processing); + sample.AmmoSpent = (int) Math.Min(spentOnAmmo, int.MaxValue); + sample.Repair = StationServices.RepairCost(items, player); + if (fullTick != null) sample.Outcome = LoopOutcome.Full; + else if (ammoOut) { sample.Outcome = LoopOutcome.AmmoOut; sample.Note = "a starting stock ran out"; } + else if (targeted == 0) { sample.Outcome = LoopOutcome.RigFault; sample.Note = "no rock of the belt could be targeted"; } + else if (ticks >= capTicks) sample.Outcome = LoopOutcome.Capped; + else { sample.Outcome = LoopOutcome.RigFault; sample.Note = "ran out of rocks before the cap"; } + sample.Mined = player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()).Where(stack => FieldKinds.IsOre(cache, items.GetData(stack))) + .GroupBy(stack => stack.Data.Key).OrderBy(g => g.Key.Value, StringComparer.Ordinal).Select(g => (g.Key, g.Sum(stack => stack.Quantity))).ToList(); + atEnd?.Invoke(player, items, processing); + // The hold sells to the processing station: it pays for the units its bays take, and the rest stays aboard. + var credits = 0; + var sale = StationServices.TrySellOre(player.CargoBays, processing, ref credits); + sample.SellValue = credits; + sample.UnitsSold = sale.Sold; + sample.UnitsRefused = sale.Offered - sale.Sold; + return sample; + } + // The simple commodities the hold carries that are not ore, summed per commodity: ammunition and consumables. The sampled stack carries the item the price is read from. + private static Dictionary Ammunition(ItemManager items, Entity player) + { + var stacks = player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()) + .Where(stack => !FieldKinds.IsOre(items.ItemData, items.GetData(stack))); + return stacks.GroupBy(stack => items.GetData(stack)).ToDictionary(g => g.Key, g => (g.Sum(stack => stack.Quantity), g.First())); + } + + // The category an offered design belongs to, for the width of its ladder: the one owner of this rule. + public static string Category(ItemData design) => design switch + { + HullData hull => "Hull/" + hull.HullType, + WeaponItemData weapon => "Weapon/" + weapon.WeaponType, + GearData gear => "Gear/" + gear.Hardpoint, + _ => design.GetType().Name + }; + + // Rates, minutes to afford and ladder widths from the samples and the catalog: pure, recomputed every run, nothing stored. + public static LoopReport Report(CultCache catalog, GameplaySettings settings, IReadOnlyList samples) + { + var rates = samples.Where(s => s.Measured).Select(s => s.RatePerMinute).OrderBy(r => r).ToList(); + var median = rates.Count == 0 ? 0 : rates.Count % 2 == 1 ? rates[rates.Count / 2] : (rates[rates.Count / 2 - 1] + rates[rates.Count / 2]) / 2; + var best = rates.Count == 0 ? 0 : rates[rates.Count - 1]; + var nets = samples.Where(s => s.Measured).Select(s => (double) s.Net).OrderBy(n => n).ToList(); + var medianNet = nets.Count == 0 ? 0 : nets.Count % 2 == 1 ? nets[nets.Count / 2] : (nets[nets.Count / 2 - 1] + nets[nets.Count / 2]) / 2; + var derived = EconomyBalance.Prices(catalog, out _); + double? Minutes(int price, double rate) => rate > 0 ? price / rate : (double?) null; + double? Width(IEnumerable prices) + { + var list = prices.Where(p => p > 0).ToList(); + return list.Count >= 2 ? list.Max() / list.Min() : (double?) null; + } + + var ladders = EconomyChecks.OfferedDesigns(catalog).GroupBy(Category).OrderBy(g => g.Key, StringComparer.Ordinal).Select(g => + { + var designs = g.Select(design => + { + var key = catalog.RefOf(design).Key.Value; + return new LoopDesign + { + Key = key, Name = design.Name, Price = design.Price, Chained = derived.ContainsKey(key), + MinutesAtMedian = Minutes(design.Price, median), MinutesAtBest = Minutes(design.Price, best), Covered = design.Price <= settings.StartingCredits + }; + }).OrderBy(d => d.Price).ThenBy(d => d.Key, StringComparer.Ordinal).ToList(); + return new LoopLadder + { + Category = g.Key, Designs = designs, + Width = Width(designs.Select(d => (double) d.Price)), + TopSorties = designs.Count >= 2 && medianNet > 0 ? designs.Max(d => d.Price) / medianNet : (double?) null + }; + }).ToList(); + + var faults = new List(); + foreach (var sample in samples) + { + var where = $"seed {sample.Seed} belt {sample.Belt + 1} of {sample.Belts}"; + if (sample.Outcome == LoopOutcome.AmmoOut) + faults.Add(new EconomyFault(HAmmo, where, $"the fit ran out of a starting stock after {sample.SimSeconds:0.#} s ({sample.Weapons}) and cannot sustain mining.")); + else if (sample.Outcome == LoopOutcome.RigFault) + faults.Add(new EconomyFault(HRig, where, $"the rig measured nothing: {sample.Note}.")); + else if (sample.Net <= 0) + faults.Add(new EconomyFault(HLoop, where, $"the sortie nets {sample.Net} (sell {sample.SellValue}, ammunition {sample.AmmoSpent}, repair {sample.Repair}): no income.")); + } + var (min, max) = (settings.EconomyLadderMin, settings.EconomyLadderMax); + if (min > 0 || max > 0) + foreach (var ladder in ladders.Where(l => Banded(l.Category))) + if (ladder.Width.HasValue && ((min > 0 && ladder.Width.Value < min) || (max > 0 && ladder.Width.Value > max))) + faults.Add(new EconomyFault(HLadder, ladder.Category, $"the ladder is {ladder.Width.Value:0.##}x wide, outside the band {min:0.##} to {max:0.##}.")); + var (sortiesMin, sortiesMax) = (settings.EconomySortiesMin, settings.EconomySortiesMax); + if (sortiesMin > 0 || sortiesMax > 0) + foreach (var ladder in ladders.Where(l => Banded(l.Category) && l.TopSorties.HasValue)) + { + var sorties = ladder.TopSorties.Value; + if ((sortiesMin > 0 && sorties < sortiesMin) || (sortiesMax > 0 && sorties > sortiesMax)) + faults.Add(new EconomyFault(HAfford, ladder.Category, $"the dearest design takes {sorties:0.#} sorties at the median net of {medianNet:0.#}, outside the band {sortiesMin:0.##} to {sortiesMax:0.##}; this rests on {nets.Count} measured sortie(s).")); + } + return new LoopReport { Samples = samples, Median = median, Best = best, MedianNet = medianNet, MeasuredSorties = nets.Count, Purse = settings.StartingCredits, Ladders = ladders, Faults = faults }; + } +} + +// A booted demo run: the arena and what a sortie or a drain reads in it. Owns the scratch copy of the catalog and the run store. +public sealed class DemoArena : IDisposable +{ + private readonly string _scratch; + + public DemoArena(string scratch) => _scratch = scratch; + + public CultCache Cache; + public ItemManager Items; + public Zone Arena; + public Ship Player; + // The refinery that buys a sortie's ore, and the trade hub that holds ore for onward haul. + public OrbitalEntity Processing, Zenith; + + public void Dispose() + { + (Cache as IDisposable)?.Dispose(); + try { Directory.Delete(_scratch, true); } catch (IOException) { } + } +} diff --git a/tools/AetherDb/EconomyPrices.cs b/tools/AetherDb/EconomyPrices.cs new file mode 100644 index 000000000..331f7f717 --- /dev/null +++ b/tools/AetherDb/EconomyPrices.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using GameCult.Caching; + +// economy prices [] [--mods ]: the reader of every price-bearing field. ItemData.Price on each record, +// OutsideMarketRow.Price, a package's hull price (every /*/ship.cc, GameData/Mods by default) and the purse the code +// defaults GameplaySettings.StartingCredits to. Given a second catalog it prints old, new and ratio (old over new) per record: the +// second catalog is the old side. Read-only. A package's old price is not in the second catalog, so a package prints its price alone. +public static class EconomyPrices +{ + public const string Usage = "economy prices [] [--mods ]"; + + public static int Run(string[] args, TextWriter output) + { + string other = null, mods = null; + for (var i = 0; i < args.Length; i++) + { + if (args[i] == "--mods" && i + 1 < args.Length) mods = args[++i]; + else if (other == null && !args[i].StartsWith("--", StringComparison.Ordinal)) other = args[i]; + else { output.WriteLine(Usage); return 1; } + } + // The shipped file alone, on purpose: a package's hull price is read from its ship.cc below, so a composed catalog would list the + // same hull twice, and the second catalog an old side is compared against is a shipped file. + using var db = AetherDb.OpenShipped(); + var now = Read(db.Cache, mods ?? Path.Combine(db.Root, "GameData", "Mods")); + if (other == null) + { + foreach (var (id, row) in now) output.WriteLine($"{id}\t{row.Label}\t{row.Price}"); + return 0; + } + using var then = AetheriaStores.Open(other); + var was = Read(then, null); + foreach (var id in now.Keys.Concat(was.Keys).Distinct().OrderBy(k => k, StringComparer.Ordinal)) + { + var hasOld = was.TryGetValue(id, out var old); + var hasNew = now.TryGetValue(id, out var current); + var ratio = hasOld && hasNew && current.Price != 0 ? (old.Price / (double) current.Price).ToString("0.####", CultureInfo.InvariantCulture) : "-"; + output.WriteLine($"{id}\t{(hasNew ? current.Label : old.Label)}\t{(hasOld ? old.Price.ToString(CultureInfo.InvariantCulture) : "-")}\t{(hasNew ? current.Price.ToString(CultureInfo.InvariantCulture) : "-")}\t{ratio}"); + } + return 0; + } + + // Every price-bearing field, by an id that names the field and the record. mods null reads the catalog alone: no packages and no purse, + // which the catalog does not hold. + public static SortedDictionary Read(CultCache catalog, string mods) + { + var rows = new SortedDictionary(StringComparer.Ordinal); + foreach (var item in catalog.GetAll()) + rows["item:" + catalog.RefOf(item).Key.Value] = ($"{item.GetType().Name} {item.Name}", item.Price); + foreach (var market in catalog.GetAll()) + foreach (var row in market.Rows ?? new List()) + if (row != null) + rows[$"market:{catalog.RefOf(market).Key.Value}:{row.Commodity.Key.Value}"] = ($"OutsideMarketRow {market.Name}", row.Price); + if (mods == null) return rows; + if (Directory.Exists(mods)) + foreach (var path in Directory.GetFiles(mods, "ship.cc", SearchOption.AllDirectories).OrderBy(p => p, StringComparer.Ordinal)) + { + var (hull, ship, _) = ShipAuthoringStore.Load(path); + rows["package:" + ship.Id] = ($"Package hull {hull.Name}", hull.Price); + } + rows["purse"] = ("GameplaySettings.StartingCredits (code default)", new GameplaySettings().StartingCredits); + return rows; + } +} diff --git a/tools/AetherDb/HardpointRotationCommand.cs b/tools/AetherDb/HardpointRotationCommand.cs new file mode 100644 index 000000000..44319edaf --- /dev/null +++ b/tools/AetherDb/HardpointRotationCommand.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using System.Linq; +using GameCult.Caching; + +// Sets one hardpoint's rotation on one catalog hull: hardpoint-rotation "" , [apply]. +// The hull is named exactly once in the catalog and the hardpoint is the one at that position, or nothing is touched. It prints +// the designs that Take the mount before and after (HardpointData.Takes, the one fit rule). Dry run unless apply; a rotation +// the mount already has writes nothing. +public static class HardpointRotationCommand +{ + public const string Usage = "hardpoint-rotation \"\" , [apply]"; + + public static int Run(string[] args) + { + var apply = args.Contains("apply"); + var positional = args.Where(a => a != "apply").ToArray(); + using var db = AetherDb.OpenShipped(catalogWritable: apply); + var code = Run(db.Cache, positional, apply, Console.Out); + if (apply && code == 0) db.Cache.FlushAsync().GetAwaiter().GetResult(); + return code; + } + + public static int Run(CultCache cache, string[] positional, bool apply, TextWriter output) + { + var coordinates = positional.Length == 3 ? positional[1].Split(',') : null; + if (coordinates == null || coordinates.Length != 2 || !int.TryParse(coordinates[0], out var x) || !int.TryParse(coordinates[1], out var y) + || !Enum.TryParse(positional[2], out var rotation) || !Enum.IsDefined(typeof(ItemRotation), rotation)) + { + output.WriteLine(Usage); + return 1; + } + var hulls = cache.GetAll().Where(h => h.Name == positional[0]).ToArray(); + if (hulls.Length != 1) + { + output.WriteLine($"The catalog holds {hulls.Length} hulls named '{positional[0]}'; exactly one is required."); + return 1; + } + var hull = hulls[0]; + var mounts = hull.Hardpoints.Where(h => h.Position.x == x && h.Position.y == y).ToArray(); + if (mounts.Length != 1) + { + output.WriteLine($"{hull.Name} has {mounts.Length} hardpoints at ({x},{y}); exactly one is required."); + return 1; + } + var mount = mounts[0]; + var designs = cache.GetAll().ToArray(); + string Takers() => string.Join(", ", designs.Where(mount.Takes).Select(d => d.Name).OrderBy(n => n, StringComparer.Ordinal)); + var before = mount.Rotation; + output.WriteLine($"{hull.Name} ({x},{y}) {mount.Type} {mount.Shape.Width}x{mount.Shape.Height}: rotation {before} [{Takers()}]"); + if (before == rotation) + { + output.WriteLine("No change."); + return 0; + } + mount.Rotation = rotation; + output.WriteLine($"{hull.Name} ({x},{y}) {mount.Type} {mount.Shape.Width}x{mount.Shape.Height}: rotation {rotation} [{Takers()}]"); + if (!apply) + { + mount.Rotation = before; + output.WriteLine("\nDry run. Pass \"apply\" to set it."); + return 0; + } + cache.Upsert(hull); + output.WriteLine($"\nSet {hull.Name}'s hardpoint ({x},{y}) rotation in Aetheria.cc"); + return 0; + } +} diff --git a/tools/AetherDb/LoadoutCommitCommand.cs b/tools/AetherDb/LoadoutCommitCommand.cs index 46913b4c5..34c110cb0 100644 --- a/tools/AetherDb/LoadoutCommitCommand.cs +++ b/tools/AetherDb/LoadoutCommitCommand.cs @@ -12,7 +12,7 @@ using GameCult.Caching; // loadout-commit [,,,[@]]... [--group ,...]... [--replace] [--boss-of ] // (aetheria-release, cut loadout-commit; rulings boss-loadouts-agent-authored, catalog-is-a-package-stack): writes one Loadout // record into GameData/Aetheria.cc through Loadouts.Commit, the only writer, and with --boss-of makes it that faction's boss in -// the same commit. Names resolve exactly against the catalog the game boots: ShipModCatalog.ResolveCatalog over the shipped +// the same commit. Names resolve exactly against the catalog the game boots: AetherDb.ComposeBooted over the shipped // file and GameData/Mods, composed into a scratch file that is never committed. So a loadout may name a package's hull, // design or product (one hull product, one design per slot, one product where a slot names one, a rotation by its // ItemRotation name, a faction by Name or ShortName). The loadout is then built once on a throwaway ItemManager with @@ -69,13 +69,12 @@ public static class LoadoutCommitCommand var scratch = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-loadout-commit-" + Guid.NewGuid().ToString("N"))).FullName; try { - var (composed, excluded) = ShipModCatalog.ResolveCatalog(catalogPath, Path.Combine(scratch, "derived.cc"), Path.Combine(root, "GameData", "Mods")); - foreach (var exclusion in excluded) output.WriteLine($"package left out, as at boot: {exclusion}"); + var composed = AetherDb.ComposeBooted(root, scratch); Loadout loadout; CultRecordRef bossOf = default; string summary; - // Disposed before the commit: with no package composed, this is the shipped file itself. + // Disposed before the commit; the commit opens the shipped file alone (it is the one writer, and a composed catalog is derived). using (var cache = AetheriaStores.Open(composed)) { loadout = Build(cache, positional[0], positional[1], positional.Skip(2).ToArray(), groups); @@ -94,6 +93,7 @@ public static class LoadoutCommitCommand (bossOf.IsSet() ? $", boss of {cache.Get(bossOf).Name}" : ""); } + // Shipped file alone, on purpose: the commit writes GameData/Aetheria.cc, never the composed catalog. if (!Loadouts.Commit(catalogPath, loadout, replace, bossOf)) throw new InvalidOperationException("the catalog changed since it was read; nothing was written"); output.WriteLine(summary); diff --git a/tools/AetherDb/MinorPowerFactionsCommand.cs b/tools/AetherDb/MinorPowerFactionsCommand.cs index 9853d07ba..d16a98bc4 100644 --- a/tools/AetherDb/MinorPowerFactionsCommand.cs +++ b/tools/AetherDb/MinorPowerFactionsCommand.cs @@ -48,7 +48,7 @@ public static class MinorPowerFactionsCommand public static int Run(string[] args, string root = null) { var apply = args.Contains("apply"); - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var existing = db.Cache.GetAll().ToArray(); // Refuse before any write: a name or short name held by a faction under another key. diff --git a/tools/AetherDb/PlaceNamesCommand.cs b/tools/AetherDb/PlaceNamesCommand.cs index 0bb0700b9..b45a78e9b 100644 --- a/tools/AetherDb/PlaceNamesCommand.cs +++ b/tools/AetherDb/PlaceNamesCommand.cs @@ -66,7 +66,7 @@ public static class PlaceNamesCommand internal static int Run(string[] args, string root, Row[] table) { var apply = args.Contains("apply"); - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var factions = db.Cache.GetAll().ToArray(); var keyOf = factions.ToDictionary(f => db.Cache.RefOf(f).Key.Value, StringComparer.Ordinal); diff --git a/tools/AetherDb/ProductLinesCommand.cs b/tools/AetherDb/ProductLinesCommand.cs index 2c82d5ebf..442cac59d 100644 --- a/tools/AetherDb/ProductLinesCommand.cs +++ b/tools/AetherDb/ProductLinesCommand.cs @@ -126,7 +126,7 @@ public static class ProductLinesCommand return 1; } - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var designs = db.Cache.GetAll().ToArray(); var factions = db.Cache.GetAll().ToArray(); var products = db.Cache.GetAll().ToArray(); @@ -204,7 +204,7 @@ public static class ProductLinesCommand // so the same command is the first apply and the replay onto a merged catalog. internal static int RunTiers(IReadOnlyList tiers, bool apply, string root) { - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var designs = db.Cache.GetAll().ToArray(); var products = db.Cache.GetAll().ToArray(); diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 2caaaed4b..ecf1dcf5a 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -25,6 +25,15 @@ public static class Program case "census": return Census(); case "station-fit": return StationFit(); case "hardpoint-fit": return HardpointFit(); + case "shield-catalog": + { + var apply = args.Contains("apply"); + using var db = AetherDb.OpenShipped(catalogWritable: apply); + var code = ShieldCatalog.Run(db.Cache, apply, Console.Out); + if (apply) db.Cache.FlushAsync().GetAwaiter().GetResult(); + return code; + } + case "hardpoint-rotation": return HardpointRotationCommand.Run(args.Skip(1).ToArray()); case "loadout": return Loadout(args.Skip(1).ToArray()); case "loadout-commit": return LoadoutCommitCommand.Run(args.Skip(1).ToArray()); case "save": return Save(); @@ -42,7 +51,6 @@ public static class Program case "targeting-catalog-6c": return TargetingCatalog6c(args.Contains("apply")); case "targeting-catalog-6d": return TargetingCatalog6d(args.Contains("apply")); case "ship-authoring": return ShipAuthoringCommands.Run(args.Skip(1).ToArray()); - case "field-kinds": return FieldKindsCatalog(args.Contains("apply")); case "pd-gear": return PdGearCatalog(args.Contains("apply")); case "mine-launcher": return MineLauncherCatalog(args.Contains("apply")); case "smoke-hull": return SmokeHullCatalog(args.Contains("apply")); @@ -59,30 +67,46 @@ public static class Program case "inspection-scanner": return InspectionScannerCatalog(args.Contains("apply")); case "product-lines": return ProductLinesCommand.Run(args.Skip(1).ToArray()); case "minor-power-factions": return MinorPowerFactionsCommand.Run(args.Skip(1).ToArray()); - case "station-reactor-spread": return StationReactorSpreadCommand.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); - case "assembly-from-maker": return AssemblyFromMakerCommand.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); + case "station-reactor-spread": return StationReactorSpreadCommand.Run(AetherDb.OpenShipped(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); + case "assembly-from-maker": return AssemblyFromMakerCommand.Run(AetherDb.OpenShipped(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); case "place-names": Console.OutputEncoding = new System.Text.UTF8Encoding(false); return PlaceNamesCommand.Run(args.Skip(1).ToArray()); case "station-kinds": { var apply = args.Contains("apply"); - using var db = AetherDb.Open(catalogWritable: apply); + // Shipped file alone, on purpose: every form here (the kinds report included) is the dry run of an apply that writes the shipped + // file, so it reads what apply would change; its report is identical over the composed catalog. + using var db = AetherDb.OpenShipped(catalogWritable: apply); int code; if (args.Length > 1 && args[1] == "hull") { if (args.Length != (apply ? 5 : 4)) { Console.WriteLine("station-kinds hull \"\" [apply]"); return 1; } code = StationKindsCatalog.SetHullKind(db.Cache, args[2], args[3], apply, Console.Out); } + else if (args.Length > 1 && args[1] == "facilities") + { + var words = args.Skip(2).Where(a => a != "apply").ToArray(); + if (words.Length < 1) { Console.WriteLine(StationKindsCatalog.FacilitiesUsage); return 1; } + code = StationKindsCatalog.SetFacilityRows(db.Cache, words[0], words.Skip(1).ToArray(), apply, Console.Out); + } else code = StationKindsCatalog.Run(db.Cache, apply, Console.Out); if (apply) db.Cache.FlushAsync().GetAwaiter().GetResult(); return code; } + case "catalog": + { + if (args.Length < 2 || args[1] != "resave") { Console.WriteLine("catalog resave [apply]"); return 1; } + var apply = args.Contains("apply"); + // Shipped file alone, on purpose: a resave restamps GameData/Aetheria.cc itself, so a composed catalog would write the packages into it. + using var db = AetherDb.OpenShipped(catalogWritable: apply); + return CatalogResaveCommand.Run(db.Cache, apply, Console.Out); + } case "economy": return EconomyCommand.Run(args.Skip(1).ToArray(), Console.Out); - case "auto-guns": return AutoGunsCatalog.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); - case "doctrine-catalog": return DoctrineCatalog.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); + case "auto-guns": return AutoGunsCatalog.Run(AetherDb.OpenShipped(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); + case "doctrine-catalog": return DoctrineCatalog.Run(AetherDb.OpenShipped(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); default: - Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], loadout-commit [,,,[@]]... [--group ,...]... [--replace] [--boss-of ], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], range-falloff [apply] [--effective ] [--end ], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply], ship-authoring create|inspect|validate|compose, field-kinds [apply], mine-launcher [apply], smoke-hull [apply], smoke-rounds [apply], roles-backfill [apply], pd-gear [apply], consumables-first-set [apply], launch-suppressor [apply], pirates-faction [apply], verse-grammar [apply], generic-designs [apply], sensor-stat-set [apply], inspection-scanner [apply], minor-power-factions [apply], place-names [apply], product-lines weapons|minor-powers|gear|tiers [apply], doctrine-catalog [apply], auto-guns [apply], assembly-from-maker [apply], station-kinds [hull \"\" ] [apply], economy report|author ... [apply]"); + Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, hardpoint-rotation \"\" , [apply], loadout [seed], loadout-commit [,,,[@]]... [--group ,...]... [--replace] [--boss-of ], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], range-falloff [apply] [--effective ] [--end ], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply], ship-authoring create|inspect|validate|compose, mine-launcher [apply], smoke-hull [apply], smoke-rounds [apply], roles-backfill [apply], pd-gear [apply], consumables-first-set [apply], launch-suppressor [apply], pirates-faction [apply], verse-grammar [apply], generic-designs [apply], sensor-stat-set [apply], inspection-scanner [apply], minor-power-factions [apply], place-names [apply], product-lines weapons|minor-powers|gear|tiers [apply], doctrine-catalog [apply], auto-guns [apply], assembly-from-maker [apply], shield-catalog [apply], station-kinds [hull \"\" | facilities \"\" ,:...] [apply], economy report|prices|author ... [apply]|balance"); return 1; } } @@ -90,7 +114,7 @@ public static class Program // Designs by kind and manufacturer, designs no product sells, and products with authored role quality. private static int Census() { - var db = AetherDb.Open(); + using var db = AetherDb.OpenBooted(); var items = db.Cache.GetAll().ToArray(); var products = db.Cache.GetAll() .OrderBy(p => db.Cache.RefOf(p).Key.Value, StringComparer.Ordinal).ToArray(); @@ -256,6 +280,15 @@ public static class Program ["Heat"] = "injector", ["EnergyUsage"] = "injector", }; + // A shield's emitter sets how much of a hit it turns, the reservoir how much it can take, the regulator how it spends + // and recovers energy. + private static readonly Dictionary ShieldRoles = new Dictionary + { + ["Efficiency"] = "emitter", + ["Capacity"] = "reservoir", + ["EnergyUsage"] = "regulator", ["RefillDuration"] = "regulator", ["RestoreDuration"] = "regulator", + }; + private static readonly Dictionary HullShipRoles = new Dictionary { ["CrossSection"] = "plating", @@ -315,6 +348,7 @@ public static class Program "Radiator" => RadiatorRoles, "Reactor" => ReactorRoles, "Sensors" => SensorRoles, + "Shield" => ShieldRoles, "Thruster" => ThrusterRoles, _ when kind == "Hull/Ship" => HullShipRoles, "Tool" => ToolRolesByDesign.TryGetValue(item.Name, out var byName) ? byName : null, @@ -339,7 +373,7 @@ public static class Program // the operator review table (grouped by item kind) either way. public static int RolesMigrate(bool apply, string root = null) { - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var items = db.Cache.GetAll().ToArray(); var products = db.Cache.GetAll().ToArray(); var changedDesigns = new List<(object Document, CultRecordKey Key)>(); @@ -503,7 +537,7 @@ public static class Program // generation equips hardpoint gear first and only the first of those is guaranteed. private static int StationFit() { - var db = AetherDb.Open(); + using var db = AetherDb.OpenBooted(); var bays = db.Cache.GetAll().ToArray(); var failures = 0; foreach (var hull in db.Cache.GetAll().Where(h => h.HullType == HullType.Station)) @@ -527,24 +561,23 @@ public static class Program return failures; } - // Every hardpoint on every hull, and which designs can fill it: LoadoutGenerator requires a matching - // HardpointType, a shape that fits the hardpoint, and exactly as many cells as the hardpoint has. A - // hardpoint no product can fill is gear the game cannot place. + // Every hardpoint on every hull the game boots (the shipped catalog with GameData/Mods composed in), and which designs + // can fill it. Fit is loose (HardpointData.Takes: a design of the mount's type whose shape lies within the mount's cells, + // at its rotation), so a smaller design serves a larger mount. A hardpoint no product sells a design for is gear the game + // cannot place; the count is UnfillableHardpoints', and so is the exit code. private static int HardpointFit() { - var db = AetherDb.Open(); - var gear = db.Cache.GetAll().ToArray(); + using var db = AetherDb.OpenBooted(); + var designs = db.Cache.GetAll().ToArray(); var sold = SoldDesigns(db.Cache.GetAll()); - var unfillable = 0; - foreach (var hull in db.Cache.GetAll().OrderBy(h => h.HullType).ThenBy(h => h.Name)) + foreach (var hull in db.Cache.GetAll().OrderBy(h => h.HullType).ThenBy(h => h.Name, StringComparer.Ordinal)) { Console.WriteLine($"\n{hull.Name} ({hull.HullType}):"); foreach (var hardpoint in hull.Hardpoints.OrderByDescending(h => h.Shape.Coordinates.Length)) { var cells = hardpoint.Shape.Coordinates.Length; - var matches = gear.Where(hardpoint.Takes).ToArray(); + var matches = designs.Where(hardpoint.Takes).ToArray(); var soldMatches = matches.Where(m => sold.Contains(db.Cache.RefOf(m).Key)).ToArray(); - if (soldMatches.Length == 0) unfillable++; Console.WriteLine($" {hardpoint.Type,-14} {cells,2} cells: {matches.Length} designs match, {soldMatches.Length} sold" + (matches.Length == 0 ? " <- no design of that size" : soldMatches.Length == 0 ? " <- designs exist but no product sells them" : "")); foreach (var match in matches) @@ -552,15 +585,32 @@ public static class Program (sold.Contains(db.Cache.RefOf(match).Key) ? "" : " (unsold)")); } } - Console.WriteLine($"\n{unfillable} hardpoints no product can fill"); - return unfillable; + var unfillable = UnfillableHardpoints(db.Cache); + foreach (var line in unfillable) Console.WriteLine($"unfillable: {line}"); + Console.WriteLine($"\n{unfillable.Count} hardpoints no product can fill"); + return unfillable.Count; + } + + // One line per hull hardpoint no design a product sells Takes, by hull type, then name, then position: the census the + // hardpoint-fit command prints and HardpointFitTests pins, over whatever catalog it is given. + public static IReadOnlyList UnfillableHardpoints(CultCache cache) + { + var sold = SoldDesigns(cache.GetAll()); + var offered = cache.GetAll().Where(design => sold.Contains(cache.RefOf(design).Key)).ToArray(); + return cache.GetAll() + .OrderBy(h => h.HullType).ThenBy(h => h.Name, StringComparer.Ordinal) + .SelectMany(hull => hull.Hardpoints + .Where(hardpoint => !offered.Any(hardpoint.Takes)) + .OrderBy(hardpoint => hardpoint.Position.x).ThenBy(hardpoint => hardpoint.Position.y) + .Select(hardpoint => $"{hull.Name} ({hull.HullType}) {hardpoint.Type} {hardpoint.Shape.Width}x{hardpoint.Shape.Height} at ({hardpoint.Position.x},{hardpoint.Position.y})")) + .ToArray(); } // The parsed shape of the settings asset, for checking where sequence items actually landed. private static int SettingsDump() { var authored = AuthoredSettings.Load(AetherDb.FindRoot()); - authored.Dump("TutorialGenerationSettings", 2); + authored.Dump("CastBackgroundSettings", 2); Console.WriteLine(); authored.Dump("GameplaySettings", 2); return 0; @@ -572,15 +622,10 @@ public static class Program { var authored = AuthoredSettings.Load(AetherDb.FindRoot()); - var tutorial = authored.Read("TutorialGenerationSettings"); - var background = authored.Read("TutorialBackgroundSettings"); + var background = authored.Read("CastBackgroundSettings"); var zones = authored.Read("ZoneSettings"); var gameplay = authored.Read("GameplaySettings"); - Console.WriteLine($"tutorial: protagonist {tutorial.ProtagonistFaction}, antagonist {tutorial.AntagonistFaction}, " + - $"buffer {tutorial.BufferFaction}, quest {tutorial.QuestFaction}, " + - $"neutrals [{string.Join(", ", tutorial.NeutralFactions ?? new string[0])}], " + - $"{tutorial.ZoneCount} zones, link density {tutorial.LinkDensity}"); Console.WriteLine($"background: frequency {background.NoiseFrequency}, amplitude {background.NoiseAmplitude}, " + $"cloud exponent {background.CloudExponent}, density at centre {background.CloudDensity(new float2(.5f)):0.000}"); Console.WriteLine($"zones: sun mass {zones.SunMass}, planet mass {zones.PlanetMass}, satellite passes {zones.SatellitePasses}, " + @@ -600,8 +645,6 @@ public static class Program else if (gameplay.Tiers.Any(t => string.IsNullOrEmpty(t.Name) || t.Quality <= 0)) missing.Add("GameplaySettings.Tiers (a tier parsed without a name or quality)"); if (gameplay.DefaultEntitySettings == null) missing.Add("GameplaySettings.DefaultEntitySettings"); if (gameplay.QualityPriceModifier == null || gameplay.QualityPriceModifier.Maximum <= 0) missing.Add("GameplaySettings.QualityPriceModifier"); - if (tutorial.NeutralFactions == null || tutorial.NeutralFactions.Length != 2) missing.Add($"TutorialGenerationSettings.NeutralFactions (expected 2, got {tutorial.NeutralFactions?.Length ?? 0})"); - if (string.IsNullOrEmpty(tutorial.ProtagonistFaction)) missing.Add("TutorialGenerationSettings.ProtagonistFaction"); Console.WriteLine($"\n{authored.Unplaced.Count} fields in the asset had nowhere to go"); foreach (var field in authored.Unplaced.Take(20)) Console.WriteLine($" {field}"); @@ -620,7 +663,7 @@ public static class Program var clear = new HashSet(args.Select((arg, i) => (arg, i)) .Where(p => p.arg == "clear" && p.i + 1 < args.Length) .Select(p => args[p.i + 1])); - var db = AetherDb.Open(catalogWritable: apply); + var db = AetherDb.OpenShipped(catalogWritable: apply); var changed = new List<(object Document, CultRecordKey Key)>(); var found = 0; @@ -728,7 +771,7 @@ public static class Program // Galaxy.NamePlaces falls back to catalogue designations for a faction without one. private static int Factions() { - var db = AetherDb.Open(); + using var db = AetherDb.OpenBooted(); var products = db.Cache.GetAll().ToArray(); Console.WriteLine($"{"faction",-26} {"short",-13} {"places",-22} {"boss loadout",-14} {"influence",-9} {"doctrine",-10} products"); var broken = 0; @@ -757,16 +800,7 @@ public static class Program return 0; } - AetherDb db; - try - { - db = AetherDb.Open(withRun: true); - } - catch (Exception e) - { - Console.WriteLine($"save does not open: {e.GetType().Name}: {e.Message}"); - return 1; - } + using var db = AetherDb.OpenBooted(withRun: true); var run = db.Cache.GetGlobal(); if (run?.Zones == null) @@ -817,7 +851,7 @@ public static class Program private static int Loadout(string[] args) { var seed = uint.TryParse(args.FirstOrDefault(), out var parsed) ? parsed : 1u; - var db = AetherDb.Open(); + using var db = AetherDb.OpenBooted(); var settings = new GameplaySettings { DefaultEntitySettings = new EntitySettings(), @@ -859,6 +893,26 @@ public static class Program foreach (var line in log.Distinct()) Console.WriteLine($" {line}"); } + // Every station kind each faction can field: the hull it draws and the facilities it carries on its Facility rows (LoadoutGenerator.EquipFacilities). + foreach (var faction in db.Cache.GetAll().OrderBy(f => f.Name, StringComparer.Ordinal)) + foreach (var kind in StationKinds.FieldableKindsOf(db.Cache, faction)) + { + var random = new Random(seed); + var generator = new LoadoutGenerator(ref random, itemManager, null, null, faction, .5f); + var label = $"{faction.Name} / {db.Cache.Get(kind).Name}"; + try + { + var station = EntitySerializer.Unpack(itemManager, null, generator.GenerateStationLoadout(kind)); + var facilities = station.Equipment.Where(item => item.Data.HardpointType == HardpointType.Facility).Select(item => item.Data.Name).ToArray(); + Console.WriteLine($"{label,-48} on {station.HullData.Name}: {(facilities.Length == 0 ? "no Facilities" : string.Join(", ", facilities))}"); + } + catch (Exception e) + { + Console.WriteLine($"{label,-48} THREW {e.GetType().Name}: {e.Message}"); + failures++; + } + } + Console.WriteLine($"\n{failures} hulls failed to generate a loadout (seed {seed}), {targetingGaps} armed hulls generated with no targeting system (fired unaided)"); return failures; } @@ -872,7 +926,7 @@ public static class Program // operator review either way). private static int ShieldMigrate(bool apply) { - var db = AetherDb.Open(catalogWritable: apply); + var db = AetherDb.OpenShipped(catalogWritable: apply); // ShieldData nests inside either host's Behaviors list (GearData: an equipped item with a hardpoint // Shape to size from; ConsumableItemData: a consumable effect with no Shape -- cells reads 0 there, and @@ -970,7 +1024,7 @@ public static class Program // same contract as ShieldMigrate. private static int BrownoutMigrate(bool apply) { - var db = AetherDb.Open(catalogWritable: apply); + var db = AetherDb.OpenShipped(catalogWritable: apply); const float gentleExponent = 1f; // (behaviour type, target performance-stat field, short label) -- one of these is also a request field @@ -1057,7 +1111,7 @@ public static class Program // otherwise. Dry run unless passed "apply", same contract as ShieldMigrate/BrownoutMigrate. private static int FiringArcMigrate(bool apply) { - var db = AetherDb.Open(catalogWritable: apply); + var db = AetherDb.OpenShipped(catalogWritable: apply); var hulls = db.Cache.GetAll().Where(h => h.Name == "Turret").ToArray(); if (hulls.Length == 0) @@ -1110,7 +1164,7 @@ public static class Program // against the catalog and not against names. private static int WeaponAmmo() { - var db = AetherDb.Open(); + using var db = AetherDb.OpenBooted(); Console.WriteLine($"{"weapon",-28} {"behaviour",-20} {"energy",-11} {"mag",5} {"reload",6} ammo"); foreach (var item in db.Cache.GetAll().OrderBy(i => i.Name, StringComparer.Ordinal)) foreach (var w in item.Behaviors.OfType()) @@ -1134,7 +1188,7 @@ public static class Program } var fraction = Option("--effective", .5f); var end = Option("--end", 0f); - var db = AetherDb.Open(catalogWritable: apply); + var db = AetherDb.OpenShipped(catalogWritable: apply); // A record is rewritten only when what it would store differs from what is stored: that is what drops the retired // key 7 from a record the command leaves otherwise unchanged, and what makes a second apply change no byte. var persisted = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(Path.Combine(db.Root, "GameData", "Aetheria.cc"))) @@ -1189,7 +1243,7 @@ public static class Program // Dry run unless passed "apply", same contract as the other *-migrate commands. private static int TargetingCatalog(bool apply) { - var db = AetherDb.Open(catalogWritable: apply); + var db = AetherDb.OpenShipped(catalogWritable: apply); Faction FactionByShortName(string shortName) { @@ -1404,7 +1458,7 @@ public static class Program // Dry run unless passed "apply", same contract as the other *-migrate commands. private static int TargetingCatalog6c(bool apply) { - var db = AetherDb.Open(catalogWritable: apply); + var db = AetherDb.OpenShipped(catalogWritable: apply); Faction FactionByShortName(string shortName) { @@ -1514,7 +1568,7 @@ public static class Program // Dry run unless passed "apply", same contract as the other *-migrate commands. private static int TargetingCatalog6d(bool apply) { - var db = AetherDb.Open(catalogWritable: apply); + var db = AetherDb.OpenShipped(catalogWritable: apply); GearData DesignByName(string name) { @@ -1568,38 +1622,6 @@ public static class Program return 0; } - // Mining Cut 3 (docs/mining-cut-refresh.md): the first field kind. A chunk is detected by reflected light, and - // its reflectivity comes from its belt's kind, so a catalog with no kind leaves every belt dark. This authors - // the one kind Cut 3 needs, "Asteroid"; Cut 7 authors the rest. CrossSection is reflectivity per schematic - // cell of chunk area: 5 sits inside the shipped hulls' 2-15 per cell (Longinus, Djinni), so a mid-size rock - // (3-6 units across, 7-28 cells) reflects like a small ship. Both numbers are for the operator to review. - private static int FieldKindsCatalog(bool apply) - { - var db = AetherDb.Open(catalogWritable: apply); - var kinds = db.Cache.GetAll().ToArray(); - foreach (var kind in kinds) - Console.WriteLine($" {kind.Name,-12} cross-section {kind.CrossSection,5:0.##} per cell, weight {kind.GenerationWeight:0.##}"); - - if (kinds.Any(kind => kind.Name == "Asteroid")) - { - Console.WriteLine("\"Asteroid\" is already authored; nothing to do."); - return 0; - } - - var asteroid = new FieldKindData { Name = "Asteroid", CrossSection = 5f, GenerationWeight = 1f }; - Console.WriteLine($"Adds \"Asteroid\": cross-section {asteroid.CrossSection} per cell, weight {asteroid.GenerationWeight}."); - if (!apply) - { - Console.WriteLine("\nDry run. Pass \"apply\" to author it."); - return 0; - } - - CultRecordRefs.Validate(asteroid); - db.Cache.Commit(batch => batch.Upsert(typeof(FieldKindData), asteroid)); - Console.WriteLine("\nAuthored \"Asteroid\" in Aetheria.cc"); - return 0; - } - // Aetheria release, cut pd-gear (ruling catalog-grows-generic-designs-branded-products): the catalog's first // point-defence class guns. Nothing in data marks a gun as PD (ruling pd-who-engages); these are PD by their // stats: a hose of light rounds, a quick light beam, and a small pellet volley. Each design is a deep copy of a @@ -1607,7 +1629,7 @@ public static class Program // each carries several products, and branding lives in the products alone. Dry run unless passed "apply". private static int PdGearCatalog(bool apply) { - var db = AetherDb.Open(catalogWritable: apply); + var db = AetherDb.OpenShipped(catalogWritable: apply); var weapons = db.Cache.GetAll().ToArray(); var designNames = new[] { "Point Defense Gun", "Point Defense Laser", "Flak Gun" }; @@ -1753,7 +1775,7 @@ public static class Program // "apply"; idempotent, so a second apply writes nothing and a catalog another cut changed is rerun, never merged. internal static int SensorStatSet(bool apply, string root = null) { - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var designs = db.Cache.GetAll().ToArray(); var products = db.Cache.GetAll().ToArray(); Faction MakerOf(FactionProductData p) => db.Cache.Get(p.Manufacturer); @@ -1910,7 +1932,7 @@ public static class Program public static int SmokeHullCatalog(bool apply, string root = null) { const string name = "Smoke Test Hull"; - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); if (db.Cache.GetAll().Any(h => h.Name == name)) { Console.WriteLine($"\"{name}\" is already authored; nothing to do."); @@ -1973,7 +1995,7 @@ public static class Program // (Velocity 150) so a scenario can kill the target while one is in the air. Dry run unless passed "apply". public static int SmokeRoundsCatalog(bool apply, string root = null) { - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var weapons = db.Cache.GetAll().ToArray(); var names = new[] { "Smoke Proximity", "Smoke Delayed", "Smoke Refused", "Smoke Refused Beam", "Smoke Refused Charge" }; var already = names.Count(name => weapons.Any(w => w.Name == name)); @@ -2069,7 +2091,7 @@ public static class Program private static int MineLauncherCatalog(bool apply) { const string name = "Mine Launcher"; - var db = AetherDb.Open(catalogWritable: apply); + var db = AetherDb.OpenShipped(catalogWritable: apply); const float minimumTemperature = 173.15f, maximumTemperature = 473.15f, optimalTemperature = 249.65f, plateauWidth = 36f; if (db.Cache.GetAll().SingleOrDefault(gear => gear.Name == name) is { } authored) { @@ -2198,7 +2220,7 @@ public static class Program public static int RolesBackfill(bool apply, string root = null) { - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var items = db.Cache.GetAll().ToArray(); var products = db.Cache.GetAll().ToArray(); var targets = BackfillDesigns.Select(name => items.Where(i => i.Name == name).ToArray()) @@ -2311,7 +2333,7 @@ public static class Program public static int PiratesFaction(bool apply, string root = null) { - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var existing = db.Cache.GetAll().FirstOrDefault(f => f.Name == "Pirates"); if (existing != null) @@ -2429,7 +2451,7 @@ public static class Program // unless passed "apply". public static int ConsumablesFirstSetCatalog(bool apply, string root = null) { - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var designNames = new[] { "Thruster Overdrive", "Coolant Vent" }; var already = designNames.Count(name => db.Cache.GetAll().Any(c => c.Name == name)); if (already == designNames.Length) @@ -2691,7 +2713,7 @@ public static class Program // shipped product text ending in the authoring note loses it. Dry run unless passed "apply". public static int GenericDesigns(bool apply, string root = null) { - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var designs = db.Cache.GetAll().ToArray(); var products = db.Cache.GetAll().ToArray(); string MakerOf(FactionProductData product) => db.Cache.Get(product.Manufacturer)?.ShortName; @@ -2796,7 +2818,7 @@ public static class Program // unless passed "apply". public static int LaunchSuppressorCatalog(bool apply, string root = null) { - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); var designNames = new[] { "Launch Suppressor", "Launch Baffle" }; var template = db.Cache.GetAll().Single(g => g.Name == "Targeting Computer"); @@ -2930,7 +2952,7 @@ public static class Program // 1x1 tool. Dry run unless passed "apply"; a catalog that is neither untouched nor fully authored is refused. public static int InspectionScannerCatalog(bool apply, string root = null) { - var db = AetherDb.Open(catalogWritable: apply, root: root); + var db = AetherDb.OpenShipped(catalogWritable: apply, root: root); const string designName = "Inspection Scanner"; const string scanArray = "scan array"; var template = db.Cache.GetAll().Single(g => g.Name == "Targeting Computer"); diff --git a/tools/AetherDb/ShieldCatalog.cs b/tools/AetherDb/ShieldCatalog.cs new file mode 100644 index 000000000..f93f30ca7 --- /dev/null +++ b/tools/AetherDb/ShieldCatalog.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using GameCult.Caching; + +// Puts shields on sale (campaign aetheria-release, cut hardpoint-fit-1; rulings catalog-grows-generic-designs-branded-products, +// designs-are-tech-nodes, hardpoint-sizes-are-footprint-palette, gear-ladder-wide-by-rare-inputs): two generic Shield designs, +// a Light Shield Projector (1x1) and a Heavy Shield Projector (2x2), each sold by two makers. Loose fit lets the light one +// serve the starter's 1x1 mount and the heavy one fill the Djinni's and the Nakovalnya's 2x2 mounts. Every stat is one linear +// Quality term on its ShieldRoles role (Min at quality 0, Max at quality 1); prices and stats are starting knobs, sim-tuned later. +// Recipes wait on aetheria-living-world:follow_up:design-bills-of-materials. Every record is keyed by its name, so the same +// apply replays byte-identically at a merge. Dry run unless apply; a catalog that is neither untouched nor fully authored is refused. +public static class ShieldCatalog +{ + public const string Light = "Light Shield Projector"; + public const string Heavy = "Heavy Shield Projector"; + private const string Emitter = "emitter", Reservoir = "reservoir", Regulator = "regulator"; + + private sealed record Design(string Name, string Description, int Size, float Mass, float Durability, int Price, + (float Min, float Max) Efficiency, (float Min, float Max) EnergyUsage, (float Min, float Max) Capacity, + (float Min, float Max) RefillDuration, (float Min, float Max) RestoreDuration); + + private static readonly Design[] Designs = + { + new(Light, "A compact emitter and reservoir that wraps a hull in a field it spends energy to hold. Small enough for any mount.", + 1, 120f, 100f, 3000, (.05f, .15f), (8f, 4f), (60f, 180f), (8f, 4f), (24f, 12f)), + new(Heavy, "A broad-aperture projector with a deep reservoir: it soaks heavy fire, and takes its time coming back when overwhelmed.", + 2, 420f, 250f, 34000, (.05f, .2f), (8f, 3f), (180f, 520f), (12f, 5f), (34f, 16f)), + }; + + private static readonly (string Name, string Design, string Maker, string Description)[] Products = + { + ("Umbrella", Light, "AU", "Shade for one hull: a small field, held steadily, and no one aboard has to think about it."), + ("Awning", Light, "Aya", "Draws out over the bow like cloth on a pole. It will not stop a siege and was never meant to."), + ("Migdal", Heavy, "Megiddo", "The tower the fleet stands behind. Megiddo sells it as a promise and builds it to keep one."), + ("Redoubt", Heavy, "Zhestokost", "A wall of field, thrown up crudely and sold cheaply to those who expect to be shot at."), + }; + + // A record's key is derived from its name: the same table lands the same records every time it is applied. + private static CultRecordKey KeyOf(string name) => + new(new Guid(SHA256.HashData(Encoding.UTF8.GetBytes("shield-catalog:" + name)).AsSpan(0, 16)).ToString("N")); + + private static PerformanceStat Rolled((float Min, float Max) range, string role) => new PerformanceStat + { + Min = range.Min, + Max = range.Max, + Terms = new List { new StatTerm { Source = StatSource.Quality, Exponent = 1f, Role = role } }, + }; + + private static GearData Build(Design row) + { + var design = new GearData + { + Name = row.Name, + Description = row.Description, + Hardpoint = HardpointType.Shield, + Mass = row.Mass, + Price = row.Price, + Durability = row.Durability, + Shape = new Shape(row.Size, row.Size), + // Thermal fields from content-batch-one 4a. + SpecificHeat = 2f, + Conductivity = 4f, + ThermalResilience = 8f, + MinimumTemperature = 173.15f, + MaximumTemperature = 573.15f, + OptimalTemperature = 258.15f, + PlateauWidth = 84f, + Roles = new[] { Emitter, Reservoir, Regulator }.Select(r => new ItemRole { Name = r }).ToList(), + Behaviors = new List + { + new ShieldData + { + Efficiency = Rolled(row.Efficiency, Emitter), + EnergyUsage = Rolled(row.EnergyUsage, Regulator), + Capacity = Rolled(row.Capacity, Reservoir), + RefillDuration = Rolled(row.RefillDuration, Regulator), + RestoreDuration = Rolled(row.RestoreDuration, Regulator), + }, + }, + }; + for (var x = 0; x < row.Size; x++) + for (var y = 0; y < row.Size; y++) + design.Shape.Cells[x, y] = true; + return design; + } + + public static int Run(CultCache cache, bool apply, TextWriter output) + { + Faction Maker(string shortName) => + cache.GetAll().FirstOrDefault(f => f.ShortName == shortName) ?? throw new InvalidOperationException($"No faction with short name \"{shortName}\"."); + foreach (var product in Products) Maker(product.Maker); + + // Authored when every design and product is present under its key; untouched when none is; anything between needs a human. + var keys = Designs.Select(d => KeyOf(d.Name)).Concat(Products.Select(p => KeyOf(p.Name))).ToArray(); + var held = cache.GetAll().Select(d => cache.RefOf(d).Key) + .Concat(cache.GetAll().Select(p => cache.RefOf(p).Key)).ToHashSet(); + var present = keys.Count(held.Contains); + var names = Designs.Select(d => d.Name).Concat(Products.Select(p => p.Name)).ToHashSet(); + var strangers = cache.GetAll().Select(d => d.Name).Concat(cache.GetAll().Select(p => p.Name)) + .Count(names.Contains); + if (present == keys.Length) + { + output.WriteLine("The shield designs are already authored; nothing to do."); + return 0; + } + if (present != 0 || strangers != 0) + throw new InvalidOperationException("The shield designs are partly authored, or their names belong to other items; the catalog needs a human."); + + var designs = Designs.Select(d => (Row: d, Gear: Build(d))).ToArray(); + output.WriteLine("New designs:"); + foreach (var (_, gear) in designs) + { + var data = gear.Behaviors.OfType().Single(); + output.WriteLine($" {gear.Name} {gear.Shape.Width}x{gear.Shape.Height} {gear.Hardpoint} mass {gear.Mass:0.##} price {gear.Price} durability {gear.Durability:0.##} roles [{string.Join(", ", gear.Roles.Select(r => r.Name))}]"); + foreach (var (label, stat) in new[] { ("Efficiency", data.Efficiency), ("EnergyUsage", data.EnergyUsage), ("Capacity", data.Capacity), ("RefillDuration", data.RefillDuration), ("RestoreDuration", data.RestoreDuration) }) + output.WriteLine($" {label} {stat.Min:0.##}-{stat.Max:0.##} ({stat.Terms.Single().Role})"); + } + output.WriteLine("\nNew products:"); + foreach (var (name, design, maker, description) in Products) + { + var (mean, dev) = Program.MakerProfiles[maker]; + output.WriteLine($" {design} -> \"{name}\" by {maker}, mean {mean:0.##} dev {dev:0.##}: {description}"); + } + if (!apply) + { + output.WriteLine($"\nDry run. Pass \"apply\" to author {Designs.Length} designs and {Products.Length} products."); + return 0; + } + + foreach (var (_, gear) in designs) CultRecordRefs.Validate(gear); + // The batch lands onto the file as it is, expecting every key it authors to be absent (ProductLinesCommand's contract). + if (!cache.Commit(batch => + { + foreach (var key in keys) batch.Expect(key, null); + foreach (var (row, gear) in designs) batch.Upsert(typeof(GearData), gear, KeyOf(row.Name)); + foreach (var (name, design, maker, description) in Products) + { + var (mean, dev) = Program.MakerProfiles[maker]; + batch.Upsert(typeof(FactionProductData), new FactionProductData + { + Name = name, + Description = description, + Design = new CultRecordRef(KeyOf(design)), + Manufacturer = cache.RefOf(Maker(maker)), + Roles = new[] { Emitter, Reservoir, Regulator }.Select(r => new ProductRole { Role = r, Mean = mean, StandardDeviation = dev }).ToList(), + }, KeyOf(name)); + } + })) + throw new InvalidOperationException("The catalog changed while the shields were being authored; nothing was written. Run it again."); + output.WriteLine($"\nAuthored {Designs.Length} designs and {Products.Length} products in Aetheria.cc"); + return 0; + } +} diff --git a/tools/AetherDb/ShipAuthoringCommands.cs b/tools/AetherDb/ShipAuthoringCommands.cs index 458ae4038..cc947be96 100644 --- a/tools/AetherDb/ShipAuthoringCommands.cs +++ b/tools/AetherDb/ShipAuthoringCommands.cs @@ -9,7 +9,7 @@ using System.Linq; // Uses the existing database executable; mod authoring does not earn another binary target. public static class ShipAuthoringCommands { - private const string Usage = "ship-authoring create [--like ] | starter --like | regenerate [apply] | inspect | centre | validate | product (--name [--description ] [--not-offered] | --remove) | price | stats [--mass m] [--durability d] [--armor a] [--drag x] [--top-speed v] | compose "; + private const string Usage = "ship-authoring create [--like ] | starter --like | regenerate [apply] | inspect | open | push [apply] (request on stdin) | centre | validate | product (--name [--description ] [--not-offered] | --remove) | price | stats [--mass m] [--durability d] [--armor a] [--drag x] [--top-speed v] | kind | compose "; private static readonly string[] StatFlags = { "--mass", "--durability", "--armor", "--drag", "--top-speed" }; @@ -36,6 +36,9 @@ public static class ShipAuthoringCommands foreach (var product in products) Console.WriteLine($"product {product.Manufacturer.Key.Value}: {product.Name}"); return 0; } + if (args[0] == "open" && args.Length == 2) return ShipAuthoringPush.Open(args[1], Console.Out); + if (args[0] == "push" && (args.Length == 2 || args.Length == 3 && args[2] == "apply")) + return ShipAuthoringPush.Push(args[1], Console.In, args.Length == 3, Console.Out); if (args[0] == "centre" && args.Length == 2) { // The one centre of mass Blender places a ship by: Shape.CenterOfMass in cell coordinates, as "x y". @@ -45,14 +48,8 @@ public static class ShipAuthoringCommands } if (args[0] == "validate" && args.Length == 2) { - // The package's GLB is judged too once it exists (node ids, mesh roles); a draft without one is judged on - // its records alone, and the output says which. var (hull, ship, products) = ShipAuthoringStore.Load(args[1]); - var model = string.IsNullOrWhiteSpace(ship.ModelAsset) ? null - : Path.Combine(Path.GetDirectoryName(Path.GetFullPath(args[1])), ship.ModelAsset); - var judged = model != null && File.Exists(model) ? "records and model" : "records only, no model yet"; - if (judged == "records and model") ShipModCatalog.ReadPackage(args[1]); - else ShipAuthoringStore.ValidateLoaded(hull, ship, products); + var judged = Judge(args[1], hull, ship, products); Console.WriteLine($"{ship.Id}: {hull.Name}, {hull.Hardpoints.Count} hardpoints, {ship.Anchors.Count} anchors, {ship.SchematicLines.Count} lines ({judged})"); return 0; } @@ -64,7 +61,7 @@ public static class ShipAuthoringCommands Directory.CreateDirectory(Path.GetDirectoryName(path)); var ship = new ShipAuthoring { Id = args[2], ModelAsset = "ship.glb", Anchors = new List() }; var hull = args.Length == 6 - ? ShipAuthoringStore.HullLike(ShippedShipHull(args[5]), args[3], ship.Id) + ? ShipAuthoringStore.HullLike(ShippedLikeHull(args[5]), args[3], ship.Id) : new HullData { Name = args[3], @@ -123,15 +120,7 @@ public static class ShipAuthoringCommands // Judged before the file is touched: a refusal leaves it byte-identical. if (!int.TryParse(args[2], NumberStyles.None, CultureInfo.InvariantCulture, out var price)) throw new InvalidOperationException("price must be a non-negative whole number."); - var (hull, ship, _) = ShipAuthoringStore.Load(args[1]); - hull.Price = price; - using (var cache = ShipAuthoringStore.Open(args[1], writable: true)) - { - ShipAuthoringStore.Write(cache, hull, ship); - cache.FlushAsync().Wait(); - } - Console.WriteLine($"{ship.Id}: price {price}."); - return 0; + return Build(args[1], request => request.Hull.Price = price, ship => $"{ship}: price {price}."); } if (args[0] == "stats" && args.Length >= 2) { @@ -147,31 +136,15 @@ public static class ShipAuthoringCommands stats[args[i]] = value; } if (stats.Count == 0) throw new InvalidOperationException("stats: name at least one stat."); - var (hull, ship, _) = ShipAuthoringStore.Load(args[1]); - if (stats.TryGetValue("--top-speed", out var topSpeed)) + // The push core owns the VelocityLimit rules: the one top speed, the add on a hull with none, the refusal of twins. + return Build(args[1], request => { - var limits = (hull.Behaviors ?? new List()).OfType().ToArray(); - if (limits.Length > 1) throw new InvalidOperationException($"{ship.Id}: --top-speed needs at most one VelocityLimit on the hull; it has {limits.Length}."); - // A hull made without --like has none, and this is its only way to get one: validate refuses a ship without a top speed. - if (limits.Length == 0) - { - limits = new[] { new VelocityLimitData() }; - (hull.Behaviors ??= new List()).Add(limits[0]); - } - // A fixed top speed, as every shipped hull authors one (Min equal to Max); its terms are kept. - limits[0].TopSpeed.Min = limits[0].TopSpeed.Max = topSpeed; - } - if (stats.TryGetValue("--mass", out var mass)) hull.Mass = mass; - if (stats.TryGetValue("--durability", out var durability)) hull.Durability = durability; - if (stats.TryGetValue("--armor", out var armor)) hull.Armor = armor; - if (stats.TryGetValue("--drag", out var drag)) hull.Drag = drag; - using (var cache = ShipAuthoringStore.Open(args[1], writable: true)) - { - ShipAuthoringStore.Write(cache, hull, ship); - cache.FlushAsync().Wait(); - } - Console.WriteLine($"{ship.Id}: " + string.Join(", ", stats.Select(stat => string.Create(CultureInfo.InvariantCulture, $"{stat.Key.Substring(2)} {stat.Value:R}"))) + "."); - return 0; + if (stats.TryGetValue("--top-speed", out var topSpeed)) request.Hull.TopSpeed = topSpeed; + if (stats.TryGetValue("--mass", out var mass)) request.Hull.Mass = mass; + if (stats.TryGetValue("--durability", out var durability)) request.Hull.Durability = durability; + if (stats.TryGetValue("--armor", out var armor)) request.Hull.Armor = armor; + if (stats.TryGetValue("--drag", out var drag)) request.Hull.Drag = drag; + }, ship => $"{ship}: " + string.Join(", ", stats.Select(stat => string.Create(CultureInfo.InvariantCulture, $"{stat.Key.Substring(2)} {stat.Value:R}"))) + "."); } if (args[0] == "product" && args.Length >= 4) { @@ -181,32 +154,32 @@ public static class ShipAuthoringCommands var remove = !notOffered && count == 4 && args[3] == "--remove"; var named = count >= 5 && args[3] == "--name" && (count == 5 || count == 7 && args[5] == "--description"); if (!remove && !named) { Console.Error.WriteLine(Usage); return 1; } - var (hull, ship, products) = ShipAuthoringStore.Load(args[1]); - var (makerKey, makerName) = ShippedFaction(args[2]); - if (remove) + var makerName = ""; + return Build(args[1], request => { - if (!products.Any(product => product.Manufacturer.Key.Equals(makerKey))) - throw new InvalidOperationException($"{ship.Id}: the package holds no product by that maker."); - } - else if (string.IsNullOrWhiteSpace(args[4])) - throw new InvalidOperationException("--name: a product needs a name."); - using (var cache = ShipAuthoringStore.Open(args[1], writable: true)) - { - if (remove) ShipAuthoringStore.DeleteProduct(cache, ship.Id, makerKey); - else - ShipAuthoringStore.WriteProduct(cache, ship.Id, new FactionProductData + var (makerKey, name) = ShippedFaction(args[2]); + makerName = name; + if (remove) + { + if (!request.Products.Any(product => product.Maker == makerKey.Value)) + throw new InvalidOperationException($"{request.Ship}: the package holds no product by that maker."); + } + else if (string.IsNullOrWhiteSpace(args[4])) + throw new InvalidOperationException("--name: a product needs a name."); + request.Products.RemoveAll(product => product.Maker == makerKey.Value); + if (!remove) + request.Products.Add(new ShipAuthoringPush.ProductRow { - Name = args[4], - Description = count == 7 ? args[6] : null, - Design = new CultRecordRef(ShipModCatalog.HullKey(ship.Id)), - Manufacturer = new CultRecordRef(makerKey), - Roles = hull.Roles.Select(role => new ProductRole { Role = role.Name }).ToList(), - NotOffered = notOffered + Maker = makerKey.Value, Name = args[4], Description = count == 7 ? args[6] : null, Offered = !notOffered }); - cache.FlushAsync().Wait(); - } - Console.WriteLine($"{ship.Id}: {(remove ? "removed" : "wrote")} the product by {makerName}{(notOffered ? ", not offered" : "")}."); - return 0; + }, ship => $"{ship}: {(remove ? "removed" : "wrote")} the product by {makerName}{(notOffered ? ", not offered" : "")}."); + } + if (args[0] == "kind" && args.Length == 3) + { + // A builder over the push core: the core judges a changed kind by the one kind rule against the shipped catalog + // and refuses it as ': ', and a hull written since the load is stale and left as it was. + var kind = StationKindData.KeyOf(args[2]).Value; + return Build(args[1], request => request.Hull.Kind = kind, ship => $"{ship}: kind {kind}."); } Console.Error.WriteLine(Usage); return 1; @@ -218,26 +191,74 @@ public static class ShipAuthoringCommands } } - // A shipped faction by name or short name, from GameData/Aetheria.cc opened read-only: exactly one, or refused. - private static (CultRecordKey Key, string Name) ShippedFaction(string nameOrShortName) + // price, stats, product and kind are request builders over the push core: each opens the package's request, sets the one + // section it owns, and applies it. A refusal throws (stderr, exit 1, the file untouched); a record written since the open + // is stale (exit 2); success prints the builder's own line. + private static int Build(string path, Action edit, Func success) { - using var catalog = AetherDb.Open().Cache; + ShipAuthoringPush.Request request; + using (var cache = ShipAuthoringStore.Open(path)) request = ShipAuthoringPush.Opened(cache, path); + edit(request); + var result = ShipAuthoringPush.Run(path, request, apply: true, judge: false); + if (result.Outcome == "refused") throw new InvalidOperationException(result.Message); + if (result.Outcome == "stale") + { + Console.Error.WriteLine($"{request.Ship}: the package was written while this ran; run it again."); + return 2; + } + Console.WriteLine(success(request.Ship)); + return 0; + } + + // The judgment validate reports and push reports on its derived records: the package's records, and its GLB too once it + // exists (node ids, mesh roles); a draft without one is judged on its records alone, and the label says which. A package + // with no products and no station kind to judge has no bin and is never offered, so the shipped catalog is opened for none. + // Throws the refusal. + internal static string Judge(string path, HullData hull, ShipAuthoring ship, FactionProductData[] products) + { + var full = Path.GetFullPath(path); + var model = string.IsNullOrWhiteSpace(ship.ModelAsset) ? null : Path.Combine(Path.GetDirectoryName(full), ship.ModelAsset); + var judged = model != null && File.Exists(model) ? "records and model" : "records only, no model yet"; + ShipAuthoringStore.ValidateLoaded(hull, ship, products); + if (judged == "records and model") ShipModCatalog.Bind(hull, ship, products, Path.GetDirectoryName(full), full); + // Shipped file alone, on purpose: a package is judged against the shipped catalog it will be composed over, never against itself. + // Compose's verdict on a package's bins and its offered hull's schematic; the author sees it here, before compose. + using var catalog = products.Length > 0 || hull.HullType == HullType.Station ? AetherDb.OpenShipped().Cache : null; + if (ShipModCatalog.MarketFault(catalog, ship, products) is { } fault) throw new InvalidOperationException(fault); + // A station package names a kind the shipped catalog holds (the rule Compose applies), so Package refuses it before compose does. + if (hull.HullType == HullType.Station && StationKinds.HullKindFault(catalog, hull) is { } kindFault) + throw new InvalidOperationException($"{ship.Id}: {kindFault}"); + return judged; + } + + // A shipped faction by record key, name or short name, from GameData/Aetheria.cc opened read-only: exactly one, or refused. + internal static (CultRecordKey Key, string Name) ShippedFaction(string text) + { + // Shipped file alone, on purpose: this resolves a shipped faction, the one a package names by key. + using var catalog = AetherDb.OpenShipped().Cache; var matches = catalog.GetAll() - .Where(faction => string.Equals(faction.Name, nameOrShortName, StringComparison.Ordinal) || - string.Equals(faction.ShortName, nameOrShortName, StringComparison.Ordinal)).ToArray(); + .Where(faction => string.Equals(faction.Name, text, StringComparison.Ordinal) || + string.Equals(faction.ShortName, text, StringComparison.Ordinal) || + string.Equals(catalog.TryGetHandle(faction).Value.Key.Value, text, StringComparison.Ordinal)).ToArray(); if (matches.Length != 1) throw new InvalidOperationException($": the shipped catalog has {matches.Length} factions with that name or short name; exactly one is required."); return (catalog.TryGetHandle(matches[0]).Value.Key, matches[0].Name); } - // A shipped ship hull by name, from GameData/Aetheria.cc opened read-only. - private static HullData ShippedShipHull(string name) + // A shipped hull by name, from GameData/Aetheria.cc opened read-only, of one of the types allowed. + private static HullData ShippedHull(string name, params HullType[] allowed) { - using var catalog = AetherDb.Open().Cache; + // Shipped file alone, on purpose: --like copies a shipped hull, not a package's. + using var catalog = AetherDb.OpenShipped().Cache; var hull = catalog.GetAll().FirstOrDefault(candidate => candidate.Name == name) ?? throw new InvalidOperationException($"--like: the shipped catalog has no hull named '{name}'."); - if (hull.HullType != HullType.Ship) - throw new InvalidOperationException($"--like: '{name}' is a {hull.HullType} hull, not a ship."); + if (!allowed.Contains(hull.HullType)) + throw new InvalidOperationException($"--like: '{name}' is a {hull.HullType} hull, not a {string.Join(" or ", allowed)}."); return hull; } + + // starter writes a flyable package, so its like hull is a ship; create --like also takes a station (never a turret). + private static HullData ShippedShipHull(string name) => ShippedHull(name, HullType.Ship); + + private static HullData ShippedLikeHull(string name) => ShippedHull(name, HullType.Ship, HullType.Station); } diff --git a/tools/AetherDb/ShipAuthoringPush.cs b/tools/AetherDb/ShipAuthoringPush.cs new file mode 100644 index 000000000..d734d224e --- /dev/null +++ b/tools/AetherDb/ShipAuthoringPush.cs @@ -0,0 +1,613 @@ +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using int2 = CultMath.int2; + +// ship-authoring open and push: one request vocabulary for the hull layout, the visual anchors and the schematic lines. +// open prints a package's authored members as a request; push reads a request, derives the records it implies from the +// stored ones, prints each change, and under `apply` writes the changed records in one commit that expects every record +// still to be the instance it was loaded as. The version token is each record's public StoredAt (every write re-mints +// it), so a record written since open is stale. Dry run is the default (ruling agents-dry-run-human-applies). +public static class ShipAuthoringPush +{ + // A request is open's output and is parsed strictly: an unknown key and a missing key are refused by name. + [JsonObject(MemberSerialization.OptIn)] + internal sealed class Request + { + [JsonProperty("ship", Required = Required.DisallowNull)] public string Ship; + // Checked against the stored HullType, never written. + [JsonProperty("hullType")] public string HullType; + [JsonProperty("versions", Required = Required.DisallowNull)] public Dictionary Versions; + [JsonProperty("layout")] public LayoutSection Layout; + [JsonProperty("visual")] public VisualSection Visual; + [JsonProperty("lines")] public List Lines; + [JsonProperty("hull")] public HullSection Hull; + [JsonProperty("products")] public List Products; + } + + [JsonObject(MemberSerialization.OptIn)] + internal sealed class HullSection + { + [JsonProperty("name", Required = Required.DisallowNull)] public string Name; + [JsonProperty("price", Required = Required.Always)] public int Price; + [JsonProperty("mass", Required = Required.Always)] public float Mass; + [JsonProperty("durability", Required = Required.Always)] public float Durability; + [JsonProperty("armor", Required = Required.Always)] public float Armor; + [JsonProperty("drag", Required = Required.Always)] public float Drag; + [JsonProperty("topSpeed", Required = Required.AllowNull)] public float? TopSpeed; + [JsonProperty("kind", Required = Required.AllowNull)] public string Kind; + } + + [JsonObject(MemberSerialization.OptIn)] + internal sealed class ProductRow + { + [JsonProperty("maker", Required = Required.DisallowNull)] public string Maker; + [JsonProperty("name", Required = Required.DisallowNull)] public string Name; + [JsonProperty("description", Required = Required.AllowNull)] public string Description; + [JsonProperty("offered", Required = Required.Always)] public bool Offered; + } + + [JsonObject(MemberSerialization.OptIn)] + internal sealed class LayoutSection + { + [JsonProperty("grid", Required = Required.DisallowNull)] public string Grid; + [JsonProperty("hardpoints", Required = Required.DisallowNull)] public List Hardpoints; + } + + [JsonObject(MemberSerialization.OptIn)] + internal sealed class HardpointRow + { + [JsonProperty("element", Required = Required.DisallowNull)] public string Element; + [JsonProperty("mount", Required = Required.DisallowNull)] public string Mount; + [JsonProperty("kind", Required = Required.DisallowNull)] public string Kind; + [JsonProperty("cell", Required = Required.DisallowNull)] public int[] Cell; + [JsonProperty("footprint", Required = Required.DisallowNull)] public string Footprint; + [JsonProperty("rotation", Required = Required.Always)] public int Rotation; + [JsonProperty("armor", Required = Required.Always)] public float Armor; + [JsonProperty("arc", Required = Required.Always)] public float Arc; + } + + [JsonObject(MemberSerialization.OptIn)] + internal sealed class VisualSection + { + [JsonProperty("model", Required = Required.DisallowNull)] public string Model; + [JsonProperty("anchors", Required = Required.DisallowNull)] public List Anchors; + } + + [JsonObject(MemberSerialization.OptIn)] + internal sealed class AnchorRow + { + [JsonProperty("id", Required = Required.DisallowNull)] public string Id; + [JsonProperty("role", Required = Required.DisallowNull)] public string Role; + [JsonProperty("node", Required = Required.DisallowNull)] public string Node; + [JsonProperty("parent", Required = Required.AllowNull)] public string Parent; + [JsonProperty("order", Required = Required.Always)] public int Order; + } + + [JsonObject(MemberSerialization.OptIn)] + internal sealed class LineRow + { + [JsonProperty("element", Required = Required.DisallowNull)] public string Element; + [JsonProperty("layer", Required = Required.AllowNull)] public string Layer; + [JsonProperty("material", Required = Required.AllowNull)] public string Material; + [JsonProperty("points", Required = Required.AllowNull)] public float[] Points; + [JsonProperty("radii", Required = Required.AllowNull)] public float[] Radii; + [JsonProperty("opacities", Required = Required.AllowNull)] public float[] Opacities; + [JsonProperty("cyclic", Required = Required.Always)] public bool Cyclic; + [JsonProperty("color", Required = Required.AllowNull)] public float[] Color; + } + + private const int MaxCells = 32; + + private static readonly JsonSerializerSettings Strict = new JsonSerializerSettings + { + MissingMemberHandling = MissingMemberHandling.Error, + DateParseHandling = DateParseHandling.None + }; + + private static MessagePackSerializerOptions PackOptions => CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + + private static byte[] Pack(T value) => MessagePackSerializer.Serialize(value, PackOptions); + + // A deep copy by the type's own MessagePack round trip, as HullLike copies a hull: a member added later is copied too. + internal static T Copy(T value) => MessagePackSerializer.Deserialize(Pack(value), PackOptions); + + // The request that, pushed back unchanged, changes nothing. + public static int Open(string path, TextWriter output) + { + using var cache = ShipAuthoringStore.Open(path); + output.WriteLine(JsonConvert.SerializeObject(Opened(cache, path), Formatting.Indented)); + return 0; + } + + // The package's authored members as a typed request: open prints it, and the builders (stats, price, kind, product) edit + // the one section they own and hand it to Run. + internal static Request Opened(CultCache cache, string path) + { + var (hull, ship, products) = ShipAuthoringStore.Load(cache, path); + return new Request + { + Ship = ship.Id, + HullType = hull.HullType.ToString(), + Versions = Versions(cache, ship.Id), + Layout = new LayoutSection + { + Grid = Footprint(hull.Shape), + Hardpoints = (hull.Hardpoints ?? new List()).Select(hardpoint => new HardpointRow + { + Element = hardpoint.Id ?? "", + Mount = hardpoint.Transform, + Kind = hardpoint.Type.ToString(), + Cell = new[] { hardpoint.Position.x, hardpoint.Position.y }, + Footprint = Footprint(hardpoint.Shape), + Rotation = (int)hardpoint.Rotation, + Armor = hardpoint.Armor, + Arc = hardpoint.FiringArc + }).ToList() + }, + Visual = new VisualSection + { + Model = ship.ModelAsset, + Anchors = (ship.Anchors ?? new List()).Select(anchor => new AnchorRow + { + Id = anchor.Id, Role = anchor.Role, Node = anchor.ModelNodeId, Parent = anchor.ParentId, Order = anchor.Order + }).ToList() + }, + Lines = (ship.SchematicLines ?? new List()).Select(line => new LineRow + { + Element = line.Id ?? "", Layer = line.Layer, Material = line.Material, Points = line.Points, Radii = line.Radii, + Opacities = line.Opacities, Cyclic = line.Cyclic, Color = line.Color + }).ToList(), + Hull = new HullSection + { + Name = hull.Name, Price = hull.Price, Mass = hull.Mass, Durability = hull.Durability, Armor = hull.Armor, + Drag = hull.Drag, TopSpeed = TopSpeed(hull), Kind = KindText(hull) + }, + Products = products.OrderBy(product => product.Manufacturer.Key.Value, StringComparer.Ordinal).Select(product => new ProductRow + { + Maker = product.Manufacturer.Key.Value, Name = product.Name, Description = product.Description, Offered = !product.NotOffered + }).ToList() + }; + } + + // The hull, the ship and every product record the package holds, each by the store's version token. + private static Dictionary Versions(CultCache cache, string shipId) => + new[] { ShipModCatalog.HullKey(shipId), ShipModCatalog.AuthoringKey(shipId) } + .Concat(cache.GetAll().Select(product => cache.TryGetHandle(product).Value.Key)) + .ToDictionary(key => key.Value, key => cache.GetStored(key).StoredAt, StringComparer.Ordinal); + + // The result of a push: what the print shows and the builders read. + internal sealed class Result + { + public string Outcome; + public int Code; + public string Message; + public List Lines = new List(); + public List Changed = new List(); + public List Stale = new List(); + public string Verdict; + public Dictionary Versions; + } + + // Reads a request from stdin and prints what it would change; with apply, writes it. Exit 0 dry run or applied, + // 1 refused (the file is untouched), 2 stale (a record was written since the request's open; nothing is written). + public static int Push(string path, TextReader requestText, bool apply, TextWriter output) + { + Request request; + try + { + request = JsonConvert.DeserializeObject(requestText.ReadToEnd(), Strict); + } + catch (JsonException error) { return Refused(output, "request: " + error.Message); } + if (request == null) return Refused(output, "request: the request is empty."); + var result = Run(path, request, apply); + if (result.Outcome == "refused") return Refused(output, result.Message); + foreach (var line in result.Lines) output.WriteLine(line); + output.WriteLine(JsonConvert.SerializeObject(new Dictionary + { + ["outcome"] = result.Outcome, ["changed"] = result.Changed, ["stale"] = result.Stale, ["verdict"] = result.Verdict, ["versions"] = result.Versions + })); + return result.Code; + } + + // The one core: push and the builders both come here. A refusal leaves the file untouched (Code 1, Message); a stale + // record writes nothing (Code 2). Push judges the derived package (judge); the builders do not. + internal static Result Run(string path, Request request, bool apply, bool judge = true) + { + var result = new Result(); + try + { + using var cache = ShipAuthoringStore.Open(path, writable: apply); + var (hull, ship, products) = ShipAuthoringStore.Load(cache, path); + var hullKey = ShipModCatalog.HullKey(ship.Id); + var shipKey = ShipModCatalog.AuthoringKey(ship.Id); + if (!string.Equals(request.Ship, ship.Id, StringComparison.Ordinal)) + throw new InvalidOperationException($"request: ship is not {ship.Id}; the request was opened from another package."); + if (request.HullType != null && !string.Equals(request.HullType, hull.HullType.ToString(), StringComparison.Ordinal)) + throw new InvalidOperationException($"request: hullType is {request.HullType}; this package's hull is a {hull.HullType}."); + + var lines = result.Lines; + var newHull = Copy(hull); + var newShip = Copy(ship); + if (request.Layout != null) DeriveLayout(request.Layout, hull, newHull, hullKey.Value, lines); + if (request.Visual != null) DeriveVisual(request.Visual, ship, newShip, shipKey.Value, lines); + if (request.Lines != null) DeriveLines(request.Lines, ship, newShip, shipKey.Value, lines); + if (request.Hull != null) DeriveHull(request.Hull, hull, newHull, hullKey.Value, ship.Id, lines); + var productWrites = request.Products != null ? DeriveProducts(request.Products, products, newHull, ship.Id, lines) : new List(); + + var writes = new List(); + if (!Pack(newHull).AsSpan().SequenceEqual(Pack(hull))) writes.Add(new Write(hullKey, typeof(HullData), hull, newHull)); + if (!Pack(newShip).AsSpan().SequenceEqual(Pack(ship))) writes.Add(new Write(shipKey, typeof(ShipAuthoring), ship, newShip)); + writes.AddRange(productWrites); + + var productPrefix = "mod-product:" + ship.Id + ":"; + foreach (var held in request.Versions.Keys) + if (held != hullKey.Value && held != shipKey.Value && !held.StartsWith(productPrefix, StringComparison.Ordinal)) + throw new InvalidOperationException($"request: versions names {held}, which this push does not write; it may name {hullKey.Value}, {shipKey.Value} and {productPrefix}."); + foreach (var write in writes) + if ((write.Key.Equals(hullKey) || write.Key.Equals(shipKey)) && !request.Versions.ContainsKey(write.Key.Value)) + throw new InvalidOperationException($"request: versions has no entry for {write.Key.Value}, which this push writes."); + result.Changed.AddRange(writes.Select(write => write.Key.Value)); + + // The products Judge sees: the stored ones with each product write applied. + var written = productWrites.ToDictionary(write => write.Key.Value, StringComparer.Ordinal); + var judged = products.Where(product => !written.ContainsKey(ShipModCatalog.ProductKey(ship.Id, product.Manufacturer.Key).Value)) + .Concat(productWrites.Where(write => write.Derived != null).Select(write => (FactionProductData)write.Derived)).ToArray(); + // A builder reports its own line and reads no verdict, so a plain stats or price write never opens the shipped catalog. + if (judge) result.Verdict = Verdict(path, newHull, newShip, judged); + + // A record the request carries a version for is expected as that instance; one it carries none for (a product it + // did not open) is expected absent. + bool Stale(Write write) => request.Versions.TryGetValue(write.Key.Value, out var version) + ? write.Held == null || !string.Equals(version, cache.GetStored(write.Key).StoredAt, StringComparison.Ordinal) + : write.Held != null; + var stale = writes.Where(Stale).Select(write => write.Key.Value).ToList(); + if (stale.Count == 0 && apply && writes.Count > 0) + { + var landed = Land(cache, writes); + if (landed) cache.FlushAsync().Wait(); + else stale = writes.Select(write => write.Key.Value).ToList(); + } + result.Stale = stale; + result.Versions = Versions(cache, ship.Id); + result.Code = stale.Count > 0 ? 2 : 0; + result.Outcome = stale.Count > 0 ? "stale" : apply ? "applied" : "dry-run"; + return result; + } + catch (InvalidOperationException error) { return new Result { Outcome = "refused", Code = 1, Message = error.Message }; } + } + + // A record to write: the instance the cache holds (null: the key is absent, an add) and the copy derived from it + // (null: a removal). + internal readonly record struct Write(CultRecordKey Key, Type Type, object Held, object Derived); + + // One commit, every record expected to still be the instance it was loaded as (or absent): a write that lands between the + // load and this commit replaces that instance and is refused here (false), never overwritten. + internal static bool Land(CultCache cache, IReadOnlyList writes) + { + try + { + return cache.Commit(batch => + { + foreach (var write in writes) + { + batch.Expect(write.Key, write.Held); + if (write.Derived == null) batch.Remove(write.Key); + else batch.Upsert(write.Type, write.Derived, write.Key); + } + }); + } + // Expect refuses an instance the cache no longer holds at the key: that write landed after the load. + catch (ArgumentException error) when (error.ParamName == "current") { return false; } + } + + private static string Verdict(string path, HullData hull, ShipAuthoring ship, FactionProductData[] products) + { + try { return "accepted: " + ShipAuthoringCommands.Judge(path, hull, ship, products); } + // The judgment's own refusals, and a model whose JSON chunk does not parse; anything else is a fault and surfaces. + catch (Exception error) when (error is InvalidOperationException or JsonException) { return "refused: " + error.Message; } + } + + private static int Refused(TextWriter output, string message) + { + output.WriteLine(JsonConvert.SerializeObject(new Dictionary { ["outcome"] = "refused", ["message"] = message })); + return 1; + } + + // ---- hull: name, price, stats, top speed, station kind ------------------------------------------------------------ + + // The one VelocityLimit's top speed when the hull has exactly one with a fixed speed (Min equal to Max), else null. + private static float? TopSpeed(HullData hull) + { + var limits = (hull.Behaviors ?? new List()).OfType().ToArray(); + return limits.Length == 1 && limits[0].TopSpeed.Min == limits[0].TopSpeed.Max ? limits[0].TopSpeed.Max : null; + } + + private static string KindText(HullData hull) => hull.Kind.IsSet() ? hull.Kind.Key.Value : null; + + private static void DeriveHull(HullSection section, HullData held, HullData derived, string key, string shipId, List lines) + { + if (section.Price < 0) throw new InvalidOperationException("hull: price must be a whole number of at least 0."); + foreach (var (field, value) in new[] { ("mass", section.Mass), ("durability", section.Durability), ("armor", section.Armor), ("drag", section.Drag) }) + if (!(value >= 0) || float.IsInfinity(value)) throw new InvalidOperationException($"hull: {field} must be finite and at least 0."); + if (string.IsNullOrWhiteSpace(section.Name)) throw new InvalidOperationException("hull: name must not be blank."); + derived.Name = section.Name; + derived.Price = section.Price; + derived.Mass = section.Mass; + derived.Durability = section.Durability; + derived.Armor = section.Armor; + derived.Drag = section.Drag; + if (section.TopSpeed is { } speed) + { + if (!float.IsFinite(speed) || speed < 0) throw new InvalidOperationException("hull: topSpeed must be null, or finite and at least 0."); + var limits = (derived.Behaviors ??= new List()).OfType().ToArray(); + if (limits.Length > 1) throw new InvalidOperationException($"{shipId}: --top-speed needs at most one VelocityLimit on the hull; it has {limits.Length}."); + // A hull made without --like has none, and this is its only way to get one: validate refuses a ship without a top speed. + if (limits.Length == 0) + { + limits = new[] { new VelocityLimitData() }; + derived.Behaviors.Add(limits[0]); + } + // A fixed top speed, as every shipped hull authors one (Min equal to Max); its terms are kept. + limits[0].TopSpeed.Min = limits[0].TopSpeed.Max = speed; + } + derived.Kind = string.IsNullOrEmpty(section.Kind) ? default : new CultRecordRef(new CultRecordKey(section.Kind)); + // A kind is judged whenever the request or the stored hull names one, so an invalid stored kind is never passed as fine; a + // kindless draft that stays kindless is not, so it still takes stats and price (and needs no catalog). + if (derived.Kind.IsSet() || held.Kind.IsSet()) + // Shipped file alone, on purpose: a station kind is the shipped catalog's, the rule Compose applies to a package. + using (var catalog = AetherDb.OpenShipped().Cache) + if (StationKinds.HullKindFault(catalog, derived) is { } fault) throw new InvalidOperationException($"{shipId}: {fault}"); + FlatDiff(lines, key, HullFields(held), HullFields(derived)); + } + + private static (string Field, string Value)[] HullFields(HullData hull) => new[] + { + ("name", hull.Name), ("price", Text(hull.Price)), ("mass", Text(hull.Mass)), ("durability", Text(hull.Durability)), + ("armor", Text(hull.Armor)), ("drag", Text(hull.Drag)), ("topSpeed", TopSpeed(hull) is { } speed ? Text(speed) : null), ("kind", KindText(hull)) + }; + + // ---- products: one FactionProductData per maker ------------------------------------------------------------------ + + private static List DeriveProducts(List request, FactionProductData[] stored, HullData hull, string shipId, List lines) + { + var byMaker = stored.ToDictionary(product => product.Manufacturer.Key.Value, StringComparer.Ordinal); + var seen = new HashSet(StringComparer.Ordinal); + var writes = new List(); + foreach (var row in request) + { + if (string.IsNullOrWhiteSpace(row.Name)) throw new InvalidOperationException($"products: {row.Maker}: a product needs a name."); + // A maker that is a stored product's own key names it; any other is a shipped faction by key, name or short name. + FactionProductData held; + CultRecordKey maker; + if (byMaker.TryGetValue(row.Maker, out held)) maker = held.Manufacturer.Key; + else + { + maker = ShipAuthoringCommands.ShippedFaction(row.Maker).Key; + byMaker.TryGetValue(maker.Value, out held); + } + if (!seen.Add(maker.Value)) throw new InvalidOperationException($"products: maker {row.Maker} names {maker.Value}, which another row names too."); + var key = ShipModCatalog.ProductKey(shipId, maker); + var derived = held != null ? Copy(held) : new FactionProductData + { + Design = new CultRecordRef(ShipModCatalog.HullKey(shipId)), + Manufacturer = new CultRecordRef(maker), + // A hull stored with no roles (Zenith, so a station made --like it) decodes with a null list. + Roles = (hull.Roles ?? new List()).Select(role => new ProductRole { Role = role.Name }).ToList() + }; + derived.Name = row.Name; + derived.Description = row.Description; + derived.NotOffered = !row.Offered; + if (held == null) + { + lines.Add($"{key.Value} added"); + writes.Add(new Write(key, typeof(FactionProductData), null, derived)); + } + else if (!Pack(derived).AsSpan().SequenceEqual(Pack(held))) + { + FlatDiff(lines, key.Value, ProductFields(held), ProductFields(derived)); + writes.Add(new Write(key, typeof(FactionProductData), held, derived)); + } + } + foreach (var gone in stored.Where(product => !seen.Contains(product.Manufacturer.Key.Value))) + { + var key = ShipModCatalog.ProductKey(shipId, gone.Manufacturer.Key); + lines.Add($"{key.Value} removed"); + writes.Add(new Write(key, typeof(FactionProductData), gone, null)); + } + return writes.OrderBy(write => write.Key.Value, StringComparer.Ordinal).ToList(); + } + + private static (string Field, string Value)[] ProductFields(FactionProductData product) => new[] + { + ("name", product.Name), ("description", product.Description), ("offered", product.NotOffered ? "false" : "true") + }; + + private static void FlatDiff(List lines, string key, (string Field, string Value)[] before, (string Field, string Value)[] after) + { + for (var i = 0; i < before.Length; i++) + if (!string.Equals(before[i].Value, after[i].Value, StringComparison.Ordinal)) + lines.Add($"{key} {before[i].Field}: {before[i].Value ?? "null"} -> {after[i].Value ?? "null"}"); + } + + // ---- layout: HullData.Shape and HullData.Hardpoints -------------------------------------------------------------- + + private static void DeriveLayout(LayoutSection layout, HullData held, HullData derived, string key, List lines) + { + var grid = ParseFootprint(layout.Grid, "layout.grid"); + derived.Shape = grid; + var oldGrid = Footprint(held.Shape); + if (Footprint(grid) != oldGrid) lines.Add($"{key} grid: {oldGrid} -> {Footprint(grid)}"); + + var stored = (held.Hardpoints ?? new List()).ToDictionary(hardpoint => hardpoint.Id, StringComparer.Ordinal); + var mounts = new HashSet(StringComparer.Ordinal); + var elements = new HashSet(StringComparer.Ordinal); + var rows = new List(); + foreach (var row in layout.Hardpoints) + { + if (string.IsNullOrWhiteSpace(row.Mount)) throw new InvalidOperationException("layout: every hardpoint needs a mount id."); + if (!mounts.Add(row.Mount)) throw new InvalidOperationException($"layout: mount id {row.Mount} is used twice."); + if (!Enum.GetNames(typeof(HardpointType)).Contains(row.Kind, StringComparer.Ordinal)) + throw new InvalidOperationException($"layout: {row.Mount}: kind {row.Kind} is not a hardpoint type ({string.Join(", ", Enum.GetNames(typeof(HardpointType)))})."); + if (row.Rotation < 0 || row.Rotation > 3) throw new InvalidOperationException($"layout: {row.Mount}: rotation {row.Rotation} is not 0..3."); + if (!(row.Armor >= 0) || float.IsInfinity(row.Armor)) throw new InvalidOperationException($"layout: {row.Mount}: armor must be finite and at least 0."); + if (!(row.Arc >= 0 && row.Arc <= 360)) throw new InvalidOperationException($"layout: {row.Mount}: arc must be finite, 0 to 360."); + if (row.Cell.Length != 2 || row.Cell[0] < 0 || row.Cell[1] < 0) throw new InvalidOperationException($"layout: {row.Mount}: cell is [x, y], whole numbers of at least 0."); + var footprint = ParseFootprint(row.Footprint, $"layout: {row.Mount}: footprint"); + HardpointData target; + if (row.Element == "") + target = new HardpointData(); + else + { + if (!elements.Add(row.Element)) throw new InvalidOperationException($"layout: element {row.Element} is used twice."); + if (!stored.TryGetValue(row.Element, out var found)) + throw new InvalidOperationException($"layout: element {row.Element} is not a hardpoint of this hull."); + target = Copy(found); + } + target.Type = Enum.Parse(row.Kind); + target.Position = new int2(row.Cell[0], row.Cell[1]); + target.Shape = footprint; + target.Transform = row.Mount; + target.Rotation = (ItemRotation)row.Rotation; + target.Armor = row.Armor; + target.FiringArc = row.Arc; + rows.Add(target); + if (row.Element == "") lines.Add($"{key} hardpoint[{row.Mount}] added"); + else Diff(lines, key, "hardpoint", row.Element, HardpointFields(stored[row.Element]), HardpointFields(target)); + } + foreach (var gone in stored.Values.Where(hardpoint => !elements.Contains(hardpoint.Id))) + lines.Add($"{key} hardpoint[{gone.Id}] removed"); + derived.Hardpoints = rows; + } + + private static (string Field, string Value)[] HardpointFields(HardpointData hardpoint) => new[] + { + ("mount", hardpoint.Transform), ("kind", hardpoint.Type.ToString()), + ("cell", Text(hardpoint.Position.x) + "," + Text(hardpoint.Position.y)), ("footprint", Footprint(hardpoint.Shape)), + ("rotation", Text((int)hardpoint.Rotation)), ("armor", Text(hardpoint.Armor)), ("arc", Text(hardpoint.FiringArc)) + }; + + // The footprint text of a shape: rows of # and . joined by /, the top row highest y. + internal static string Footprint(Shape shape) + { + var rows = new string[shape.Height]; + for (var y = 0; y < shape.Height; y++) + rows[shape.Height - 1 - y] = new string(Enumerable.Range(0, shape.Width).Select(x => shape.Cells[x, y] ? '#' : '.').ToArray()); + return string.Join("/", rows); + } + + internal static Shape ParseFootprint(string text, string label) + { + var rows = text.Split('/'); + var width = rows[0].Length; + if (width < 1 || width > MaxCells || rows.Length > MaxCells) + throw new InvalidOperationException($"{label}: must be 1..{MaxCells} cells wide and high."); + if (rows.Any(row => row.Length != width || row.Any(c => c != '#' && c != '.'))) + throw new InvalidOperationException($"{label}: rows of # and . of one width, separated by /."); + if (!rows.Any(row => row.Contains('#'))) throw new InvalidOperationException($"{label}: needs an occupied cell."); + var shape = new Shape(width, rows.Length); + for (var y = 0; y < rows.Length; y++) + for (var x = 0; x < width; x++) + shape.Cells[x, y] = rows[rows.Length - 1 - y][x] == '#'; + return shape; + } + + // ---- visual: ShipAuthoring.ModelAsset and Anchors ---------------------------------------------------------------- + + private static void DeriveVisual(VisualSection visual, ShipAuthoring held, ShipAuthoring derived, string key, List lines) + { + if (held.ModelAsset != visual.Model) lines.Add($"{key} model: {held.ModelAsset} -> {visual.Model}"); + derived.ModelAsset = visual.Model; + var stored = (held.Anchors ?? new List()).ToDictionary(anchor => anchor.Id, StringComparer.Ordinal); + var seen = new HashSet(StringComparer.Ordinal); + var rows = new List(); + foreach (var row in visual.Anchors) + { + if (string.IsNullOrWhiteSpace(row.Id)) throw new InvalidOperationException("visual: every anchor needs an id."); + if (!seen.Add(row.Id)) throw new InvalidOperationException($"visual: anchor id {row.Id} is used twice."); + // Joint is not authored here and is carried by the anchor's identity; so is its element id. + var target = stored.TryGetValue(row.Id, out var found) ? Copy(found) : new ShipAnchor { Id = row.Id, ElementId = row.Id }; + target.Role = row.Role; + target.ModelNodeId = row.Node; + target.ParentId = row.Parent; + target.Order = row.Order; + rows.Add(target); + if (found == null) lines.Add($"{key} anchor[{row.Id}] added"); + else Diff(lines, key, "anchor", row.Id, AnchorFields(found), AnchorFields(target)); + } + foreach (var gone in stored.Keys.Where(id => !seen.Contains(id))) lines.Add($"{key} anchor[{gone}] removed"); + derived.Anchors = rows; + } + + private static (string Field, string Value)[] AnchorFields(ShipAnchor anchor) => new[] + { + ("role", anchor.Role), ("node", anchor.ModelNodeId), ("parent", anchor.ParentId), ("order", Text(anchor.Order)) + }; + + // ---- lines: ShipAuthoring.SchematicLines ------------------------------------------------------------------------- + + private static void DeriveLines(List request, ShipAuthoring held, ShipAuthoring derived, string key, List lines) + { + var stored = (held.SchematicLines ?? new List()).ToDictionary(line => line.Id, StringComparer.Ordinal); + var seen = new HashSet(StringComparer.Ordinal); + var rows = new List(); + foreach (var row in request) + { + ShipPolyline found = null; + if (row.Element != "") + { + if (!seen.Add(row.Element)) throw new InvalidOperationException($"lines: element {row.Element} is used twice."); + if (!stored.TryGetValue(row.Element, out found)) + throw new InvalidOperationException($"lines: element {row.Element} is not a line of this ship."); + } + var target = new ShipPolyline + { + Id = row.Element, Layer = row.Layer, Material = row.Material, Points = row.Points, Radii = row.Radii, + Opacities = row.Opacities, Cyclic = row.Cyclic, Color = row.Color + }; + rows.Add(target); + if (found == null) lines.Add($"{key} line[] added"); + else Diff(lines, key, "line", row.Element, LineFields(found), LineFields(target)); + } + foreach (var gone in stored.Keys.Where(id => !seen.Contains(id))) lines.Add($"{key} line[{gone}] removed"); + derived.SchematicLines = rows; + } + + private static (string Field, string Value)[] LineFields(ShipPolyline line) => new[] + { + ("layer", line.Layer), ("material", line.Material), ("cyclic", line.Cyclic ? "true" : "false"), + ("points", Floats(line.Points)), ("radii", Floats(line.Radii)), ("opacities", Floats(line.Opacities)), ("color", Floats(line.Color)) + }; + + // ---- output ------------------------------------------------------------------------------------------------------ + + private static void Diff(List lines, string key, string member, string element, + (string Field, string Value)[] before, (string Field, string Value)[] after) + { + for (var i = 0; i < before.Length; i++) + if (!string.Equals(before[i].Value, after[i].Value, StringComparison.Ordinal)) + lines.Add($"{key} {member}[{element}] {before[i].Field}: {before[i].Value ?? "null"} -> {after[i].Value ?? "null"}"); + } + + private static string Text(int value) => value.ToString(CultureInfo.InvariantCulture); + + private static string Text(float value) => value.ToString("R", CultureInfo.InvariantCulture); + + // A float list is long; the line says how many values, and the contents when the list is short. + private static string Floats(float[] values) => + values == null ? null : values.Length <= 6 ? "[" + string.Join(",", values.Select(Text)) + "]" : $"{values.Length} values {Digest(values)}"; + + // A cheap content tag so two long lists of equal length differ in the diff; not a revision or a version token. + private static string Digest(float[] values) + { + var hash = 17; + foreach (var value in values) hash = unchecked(hash * 31 + BitConverter.SingleToInt32Bits(value)); + return hash.ToString("x8", CultureInfo.InvariantCulture); + } +} diff --git a/tools/AetherDb/ShipStarterCommand.cs b/tools/AetherDb/ShipStarterCommand.cs index 2a502a1f5..ebb3f4682 100644 --- a/tools/AetherDb/ShipStarterCommand.cs +++ b/tools/AetherDb/ShipStarterCommand.cs @@ -25,6 +25,9 @@ public static class ShipStarterCommand public float3 Position; // Box half-extents; null for an empty node. Scale is the node scale, used by the shield envelope. public float3? Half; + // A directional thruster emitter has one face, the (axis, sign) its exhaust leaves by in the Blender frame; a box with all six + // would fire exhaust both ways along the push. These drives push toward the bow (Reversed), so the exhaust leaves aft, +Y. + public (int Axis, int Sign)? Face; public float3? Scale; } @@ -43,8 +46,8 @@ public static class ShipStarterCommand new Part { Id = "collider", Role = "hull-collider", Half = new float3(3f, 5f, 1f) }, new Part { Id = "shield", Role = "shield", Scale = new float3(4f, 6f, 2.5f) }, new Part { Id = "tractor", Role = "tractor", Position = new float3(0f, -5f, 0f) }, - new Part { Id = "thruster.port", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(0, 0), Size = new int2(2, 1), Position = new float3(2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f) }, - new Part { Id = "thruster.starboard", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(2, 0), Size = new int2(2, 1), Position = new float3(-2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f) }, + new Part { Id = "thruster.port", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(0, 0), Size = new int2(2, 1), Position = new float3(2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f), Face = (1, 1) }, + new Part { Id = "thruster.starboard", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(2, 0), Size = new int2(2, 1), Position = new float3(-2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f), Face = (1, 1) }, new Part { Id = "radiator", Role = "radiator-mesh", Mount = HardpointType.Radiator, Cell = new int2(1, 1), Size = new int2(2, 1), Position = new float3(0f, 2f, 1.1f), Half = new float3(1.5f, .8f, .08f) }, new Part { Id = "gun.port", Role = "weapon-mount", Mount = HardpointType.Energy, Cell = new int2(0, 5), Position = new float3(1.8f, -3f, 1.1f) }, new Part { Id = "gun.port.muzzle", Role = "weapon-muzzle", Parent = "gun.port", Position = new float3(1.8f, -4f, 1.1f) }, @@ -125,8 +128,8 @@ public static class ShipStarterCommand var positions = new List(); var normals = new List(); var indices = new List(); - // Six faces, outward normals, in the Blender frame; Gltf() turns each into glTF's. - foreach (var (axis, sign) in new[] { (0, 1), (0, -1), (1, 1), (1, -1), (2, 1), (2, -1) }) + // Six faces (one for a thruster emitter), outward normals, in the Blender frame; Gltf() turns each into glTF's. + foreach (var (axis, sign) in part.Face != null ? new[] { part.Face.Value } : new[] { (0, 1), (0, -1), (1, 1), (1, -1), (2, 1), (2, -1) }) { var u = (axis + 1) % 3; var v = (axis + 2) % 3; diff --git a/tools/AetherDb/StationKindsCatalog.cs b/tools/AetherDb/StationKindsCatalog.cs index 51d865f57..8a643444b 100644 --- a/tools/AetherDb/StationKindsCatalog.cs +++ b/tools/AetherDb/StationKindsCatalog.cs @@ -1,7 +1,10 @@ using System; using System.IO; +using System.Collections.Generic; +using System.Globalization; using System.Linq; using GameCult.Caching; +using int2 = CultMath.int2; // Authors the catalog's one list of station kinds (aetheria-living-world, cut station-kind-datum) and gives Zenith, the // one station hull in the repo, its ruled kind (ruling zenith-is-a-trade-hub: provisional, one edit here to change). @@ -14,7 +17,7 @@ public static class StationKindsCatalog private static readonly (string id, string name, string description)[] Table = { - ("mining", "Mining Station", "Extracts ore (Rock, New Metals, Gold, Potassium) and Diamond from bodies and belts; consumes tools and food."), + ("mining", "Mining Station", "Extracts ore from belts: Regolith, Nickel-Iron and Troilite in common ground; Magnetite and Pentlandite in carbonaceous rock; Ilmenite and Anorthite in basalt; and only where the ground holds them Sylvite, Orthoclase, Chalcopyrite, Sperrylite, Native Copper, Native Gold, Isoferroplatinum, Uraninite, Brannerite, Monazite, Columbite and Wolframite. Cuts Diamond from deep cores; consumes tools and food."), ("volatiles", "Volatiles Station", "Skims Methane, Ammonia and Water from gas giants and ice; consumes tools."), ("agriculture", "Agriculture Station", "Grows Algae from Water and Potassium; feeds residential."), ("processing", "Processing Station", "Refines ore and volatiles into Metals, Alloys and Compounds."), @@ -102,4 +105,87 @@ public static class StationKindsCatalog output.WriteLine($"\nSet {hull.Name}'s kind in Aetheria.cc"); return 0; } + + public const string FacilitiesUsage = "station-kinds facilities \"\" ,:... [apply]"; + + // Sets a shipped station hull's whole set of Facility rows (ruling station-facilities-on-typed-mounts): the one writer of a + // shipped hull's Facility rows (a package's go through ship-authoring push). A row is ,:, the footprint as + // package_hull.md writes it (rows of # and . joined by /, the top row highest y), the cell its lowest-x, lowest-y cell. The + // rows replace the hull's Facility rows exactly, mount ids Fa.1, Fa.2... in argument order; every other row is kept untouched. + // Refuses a hull that is not a Station, a malformed row, a cell outside the interior and a row over another row. Prints the + // designs that take each Facility row before and after. Rows equal to the hull's write nothing. Dry run unless apply. + public static int SetFacilityRows(CultCache cache, string hullName, string[] rows, bool apply, TextWriter output) + { + var named = cache.GetAll().Where(h => h.Name == hullName).ToArray(); + if (named.Length != 1) + { + output.WriteLine($"The catalog holds {named.Length} hulls named '{hullName}'; exactly one is required."); + return 1; + } + var hull = named[0]; + if (hull.HullType != HullType.Station) + { + output.WriteLine($"Hull '{hull.Name}' is a {hull.HullType}; only a station hull takes facilities."); + return 1; + } + var wanted = new List(); + var claimed = new HashSet<(int, int)>(); + foreach (var other in hull.Hardpoints.Where(row => row.Type != HardpointType.Facility)) + foreach (var cell in other.Shape.Coordinates) claimed.Add((other.Position.x + cell.x, other.Position.y + cell.y)); + foreach (var text in rows) + { + var colon = text.IndexOf(':'); + var at = colon < 0 ? null : text.Substring(0, colon).Split(','); + if (at == null || at.Length != 2 || !int.TryParse(at[0], NumberStyles.None, CultureInfo.InvariantCulture, out var x) || !int.TryParse(at[1], NumberStyles.None, CultureInfo.InvariantCulture, out var y)) + { + output.WriteLine($"'{text}' is not a row: {FacilitiesUsage}"); + return 1; + } + Shape shape; + try { shape = ShipAuthoringPush.ParseFootprint(text.Substring(colon + 1), $"Row '{text}'"); } + catch (InvalidOperationException e) + { + output.WriteLine(e.Message); + return 1; + } + foreach (var cell in shape.Coordinates) + { + var taken = (x + cell.x, y + cell.y); + if (x + cell.x >= hull.Shape.Width || y + cell.y >= hull.Shape.Height || !hull.InteriorCells[new int2(taken.Item1, taken.Item2)]) + { + output.WriteLine($"Row '{text}' puts cell ({taken.Item1},{taken.Item2}) outside {hull.Name}'s interior."); + return 1; + } + if (!claimed.Add(taken)) + { + output.WriteLine($"Row '{text}' overlaps another row at cell ({taken.Item1},{taken.Item2})."); + return 1; + } + } + wanted.Add(new HardpointData { Type = HardpointType.Facility, Position = new int2(x, y), Shape = shape, Transform = "Fa." + (wanted.Count + 1) }); + } + var held = hull.Hardpoints.Where(row => row.Type == HardpointType.Facility).ToArray(); + var designs = cache.GetAll().ToArray(); + string Describe(HardpointData row) => $"{row.Transform} ({row.Position.x},{row.Position.y}) {ShipAuthoringPush.Footprint(row.Shape)} [{string.Join(", ", designs.Where(row.Takes).Select(d => d.Name).OrderBy(n => n, StringComparer.Ordinal))}]"; + foreach (var row in held) output.WriteLine($"{hull.Name} held {Describe(row)}"); + foreach (var row in wanted) output.WriteLine($"{hull.Name} sets {Describe(row)}"); + if (held.Length == 0 && wanted.Count == 0 || held.Length == wanted.Count && held.Zip(wanted, (a, b) => Same(a, b)).All(same => same)) + { + output.WriteLine("No change."); + return 0; + } + if (!apply) + { + output.WriteLine("\nDry run. Pass \"apply\" to set them."); + return 0; + } + hull.Hardpoints = hull.Hardpoints.Where(row => row.Type != HardpointType.Facility).Concat(wanted).ToList(); + cache.Upsert(hull); + output.WriteLine($"\nSet {hull.Name}'s Facility rows in Aetheria.cc"); + return 0; + } + + private static bool Same(HardpointData a, HardpointData b) => + a.Transform == b.Transform && a.Position.x == b.Position.x && a.Position.y == b.Position.y && a.Rotation == b.Rotation && a.Armor == b.Armor + && a.FiringArc == b.FiringArc && ShipAuthoringPush.Footprint(a.Shape) == ShipAuthoringPush.Footprint(b.Shape); } diff --git a/tools/AetherDb/VerseGrammarCommand.cs b/tools/AetherDb/VerseGrammarCommand.cs index 883fe840d..c1ee102c0 100644 --- a/tools/AetherDb/VerseGrammarCommand.cs +++ b/tools/AetherDb/VerseGrammarCommand.cs @@ -52,6 +52,7 @@ public static class VerseGrammarCommand public static int Run(bool apply, string root = null) { + // Shipped file alone, on purpose: the grammar is authored into GameData/Aetheria.cc, and the dry run reads what apply would write. var catalogPath = Path.Combine(root ?? AetherDb.FindRoot(), "GameData", "Aetheria.cc"); using var cache = new CultCache(); cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalogPath, !apply), AetheriaStores.CatalogTypes); diff --git a/tools/blender/aetheria_ships/__init__.py b/tools/blender/aetheria_ships/__init__.py index 821529244..4f5fa25e3 100644 --- a/tools/blender/aetheria_ships/__init__.py +++ b/tools/blender/aetheria_ships/__init__.py @@ -10,6 +10,7 @@ bl_info = { "category": "Object", } +import json import math import shutil import subprocess @@ -23,9 +24,7 @@ import numpy from mathutils import Matrix, Vector from . import hull_grid, hull_source -from .ship_cc import (HARDPOINT_MEMBERS, HARDPOINT_TYPE_NAMES, ROTATION_NAMES, capture_grease_pencil, clear_lines, decode_hardpoint, - encode_hardpoint, layout_revision, read, read_hull_type, read_layout, replace_layout, replace_lines, - product_makers, replace_visual, valid_ship_id) +from .ship_cc import HARDPOINT_TYPE_NAMES, ROTATION_NAMES, capture_grease_pencil, valid_ship_id MODEL_ASSET = "ship.glb" SOURCE = "Source" # child collection: the Tripo mesh, input to Rasterise, never exported @@ -44,6 +43,7 @@ class AETHERIA_PG_cell(bpy.types.PropertyGroup): class AETHERIA_PG_hardpoint(bpy.types.PropertyGroup): mount_id: bpy.props.StringProperty(name="Mount ID") + element: bpy.props.StringProperty() # the stored hardpoint this row is, as open named it; '' for a row made here kind: bpy.props.EnumProperty(name="Type", items=HARDPOINT_TYPES) x: bpy.props.IntProperty(name="X", min=0, max=31) y: bpy.props.IntProperty(name="Y", min=0, max=31) @@ -58,7 +58,7 @@ class AETHERIA_PG_hardpoint(bpy.types.PropertyGroup): class AETHERIA_PG_layout(bpy.types.PropertyGroup): ship_id: bpy.props.StringProperty() ship_cc: bpy.props.StringProperty() - revision: bpy.props.StringProperty() + versions: bpy.props.StringProperty() # open's versions as JSON text: opaque, replaced by an Apply width: bpy.props.IntProperty(default=1) height: bpy.props.IntProperty(default=1) new_width: bpy.props.IntProperty(name="Width", default=1, min=1, max=32) @@ -101,24 +101,26 @@ def _set_cells(state, width, height, cells): def _load_layout(context, collection, path): """Fills the scene's layout buffer from the bound .cc and redraws the Grid; returns (width, height, hardpoints).""" - shape, hardpoints, revision = read_layout(path, _brokkr_cultlib(context)) - width, height, cells = shape + opened = _open(context, path) + layout = opened["layout"] + width, height, cells = _parse_footprint(layout["grid"])[0] + hardpoints = layout["hardpoints"] state = context.scene.aetheria_layout state.ship_id = collection["aetheria.id"] state.ship_cc = path - state.revision = revision + state.versions = json.dumps(opened["versions"]) _set_cells(state, width, height, cells) state.hardpoints.clear() - for raw in hardpoints: - fields = decode_hardpoint(raw) + for row in hardpoints: hp = state.hardpoints.add() - hp.kind = str(fields["Type"]) - hp.x, hp.y = fields["Position"] - hp.footprint = _footprint(fields["Shape"]) - hp.mount_id = fields["Transform"] or "" - hp.rotation = str(fields["Rotation"]) - hp.armor = fields["Armor"] - hp.firing_arc = fields["FiringArc"] + hp.element = row["element"] + hp.kind = str(HARDPOINT_TYPE_NAMES.index(row["kind"])) + hp.x, hp.y = row["cell"] + hp.footprint = row["footprint"] + hp.mount_id = row["mount"] + hp.rotation = str(row["rotation"]) + hp.armor = row["armor"] + hp.firing_arc = row["arc"] _redraw_grid(collection, state) return width, height, len(hardpoints) @@ -144,23 +146,6 @@ def _refuse(operator, exc): return {"CANCELLED"} -class AETHERIA_OT_load_layout(bpy.types.Operator): - bl_idname = "aetheria.load_ship_layout" - bl_label = "Load Ship Layout" - bl_options = {"REGISTER"} - - def execute(self, context): - try: - collection, path = _layout_path(context) - if collection.get("aetheria.pending"): - raise ValueError("Not saved yet; Save Layout creates it") - width, height, count = _load_layout(context, collection, path) - self.report({"INFO"}, f"Loaded {width}x{height} layout and {count} hardpoints") - return {"FINISHED"} - except _EXPECTED as exc: - return _refuse(self, exc) - - class AETHERIA_OT_resize_layout(bpy.types.Operator): bl_idname = "aetheria.resize_ship_layout" bl_label = "Resize Grid" @@ -234,7 +219,7 @@ def _mount_frame(context): collection, path = _layout_path(context) state = context.scene.aetheria_layout if state.ship_id != collection["aetheria.id"] or state.ship_cc != path: - raise ValueError("Load this collection's layout first") + raise ValueError("Open this collection first") root = _ship_root(collection) if root is None: raise ValueError("A mount needs the ship's Ship Root: Rasterise or Build From Hull Source first") @@ -389,33 +374,91 @@ class AETHERIA_OT_remove_mount(bpy.types.Operator): return {"FINISHED"} -def _encode_buffer(state): - """The layout buffer as ship_cc stores it: (shape, hardpoint rows).""" - shape = [state.width, state.height, [cell.occupied for cell in state.cells]] - rows = [encode_hardpoint(Type=int(hp.kind), Position=[hp.x, hp.y], Shape=_parse_footprint(hp.footprint), - Transform=hp.mount_id, Rotation=int(hp.rotation), Armor=hp.armor, FiringArc=hp.firing_arc) - for hp in state.hardpoints] - return shape, rows +def _layout_section(state): + """The layout buffer as a push request's layout section.""" + rows = [] + for hp in state.hardpoints: + _parse_footprint(hp.footprint) # refuses a malformed footprint here, in the buffer's own words + rows.append({"element": hp.element, "mount": hp.mount_id, "kind": HARDPOINT_TYPE_NAMES[int(hp.kind)], + "cell": [hp.x, hp.y], "footprint": hp.footprint, "rotation": int(hp.rotation), + "armor": hp.armor, "arc": hp.firing_arc}) + return {"grid": _footprint([[state.width, state.height, [cell.occupied for cell in state.cells]]]), + "hardpoints": rows} -def _save_layout(context, collection, state): - """The one writer of the .cc layout: writes the layout buffer, creating the file first when the ship is pending. A - failure after the file was created removes what this save made. Returns the hardpoint count.""" +def _request(context, collection): + """The one builder of what a push carries: (path, pending, request) for the collection and the layout buffer. The + buffer must be this ship's; a pending ship's request has no versions (Apply makes them when it creates the file).""" if not collection.get("aetheria.ship_cc"): raise ValueError("The ship collection has no bound .cc path") path = bpy.path.abspath(collection["aetheria.ship_cc"]) ship_id = collection["aetheria.id"] + state = context.scene.aetheria_layout if state.ship_id != ship_id or state.ship_cc != path: - raise ValueError("Load this collection's layout before saving") - cultlib = _brokkr_cultlib(context) - shape, rows = _encode_buffer(state) + raise Refusal("Open this collection first") pending = collection.get("aetheria.pending") + pending = list(pending) if pending else None + if not pending and not state.versions: + raise Refusal("Open this collection first") + versions = {} if pending else json.loads(state.versions) + return path, pending, {"ship": ship_id, "versions": versions, "layout": _layout_section(state)} + + +def _summary(outcome): + """The one line that ends a push's result: AetherDb's outcome and what it carries.""" + kind = outcome["outcome"] + if kind == "refused": + return f"refused: {outcome.get('message', '')}" + if kind == "stale": + return "stale: the .cc changed since it was opened; Open and push again" + count = len(outcome.get("changed", [])) + if kind == "applied": + return f"applied: {count} changed; {outcome.get('verdict', '')}" + return f"{kind}: {count} changed" if count else f"{kind}: nothing would change" + + +def _result_text(outcome): + return "\n".join(outcome.get("lines", []) + [_summary(outcome)]) + + +def _push_ship(context, collection): + """A dry run of the buffer, or for a pending ship the sentence about what Apply will do. Writes only the window + manager's result and reviewed text: nothing undo tracks.""" + path, pending, request = _request(context, collection) + if pending: + text = (f"new: Apply creates the ship like {pending[1]}, then writes " + f"{len(request['layout']['hardpoints'])} hardpoints") + outcome = {"outcome": "new", "lines": [text], "changed": []} + else: + outcome = _push(context, path, request, apply=False) + text = _result_text(outcome) + wm = context.window_manager + wm.aetheria_push_result = text + wm.aetheria_push_reviewed = json.dumps({"ship_cc": path, "pending": pending, "request": request, + "outcome": outcome["outcome"]}, sort_keys=True) + return outcome + + +def _apply(context, collection): + """The one lander of the layout buffer: writes exactly what the last dry run showed, creating the file first when + the ship is pending. A failure after the file was created removes what this made. Returns the hardpoint count.""" + wm = context.window_manager + if not wm.aetheria_push_reviewed: + raise Refusal("Push (dry run) first") + reviewed = json.loads(wm.aetheria_push_reviewed) + path, pending, request = _request(context, collection) + fresh = {"ship_cc": path, "pending": pending, "request": request} + if json.dumps(fresh, sort_keys=True) != json.dumps({key: reviewed[key] for key in fresh}, sort_keys=True): + raise Refusal("The scene changed since the dry run; Push again") + if reviewed["outcome"] not in ("dry-run", "new"): + raise Refusal("The dry run did not pass; Open and Push again") + state = context.scene.aetheria_layout + ship_id = collection["aetheria.id"] folder = Path(path).parent if pending and Path(path).exists(): - raise ValueError("A ship file already exists at the bound path (Ctrl+Z past a first Save leaves it there); " - "use Bind Ship Collection with that ship.cc, then Load Layout") + raise ValueError("A ship file already exists at the bound path (Ctrl+Z past a first Apply leaves it there); " + "choose that ship.cc and Open") made_folder = bool(pending) and not folder.exists() - revision = state.revision try: if pending: code, output = _aetherdb(context, "create", path, ship_id, pending[0], "--like", pending[1], ship_cc=path) @@ -423,50 +466,105 @@ def _save_layout(context, collection, state): print(output) if code != 0: raise RuntimeError("AetherDb refused to create the ship; its message is in the system console") - revision = read_layout(path, cultlib)[2] - revision = replace_layout(path, cultlib, ship_id, revision, shape, rows) + request["versions"] = _open(context, path)["versions"] + outcome = _landed(_push(context, path, request, apply=True)) except Exception: if pending: Path(path).unlink(missing_ok=True) if made_folder: shutil.rmtree(folder, ignore_errors=True) raise - state.revision = revision + state.versions = json.dumps(outcome["versions"]) + # The store minted an element id for every row made here: take them, so the next push names these rows, not new ones. + elements = {row["mount"]: row["element"] for row in _open(context, path)["layout"]["hardpoints"]} + for hp in state.hardpoints: + hp.element = elements[hp.mount_id] if pending: del collection["aetheria.pending"] _redraw_grid(collection, state) - return len(rows) + wm.aetheria_push_reviewed = "" + wm.aetheria_push_result = _result_text(outcome) + return len(request["layout"]["hardpoints"]) -class AETHERIA_OT_save_layout(bpy.types.Operator): - bl_idname = "aetheria.save_ship_layout" - bl_label = "Save Layout to .cc" - bl_options = {"REGISTER"} +class AETHERIA_OT_open_ship(bpy.types.Operator): + bl_idname = "aetheria.open_ship" + bl_label = "Open Ship" + bl_description = ("Read the ship's .cc into the layout buffer. A collection that is not bound yet is bound to the " + "Ship .cc file first") + bl_options = {"REGISTER", "UNDO"} + + collection: bpy.props.StringProperty(name="Collection", default="", maxlen=63, + description="The ship collection's name; empty means the active object's") def execute(self, context): try: - collection, _ = _layout_path(context) - count = _save_layout(context, collection, context.scene.aetheria_layout) - self.report({"INFO"}, f"Saved the layout and {count} hardpoints") + collection = _ship_collection(context, unbound_ok=True, name=self.collection) + if collection.get("aetheria.pending"): + raise Refusal("Not created yet; Apply creates it") + if not _is_ship(collection) or not collection.get("aetheria.ship_cc"): + if not context.scene.aetheria_ship_cc_path: + raise Refusal("Choose the ship's .cc, then Open") + path = bpy.path.abspath(context.scene.aetheria_ship_cc_path) + _bind_collection(collection, path, _open(context, path)["ship"]) + path = bpy.path.abspath(collection["aetheria.ship_cc"]) + width, height, count = _load_layout(context, collection, path) + context.window_manager.aetheria_push_reviewed = "" + context.window_manager.aetheria_push_result = f"opened: {width}x{height}, {count} hardpoints" + self.report({"INFO"}, f"Opened {width}x{height} layout and {count} hardpoints") return {"FINISHED"} except _EXPECTED as exc: return _refuse(self, exc) -def _brokkr_cultlib(context): - brokkr = context.preferences.addons.get("brokkr_bridge") - if brokkr is None: - raise RuntimeError("Enable Brokkr before using Aetheria Ships") - return brokkr.preferences.cultlib_py_src +class AETHERIA_OT_push_ship(bpy.types.Operator): + bl_idname = "aetheria.push_ship" + bl_label = "Push (dry run)" + bl_description = "Show what Apply would change in the ship's .cc; writes nothing" + bl_options = {"REGISTER"} + + collection: bpy.props.StringProperty(name="Collection", default="", maxlen=63, + description="The ship collection's name; empty means the active object's") + + def execute(self, context): + try: + _push_ship(context, _ship_collection(context, name=self.collection)) + return {"FINISHED"} + except _EXPECTED as exc: + return _refuse(self, exc) + + +class AETHERIA_OT_apply_ship(bpy.types.Operator): + bl_idname = "aetheria.apply_ship" + bl_label = "Apply to .cc" + bl_description = "Write to the ship's .cc exactly what the last dry run showed. Only you press this" + bl_options = {"REGISTER"} + + collection: bpy.props.StringProperty(name="Collection", default="", maxlen=63, + description="The ship collection's name; empty means the active object's") + + def execute(self, context): + try: + count = _apply(context, _ship_collection(context, name=self.collection)) + self.report({"INFO"}, f"Applied the layout and {count} hardpoints") + return {"FINISHED"} + except _EXPECTED as exc: + return _refuse(self, exc) def _is_ship(collection): return collection.get("aetheria.asset_kind") == "ship" -def _ship_collection(context, unbound_ok=False): - """The one chooser: the ship collection holding the active object. unbound_ok (Bind, New Ship) also accepts the - active object's only collection when no ship collection holds it.""" +def _ship_collection(context, unbound_ok=False, name=""): + """The one chooser: the ship collection holding the active object. unbound_ok (Open, New Ship) also accepts the + active object's only collection when no ship collection holds it. name (an agent's field) chooses the one collection + of that name instead: a ship collection, or with unbound_ok any.""" + if name: + found = bpy.data.collections.get(name) + if found is None or not (unbound_ok or _is_ship(found)): + raise Refusal("Name a ship collection") + return found obj = context.active_object if obj is None: raise Refusal("Select an object in the ship collection") @@ -481,7 +579,7 @@ def _ship_collection(context, unbound_ok=False): def _bind_collection(collection, path, ship_id, pending=None): """Binds the collection to the ship .cc at path (aetheria.asset_kind, .id and .ship_cc, and .pending = [name, - reference] for a ship whose file the first Save creates), or changes nothing.""" + reference] for a ship whose file the first Apply creates), or changes nothing.""" if collection.get("aetheria.asset_kind") not in (None, "ship"): raise ValueError("The collection has another aetheria.asset_kind") if collection.get("aetheria.id") not in (None, ship_id): @@ -511,25 +609,6 @@ def _bind_collection(collection, path, ship_id, pending=None): raise -class AETHERIA_OT_bind_ship_collection(bpy.types.Operator): - bl_idname = "aetheria.bind_ship_collection" - bl_label = "Bind Ship Collection" - bl_description = "Bind the active collection to one typed ship .cc record" - bl_options = {"REGISTER", "UNDO"} - - def execute(self, context): - try: - if not context.scene.aetheria_ship_cc_path: - raise ValueError("Choose an existing ship authoring .cc file") - path = bpy.path.abspath(context.scene.aetheria_ship_cc_path) - collection = _ship_collection(context, unbound_ok=True) - _bind_collection(collection, path, read(path, _brokkr_cultlib(context)).ship.body[0]) - self.report({"INFO"}, "Bound the ship collection") - return {"FINISHED"} - except _EXPECTED as exc: - return _refuse(self, exc) - - class AETHERIA_OT_capture_ship_lines(bpy.types.Operator): bl_idname = "aetheria.capture_ship_lines" bl_label = "Capture Ship Lines" @@ -542,18 +621,18 @@ class AETHERIA_OT_capture_ship_lines(bpy.types.Operator): if not collection.get("aetheria.ship_cc"): raise ValueError("The ship collection has no bound .cc path") path = bpy.path.abspath(collection["aetheria.ship_cc"]) - cultlib = _brokkr_cultlib(context) - if read(path, cultlib).ship.body[0] != collection["aetheria.id"]: + opened = _open(context, path) + if opened["ship"] != collection["aetheria.id"]: raise ValueError("The bound collection ID does not match its .cc ship ID") - saved_shape, _, _ = read_layout(path, cultlib) root = _ship_root(collection) if root is not None: # the frame Package would write the model in, so the lines match ship.glb - _frame_ship(context, collection, root, path, saved_shape) + _frame_ship(context, collection, root, path, _parse_footprint(opened["layout"]["grid"])[0]) lines = _schematic_lines(context, collection) if lines is None: raise ValueError("No schematic lines were captured; the ship record was not changed") - count = replace_lines(path, cultlib, lines) - self.report({"INFO"}, f"Captured {count} lines") + _landed(_push(context, path, {"ship": opened["ship"], "versions": opened["versions"], + "lines": _line_rows(lines)}, apply=True)) + self.report({"INFO"}, f"Captured {len(lines)} lines") return {"FINISHED"} except _EXPECTED as exc: return _refuse(self, exc) @@ -624,22 +703,69 @@ def _game_folder(context, ship_cc=None): raise ValueError(GAME_FOLDER_REFUSAL) -def _aetherdb(context, *args, ship_cc=None): - """Runs one AetherDb ship-authoring command from the game folder's ModTools; returns its exit code and its output, - stdout then stderr. ship_cc is the bound .cc the game folder is found from when the preference is empty.""" +def _call(context, args, ship_cc=None, stdin=None): + """Runs one AetherDb ship-authoring command from the game folder's ModTools, stdin to its standard input; returns + (exit code, stdout, stderr). ship_cc is the bound .cc the game folder is found from when the preference is empty.""" folder = _game_folder(context, ship_cc) tool = folder / "ModTools" / ("AetherDb.exe" if sys.platform == "win32" else "AetherDb") if not tool.is_file(): raise ValueError(GAME_FOLDER_REFUSAL) try: result = subprocess.run([str(tool), "ship-authoring", *args], cwd=folder, capture_output=True, text=True, - timeout=AETHERDB_TIMEOUT) + input=stdin, timeout=AETHERDB_TIMEOUT) except subprocess.TimeoutExpired: raise RuntimeError("AetherDb did not finish in time") from None except OSError: raise RuntimeError("AetherDb could not be started") from None - lines = (result.stdout + "\n" + result.stderr).splitlines() - return result.returncode, "\n".join(line for line in lines if line.strip()) + return result.returncode, result.stdout, result.stderr + + +def _merged(out, err): + return "\n".join(line for line in (out + "\n" + err).splitlines() if line.strip()) + + +def _aetherdb(context, *args, ship_cc=None): + """Runs one AetherDb ship-authoring command; returns its exit code and its output, stdout then stderr.""" + code, out, err = _call(context, args, ship_cc) + return code, _merged(out, err) + + +def _open(context, path): + """'ship-authoring open' as a dict: the package's authored members and the versions they were read at.""" + code, out, err = _call(context, ("open", path), ship_cc=path) + if code != 0: + print(_merged(out, err)) + raise RuntimeError("AetherDb could not open the ship; its message is in the system console") + return json.loads(out) + + +def _push(context, path, request, apply): + """'ship-authoring push' of a request: its change lines and outcome go to the system console. Returns AetherDb's + outcome dict (outcome, changed, stale, verdict, versions; a refusal has outcome and message) with 'lines', the change + lines before the JSON line, for exit 0, 1 and 2; judging is AetherDb's alone.""" + args = ("push", path, "apply") if apply else ("push", path) + code, out, err = _call(context, args, ship_cc=path, stdin=json.dumps(request)) + shown = _merged(out, err) + if shown: + print(shown) + rows = [line for line in out.splitlines() if line.strip()] + try: + outcome = json.loads(rows[-1]) + except (IndexError, ValueError): + raise RuntimeError("AetherDb printed no outcome; its message is in the system console") from None + if code not in (0, 1, 2) or not isinstance(outcome, dict) or "outcome" not in outcome: + raise RuntimeError("AetherDb did not answer the push; its message is in the system console") + outcome["lines"] = rows[:-1] + return outcome + + +def _landed(outcome): + """The outcome of a push that was to write: stale and refused raise their fixed texts.""" + if outcome["outcome"] == "stale": + raise RuntimeError("The .cc changed since it was opened; Open and try again") + if outcome["outcome"] == "refused": + raise RuntimeError("AetherDb refused the push; its message is in the system console") + return outcome def _layer_collection(layer, collection): @@ -846,7 +972,7 @@ def _frame_inputs(context, collection, state): if root is None: raise ValueError("The ship collection has no Ship Root; run New Ship first") if state.ship_id != collection["aetheria.id"]: - raise ValueError("Load this collection's layout first") + raise ValueError("Open this collection first") _refuse_loose_meshes(context, collection) meshes = _frame_meshes(collection) if not meshes: @@ -1040,7 +1166,7 @@ def _regenerate_anchors(context, collection, root): class AETHERIA_OT_rasterise_hull(bpy.types.Operator): bl_idname = "aetheria.rasterise_hull" bl_label = "Rasterise Hull" - bl_description = "Propose the hull's cells from its top-down silhouette; you edit them afterwards, then Save Layout" + bl_description = "Propose the hull's cells from its top-down silhouette; you edit them afterwards, then Push and Apply" bl_options = {"REGISTER", "UNDO"} def execute(self, context): @@ -1396,7 +1522,7 @@ def _new_ship(context, ship_id, name, reference, length): them nose to -Y, sizes them to length cells, fills the layout buffer and draws the Grid. The meshes keep their data: the placement is the objects' own matrix, so modifiers act as the author saw them and the cells are the ones checked here. Every check and the rasterising come first; after the bind nothing can refuse. Nothing is written to disk: the - first Save creates the file.""" + first Apply creates the file.""" if not valid_ship_id(ship_id): raise ValueError("The ship ID must use lower-case letters, digits, dots, underscores or hyphens, must not end " "in a dot, and must not be a Windows device name") @@ -1404,8 +1530,8 @@ def _new_ship(context, ship_id, name, reference, length): raise ValueError("Give the ship a display name and a reference hull") path = _game_folder(context, bpy.data.filepath or None) / "GameData" / "Mods" / ship_id / "ship.cc" if path.exists(): - raise ValueError("A ship with this ID already exists under GameData/Mods (Ctrl+Z past a first Save leaves it " - "there); use Bind Ship Collection with its ship.cc, then Load Layout, or give the new ship " + raise ValueError("A ship with this ID already exists under GameData/Mods (Ctrl+Z past a first Apply leaves it " + "there); choose its ship.cc and Open, or give the new ship " "another ID") collection = _ship_collection(context, unbound_ok=True) if collection.get("aetheria.id") is not None or _ship_root(collection) is not None: @@ -1442,7 +1568,7 @@ def _new_ship(context, ship_id, name, reference, length): state = context.scene.aetheria_layout state.ship_id = ship_id state.ship_cc = bpy.path.abspath(collection["aetheria.ship_cc"]) - state.revision = "" + state.versions = "" state.hardpoints.clear() _place_grid(collection, state, width, height, cells, origin) @@ -1451,7 +1577,7 @@ class AETHERIA_OT_new_ship(bpy.types.Operator): bl_idname = "aetheria.new_ship" bl_label = "New Ship" bl_description = ("Set the active collection up as a new ship: nose toward -Y, sized to the length, with a drafted " - "grid. Nothing is written until Save Layout") + "grid. Nothing is written until Apply") bl_options = {"REGISTER", "UNDO"} def execute(self, context): @@ -1459,7 +1585,7 @@ class AETHERIA_OT_new_ship(bpy.types.Operator): try: _new_ship(context, scene.aetheria_new_ship_id, scene.aetheria_new_ship_name, scene.aetheria_new_ship_like, scene.aetheria_new_ship_length) - self.report({"INFO"}, "New ship set up; Save Layout creates its file") + self.report({"INFO"}, "New ship set up; Apply creates its file") return {"FINISHED"} except _EXPECTED as exc: return _refuse(self, exc) @@ -1578,7 +1704,7 @@ def _build_hull_source(context, collection): "changed; Build From Hull Source replaces only what it made and nobody touched") addon = context.preferences.addons.get(__package__) executable = addon.preferences.openscad if addon and addon.preferences else DEFAULT_OPENSCAD - hull_type = read_hull_type(bpy.path.abspath(collection["aetheria.ship_cc"]), _brokkr_cultlib(context)) + hull_type = _open(context, bpy.path.abspath(collection["aetheria.ship_cc"]))["hullType"] hull = hull_source.build(hull_source.openscad_runner(executable, source), hull_source.language_library(executable), hull_type, hull_source.openscad_projector(executable)) broken = hull.failed() @@ -1665,6 +1791,14 @@ def _schematic_lines(context, collection): return rows +def _line_rows(lines): + """_schematic_lines rows [layer, material, points, radii, opacities, cyclic, color] as a push request's line rows; + every row is new (element '').""" + return [{"element": "", "layer": layer, "material": material, "points": points, "radii": radii, + "opacities": opacities, "cyclic": cyclic, "color": color} + for layer, material, points, radii, opacities, cyclic, color in lines] + + def _hull_state(collection): """The one owner of a ship collection's hull state (map HS), decided in this order: an untouched Build zone mesh keeps the hull agent's; her meshes beside Build's record or hull.scad make it art; then Build's record is agent, @@ -1698,7 +1832,7 @@ def _retire_hull_source(collection): return True -def _refuse_wrong_maker(collection, path, cultlib): +def _refuse_wrong_maker(collection, opened): """Refuses, before Package writes anything, a hull in the agent state unless the package holds a product and every product is by the maker of the language Build judged the hull against (ruling hull-faction-is-product-maker), and refuses an unbuilt hull.scad. _hull_state is the owner of which state this is; this function reads neither hull.scad @@ -1712,7 +1846,7 @@ def _refuse_wrong_maker(collection, path, cultlib): maker = collection.get(HULL_MAKER) if maker is None: raise ValueError("Build From Hull Source first: Package needs the maker it judged the hull against") - makers = product_makers(path, cultlib) + makers = [row["maker"] for row in opened["products"]] if not makers: raise ValueError("The package has no product: add one for the hull's maker before packaging") if any(product != maker for product in makers): @@ -1750,40 +1884,39 @@ class AETHERIA_OT_package_ship(bpy.types.Operator): try: collection, path = _layout_path(context) if collection.get("aetheria.pending"): - raise ValueError("Save Layout first") + raise ValueError("Apply first") _refuse_loose_meshes(context, collection) _refuse_shared_ids(context, collection) - cultlib = _brokkr_cultlib(context) - _refuse_wrong_maker(collection, path, cultlib) + opened = _open(context, path) + _refuse_wrong_maker(collection, opened) ship_id = collection["aetheria.id"] state = scene.aetheria_layout - saved_shape, saved_rows, _ = read_layout(path, cultlib) if state.ship_id == ship_id and state.ship_cc == path: - shape, rows = _encode_buffer(state) - if layout_revision(shape, rows) != layout_revision( - saved_shape, [row[:len(HARDPOINT_MEMBERS)] for row in saved_rows]): - raise ValueError("Save Layout first") - if read(path, cultlib).ship.body[0] != ship_id: + gate = _landed(_push(context, path, dict(_request(context, collection)[2], versions=opened["versions"]), + apply=False)) + if gate["changed"]: + raise ValueError("Apply first") + if opened["ship"] != ship_id: raise ValueError("The bound collection ID does not match its .cc ship ID") root = _ship_root(collection) if root is not None: - _frame_ship(context, collection, root, path, saved_shape) + _frame_ship(context, collection, root, path, _parse_footprint(opened["layout"]["grid"])[0]) anchors = _anchors(collection) _export_glb(context, collection, str(Path(path).with_name(MODEL_ASSET))) - replace_visual(path, cultlib, ship_id, MODEL_ASSET, anchors) + request = {"ship": opened["ship"], "versions": opened["versions"], + "visual": {"model": MODEL_ASSET, "anchors": [ + {"id": a[0], "role": a[1], "node": a[2], "parent": a[3], "order": a[4]} for a in anchors]}} lines = _schematic_lines(context, collection) if lines is not None: - replace_lines(path, cultlib, lines) + request["lines"] = _line_rows(lines) elif _hull_state(collection) == HULL_ART: # the lines in the slot are the retired hull's, not hers - clear_lines(path, cultlib) - code, message = _aetherdb(context, "validate", path, ship_cc=path) + request["lines"] = [] + outcome = _landed(_push(context, path, request, apply=True)) except _EXPECTED as exc: scene.aetheria_package_report = f"Package failed: {_failure_text(exc)}" self.report({"ERROR"}, scene.aetheria_package_report) return {"CANCELLED"} - if message: - print(message) - if code != 0: + if not outcome["verdict"].startswith("accepted"): scene.aetheria_package_report = (f"Packaged {len(anchors)} anchors; the validator refused the ship; " "its message is in the system console") self.report({"ERROR"}, scene.aetheria_package_report) @@ -1811,7 +1944,6 @@ class AETHERIA_PT_ship(bpy.types.Panel): new.prop(context.scene, prop) new.operator("aetheria.new_ship", icon="ADD") layout.prop(context.scene, "aetheria_ship_cc_path") - layout.operator("aetheria.bind_ship_collection", icon="LINKED") layout.prop(context.scene, "aetheria_capture_evaluated_lines") obj = context.active_object layout.label(text=f"Source: {obj.name if obj else '(none)'}") @@ -1820,7 +1952,7 @@ class AETHERIA_PT_ship(bpy.types.Panel): collection = _ship_collection(context) layout.label(text=f"Ship: {collection['aetheria.id']}") if collection.get("aetheria.pending"): - layout.label(text="Not saved yet: Save Layout creates the file", icon="INFO") + layout.label(text="Not created yet: Apply creates the file", icon="INFO") elif (collection.get("aetheria.grid_origin") is not None and state.ship_id == collection["aetheria.id"] and not _grid_current(collection, state)): layout.label(text="Rasterise again: the grid no longer matches the layout", icon="INFO") @@ -1830,7 +1962,7 @@ class AETHERIA_PT_ship(bpy.types.Panel): layout.separator() row = layout.row(align=True) - row.operator("aetheria.load_ship_layout", icon="IMPORT") + row.operator("aetheria.open_ship", icon="IMPORT") row.operator("aetheria.flip_nose", icon="LOOP_BACK") row.operator("aetheria.rasterise_hull", icon="MESH_GRID") layout.operator("aetheria.bake_from_source", icon="RENDER_RESULT") @@ -1884,12 +2016,23 @@ class AETHERIA_PT_ship(bpy.types.Panel): mount_box.operator("aetheria.add_ship_muzzle", icon="ADD") mount_box.operator("aetheria.mirror_ship_mount", icon="MOD_MIRROR") mount_box.operator("aetheria.remove_ship_mount", icon="X") - layout.operator("aetheria.save_ship_layout", icon="FILE_TICK") self._draw_package(context, layout) @staticmethod def _draw_package(context, layout): layout.separator() + if context.scene.aetheria_layout.ship_id: + layout.operator("aetheria.push_ship", icon="VIEWZOOM") + row = layout.row() + row.enabled = bool(context.window_manager.aetheria_push_reviewed) + row.operator("aetheria.apply_ship", icon="FILE_TICK") + lines = context.window_manager.aetheria_push_result.splitlines() + if lines: + box = layout.box() + for line in lines[:40]: + box.label(text=line) + if len(lines) > 40: + box.label(text=f"... {len(lines) - 40} more") layout.operator("aetheria.package_ship", icon="PACKAGE") obj = context.active_object if obj is not None and "aetheria.role" in obj: @@ -1908,10 +2051,10 @@ class AETHERIA_PT_ship(bpy.types.Panel): classes = (AETHERIA_PG_cell, AETHERIA_PG_hardpoint, AETHERIA_PG_layout, - AETHERIA_OT_load_layout, AETHERIA_OT_resize_layout, + AETHERIA_OT_open_ship, AETHERIA_OT_push_ship, AETHERIA_OT_apply_ship, + AETHERIA_OT_resize_layout, AETHERIA_OT_add_hardpoint, AETHERIA_OT_remove_hardpoint, AETHERIA_OT_add_weapon, AETHERIA_OT_add_muzzle, AETHERIA_OT_mirror_mount, AETHERIA_OT_remove_mount, - AETHERIA_OT_save_layout, AETHERIA_OT_bind_ship_collection, AETHERIA_OT_capture_ship_lines, AETHERIA_OT_new_ship, AETHERIA_OT_flip_nose, AETHERIA_OT_bake_from_source, AETHERIA_OT_rasterise_hull, AETHERIA_OT_build_hull_source, AETHERIA_OT_package_ship, @@ -1933,6 +2076,10 @@ def register(): bpy.types.Scene.aetheria_new_ship_length = bpy.props.IntProperty( name="Length (cells)", default=10, min=1, max=hull_grid.MAX_CELLS, description="Cells from stern to nose; the hull's long axis becomes this many 2 m cells") + bpy.types.WindowManager.aetheria_push_result = bpy.props.StringProperty( + name="Push result", description="AetherDb's change lines and outcome of the last Push, Apply or Open; display only") + bpy.types.WindowManager.aetheria_push_reviewed = bpy.props.StringProperty( + name="Reviewed push", description="The last dry run's request, which Apply compares the scene against") bpy.types.Scene.aetheria_package_report = bpy.props.StringProperty( name="Package report", description="AetherDb's verdict on the last Package Ship") bpy.types.Scene.aetheria_capture_evaluated_lines = bpy.props.BoolProperty( @@ -1951,5 +2098,7 @@ def unregister(): del bpy.types.Scene.aetheria_new_ship_name del bpy.types.Scene.aetheria_new_ship_id del bpy.types.Scene.aetheria_package_report + del bpy.types.WindowManager.aetheria_push_reviewed + del bpy.types.WindowManager.aetheria_push_result del bpy.types.Scene.aetheria_ship_cc_path diff --git a/tools/blender/aetheria_ships/brokkr_actions.json b/tools/blender/aetheria_ships/brokkr_actions.json new file mode 100644 index 000000000..8bc304a54 --- /dev/null +++ b/tools/blender/aetheria_ships/brokkr_actions.json @@ -0,0 +1,24 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "aetheria.open_ship", + "doc": "Read the ship's .cc into the layout buffer (binds the collection from the Ship .cc field when it is not bound yet). Replaces the buffer; one undo step.", + "changesScene": true, + "editModeSafe": false, + "fields": [ + {"name": "collection", "type": "string", "default": "", "maxLength": 63, "doc": "the ship collection's name; empty means the active object's collection"} + ] + }, + { + "name": "aetheria.push_ship", + "doc": "Dry-run the layout buffer against the ship's .cc: the result lists the changes Apply would write. Writes nothing.", + "changesScene": false, + "editModeSafe": true, + "result": "aetheria_push_result", + "fields": [ + {"name": "collection", "type": "string", "default": "", "maxLength": 63, "doc": "the ship collection's name; empty means the active object's collection"} + ] + } + ] +} diff --git a/tools/blender/aetheria_ships/hull_source.py b/tools/blender/aetheria_ships/hull_source.py index 2d6d0ca16..4c7771e94 100644 --- a/tools/blender/aetheria_ships/hull_source.py +++ b/tools/blender/aetheria_ships/hull_source.py @@ -14,7 +14,8 @@ with it (a hull that redefines or shadows an included language fails a check): lines ECHO line = [layer, cyclic, [[x, y, z], ...]] one line per kit part that draws one, points in the Ship Root frame (lowpoly.scad lp_line under lp_at frames); layer is one of KIT_LAYERS the zone's geometry, OFF; a donor's zone is named ":" - emit:, rad: the mesh of a thruster-emitter or radiator-mesh anchor + emit:, rad: the mesh of a thruster-emitter or radiator-mesh anchor; build() keeps of an emitter only the triangles + that face its exhaust (exhaust_face), so a closed box an author draws becomes its one exhaust-facing side marks OFF, a tiny cube at the first point of each kit line, drawn through the frame the geometry is drawn in (lp_line) Frame: Ship Root, metres, nose -Y, starboard -X, up +Z. build() also takes the hull's HullData.HullType ("Ship", @@ -183,6 +184,28 @@ def parse_off(text): return Mesh(vertices, tuple(triangles)) +def exhaust_face(mesh, yaw): + """The part of a thruster emitter's mesh that faces its exhaust, which leaves the way the anchor faces (its yaw: 0 the nose, + -Y; 90 port, +X): the triangles whose outward normal lies within 60 degrees of it, with the vertices they use. The + exhaust of a thruster is born along each triangle's normal of this mesh, so an emitter with a triangle facing the + other way fires along the push too: a directional thruster's emitter is one-sided. The hull source draws the surface + in whatever solid is convenient (a thin box); the closed sides drop here, and a mesh with no side facing the exhaust + is left empty, which the emitter-has-a-mesh check refuses. A future ring thruster, whose exhaust leaves radially, is a + different emitter with its own rule and does not come through here.""" + facing = (math.sin(math.radians(yaw)), -math.cos(math.radians(yaw))) + kept = [] + for a, b, c in mesh.triangles: + pa, pb, pc = mesh.vertices[a], mesh.vertices[b], mesh.vertices[c] + u, v = [pb[i] - pa[i] for i in range(3)], [pc[i] - pa[i] for i in range(3)] + normal = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) + length = math.sqrt(sum(n * n for n in normal)) + if length > 0 and (normal[0] * facing[0] + normal[1] * facing[1]) / length > 0.5: + kept.append((a, b, c)) + used = sorted({i for tri in kept for i in tri}) + renumber = {old: new for new, old in enumerate(used)} + return Mesh(tuple(mesh.vertices[i] for i in used), tuple(tuple(renumber[i] for i in tri) for tri in kept)) + + def parse_echoes(text, name): """The values of every 'ECHO: = ' line. OpenSCAD prints JSON-compatible values.""" values = [] @@ -439,6 +462,13 @@ def build(runner, library, hull_type, projector): if len(set(ids)) != len(ids) or any(a.role not in ANCHOR_ROLES for a in anchors): raise HullSourceError("The hull source's anchors repeat an id or name a role a hull source does not make") anchor_meshes = {a.id: parse_off(runner(MESH_ROLES[a.role] + a.id)[0]) for a in anchors if a.role in MESH_ROLES} + for a in anchors: + if a.role == "thruster-emitter": + # The hardpoint Rotation the catalog gate judges the emitter against is one of four directions, so the one authority + # for which way an emitter faces is a quarter turn; a source that turns one otherwise is refused here, not rounded. + if abs(a.yaw / 90 - round(a.yaw / 90)) > 1e-6: + raise HullSourceError("The hull source turns a thruster emitter by something other than a quarter turn") + anchor_meshes[a.id] = exhaust_face(anchor_meshes[a.id], a.yaw) kit_lines = read_lines(runner("lines")[1]) judge = donor or own body_zone = f"{donor.faction}:{donor.body}" if donor else own.body diff --git a/tools/blender/aetheria_ships/ship_cc.py b/tools/blender/aetheria_ships/ship_cc.py index b7dca307c..11ec7a9d3 100644 --- a/tools/blender/aetheria_ships/ship_cc.py +++ b/tools/blender/aetheria_ships/ship_cc.py @@ -1,56 +1,16 @@ -"""Aetheria's Blender-side view of one ship file: a typed HullData record and the ShipAuthoring visual it names. - -The schemas and authority live in Aetheria's C# HullData and ShipAuthoring types. This module edits the hull's grid -and hardpoints and the visual's lines, and preserves the C# schema catalog and every slot it does not edit. The file -also holds the hull's products (FactionProductData records), which C# owns: every push here leaves them untouched. Brokkr -supplies the Blender host and CultLib Python dependency path. +"""Aetheria ship vocabulary the Blender add-on shares with its tools: the ship id rule, the enum member names, and Grease +Pencil capture. The ship.cc record and its schemas belong to AetherDb ('ship-authoring open' and 'push'); nothing here +reads or writes the file. ShipSchemaPinTests in tests/Aetheria.Shared.Tests pins the ship id rule and the enum names to +the C# types. """ from __future__ import annotations -import sys -import hashlib -import tomllib -from dataclasses import replace -from datetime import datetime, timezone -from pathlib import Path -from typing import Any, NamedTuple +from typing import Any -if __package__: - from . import hull_grid -else: # loaded by path (tests, hull_source loaded by path): load the sibling the same way - import importlib.util - _grid_spec = importlib.util.spec_from_file_location("hull_grid", Path(__file__).with_name("hull_grid.py")) - hull_grid = importlib.util.module_from_spec(_grid_spec) - _grid_spec.loader.exec_module(hull_grid) - -# The cultcache-py this module's raw envelope writes were tested against. cultcache_py has no __version__ and is loaded -# from source, so the guard reads [project].version of the checkout the imported module itself came from. -TESTED_CULTCACHE_PY = "0.3.0" - -SCHEMA = "aetheria.ship_authoring" -HULL_SCHEMA = "aetheria.hulldata" -PRODUCT_SCHEMA = "aetheria.factionproductdata" -PRODUCT_MANUFACTURER_SLOT = 4 # FactionProductData.Manufacturer - -# MessagePack slots of the C# types, which own them (ShipAuthoring, ItemData.Shape, HullData.Hardpoints, -# HardpointData). RETIRED_HULL_SLOT is the ShipAuthoring key that held the embedded hull before S1; no member owns it now. ShipSchemaPinTests in tests/Aetheria.Shared.Tests fails when any number or name below -# disagrees with those types' [Key] attributes, so a renumbered or added member cannot drift silently. -RETIRED_HULL_SLOT = 1 -MODEL_ASSET_SLOT = 2 # ShipAuthoring.ModelAsset -ANCHORS_SLOT = 3 # ShipAuthoring.Anchors -SCHEMATIC_LINES_SLOT = 4 # ShipAuthoring.SchematicLines -HULL_SHAPE_SLOT = 5 # ItemData.Shape -HULL_HARDPOINTS_SLOT = 23 # HullData.Hardpoints -HULL_TYPE_SLOT = 25 # HullData.HullType -# HardpointData member names in slot order; a hardpoint row is one value per name, and any slot past the last -# name belongs to a later schema and is carried through untouched. -HARDPOINT_MEMBERS = ("Type", "Position", "Shape", "Transform", "Rotation", "Armor", "FiringArc") -# ShipAnchor member names in slot order; as for hardpoints, slots past the last name are carried through by anchor Id. -ANCHOR_MEMBERS = ("Id", "Role", "ModelNodeId", "ParentId", "Order") # Enum member names in value order (HardpointType, ItemRotation, HullType). HARDPOINT_TYPE_NAMES = ("Hull", "Tool", "Thermal", "Thruster", "WarpDrive", "Reactor", "Radiator", - "Shield", "Sensors", "Energy", "Ballistic", "Launcher", "ControlModule") + "Shield", "Sensors", "Energy", "Ballistic", "Launcher", "ControlModule", "Facility") ROTATION_NAMES = ("None", "CounterClockwise", "Reversed", "Clockwise") HULL_TYPE_NAMES = ("Ship", "Station", "Turret") @@ -70,221 +30,6 @@ def valid_ship_id(ship_id: str) -> bool: and not ship_id.endswith(".") and ship_id.split(".")[0] not in RESERVED_SHIP_IDS) -def decode_hardpoint(row: list[Any]) -> dict[str, Any]: - return dict(zip(HARDPOINT_MEMBERS, row)) - - -def encode_hardpoint(**fields: Any) -> list[Any]: - if set(fields) != set(HARDPOINT_MEMBERS): - raise ValueError(f"A hardpoint row needs exactly {', '.join(HARDPOINT_MEMBERS)}") - return [fields[name] for name in HARDPOINT_MEMBERS] - - -def _cultcache_py_version(module: Any) -> str: - """[project].version of the cultcache-py checkout the imported module lives in (src/cultcache_py/__init__.py sits - two levels under it). A module with no file or no readable pyproject has no version: "".""" - try: - with (Path(module.__file__).parents[2] / "pyproject.toml").open("rb") as handle: - return str(tomllib.load(handle)["project"]["version"]) - except (AttributeError, TypeError, IndexError, OSError, tomllib.TOMLDecodeError, KeyError): - return "" - - -def _libraries(cultlib_packages: str): - source = Path(cultlib_packages) / "cultcache-py" / "src" - if source.exists() and str(source) not in sys.path: - sys.path.insert(0, str(source)) - import cultcache_py # type: ignore - import msgpack # type: ignore - found = _cultcache_py_version(cultcache_py) - if found != TESTED_CULTCACHE_PY: - raise ValueError(f"the imported cultcache-py (version {found or 'unreadable'}; CultLib packages {cultlib_packages}) " - f"is not the tested {TESTED_CULTCACHE_PY}; the add-on writes raw envelopes and refuses a " - f"CultLib whose write path may have moved") - return cultcache_py, msgpack - - -class Record(NamedTuple): - envelope: Any - body: list - - -class ShipFile(NamedTuple): - store: Any - ship: Record # the ShipAuthoring visual - hull: Record # the HullData it belongs to - msgpack: Any - - -def read(path: str, cultlib_packages: str) -> ShipFile: - cultcache, msgpack = _libraries(cultlib_packages) - store = cultcache.SingleFileMessagePackBackingStore(path) - try: - envelopes = store.pull_all() - except OSError as error: - raise ValueError(f"The ship file cannot be read: {error.strerror}") from None - ships = [envelope for envelope in envelopes if envelope.type == SCHEMA] - hulls = [envelope for envelope in envelopes if envelope.type == HULL_SCHEMA] - # Before S1 the hull lived inside the ship record. Saving such a file would preserve the stale hull under a ship that - # no longer reads it, so it is refused before anything else is said about its shape. - for envelope in ships: - body = msgpack.unpackb(envelope.payload, raw=False) - if isinstance(body, list) and len(body) > RETIRED_HULL_SLOT and body[RETIRED_HULL_SLOT] is not None: - raise ValueError( - f"The ship file has a legacy embedded hull at retired key {RETIRED_HULL_SLOT} of the {SCHEMA} record; " - f"migrate it into its own {HULL_SCHEMA} record that names the visual, and drop key {RETIRED_HULL_SLOT}") - products = [envelope for envelope in envelopes if envelope.type == PRODUCT_SCHEMA] - if len(ships) != 1 or len(hulls) != 1 or len(ships) + len(hulls) + len(products) != len(envelopes): - raise ValueError(f"The ship file must hold exactly one {SCHEMA} record and one {HULL_SCHEMA} record, " - f"and may hold {PRODUCT_SCHEMA} records beside them, nothing else") - bodies = [] - for envelope in (ships[0], hulls[0]): - body = msgpack.unpackb(envelope.payload, raw=False) - if not isinstance(body, list): - raise ValueError(f"The ship file has an incompatible {envelope.type} payload") - bodies.append(Record(envelope, body)) - ship, hull = bodies - if len(ship.body) < SCHEMATIC_LINES_SLOT + 1: - raise ValueError(f"The ship file has an incompatible {SCHEMA} payload") - return ShipFile(store, ship, hull, msgpack) - - -def product_makers(path: str, cultlib_packages: str) -> list[str]: - """The Manufacturer (Faction record key) of every product record in the file, in file order. C# owns products and - this only reads them: a product whose Manufacturer is missing or not a non-empty string is refused, naming nothing.""" - cultcache, msgpack = _libraries(cultlib_packages) - makers = [] - for envelope in cultcache.SingleFileMessagePackBackingStore(path).pull_all(): - if envelope.type != PRODUCT_SCHEMA: - continue - body = msgpack.unpackb(envelope.payload, raw=False) - maker = body[PRODUCT_MANUFACTURER_SLOT] if isinstance(body, list) and len(body) > PRODUCT_MANUFACTURER_SLOT else None - if not isinstance(maker, str) or not maker: - raise ValueError(f"A {PRODUCT_SCHEMA} record names no manufacturer") - makers.append(maker) - return makers - - -def _stamped(record: Record, msgpack: Any): - return replace( - record.envelope, - payload=msgpack.packb(record.body, use_bin_type=True), - stored_at=datetime.now(timezone.utc).isoformat(), - ) - - -def replace_lines(path: str, cultlib_packages: str, lines: list[list[Any]]) -> int: - file = read(path, cultlib_packages) - if not lines: - raise ValueError("No schematic lines were captured; the ship record was not changed") - file.ship.body[SCHEMATIC_LINES_SLOT] = lines - file.store.push(_stamped(file.ship, file.msgpack)) - return len(lines) - - -def clear_lines(path: str, cultlib_packages: str) -> int: - """Empties the line slot and nothing else; returns how many lines it held. replace_lines refuses an empty capture so a - failed capture never wipes a ship; this is the one deliberate way to leave a ship without lines.""" - file = read(path, cultlib_packages) - held = len(file.ship.body[SCHEMATIC_LINES_SLOT] or []) - file.ship.body[SCHEMATIC_LINES_SLOT] = [] - file.store.push(_stamped(file.ship, file.msgpack)) - return held - - -def replace_visual(path: str, cultlib_packages: str, expected_id: str, model_asset: str, - anchors: list[list[Any]]) -> int: - """Writes the visual's model asset and anchor list (ShipAuthoring slots 2 and 3) and nothing else. Each anchor row is - ANCHOR_MEMBERS in order; the slots past Order that the same anchor Id carried before are appended to it unchanged.""" - file = read(path, cultlib_packages) - if file.ship.body[0] != expected_id: - raise ValueError("The bound ship ID changed; rebind the collection") - known = len(ANCHOR_MEMBERS) - ids = set() - for anchor in anchors: - if len(anchor) != known: - raise ValueError(f"Each anchor row needs exactly {', '.join(ANCHOR_MEMBERS)}") - anchor_id = anchor[0] - if not isinstance(anchor_id, str) or not anchor_id.strip(): - raise ValueError("Every anchor needs an ID") - if anchor_id in ids: - raise ValueError("An anchor ID is used twice") - ids.add(anchor_id) - previous = file.ship.body[ANCHORS_SLOT] if len(file.ship.body) > ANCHORS_SLOT else None - later = {row[0]: row[known:] for row in previous or [] - if isinstance(row, list) and len(row) > known and isinstance(row[0], str)} - file.ship.body[MODEL_ASSET_SLOT] = model_asset - file.ship.body[ANCHORS_SLOT] = [list(anchor) + later.get(anchor[0], []) for anchor in anchors] - file.store.push(_stamped(file.ship, file.msgpack)) - return len(anchors) - - -def _hull_body(file: ShipFile) -> list: - if len(file.hull.body) <= HULL_HARDPOINTS_SLOT: - raise ValueError("Ship hull has an incompatible typed payload") - return file.hull.body - - -def read_layout(path: str, cultlib_packages: str): - file = read(path, cultlib_packages) - hull = _hull_body(file) - return hull[HULL_SHAPE_SLOT][0], hull[HULL_HARDPOINTS_SLOT], layout_revision(hull[HULL_SHAPE_SLOT][0], hull[HULL_HARDPOINTS_SLOT]) - - -def read_hull_type(path: str, cultlib_packages: str) -> str: - """The hull's HullData.HullType as its enum member name ("Ship", "Station" or "Turret").""" - hull = _hull_body(read(path, cultlib_packages)) - value = hull[HULL_TYPE_SLOT] if len(hull) > HULL_TYPE_SLOT else None - if type(value) is not int or not 0 <= value < len(HULL_TYPE_NAMES): - raise ValueError("The ship file's hull has no hull type this add-on knows") - return HULL_TYPE_NAMES[value] - - -def layout_revision(shape: list[Any], hardpoints: list[list[Any]]) -> str: - """The revision of a layout: a hash of its shape ([width, height, cells]) and hardpoint rows as the file stores - them. replace_layout returns it, Load records it, and Package compares the layout buffer's against the file's.""" - import msgpack # type: ignore - return hashlib.sha256(msgpack.packb([[shape], hardpoints], use_bin_type=True)).hexdigest() - - -def replace_layout(path: str, cultlib_packages: str, expected_id: str, expected_revision: str, - shape: list[Any], hardpoints: list[list[Any]]) -> str: - file = read(path, cultlib_packages) - if file.ship.body[0] != expected_id: - raise ValueError("The bound ship ID changed; reload its layout") - hull = _hull_body(file) - if layout_revision(hull[HULL_SHAPE_SLOT][0], hull[HULL_HARDPOINTS_SLOT]) != expected_revision: - raise ValueError("The .cc layout changed since Load; reload before saving") - width, height, cells = shape - limit = hull_grid.MAX_CELLS - if not (1 <= width <= limit and 1 <= height <= limit and len(cells) == width * height): - raise ValueError(f"Hull grid must be 1..{limit} cells wide and high with one value per cell") - if not all(type(cell) is bool for cell in cells): - raise ValueError("Hull grid cells must be booleans") - if not any(cells): - raise ValueError("Hull grid needs an occupied cell") - known = len(HARDPOINT_MEMBERS) - previous = {decode_hardpoint(hp)["Transform"]: hp[known:] for hp in hull[HULL_HARDPOINTS_SLOT] - if isinstance(hp, list) and len(hp) > known and isinstance(decode_hardpoint(hp)["Transform"], str)} - updated_hardpoints = [] - for hardpoint in hardpoints: - fields = decode_hardpoint(hardpoint) - mount = fields.get("Transform") - if len(hardpoint) != known or not isinstance(mount, str) or not mount: - raise ValueError(f"Each hardpoint needs {known} typed fields and a stable mount ID") - hp_width, hp_height, hp_cells = fields["Shape"][0] - if not all(type(cell) is bool for cell in hp_cells): - raise ValueError("Hardpoint footprint cells must be booleans") - if not (1 <= hp_width <= 32 and 1 <= hp_height <= 32 and - len(hp_cells) == hp_width * hp_height and any(hp_cells)): - raise ValueError("A hardpoint has an invalid footprint") - updated_hardpoints.append(hardpoint + previous.get(mount, [])) - hull[HULL_SHAPE_SLOT] = [shape] - hull[HULL_HARDPOINTS_SLOT] = updated_hardpoints - file.store.push(_stamped(file.hull, file.msgpack)) - return layout_revision(hull[HULL_SHAPE_SLOT][0], hull[HULL_HARDPOINTS_SLOT]) - - def capture_grease_pencil(obj: Any, depsgraph: Any, frame_number: int, *, evaluated: bool = True) -> list[list[Any]]: if obj.type != "GREASEPENCIL": raise ValueError("The selected object is not a Grease Pencil object") diff --git a/tools/blender/hull_packager/build_aetherdb.ps1 b/tools/blender/hull_packager/build_aetherdb.ps1 new file mode 100644 index 000000000..0f2f2c566 --- /dev/null +++ b/tools/blender/hull_packager/build_aetherdb.ps1 @@ -0,0 +1,15 @@ +# build_aetherdb.ps1 -Game -CultLibRoot -CultMathRoot [-Repo ] +# Publishes tools/AetherDb into \ModTools, the AetherDb.exe package_hull.py runs. also needs GameData\Aetheria.cc +# (the shipped catalog's content, not its LFS pointer). CultLibRoot and CultMathRoot are CultLib worktrees at the revisions +# Directory.Build.props names for this repo revision (git worktree add --detach ). +# ErrorOnDuplicatePublishOutputFiles=false is the NETSDK1152 workaround: Aetheria.Shared and CultLib publish the same files. +param( + [Parameter(Mandatory)] [string]$Game, + [Parameter(Mandatory)] [string]$CultLibRoot, + [Parameter(Mandatory)] [string]$CultMathRoot, + [string]$Repo = (Resolve-Path "$PSScriptRoot\..\..\..").Path +) +$ErrorActionPreference = "Stop" +& dotnet publish "$Repo\tools\AetherDb" -c Release -o "$Game\ModTools" "-p:CultLibRoot=$CultLibRoot" "-p:CultMathRoot=$CultMathRoot" "-p:ErrorOnDuplicatePublishOutputFiles=false" +if ($LASTEXITCODE -ne 0) { throw "dotnet publish exited $LASTEXITCODE" } +if (-not (Test-Path "$Game\ModTools\AetherDb.exe")) { throw "no AetherDb.exe in $Game\ModTools" } diff --git a/tools/blender/hull_packager/compare.py b/tools/blender/hull_packager/compare.py new file mode 100644 index 000000000..518354b95 --- /dev/null +++ b/tools/blender/hull_packager/compare.py @@ -0,0 +1,39 @@ +"""compare.py : exit 0 and COMPARE_EQUAL when the two packages hold the same grid, hardpoint +rows (mount, kind, cell, footprint, rotation, armour, arc, in order), hull section (name, price, stats, top speed, kind) and +products (maker, name, description, offered), both read through AetherDb's 'ship-authoring open'. GLB bytes are not compared. +Needs GAME_FOLDER, whose ModTools holds AetherDb.""" +import json +import os +import subprocess +import sys +from pathlib import Path + + +def opened(path): + """'ship-authoring open' of a ship.cc as a dict.""" + game = Path(os.environ["GAME_FOLDER"]) + tool = game / "ModTools" / ("AetherDb.exe" if sys.platform == "win32" else "AetherDb") + run = subprocess.run([str(tool), "ship-authoring", "open", str(path)], cwd=game, capture_output=True, text=True, timeout=120) + if run.returncode != 0: + sys.exit(f"open refused {path}: {run.stdout.strip()} {run.stderr.strip()}") + return json.loads(run.stdout) + + +def view(path): + o = opened(path) + return {"grid": o["layout"]["grid"], + "rows": [{k: v for k, v in row.items() if k != "element"} for row in o["layout"]["hardpoints"]], + "hull": o["hull"], "products": o["products"]} + + +if __name__ == "__main__": + a, b = view(sys.argv[1]), view(sys.argv[2]) + bad = [k for k in a if a[k] != b[k]] + for k in bad: + print("DIFF", k, *([] if k == "rows" else [a[k], b[k]])) + if "rows" in bad: + for x, y in zip(a["rows"], b["rows"]): + if x != y: + print("DIFF row", x, y) + print("COMPARE_EQUAL" if not bad else "COMPARE_DIFFERENT", len(a["rows"]), "rows") + sys.exit(1 if bad else 0) diff --git a/tools/blender/hull_packager/gen_manifest.py b/tools/blender/hull_packager/gen_manifest.py new file mode 100644 index 000000000..8a7ad5d67 --- /dev/null +++ b/tools/blender/hull_packager/gen_manifest.py @@ -0,0 +1,55 @@ +"""gen_manifest.py --like --extent X Y Z --maker [--length N] + +A packager manifest (see ../package_hull.md) from an existing package's ship.cc, read through AetherDb's 'ship-authoring +open': rows, stats, price and product come from the .cc; the arguments are what a .cc does not record (the hull to copy, the +model extent in metres, the maker, the schematic length in cells). The id is the package folder's name. The hull.scad is +copied beside the manifest. Needs GAME_FOLDER, whose ModTools holds AetherDb. +""" +import argparse +import json +import shutil +import sys +from pathlib import Path + +from compare import opened + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("ship_cc") + parser.add_argument("hull_scad") + parser.add_argument("out") + parser.add_argument("--like", required=True) + parser.add_argument("--extent", required=True, nargs=3, type=float) + parser.add_argument("--maker", required=True) + parser.add_argument("--length", type=int, default=30) + args = parser.parse_args() + o = opened(args.ship_cc) + hull = o["hull"] + if o["hullType"] == "Station": + sys.exit("gen_manifest reads a ship: a station has no top speed and its kind is not in the hull record. " + "Station manifests are written by hand (see manifests/arsenal-depot, package_hull.md).") + if hull["topSpeed"] is None: + sys.exit("the hull has no single fixed top speed; the manifest holds one") + if len(o["products"]) != 1: + sys.exit(f"the package holds {len(o['products'])} products; the manifest holds one") + product = o["products"][0] + manifest = { + "id": Path(args.ship_cc).resolve().parent.name, + "name": hull["name"], "like": args.like, "length": args.length, "extent": args.extent, + "hull": Path(args.hull_scad).name, "maker": args.maker, "description": product["description"], + "offered": product["offered"], "price": hull["price"], + "stats": {"mass": hull["mass"], "durability": hull["durability"], "armor": hull["armor"], + "drag": round(hull["drag"], 6), "top_speed": hull["topSpeed"]}, + "rows": [{"id": row["mount"], "kind": row["kind"], "cell": row["cell"], "footprint": row["footprint"], + "rotation": row["rotation"], "armor": row["armor"], "arc": row["arc"]} + for row in o["layout"]["hardpoints"]], + } + out = Path(args.out) + out.write_text(json.dumps(manifest, indent=1), encoding="utf-8") + shutil.copy(args.hull_scad, out.parent / Path(args.hull_scad).name) + print("manifest", out, len(manifest["rows"]), "rows") + + +if __name__ == "__main__": + main() diff --git a/tools/blender/hull_packager/job.ps1 b/tools/blender/hull_packager/job.ps1 new file mode 100644 index 000000000..742d08984 --- /dev/null +++ b/tools/blender/hull_packager/job.ps1 @@ -0,0 +1,79 @@ +# job.ps1 -Scratch -Game [-Blender ] [-OpenScad ] [-Lock ] +# The packager's regression job: package_hull.py on the fixture manifest; on a manifest generated from the committed +# aetheria.nakovalnya package, compared (compare.py) with that package; a second run without --replace (must refuse and leave +# the package byte-identical); a --replace that fails (must leave it byte-identical); and AetherDb compose over the result. +# Launch detached. It logs to \job.log and writes \job.status (pid, state, time): +# Start-Process powershell -ArgumentList '-NoProfile','-File','tools\blender\hull_packager\job.ps1','-Scratch','','-Game','\game' +# holds GameData\Aetheria.cc and ModTools\AetherDb.exe (build_aetherdb.ps1); its GameData\Mods is emptied first. +param( + [Parameter(Mandatory)] [string]$Scratch, + [Parameter(Mandatory)] [string]$Game, + [string]$Blender = "C:\Program Files (x86)\Steam\steamapps\common\Blender\blender.exe", + [string]$OpenScad = "C:\Tools\OpenSCAD-2026.09.23-x86-64\openscad.com", + [string]$Lock = "F:\Projects\eureka-handoff-aux-2026-10-19\starfire_lock.py" +) +$ErrorActionPreference = "Stop" +$Repo = (Resolve-Path "$PSScriptRoot\..\..\..").Path +$Log = "$Scratch\job.log" +$Status = "$Scratch\job.status" +$Packager = "$Repo\tools\blender\package_hull.py" +function Say($text) { Add-Content -Path $Log -Value "$(Get-Date -Format s) $text" -Encoding utf8 } +function State($text) { Set-Content -Path $Status -Value "pid $PID`n$text`n$(Get-Date -Format s)" -Encoding utf8 } +function Native($label, [scriptblock]$block, [int]$want = 0) { + Say "BEGIN $label" + & $block 2>&1 | ForEach-Object { Add-Content -Path $Log -Value " $_" -Encoding utf8 } + $code = $LASTEXITCODE + Say "END $label exit $code" + if ($code -ne $want) { throw "$label exited $code, wanted $want" } +} +function Digest($dir) { (Get-ChildItem $dir -Recurse -File | Sort-Object FullName | ForEach-Object { "$($_.Name) $((Get-FileHash $_.FullName).Hash)" }) -join "`n" } +function Pack($manifest, $flags = @()) { & $Blender --background --factory-startup --python-use-system-env --python $Packager -- $manifest @flags } + +New-Item -ItemType Directory -Force $Scratch | Out-Null +Set-Content -Path $Log -Value "" -Encoding utf8 +State "waiting for the Starfire lock" +if (Test-Path $Lock) { & py -3 $Lock acquire hull-packager 2>&1 | ForEach-Object { Say $_ } } +try { + $env:GAME_FOLDER = $Game + $env:OPENSCAD = $OpenScad + $Fixture = "$Repo\tools\blender\tests\fixtures\hulls\zh-ammo-tender\package.json" + $Committed = "$Repo\GameData\Mods\aetheria.nakovalnya" + $Mods = "$Game\GameData\Mods" + $Nak = "$Scratch\nakovalnya.json" + Set-Location $Game + Remove-Item -Recurse -Force $Mods -ErrorAction SilentlyContinue + New-Item -ItemType Directory -Force $Mods | Out-Null + + State "running: fixture" + Native "packager on the fixture manifest" { Pack $Fixture } + Native "validate fixture" { & "$Game\ModTools\AetherDb.exe" ship-authoring validate "$Mods\smoke.package.tender\ship.cc" } + + State "running: nakovalnya" + Native "manifest from the committed package" { & py -3 "$PSScriptRoot\gen_manifest.py" "$Committed\ship.cc" "$Committed\hull.scad" $Nak --like Djinni --extent 37.6 58.4 14.9 --maker Zhestokost } + Native "packager on the Nakovalnya manifest" { Pack $Nak } + Native "validate nakovalnya" { & "$Game\ModTools\AetherDb.exe" ship-authoring validate "$Mods\aetheria.nakovalnya\ship.cc" } + Native "compare to the committed package" { & py -3 "$PSScriptRoot\compare.py" "$Committed\ship.cc" "$Mods\aetheria.nakovalnya\ship.cc" } + + State "running: refusal, failed replace, compose" + $before = Digest "$Mods\aetheria.nakovalnya" + Native "second run without --replace refuses" { Pack $Nak } 1 + if ($before -ne (Digest "$Mods\aetheria.nakovalnya")) { throw "the refused run changed the package" } + Say "REFUSAL LEFT THE PACKAGE BYTE-IDENTICAL" + # A manifest that fails after the build has started: its first row sits far off the raster (hull.scad is beside it already). + $bad = Get-Content $Nak -Raw | ConvertFrom-Json + $bad.rows[0].cell = @(500, 500) + [IO.File]::WriteAllText("$Scratch\bad.json", ($bad | ConvertTo-Json -Depth 8), (New-Object Text.UTF8Encoding $false)) + Native "failed --replace" { Pack "$Scratch\bad.json" @("--replace") } 1 + if (-not (Select-String -Path $Log -Pattern "PACKAGE_FAILED: row .* raster" -Quiet)) { throw "the --replace failed, but not on the off-raster row" } + if ($before -ne (Digest "$Mods\aetheria.nakovalnya")) { throw "the failed --replace changed the package" } + Say "FAILED REPLACE LEFT THE PACKAGE BYTE-IDENTICAL" + Remove-Item "$Scratch\derived.cc" -ErrorAction SilentlyContinue + Native "compose" { & "$Game\ModTools\AetherDb.exe" ship-authoring compose "$Game\GameData\Aetheria.cc" "$Scratch\derived.cc" $Mods } + Say "JOB OK" + State "done: OK" +} catch { + Say "JOB FAILED: $_" + State "done: FAILED $_" +} finally { + if (Test-Path $Lock) { & py -3 $Lock release hull-packager 2>&1 | ForEach-Object { Say $_ } } +} diff --git a/tools/blender/manifests/arsenal-depot/hull.scad b/tools/blender/manifests/arsenal-depot/hull.scad new file mode 100644 index 000000000..f7fc3c4a6 --- /dev/null +++ b/tools/blender/manifests/arsenal-depot/hull.scad @@ -0,0 +1,78 @@ +// Zhestokost Arsenal Depot, a station: the hull bench's cast-iron Dutch oven with its lid on (AetheriaLore, Brainstorming/Ship +// Prompt Bench.md, Stations and Station Modules). One squat charcoal pot, a heavy iron-grey stepped lid with a round knob +// for its control tower, two thick lugs on opposite flanks that are the docking piers, four broad magazine bands round the +// pot wall with oxide hatches. Built only from the Zhestokost kit and lowpoly primitives. +// part = lang | brief | anchors | lines | primary | secondary | accent | recess | marking | rad: +// Frame: Ship Root, metres, nose -Y, starboard -X, up +Z. The piers stand on the X axis; the rest of the outline is round. +include +part = "primary"; + +HULL_FACTION = "zhestokost"; +HULL_DONOR = ""; +HULL_ROLE = "depot"; +HULL_LENGTH = [20, 26]; +HULL_TRIANGLES = [800, 9000]; +HULL_READS = ["the hull is a cast-iron Dutch oven with its lid on: one squat thick charcoal pot, a heavy stepped iron lid, a round knob on top", + "the knob is the control tower, ringed by narrow observation slits", + "two thick lugs on opposite flanks are the docking piers, each ending in one square-set docking collar with guide lugs", + "four broad magazine bands ring the pot wall, oxide-red square hatches set in them", + "two radiator troughs on the lid, either side of the knob; no thrusters and no guns, a depot does not move or fight"]; +if (part == "brief") echo(brief = [HULL_FACTION, HULL_DONOR, HULL_ROLE, HULL_LENGTH, HULL_TRIANGLES, HULL_READS]); + +POT_R = 11.7; // pot wall circumradius; its top-view raster must stay a disc of about 12 cells +POT_H = 7.2; +BAND_R = 11.85; // bands stand 0.15 m proud: the widest the top view gets (23.7 m, 12 cells) +BANDS = [[0.5, 2.0], [2.3, 3.8], [4.1, 5.6], [5.9, 7.1]]; +LID = [[POT_H - 0.2, 11.85], [8.7, 10.0], [10.4, 8.0]]; // [z, radius]: lip, first step, deck +DECK_Z = 10.4; +TOWER_R = 2.4; +TOWER_TOP = 13.2; +LUG_X = [9.4, 13.1]; // piers: x from the pot into the flank; the collars end at 13.95 m +LUG_Y = 4.0; +LUG_H = 5.2; +HATCH_AT = [50, 130, 230, 310]; // azimuths, deg: clear of the piers on the X axis and of the y extremes +RAD_Y = 4.9; RAD_W = 5.2; RAD_L = 2.4; +RADS = [["Ra.N1", -1, 1], ["Ra.N2", -1, -1], ["Ra.S1", 1, 1], ["Ra.S2", 1, -1]]; // [id, trough y sign, trough side] + +// A round mass from z0 to z1, r0 at the base and r1 at the top. +module cone(z0, z1, r0, r1, fn=24) translate([0, 0, z0]) cylinder(r1=r0, r2=r1, h=z1 - z0, $fn=fn); + +// pot (charcoal) with its bottom chamfer +zh_z("secondary") { + cone(0, 0.6, POT_R - 0.9, POT_R); + cone(0.6, POT_H, POT_R, POT_R); +} +// four magazine bands, proud of the pot +for (b = BANDS) zh_z("secondary") cone(b[0], b[1], BAND_R, BAND_R); +// lid: a lip, then two steps up to a flat deck (iron grey) +zh_z("primary") { + cone(LID[0][0], 7.7, LID[0][1], LID[0][1]); + cone(7.7, LID[1][0], LID[0][1], LID[1][1]); + cone(LID[1][0], LID[2][0] + 0.05, LID[1][1], LID[2][1]); + // knob: the control tower + cone(DECK_Z - 0.05, TOWER_TOP, TOWER_R + 0.5, TOWER_R, 12); +} +zh_z("secondary") cone(TOWER_TOP - 0.05, TOWER_TOP + 0.45, TOWER_R + 0.35, TOWER_R + 0.35, 12); +// observation slits ring the tower: black recesses sunk in its wall +zh_z("recess") for (k = [0:11]) rotate([0, 0, k*30 + 15]) translate([TOWER_R - 0.05, 0, 12.2]) cube([0.28, 0.5, 0.45], center=true); +// the piers: a thick lug on each flank, one docking collar on each outer face +for (s = [-1, 1]) { + zh_z("secondary") translate([s*(LUG_X[0] + LUG_X[1])/2, 0, LUG_H/2]) cbox([LUG_X[1] - LUG_X[0], LUG_Y, LUG_H], 0.3); + lp_at(t=[s*LUG_X[1], 0, LUG_H/2], r=[0, 90*s, 0]) zh_collar(1.5, 0.55); + lp_at(t=[s*(LUG_X[0] + LUG_X[1])/2, 0, LUG_H], r=[0, 0, 90]) zh_stripes(2.4, 1.4, 3); +} +// magazine hatches on each band, at four azimuths; cream serials on the bands between them +for (b = BANDS, a = HATCH_AT) + lp_at(t=[BAND_R*cos(a), BAND_R*sin(a), (b[0] + b[1])/2], r=[90, 0, a + 90]) zh_hatch(1.9, 1.0, dogs=false); +for (a = [80, 100, 260, 280]) + lp_at(t=[BAND_R*cos(a), BAND_R*sin(a), 3.05], r=[90, 0, a + 90]) zh_serial(0.5, 3); +// two radiator troughs on the deck, either side of the knob +for (y = [-RAD_Y, RAD_Y]) lp_at(t=[0, y, DECK_Z]) zh_rad_trough(RAD_W, RAD_L, 0.45); +// silhouette lines: the pot's cast belt and the lid deck edge +lp_line("outline", [for (a = [0:15:345]) [BAND_R*cos(a), BAND_R*sin(a), POT_H]], true); +lp_line("step", [for (a = [0:15:345]) [LID[2][1]*cos(a), LID[2][1]*sin(a), DECK_Z]], true); + +// ---- anchor meshes: each radiator is one half of a trough ---- +for (r = RADS) if (part == str("rad:", r[0])) lp_at(t=[0, r[1]*RAD_Y, DECK_Z]) zh_rad_vanes(RAD_W, RAD_L, r[2], 4, 1.0); +if (part == "anchors") for (r = RADS) + echo(anchor=[r[0], "radiator-mesh", [0, r[1]*RAD_Y, DECK_Z] + zh_rad_centre(RAD_W, r[2], 1.0), 0, ""]); diff --git a/tools/blender/manifests/arsenal-depot/package.json b/tools/blender/manifests/arsenal-depot/package.json new file mode 100644 index 000000000..bd69a5f81 --- /dev/null +++ b/tools/blender/manifests/arsenal-depot/package.json @@ -0,0 +1,22 @@ +{ + "id": "aetheria.arsenal-depot", + "name": "Arsenal Depot", + "like": "Zenith", + "kind": "depot", + "length": 12, + "extent": [28.0, 23.7, 13.6], + "hull": "hull.scad", + "maker": "Zhestokost", + "description": "A Zhestokost ammunition depot built like a lidded cast-iron Dutch oven: one squat charcoal pot under a heavy iron lid, a round control-tower knob, two thick lugs that are the docking piers and four magazine bands with oxide hatches.", + "offered": true, + "price": 100000, + "stats": {"mass": 50000, "durability": 5000, "armor": 100, "drag": 0}, + "rows": [ + {"id": "Reactor", "kind": "Reactor", "cell": [5, 8], "footprint": "####/####/####/####", "rotation": 0, "armor": 0, "arc": 0}, + {"id": "Ra.N1", "kind": "Radiator", "cell": [2, 2], "footprint": "#/#/#/#", "rotation": 1, "armor": 0, "arc": 0}, + {"id": "Ra.N2", "kind": "Radiator", "cell": [2, 6], "footprint": "#/#/#/#", "rotation": 1, "armor": 0, "arc": 0}, + {"id": "Ra.S1", "kind": "Radiator", "cell": [11, 2], "footprint": "#/#/#/#", "rotation": 3, "armor": 0, "arc": 0}, + {"id": "Ra.S2", "kind": "Radiator", "cell": [11, 6], "footprint": "#/#/#/#", "rotation": 3, "armor": 0, "arc": 0}, + {"id": "Fa.1", "kind": "Facility", "cell": [4, 2], "footprint": "##/##", "rotation": 0, "armor": 0, "arc": 0} + ] +} diff --git a/tools/blender/manifests/seized-refinery/hull.scad b/tools/blender/manifests/seized-refinery/hull.scad new file mode 100644 index 000000000..fe3850921 --- /dev/null +++ b/tools/blender/manifests/seized-refinery/hull.scad @@ -0,0 +1,110 @@ +// Pirate Coalition station "Seized Refinery" on a stolen Zhestokost donor: a cast-iron pot-bellied stove, the furnace, with +// Pirate additions welded on one side. The firebox is an octagonal cast box, not a drum: flat faces keep the station's interior roomy. An agent-built hull source: the donor body and its fittings come from the Zhestokost +// language (zones keyed zhestokost:), every addition from the Pirate language. No bench prompt names a refinery; this +// is a first proposal of the form, not a ruling on it. +// part = lang | brief | anchors | lines | marks | zhestokost: | primer | weld | accent | recess | rad: +// Frame: Ship Root, metres, nose -Y, starboard -X, up +Z. The docking door faces the nose; the stovepipe is the control tower. +include +include +part = "zhestokost:primary"; + +HULL_FACTION = "pirate"; +HULL_DONOR = "zhestokost"; +HULL_ROLE = "refinery"; +HULL_LENGTH = [14, 26]; +HULL_TRIANGLES = [800, 9000]; +HULL_READS = ["the stolen Zhestokost body is still a cast-iron pot-bellied stove: one squat octagonal firebox belly, a flat cooktop, a tall stovepipe that is the control tower", + "a square firebox door on the nose with a docking collar in it is the ore intake, an ash-pan drawer below it", + "bolted primer-red salvage plates cover a breach in the belly, an exposed cable run climbs from a stolen reactor saddle on the cooktop to a second docking collar welded on the starboard flank", + "one oversized stolen gun on an adapted saddle, out of proportion to the stove", + "Zhestokost stencils on the belly are crossed out in the crew's own colour", + "no thrusters, a refinery does not move; asymmetric"]; +if (part == "brief") echo(brief = [HULL_FACTION, HULL_DONOR, HULL_ROLE, HULL_LENGTH, HULL_TRIANGLES, HULL_READS]); + +A = 10.2; // belly apothem (centre to the middle of a flat face) +TOP_A = 7.6; // cooktop apothem +TOP = 9.0; // cooktop height +PIPE = [0, 1.0]; // stovepipe centre +PIER_X = [A - 0.8, A + 3.0]; // the welded pier on the starboard flank: x from the belly out (mirrored to -X) +PIER_Y = -1.5; +PIER_W = 9.0; // the pier's width along Y +RAD_W = 2.6; RAD_L = 3.6; +TROUGH = [[4.1, 1.0], [-4.1, 1.0]]; +RADS = [["Ra.1", 0, 1], ["Ra.2", 1, -1]]; // [id, trough index, side of the trough its vanes stand in] + +// A round mass from z0 to z1, r0 at the base and r1 at the top. +module cone(z0, z1, r0, r1, fn=28) translate([0, 0, z0]) cylinder(r1=r0, r2=r1, h=z1 - z0, $fn=fn); +// An octagonal mass, flat faces on the axes, from z0 to z1; a0 and a1 are apothems. +module oct(z0, z1, a0, a1) rotate([0, 0, 22.5]) cone(z0, z1, a0/cos(22.5), a1/cos(22.5), 8); +function oct_ring(a, z) = [for (k = [0:7]) let(t = 22.5 + 45*k) [a/cos(22.5)*cos(t), a/cos(22.5)*sin(t), z]]; +// A frame on a flat face of the belly at azimuth a (a multiple of 45), height z: local +Z points out of the face. +module on_wall(a, z, out=0) lp_at(t=[(A + out)*cos(a), (A + out)*sin(a), z], r=[90, 0, a + 90]) children(); + +// ---- the donor: the stove ---- +// firebox belly (body): a chamfered foot, the cast belly, a battered shoulder up to the cooktop +zh_z("primary") { + oct(0.4, 1.4, A - 1.0, A); + oct(1.4, 6.0, A, A); + oct(6.0, TOP - 0.4, A, TOP_A - 0.2); +} +// the cooktop, two cast belts, the stovepipe's flared foot and its cap +zh_z("secondary") { + oct(TOP - 0.6, TOP, TOP_A, TOP_A - 0.2); + oct(3.0, 3.6, A + 0.15, A + 0.15); + oct(5.0, 5.5, A + 0.15, A + 0.15); + translate([PIPE[0], PIPE[1], 0]) { cone(TOP - 0.05, TOP + 1.3, 2.4, 1.5, 12); cone(TOP + 6.9, TOP + 7.5, 1.85, 1.85, 12); } +} +// the stovepipe: the control tower, ringed by narrow observation slits +zh_z("primary") translate([PIPE[0], PIPE[1], 0]) cone(TOP + 1.2, TOP + 7.0, 1.5, 1.3, 12); +zh_z("recess") translate([PIPE[0], PIPE[1], 0]) for (k = [0:9]) rotate([0, 0, k*36 + 18]) translate([1.3, 0, TOP + 5.4]) cube([0.3, 0.55, 0.5], center=true); +// the firebox door on the nose face: the ore intake, with the docking collar in it; the ash-pan drawer below +lp_at(t=[0, -A, 3.2], r=[90, 0, 0]) zh_hatch(4.4, 3.6, dogs=false); +lp_at(t=[0, -A - 0.2, 3.2], r=[90, 0, 0]) zh_collar(1.6, 0.6); +zh_z("secondary") translate([0, -A - 0.5, 0.95]) cbox([5.0, 2.6, 1.5], 0.2); +zh_z("accent") translate([0, -A - 1.85, 0.95]) cbox([2.6, 0.4, 0.4], 0.08); +// two radiator troughs on the cooktop, either side of the pipe +for (t = TROUGH) lp_at(t=[t[0], t[1], TOP]) zh_rad_trough(RAD_W, RAD_L, 0.45); +// Zhestokost stencils on the two faces flanking the door +for (a = [225, 315]) on_wall(a, 3.2) zh_serial(0.9, 3); +// silhouette lines: the belly's cast belt and the cooktop edge +lp_line("outline", oct_ring(A + 0.15, 3.6), true); +lp_line("step", oct_ring(TOP_A, TOP), true); + +// ---- the Pirate additions, one side and unmatched ---- +// primer-red salvage plates bolted over a breach in the starboard rear face +module wall_plate(a, y, z, w, l, tilt) translate([A*cos(a), y, z]) rotate([0, 0, a + 90]) rotate([90, 0, 0]) pi_plate(w, l, 0.14, tilt); +if (part == "primer") { + translate([-(A + 0.02)*cos(45), (A + 0.02)*sin(45), 0]) {} // (faces at 135 degrees carry the plates below) + for (p = [[2.6, 2.4, 3.2, 3.0, 4], [4.3, -0.8, 2.4, 2.0, -6], [1.9, 3.8, 1.8, 1.6, 7]]) + translate([A*cos(135) + 0.0, A*sin(135) + 0, 0]) rotate([0, 0, 135 + 90]) translate([p[1], 0, p[0]]) rotate([90, 0, 0]) pi_plate(p[2], p[3], 0.14, p[4]); + translate([-4.6, 5.0, TOP + 0.1]) pi_plate(2.2, 1.8, 0.12, 5); +} +// the welded pier with its second docking collar, the stolen reactor on its saddle, the exposed cable run, the oversized gun +module cables() { + pi_cable([[-3.0, -3.9, TOP + 1.0], [-5.4, -3.5, TOP + 0.6], [-(TOP_A + 0.8), -3.0, TOP - 1.2], [-(A + 0.1), -2.6, 5.0], [-(A + 1.2), -2.0, 4.6]]); + pi_cable([[-3.4, -3.3, TOP + 0.8], [-5.6, -2.4, TOP + 0.5], [-(TOP_A + 0.9), -1.9, TOP - 1.3], [-(A + 0.1), -1.4, 5.0], [-(A + 1.4), -1.2, 4.6]], 0.05); +} +if (part == "weld") { + translate([-(PIER_X[0] + PIER_X[1])/2, PIER_Y, 2.6]) cbox([PIER_X[1] - PIER_X[0], PIER_W, 3.6], 0.2); + translate([-(PIER_X[0] + 1.6), PIER_Y, 5.1]) rotate([0, 0, 90]) pi_plate(1.6, 1.4, 0.12, 3); + strut([-(PIER_X[0] + 0.4), PIER_Y - 1.4, 4.4], [-(A - 0.6), PIER_Y - 3.4, 6.4], 0.12); + strut([-(PIER_X[0] + 0.4), PIER_Y + 1.4, 4.4], [-(A - 0.4), PIER_Y + 3.2, 6.0], 0.12); + translate([-(PIER_X[1] + 0.05), PIER_Y, 2.6]) rotate([0, 90, 0]) pi_collar(1.8, 0.3); + translate([-3.0, -3.8, TOP]) { pi_saddle(2.6, 3.2, 1.0); translate([0, 0, 1.0]) cylinder(r=0.85, h=1.3, $fn=10); } + cables(); + translate([2.8, -3.2, TOP]) { pi_saddle(1.4, 2.6, 0.6); translate([0, 0, 1.0]) pi_big_gun(8.0, 0.2); } +} +if (part == "recess") translate([-(PIER_X[1] + 0.2), PIER_Y, 2.6]) rotate([0, 90, 0]) pi_collar(1.25, 0.2); +// the crew's own colour: one slash across a crossed-out stencil, one across the cooktop, a sensor pod on the stovepipe +if (part == "accent") { + translate([(A + 0.06)*cos(315), (A + 0.06)*sin(315), 3.2]) rotate([0, 0, 315 + 90]) rotate([90, 0, 0]) rotate([0, 0, 40]) cube([3.4, 0.4, 0.12], center=true); + translate([-0.5, -1.2, TOP + 0.04]) rotate([0, 0, -38]) cube([0.7, 7.0, 0.06], center=true); + translate([2.5, PIPE[1] + 0.4, TOP + 4.4]) pi_sensor_pod(1.6, 0.34); + strut([1.2, PIPE[1] + 0.2, TOP + 4.2], [2.5, PIPE[1] + 0.4, TOP + 4.4], 0.07); +} + +// ---- anchor meshes: each radiator is one half of a trough; the other half was stripped ---- +for (r = RADS) if (part == str("rad:", r[0])) + lp_at(t=[TROUGH[r[1]][0], TROUGH[r[1]][1], TOP]) zh_rad_vanes(RAD_W, RAD_L, r[2], 4, 1.0); +if (part == "anchors") for (r = RADS) + echo(anchor=[r[0], "radiator-mesh", [TROUGH[r[1]][0], TROUGH[r[1]][1], TOP] + zh_rad_centre(RAD_W, r[2], 1.0), 0, ""]); diff --git a/tools/blender/manifests/seized-refinery/package.json b/tools/blender/manifests/seized-refinery/package.json new file mode 100644 index 000000000..ea068d811 --- /dev/null +++ b/tools/blender/manifests/seized-refinery/package.json @@ -0,0 +1,20 @@ +{ + "id": "aetheria.seized-refinery", + "name": "🔥🏭", + "like": "Zenith", + "kind": "processing", + "length": 12, + "extent": [23.9, 22.6, 16.5], + "hull": "hull.scad", + "maker": "Pirates", + "description": "A Pirate refinery seized from the Zhestokost: an octagonal cast-iron pot-bellied stove with a tall stovepipe for a control tower and a square firebox door that is the ore intake, its donor body patched with primer-red salvage plates, a stolen reactor on a cable run to a second docking collar welded on the flank, and one oversized stolen gun.", + "offered": true, + "price": 100000, + "stats": {"mass": 50000, "durability": 5000, "armor": 100, "drag": 0}, + "rows": [ + {"id": "Reactor", "kind": "Reactor", "cell": [3, 0], "footprint": "####/####/####/####", "rotation": 0, "armor": 0, "arc": 0}, + {"id": "Ra.1", "kind": "Radiator", "cell": [0, 3], "footprint": "#/#/#/#", "rotation": 1, "armor": 0, "arc": 0}, + {"id": "Ra.2", "kind": "Radiator", "cell": [11, 4], "footprint": "#/#/#/#", "rotation": 3, "armor": 0, "arc": 0}, + {"id": "Fa.1", "kind": "Facility", "cell": [4, 10], "footprint": "##/##", "rotation": 0, "armor": 0, "arc": 0} + ] +} diff --git a/tools/blender/package_hull.md b/tools/blender/package_hull.md new file mode 100644 index 000000000..7b9cf3090 --- /dev/null +++ b/tools/blender/package_hull.md @@ -0,0 +1,65 @@ +# package_hull.py: the hull packager + +One bench hull plus one manifest becomes one ship package (`GameData/Mods//ship.cc`, `ship.glb`, `hull.scad`) that the +validator accepts, with no Unity and no clicking. The header of `package_hull.py` gives the command line, the environment +(`GAME_FOLDER`, `OPENSCAD`) and the order of steps. This file is the manifest schema and the way to check the +packager still matches the committed first-party package. + +## Contract + +- The manifest is creation input only. Once `GameData/Mods/` exists, its `ship.cc` owns rows, stats and product; the manifest + is never read again. Without `--replace` an existing package is refused untouched. With `--replace` it is re-derived and edits + made since are discarded, but only on success: the old package is moved aside during the run, and any failure removes what the + run built and puts the old one back exactly as it was. +- The last output line is `PACKAGE_OK` (exit 0) or `PACKAGE_FAILED` (exit 1, with the reason). There is no third state: a row whose + cell is off the raster, outside the hull shape or overlapping an earlier row fails the run; nothing is moved for you. +- A manifest is checked before Blender or the game folder is touched: bad JSON, an unknown or missing key, an unknown `kind`, a + malformed footprint, a duplicate row id and a missing hull file are each refused by name. + +## Manifest (JSON; no key may be missing or unknown) + +| key | meaning | +| --- | --- | +| `id` | the stable ship id and the folder name under `GameData/Mods`; `ship_cc.valid_ship_id` decides what is valid | +| `name` | the hull's display name | +| `like` | the name of a shipped catalog hull of type Ship or Station whose stats the new hull starts from (AetherDb `--like`); a Station's kind is not copied | +| `length` | whole cells, at least 1: the New Ship length field of the add-on | +| `extent` | `[x, y, z]` metres of the stand-in box the model is made from; with the add-on's `CELL_SIZE` of 2 m (`aetheria_ships/hull_grid.py`) this fixes the raster, so rows written for one extent do not carry to another | +| `hull` | a file beside the manifest, copied to the package as `hull.scad` (OpenSCAD source with the kit's faction modules) | +| `maker` | the name of a faction the shipped catalog holds; the product record is made for it | +| `description` | the product's description | +| `offered` | `true` or `false`: whether the maker sells it | +| `price` | at least 0 (AetherDb `price`) | +| `stats` | `mass`, `durability`, `armor`, `drag`, each at least 0, and optionally `top_speed` (a hull without it keeps `like`'s) | +| `rows` | a non-empty list of hardpoint rows, below | +| `kind` | optional: a station kind id (such as `depot`), written by AetherDb `ship-authoring kind` after stats; required when `like` is a Station, because `validate` refuses a station package that names no kind the shipped catalog holds | + +A row has all of `id`, `kind`, `cell`, `footprint`, `rotation`, `armor`, `arc`: + +- `id` is the mount id the model's anchor binds to (`aetheria.id`); unique in the manifest. +- `kind` is one of `ship_cc.HARDPOINT_TYPE_NAMES` (Hull, Tool, Thermal, Thruster, WarpDrive, Reactor, Radiator, Shield, Sensors, + Energy, Ballistic, Launcher, ControlModule, Facility). The packager keeps no list of its own. A `Facility` row is internal (no + anchor, nothing on the model) and only a Station hull takes one. +- `cell` is `[x, y]`, whole numbers of at least 0: the footprint's lowest-x, lowest-y cell on the raster. `x` runs across, `y` from + the stern (0) toward the bow, as the layout panel shows it. Cells are in schematic space, not model space. +- `footprint` is rows of `#` (the mount's cells) and `.` separated by `/`, all one width, at least one `#`. The first row is the top + (highest y); the last row is `y` itself. `##/#.` is a 2x2 box missing its lower-right cell. +- `rotation` is `0` None, `1` CounterClockwise, `2` Reversed, `3` Clockwise (`ship_cc.ROTATION_NAMES`). +- `armor` is at least 0; `arc` is the firing arc in degrees, 0 to 360. + +The committed example is `tests/fixtures/hulls/zh-ammo-tender/package.json`; its rows fit the raster that its `hull.scad` and +`extent` produce. + +## Reproducers (`hull_packager/`) + +- `build_aetherdb.ps1` publishes `tools/AetherDb` into `/ModTools`: it needs CultLib and CultMath worktrees at the revisions + `Directory.Build.props` names and passes `ErrorOnDuplicatePublishOutputFiles=false` (the NETSDK1152 workaround). +- `manifests/arsenal-depot/` is the committed manifest of the Arsenal Depot (its `hull.scad` is a copy of the package's; a test holds both equal to the shipped package, `Fa.1` included): a station's manifest is written by hand, and `gen_manifest.py` refuses a station with a message. +- `gen_manifest.py --like ... --extent X Y Z --maker ...` turns an existing package into a manifest. `gen_manifest.py` and `compare.py` read through AetherDb's `ship-authoring open` and need `GAME_FOLDER`. +- `compare.py ` prints `COMPARE_EQUAL` when shape, rows, stats, price and product match. +- `job.ps1` runs the regression on a workstation with Blender and OpenSCAD: the fixture manifest; the committed + `aetheria.nakovalnya` regenerated from its own manifest and compared; a refused second run and a failed `--replace`, each + required to leave the package byte-identical; then compose. Launch it detached; its header gives the log and status files. + +`python -m unittest discover -s tools/blender/tests -p test_package_hull.py` runs the Blender-free tests (manifest refusals, row +placement, the all-or-nothing swap). diff --git a/tools/blender/package_hull.py b/tools/blender/package_hull.py new file mode 100644 index 000000000..434af2484 --- /dev/null +++ b/tools/blender/package_hull.py @@ -0,0 +1,349 @@ +"""Headless hull packager: a bench hull and its manifest become one ship package accepted by the validator. + + blender --background --factory-startup --python-use-system-env --python tools/blender/package_hull.py -- [--replace] + +Environment: GAME_FOLDER (holds GameData/Aetheria.cc and ModTools/AetherDb.exe) and OPENSCAD. The repo (and so the +add-on) is found from this file. The manifest is creation input only: once GameData/Mods/ exists, ship.cc owns rows, stats and +product, and a manifest is never read again; --replace re-derives the package and discards edits made since. Without --replace an +existing package is refused untouched. A run is all or nothing: --replace moves the existing package aside, builds, and deletes the old one +only when the new one is complete; any failure removes what the run built and puts the old package back as it was. + +Order, one owner per step: New Ship --like, the first Push and Apply create ship.cc, AetherDb stats/kind/price/product (the one writer of +each; kind only for a station manifest), hull.scad copied in, Open, Build From Hull Source, Rasterise Hull, the rows through place(), Push then Apply, Package Ship. +The last line is PACKAGE_OK (exit 0) or PACKAGE_FAILED (exit 1); a row that does not fit its cell is a failure, never a move. +Manifest schema and the reproducers: package_hull.md. Everything outside package() is pure Python (test_package_hull.py). +""" + +import importlib.util +import json +import os +import shutil +import subprocess +import sys +import traceback +from contextlib import contextmanager +from pathlib import Path + +HERE = Path(__file__).resolve().parent + +MANIFEST_KEYS = ("id", "name", "like", "length", "extent", "hull", "maker", "description", "offered", "price", "stats", "rows") +MANIFEST_OPTIONAL = ("kind",) +STATS_KEYS = ("mass", "durability", "armor", "drag") +STATS_OPTIONAL = ("top_speed",) +ROW_KEYS = ("id", "kind", "cell", "footprint", "rotation", "armor", "arc") + + +class Refused(Exception): + pass + + +def _ship_cc(): + """ship_cc.py by path: the add-on's package __init__ imports bpy, and the hardpoint kind names live in ship_cc.""" + spec = importlib.util.spec_from_file_location("ship_cc", HERE / "aetheria_ships" / "ship_cc.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _keys(where, mapping, required, optional=()): + if not isinstance(mapping, dict): + raise Refused(f"{where} is not an object") + unknown = sorted(set(mapping) - set(required) - set(optional)) + missing = [key for key in required if key not in mapping] + if unknown: + raise Refused(f"{where} has unknown key(s): {', '.join(unknown)}") + if missing: + raise Refused(f"{where} is missing key(s): {', '.join(missing)}") + + +def _number(where, value, minimum=None): + if isinstance(value, bool) or not isinstance(value, (int, float)) or (minimum is not None and value < minimum): + raise Refused(f"{where} must be a number" + ("" if minimum is None else f" of at least {minimum}")) + return value + + +def _text(where, value): + if not isinstance(value, str) or not value: + raise Refused(f"{where} must be a non-empty string") + return value + + +def valid_footprint(footprint): + """Top-to-bottom rows of # and . separated by /, all one width, at least one #.""" + rows = footprint.split("/") if isinstance(footprint, str) else [] + return (bool(rows) and len(rows[0]) > 0 and all(len(row) == len(rows[0]) and set(row) <= {"#", "."} for row in rows) + and any("#" in row for row in rows)) + + +def load_manifest(path): + """The manifest as a dict, or Refused naming the first fault. Nothing here touches Blender or the game folder.""" + path = Path(path) + try: + manifest = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + raise Refused(f"The manifest cannot be read: {error}") from None + _keys("The manifest", manifest, MANIFEST_KEYS, MANIFEST_OPTIONAL) + ship_cc = _ship_cc() + if not isinstance(manifest["id"], str) or not ship_cc.valid_ship_id(manifest["id"]): + raise Refused(f"id {manifest['id']!r} is not a valid ship id") + for key in ("name", "like", "maker", "description", "hull"): + _text(key, manifest[key]) + if "kind" in manifest: + _text("kind", manifest["kind"]) + if isinstance(manifest["length"], bool) or not isinstance(manifest["length"], int) or manifest["length"] < 1: + raise Refused("length must be a whole number of cells of at least 1") + extent = manifest["extent"] + if not isinstance(extent, list) or len(extent) != 3: + raise Refused("extent must be [x, y, z] in metres") + for axis, value in zip("xyz", extent): + _number(f"extent {axis}", value, 1e-6) + if not isinstance(manifest["offered"], bool): + raise Refused("offered must be true or false") + _number("price", manifest["price"], 0) + stats = manifest["stats"] + _keys("stats", stats, STATS_KEYS, STATS_OPTIONAL) + for key, value in stats.items(): + _number(f"stats {key}", value, 0) + if not (path.parent / manifest["hull"]).is_file(): + raise Refused(f"hull {manifest['hull']!r} is not a file beside the manifest") + if not isinstance(manifest["rows"], list) or not manifest["rows"]: + raise Refused("rows must be a non-empty list") + seen = set() + for index, row in enumerate(manifest["rows"]): + _keys(f"row {index}", row, ROW_KEYS) + _text(f"row {index} id", row["id"]) + where = f"row {row['id']!r}" + if row["id"] in seen: + raise Refused(f"{where} is a duplicate row id") + seen.add(row["id"]) + if row["kind"] not in ship_cc.HARDPOINT_TYPE_NAMES: + raise Refused(f"{where} has unknown kind {row['kind']!r}") + cell = row["cell"] + if (not isinstance(cell, list) or len(cell) != 2 + or any(isinstance(v, bool) or not isinstance(v, int) or v < 0 for v in cell)): + raise Refused(f"{where} cell must be [x, y] whole numbers of at least 0") + if not valid_footprint(row["footprint"]): + raise Refused(f"{where} has a malformed footprint {row['footprint']!r}") + if isinstance(row["rotation"], bool) or row["rotation"] not in range(len(ship_cc.ROTATION_NAMES)): + raise Refused(f"{where} rotation must be 0 to {len(ship_cc.ROTATION_NAMES) - 1}") + _number(f"{where} armor", row["armor"], 0) + if _number(f"{where} arc", row["arc"], 0) > 360: + raise Refused(f"{where} arc is over 360") + return manifest + + +def cells_of(x, y, footprint): + rows = footprint.split("/") + height = len(rows) + return [(x + fx, y + fy) for fy in range(height) for fx in range(len(rows[0])) if rows[height - 1 - fy][fx] == "#"] + + +def place(rows, width, height, occupied): + """Each row at its cell, or Refused naming the row: the manifest's cells are authored against the raster, so a cell off the + raster, outside the shape or overlapping an earlier row is a fault in the manifest, not something to move.""" + taken, placed = set(), [] + for mount_id, kind, (x, y), footprint, rotation, armor, arc in rows: + for cx, cy in cells_of(x, y, footprint): + if not (0 <= cx < width and 0 <= cy < height): + raise Refused(f"row {mount_id or kind} cell ({cx}, {cy}) is off the {width}x{height} raster") + if not occupied(cx, cy): + raise Refused(f"row {mount_id or kind} cell ({cx}, {cy}) is outside the hull shape") + if (cx, cy) in taken: + raise Refused(f"row {mount_id or kind} cell ({cx}, {cy}) overlaps an earlier row") + taken.update(cells_of(x, y, footprint)) + placed.append((mount_id, kind, (x, y), footprint, rotation, armor, arc)) + return placed + + +@contextmanager +def swap(package_dir, backup, replace): + """The all-or-nothing run. An existing package is refused untouched, or with replace moved to backup (same volume, a rename) + before the build. On any failure what the run built is removed and the old package moved back; on success the backup goes.""" + existed = package_dir.exists() + if existed and not replace: + raise Refused(f"{package_dir} exists; pass --replace to re-derive it (this discards edits made since)") + if backup.exists(): + raise Refused(f"{backup} is left from an interrupted run; restore or delete it first") + if existed: + backup.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(package_dir), str(backup)) + try: + yield + except BaseException: + shutil.rmtree(package_dir, ignore_errors=True) + if existed: + shutil.move(str(backup), str(package_dir)) + raise + if existed: + shutil.rmtree(backup) + + +def rows_of(manifest): + return [(row["id"], row["kind"], tuple(row["cell"]), row["footprint"], row["rotation"], row["armor"], row["arc"]) + for row in manifest["rows"]] + + +def package(manifest, manifest_dir, game, openscad): + """The Blender half, run inside swap(). Builds GameData/Mods/; raises Refused with a message on any failure.""" + import addon_utils + import bmesh + import bpy + + ship_id, name = manifest["id"], manifest["name"] + package_dir = game / "GameData" / "Mods" / ship_id + ship_cc_path = package_dir / "ship.cc" + aetherdb = game / "ModTools" / "AetherDb.exe" + print(f"STEP Blender {bpy.app.version_string}", flush=True) + + def require(condition, message): + if not condition: + raise Refused(message) + + def select(obj): + bpy.context.view_layer.objects.active = obj + obj.select_set(True) + + def run(operator): + try: + return operator(), "" + except RuntimeError as exc: + return {"CANCELLED"}, str(exc) + + def land(what): + """Push (dry run), then Apply: her two buttons, in order, outside any agent turn.""" + result, message = run(bpy.ops.aetheria.push_ship) + require(result == {"FINISHED"}, f"{what}: Push was refused: {message}") + result, message = run(bpy.ops.aetheria.apply_ship) + require(result == {"FINISHED"}, f"{what}: Apply was refused: {message}") + + def db(*args): + result = subprocess.run([str(aetherdb), "ship-authoring", *map(str, args)], cwd=game, capture_output=True, text=True, timeout=120) + print(f"AetherDb {args[0]}: exit {result.returncode} {result.stdout.strip()} {result.stderr.strip()}", flush=True) + return result.returncode + + if bpy.data.objects.get("Cube") is not None: + bpy.data.objects.remove(bpy.data.objects["Cube"], do_unlink=True) + sys.path.insert(0, str(HERE)) + addon_utils.enable("aetheria_ships", default_set=True, handle_error=None) + import aetheria_ships + preferences = bpy.context.preferences.addons["aetheria_ships"].preferences + preferences.game_folder = str(game) + preferences.openscad = openscad + scene = bpy.context.scene + kind_value = {kind: value for value, kind, _ in aetheria_ships.HARDPOINT_TYPES} + + collection = bpy.data.collections.new(name) + scene.collection.children.link(collection) + mesh = bpy.data.meshes.new("stand-in") + bm = bmesh.new() + bmesh.ops.create_cube(bm, size=1.0) + bm.to_mesh(mesh) + bm.free() + box = bpy.data.objects.new("stand-in", mesh) + box.scale = tuple(manifest["extent"]) + collection.objects.link(box) + select(box) + scene.aetheria_new_ship_id, scene.aetheria_new_ship_name = ship_id, name + scene.aetheria_new_ship_like, scene.aetheria_new_ship_length = manifest["like"], manifest["length"] + result, message = run(bpy.ops.aetheria.new_ship) + require(result == {"FINISHED"}, f"New Ship was refused: {message}") + land("The first Apply") + require(ship_cc_path.is_file(), "The first Apply did not create ship.cc") + print(f"STEP new ship and first apply: {ship_cc_path}", flush=True) + + stats = manifest["stats"] + args = ["stats", ship_cc_path, "--mass", stats["mass"], "--durability", stats["durability"], "--armor", stats["armor"], + "--drag", stats["drag"]] + if "top_speed" in stats: + args += ["--top-speed", stats["top_speed"]] + require(db(*args) == 0, "stats was refused") + if "top_speed" in stats: + require(aetheria_ships._open(bpy.context, str(ship_cc_path))["hull"]["topSpeed"] == stats["top_speed"], + "stats did not set the top speed") + if "kind" in manifest: + # A station's kind is ship.cc's own fact and AetherDb its one writer; the packager holds no kind table. + require(db("kind", ship_cc_path, manifest["kind"]) == 0, "kind was refused") + require(db("price", ship_cc_path, manifest["price"]) == 0, "price was refused") + product = ["product", ship_cc_path, manifest["maker"], "--name", name, "--description", manifest["description"]] + require(db(*product, *([] if manifest["offered"] else ["--not-offered"])) == 0, "product was refused") + print("STEP stats, price and product written", flush=True) + + shutil.copy(manifest_dir / manifest["hull"], package_dir / "hull.scad") + select(box) + result, message = run(bpy.ops.aetheria.open_ship) + require(result == {"FINISHED"}, f"Open was refused: {message}") + select(box) + result, message = run(bpy.ops.aetheria.build_hull_source) + require(result == {"FINISHED"}, f"Build was refused: {message}") + built = collection.get("aetheria.hull_built") + objects = [obj for obj in collection.all_objects if built is not None and obj.name in built] + zones = sorted(obj.name for obj in objects if obj.type == "MESH" and not obj.get("aetheria.role")) + anchors = sorted(obj.get("aetheria.id") for obj in objects if obj.get("aetheria.role") in + ("weapon-mount", "weapon-muzzle", "thruster-emitter", "radiator-mesh")) + print(f"STEP Build: {len(zones)} zones {zones}; {len(anchors)} anchors {anchors}", flush=True) + + select(box) + result, message = run(bpy.ops.aetheria.rasterise_hull) + require(result == {"FINISHED"}, f"Rasterise was refused: {message}") + state = scene.aetheria_layout + width, height = state.width, state.height + print(f"STEP Rasterise: {width}x{height}", flush=True) + for y in range(height - 1, -1, -1): + print("GRID " + "".join("#" if state.cells[x * height + y].occupied else "." for x in range(width)), flush=True) + + occupied = lambda x, y: state.cells[x * height + y].occupied + for mount_id, kind, (x, y), footprint, rotation, armor, arc in place(rows_of(manifest), width, height, occupied): + bpy.ops.aetheria.add_ship_hardpoint() + hp = state.hardpoints[len(state.hardpoints) - 1] + hp.mount_id, hp.kind, hp.x, hp.y, hp.footprint = mount_id, kind_value[kind], x, y, footprint + hp.rotation, hp.armor, hp.firing_arc = str(rotation), armor, arc + select(box) + land("The layout") + print(f"STEP layout applied: {len(state.hardpoints)} rows", flush=True) + for hp in state.hardpoints: + print(f"ROW {hp.mount_id or '-'} kind {hp.kind} at ({hp.x},{hp.y}) {hp.footprint} rot {hp.rotation} armor {hp.armor:g} arc {hp.firing_arc:g}", flush=True) + + select(box) + result, message = run(bpy.ops.aetheria.package_ship) + report = scene.aetheria_package_report + require(result == {"FINISHED"} and "validator accepted" in report, f"Package refused the ship: {report!r} {message!r}") + require((package_dir / "ship.glb").is_file() and (package_dir / "hull.scad").is_file(), "Package did not leave ship.glb and hull.scad") + print(f"STEP Package: {report}", flush=True) + + +def main(argv): + replace = "--replace" in argv + paths = [a for a in argv if a != "--replace"] + if len(paths) != 1: + raise Refused("usage: package_hull.py -- [--replace]") + env = {} + for key in ("GAME_FOLDER", "OPENSCAD"): + if not os.environ.get(key): + raise Refused(f"Set {key}") + env[key] = os.environ[key] + manifest_path = Path(paths[0]).resolve() + manifest = load_manifest(manifest_path) + game = Path(env["GAME_FOLDER"]) + with swap(game / "GameData" / "Mods" / manifest["id"], game / f".hull-packager-backup-{manifest['id']}", replace): + package(manifest, manifest_path.parent, game, env["OPENSCAD"]) + + +def entry(argv): + """The exit status: 0 and PACKAGE_OK, or 1 and PACKAGE_FAILED. swap() has already put the game folder back.""" + try: + main(argv) + except Refused as stop: + print(f"PACKAGE_FAILED: {stop}", flush=True) + return 1 + except Exception: + traceback.print_exc() + print("PACKAGE_FAILED", flush=True) + return 1 + print("PACKAGE_OK", flush=True) + return 0 + + +if __name__ == "__main__": + code = entry(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []) + sys.stdout.flush() + os._exit(code) diff --git a/tools/blender/tests/fixtures/hulls/zh-ammo-tender/package.json b/tools/blender/tests/fixtures/hulls/zh-ammo-tender/package.json new file mode 100644 index 000000000..da7d12112 --- /dev/null +++ b/tools/blender/tests/fixtures/hulls/zh-ammo-tender/package.json @@ -0,0 +1,21 @@ +{ + "id": "smoke.package.tender", + "name": "Oboz Tender", + "like": "Djinni", + "length": 12, + "extent": [10.0, 23.4, 2.0], + "hull": "hull.scad", + "maker": "Zhestokost", + "description": "A packager fixture: the Zhestokost ammunition tender with one defensive mount, two drive pods and two radiators.", + "offered": true, + "price": 1000000, + "stats": {"mass": 20000, "durability": 2000, "armor": 20, "drag": 0.35}, + "rows": [ + {"id": "Gun.D", "kind": "Ballistic", "cell": [2, 3], "footprint": "#", "rotation": 0, "armor": 20, "arc": 90}, + {"id": "Th.L", "kind": "Thruster", "cell": [3, 0], "footprint": "#", "rotation": 2, "armor": 20, "arc": 0}, + {"id": "Th.R", "kind": "Thruster", "cell": [4, 0], "footprint": "#", "rotation": 2, "armor": 20, "arc": 0}, + {"id": "Ra.L", "kind": "Radiator", "cell": [2, 1], "footprint": "#", "rotation": 0, "armor": 10, "arc": 0}, + {"id": "Ra.R", "kind": "Radiator", "cell": [5, 1], "footprint": "#", "rotation": 0, "armor": 10, "arc": 0}, + {"id": "Reactor", "kind": "Reactor", "cell": [3, 2], "footprint": "#", "rotation": 0, "armor": 0, "arc": 0} + ] +} diff --git a/tools/blender/tests/live_authoring_surface.py b/tools/blender/tests/live_authoring_surface.py new file mode 100644 index 000000000..5f348f192 --- /dev/null +++ b/tools/blender/tests/live_authoring_surface.py @@ -0,0 +1,430 @@ +"""Live proof, in GUI Blender 5.3 with Brokkr installed as an extension and aetheria_ships in the scripts folder, that the +add-on's brokkr_actions.json gives agents Open and Push and nothing else: Open is one undo step, Push writes nothing and +returns AetherDb's change lines as hostResult (also in Edit Mode), and the operators that write game data stay human-only. + + BROKKR_SCRATCH= + BROKKR_CULTLIB= + SMOKE_GAME_FOLDER= + BROKKR_ADDON_MODULE= + LIVE_SHOT= + blender --enable-event-simulate --python live_authoring_surface.py -- + +Run it in Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (Blender +5.3 ignores BLENDER_USER_RESOURCE_PATH). The script refuses to run when they are unset or are not the folders Blender +uses. It copies this repo's aetheria_ships into BLENDER_USER_SCRIPTS/addons and enables it there, makes the ship +live.surface under /GameData/Mods and removes it at the end. Every intent is put into the node database as +brokkr-ctl does and answered by the add-on's own 1 s drain. wm.undo_stack is the counter. Proves: + + * after the human's Reload Host Actions the snapshot lists exactly aetheria.open_ship and aetheria.push_ship (host + aetheria_ships) and no hostActionErrors; + * open is accepted as exactly one new undo step with the buffer filled from the .cc, and one undo restores the buffer; + * push after a buffer edit is accepted with no new step, hostResult equal to wm().aetheria_push_result and holding the + 'armor: a -> b' line, ship.cc byte-identical; push is also accepted while an object is in Edit Mode, where open is denied; + * intents naming aetheria.apply_ship, package_ship, capture_ship_lines and new_ship are denied Unsupported, no step, + ship.cc byte-identical; the driver's own bpy.ops.aetheria.apply_ship, outside a turn, lands the reviewed push. + +Writes .result.json, then quits Blender. +""" +import hashlib +import importlib +import json +import os +import re +import shutil +import sys +import time +import traceback +from pathlib import Path + +import bpy + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own folders are used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +for _name, _kind in (("BLENDER_USER_EXTENSIONS", "EXTENSIONS"), ("BLENDER_USER_SCRIPTS", "SCRIPTS")): + if os.path.normcase(os.path.abspath(bpy.utils.user_resource(_kind))) != os.path.normcase(os.path.abspath(os.environ[_name])): + raise SystemExit(f"Blender's {_kind.lower()} folder is not {_name}; refusing to touch it") + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +GAME = Path(os.environ["SMOKE_GAME_FOLDER"]).resolve() +OUT = sys.argv[sys.argv.index("--") + 1] +SHOT = os.environ.get("LIVE_SHOT") +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +HOST = "aetheria_ships" +SHIP_ID, COLLECTION = "live.surface", "Live Surface" +SHIP_FOLDER = GAME / "GameData" / "Mods" / SHIP_ID +SHIP_CC = SHIP_FOLDER / "ship.cc" +SOURCE = Path(__file__).resolve().parents[1] / HOST +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": []} + +addons_dir = Path(os.environ["BLENDER_USER_SCRIPTS"]) / "addons" +addons_dir.mkdir(parents=True, exist_ok=True) +if (addons_dir / HOST).exists(): + shutil.rmtree(addons_dir / HOST) +shutil.copytree(SOURCE, addons_dir / HOST, ignore=shutil.ignore_patterns("__pycache__")) +bpy.utils.refresh_script_paths() + +bpy.ops.preferences.addon_enable(module=MODULE) +bpy.ops.preferences.addon_enable(module=HOST) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +ships = importlib.import_module(HOST) +prefs = bpy.context.preferences.addons[MODULE].preferences +bpy.context.preferences.addons[HOST].preferences.game_folder = str(GAME) +bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "live.blend")) +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = "" +prefs.auto_drain_commands = True # the sink +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() +bpy.ops.brokkr.reload_host_actions() # the human's button: the host file is read here + + + +def scene(): # read fresh every time: an undo step replaces the data-blocks + return bpy.context.scene + + +def wm(): + return bpy.context.window_manager + + +def state(): + return scene().aetheria_layout + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + return bpy.context.temp_override(window=wm().windows[0]) + + +def steps_now(): + return [s.name for s in wm().undo_stack.steps] + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def redo(): + with win(): + bpy.ops.ed.redo() + + +def digest(): + return hashlib.sha256(SHIP_CC.read_bytes()).hexdigest() + + +def armor(): + return state().hardpoints[0].armor + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +N = [0] +RUN = "%x" % int(time.time()) # the queue file outlives a run: an id is single-use, so a rerun needs ids of its own + + +def queue(**cmd): + N[0] += 1 + cid = "surface-%s-%04d" % (RUN, N[0]) + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA, requestedBy="nibu/hands") + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + return cid + + +def receipt(cid): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{cid}") + + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=60): + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("the drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def send(key, **fields): + S[key + ":before"] = {"steps": steps_now(), "digest": digest()} + S[key] = queue(**fields) + + +def done(key): + return lambda: receipt(S[key]) is not None + + +def make_ship(): + """The ship collection, applied through the human's buttons: a pending ship, then one hardpoint.""" + if SHIP_FOLDER.exists(): + shutil.rmtree(SHIP_FOLDER) + collection = bpy.data.collections.new(COLLECTION) + scene().collection.children.link(collection) + mesh = bpy.data.meshes.new("Live Hull") + corners = [(sx * 1.0, sy * 3.0, sz * 0.5) for sx in (-1, 1) for sy in (-1, 1) for sz in (-1, 1)] + mesh.from_pydata(corners, [], [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)]) + hull = bpy.data.objects.new("Live Hull", mesh) + collection.objects.link(hull) + bpy.context.view_layer.objects.active = hull + hull.select_set(True) + scene().aetheria_new_ship_id, scene().aetheria_new_ship_name = SHIP_ID, "Live Surface" + scene().aetheria_new_ship_like, scene().aetheria_new_ship_length = "Djinni", 10 + bpy.ops.aetheria.new_ship() + bpy.ops.aetheria.push_ship() + bpy.ops.aetheria.apply_ship() + bpy.ops.aetheria.add_ship_hardpoint() + hp = state().hardpoints[0] + hp.mount_id, hp.kind, hp.x, hp.y, hp.footprint, hp.armor, hp.firing_arc = "mount.live", "5", 1, 2, "#", 5.0, 90.0 + bpy.ops.aetheria.push_ship() + bpy.ops.aetheria.apply_ship() + + +make_ship() + + +def snapshot_check(): + R["windows"] = len(wm().windows) + R["undo_steps_at_start"] = steps_now() + snapshot = adapter.capture_snapshot(bpy.context, True) + rows = snapshot["hostActions"] + expect = sorted(f"{HOST[:-6] if False else 'aetheria'}.{n}" for n in ("open_ship", "push_ship")) + check("the snapshot lists exactly aetheria.open_ship and aetheria.push_ship, host aetheria_ships", + sorted(r["name"] for r in rows) == expect and {r["host"] for r in rows} == {HOST}, [r["name"] for r in rows]) + check("the snapshot carries no hostActionErrors", snapshot["hostActionErrors"] == [], snapshot["hostActionErrors"]) + + +def edit_armor(): + S["armor:old"] = armor() + state().hardpoints[0].armor = 9.0 + S["edited"] = json.dumps(ships._layout_section(state()), sort_keys=True) + with win(): + bpy.ops.ed.undo_push(message="Her armor edit") # the step the UI pushes for her own edit: what one undo returns to + + +def open_check(): + r = receipt(S["open"]) + before = S["open:before"] + after = steps_now() + check("open is accepted", r["status"] == "accepted", r) + check("open is exactly one new undo step carrying the receipt's label", + len(after) == len(before["steps"]) + 1 and after[-1] == r["undoLabel"] and r["undoLabel"].startswith("Brokkr nibu/hands: aetheria.open_ship "), + {"before": before["steps"][-2:], "after": after[-2:], "label": r["undoLabel"]}) + check("open filled the buffer from the .cc: the edited armor is gone", abs(armor() - S["armor:old"]) < 1e-6, armor()) + check("open wrote nothing", digest() == before["digest"]) + undo() + check("one undo restores the buffer before the open", abs(armor() - 9.0) < 1e-6, armor()) + + +def push_check(): + r = receipt(S["push"]) + before = S["push:before"] + check("push is accepted", r["status"] == "accepted", r) + check("push pushed no undo step", steps_now() == before["steps"] and r["undoLabel"] == "", [steps_now()[-2:], before["steps"][-2:]]) + check("hostResult equals wm.aetheria_push_result", r["hostResult"] == wm().aetheria_push_result and r["hostResult"] != "", r["hostResult"]) + check("hostResult holds the armor change line and the dry-run summary", + re.search(r"armor: 5 -> 9", r["hostResult"]) and r["hostResult"].splitlines()[-1].startswith("dry-run"), r["hostResult"]) + check("push left ship.cc byte-identical and the buffer as edited", + digest() == before["digest"] and json.dumps(ships._layout_section(state()), sort_keys=True) == S["edited"]) + + +def enter_edit_mode(): + hull = bpy.data.objects["Live Hull"] + bpy.context.view_layer.objects.active = hull + with win(): + bpy.ops.object.mode_set(mode="EDIT") + check("an object is in Edit Mode", bpy.data.objects["Live Hull"].mode == "EDIT", bpy.data.objects["Live Hull"].mode) + + +def leave_edit_mode(): + with win(): + bpy.ops.object.mode_set(mode="OBJECT") + + +def edit_push_check(): + r = receipt(S["epush"]) + check("push is accepted in Edit Mode", r["status"] == "accepted" and "armor: 5 -> 9" in r["hostResult"], r) + check("and wrote nothing", steps_now() == S["epush:before"]["steps"] and digest() == S["epush:before"]["digest"]) + + +def edit_open_check(): + r = receipt(S["eopen"]) + check("open is denied in Edit Mode", r["status"] == "denied", r) + check("and changed nothing", steps_now() == S["eopen:before"]["steps"] and abs(armor() - 9.0) < 1e-6) + + +def denied_check(key, action): + def run(): + r = receipt(S[key]) + before = S[key + ":before"] + check(f"{action} is denied Unsupported", r["status"] == "denied" and "Unsupported Blender command action" in r["message"], r) + check(f"{action} ran nothing: no step, ship.cc byte-identical", steps_now() == before["steps"] and digest() == before["digest"]) + return run + + +def human_apply(): + before = digest() + bpy.ops.aetheria.push_ship() + lines = wm().aetheria_push_result.splitlines() + check("the human's own Push shows the armor change", any("armor: 5 -> 9" in line for line in lines), lines) + S["human_before"] = before + bpy.ops.aetheria.apply_ship() + check("the human's Apply, outside a turn, lands the reviewed push", digest() != before, wm().aetheria_push_result) + check("and the .cc holds the new armor", ships._open(bpy.context, str(SHIP_CC))["layout"]["hardpoints"][0]["armor"] == 9.0) + + +def view3d(): + area = next(a for a in bpy.context.screen.areas if a.type == "VIEW_3D") + return area, next(r for r in area.regions if r.type == "UI"), next(r for r in area.regions if r.type == "WINDOW") + + +def stage_shot(): + """Leaves the panel as she would see it after an agent's push: an edit, then the dry run in the panel, the Brokkr tab + open. The tab is chosen and the sidebar widened by simulated events (Blender run with --enable-event-simulate).""" + state().hardpoints[0].armor = 12.0 + bpy.ops.aetheria.push_ship() + area, ui, _ = view3d() + area.spaces.active.show_region_ui = True + area.tag_redraw() + R["shot"] = {"category_before": ui.active_panel_category, "ui": [ui.x, ui.y, ui.width, ui.height]} + + +def simulate(**event): + window = wm().windows[0] + window.event_simulate(**event) + + +def tab_point(): + area, ui, _ = view3d() + tabs = ui.x + ui.width - 15 # the tab strip is the sidebar's right edge; Brokkr is the last of five tabs + return tabs, area.y + area.height - 295 + + +def sim(type, value="NOTHING", **where): + x, y = tab_point() + wm().windows[0].event_simulate(type=type, value=value, x=where.get("x", x), y=where.get("y", y)) + + +def widen(step): + area, ui, _ = view3d() + edge, y = ui.x + 1, ui.y + ui.height // 2 + if step == 0: + sim("MOUSEMOVE", x=edge, y=y) + elif step == 1: + sim("LEFTMOUSE", "PRESS", x=edge, y=y) + elif step == 2: + sim("MOUSEMOVE", x=edge - 150, y=y) + elif step == 3: + sim("MOUSEMOVE", x=edge - 300, y=y) + else: + sim("LEFTMOUSE", "RELEASE", x=edge - 300, y=y) + + +def collapse_and_scroll(step): + """Collapses the Brokkr panel (a click on its header), then scrolls the sidebar to its end, where the push result is.""" + area, ui, _ = view3d() + x, y = ui.x + 120, area.y + area.height - 67 + if step == 0: + sim("MOUSEMOVE", x=x, y=y) + elif step == 1: + sim("LEFTMOUSE", "PRESS", x=x, y=y) + elif step == 2: + sim("LEFTMOUSE", "RELEASE", x=x, y=y) + else: + sim("MOUSEMOVE", x=ui.x + 300, y=ui.y + ui.height // 2) + for _ in range(12): + sim("WHEELDOWNMOUSE", "PRESS", x=ui.x + 300, y=ui.y + ui.height // 2) + + +def note_shot(): + area, ui, _ = view3d() + R["shot"].update(category_after=ui.active_panel_category, ui_after=[ui.x, ui.y, ui.width, ui.height]) + + +def shoot(): + if not SHOT: + return + area, _, region = view3d() + with bpy.context.temp_override(window=wm().windows[0], area=area, region=region): + bpy.ops.screen.screenshot_area(filepath=SHOT) + check("the panel screenshot was written", Path(SHOT).is_file(), SHOT) + + +def cleanup(): + leave_edit_mode() + shutil.rmtree(SHIP_FOLDER, ignore_errors=True) + + +steps = [ + once(snapshot_check), + once(edit_armor), + once(lambda: send("open", action="aetheria.open_ship", collection=COLLECTION)), until(done("open")), once(open_check), + once(lambda: send("push", action="aetheria.push_ship", collection=COLLECTION)), until(done("push")), once(push_check), + once(enter_edit_mode), + once(lambda: send("epush", action="aetheria.push_ship", collection=COLLECTION)), until(done("epush")), once(edit_push_check), + once(lambda: send("eopen", action="aetheria.open_ship", collection=COLLECTION)), until(done("eopen")), once(edit_open_check), + once(leave_edit_mode), + once(lambda: send("apply", action="aetheria.apply_ship", collection=COLLECTION)), until(done("apply")), once(denied_check("apply", "aetheria.apply_ship")), + once(lambda: send("package", action="aetheria.package_ship", collection=COLLECTION)), until(done("package")), once(denied_check("package", "aetheria.package_ship")), + once(lambda: send("capture", action="aetheria.capture_ship_lines", collection=COLLECTION)), until(done("capture")), once(denied_check("capture", "aetheria.capture_ship_lines")), + once(lambda: send("new", action="aetheria.new_ship")), until(done("new")), once(denied_check("new", "aetheria.new_ship")), + once(human_apply), + once(stage_shot), until(lambda: True), once(lambda: sim('MOUSEMOVE')), until(lambda: True), once(lambda: sim('LEFTMOUSE', 'PRESS')), until(lambda: True), once(lambda: sim('LEFTMOUSE', 'RELEASE')), until(lambda: True), + once(lambda: widen(0)), until(lambda: True), once(lambda: widen(1)), until(lambda: True), once(lambda: widen(2)), until(lambda: True), once(lambda: widen(3)), until(lambda: True), once(lambda: widen(4)), until(lambda: True), + once(lambda: collapse_and_scroll(0)), until(lambda: True), once(lambda: collapse_and_scroll(1)), until(lambda: True), once(lambda: collapse_and_scroll(2)), until(lambda: True), once(lambda: collapse_and_scroll(3)), until(lambda: True), until(lambda: True), until(lambda: True), + once(note_shot), once(shoot), +] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def tick(): + global i + if i < len(steps): + try: + if steps[i](): + i += 1 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + i = len(steps) + write() + return 0.5 + try: + cleanup() + except Exception: + R.setdefault("errors", []).append({"step": "cleanup", "error": traceback.format_exc()}) + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/tools/blender/tests/smoke_bake.py b/tools/blender/tests/smoke_bake.py index a51c4601b..52598c754 100644 --- a/tools/blender/tests/smoke_bake.py +++ b/tools/blender/tests/smoke_bake.py @@ -3,7 +3,7 @@ blender --background --factory-startup --python-use-system-env --python tools/blender/tests/smoke_bake.py Blender 5.2 is required: the tolerances below were measured on 5.2.2 (Cycles on the CPU, 256 x 256, one sample). -Environment as smoke_package.py's header says: CULTLIB_PACKAGES and SMOKE_GAME_FOLDER (a folder holding +Environment as smoke_package.py's header says: SMOKE_GAME_FOLDER (a folder holding GameData/Aetheria.cc and the published AetherDb under ModTools, no dotnet). The ship is created under /GameData/Mods/smoke.bake, which this smoke removes when it ends. @@ -39,7 +39,6 @@ import numpy REPO = Path(__file__).resolve().parents[3] FIXTURE = REPO / "tools" / "blender" / "tests" / "fixtures" / "tripo-hull.glb" -PACKAGES = os.environ.get("CULTLIB_PACKAGES") or sys.exit("Set CULTLIB_PACKAGES to CultLib's packages directory") GAME = Path(os.environ.get("SMOKE_GAME_FOLDER") or sys.exit("Set SMOKE_GAME_FOLDER to a folder holding GameData/Aetheria.cc and ModTools/AetherDb")) SHIP_ID = "smoke.bake" COLLECTION = "Smoke Bake" @@ -63,6 +62,12 @@ def run(operator, **arguments): return {"CANCELLED"}, str(exc) +def land(): + """Her two buttons in order, as an operator: Push (dry run), then Apply. Like bpy.ops it raises RuntimeError when either is refused.""" + bpy.ops.aetheria.push_ship() + return bpy.ops.aetheria.apply_ship() + + def pixels(image): flat = numpy.empty(len(image.pixels), dtype=numpy.float32) image.pixels.foreach_get(flat) @@ -312,13 +317,12 @@ def refusal(label, expected, snapshot, offenders=None): def main(): - require(bpy.app.version[:2] == (5, 2), f"This smoke is for Blender 5.2; this is {bpy.app.version_string}") + require(bpy.app.version[:2] in ((5, 2), (5, 3)), f"This smoke is for Blender 5.2 or 5.3; this is {bpy.app.version_string}") require(FIXTURE.is_file() and FIXTURE.stat().st_size > 1_000_000, "tripo-hull.glb is missing or an LFS pointer") bpy.data.objects.remove(bpy.data.objects["Cube"], do_unlink=True) sys.path.insert(0, str(REPO / "tools" / "blender")) addon_utils.enable("aetheria_ships", default_set=True, handle_error=None) import aetheria_ships - aetheria_ships._brokkr_cultlib = lambda context: PACKAGES preferences = bpy.context.preferences.addons["aetheria_ships"].preferences preferences.game_folder = str(GAME) require(preferences.bake_size == 2048 and abs(preferences.bake_cage_extrusion - 0.05) < 1e-6 @@ -513,8 +517,8 @@ def pass_four(aetheria_ships): collider["aetheria.role"], collider["aetheria.id"] = "hull-collider", "collider" bpy.data.collections[COLLECTION].objects.link(collider) collider.parent = bpy.data.objects["Ship Root"] - result, message = run(bpy.ops.aetheria.save_ship_layout) - require(result == {"FINISHED"}, f"Pass 4: Save Layout was refused: {message}") + result, message = run(land) + require(result == {"FINISHED"}, f"Pass 4: Apply was refused: {message}") blend = Path(tempfile.mkdtemp(prefix="aetheria-smoke-bake-")) / "ship.blend" bpy.ops.wm.save_as_mainfile(filepath=str(blend)) bpy.ops.wm.open_mainfile(filepath=str(blend)) diff --git a/tools/blender/tests/smoke_frame.py b/tools/blender/tests/smoke_frame.py index f05650228..4d2b9ab37 100644 --- a/tools/blender/tests/smoke_frame.py +++ b/tools/blender/tests/smoke_frame.py @@ -2,8 +2,8 @@ blender --background --factory-startup --python-use-system-env --python tools/blender/tests/smoke_frame.py -Environment as smoke_package.py's header says: CULTLIB_PACKAGES and SMOKE_GAME_FOLDER (the published AetherDb under its -ModTools, no dotnet), and msgpack importable. The ship is created under /GameData/Mods/smoke.frame, which +Environment as smoke_package.py's header says: SMOKE_GAME_FOLDER (the published AetherDb under its +ModTools, no dotnet). The ship is created under /GameData/Mods/smoke.frame, which this smoke removes when it ends. Pass 1 sends a UV sphere (1 x 0.6 x 0.4, long axis X, off the origin) through New Ship, length 10, like Djinni: nothing @@ -18,7 +18,7 @@ Pass 7 pins the guards that protect an author's files: a Save over an existing s Save leaves the files that were in the folder before, New Ship takes none of the previous ship's hardpoints, and a buffer that belongs to another ship is neither saved nor rasterised. Pass 8 calls the operators with undo=True, which pushes the native undo step in background Blender only for an operator that carries UNDO: Rasterise, Flip Nose and New Ship are -undoable, Save is not. +undoable, Push and Apply are not (Open is). Pass 7b pins what Package does to a ship with a Ship Root: it puts the saved Shape's centre of mass at the world origin (through AetherDb 'centre'), makes the map icon, shield and tractor nobody owns from the render meshes, and never makes a @@ -41,7 +41,6 @@ import bmesh import bpy REPO = Path(__file__).resolve().parents[3] -PACKAGES = os.environ.get("CULTLIB_PACKAGES") or sys.exit("Set CULTLIB_PACKAGES to CultLib's packages directory") SHIP_ID = "smoke.frame" GAME = Path(os.environ.get("SMOKE_GAME_FOLDER") or sys.exit("Set SMOKE_GAME_FOLDER to a folder holding GameData/Aetheria.cc and ModTools/AetherDb")) MODS = GAME / "GameData" / "Mods" @@ -90,6 +89,12 @@ def run(operator): return {"CANCELLED"}, str(exc) +def land(): + """Her two buttons in order, as an operator: Push (dry run), then Apply. Like bpy.ops it raises RuntimeError when either is refused.""" + bpy.ops.aetheria.push_ship() + return bpy.ops.aetheria.apply_ship() + + def require(condition, message): if not condition: raise SystemExit(message) @@ -106,9 +111,10 @@ def refused(operator, expected, what): def saved_layout(path, aetheria_ships): - shape, hardpoints, revision = aetheria_ships.ship_cc.read_layout(path, PACKAGES) - width, height, cells = shape - return width, height, {(i // height, i % height) for i, cell in enumerate(cells) if cell}, hardpoints, revision + opened = aetheria_ships._open(bpy.context, path) + width, height, cells = aetheria_ships._parse_footprint(opened["layout"]["grid"])[0] + rows = [{key: value for key, value in row.items() if key != "element"} for row in opened["layout"]["hardpoints"]] + return width, height, {(i // height, i % height) for i, cell in enumerate(cells) if cell}, rows, opened["versions"] def buffer(scene): @@ -173,12 +179,11 @@ def new_ship(scene, ship_id=SHIP_ID, name="Smoke Frame", reference="Djinni", len def main(): - require(bpy.app.version[:2] == (5, 2), f"This smoke is for Blender 5.2; this is {bpy.app.version_string}") + require(bpy.app.version[:2] in ((5, 2), (5, 3)), f"This smoke is for Blender 5.2 or 5.3; this is {bpy.app.version_string}") bpy.data.objects.remove(bpy.data.objects["Cube"], do_unlink=True) sys.path.insert(0, str(REPO / "tools" / "blender")) addon_utils.enable("aetheria_ships", default_set=True, handle_error=None) import aetheria_ships - aetheria_ships._brokkr_cultlib = lambda context: PACKAGES bpy.context.preferences.addons["aetheria_ships"].preferences.game_folder = str(GAME) require(not (MODS / SHIP_ID).exists(), f"{MODS / SHIP_ID} exists; remove it first") path = str(MODS / SHIP_ID / "ship.cc") @@ -234,7 +239,7 @@ def main(): width, height, cells, hardpoints = buffer(scene) require((width, height) == (6, 10) and hardpoints == 0, f"The buffer is {width}x{height} with {hardpoints} hardpoints") require((0, 0) not in cells and (width // 2, height // 2) in cells, "The ellipse's cells are wrong") - require(not scene.aetheria_layout.revision, "A pending ship's buffer has a revision") + require(not scene.aetheria_layout.versions, "A pending ship's buffer has versions") origin = collection.get("aetheria.grid_origin") require(origin is not None and len(origin) == 4 and (origin[2], origin[3]) == (width, height), "aetheria.grid_origin does not carry the grid's size") @@ -249,7 +254,7 @@ def main(): require(grid.parent == root and grid.display_type == "WIRE", "The Grid is not a wire child of Ship Root") require(len(grid.data.polygons) == len(cells) and len(grid.data.edges) == 4 * width * height, "The Grid does not draw occupied cells as faces and every cell's edges") - refused(bpy.ops.aetheria.load_ship_layout, "Not saved yet", "Load on a pending ship") + refused(bpy.ops.aetheria.open_ship, "Not created yet", "Open on a pending ship") scene, collection = undo_to_before("New Ship") require("aetheria.id" not in collection and "aetheria.pending" not in collection, "Undo left the collection bound") @@ -266,28 +271,28 @@ def main(): # Pass 2: a Save that fails in create or after it leaves nothing behind and tells the author nothing of the input; # the retry succeeds. collection["aetheria.pending"] = ["Smoke Frame", "NoSuchHullXYZ"] - refused(bpy.ops.aetheria.save_ship_layout, "AetherDb refused to create the ship", "Save with an unknown reference hull") + refused(land, "AetherDb refused to create the ship", "Save with an unknown reference hull") require(not (MODS / SHIP_ID).exists(), "A refused create left the ship folder behind") collection["aetheria.pending"] = ["Smoke Frame", "Djinni"] - real = aetheria_ships.replace_layout + real = aetheria_ships._push def failing(*args, **kwargs): - raise ValueError("probe: replace_layout failed") + raise ValueError("probe: push failed") - aetheria_ships.replace_layout = failing + aetheria_ships._push = failing try: - message = refused(bpy.ops.aetheria.save_ship_layout, "probe: replace_layout failed", "Save with a failing write") + message = refused(land, "probe: push failed", "Save with a failing write") finally: - aetheria_ships.replace_layout = real + aetheria_ships._push = real require(not (MODS / SHIP_ID).exists(), "A failed first Save left the ship folder behind") require(collection.get("aetheria.pending") is not None, "A failed first Save cleared aetheria.pending") - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"}, f"The retried Save was refused: {message}") require(collection.get("aetheria.pending") is None, "Save left aetheria.pending set") - width, height, cells, hardpoints, revision = saved_layout(path, aetheria_ships) + width, height, cells, hardpoints, versions = saved_layout(path, aetheria_ships) require((width, height, cells) == buffer(scene)[:3], "The saved .cc is not the buffer") - require(scene.aetheria_layout.revision == revision, "The buffer did not record the saved revision") - require(aetheria_ships.ship_cc.read(path, PACKAGES).ship.body[0] == SHIP_ID, "The saved file is not the ship") + require(json.loads(scene.aetheria_layout.versions) == versions, "The buffer did not record the saved versions") + require(aetheria_ships._open(bpy.context, path)["ship"] == SHIP_ID, "The saved file is not the ship") require(grid_faces() == len(cells), "Save did not redraw the Grid") refused_existing = _second_collection_refused() print("PASS 2 save creates and cleans up ok", refused_existing) @@ -319,13 +324,13 @@ def main(): hp = bpy.context.scene.aetheria_layout.hardpoints[index] hp.mount_id, hp.kind, hp.x, hp.y, hp.footprint = mount, "5", x, y, "#" # Reactor: internal, no anchor hp.armor, hp.firing_arc = 5.0, 90.0 - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"}, f"Save with hardpoints was refused: {message}") rows = saved_layout(path, aetheria_ships)[3] require(len(rows) == 2, "The saved .cc does not hold two hardpoints") result, message = run(bpy.ops.aetheria.rasterise_hull) require(result == {"FINISHED"} and buffer(bpy.context.scene)[3] == 2, "Rasterise dropped the buffer's hardpoints") - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"}, f"The second Save was refused: {message}") require(saved_layout(path, aetheria_ships)[3] == rows, "The second Save changed the hardpoint rows") scene = bpy.context.scene @@ -333,11 +338,11 @@ def main(): state = scene.aetheria_layout cell = next(c for c in state.cells if c.occupied) cell.occupied = False - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"} and grid_faces() == faces - 1, "Toggling a cell and Save did not redraw the Grid") state.new_width = state.width + 1 # a layout resized after the grid was placed: the placement no longer fits it bpy.ops.aetheria.resize_ship_layout() - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"} and bpy.data.objects.get("Grid") is None, "A Grid placed for another size is still drawn after the layout was resized") print("PASS 4 hardpoints and save ok") @@ -413,11 +418,11 @@ def main(): select(bpy.data.objects["Hull"]) saved_digest = digest(path) result, message = run(bpy.ops.aetheria.package_ship) - require(result == {"CANCELLED"} and "Save Layout first" in scene.aetheria_package_report, + require(result == {"CANCELLED"} and "Apply first" in scene.aetheria_package_report, f"Package took an unsaved buffer: {scene.aetheria_package_report}") require(digest(path) == saved_digest and not Path(path).with_name("ship.glb").exists(), "A refused Package wrote the .cc or the GLB") - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"}, f"Save before Package was refused: {message}") preferences.game_folder = "" # the game folder is then found from the bound .cc result, message = run(bpy.ops.aetheria.package_ship) @@ -431,19 +436,6 @@ def main(): require("Source Sphere" not in names and "Grid" not in names, "The GLB holds the Source or the Grid") require("the validator accepted the ship" in report and not any(name in report for name in NAMES_NOT_ECHOED), f"Package's report is not the fixed text: {report}") - # Members a later schema adds to a hardpoint row are not unsaved edits. - real_read_layout = aetheria_ships.read_layout - - def later_schema(*args, **kwargs): - shape, rows, revision = real_read_layout(*args, **kwargs) - return shape, [list(row) + [0] for row in rows], revision - - aetheria_ships.read_layout = later_schema - try: - result, message = run(bpy.ops.aetheria.package_ship) - finally: - aetheria_ships.read_layout = real_read_layout - require(result == {"FINISHED"}, f"A .cc whose rows carry a later schema's members read as unsaved edits: {message}") # A library error is the console's, not the panel's: a directory where ship.glb goes fails the exporter. glb = Path(path).with_name("ship.glb") glb.unlink() @@ -456,17 +448,17 @@ def main(): require(result == {"CANCELLED"} and "The GLB export failed" in report, f"A failed GLB export was not refused: {report}") require("Traceback" not in report and not any(name in report for name in NAMES_NOT_ECHOED), f"A library error reached the report: {report}") - real_visual = aetheria_ships.replace_visual + real_push = aetheria_ships._push def unwritable(*args, **kwargs): raise OSError(f"probe: cannot write {path}") - aetheria_ships.replace_visual = unwritable + aetheria_ships._push = unwritable try: result, message = run(bpy.ops.aetheria.package_ship) report = scene.aetheria_package_report finally: - aetheria_ships.replace_visual = real_visual + aetheria_ships._push = real_push require(result == {"CANCELLED"} and report == "Package failed: Stopped by OSError; see the system console", f"A library error of another type is not reported by its type alone: {report}") result, message = run(bpy.ops.aetheria.package_ship) @@ -509,7 +501,7 @@ def package_frame_pass(aetheria_ships): def save_l(): for index, cell in enumerate(state.cells): # column 0 and row 0 of the grid: an L, not its bounds' middle cell.occupied = index // state.height == 0 or index % state.height == 0 - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"}, f"Save of the L was refused: {message}") def world_state(): @@ -525,7 +517,7 @@ def package_frame_pass(aetheria_ships): # A layout resized after Rasterise and saved no longer matches the grid: refused, and nothing moved or made. state.new_width = state.width + 1 bpy.ops.aetheria.resize_ship_layout() - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"}, f"Save of the resized layout was refused: {message}") unchanged = world_state() select(render) @@ -653,7 +645,7 @@ def package_asymmetric_pass(aetheria_ships): select(arm) result, message = run(bpy.ops.aetheria.rasterise_hull) require(result == {"FINISHED"}, f"Rasterise of the L hull was refused: {message}") - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"}, f"Save of the L hull was refused: {message}") select(arm) run(bpy.ops.aetheria.package_ship) @@ -685,7 +677,7 @@ def package_asymmetric_pass(aetheria_ships): select(source_hull) result, message = run(bpy.ops.aetheria.rasterise_hull) require(result == {"FINISHED"}, f"Rasterise of the Source-only ship was refused: {message}") - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"}, f"Save of the Source-only ship was refused: {message}") select(source_hull) run(bpy.ops.aetheria.package_ship) @@ -769,33 +761,40 @@ def guards_pass(aetheria_ships): hp = bpy.context.scene.aetheria_layout.hardpoints[index] hp.mount_id, hp.kind, hp.x, hp.y, hp.footprint = mount, "5", index + 1, 2, "#" select(hull_a) - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"} and len(saved_layout(path_a, aetheria_ships)[3]) == 2, f"Ship A was not saved: {message}") # A pending ship over an existing ship.cc (what Ctrl+Z past a first Save restores) is refused, and the file stays. saved = digest(path_a) collection_a["aetheria.pending"] = ["Guard A", "Djinni"] - refused(bpy.ops.aetheria.save_ship_layout, "use Bind Ship Collection with that ship.cc, then Load Layout", "Save of a pending ship over its file") + refused(land, "choose that ship.cc and Open", "Save of a pending ship over its file") require(Path(path_a).is_file() and digest(path_a) == saved, "A refused Save deleted or changed the author's ship.cc") del collection_a["aetheria.pending"] # A failed Save of a saved ship (a write that raises, then a .cc that changed since Load) leaves its real ship.cc. - real = aetheria_ships.replace_layout + real = aetheria_ships._push def failing(*args, **kwargs): - raise ValueError("probe: replace_layout failed") + raise ValueError("probe: push failed") - aetheria_ships.replace_layout = failing + result, message = run(bpy.ops.aetheria.push_ship) # the dry run is real; the Apply's write is the one that raises + require(result == {"FINISHED"}, f"Push of a saved ship was refused: {message}") + aetheria_ships._push = failing try: - refused(bpy.ops.aetheria.save_ship_layout, "probe: replace_layout failed", "Save of a saved ship with a failing write") + refused(bpy.ops.aetheria.apply_ship, "probe: push failed", "Apply of a saved ship with a failing write") finally: - aetheria_ships.replace_layout = real + aetheria_ships._push = real require(Path(path_a).is_file() and digest(path_a) == saved, "A failed Save deleted or changed a saved ship's ship.cc") state = bpy.context.scene.aetheria_layout - revision, state.revision = state.revision, "changed outside Blender" - refused(bpy.ops.aetheria.save_ship_layout, "changed since Load", "Save with a stale revision") - state.revision = revision - require(Path(path_a).is_file() and digest(path_a) == saved, "A stale-revision Save deleted or changed the ship.cc") + versions, armor = state.versions, state.hardpoints[0].armor + state.hardpoints[0].armor = armor + 1 # a change, so the push has a write to find stale + state.versions = json.dumps({key: "1999-01-01T00:00:00.0000000+00:00" for key in json.loads(versions)}) + result, message = run(bpy.ops.aetheria.push_ship) + last_line = bpy.context.window_manager.aetheria_push_result.splitlines()[-1] + require(result == {"FINISHED"} and last_line.startswith("stale"), f"Push with a stale version did not finish stale: {message} {last_line!r}") + refused(bpy.ops.aetheria.apply_ship, "The dry run did not pass", "Apply after a stale dry run") + state.versions, state.hardpoints[0].armor = versions, armor + require(Path(path_a).is_file() and digest(path_a) == saved, "A stale-version Save deleted or changed the ship.cc") # New Ship checks everything, the rasterising included, before it changes the collection: a vertical wall has # horizontal extent and no top-down area. @@ -833,15 +832,15 @@ def guards_pass(aetheria_ships): # A pending ship is not packaged, and nothing is written for it. select(hull_b) - refused(bpy.ops.aetheria.package_ship, "Save Layout first", "Package of a pending ship") + refused(bpy.ops.aetheria.package_ship, "Apply first", "Package of a pending ship") require(not (MODS / GUARD_B).exists(), "Package wrote for a pending ship") # A buffer that belongs to ship B is neither saved into ship A's file nor rasterised onto ship A. select(hull_a) - refused(bpy.ops.aetheria.save_ship_layout, "Load this collection's layout before saving", "Save with another ship's buffer") + refused(land, "Open this collection first", "Save with another ship's buffer") require(digest(path_a) == saved, "Save wrote another ship's buffer into ship A's file") before = buffer(bpy.context.scene) - refused(bpy.ops.aetheria.rasterise_hull, "Load this collection's layout first", "Rasterise with another ship's buffer") + refused(bpy.ops.aetheria.rasterise_hull, "Open this collection first", "Rasterise with another ship's buffer") require(buffer(bpy.context.scene) == before, "Rasterise replaced another ship's buffer") # A failed Save leaves what the author had in a Mods/ folder that existed before it; the retry succeeds. @@ -849,26 +848,26 @@ def guards_pass(aetheria_ships): keep = MODS / GUARD_B / "keep.txt" keep.write_text("an author file") select(hull_b) - real = aetheria_ships.replace_layout + real = aetheria_ships._push def failing(*args, **kwargs): - raise ValueError("probe: replace_layout failed") + raise ValueError("probe: push failed") - aetheria_ships.replace_layout = failing + aetheria_ships._push = failing try: - refused(bpy.ops.aetheria.save_ship_layout, "probe: replace_layout failed", "Save with a failing write into an existing folder") + refused(land, "probe: push failed", "Save with a failing write into an existing folder") finally: - aetheria_ships.replace_layout = real + aetheria_ships._push = real require(keep.is_file(), "A failed Save deleted a file the author had in the ship folder") require(not Path(path_b).exists() and collection_b.get("aetheria.pending") is not None, "A failed Save left a half-made ship") - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"} and keep.is_file(), f"The retried Save was refused or took the author's file: {message}") require(saved_layout(path_b, aetheria_ships)[3] == [], "Ship B's file holds hardpoints from ship A") # Another ship's unsaved buffer is no reason to refuse Package: ship A's own file is what it checks. select(hull_a) result, message = run(bpy.ops.aetheria.package_ship) - require("Save Layout first" not in message and "Save Layout first" not in scene.aetheria_package_report, + require("Apply first" not in message and "Apply first" not in scene.aetheria_package_report, "Package read another ship's buffer as ship A's unsaved edits") # A buffer whose cells do not fill its size draws no Grid. @@ -930,36 +929,74 @@ def undo_pass(): select(bpy.data.objects["Undo Hull"]) undoable(bpy.ops.aetheria.flip_nose, "Flip Nose") - # Save pushes no step: one undo after it takes back the step before it, and the file stays. + # Push and Apply push no step: one undo after them takes back the step before, and the file stays. result, message = native(bpy.ops.aetheria.flip_nose) require(result == {"FINISHED"}, f"Flip Nose was refused: {message}") select(bpy.data.objects["Undo Hull"]) flipped = frame() - result, message = native(bpy.ops.aetheria.save_ship_layout) - require(result == {"FINISHED"}, f"Save was refused: {message}") + for operator, what in ((bpy.ops.aetheria.push_ship, "Push"), (bpy.ops.aetheria.apply_ship, "Apply")): + result, message = native(operator) + require(result == {"FINISHED"}, f"{what} was refused: {message}") path = MODS / UNDO_SHIP / "ship.cc" - require(path.is_file(), "Save did not create the file") + require(path.is_file(), "Apply did not create the file") result, _ = run(bpy.ops.ed.undo) - require(result == {"FINISHED"} and frame()[2:] != flipped[2:], "Save is undoable: one undo took back Save and not the step before it") + require(result == {"FINISHED"} and frame()[2:] != flipped[2:], "Push or Apply is undoable: one undo took back more than the step before it") require(path.is_file(), "Undo changed the .cc") - # Ctrl+Z past the first Save leaves the .cc behind an unbound collection: New Ship with the ID is refused with the - # way forward, and following it (Bind, Load, Save) works. + # Ctrl+Z past the first Apply leaves the .cc behind an unbound collection: New Ship with the ID is refused with the + # way forward, and following it (choose ship.cc, Open, Push, Apply) works. Open is one native undo step of its own. for _ in range(12): if not frame()[0]: break - require(run(bpy.ops.ed.undo)[0] == {"FINISHED"}, "ed.undo past the first Save did not run") - require(not frame()[0] and path.is_file(), "Undo past the first Save did not unbind the collection or changed the .cc") + require(run(bpy.ops.ed.undo)[0] == {"FINISHED"}, "ed.undo past the first Apply did not run") + require(not frame()[0] and path.is_file(), "Undo past the first Apply did not unbind the collection or changed the .cc") scene = bpy.context.scene select(bpy.data.objects["Undo Hull"]) scene.aetheria_new_ship_id, scene.aetheria_new_ship_name = UNDO_SHIP, "Undo Ship" scene.aetheria_new_ship_like, scene.aetheria_new_ship_length = "Djinni", 10 - refused(bpy.ops.aetheria.new_ship, "use Bind Ship Collection with its ship.cc, then Load Layout", "New Ship over the ship the first Save made") + refused(bpy.ops.aetheria.new_ship, "choose its ship.cc and Open", "New Ship over the ship the first Apply made") scene.aetheria_ship_cc_path = str(path) - for operator, what in ((bpy.ops.aetheria.bind_ship_collection, "Bind"), (bpy.ops.aetheria.load_ship_layout, "Load"), - (bpy.ops.aetheria.save_ship_layout, "Save")): + undoable(bpy.ops.aetheria.open_ship, "Open") + bpy.context.scene.aetheria_ship_cc_path = str(path) # the undo took the author's field back with the scene + select(bpy.data.objects["Undo Hull"]) + for operator, what in ((bpy.ops.aetheria.open_ship, "Open"), (bpy.ops.aetheria.push_ship, "Push"), + (bpy.ops.aetheria.apply_ship, "Apply")): result, message = run(operator) - require(result == {"FINISHED"}, f"{what} on the way forward after undoing past the first Save was refused: {message}") + require(result == {"FINISHED"}, f"{what} on the way forward after undoing past the first Apply was refused: {message}") + authoring_guards(path) + + +def authoring_guards(path): + """Push writes nothing; Apply lands exactly the dry run it was shown and refuses a scene that moved since.""" + import aetheria_ships + scene, wm = bpy.context.scene, bpy.context.window_manager + state = scene.aetheria_layout + select(bpy.data.objects["Undo Hull"]) + bpy.ops.aetheria.add_ship_hardpoint() + hp = state.hardpoints[0] + hp.mount_id, hp.kind, hp.x, hp.y, hp.footprint, hp.armor = "mount.u", "5", 1, 1, "#", 5.0 + require(run(land)[0] == {"FINISHED"}, "Apply of the first hardpoint was refused") + world = lambda: sorted((obj.name, rounded(obj.matrix_world)) for obj in bpy.data.objects) + before = (digest(path), json.dumps(aetheria_ships._layout_section(state), sort_keys=True), world()) + state.hardpoints[0].armor = 9.0 + edited = json.dumps(aetheria_ships._layout_section(state), sort_keys=True) + result, message = run(bpy.ops.aetheria.push_ship) + require(result == {"FINISHED"}, f"Push was refused: {message}") + lines = wm.aetheria_push_result.splitlines() + require(any("armor" in line and "5" in line and "9" in line for line in lines) and lines[-1].startswith("dry-run"), + f"Push did not show the armor change: {lines}") + require(digest(path) == before[0] and json.dumps(aetheria_ships._layout_section(state), sort_keys=True) == edited + and world() == before[2], "Push wrote the .cc or changed the scene") + state.hardpoints[0].armor = 12.0 # the scene moves after the dry run + refused(bpy.ops.aetheria.apply_ship, "changed since the dry run", "Apply after the scene changed") + require(digest(path) == before[0], "A refused Apply wrote the .cc") + require(run(bpy.ops.aetheria.push_ship)[0] == {"FINISHED"}, "Push again was refused") + result, message = run(bpy.ops.aetheria.apply_ship) + require(result == {"FINISHED"} and digest(path) != before[0], f"Apply of the shown dry run did not land: {message}") + require(not wm.aetheria_push_reviewed, "Apply left the reviewed dry run set") + refused(bpy.ops.aetheria.apply_ship, "Push (dry run) first", "A second Apply") + require(aetheria_ships._open(bpy.context, str(path))["layout"]["hardpoints"][0]["armor"] == 12.0, + "The .cc does not hold the armor Apply landed") def _root_count(): diff --git a/tools/blender/tests/smoke_hull_source.py b/tools/blender/tests/smoke_hull_source.py index a3676b0c7..c1622393e 100644 --- a/tools/blender/tests/smoke_hull_source.py +++ b/tools/blender/tests/smoke_hull_source.py @@ -2,8 +2,8 @@ blender --background --factory-startup --python-use-system-env --python tools/blender/tests/smoke_hull_source.py -Environment: CULTLIB_PACKAGES and SMOKE_GAME_FOLDER as smoke_package.py's header says (the published AetherDb under -ModTools, GameData/Aetheria.cc), msgpack importable, and OpenSCAD 2026.09 or later at SMOKE_OPENSCAD (default: the add-on +Environment: SMOKE_GAME_FOLDER as smoke_package.py's header says (the published AetherDb under +ModTools, GameData/Aetheria.cc) and OpenSCAD 2026.09 or later at SMOKE_OPENSCAD (default: the add-on preference's default). SMOKE_PID_LOG, when set, receives one line per OpenSCAD process. Each ship is created under /GameData/Mods/smoke.hull.*, which this smoke removes when it ends. @@ -59,10 +59,8 @@ from pathlib import Path import addon_utils import bmesh import bpy -import msgpack REPO = Path(__file__).resolve().parents[3] -PACKAGES = os.environ.get("CULTLIB_PACKAGES") or sys.exit("Set CULTLIB_PACKAGES to CultLib's packages directory") GAME = Path(os.environ.get("SMOKE_GAME_FOLDER") or sys.exit("Set SMOKE_GAME_FOLDER to a folder holding GameData/Aetheria.cc and ModTools/AetherDb")) OPENSCAD = os.environ.get("SMOKE_OPENSCAD") PID_LOG = os.environ.get("SMOKE_PID_LOG") @@ -123,6 +121,12 @@ def run(operator): return {"CANCELLED"}, str(exc) +def land(): + """Her two buttons in order, as an operator: Push (dry run), then Apply. Like bpy.ops it raises RuntimeError when either is refused.""" + bpy.ops.aetheria.push_ship() + return bpy.ops.aetheria.apply_ship() + + def approx(a, b, tolerance=1e-3): return all(abs(x - y) <= tolerance for x, y in zip(a, b)) @@ -167,7 +171,9 @@ def make_ship(scene, fixture, ship_id, extent, length, rows): bpy.ops.aetheria.add_ship_hardpoint() hp = state.hardpoints[len(state.hardpoints) - 1] hp.mount_id, hp.kind, hp.x, hp.y, hp.footprint = mount_id, kind, x, y, "#" - result, message = run(bpy.ops.aetheria.save_ship_layout) + if kind == THRUSTER: + hp.rotation = "2" # Reversed: the hull sources' drives sit at the stern, their emitters yawed 180 so the exhaust leaves aft + result, message = run(land) require(result == {"FINISHED"}, f"Save was refused: {message}") package = MODS / ship_id shutil.copy(FIXTURES / fixture / "hull.scad", package / "hull.scad") @@ -321,32 +327,6 @@ def one_hull(scene, number, fixture, ship_id, extent, length, rows, body, palett root.location.x = off_centre require(aetherdb(ship_cc, "product", ship_cc, other, "--remove") == 0, "AetherDb could not remove the other maker's product") - # Record keys compare exactly: a Manufacturer that differs from the language's maker only in case names no Faction. - # AetherDb cannot write one, but a hand-edited ship.cc or a cultcache-py push can, and the guard alone refuses it. - def manufacturer_as(change): - ship_module = sys.modules["aetheria_ships.ship_cc"] - store = ship_module.read(ship_cc, PACKAGES).store - seen = [] - for envelope in store.pull_all(): - if envelope.type == ship_module.PRODUCT_SCHEMA: - values = msgpack.unpackb(envelope.payload, raw=False) - seen.append(values[ship_module.PRODUCT_MANUFACTURER_SLOT]) - values[ship_module.PRODUCT_MANUFACTURER_SLOT] = change(seen[-1]) - store.push(dataclasses.replace(envelope, payload=msgpack.packb(values, use_bin_type=True))) - return seen - - written = manufacturer_as(str.upper) - require(written and all(key.upper() != key for key in written), "The package holds no product with a cased key to rewrite") - select(box) - result, message = run(bpy.ops.aetheria.package_ship) - report = scene.aetheria_package_report - require(result == {"CANCELLED"} and "not by the maker of the hull's faction language" in report, - f"Package took a product whose Manufacturer differs from the maker in case: {report!r} {message!r}") - require(not (package / "ship.glb").exists(), "Package wrote ship.glb for a case-variant Manufacturer") - for echoed in (ship_id, str(GAME), maker, collection["aetheria.hull_maker"], collection["aetheria.hull_maker"].upper()): - require(echoed not in report, f"The refusal echoes an input ({echoed})") - manufacturer_as(lambda _: written.pop(0)) - # Package: the validator accepts the built ship and the GLB holds a node per anchor. mount = bpy.data.objects[roles["weapon-mount"][0]] straight = mount.rotation_euler.z @@ -372,22 +352,22 @@ def one_hull(scene, number, fixture, ship_id, extent, length, rows, body, palett # Schematic lines: Build's, else hers, and never two of hers. packaged = ship_lines(ship_cc) - require(packaged and packaged[0][0] == "silhouette" and packaged[0][5] is True, f"The first line is not the silhouette: {packaged[:1]}") - kit = [row for row in packaged if row[0] != "silhouette"] - drawn = [row[0] for row in packaged] + require(packaged and packaged[0]["layer"] == "silhouette" and packaged[0]["cyclic"] is True, f"The first line is not the silhouette: {packaged[:1]}") + kit = [row for row in packaged if row["layer"] != "silhouette"] + drawn = [row["layer"] for row in packaged] require(drawn[:len(packaged) - len(kit)] == ["silhouette"] * (len(packaged) - len(kit)), "The silhouette contours are not first") - require(all(row[3] is None and row[4] is None and row[1] == "" for row in packaged), + require(all(row["radii"] is None and row["opacities"] is None and row["material"] == "" for row in packaged), "A kit line row is not shaped as Package writes it") require(bool(kit) == (fixture == "zh-ammo-tender"), f"The kit drew {len(kit)} lines for {fixture}") - require(all(approx(row[6], hull_source.LINE_STYLE[row[0]]) for row in packaged), "A line lost its style") - shipped_z = {round(c, 3) for row in packaged for c in row[2][2::3]} + require(all(approx(row["color"], hull_source.LINE_STYLE[row["layer"]]) for row in packaged), "A line lost its style") + shipped_z = {round(c, 3) for row in packaged for c in row["points"][2::3]} require(len(shipped_z) >= 1, "The lines have no height") pencil = grease_pencil(collection, "her lines", [(0, 0, 0), (1, 0, 0), (1, 1, 0)]) select(box) result, message = run(bpy.ops.aetheria.package_ship) require(result == {"FINISHED"}, f"Package refused a ship with one Grease Pencil: {message!r}") hers = ship_lines(ship_cc) - require(len(hers) == 1 and hers[0][0] == "hers" and len(hers[0][2]) == 9, f"Her Grease Pencil did not replace the kit's lines: {hers}") + require(len(hers) == 1 and hers[0]["layer"] == "hers" and len(hers[0]["points"]) == 9, f"Her Grease Pencil did not replace the kit's lines: {hers}") second = grease_pencil(collection, "second lines", [(0, 0, 0), (2, 0, 0)]) before = ship_lines(ship_cc) for operator in (bpy.ops.aetheria.package_ship, bpy.ops.aetheria.capture_ship_lines): @@ -403,7 +383,7 @@ def one_hull(scene, number, fixture, ship_id, extent, length, rows, body, palett require(result == {"FINISHED"} and len(ship_lines(ship_cc)) == len(packaged), f"Without Grease Pencil the kit's lines are back: {message!r}") print(f"PASS {number}.5b the kit's lines ship, her Grease Pencil wins, two are refused") - # Capture's kit branch writes what Package wrote, and also when Save Layout has moved the centre of mass since the last + # Capture's kit branch writes what Package wrote, and also when Apply has moved the centre of mass since the last # Package (here: Ship Root is off the origin), because Capture frames the ship as Package does. shipped = ship_lines(ship_cc) select(box) @@ -586,7 +566,7 @@ def shared_ids_refused(scene, box, collection, ship_id, package, objects, number def check_poses(collection, root, runner): """Every built anchor stands where the hull source says in Ship Root's frame, turned as it says, and the emitter and - radiator meshes are the source's meshes in that frame.""" + radiator meshes are the source's meshes in that frame (an emitter's cut to the side that faces its exhaust).""" inverse = root.matrix_world.inverted() for anchor in hull_source.read_anchors(runner("anchors")[1]): obj = bpy.data.objects[anchor.id] @@ -599,7 +579,10 @@ def check_poses(collection, root, runner): f"{anchor.id} is turned {math.degrees(turn):.1f} degrees, not {anchor.yaw}") if anchor.role in hull_source.MESH_ROLES: made = sorted(tuple(round(c, 3) for c in (inverse @ obj.matrix_world @ v.co)) for v in obj.data.vertices) - wanted = sorted(tuple(round(c, 3) for c in v) for v in hull_source.parse_off(runner(hull_source.MESH_ROLES[anchor.role] + anchor.id)[0]).vertices) + source = hull_source.parse_off(runner(hull_source.MESH_ROLES[anchor.role] + anchor.id)[0]) + if anchor.role == "thruster-emitter": # Build keeps of an emitter only the side facing its exhaust + source = hull_source.exhaust_face(source, anchor.yaw) + wanted = sorted(tuple(round(c, 3) for c in v) for v in source.vertices) require(len(made) == len(wanted) and all(approx(a, b, 2e-3) for a, b in zip(made, wanted)), f"The mesh of {anchor.id} is not the source's mesh in Ship Root's frame") @@ -628,15 +611,16 @@ def clear(collection): def ship_lines(ship_path): - """The ShipAuthoring.SchematicLines rows of a ship.cc, as Package wrote them.""" - return sys.modules["aetheria_ships"].read(ship_path, PACKAGES).ship.body[sys.modules["aetheria_ships"].ship_cc.SCHEMATIC_LINES_SLOT] + """The schematic line rows of a ship.cc as open prints them, as Package wrote them.""" + return sys.modules["aetheria_ships"]._open(bpy.context, ship_path)["lines"] def same_lines(a, b, tolerance=1e-4): - """Whether two SchematicLines slots hold the same rows: layer, cyclic, colour and every point within tolerance.""" + """Whether two line lists hold the same rows: layer, cyclic, colour and every point within tolerance.""" return len(a) == len(b) and all( - x[0] == y[0] and x[5] == y[5] and len(x[2]) == len(y[2]) and approx(x[6], y[6], tolerance) - and all(abs(p - q) <= tolerance for p, q in zip(x[2], y[2])) for x, y in zip(a, b)) + x["layer"] == y["layer"] and x["cyclic"] == y["cyclic"] and len(x["points"]) == len(y["points"]) + and approx(x["color"], y["color"], tolerance) + and all(abs(p - q) <= tolerance for p, q in zip(x["points"], y["points"])) for x, y in zip(a, b)) def grease_pencil(collection, name, points): @@ -826,7 +810,7 @@ def hull_type_gate(scene): fixture, _, extent, length, rows, *_ = HULLS[0] ship_id = "smoke.hull.role" collection, box, package = make_ship(scene, fixture, ship_id, extent, length, rows) - ship_module = sys.modules["aetheria_ships.ship_cc"] + module = sys.modules["aetheria_ships"] path = str(package / "ship.cc") source = package / "hull.scad" original = source.read_text() @@ -841,20 +825,22 @@ def hull_type_gate(scene): sys.modules["aetheria_ships"].hull_source.build = recorded try: - require(ship_module.read_hull_type(path, PACKAGES) == "Ship", "New Ship did not write a Ship hull") + require(module._open(bpy.context, path)["hullType"] == "Ship", "New Ship did not write a Ship hull") select(box) result, message = run(bpy.ops.aetheria.build_hull_source) require(result == {"CANCELLED"} and "the body's proportions lie inside the language's ranges" in message, f"A Ship far wider than its language allows was built: {message!r}") print("PASS 5.1 a body wider than the language's ships is refused as Ship, on proportion") - store = ship_module.read(path, PACKAGES).store - for envelope in store.pull_all(): - if envelope.type == ship_module.HULL_SCHEMA: - values = msgpack.unpackb(envelope.payload, raw=False) - values[ship_module.HULL_TYPE_SLOT] = 1 - store.push(dataclasses.replace(envelope, payload=msgpack.packb(values, use_bin_type=True))) - require(ship_module.read_hull_type(path, PACKAGES) == "Station", "The pushed HullType did not read back as Station") + # The add-on's one hull-type reader says Station for this ship: the rest of Build reads it from there. + real_open = module._open + + def station(context, ship_path): + opened = real_open(context, ship_path) + opened["hullType"] = "Station" + return opened + + module._open = station select(box) result, message = run(bpy.ops.aetheria.build_hull_source) names = [c.name for c in judged[-1].checks] @@ -875,19 +861,19 @@ def hull_type_gate(scene): print("PASS 5.3 a Station 70 m wide is refused on the layout grid, not on proportion") finally: sys.modules["aetheria_ships"].hull_source.build = real + module._open = real_open print("HULL_TYPE_GATE_OK", flush=True) return collection def main(): - require(bpy.app.version[:2] == (5, 2), f"This smoke is for Blender 5.2; this is {bpy.app.version_string}") + require(bpy.app.version[:2] in ((5, 2), (5, 3)), f"This smoke is for Blender 5.2 or 5.3; this is {bpy.app.version_string}") bpy.data.objects.remove(bpy.data.objects["Cube"], do_unlink=True) sys.path.insert(0, str(REPO / "tools" / "blender")) addon_utils.enable("aetheria_ships", default_set=True, handle_error=None) import aetheria_ships global hull_source, EXECUTABLE hull_source = aetheria_ships.hull_source - aetheria_ships._brokkr_cultlib = lambda context: PACKAGES preferences = bpy.context.preferences.addons["aetheria_ships"].preferences preferences.game_folder = str(GAME) if OPENSCAD: diff --git a/tools/blender/tests/smoke_mounts.py b/tools/blender/tests/smoke_mounts.py index 53418abb1..1119bf54c 100644 --- a/tools/blender/tests/smoke_mounts.py +++ b/tools/blender/tests/smoke_mounts.py @@ -3,8 +3,8 @@ Mount, and that Package moves nothing of them. blender --background --factory-startup --python-use-system-env --python tools/blender/tests/smoke_mounts.py -Environment as smoke_package.py's header says: CULTLIB_PACKAGES and SMOKE_GAME_FOLDER (the published AetherDb under its -ModTools, no dotnet), and msgpack importable. The ship is created under /GameData/Mods/smoke.mounts, which +Environment as smoke_package.py's header says: SMOKE_GAME_FOLDER (the published AetherDb under its +ModTools, no dotnet). The ship is created under /GameData/Mods/smoke.mounts, which this smoke removes when it ends. The schematic and the model are separate spaces (ruling schematic-and-model-are-separate-spaces): a row's Position is @@ -34,7 +34,6 @@ import bpy from mathutils import Vector REPO = Path(__file__).resolve().parents[3] -PACKAGES = os.environ.get("CULTLIB_PACKAGES") or sys.exit("Set CULTLIB_PACKAGES to CultLib's packages directory") SHIP_ID = "smoke.mounts" ODD_ID = "smoke.mounts.odd" # (ship id, length in cells, the source sphere's Y scale, wide, grid width parity) of passes 6 to 8; the id's mod directory @@ -69,6 +68,14 @@ def quad(name, size): return mesh +def exhaust_quad(name, size): + """A thruster emitter for a hardpoint of Rotation None: an upright quad whose one side faces the nose (-Y), the way its exhaust leaves.""" + mesh = bpy.data.meshes.new(name) + half = size / 2 + mesh.from_pydata([(-half, 0, -half), (half, 0, -half), (half, 0, half), (-half, 0, half)], [], [(0, 1, 2, 3)]) + return mesh + + def tetrahedron(name): mesh = bpy.data.meshes.new(name) mesh.from_pydata([(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)], [], [(0, 2, 1), (0, 1, 3), (0, 3, 2), (1, 2, 3)]) @@ -83,6 +90,12 @@ def run(operator): return {"CANCELLED"}, str(exc) +def land(): + """Her two buttons in order, as an operator: Push (dry run), then Apply. Like bpy.ops it raises RuntimeError when either is refused.""" + bpy.ops.aetheria.push_ship() + return bpy.ops.aetheria.apply_ship() + + def require(condition, message): if not condition: raise SystemExit(message) @@ -258,12 +271,11 @@ def mirror_matrix(scene, root, sphere): def main(): - require(bpy.app.version[:2] == (5, 2), f"This smoke is for Blender 5.2; this is {bpy.app.version_string}") + require(bpy.app.version[:2] in ((5, 2), (5, 3)), f"This smoke is for Blender 5.2 or 5.3; this is {bpy.app.version_string}") bpy.data.objects.remove(bpy.data.objects["Cube"], do_unlink=True) sys.path.insert(0, str(REPO / "tools" / "blender")) addon_utils.enable("aetheria_ships", default_set=True, handle_error=None) import aetheria_ships - aetheria_ships._brokkr_cultlib = lambda context: PACKAGES bpy.context.preferences.addons["aetheria_ships"].preferences.game_folder = str(GAME) require(not (MODS / SHIP_ID).exists(), f"{MODS / SHIP_ID} exists; remove it first") path = str(MODS / SHIP_ID / "ship.cc") @@ -294,13 +306,13 @@ def main(): tag(new_object(collection, "Hull Collider", tetrahedron("Hull Collider"), parent=root), "hull-collider", "collider") tag(new_object(collection, "Shield", None, parent=root), "shield", "shield") tag(new_object(collection, "Tractor", None, (0, 2, 0), root), "tractor", "tractor") - disc = new_object(collection, "Thruster", quad("Thruster", 0.4), (0, 8, 0), root) + disc = new_object(collection, "Thruster", exhaust_quad("Thruster", 0.4), (0, 8, 0), root) tag(disc, "thruster-emitter", "thruster") for mount, kind, x, y in (("thruster", "3", 2, 0), ("reactor.a", "5", 2, 2)): bpy.ops.aetheria.add_ship_hardpoint() hp = state.hardpoints[len(state.hardpoints) - 1] hp.mount_id, hp.kind, hp.x, hp.y, hp.footprint = mount, kind, x, y, "#" - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"}, f"Save was refused: {message}") reactor_before = row(scene, "reactor.a") select(sphere) @@ -373,7 +385,7 @@ def main(): # Pass 2: Package; the GLB's muzzle nodes face outboard. select(sphere) - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"}, f"Save before Package was refused: {message}") result, message = run(bpy.ops.aetheria.package_ship) report = scene.aetheria_package_report @@ -395,7 +407,7 @@ def main(): if hp.mount_id == "weapon.2": hp.rotation = str(REVERSED) select(sphere) - require(run(bpy.ops.aetheria.save_ship_layout)[0] == {"FINISHED"}, "Save before the second Package was refused") + require(run(land)[0] == {"FINISHED"}, "Save before the second Package was refused") authored = rows(scene) result, message = run(bpy.ops.aetheria.package_ship) report = scene.aetheria_package_report @@ -405,11 +417,26 @@ def main(): require(row(scene, "weapon.2")[3] == REVERSED and row(scene, "reactor.a") == reactor_before, "Package changed a Rotation or an internal row") require(abs(gun.rotation_euler.z - 0.3) < 1e-6, f"Package turned a hand-set yaw: {gun.rotation_euler.z}") require(abs(twin.rotation_euler.z - twin_yaw) < 1e-6, f"Package turned a mount to its row's Rotation: {twin.rotation_euler.z}") - saved = aetheria_ships.ship_cc.read_layout(path, PACKAGES)[1] - by_mount = {fields["Transform"]: fields for fields in map(aetheria_ships.ship_cc.decode_hardpoint, saved)} - require(tuple(by_mount["weapon.1"]["Position"]) == (4, 5) and tuple(by_mount["weapon.2"]["Position"]) == (1, 5) - and by_mount["weapon.2"]["Rotation"] == REVERSED and tuple(by_mount["reactor.a"]["Position"]) == (2, 2), + def saved_rows(): + return {fields["mount"]: fields for fields in aetheria_ships._open(bpy.context, path)["layout"]["hardpoints"]} + + by_mount = saved_rows() + require(tuple(by_mount["weapon.1"]["cell"]) == (4, 5) and tuple(by_mount["weapon.2"]["cell"]) == (1, 5) + and by_mount["weapon.2"]["rotation"] == REVERSED and tuple(by_mount["reactor.a"]["cell"]) == (2, 2), "The .cc does not hold what the author left") + # An element id is carried: after Load, a row moved and saved stands at its new cell under the same element. + select(sphere) + require(run(bpy.ops.aetheria.open_ship)[0] == {"FINISHED"}, "Open before the element check was refused") + element = saved_rows()["weapon.1"]["element"] + require(element, "Open names no element for a saved hardpoint") + moved = next(hp for hp in scene.aetheria_layout.hardpoints if hp.mount_id == "weapon.1") + require(moved.element == element, "Open did not carry the element") + moved.x -= 1 + require(run(land)[0] == {"FINISHED"}, "Save of a moved row was refused") + after = saved_rows()["weapon.1"] + require(after["element"] == element and tuple(after["cell"]) == (3, 5), "A moved row did not keep its element") + moved.x += 1 + require(run(land)[0] == {"FINISHED"}, "Save of the restored row was refused") require([r for r in rows(scene) if r in pair_rows] == pair_rows, "The second Package moved a mirrored pair") print("PASS 3 package moves nothing ok") @@ -439,7 +466,7 @@ def matrix_pass(scene, previous, ship_id, length, y_scale, wide, parity): scene.aetheria_new_ship_like, scene.aetheria_new_ship_length = "Djinni", length result, message = run(bpy.ops.aetheria.new_ship) require(result == {"FINISHED"}, f"New Ship ({ship_id}) was refused: {message}") - result, message = run(bpy.ops.aetheria.save_ship_layout) + result, message = run(land) require(result == {"FINISHED"}, f"Save ({ship_id}) was refused: {message}") width = scene.aetheria_layout.width require(width % 2 == parity and (width >= 10 or not wide), f"The {ship_id} grid is {width} wide") diff --git a/tools/blender/tests/smoke_package.py b/tools/blender/tests/smoke_package.py index 886c349e2..2bebb014c 100644 --- a/tools/blender/tests/smoke_package.py +++ b/tools/blender/tests/smoke_package.py @@ -2,7 +2,7 @@ blender --background --factory-startup --python-use-system-env --python tools/blender/tests/smoke_package.py -Environment: CULTLIB_PACKAGES (CultLib's packages directory, as test_ship_cc.py) and SMOKE_GAME_FOLDER, a folder holding +Environment: SMOKE_GAME_FOLDER, a folder holding GameData/Aetheria.cc and the published AetherDb under ModTools (AetherDb.exe on Windows), which the smoke sets as the add-on's Game folder. No dotnet is needed: the add-on runs the published tool and nothing else. SMOKE_MODS names the mods directory to write into (default: a new temp directory); the package is left there so the @@ -36,7 +36,6 @@ import bpy REPO = Path(__file__).resolve().parents[3] GAME = Path(os.environ.get("SMOKE_GAME_FOLDER") or sys.exit("Set SMOKE_GAME_FOLDER to a folder holding GameData/Aetheria.cc and ModTools/AetherDb")) -PACKAGES = os.environ.get("CULTLIB_PACKAGES") or sys.exit("Set CULTLIB_PACKAGES to CultLib's packages directory") SHIP_ID = "smoke.gale" @@ -53,6 +52,14 @@ def quad(name, size=1.0): return mesh +def exhaust_quad(name, size): + """A thruster emitter for a hardpoint of Rotation None: an upright quad whose one side faces the nose (-Y), the way its exhaust leaves.""" + mesh = bpy.data.meshes.new(name) + half = size / 2 + mesh.from_pydata([(-half, 0, -half), (half, 0, -half), (half, 0, half), (-half, 0, half)], [], [(0, 1, 2, 3)]) + return mesh + + def tagged(collection, name, data, role=None, anchor_id=None, location=(0, 0, 0), parent=None): obj = bpy.data.objects.new(name, data) obj.location = location @@ -215,7 +222,7 @@ def bind(ship, label): if key in ship: del ship[key] try: - result = bpy.ops.aetheria.bind_ship_collection() + result = bpy.ops.aetheria.open_ship() except RuntimeError: result = {"CANCELLED"} stored = ship.get("aetheria.ship_cc") @@ -321,8 +328,6 @@ def main(): sys.path.insert(0, str(REPO / "tools" / "blender")) addon_utils.enable("aetheria_ships", default_set=True, handle_error=None) import aetheria_ships - # Brokkr is the Blender host's CultLib path provider and is not installed in a factory-startup Blender. - aetheria_ships._brokkr_cultlib = lambda context: PACKAGES bpy.context.preferences.addons["aetheria_ships"].preferences.game_folder = str(GAME) mods = Path(os.environ.get("SMOKE_MODS") or tempfile.mkdtemp(prefix="aetheria-smoke-mods-")) @@ -345,7 +350,7 @@ def main(): tagged(ship, "Hull Collider", tetrahedron("Hull Collider"), "hull-collider", "collider") tagged(ship, "Shield", None, "shield", "shield") tagged(ship, "Tractor", None, "tractor", "tractor", (0, 2, 0)) - disc = tagged(ship, "Thruster", quad("Thruster", 0.4), "thruster-emitter", "thruster", (0, -1, 0)) + disc = tagged(ship, "Thruster", exhaust_quad("Thruster", 0.4), "thruster-emitter", "thruster", (0, -1, 0)) gun = tagged(ship, "Gun", None, "weapon-mount", "gun", (1, 0, 0)) tagged(ship, "Gun Muzzle", None, "weapon-muzzle", "gun.muzzle", (0, 0.5, 0), parent=gun) tagged(ship, "Radiator", quad("Radiator", 0.5), "radiator-mesh", "radiator", (-1, 0, 0)) @@ -354,16 +359,15 @@ def main(): bpy.context.view_layer.objects.active = hull bind_cases(ship, path, mods) - ship_cc = aetheria_ships.ship_cc - _, _, revision = ship_cc.read_layout(path, PACKAGES) - def hardpoint(kind, x, mount): - return ship_cc.encode_hardpoint(Type=ship_cc.HARDPOINT_TYPE_NAMES.index(kind), Position=[x, 0], - Shape=[[1, 1, [True]]], Transform=mount, Rotation=0, Armor=0.0, FiringArc=0.0) + return {"element": "", "mount": mount, "kind": kind, "cell": [x, 0], "footprint": "#", "rotation": 0, + "armor": 0.0, "arc": 0.0} - ship_cc.replace_layout(path, PACKAGES, SHIP_ID, revision, [4, 1, [True] * 4], [ - hardpoint("Thruster", 0, "thruster"), hardpoint("Radiator", 1, "radiator"), - hardpoint("Energy", 2, "gun"), hardpoint("Reactor", 3, "reactor")]) + aetheria_ships._push(bpy.context, path, { + "ship": SHIP_ID, "versions": aetheria_ships._open(bpy.context, path)["versions"], + "layout": {"grid": "####", "hardpoints": [ + hardpoint("Thruster", 0, "thruster"), hardpoint("Radiator", 1, "radiator"), + hardpoint("Energy", 2, "gun"), hardpoint("Reactor", 3, "reactor")]}}, apply=True) objects_before = sorted(obj.name for obj in bpy.data.objects) result, report = package(aetheria_ships) diff --git a/tools/blender/tests/test_brokkr_actions.py b/tools/blender/tests/test_brokkr_actions.py new file mode 100644 index 000000000..9dc48dd3f --- /dev/null +++ b/tools/blender/tests/test_brokkr_actions.py @@ -0,0 +1,40 @@ +"""Blender-free test of aetheria_ships/brokkr_actions.json, the host file Brokkr reads: agents may open and dry-run a +ship; every operator that writes game data or applies lines and visuals is absent (human-only is absence). + + python -m unittest discover -s tools/blender/tests +""" + +import json +import re +import unittest +from pathlib import Path + +FILE = Path(__file__).resolve().parents[1] / "aetheria_ships" / "brokkr_actions.json" + + +class HostActionFileTests(unittest.TestCase): + def setUp(self): + self.document = json.loads(FILE.read_text(encoding="utf-8")) + self.rows = {row["name"]: row for row in self.document["actions"]} + + def test_lists_exactly_open_and_push(self): + self.assertEqual("brokkr.blender.host_actions.v0", self.document["schema"]) + self.assertEqual({"aetheria.open_ship", "aetheria.push_ship"}, set(self.rows)) + self.assertEqual(2, len(self.document["actions"])) + + def test_push_changes_nothing_and_returns_its_result_property(self): + push = self.rows["aetheria.push_ship"] + self.assertIs(False, push["changesScene"]) + self.assertEqual("aetheria_push_result", push["result"]) + + def test_open_is_one_undo_step_refused_in_edit_mode(self): + opened = self.rows["aetheria.open_ship"] + self.assertIs(True, opened["changesScene"]) + self.assertIs(False, opened["editModeSafe"]) + + def test_no_row_names_a_human_only_operator(self): + self.assertIsNone(re.search(r"apply_ship|package_ship|capture_ship_lines|new_ship|bind_ship", FILE.read_text(encoding="utf-8"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/blender/tests/test_hull_source.py b/tools/blender/tests/test_hull_source.py index e77ec11b2..ce78c313f 100644 --- a/tools/blender/tests/test_hull_source.py +++ b/tools/blender/tests/test_hull_source.py @@ -28,7 +28,7 @@ SECRET = "SECRET-NAME-7" # a value a hull source supplies and no refusal may ec def box(x0, x1, y0, y1, z0, z1): """An OFF text for an axis-aligned box: 8 vertices, 6 quads (12 triangles once fanned).""" v = [(x, y, z) for z in (z0, z1) for y in (y0, y1) for x in (x0, x1)] - quads = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)] + quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)] # outward, counter-clockwise from outside rows = ["OFF", "8 6 0"] + [f"{x} {y} {z}" for x, y, z in v] + [f"4 {a} {b} {c} {d}" for a, b, c, d in quads] return "\n".join(rows) @@ -339,9 +339,9 @@ class JudgementTests(unittest.TestCase): self.assertEqual(fixture.failed(), ["the triangle count lies inside the brief's budget"], budget) def test_the_budget_counts_the_triangles_of_the_emitter_meshes_too(self): - # 12 + 12 triangles of zones, 12 of the emitter: a budget of 30 holds without the emitter and not with it + # 12 + 12 triangles of zones, 2 of the emitter (its exhaust-facing side): a budget of 25 holds without it and not with it fixture = Fixture() - fixture.parts["brief"] = ("", brief(triangles=(10, 30))) + fixture.parts["brief"] = ("", brief(triangles=(10, 25))) self.assertEqual(fixture.failed(), ["the triangle count lies inside the brief's budget"]) def test_the_length_is_a_range_with_two_ends(self): @@ -385,6 +385,47 @@ class JudgementTests(unittest.TestCase): fixture.parts["emit:Th.A"] = ("", "") self.assertEqual(fixture.failed(), ["every emitter and radiator anchor has a mesh"]) + @staticmethod + def _normals(mesh): + """The unit outward normal of each triangle.""" + out = [] + for a, b, c in mesh.triangles: + pa, pb, pc = (mesh.vertices[i] for i in (a, b, c)) + u, v = [pb[i] - pa[i] for i in range(3)], [pc[i] - pa[i] for i in range(3)] + n = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) + length = sum(x * x for x in n) ** 0.5 + out.append(tuple(round(x / length) for x in n)) + return out + + def test_an_emitter_keeps_only_the_side_that_faces_its_exhaust(self): + # The thin box the hull source draws is closed; its exhaust leaves the way the anchor faces (yaw 180 aft, +Y; yaw 90 + # port, +X; yaw 0 the nose, -Y), and only the triangles facing that way are the emitter. + for yaw, thin, facing in ((180, (5, 5.1, "y"), (0, 1, 0)), (0, (5, 5.1, "y"), (0, -1, 0)), (90, (5, 5.1, "x"), (1, 0, 0))): + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", ["Gun.A", "weapon-mount", [0, 0, 3], 0, ""]) + + echo("anchor", ["Gun.A.muzzle", "weapon-muzzle", [0, -3, 3], 0, "Gun.A"]) + + echo("anchor", ["Th.A", "thruster-emitter", [1, 5, 1], yaw, ""])) + fixture.parts["emit:Th.A"] = (box(5, 5.1, 1, 2, 0.5, 1.5) if thin[2] == "x" else box(0.5, 1.5, 5, 5.1, 0.5, 1.5), "") + mesh = fixture.build().anchor_meshes["Th.A"] + self.assertEqual(len(mesh.triangles), 2, yaw) + self.assertEqual(set(self._normals(mesh)), {facing}, yaw) + + def test_an_emitter_turned_off_a_quarter_turn_is_refused(self): + # The gate knows four directions (a hardpoint Rotation); an emitter yawed 45 degrees has none, so it is not rounded. + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", ["Gun.A", "weapon-mount", [0, 0, 3], 0, ""]) + + echo("anchor", ["Gun.A.muzzle", "weapon-muzzle", [0, -3, 3], 0, "Gun.A"]) + + echo("anchor", ["Th.A", "thruster-emitter", [1, 5, 1], 45, ""])) + with self.assertRaises(hs.HullSourceError): + fixture.build() + + def test_an_emitter_with_no_side_facing_its_exhaust_is_refused(self): + # A single quad that faces the push, not the exhaust, has nothing left once the wrong side is dropped. + fixture = Fixture() + quad_toward_push = "OFF\n4 1 0\n0.5 5 0.5\n1.5 5 0.5\n1.5 5 1.5\n0.5 5 1.5\n4 0 1 2 3" # normal -Y, anchor exhaust +Y + fixture.parts["emit:Th.A"] = (quad_toward_push, "") + self.assertEqual(fixture.failed(), ["every emitter and radiator anchor has a mesh"]) + def test_the_collider_zone_is_the_languages_body(self): self.assertEqual(Fixture().build().body_zone, "primary") diff --git a/tools/blender/tests/test_package_hull.py b/tools/blender/tests/test_package_hull.py new file mode 100644 index 000000000..8b79147e5 --- /dev/null +++ b/tools/blender/tests/test_package_hull.py @@ -0,0 +1,203 @@ +"""Blender-free tests for package_hull.py: manifest refusals and place(). The Blender half runs on the fixture manifest +(fixtures/hulls/zh-ammo-tender/package.json) in the Starfire job, not here. + + python -m unittest discover -s tools/blender/tests -p "test_package_hull.py" + +package_hull is loaded by path; its bpy imports are inside package(), and its driver block runs only as __main__. +""" + +import importlib.util +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +_spec = importlib.util.spec_from_file_location( + "package_hull", Path(__file__).resolve().parents[1] / "package_hull.py") +ph = importlib.util.module_from_spec(_spec) +sys.modules["package_hull"] = ph +_spec.loader.exec_module(ph) + +FIXTURE = Path(__file__).resolve().parent / "fixtures" / "hulls" / "zh-ammo-tender" / "package.json" + + +class ManifestTests(unittest.TestCase): + def load(self, edit=None): + manifest = json.loads(FIXTURE.read_text(encoding="utf-8")) + if edit: + edit(manifest) + with tempfile.TemporaryDirectory() as folder: + (Path(folder) / "hull.scad").write_text("// hull\n", encoding="utf-8") + path = Path(folder) / "package.json" + path.write_text(json.dumps(manifest), encoding="utf-8") + return ph.load_manifest(path) + + def refused(self, edit, *words): + with self.assertRaises(ph.Refused) as caught: + self.load(edit) + for word in words: + self.assertIn(word, str(caught.exception)) + + def test_the_fixture_manifest_loads(self): + manifest = self.load() + self.assertEqual(len(manifest["rows"]), 6) + self.assertEqual(ph.rows_of(manifest)[0], ("Gun.D", "Ballistic", (2, 3), "#", 0, 20, 90)) + + def test_a_station_kind_loads_and_must_be_text(self): + self.assertEqual(self.load(lambda m: m.update(kind="depot"))["kind"], "depot") + for bad in (7, "", None): + self.refused(lambda m, bad=bad: m.update(kind=bad), "kind") + + def test_a_missing_key_is_named(self): + self.refused(lambda m: m.pop("price"), "missing", "price") + self.refused(lambda m: m["stats"].pop("drag"), "stats", "drag") + self.refused(lambda m: m["rows"][2].pop("arc"), "row 2", "arc") + + def test_an_unknown_key_is_named(self): + self.refused(lambda m: m.update(nakovalnya=1), "unknown", "nakovalnya") + self.refused(lambda m: m["stats"].update(speed=1), "stats", "speed") + self.refused(lambda m: m["rows"][0].update(colour="red"), "row 0", "colour") + + def test_an_unknown_kind_is_named(self): + self.refused(lambda m: m["rows"][1].update(kind="THRUSTER"), "Th.L", "THRUSTER") + + def test_a_malformed_footprint_is_named(self): + for bad in ("", "#.#/#", "x", "..", "##/#X"): + self.refused(lambda m, bad=bad: m["rows"][0].update(footprint=bad), "Gun.D", "footprint") + + def test_a_duplicate_row_id_is_named(self): + self.refused(lambda m: m["rows"][4].update(id="Ra.L"), "Ra.L", "duplicate") + + def test_a_missing_hull_is_named(self): + self.refused(lambda m: m.update(hull="absent.scad"), "absent.scad") + + +class PlaceTests(unittest.TestCase): + ROW = ("Gun.D", "Ballistic", (2, 2), "##/##", 0, 20, 90) + + def test_a_fitting_row_keeps_its_cell(self): + placed = ph.place([self.ROW], 6, 6, lambda x, y: True) + self.assertEqual(placed[0][2], (2, 2)) + + def refused(self, rows, width, height, occupied, *words): + with self.assertRaises(ph.Refused) as caught: + ph.place(rows, width, height, occupied) + for word in words: + self.assertIn(word, str(caught.exception)) + + def test_a_row_off_the_raster_is_refused_not_moved(self): + self.refused([("Gun.D", "Ballistic", (50, 50), "#", 0, 20, 90)], 6, 6, lambda x, y: True, "Gun.D", "off the 6x6 raster") + self.refused([("Gun.D", "Ballistic", (5, 5), "##/##", 0, 20, 90)], 6, 6, lambda x, y: True, "Gun.D", "off the 6x6 raster") + + def test_a_row_outside_the_shape_is_refused_not_moved(self): + self.refused([self.ROW], 6, 6, lambda x, y: x < 2, "Gun.D", "outside the hull shape") + + def test_a_row_overlapping_an_earlier_one_is_refused_not_moved(self): + second = ("Gun.E", "Ballistic", (3, 3), "#", 0, 20, 90) + self.refused([self.ROW, second], 6, 6, lambda x, y: True, "Gun.E", "overlaps") + + +class SwapTests(unittest.TestCase): + """The all-or-nothing run, through main() with the Blender half replaced by one that writes into the package and then fails + or finishes. The existing package must be exactly as it was after any failure.""" + + def setUp(self): + self.work = tempfile.TemporaryDirectory() + self.addCleanup(self.work.cleanup) + root = Path(self.work.name) + self.game = root / "game" + self.manifest = root / "package.json" + data = json.loads(FIXTURE.read_text(encoding="utf-8")) + self.id = data["id"] + self.manifest.write_text(json.dumps(data), encoding="utf-8") + (root / data["hull"]).write_text("// hull" + chr(10), encoding="utf-8") + self.package_dir = self.game / "GameData" / "Mods" / self.id + old = mock.patch.dict(os.environ, {"GAME_FOLDER": str(self.game), "OPENSCAD": "x"}) + old.start() + self.addCleanup(old.stop) + self.real = ph.package + self.addCleanup(setattr, ph, "package", self.real) + + def existing(self): + self.package_dir.mkdir(parents=True) + (self.package_dir / "ship.cc").write_bytes(b"studio edits") + (self.package_dir / "ship.glb").write_bytes(b"model") + + def digest(self): + files = sorted(self.game.rglob("*")) if self.game.exists() else [] + return [(str(p.relative_to(self.game)), p.read_bytes() if p.is_file() else None) for p in files] + + def builder(self, then): + def package(manifest, manifest_dir, game, openscad): + self.package_dir.mkdir(parents=True, exist_ok=True) + (self.package_dir / "ship.cc").write_bytes(b"derived") + (self.package_dir / "hull.scad").write_bytes(b"half built") + then() + ph.package = package + + def run_entry(self, *flags): + import io + from contextlib import redirect_stderr, redirect_stdout + with redirect_stdout(io.StringIO()) as out, redirect_stderr(io.StringIO()): + code = ph.entry([str(self.manifest), *flags]) + return code, out.getvalue() + + def fail(self): + raise ph.Refused("No cell fits") + + def test_a_failed_replace_leaves_the_package_exactly_as_it_was(self): + self.existing() + before = self.digest() + self.builder(self.fail) + code, out = self.run_entry("--replace") + self.assertEqual(code, 1) + self.assertIn("PACKAGE_FAILED: No cell fits", out) + self.assertEqual(self.digest(), before) + + def test_a_crash_in_a_replace_leaves_the_package_exactly_as_it_was(self): + self.existing() + before = self.digest() + self.builder(lambda: 1 / 0) + code, out = self.run_entry("--replace") + self.assertEqual(code, 1) + self.assertTrue(out.rstrip().endswith("PACKAGE_FAILED")) + self.assertEqual(self.digest(), before) + + def test_a_successful_replace_swaps_and_leaves_no_backup(self): + self.existing() + self.builder(lambda: None) + code, out = self.run_entry("--replace") + self.assertEqual((code, out.rstrip().endswith("PACKAGE_OK")), (0, True)) + self.assertEqual((self.package_dir / "ship.cc").read_bytes(), b"derived") + self.assertEqual(sorted(p.name for p in self.game.iterdir()), ["GameData"]) + + def test_an_existing_package_without_replace_is_refused_untouched(self): + self.existing() + before = self.digest() + self.builder(lambda: self.fail()) + code, out = self.run_entry() + self.assertEqual(code, 1) + self.assertIn("--replace", out) + self.assertEqual(self.digest(), before) + + def test_a_failed_first_run_leaves_no_package(self): + self.builder(self.fail) + code, _ = self.run_entry() + self.assertEqual(code, 1) + self.assertFalse(self.package_dir.exists()) + + def test_a_manifest_off_the_raster_exits_1(self): + def rows(): + ph.place([("Gun.D", "Ballistic", (50, 50), "#", 0, 20, 90)], 6, 6, lambda x, y: True) + self.builder(rows) + code, out = self.run_entry() + self.assertEqual(code, 1) + self.assertIn("PACKAGE_FAILED: row Gun.D", out) + self.assertFalse(self.package_dir.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/blender/tests/test_ship_cc.py b/tools/blender/tests/test_ship_cc.py index 0b4da5677..4ccb32aa4 100644 --- a/tools/blender/tests/test_ship_cc.py +++ b/tools/blender/tests/test_ship_cc.py @@ -1,791 +1,21 @@ -"""Blender-free tests for aetheria_ships/ship_cc.py, the Python view of a ship file's HullData and ShipAuthoring records. +"""Blender-free tests for aetheria_ships/ship_cc.py: the ship id rule and Grease Pencil capture. -Run with CultLib's cultcache-py and msgpack importable: + python -m unittest discover -s tools/blender/tests - CULTLIB_PACKAGES=/packages python -m unittest discover -s tools/blender/tests - -ship_cc is loaded by path because the package __init__ imports bpy. The record layout the tests build comes from -ship_cc's own slot constants; ShipSchemaPinTests (C#) pins those constants to the C# [Key] attributes. +ship_cc is loaded by path because the package __init__ imports bpy. ShipSchemaPinTests (C#) pins the ship id rule and +the enum names to the C# types. """ -import dataclasses import importlib.util -import os -import shutil -import sys -import tempfile import unittest -from unittest import mock -from datetime import datetime from pathlib import Path from types import SimpleNamespace -PACKAGES = os.environ.get("CULTLIB_PACKAGES") -if not PACKAGES: - raise RuntimeError("Set CULTLIB_PACKAGES to CultLib's packages directory") - _spec = importlib.util.spec_from_file_location( "ship_cc", Path(__file__).resolve().parents[1] / "aetheria_ships" / "ship_cc.py") ship_cc = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(ship_cc) -sys.path.insert(0, str(Path(PACKAGES) / "cultcache-py" / "src")) -import cultcache_py # noqa: E402 -import msgpack # noqa: E402 - - -def shape(width, height, cells): - return [width, height, cells] - - -def hardpoint_row(mount="thruster.port", tail=("future-hardpoint-slot",)): - row = ship_cc.encode_hardpoint( - Type=3, Position=[1, 0], Shape=[shape(1, 1, [True])], Transform=mount, Rotation=0, Armor=0.0, FiringArc=0.0) - return row + list(tail) - - -def hull_body(): - hull = [None] * (ship_cc.HULL_TYPE_SLOT + 1) - hull[1] = "Skiff" - hull[ship_cc.HULL_TYPE_SLOT] = 0 - hull[ship_cc.HULL_SHAPE_SLOT] = [shape(2, 2, [True, False, True, False])] - hull[ship_cc.HULL_HARDPOINTS_SLOT] = [hardpoint_row()] - hull.append("future-hull-slot") - return hull - - -LINES = [["Hull", "White", [0.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0.01, 0.01], [1.0, 1.0], False, [1.0, 1.0, 1.0, 1.0]]] - - -def ship_body(): - body = [None] * (ship_cc.SCHEMATIC_LINES_SLOT + 1) - body[0] = "mod.skiff" - body[2] = "skiff.glb" - body[3] = [["map", "map-icon", "map", None, 0]] - body[ship_cc.SCHEMATIC_LINES_SLOT] = LINES - return body - - -def catalog(schema_id, schema_name): - return cultcache_py.CultCacheSchemaCatalogEntry( - schema_id=schema_id, schema_name=schema_name, schema_version="1", - content_hash="hash", canonical_schema_json='{"members":[{"slot":9,"name":"FutureMember"}]}', - compatible_schema_ids=(schema_id,), - members=(cultcache_py.CultCacheSchemaCatalogMember(slot=9, member_name="FutureMember", type_name="string"),)) - - -CATALOG = catalog("ship-authoring-schema-1", ship_cc.SCHEMA) -HULL_CATALOG = catalog("hull-schema-1", ship_cc.HULL_SCHEMA) - - -def envelope(key, schema, entry, body): - return cultcache_py.CultCacheEnvelope.create( - key=key, type=schema, payload=msgpack.packb(body, use_bin_type=True), - schema_id=entry.schema_id, catalog_entry=entry) - - -class ShipFileCase(unittest.TestCase): - def setUp(self): - directory = tempfile.TemporaryDirectory() - self.addCleanup(directory.cleanup) - self.path = str(Path(directory.name) / "ship.cc") - self.write(ship_body(), hull_body()) - - def write(self, ship, hull, path=None): - cultcache_py.SingleFileMessagePackBackingStore(path or self.path).push_all([ - envelope("mod-ship:mod.skiff", ship_cc.SCHEMA, CATALOG, ship), - envelope("mod-hull:mod.skiff", ship_cc.HULL_SCHEMA, HULL_CATALOG, hull)]) - - def ship(self): - return ship_cc.read(self.path, PACKAGES).ship.body - - def add_products(self): - """Two products as C# stores them, one per maker; Python reads them as envelopes and never encodes one.""" - entry = catalog("product-schema-1", ship_cc.PRODUCT_SCHEMA) - store = cultcache_py.SingleFileMessagePackBackingStore(self.path) - store.push(envelope("mod-product:mod.skiff:faction:acme", ship_cc.PRODUCT_SCHEMA, entry, - [None, "Acme Skiff", "Reliable.", None, "acme-faction-key"])) - store.push(envelope("mod-product:mod.skiff:faction:rival", ship_cc.PRODUCT_SCHEMA, entry, - [None, "Rival Skiff", None, "tail", "rival-faction-key"])) - - def products(self): - return {(e.type, e.key): e for e in cultcache_py.SingleFileMessagePackBackingStore(self.path).pull_all() - if e.type == ship_cc.PRODUCT_SCHEMA} - - def hull(self): - return ship_cc.read(self.path, PACKAGES).hull.body - - def envelopes(self): - return {(e.type, e.key): e for e in cultcache_py.SingleFileMessagePackBackingStore(self.path).pull_all()} - - def bytes(self): - return Path(self.path).read_bytes() - - -class ReadTests(ShipFileCase): - def test_reads_the_ship_and_its_hull(self): - file = ship_cc.read(self.path, PACKAGES) - self.assertEqual("mod.skiff", file.ship.body[0]) - self.assertEqual(ship_cc.SCHEMA, file.ship.envelope.type) - self.assertEqual("Skiff", file.hull.body[1]) - self.assertEqual(ship_cc.HULL_SCHEMA, file.hull.envelope.type) - - def test_reads_the_hulls_type_by_its_enum_name(self): - for value, name in ((0, "Ship"), (1, "Station"), (2, "Turret")): - with self.subTest(name): - hull = hull_body() - hull[ship_cc.HULL_TYPE_SLOT] = value - self.write(ship_body(), hull) - self.assertEqual(name, ship_cc.read_hull_type(self.path, PACKAGES)) - - def test_refuses_a_hull_type_it_does_not_know_without_echoing_the_path(self): - short = hull_body()[:ship_cc.HULL_TYPE_SLOT] - for label, value in (("past the enum", 3), ("negative", -1), ("bool", True), ("missing", None), - ("text", "Ship"), ("short body", short)): - with self.subTest(label): - hull = value if label == "short body" else hull_body() - if label != "short body": - hull[ship_cc.HULL_TYPE_SLOT] = value - self.write(ship_body(), hull) - with self.assertRaises(ValueError) as caught: - ship_cc.read_hull_type(self.path, PACKAGES) - self.assertEqual("The ship file's hull has no hull type this add-on knows", str(caught.exception)) - self.assertNotIn(self.path, str(caught.exception)) - - def test_reads_a_file_whose_hull_also_carries_products(self): - self.add_products() - file = ship_cc.read(self.path, PACKAGES) - self.assertEqual("mod.skiff", file.ship.body[0]) - self.assertEqual("Skiff", file.hull.body[1]) - - def test_refuses_a_file_with_another_record_beside_the_pair(self): - cultcache_py.SingleFileMessagePackBackingStore(self.path).push(cultcache_py.CultCacheEnvelope.create( - key="other", type="aetheria.something", payload=msgpack.packb([1], use_bin_type=True))) - with self.assertRaisesRegex(ValueError, "must hold exactly one"): - ship_cc.read(self.path, PACKAGES) - - def test_refuses_a_file_missing_either_half_of_the_pair(self): - for name, schema, entry, body in (("hull only", ship_cc.HULL_SCHEMA, HULL_CATALOG, hull_body()), - ("ship only", ship_cc.SCHEMA, CATALOG, ship_body())): - other = str(Path(self.path).with_name(name.replace(" ", "-") + ".cc")) - cultcache_py.SingleFileMessagePackBackingStore(other).push(envelope("key", schema, entry, body)) - with self.subTest(name): - with self.assertRaisesRegex(ValueError, "must hold exactly one"): - ship_cc.read(other, PACKAGES) - - def test_refuses_a_file_with_two_hulls(self): - cultcache_py.SingleFileMessagePackBackingStore(self.path).push( - envelope("mod-hull:mod.other", ship_cc.HULL_SCHEMA, HULL_CATALOG, hull_body())) - with self.assertRaisesRegex(ValueError, "must hold exactly one"): - ship_cc.read(self.path, PACKAGES) - - def test_refuses_a_zero_byte_file_as_cultcache_does(self): - # An empty file is not a store (CultLib pins this): the owner's refusal passes through, the add-on adds none. - empty = str(Path(self.path).with_name("empty.cc")) - Path(empty).write_bytes(b"") - with self.assertRaises(ValueError) as owner: - cultcache_py.SingleFileMessagePackBackingStore(empty).pull_all() - with self.assertRaises(ValueError) as raised: - ship_cc.read(empty, PACKAGES) - # The very refusal cultcache-py makes, not one the add-on spells beside it (its shape refusal is a ValueError too). - self.assertIs(type(raised.exception), type(owner.exception)) - self.assertEqual(str(raised.exception), str(owner.exception)) - self.assertNotIn("must hold exactly one", str(raised.exception)) - - def test_refuses_a_ship_record_that_still_carries_the_retired_embedded_hull(self): - for name, ship in (("nested hull", ["mod.skiff", hull_body()]), - ("any value", ["mod.skiff", 0])): - body = ship_body() - body[ship_cc.RETIRED_HULL_SLOT] = ship[1] - with self.subTest(name): - self.write(body, hull_body()) - with self.assertRaisesRegex(ValueError, "legacy embedded hull at retired key 1"): - ship_cc.read(self.path, PACKAGES) - # Nothing else is said about its shape: an old file has no hull record beside the ship. - cultcache_py.SingleFileMessagePackBackingStore(self.path).push_all( - [envelope("mod-ship:mod.skiff", ship_cc.SCHEMA, CATALOG, body)]) - with self.assertRaisesRegex(ValueError, "legacy embedded hull"): - ship_cc.read(self.path, PACKAGES) - - def test_refuses_a_save_over_a_file_with_the_retired_embedded_hull_and_writes_nothing(self): - body = ship_body() - body[ship_cc.RETIRED_HULL_SLOT] = hull_body() - self.write(body, hull_body()) - before = self.bytes() - with self.assertRaisesRegex(ValueError, "legacy embedded hull"): - ship_cc.replace_lines(self.path, PACKAGES, LINES) - with self.assertRaisesRegex(ValueError, "legacy embedded hull"): - ship_cc.replace_layout(self.path, PACKAGES, "mod.skiff", "any", [2, 2, [True] * 4], []) - self.assertEqual(before, self.bytes()) - - def test_a_nil_in_the_retired_slot_is_the_current_shape(self): - self.assertIsNone(self.ship()[ship_cc.RETIRED_HULL_SLOT]) - - def test_refuses_a_ship_payload_too_short_for_the_line_slot(self): - for body in (["mod.skiff"], ["mod.skiff", None]): - with self.subTest(slots=len(body)): - self.write(body, hull_body()) - with self.assertRaisesRegex(ValueError, "incompatible"): - ship_cc.read(self.path, PACKAGES) - - def test_refuses_a_payload_that_is_not_an_array(self): - for payload in ({"Id": "mod.skiff"}, {str(index): index for index in range(9)}, "a string long enough to fill every slot"): - with self.subTest(ship=payload): - self.write(payload, hull_body()) - with self.assertRaisesRegex(ValueError, "incompatible"): - ship_cc.read(self.path, PACKAGES) - with self.subTest(hull=payload): - self.write(ship_body(), payload) - with self.assertRaisesRegex(ValueError, "incompatible"): - ship_cc.read(self.path, PACKAGES) - - -class ProductMakerTests(ShipFileCase): - """Manufacturer is slot 4 of a product, the Faction record key; Python reads it and never writes a product.""" - - def push_product(self, key, body): - entry = catalog("product-schema-1", ship_cc.PRODUCT_SCHEMA) - cultcache_py.SingleFileMessagePackBackingStore(self.path).push(envelope(key, ship_cc.PRODUCT_SCHEMA, entry, body)) - - def test_each_products_manufacturer_is_read_in_file_order(self): - self.add_products() - self.assertEqual(["acme-faction-key", "rival-faction-key"], ship_cc.product_makers(self.path, PACKAGES)) - - def test_a_file_with_no_product_has_no_maker(self): - self.assertEqual([], ship_cc.product_makers(self.path, PACKAGES)) - - def test_the_manufacturer_is_read_from_its_slot_not_from_a_neighbour(self): - self.push_product("mod-product:mod.skiff:faction:acme", [None, "name-slot", "description-slot", "design-slot", - "maker-slot", "roles-slot"]) - self.assertEqual(["maker-slot"], ship_cc.product_makers(self.path, PACKAGES)) - - def test_manufacturer_keys_are_compared_as_written_not_case_folded(self): - self.push_product("mod-product:mod.skiff:faction:a", [None, "A", None, None, "Acme-Key"]) - self.push_product("mod-product:mod.skiff:faction:b", [None, "B", None, None, "acme-key"]) - self.assertEqual(["Acme-Key", "acme-key"], ship_cc.product_makers(self.path, PACKAGES)) - - def test_a_product_with_no_manufacturer_is_refused_naming_no_input(self): - canary = "canary-product-name" - for body in ([None, canary, "Reliable."], [None, canary, None, None], [None, canary, None, None, None], - [None, canary, None, None, ""], - [None, canary, None, None, 7], "a bare string body is no list of slots, whatever its fifth character"): - with self.subTest(body=body): - self.setUp() - self.push_product("mod-product:mod.skiff:faction:" + canary, body) - with self.assertRaises(ValueError) as caught: - ship_cc.product_makers(self.path, PACKAGES) - self.assertNotIn(canary, str(caught.exception)) - self.assertNotIn(self.path, str(caught.exception)) - - -class ProductCarryThroughTests(ShipFileCase): - """Products lie beside the pair, owned by C#: every push rewrites the file and leaves them byte-identical.""" - - def test_each_edit_leaves_both_product_envelopes_byte_identical(self): - self.add_products() - before = self.products() - self.assertEqual(2, len(before)) - hull = hull_body() - revision = ship_cc.layout_revision(hull[ship_cc.HULL_SHAPE_SLOT][0], hull[ship_cc.HULL_HARDPOINTS_SLOT]) - edits = ( - lambda: ship_cc.replace_lines(self.path, PACKAGES, LINES), - lambda: ship_cc.replace_visual(self.path, PACKAGES, "mod.skiff", "ship.glb", [["map", "map-icon", "map", None, 0]]), - lambda: ship_cc.replace_layout(self.path, PACKAGES, "mod.skiff", revision, [2, 2, [True, True, True, False]], - [row[:len(ship_cc.HARDPOINT_MEMBERS)] for row in hull[ship_cc.HULL_HARDPOINTS_SLOT]]), - ) - for index, edit in enumerate(edits): - with self.subTest(edit=index): - edit() - after = self.products() - self.assertEqual(before.keys(), after.keys()) - for key in before: - self.assertEqual(before[key].payload, after[key].payload) - self.assertEqual(before[key].key, after[key].key) - # The edits really ran: the shape the layout edit wrote is in the file beside the carried products. - self.assertEqual([2, 2, [True, True, True, False]], ship_cc.read(self.path, PACKAGES).hull.body[ship_cc.HULL_SHAPE_SLOT][0]) - - -class RigCarryThroughTests(ShipFileCase): - """The rig (ShipAuthoring slot 5 Joints, ShipAnchor slot 5 Joint) lies past every slot this module edits, so a save keeps it.""" - - JOINTS = [["turret", None, [0.0, 1.0, 0.0], [-30.0], [30.0]]] - - def setUp(self): - super().setUp() - ship = ship_body() - ship.append(self.JOINTS) - ship[ship_cc.ANCHORS_SLOT] = [["gun", "weapon-mount", "gun", None, 0, "turret"], ["map", "map-icon", "map", None, 0]] - self.write(ship, hull_body()) - - def test_replace_visual_keeps_the_joints_and_each_mounts_joint_by_anchor_id(self): - ship_cc.replace_visual(self.path, PACKAGES, "mod.skiff", "ship.glb", - [["map", "map-icon", "map", None, 0], ["gun", "weapon-mount", "gun", None, 0]]) - ship = self.ship() - self.assertEqual(self.JOINTS, ship[5]) - self.assertEqual([["map", "map-icon", "map", None, 0], ["gun", "weapon-mount", "gun", None, 0, "turret"]], - ship[ship_cc.ANCHORS_SLOT]) - - def test_replace_lines_keeps_the_joints_and_the_anchor_rows(self): - before = self.ship() - ship_cc.replace_lines(self.path, PACKAGES, LINES) - after = self.ship() - self.assertEqual(self.JOINTS, after[5]) - self.assertEqual(before[ship_cc.ANCHORS_SLOT], after[ship_cc.ANCHORS_SLOT]) - - -class ReplaceLinesTests(ShipFileCase): - def test_replaces_only_the_line_slot(self): - new_lines = [["Detail", "Red", [0.0] * 6, [0.1, 0.1], [1.0, 1.0], True, [1.0, 0.0, 0.0, 1.0]]] - before = self.ship() - self.assertEqual(1, ship_cc.replace_lines(self.path, PACKAGES, new_lines)) - after = self.ship() - self.assertEqual(new_lines, after[ship_cc.SCHEMATIC_LINES_SLOT]) - for slot in range(len(before)): - if slot != ship_cc.SCHEMATIC_LINES_SLOT: - self.assertEqual(before[slot], after[slot], f"slot {slot} changed") - - def test_clear_lines_empties_only_the_line_slot(self): - ship_cc.replace_lines(self.path, PACKAGES, LINES) - before = self.ship() - self.assertEqual(len(LINES), ship_cc.clear_lines(self.path, PACKAGES)) - after = self.ship() - self.assertEqual([], after[ship_cc.SCHEMATIC_LINES_SLOT]) - for slot in range(len(before)): - if slot != ship_cc.SCHEMATIC_LINES_SLOT: - self.assertEqual(before[slot], after[slot], f"slot {slot} changed") - - def test_replace_lines_still_refuses_an_empty_capture(self): - ship_cc.replace_lines(self.path, PACKAGES, LINES) - with self.assertRaises(ValueError): - ship_cc.replace_lines(self.path, PACKAGES, []) - self.assertEqual(LINES, self.ship()[ship_cc.SCHEMATIC_LINES_SLOT]) - - def test_a_save_refreshes_the_stored_at_of_the_record_it_writes_and_only_that_one(self): - stale = "2000-01-01T00:00:00+00:00" - envelopes = self.envelopes() - cultcache_py.SingleFileMessagePackBackingStore(self.path).push_all( - [dataclasses.replace(envelopes[key], stored_at=stale) for key in envelopes]) - ship_cc.replace_lines(self.path, PACKAGES, LINES) - after = self.envelopes() - self.assertGreater(datetime.fromisoformat(after[(ship_cc.SCHEMA, "mod-ship:mod.skiff")].stored_at), - datetime.fromisoformat(stale)) - self.assertEqual(stale, after[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")].stored_at) - - def test_leaves_the_hull_record_byte_identical(self): - before = self.envelopes()[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")] - ship_cc.replace_lines(self.path, PACKAGES, LINES) - self.assertEqual(before, self.envelopes()[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")]) - - def test_keeps_the_schema_catalog(self): - ship_cc.replace_lines(self.path, PACKAGES, LINES) - envelope = self.envelopes()[(ship_cc.SCHEMA, "mod-ship:mod.skiff")] - self.assertEqual(CATALOG.members, envelope.catalog_entry.members) - self.assertEqual(CATALOG.canonical_schema_json, envelope.catalog_entry.canonical_schema_json) - - def test_refuses_an_empty_capture_and_changes_nothing(self): - before = self.bytes() - with self.assertRaisesRegex(ValueError, "No schematic lines"): - ship_cc.replace_lines(self.path, PACKAGES, []) - self.assertEqual(before, self.bytes()) - - -class ReplaceVisualTests(ShipFileCase): - def anchor(self, anchor_id, role="map-icon", parent=None, order=0): - return [anchor_id, role, anchor_id, parent, order] - - def test_writes_the_model_asset_and_anchor_rows_in_member_order(self): - rows = [self.anchor("map"), self.anchor("gun", "weapon-mount"), self.anchor("gun.muzzle", "weapon-muzzle", "gun", 1)] - self.assertEqual(3, ship_cc.replace_visual(self.path, PACKAGES, "mod.skiff", "ship.glb", rows)) - ship = self.ship() - self.assertEqual("ship.glb", ship[ship_cc.MODEL_ASSET_SLOT]) - self.assertEqual(rows, ship[ship_cc.ANCHORS_SLOT]) - self.assertEqual(dict(zip(ship_cc.ANCHOR_MEMBERS, rows[2])), - {"Id": "gun.muzzle", "Role": "weapon-muzzle", "ModelNodeId": "gun.muzzle", "ParentId": "gun", "Order": 1}) - - def test_replace_visual_carries_unknown_anchor_slots_by_id(self): - ship = ship_body() - ship[ship_cc.ANCHORS_SLOT] = [["map", "map-icon", "map", None, 0, "future-anchor-slot"], - ["shield", "shield", "shield", None, 0, "shield-future"]] - self.write(ship, hull_body()) - # Reordered, with one new anchor: each known Id keeps its own tail, the new one gets none. - ship_cc.replace_visual(self.path, PACKAGES, "mod.skiff", "ship.glb", - [self.anchor("shield", "shield"), self.anchor("tractor", "tractor"), self.anchor("map")]) - self.assertEqual([["shield", "shield", "shield", None, 0, "shield-future"], - ["tractor", "tractor", "tractor", None, 0], - ["map", "map-icon", "map", None, 0, "future-anchor-slot"]], self.ship()[ship_cc.ANCHORS_SLOT]) - - def test_replace_visual_refuses_blank_or_duplicate_ids_and_a_changed_ship(self): - before = self.bytes() - cases = (("blank", "mod.skiff", [self.anchor(" ")], "needs an ID"), - ("none", "mod.skiff", [[None, "map-icon", "x", None, 0]], "needs an ID"), - ("duplicate", "mod.skiff", [self.anchor("map"), self.anchor("map", "shield")], "used twice"), - ("arity", "mod.skiff", [["map", "map-icon", "map", None]], "exactly"), - ("ship", "mod.other", [self.anchor("map")], "ship ID changed")) - for name, ship_id, rows, message in cases: - with self.subTest(name): - with self.assertRaisesRegex(ValueError, message): - ship_cc.replace_visual(self.path, PACKAGES, ship_id, "ship.glb", rows) - self.assertEqual(before, self.bytes()) - - def test_replace_visual_touches_only_model_asset_and_anchors(self): - hull_before = self.envelopes()[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")] - ship_before = self.ship() - ship_cc.replace_visual(self.path, PACKAGES, "mod.skiff", "ship.glb", [self.anchor("hull", "hull-collider")]) - after = self.envelopes() - self.assertEqual(hull_before, after[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")]) - ship_after = self.ship() - for slot, (old, new) in enumerate(zip(ship_before, ship_after)): - if slot not in (ship_cc.MODEL_ASSET_SLOT, ship_cc.ANCHORS_SLOT): - self.assertEqual(old, new, f"slot {slot}") - self.assertEqual(len(ship_before), len(ship_after)) - self.assertEqual(LINES, ship_after[ship_cc.SCHEMATIC_LINES_SLOT]) - self.assertEqual(CATALOG.schema_id, after[(ship_cc.SCHEMA, "mod-ship:mod.skiff")].schema_id) - - -class LayoutTests(ShipFileCase): - def layout(self): - return ship_cc.read_layout(self.path, PACKAGES) - - def edit(self, revision, width=2, height=2, cells=None, hardpoints=None, ship_id="mod.skiff"): - return ship_cc.replace_layout( - self.path, PACKAGES, ship_id, revision, - [width, height, cells if cells is not None else [True, True, True, False]], - hardpoints if hardpoints is not None else [hardpoint_row(tail=())]) - - def test_reads_the_shape_hardpoints_and_a_revision(self): - shape_triple, hardpoints, revision = self.layout() - self.assertEqual([2, 2, [True, False, True, False]], shape_triple) - self.assertEqual("thruster.port", ship_cc.decode_hardpoint(hardpoints[0])["Transform"]) - self.assertEqual(64, len(revision)) - - def test_the_revision_follows_the_layout_and_only_the_layout(self): - _, _, revision = self.layout() - ship = self.ship() - ship[ship_cc.SCHEMATIC_LINES_SLOT] = [] - hull = self.hull() - hull[1] = "Renamed" - self.write(ship, hull) - self.assertEqual(revision, self.layout()[2]) - hull[ship_cc.HULL_SHAPE_SLOT] = [shape(2, 2, [True, True, True, True])] - self.write(ship, hull) - self.assertNotEqual(revision, self.layout()[2]) - - def test_layout_revision_is_the_revision_replace_layout_returns_for_the_same_shape_and_rows(self): - _, _, revision = self.layout() - cells = [True, True, True, False] - rows = [hardpoint_row("thruster.starboard", tail=())] # a mount the file carried no later slots for - saved = self.edit(revision, cells=cells, hardpoints=rows) - self.assertEqual(saved, ship_cc.layout_revision(shape(2, 2, cells), rows)) - self.assertEqual(saved, self.layout()[2]) - self.assertNotEqual(saved, ship_cc.layout_revision(shape(2, 2, [True, True, False, False]), rows)) - self.assertNotEqual(saved, ship_cc.layout_revision(shape(2, 2, cells), [])) - - def test_the_revision_follows_the_hardpoints_too(self): - _, _, revision = self.layout() - moved = hardpoint_row(tail=()) - moved[1] = [0, 0] - same_cells = [True, False, True, False] - self.assertEqual(revision, self.edit(revision, cells=same_cells, hardpoints=[hardpoint_row(tail=())])) - self.assertNotEqual(revision, self.edit(revision, cells=same_cells, hardpoints=[moved])) - - def test_saves_the_layout_and_returns_the_new_revision(self): - _, _, revision = self.layout() - moved = hardpoint_row(tail=()) - moved[1] = [0, 0] - returned = self.edit(revision, cells=[True, True, True, False], hardpoints=[moved]) - shape_triple, hardpoints, saved = self.layout() - self.assertEqual([2, 2, [True, True, True, False]], shape_triple) - self.assertEqual([0, 0], ship_cc.decode_hardpoint(hardpoints[0])["Position"]) - self.assertEqual(saved, returned) - self.assertNotEqual(revision, returned) - - def test_preserves_every_slot_it_does_not_edit(self): - _, _, revision = self.layout() - ship_before, hull_before = self.ship(), self.hull() - ship_envelope = self.envelopes()[(ship_cc.SCHEMA, "mod-ship:mod.skiff")] - self.edit(revision) - self.assertEqual(ship_before, self.ship()) - self.assertEqual(ship_envelope, self.envelopes()[(ship_cc.SCHEMA, "mod-ship:mod.skiff")]) - hull_after = self.hull() - self.assertEqual(len(hull_before), len(hull_after)) - for slot in range(len(hull_before)): - if slot not in (ship_cc.HULL_SHAPE_SLOT, ship_cc.HULL_HARDPOINTS_SLOT): - self.assertEqual(hull_before[slot], hull_after[slot], f"hull slot {slot} changed") - - def test_carries_a_later_schemas_hardpoint_slots_by_mount_id(self): - _, _, revision = self.layout() - starboard = hardpoint_row("thruster.starboard", tail=()) - self.edit(revision, hardpoints=[starboard, hardpoint_row(tail=())]) - rows = self.layout()[1] - self.assertEqual(["thruster.starboard", "thruster.port"], [ship_cc.decode_hardpoint(row)["Transform"] for row in rows]) - self.assertEqual(len(ship_cc.HARDPOINT_MEMBERS), len(rows[0])) - self.assertEqual(["future-hardpoint-slot"], rows[1][len(ship_cc.HARDPOINT_MEMBERS):]) - - def test_drops_the_row_of_a_removed_mount(self): - _, _, revision = self.layout() - self.edit(revision, hardpoints=[]) - self.assertEqual([], self.layout()[1]) - - def test_keeps_the_schema_catalog(self): - _, _, revision = self.layout() - self.edit(revision) - envelope = self.envelopes()[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")] - self.assertEqual(HULL_CATALOG.members, envelope.catalog_entry.members) - - def test_refuses_a_ship_id_that_changed_and_writes_nothing(self): - _, _, revision = self.layout() - before = self.bytes() - with self.assertRaisesRegex(ValueError, "bound ship ID changed"): - self.edit(revision, ship_id="mod.other") - self.assertEqual(before, self.bytes()) - - def test_refuses_a_stale_revision_and_writes_nothing(self): - _, _, revision = self.layout() - self.edit(revision) - before = self.bytes() - with self.assertRaisesRegex(ValueError, "layout changed since Load"): - self.edit(revision) - self.assertEqual(before, self.bytes()) - - def test_refuses_grid_sizes_outside_one_to_thirty_two_and_writes_nothing(self): - _, _, revision = self.layout() - before = self.bytes() - for width, height in ((0, 2), (2, 0), (33, 1), (1, 33)): - with self.subTest(width=width, height=height): - with self.assertRaisesRegex(ValueError, "1..32 cells"): - self.edit(revision, width=width, height=height, cells=[True] * (width * height)) - for width, height in ((1, 1), (32, 32)): - with self.subTest(width=width, height=height): - self.edit(revision, width=width, height=height, cells=[True] * (width * height), hardpoints=[]) - revision = self.layout()[2] - self.assertNotEqual(before, self.bytes()) - - def test_the_grid_limit_is_hull_grids_max_cells(self): - _, _, revision = self.layout() - before = self.bytes() - with self.assertRaisesRegex(ValueError, f"1..{ship_cc.hull_grid.MAX_CELLS} cells"): - self.edit(revision, width=33, height=1, cells=[True] * 33) - self.assertEqual(before, self.bytes()) - with mock.patch.object(ship_cc.hull_grid, "MAX_CELLS", 33): - self.edit(revision, width=33, height=1, cells=[True] * 33, hardpoints=[]) - self.assertEqual([33, 1, [True] * 33], self.layout()[0]) - - def test_a_layout_save_refreshes_the_stored_at_of_the_hull_and_leaves_the_ships(self): - stale = "2000-01-01T00:00:00+00:00" - envelopes = self.envelopes() - cultcache_py.SingleFileMessagePackBackingStore(self.path).push_all( - [dataclasses.replace(envelopes[key], stored_at=stale) for key in envelopes]) - self.edit(self.layout()[2]) - after = self.envelopes() - self.assertGreater(datetime.fromisoformat(after[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")].stored_at), - datetime.fromisoformat(stale)) - self.assertEqual(stale, after[(ship_cc.SCHEMA, "mod-ship:mod.skiff")].stored_at) - - def test_refuses_cells_that_are_not_booleans_and_writes_nothing(self): - _, _, revision = self.layout() - before = self.bytes() - for name, cells in (("integer", [True, 1, True, False]), ("zero", [True, True, True, 0]), - ("string", [True, "x", True, False]), ("none", [True, None, True, False])): - with self.subTest(name): - with self.assertRaisesRegex(ValueError, "Hull grid cells must be booleans"): - self.edit(revision, cells=cells) - self.assertEqual(before, self.bytes()) - - def test_refuses_hardpoint_footprint_cells_that_are_not_booleans_and_writes_nothing(self): - _, _, revision = self.layout() - before = self.bytes() - for name, cells in (("integer", [1, True]), ("none", [True, None])): - row = ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(hardpoint_row(tail=())), - "Shape": [shape(2, 1, cells)]}) - with self.subTest(name): - with self.assertRaisesRegex(ValueError, "Hardpoint footprint cells must be booleans"): - self.edit(revision, hardpoints=[row]) - self.assertEqual(before, self.bytes()) - - def test_refuses_a_cell_count_that_does_not_fill_the_grid(self): - _, _, revision = self.layout() - before = self.bytes() - with self.assertRaisesRegex(ValueError, "1..32 cells"): - self.edit(revision, cells=[True, True, True]) - self.assertEqual(before, self.bytes()) - - def test_refuses_a_grid_with_no_occupied_cell(self): - _, _, revision = self.layout() - with self.assertRaisesRegex(ValueError, "needs an occupied cell"): - self.edit(revision, cells=[False] * 4) - - def test_refuses_a_hardpoint_row_of_the_wrong_arity_or_without_a_mount_id(self): - _, _, revision = self.layout() - before = self.bytes() - row = hardpoint_row(tail=()) - for name, bad in (("short", row[:-1]), ("long", row + [0]), - ("blank", ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(row), "Transform": ""})), - ("none", ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(row), "Transform": None})), - ("number", ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(row), "Transform": 4}))): - with self.subTest(name): - with self.assertRaisesRegex(ValueError, "stable mount ID"): - self.edit(revision, hardpoints=[bad]) - self.assertEqual(before, self.bytes()) - - def test_refuses_a_hardpoint_footprint_that_is_not_a_filled_grid_of_one_to_thirty_two(self): - _, _, revision = self.layout() - before = self.bytes() - for name, footprint in (("no width", shape(0, 1, [])), ("no height", shape(1, 0, [])), - ("too wide", shape(33, 1, [True] * 33)), ("too tall", shape(1, 33, [True] * 33)), - ("short", shape(2, 1, [True])), ("empty", shape(1, 1, [False]))): - row = ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(hardpoint_row(tail=())), "Shape": [footprint]}) - with self.subTest(name): - with self.assertRaisesRegex(ValueError, "hardpoint has an invalid footprint"): - self.edit(revision, hardpoints=[row]) - self.assertEqual(before, self.bytes()) - - def test_refuses_a_hull_payload_without_the_hardpoint_slot(self): - hull = self.hull()[:ship_cc.HULL_HARDPOINTS_SLOT] - self.write(self.ship(), hull) - with self.assertRaisesRegex(ValueError, "incompatible typed payload"): - self.layout() - - -@unittest.skipUnless(os.environ.get("SHIP_FIXTURE_DIR"), "SHIP_FIXTURE_DIR names the C#-written fixture (see below)") -class CSharpWrittenFixtureTests(unittest.TestCase): - """Gate 1's Python half: a package C# wrote survives a Python edit with every untouched slot intact. - - The fixture comes from the C# suite (`AETHERIA_SHIP_FIXTURE_DIR= dotnet test ... --filter - TheFixturePackageIsCompleteAndItsGlbCarriesAScene`). Point SHIP_FIXTURE_DIR at that and, optionally, - SHIP_EDITED_DIR at an empty directory to keep the edited package; C# then reopens and validates it with - `dotnet run --project tools/AetherDb -- ship-authoring validate /mod.skiff/ship.cc`. - """ - - def test_a_layout_and_line_edit_preserves_every_slot_it_does_not_own(self): - with tempfile.TemporaryDirectory() as scratch: - path = str(Path(scratch) / "ship.cc") - shutil.copy(Path(os.environ["SHIP_FIXTURE_DIR"]) / "mod.skiff" / "ship.cc", path) - before = ship_cc.read(path, PACKAGES) - shape_triple, hardpoints, revision = ship_cc.read_layout(path, PACKAGES) - width, height, cells = shape_triple - self.assertEqual(64, len(revision)) - cells = list(cells) - cells[-1] = True - ship_cc.replace_layout(path, PACKAGES, before.ship.body[0], revision, [width, height, cells], hardpoints) - ship_cc.replace_lines(path, PACKAGES, before.ship.body[ship_cc.SCHEMATIC_LINES_SLOT]) - after = ship_cc.read(path, PACKAGES) - - self.assertEqual(before.ship.body, after.ship.body) - self.assertEqual(before.ship.envelope.key, after.ship.envelope.key) - self.assertEqual(before.ship.envelope.catalog_entry, after.ship.envelope.catalog_entry) - self.assertEqual(before.hull.envelope.key, after.hull.envelope.key) - self.assertEqual(before.hull.envelope.catalog_entry, after.hull.envelope.catalog_entry) - for slot in range(len(before.hull.body)): - if slot != ship_cc.HULL_SHAPE_SLOT: - self.assertEqual(before.hull.body[slot], after.hull.body[slot], f"hull slot {slot} changed") - self.assertTrue(after.hull.body[ship_cc.HULL_SHAPE_SLOT][0][2][-1]) - - kept = os.environ.get("SHIP_EDITED_DIR") - if kept: - target = Path(kept) / "mod.skiff" - target.mkdir(parents=True, exist_ok=True) - shutil.copy(path, target / "ship.cc") - shutil.copy(Path(os.environ["SHIP_FIXTURE_DIR"]) / "mod.skiff" / "skiff.glb", target / "skiff.glb") - - -class RefusalsNameNoInputTests(ShipFileCase): - def test_refusals_name_no_path_mount_or_anchor_id(self): - _, _, revision = ship_cc.read_layout(self.path, PACKAGES) - mount = "mount.zq-unique" - duplicate = [[ "anchor.zq-unique", "map-icon", "n1", None, 0], ["anchor.zq-unique", "shield", "n2", None, 0]] - bad_footprint = ship_cc.encode_hardpoint( - Type=3, Position=[1, 0], Shape=[[1, 1, [0]]], Transform=mount, Rotation=0, Armor=0.0, FiringArc=0.0) - empty_footprint = ship_cc.encode_hardpoint( - Type=3, Position=[1, 0], Shape=[[1, 1, [False]]], Transform=mount, Rotation=0, Armor=0.0, FiringArc=0.0) - calls = (lambda: ship_cc.replace_visual(self.path, PACKAGES, "mod.skiff", "ship.glb", duplicate), - lambda: ship_cc.replace_layout(self.path, PACKAGES, "mod.skiff", revision, [2, 2, [True] * 4], [bad_footprint]), - lambda: ship_cc.replace_layout(self.path, PACKAGES, "mod.skiff", revision, [2, 2, [True] * 4], [empty_footprint]), - lambda: ship_cc.read(os.path.join(self.path, "missing.cc"), PACKAGES)) - for call in calls: - with self.subTest(call): - with self.assertRaises(Exception) as caught: - call() - for forbidden in ("zq-unique", self.path, os.path.dirname(self.path)): - self.assertNotIn(forbidden, str(caught.exception)) - - -class UntestedCultCacheTests(ShipFileCase): - """_libraries refuses a cultcache-py that is not the version the raw envelope writes were tested against. The version - is read from the checkout of the module that actually imports, so each case imports a stub cultcache_py.""" - - def setUp(self): - super().setUp() - saved_modules = {name: module for name, module in sys.modules.items() if name.split(".")[0] == "cultcache_py"} - saved_path = list(sys.path) - for name in saved_modules: - del sys.modules[name] - self.addCleanup(self.restore, saved_modules, saved_path) - - @staticmethod - def restore(saved_modules, saved_path): - for name in [name for name in sys.modules if name.split(".")[0] == "cultcache_py"]: - del sys.modules[name] - sys.modules.update(saved_modules) - sys.path[:] = saved_path - - def packages(self, version=None, with_source=True): - root = Path(tempfile.mkdtemp()) - self.addCleanup(shutil.rmtree, root, True) - checkout = root / "cultcache-py" - checkout.mkdir() - if version is not None: - (checkout / "pyproject.toml").write_text( - f'[project]\nname = "cultcache-py"\nversion = "{version}"\n', encoding="utf-8") - if with_source: - (checkout / "src" / "cultcache_py").mkdir(parents=True) - (checkout / "src" / "cultcache_py" / "__init__.py").write_text("", encoding="utf-8") - return str(root) - - def test_a_different_version_is_refused_naming_the_version_and_the_packages_path(self): - before = self.bytes() - # any drift, not only a different major; 0.3.0.1 and 0.3.0rc1 start with the tested version and are not it - for version in ("9.9.9", "0.4.0", "0.3.1", "0.3", "0.3.0.1", "0.3.0rc1", "0.3.00"): - for call in (lambda stub: ship_cc.read(self.path, stub), lambda stub: ship_cc.read_layout(self.path, stub)): - stub = self.packages(version) - with self.subTest(version=version), self.assertRaises(ValueError) as caught: - call(stub) - self.fail("accepted") - self.assertIn(version, str(caught.exception)) - self.assertIn(stub, str(caught.exception)) - self.restore({}, list(sys.path)) # the next import is fresh - self.assertEqual(before, self.bytes()) - - def test_a_save_through_an_untested_cultcache_writes_nothing(self): - _, _, revision = ship_cc.read_layout(self.path, PACKAGES) - before = self.bytes() - self.restore({}, list(sys.path)) - with self.assertRaises(ValueError): - ship_cc.replace_layout(self.path, self.packages("9.9.9"), "mod.skiff", revision, [2, 2, [True] * 4], []) - self.assertEqual(before, self.bytes()) - - def test_a_missing_pyproject_is_refused(self): - stub = self.packages() - with self.assertRaises(ValueError) as caught: - ship_cc.read(self.path, stub) - self.assertIn(stub, str(caught.exception)) - - def test_the_guard_certifies_the_library_that_is_imported_not_the_path_it_was_given(self): - # A pyproject that says 0.3.0 beside a path whose source is not what imports does not vouch for the import. - real = self.packages("0.4.0") # imports first, and is the library in use - with self.assertRaises(ValueError): - ship_cc.read(self.path, real) - liar = self.packages("0.3.0", with_source=False) # claims the tested version, supplies no source - sys.path.insert(0, str(Path(real) / "cultcache-py" / "src")) - with self.assertRaises(ValueError) as caught: - ship_cc.read(self.path, liar) - self.assertIn("0.4.0", str(caught.exception)) - - def test_the_tested_version_is_the_one_the_real_packages_directory_carries(self): - self.restore({}, list(sys.path)) - self.assertEqual("mod.skiff", ship_cc.read(self.path, PACKAGES).ship.body[0]) - import cultcache_py - self.assertEqual(ship_cc.TESTED_CULTCACHE_PY, ship_cc._cultcache_py_version(cultcache_py)) - class ShipIdTests(unittest.TestCase): def test_admits_the_ids_the_c_sharp_rule_admits(self): @@ -804,19 +34,6 @@ class ShipIdTests(unittest.TestCase): self.assertEqual(22, len(ship_cc.RESERVED_SHIP_IDS)) -class HardpointRowTests(unittest.TestCase): - def test_a_row_is_one_value_per_member_in_slot_order(self): - fields = dict(Type=1, Position=[2, 3], Shape="shape", Transform="mount", Rotation=2, Armor=4.0, FiringArc=90.0) - row = ship_cc.encode_hardpoint(**fields) - self.assertEqual([fields[name] for name in ship_cc.HARDPOINT_MEMBERS], row) - self.assertEqual(fields, ship_cc.decode_hardpoint(row)) - - def test_encoding_needs_every_member_and_no_other(self): - good = dict.fromkeys(ship_cc.HARDPOINT_MEMBERS, 0) - with self.assertRaises(ValueError): - ship_cc.encode_hardpoint(**{name: 0 for name in ship_cc.HARDPOINT_MEMBERS[1:]}) - with self.assertRaises(ValueError): - ship_cc.encode_hardpoint(**good, Extra=1) class Matrix: