refactor: own transport runtime and preserve saved cart state

This commit is contained in:
2026-09-24 20:43:20 +03:00
parent 8f357b1c9c
commit c9a4e9d643
31 changed files with 2060 additions and 65 deletions
+37 -19
View File
@@ -1,9 +1,12 @@
# AstraContent 0.2.5 # AstraContent 0.2.6
Контент для Minecraft 26.2, NeoForge 26.2.0.79 и Java 25. Контент для Minecraft 26.2, NeoForge 26.2.0.79 и Java 25.
AstraContent 0.2.5 владеет обработчиками дополнительных боеприпасов и их двумя mixin. AstraContent владеет обработчиками дополнительных боеприпасов и транспорта: скоростью
Требуется AstraPlus 0.9.11+; AstraPacks обслуживает ресурспак. Без AstraContent новый вагонеток, сцепками, отскоком от слизи и совместимостью старых рельсов. Здесь находятся
AstraPlus не меняет боеприпасы арбалета и не запускает огненный заряд по ПКМ в воздух. два mixin боеприпасов и семь перенесённых mixin транспорта; новых точек вмешательства
при переносе не добавлено. Требуется AstraPlus 0.9.13+; AstraPacks обслуживает ресурспак.
Без AstraContent ядро не подключает эти конкретные обработчики, даже если их настройки
остались на диске. Общий API декларативных свойств блоков остаётся в AstraPlus.
На клиент мод устанавливать не нужно. Оформление передаётся обычным ресурспаком. На клиент мод устанавливать не нужно. Оформление передаётся обычным ресурспаком.
## Арбалет и огненный заряд ## Арбалет и огненный заряд
@@ -121,9 +124,10 @@ Shift + ПКМ киркой по выбранному торцу снимает
## Установка и разработка ## Установка и разработка
Устанавливаются AstraPlus 0.9.11+, AstraContent 0.2.5+ и AstraPacks. Прежний Content 0.2.4 Устанавливаются AstraPlus 0.9.13+, AstraContent 0.2.6+ и AstraPacks. В Content 0.2.5 ещё
был пустой оболочкой: новую версию ядра нельзя устанавливать вместе с этой оболочкой, не было обработчиков транспорта: новое ядро отклоняет прежнюю версию, а не запускает
загрузчик отклонит такую пару. Старые JAR следует архивировать, не оставляя дубликатов. мир с отсутствующей механикой. Ядро и модуль обновляются вместе. Старые JAR следует
архивировать, не оставляя дубликатов.
Модели, переводы и рельсы пока остаются входами сборки AstraPlus. Существующие ресурсы, Модели, переводы и рельсы пока остаются входами сборки AstraPlus. Существующие ресурсы,
настройки и миры не заменяются. Это частичное, а не завершённое разделение всех механик. настройки и миры не заменяются. Это частичное, а не завершённое разделение всех механик.
При выключенной стартовой сборке ресурспака выполнить `/astraplus build`. При выключенной стартовой сборке ресурспака выполнить `/astraplus build`.
@@ -140,12 +144,19 @@ Shift + ПКМ киркой по выбранному торцу снимает
Глобальные правила транспорта и боеприпасов находятся в `src/main/resources/content/policies`: Глобальные правила транспорта и боеприпасов находятся в `src/main/resources/content/policies`:
`transport-defaults.json` и `projectile-defaults.json` — реальные настраиваемые политики, `transport-defaults.json` и `projectile-defaults.json` — реальные настраиваемые политики,
соответствующие `*-schema.json` — формы Studio. `*-compatibility.json` сохраняют прежние соответствующие `*-schema.json` — формы Studio. `*-compatibility.json` сохраняют прежние
ключи миров, идентичности и командные псевдонимы. Боеприпасы исполняет Java-модуль этого ключи миров, идентичности и командные псевдонимы. Обе политики исполняет Java-модуль этого
репозитория; транспорт пока исполняет AstraPlus. Сохранение `astracontent:projectiles` репозитория. Сохранение `astracontent:projectiles` и `astracontent:transport` в Studio
в Studio проверяет и обновляет именно `config/astracontent-projectiles.json` и текущий обновляет соответственно `config/astracontent-projectiles.json` и
обработчик. При старте и перезапуске существующий файл сохраняется, некорректный файл `config/astracontent-transport.json`, а также текущий обработчик. Существующие файлы
не заменяется значениями по умолчанию. Селектор пользовательских предметов использует не заменяются значениями по умолчанию. Селектор боеприпасов использует публичный
публичный `AstraPlusApi.identify`, а не внутренние классы ядра. `AstraPlusApi.identify`, а не внутренние классы ядра.
Транспорт объявляет прежние вложения чанков до заморозки реестров и запускается после
публикации API, до загрузки сущностей мира. Имена `AstraContentSpeed`, `AstraTrainFrontX`,
`AstraTrainFrontZ` и `astracontent:trains` сохранены. При остановке обработчики отключаются,
но ключи сериализации остаются доступны до завершения ванильного сохранения. Удаление
модуля из существующего мира не является процедурой безопасного удаления его данных:
обновляйте оба JAR вместе, сохраняя резервную копию мира.
Это настраиваемые правила, не полная реализация обработчика узлами. `_astra.logic` Это настраиваемые правила, не полная реализация обработчика узлами. `_astra.logic`
остаётся дополнительным графом; перенос файлов между модулями этого ограничения не снимает. остаётся дополнительным графом; перенос файлов между модулями этого ограничения не снимает.
@@ -154,6 +165,7 @@ Shift + ПКМ киркой по выбранному торцу снимает
.\gradlew.bat build .\gradlew.bat build
.\gradlew.bat integrationTest .\gradlew.bat integrationTest
.\gradlew.bat integrationTest -Pexperimental .\gradlew.bat integrationTest -Pexperimental
.\gradlew.bat integrationTest -PupgradeFrom="build/verification-YYYYMMDD-HHMMSS"
``` ```
Для запуска серверных проверок нужны PowerShell 7 и соседние сборки AstraPlus/AstraPacks. Для запуска серверных проверок нужны PowerShell 7 и соседние сборки AstraPlus/AstraPacks.
@@ -163,16 +175,22 @@ AstraPlus/AstraPacks/AstraContent с отдельным тестовым мод
без AstraContent находится в `AstraPlus/src/integrationTest/.../ContentBoundarySmoke.java`. без AstraContent находится в `AstraPlus/src/integrationTest/.../ContentBoundarySmoke.java`.
Перед ними нужно собрать соседний дистрибутив AstraPlus. Рабочие миры и конфигурации Перед ними нужно собрать соседний дистрибутив AstraPlus. Рабочие миры и конфигурации
при проверках не используются. при проверках не используются.
Проверка состава стартового набора рассчитана на AstraPlus 0.9.12: три оставшиеся Проверка состава стартового набора рассчитана на AstraPlus 0.9.13: две оставшиеся
политики ядра, без модуля котлов. Основной JAR AstraContent сохраняет совместимость политики ядра и две политики AstraContent, без модуля котлов.
с AstraPlus 0.9.11; изменение этого теста не добавляет новой зависимости runtime.
Отдельная проверка несовместимого обновления запускает AstraPlus 0.9.11 со старой Для `upgradeFrom` укажите успешный старый прогон из `build/verification-*`, созданный
оболочкой AstraContent 0.2.4 и требует отказа загрузчика именно по диапазону версии, с AstraPlus 0.9.12 и AstraContent 0.2.5. Проверяются реальные версии старых JAR и
результаты обеих фаз. Мир, конфигурации и контрольные объекты копируются в новый
каталог `build`; исходный прогон не изменяется. Проверяется загрузка старых вагонеток
и сцепок новым модулем, а не только перезапуск одной версии. Рабочий мир и каталоги
со ссылками для этого режима не принимаются.
Отдельная проверка несовместимого обновления запускает AstraPlus 0.9.13 со старым
AstraContent 0.2.5 и требует отказа загрузчика именно по диапазону версии,
до открытия мира. После обновления передайте сохранённый архивный JAR: до открытия мира. После обновления передайте сохранённый архивный JAR:
```powershell ```powershell
.\gradlew.bat compatibilityTest -PoldContentJar="C:/path/to/archive/AstraContent-0.2.4.jar" .\gradlew.bat compatibilityTest -PoldContentJar="C:/path/to/archive/AstraContent-0.2.5.jar"
``` ```
`src/integrationTest/compatibility.ps1` ограничивает время запуска и завершает только `src/integrationTest/compatibility.ps1` ограничивает время запуска и завершает только
+5 -3
View File
@@ -3,12 +3,12 @@ plugins {
id("net.neoforged.moddev") version "2.0.146" id("net.neoforged.moddev") version "2.0.146"
} }
group = "online.astradev" group = "online.astradev"
version = "0.2.5" version = "0.2.6"
repositories { mavenCentral() } repositories { mavenCentral() }
val astraPlusApi = providers.gradleProperty("astraPlusApi") val astraPlusApi = providers.gradleProperty("astraPlusApi")
.orElse("../AstraPlus/build/libs/AstraPlus-0.9.11-api.jar") .orElse("../AstraPlus/build/libs/AstraPlus-0.9.13-api.jar")
val astraPlusRuntime = providers.gradleProperty("astraPlusRuntime") val astraPlusRuntime = providers.gradleProperty("astraPlusRuntime")
.orElse("../AstraPlus/build/libs/AstraPlus-0.9.11.jar") .orElse("../AstraPlus/build/libs/AstraPlus-0.9.13.jar")
dependencies { dependencies {
compileOnly(files(astraPlusApi)) compileOnly(files(astraPlusApi))
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
@@ -60,6 +60,8 @@ tasks.register<Exec>("integrationTest") {
dependsOn("build", "integrationTestJar") dependsOn("build", "integrationTestJar")
commandLine("pwsh", "-NoProfile", "-File", "src/integrationTest/run.ps1") commandLine("pwsh", "-NoProfile", "-File", "src/integrationTest/run.ps1")
if (providers.gradleProperty("experimental").isPresent) args("-Experimental") if (providers.gradleProperty("experimental").isPresent) args("-Experimental")
providers.gradleProperty("upgradeFrom").orNull?.let { args("-UpgradeFrom", it) }
providers.gradleProperty("astraPlusRuntime").orNull?.let { args("-PlusJar", it) }
} }
tasks.register<Exec>("compatibilityTest") { tasks.register<Exec>("compatibilityTest") {
+9 -9
View File
@@ -9,8 +9,8 @@ $ErrorActionPreference = 'Stop'
$project = (Resolve-Path -LiteralPath "$PSScriptRoot/../..").Path $project = (Resolve-Path -LiteralPath "$PSScriptRoot/../..").Path
$runtime = (Resolve-Path -LiteralPath $ServerRoot).Path $runtime = (Resolve-Path -LiteralPath $ServerRoot).Path
$plusRoot = Join-Path (Split-Path $project -Parent) 'AstraPlus' $plusRoot = Join-Path (Split-Path $project -Parent) 'AstraPlus'
if (!$PlusJar) { $PlusJar = Join-Path $plusRoot 'build/libs/AstraPlus-0.9.11.jar' } if (!$PlusJar) { $PlusJar = Join-Path $plusRoot 'build/libs/AstraPlus-0.9.13.jar' }
if (!$OldContentJar) { $OldContentJar = Join-Path $runtime 'mods/AstraContent-0.2.4.jar' } if (!$OldContentJar) { $OldContentJar = Join-Path $runtime 'mods/AstraContent-0.2.5.jar' }
$plus = (Get-Item -LiteralPath $PlusJar).FullName $plus = (Get-Item -LiteralPath $PlusJar).FullName
$oldContent = (Get-Item -LiteralPath $OldContentJar).FullName $oldContent = (Get-Item -LiteralPath $OldContentJar).FullName
$acceptedEula = Join-Path $runtime 'eula.txt' $acceptedEula = Join-Path $runtime 'eula.txt'
@@ -19,7 +19,7 @@ if (!(Test-Path -LiteralPath $acceptedEula) -or
throw 'The server owner must have accepted the Minecraft EULA before this test can run.' throw 'The server owner must have accepted the Minecraft EULA before this test can run.'
} }
# Refuse misleading inputs: this regression is specifically about the old shell mod. # Refuse misleading inputs: this regression targets the version before transport moved here.
Add-Type -AssemblyName System.IO.Compression.FileSystem Add-Type -AssemblyName System.IO.Compression.FileSystem
function Assert-ModVersion([string]$Path, [string]$Id, [string]$Version) { function Assert-ModVersion([string]$Path, [string]$Id, [string]$Version) {
$archive = [IO.Compression.ZipFile]::OpenRead($Path) $archive = [IO.Compression.ZipFile]::OpenRead($Path)
@@ -33,8 +33,8 @@ function Assert-ModVersion([string]$Path, [string]$Id, [string]$Version) {
if ($metadata -notmatch $pattern) { throw "Expected $Id $Version in $Path" } if ($metadata -notmatch $pattern) { throw "Expected $Id $Version in $Path" }
} finally { $archive.Dispose() } } finally { $archive.Dispose() }
} }
Assert-ModVersion $plus 'astraplus' '0.9.11' Assert-ModVersion $plus 'astraplus' '0.9.13'
Assert-ModVersion $oldContent 'astracontent' '0.2.4' Assert-ModVersion $oldContent 'astracontent' '0.2.5'
$output = Join-Path $project ('build/compatibility-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) $output = Join-Path $project ('build/compatibility-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0, 8))
New-Item -ItemType Directory -Path "$output/mods", "$output/config" | Out-Null New-Item -ItemType Directory -Path "$output/mods", "$output/config" | Out-Null
@@ -95,16 +95,16 @@ try {
$errText | Set-Content -LiteralPath "$output/stderr.log" $errText | Set-Content -LiteralPath "$output/stderr.log"
$log = $outText + "`n" + $errText $log = $outText + "`n" + $errText
if ($exitCode -eq 0) { throw "Incompatible mods unexpectedly exited successfully. Evidence: $output" } if ($exitCode -eq 0) { throw "Incompatible mods unexpectedly exited successfully. Evidence: $output" }
$dependencyError = "(?s)Mod ID: 'astracontent', Requested by: 'astraplus', Expected range: '\[0\.2\.5,\)', Actual version: '0\.2\.4'" $dependencyError = "(?s)Mod ID: 'astracontent', Requested by: 'astraplus', Expected range: '\[0\.2\.6,\)', Actual version: '0\.2\.5'"
$translatedError = '(?is)Mod astraplus only supports astracontent 0\.2\.5 or above\s*Currently,? astracontent is 0\.2\.4' $translatedError = '(?is)Mod astraplus only supports astracontent 0\.2\.6 or above\s*Currently,? astracontent is 0\.2\.5'
if ($log -notmatch $dependencyError -and $log -notmatch $translatedError) { if ($log -notmatch $dependencyError -and $log -notmatch $translatedError) {
throw "Failure was not the expected AstraPlus -> AstraContent [0.2.5,) / actual 0.2.4 dependency rejection. Evidence: $output" throw "Failure was not the expected AstraPlus -> AstraContent [0.2.6,) / actual 0.2.5 dependency rejection. Evidence: $output"
} }
if ((Test-Path -LiteralPath "$output/compatibility-world") -or (Test-Path -LiteralPath "$output/world") -or if ((Test-Path -LiteralPath "$output/compatibility-world") -or (Test-Path -LiteralPath "$output/world") -or
$log -match 'Preparing level|Preparing start region|Done \([\d.,]+s\)!') { $log -match 'Preparing level|Preparing start region|Done \([\d.,]+s\)!') {
throw "Loader opened a world despite incompatible mods. Evidence: $output" throw "Loader opened a world despite incompatible mods. Evidence: $output"
} }
$result = "PASS compatibility: AstraPlus 0.9.11 rejects AstraContent 0.2.4 for [0.2.5,), exit=$exitCode, no world opened" $result = "PASS compatibility: AstraPlus 0.9.13 rejects AstraContent 0.2.5 for [0.2.6,), exit=$exitCode, no world opened"
$result | Set-Content -LiteralPath "$output/verification-result.txt" $result | Set-Content -LiteralPath "$output/verification-result.txt"
Write-Output $result Write-Output $result
Write-Output "Evidence: $output" Write-Output "Evidence: $output"
@@ -32,8 +32,8 @@ import net.neoforged.neoforge.common.util.FakePlayerFactory;
import net.neoforged.neoforge.event.tick.ServerTickEvent; import net.neoforged.neoforge.event.tick.ServerTickEvent;
import online.astradev.content.rail.*; import online.astradev.content.rail.*;
import online.astradev.plus.capability.transport.rail.CartSpeed; import online.astradev.content.transport.rail.CartSpeed;
import online.astradev.plus.capability.transport.rail.RailSpeed; import online.astradev.content.transport.rail.RailSpeed;
import online.astradev.plus.api.AstraPlusApi; import online.astradev.plus.api.AstraPlusApi;
import online.astradev.plus.effect.EffectDisplay; import online.astradev.plus.effect.EffectDisplay;
@@ -50,6 +50,7 @@ public final class ContentVerification {
public ContentVerification() { public ContentVerification() {
if (!Boolean.getBoolean("astracontent.verify")) if (!Boolean.getBoolean("astracontent.verify"))
throw new IllegalStateException("Isolated test server only"); throw new IllegalStateException("Isolated test server only");
TransportBoundaryVerification.register();
NeoForge.EVENT_BUS.addListener(this::tick); NeoForge.EVENT_BUS.addListener(this::tick);
} }
@@ -65,6 +66,7 @@ public final class ContentVerification {
server.createCommandSourceStack(), "forceload add 0 0 159 95"); server.createCommandSourceStack(), "forceload add 0 0 159 95");
if (ticks == 20) { if (ticks == 20) {
StarterBundleVerification.run(); StarterBundleVerification.run();
TransportBoundaryVerification.run(level);
require( require(
AbstractMinecart.useExperimentalMovement(level) AbstractMinecart.useExperimentalMovement(level)
== Boolean.getBoolean("astracontent.expectedExperimental"), == Boolean.getBoolean("astracontent.expectedExperimental"),
@@ -96,7 +98,7 @@ public final class ContentVerification {
Math.abs(((CartSpeed) saved).astraplus$transportLimit(level) - 1) < .001, Math.abs(((CartSpeed) saved).astraplus$transportLimit(level) - 1) < .001,
"personal speed survives restart on ordinary rails"); "personal speed survives restart on ordinary rails");
require( require(
online.astradev.plus.capability.transport.train.CouplingGeometry.front((AbstractMinecart) saved).x < -.99, online.astradev.content.transport.train.CouplingGeometry.front((AbstractMinecart) saved).x < -.99,
"physical front survives restart independently of saved yaw"); "physical front survives restart independently of saved yaw");
TrainVerification.restart(level); TrainVerification.restart(level);
finish( finish(
@@ -149,7 +151,7 @@ public final class ContentVerification {
saved.setPos(30.5, 100.0625, 40.5); saved.setPos(30.5, 100.0625, 40.5);
saved.setDeltaMovement(Vec3.ZERO); saved.setDeltaMovement(Vec3.ZERO);
saved.setYRot(0); saved.setYRot(0);
online.astradev.plus.capability.transport.train.CouplingGeometry.restoreFront(saved, new Vec3(-1, 0, 0)); online.astradev.content.transport.train.CouplingGeometry.restoreFront(saved, new Vec3(-1, 0, 0));
require(Math.abs(((CartSpeed) saved).astraplus$transportLimit(level) - 1) < .001, require(Math.abs(((CartSpeed) saved).astraplus$transportLimit(level) - 1) < .001,
"personal speed exists before shutdown on ordinary rails"); "personal speed exists before shutdown on ordinary rails");
level.addFreshEntity(saved); level.addFreshEntity(saved);
@@ -282,7 +284,7 @@ public final class ContentVerification {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static online.astradev.plus.api.content.BlockData<Integer> previousRailData() private static online.astradev.plus.api.content.BlockData<Integer> previousRailData()
throws Exception { throws Exception {
var field = online.astradev.plus.capability.transport.LegacyBlockMappings.class.getDeclaredField("mappings"); var field = online.astradev.content.transport.LegacyBlockMappings.class.getDeclaredField("mappings");
field.setAccessible(true); field.setAccessible(true);
var mapping = ((java.util.List<?>) field.get(null)).getFirst(); var mapping = ((java.util.List<?>) field.get(null)).getFirst();
var data = mapping.getClass().getDeclaredField("data"); var data = mapping.getClass().getDeclaredField("data");
@@ -14,13 +14,13 @@ import java.util.Map;
import java.util.HashSet; import java.util.HashSet;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** Runs before gameplay with core declarations plus the separately owned projectile content mod. */ /** Runs before gameplay with core declarations plus the separately owned content runtimes. */
final class StarterBundleVerification { final class StarterBundleVerification {
static void run() throws Exception { static void run() throws Exception {
for (String forbidden : new String[]{"astracauldron", "astraspears"}) for (String forbidden : new String[]{"astracauldron", "astraspears"})
require(!ModList.get().isLoaded(forbidden), "Concrete mod is not required: " + forbidden); require(!ModList.get().isLoaded(forbidden), "Concrete mod is not required: " + forbidden);
require(ModList.get().isLoaded("astraplus") && ModList.get().isLoaded("astrapacks"), "Two distribution mods loaded"); require(ModList.get().isLoaded("astraplus") && ModList.get().isLoaded("astrapacks"), "Two distribution mods loaded");
require(ModList.get().isLoaded("astracontent"), "Projectile verification loads its real content owner JAR"); require(ModList.get().isLoaded("astracontent"), "Transport and projectile verification loads its real content owner JAR");
var kindMap = Map.of("items", SnapshotKind.ITEM, "blocks", SnapshotKind.BLOCK, var kindMap = Map.of("items", SnapshotKind.ITEM, "blocks", SnapshotKind.BLOCK,
"mobs", SnapshotKind.MOB, "skills", SnapshotKind.SKILL, "recipes", SnapshotKind.RECIPE, "mobs", SnapshotKind.MOB, "skills", SnapshotKind.SKILL, "recipes", SnapshotKind.RECIPE,
"enchantments", SnapshotKind.ENCHANTMENT, "effects", SnapshotKind.EFFECT, "enchantments", SnapshotKind.ENCHANTMENT, "effects", SnapshotKind.EFFECT,
@@ -48,7 +48,7 @@ final class StarterBundleVerification {
require(document.source() == SnapshotSource.FILE && !document.readOnly(), "Authored declaration is editable FILE: " + id); require(document.source() == SnapshotSource.FILE && !document.readOnly(), "Authored declaration is editable FILE: " + id);
editable++; editable++;
} }
require(manifest.getAsJsonArray("capabilities").size() == 3, "Three remaining core capability policies; cauldrons belong to their optional module"); require(manifest.getAsJsonArray("capabilities").size() == 2, "Two remaining core capability policies; transport, projectiles and cauldrons belong to their optional modules");
for (var value : manifest.getAsJsonArray("capabilities")) { for (var value : manifest.getAsJsonArray("capabilities")) {
var policy = value.getAsJsonObject(); var policy = value.getAsJsonObject();
String id = policy.get("id").getAsString(); String id = policy.get("id").getAsString();
@@ -58,17 +58,21 @@ final class StarterBundleVerification {
require(document != null && document.source() == SnapshotSource.FILE && !document.readOnly(), "Live FILE policy is editable: " + id); require(document != null && document.source() == SnapshotSource.FILE && !document.readOnly(), "Live FILE policy is editable: " + id);
} }
require(!expectedProviders.contains("astracontent:projectiles"), "Core starter no longer owns projectile policy"); require(!expectedProviders.contains("astracontent:projectiles"), "Core starter no longer owns projectile policy");
require(!expectedProviders.contains("astracontent:transport"), "Core starter no longer owns transport policy");
require(expectedProviders.contains("astraplus:villager_appearance"), "Native villager appearance is editable policy data"); require(expectedProviders.contains("astraplus:villager_appearance"), "Native villager appearance is editable policy data");
expectedProviders.add("astracontent:projectiles"); for (String capability : new String[]{"projectiles", "transport"}) {
var projectile = documents.get(SnapshotKind.MECHANIC + ":astracontent:projectiles"); String id = "astracontent:" + capability;
require(projectile != null && projectile.source() == SnapshotSource.FILE && !projectile.readOnly(), "Content-owned projectile policy stays editable through the public snapshot"); expectedProviders.add(id);
require(Files.isRegularFile(FMLPaths.GAMEDIR.get().resolve("config/astracontent-projectiles.json")), "Content-owned projectile FILE is installed"); var document = documents.get(SnapshotKind.MECHANIC + ":" + id);
require(document != null && document.source() == SnapshotSource.FILE && !document.readOnly(), "Content-owned policy stays editable through the public snapshot: " + id);
require(Files.isRegularFile(FMLPaths.GAMEDIR.get().resolve("config/astracontent-" + capability + ".json")), "Content-owned FILE is installed: " + id);
}
require(EditorDefinitions.all().stream().map(value -> value.id()).collect(Collectors.toSet()).equals(expectedProviders), "Only the declared live providers are installed"); require(EditorDefinitions.all().stream().map(value -> value.id()).collect(Collectors.toSet()).equals(expectedProviders), "Only the declared live providers are installed");
} }
require(installed == 186 && editable == installed, "Exact authored editable content file count: " + installed); require(installed == 186 && editable == installed, "Exact authored editable content file count: " + installed);
require(modelFiles == 142 && documents.values().stream().filter(document -> document.kind() == SnapshotKind.MODEL).count() == 142, "All 142 authored models appear in the public runtime snapshot"); require(modelFiles == 142 && documents.values().stream().filter(document -> document.kind() == SnapshotKind.MODEL).count() == 142, "All 142 authored models appear in the public runtime snapshot");
System.out.println("PASS modular distribution: contentFiles=" + installed + " editableCatalog=" + editable System.out.println("PASS modular distribution: contentFiles=" + installed + " editableCatalog=" + editable
+ " models=" + modelFiles + " coreMechanics=3; contentProjectileMechanics=1"); + " models=" + modelFiles + " coreMechanics=2; contentProjectileAndTransportMechanics=2");
} }
private static void require(boolean condition, String message) { if (!condition) throw new AssertionError(message); } private static void require(boolean condition, String message) { if (!condition) throw new AssertionError(message); }
@@ -10,7 +10,7 @@ import net.minecraft.world.level.block.state.properties.RailShape;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
import online.astradev.content.rail.*; import online.astradev.content.rail.*;
import online.astradev.plus.capability.transport.rail.RailSpeed; import online.astradev.content.transport.rail.RailSpeed;
import java.util.*; import java.util.*;
@@ -15,8 +15,8 @@ import net.minecraft.world.phys.*;
import net.neoforged.neoforge.common.util.FakePlayerFactory; import net.neoforged.neoforge.common.util.FakePlayerFactory;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
import online.astradev.plus.capability.transport.train.*; import online.astradev.content.transport.train.*;
import online.astradev.plus.capability.transport.collision.SurfaceBounce; import online.astradev.content.transport.collision.SurfaceBounce;
import online.astradev.plus.api.BlockLine; import online.astradev.plus.api.BlockLine;
import java.nio.file.*; import java.nio.file.*;
@@ -0,0 +1,188 @@
package online.astradev.content.verification;
import com.google.gson.JsonParser;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.fml.loading.FMLPaths;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
import net.neoforged.neoforge.event.level.LevelEvent;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import online.astradev.content.AstraContent;
import online.astradev.content.transport.LegacyBlockMappings;
import online.astradev.content.transport.TransportCapabilities;
import online.astradev.content.transport.TransportPersistence;
import online.astradev.content.transport.collision.SurfaceBounce;
import online.astradev.content.transport.rail.CartSpeed;
import online.astradev.content.transport.rail.RailSpeed;
import online.astradev.content.transport.train.CouplingGeometry;
import online.astradev.content.transport.train.TrainData;
import online.astradev.content.transport.train.Trains;
import online.astradev.plus.api.AstraPlusApi;
import online.astradev.plus.api.RailBehavior;
import online.astradev.plus.api.editor.EditorDefinitions;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/** Checks the ownership and the load ordering that a normal post-start gameplay test can miss. */
final class TransportBoundaryVerification {
private static final List<String> MIXINS = List.of(
"TransportBoatPacketMixin", "TransportExperimentalCartMixin", "TransportFurnaceCartMixin",
"TransportMinecartMixin", "TransportSlimeCollisionMixin", "TransportTrainCartMixin",
"LegacyDataBlockPlacementMixin");
private static Path config;
private static byte[] existingConfig;
private static UUID savedCart;
private static boolean levelLoaded;
private static boolean activeBeforeWorldLoad = true;
private static boolean speedRuntimeBeforeWorldLoad = true;
private static boolean savedCartJoined;
private static boolean savedSpeedLoaded;
private static boolean savedFrontLoaded;
private TransportBoundaryVerification() {}
static void register() {
try {
config = FMLPaths.GAMEDIR.get().resolve("config/astracontent-transport.json");
if (!Files.exists(config)) {
// A pre-existing file must not be replaced or reformatted by the new owner.
Files.createDirectories(config.getParent());
Files.writeString(config, resource(AstraContent.class,
"/content/policies/transport-defaults.json") + "\n\n", StandardCharsets.UTF_8);
}
existingConfig = Files.readAllBytes(config);
if (Files.exists(Path.of("first-pass.txt"))) {
savedCart = UUID.fromString(Files.readString(Path.of("saved-cart.txt")));
}
} catch (IOException error) {
throw new IllegalStateException("Cannot prepare isolated transport verification", error);
}
NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, TransportBoundaryVerification::levelLoad);
NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, TransportBoundaryVerification::entityLoad);
NeoForge.EVENT_BUS.addListener(EventPriority.LOW, TransportBoundaryVerification::stopping);
}
private static void levelLoad(LevelEvent.Load event) {
if (!(event.getLevel() instanceof ServerLevel)) return;
levelLoaded = true;
activeBeforeWorldLoad &= TransportCapabilities.active()
&& TransportCapabilities.persistence() != null
&& EditorDefinitions.find("astracontent:transport").isPresent();
speedRuntimeBeforeWorldLoad &= RailBehavior.speedRuntimeAvailable();
}
private static void entityLoad(EntityJoinLevelEvent event) {
if (savedCart == null || !event.getEntity().getUUID().equals(savedCart)
|| !(event.getLevel() instanceof ServerLevel level)
|| !(event.getEntity() instanceof AbstractMinecart cart)) return;
savedCartJoined = true;
// The saved cart is on ordinary rails: no regulator can repair a missed NBT read.
savedSpeedLoaded = Math.abs(((CartSpeed) cart).astraplus$transportLimit(level) - 1) < .001;
savedFrontLoaded = CouplingGeometry.front(cart).x < -.99;
}
private static void stopping(ServerStoppingEvent event) {
// Module shutdown runs at NORMAL; vanilla entity/SavedData writes happen afterwards.
require(!TransportCapabilities.active(), "Transport stops before the final vanilla save");
require(!RailBehavior.speedRuntimeAvailable(),
"The public speed-runtime availability is revoked when the content module stops");
require(EditorDefinitions.find("astracontent:transport").isEmpty(),
"Stopping the module unregisters its editor policy");
require(TransportCapabilities.persistence() != null,
"Serialization keys outlive live transport behavior for the final save");
try {
UUID id = UUID.fromString(Files.readString(Path.of("saved-cart.txt")));
var level = event.getServer().overworld();
var cart = level.getEntity(id);
require(cart instanceof CartSpeed && ((CartSpeed) cart).astraplus$transportLimit(level) == 0,
"Stopped module returns vanilla speed without erasing the stored regulator speed");
} catch (IOException error) {
throw new IllegalStateException("Cannot verify the final cart save", error);
}
System.out.println("PASS transport shutdown: editor removed, vanilla speed restored, serialization retained for final save");
}
static void run(ServerLevel level) throws Exception {
require(levelLoaded && activeBeforeWorldLoad,
"Transport policy and persistence are available before the first world load");
require(levelLoaded && speedRuntimeBeforeWorldLoad,
"The public speed-runtime availability is published before the first world load");
require(Arrays.equals(existingConfig, Files.readAllBytes(config)),
"Existing transport config keeps its exact path and bytes on both launches");
require(TransportCapabilities.active(), "The content-owned transport runtime is active");
require(RailBehavior.speedRuntimeAvailable(),
"The public API reports the running content-owned speed handler");
var owner = AstraContent.class.getProtectionDomain().getCodeSource().getLocation();
for (Class<?> type : List.of(TransportCapabilities.class, TransportPersistence.class,
LegacyBlockMappings.class, RailSpeed.class, CartSpeed.class, Trains.class,
TrainData.class, CouplingGeometry.class, SurfaceBounce.class)) {
require(owner.equals(type.getProtectionDomain().getCodeSource().getLocation()),
"Transport runtime class belongs to the actual AstraContent JAR: " + type.getName());
missing(type.getName().replace("online.astradev.content.transport.",
"online.astradev.plus.capability.transport."));
}
var contentMixins = JsonParser.parseString(resource(AstraContent.class,
"/astracontent.mixins.json")).getAsJsonObject();
require(contentMixins.get("package").getAsString().equals("online.astradev.content.mixin"),
"Native transport hooks belong to the content module");
var coreMixins = JsonParser.parseString(resource(AstraPlusApi.class,
"/astraplus.mixins.json")).getAsJsonObject().getAsJsonArray("mixins");
for (String name : MIXINS) {
require(contentMixins.getAsJsonArray("mixins").asList().stream()
.anyMatch(value -> value.getAsString().equals(name)),
"Content installs its native hook: " + name);
require(coreMixins.asList().stream().noneMatch(value -> value.getAsString().equals(name)),
"Core does not install the content hook: " + name);
require(AstraPlusApi.class.getResource("/online/astradev/plus/mixin/" + name + ".class") == null,
"Old core hook class is absent: " + name);
}
for (var entry : Map.of("cartSpeedKey", "AstraContentSpeed", "frontXKey", "AstraTrainFrontX",
"frontZKey", "AstraTrainFrontZ", "trainStorageId", "astracontent:trains").entrySet()) {
require(TransportCapabilities.storage(entry.getKey()).equals(entry.getValue()),
"Existing saved transport identity is unchanged: " + entry.getKey());
}
var root = level.getServer().getCommands().getDispatcher().getRoot().getChild("astracontent");
require(root != null && root.getChild("give") != null, "Previous /astracontent give command survives");
for (String name : List.of("copper_rail", "exposed_copper_rail", "weathered_copper_rail",
"oxidized_copper_rail", "waxed_copper_rail", "waxed_exposed_copper_rail",
"waxed_weathered_copper_rail", "waxed_oxidized_copper_rail")) {
require(root.getChild("give").getChild(name) != null, "Previous rail command alias survives: " + name);
}
if (savedCart != null) {
require(savedCartJoined && savedSpeedLoaded && savedFrontLoaded,
"Saved cart speed and physical front are restored on entity join before its first tick");
}
System.out.println("PASS transport boundary: content-owned runtime and hooks, no old core classes,"
+ " unchanged config and saved keys, command aliases, policy ready before world load"
+ (savedCart != null ? ", speed and front restored before the first entity tick" : ""));
}
private static String resource(Class<?> owner, String path) throws IOException {
try (var stream = owner.getResourceAsStream(path)) {
if (stream == null) throw new IOException("Missing required resource " + path);
return new String(stream.readAllBytes(), StandardCharsets.UTF_8);
}
}
private static void missing(String name) {
try {
Class.forName(name, false, ContentVerification.class.getClassLoader());
throw new AssertionError("Old core runtime class remains loadable: " + name);
} catch (ClassNotFoundException expected) {
// Only the content implementation should be present in this distribution.
}
}
private static void require(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
}
+117 -6
View File
@@ -1,10 +1,110 @@
param([string]$ServerRoot='C:\Users\ScarPC\Documents\NeoForge Server 26.2',[switch]$Experimental,[string]$PlusJar) param(
[string]$ServerRoot='C:\Users\ScarPC\Documents\NeoForge Server 26.2',
[switch]$Experimental,
[string]$PlusJar,
[string]$UpgradeFrom
)
$ErrorActionPreference='Stop' $ErrorActionPreference='Stop'
$project=(Resolve-Path "$PSScriptRoot/../..").Path $project=(Resolve-Path "$PSScriptRoot/../..").Path
function Assert-PlainTree([string]$Root) {
$pending = [Collections.Generic.Stack[string]]::new()
$pending.Push($Root)
while ($pending.Count -gt 0) {
$entry = Get-Item -Force -LiteralPath $pending.Pop()
if (($entry.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
throw "Upgrade fixtures cannot contain links or reparse points: $($entry.FullName)"
}
if ($entry.PSIsContainer) {
foreach ($child in Get-ChildItem -Force -LiteralPath $entry.FullName) {
$pending.Push($child.FullName)
}
}
}
}
function Assert-OldMod([string]$Jar, [string]$Id, [string]$Version) {
$archive = [IO.Compression.ZipFile]::OpenRead($Jar)
try {
$entry = $archive.GetEntry('META-INF/neoforge.mods.toml')
if (!$entry) { throw "Missing mod metadata: $Jar" }
$reader = [IO.StreamReader]::new($entry.Open())
try { $metadata = $reader.ReadToEnd() } finally { $reader.Dispose() }
$mods = [regex]::Matches($metadata, '(?ms)^\[\[mods\]\]\s*(.*?)(?=^\[|\z)')
$matching = @($mods | Where-Object {
$_.Groups[1].Value -match ('(?m)^modId\s*=\s*"' + [regex]::Escape($Id) + '"\s*$')
})
if ($matching.Count -ne 1 -or $matching[0].Groups[1].Value -notmatch
('(?m)^version\s*=\s*"' + [regex]::Escape($Version) + '"\s*$')) {
throw "Upgrade fixture must contain the actual $Id $Version JAR: $Jar"
}
} finally { $archive.Dispose() }
}
$upgradeSource = $null
if ($UpgradeFrom) {
if ($Experimental) { throw 'UpgradeFrom uses an existing stable world; do not combine it with Experimental.' }
$buildRoot = [IO.Path]::GetFullPath((Join-Path $project 'build'))
$upgradeSource = (Get-Item -Force -LiteralPath $UpgradeFrom).FullName
if (!(Split-Path $upgradeSource -Parent).Equals($buildRoot, [StringComparison]::OrdinalIgnoreCase) -or
(Split-Path $upgradeSource -Leaf) -notmatch '^verification-\d{8}-\d{6}(?:-[a-f0-9]+)?$') {
throw 'UpgradeFrom must be an existing verification-* directory directly inside this project build directory.'
}
# Check all ancestors and then every entry without traversing links. No user or live
# world outside this project can be reached through a junction in an accepted fixture.
for ($ancestor = Get-Item -Force -LiteralPath $upgradeSource; $null -ne $ancestor; $ancestor = $ancestor.Parent) {
if (($ancestor.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
throw "Upgrade source has a linked ancestor: $($ancestor.FullName)"
}
}
Assert-PlainTree $upgradeSource
foreach ($pass in @('gameplay', 'restart')) {
$marker = Join-Path $upgradeSource "$pass-result.txt"
if (!(Test-Path -LiteralPath $marker -PathType Leaf) -or
!(Get-Content -Raw -LiteralPath $marker).StartsWith("PASS $pass")) {
throw "Upgrade source is not a successful old gameplay/restart run: $marker"
}
}
if ((Get-Content -Raw -LiteralPath (Join-Path $upgradeSource 'first-pass.txt')).Trim() -ne 'PASS') {
throw 'Upgrade source has no valid saved gameplay fixture.'
}
foreach ($directory in @('world', 'config', 'astraplus')) {
if (!(Test-Path -LiteralPath (Join-Path $upgradeSource $directory) -PathType Container)) {
throw "Missing upgrade fixture directory: $directory"
}
}
foreach ($file in @('saved-cart.txt', 'saved-train.txt')) {
if (!(Test-Path -LiteralPath (Join-Path $upgradeSource $file) -PathType Leaf)) {
throw "Missing upgrade fixture: $file"
}
}
$oldProperties = Get-Content -Raw -LiteralPath (Join-Path $upgradeSource 'server.properties')
if ($oldProperties -match '(?m)^initial-enabled-packs\s*=.*minecart_improvements') {
throw 'UpgradeFrom must contain a stable-movement fixture, not an experimental world.'
}
$oldConfig = Get-Content -Raw -LiteralPath (Join-Path $upgradeSource 'config/astraplus.json') | ConvertFrom-Json
$oldPacks = Get-Content -Raw -LiteralPath (Join-Path $upgradeSource 'config/astrapacks.json') | ConvertFrom-Json
if ($oldConfig.editor.enabled -ne $false -or $oldConfig.astraPacks.enabled -ne $false -or $oldPacks.enabled -ne $false) {
throw 'Upgrade fixture must keep the administrator editor and pack web services disabled.'
}
Add-Type -AssemblyName System.IO.Compression.FileSystem
Assert-OldMod (Join-Path $upgradeSource 'mods/AstraPlus-0.9.12.jar') 'astraplus' '0.9.12'
Assert-OldMod (Join-Path $upgradeSource 'mods/AstraContent-0.2.5.jar') 'astracontent' '0.2.5'
}
$java = 'java' $java = 'java'
if ($env:JAVA_HOME) { $java = Join-Path $env:JAVA_HOME 'bin/java.exe' } if ($env:JAVA_HOME) { $java = Join-Path $env:JAVA_HOME 'bin/java.exe' }
$output=Join-Path $project ('build/verification-'+(Get-Date -Format 'yyyyMMdd-HHmmss')) $output=Join-Path $project ('build/verification-'+(Get-Date -Format 'yyyyMMdd-HHmmss')+'-'+[guid]::NewGuid().ToString('N').Substring(0,8))
New-Item -ItemType Directory -Path "$output/mods","$output/config" | Out-Null New-Item -ItemType Directory -Path "$output/mods" | Out-Null
if ($upgradeSource) {
foreach ($name in @('world', 'config', 'astraplus', 'first-pass.txt', 'saved-cart.txt', 'saved-train.txt')) {
Copy-Item -LiteralPath (Join-Path $upgradeSource $name) -Destination $output -Recurse
}
"Read-only source: $upgradeSource`nOld versions: AstraPlus 0.9.12 + AstraContent 0.2.5" |
Set-Content -LiteralPath "$output/upgrade-source.txt"
} else {
New-Item -ItemType Directory -Path "$output/config" | Out-Null
}
$runtime=(Resolve-Path -LiteralPath $ServerRoot).Path.Replace('\','/') $runtime=(Resolve-Path -LiteralPath $ServerRoot).Path.Replace('\','/')
$lines=(Get-Content -Raw "$runtime/libraries/net/neoforged/neoforge/26.2.0.79/win_args.txt").Replace('libraries/',($runtime+'/libraries/')) -split "`r?`n" $lines=(Get-Content -Raw "$runtime/libraries/net/neoforged/neoforge/26.2.0.79/win_args.txt").Replace('libraries/',($runtime+'/libraries/')) -split "`r?`n"
for($i=0;$i -lt $lines.Length;$i++) { for($i=0;$i -lt $lines.Length;$i++) {
@@ -31,26 +131,37 @@ spawn-protection=0
max-tick-time=120000 max-tick-time=120000
'@ | Set-Content "$output/server.properties" '@ | Set-Content "$output/server.properties"
if($Experimental){'initial-enabled-packs=vanilla,minecart_improvements' | Add-Content "$output/server.properties"} if($Experimental){'initial-enabled-packs=vanilla,minecart_improvements' | Add-Content "$output/server.properties"}
'{"build":{"onStartup":true},"astraPacks":{"enabled":false},"editor":{"enabled":false}}' | Set-Content "$output/config/astraplus.json" if (!$upgradeSource) {
'{"build":{"onStartup":true},"astraPacks":{"enabled":false},"editor":{"enabled":false}}' | Set-Content "$output/config/astraplus.json"
}
$plusRoot=Join-Path (Split-Path $project -Parent) 'AstraPlus' $plusRoot=Join-Path (Split-Path $project -Parent) 'AstraPlus'
$plusVersion=[regex]::Match((Get-Content "$plusRoot/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value $plusVersion=[regex]::Match((Get-Content "$plusRoot/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value
$plus=Get-Item -LiteralPath $(if ($PlusJar) { $PlusJar } else { "$plusRoot/build/libs/AstraPlus-$plusVersion.jar" }) $plus=Get-Item -LiteralPath $(if ($PlusJar) { $PlusJar } else { "$plusRoot/build/libs/AstraPlus-$plusVersion.jar" })
$packsRoot=Join-Path (Split-Path $project -Parent) 'AstraPacks' $packsRoot=Join-Path (Split-Path $project -Parent) 'AstraPacks'
$packsVersion=[regex]::Match((Get-Content "$packsRoot/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value $packsVersion=[regex]::Match((Get-Content "$packsRoot/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value
Copy-Item -LiteralPath "$packsRoot/build/libs/AstraPacks-$packsVersion.jar" -Destination "$output/mods" Copy-Item -LiteralPath "$packsRoot/build/libs/AstraPacks-$packsVersion.jar" -Destination "$output/mods"
'{"enabled":false}' | Set-Content "$output/config/astrapacks.json" if (!$upgradeSource) { '{"enabled":false}' | Set-Content "$output/config/astrapacks.json" }
$contentVersion=[regex]::Match((Get-Content "$project/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value $contentVersion=[regex]::Match((Get-Content "$project/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value
Copy-Item -LiteralPath $plus.FullName,"$project/build/libs/AstraContent-$contentVersion.jar","$project/build/libs/AstraContent-$contentVersion-integration-tests.jar" -Destination "$output/mods" Copy-Item -LiteralPath $plus.FullName,"$project/build/libs/AstraContent-$contentVersion.jar","$project/build/libs/AstraContent-$contentVersion-integration-tests.jar" -Destination "$output/mods"
Push-Location $output Push-Location $output
try { try {
foreach($pass in @('gameplay','restart')) { $passes = if ($upgradeSource) { @('restart') } else { @('gameplay','restart') }
foreach($pass in $passes) {
& $java '-Xmx2G' '-Dastracontent.verify=true' "-Dastracontent.expectedExperimental=$($Experimental.IsPresent.ToString().ToLowerInvariant())" '@server-args.txt' nogui *> "$pass.log" & $java '-Xmx2G' '-Dastracontent.verify=true' "-Dastracontent.expectedExperimental=$($Experimental.IsPresent.ToString().ToLowerInvariant())" '@server-args.txt' nogui *> "$pass.log"
if($LASTEXITCODE -ne 0){throw "Server failed: $output/$pass.log"} if($LASTEXITCODE -ne 0){throw "Server failed: $output/$pass.log"}
if(Select-String -Quiet -LiteralPath "$pass.log" -Pattern 'Exception stopping the server|Encountered an unexpected exception|Failed to save chunk|Mixin apply failed'){throw "Server lifecycle failed: $output/$pass.log"} if(Select-String -Quiet -LiteralPath "$pass.log" -Pattern 'Exception stopping the server|Encountered an unexpected exception|Failed to save chunk|Mixin apply failed'){throw "Server lifecycle failed: $output/$pass.log"}
if(!(Select-String -Quiet -LiteralPath "$pass.log" -SimpleMatch 'PASS transport shutdown: editor removed, vanilla speed restored, serialization retained for final save')) {
throw "Transport shutdown contract was not verified: $output/$pass.log"
}
$result=Get-Content -Raw verification-result.txt $result=Get-Content -Raw verification-result.txt
if(!$result.StartsWith("PASS $pass")){throw "Verification failed: $result ($output/$pass.log)"} if(!$result.StartsWith("PASS $pass")){throw "Verification failed: $result ($output/$pass.log)"}
Copy-Item verification-result.txt "$pass-result.txt" Copy-Item verification-result.txt "$pass-result.txt"
Write-Output $result.Trim() Write-Output $result.Trim()
} }
}finally{Pop-Location} }finally{Pop-Location}
if ($upgradeSource) {
$result = "PASS upgrade: old AstraPlus 0.9.12 + AstraContent 0.2.5 world loaded with AstraPlus $plusVersion + AstraContent $contentVersion; source unchanged"
$result | Set-Content -LiteralPath "$output/upgrade-result.txt"
Write-Output $result
}
Write-Output "Evidence: $output" Write-Output "Evidence: $output"
@@ -1,17 +1,22 @@
package online.astradev.content; package online.astradev.content;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.fml.common.Mod; import net.neoforged.fml.common.Mod;
import net.neoforged.fml.loading.FMLPaths; import net.neoforged.fml.loading.FMLPaths;
import net.neoforged.neoforge.common.NeoForge; import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.server.ServerAboutToStartEvent;
import net.neoforged.neoforge.event.server.ServerStartingEvent; import net.neoforged.neoforge.event.server.ServerStartingEvent;
import net.neoforged.neoforge.event.server.ServerStoppedEvent; import net.neoforged.neoforge.event.server.ServerStoppedEvent;
import net.neoforged.neoforge.event.server.ServerStoppingEvent; import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import online.astradev.content.projectile.ProjectileCapabilities; import online.astradev.content.projectile.ProjectileCapabilities;
import online.astradev.content.transport.TransportCapabilities;
import online.astradev.plus.api.AstraPlusApi; import online.astradev.plus.api.AstraPlusApi;
import online.astradev.plus.api.RailBehavior;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -19,17 +24,50 @@ import java.nio.file.Path;
@Mod(value = "astracontent", dist = Dist.DEDICATED_SERVER) @Mod(value = "astracontent", dist = Dist.DEDICATED_SERVER)
public final class AstraContent { public final class AstraContent {
private static final String POLICY_RESOURCES = "/content/policies/projectile-"; private static final String POLICY_RESOURCES = "/content/policies/";
private static final int POLICY_RESOURCE_LIMIT = 512 * 1024; private static final int POLICY_RESOURCE_LIMIT = 512 * 1024;
private ProjectileCapabilities projectiles; private ProjectileCapabilities projectiles;
private final JsonObject transportCompatibility;
private boolean transportStarted;
private RailBehavior.Registration railSpeedRuntime;
public AstraContent() { public AstraContent() {
// Legacy block attachments must be declared before NeoForge freezes its registries.
// This immutable declaration neither starts gameplay nor opens a world/configuration.
try {
transportCompatibility = JsonParser.parseString(resource("transport", "compatibility")).getAsJsonObject();
TransportCapabilities.declareCompatibility(transportCompatibility);
} catch (IOException | RuntimeException failure) {
throw new IllegalStateException("Cannot declare AstraContent transport compatibility", failure);
}
TransportCapabilities.register(NeoForge.EVENT_BUS);
NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::aboutToStart);
NeoForge.EVENT_BUS.addListener(this::start); NeoForge.EVENT_BUS.addListener(this::start);
NeoForge.EVENT_BUS.addListener(this::stopping); NeoForge.EVENT_BUS.addListener(this::stopping);
NeoForge.EVENT_BUS.addListener(this::stopped); NeoForge.EVENT_BUS.addListener(this::stopped);
} }
private void aboutToStart(ServerAboutToStartEvent event) {
if (transportStarted) throw new IllegalStateException("AstraContent transport already started");
// AstraPlus publishes its API at NORMAL priority. Cart speed/front keys must exist
// before vanilla loads entities, not only when ServerStartingEvent is dispatched.
if (AstraPlusApi.current().isEmpty()) {
throw new IllegalStateException("AstraContent requires the running AstraPlus API");
}
try {
TransportCapabilities.start(
FMLPaths.GAMEDIR.get().resolve("config/astracontent-transport.json"),
"astracontent:transport", "Транспорт",
resource("transport", "defaults"), resource("transport", "schema"), transportCompatibility);
railSpeedRuntime = RailBehavior.registerSpeedRuntime("astracontent:transport");
transportStarted = true;
} catch (IOException | RuntimeException failure) {
close();
throw new IllegalStateException("Cannot initialize AstraContent transport policy", failure);
}
}
private void start(ServerStartingEvent event) { private void start(ServerStartingEvent event) {
if (projectiles != null) throw new IllegalStateException("AstraContent already started"); if (projectiles != null) throw new IllegalStateException("AstraContent already started");
// AstraPlus publishes its API during ServerAboutToStartEvent. The FILE definition must // AstraPlus publishes its API during ServerAboutToStartEvent. The FILE definition must
@@ -53,13 +91,13 @@ public final class AstraContent {
gameDirectory.resolve("config/astracontent-projectiles.json"), gameDirectory.resolve("config/astracontent-projectiles.json"),
"astracontent:projectiles", "astracontent:projectiles",
"Боеприпасы", "Боеприпасы",
resource("defaults"), resource("projectile", "defaults"),
resource("schema"), resource("projectile", "schema"),
JsonParser.parseString(resource("compatibility")).getAsJsonObject()); JsonParser.parseString(resource("projectile", "compatibility")).getAsJsonObject());
} }
private static String resource(String kind) throws IOException { private static String resource(String policy, String kind) throws IOException {
String path = POLICY_RESOURCES + kind + ".json"; String path = POLICY_RESOURCES + policy + "-" + kind + ".json";
try (var stream = AstraContent.class.getResourceAsStream(path)) { try (var stream = AstraContent.class.getResourceAsStream(path)) {
if (stream == null) throw new IOException("Missing AstraContent policy resource: " + path); if (stream == null) throw new IOException("Missing AstraContent policy resource: " + path);
byte[] bytes = stream.readNBytes(POLICY_RESOURCE_LIMIT + 1); byte[] bytes = stream.readNBytes(POLICY_RESOURCE_LIMIT + 1);
@@ -79,8 +117,17 @@ public final class AstraContent {
} }
private void close() { private void close() {
if (projectiles == null) return; if (projectiles != null) {
projectiles.close(); projectiles.close();
projectiles = null; projectiles = null;
} }
// Stop callbacks before vanilla saves worlds, while retaining immutable save keys
// and per-cart fronts until Trains receives ServerStoppedEvent after that save.
if (railSpeedRuntime != null) {
railSpeedRuntime.close();
railSpeedRuntime = null;
}
TransportCapabilities.close();
transportStarted = false;
}
} }
@@ -0,0 +1,22 @@
package online.astradev.content.mixin;
import com.llamalad7.mixinextras.injector.wrapmethod.WrapMethod;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.block.state.BlockState;
import online.astradev.content.transport.LegacyBlockMappings;
import org.spongepowered.asm.mixin.Mixin;
/** Imports declared old item tags at ordinary native placement, without replacing modern IDs. */
@Mixin(BlockItem.class)
public abstract class LegacyDataBlockPlacementMixin {
@WrapMethod(method = "placeBlock")
private boolean astraplus$legacyPlace(BlockPlaceContext context, BlockState state, Operation<Boolean> original) {
boolean placed = original.call(context, state);
if (placed && context.getLevel() instanceof ServerLevel level)
LegacyBlockMappings.placed(level, context.getClickedPos(), context.getItemInHand());
return placed;
}
}
@@ -0,0 +1,45 @@
package online.astradev.content.mixin;
import online.astradev.content.transport.TransportCapabilities;
import net.minecraft.network.protocol.game.ServerboundMoveVehiclePacket;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;
import online.astradev.content.transport.collision.SurfaceBounce;
import org.spongepowered.asm.mixin.*;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerGamePacketListenerImpl.class)
public abstract class TransportBoatPacketMixin {
@Shadow public ServerPlayer player;
@Unique private Entity astra$boat;
@Unique private Vec3 astra$boatBefore;
// Run after vanilla's thread check, so packet-thread rescheduling never mutates state.
@Inject(
method = "handleMoveVehicle",
at =
@At(
value = "INVOKE",
target =
"Lnet/minecraft/server/level/ServerPlayer;getRootVehicle()Lnet/minecraft/world/entity/Entity;",
shift = At.Shift.BEFORE))
private void astra$before(ServerboundMoveVehiclePacket packet, CallbackInfo ci) {
astra$boat = player.getRootVehicle();
astra$boatBefore = astra$boat.position();
}
@Inject(method = "handleMoveVehicle", at = @At("RETURN"))
private void astra$after(ServerboundMoveVehiclePacket packet, CallbackInfo ci) {
if (astra$boat != null && astra$boatBefore != null) {
SurfaceBounce.boatPacket(astra$boat, astra$boatBefore);
astra$boat = null;
astra$boatBefore = null;
}
}
}
@@ -0,0 +1,29 @@
package online.astradev.content.mixin;
import online.astradev.content.transport.TransportCapabilities;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.vehicle.minecart.*;
import net.minecraft.world.phys.Vec3;
import online.astradev.content.transport.rail.CartSpeed;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(NewMinecartBehavior.class)
public abstract class TransportExperimentalCartMixin extends MinecartBehavior {
protected TransportExperimentalCartMixin(AbstractMinecart cart) {
super(cart);
}
@Inject(method = "calculateTrackSpeed", at = @At("RETURN"), cancellable = true)
private void astra$exactSpeed(CallbackInfoReturnable<Vec3> cir) {
if (!(level() instanceof ServerLevel level)) return;
double limit = ((CartSpeed) minecart).astraplus$transportLimit(level);
var movement = cir.getReturnValue();
if (limit > 0 && movement.horizontalDistance() > limit)
cir.setReturnValue(movement.scale(limit / movement.horizontalDistance()));
}
}
@@ -0,0 +1,21 @@
package online.astradev.content.mixin;
import online.astradev.content.transport.TransportCapabilities;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.vehicle.minecart.MinecartFurnace;
import online.astradev.content.transport.rail.CartSpeed;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(MinecartFurnace.class)
public abstract class TransportFurnaceCartMixin {
@Inject(method = "getMaxSpeed", at = @At("RETURN"), cancellable = true)
private void astra$furnace(ServerLevel level, CallbackInfoReturnable<Double> cir) {
double limit = ((CartSpeed) this).astraplus$transportLimit(level);
if (limit > 0) cir.setReturnValue(limit);
}
}
@@ -0,0 +1,49 @@
package online.astradev.content.mixin;
import online.astradev.content.transport.TransportCapabilities;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
import net.minecraft.world.level.storage.*;
import online.astradev.content.transport.rail.CartSpeed;
import online.astradev.content.transport.rail.RailSpeed;
import org.spongepowered.asm.mixin.*;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.*;
@Mixin(AbstractMinecart.class)
public abstract class TransportMinecartMixin implements CartSpeed {
@Unique private double astra$speed;
@Inject(method = "getMaxSpeed", at = @At("RETURN"), cancellable = true)
private void astra$limit(ServerLevel level, CallbackInfoReturnable<Double> cir) {
double limit = astraplus$transportLimit(level);
if (limit > 0) cir.setReturnValue(limit);
}
@Override
public double astraplus$transportLimit(ServerLevel level) {
// Retain the saved speed for final serialization, but never apply it outside a live runtime.
if (!TransportCapabilities.active()) return 0;
var cart = (AbstractMinecart) (Object) this;
astra$speed = RailSpeed.target(level, cart.getCurrentBlockPosOrRailBelow(), astra$speed);
// Preserve existing experimental gamerules until this cart reaches a regulator.
if (astra$speed == 0) return 0;
double limit = RailSpeed.safeLimit(cart, level, astra$speed / 20);
return limit * (cart.isInWater() && TransportCapabilities.active() ? TransportCapabilities.policy().rail().waterMultiplier() : 1);
}
@Inject(method = "addAdditionalSaveData", at = @At("RETURN"))
private void astra$save(ValueOutput out, CallbackInfo ci) {
var savedState = TransportCapabilities.persistence();
if (savedState != null) savedState.saveSpeed(astra$speed, out::putDouble);
}
@Inject(method = "readAdditionalSaveData", at = @At("RETURN"))
private void astra$read(ValueInput in, CallbackInfo ci) {
var savedState = TransportCapabilities.persistence();
if (savedState != null) astra$speed = savedState.readSpeed(key -> in.getDoubleOr(key, 0));
}
}
@@ -0,0 +1,45 @@
package online.astradev.content.mixin;
import online.astradev.content.transport.TransportCapabilities;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
import net.minecraft.world.level.block.BaseRailBlock;
import net.minecraft.world.phys.Vec3;
import online.astradev.content.transport.train.Trains;
import online.astradev.content.transport.collision.SurfaceBounce;
import org.spongepowered.asm.mixin.*;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Entity.class)
public abstract class TransportSlimeCollisionMixin {
@Unique private Vec3 astra$beforeMove;
@Unique private Vec3 astra$incoming;
@Inject(method = "move", at = @At("HEAD"), cancellable = true)
private void astra$before(MoverType type, Vec3 delta, CallbackInfo ci) {
var entity = (Entity) (Object) this;
astra$beforeMove =
type == MoverType.SELF && SurfaceBounce.supports(entity) ? entity.position() : null;
astra$incoming = entity.getDeltaMovement();
// Native powered rails can accelerate from zero within this same tick.
if (type == MoverType.SELF
&& entity instanceof AbstractMinecart cart
&& Trains.paused(cart)
&& cart.level().getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock()
instanceof BaseRailBlock) {
astra$beforeMove = null;
cart.setDeltaMovement(Vec3.ZERO);
ci.cancel();
}
}
@Inject(method = "move", at = @At("RETURN"))
private void astra$after(MoverType type, Vec3 delta, CallbackInfo ci) {
if (astra$beforeMove != null)
SurfaceBounce.afterMove((Entity) (Object) this, astra$beforeMove, delta, astra$incoming);
}
}
@@ -0,0 +1,49 @@
package online.astradev.content.mixin;
import online.astradev.content.transport.TransportCapabilities;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
import net.minecraft.world.level.storage.*;
import net.minecraft.world.phys.Vec3;
import online.astradev.content.transport.train.*;
import org.spongepowered.asm.mixin.*;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(AbstractMinecart.class)
public abstract class TransportTrainCartMixin {
@Unique private Vec3 astra$beforePlayerPush;
@Inject(method = "addAdditionalSaveData", at = @At("RETURN"))
private void astra$save(ValueOutput output, CallbackInfo ci) {
CouplingGeometry.save((AbstractMinecart) (Object) this, output);
}
@Inject(method = "readAdditionalSaveData", at = @At("RETURN"))
private void astra$read(ValueInput input, CallbackInfo ci) {
CouplingGeometry.load((AbstractMinecart) (Object) this, input);
}
@Inject(
method = "push(Lnet/minecraft/world/entity/Entity;)V",
at = @At("HEAD"),
cancellable = true)
private void astra$noInternalCollision(Entity other, CallbackInfo ci) {
var self = (AbstractMinecart) (Object) this;
astra$beforePlayerPush = other instanceof Player ? self.getDeltaMovement() : null;
if (other instanceof AbstractMinecart cart && Trains.connected(self, cart)) ci.cancel();
}
@Inject(method = "push(Lnet/minecraft/world/entity/Entity;)V", at = @At("RETURN"))
private void astra$playerPush(Entity other, CallbackInfo ci) {
var self = (AbstractMinecart) (Object) this;
if (astra$beforePlayerPush == null) return;
Vec3 impulse = self.getDeltaMovement().subtract(astra$beforePlayerPush);
astra$beforePlayerPush = null;
if (impulse.horizontalDistanceSqr() > 1e-12) Trains.playerPush(self);
}
}
@@ -0,0 +1,132 @@
package online.astradev.content.transport;
import com.google.gson.JsonObject;
import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponents;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.chunk.LevelChunk;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.level.ChunkEvent;
import online.astradev.plus.api.AstraPlusApi;
import online.astradev.plus.api.content.BlockData;
import online.astradev.plus.api.content.ContentModule;
import online.astradev.plus.api.world.BlockPosition;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** Forward-only declared saved identities, never a fallback to a previous concrete behavior. */
public final class LegacyBlockMappings {
private record Mapping(String base, String itemTag, BlockData<Integer> data, Map<Integer, String> variants) {}
private static final List<Mapping> mappings = new ArrayList<>();
private static String declared;
private static final List<JsonObject> commands = new ArrayList<>();
private LegacyBlockMappings() {}
public static synchronized void declare(JsonObject compatibility) {
var source = compatibility.getAsJsonArray("legacyBlocks");
if (source == null) return;
String serialized = source.toString();
if (declared != null) {
if (!declared.equals(serialized)) throw new IllegalArgumentException("Legacy identity declarations cannot change at runtime");
return;
}
if (compatibility.has("commands")) {
var aliases = compatibility.getAsJsonArray("commands");
if (aliases.size() > 32) throw new IllegalArgumentException("Too many command aliases");
for (var entry : aliases) {
var command = entry.getAsJsonObject();
for (String key : List.of("root", "branch"))
if (!command.get(key).getAsString().matches("[a-z0-9_-]{1,64}"))
throw new IllegalArgumentException("Invalid command literal");
int count = command.get("count").getAsInt();
if (count < 1 || count > 64 || command.getAsJsonObject("items").size() > 1024)
throw new IllegalArgumentException("Invalid command items");
command.getAsJsonObject("items").entrySet().forEach(item -> {
if (!item.getKey().matches("[a-z0-9_/-]{1,128}")) throw new IllegalArgumentException("Invalid item alias");
TransportPolicy.identifier(item.getValue().getAsString());
});
commands.add(command.deepCopy());
}
}
if (source.size() > 64) throw new IllegalArgumentException("Too many compatibility mappings");
for (var entry : source) {
var json = entry.getAsJsonObject();
var storage = Identifier.parse(json.get("storage").getAsString());
String base = json.get("base").getAsString(), itemTag = json.get("itemTag").getAsString();
TransportPolicy.identifier(base);
var variants = new LinkedHashMap<Integer, String>();
json.getAsJsonObject("variants").entrySet().forEach(value -> {
String id = value.getValue().getAsString();
TransportPolicy.identifier(id);
variants.put(Integer.parseInt(value.getKey()), id);
});
if (variants.isEmpty() || variants.size() > 1024) throw new IllegalArgumentException("Invalid legacy variants");
int min = variants.keySet().stream().mapToInt(Integer::intValue).min().orElseThrow();
int max = variants.keySet().stream().mapToInt(Integer::intValue).max().orElseThrow();
var data = new ContentModule(storage.getNamespace()).blockData(storage.getPath(),
BlockData.integers(json.get("field").getAsString(), min, max));
mappings.add(new Mapping(base, itemTag, data, Map.copyOf(variants)));
}
declared = serialized;
}
static void configure(JsonObject compatibility) {
var source = compatibility.getAsJsonArray("legacyBlocks");
if (source != null && !source.toString().equals(declared))
throw new IllegalStateException("Declare compatibility before attachment registry freeze");
}
static void clear() { /* Attachment declarations belong to this JVM's frozen registry. */ }
@SubscribeEvent
public static void commands(net.neoforged.neoforge.event.RegisterCommandsEvent event) {
for (var declaration : commands) {
var branch = net.minecraft.commands.Commands.literal(declaration.get("branch").getAsString());
declaration.getAsJsonObject("items").entrySet().forEach(item -> branch.then(
net.minecraft.commands.Commands.literal(item.getKey()).executes(context -> {
var player = context.getSource().getPlayerOrException();
var stack = AstraPlusApi.current().orElseThrow().create(
Identifier.parse(item.getValue().getAsString()), declaration.get("count").getAsInt());
AstraPlusApi.give(player, stack);
return 1;
})));
event.getDispatcher().register(net.minecraft.commands.Commands.literal(declaration.get("root").getAsString())
.requires(net.minecraft.commands.Commands.hasPermission(net.minecraft.commands.Commands.LEVEL_GAMEMASTERS)).then(branch));
}
}
public static void placed(ServerLevel level, BlockPos pos, ItemStack item) {
if (!TransportCapabilities.active()) return;
var world = AstraPlusApi.world(level);
var position = AstraPlusApi.position(pos);
var tag = item.get(DataComponents.CUSTOM_DATA);
for (var mapping : mappings) {
if (!world.block(position).equals(mapping.base)) continue;
mapping.data.remove(world, position);
if (tag == null) continue;
String id = mapping.variants.get(tag.copyTag().getIntOr(mapping.itemTag, Integer.MIN_VALUE));
if (id != null) world.replaceBlock(position, id);
}
}
@SubscribeEvent
public static void load(ChunkEvent.Load event) {
if (!(event.getLevel() instanceof ServerLevel level) || !(event.getChunk() instanceof LevelChunk chunk)) return;
level.getServer().execute(() -> {
if (!TransportCapabilities.active() || AstraPlusApi.current().isEmpty()) return;
var chunkPos = chunk.getPos();
if (level.getChunkSource().getChunkNow(chunkPos.x(), chunkPos.z()) != chunk) return;
var origin = new BlockPosition(chunkPos.x() << 4, level.getMinY(), chunkPos.z() << 4);
var world = AstraPlusApi.world(level);
for (var mapping : mappings) for (var saved : mapping.data.inChunk(world, origin).entrySet()) {
String id = mapping.variants.get(saved.getValue());
if (id != null && world.block(saved.getKey()).equals(mapping.base)) world.replaceBlock(saved.getKey(), id);
// A newer explicit identity always wins; retired data is never reapplied backwards.
mapping.data.remove(world, saved.getKey());
}
});
}
}
@@ -0,0 +1,105 @@
package online.astradev.content.transport;
import com.google.gson.JsonObject;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.state.BlockState;
import net.neoforged.bus.api.IEventBus;
import online.astradev.plus.api.AstraPlusApi;
import online.astradev.plus.api.editor.EditorDefinitions;
import online.astradev.plus.api.editor.FileEditorDefinition;
import online.astradev.content.transport.train.Trains;
import online.astradev.content.transport.collision.SurfaceBounce;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
/** Engine bootstrap; distribution supplies every concrete policy and saved-state identifier. */
public final class TransportCapabilities {
private static volatile TransportPolicy current;
private static volatile TransportPersistence persistence;
private static FileEditorDefinition<TransportPolicy> provider;
private static boolean registered;
private TransportCapabilities() {}
public static void declareCompatibility(JsonObject legacy) { LegacyBlockMappings.declare(legacy); }
public static void register(IEventBus bus) {
if (registered) return;
registered = true;
bus.register(Trains.class);
bus.register(SurfaceBounce.class);
bus.register(LegacyBlockMappings.class);
}
public static void start(Path actualFile, String id, String name, String defaultsJson,
String schemaJson, JsonObject legacy) throws IOException {
close();
var compatibility = legacy.deepCopy();
var keys = TransportPersistence.keys(compatibility);
var next = new FileEditorDefinition<>(actualFile, id, name, schemaJson,
TransportCapabilities::prepare, value -> publish(value, keys));
next.initialize(defaultsJson);
var prepared = prepare(next.snapshot().documentJson());
var savedState = new TransportPersistence(keys, prepared.rail().maximumStoredSpeed());
LegacyBlockMappings.configure(compatibility);
EditorDefinitions.register(next);
provider = next;
persistence = savedState;
current = prepared;
}
public static TransportPolicy policy() { return current; }
public static boolean active() { return current != null; }
public static TransportPersistence persistence() { return persistence; }
public static String storage(String key) {
var savedState = persistence;
if (savedState == null) throw new IllegalStateException("Transport storage is not configured");
return savedState.key(key);
}
static void publish(TransportPolicy value, java.util.Map<String, String> keys) {
persistence = new TransportPersistence(keys, value.rail().maximumStoredSpeed());
current = value;
}
private static TransportPolicy prepare(String json) {
var value = TransportPolicy.parse(json);
if (!(BuiltInRegistries.ITEM.getValue(Identifier.parse(value.coupling().fallbackItem())) instanceof net.minecraft.world.item.BlockItem))
throw new IllegalArgumentException("Предмет возврата сцепки должен быть блоком.");
return value;
}
public static boolean itemMatches(ItemStack stack, List<String> selectors) {
for (String selector : selectors) {
if (selector.startsWith("#")) {
if (stack.is(TagKey.create(Registries.ITEM, Identifier.parse(selector.substring(1))))) return true;
} else if (BuiltInRegistries.ITEM.getKey(stack.getItem()).toString().equals(selector)
|| AstraPlusApi.current().flatMap(api -> api.find(stack)).map(value -> value.id().toString().equals(selector)).orElse(false)) return true;
}
return false;
}
public static boolean blockMatches(BlockState state, List<String> selectors) {
for (String selector : selectors) {
if (selector.startsWith("#")) {
if (state.is(TagKey.create(Registries.BLOCK, Identifier.parse(selector.substring(1))))) return true;
} else if (BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString().equals(selector)) return true;
}
return false;
}
public static void close() {
current = null;
if (provider != null) EditorDefinitions.unregister(provider);
provider = null;
Trains.close();
SurfaceBounce.clear();
// Vanilla saves entities and SavedData after ServerStoppingEvent. Keep immutable
// keys/limits and per-cart front directions available until that save is finished.
LegacyBlockMappings.clear();
}
}
@@ -0,0 +1,55 @@
package online.astradev.content.transport;
import com.google.gson.JsonObject;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.ToDoubleFunction;
/** Immutable serialization metadata; unlike live behavior it outlives ServerStoppingEvent. */
public record TransportPersistence(Map<String, String> keys, double maximumStoredSpeed) {
public TransportPersistence {
keys = Map.copyOf(keys);
for (String key : List.of("cartSpeedKey", "frontXKey", "frontZKey", "trainStorageId")) {
String value = keys.get(key);
if (value == null || value.isBlank() || value.length() > 128)
throw new IllegalArgumentException("Missing transport storage key " + key);
}
TransportPolicy.identifier(keys.get("trainStorageId"));
if (!Double.isFinite(maximumStoredSpeed) || maximumStoredSpeed < .1 || maximumStoredSpeed > 120)
throw new IllegalArgumentException("Invalid transport persistence speed limit");
}
static Map<String, String> keys(JsonObject source) {
var result = new LinkedHashMap<String, String>();
for (String key : List.of("cartSpeedKey", "frontXKey", "frontZKey", "trainStorageId")) {
var value = source.get(key);
if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString())
throw new IllegalArgumentException("Missing transport storage key " + key);
result.put(key, value.getAsString());
}
return Map.copyOf(result);
}
public String key(String name) {
String result = keys.get(name);
if (result == null) throw new IllegalArgumentException("Unknown transport storage key " + name);
return result;
}
public void saveSpeed(double speed, BiConsumer<String, Double> output) {
if (Double.isFinite(speed) && speed > 0) output.accept(key("cartSpeedKey"), speed);
}
public double readSpeed(ToDoubleFunction<String> input) {
double value = input.applyAsDouble(key("cartSpeedKey"));
return Double.isFinite(value) && value > 0 ? Math.clamp(value, .1, maximumStoredSpeed) : 0;
}
public void saveFront(double x, double z, BiConsumer<String, Double> output) {
if (!Double.isFinite(x) || !Double.isFinite(z)) return;
output.accept(key("frontXKey"), x);
output.accept(key("frontZKey"), z);
}
}
@@ -0,0 +1,81 @@
package online.astradev.content.transport;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import java.util.List;
import java.util.Map;
/** Values and selectors are declarations; this type describes reusable transport capabilities. */
public record TransportPolicy(Rail rail, Coupling coupling, Bounce bounce) {
public record Rail(boolean enabled, double signalUnits, double minimumSignalSpeed,
int signalReach, double maximumStoredSpeed, double waterMultiplier,
int safeLookAhead, double cornerSpeed) {}
public record Coupling(boolean enabled, List<String> linkItems, List<String> unlinkTools,
boolean requireSneaking, double minimumDistance, double maximumDistance,
double maximumVerticalDistance, double alignment, double breakDistance,
double springStrength, double maximumCorrection, double hitEndDistance,
double hitEndRatio, double anchorHeight, double anchorOffset, int unlinkDamage,
int itemCost, String fallbackItem, Map<String, String> messages) {}
public record Bounce(boolean enabled, List<String> entityKinds, List<String> blocks,
double minimumSpeed, double collisionEpsilon, double surfaceMargin,
double verticalInset, double restitution) {}
public static TransportPolicy parse(String source) {
try {
var json = JsonParser.parseString(source);
if (!json.isJsonObject()) throw new IllegalArgumentException("Transport settings must be an object");
var value = new Gson().fromJson(json, TransportPolicy.class);
value.validate();
return value;
} catch (RuntimeException invalid) {
throw new IllegalArgumentException("Некорректные настройки транспорта: " + invalid.getMessage(), invalid);
}
}
public TransportPolicy {
if (coupling != null) coupling = new Coupling(coupling.enabled,
List.copyOf(coupling.linkItems), List.copyOf(coupling.unlinkTools),
coupling.requireSneaking, coupling.minimumDistance, coupling.maximumDistance,
coupling.maximumVerticalDistance, coupling.alignment, coupling.breakDistance,
coupling.springStrength, coupling.maximumCorrection, coupling.hitEndDistance,
coupling.hitEndRatio, coupling.anchorHeight, coupling.anchorOffset,
coupling.unlinkDamage, coupling.itemCost, coupling.fallbackItem,
Map.copyOf(coupling.messages));
if (bounce != null) bounce = new Bounce(bounce.enabled, List.copyOf(bounce.entityKinds),
List.copyOf(bounce.blocks), bounce.minimumSpeed, bounce.collisionEpsilon,
bounce.surfaceMargin, bounce.verticalInset, bounce.restitution);
}
private void validate() {
if (rail == null || coupling == null || bounce == null) throw new IllegalArgumentException("rail/coupling/bounce required");
range(rail.signalUnits, 0, 120); range(rail.minimumSignalSpeed, 0, 120);
range(rail.signalReach, 0, 64); range(rail.maximumStoredSpeed, .1, 120);
range(rail.waterMultiplier, 0, 1); range(rail.safeLookAhead, 0, 16); range(rail.cornerSpeed, .01, 6);
selectors(coupling.linkItems); selectors(coupling.unlinkTools); identifier(coupling.fallbackItem);
range(coupling.minimumDistance, .1, 32); range(coupling.maximumDistance, coupling.minimumDistance, 32);
range(coupling.maximumVerticalDistance, 0, 32); range(coupling.alignment, 0, 1);
range(coupling.breakDistance, coupling.maximumDistance, 64); range(coupling.springStrength, 0, 4);
range(coupling.maximumCorrection, 0, 4); range(coupling.hitEndDistance, 0, 2);
range(coupling.hitEndRatio, 0, 10); range(coupling.anchorHeight, -4, 4); range(coupling.anchorOffset, 0, 4);
range(coupling.unlinkDamage, 0, 10000); range(coupling.itemCost, 0, 1);
for (String key : List.of("invalidEnd", "noLink", "occupied", "linked", "noCandidate"))
if (!coupling.messages.containsKey(key) || coupling.messages.get(key).length() > 1024)
throw new IllegalArgumentException("Missing/oversized transport message " + key);
if (bounce.entityKinds.size() > 2 || !List.of("boat", "minecart").containsAll(bounce.entityKinds))
throw new IllegalArgumentException("Supported entityKinds: boat, minecart");
selectors(bounce.blocks); range(bounce.minimumSpeed, 0, 4); range(bounce.collisionEpsilon, 0, .1);
range(bounce.surfaceMargin, 0, .5); range(bounce.verticalInset, 0, .5); range(bounce.restitution, 0, 2);
}
private static void selectors(List<String> values) {
if (values.size() > 256) throw new IllegalArgumentException("Too many selectors");
for (var value : values) identifier(value.startsWith("#") ? value.substring(1) : value);
}
public static void identifier(String value) {
if (value == null || value.length() > 256 || !value.matches("[a-z0-9_.-]+:[a-z0-9_./-]+") || value.contains(".."))
throw new IllegalArgumentException("Invalid identifier");
}
private static void range(double value, double min, double max) {
if (!Double.isFinite(value) || value < min || value > max) throw new IllegalArgumentException("Value outside " + min + ".." + max);
}
}
@@ -0,0 +1,124 @@
package online.astradev.content.transport.collision;
import online.astradev.content.transport.TransportCapabilities;
import online.astradev.content.transport.TransportPolicy;
import net.minecraft.core.BlockPos;
import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.vehicle.boat.AbstractBoat;
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.phys.*;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.tick.EntityTickEvent;
import online.astradev.content.transport.train.Trains;
import java.util.*;
public final class SurfaceBounce {
private static final Map<Entity, Vec3> PENDING = new WeakHashMap<>();
private static final Map<Entity, Vec3> BOAT_MOTION = new WeakHashMap<>();
private SurfaceBounce() {}
public static void clear() { PENDING.clear(); BOAT_MOTION.clear(); }
private static TransportPolicy.Bounce settings() { return TransportCapabilities.policy().bounce(); }
public static boolean supports(Entity entity) {
return TransportCapabilities.active() && TransportCapabilities.policy().bounce().enabled()
&& entity.level() instanceof ServerLevel
&& ((entity instanceof AbstractMinecart && settings().entityKinds().contains("minecart"))
|| (entity instanceof AbstractBoat && settings().entityKinds().contains("boat")));
}
public static void afterMove(Entity entity, Vec3 before, Vec3 requested, Vec3 incoming) {
if (!supports(entity) || entity.noPhysics) return;
Vec3 actual = entity.position().subtract(before);
boolean x =
Math.abs(requested.x - actual.x) > settings().collisionEpsilon() && touchesSurface(entity, requested.x, 0);
boolean z =
Math.abs(requested.z - actual.z) > settings().collisionEpsilon() && touchesSurface(entity, 0, requested.z);
if ((x || z) && requested.horizontalDistance() > settings().minimumSpeed()) {
// Experimental rail movement splits one tick into smaller moves at rail boundaries.
if (entity instanceof AbstractMinecart cart
&& AbstractMinecart.useExperimentalMovement(cart.level()))
requested = requested.horizontal().normalize().scale(incoming.horizontalDistance());
Vec3 reflected =
new Vec3(
(x ? -requested.x : requested.x) * settings().restitution(),
entity.getDeltaMovement().y,
(z ? -requested.z : requested.z) * settings().restitution());
PENDING.put(entity, reflected);
entity.setDeltaMovement(reflected);
}
}
/** Check the actual contacted face, not nearby matching surface or the block beneath the vehicle. */
private static boolean touchesSurface(Entity entity, double dx, double dz) {
if (dx == 0 && dz == 0) return false;
var box = entity.getBoundingBox();
double eps = settings().surfaceMargin();
double x0 = contactEdge(dx, box.minX, box.maxX, eps);
double x1 = dx != 0 ? x0 : box.maxX - eps;
double z0 = contactEdge(dz, box.minZ, box.maxZ, eps);
double z1 = dz != 0 ? z0 : box.maxZ - eps;
for (var pos :
BlockPos.betweenClosed(
BlockPos.containing(x0, box.minY + settings().verticalInset(), z0),
BlockPos.containing(x1, box.maxY - settings().verticalInset(), z1)))
if (entity.level().hasChunkAt(pos)
&& TransportCapabilities.blockMatches(entity.level().getBlockState(pos), settings().blocks())) return true;
return false;
}
private static double contactEdge(double movement, double min, double max, double margin) {
if (movement > 0) return max + margin;
if (movement < 0) return min - margin;
return min + margin;
}
@SubscribeEvent
public static void afterTick(EntityTickEvent.Post event) {
flush(event.getEntity());
}
public static void flush(Entity entity) {
var reflected = PENDING.remove(entity);
if (reflected == null || entity.isRemoved()) return;
if (entity instanceof AbstractMinecart cart) Trains.reverse(cart, reflected);
else entity.setDeltaMovement(reflected);
entity.hurtMarked = true;
if (entity instanceof AbstractBoat)
for (var passenger : entity.getPassengers())
if (passenger instanceof ServerPlayer player)
player.connection.send(new ClientboundSetEntityMotionPacket(entity));
}
/**
* A vanilla player steers boats on the client. Detect its reported contact and return a vanilla
* impulse packet.
*/
public static void boatPacket(Entity entity, Vec3 before) {
if (!supports(entity) || !(entity instanceof AbstractBoat)) return;
Vec3 motion = entity.position().subtract(before);
Vec3 prior = BOAT_MOTION.getOrDefault(entity, motion);
Vec3 incoming = prior.horizontalDistance() > motion.horizontalDistance() ? prior : motion;
boolean x = Math.abs(incoming.x) > settings().minimumSpeed() && touchesSurface(entity, incoming.x, 0);
boolean z = Math.abs(incoming.z) > settings().minimumSpeed() && touchesSurface(entity, 0, incoming.z);
if (x || z) {
var reflected =
new Vec3(
(x ? -incoming.x : incoming.x) * settings().restitution(),
entity.getDeltaMovement().y,
(z ? -incoming.z : incoming.z) * settings().restitution());
PENDING.put(entity, reflected);
BOAT_MOTION.put(entity, reflected);
flush(entity);
} else BOAT_MOTION.put(entity, motion);
}
}
@@ -0,0 +1,8 @@
package online.astradev.content.transport.rail;
import net.minecraft.server.level.ServerLevel;
public interface CartSpeed {
/** Blocks per tick, or zero until the cart encounters a powered speed regulator. */
double astraplus$transportLimit(ServerLevel level);
}
@@ -0,0 +1,121 @@
package online.astradev.content.transport.rail;
import online.astradev.content.transport.TransportCapabilities;
import online.astradev.content.transport.TransportPolicy;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Vec3i;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.RailShape;
import java.util.*;
import online.astradev.plus.api.RailBehavior;
public final class RailSpeed {
private RailSpeed() {}
public static double signalSpeed(int signal) {
return TransportCapabilities.active() ? Math.clamp(signal, 0, 15) * TransportCapabilities.policy().rail().signalUnits() : 0;
}
public static double target(ServerLevel level, BlockPos pos, double previous) {
var state = level.getBlockState(pos);
if (!state.is(Blocks.POWERED_RAIL) || !state.getValue(PoweredRailBlock.POWERED))
return previous;
double configured = RailBehavior.targetSpeed(level, pos);
if (Double.isFinite(configured)) return configured;
var policy = TransportCapabilities.policy();
return policy != null && policy.rail().enabled()
? Math.max(policy.rail().minimumSignalSpeed(), signalSpeed(signal(level, pos))) : previous;
}
/** Mirror the vanilla eight-rail power reach, preserving bends, slopes and highest input. */
public static int signal(ServerLevel level, BlockPos origin) {
record Step(BlockPos pos, int distance) {}
var queue = new ArrayDeque<Step>();
var seen = new HashSet<BlockPos>();
queue.add(new Step(origin, 0));
int best = 0;
while (!queue.isEmpty()) {
var step = queue.removeFirst();
if (!seen.add(step.pos) || !level.hasChunkAt(step.pos)) continue;
var state = level.getBlockState(step.pos);
if (!state.is(Blocks.POWERED_RAIL)) continue;
best = Math.max(best, level.getBestNeighborSignal(step.pos));
if (best == 15) return best;
if (step.distance == TransportCapabilities.policy().rail().signalReach()) continue;
var shape = state.getValue(PoweredRailBlock.SHAPE);
var exits = AbstractMinecart.exits(shape);
for (var exit : List.of(exits.getFirst(), exits.getSecond())) {
var adjacent =
step.pos.offset(
exit.getX(), shape.isSlope() ? exit.getY() + 1 : 0, exit.getZ());
for (var candidate : List.of(adjacent, adjacent.below())) {
if (!level.hasChunkAt(candidate)) continue;
var other = level.getBlockState(candidate);
if (other.is(Blocks.POWERED_RAIL)
&& connected(
step.pos,
shape,
candidate,
other.getValue(PoweredRailBlock.SHAPE)))
queue.add(new Step(candidate, step.distance + 1));
}
}
}
return best;
}
private static boolean connected(BlockPos a, RailShape sa, BlockPos b, RailShape sb) {
var ea = AbstractMinecart.exits(sa);
var eb = AbstractMinecart.exits(sb);
for (var exitA : List.of(ea.getFirst(), ea.getSecond())) {
if (a.getX() + exitA.getX() != b.getX()) continue;
if (a.getZ() + exitA.getZ() != b.getZ()) continue;
int heightA = exitHeight(a, sa, exitA);
for (var exitB : List.of(eb.getFirst(), eb.getSecond())) {
if (b.getX() + exitB.getX() != a.getX()) continue;
if (b.getZ() + exitB.getZ() != a.getZ()) continue;
if (heightA == exitHeight(b, sb, exitB)) return true;
}
}
return false;
}
private static int exitHeight(BlockPos pos, RailShape shape, Vec3i exit) {
if (shape.isSlope()) return pos.getY() + exit.getY() + 1;
return pos.getY();
}
private static boolean stopsFastTravel(BlockState state) {
if (state.is(Blocks.DETECTOR_RAIL) || state.is(Blocks.ACTIVATOR_RAIL)) return true;
return state.is(Blocks.POWERED_RAIL) && !state.getValue(PoweredRailBlock.POWERED);
}
/** Old movement needs vanilla speed when approaching bends, slopes or the end of a track. */
public static double safeLimit(AbstractMinecart cart, ServerLevel level, double limit) {
var policy = TransportCapabilities.policy();
if (policy == null) return limit;
double corner = policy.rail().cornerSpeed();
if (AbstractMinecart.useExperimentalMovement(level) || limit <= corner) return limit;
var pos = cart.getCurrentBlockPosOrRailBelow();
var movement = cart.getDeltaMovement();
int dx = (int) Math.signum(movement.x), dz = (int) Math.signum(movement.z);
for (int i = 0; i <= policy.rail().safeLookAhead(); i++) {
var check = pos.offset(dx * i, 0, dz * i);
if (!level.hasChunkAt(check)) return corner;
BlockState state = level.getBlockState(check);
if (!(state.getBlock() instanceof BaseRailBlock rail))
return TransportCapabilities.blockMatches(state, policy.bounce().blocks()) ? limit : corner;
RailShape shape = rail.getRailDirection(state, level, check, cart);
if (shape != RailShape.NORTH_SOUTH && shape != RailShape.EAST_WEST) return corner;
if (i > 0 && stopsFastTravel(state)) return corner;
// Never jump over a single slower regulator.
if (i > 0) limit = Math.min(limit, target(level, check, limit * 20) / 20);
}
return limit;
}
}
@@ -0,0 +1,100 @@
package online.astradev.content.transport.train;
import online.astradev.content.transport.TransportCapabilities;
import online.astradev.content.transport.TransportPolicy;
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
import net.minecraft.world.level.block.BaseRailBlock;
import net.minecraft.world.level.storage.ValueInput;
import net.minecraft.world.level.storage.ValueOutput;
import net.minecraft.world.phys.Vec3;
import java.util.Map;
import java.util.WeakHashMap;
public final class CouplingGeometry {
// Remember physical ends even when movement reverses. Unloaded carts are not retained.
private static final Map<AbstractMinecart, Vec3> FRONTS = new WeakHashMap<>();
private CouplingGeometry() {}
public static Vec3 front(AbstractMinecart cart) {
Vec3 previous = FRONTS.getOrDefault(cart, Vec3.ZERO);
if (previous.lengthSqr() < 0.5) previous = facing(cart);
Vec3 direction = railDirection(cart);
if (direction == null) direction = previous;
else if (direction.dot(previous) < 0) direction = direction.scale(-1);
FRONTS.put(cart, direction);
return direction;
}
private static Vec3 facing(AbstractMinecart cart) {
double yaw = Math.toRadians(cart.getYRot());
double x = Math.cos(yaw);
double z = Math.sin(yaw);
if (AbstractMinecart.useExperimentalMovement(cart.level())) z = -z;
return new Vec3(x, 0, z);
}
public static boolean onRail(AbstractMinecart cart) {
var position = cart.getCurrentBlockPosOrRailBelow();
return cart.level().getBlockState(position).getBlock() instanceof BaseRailBlock;
}
/** Vanilla exit order, without the persistent choice of a front end; null off rails. */
public static Vec3 railDirection(AbstractMinecart cart) {
var pos = cart.getCurrentBlockPosOrRailBelow();
var state = cart.level().getBlockState(pos);
if (!(state.getBlock() instanceof BaseRailBlock rail)) return null;
var shape = rail.getRailDirection(state, cart.level(), pos, cart);
var exits = AbstractMinecart.exits(shape);
Vec3 start = new Vec3(exits.getFirst());
Vec3 end = new Vec3(exits.getSecond());
return end.subtract(start).horizontal().normalize();
}
public static void restoreFront(AbstractMinecart cart, Vec3 direction) {
if (!Double.isFinite(direction.x) || !Double.isFinite(direction.z)) {
FRONTS.remove(cart);
return;
}
FRONTS.put(cart, direction.horizontal().normalize());
}
public static void save(AbstractMinecart cart, ValueOutput output) {
var savedState = TransportCapabilities.persistence();
if (savedState == null) return;
Vec3 front = FRONTS.getOrDefault(cart, Vec3.ZERO);
savedState.saveFront(front.x, front.z, output::putDouble);
}
public static void load(AbstractMinecart cart, ValueInput input) {
var savedState = TransportCapabilities.persistence();
if (savedState == null) return;
double x = input.getDoubleOr(savedState.key("frontXKey"), 0);
double z = input.getDoubleOr(savedState.key("frontZKey"), 0);
restoreFront(cart, new Vec3(x, 0, z));
}
public static void clear() {
FRONTS.clear();
}
public static int hitEnd(Vec3 axis, Vec3 localHit) {
double along = localHit.horizontal().dot(axis);
double across = Math.abs(localHit.x * axis.z - localHit.z * axis.x);
if (Math.abs(along) < TransportCapabilities.policy().coupling().hitEndDistance() || Math.abs(along) <= across * TransportCapabilities.policy().coupling().hitEndRatio()) return -1;
return along > 0 ? 0 : 1;
}
public static Vec3 outward(AbstractMinecart cart, int end) {
Vec3 direction = front(cart);
return end == 0 ? direction : direction.scale(-1);
}
public static Vec3 anchor(AbstractMinecart cart, int end) {
Vec3 center = cart.position().add(0, TransportCapabilities.policy().coupling().anchorHeight(), 0);
Vec3 offset = outward(cart, end).scale(TransportCapabilities.policy().coupling().anchorOffset());
return center.add(offset);
}
}
@@ -0,0 +1,117 @@
package online.astradev.content.transport.train;
import online.astradev.content.transport.TransportCapabilities;
import online.astradev.content.transport.TransportPolicy;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.saveddata.*;
import java.util.*;
/** One authoritative record per chain, including unloaded carts. No duplicated refunds. */
public final class TrainData extends SavedData {
public record Link(
UUID a, int endA, UUID b, int endB, String item, boolean paid, double length) {
private static final Codec<UUID> UUID_CODEC =
Codec.STRING.xmap(UUID::fromString, UUID::toString);
static final Codec<Link> CODEC =
RecordCodecBuilder.create(
instance -> {
var a = UUID_CODEC.fieldOf("a").forGetter(Link::a);
var endA = Codec.intRange(0, 1).fieldOf("end_a").forGetter(Link::endA);
var b = UUID_CODEC.fieldOf("b").forGetter(Link::b);
var endB = Codec.intRange(0, 1).fieldOf("end_b").forGetter(Link::endB);
var item = Codec.STRING.fieldOf("item").forGetter(Link::item);
var paid = Codec.BOOL.fieldOf("paid").forGetter(Link::paid);
var length =
Codec.doubleRange(.1, 64)
.fieldOf("length")
.forGetter(Link::length);
var fields = instance.group(a, endA, b, endB, item, paid, length);
return fields.apply(instance, Link::new);
});
public boolean touches(UUID id) {
return a.equals(id) || b.equals(id);
}
public UUID other(UUID id) {
return a.equals(id) ? b : a;
}
public int end(UUID id) {
return a.equals(id) ? endA : endB;
}
}
private static final Codec<TrainData> CODEC =
Link.CODEC
.listOf()
.xmap(TrainData::new, d -> List.copyOf(d.links))
.fieldOf("links")
.codec();
private static final Map<String, SavedDataType<TrainData>> TYPES = new HashMap<>();
private final List<Link> links = new ArrayList<>();
private final Map<UUID, Set<UUID>> components = new HashMap<>();
public TrainData() {}
private TrainData(List<Link> links) {
this.links.addAll(links);
}
public static TrainData get(ServerLevel level) {
String id = TransportCapabilities.storage("trainStorageId");
var type = TYPES.computeIfAbsent(id, key -> new SavedDataType<>(Identifier.parse(key), TrainData::new, CODEC));
return level.getDataStorage().computeIfAbsent(type);
}
public List<Link> links() {
return List.copyOf(links);
}
public Link at(UUID cart, int end) {
for (Link link : links) {
if (link.touches(cart) && link.end(cart) == end) return link;
}
return null;
}
public void add(Link link) {
links.add(link);
components.clear();
setDirty();
}
public boolean remove(Link link) {
boolean removed = links.remove(link);
if (removed) {
components.clear();
setDirty();
}
return removed;
}
public Set<UUID> component(UUID root) {
var cached = components.get(root);
if (cached != null) return cached;
var seen = new HashSet<UUID>();
var pending = new ArrayDeque<UUID>();
pending.add(root);
while (!pending.isEmpty()) {
var id = pending.removeFirst();
if (!seen.add(id)) continue;
for (var link : links) if (link.touches(id)) pending.add(link.other(id));
}
var component = Set.copyOf(seen);
// Collision checks reuse topology until a chain changes; ordinary carts are not cached.
if (component.size() > 1) {
for (UUID cart : component) components.put(cart, component);
}
return component;
}
}
@@ -0,0 +1,402 @@
package online.astradev.content.transport.train;
import online.astradev.content.transport.TransportCapabilities;
import online.astradev.content.transport.TransportPolicy;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.tags.ItemTags;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
import net.minecraft.world.item.*;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.block.*;
import net.minecraft.world.phys.*;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.entity.EntityLeaveLevelEvent;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
import online.astradev.plus.api.BlockLine;
import java.util.*;
public final class Trains {
private record DisplayKey(ServerLevel level, TrainData.Link link) {}
private static final Map<DisplayKey, BlockLine> DISPLAYS = new HashMap<>();
private static final Map<ServerLevel, Set<UUID>> PAUSED = new HashMap<>();
private static final Map<ServerLevel, Set<UUID>> PLAYER_PUSHES = new HashMap<>();
private Trains() {}
private static boolean enabled() { return TransportCapabilities.active() && TransportCapabilities.policy().coupling().enabled(); }
private static TransportPolicy.Coupling settings() { return TransportCapabilities.policy().coupling(); }
private static Component message(String key) { return Component.literal(settings().messages().get(key)); }
public static boolean paused(AbstractMinecart cart) {
return enabled() && PAUSED.getOrDefault(cart.level(), Set.of()).contains(cart.getUUID());
}
public static void playerPush(AbstractMinecart cart) {
if (enabled() && cart.level() instanceof ServerLevel level)
PLAYER_PUSHES.computeIfAbsent(level, key -> new HashSet<>()).add(cart.getUUID());
}
public static boolean isChain(ItemStack stack) {
return enabled() && stack.getItem() instanceof BlockItem
&& TransportCapabilities.itemMatches(stack, settings().linkItems());
}
public static boolean connected(AbstractMinecart a, AbstractMinecart b) {
return enabled() && a.level() instanceof ServerLevel level
&& b.level() == level
&& TrainData.get(level).component(a.getUUID()).contains(b.getUUID());
}
@SubscribeEvent
public static void interact(PlayerInteractEvent.EntityInteract event) {
if (!enabled() || event.isCanceled() || !(event.getTarget() instanceof AbstractMinecart cart)) return;
if (!(event.getEntity() instanceof ServerPlayer player)) return;
if (settings().requireSneaking() && !player.isShiftKeyDown()) return;
var level = player.level();
var item = event.getItemStack();
boolean chain = isChain(item);
if (!chain && !TransportCapabilities.itemMatches(item, settings().unlinkTools())) return;
event.setCanceled(true);
event.setCancellationResult(InteractionResult.SUCCESS);
if (!player.mayBuild()) return;
int end = CouplingGeometry.hitEnd(CouplingGeometry.front(cart), event.getLocation());
if (end < 0) {
player.sendSystemMessage(
message("invalidEnd"), true);
return;
}
var data = TrainData.get(level);
var existing = data.at(cart.getUUID(), end);
if (!chain) {
if (existing == null) {
player.sendSystemMessage(message("noLink"), true);
return;
}
unlink(level, existing, cart, true);
item.hurtAndBreak(settings().unlinkDamage(), player, event.getHand().asEquipmentSlot());
return;
}
if (existing != null) {
player.sendSystemMessage(message("occupied"), true);
return;
}
Vec3 outward = CouplingGeometry.outward(cart, end);
var candidates =
level.getEntitiesOfClass(
AbstractMinecart.class,
cart.getBoundingBox().inflate(settings().maximumDistance()),
other -> other != cart && other.isAlive());
candidates.sort(Comparator.comparingDouble(cart::distanceToSqr));
for (var other : candidates) {
Vec3 between = other.position().subtract(cart.position());
double distance = between.length();
if (distance < settings().minimumDistance() || distance > settings().maximumDistance() || Math.abs(between.y) > settings().maximumVerticalDistance()) continue;
var direction = between.horizontal().normalize();
if (direction.dot(outward) < settings().alignment()) continue;
int otherEnd = CouplingGeometry.front(other).dot(direction) > 0 ? 1 : 0;
if (CouplingGeometry.outward(other, otherEnd).dot(direction) > -settings().alignment()
|| data.at(other.getUUID(), otherEnd) != null) continue;
if (!CouplingGeometry.onRail(cart) || !CouplingGeometry.onRail(other)) continue;
var hit =
level.clip(
new ClipContext(
CouplingGeometry.anchor(cart, end),
CouplingGeometry.anchor(other, otherEnd),
ClipContext.Block.COLLIDER,
ClipContext.Fluid.NONE,
cart));
if (hit.getType() != HitResult.Type.MISS) continue;
data.add(
new TrainData.Link(
cart.getUUID(),
end,
other.getUUID(),
otherEnd,
online.astradev.plus.api.AstraPlusApi.current().flatMap(api -> api.find(item))
.map(value -> value.id().toString())
.orElseGet(() -> BuiltInRegistries.ITEM.getKey(item.getItem()).toString()),
!player.hasInfiniteMaterials() && settings().itemCost() > 0,
distance));
item.consume(settings().itemCost(), player);
player.sendSystemMessage(message("linked"), true);
return;
}
player.sendSystemMessage(
message("noCandidate"),
true);
}
public static void unlink(ServerLevel level, TrainData.Link link, Entity at, boolean refund) {
if (!TrainData.get(level).remove(link)) return;
discard(new DisplayKey(level, link));
if (refund && link.paid()) at.spawnAtLocation(level, chainStack(link));
}
private static Item chainItem(TrainData.Link link) {
return chainStack(link).getItem();
}
private static ItemStack chainStack(TrainData.Link link) {
var id = Identifier.tryParse(link.item());
if (id != null) {
var api = online.astradev.plus.api.AstraPlusApi.current().orElse(null);
if (api != null && api.find(id).isPresent()) {
var saved = api.create(id, 1);
if (saved.getItem() instanceof BlockItem) return saved;
}
}
var item = id == null ? BuiltInRegistries.ITEM.getValue(Identifier.parse(settings().fallbackItem())) : BuiltInRegistries.ITEM.getValue(id);
return new ItemStack(item instanceof BlockItem ? item : BuiltInRegistries.ITEM.getValue(Identifier.parse(settings().fallbackItem())));
}
private static AbstractMinecart cart(ServerLevel level, UUID id) {
return level.getEntity(id) instanceof AbstractMinecart cart && cart.isAlive() ? cart : null;
}
@SubscribeEvent
public static void leave(EntityLeaveLevelEvent event) {
if (!enabled() || !(event.getEntity() instanceof AbstractMinecart cart)
|| !(event.getLevel() instanceof ServerLevel level)) return;
var reason = cart.getRemovalReason();
for (var link : TrainData.get(level).links())
if (link.touches(cart.getUUID())) {
// Visibility/unload callbacks can run while vanilla iterates an entity section.
// Let the post-tick display pass remove those visuals outside that iteration.
if (reason != null
&& (reason.shouldDestroy()
|| reason == Entity.RemovalReason.CHANGED_DIMENSION))
unlink(level, link, cart, true);
}
}
@SubscribeEvent
public static void pre(ServerTickEvent.Pre event) {
if (enabled()) for (var level : event.getServer().getAllLevels()) step(level);
}
/**
* Synchronize momentum along each cart's rail tangent; springs correct chain slack, never
* teleport carts.
*/
public static void step(ServerLevel level) {
if (!enabled()) return;
var pausedCarts = new HashSet<UUID>();
PAUSED.put(level, pausedCarts);
var playerPushes = PLAYER_PUSHES.remove(level);
if (playerPushes == null) playerPushes = Set.of();
var data = TrainData.get(level);
var links = data.links();
var visited = new HashSet<UUID>();
for (var seed : links) {
if (visited.contains(seed.a())) continue;
var signs = directions(seed.a(), links);
visited.addAll(signs.keySet());
moveTrain(level, links, signs, pausedCarts, playerPushes);
}
}
private static void moveTrain(
ServerLevel level,
List<TrainData.Link> links,
Map<UUID, Integer> signs,
Set<UUID> pausedCarts,
Set<UUID> playerPushes) {
var carts = new LinkedHashMap<UUID, AbstractMinecart>();
var axes = new HashMap<UUID, Vec3>();
boolean paused = false;
double momentum = 0;
double limit = Double.MAX_VALUE;
double controlledMomentum = 0;
var controls = new HashSet<UUID>();
for (var pair : signs.entrySet()) {
var cart = cart(level, pair.getKey());
if (cart == null) {
paused = true;
continue;
}
carts.put(pair.getKey(), cart);
Vec3 tangent = CouplingGeometry.front(cart).scale(pair.getValue());
axes.put(pair.getKey(), tangent);
if (!CouplingGeometry.onRail(cart)) paused = true;
double scale = travelScale(cart);
momentum += cart.getDeltaMovement().dot(tangent) * scale;
if (playerControls(cart, playerPushes)) {
controlledMomentum += alignedSpeed(cart, tangent) * scale;
controls.add(cart.getUUID());
}
limit = Math.min(limit, cart.getMaxSpeed(level));
}
if (carts.isEmpty()) return;
if (paused) {
pausedCarts.addAll(carts.keySet());
carts.values().forEach(c -> c.setDeltaMovement(Vec3.ZERO));
return;
}
// Player input drives the train as a unit. Averaging it with idle carts diluted
// the tiny vanilla rider impulse; a dot product also erased side-on walking pushes.
double speed = momentum / carts.size();
if (!controls.isEmpty()) speed = controlledMomentum / controls.size();
speed = Math.clamp(speed, -limit, limit);
var corrections = new HashMap<UUID, Double>();
for (var link : links)
if (carts.containsKey(link.a()) && carts.containsKey(link.b())) {
var a = carts.get(link.a());
var b = carts.get(link.b());
double distance = a.position().distanceTo(b.position());
if (distance > settings().breakDistance()) {
unlink(level, link, a, true);
continue;
}
double pull = Math.clamp((distance - link.length()) * settings().springStrength(), -settings().maximumCorrection(), settings().maximumCorrection());
double direction = signs.get(link.a()) * (link.endA() == 0 ? 1 : -1);
corrections.merge(link.a(), pull * direction, Double::sum);
corrections.merge(link.b(), -pull * direction, Double::sum);
}
for (var pair : carts.entrySet()) {
// Followers take up slack; pulling back the driven cart would cancel its 0.001
// rider impulse.
var cart = pair.getValue();
double cartSpeed = speed;
if (!controls.contains(pair.getKey())) {
cartSpeed += corrections.getOrDefault(pair.getKey(), 0.0);
}
cartSpeed = Math.clamp(cartSpeed, -limit, limit);
Vec3 direction = axes.get(pair.getKey());
Vec3 velocity = direction.scale(cartSpeed / travelScale(cart));
cart.setDeltaMovement(velocity.x, cart.getDeltaMovement().y, velocity.z);
}
}
private static Map<UUID, Integer> directions(UUID start, List<TrainData.Link> links) {
var signs = new LinkedHashMap<UUID, Integer>();
var pending = new ArrayDeque<UUID>();
signs.put(start, 1);
pending.add(start);
while (!pending.isEmpty()) {
var id = pending.removeFirst();
for (var link : links) {
if (!link.touches(id)) continue;
var other = link.other(id);
if (signs.containsKey(other)) continue;
int sign = signs.get(id);
if (link.end(id) == link.end(other)) sign = -sign;
signs.put(other, sign);
pending.add(other);
}
}
return signs;
}
private static boolean playerControls(AbstractMinecart cart, Set<UUID> pushes) {
if (pushes.contains(cart.getUUID())) return true;
if (!(cart.getFirstPassenger() instanceof ServerPlayer player)) return false;
return player.getLastClientMoveIntent().horizontalDistanceSqr() > 0;
}
private static double travelScale(AbstractMinecart cart) {
return !AbstractMinecart.useExperimentalMovement(cart.level()) && cart.isVehicle()
? .75
: 1;
}
private static double alignedSpeed(AbstractMinecart cart, Vec3 tangent) {
var movement = cart.getDeltaMovement();
double along = movement.dot(tangent);
if (Math.abs(along) < 1e-9) {
Vec3 railDirection = CouplingGeometry.railDirection(cart);
if (railDirection != null) {
along = railDirection.dot(tangent);
// Vanilla reverses the default exit for perpendicular input in the new engine.
if (AbstractMinecart.useExperimentalMovement(cart.level())) along = -along;
}
}
return Math.copySign(movement.horizontalDistance(), along);
}
@SubscribeEvent
public static void post(ServerTickEvent.Post event) {
if (enabled()) for (var level : event.getServer().getAllLevels()) show(level);
else {
for (var key : new ArrayList<>(DISPLAYS.keySet())) discard(key);
PAUSED.clear();
PLAYER_PUSHES.clear();
}
}
public static void show(ServerLevel level) {
if (!enabled()) return;
var keys = new HashSet<DisplayKey>();
for (var link : TrainData.get(level).links()) {
var a = cart(level, link.a());
var b = cart(level, link.b());
if (a == null || b == null) continue;
var key = new DisplayKey(level, link);
keys.add(key);
var display = DISPLAYS.get(key);
boolean create = display == null || display.isRemoved();
if (create) {
var chain = (BlockItem) chainItem(link);
display = new BlockLine(level, chain.getBlock().defaultBlockState());
}
Vec3 start = CouplingGeometry.anchor(a, link.endA());
Vec3 end = CouplingGeometry.anchor(b, link.endB());
display.connect(start, end);
if (create && level.addFreshEntity(display)) DISPLAYS.put(key, display);
}
for (var key : new ArrayList<>(DISPLAYS.keySet()))
if (key.level == level && !keys.contains(key)) discard(key);
}
public static void reverse(AbstractMinecart hit, Vec3 reflected) {
if (!enabled() || !(hit.level() instanceof ServerLevel level)) { hit.setDeltaMovement(reflected); return; }
var data = TrainData.get(level);
var ids = data.component(hit.getUUID());
if (ids.size() == 1) {
hit.setDeltaMovement(reflected.scale(1 / travelScale(hit)));
return;
}
// Propagate reversal through the closed or open graph, preserving each cart's local travel
// direction.
var signs = directions(hit.getUUID(), data.links());
double speed = reflected.dot(CouplingGeometry.front(hit));
for (var id : ids) {
var cart = cart(level, id);
if (cart != null) {
var v =
CouplingGeometry.front(cart)
.scale(speed * signs.getOrDefault(id, 1) / travelScale(cart));
cart.setDeltaMovement(v.x, cart.getDeltaMovement().y, v.z);
}
}
}
private static void discard(DisplayKey key) {
var display = DISPLAYS.remove(key);
if (display != null) display.discard();
}
@SubscribeEvent
public static void stop(ServerStoppedEvent event) {
close();
CouplingGeometry.clear();
}
/** Stop callbacks/visuals before world saving, but retain entity serialization state. */
public static void close() {
for (var key : new ArrayList<>(DISPLAYS.keySet())) discard(key);
PAUSED.clear();
PLAYER_PUSHES.clear();
}
}
@@ -5,7 +5,7 @@ license="All Rights Reserved"
modId="astracontent" modId="astracontent"
version="${version}" version="${version}"
displayName="AstraContent" displayName="AstraContent"
description='''Server-only crossbow ammunition and copper rails. Vanilla clients supported.''' description='''Server-only ammunition, copper rails, minecart trains and transport policies. Vanilla clients supported.'''
[[mixins]] [[mixins]]
config="astracontent.mixins.json" config="astracontent.mixins.json"
[[dependencies.astracontent]] [[dependencies.astracontent]]
@@ -21,6 +21,6 @@ side="SERVER"
[[dependencies.astracontent]] [[dependencies.astracontent]]
modId="astraplus" modId="astraplus"
type="required" type="required"
versionRange="[0.9.11,0.10)" versionRange="[0.9.13,0.10)"
ordering="AFTER" ordering="AFTER"
side="SERVER" side="SERVER"
+8 -1
View File
@@ -4,7 +4,14 @@
"compatibilityLevel": "JAVA_25", "compatibilityLevel": "JAVA_25",
"mixins": [ "mixins": [
"ProjectilePolicyCrossbowMixin", "ProjectilePolicyCrossbowMixin",
"ProjectilePayloadMixin" "ProjectilePayloadMixin",
"LegacyDataBlockPlacementMixin",
"TransportMinecartMixin",
"TransportFurnaceCartMixin",
"TransportExperimentalCartMixin",
"TransportTrainCartMixin",
"TransportSlimeCollisionMixin",
"TransportBoatPacketMixin"
], ],
"injectors": {"defaultRequire": 1} "injectors": {"defaultRequire": 1}
} }
@@ -0,0 +1,75 @@
package online.astradev.content.transport;
import com.google.gson.JsonParser;
import java.lang.reflect.Proxy;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.world.level.storage.ValueOutput;
import net.minecraft.world.phys.Vec3;
import online.astradev.content.transport.train.CouplingGeometry;
import online.astradev.content.transport.train.Trains;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class TransportPersistenceTest {
private String resource(String name) throws Exception {
try (var input = getClass().getResourceAsStream("/content/policies/transport-" + name + ".json")) {
assertNotNull(input);
return new String(input.readAllBytes(), StandardCharsets.UTF_8);
}
}
@Test void shutdownDisablesBehaviorButPreservesSpeedAndFrontUntilVanillaSaveCompletes() throws Exception {
var policy = TransportPolicy.parse(resource("defaults"));
var keys = TransportPersistence.keys(JsonParser.parseString(resource("compatibility")).getAsJsonObject());
TransportCapabilities.publish(policy, keys);
var snapshot = TransportCapabilities.persistence();
// A null sentinel exercises the WeakHashMap serialization lifecycle without a running level.
CouplingGeometry.restoreFront(null, new Vec3(-1, 0, 0));
var saved = new HashMap<String, Double>();
ValueOutput output = (ValueOutput) Proxy.newProxyInstance(ValueOutput.class.getClassLoader(),
new Class<?>[]{ValueOutput.class}, (proxy, method, arguments) -> {
if (method.getName().equals("putDouble")) saved.put((String) arguments[0], (Double) arguments[1]);
return null;
});
try {
assertTrue(TransportCapabilities.active());
TransportCapabilities.close(); // ServerStoppingEvent happens before entity/world serialization.
assertFalse(TransportCapabilities.active());
assertNull(TransportCapabilities.policy());
assertSame(snapshot, TransportCapabilities.persistence());
assertEquals(keys.get("trainStorageId"), TransportCapabilities.storage("trainStorageId"));
TransportCapabilities.persistence().saveSpeed(20, saved::put);
CouplingGeometry.save(null, output);
assertEquals(20.0, saved.get(keys.get("cartSpeedKey")));
assertEquals(-1.0, saved.get(keys.get("frontXKey")));
assertEquals(0.0, saved.get(keys.get("frontZKey")));
assertEquals(20.0, snapshot.readSpeed(key -> saved.getOrDefault(key, 0.0)));
Trains.stop(null); // ServerStoppedEvent is after the final world save.
saved.clear();
CouplingGeometry.save(null, output);
assertEquals(0.0, saved.get(keys.get("frontXKey")), "front cache is released after saving");
assertFalse(TransportCapabilities.active(), "retained metadata never reactivates callbacks");
} finally {
TransportCapabilities.close();
Trains.stop(null);
}
}
@Test void immutableKeysAndFiniteBoundedSpeedAreIndependentOfLivePolicy() {
var keys = new HashMap<>(Map.of("cartSpeedKey", "test-speed", "frontXKey", "test-x", "frontZKey", "test-z", "trainStorageId", "test:trains"));
var savedState = new TransportPersistence(keys, 40);
keys.put("cartSpeedKey", "changed");
assertEquals("test-speed", savedState.key("cartSpeedKey"));
assertThrows(UnsupportedOperationException.class, () -> savedState.keys().clear());
assertEquals(40, savedState.readSpeed(key -> 100));
assertEquals(.1, savedState.readSpeed(key -> .01));
for (double invalid : new double[]{0, -1, Double.NaN, Double.POSITIVE_INFINITY}) {
assertEquals(0, savedState.readSpeed(key -> invalid));
var output = new HashMap<String, Double>();
savedState.saveSpeed(invalid, output::put);
assertTrue(output.isEmpty());
}
}
}
@@ -0,0 +1,36 @@
package online.astradev.content.transport;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*;
class TransportPolicyTest {
private JsonObject bundled() throws Exception {
try (var input = getClass().getResourceAsStream("/content/policies/transport-defaults.json")) {
assertNotNull(input, "Distribution must supply declarations, not Java defaults");
return JsonParser.parseString(new String(input.readAllBytes(), StandardCharsets.UTF_8)).getAsJsonObject();
}
}
@Test void declarationsAreImmutableAndTunableWithoutProviders() throws Exception {
var json = bundled();
json.getAsJsonObject("rail").addProperty("signalUnits", 3);
json.getAsJsonObject("bounce").addProperty("restitution", .25);
var settings = TransportPolicy.parse(json.toString());
assertEquals(3, settings.rail().signalUnits());
assertEquals(.25, settings.bounce().restitution());
assertThrows(UnsupportedOperationException.class, () -> settings.bounce().blocks().clear());
assertThrows(UnsupportedOperationException.class, () -> settings.coupling().messages().clear());
}
@Test void rejectsUnsafeRangesAndUnknownAdapterKindsBeforePublication() throws Exception {
var json = bundled();
json.getAsJsonObject("coupling").addProperty("maximumDistance", 1000000);
assertThrows(IllegalArgumentException.class, () -> TransportPolicy.parse(json.toString()));
var invalid = bundled();
invalid.getAsJsonObject("bounce").getAsJsonArray("entityKinds").add("unknown-provider");
assertThrows(IllegalArgumentException.class, () -> TransportPolicy.parse(invalid.toString()));
}
}