Simplify train and rail logic and consolidate integration tests
This commit is contained in:
@@ -1,8 +0,0 @@
|
|||||||
# AstraContent
|
|
||||||
|
|
||||||
- Серверный мод Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25.
|
|
||||||
- Клиент — ванильный Minecraft с серверным ресурспаком. Не добавлять клиентские регистрации или обязательные сетевые каналы.
|
|
||||||
- Предметы и рецепты используют ванильные компоненты и сериализаторы; ресурсы добавляются в исходники ресурспака AstraPlus. Механики принадлежат AstraContent.
|
|
||||||
- Правила родительского AGENTS.md о Git и резервных копиях обязательны.
|
|
||||||
- Для этого мода вместо Paper использовать `C:\Users\ScarPC\Documents\NeoForge Server 26.2\mods`, архив — `old-mods/YYYYMMDD-HHMMSS`.
|
|
||||||
- Собирать, проверять, устанавливать прямо в mods, сравнивать SHA-256; не менять конфигурации и мир рабочего сервера.
|
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
# AstraContent 0.2.1
|
# AstraContent 0.2.2
|
||||||
|
|
||||||
Серверный мод для Minecraft 26.2, NeoForge 26.2.0.79 и Java 25.
|
Серверный мод для Minecraft 26.2, NeoForge 26.2.0.79 и Java 25.
|
||||||
**На клиент мод устанавливать не нужно.** Для медного оформления используется обычный
|
**На клиент мод устанавливать не нужно.** Для медного оформления используется обычный
|
||||||
серверный ресурспак AstraPlus. AstraPlus 0.5.x обязателен для сборки ресурсов;
|
серверный ресурспак AstraPlus. AstraPlus 0.9.x обязателен для сборки ресурсов;
|
||||||
AstraPacks раздаёт их игрокам, если установлен и настроен.
|
AstraPacks раздаёт их игрокам, если установлен и настроен.
|
||||||
|
|
||||||
## Арбалет и огненный заряд
|
## Арбалет и огненный заряд
|
||||||
@@ -115,27 +115,19 @@ Shift + ПКМ киркой по выбранному торцу снимает
|
|||||||
|
|
||||||
## Установка и разработка
|
## Установка и разработка
|
||||||
|
|
||||||
Рабочий JAR: `C:\Users\ScarPC\Documents\NeoForge Server 26.2\mods\AstraContent-0.2.1.jar`.
|
Рабочий JAR: `C:\Users\ScarPC\Documents\NeoForge Server 26.2\mods\AstraContent-0.2.2.jar`.
|
||||||
После установки требуется перезапуск сервера. При запуске добавляются только отсутствующие
|
После установки требуется перезапуск сервера. При запуске добавляются только отсутствующие
|
||||||
ресурсы в `astraplus/resources/assets/astracontent`; правки администратора не заменяются.
|
ресурсы в `astraplus/resources/assets/astracontent`; правки администратора не заменяются.
|
||||||
При выключенной стартовой сборке ресурспака выполнить `/astraplus build`.
|
При выключенной стартовой сборке ресурспака выполнить `/astraplus build`.
|
||||||
Конфигурации, миры и исходники AstraPlus установка JAR не заменяет.
|
Конфигурации, миры и исходники AstraPlus установка JAR не заменяет.
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
.\gradlew.bat build verificationJar
|
.\gradlew.bat build
|
||||||
.\tools\verify-server.ps1
|
.\gradlew.bat integrationTest
|
||||||
.\tools\verify-server.ps1 -Experimental
|
.\gradlew.bat integrationTest -Pexperimental
|
||||||
```
|
```
|
||||||
|
|
||||||
Проверки используют отдельные временные миры в `build/verification-*`, затем перезапускают
|
Для запуска серверных проверок нужны PowerShell 7 и соседние сборки AstraPlus/AstraPacks.
|
||||||
их для проверки сохранения. Проверяются настоящий крафт и размещение, дроп, вощение,
|
Серверные проверки находятся в src/integrationTest, результаты — только в build.
|
||||||
боеприпасы, мультивыстрел, ПКМ огненным зарядом, скорости и аналоговый редстоун,
|
Они проверяют оба движка вагонеток и сохранение после перезапуска. Перед ними нужно
|
||||||
повороты/уклоны во всех направлениях, тормоза, детекторы, активаторы, вода,
|
собрать соседний AstraPlus. Рабочие миры и конфигурации при проверках не используются.
|
||||||
типы вагонеток и переходы между ограничениями, сцепки/расход/возврат цепей,
|
|
||||||
движущийся замкнутый состав, повороты и уклоны составов, удары о слизь/камень,
|
|
||||||
столкновения лодок и сохранение сцепок. Тестовый JAR на рабочий сервер не устанавливается.
|
|
||||||
Толкание игроком с четырёх сторон и движение пассажира вперёд/назад сравниваются
|
|
||||||
с одиночной вагонеткой на обычных рельсах.
|
|
||||||
|
|
||||||
Модели состоят из геометрии и ссылок на ванильные текстуры. Воспроизводимая генерация:
|
|
||||||
`tools/generate-resources.ps1`. Визуальная проверка в живом клиенте отдельно не автоматизирована.
|
|
||||||
|
|||||||
+32
-8
@@ -1,6 +1,9 @@
|
|||||||
plugins { java; id("net.neoforged.moddev") version "2.0.146" }
|
plugins {
|
||||||
|
java
|
||||||
|
id("net.neoforged.moddev") version "2.0.146"
|
||||||
|
}
|
||||||
group = "online.astradev"
|
group = "online.astradev"
|
||||||
version = "0.2.1"
|
version = "0.2.2"
|
||||||
repositories { mavenCentral() }
|
repositories { mavenCentral() }
|
||||||
dependencies {
|
dependencies {
|
||||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||||
@@ -10,13 +13,34 @@ neoForge {
|
|||||||
version = "26.2.0.79"
|
version = "26.2.0.79"
|
||||||
mods { create("astracontent") { sourceSet(sourceSets.main.get()) } }
|
mods { create("astracontent") { sourceSet(sourceSets.main.get()) } }
|
||||||
}
|
}
|
||||||
java { toolchain.languageVersion.set(JavaLanguageVersion.of(25)); withSourcesJar() }
|
java {
|
||||||
tasks.withType<JavaCompile>().configureEach { options.encoding = "UTF-8"; options.release.set(25) }
|
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
|
||||||
tasks.processResources { filesMatching("META-INF/neoforge.mods.toml") { expand("version" to project.version) } }
|
withSourcesJar()
|
||||||
|
}
|
||||||
|
tasks.withType<JavaCompile>().configureEach {
|
||||||
|
options.encoding = "UTF-8"
|
||||||
|
options.release.set(25)
|
||||||
|
}
|
||||||
|
tasks.processResources {
|
||||||
|
inputs.property("modVersion", project.version)
|
||||||
|
filesMatching("META-INF/neoforge.mods.toml") { expand("version" to project.version) }
|
||||||
|
}
|
||||||
tasks.test { useJUnitPlatform() }
|
tasks.test { useJUnitPlatform() }
|
||||||
sourceSets.test { compileClasspath += sourceSets.main.get().compileClasspath; runtimeClasspath += sourceSets.main.get().compileClasspath }
|
sourceSets.test {
|
||||||
val verification = sourceSets.create("verification") {
|
compileClasspath += sourceSets.main.get().compileClasspath
|
||||||
|
runtimeClasspath += sourceSets.main.get().compileClasspath
|
||||||
|
}
|
||||||
|
val integrationTest = sourceSets.create("integrationTest") {
|
||||||
compileClasspath += sourceSets.main.get().output + sourceSets.main.get().compileClasspath
|
compileClasspath += sourceSets.main.get().output + sourceSets.main.get().compileClasspath
|
||||||
runtimeClasspath += output + compileClasspath
|
runtimeClasspath += output + compileClasspath
|
||||||
}
|
}
|
||||||
tasks.register<Jar>("verificationJar") { from(verification.output); archiveClassifier.set("verification") }
|
tasks.register<Jar>("integrationTestJar") {
|
||||||
|
from(integrationTest.output)
|
||||||
|
archiveClassifier.set("integration-tests")
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.register<Exec>("integrationTest") {
|
||||||
|
dependsOn("build", "integrationTestJar")
|
||||||
|
commandLine("pwsh", "-NoProfile", "-File", "src/integrationTest/run.ps1")
|
||||||
|
if (providers.gradleProperty("experimental").isPresent) args("-Experimental")
|
||||||
|
}
|
||||||
|
|||||||
+370
@@ -0,0 +1,370 @@
|
|||||||
|
package online.astradev.content.verification;
|
||||||
|
|
||||||
|
import net.minecraft.core.*;
|
||||||
|
import net.minecraft.core.component.DataComponents;
|
||||||
|
import net.minecraft.server.level.ServerLevel;
|
||||||
|
import net.minecraft.world.InteractionHand;
|
||||||
|
import net.minecraft.world.entity.*;
|
||||||
|
import net.minecraft.world.entity.item.ItemEntity;
|
||||||
|
import net.minecraft.world.entity.projectile.FireworkRocketEntity;
|
||||||
|
import net.minecraft.world.entity.projectile.arrow.AbstractArrow;
|
||||||
|
import net.minecraft.world.entity.vehicle.minecart.*;
|
||||||
|
import net.minecraft.world.item.*;
|
||||||
|
import net.minecraft.world.item.component.ChargedProjectiles;
|
||||||
|
import net.minecraft.world.item.context.UseOnContext;
|
||||||
|
import net.minecraft.world.level.block.*;
|
||||||
|
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||||
|
import net.minecraft.world.phys.*;
|
||||||
|
import net.neoforged.api.distmarker.Dist;
|
||||||
|
import net.neoforged.fml.common.Mod;
|
||||||
|
import net.neoforged.neoforge.common.NeoForge;
|
||||||
|
import net.neoforged.neoforge.common.util.FakePlayerFactory;
|
||||||
|
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||||
|
|
||||||
|
import online.astradev.content.rail.*;
|
||||||
|
import online.astradev.content.weapon.*;
|
||||||
|
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
@Mod(value = "astracontent_verify", dist = Dist.DEDICATED_SERVER)
|
||||||
|
public final class ContentVerification {
|
||||||
|
private int ticks;
|
||||||
|
private final List<AbstractMinecart> carts = new ArrayList<>();
|
||||||
|
private boolean done;
|
||||||
|
private final double[] previousX = new double[4];
|
||||||
|
|
||||||
|
public ContentVerification() {
|
||||||
|
if (!Boolean.getBoolean("astracontent.verify"))
|
||||||
|
throw new IllegalStateException("Isolated test server only");
|
||||||
|
NeoForge.EVENT_BUS.addListener(this::tick);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void tick(ServerTickEvent.Post event) {
|
||||||
|
if (done) return;
|
||||||
|
var server = event.getServer();
|
||||||
|
var level = server.overworld();
|
||||||
|
try {
|
||||||
|
ticks++;
|
||||||
|
if (ticks == 1)
|
||||||
|
server.getCommands()
|
||||||
|
.performPrefixedCommand(
|
||||||
|
server.createCommandSourceStack(), "forceload add 0 0 159 95");
|
||||||
|
if (ticks == 20) {
|
||||||
|
require(
|
||||||
|
AbstractMinecart.useExperimentalMovement(level)
|
||||||
|
== Boolean.getBoolean("astracontent.expectedExperimental"),
|
||||||
|
"requested movement engine enabled");
|
||||||
|
if (Files.exists(Path.of("first-pass.txt"))) {
|
||||||
|
for (int age = 0; age < 4; age++)
|
||||||
|
require(
|
||||||
|
Rails.find(level, new BlockPos(2, 100, age * 4)).age() == age,
|
||||||
|
"chunk identity survives restart");
|
||||||
|
var saved =
|
||||||
|
level.getEntity(
|
||||||
|
UUID.fromString(Files.readString(Path.of("saved-cart.txt"))));
|
||||||
|
require(saved instanceof AbstractMinecart, "saved minecart restored");
|
||||||
|
require(
|
||||||
|
Math.abs(((CartSpeed) saved).astracontent$limit(level) - 1) < .001,
|
||||||
|
"personal speed survives restart on ordinary rails");
|
||||||
|
TrainVerification.restart(level);
|
||||||
|
finish(
|
||||||
|
server,
|
||||||
|
"PASS restart: rail ages, personal speed, train and chain display"
|
||||||
|
+ " survive reload");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setup(level);
|
||||||
|
ammunition(level);
|
||||||
|
}
|
||||||
|
if (ticks == 129)
|
||||||
|
for (int age = 0; age < 4; age++) previousX[age] = carts.get(age).getX();
|
||||||
|
if (ticks == 130) {
|
||||||
|
for (int age = 0; age < 4; age++) {
|
||||||
|
var cart = carts.get(age);
|
||||||
|
double actual = cart.getX() - previousX[age];
|
||||||
|
double expected = (20 - age * 4) / 20.0;
|
||||||
|
require(
|
||||||
|
Math.abs(actual - expected) < .015,
|
||||||
|
"copper measured speed "
|
||||||
|
+ age
|
||||||
|
+ ": "
|
||||||
|
+ actual
|
||||||
|
+ " expected "
|
||||||
|
+ expected);
|
||||||
|
}
|
||||||
|
TrackVerification.run(level);
|
||||||
|
TrainVerification.run(level);
|
||||||
|
var saved = new Minecart(EntityTypes.MINECART, level);
|
||||||
|
saved.setPos(2.5, 100.0625, .5);
|
||||||
|
saved.setDeltaMovement(.1, 0, 0);
|
||||||
|
saved.tick();
|
||||||
|
for (int x = 29; x <= 33; x++) {
|
||||||
|
var p = new BlockPos(x, 100, 40);
|
||||||
|
level.setBlockAndUpdate(p.below(), Blocks.STONE.defaultBlockState());
|
||||||
|
level.setBlockAndUpdate(
|
||||||
|
p,
|
||||||
|
Blocks.RAIL
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(RailBlock.SHAPE, RailShape.EAST_WEST));
|
||||||
|
}
|
||||||
|
saved.setPos(30.5, 100.0625, 40.5);
|
||||||
|
saved.setDeltaMovement(Vec3.ZERO);
|
||||||
|
level.addFreshEntity(saved);
|
||||||
|
Files.writeString(Path.of("saved-cart.txt"), saved.getUUID().toString());
|
||||||
|
Files.writeString(Path.of("first-pass.txt"), "PASS");
|
||||||
|
finish(
|
||||||
|
server,
|
||||||
|
"PASS gameplay: native placement, all ages, drops, power, ammunition, and"
|
||||||
|
+ " measured 20/16/12/8 m/s");
|
||||||
|
}
|
||||||
|
} catch (Throwable error) {
|
||||||
|
error.printStackTrace();
|
||||||
|
try {
|
||||||
|
Files.writeString(Path.of("verification-result.txt"), "FAIL " + error);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
done = true;
|
||||||
|
server.halt(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setup(ServerLevel level) {
|
||||||
|
var ingredients =
|
||||||
|
List.of(
|
||||||
|
new ItemStack(Items.COPPER_INGOT),
|
||||||
|
ItemStack.EMPTY,
|
||||||
|
new ItemStack(Items.COPPER_INGOT),
|
||||||
|
new ItemStack(Items.COPPER_INGOT),
|
||||||
|
new ItemStack(Items.STICK),
|
||||||
|
new ItemStack(Items.COPPER_INGOT),
|
||||||
|
new ItemStack(Items.COPPER_INGOT),
|
||||||
|
new ItemStack(Items.REDSTONE),
|
||||||
|
new ItemStack(Items.COPPER_INGOT));
|
||||||
|
var input = net.minecraft.world.item.crafting.CraftingInput.of(3, 3, ingredients);
|
||||||
|
var recipe =
|
||||||
|
level.getServer()
|
||||||
|
.getRecipeManager()
|
||||||
|
.getRecipeFor(
|
||||||
|
net.minecraft.world.item.crafting.RecipeType.CRAFTING, input, level)
|
||||||
|
.orElseThrow();
|
||||||
|
var crafted = recipe.value().assemble(input);
|
||||||
|
require(
|
||||||
|
crafted.getCount() == 6 && new RailKind(0, false).equals(RailItems.find(crafted)),
|
||||||
|
"native crafting recipe makes six copper rails");
|
||||||
|
for (int code = 0; code < 8; code++)
|
||||||
|
require(
|
||||||
|
RailItems.find(Rails.stack(RailKind.decode(code), 1)).code() == code,
|
||||||
|
"item variant " + code);
|
||||||
|
for (int age = 0; age < 4; age++) {
|
||||||
|
int z = age * 4;
|
||||||
|
for (int x = 0; x < 160; x++) {
|
||||||
|
var pos = new BlockPos(x, 100, z);
|
||||||
|
level.setBlockAndUpdate(pos.below(), Blocks.REDSTONE_BLOCK.defaultBlockState());
|
||||||
|
level.setBlockAndUpdate(
|
||||||
|
pos,
|
||||||
|
Blocks.POWERED_RAIL
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(PoweredRailBlock.SHAPE, RailShape.EAST_WEST));
|
||||||
|
Rails.put(level, pos, new RailKind(age, true));
|
||||||
|
}
|
||||||
|
var cart = new Minecart(EntityTypes.MINECART, level);
|
||||||
|
cart.setPos(2.5, 100.0625, z + .5);
|
||||||
|
cart.setDeltaMovement(.25, 0, 0);
|
||||||
|
level.addFreshEntity(cart);
|
||||||
|
carts.add(cart);
|
||||||
|
}
|
||||||
|
var pos = new BlockPos(5, 100, 24);
|
||||||
|
level.setBlockAndUpdate(pos.below(), Blocks.STONE.defaultBlockState());
|
||||||
|
var item = Rails.stack(new RailKind(2, false), 2);
|
||||||
|
var context =
|
||||||
|
new UseOnContext(
|
||||||
|
level,
|
||||||
|
null,
|
||||||
|
InteractionHand.MAIN_HAND,
|
||||||
|
item,
|
||||||
|
new BlockHitResult(
|
||||||
|
Vec3.atCenterOf(pos.below()), Direction.UP, pos.below(), false));
|
||||||
|
require(item.getItem().useOn(context).consumesAction(), "native BlockItem placement");
|
||||||
|
require(level.getBlockState(pos).is(Blocks.POWERED_RAIL), "real vanilla carrier");
|
||||||
|
require(Rails.find(level, pos).age() == 2, "placement preserves variant");
|
||||||
|
require(item.getCount() == 1, "placement consumes exactly one");
|
||||||
|
var player = FakePlayerFactory.getMinecraft(level);
|
||||||
|
player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.HONEYCOMB, 2));
|
||||||
|
var hit = new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false);
|
||||||
|
Rails.use(
|
||||||
|
new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickBlock(
|
||||||
|
player, InteractionHand.MAIN_HAND, pos, hit));
|
||||||
|
require(Rails.find(level, pos).waxed(), "waxing native rail");
|
||||||
|
require(player.getMainHandItem().getCount() == 1, "wax consumes one honeycomb");
|
||||||
|
player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.IRON_AXE));
|
||||||
|
Rails.use(
|
||||||
|
new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickBlock(
|
||||||
|
player, InteractionHand.MAIN_HAND, pos, hit));
|
||||||
|
require(
|
||||||
|
!Rails.find(level, pos).waxed() && Rails.find(level, pos).age() == 2,
|
||||||
|
"axe removes wax first");
|
||||||
|
Rails.use(
|
||||||
|
new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickBlock(
|
||||||
|
player, InteractionHand.MAIN_HAND, pos, hit));
|
||||||
|
require(Rails.find(level, pos).age() == 1, "axe removes one oxidation stage");
|
||||||
|
Rails.put(level, pos, new RailKind(2, false));
|
||||||
|
var drops = Block.getDrops(level.getBlockState(pos), level, pos, null);
|
||||||
|
require(
|
||||||
|
drops.size() == 1
|
||||||
|
&& new RailKind(2, false).equals(RailItems.find(drops.getFirst())),
|
||||||
|
"custom loot");
|
||||||
|
level.destroyBlock(pos.below(), true);
|
||||||
|
require(Rails.find(level, pos) == null, "support loss clears identity");
|
||||||
|
require(
|
||||||
|
level.getEntitiesOfClass(ItemEntity.class, new AABB(pos).inflate(2)).stream()
|
||||||
|
.anyMatch(e -> RailItems.find(e.getItem()) != null),
|
||||||
|
"support loss drops custom rail");
|
||||||
|
var signalPos = new BlockPos(20, 100, 24);
|
||||||
|
level.setBlockAndUpdate(signalPos.below(), Blocks.REDSTONE_BLOCK.defaultBlockState());
|
||||||
|
level.setBlockAndUpdate(signalPos, Blocks.POWERED_RAIL.defaultBlockState());
|
||||||
|
require(RailSpeed.signal(level, signalPos) == 15, "redstone block supplies 15");
|
||||||
|
require(RailSpeed.target(level, signalPos, 8) == 30, "gold rail 30 m/s at signal 15");
|
||||||
|
require(Rails.find(level, signalPos) == null, "ordinary golden rail stays ordinary");
|
||||||
|
analog(level);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void analog(ServerLevel level) {
|
||||||
|
var rail = new BlockPos(30, 100, 24);
|
||||||
|
var input = rail.west();
|
||||||
|
var other = rail.east();
|
||||||
|
for (var p : List.of(rail, input, other))
|
||||||
|
level.setBlockAndUpdate(p.below(), Blocks.STONE.defaultBlockState());
|
||||||
|
level.setBlockAndUpdate(
|
||||||
|
input,
|
||||||
|
Blocks.COMPARATOR
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(ComparatorBlock.FACING, Direction.WEST)
|
||||||
|
.setValue(ComparatorBlock.POWERED, true));
|
||||||
|
level.setBlockAndUpdate(
|
||||||
|
other,
|
||||||
|
Blocks.COMPARATOR
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(ComparatorBlock.FACING, Direction.EAST)
|
||||||
|
.setValue(ComparatorBlock.POWERED, true));
|
||||||
|
level.setBlockAndUpdate(rail, Blocks.POWERED_RAIL.defaultBlockState());
|
||||||
|
var source =
|
||||||
|
(net.minecraft.world.level.block.entity.ComparatorBlockEntity)
|
||||||
|
level.getBlockEntity(input);
|
||||||
|
var second =
|
||||||
|
(net.minecraft.world.level.block.entity.ComparatorBlockEntity)
|
||||||
|
level.getBlockEntity(other);
|
||||||
|
for (int signal = 1; signal <= 15; signal++) {
|
||||||
|
source.setOutputSignal(signal);
|
||||||
|
second.setOutputSignal(Math.max(0, signal - 2));
|
||||||
|
level.setBlock(
|
||||||
|
rail,
|
||||||
|
Blocks.POWERED_RAIL
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(PoweredRailBlock.POWERED, true),
|
||||||
|
2);
|
||||||
|
require(RailSpeed.signal(level, rail) == signal, "actual comparator input " + signal);
|
||||||
|
require(RailSpeed.target(level, rail, 8) == signal * 2, "actual golden cap " + signal);
|
||||||
|
}
|
||||||
|
source.setOutputSignal(3);
|
||||||
|
second.setOutputSignal(11);
|
||||||
|
require(RailSpeed.signal(level, rail) == 11, "maximum of two inputs");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ammunition(ServerLevel level) {
|
||||||
|
var player = FakePlayerFactory.getMinecraft(level);
|
||||||
|
player.setPos(40, 115, 35);
|
||||||
|
var crossbow = (CrossbowItem) Items.CROSSBOW;
|
||||||
|
var supported =
|
||||||
|
List.of(
|
||||||
|
Items.ENDER_PEARL,
|
||||||
|
Items.FIRE_CHARGE,
|
||||||
|
Items.ENDER_EYE,
|
||||||
|
Items.EGG,
|
||||||
|
Items.BLUE_EGG,
|
||||||
|
Items.BROWN_EGG,
|
||||||
|
Items.SNOWBALL,
|
||||||
|
Items.WIND_CHARGE,
|
||||||
|
Items.EXPERIENCE_BOTTLE,
|
||||||
|
Items.TNT);
|
||||||
|
for (var ammo : supported) {
|
||||||
|
var weapon = new ItemStack(Items.CROSSBOW);
|
||||||
|
var stack = new ItemStack(ammo, 2);
|
||||||
|
player.setItemInHand(InteractionHand.MAIN_HAND, weapon);
|
||||||
|
player.setItemInHand(InteractionHand.OFF_HAND, stack);
|
||||||
|
require(crossbow.getSupportedHeldProjectiles().test(stack), "held ammunition " + ammo);
|
||||||
|
require(
|
||||||
|
crossbow.getAllSupportedProjectiles().test(stack),
|
||||||
|
"inventory ammunition " + ammo);
|
||||||
|
require(
|
||||||
|
crossbow.use(level, player, InteractionHand.MAIN_HAND).consumesAction(),
|
||||||
|
"start loading " + ammo);
|
||||||
|
crossbow.onUseTick(
|
||||||
|
level, player, weapon, 72000 - CrossbowItem.getChargeDuration(weapon, player));
|
||||||
|
require(CrossbowItem.isCharged(weapon), "loaded " + ammo);
|
||||||
|
require(stack.getCount() == 1, "one ammo consumed " + ammo);
|
||||||
|
crossbow.performShooting(
|
||||||
|
level, player, InteractionHand.MAIN_HAND, weapon, 3.15f, 0, null);
|
||||||
|
require(!CrossbowItem.isCharged(weapon), "unloaded after shot " + ammo);
|
||||||
|
require(weapon.getDamageValue() == 1, "durability " + ammo);
|
||||||
|
player.stopUsingItem();
|
||||||
|
}
|
||||||
|
for (var ammo : List.of(Items.ARROW, Items.FIREWORK_ROCKET)) {
|
||||||
|
var weapon = new ItemStack(Items.CROSSBOW);
|
||||||
|
weapon.set(
|
||||||
|
DataComponents.CHARGED_PROJECTILES,
|
||||||
|
ChargedProjectiles.ofNonEmpty(List.of(new ItemStack(ammo))));
|
||||||
|
crossbow.performShooting(
|
||||||
|
level, player, InteractionHand.MAIN_HAND, weapon, 3.15f, 0, null);
|
||||||
|
}
|
||||||
|
require(
|
||||||
|
!level.getEntitiesOfClass(
|
||||||
|
AbstractArrow.class, new AABB(player.blockPosition()).inflate(8))
|
||||||
|
.isEmpty(),
|
||||||
|
"vanilla arrows remain arrows");
|
||||||
|
require(
|
||||||
|
!level.getEntitiesOfClass(
|
||||||
|
FireworkRocketEntity.class,
|
||||||
|
new AABB(player.blockPosition()).inflate(8))
|
||||||
|
.isEmpty(),
|
||||||
|
"vanilla fireworks remain fireworks");
|
||||||
|
var multi = new ItemStack(Items.CROSSBOW);
|
||||||
|
multi.enchant(
|
||||||
|
level.registryAccess()
|
||||||
|
.lookupOrThrow(net.minecraft.core.registries.Registries.ENCHANTMENT)
|
||||||
|
.getOrThrow(net.minecraft.world.item.enchantment.Enchantments.MULTISHOT),
|
||||||
|
1);
|
||||||
|
player.setItemInHand(InteractionHand.MAIN_HAND, multi);
|
||||||
|
player.setItemInHand(InteractionHand.OFF_HAND, new ItemStack(Items.SNOWBALL, 2));
|
||||||
|
crossbow.use(level, player, InteractionHand.MAIN_HAND);
|
||||||
|
crossbow.onUseTick(
|
||||||
|
level, player, multi, 72000 - CrossbowItem.getChargeDuration(multi, player));
|
||||||
|
require(
|
||||||
|
multi.get(DataComponents.CHARGED_PROJECTILES).itemCopies().size() == 3,
|
||||||
|
"multishot loads three snowballs");
|
||||||
|
require(player.getOffhandItem().getCount() == 1, "multishot consumes one ammo");
|
||||||
|
player.stopUsingItem();
|
||||||
|
player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.FIRE_CHARGE, 2));
|
||||||
|
Ammunition.fireCharge(
|
||||||
|
new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickItem(
|
||||||
|
player, InteractionHand.MAIN_HAND));
|
||||||
|
require(player.getMainHandItem().getCount() == 1, "right click fire charge consumes one");
|
||||||
|
Ammunition.fireCharge(
|
||||||
|
new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickItem(
|
||||||
|
player, InteractionHand.MAIN_HAND));
|
||||||
|
require(
|
||||||
|
player.getMainHandItem().getCount() == 1,
|
||||||
|
"fire charge cooldown prevents second shot");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finish(net.minecraft.server.MinecraftServer server, String text) throws Exception {
|
||||||
|
Files.writeString(Path.of("verification-result.txt"), text);
|
||||||
|
System.out.println(text);
|
||||||
|
done = true;
|
||||||
|
server.halt(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void require(boolean condition, String message) {
|
||||||
|
if (!condition) throw new AssertionError(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
+114
@@ -0,0 +1,114 @@
|
|||||||
|
package online.astradev.content.verification;
|
||||||
|
|
||||||
|
import static online.astradev.content.verification.TrackVerification.*;
|
||||||
|
import static online.astradev.content.verification.TrainVerification.*;
|
||||||
|
|
||||||
|
import net.minecraft.server.level.ServerLevel;
|
||||||
|
import net.minecraft.world.entity.player.Input;
|
||||||
|
import net.minecraft.world.entity.vehicle.minecart.Minecart;
|
||||||
|
import net.minecraft.world.level.block.Blocks;
|
||||||
|
import net.minecraft.world.level.block.RailBlock;
|
||||||
|
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||||
|
import net.minecraft.world.phys.Vec3;
|
||||||
|
import net.neoforged.neoforge.common.util.FakePlayerFactory;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
final class PlayerTrainVerification {
|
||||||
|
static void run(ServerLevel level) {
|
||||||
|
for (int side = 0; side < 4; side++) {
|
||||||
|
double ordinary = push(level, side, 1), train = push(level, side, 3);
|
||||||
|
require(Math.abs(ordinary) > .02, "ordinary cart reacts to player push");
|
||||||
|
require(
|
||||||
|
Math.abs(train - ordinary) < .005,
|
||||||
|
"same player push reaches whole train side="
|
||||||
|
+ side
|
||||||
|
+ ": "
|
||||||
|
+ train
|
||||||
|
+ " vs "
|
||||||
|
+ ordinary);
|
||||||
|
}
|
||||||
|
for (boolean reverse : new boolean[] {false, true}) {
|
||||||
|
double ordinary = ride(level, reverse, 1), train = ride(level, reverse, 3);
|
||||||
|
require(Math.abs(ordinary) > .1, "ordinary cart responds to seated input");
|
||||||
|
require(
|
||||||
|
Math.signum(train) == Math.signum(ordinary)
|
||||||
|
&& Math.abs(train) >= Math.abs(ordinary) * .8,
|
||||||
|
"seated player controls train reverse="
|
||||||
|
+ reverse
|
||||||
|
+ ": "
|
||||||
|
+ train
|
||||||
|
+ " vs "
|
||||||
|
+ ordinary);
|
||||||
|
}
|
||||||
|
System.out.println(
|
||||||
|
"PASS player controls: walking pushes from four sides and seated forward/backward"
|
||||||
|
+ " input compared with ordinary cart");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Minecart> setup(ServerLevel level, int count) {
|
||||||
|
var path = new ArrayList<Track>();
|
||||||
|
for (int x = 0; x <= 14; x++)
|
||||||
|
path.add(
|
||||||
|
new Track(
|
||||||
|
at(x, 0, 0, 0),
|
||||||
|
Blocks.RAIL
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(RailBlock.SHAPE, RailShape.EAST_WEST)));
|
||||||
|
build(level, path, -1);
|
||||||
|
var carts = new ArrayList<Minecart>();
|
||||||
|
for (int i = 0; i < count; i++) carts.add(cart(level, at(4 + i * 2, 0, 0, 0), Vec3.ZERO));
|
||||||
|
for (int i = 0; i < count - 1; i++) link(level, carts.get(i), carts.get(i + 1));
|
||||||
|
return carts;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double push(ServerLevel level, int side, int count) {
|
||||||
|
var carts = setup(level, count);
|
||||||
|
var target = carts.getFirst();
|
||||||
|
var player = FakePlayerFactory.getMinecraft(level);
|
||||||
|
player.stopRiding();
|
||||||
|
player.setLastClientInput(Input.EMPTY);
|
||||||
|
player.setShiftKeyDown(false);
|
||||||
|
player.setPos(target.position().add(direction(side, .6)));
|
||||||
|
player.setDeltaMovement(Vec3.ZERO);
|
||||||
|
target.push(player);
|
||||||
|
double before = target.getX();
|
||||||
|
tick(level, carts);
|
||||||
|
double result = target.getX() - before;
|
||||||
|
if (count > 1)
|
||||||
|
for (var c : carts)
|
||||||
|
require(
|
||||||
|
c.getDeltaMovement().horizontalDistance() > .01,
|
||||||
|
"every coupled cart receives walking push");
|
||||||
|
cleanup(carts);
|
||||||
|
player.setPos(40, 115, 35);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double ride(ServerLevel level, boolean reverse, int count) {
|
||||||
|
var carts = setup(level, count);
|
||||||
|
var target = carts.getFirst();
|
||||||
|
// NeoForge FakePlayer deliberately refuses all riding; use the real ServerPlayer
|
||||||
|
// implementation.
|
||||||
|
var player =
|
||||||
|
new net.minecraft.server.level.ServerPlayer(
|
||||||
|
level.getServer(),
|
||||||
|
level,
|
||||||
|
new com.mojang.authlib.GameProfile(UUID.randomUUID(), "TrainRider"),
|
||||||
|
net.minecraft.server.level.ClientInformation.createDefault());
|
||||||
|
player.connection = FakePlayerFactory.getMinecraft(level).connection;
|
||||||
|
player.setShiftKeyDown(false);
|
||||||
|
player.setPos(target.position());
|
||||||
|
require(player.startRiding(target), "player mounts minecart");
|
||||||
|
player.setYRot(-90);
|
||||||
|
player.setLastClientInput(new Input(!reverse, reverse, false, false, false, false, false));
|
||||||
|
double before = target.getX();
|
||||||
|
for (int i = 0; i < 100; i++) tick(level, carts);
|
||||||
|
double result = target.getX() - before;
|
||||||
|
player.setLastClientInput(Input.EMPTY);
|
||||||
|
player.stopRiding();
|
||||||
|
cleanup(carts);
|
||||||
|
player.setPos(40, 115, 35);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
package online.astradev.content.verification;
|
||||||
|
|
||||||
|
import net.minecraft.core.*;
|
||||||
|
import net.minecraft.server.level.ServerLevel;
|
||||||
|
import net.minecraft.world.entity.EntityTypes;
|
||||||
|
import net.minecraft.world.entity.vehicle.minecart.Minecart;
|
||||||
|
import net.minecraft.world.level.block.*;
|
||||||
|
import net.minecraft.world.level.block.state.BlockState;
|
||||||
|
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||||
|
import net.minecraft.world.phys.Vec3;
|
||||||
|
|
||||||
|
import online.astradev.content.rail.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Real native movement on mirrored/rotated tracks, never just a speed-formula test. */
|
||||||
|
final class TrackVerification {
|
||||||
|
record Track(BlockPos pos, BlockState state) {}
|
||||||
|
|
||||||
|
static void run(ServerLevel level) {
|
||||||
|
for (int turn = 0; turn < 4; turn++)
|
||||||
|
for (int mirror : new int[] {-1, 1}) corner(level, turn, mirror);
|
||||||
|
for (int turn = 0; turn < 4; turn++)
|
||||||
|
for (boolean uphill : new boolean[] {false, true}) slope(level, turn, uphill);
|
||||||
|
brakes(level);
|
||||||
|
detectors(level);
|
||||||
|
water(level);
|
||||||
|
cartTypes(level);
|
||||||
|
transitions(level);
|
||||||
|
System.out.println(
|
||||||
|
"PASS tracks: 8 corner routes, 8 slope routes, brakes, detector, activator, water,"
|
||||||
|
+ " 7 cart types, speed transitions");
|
||||||
|
}
|
||||||
|
|
||||||
|
static BlockPos at(int x, int y, int z, int turn) {
|
||||||
|
for (int i = 0; i < turn; i++) {
|
||||||
|
int old = x;
|
||||||
|
x = -z;
|
||||||
|
z = old;
|
||||||
|
}
|
||||||
|
return new BlockPos(60 + x, 100 + y, 64 + z);
|
||||||
|
}
|
||||||
|
|
||||||
|
static BlockState rotate(BlockState state, int turns) {
|
||||||
|
for (int i = 0; i < turns; i++) state = state.rotate(Rotation.CLOCKWISE_90);
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
static BlockState powered(RailShape shape) {
|
||||||
|
return Blocks.POWERED_RAIL
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(PoweredRailBlock.SHAPE, shape)
|
||||||
|
.setValue(PoweredRailBlock.POWERED, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void clear(ServerLevel level) {
|
||||||
|
for (int x = 43; x <= 77; x++)
|
||||||
|
for (int z = 47; z <= 81; z++)
|
||||||
|
for (int y = 98; y <= 105; y++)
|
||||||
|
level.setBlock(new BlockPos(x, y, z), Blocks.AIR.defaultBlockState(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void build(ServerLevel level, List<Track> path, int age) {
|
||||||
|
clear(level);
|
||||||
|
for (var p : path)
|
||||||
|
level.setBlock(p.pos.below(), Blocks.REDSTONE_BLOCK.defaultBlockState(), 2);
|
||||||
|
for (var p : path) level.setBlock(p.pos, p.state, 2);
|
||||||
|
// Placement recomputes neighbor shapes; now set the exact constructed route.
|
||||||
|
for (var p : path) {
|
||||||
|
level.setBlock(p.pos, p.state, 2);
|
||||||
|
if (p.state.is(Blocks.POWERED_RAIL) && age >= 0)
|
||||||
|
Rails.put(level, p.pos, new RailKind(age, true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static Minecart cart(ServerLevel level, BlockPos start, Vec3 velocity) {
|
||||||
|
var cart = new Minecart(EntityTypes.MINECART, level);
|
||||||
|
cart.setPos(start.getX() + .5, start.getY() + .0625, start.getZ() + .5);
|
||||||
|
cart.setDeltaMovement(velocity);
|
||||||
|
level.addFreshEntity(cart);
|
||||||
|
return cart;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Vec3 direction(int turns, double speed) {
|
||||||
|
return switch (turns) {
|
||||||
|
case 0 -> new Vec3(speed, 0, 0);
|
||||||
|
case 1 -> new Vec3(0, 0, speed);
|
||||||
|
case 2 -> new Vec3(-speed, 0, 0);
|
||||||
|
default -> new Vec3(0, 0, -speed);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void travel(ServerLevel level, List<Track> path, int turn, String label) {
|
||||||
|
var cart = cart(level, path.getFirst().pos, direction(turn, 1.5));
|
||||||
|
var end = Vec3.atCenterOf(path.getLast().pos);
|
||||||
|
boolean arrived = false;
|
||||||
|
for (int tick = 0; tick < 180; tick++) {
|
||||||
|
cart.tick();
|
||||||
|
double nearest =
|
||||||
|
path.stream()
|
||||||
|
.mapToDouble(
|
||||||
|
p ->
|
||||||
|
Math.hypot(
|
||||||
|
cart.getX() - p.pos.getX() - .5,
|
||||||
|
cart.getZ() - p.pos.getZ() - .5))
|
||||||
|
.min()
|
||||||
|
.orElseThrow();
|
||||||
|
require(nearest < 1.1, label + " derailed at " + cart.position());
|
||||||
|
if (cart.position().distanceTo(end) < 1.2) {
|
||||||
|
arrived = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cart.discard();
|
||||||
|
require(arrived, label + " never reached end");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void corner(ServerLevel level, int turn, int mirror) {
|
||||||
|
var path = new ArrayList<Track>();
|
||||||
|
for (int x = 0; x < 8; x++)
|
||||||
|
path.add(new Track(at(x, 0, 0, turn), rotate(powered(RailShape.EAST_WEST), turn)));
|
||||||
|
path.add(
|
||||||
|
new Track(
|
||||||
|
at(8, 0, 0, turn),
|
||||||
|
rotate(
|
||||||
|
Blocks.RAIL
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(
|
||||||
|
RailBlock.SHAPE,
|
||||||
|
mirror == 1
|
||||||
|
? RailShape.SOUTH_WEST
|
||||||
|
: RailShape.NORTH_WEST),
|
||||||
|
turn)));
|
||||||
|
for (int z = 1; z <= 8; z++)
|
||||||
|
path.add(
|
||||||
|
new Track(
|
||||||
|
at(8, 0, z * mirror, turn),
|
||||||
|
rotate(powered(RailShape.NORTH_SOUTH), turn)));
|
||||||
|
build(level, path, turn);
|
||||||
|
travel(level, path, turn, "corner " + turn + "/" + mirror);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void slope(ServerLevel level, int turn, boolean uphill) {
|
||||||
|
var path = new ArrayList<Track>();
|
||||||
|
for (int x = 0; x <= 14; x++) {
|
||||||
|
int height = x < 5 ? 0 : x < 8 ? x - 5 : 3;
|
||||||
|
if (!uphill) height = 3 - height;
|
||||||
|
if (!uphill && x >= 5 && x < 8) height--;
|
||||||
|
RailShape shape =
|
||||||
|
x >= 5 && x < 8
|
||||||
|
? (uphill ? RailShape.ASCENDING_EAST : RailShape.ASCENDING_WEST)
|
||||||
|
: RailShape.EAST_WEST;
|
||||||
|
path.add(new Track(at(x, height, 0, turn), rotate(powered(shape), turn)));
|
||||||
|
}
|
||||||
|
build(level, path, turn);
|
||||||
|
for (var p : path) level.setBlock(p.pos.below(), Blocks.STONE.defaultBlockState(), 2);
|
||||||
|
level.setBlock(path.getFirst().pos.below(), Blocks.REDSTONE_BLOCK.defaultBlockState(), 2);
|
||||||
|
for (int i = 0; i <= 8; i++)
|
||||||
|
require(
|
||||||
|
RailSpeed.signal(level, path.get(i).pos) == 15,
|
||||||
|
"signal over slope " + turn + "/" + uphill + " at " + i);
|
||||||
|
require(RailSpeed.signal(level, path.get(10).pos) == 0, "signal respects eight-rail reach");
|
||||||
|
for (var p : path)
|
||||||
|
level.setBlock(p.pos.below(), Blocks.REDSTONE_BLOCK.defaultBlockState(), 2);
|
||||||
|
travel(level, path, turn, "slope " + turn + "/" + uphill);
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<Track> straight() {
|
||||||
|
var path = new ArrayList<Track>();
|
||||||
|
for (int x = 0; x <= 14; x++)
|
||||||
|
path.add(new Track(at(x, 0, 0, 0), powered(RailShape.EAST_WEST)));
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void brakes(ServerLevel level) {
|
||||||
|
var path = straight();
|
||||||
|
build(level, path, -1);
|
||||||
|
for (int x = 5; x <= 14; x++) {
|
||||||
|
level.setBlock(at(x, -1, 0, 0), Blocks.STONE.defaultBlockState(), 2);
|
||||||
|
level.setBlock(
|
||||||
|
at(x, 0, 0, 0),
|
||||||
|
powered(RailShape.EAST_WEST).setValue(PoweredRailBlock.POWERED, false),
|
||||||
|
2);
|
||||||
|
}
|
||||||
|
// Remove propagated power in this controlled fixture.
|
||||||
|
for (int x = 5; x <= 14; x++)
|
||||||
|
level.setBlock(
|
||||||
|
at(x, 0, 0, 0),
|
||||||
|
powered(RailShape.EAST_WEST).setValue(PoweredRailBlock.POWERED, false),
|
||||||
|
2);
|
||||||
|
var cart = cart(level, at(0, 0, 0, 0), new Vec3(1.5, 0, 0));
|
||||||
|
for (int t = 0; t < 70; t++) cart.tick();
|
||||||
|
require(cart.getDeltaMovement().horizontalDistance() < .01, "unpowered braking");
|
||||||
|
require(cart.getX() < 70, "brakes stop cart before track end");
|
||||||
|
cart.discard();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void detectors(ServerLevel level) {
|
||||||
|
var path = straight();
|
||||||
|
build(level, path, -1);
|
||||||
|
var detector = at(5, 0, 0, 0);
|
||||||
|
var activator = at(9, 0, 0, 0);
|
||||||
|
level.setBlock(
|
||||||
|
detector,
|
||||||
|
Blocks.DETECTOR_RAIL
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(DetectorRailBlock.SHAPE, RailShape.EAST_WEST),
|
||||||
|
2);
|
||||||
|
level.setBlock(
|
||||||
|
activator,
|
||||||
|
Blocks.ACTIVATOR_RAIL
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(PoweredRailBlock.SHAPE, RailShape.EAST_WEST)
|
||||||
|
.setValue(PoweredRailBlock.POWERED, true),
|
||||||
|
2);
|
||||||
|
var cart = cart(level, at(0, 0, 0, 0), new Vec3(1.5, 0, 0));
|
||||||
|
boolean detected = false, activated = false;
|
||||||
|
for (int t = 0; t < 65; t++) {
|
||||||
|
cart.tick();
|
||||||
|
detected |= level.getBlockState(detector).getValue(DetectorRailBlock.POWERED);
|
||||||
|
activated |= cart.getHurtTime() > 0;
|
||||||
|
if (cart.getX() > 73) break;
|
||||||
|
}
|
||||||
|
require(detected, "detector rail registers high speed cart");
|
||||||
|
require(activated, "activator rail activates cart");
|
||||||
|
cart.discard();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void water(ServerLevel level) {
|
||||||
|
var path = straight();
|
||||||
|
build(level, path, 0);
|
||||||
|
for (var rail : path)
|
||||||
|
level.setBlock(rail.pos, rail.state.setValue(BaseRailBlock.WATERLOGGED, true), 2);
|
||||||
|
var cart = cart(level, at(3, 0, 0, 0), new Vec3(1.5, 0, 0));
|
||||||
|
double previousX = cart.getX();
|
||||||
|
for (int t = 0; t < 5; t++) {
|
||||||
|
previousX = cart.getX();
|
||||||
|
cart.tick();
|
||||||
|
}
|
||||||
|
require(cart.isInWater(), "waterlogged track is native water");
|
||||||
|
require(
|
||||||
|
cart.getX() - previousX <= .501,
|
||||||
|
"water speed reduction: " + (cart.getX() - previousX));
|
||||||
|
cart.discard();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void cartTypes(ServerLevel level) {
|
||||||
|
build(level, straight(), 0);
|
||||||
|
List<
|
||||||
|
net.minecraft.world.entity.EntityType<
|
||||||
|
? extends
|
||||||
|
net.minecraft.world.entity.vehicle.minecart
|
||||||
|
.AbstractMinecart>>
|
||||||
|
types =
|
||||||
|
List.of(
|
||||||
|
EntityTypes.MINECART,
|
||||||
|
EntityTypes.CHEST_MINECART,
|
||||||
|
EntityTypes.HOPPER_MINECART,
|
||||||
|
EntityTypes.FURNACE_MINECART,
|
||||||
|
EntityTypes.TNT_MINECART,
|
||||||
|
EntityTypes.COMMAND_BLOCK_MINECART,
|
||||||
|
EntityTypes.SPAWNER_MINECART);
|
||||||
|
for (var type : types) {
|
||||||
|
var cart = type.create(level, net.minecraft.world.entity.EntitySpawnReason.COMMAND);
|
||||||
|
require(cart != null, "create " + type);
|
||||||
|
cart.setPos(63.5, 100.0625, 64.5);
|
||||||
|
cart.setDeltaMovement(2, 0, 0);
|
||||||
|
level.addFreshEntity(cart);
|
||||||
|
cart.tick();
|
||||||
|
double before = cart.getX();
|
||||||
|
cart.tick();
|
||||||
|
double distance = cart.getX() - before;
|
||||||
|
require(Math.abs(distance - 1) < .015, "20 m/s for " + type + ": " + distance);
|
||||||
|
cart.discard();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void transitions(ServerLevel level) {
|
||||||
|
build(level, straight(), 0);
|
||||||
|
for (int x = 6; x <= 14; x++) Rails.put(level, at(x, 0, 0, 0), new RailKind(3, true));
|
||||||
|
var cart = cart(level, at(2, 0, 0, 0), new Vec3(1.5, 0, 0));
|
||||||
|
boolean crossed = false;
|
||||||
|
for (int t = 0; t < 35; t++) {
|
||||||
|
double before = cart.getX();
|
||||||
|
cart.tick();
|
||||||
|
if (before >= 66.1) {
|
||||||
|
crossed = true;
|
||||||
|
require(cart.getX() - before <= .415, "20 to 8 transition obeys slower rail");
|
||||||
|
}
|
||||||
|
if (cart.getX() > 72) break;
|
||||||
|
}
|
||||||
|
require(crossed, "crossed oxidation boundary");
|
||||||
|
cart.discard();
|
||||||
|
build(level, straight(), -1);
|
||||||
|
// Native rail at the end: approach is limited before the cart leaves the track.
|
||||||
|
cart = cart(level, at(13, 0, 0, 0), new Vec3(1.5, 0, 0));
|
||||||
|
double before = cart.getX();
|
||||||
|
cart.tick();
|
||||||
|
if (!net.minecraft.world.entity.vehicle.minecart.AbstractMinecart.useExperimentalMovement(
|
||||||
|
level)) require(cart.getX() - before <= .415, "end of track safe approach");
|
||||||
|
cart.discard();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void require(boolean condition, String message) {
|
||||||
|
if (!condition) throw new AssertionError(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,396 @@
|
|||||||
|
package online.astradev.content.verification;
|
||||||
|
|
||||||
|
import static online.astradev.content.verification.TrackVerification.*;
|
||||||
|
|
||||||
|
import net.minecraft.core.BlockPos;
|
||||||
|
import net.minecraft.server.level.ServerLevel;
|
||||||
|
import net.minecraft.world.InteractionHand;
|
||||||
|
import net.minecraft.world.entity.*;
|
||||||
|
import net.minecraft.world.entity.item.ItemEntity;
|
||||||
|
import net.minecraft.world.entity.vehicle.minecart.*;
|
||||||
|
import net.minecraft.world.item.*;
|
||||||
|
import net.minecraft.world.level.block.*;
|
||||||
|
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||||
|
import net.minecraft.world.phys.*;
|
||||||
|
import net.neoforged.neoforge.common.util.FakePlayerFactory;
|
||||||
|
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||||
|
|
||||||
|
import online.astradev.content.train.*;
|
||||||
|
import online.astradev.content.transport.SlimeBounce;
|
||||||
|
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
final class TrainVerification {
|
||||||
|
static void run(ServerLevel level) throws Exception {
|
||||||
|
interaction(level);
|
||||||
|
PlayerTrainVerification.run(level);
|
||||||
|
unloaded(level);
|
||||||
|
for (int turn = 0; turn < 4; turn++)
|
||||||
|
for (int mirror : new int[] {-1, 1}) route(level, turn, mirror, false);
|
||||||
|
for (int turn = 0; turn < 4; turn++)
|
||||||
|
for (int slope : new int[] {-1, 1}) route(level, turn, slope, true);
|
||||||
|
ring(level);
|
||||||
|
for (int turn = 0; turn < 4; turn++) {
|
||||||
|
buffer(level, turn, true);
|
||||||
|
buffer(level, turn, false);
|
||||||
|
trainBuffer(level, turn);
|
||||||
|
boat(level, turn);
|
||||||
|
}
|
||||||
|
offRailBounce(level);
|
||||||
|
persistence(level);
|
||||||
|
System.out.println(
|
||||||
|
"PASS trains: endpoint interactions, refunds, 8 turns, 8 slopes, closed moving"
|
||||||
|
+ " ring, four-direction slime/stone and boat collisions");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void click(ServerLevel level, AbstractMinecart cart, Item item, Vec3 hit) {
|
||||||
|
var player = FakePlayerFactory.getMinecraft(level);
|
||||||
|
player.setShiftKeyDown(true);
|
||||||
|
player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(item, 8));
|
||||||
|
Trains.interact(
|
||||||
|
new PlayerInteractEvent.EntityInteract(
|
||||||
|
player, InteractionHand.MAIN_HAND, cart, hit));
|
||||||
|
}
|
||||||
|
|
||||||
|
static TrainData.Link link(ServerLevel level, AbstractMinecart a, AbstractMinecart b) {
|
||||||
|
var link =
|
||||||
|
new TrainData.Link(
|
||||||
|
a.getUUID(),
|
||||||
|
0,
|
||||||
|
b.getUUID(),
|
||||||
|
1,
|
||||||
|
"minecraft:iron_chain",
|
||||||
|
true,
|
||||||
|
a.position().distanceTo(b.position()));
|
||||||
|
TrainData.get(level).add(link);
|
||||||
|
return link;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void tick(ServerLevel level, List<? extends AbstractMinecart> carts) {
|
||||||
|
Trains.step(level);
|
||||||
|
for (var cart : carts) {
|
||||||
|
cart.setOldPosAndRot();
|
||||||
|
cart.tick();
|
||||||
|
SlimeBounce.flush(cart);
|
||||||
|
}
|
||||||
|
Trains.show(level);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void cleanup(List<? extends Entity> carts) {
|
||||||
|
for (var cart : carts) cart.discard();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void unloaded(ServerLevel level) {
|
||||||
|
build(level, straight(), 0);
|
||||||
|
var a = cart(level, at(2, 0, 0, 0), new Vec3(1, 0, 0));
|
||||||
|
var b = cart(level, at(4, 0, 0, 0), Vec3.ZERO);
|
||||||
|
var saved = link(level, a, b);
|
||||||
|
b.remove(Entity.RemovalReason.UNLOADED_TO_CHUNK);
|
||||||
|
var position = a.position();
|
||||||
|
for (int i = 0; i < 10; i++) tick(level, List.of(a));
|
||||||
|
require(
|
||||||
|
a.position().horizontal().distanceTo(position.horizontal()) < .01,
|
||||||
|
"loaded half of train pauses");
|
||||||
|
require(TrainData.get(level).links().contains(saved), "unloading keeps saved chain");
|
||||||
|
TrainData.get(level).remove(saved);
|
||||||
|
a.discard();
|
||||||
|
Trains.step(level);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void interaction(ServerLevel level) {
|
||||||
|
build(level, straight(), 0);
|
||||||
|
var a = cart(level, at(2, 0, 0, 0), Vec3.ZERO);
|
||||||
|
var b = cart(level, at(4, 0, 0, 0), Vec3.ZERO);
|
||||||
|
var data = TrainData.get(level);
|
||||||
|
var player = FakePlayerFactory.getMinecraft(level);
|
||||||
|
click(level, a, Items.IRON_CHAIN, new Vec3(0, .2, .49));
|
||||||
|
require(data.links().isEmpty(), "side cannot attach");
|
||||||
|
click(level, a, Items.IRON_CHAIN, new Vec3(.49, .2, 0));
|
||||||
|
require(data.links().size() == 1, "front auto couples");
|
||||||
|
require(player.getMainHandItem().getCount() == 7, "one chain consumed");
|
||||||
|
click(level, a, Items.IRON_CHAIN, new Vec3(.49, .2, 0));
|
||||||
|
require(
|
||||||
|
data.links().size() == 1 && player.getMainHandItem().getCount() == 8,
|
||||||
|
"occupied end rejects");
|
||||||
|
Trains.show(level);
|
||||||
|
Trains.show(level);
|
||||||
|
require(
|
||||||
|
level.getEntitiesOfClass(ChainDisplay.class, a.getBoundingBox().inflate(5)).size()
|
||||||
|
== 1,
|
||||||
|
"one visible vanilla chain");
|
||||||
|
int drops =
|
||||||
|
level.getEntitiesOfClass(ItemEntity.class, a.getBoundingBox().inflate(5)).size();
|
||||||
|
click(level, b, Items.IRON_PICKAXE, new Vec3(-.49, .2, 0));
|
||||||
|
require(data.links().isEmpty(), "detach from opposite end");
|
||||||
|
require(
|
||||||
|
level.getEntitiesOfClass(ItemEntity.class, a.getBoundingBox().inflate(5)).size()
|
||||||
|
== drops + 1,
|
||||||
|
"exactly one refund");
|
||||||
|
click(level, b, Items.IRON_PICKAXE, new Vec3(-.49, .2, 0));
|
||||||
|
require(
|
||||||
|
level.getEntitiesOfClass(ItemEntity.class, a.getBoundingBox().inflate(5)).size()
|
||||||
|
== drops + 1,
|
||||||
|
"no duplicate refund");
|
||||||
|
link(level, a, b);
|
||||||
|
b.discard();
|
||||||
|
require(data.links().isEmpty(), "destroy removes saved link");
|
||||||
|
a.discard();
|
||||||
|
player.setShiftKeyDown(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void route(ServerLevel level, int turn, int side, boolean slope) {
|
||||||
|
var path = new ArrayList<Track>();
|
||||||
|
if (slope) {
|
||||||
|
for (int x = 0; x <= 20; x++) {
|
||||||
|
int y = x < 8 ? 0 : x < 11 ? x - 8 : 3;
|
||||||
|
if (side < 0) y = 3 - y - (x >= 8 && x < 11 ? 1 : 0);
|
||||||
|
var shape =
|
||||||
|
x >= 8 && x < 11
|
||||||
|
? (side > 0 ? RailShape.ASCENDING_EAST : RailShape.ASCENDING_WEST)
|
||||||
|
: RailShape.EAST_WEST;
|
||||||
|
path.add(new Track(at(x, y, 0, turn), rotate(powered(shape), turn)));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (int x = 0; x < 9; x++)
|
||||||
|
path.add(new Track(at(x, 0, 0, turn), rotate(powered(RailShape.EAST_WEST), turn)));
|
||||||
|
path.add(
|
||||||
|
new Track(
|
||||||
|
at(9, 0, 0, turn),
|
||||||
|
rotate(
|
||||||
|
Blocks.RAIL
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(
|
||||||
|
RailBlock.SHAPE,
|
||||||
|
side > 0
|
||||||
|
? RailShape.SOUTH_WEST
|
||||||
|
: RailShape.NORTH_WEST),
|
||||||
|
turn)));
|
||||||
|
for (int z = 1; z <= 12; z++)
|
||||||
|
path.add(
|
||||||
|
new Track(
|
||||||
|
at(9, 0, z * side, turn),
|
||||||
|
rotate(powered(RailShape.NORTH_SOUTH), turn)));
|
||||||
|
}
|
||||||
|
build(level, path, 0);
|
||||||
|
var carts = new ArrayList<Minecart>();
|
||||||
|
for (int i = 0; i < 3; i++) {
|
||||||
|
var c = cart(level, path.get(1 + i * 2).pos(), direction(turn, .5));
|
||||||
|
((CartFrame) c).astracontent$front(direction(turn, 1));
|
||||||
|
carts.add(c);
|
||||||
|
}
|
||||||
|
link(level, carts.get(0), carts.get(1));
|
||||||
|
link(level, carts.get(1), carts.get(2));
|
||||||
|
boolean reached = false;
|
||||||
|
for (int t = 0; t < 200; t++) {
|
||||||
|
tick(level, carts);
|
||||||
|
for (var c : carts) {
|
||||||
|
double nearest =
|
||||||
|
path.stream()
|
||||||
|
.mapToDouble(
|
||||||
|
p ->
|
||||||
|
c.position()
|
||||||
|
.distanceTo(
|
||||||
|
Vec3.atBottomCenterOf(p.pos())
|
||||||
|
.add(0, .1, 0)))
|
||||||
|
.min()
|
||||||
|
.orElseThrow();
|
||||||
|
require(
|
||||||
|
nearest < 1.3,
|
||||||
|
"train derailed "
|
||||||
|
+ turn
|
||||||
|
+ "/"
|
||||||
|
+ side
|
||||||
|
+ " slope="
|
||||||
|
+ slope
|
||||||
|
+ " "
|
||||||
|
+ c.position());
|
||||||
|
}
|
||||||
|
require(TrainData.get(level).links().size() == 2, "train stays coupled on route");
|
||||||
|
if (carts.get(0).position().distanceTo(Vec3.atCenterOf(path.get(path.size() - 6).pos()))
|
||||||
|
< 1.2) {
|
||||||
|
reached = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require(reached, "whole train traverses " + turn + "/" + side + " slope=" + slope);
|
||||||
|
cleanup(carts);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ring(ServerLevel level) {
|
||||||
|
var path = new ArrayList<Track>();
|
||||||
|
var positions = new ArrayList<BlockPos>();
|
||||||
|
for (int x = 0; x <= 8; x++)
|
||||||
|
for (int z = 0; z <= 8; z++)
|
||||||
|
if (x == 0 || x == 8 || z == 0 || z == 8) {
|
||||||
|
RailShape shape =
|
||||||
|
z == 0 || z == 8 ? RailShape.EAST_WEST : RailShape.NORTH_SOUTH;
|
||||||
|
if (x == 0 && z == 0) shape = RailShape.SOUTH_EAST;
|
||||||
|
if (x == 8 && z == 0) shape = RailShape.SOUTH_WEST;
|
||||||
|
if (x == 8 && z == 8) shape = RailShape.NORTH_WEST;
|
||||||
|
if (x == 0 && z == 8) shape = RailShape.NORTH_EAST;
|
||||||
|
path.add(
|
||||||
|
new Track(
|
||||||
|
at(x, 0, z, 0),
|
||||||
|
shape.isSlope()
|
||||||
|
|| shape == RailShape.EAST_WEST
|
||||||
|
|| shape == RailShape.NORTH_SOUTH
|
||||||
|
? powered(shape)
|
||||||
|
: Blocks.RAIL
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(RailBlock.SHAPE, shape)));
|
||||||
|
}
|
||||||
|
for (int x = 4; x <= 8; x += 2) positions.add(at(x, 0, 0, 0));
|
||||||
|
for (int z = 2; z <= 8; z += 2) positions.add(at(8, 0, z, 0));
|
||||||
|
for (int x = 6; x >= 0; x -= 2) positions.add(at(x, 0, 8, 0));
|
||||||
|
for (int z = 6; z >= 0; z -= 2) positions.add(at(0, 0, z, 0));
|
||||||
|
positions.add(at(2, 0, 0, 0));
|
||||||
|
build(level, path, 3);
|
||||||
|
var carts = new ArrayList<Minecart>();
|
||||||
|
for (int i = 0; i < positions.size(); i++) {
|
||||||
|
var dir =
|
||||||
|
Vec3.atCenterOf(positions.get((i + 1) % positions.size()))
|
||||||
|
.subtract(Vec3.atCenterOf(positions.get(i)))
|
||||||
|
.normalize();
|
||||||
|
var c = cart(level, positions.get(i), dir.scale(.3));
|
||||||
|
((CartFrame) c).astracontent$front(dir);
|
||||||
|
carts.add(c);
|
||||||
|
}
|
||||||
|
for (int i = 0; i < carts.size() - 1; i++) link(level, carts.get(i), carts.get(i + 1));
|
||||||
|
click(level, carts.getLast(), Items.IRON_CHAIN, new Vec3(.49, .2, 0));
|
||||||
|
require(
|
||||||
|
TrainData.get(level).links().size() == carts.size(),
|
||||||
|
"player closes same train into ring");
|
||||||
|
double traveled = 0;
|
||||||
|
for (int t = 0; t < 100; t++) {
|
||||||
|
var before = carts.getFirst().position();
|
||||||
|
tick(level, carts);
|
||||||
|
traveled += before.distanceTo(carts.getFirst().position());
|
||||||
|
require(
|
||||||
|
TrainData.get(level).links().size() == carts.size(),
|
||||||
|
"closed ring remains intact");
|
||||||
|
for (var c : carts)
|
||||||
|
require(
|
||||||
|
level.getBlockState(c.getCurrentBlockPosOrRailBelow()).getBlock()
|
||||||
|
instanceof BaseRailBlock,
|
||||||
|
"ring cart remains on rail " + c.position());
|
||||||
|
}
|
||||||
|
require(traveled > 15, "closed ring actually moves: " + traveled);
|
||||||
|
cleanup(carts);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void buffer(ServerLevel level, int turn, boolean slime) {
|
||||||
|
var path = new ArrayList<Track>();
|
||||||
|
for (int x = 0; x <= 10; x++)
|
||||||
|
path.add(new Track(at(x, 0, 0, turn), rotate(powered(RailShape.EAST_WEST), turn)));
|
||||||
|
build(level, path, 0);
|
||||||
|
level.setBlock(
|
||||||
|
at(11, 0, 0, turn),
|
||||||
|
(slime ? Blocks.SLIME_BLOCK : Blocks.STONE).defaultBlockState(),
|
||||||
|
2);
|
||||||
|
var cart = cart(level, at(8, 0, 0, turn), direction(turn, 1));
|
||||||
|
boolean reflected = false;
|
||||||
|
double speed = 0;
|
||||||
|
for (int t = 0; t < 15; t++) {
|
||||||
|
cart.setOldPosAndRot();
|
||||||
|
cart.tick();
|
||||||
|
SlimeBounce.flush(cart);
|
||||||
|
double v = cart.getDeltaMovement().dot(direction(turn, 1));
|
||||||
|
if (v < -.1) {
|
||||||
|
reflected = true;
|
||||||
|
speed = -v;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (slime) require(reflected, "slime reflects direction " + turn);
|
||||||
|
else require(speed < .4, "stone retains native slow powered-rail restart: " + speed);
|
||||||
|
if (slime) require(speed > .9, "full impact speed preserved " + turn + ": " + speed);
|
||||||
|
cart.discard();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void boat(ServerLevel level, int turn) {
|
||||||
|
clear(level);
|
||||||
|
var wall = at(4, 0, 0, turn);
|
||||||
|
level.setBlock(wall, Blocks.SLIME_BLOCK.defaultBlockState(), 2);
|
||||||
|
var boat = EntityTypes.OAK_BOAT.create(level, EntitySpawnReason.COMMAND);
|
||||||
|
var dir = direction(turn, 1);
|
||||||
|
boat.setPos(Vec3.atBottomCenterOf(wall).subtract(dir.scale(1.5)));
|
||||||
|
level.addFreshEntity(boat);
|
||||||
|
boat.setDeltaMovement(dir);
|
||||||
|
boat.move(MoverType.SELF, dir);
|
||||||
|
SlimeBounce.flush(boat);
|
||||||
|
require(boat.getDeltaMovement().dot(dir) < -.99, "boat full speed bounce " + turn);
|
||||||
|
boat.discard();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void trainBuffer(ServerLevel level, int turn) {
|
||||||
|
var path = new ArrayList<Track>();
|
||||||
|
for (int x = 0; x <= 10; x++)
|
||||||
|
path.add(new Track(at(x, 0, 0, turn), rotate(powered(RailShape.EAST_WEST), turn)));
|
||||||
|
build(level, path, 0);
|
||||||
|
level.setBlock(at(11, 0, 0, turn), Blocks.SLIME_BLOCK.defaultBlockState(), 2);
|
||||||
|
var carts = new ArrayList<Minecart>();
|
||||||
|
var direction = direction(turn, 1);
|
||||||
|
for (int x = 4; x <= 8; x += 2) {
|
||||||
|
var c = cart(level, at(x, 0, 0, turn), direction);
|
||||||
|
((CartFrame) c).astracontent$front(direction);
|
||||||
|
carts.add(c);
|
||||||
|
}
|
||||||
|
link(level, carts.get(0), carts.get(1));
|
||||||
|
link(level, carts.get(1), carts.get(2));
|
||||||
|
boolean bounced = false;
|
||||||
|
for (int i = 0; i < 15; i++) {
|
||||||
|
tick(level, carts);
|
||||||
|
if (carts.getLast().getDeltaMovement().dot(direction) < -.1) {
|
||||||
|
bounced = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require(bounced, "whole train hits buffer " + turn);
|
||||||
|
for (var c : carts)
|
||||||
|
require(
|
||||||
|
c.getDeltaMovement().dot(direction) < -.85,
|
||||||
|
"whole train reverses at impact speed " + turn);
|
||||||
|
cleanup(carts);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void offRailBounce(ServerLevel level) {
|
||||||
|
clear(level);
|
||||||
|
level.setBlock(at(4, 0, 0, 0), Blocks.SLIME_BLOCK.defaultBlockState(), 2);
|
||||||
|
var cart = cart(level, at(3, 0, 0, 0), new Vec3(1, 0, .2));
|
||||||
|
cart.move(MoverType.SELF, cart.getDeltaMovement());
|
||||||
|
SlimeBounce.flush(cart);
|
||||||
|
require(
|
||||||
|
Math.abs(cart.getDeltaMovement().x + 1) < .001
|
||||||
|
&& Math.abs(cart.getDeltaMovement().z - .2) < .001,
|
||||||
|
"off-rail bounce preserves tangential speed");
|
||||||
|
cart.discard();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void persistence(ServerLevel level) throws Exception {
|
||||||
|
build(level, straight(), 0);
|
||||||
|
var a = cart(level, at(3, 0, 0, 0), Vec3.ZERO);
|
||||||
|
var b = cart(level, at(5, 0, 0, 0), Vec3.ZERO);
|
||||||
|
link(level, a, b);
|
||||||
|
Trains.show(level);
|
||||||
|
Files.writeString(Path.of("saved-train.txt"), a.getUUID() + "\n" + b.getUUID());
|
||||||
|
}
|
||||||
|
|
||||||
|
static void restart(ServerLevel level) throws Exception {
|
||||||
|
var ids = Files.readAllLines(Path.of("saved-train.txt"));
|
||||||
|
var data = TrainData.get(level);
|
||||||
|
require(data.links().size() == 1, "one saved link after restart");
|
||||||
|
var a = (AbstractMinecart) level.getEntity(UUID.fromString(ids.get(0)));
|
||||||
|
var b = (AbstractMinecart) level.getEntity(UUID.fromString(ids.get(1)));
|
||||||
|
require(a != null && b != null && Trains.connected(a, b), "saved train restored");
|
||||||
|
Trains.show(level);
|
||||||
|
require(
|
||||||
|
level.getEntitiesOfClass(ChainDisplay.class, a.getBoundingBox().inflate(5)).size()
|
||||||
|
== 1,
|
||||||
|
"one chain recreated after restart");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void require(boolean value, String message) {
|
||||||
|
if (!value) throw new AssertionError(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
param([string]$ServerRoot='C:\Users\ScarPC\Documents\NeoForge Server 26.2',[switch]$Experimental)
|
param([string]$ServerRoot='C:\Users\ScarPC\Documents\NeoForge Server 26.2',[switch]$Experimental)
|
||||||
$ErrorActionPreference='Stop'
|
$ErrorActionPreference='Stop'
|
||||||
$project=(Resolve-Path "$PSScriptRoot/..").Path
|
$project=(Resolve-Path "$PSScriptRoot/../..").Path
|
||||||
|
$java = 'java'
|
||||||
|
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'))
|
||||||
New-Item -ItemType Directory -Path "$output/mods","$output/config" | Out-Null
|
New-Item -ItemType Directory -Path "$output/mods","$output/config" | Out-Null
|
||||||
$runtime=(Resolve-Path -LiteralPath $ServerRoot).Path.Replace('\','/')
|
$runtime=(Resolve-Path -LiteralPath $ServerRoot).Path.Replace('\','/')
|
||||||
@@ -24,13 +26,19 @@ 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":false},"astraPacks":{"enabled":false},"editor":{"enabled":false}}' | Set-Content "$output/config/astraplus.json"
|
'{"build":{"onStartup":false},"astraPacks":{"enabled":false},"editor":{"enabled":false}}' | Set-Content "$output/config/astraplus.json"
|
||||||
$plus=Get-ChildItem -LiteralPath "$ServerRoot/mods" -Filter 'AstraPlus-*.jar' | Where-Object Name -NotMatch 'sources|api|verification'
|
$plusRoot=Join-Path (Split-Path $project -Parent) 'AstraPlus'
|
||||||
if(@($plus).Count -ne 1){throw 'Expected exactly one installed AstraPlus JAR'}
|
$plusVersion=[regex]::Match((Get-Content "$plusRoot/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value
|
||||||
Copy-Item -LiteralPath $plus.FullName,"$project/build/libs/AstraContent-0.2.1.jar","$project/build/libs/AstraContent-0.2.1-verification.jar" -Destination "$output/mods"
|
$plus=Get-Item -LiteralPath "$plusRoot/build/libs/AstraPlus-$plusVersion.jar"
|
||||||
|
$packsRoot=Join-Path (Split-Path $project -Parent) 'AstraPacks'
|
||||||
|
$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"
|
||||||
|
'{"enabled":false}' | Set-Content "$output/config/astrapacks.json"
|
||||||
|
$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"
|
||||||
Push-Location $output
|
Push-Location $output
|
||||||
try {
|
try {
|
||||||
foreach($pass in @('gameplay','restart')) {
|
foreach($pass in @('gameplay','restart')) {
|
||||||
& 'C:/Users/ScarPC/.gradle/jdks/eclipse_adoptium-25-amd64-windows.2/bin/java.exe' '-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"}
|
||||||
$result=Get-Content -Raw verification-result.txt
|
$result=Get-Content -Raw verification-result.txt
|
||||||
@@ -5,6 +5,7 @@ import net.neoforged.bus.api.IEventBus;
|
|||||||
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 online.astradev.content.rail.Rails;
|
import online.astradev.content.rail.Rails;
|
||||||
import online.astradev.content.weapon.Ammunition;
|
import online.astradev.content.weapon.Ammunition;
|
||||||
|
|
||||||
|
|||||||
@@ -1,20 +1,31 @@
|
|||||||
package online.astradev.content;
|
package online.astradev.content;
|
||||||
|
|
||||||
import java.nio.file.*;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.*;
|
||||||
|
|
||||||
/** Install absent defaults before AstraPlus loads its catalog. Never overwrite administrator edits. */
|
/**
|
||||||
|
* Install absent defaults before AstraPlus loads its catalog. Never overwrite administrator edits.
|
||||||
|
*/
|
||||||
public final class Defaults {
|
public final class Defaults {
|
||||||
private Defaults() {}
|
private Defaults() {}
|
||||||
|
|
||||||
public static void install(Path root) {
|
public static void install(Path root) {
|
||||||
try (var index = Defaults.class.getResourceAsStream("/defaults/index.txt")) {
|
try (var index = Defaults.class.getResourceAsStream("/defaults/index.txt")) {
|
||||||
if (index == null) throw new IllegalStateException("Missing content index");
|
if (index == null) throw new IllegalStateException("Missing content index");
|
||||||
for (String name : new String(index.readAllBytes(), StandardCharsets.UTF_8).lines().toList()) {
|
for (String name :
|
||||||
|
new String(index.readAllBytes(), StandardCharsets.UTF_8).lines().toList()) {
|
||||||
if (name.isBlank()) continue;
|
if (name.isBlank()) continue;
|
||||||
Path target = root.toAbsolutePath().normalize().resolve("astraplus").resolve(name).normalize();
|
Path target =
|
||||||
if (!target.startsWith(root.toAbsolutePath().normalize().resolve("astraplus"))) throw new IllegalArgumentException(name);
|
root.toAbsolutePath()
|
||||||
|
.normalize()
|
||||||
|
.resolve("astraplus")
|
||||||
|
.resolve(name)
|
||||||
|
.normalize();
|
||||||
|
if (!target.startsWith(root.toAbsolutePath().normalize().resolve("astraplus")))
|
||||||
|
throw new IllegalArgumentException(name);
|
||||||
for (Path part = target; part != null; part = part.getParent())
|
for (Path part = target; part != null; part = part.getParent())
|
||||||
if (Files.isSymbolicLink(part)) throw new IllegalStateException("Symbolic link: " + part);
|
if (Files.isSymbolicLink(part))
|
||||||
|
throw new IllegalStateException("Symbolic link: " + part);
|
||||||
if (Files.exists(target)) continue;
|
if (Files.exists(target)) continue;
|
||||||
Files.createDirectories(target.getParent());
|
Files.createDirectories(target.getParent());
|
||||||
try (var stream = Defaults.class.getResourceAsStream("/defaults/" + name)) {
|
try (var stream = Defaults.class.getResourceAsStream("/defaults/" + name)) {
|
||||||
@@ -22,6 +33,8 @@ public final class Defaults {
|
|||||||
Files.copy(stream, target);
|
Files.copy(stream, target);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (java.io.IOException e) { throw new IllegalStateException("Cannot install AstraContent defaults", e); }
|
} catch (java.io.IOException e) {
|
||||||
|
throw new IllegalStateException("Cannot install AstraContent defaults", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,43 @@
|
|||||||
package online.astradev.content.mixin;
|
package online.astradev.content.mixin;
|
||||||
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
|
||||||
import net.minecraft.server.level.ServerPlayer;
|
|
||||||
import net.minecraft.network.protocol.game.ServerboundMoveVehiclePacket;
|
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.entity.Entity;
|
||||||
import net.minecraft.world.phys.Vec3;
|
import net.minecraft.world.phys.Vec3;
|
||||||
|
|
||||||
import online.astradev.content.transport.SlimeBounce;
|
import online.astradev.content.transport.SlimeBounce;
|
||||||
|
|
||||||
import org.spongepowered.asm.mixin.*;
|
import org.spongepowered.asm.mixin.*;
|
||||||
import org.spongepowered.asm.mixin.injection.*;
|
import org.spongepowered.asm.mixin.injection.*;
|
||||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||||
|
|
||||||
@Mixin(ServerGamePacketListenerImpl.class)
|
@Mixin(ServerGamePacketListenerImpl.class)
|
||||||
public abstract class BoatPacketMixin {
|
public abstract class BoatPacketMixin {
|
||||||
@Shadow public ServerPlayer player;
|
@Shadow public ServerPlayer player;
|
||||||
@Unique private Entity astra$boat;
|
@Unique private Entity astra$boat;
|
||||||
@Unique private Vec3 astra$boatBefore;
|
@Unique private Vec3 astra$boatBefore;
|
||||||
|
|
||||||
// Run after vanilla's thread check, so packet-thread rescheduling never mutates state.
|
// 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))
|
@Inject(
|
||||||
private void astra$before(ServerboundMoveVehiclePacket packet,CallbackInfo ci){astra$boat=player.getRootVehicle();astra$boatBefore=astra$boat.position();}
|
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"))
|
@Inject(method = "handleMoveVehicle", at = @At("RETURN"))
|
||||||
private void astra$after(ServerboundMoveVehiclePacket packet, CallbackInfo ci) {
|
private void astra$after(ServerboundMoveVehiclePacket packet, CallbackInfo ci) {
|
||||||
if(astra$boat!=null&&astra$boatBefore!=null){SlimeBounce.boatPacket(astra$boat,astra$boatBefore);astra$boat=null;astra$boatBefore=null;}
|
if (astra$boat != null && astra$boatBefore != null) {
|
||||||
|
SlimeBounce.boatPacket(astra$boat, astra$boatBefore);
|
||||||
|
astra$boat = null;
|
||||||
|
astra$boatBefore = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,39 @@
|
|||||||
package online.astradev.content.mixin;
|
package online.astradev.content.mixin;
|
||||||
|
|
||||||
import java.util.function.Predicate;
|
|
||||||
import net.minecraft.world.item.*;
|
|
||||||
import net.minecraft.world.level.Level;
|
|
||||||
import net.minecraft.world.entity.LivingEntity;
|
import net.minecraft.world.entity.LivingEntity;
|
||||||
import net.minecraft.world.entity.projectile.Projectile;
|
import net.minecraft.world.entity.projectile.Projectile;
|
||||||
|
import net.minecraft.world.item.*;
|
||||||
|
import net.minecraft.world.level.Level;
|
||||||
|
|
||||||
import online.astradev.content.weapon.Ammunition;
|
import online.astradev.content.weapon.Ammunition;
|
||||||
|
|
||||||
import org.spongepowered.asm.mixin.Mixin;
|
import org.spongepowered.asm.mixin.Mixin;
|
||||||
import org.spongepowered.asm.mixin.injection.*;
|
import org.spongepowered.asm.mixin.injection.*;
|
||||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||||
|
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
|
||||||
@Mixin(CrossbowItem.class)
|
@Mixin(CrossbowItem.class)
|
||||||
public abstract class CrossbowMixin {
|
public abstract class CrossbowMixin {
|
||||||
@Inject(method = {"getSupportedHeldProjectiles()Ljava/util/function/Predicate;", "getAllSupportedProjectiles()Ljava/util/function/Predicate;"}, at = @At("RETURN"), cancellable = true)
|
@Inject(
|
||||||
private void astra$ammo(CallbackInfoReturnable<Predicate<ItemStack>> cir) { cir.setReturnValue(cir.getReturnValue().or(Ammunition::accepts)); }
|
method = {
|
||||||
|
"getSupportedHeldProjectiles()Ljava/util/function/Predicate;",
|
||||||
|
"getAllSupportedProjectiles()Ljava/util/function/Predicate;"
|
||||||
|
},
|
||||||
|
at = @At("RETURN"),
|
||||||
|
cancellable = true)
|
||||||
|
private void astra$ammo(CallbackInfoReturnable<Predicate<ItemStack>> cir) {
|
||||||
|
cir.setReturnValue(cir.getReturnValue().or(Ammunition::accepts));
|
||||||
|
}
|
||||||
|
|
||||||
@Inject(method = "createProjectile", at = @At("HEAD"), cancellable = true)
|
@Inject(method = "createProjectile", at = @At("HEAD"), cancellable = true)
|
||||||
private void astra$create(Level level, LivingEntity owner, ItemStack weapon, ItemStack ammo, boolean critical, CallbackInfoReturnable<Projectile> cir) {
|
private void astra$create(
|
||||||
|
Level level,
|
||||||
|
LivingEntity owner,
|
||||||
|
ItemStack weapon,
|
||||||
|
ItemStack ammo,
|
||||||
|
boolean critical,
|
||||||
|
CallbackInfoReturnable<Projectile> cir) {
|
||||||
if (Ammunition.accepts(ammo)) cir.setReturnValue(Ammunition.create(level, owner, ammo));
|
if (Ammunition.accepts(ammo)) cir.setReturnValue(Ammunition.create(level, owner, ammo));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,19 +3,25 @@ package online.astradev.content.mixin;
|
|||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.world.entity.vehicle.minecart.*;
|
import net.minecraft.world.entity.vehicle.minecart.*;
|
||||||
import net.minecraft.world.phys.Vec3;
|
import net.minecraft.world.phys.Vec3;
|
||||||
|
|
||||||
import online.astradev.content.rail.CartSpeed;
|
import online.astradev.content.rail.CartSpeed;
|
||||||
|
|
||||||
import org.spongepowered.asm.mixin.Mixin;
|
import org.spongepowered.asm.mixin.Mixin;
|
||||||
import org.spongepowered.asm.mixin.injection.*;
|
import org.spongepowered.asm.mixin.injection.*;
|
||||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||||
|
|
||||||
@Mixin(NewMinecartBehavior.class)
|
@Mixin(NewMinecartBehavior.class)
|
||||||
public abstract class ExperimentalCartMixin extends MinecartBehavior {
|
public abstract class ExperimentalCartMixin extends MinecartBehavior {
|
||||||
protected ExperimentalCartMixin(AbstractMinecart cart){super(cart);}
|
protected ExperimentalCartMixin(AbstractMinecart cart) {
|
||||||
|
super(cart);
|
||||||
|
}
|
||||||
|
|
||||||
@Inject(method = "calculateTrackSpeed", at = @At("RETURN"), cancellable = true)
|
@Inject(method = "calculateTrackSpeed", at = @At("RETURN"), cancellable = true)
|
||||||
private void astra$exactSpeed(CallbackInfoReturnable<Vec3> cir) {
|
private void astra$exactSpeed(CallbackInfoReturnable<Vec3> cir) {
|
||||||
if (!(level() instanceof ServerLevel level)) return;
|
if (!(level() instanceof ServerLevel level)) return;
|
||||||
double limit = ((CartSpeed) minecart).astracontent$limit(level);
|
double limit = ((CartSpeed) minecart).astracontent$limit(level);
|
||||||
var movement = cir.getReturnValue();
|
var movement = cir.getReturnValue();
|
||||||
if(limit>0 && movement.horizontalDistance()>limit)cir.setReturnValue(movement.scale(limit/movement.horizontalDistance()));
|
if (limit > 0 && movement.horizontalDistance() > limit)
|
||||||
|
cir.setReturnValue(movement.scale(limit / movement.horizontalDistance()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,19 @@
|
|||||||
package online.astradev.content.mixin;
|
package online.astradev.content.mixin;
|
||||||
|
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.world.entity.vehicle.minecart.MinecartFurnace;
|
import net.minecraft.world.entity.vehicle.minecart.MinecartFurnace;
|
||||||
|
|
||||||
import online.astradev.content.rail.CartSpeed;
|
import online.astradev.content.rail.CartSpeed;
|
||||||
|
|
||||||
import org.spongepowered.asm.mixin.Mixin;
|
import org.spongepowered.asm.mixin.Mixin;
|
||||||
import org.spongepowered.asm.mixin.injection.*;
|
import org.spongepowered.asm.mixin.injection.*;
|
||||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||||
|
|
||||||
@Mixin(MinecartFurnace.class)
|
@Mixin(MinecartFurnace.class)
|
||||||
public abstract class FurnaceCartMixin {
|
public abstract class FurnaceCartMixin {
|
||||||
@Inject(method = "getMaxSpeed", at = @At("RETURN"), cancellable = true)
|
@Inject(method = "getMaxSpeed", at = @At("RETURN"), cancellable = true)
|
||||||
private void astra$furnace(ServerLevel level, CallbackInfoReturnable<Double> cir) {
|
private void astra$furnace(ServerLevel level, CallbackInfoReturnable<Double> cir) {
|
||||||
double limit=((CartSpeed)this).astracontent$limit(level);if(limit>0)cir.setReturnValue(limit);
|
double limit = ((CartSpeed) this).astracontent$limit(level);
|
||||||
|
if (limit > 0) cir.setReturnValue(limit);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ package online.astradev.content.mixin;
|
|||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||||
import net.minecraft.world.level.storage.*;
|
import net.minecraft.world.level.storage.*;
|
||||||
|
|
||||||
import online.astradev.content.rail.RailSpeed;
|
import online.astradev.content.rail.RailSpeed;
|
||||||
|
|
||||||
import org.spongepowered.asm.mixin.*;
|
import org.spongepowered.asm.mixin.*;
|
||||||
import org.spongepowered.asm.mixin.injection.*;
|
import org.spongepowered.asm.mixin.injection.*;
|
||||||
import org.spongepowered.asm.mixin.injection.callback.*;
|
import org.spongepowered.asm.mixin.injection.callback.*;
|
||||||
@@ -11,12 +13,15 @@ import org.spongepowered.asm.mixin.injection.callback.*;
|
|||||||
@Mixin(AbstractMinecart.class)
|
@Mixin(AbstractMinecart.class)
|
||||||
public abstract class MinecartMixin implements online.astradev.content.rail.CartSpeed {
|
public abstract class MinecartMixin implements online.astradev.content.rail.CartSpeed {
|
||||||
@Unique private double astra$speed;
|
@Unique private double astra$speed;
|
||||||
|
|
||||||
@Inject(method = "getMaxSpeed", at = @At("RETURN"), cancellable = true)
|
@Inject(method = "getMaxSpeed", at = @At("RETURN"), cancellable = true)
|
||||||
private void astra$limit(ServerLevel level, CallbackInfoReturnable<Double> cir) {
|
private void astra$limit(ServerLevel level, CallbackInfoReturnable<Double> cir) {
|
||||||
double limit = astracontent$limit(level);
|
double limit = astracontent$limit(level);
|
||||||
if (limit > 0) cir.setReturnValue(limit);
|
if (limit > 0) cir.setReturnValue(limit);
|
||||||
}
|
}
|
||||||
@Override public double astracontent$limit(ServerLevel level) {
|
|
||||||
|
@Override
|
||||||
|
public double astracontent$limit(ServerLevel level) {
|
||||||
var cart = (AbstractMinecart) (Object) this;
|
var cart = (AbstractMinecart) (Object) this;
|
||||||
astra$speed = RailSpeed.target(level, cart.getCurrentBlockPosOrRailBelow(), astra$speed);
|
astra$speed = RailSpeed.target(level, cart.getCurrentBlockPosOrRailBelow(), astra$speed);
|
||||||
// Preserve existing experimental gamerules until this cart reaches a regulator.
|
// Preserve existing experimental gamerules until this cart reaches a regulator.
|
||||||
@@ -24,10 +29,15 @@ public abstract class MinecartMixin implements online.astradev.content.rail.Cart
|
|||||||
double limit = RailSpeed.safeLimit(cart, level, astra$speed / 20);
|
double limit = RailSpeed.safeLimit(cart, level, astra$speed / 20);
|
||||||
return limit * (cart.isInWater() ? .5 : 1);
|
return limit * (cart.isInWater() ? .5 : 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Inject(method = "addAdditionalSaveData", at = @At("RETURN"))
|
@Inject(method = "addAdditionalSaveData", at = @At("RETURN"))
|
||||||
private void astra$save(ValueOutput out,CallbackInfo ci) { if(astra$speed>0)out.putDouble("AstraContentSpeed",astra$speed); }
|
private void astra$save(ValueOutput out, CallbackInfo ci) {
|
||||||
|
if (astra$speed > 0) out.putDouble("AstraContentSpeed", astra$speed);
|
||||||
|
}
|
||||||
|
|
||||||
@Inject(method = "readAdditionalSaveData", at = @At("RETURN"))
|
@Inject(method = "readAdditionalSaveData", at = @At("RETURN"))
|
||||||
private void astra$read(ValueInput in, CallbackInfo ci) {
|
private void astra$read(ValueInput in, CallbackInfo ci) {
|
||||||
double value=in.getDoubleOr("AstraContentSpeed",0); astra$speed=Double.isFinite(value) && value>0?Math.clamp(value,2,30):0;
|
double value = in.getDoubleOr("AstraContentSpeed", 0);
|
||||||
|
astra$speed = Double.isFinite(value) && value > 0 ? Math.clamp(value, 2, 30) : 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ package online.astradev.content.mixin;
|
|||||||
|
|
||||||
import net.minecraft.world.entity.projectile.EyeOfEnder;
|
import net.minecraft.world.entity.projectile.EyeOfEnder;
|
||||||
import net.minecraft.world.phys.Vec3;
|
import net.minecraft.world.phys.Vec3;
|
||||||
|
|
||||||
import online.astradev.content.weapon.PayloadProjectile;
|
import online.astradev.content.weapon.PayloadProjectile;
|
||||||
|
|
||||||
import org.spongepowered.asm.mixin.*;
|
import org.spongepowered.asm.mixin.*;
|
||||||
import org.spongepowered.asm.mixin.injection.*;
|
import org.spongepowered.asm.mixin.injection.*;
|
||||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||||
@@ -10,8 +12,10 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
|||||||
@Mixin(EyeOfEnder.class)
|
@Mixin(EyeOfEnder.class)
|
||||||
public abstract class PayloadMixin {
|
public abstract class PayloadMixin {
|
||||||
@Shadow private boolean surviveAfterDeath;
|
@Shadow private boolean surviveAfterDeath;
|
||||||
|
|
||||||
@Inject(method = "signalTo", at = @At("RETURN"))
|
@Inject(method = "signalTo", at = @At("RETURN"))
|
||||||
private void astra$noDuplicate(Vec3 target, CallbackInfo ci) {
|
private void astra$noDuplicate(Vec3 target, CallbackInfo ci) {
|
||||||
if (((EyeOfEnder)(Object)this).entityTags().contains(PayloadProjectile.NO_EYE_DROP)) surviveAfterDeath = false;
|
if (((EyeOfEnder) (Object) this).entityTags().contains(PayloadProjectile.NO_EYE_DROP))
|
||||||
|
surviveAfterDeath = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package online.astradev.content.mixin;
|
package online.astradev.content.mixin;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.world.entity.LivingEntity;
|
import net.minecraft.world.entity.LivingEntity;
|
||||||
@@ -10,25 +9,50 @@ import net.minecraft.world.level.block.*;
|
|||||||
import net.minecraft.world.level.block.state.BlockState;
|
import net.minecraft.world.level.block.state.BlockState;
|
||||||
import net.minecraft.world.level.storage.loot.LootParams;
|
import net.minecraft.world.level.storage.loot.LootParams;
|
||||||
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
|
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
|
||||||
|
|
||||||
import online.astradev.content.rail.Rails;
|
import online.astradev.content.rail.Rails;
|
||||||
|
|
||||||
import org.spongepowered.asm.mixin.Mixin;
|
import org.spongepowered.asm.mixin.Mixin;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Mixin(PoweredRailBlock.class)
|
@Mixin(PoweredRailBlock.class)
|
||||||
public abstract class RailBlockMixin extends BaseRailBlock {
|
public abstract class RailBlockMixin extends BaseRailBlock {
|
||||||
protected RailBlockMixin(boolean straight, Properties properties) { super(straight,properties); }
|
protected RailBlockMixin(boolean straight, Properties properties) {
|
||||||
@Override public void setPlacedBy(Level level, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
|
super(straight, properties);
|
||||||
super.setPlacedBy(level,pos,state,placer,stack);
|
|
||||||
if (state.is(Blocks.POWERED_RAIL) && level instanceof ServerLevel server) Rails.placed(server,pos,stack);
|
|
||||||
}
|
}
|
||||||
@Override protected List<ItemStack> getDrops(BlockState state, LootParams.Builder params) {
|
|
||||||
var drops = super.getDrops(state,params); var origin = params.getOptionalParameter(LootContextParams.ORIGIN);
|
@Override
|
||||||
|
public void setPlacedBy(
|
||||||
|
Level level, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
|
||||||
|
super.setPlacedBy(level, pos, state, placer, stack);
|
||||||
|
if (state.is(Blocks.POWERED_RAIL) && level instanceof ServerLevel server)
|
||||||
|
Rails.placed(server, pos, stack);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected List<ItemStack> getDrops(BlockState state, LootParams.Builder params) {
|
||||||
|
var drops = super.getDrops(state, params);
|
||||||
|
var origin = params.getOptionalParameter(LootContextParams.ORIGIN);
|
||||||
if (!state.is(Blocks.POWERED_RAIL) || origin == null) return drops;
|
if (!state.is(Blocks.POWERED_RAIL) || origin == null) return drops;
|
||||||
var kind = Rails.loot(params.getLevel(), BlockPos.containing(origin));
|
var kind = Rails.loot(params.getLevel(), BlockPos.containing(origin));
|
||||||
return kind == null ? drops : drops.stream().map(stack -> stack.is(asItem()) ? Rails.stack(kind,stack.getCount()) : stack).toList();
|
return kind == null
|
||||||
|
? drops
|
||||||
|
: drops.stream()
|
||||||
|
.map(
|
||||||
|
stack ->
|
||||||
|
stack.is(asItem())
|
||||||
|
? Rails.stack(kind, stack.getCount())
|
||||||
|
: stack)
|
||||||
|
.toList();
|
||||||
}
|
}
|
||||||
@Override protected ItemStack getCloneItemStack(LevelReader level, BlockPos pos, BlockState state, boolean includeData) {
|
|
||||||
|
@Override
|
||||||
|
protected ItemStack getCloneItemStack(
|
||||||
|
LevelReader level, BlockPos pos, BlockState state, boolean includeData) {
|
||||||
if (level instanceof ServerLevel server && state.is(Blocks.POWERED_RAIL)) {
|
if (level instanceof ServerLevel server && state.is(Blocks.POWERED_RAIL)) {
|
||||||
var kind=Rails.find(server,pos); if(kind!=null) return Rails.stack(kind,1);
|
var kind = Rails.find(server, pos);
|
||||||
|
if (kind != null) return Rails.stack(kind, 1);
|
||||||
}
|
}
|
||||||
return super.getCloneItemStack(level, pos, state, includeData);
|
return super.getCloneItemStack(level, pos, state, includeData);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,22 @@
|
|||||||
package online.astradev.content.mixin;
|
package online.astradev.content.mixin;
|
||||||
|
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.world.level.block.state.BlockState;
|
import net.minecraft.world.level.block.state.BlockState;
|
||||||
import net.minecraft.world.level.chunk.LevelChunk;
|
import net.minecraft.world.level.chunk.LevelChunk;
|
||||||
|
|
||||||
import online.astradev.content.rail.Rails;
|
import online.astradev.content.rail.Rails;
|
||||||
|
|
||||||
import org.spongepowered.asm.mixin.Mixin;
|
import org.spongepowered.asm.mixin.Mixin;
|
||||||
import org.spongepowered.asm.mixin.injection.*;
|
import org.spongepowered.asm.mixin.injection.*;
|
||||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||||
|
|
||||||
@Mixin(LevelChunk.class)
|
@Mixin(LevelChunk.class)
|
||||||
public abstract class RailChunkMixin {
|
public abstract class RailChunkMixin {
|
||||||
@Inject(method = "setBlockState", at = @At("RETURN"))
|
@Inject(method = "setBlockState", at = @At("RETURN"))
|
||||||
private void astra$changed(BlockPos pos,BlockState state,int flags,CallbackInfoReturnable<BlockState> cir) {
|
private void astra$changed(
|
||||||
if (((LevelChunk)(Object)this).getLevel() instanceof ServerLevel level) Rails.changed(level,pos,cir.getReturnValue(),state);
|
BlockPos pos, BlockState state, int flags, CallbackInfoReturnable<BlockState> cir) {
|
||||||
|
if (((LevelChunk) (Object) this).getLevel() instanceof ServerLevel level)
|
||||||
|
Rails.changed(level, pos, cir.getReturnValue(), state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,43 @@
|
|||||||
package online.astradev.content.mixin;
|
package online.astradev.content.mixin;
|
||||||
|
|
||||||
import net.minecraft.world.entity.*;
|
import net.minecraft.world.entity.*;
|
||||||
import net.minecraft.world.phys.Vec3;
|
|
||||||
import online.astradev.content.transport.SlimeBounce;
|
|
||||||
import online.astradev.content.train.Trains;
|
|
||||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||||
import net.minecraft.world.level.block.BaseRailBlock;
|
import net.minecraft.world.level.block.BaseRailBlock;
|
||||||
|
import net.minecraft.world.phys.Vec3;
|
||||||
|
|
||||||
|
import online.astradev.content.train.Trains;
|
||||||
|
import online.astradev.content.transport.SlimeBounce;
|
||||||
|
|
||||||
import org.spongepowered.asm.mixin.*;
|
import org.spongepowered.asm.mixin.*;
|
||||||
import org.spongepowered.asm.mixin.injection.*;
|
import org.spongepowered.asm.mixin.injection.*;
|
||||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||||
|
|
||||||
@Mixin(Entity.class)
|
@Mixin(Entity.class)
|
||||||
public abstract class SlimeCollisionMixin {
|
public abstract class SlimeCollisionMixin {
|
||||||
@Unique private Vec3 astra$beforeMove;
|
@Unique private Vec3 astra$beforeMove;
|
||||||
@Unique private Vec3 astra$incoming;
|
@Unique private Vec3 astra$incoming;
|
||||||
|
|
||||||
@Inject(method = "move", at = @At("HEAD"), cancellable = true)
|
@Inject(method = "move", at = @At("HEAD"), cancellable = true)
|
||||||
private void astra$before(MoverType type, Vec3 delta, CallbackInfo ci) {
|
private void astra$before(MoverType type, Vec3 delta, CallbackInfo ci) {
|
||||||
var entity=(Entity)(Object)this;astra$beforeMove=type==MoverType.SELF&&SlimeBounce.supports(entity)?entity.position():null;
|
var entity = (Entity) (Object) this;
|
||||||
|
astra$beforeMove =
|
||||||
|
type == MoverType.SELF && SlimeBounce.supports(entity) ? entity.position() : null;
|
||||||
astra$incoming = entity.getDeltaMovement();
|
astra$incoming = entity.getDeltaMovement();
|
||||||
// Native powered rails can accelerate from zero within this same tick.
|
// Native powered rails can accelerate from zero within this same tick.
|
||||||
if(type==MoverType.SELF && entity instanceof AbstractMinecart cart && Trains.paused(cart)
|
if (type == MoverType.SELF
|
||||||
&& cart.level().getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock){
|
&& entity instanceof AbstractMinecart cart
|
||||||
astra$beforeMove=null;cart.setDeltaMovement(Vec3.ZERO);ci.cancel();
|
&& 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"))
|
@Inject(method = "move", at = @At("RETURN"))
|
||||||
private void astra$after(MoverType type, Vec3 delta, CallbackInfo ci) {
|
private void astra$after(MoverType type, Vec3 delta, CallbackInfo ci) {
|
||||||
if(astra$beforeMove!=null)SlimeBounce.afterMove((Entity)(Object)this,astra$beforeMove,delta,astra$incoming);
|
if (astra$beforeMove != null)
|
||||||
|
SlimeBounce.afterMove((Entity) (Object) this, astra$beforeMove, delta, astra$incoming);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ import net.minecraft.world.entity.Entity;
|
|||||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||||
import net.minecraft.world.level.storage.*;
|
import net.minecraft.world.level.storage.*;
|
||||||
import net.minecraft.world.phys.Vec3;
|
import net.minecraft.world.phys.Vec3;
|
||||||
|
|
||||||
import online.astradev.content.train.*;
|
import online.astradev.content.train.*;
|
||||||
|
|
||||||
import org.spongepowered.asm.mixin.*;
|
import org.spongepowered.asm.mixin.*;
|
||||||
import org.spongepowered.asm.mixin.injection.*;
|
import org.spongepowered.asm.mixin.injection.*;
|
||||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||||
@@ -13,26 +15,51 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
|||||||
public abstract class TrainCartMixin implements CartFrame {
|
public abstract class TrainCartMixin implements CartFrame {
|
||||||
@Unique private Vec3 astra$front = Vec3.ZERO;
|
@Unique private Vec3 astra$front = Vec3.ZERO;
|
||||||
@Unique private Vec3 astra$beforePlayerPush;
|
@Unique private Vec3 astra$beforePlayerPush;
|
||||||
@Override public Vec3 astracontent$front(){return astra$front;}
|
|
||||||
@Override public void astracontent$front(Vec3 axis){astra$front=axis;}
|
@Override
|
||||||
|
public Vec3 astracontent$front() {
|
||||||
|
return astra$front;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void astracontent$front(Vec3 axis) {
|
||||||
|
astra$front = axis;
|
||||||
|
}
|
||||||
|
|
||||||
@Inject(method = "addAdditionalSaveData", at = @At("RETURN"))
|
@Inject(method = "addAdditionalSaveData", at = @At("RETURN"))
|
||||||
private void astra$save(ValueOutput out,CallbackInfo ci){out.putDouble("AstraTrainFrontX",astra$front.x);out.putDouble("AstraTrainFrontZ",astra$front.z);}
|
private void astra$save(ValueOutput out, CallbackInfo ci) {
|
||||||
|
out.putDouble("AstraTrainFrontX", astra$front.x);
|
||||||
|
out.putDouble("AstraTrainFrontZ", astra$front.z);
|
||||||
|
}
|
||||||
|
|
||||||
@Inject(method = "readAdditionalSaveData", at = @At("RETURN"))
|
@Inject(method = "readAdditionalSaveData", at = @At("RETURN"))
|
||||||
private void astra$read(ValueInput in, CallbackInfo ci) {
|
private void astra$read(ValueInput in, CallbackInfo ci) {
|
||||||
double x = in.getDoubleOr("AstraTrainFrontX", 0), z = in.getDoubleOr("AstraTrainFrontZ", 0);
|
double x = in.getDoubleOr("AstraTrainFrontX", 0), z = in.getDoubleOr("AstraTrainFrontZ", 0);
|
||||||
astra$front=Double.isFinite(x)&&Double.isFinite(z)?new Vec3(x,0,z).normalize():Vec3.ZERO;
|
astra$front =
|
||||||
|
Double.isFinite(x) && Double.isFinite(z)
|
||||||
|
? new Vec3(x, 0, z).normalize()
|
||||||
|
: Vec3.ZERO;
|
||||||
}
|
}
|
||||||
@Inject(method="push(Lnet/minecraft/world/entity/Entity;)V",at=@At("HEAD"),cancellable=true)
|
|
||||||
|
@Inject(
|
||||||
|
method = "push(Lnet/minecraft/world/entity/Entity;)V",
|
||||||
|
at = @At("HEAD"),
|
||||||
|
cancellable = true)
|
||||||
private void astra$noInternalCollision(Entity other, CallbackInfo ci) {
|
private void astra$noInternalCollision(Entity other, CallbackInfo ci) {
|
||||||
var self = (AbstractMinecart) (Object) this;
|
var self = (AbstractMinecart) (Object) this;
|
||||||
astra$beforePlayerPush=other instanceof net.minecraft.world.entity.player.Player?self.getDeltaMovement():null;
|
astra$beforePlayerPush =
|
||||||
|
other instanceof net.minecraft.world.entity.player.Player
|
||||||
|
? self.getDeltaMovement()
|
||||||
|
: null;
|
||||||
if (other instanceof AbstractMinecart cart && Trains.connected(self, cart)) ci.cancel();
|
if (other instanceof AbstractMinecart cart && Trains.connected(self, cart)) ci.cancel();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Inject(method = "push(Lnet/minecraft/world/entity/Entity;)V", at = @At("RETURN"))
|
@Inject(method = "push(Lnet/minecraft/world/entity/Entity;)V", at = @At("RETURN"))
|
||||||
private void astra$playerPush(Entity other, CallbackInfo ci) {
|
private void astra$playerPush(Entity other, CallbackInfo ci) {
|
||||||
var self = (AbstractMinecart) (Object) this;
|
var self = (AbstractMinecart) (Object) this;
|
||||||
if(astra$beforePlayerPush!=null && self.getDeltaMovement().subtract(astra$beforePlayerPush).horizontalDistanceSqr()>1e-12)
|
if (astra$beforePlayerPush != null
|
||||||
Trains.playerPush(self);
|
&& self.getDeltaMovement().subtract(astra$beforePlayerPush).horizontalDistanceSqr()
|
||||||
|
> 1e-12) Trains.playerPush(self);
|
||||||
astra$beforePlayerPush = null;
|
astra$beforePlayerPush = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package online.astradev.content.rail;
|
package online.astradev.content.rail;
|
||||||
|
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
|
|
||||||
public interface CartSpeed {
|
public interface CartSpeed {
|
||||||
/** Blocks per tick, or zero until the cart encounters a powered speed regulator. */
|
/** Blocks per tick, or zero until the cart encounters a powered speed regulator. */
|
||||||
double astracontent$limit(ServerLevel level);
|
double astracontent$limit(ServerLevel level);
|
||||||
|
|||||||
@@ -1,20 +1,32 @@
|
|||||||
package online.astradev.content.rail;
|
package online.astradev.content.rail;
|
||||||
|
|
||||||
import net.minecraft.commands.Commands;
|
import net.minecraft.commands.Commands;
|
||||||
import net.neoforged.bus.api.SubscribeEvent;
|
import net.neoforged.bus.api.SubscribeEvent;
|
||||||
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
||||||
|
|
||||||
public final class RailCommands {
|
public final class RailCommands {
|
||||||
private RailCommands() {}
|
private RailCommands() {}
|
||||||
@SubscribeEvent public static void register(RegisterCommandsEvent event) {
|
|
||||||
|
@SubscribeEvent
|
||||||
|
public static void register(RegisterCommandsEvent event) {
|
||||||
var give = Commands.literal("give");
|
var give = Commands.literal("give");
|
||||||
for (int i = 0; i < 8; i++) {
|
for (int i = 0; i < 8; i++) {
|
||||||
var kind = RailKind.decode(i);
|
var kind = RailKind.decode(i);
|
||||||
give.then(Commands.literal(kind.id().getPath()).executes(ctx->{
|
give.then(
|
||||||
|
Commands.literal(kind.id().getPath())
|
||||||
|
.executes(
|
||||||
|
ctx -> {
|
||||||
var player = ctx.getSource().getPlayerOrException();
|
var player = ctx.getSource().getPlayerOrException();
|
||||||
var stack = Rails.stack(kind, 64);
|
var stack = Rails.stack(kind, 64);
|
||||||
if(!player.getInventory().add(stack)) player.drop(stack,false);
|
if (!player.getInventory().add(stack))
|
||||||
|
player.drop(stack, false);
|
||||||
return 1;
|
return 1;
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
event.getDispatcher().register(Commands.literal("astracontent").requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS)).then(give));
|
event.getDispatcher()
|
||||||
|
.register(
|
||||||
|
Commands.literal("astracontent")
|
||||||
|
.requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS))
|
||||||
|
.then(give));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,21 +13,45 @@ import net.minecraft.world.level.storage.ValueOutput;
|
|||||||
|
|
||||||
final class RailDisplay extends Display.ItemDisplay {
|
final class RailDisplay extends Display.ItemDisplay {
|
||||||
private String previous;
|
private String previous;
|
||||||
|
|
||||||
RailDisplay(ServerLevel level, BlockPos pos) {
|
RailDisplay(ServerLevel level, BlockPos pos) {
|
||||||
super(EntityTypes.ITEM_DISPLAY, level);
|
super(EntityTypes.ITEM_DISPLAY, level);
|
||||||
setPos(pos.getX() + .5, pos.getY() + .5, pos.getZ() + .5);
|
setPos(pos.getX() + .5, pos.getY() + .5, pos.getZ() + .5);
|
||||||
setItemTransform(ItemDisplayContext.NONE); setNoGravity(true); setInvulnerable(true); setSilent(true);
|
setItemTransform(ItemDisplayContext.NONE);
|
||||||
|
setNoGravity(true);
|
||||||
|
setInvulnerable(true);
|
||||||
|
setSilent(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
void update(RailKind kind, BlockState state) {
|
void update(RailKind kind, BlockState state) {
|
||||||
var shape = state.getValue(PoweredRailBlock.SHAPE);
|
var shape = state.getValue(PoweredRailBlock.SHAPE);
|
||||||
String model = "rail_display/" + kind.age() + "/" + state.getValue(PoweredRailBlock.SHAPE).getSerializedName()
|
String model =
|
||||||
|
"rail_display/"
|
||||||
|
+ kind.age()
|
||||||
|
+ "/"
|
||||||
|
+ state.getValue(PoweredRailBlock.SHAPE).getSerializedName()
|
||||||
+ (state.getValue(PoweredRailBlock.POWERED) ? "_on" : "");
|
+ (state.getValue(PoweredRailBlock.POWERED) ? "_on" : "");
|
||||||
if (model.equals(previous)) return;
|
if (model.equals(previous)) return;
|
||||||
var stack = new ItemStack(Items.PAPER); stack.set(DataComponents.ITEM_MODEL,Identifier.fromNamespaceAndPath("astracontent",model));
|
var stack = new ItemStack(Items.PAPER);
|
||||||
getSlot(0).set(stack); previous=model;
|
stack.set(
|
||||||
setTransformation(new com.mojang.math.Transformation(new org.joml.Vector3f(),
|
DataComponents.ITEM_MODEL, Identifier.fromNamespaceAndPath("astracontent", model));
|
||||||
RailDisplayTransform.orientation(shape),new org.joml.Vector3f(1),new org.joml.Quaternionf()));
|
getSlot(0).set(stack);
|
||||||
|
previous = model;
|
||||||
|
setTransformation(
|
||||||
|
new com.mojang.math.Transformation(
|
||||||
|
new org.joml.Vector3f(),
|
||||||
|
RailDisplayTransform.orientation(shape),
|
||||||
|
new org.joml.Vector3f(1),
|
||||||
|
new org.joml.Quaternionf()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean shouldBeSaved() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean saveAsPassenger(ValueOutput output) {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
@Override public boolean shouldBeSaved() { return false; }
|
|
||||||
@Override public boolean saveAsPassenger(ValueOutput output) { return false; }
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,17 @@
|
|||||||
package online.astradev.content.rail;
|
package online.astradev.content.rail;
|
||||||
|
|
||||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||||
|
|
||||||
import org.joml.Quaternionf;
|
import org.joml.Quaternionf;
|
||||||
|
|
||||||
final class RailDisplayTransform {
|
final class RailDisplayTransform {
|
||||||
private RailDisplayTransform() {}
|
private RailDisplayTransform() {}
|
||||||
|
|
||||||
static Quaternionf orientation(RailShape shape) {
|
static Quaternionf orientation(RailShape shape) {
|
||||||
boolean eastWest=shape==RailShape.EAST_WEST||shape==RailShape.ASCENDING_EAST||shape==RailShape.ASCENDING_WEST;
|
boolean eastWest =
|
||||||
|
shape == RailShape.EAST_WEST
|
||||||
|
|| shape == RailShape.ASCENDING_EAST
|
||||||
|
|| shape == RailShape.ASCENDING_WEST;
|
||||||
// ItemDisplayRenderer itself applies Y=180 degrees before drawing an item model.
|
// ItemDisplayRenderer itself applies Y=180 degrees before drawing an item model.
|
||||||
// Cancel that turn so the model's raised end matches the actual rail's raised end.
|
// Cancel that turn so the model's raised end matches the actual rail's raised end.
|
||||||
return new Quaternionf().rotateY((float) Math.PI + (eastWest ? -(float) Math.PI / 2 : 0));
|
return new Quaternionf().rotateY((float) Math.PI + (eastWest ? -(float) Math.PI / 2 : 0));
|
||||||
|
|||||||
@@ -9,21 +9,38 @@ import net.minecraft.world.item.component.CustomData;
|
|||||||
/** Vanilla item, vanilla components: native placement prediction without a client mod. */
|
/** Vanilla item, vanilla components: native placement prediction without a client mod. */
|
||||||
public final class RailItems {
|
public final class RailItems {
|
||||||
public static final String KEY = "astracontent:rail";
|
public static final String KEY = "astracontent:rail";
|
||||||
|
|
||||||
private RailItems() {}
|
private RailItems() {}
|
||||||
|
|
||||||
public static RailKind find(ItemStack stack) {
|
public static RailKind find(ItemStack stack) {
|
||||||
if (!stack.is(Items.POWERED_RAIL)) return null;
|
if (!stack.is(Items.POWERED_RAIL)) return null;
|
||||||
var data=stack.get(DataComponents.CUSTOM_DATA);if(data==null)return null;
|
var data = stack.get(DataComponents.CUSTOM_DATA);
|
||||||
|
if (data == null) return null;
|
||||||
int value = data.copyTag().getIntOr(KEY, -1);
|
int value = data.copyTag().getIntOr(KEY, -1);
|
||||||
return value >= 0 && value < 8 ? RailKind.decode(value) : null;
|
return value >= 0 && value < 8 ? RailKind.decode(value) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ItemStack create(RailKind kind, int count) {
|
public static ItemStack create(RailKind kind, int count) {
|
||||||
var stack = new ItemStack(Items.POWERED_RAIL, count);
|
var stack = new ItemStack(Items.POWERED_RAIL, count);
|
||||||
var tag=new CompoundTag();tag.putInt(KEY,kind.code());stack.set(DataComponents.CUSTOM_DATA,CustomData.of(tag));
|
var tag = new CompoundTag();
|
||||||
|
tag.putInt(KEY, kind.code());
|
||||||
|
stack.set(DataComponents.CUSTOM_DATA, CustomData.of(tag));
|
||||||
stack.set(DataComponents.ITEM_MODEL, kind.id());
|
stack.set(DataComponents.ITEM_MODEL, kind.id());
|
||||||
stack.set(DataComponents.ITEM_NAME,Component.translatableWithFallback("item.astracontent."+kind.id().getPath(),name(kind)));
|
stack.set(
|
||||||
|
DataComponents.ITEM_NAME,
|
||||||
|
Component.translatableWithFallback(
|
||||||
|
"item.astracontent." + kind.id().getPath(), name(kind)));
|
||||||
return stack;
|
return stack;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String name(RailKind kind) {
|
public static String name(RailKind kind) {
|
||||||
return (kind.waxed()?"Вощёные: ":"")+new String[]{"Медные рельсы","Потемневшие медные рельсы","Состаренные медные рельсы","Окисленные медные рельсы"}[kind.age()];
|
return (kind.waxed() ? "Вощёные: " : "")
|
||||||
|
+ new String[] {
|
||||||
|
"Медные рельсы",
|
||||||
|
"Потемневшие медные рельсы",
|
||||||
|
"Состаренные медные рельсы",
|
||||||
|
"Окисленные медные рельсы"
|
||||||
|
}
|
||||||
|
[kind.age()];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,32 @@
|
|||||||
package online.astradev.content.rail;
|
package online.astradev.content.rail;
|
||||||
|
|
||||||
import net.minecraft.resources.Identifier;
|
import net.minecraft.resources.Identifier;
|
||||||
|
|
||||||
public record RailKind(int age, boolean waxed) {
|
public record RailKind(int age, boolean waxed) {
|
||||||
public RailKind { if (age < 0 || age > 3) throw new IllegalArgumentException("Oxidation: " + age); }
|
public RailKind {
|
||||||
public int speed() { return 20 - 4 * age; }
|
if (age < 0 || age > 3) throw new IllegalArgumentException("Oxidation: " + age);
|
||||||
public int code() { return age + (waxed ? 4 : 0); }
|
|
||||||
public static RailKind decode(int code) { return new RailKind(code & 3, (code & 4) != 0); }
|
|
||||||
public Identifier id() {
|
|
||||||
return Identifier.fromNamespaceAndPath("astracontent", (waxed ? "waxed_" : "")
|
|
||||||
+ new String[]{"", "exposed_", "weathered_", "oxidized_"}[age] + "copper_rail");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public int speed() {
|
||||||
|
return 20 - 4 * age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int code() {
|
||||||
|
return age + (waxed ? 4 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static RailKind decode(int code) {
|
||||||
|
return new RailKind(code & 3, (code & 4) != 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Identifier id() {
|
||||||
|
return Identifier.fromNamespaceAndPath(
|
||||||
|
"astracontent",
|
||||||
|
(waxed ? "waxed_" : "")
|
||||||
|
+ new String[] {"", "exposed_", "weathered_", "oxidized_"}[age]
|
||||||
|
+ "copper_rail");
|
||||||
|
}
|
||||||
|
|
||||||
public static RailKind fromId(Identifier id) {
|
public static RailKind fromId(Identifier id) {
|
||||||
for (int code = 0; code < 8; code++) if (decode(code).id().equals(id)) return decode(code);
|
for (int code = 0; code < 8; code++) if (decode(code).id().equals(id)) return decode(code);
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import net.minecraft.world.level.gamerules.GameRules;
|
|||||||
/** Match copper's random-tick selection, age neighborhood and oxidation probability. */
|
/** Match copper's random-tick selection, age neighborhood and oxidation probability. */
|
||||||
final class RailOxidation {
|
final class RailOxidation {
|
||||||
private RailOxidation() {}
|
private RailOxidation() {}
|
||||||
|
|
||||||
static boolean advance(ServerLevel level, BlockPos pos, RailKind kind) {
|
static boolean advance(ServerLevel level, BlockPos pos, RailKind kind) {
|
||||||
if (kind.waxed() || kind.age() == 3 || !level.isPositionEntityTicking(pos)) return false;
|
if (kind.waxed() || kind.age() == 3 || !level.isPositionEntityTicking(pos)) return false;
|
||||||
int rate = level.getGameRules().get(GameRules.RANDOM_TICK_SPEED);
|
int rate = level.getGameRules().get(GameRules.RANDOM_TICK_SPEED);
|
||||||
@@ -15,12 +16,18 @@ final class RailOxidation {
|
|||||||
if (level.getRandom().nextDouble() >= chance) return false;
|
if (level.getRandom().nextDouble() >= chance) return false;
|
||||||
int older = 0, same = 0;
|
int older = 0, same = 0;
|
||||||
for (var other : BlockPos.withinManhattan(pos, 4, 4, 4)) {
|
for (var other : BlockPos.withinManhattan(pos, 4, 4, 4)) {
|
||||||
int distance=other.distManhattan(pos);if(distance>4)break;if(distance==0 || !level.hasChunkAt(other))continue;
|
int distance = other.distManhattan(pos);
|
||||||
|
if (distance > 4) break;
|
||||||
|
if (distance == 0 || !level.hasChunkAt(other)) continue;
|
||||||
int age = -1;
|
int age = -1;
|
||||||
var rail = Rails.find(level, other);
|
var rail = Rails.find(level, other);
|
||||||
if (rail != null && !rail.waxed()) age = rail.age();
|
if (rail != null && !rail.waxed()) age = rail.age();
|
||||||
else if(level.getBlockState(other).getBlock() instanceof WeatheringCopper copper)age=copper.getAge().ordinal();
|
else if (level.getBlockState(other).getBlock() instanceof WeatheringCopper copper)
|
||||||
if(age<0)continue;if(age<kind.age())return false;if(age>kind.age())older++;else same++;
|
age = copper.getAge().ordinal();
|
||||||
|
if (age < 0) continue;
|
||||||
|
if (age < kind.age()) return false;
|
||||||
|
if (age > kind.age()) older++;
|
||||||
|
else same++;
|
||||||
}
|
}
|
||||||
double ratio = (older + 1.0) / (older + same + 1.0);
|
double ratio = (older + 1.0) / (older + same + 1.0);
|
||||||
return level.getRandom().nextDouble() < ratio * ratio * (kind.age() == 0 ? .75 : 1);
|
return level.getRandom().nextDouble() < ratio * ratio * (kind.age() == 0 ? .75 : 1);
|
||||||
|
|||||||
@@ -1,69 +1,108 @@
|
|||||||
package online.astradev.content.rail;
|
package online.astradev.content.rail;
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
|
import net.minecraft.core.Vec3i;
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||||
import net.minecraft.world.level.block.*;
|
import net.minecraft.world.level.block.*;
|
||||||
import net.minecraft.world.level.block.state.BlockState;
|
import net.minecraft.world.level.block.state.BlockState;
|
||||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
public final class RailSpeed {
|
public final class RailSpeed {
|
||||||
private RailSpeed() {}
|
private RailSpeed() {}
|
||||||
public static int signalSpeed(int signal) { return Math.clamp(signal,0,15)*2; }
|
|
||||||
|
public static int signalSpeed(int signal) {
|
||||||
|
return Math.clamp(signal, 0, 15) * 2;
|
||||||
|
}
|
||||||
|
|
||||||
public static double target(ServerLevel level, BlockPos pos, double previous) {
|
public static double target(ServerLevel level, BlockPos pos, double previous) {
|
||||||
var state = level.getBlockState(pos);
|
var state = level.getBlockState(pos);
|
||||||
if (!state.is(Blocks.POWERED_RAIL) || !state.getValue(PoweredRailBlock.POWERED)) return previous;
|
if (!state.is(Blocks.POWERED_RAIL) || !state.getValue(PoweredRailBlock.POWERED))
|
||||||
|
return previous;
|
||||||
var kind = Rails.find(level, pos);
|
var kind = Rails.find(level, pos);
|
||||||
return kind != null ? kind.speed() : Math.max(2, signalSpeed(signal(level, pos)));
|
return kind != null ? kind.speed() : Math.max(2, signalSpeed(signal(level, pos)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Mirror the vanilla eight-rail power reach, preserving bends, slopes and highest input. */
|
/** Mirror the vanilla eight-rail power reach, preserving bends, slopes and highest input. */
|
||||||
public static int signal(ServerLevel level, BlockPos origin) {
|
public static int signal(ServerLevel level, BlockPos origin) {
|
||||||
record Step(BlockPos pos, int distance) {}
|
record Step(BlockPos pos, int distance) {}
|
||||||
var queue=new ArrayDeque<Step>(); var seen=new HashSet<BlockPos>(); queue.add(new Step(origin,0));
|
var queue = new ArrayDeque<Step>();
|
||||||
|
var seen = new HashSet<BlockPos>();
|
||||||
|
queue.add(new Step(origin, 0));
|
||||||
int best = 0;
|
int best = 0;
|
||||||
while (!queue.isEmpty()) {
|
while (!queue.isEmpty()) {
|
||||||
var step=queue.removeFirst(); if(!seen.add(step.pos) || !level.hasChunkAt(step.pos)) continue;
|
var step = queue.removeFirst();
|
||||||
|
if (!seen.add(step.pos) || !level.hasChunkAt(step.pos)) continue;
|
||||||
var state = level.getBlockState(step.pos);
|
var state = level.getBlockState(step.pos);
|
||||||
if (!state.is(Blocks.POWERED_RAIL)) continue;
|
if (!state.is(Blocks.POWERED_RAIL)) continue;
|
||||||
best=Math.max(best,level.getBestNeighborSignal(step.pos)); if(best==15) return best;
|
best = Math.max(best, level.getBestNeighborSignal(step.pos));
|
||||||
|
if (best == 15) return best;
|
||||||
if (step.distance == 8) continue;
|
if (step.distance == 8) continue;
|
||||||
var shape = state.getValue(PoweredRailBlock.SHAPE);
|
var shape = state.getValue(PoweredRailBlock.SHAPE);
|
||||||
var exits = AbstractMinecart.exits(shape);
|
var exits = AbstractMinecart.exits(shape);
|
||||||
for (var exit : List.of(exits.getFirst(), exits.getSecond())) {
|
for (var exit : List.of(exits.getFirst(), exits.getSecond())) {
|
||||||
var adjacent=step.pos.offset(exit.getX(),shape.isSlope()?exit.getY()+1:0,exit.getZ());
|
var adjacent =
|
||||||
|
step.pos.offset(
|
||||||
|
exit.getX(), shape.isSlope() ? exit.getY() + 1 : 0, exit.getZ());
|
||||||
for (var candidate : List.of(adjacent, adjacent.below())) {
|
for (var candidate : List.of(adjacent, adjacent.below())) {
|
||||||
if (!level.hasChunkAt(candidate)) continue;
|
if (!level.hasChunkAt(candidate)) continue;
|
||||||
var other = level.getBlockState(candidate);
|
var other = level.getBlockState(candidate);
|
||||||
if(other.is(Blocks.POWERED_RAIL) && connected(step.pos,shape,candidate,other.getValue(PoweredRailBlock.SHAPE)))
|
if (other.is(Blocks.POWERED_RAIL)
|
||||||
|
&& connected(
|
||||||
|
step.pos,
|
||||||
|
shape,
|
||||||
|
candidate,
|
||||||
|
other.getValue(PoweredRailBlock.SHAPE)))
|
||||||
queue.add(new Step(candidate, step.distance + 1));
|
queue.add(new Step(candidate, step.distance + 1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return best;
|
return best;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean connected(BlockPos a, RailShape sa, BlockPos b, RailShape sb) {
|
private static boolean connected(BlockPos a, RailShape sa, BlockPos b, RailShape sb) {
|
||||||
var ea=AbstractMinecart.exits(sa); var eb=AbstractMinecart.exits(sb);
|
var ea = AbstractMinecart.exits(sa);
|
||||||
for(var x:List.of(ea.getFirst(),ea.getSecond())) for(var y:List.of(eb.getFirst(),eb.getSecond()))
|
var eb = AbstractMinecart.exits(sb);
|
||||||
if(a.getX()+x.getX()==b.getX() && a.getZ()+x.getZ()==b.getZ()
|
for (var exitA : List.of(ea.getFirst(), ea.getSecond())) {
|
||||||
&& b.getX()+y.getX()==a.getX() && b.getZ()+y.getZ()==a.getZ()
|
if (a.getX() + exitA.getX() != b.getX()) continue;
|
||||||
&& a.getY()+(sa.isSlope()?x.getY()+1:0)==b.getY()+(sb.isSlope()?y.getY()+1:0)) return true;
|
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;
|
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. */
|
/** 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) {
|
public static double safeLimit(AbstractMinecart cart, ServerLevel level, double limit) {
|
||||||
if (AbstractMinecart.useExperimentalMovement(level) || limit <= .4) return limit;
|
if (AbstractMinecart.useExperimentalMovement(level) || limit <= .4) return limit;
|
||||||
var pos=cart.getCurrentBlockPosOrRailBelow(); var movement=cart.getDeltaMovement();
|
var pos = cart.getCurrentBlockPosOrRailBelow();
|
||||||
|
var movement = cart.getDeltaMovement();
|
||||||
int dx = (int) Math.signum(movement.x), dz = (int) Math.signum(movement.z);
|
int dx = (int) Math.signum(movement.x), dz = (int) Math.signum(movement.z);
|
||||||
for (int i = 0; i <= 2; i++) {
|
for (int i = 0; i <= 2; i++) {
|
||||||
var check = pos.offset(dx * i, 0, dz * i);
|
var check = pos.offset(dx * i, 0, dz * i);
|
||||||
if (!level.hasChunkAt(check)) return .4;
|
if (!level.hasChunkAt(check)) return .4;
|
||||||
BlockState state = level.getBlockState(check);
|
BlockState state = level.getBlockState(check);
|
||||||
if(!(state.getBlock() instanceof BaseRailBlock rail)) return state.is(Blocks.SLIME_BLOCK)?limit:.4;
|
if (!(state.getBlock() instanceof BaseRailBlock rail))
|
||||||
|
return state.is(Blocks.SLIME_BLOCK) ? limit : .4;
|
||||||
RailShape shape = rail.getRailDirection(state, level, check, cart);
|
RailShape shape = rail.getRailDirection(state, level, check, cart);
|
||||||
if (shape != RailShape.NORTH_SOUTH && shape != RailShape.EAST_WEST) return .4;
|
if (shape != RailShape.NORTH_SOUTH && shape != RailShape.EAST_WEST) return .4;
|
||||||
if (i>0 && (state.is(Blocks.DETECTOR_RAIL) || state.is(Blocks.ACTIVATOR_RAIL)
|
if (i > 0 && stopsFastTravel(state)) return .4;
|
||||||
|| state.is(Blocks.POWERED_RAIL) && !state.getValue(PoweredRailBlock.POWERED))) return .4;
|
|
||||||
// Never jump over a single slower regulator.
|
// Never jump over a single slower regulator.
|
||||||
if (i > 0) limit = Math.min(limit, target(level, check, limit * 20) / 20);
|
if (i > 0) limit = Math.min(limit, target(level, check, limit * 20) / 20);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
package online.astradev.content.rail;
|
package online.astradev.content.rail;
|
||||||
|
|
||||||
import com.mojang.serialization.Codec;
|
import com.mojang.serialization.Codec;
|
||||||
import java.util.*;
|
|
||||||
import java.util.function.Supplier;
|
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.world.InteractionResult;
|
import net.minecraft.world.InteractionResult;
|
||||||
@@ -12,104 +11,196 @@ import net.minecraft.world.level.block.state.BlockState;
|
|||||||
import net.minecraft.world.level.chunk.LevelChunk;
|
import net.minecraft.world.level.chunk.LevelChunk;
|
||||||
import net.neoforged.bus.api.*;
|
import net.neoforged.bus.api.*;
|
||||||
import net.neoforged.neoforge.attachment.AttachmentType;
|
import net.neoforged.neoforge.attachment.AttachmentType;
|
||||||
import net.neoforged.neoforge.registries.*;
|
|
||||||
import net.neoforged.neoforge.event.level.ChunkEvent;
|
|
||||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
import net.neoforged.neoforge.event.level.ChunkEvent;
|
||||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||||
|
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||||
|
import net.neoforged.neoforge.registries.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
/** Native powered rails own placement, shape, redstone, collision and destruction. */
|
/** Native powered rails own placement, shape, redstone, collision and destruction. */
|
||||||
public final class Rails {
|
public final class Rails {
|
||||||
private static final DeferredRegister<AttachmentType<?>> TYPES = DeferredRegister.create(NeoForgeRegistries.Keys.ATTACHMENT_TYPES, "astracontent");
|
private static final DeferredRegister<AttachmentType<?>> TYPES =
|
||||||
public static final Supplier<AttachmentType<Map<Long, Integer>>> DATA = TYPES.register("copper_rails", () ->
|
DeferredRegister.create(NeoForgeRegistries.Keys.ATTACHMENT_TYPES, "astracontent");
|
||||||
AttachmentType.<Map<Long,Integer>>builder(() -> new HashMap<>()).serialize(
|
public static final Supplier<AttachmentType<Map<Long, Integer>>> DATA =
|
||||||
Codec.unboundedMap(Codec.STRING.xmap(Long::parseLong, String::valueOf), Codec.intRange(0,7))
|
TYPES.register(
|
||||||
.xmap(map -> (Map<Long,Integer>)new HashMap<>(map), map -> map).fieldOf("rails"), map -> !map.isEmpty()).build());
|
"copper_rails",
|
||||||
|
() ->
|
||||||
|
AttachmentType.<Map<Long, Integer>>builder(() -> new HashMap<>())
|
||||||
|
.serialize(
|
||||||
|
Codec.unboundedMap(
|
||||||
|
Codec.STRING.xmap(
|
||||||
|
Long::parseLong,
|
||||||
|
String::valueOf),
|
||||||
|
Codec.intRange(0, 7))
|
||||||
|
.xmap(
|
||||||
|
map ->
|
||||||
|
(Map<Long, Integer>)
|
||||||
|
new HashMap<>(map),
|
||||||
|
map -> map)
|
||||||
|
.fieldOf("rails"),
|
||||||
|
map -> !map.isEmpty())
|
||||||
|
.build());
|
||||||
|
|
||||||
private record Position(ServerLevel level, BlockPos pos) {}
|
private record Position(ServerLevel level, BlockPos pos) {}
|
||||||
|
|
||||||
private record Removed(RailKind kind, long tick) {}
|
private record Removed(RailKind kind, long tick) {}
|
||||||
|
|
||||||
private static final Map<Position, RailDisplay> ACTIVE = new HashMap<>();
|
private static final Map<Position, RailDisplay> ACTIVE = new HashMap<>();
|
||||||
private static final Map<Position, Removed> REMOVED = new HashMap<>();
|
private static final Map<Position, Removed> REMOVED = new HashMap<>();
|
||||||
|
|
||||||
private Rails() {}
|
private Rails() {}
|
||||||
public static void register(IEventBus bus) { TYPES.register(bus); }
|
|
||||||
|
public static void register(IEventBus bus) {
|
||||||
|
TYPES.register(bus);
|
||||||
|
}
|
||||||
|
|
||||||
public static RailKind find(ServerLevel level, BlockPos pos) {
|
public static RailKind find(ServerLevel level, BlockPos pos) {
|
||||||
var chunk = level.getChunkSource().getChunkNow(pos.getX() >> 4, pos.getZ() >> 4);
|
var chunk = level.getChunkSource().getChunkNow(pos.getX() >> 4, pos.getZ() >> 4);
|
||||||
if (chunk == null || !chunk.hasData(DATA)) return null;
|
if (chunk == null || !chunk.hasData(DATA)) return null;
|
||||||
Integer code = chunk.getData(DATA).get(pos.asLong());
|
Integer code = chunk.getData(DATA).get(pos.asLong());
|
||||||
return code == null ? null : RailKind.decode(code);
|
return code == null ? null : RailKind.decode(code);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static RailKind loot(ServerLevel level, BlockPos pos) {
|
public static RailKind loot(ServerLevel level, BlockPos pos) {
|
||||||
var kind = find(level, pos);
|
var kind = find(level, pos);
|
||||||
|
if (kind != null) return kind;
|
||||||
var removed = REMOVED.get(new Position(level, pos));
|
var removed = REMOVED.get(new Position(level, pos));
|
||||||
return kind != null ? kind : removed != null && removed.tick == level.getGameTime() ? removed.kind : null;
|
if (removed == null || removed.tick != level.getGameTime()) return null;
|
||||||
|
return removed.kind;
|
||||||
}
|
}
|
||||||
public static ItemStack stack(RailKind kind, int count) { return RailItems.create(kind,count); }
|
|
||||||
|
public static ItemStack stack(RailKind kind, int count) {
|
||||||
|
return RailItems.create(kind, count);
|
||||||
|
}
|
||||||
|
|
||||||
public static void placed(ServerLevel level, BlockPos pos, ItemStack stack) {
|
public static void placed(ServerLevel level, BlockPos pos, ItemStack stack) {
|
||||||
clear(level,pos); REMOVED.remove(new Position(level,pos));
|
clear(level, pos);
|
||||||
|
REMOVED.remove(new Position(level, pos));
|
||||||
var kind = RailItems.find(stack);
|
var kind = RailItems.find(stack);
|
||||||
if (kind != null) put(level, pos, kind);
|
if (kind != null) put(level, pos, kind);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void put(ServerLevel level, BlockPos pos, RailKind kind) {
|
public static void put(ServerLevel level, BlockPos pos, RailKind kind) {
|
||||||
var chunk = level.getChunkAt(pos); chunk.getData(DATA).put(pos.asLong(),kind.code()); chunk.markUnsaved();
|
var chunk = level.getChunkAt(pos);
|
||||||
|
chunk.getData(DATA).put(pos.asLong(), kind.code());
|
||||||
|
chunk.markUnsaved();
|
||||||
ACTIVE.putIfAbsent(new Position(level, pos.immutable()), null);
|
ACTIVE.putIfAbsent(new Position(level, pos.immutable()), null);
|
||||||
}
|
}
|
||||||
public static void changed(ServerLevel level, BlockPos pos, BlockState before, BlockState after) {
|
|
||||||
if (before == null || !before.is(Blocks.POWERED_RAIL) || after.is(Blocks.POWERED_RAIL)) return;
|
public static void changed(
|
||||||
|
ServerLevel level, BlockPos pos, BlockState before, BlockState after) {
|
||||||
|
if (before == null || !before.is(Blocks.POWERED_RAIL) || after.is(Blocks.POWERED_RAIL))
|
||||||
|
return;
|
||||||
var kind = find(level, pos);
|
var kind = find(level, pos);
|
||||||
if (kind != null) { REMOVED.put(new Position(level,pos.immutable()),new Removed(kind,level.getGameTime())); clear(level,pos); }
|
if (kind != null) {
|
||||||
|
REMOVED.put(
|
||||||
|
new Position(level, pos.immutable()), new Removed(kind, level.getGameTime()));
|
||||||
|
clear(level, pos);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static void clear(ServerLevel level, BlockPos pos) {
|
private static void clear(ServerLevel level, BlockPos pos) {
|
||||||
var chunk = level.getChunkSource().getChunkNow(pos.getX() >> 4, pos.getZ() >> 4);
|
var chunk = level.getChunkSource().getChunkNow(pos.getX() >> 4, pos.getZ() >> 4);
|
||||||
if (chunk != null && chunk.hasData(DATA) && chunk.getData(DATA).remove(pos.asLong()) != null) chunk.markUnsaved();
|
if (chunk != null
|
||||||
var display = ACTIVE.remove(new Position(level,pos)); if (display != null) display.discard();
|
&& chunk.hasData(DATA)
|
||||||
|
&& chunk.getData(DATA).remove(pos.asLong()) != null) chunk.markUnsaved();
|
||||||
|
var display = ACTIVE.remove(new Position(level, pos));
|
||||||
|
if (display != null) display.discard();
|
||||||
}
|
}
|
||||||
@SubscribeEvent public static void load(ChunkEvent.Load event) {
|
|
||||||
if (!(event.getLevel() instanceof ServerLevel level) || !(event.getChunk() instanceof LevelChunk chunk)) return;
|
@SubscribeEvent
|
||||||
level.getServer().execute(() -> {
|
public static void load(ChunkEvent.Load event) {
|
||||||
if (level.getChunkSource().getChunkNow(chunk.getPos().x(),chunk.getPos().z()) != chunk || !chunk.hasData(DATA)) return;
|
if (!(event.getLevel() instanceof ServerLevel level)
|
||||||
chunk.getData(DATA).forEach((packed,code) -> {
|
|| !(event.getChunk() instanceof LevelChunk chunk)) return;
|
||||||
|
level.getServer()
|
||||||
|
.execute(
|
||||||
|
() -> {
|
||||||
|
if (level.getChunkSource()
|
||||||
|
.getChunkNow(
|
||||||
|
chunk.getPos().x(), chunk.getPos().z())
|
||||||
|
!= chunk
|
||||||
|
|| !chunk.hasData(DATA)) return;
|
||||||
|
chunk.getData(DATA)
|
||||||
|
.forEach(
|
||||||
|
(packed, code) -> {
|
||||||
var pos = BlockPos.of(packed);
|
var pos = BlockPos.of(packed);
|
||||||
if (pos.getX() >> 4 == chunk.getPos().x() && pos.getZ() >> 4 == chunk.getPos().z())
|
if (pos.getX() >> 4 == chunk.getPos().x()
|
||||||
ACTIVE.putIfAbsent(new Position(level,pos),null);
|
&& pos.getZ() >> 4 == chunk.getPos().z())
|
||||||
|
ACTIVE.putIfAbsent(
|
||||||
|
new Position(level, pos), null);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@SubscribeEvent public static void unload(ChunkEvent.Unload event) {
|
|
||||||
for (var key : new ArrayList<>(ACTIVE.keySet())) if (key.level == event.getLevel()
|
@SubscribeEvent
|
||||||
&& key.pos.getX() >> 4 == event.getChunk().getPos().x() && key.pos.getZ() >> 4 == event.getChunk().getPos().z()) {
|
public static void unload(ChunkEvent.Unload event) {
|
||||||
var display = ACTIVE.remove(key); if (display != null) display.discard();
|
for (var key : new ArrayList<>(ACTIVE.keySet()))
|
||||||
|
if (key.level == event.getLevel()
|
||||||
|
&& key.pos.getX() >> 4 == event.getChunk().getPos().x()
|
||||||
|
&& key.pos.getZ() >> 4 == event.getChunk().getPos().z()) {
|
||||||
|
var display = ACTIVE.remove(key);
|
||||||
|
if (display != null) display.discard();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@SubscribeEvent public static void stopped(ServerStoppedEvent event) {
|
|
||||||
ACTIVE.values().stream().filter(Objects::nonNull).forEach(RailDisplay::discard); ACTIVE.clear(); REMOVED.clear();
|
@SubscribeEvent
|
||||||
|
public static void stopped(ServerStoppedEvent event) {
|
||||||
|
ACTIVE.values().stream().filter(Objects::nonNull).forEach(RailDisplay::discard);
|
||||||
|
ACTIVE.clear();
|
||||||
|
REMOVED.clear();
|
||||||
}
|
}
|
||||||
@SubscribeEvent public static void tick(ServerTickEvent.Post event) {
|
|
||||||
|
@SubscribeEvent
|
||||||
|
public static void tick(ServerTickEvent.Post event) {
|
||||||
for (var key : new ArrayList<>(ACTIVE.keySet())) {
|
for (var key : new ArrayList<>(ACTIVE.keySet())) {
|
||||||
var state = key.level.getBlockState(key.pos); var kind = find(key.level,key.pos);
|
var state = key.level.getBlockState(key.pos);
|
||||||
if (kind == null || !state.is(Blocks.POWERED_RAIL)) { clear(key.level,key.pos); continue; }
|
var kind = find(key.level, key.pos);
|
||||||
|
if (kind == null || !state.is(Blocks.POWERED_RAIL)) {
|
||||||
|
clear(key.level, key.pos);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (RailOxidation.advance(key.level, key.pos, kind)) {
|
if (RailOxidation.advance(key.level, key.pos, kind)) {
|
||||||
kind = new RailKind(kind.age()+1,false); put(key.level,key.pos,kind);
|
kind = new RailKind(kind.age() + 1, false);
|
||||||
|
put(key.level, key.pos, kind);
|
||||||
}
|
}
|
||||||
var display = ACTIVE.get(key);
|
var display = ACTIVE.get(key);
|
||||||
if (display == null || display.isRemoved()) {
|
if (display == null || display.isRemoved()) {
|
||||||
display = new RailDisplay(key.level,key.pos); display.update(kind,state);
|
display = new RailDisplay(key.level, key.pos);
|
||||||
|
display.update(kind, state);
|
||||||
if (key.level.addFreshEntity(display)) ACTIVE.put(key, display);
|
if (key.level.addFreshEntity(display)) ACTIVE.put(key, display);
|
||||||
} else display.update(kind, state);
|
} else display.update(kind, state);
|
||||||
}
|
}
|
||||||
REMOVED.entrySet().removeIf(entry -> entry.getValue().tick < entry.getKey().level.getGameTime());
|
REMOVED.entrySet()
|
||||||
|
.removeIf(entry -> entry.getValue().tick < entry.getKey().level.getGameTime());
|
||||||
}
|
}
|
||||||
@SubscribeEvent public static void use(PlayerInteractEvent.RightClickBlock event) {
|
|
||||||
|
@SubscribeEvent
|
||||||
|
public static void use(PlayerInteractEvent.RightClickBlock event) {
|
||||||
if (!(event.getLevel() instanceof ServerLevel level)) return;
|
if (!(event.getLevel() instanceof ServerLevel level)) return;
|
||||||
var kind = find(level,event.getPos()); if (kind == null) return;
|
var kind = find(level, event.getPos());
|
||||||
var item = event.getItemStack(); RailKind next;
|
if (kind == null) return;
|
||||||
|
var item = event.getItemStack();
|
||||||
|
RailKind next;
|
||||||
int effect;
|
int effect;
|
||||||
if (item.is(Items.HONEYCOMB) && !kind.waxed()) { next = new RailKind(kind.age(),true); effect=3003; }
|
if (item.is(Items.HONEYCOMB) && !kind.waxed()) {
|
||||||
else if (item.getItem() instanceof AxeItem && (kind.waxed() || kind.age()>0)) {
|
next = new RailKind(kind.age(), true);
|
||||||
next = kind.waxed() ? new RailKind(kind.age(),false) : new RailKind(kind.age()-1,false); effect=kind.waxed()?3004:3005;
|
effect = 3003;
|
||||||
|
} else if (item.getItem() instanceof AxeItem && (kind.waxed() || kind.age() > 0)) {
|
||||||
|
next =
|
||||||
|
kind.waxed()
|
||||||
|
? new RailKind(kind.age(), false)
|
||||||
|
: new RailKind(kind.age() - 1, false);
|
||||||
|
effect = kind.waxed() ? 3004 : 3005;
|
||||||
} else return;
|
} else return;
|
||||||
if (!event.getEntity().mayBuild()) return;
|
if (!event.getEntity().mayBuild()) return;
|
||||||
put(level,event.getPos(),next); level.levelEvent(null,effect,event.getPos(),0);
|
put(level, event.getPos(), next);
|
||||||
|
level.levelEvent(null, effect, event.getPos(), 0);
|
||||||
if (item.is(Items.HONEYCOMB)) item.consume(1, event.getEntity());
|
if (item.is(Items.HONEYCOMB)) item.consume(1, event.getEntity());
|
||||||
else item.hurtAndBreak(1, event.getEntity(), event.getHand().asEquipmentSlot());
|
else item.hurtAndBreak(1, event.getEntity(), event.getHand().asEquipmentSlot());
|
||||||
event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS);
|
event.setCanceled(true);
|
||||||
|
event.setCancellationResult(InteractionResult.SUCCESS);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package online.astradev.content.train;
|
package online.astradev.content.train;
|
||||||
|
|
||||||
import net.minecraft.world.phys.Vec3;
|
import net.minecraft.world.phys.Vec3;
|
||||||
|
|
||||||
public interface CartFrame {
|
public interface CartFrame {
|
||||||
Vec3 astracontent$front();
|
Vec3 astracontent$front();
|
||||||
|
|
||||||
void astracontent$front(Vec3 axis);
|
void astracontent$front(Vec3 axis);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,49 @@
|
|||||||
package online.astradev.content.train;
|
package online.astradev.content.train;
|
||||||
|
|
||||||
import com.mojang.math.Transformation;
|
import com.mojang.math.Transformation;
|
||||||
|
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.world.entity.Display;
|
import net.minecraft.world.entity.Display;
|
||||||
import net.minecraft.world.entity.EntityTypes;
|
import net.minecraft.world.entity.EntityTypes;
|
||||||
import net.minecraft.world.level.block.state.BlockState;
|
import net.minecraft.world.level.block.state.BlockState;
|
||||||
import net.minecraft.world.level.storage.ValueOutput;
|
import net.minecraft.world.level.storage.ValueOutput;
|
||||||
import net.minecraft.world.phys.Vec3;
|
import net.minecraft.world.phys.Vec3;
|
||||||
|
|
||||||
import org.joml.*;
|
import org.joml.*;
|
||||||
|
|
||||||
public final class ChainDisplay extends Display.BlockDisplay {
|
public final class ChainDisplay extends Display.BlockDisplay {
|
||||||
public ChainDisplay(ServerLevel level, BlockState chain) {
|
public ChainDisplay(ServerLevel level, BlockState chain) {
|
||||||
super(EntityTypes.BLOCK_DISPLAY,level);setBlockState(chain);setNoGravity(true);setInvulnerable(true);setSilent(true);
|
super(EntityTypes.BLOCK_DISPLAY, level);
|
||||||
setPosRotInterpolationDuration(1);setTransformationInterpolationDuration(1);
|
setBlockState(chain);
|
||||||
|
setNoGravity(true);
|
||||||
|
setInvulnerable(true);
|
||||||
|
setSilent(true);
|
||||||
|
setPosRotInterpolationDuration(1);
|
||||||
|
setTransformationInterpolationDuration(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void update(Vec3 a, Vec3 b) {
|
public void update(Vec3 a, Vec3 b) {
|
||||||
Vec3 delta=b.subtract(a);float length=(float)delta.length();if(length<.02)return;
|
Vec3 delta = b.subtract(a);
|
||||||
var rotation=new Quaternionf().rotateTo(new Vector3f(0,1,0),delta.normalize().toVector3f());
|
float length = (float) delta.length();
|
||||||
|
if (length < .02) return;
|
||||||
|
var rotation =
|
||||||
|
new Quaternionf().rotateTo(new Vector3f(0, 1, 0), delta.normalize().toVector3f());
|
||||||
var translation = new Vector3f(-.5f, -length / 2, -.5f).rotate(rotation);
|
var translation = new Vector3f(-.5f, -length / 2, -.5f).rotate(rotation);
|
||||||
Vec3 mid=a.add(b).scale(.5);setPos(mid);
|
Vec3 mid = a.add(b).scale(.5);
|
||||||
setTransformation(new Transformation(translation,rotation,new Vector3f(1,length,1),new Quaternionf()));
|
setPos(mid);
|
||||||
|
setTransformation(
|
||||||
|
new Transformation(
|
||||||
|
translation, rotation, new Vector3f(1, length, 1), new Quaternionf()));
|
||||||
setTransformationInterpolationDelay(0);
|
setTransformationInterpolationDelay(0);
|
||||||
}
|
}
|
||||||
@Override public boolean shouldBeSaved(){return false;}
|
|
||||||
@Override public boolean saveAsPassenger(ValueOutput output){return false;}
|
@Override
|
||||||
|
public boolean shouldBeSaved() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean saveAsPassenger(ValueOutput output) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,24 +6,50 @@ import net.minecraft.world.phys.Vec3;
|
|||||||
|
|
||||||
public final class CouplingGeometry {
|
public final class CouplingGeometry {
|
||||||
private CouplingGeometry() {}
|
private CouplingGeometry() {}
|
||||||
|
|
||||||
public static Vec3 axis(AbstractMinecart cart) {
|
public static Vec3 axis(AbstractMinecart cart) {
|
||||||
var frame=(CartFrame)cart;var previous=frame.astracontent$front();
|
var frame = (CartFrame) cart;
|
||||||
|
var previous = frame.astracontent$front();
|
||||||
double yaw = Math.toRadians(cart.getYRot());
|
double yaw = Math.toRadians(cart.getYRot());
|
||||||
if(previous.lengthSqr()<.5)previous=new Vec3(Math.cos(yaw),0,Math.sin(yaw)*(AbstractMinecart.useExperimentalMovement(cart.level())?-1:1));
|
if (previous.lengthSqr() < .5)
|
||||||
var pos=cart.getCurrentBlockPosOrRailBelow();var state=cart.level().getBlockState(pos);
|
previous =
|
||||||
|
new Vec3(
|
||||||
|
Math.cos(yaw),
|
||||||
|
0,
|
||||||
|
Math.sin(yaw)
|
||||||
|
* (AbstractMinecart.useExperimentalMovement(cart.level())
|
||||||
|
? -1
|
||||||
|
: 1));
|
||||||
|
var pos = cart.getCurrentBlockPosOrRailBelow();
|
||||||
|
var state = cart.level().getBlockState(pos);
|
||||||
Vec3 axis = previous;
|
Vec3 axis = previous;
|
||||||
if (state.getBlock() instanceof BaseRailBlock rail) {
|
if (state.getBlock() instanceof BaseRailBlock rail) {
|
||||||
var exits=AbstractMinecart.exits(rail.getRailDirection(state,cart.level(),pos,cart));
|
var exits =
|
||||||
axis=new Vec3(exits.getSecond().getX()-exits.getFirst().getX(),0,exits.getSecond().getZ()-exits.getFirst().getZ()).normalize();
|
AbstractMinecart.exits(rail.getRailDirection(state, cart.level(), pos, cart));
|
||||||
|
axis =
|
||||||
|
new Vec3(
|
||||||
|
exits.getSecond().getX() - exits.getFirst().getX(),
|
||||||
|
0,
|
||||||
|
exits.getSecond().getZ() - exits.getFirst().getZ())
|
||||||
|
.normalize();
|
||||||
if (axis.dot(previous) < 0) axis = axis.scale(-1);
|
if (axis.dot(previous) < 0) axis = axis.scale(-1);
|
||||||
}
|
}
|
||||||
frame.astracontent$front(axis);return axis;
|
frame.astracontent$front(axis);
|
||||||
|
return axis;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int hitEnd(Vec3 axis, Vec3 localHit) {
|
public static int hitEnd(Vec3 axis, Vec3 localHit) {
|
||||||
double along = localHit.horizontal().dot(axis);
|
double along = localHit.horizontal().dot(axis);
|
||||||
double across = Math.abs(localHit.x * axis.z - localHit.z * axis.x);
|
double across = Math.abs(localHit.x * axis.z - localHit.z * axis.x);
|
||||||
return Math.abs(along)>=.32 && Math.abs(along)>across*1.3?(along>0?0:1):-1;
|
if (Math.abs(along) < .32 || Math.abs(along) <= across * 1.3) return -1;
|
||||||
|
return along > 0 ? 0 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Vec3 outward(AbstractMinecart cart, int end) {
|
||||||
|
return axis(cart).scale(end == 0 ? 1 : -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Vec3 anchor(AbstractMinecart cart, int end) {
|
||||||
|
return cart.position().add(0, .35, 0).add(outward(cart, end).scale(.48));
|
||||||
}
|
}
|
||||||
public static Vec3 outward(AbstractMinecart cart,int end){return axis(cart).scale(end==0?1:-1);}
|
|
||||||
public static Vec3 anchor(AbstractMinecart cart,int end){return cart.position().add(0,.35,0).add(outward(cart,end).scale(.48));}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,37 +2,105 @@ package online.astradev.content.train;
|
|||||||
|
|
||||||
import com.mojang.serialization.Codec;
|
import com.mojang.serialization.Codec;
|
||||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||||
import java.util.*;
|
|
||||||
import net.minecraft.resources.Identifier;
|
import net.minecraft.resources.Identifier;
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.world.level.saveddata.*;
|
import net.minecraft.world.level.saveddata.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
/** One authoritative record per chain, including unloaded carts. No duplicated refunds. */
|
/** One authoritative record per chain, including unloaded carts. No duplicated refunds. */
|
||||||
public final class TrainData extends SavedData {
|
public final class TrainData extends SavedData {
|
||||||
public record Link(UUID a,int endA,UUID b,int endB,String item,boolean paid,double length) {
|
public record Link(
|
||||||
private static final Codec<UUID> UUID_CODEC=Codec.STRING.xmap(UUID::fromString,UUID::toString);
|
UUID a, int endA, UUID b, int endB, String item, boolean paid, double length) {
|
||||||
static final Codec<Link> CODEC=RecordCodecBuilder.create(i->i.group(
|
private static final Codec<UUID> UUID_CODEC =
|
||||||
UUID_CODEC.fieldOf("a").forGetter(Link::a),Codec.intRange(0,1).fieldOf("end_a").forGetter(Link::endA),
|
Codec.STRING.xmap(UUID::fromString, UUID::toString);
|
||||||
UUID_CODEC.fieldOf("b").forGetter(Link::b),Codec.intRange(0,1).fieldOf("end_b").forGetter(Link::endB),
|
static final Codec<Link> CODEC =
|
||||||
Codec.STRING.fieldOf("item").forGetter(Link::item),Codec.BOOL.fieldOf("paid").forGetter(Link::paid),
|
RecordCodecBuilder.create(
|
||||||
Codec.doubleRange(1,4).fieldOf("length").forGetter(Link::length)).apply(i,Link::new));
|
i ->
|
||||||
public boolean touches(UUID id){return a.equals(id)||b.equals(id);}
|
i.group(
|
||||||
public UUID other(UUID id){return a.equals(id)?b:a;}
|
UUID_CODEC.fieldOf("a").forGetter(Link::a),
|
||||||
public int end(UUID id){return a.equals(id)?endA:endB;}
|
Codec.intRange(0, 1)
|
||||||
|
.fieldOf("end_a")
|
||||||
|
.forGetter(Link::endA),
|
||||||
|
UUID_CODEC.fieldOf("b").forGetter(Link::b),
|
||||||
|
Codec.intRange(0, 1)
|
||||||
|
.fieldOf("end_b")
|
||||||
|
.forGetter(Link::endB),
|
||||||
|
Codec.STRING.fieldOf("item").forGetter(Link::item),
|
||||||
|
Codec.BOOL.fieldOf("paid").forGetter(Link::paid),
|
||||||
|
Codec.doubleRange(1, 4)
|
||||||
|
.fieldOf("length")
|
||||||
|
.forGetter(Link::length))
|
||||||
|
.apply(i, Link::new));
|
||||||
|
|
||||||
|
public boolean touches(UUID id) {
|
||||||
|
return a.equals(id) || b.equals(id);
|
||||||
}
|
}
|
||||||
private static final Codec<TrainData> CODEC=Link.CODEC.listOf().xmap(TrainData::new,d->List.copyOf(d.links)).fieldOf("links").codec();
|
|
||||||
private static final SavedDataType<TrainData> TYPE=new SavedDataType<>(Identifier.fromNamespaceAndPath("astracontent","trains"),TrainData::new,CODEC);
|
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 SavedDataType<TrainData> TYPE =
|
||||||
|
new SavedDataType<>(
|
||||||
|
Identifier.fromNamespaceAndPath("astracontent", "trains"),
|
||||||
|
TrainData::new,
|
||||||
|
CODEC);
|
||||||
private final List<Link> links = new ArrayList<>();
|
private final List<Link> links = new ArrayList<>();
|
||||||
|
|
||||||
public TrainData() {}
|
public TrainData() {}
|
||||||
private TrainData(List<Link> links){this.links.addAll(links);}
|
|
||||||
public static TrainData get(ServerLevel level){return level.getDataStorage().computeIfAbsent(TYPE);}
|
private TrainData(List<Link> links) {
|
||||||
public List<Link> links(){return List.copyOf(links);}
|
this.links.addAll(links);
|
||||||
public Link at(UUID cart,int end){return links.stream().filter(l->l.touches(cart)&&l.end(cart)==end).findFirst().orElse(null);}
|
}
|
||||||
public void add(Link link){links.add(link);setDirty();}
|
|
||||||
public boolean remove(Link link){boolean removed=links.remove(link);if(removed)setDirty();return removed;}
|
public static TrainData get(ServerLevel level) {
|
||||||
|
return level.getDataStorage().computeIfAbsent(TYPE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Link> links() {
|
||||||
|
return List.copyOf(links);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Link at(UUID cart, int end) {
|
||||||
|
return links.stream()
|
||||||
|
.filter(l -> l.touches(cart) && l.end(cart) == end)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void add(Link link) {
|
||||||
|
links.add(link);
|
||||||
|
setDirty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean remove(Link link) {
|
||||||
|
boolean removed = links.remove(link);
|
||||||
|
if (removed) setDirty();
|
||||||
|
return removed;
|
||||||
|
}
|
||||||
|
|
||||||
public Set<UUID> component(UUID root) {
|
public Set<UUID> component(UUID root) {
|
||||||
var seen=new HashSet<UUID>();var pending=new ArrayDeque<UUID>();pending.add(root);
|
var seen = new HashSet<UUID>();
|
||||||
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 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));
|
||||||
|
}
|
||||||
return seen;
|
return seen;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package online.astradev.content.train;
|
package online.astradev.content.train;
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
import net.minecraft.core.registries.BuiltInRegistries;
|
import net.minecraft.core.registries.BuiltInRegistries;
|
||||||
import net.minecraft.network.chat.Component;
|
import net.minecraft.network.chat.Component;
|
||||||
import net.minecraft.resources.Identifier;
|
import net.minecraft.resources.Identifier;
|
||||||
@@ -19,166 +18,374 @@ import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
|||||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
public final class Trains {
|
public final class Trains {
|
||||||
private record DisplayKey(ServerLevel level, TrainData.Link link) {}
|
private record DisplayKey(ServerLevel level, TrainData.Link link) {}
|
||||||
|
|
||||||
private static final Map<DisplayKey, ChainDisplay> DISPLAYS = new HashMap<>();
|
private static final Map<DisplayKey, ChainDisplay> DISPLAYS = new HashMap<>();
|
||||||
private static final Map<ServerLevel, Set<UUID>> PAUSED = new HashMap<>();
|
private static final Map<ServerLevel, Set<UUID>> PAUSED = new HashMap<>();
|
||||||
private static final Map<ServerLevel, Set<UUID>> PLAYER_PUSHES = new HashMap<>();
|
private static final Map<ServerLevel, Set<UUID>> PLAYER_PUSHES = new HashMap<>();
|
||||||
|
|
||||||
private Trains() {}
|
private Trains() {}
|
||||||
public static boolean paused(AbstractMinecart cart){return PAUSED.getOrDefault(cart.level(),Set.of()).contains(cart.getUUID());}
|
|
||||||
public static void playerPush(AbstractMinecart cart){
|
public static boolean paused(AbstractMinecart cart) {
|
||||||
if(cart.level() instanceof ServerLevel level)PLAYER_PUSHES.computeIfAbsent(level,key->new HashSet<>()).add(cart.getUUID());
|
return PAUSED.getOrDefault(cart.level(), Set.of()).contains(cart.getUUID());
|
||||||
}
|
}
|
||||||
public static boolean isChain(ItemStack stack){return stack.getItem() instanceof BlockItem item && item.getBlock() instanceof ChainBlock;}
|
|
||||||
|
public static void playerPush(AbstractMinecart cart) {
|
||||||
|
if (cart.level() instanceof ServerLevel level)
|
||||||
|
PLAYER_PUSHES.computeIfAbsent(level, key -> new HashSet<>()).add(cart.getUUID());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isChain(ItemStack stack) {
|
||||||
|
return stack.getItem() instanceof BlockItem item && item.getBlock() instanceof ChainBlock;
|
||||||
|
}
|
||||||
|
|
||||||
public static boolean connected(AbstractMinecart a, AbstractMinecart b) {
|
public static boolean connected(AbstractMinecart a, AbstractMinecart b) {
|
||||||
return a.level() instanceof ServerLevel level && b.level()==level
|
return a.level() instanceof ServerLevel level
|
||||||
|
&& b.level() == level
|
||||||
&& TrainData.get(level).component(a.getUUID()).contains(b.getUUID());
|
&& TrainData.get(level).component(a.getUUID()).contains(b.getUUID());
|
||||||
}
|
}
|
||||||
@SubscribeEvent public static void interact(PlayerInteractEvent.EntityInteract event){
|
|
||||||
if(!(event.getTarget() instanceof AbstractMinecart cart) || !(cart.level() instanceof ServerLevel level)
|
@SubscribeEvent
|
||||||
|
public static void interact(PlayerInteractEvent.EntityInteract event) {
|
||||||
|
if (!(event.getTarget() instanceof AbstractMinecart cart)
|
||||||
|
|| !(cart.level() instanceof ServerLevel level)
|
||||||
|| !event.getEntity().isShiftKeyDown()) return;
|
|| !event.getEntity().isShiftKeyDown()) return;
|
||||||
var player=event.getEntity();var item=event.getItemStack();boolean chain=isChain(item);
|
var player = event.getEntity();
|
||||||
|
var item = event.getItemStack();
|
||||||
|
boolean chain = isChain(item);
|
||||||
if (!chain && !item.is(ItemTags.PICKAXES)) return;
|
if (!chain && !item.is(ItemTags.PICKAXES)) return;
|
||||||
event.setCanceled(true);event.setCancellationResult(InteractionResult.SUCCESS);
|
event.setCanceled(true);
|
||||||
|
event.setCancellationResult(InteractionResult.SUCCESS);
|
||||||
if (!player.mayBuild()) return;
|
if (!player.mayBuild()) return;
|
||||||
int end = CouplingGeometry.hitEnd(CouplingGeometry.axis(cart), event.getLocation());
|
int end = CouplingGeometry.hitEnd(CouplingGeometry.axis(cart), event.getLocation());
|
||||||
if(end<0){message(player,"Цепь крепится только к переднему или заднему торцу.");return;}
|
if (end < 0) {
|
||||||
var data=TrainData.get(level);var existing=data.at(cart.getUUID(),end);
|
message(player, "Цепь крепится только к переднему или заднему торцу.");
|
||||||
if(!chain){
|
return;
|
||||||
if(existing==null){message(player,"На этом торце нет цепи.");return;}
|
}
|
||||||
unlink(level,existing,cart,true);item.hurtAndBreak(1,player,event.getHand().asEquipmentSlot());return;
|
var data = TrainData.get(level);
|
||||||
|
var existing = data.at(cart.getUUID(), end);
|
||||||
|
if (!chain) {
|
||||||
|
if (existing == null) {
|
||||||
|
message(player, "На этом торце нет цепи.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unlink(level, existing, cart, true);
|
||||||
|
item.hurtAndBreak(1, player, event.getHand().asEquipmentSlot());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (existing != null) {
|
||||||
|
message(player, "Этот торец уже сцеплен.");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
if(existing!=null){message(player,"Этот торец уже сцеплен.");return;}
|
|
||||||
Vec3 outward = CouplingGeometry.outward(cart, end);
|
Vec3 outward = CouplingGeometry.outward(cart, end);
|
||||||
var candidates=level.getEntitiesOfClass(AbstractMinecart.class,cart.getBoundingBox().inflate(3.5),other->other!=cart && other.isAlive());
|
var candidates =
|
||||||
|
level.getEntitiesOfClass(
|
||||||
|
AbstractMinecart.class,
|
||||||
|
cart.getBoundingBox().inflate(3.5),
|
||||||
|
other -> other != cart && other.isAlive());
|
||||||
candidates.sort(Comparator.comparingDouble(cart::distanceToSqr));
|
candidates.sort(Comparator.comparingDouble(cart::distanceToSqr));
|
||||||
for (var other : candidates) {
|
for (var other : candidates) {
|
||||||
Vec3 between=other.position().subtract(cart.position());double distance=between.length();
|
Vec3 between = other.position().subtract(cart.position());
|
||||||
|
double distance = between.length();
|
||||||
if (distance < 1 || distance > 3.5 || Math.abs(between.y) > 1.5) continue;
|
if (distance < 1 || distance > 3.5 || Math.abs(between.y) > 1.5) continue;
|
||||||
var direction = between.horizontal().normalize();
|
var direction = between.horizontal().normalize();
|
||||||
if (direction.dot(outward) < .90) continue;
|
if (direction.dot(outward) < .90) continue;
|
||||||
int otherEnd = CouplingGeometry.axis(other).dot(direction) > 0 ? 1 : 0;
|
int otherEnd = CouplingGeometry.axis(other).dot(direction) > 0 ? 1 : 0;
|
||||||
if(CouplingGeometry.outward(other,otherEnd).dot(direction)>-.90 || data.at(other.getUUID(),otherEnd)!=null)continue;
|
if (CouplingGeometry.outward(other, otherEnd).dot(direction) > -.90
|
||||||
if(!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock)
|
|| data.at(other.getUUID(), otherEnd) != null) continue;
|
||||||
|| !(level.getBlockState(other.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock))continue;
|
if (!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock()
|
||||||
var hit=level.clip(new ClipContext(CouplingGeometry.anchor(cart,end),CouplingGeometry.anchor(other,otherEnd),ClipContext.Block.COLLIDER,ClipContext.Fluid.NONE,cart));
|
instanceof BaseRailBlock)
|
||||||
|
|| !(level.getBlockState(other.getCurrentBlockPosOrRailBelow()).getBlock()
|
||||||
|
instanceof BaseRailBlock)) 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;
|
if (hit.getType() != HitResult.Type.MISS) continue;
|
||||||
data.add(new TrainData.Link(cart.getUUID(),end,other.getUUID(),otherEnd,
|
data.add(
|
||||||
BuiltInRegistries.ITEM.getKey(item.getItem()).toString(),!player.hasInfiniteMaterials(),distance));
|
new TrainData.Link(
|
||||||
item.consume(1,player);message(player,"Вагонетки сцеплены.");return;
|
cart.getUUID(),
|
||||||
|
end,
|
||||||
|
other.getUUID(),
|
||||||
|
otherEnd,
|
||||||
|
BuiltInRegistries.ITEM.getKey(item.getItem()).toString(),
|
||||||
|
!player.hasInfiniteMaterials(),
|
||||||
|
distance));
|
||||||
|
item.consume(1, player);
|
||||||
|
message(player, "Вагонетки сцеплены.");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
message(player, "У этого торца нет подходящей свободной вагонетки в пределах 3,5 блока.");
|
message(player, "У этого торца нет подходящей свободной вагонетки в пределах 3,5 блока.");
|
||||||
}
|
}
|
||||||
private static void message(net.minecraft.world.entity.player.Player player,String text){if(player instanceof net.minecraft.server.level.ServerPlayer serverPlayer)serverPlayer.sendSystemMessage(Component.literal(text),true);}
|
|
||||||
|
private static void message(net.minecraft.world.entity.player.Player player, String text) {
|
||||||
|
if (player instanceof net.minecraft.server.level.ServerPlayer serverPlayer)
|
||||||
|
serverPlayer.sendSystemMessage(Component.literal(text), true);
|
||||||
|
}
|
||||||
|
|
||||||
public static void unlink(ServerLevel level, TrainData.Link link, Entity at, boolean refund) {
|
public static void unlink(ServerLevel level, TrainData.Link link, Entity at, boolean refund) {
|
||||||
if (!TrainData.get(level).remove(link)) return;
|
if (!TrainData.get(level).remove(link)) return;
|
||||||
discard(new DisplayKey(level, link));
|
discard(new DisplayKey(level, link));
|
||||||
if (refund && link.paid()) at.spawnAtLocation(level, new ItemStack(chainItem(link)));
|
if (refund && link.paid()) at.spawnAtLocation(level, new ItemStack(chainItem(link)));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Item chainItem(TrainData.Link link) {
|
private static Item chainItem(TrainData.Link link) {
|
||||||
var id=Identifier.tryParse(link.item());var item=id==null?Items.IRON_CHAIN:BuiltInRegistries.ITEM.getValue(id);
|
var id = Identifier.tryParse(link.item());
|
||||||
|
var item = id == null ? Items.IRON_CHAIN : BuiltInRegistries.ITEM.getValue(id);
|
||||||
return item != null && isChain(new ItemStack(item)) ? item : Items.IRON_CHAIN;
|
return item != null && isChain(new ItemStack(item)) ? item : Items.IRON_CHAIN;
|
||||||
}
|
}
|
||||||
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){
|
private static AbstractMinecart cart(ServerLevel level, UUID id) {
|
||||||
if(!(event.getEntity() instanceof AbstractMinecart cart) || !(event.getLevel() instanceof ServerLevel level))return;
|
return level.getEntity(id) instanceof AbstractMinecart cart && cart.isAlive() ? cart : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SubscribeEvent
|
||||||
|
public static void leave(EntityLeaveLevelEvent event) {
|
||||||
|
if (!(event.getEntity() instanceof AbstractMinecart cart)
|
||||||
|
|| !(event.getLevel() instanceof ServerLevel level)) return;
|
||||||
var reason = cart.getRemovalReason();
|
var reason = cart.getRemovalReason();
|
||||||
for(var link:TrainData.get(level).links())if(link.touches(cart.getUUID())){
|
for (var link : TrainData.get(level).links())
|
||||||
|
if (link.touches(cart.getUUID())) {
|
||||||
// Visibility/unload callbacks can run while vanilla iterates an entity section.
|
// Visibility/unload callbacks can run while vanilla iterates an entity section.
|
||||||
// Let the post-tick display pass remove those visuals outside that iteration.
|
// 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);
|
if (reason != null
|
||||||
|
&& (reason.shouldDestroy()
|
||||||
|
|| reason == Entity.RemovalReason.CHANGED_DIMENSION))
|
||||||
|
unlink(level, link, cart, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@SubscribeEvent public static void pre(ServerTickEvent.Pre event){for(var level:event.getServer().getAllLevels())step(level);}
|
|
||||||
/** Synchronize momentum along each cart's rail tangent; springs correct chain slack, never teleport carts. */
|
@SubscribeEvent
|
||||||
|
public static void pre(ServerTickEvent.Pre event) {
|
||||||
|
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) {
|
public static void step(ServerLevel level) {
|
||||||
var pausedCarts=new HashSet<UUID>();PAUSED.put(level,pausedCarts);
|
var pausedCarts = new HashSet<UUID>();
|
||||||
var playerPushes=PLAYER_PUSHES.remove(level);if(playerPushes==null)playerPushes=Set.of();
|
PAUSED.put(level, pausedCarts);
|
||||||
var data=TrainData.get(level);var links=data.links();var visited=new HashSet<UUID>();
|
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) {
|
for (var seed : links) {
|
||||||
if (visited.contains(seed.a())) continue;
|
if (visited.contains(seed.a())) continue;
|
||||||
var signs=new LinkedHashMap<UUID,Integer>();var pending=new ArrayDeque<UUID>();signs.put(seed.a(),1);pending.add(seed.a());
|
var signs = directions(seed.a(), links);
|
||||||
while(!pending.isEmpty()){
|
visited.addAll(signs.keySet());
|
||||||
var id=pending.removeFirst();
|
moveTrain(level, links, signs, pausedCarts, playerPushes);
|
||||||
for(var link:links)if(link.touches(id)){
|
|
||||||
var other=link.other(id);int sign=-signs.get(id)*(link.end(id)==0?1:-1)*(link.end(other)==0?1:-1);
|
|
||||||
if(!signs.containsKey(other)){signs.put(other,sign);pending.add(other);}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
visited.addAll(signs.keySet());var carts=new LinkedHashMap<UUID,AbstractMinecart>();
|
|
||||||
var axes=new HashMap<UUID,Vec3>();boolean paused=false;double momentum=0,limit=Double.MAX_VALUE;
|
private static void moveTrain(
|
||||||
double controlledMomentum=0;var controls=new HashSet<UUID>();
|
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, limit = Double.MAX_VALUE;
|
||||||
|
double controlledMomentum = 0;
|
||||||
|
var controls = new HashSet<UUID>();
|
||||||
for (var pair : signs.entrySet()) {
|
for (var pair : signs.entrySet()) {
|
||||||
var cart=cart(level,pair.getKey());if(cart==null){paused=true;continue;}carts.put(pair.getKey(),cart);
|
var cart = cart(level, pair.getKey());
|
||||||
Vec3 tangent=CouplingGeometry.axis(cart).scale(pair.getValue());axes.put(pair.getKey(),tangent);
|
if (cart == null) {
|
||||||
if(!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock))paused=true;
|
paused = true;
|
||||||
double scale=travelScale(cart);momentum+=cart.getDeltaMovement().dot(tangent)*scale;
|
continue;
|
||||||
if(playerPushes.contains(cart.getUUID()) || cart.getFirstPassenger() instanceof net.minecraft.server.level.ServerPlayer player
|
}
|
||||||
&& player.getLastClientMoveIntent().horizontalDistanceSqr()>0){
|
carts.put(pair.getKey(), cart);
|
||||||
controlledMomentum+=alignedSpeed(cart,tangent)*scale;controls.add(cart.getUUID());
|
Vec3 tangent = CouplingGeometry.axis(cart).scale(pair.getValue());
|
||||||
|
axes.put(pair.getKey(), tangent);
|
||||||
|
if (!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock()
|
||||||
|
instanceof BaseRailBlock)) 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));
|
limit = Math.min(limit, cart.getMaxSpeed(level));
|
||||||
}
|
}
|
||||||
if(carts.isEmpty())continue;
|
if (carts.isEmpty()) return;
|
||||||
if(paused){pausedCarts.addAll(carts.keySet());carts.values().forEach(c->c.setDeltaMovement(Vec3.ZERO));continue;}
|
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
|
// 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.
|
// the tiny vanilla rider impulse; a dot product also erased side-on walking pushes.
|
||||||
double speed=Math.clamp(!controls.isEmpty()?controlledMomentum/controls.size():momentum/carts.size(),-limit,limit);
|
double speed =
|
||||||
|
Math.clamp(
|
||||||
|
!controls.isEmpty()
|
||||||
|
? controlledMomentum / controls.size()
|
||||||
|
: momentum / carts.size(),
|
||||||
|
-limit,
|
||||||
|
limit);
|
||||||
var corrections = new HashMap<UUID, Double>();
|
var corrections = new HashMap<UUID, Double>();
|
||||||
for(var link:links)if(carts.containsKey(link.a()) && carts.containsKey(link.b())){
|
for (var link : links)
|
||||||
var a=carts.get(link.a());var b=carts.get(link.b());double distance=a.position().distanceTo(b.position());
|
if (carts.containsKey(link.a()) && carts.containsKey(link.b())) {
|
||||||
if(distance>6){unlink(level,link,a,true);continue;}
|
var a = carts.get(link.a());
|
||||||
|
var b = carts.get(link.b());
|
||||||
|
double distance = a.position().distanceTo(b.position());
|
||||||
|
if (distance > 6) {
|
||||||
|
unlink(level, link, a, true);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
double pull = Math.clamp((distance - link.length()) * .22, -.18, .18);
|
double pull = Math.clamp((distance - link.length()) * .22, -.18, .18);
|
||||||
double direction = signs.get(link.a()) * (link.endA() == 0 ? 1 : -1);
|
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);
|
corrections.merge(link.a(), pull * direction, Double::sum);
|
||||||
|
corrections.merge(link.b(), -pull * direction, Double::sum);
|
||||||
}
|
}
|
||||||
for (var pair : carts.entrySet()) {
|
for (var pair : carts.entrySet()) {
|
||||||
// Followers take up slack; pulling back the driven cart would cancel its 0.001 rider impulse.
|
// Followers take up slack; pulling back the driven cart would cancel its 0.001
|
||||||
var cart=pair.getValue();double value=Math.clamp(speed+(controls.contains(pair.getKey())?0:corrections.getOrDefault(pair.getKey(),0.0)),-limit,limit);
|
// rider impulse.
|
||||||
|
var cart = pair.getValue();
|
||||||
|
double value =
|
||||||
|
Math.clamp(
|
||||||
|
speed
|
||||||
|
+ (controls.contains(pair.getKey())
|
||||||
|
? 0
|
||||||
|
: corrections.getOrDefault(pair.getKey(), 0.0)),
|
||||||
|
-limit,
|
||||||
|
limit);
|
||||||
var velocity = axes.get(pair.getKey()).scale(value / travelScale(cart));
|
var velocity = axes.get(pair.getKey()).scale(value / travelScale(cart));
|
||||||
cart.setDeltaMovement(velocity.x, cart.getDeltaMovement().y, velocity.z);
|
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);
|
||||||
}
|
}
|
||||||
private static double travelScale(AbstractMinecart cart){return !AbstractMinecart.useExperimentalMovement(cart.level())&&cart.isVehicle()?.75:1;}
|
}
|
||||||
|
return signs;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean playerControls(AbstractMinecart cart, Set<UUID> pushes) {
|
||||||
|
if (pushes.contains(cart.getUUID())) return true;
|
||||||
|
if (!(cart.getFirstPassenger() instanceof net.minecraft.server.level.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) {
|
private static double alignedSpeed(AbstractMinecart cart, Vec3 tangent) {
|
||||||
var movement=cart.getDeltaMovement();double along=movement.dot(tangent);
|
var movement = cart.getDeltaMovement();
|
||||||
|
double along = movement.dot(tangent);
|
||||||
if (Math.abs(along) < 1e-9) {
|
if (Math.abs(along) < 1e-9) {
|
||||||
var pos=cart.getCurrentBlockPosOrRailBelow();var state=cart.level().getBlockState(pos);
|
var pos = cart.getCurrentBlockPosOrRailBelow();
|
||||||
|
var state = cart.level().getBlockState(pos);
|
||||||
if (state.getBlock() instanceof BaseRailBlock rail) {
|
if (state.getBlock() instanceof BaseRailBlock rail) {
|
||||||
var exits=AbstractMinecart.exits(rail.getRailDirection(state,cart.level(),pos,cart));
|
var exits =
|
||||||
var nativeAxis=new Vec3(exits.getSecond()).subtract(new Vec3(exits.getFirst())).horizontal();
|
AbstractMinecart.exits(
|
||||||
// Vanilla chooses the opposite default exit for a perpendicular input in the new engine.
|
rail.getRailDirection(state, cart.level(), pos, cart));
|
||||||
along=nativeAxis.dot(tangent)*(AbstractMinecart.useExperimentalMovement(cart.level())?-1:1);
|
var nativeAxis =
|
||||||
|
new Vec3(exits.getSecond())
|
||||||
|
.subtract(new Vec3(exits.getFirst()))
|
||||||
|
.horizontal();
|
||||||
|
// Vanilla chooses the opposite default exit for a perpendicular input in the new
|
||||||
|
// engine.
|
||||||
|
along =
|
||||||
|
nativeAxis.dot(tangent)
|
||||||
|
* (AbstractMinecart.useExperimentalMovement(cart.level()) ? -1 : 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Math.copySign(movement.horizontalDistance(), along);
|
return Math.copySign(movement.horizontalDistance(), along);
|
||||||
}
|
}
|
||||||
@SubscribeEvent public static void post(ServerTickEvent.Post event){for(var level:event.getServer().getAllLevels())show(level);}
|
|
||||||
|
@SubscribeEvent
|
||||||
|
public static void post(ServerTickEvent.Post event) {
|
||||||
|
for (var level : event.getServer().getAllLevels()) show(level);
|
||||||
|
}
|
||||||
|
|
||||||
public static void show(ServerLevel level) {
|
public static void show(ServerLevel level) {
|
||||||
var keys = new HashSet<DisplayKey>();
|
var keys = new HashSet<DisplayKey>();
|
||||||
for (var link : TrainData.get(level).links()) {
|
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 a = cart(level, link.a());
|
||||||
var key=new DisplayKey(level,link);keys.add(key);var display=DISPLAYS.get(key);
|
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);
|
||||||
if (display == null || display.isRemoved()) {
|
if (display == null || display.isRemoved()) {
|
||||||
display=new ChainDisplay(level,((BlockItem)chainItem(link)).getBlock().defaultBlockState());
|
display =
|
||||||
display.update(CouplingGeometry.anchor(a,link.endA()),CouplingGeometry.anchor(b,link.endB()));
|
new ChainDisplay(
|
||||||
|
level,
|
||||||
|
((BlockItem) chainItem(link)).getBlock().defaultBlockState());
|
||||||
|
display.update(
|
||||||
|
CouplingGeometry.anchor(a, link.endA()),
|
||||||
|
CouplingGeometry.anchor(b, link.endB()));
|
||||||
if (level.addFreshEntity(display)) DISPLAYS.put(key, display);
|
if (level.addFreshEntity(display)) DISPLAYS.put(key, display);
|
||||||
}else display.update(CouplingGeometry.anchor(a,link.endA()),CouplingGeometry.anchor(b,link.endB()));
|
} else
|
||||||
|
display.update(
|
||||||
|
CouplingGeometry.anchor(a, link.endA()),
|
||||||
|
CouplingGeometry.anchor(b, link.endB()));
|
||||||
}
|
}
|
||||||
for(var key:new ArrayList<>(DISPLAYS.keySet()))if(key.level==level&&!keys.contains(key))discard(key);
|
for (var key : new ArrayList<>(DISPLAYS.keySet()))
|
||||||
|
if (key.level == level && !keys.contains(key)) discard(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void reverse(AbstractMinecart hit, Vec3 reflected) {
|
public static void reverse(AbstractMinecart hit, Vec3 reflected) {
|
||||||
if (!(hit.level() instanceof ServerLevel level)) return;
|
if (!(hit.level() instanceof ServerLevel level)) return;
|
||||||
var data=TrainData.get(level);var ids=data.component(hit.getUUID());
|
var data = TrainData.get(level);
|
||||||
if(ids.size()==1){hit.setDeltaMovement(reflected.scale(1/travelScale(hit)));return;}
|
var ids = data.component(hit.getUUID());
|
||||||
// Propagate reversal through the closed or open graph, preserving each cart's local travel direction.
|
if (ids.size() == 1) {
|
||||||
var signs=new HashMap<UUID,Integer>();var pending=new ArrayDeque<UUID>();signs.put(hit.getUUID(),1);pending.add(hit.getUUID());
|
hit.setDeltaMovement(reflected.scale(1 / travelScale(hit)));
|
||||||
while(!pending.isEmpty()){var id=pending.removeFirst();for(var link:data.links())if(link.touches(id)&&!signs.containsKey(link.other(id))){
|
return;
|
||||||
signs.put(link.other(id),-signs.get(id)*(link.end(id)==0?1:-1)*(link.end(link.other(id))==0?1:-1));pending.add(link.other(id));}}
|
}
|
||||||
|
// 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.axis(hit));
|
double speed = reflected.dot(CouplingGeometry.axis(hit));
|
||||||
for(var id:ids){var cart=cart(level,id);if(cart!=null){var v=CouplingGeometry.axis(cart).scale(speed*signs.getOrDefault(id,1)/travelScale(cart));cart.setDeltaMovement(v.x,cart.getDeltaMovement().y,v.z);}}
|
for (var id : ids) {
|
||||||
|
var cart = cart(level, id);
|
||||||
|
if (cart != null) {
|
||||||
|
var v =
|
||||||
|
CouplingGeometry.axis(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) {
|
||||||
|
for (var key : new ArrayList<>(DISPLAYS.keySet())) discard(key);
|
||||||
|
PAUSED.clear();
|
||||||
|
PLAYER_PUSHES.clear();
|
||||||
}
|
}
|
||||||
private static void discard(DisplayKey key){var display=DISPLAYS.remove(key);if(display!=null)display.discard();}
|
|
||||||
@SubscribeEvent public static void stop(ServerStoppedEvent event){for(var key:new ArrayList<>(DISPLAYS.keySet()))discard(key);PAUSED.clear();PLAYER_PUSHES.clear();}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package online.astradev.content.transport;
|
package online.astradev.content.transport;
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket;
|
import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket;
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
@@ -12,56 +11,105 @@ import net.minecraft.world.level.block.Blocks;
|
|||||||
import net.minecraft.world.phys.*;
|
import net.minecraft.world.phys.*;
|
||||||
import net.neoforged.bus.api.SubscribeEvent;
|
import net.neoforged.bus.api.SubscribeEvent;
|
||||||
import net.neoforged.neoforge.event.tick.EntityTickEvent;
|
import net.neoforged.neoforge.event.tick.EntityTickEvent;
|
||||||
|
|
||||||
import online.astradev.content.train.Trains;
|
import online.astradev.content.train.Trains;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
public final class SlimeBounce {
|
public final class SlimeBounce {
|
||||||
private static final Map<Entity, Vec3> PENDING = new WeakHashMap<>();
|
private static final Map<Entity, Vec3> PENDING = new WeakHashMap<>();
|
||||||
private static final Map<Entity, Vec3> BOAT_MOTION = new WeakHashMap<>();
|
private static final Map<Entity, Vec3> BOAT_MOTION = new WeakHashMap<>();
|
||||||
|
|
||||||
private SlimeBounce() {}
|
private SlimeBounce() {}
|
||||||
public static boolean supports(Entity entity){return entity.level() instanceof ServerLevel && (entity instanceof AbstractMinecart || entity instanceof AbstractBoat);}
|
|
||||||
|
public static boolean supports(Entity entity) {
|
||||||
|
return entity.level() instanceof ServerLevel
|
||||||
|
&& (entity instanceof AbstractMinecart || entity instanceof AbstractBoat);
|
||||||
|
}
|
||||||
|
|
||||||
public static void afterMove(Entity entity, Vec3 before, Vec3 requested, Vec3 incoming) {
|
public static void afterMove(Entity entity, Vec3 before, Vec3 requested, Vec3 incoming) {
|
||||||
if (!supports(entity) || entity.noPhysics) return;
|
if (!supports(entity) || entity.noPhysics) return;
|
||||||
Vec3 actual = entity.position().subtract(before);
|
Vec3 actual = entity.position().subtract(before);
|
||||||
boolean x=Math.abs(requested.x-actual.x)>.00001 && touchesSlime(entity,requested.x,0);
|
boolean x =
|
||||||
boolean z=Math.abs(requested.z-actual.z)>.00001 && touchesSlime(entity,0,requested.z);
|
Math.abs(requested.x - actual.x) > .00001 && touchesSlime(entity, requested.x, 0);
|
||||||
|
boolean z =
|
||||||
|
Math.abs(requested.z - actual.z) > .00001 && touchesSlime(entity, 0, requested.z);
|
||||||
if ((x || z) && requested.horizontalDistance() > .01) {
|
if ((x || z) && requested.horizontalDistance() > .01) {
|
||||||
// Experimental rail movement splits one tick into smaller moves at rail boundaries.
|
// Experimental rail movement splits one tick into smaller moves at rail boundaries.
|
||||||
if(entity instanceof AbstractMinecart cart && AbstractMinecart.useExperimentalMovement(cart.level()))
|
if (entity instanceof AbstractMinecart cart
|
||||||
|
&& AbstractMinecart.useExperimentalMovement(cart.level()))
|
||||||
requested = requested.horizontal().normalize().scale(incoming.horizontalDistance());
|
requested = requested.horizontal().normalize().scale(incoming.horizontalDistance());
|
||||||
Vec3 reflected=new Vec3(x?-requested.x:requested.x,entity.getDeltaMovement().y,z?-requested.z:requested.z);
|
Vec3 reflected =
|
||||||
PENDING.put(entity,reflected);entity.setDeltaMovement(reflected);
|
new Vec3(
|
||||||
|
x ? -requested.x : requested.x,
|
||||||
|
entity.getDeltaMovement().y,
|
||||||
|
z ? -requested.z : requested.z);
|
||||||
|
PENDING.put(entity, reflected);
|
||||||
|
entity.setDeltaMovement(reflected);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Check the actual contacted face, not nearby slime or the block beneath the vehicle. */
|
/** Check the actual contacted face, not nearby slime or the block beneath the vehicle. */
|
||||||
private static boolean touchesSlime(Entity entity, double dx, double dz) {
|
private static boolean touchesSlime(Entity entity, double dx, double dz) {
|
||||||
if (dx == 0 && dz == 0) return false;
|
if (dx == 0 && dz == 0) return false;
|
||||||
var box=entity.getBoundingBox();double eps=.015;
|
var box = entity.getBoundingBox();
|
||||||
double x0=dx>0?box.maxX+eps:dx<0?box.minX-eps:box.minX+eps;
|
double eps = .015;
|
||||||
|
double x0 = contactEdge(dx, box.minX, box.maxX, eps);
|
||||||
double x1 = dx != 0 ? x0 : box.maxX - eps;
|
double x1 = dx != 0 ? x0 : box.maxX - eps;
|
||||||
double z0=dz>0?box.maxZ+eps:dz<0?box.minZ-eps:box.minZ+eps;
|
double z0 = contactEdge(dz, box.minZ, box.maxZ, eps);
|
||||||
double z1 = dz != 0 ? z0 : box.maxZ - eps;
|
double z1 = dz != 0 ? z0 : box.maxZ - eps;
|
||||||
for(var pos:BlockPos.betweenClosed(BlockPos.containing(x0,box.minY+.05,z0),BlockPos.containing(x1,box.maxY-.05,z1)))
|
for (var pos :
|
||||||
if(entity.level().hasChunkAt(pos)&&entity.level().getBlockState(pos).is(Blocks.SLIME_BLOCK))return true;
|
BlockPos.betweenClosed(
|
||||||
|
BlockPos.containing(x0, box.minY + .05, z0),
|
||||||
|
BlockPos.containing(x1, box.maxY - .05, z1)))
|
||||||
|
if (entity.level().hasChunkAt(pos)
|
||||||
|
&& entity.level().getBlockState(pos).is(Blocks.SLIME_BLOCK)) return true;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@SubscribeEvent public static void afterTick(EntityTickEvent.Post event){flush(event.getEntity());}
|
|
||||||
|
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) {
|
public static void flush(Entity entity) {
|
||||||
var reflected=PENDING.remove(entity);if(reflected==null||entity.isRemoved())return;
|
var reflected = PENDING.remove(entity);
|
||||||
if(entity instanceof AbstractMinecart cart)Trains.reverse(cart,reflected);else entity.setDeltaMovement(reflected);
|
if (reflected == null || entity.isRemoved()) return;
|
||||||
|
if (entity instanceof AbstractMinecart cart) Trains.reverse(cart, reflected);
|
||||||
|
else entity.setDeltaMovement(reflected);
|
||||||
entity.hurtMarked = true;
|
entity.hurtMarked = true;
|
||||||
if(entity instanceof AbstractBoat)for(var passenger:entity.getPassengers())if(passenger instanceof ServerPlayer player)
|
if (entity instanceof AbstractBoat)
|
||||||
|
for (var passenger : entity.getPassengers())
|
||||||
|
if (passenger instanceof ServerPlayer player)
|
||||||
player.connection.send(new ClientboundSetEntityMotionPacket(entity));
|
player.connection.send(new ClientboundSetEntityMotionPacket(entity));
|
||||||
}
|
}
|
||||||
/** A vanilla player steers boats on the client. Detect its reported contact and return a vanilla impulse packet. */
|
|
||||||
|
/**
|
||||||
|
* 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) {
|
public static void boatPacket(Entity entity, Vec3 before) {
|
||||||
if (!(entity instanceof AbstractBoat) || !(entity.level() instanceof ServerLevel)) return;
|
if (!(entity instanceof AbstractBoat) || !(entity.level() instanceof ServerLevel)) return;
|
||||||
Vec3 motion=entity.position().subtract(before);Vec3 prior=BOAT_MOTION.getOrDefault(entity,motion);
|
Vec3 motion = entity.position().subtract(before);
|
||||||
|
Vec3 prior = BOAT_MOTION.getOrDefault(entity, motion);
|
||||||
Vec3 incoming = prior.horizontalDistance() > motion.horizontalDistance() ? prior : motion;
|
Vec3 incoming = prior.horizontalDistance() > motion.horizontalDistance() ? prior : motion;
|
||||||
boolean x = Math.abs(incoming.x) > .01 && touchesSlime(entity, incoming.x, 0);
|
boolean x = Math.abs(incoming.x) > .01 && touchesSlime(entity, incoming.x, 0);
|
||||||
boolean z = Math.abs(incoming.z) > .01 && touchesSlime(entity, 0, incoming.z);
|
boolean z = Math.abs(incoming.z) > .01 && touchesSlime(entity, 0, incoming.z);
|
||||||
if (x || z) {
|
if (x || z) {
|
||||||
var reflected=new Vec3(x?-incoming.x:incoming.x,entity.getDeltaMovement().y,z?-incoming.z:incoming.z);
|
var reflected =
|
||||||
PENDING.put(entity,reflected);BOAT_MOTION.put(entity,reflected);flush(entity);
|
new Vec3(
|
||||||
|
x ? -incoming.x : incoming.x,
|
||||||
|
entity.getDeltaMovement().y,
|
||||||
|
z ? -incoming.z : incoming.z);
|
||||||
|
PENDING.put(entity, reflected);
|
||||||
|
BOAT_MOTION.put(entity, reflected);
|
||||||
|
flush(entity);
|
||||||
} else BOAT_MOTION.put(entity, motion);
|
} else BOAT_MOTION.put(entity, motion);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package online.astradev.content.weapon;
|
package online.astradev.content.weapon;
|
||||||
|
|
||||||
import net.minecraft.core.component.DataComponents;
|
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.sounds.*;
|
import net.minecraft.sounds.*;
|
||||||
import net.minecraft.stats.Stats;
|
import net.minecraft.stats.Stats;
|
||||||
@@ -8,8 +7,8 @@ import net.minecraft.world.InteractionResult;
|
|||||||
import net.minecraft.world.entity.LivingEntity;
|
import net.minecraft.world.entity.LivingEntity;
|
||||||
import net.minecraft.world.entity.projectile.Projectile;
|
import net.minecraft.world.entity.projectile.Projectile;
|
||||||
import net.minecraft.world.entity.projectile.hurtingprojectile.SmallFireball;
|
import net.minecraft.world.entity.projectile.hurtingprojectile.SmallFireball;
|
||||||
import net.minecraft.world.entity.projectile.throwableitemprojectile.*;
|
|
||||||
import net.minecraft.world.entity.projectile.hurtingprojectile.windcharge.WindCharge;
|
import net.minecraft.world.entity.projectile.hurtingprojectile.windcharge.WindCharge;
|
||||||
|
import net.minecraft.world.entity.projectile.throwableitemprojectile.*;
|
||||||
import net.minecraft.world.item.*;
|
import net.minecraft.world.item.*;
|
||||||
import net.minecraft.world.level.Level;
|
import net.minecraft.world.level.Level;
|
||||||
import net.neoforged.bus.api.SubscribeEvent;
|
import net.neoforged.bus.api.SubscribeEvent;
|
||||||
@@ -17,11 +16,18 @@ import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
|||||||
|
|
||||||
public final class Ammunition {
|
public final class Ammunition {
|
||||||
private Ammunition() {}
|
private Ammunition() {}
|
||||||
|
|
||||||
public static boolean accepts(ItemStack stack) {
|
public static boolean accepts(ItemStack stack) {
|
||||||
return stack.is(Items.ENDER_PEARL) || stack.is(Items.FIRE_CHARGE) || stack.is(Items.ENDER_EYE)
|
return stack.is(Items.ENDER_PEARL)
|
||||||
|| stack.getItem() instanceof EggItem || stack.is(Items.SNOWBALL) || stack.is(Items.WIND_CHARGE)
|
|| stack.is(Items.FIRE_CHARGE)
|
||||||
|| stack.is(Items.EXPERIENCE_BOTTLE) || stack.is(Items.TNT);
|
|| stack.is(Items.ENDER_EYE)
|
||||||
|
|| stack.getItem() instanceof EggItem
|
||||||
|
|| stack.is(Items.SNOWBALL)
|
||||||
|
|| stack.is(Items.WIND_CHARGE)
|
||||||
|
|| stack.is(Items.EXPERIENCE_BOTTLE)
|
||||||
|
|| stack.is(Items.TNT);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Projectile create(Level level, LivingEntity owner, ItemStack ammo) {
|
public static Projectile create(Level level, LivingEntity owner, ItemStack ammo) {
|
||||||
if (ammo.is(Items.ENDER_PEARL)) return new ThrownEnderpearl(level, owner, ammo);
|
if (ammo.is(Items.ENDER_PEARL)) return new ThrownEnderpearl(level, owner, ammo);
|
||||||
if (ammo.getItem() instanceof EggItem) return new ThrownEgg(level, owner, ammo);
|
if (ammo.getItem() instanceof EggItem) return new ThrownEgg(level, owner, ammo);
|
||||||
@@ -29,25 +35,52 @@ public final class Ammunition {
|
|||||||
if (ammo.is(Items.EXPERIENCE_BOTTLE)) return new ThrownExperienceBottle(level, owner, ammo);
|
if (ammo.is(Items.EXPERIENCE_BOTTLE)) return new ThrownExperienceBottle(level, owner, ammo);
|
||||||
if (ammo.is(Items.FIRE_CHARGE)) {
|
if (ammo.is(Items.FIRE_CHARGE)) {
|
||||||
var fire = new SmallFireball(level, owner, owner.getLookAngle());
|
var fire = new SmallFireball(level, owner, owner.getLookAngle());
|
||||||
fire.setPos(owner.getX(), owner.getEyeY() - .15, owner.getZ()); fire.setItem(ammo); return fire;
|
fire.setPos(owner.getX(), owner.getEyeY() - .15, owner.getZ());
|
||||||
|
fire.setItem(ammo);
|
||||||
|
return fire;
|
||||||
}
|
}
|
||||||
if (ammo.is(Items.WIND_CHARGE)) {
|
if (ammo.is(Items.WIND_CHARGE)) {
|
||||||
var wind = new WindCharge(level, owner.getX(), owner.getEyeY() - .15, owner.getZ(), owner.getLookAngle());
|
var wind =
|
||||||
wind.setOwner(owner); return wind;
|
new WindCharge(
|
||||||
|
level,
|
||||||
|
owner.getX(),
|
||||||
|
owner.getEyeY() - .15,
|
||||||
|
owner.getZ(),
|
||||||
|
owner.getLookAngle());
|
||||||
|
wind.setOwner(owner);
|
||||||
|
return wind;
|
||||||
}
|
}
|
||||||
if (ammo.is(Items.TNT) || ammo.is(Items.ENDER_EYE)) return new PayloadProjectile(level, owner, ammo);
|
if (ammo.is(Items.TNT) || ammo.is(Items.ENDER_EYE))
|
||||||
|
return new PayloadProjectile(level, owner, ammo);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@SubscribeEvent public static void fireCharge(PlayerInteractEvent.RightClickItem event) {
|
|
||||||
if (!(event.getLevel() instanceof ServerLevel level) || !event.getItemStack().is(Items.FIRE_CHARGE)) return;
|
@SubscribeEvent
|
||||||
var player = event.getEntity(); var stack = event.getItemStack();
|
public static void fireCharge(PlayerInteractEvent.RightClickItem event) {
|
||||||
|
if (!(event.getLevel() instanceof ServerLevel level)
|
||||||
|
|| !event.getItemStack().is(Items.FIRE_CHARGE)) return;
|
||||||
|
var player = event.getEntity();
|
||||||
|
var stack = event.getItemStack();
|
||||||
if (player.getCooldowns().isOnCooldown(stack)) return;
|
if (player.getCooldowns().isOnCooldown(stack)) return;
|
||||||
var fire = create(level, player, stack);
|
var fire = create(level, player, stack);
|
||||||
Projectile.spawnProjectile(fire, level, stack, shot -> shot.shootFromRotation(player, player.getXRot(), player.getYRot(), 0, 1.5f, 1));
|
Projectile.spawnProjectile(
|
||||||
level.playSound(null, player.blockPosition(), SoundEvents.FIRECHARGE_USE, SoundSource.PLAYERS, 1, 1);
|
fire,
|
||||||
|
level,
|
||||||
|
stack,
|
||||||
|
shot ->
|
||||||
|
shot.shootFromRotation(
|
||||||
|
player, player.getXRot(), player.getYRot(), 0, 1.5f, 1));
|
||||||
|
level.playSound(
|
||||||
|
null,
|
||||||
|
player.blockPosition(),
|
||||||
|
SoundEvents.FIRECHARGE_USE,
|
||||||
|
SoundSource.PLAYERS,
|
||||||
|
1,
|
||||||
|
1);
|
||||||
player.getCooldowns().addCooldown(stack, 10);
|
player.getCooldowns().addCooldown(stack, 10);
|
||||||
player.awardStat(Stats.ITEM_USED.get(stack.getItem()));
|
player.awardStat(Stats.ITEM_USED.get(stack.getItem()));
|
||||||
stack.consume(1, player);
|
stack.consume(1, player);
|
||||||
event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS);
|
event.setCanceled(true);
|
||||||
|
event.setCancellationResult(InteractionResult.SUCCESS);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,20 +14,37 @@ import net.minecraft.world.phys.Vec3;
|
|||||||
/** One-tick shooting adapter; the payload itself is a vanilla entity understood by every client. */
|
/** One-tick shooting adapter; the payload itself is a vanilla entity understood by every client. */
|
||||||
public final class PayloadProjectile extends Snowball {
|
public final class PayloadProjectile extends Snowball {
|
||||||
public static final String NO_EYE_DROP = "astracontent:no_eye_drop";
|
public static final String NO_EYE_DROP = "astracontent:no_eye_drop";
|
||||||
public PayloadProjectile(Level level, LivingEntity owner, ItemStack stack) { super(level, owner, stack); }
|
|
||||||
@Override public void tick() {
|
public PayloadProjectile(Level level, LivingEntity owner, ItemStack stack) {
|
||||||
|
super(level, owner, stack);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void tick() {
|
||||||
if (!(level() instanceof ServerLevel level)) return;
|
if (!(level() instanceof ServerLevel level)) return;
|
||||||
if (getItem().is(Items.TNT)) {
|
if (getItem().is(Items.TNT)) {
|
||||||
var tnt = new PrimedTnt(level, getX(), getY(), getZ(), getOwner() instanceof LivingEntity living ? living : null);
|
var tnt =
|
||||||
tnt.setDeltaMovement(getDeltaMovement()); level.addFreshEntity(tnt);
|
new PrimedTnt(
|
||||||
|
level,
|
||||||
|
getX(),
|
||||||
|
getY(),
|
||||||
|
getZ(),
|
||||||
|
getOwner() instanceof LivingEntity living ? living : null);
|
||||||
|
tnt.setDeltaMovement(getDeltaMovement());
|
||||||
|
level.addFreshEntity(tnt);
|
||||||
} else {
|
} else {
|
||||||
var target = level.findNearestMapStructure(StructureTags.EYE_OF_ENDER_LOCATED, blockPosition(), 100, false);
|
var target =
|
||||||
|
level.findNearestMapStructure(
|
||||||
|
StructureTags.EYE_OF_ENDER_LOCATED, blockPosition(), 100, false);
|
||||||
if (target != null) {
|
if (target != null) {
|
||||||
var eye = new EyeOfEnder(level, getX(), getY(), getZ());
|
var eye = new EyeOfEnder(level, getX(), getY(), getZ());
|
||||||
eye.setItem(getItem());
|
eye.setItem(getItem());
|
||||||
if (getItem().has(DataComponents.INTANGIBLE_PROJECTILE)) eye.addTag(NO_EYE_DROP);
|
if (getItem().has(DataComponents.INTANGIBLE_PROJECTILE)) eye.addTag(NO_EYE_DROP);
|
||||||
eye.signalTo(Vec3.atLowerCornerOf(target)); eye.setDeltaMovement(getDeltaMovement()); level.addFreshEntity(eye);
|
eye.signalTo(Vec3.atLowerCornerOf(target));
|
||||||
} else if (!getItem().has(DataComponents.INTANGIBLE_PROJECTILE)) spawnAtLocation(level, getItem().copyWithCount(1));
|
eye.setDeltaMovement(getDeltaMovement());
|
||||||
|
level.addFreshEntity(eye);
|
||||||
|
} else if (!getItem().has(DataComponents.INTANGIBLE_PROJECTILE))
|
||||||
|
spawnAtLocation(level, getItem().copyWithCount(1));
|
||||||
}
|
}
|
||||||
discard();
|
discard();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,6 @@ side="SERVER"
|
|||||||
[[dependencies.astracontent]]
|
[[dependencies.astracontent]]
|
||||||
modId="astraplus"
|
modId="astraplus"
|
||||||
type="required"
|
type="required"
|
||||||
versionRange="[0.5.0,0.6)"
|
versionRange="[0.9,0.10)"
|
||||||
ordering="AFTER"
|
ordering="AFTER"
|
||||||
side="SERVER"
|
side="SERVER"
|
||||||
|
|||||||
@@ -1,42 +1,102 @@
|
|||||||
package online.astradev.content.rail;
|
package online.astradev.content.rail;
|
||||||
|
|
||||||
import com.google.gson.*;
|
|
||||||
import java.io.InputStreamReader;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
|
||||||
import org.joml.Vector3f;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import com.google.gson.*;
|
||||||
|
|
||||||
|
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||||
|
|
||||||
|
import org.joml.Vector3f;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
class RailDisplayTransformTest {
|
class RailDisplayTransformTest {
|
||||||
@Test void everyOverlayVertexMatchesNativeRailPlane()throws Exception{
|
@Test
|
||||||
for(int age=0;age<4;age++)for(boolean powered:new boolean[]{false,true})for(var shape:new RailShape[]{
|
void everyOverlayVertexMatchesNativeRailPlane() throws Exception {
|
||||||
RailShape.NORTH_SOUTH,RailShape.EAST_WEST,RailShape.ASCENDING_NORTH,RailShape.ASCENDING_SOUTH,RailShape.ASCENDING_EAST,RailShape.ASCENDING_WEST}){
|
for (int age = 0; age < 4; age++)
|
||||||
String path="/defaults/resources/assets/astracontent/models/rail_display/"+age+"/"+shape.getSerializedName()+(powered?"_on":"")+".json";
|
for (boolean powered : new boolean[] {false, true})
|
||||||
|
for (var shape :
|
||||||
|
new RailShape[] {
|
||||||
|
RailShape.NORTH_SOUTH,
|
||||||
|
RailShape.EAST_WEST,
|
||||||
|
RailShape.ASCENDING_NORTH,
|
||||||
|
RailShape.ASCENDING_SOUTH,
|
||||||
|
RailShape.ASCENDING_EAST,
|
||||||
|
RailShape.ASCENDING_WEST
|
||||||
|
}) {
|
||||||
|
String path =
|
||||||
|
"/defaults/resources/assets/astracontent/models/rail_display/"
|
||||||
|
+ age
|
||||||
|
+ "/"
|
||||||
|
+ shape.getSerializedName()
|
||||||
|
+ (powered ? "_on" : "")
|
||||||
|
+ ".json";
|
||||||
try (var stream = getClass().getResourceAsStream(path)) {
|
try (var stream = getClass().getResourceAsStream(path)) {
|
||||||
assertNotNull(stream,path);var model=JsonParser.parseReader(new InputStreamReader(stream,StandardCharsets.UTF_8)).getAsJsonObject();
|
assertNotNull(stream, path);
|
||||||
|
var model =
|
||||||
|
JsonParser.parseReader(
|
||||||
|
new InputStreamReader(
|
||||||
|
stream, StandardCharsets.UTF_8))
|
||||||
|
.getAsJsonObject();
|
||||||
for (var value : model.getAsJsonArray("elements")) {
|
for (var value : model.getAsJsonArray("elements")) {
|
||||||
var element=value.getAsJsonObject();var from=vector(element.getAsJsonArray("from"));var to=vector(element.getAsJsonArray("to"));
|
var element = value.getAsJsonObject();
|
||||||
for(float x:new float[]{from.x,to.x})for(float z:new float[]{from.z,to.z}){
|
var from = vector(element.getAsJsonArray("from"));
|
||||||
|
var to = vector(element.getAsJsonArray("to"));
|
||||||
|
for (float x : new float[] {from.x, to.x})
|
||||||
|
for (float z : new float[] {from.z, to.z}) {
|
||||||
var point = new Vector3f(x, from.y, z);
|
var point = new Vector3f(x, from.y, z);
|
||||||
if (element.has("rotation")) {
|
if (element.has("rotation")) {
|
||||||
var rotation=element.getAsJsonObject("rotation");var origin=vector(rotation.getAsJsonArray("origin"));
|
var rotation = element.getAsJsonObject("rotation");
|
||||||
float radians=(float)Math.toRadians(rotation.get("angle").getAsFloat());point.sub(origin);
|
var origin = vector(rotation.getAsJsonArray("origin"));
|
||||||
if(rotation.get("rescale").getAsBoolean()){float scale=1/(float)Math.cos(radians);point.mul(1,scale,scale);}
|
float radians =
|
||||||
|
(float)
|
||||||
|
Math.toRadians(
|
||||||
|
rotation.get("angle").getAsFloat());
|
||||||
|
point.sub(origin);
|
||||||
|
if (rotation.get("rescale").getAsBoolean()) {
|
||||||
|
float scale = 1 / (float) Math.cos(radians);
|
||||||
|
point.mul(1, scale, scale);
|
||||||
|
}
|
||||||
point.rotateX(radians).add(origin);
|
point.rotateX(radians).add(origin);
|
||||||
}
|
}
|
||||||
// Item models are centered at .5, then the vanilla item renderer turns them by pi.
|
// Item models are centered at .5, then the vanilla item
|
||||||
point.div(16).sub(.5f,.5f,.5f).rotateY((float)Math.PI).rotate(RailDisplayTransform.orientation(shape)).add(.5f,.5f,.5f);
|
// renderer turns them by pi.
|
||||||
float nativeHeight=1f/16+switch(shape){
|
point.div(16)
|
||||||
case ASCENDING_NORTH->1-point.z;case ASCENDING_SOUTH->point.z;
|
.sub(.5f, .5f, .5f)
|
||||||
case ASCENDING_EAST->point.x;case ASCENDING_WEST->1-point.x;default->0;
|
.rotateY((float) Math.PI)
|
||||||
|
.rotate(RailDisplayTransform.orientation(shape))
|
||||||
|
.add(.5f, .5f, .5f);
|
||||||
|
float nativeHeight =
|
||||||
|
1f / 16
|
||||||
|
+ switch (shape) {
|
||||||
|
case ASCENDING_NORTH -> 1 - point.z;
|
||||||
|
case ASCENDING_SOUTH -> point.z;
|
||||||
|
case ASCENDING_EAST -> point.x;
|
||||||
|
case ASCENDING_WEST -> 1 - point.x;
|
||||||
|
default -> 0;
|
||||||
};
|
};
|
||||||
assertTrue(point.y>nativeHeight && point.y-nativeHeight<.01,path+" vertex="+point+" rail height="+nativeHeight);
|
assertTrue(
|
||||||
assertTrue(point.x>-.01 && point.x<1.01 && point.z>-.01 && point.z<1.01,path+" stays inside rail footprint");
|
point.y > nativeHeight && point.y - nativeHeight < .01,
|
||||||
|
path
|
||||||
|
+ " vertex="
|
||||||
|
+ point
|
||||||
|
+ " rail height="
|
||||||
|
+ nativeHeight);
|
||||||
|
assertTrue(
|
||||||
|
point.x > -.01
|
||||||
|
&& point.x < 1.01
|
||||||
|
&& point.z > -.01
|
||||||
|
&& point.z < 1.01,
|
||||||
|
path + " stays inside rail footprint");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private static Vector3f vector(JsonArray a){return new Vector3f(a.get(0).getAsFloat(),a.get(1).getAsFloat(),a.get(2).getAsFloat());}
|
|
||||||
|
private static Vector3f vector(JsonArray a) {
|
||||||
|
return new Vector3f(a.get(0).getAsFloat(), a.get(1).getAsFloat(), a.get(2).getAsFloat());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,23 @@
|
|||||||
package online.astradev.content.rail;
|
package online.astradev.content.rail;
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
class RailSpeedTest {
|
class RailSpeedTest {
|
||||||
@Test void fixedCopperSpeedsAndWaxDoNotChangeLimit() {
|
@Test
|
||||||
|
void fixedCopperSpeedsAndWaxDoNotChangeLimit() {
|
||||||
for (int age = 0; age < 4; age++) {
|
for (int age = 0; age < 4; age++) {
|
||||||
assertEquals(20 - 4 * age, new RailKind(age, false).speed());
|
assertEquals(20 - 4 * age, new RailKind(age, false).speed());
|
||||||
assertEquals(20 - 4 * age, new RailKind(age, true).speed());
|
assertEquals(20 - 4 * age, new RailKind(age, true).speed());
|
||||||
assertEquals(new RailKind(age, true), RailKind.decode(new RailKind(age, true).code()));
|
assertEquals(new RailKind(age, true), RailKind.decode(new RailKind(age, true).code()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Test void analogInputIsTwoBlocksPerSecondPerLevel() {
|
|
||||||
|
@Test
|
||||||
|
void analogInputIsTwoBlocksPerSecondPerLevel() {
|
||||||
for (int i = 0; i <= 15; i++) assertEquals(i * 2, RailSpeed.signalSpeed(i));
|
for (int i = 0; i <= 15; i++) assertEquals(i * 2, RailSpeed.signalSpeed(i));
|
||||||
assertEquals(0,RailSpeed.signalSpeed(-1)); assertEquals(30,RailSpeed.signalSpeed(99));
|
assertEquals(0, RailSpeed.signalSpeed(-1));
|
||||||
|
assertEquals(30, RailSpeed.signalSpeed(99));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,193 +0,0 @@
|
|||||||
package online.astradev.content.verification;
|
|
||||||
|
|
||||||
import java.nio.file.*;
|
|
||||||
import java.util.*;
|
|
||||||
import net.minecraft.core.*;
|
|
||||||
import net.minecraft.core.component.DataComponents;
|
|
||||||
import net.minecraft.server.level.ServerLevel;
|
|
||||||
import net.minecraft.world.InteractionHand;
|
|
||||||
import net.minecraft.world.entity.*;
|
|
||||||
import net.minecraft.world.entity.item.ItemEntity;
|
|
||||||
import net.minecraft.world.entity.vehicle.minecart.*;
|
|
||||||
import net.minecraft.world.entity.projectile.Projectile;
|
|
||||||
import net.minecraft.world.entity.projectile.arrow.AbstractArrow;
|
|
||||||
import net.minecraft.world.entity.projectile.FireworkRocketEntity;
|
|
||||||
import net.minecraft.world.item.*;
|
|
||||||
import net.minecraft.world.item.component.ChargedProjectiles;
|
|
||||||
import net.minecraft.world.item.context.UseOnContext;
|
|
||||||
import net.minecraft.world.level.block.*;
|
|
||||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
|
||||||
import net.minecraft.world.phys.*;
|
|
||||||
import net.neoforged.api.distmarker.Dist;
|
|
||||||
import net.neoforged.fml.common.Mod;
|
|
||||||
import net.neoforged.neoforge.common.NeoForge;
|
|
||||||
import net.neoforged.neoforge.common.util.FakePlayerFactory;
|
|
||||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
|
||||||
import online.astradev.content.rail.*;
|
|
||||||
import online.astradev.content.weapon.*;
|
|
||||||
|
|
||||||
@Mod(value="astracontent_verify",dist=Dist.DEDICATED_SERVER)
|
|
||||||
public final class ContentVerification {
|
|
||||||
private int ticks;
|
|
||||||
private final List<AbstractMinecart> carts=new ArrayList<>();
|
|
||||||
private boolean done;
|
|
||||||
private final double[] previousX=new double[4];
|
|
||||||
public ContentVerification() {
|
|
||||||
if(!Boolean.getBoolean("astracontent.verify")) throw new IllegalStateException("Isolated test server only");
|
|
||||||
NeoForge.EVENT_BUS.addListener(this::tick);
|
|
||||||
}
|
|
||||||
private void tick(ServerTickEvent.Post event) {
|
|
||||||
if(done)return;
|
|
||||||
var server=event.getServer(); var level=server.overworld();
|
|
||||||
try {
|
|
||||||
ticks++;
|
|
||||||
if(ticks==1) server.getCommands().performPrefixedCommand(server.createCommandSourceStack(),"forceload add 0 0 159 95");
|
|
||||||
if(ticks==20) {
|
|
||||||
require(AbstractMinecart.useExperimentalMovement(level)==Boolean.getBoolean("astracontent.expectedExperimental"),"requested movement engine enabled");
|
|
||||||
if(Files.exists(Path.of("first-pass.txt"))) {
|
|
||||||
for(int age=0;age<4;age++) require(Rails.find(level,new BlockPos(2,100,age*4)).age()==age,"chunk identity survives restart");
|
|
||||||
var saved=level.getEntity(UUID.fromString(Files.readString(Path.of("saved-cart.txt"))));
|
|
||||||
require(saved instanceof AbstractMinecart,"saved minecart restored");
|
|
||||||
require(Math.abs(((CartSpeed)saved).astracontent$limit(level)-1)<.001,"personal speed survives restart on ordinary rails");
|
|
||||||
TrainVerification.restart(level);
|
|
||||||
finish(server,"PASS restart: rail ages, personal speed, train and chain display survive reload"); return;
|
|
||||||
}
|
|
||||||
setup(level); ammunition(level);
|
|
||||||
}
|
|
||||||
if(ticks==129)for(int age=0;age<4;age++)previousX[age]=carts.get(age).getX();
|
|
||||||
if(ticks==130) {
|
|
||||||
for(int age=0;age<4;age++) {
|
|
||||||
var cart=carts.get(age);
|
|
||||||
double actual=cart.getX()-previousX[age];
|
|
||||||
double expected=(20-age*4)/20.0;
|
|
||||||
require(Math.abs(actual-expected)<.015,"copper measured speed "+age+": "+actual+" expected "+expected);
|
|
||||||
}
|
|
||||||
TrackVerification.run(level);
|
|
||||||
TrainVerification.run(level);
|
|
||||||
var saved=new Minecart(EntityTypes.MINECART,level);saved.setPos(2.5,100.0625,.5);saved.setDeltaMovement(.1,0,0);saved.tick();
|
|
||||||
for(int x=29;x<=33;x++) {
|
|
||||||
var p=new BlockPos(x,100,40);level.setBlockAndUpdate(p.below(),Blocks.STONE.defaultBlockState());
|
|
||||||
level.setBlockAndUpdate(p,Blocks.RAIL.defaultBlockState().setValue(RailBlock.SHAPE,RailShape.EAST_WEST));
|
|
||||||
}
|
|
||||||
saved.setPos(30.5,100.0625,40.5);saved.setDeltaMovement(Vec3.ZERO);level.addFreshEntity(saved);
|
|
||||||
Files.writeString(Path.of("saved-cart.txt"),saved.getUUID().toString());
|
|
||||||
Files.writeString(Path.of("first-pass.txt"),"PASS");
|
|
||||||
finish(server,"PASS gameplay: native placement, all ages, drops, power, ammunition, and measured 20/16/12/8 m/s");
|
|
||||||
}
|
|
||||||
} catch(Throwable error) {
|
|
||||||
error.printStackTrace();
|
|
||||||
try { Files.writeString(Path.of("verification-result.txt"),"FAIL "+error); }catch(Exception ignored){}
|
|
||||||
done=true;server.halt(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private void setup(ServerLevel level) {
|
|
||||||
var ingredients=List.of(new ItemStack(Items.COPPER_INGOT),ItemStack.EMPTY,new ItemStack(Items.COPPER_INGOT),
|
|
||||||
new ItemStack(Items.COPPER_INGOT),new ItemStack(Items.STICK),new ItemStack(Items.COPPER_INGOT),
|
|
||||||
new ItemStack(Items.COPPER_INGOT),new ItemStack(Items.REDSTONE),new ItemStack(Items.COPPER_INGOT));
|
|
||||||
var input=net.minecraft.world.item.crafting.CraftingInput.of(3,3,ingredients);
|
|
||||||
var recipe=level.getServer().getRecipeManager().getRecipeFor(net.minecraft.world.item.crafting.RecipeType.CRAFTING,input,level).orElseThrow();
|
|
||||||
var crafted=recipe.value().assemble(input);
|
|
||||||
require(crafted.getCount()==6 && new RailKind(0,false).equals(RailItems.find(crafted)),"native crafting recipe makes six copper rails");
|
|
||||||
for(int code=0;code<8;code++) require(RailItems.find(Rails.stack(RailKind.decode(code),1)).code()==code,"item variant "+code);
|
|
||||||
for(int age=0;age<4;age++) {
|
|
||||||
int z=age*4;
|
|
||||||
for(int x=0;x<160;x++) {
|
|
||||||
var pos=new BlockPos(x,100,z);
|
|
||||||
level.setBlockAndUpdate(pos.below(),Blocks.REDSTONE_BLOCK.defaultBlockState());
|
|
||||||
level.setBlockAndUpdate(pos,Blocks.POWERED_RAIL.defaultBlockState().setValue(PoweredRailBlock.SHAPE,RailShape.EAST_WEST));
|
|
||||||
Rails.put(level,pos,new RailKind(age,true));
|
|
||||||
}
|
|
||||||
var cart=new Minecart(EntityTypes.MINECART,level); cart.setPos(2.5,100.0625,z+.5);cart.setDeltaMovement(.25,0,0);
|
|
||||||
level.addFreshEntity(cart);carts.add(cart);
|
|
||||||
}
|
|
||||||
var pos=new BlockPos(5,100,24);level.setBlockAndUpdate(pos.below(),Blocks.STONE.defaultBlockState());
|
|
||||||
var item=Rails.stack(new RailKind(2,false),2);
|
|
||||||
var context=new UseOnContext(level,null,InteractionHand.MAIN_HAND,item,new BlockHitResult(Vec3.atCenterOf(pos.below()),Direction.UP,pos.below(),false));
|
|
||||||
require(item.getItem().useOn(context).consumesAction(),"native BlockItem placement");
|
|
||||||
require(level.getBlockState(pos).is(Blocks.POWERED_RAIL),"real vanilla carrier");
|
|
||||||
require(Rails.find(level,pos).age()==2,"placement preserves variant");
|
|
||||||
require(item.getCount()==1,"placement consumes exactly one");
|
|
||||||
var player=FakePlayerFactory.getMinecraft(level);
|
|
||||||
player.setItemInHand(InteractionHand.MAIN_HAND,new ItemStack(Items.HONEYCOMB,2));
|
|
||||||
var hit=new BlockHitResult(Vec3.atCenterOf(pos),Direction.UP,pos,false);
|
|
||||||
Rails.use(new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickBlock(player,InteractionHand.MAIN_HAND,pos,hit));
|
|
||||||
require(Rails.find(level,pos).waxed(),"waxing native rail");
|
|
||||||
require(player.getMainHandItem().getCount()==1,"wax consumes one honeycomb");
|
|
||||||
player.setItemInHand(InteractionHand.MAIN_HAND,new ItemStack(Items.IRON_AXE));
|
|
||||||
Rails.use(new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickBlock(player,InteractionHand.MAIN_HAND,pos,hit));
|
|
||||||
require(!Rails.find(level,pos).waxed() && Rails.find(level,pos).age()==2,"axe removes wax first");
|
|
||||||
Rails.use(new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickBlock(player,InteractionHand.MAIN_HAND,pos,hit));
|
|
||||||
require(Rails.find(level,pos).age()==1,"axe removes one oxidation stage");
|
|
||||||
Rails.put(level,pos,new RailKind(2,false));
|
|
||||||
var drops=Block.getDrops(level.getBlockState(pos),level,pos,null);
|
|
||||||
require(drops.size()==1 && new RailKind(2,false).equals(RailItems.find(drops.getFirst())),"custom loot");
|
|
||||||
level.destroyBlock(pos.below(),true);
|
|
||||||
require(Rails.find(level,pos)==null,"support loss clears identity");
|
|
||||||
require(level.getEntitiesOfClass(ItemEntity.class,new AABB(pos).inflate(2)).stream().anyMatch(e->RailItems.find(e.getItem())!=null),"support loss drops custom rail");
|
|
||||||
var signalPos=new BlockPos(20,100,24);
|
|
||||||
level.setBlockAndUpdate(signalPos.below(),Blocks.REDSTONE_BLOCK.defaultBlockState());
|
|
||||||
level.setBlockAndUpdate(signalPos,Blocks.POWERED_RAIL.defaultBlockState());
|
|
||||||
require(RailSpeed.signal(level,signalPos)==15,"redstone block supplies 15");
|
|
||||||
require(RailSpeed.target(level,signalPos,8)==30,"gold rail 30 m/s at signal 15");
|
|
||||||
require(Rails.find(level,signalPos)==null,"ordinary golden rail stays ordinary");
|
|
||||||
analog(level);
|
|
||||||
}
|
|
||||||
private void analog(ServerLevel level) {
|
|
||||||
var rail=new BlockPos(30,100,24);var input=rail.west();var other=rail.east();
|
|
||||||
for(var p:List.of(rail,input,other))level.setBlockAndUpdate(p.below(),Blocks.STONE.defaultBlockState());
|
|
||||||
level.setBlockAndUpdate(input,Blocks.COMPARATOR.defaultBlockState().setValue(ComparatorBlock.FACING,Direction.WEST).setValue(ComparatorBlock.POWERED,true));
|
|
||||||
level.setBlockAndUpdate(other,Blocks.COMPARATOR.defaultBlockState().setValue(ComparatorBlock.FACING,Direction.EAST).setValue(ComparatorBlock.POWERED,true));
|
|
||||||
level.setBlockAndUpdate(rail,Blocks.POWERED_RAIL.defaultBlockState());
|
|
||||||
var source=(net.minecraft.world.level.block.entity.ComparatorBlockEntity)level.getBlockEntity(input);
|
|
||||||
var second=(net.minecraft.world.level.block.entity.ComparatorBlockEntity)level.getBlockEntity(other);
|
|
||||||
for(int signal=1;signal<=15;signal++) {
|
|
||||||
source.setOutputSignal(signal); second.setOutputSignal(Math.max(0,signal-2));
|
|
||||||
level.setBlock(rail,Blocks.POWERED_RAIL.defaultBlockState().setValue(PoweredRailBlock.POWERED,true),2);
|
|
||||||
require(RailSpeed.signal(level,rail)==signal,"actual comparator input "+signal);
|
|
||||||
require(RailSpeed.target(level,rail,8)==signal*2,"actual golden cap "+signal);
|
|
||||||
}
|
|
||||||
source.setOutputSignal(3); second.setOutputSignal(11);
|
|
||||||
require(RailSpeed.signal(level,rail)==11,"maximum of two inputs");
|
|
||||||
}
|
|
||||||
private void ammunition(ServerLevel level) {
|
|
||||||
var player=FakePlayerFactory.getMinecraft(level);player.setPos(40,115,35);
|
|
||||||
var crossbow=(CrossbowItem)Items.CROSSBOW;
|
|
||||||
var supported=List.of(Items.ENDER_PEARL,Items.FIRE_CHARGE,Items.ENDER_EYE,Items.EGG,Items.BLUE_EGG,Items.BROWN_EGG,Items.SNOWBALL,Items.WIND_CHARGE,Items.EXPERIENCE_BOTTLE,Items.TNT);
|
|
||||||
for(var ammo:supported) {
|
|
||||||
var weapon=new ItemStack(Items.CROSSBOW);var stack=new ItemStack(ammo,2);
|
|
||||||
player.setItemInHand(InteractionHand.MAIN_HAND,weapon);player.setItemInHand(InteractionHand.OFF_HAND,stack);
|
|
||||||
require(crossbow.getSupportedHeldProjectiles().test(stack),"held ammunition "+ammo);
|
|
||||||
require(crossbow.getAllSupportedProjectiles().test(stack),"inventory ammunition "+ammo);
|
|
||||||
require(crossbow.use(level,player,InteractionHand.MAIN_HAND).consumesAction(),"start loading "+ammo);
|
|
||||||
crossbow.onUseTick(level,player,weapon,72000-CrossbowItem.getChargeDuration(weapon,player));
|
|
||||||
require(CrossbowItem.isCharged(weapon),"loaded "+ammo);
|
|
||||||
require(stack.getCount()==1,"one ammo consumed "+ammo);
|
|
||||||
crossbow.performShooting(level,player,InteractionHand.MAIN_HAND,weapon,3.15f,0,null);
|
|
||||||
require(!CrossbowItem.isCharged(weapon),"unloaded after shot "+ammo);
|
|
||||||
require(weapon.getDamageValue()==1,"durability "+ammo);
|
|
||||||
player.stopUsingItem();
|
|
||||||
}
|
|
||||||
for(var ammo:List.of(Items.ARROW,Items.FIREWORK_ROCKET)) {
|
|
||||||
var weapon=new ItemStack(Items.CROSSBOW);weapon.set(DataComponents.CHARGED_PROJECTILES,ChargedProjectiles.ofNonEmpty(List.of(new ItemStack(ammo))));
|
|
||||||
crossbow.performShooting(level,player,InteractionHand.MAIN_HAND,weapon,3.15f,0,null);
|
|
||||||
}
|
|
||||||
require(!level.getEntitiesOfClass(AbstractArrow.class,new AABB(player.blockPosition()).inflate(8)).isEmpty(),"vanilla arrows remain arrows");
|
|
||||||
require(!level.getEntitiesOfClass(FireworkRocketEntity.class,new AABB(player.blockPosition()).inflate(8)).isEmpty(),"vanilla fireworks remain fireworks");
|
|
||||||
var multi=new ItemStack(Items.CROSSBOW);
|
|
||||||
multi.enchant(level.registryAccess().lookupOrThrow(net.minecraft.core.registries.Registries.ENCHANTMENT).getOrThrow(net.minecraft.world.item.enchantment.Enchantments.MULTISHOT),1);
|
|
||||||
player.setItemInHand(InteractionHand.MAIN_HAND,multi);player.setItemInHand(InteractionHand.OFF_HAND,new ItemStack(Items.SNOWBALL,2));
|
|
||||||
crossbow.use(level,player,InteractionHand.MAIN_HAND);
|
|
||||||
crossbow.onUseTick(level,player,multi,72000-CrossbowItem.getChargeDuration(multi,player));
|
|
||||||
require(multi.get(DataComponents.CHARGED_PROJECTILES).itemCopies().size()==3,"multishot loads three snowballs");
|
|
||||||
require(player.getOffhandItem().getCount()==1,"multishot consumes one ammo");player.stopUsingItem();
|
|
||||||
player.setItemInHand(InteractionHand.MAIN_HAND,new ItemStack(Items.FIRE_CHARGE,2));
|
|
||||||
Ammunition.fireCharge(new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickItem(player,InteractionHand.MAIN_HAND));
|
|
||||||
require(player.getMainHandItem().getCount()==1,"right click fire charge consumes one");
|
|
||||||
Ammunition.fireCharge(new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickItem(player,InteractionHand.MAIN_HAND));
|
|
||||||
require(player.getMainHandItem().getCount()==1,"fire charge cooldown prevents second shot");
|
|
||||||
}
|
|
||||||
private void finish(net.minecraft.server.MinecraftServer server,String text)throws Exception {
|
|
||||||
Files.writeString(Path.of("verification-result.txt"),text);System.out.println(text);done=true;server.halt(false);
|
|
||||||
}
|
|
||||||
private static void require(boolean condition,String message) {if(!condition)throw new AssertionError(message);}
|
|
||||||
}
|
|
||||||
-55
@@ -1,55 +0,0 @@
|
|||||||
package online.astradev.content.verification;
|
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
import net.minecraft.server.level.ServerLevel;
|
|
||||||
import net.minecraft.world.entity.player.Input;
|
|
||||||
import net.minecraft.world.entity.vehicle.minecart.Minecart;
|
|
||||||
import net.minecraft.world.level.block.Blocks;
|
|
||||||
import net.minecraft.world.level.block.RailBlock;
|
|
||||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
|
||||||
import net.minecraft.world.phys.Vec3;
|
|
||||||
import net.neoforged.neoforge.common.util.FakePlayerFactory;
|
|
||||||
import static online.astradev.content.verification.TrackVerification.*;
|
|
||||||
import static online.astradev.content.verification.TrainVerification.*;
|
|
||||||
|
|
||||||
final class PlayerTrainVerification {
|
|
||||||
static void run(ServerLevel level){
|
|
||||||
for(int side=0;side<4;side++){
|
|
||||||
double ordinary=push(level,side,1),train=push(level,side,3);
|
|
||||||
require(Math.abs(ordinary)>.02,"ordinary cart reacts to player push");
|
|
||||||
require(Math.abs(train-ordinary)<.005,"same player push reaches whole train side="+side+": "+train+" vs "+ordinary);
|
|
||||||
}
|
|
||||||
for(boolean reverse:new boolean[]{false,true}){
|
|
||||||
double ordinary=ride(level,reverse,1),train=ride(level,reverse,3);
|
|
||||||
require(Math.abs(ordinary)>.1,"ordinary cart responds to seated input");
|
|
||||||
require(Math.signum(train)==Math.signum(ordinary)&&Math.abs(train)>=Math.abs(ordinary)*.8,
|
|
||||||
"seated player controls train reverse="+reverse+": "+train+" vs "+ordinary);
|
|
||||||
}
|
|
||||||
System.out.println("PASS player controls: walking pushes from four sides and seated forward/backward input compared with ordinary cart");
|
|
||||||
}
|
|
||||||
private static List<Minecart> setup(ServerLevel level,int count){
|
|
||||||
var path=new ArrayList<Track>();for(int x=0;x<=14;x++)path.add(new Track(at(x,0,0,0),Blocks.RAIL.defaultBlockState().setValue(RailBlock.SHAPE,RailShape.EAST_WEST)));
|
|
||||||
build(level,path,-1);var carts=new ArrayList<Minecart>();
|
|
||||||
for(int i=0;i<count;i++)carts.add(cart(level,at(4+i*2,0,0,0),Vec3.ZERO));
|
|
||||||
for(int i=0;i<count-1;i++)link(level,carts.get(i),carts.get(i+1));return carts;
|
|
||||||
}
|
|
||||||
private static double push(ServerLevel level,int side,int count){
|
|
||||||
var carts=setup(level,count);var target=carts.getFirst();var player=FakePlayerFactory.getMinecraft(level);
|
|
||||||
player.stopRiding();player.setLastClientInput(Input.EMPTY);player.setShiftKeyDown(false);
|
|
||||||
player.setPos(target.position().add(direction(side,.6)));player.setDeltaMovement(Vec3.ZERO);
|
|
||||||
target.push(player);double before=target.getX();tick(level,carts);double result=target.getX()-before;
|
|
||||||
if(count>1)for(var c:carts)require(c.getDeltaMovement().horizontalDistance()>.01,"every coupled cart receives walking push");
|
|
||||||
cleanup(carts);player.setPos(40,115,35);return result;
|
|
||||||
}
|
|
||||||
private static double ride(ServerLevel level,boolean reverse,int count){
|
|
||||||
var carts=setup(level,count);var target=carts.getFirst();
|
|
||||||
// NeoForge FakePlayer deliberately refuses all riding; use the real ServerPlayer implementation.
|
|
||||||
var player=new net.minecraft.server.level.ServerPlayer(level.getServer(),level,
|
|
||||||
new com.mojang.authlib.GameProfile(UUID.randomUUID(),"TrainRider"),net.minecraft.server.level.ClientInformation.createDefault());
|
|
||||||
player.connection=FakePlayerFactory.getMinecraft(level).connection;
|
|
||||||
player.setShiftKeyDown(false);player.setPos(target.position());require(player.startRiding(target),"player mounts minecart");
|
|
||||||
player.setYRot(-90);player.setLastClientInput(new Input(!reverse,reverse,false,false,false,false,false));
|
|
||||||
double before=target.getX();for(int i=0;i<100;i++)tick(level,carts);double result=target.getX()-before;
|
|
||||||
player.setLastClientInput(Input.EMPTY);player.stopRiding();cleanup(carts);player.setPos(40,115,35);return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
package online.astradev.content.verification;
|
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
import net.minecraft.core.*;
|
|
||||||
import net.minecraft.server.level.ServerLevel;
|
|
||||||
import net.minecraft.world.entity.EntityTypes;
|
|
||||||
import net.minecraft.world.entity.vehicle.minecart.Minecart;
|
|
||||||
import net.minecraft.world.level.block.*;
|
|
||||||
import net.minecraft.world.level.block.state.BlockState;
|
|
||||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
|
||||||
import net.minecraft.world.phys.Vec3;
|
|
||||||
import online.astradev.content.rail.*;
|
|
||||||
|
|
||||||
/** Real native movement on mirrored/rotated tracks, never just a speed-formula test. */
|
|
||||||
final class TrackVerification {
|
|
||||||
record Track(BlockPos pos,BlockState state) {}
|
|
||||||
static void run(ServerLevel level) {
|
|
||||||
for(int turn=0;turn<4;turn++) for(int mirror:new int[]{-1,1}) corner(level,turn,mirror);
|
|
||||||
for(int turn=0;turn<4;turn++) for(boolean uphill:new boolean[]{false,true}) slope(level,turn,uphill);
|
|
||||||
brakes(level); detectors(level); water(level); cartTypes(level); transitions(level);
|
|
||||||
System.out.println("PASS tracks: 8 corner routes, 8 slope routes, brakes, detector, activator, water, 7 cart types, speed transitions");
|
|
||||||
}
|
|
||||||
static BlockPos at(int x,int y,int z,int turn) {
|
|
||||||
for(int i=0;i<turn;i++){int old=x;x=-z;z=old;}
|
|
||||||
return new BlockPos(60+x,100+y,64+z);
|
|
||||||
}
|
|
||||||
static BlockState rotate(BlockState state,int turns) { for(int i=0;i<turns;i++)state=state.rotate(Rotation.CLOCKWISE_90);return state; }
|
|
||||||
static BlockState powered(RailShape shape) {return Blocks.POWERED_RAIL.defaultBlockState().setValue(PoweredRailBlock.SHAPE,shape).setValue(PoweredRailBlock.POWERED,true);}
|
|
||||||
static void clear(ServerLevel level) {
|
|
||||||
for(int x=43;x<=77;x++)for(int z=47;z<=81;z++)for(int y=98;y<=105;y++)level.setBlock(new BlockPos(x,y,z),Blocks.AIR.defaultBlockState(),2);
|
|
||||||
}
|
|
||||||
static void build(ServerLevel level,List<Track> path,int age) {
|
|
||||||
clear(level);
|
|
||||||
for(var p:path)level.setBlock(p.pos.below(),Blocks.REDSTONE_BLOCK.defaultBlockState(),2);
|
|
||||||
for(var p:path)level.setBlock(p.pos,p.state,2);
|
|
||||||
// Placement recomputes neighbor shapes; now set the exact constructed route.
|
|
||||||
for(var p:path) {
|
|
||||||
level.setBlock(p.pos,p.state,2);
|
|
||||||
if(p.state.is(Blocks.POWERED_RAIL) && age>=0)Rails.put(level,p.pos,new RailKind(age,true));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
static Minecart cart(ServerLevel level,BlockPos start,Vec3 velocity) {
|
|
||||||
var cart=new Minecart(EntityTypes.MINECART,level);cart.setPos(start.getX()+.5,start.getY()+.0625,start.getZ()+.5);
|
|
||||||
cart.setDeltaMovement(velocity);level.addFreshEntity(cart);return cart;
|
|
||||||
}
|
|
||||||
static Vec3 direction(int turns,double speed) {
|
|
||||||
return switch(turns){case 0->new Vec3(speed,0,0);case 1->new Vec3(0,0,speed);case 2->new Vec3(-speed,0,0);default->new Vec3(0,0,-speed);};
|
|
||||||
}
|
|
||||||
private static void travel(ServerLevel level,List<Track> path,int turn,String label) {
|
|
||||||
var cart=cart(level,path.getFirst().pos,direction(turn,1.5));
|
|
||||||
var end=Vec3.atCenterOf(path.getLast().pos);
|
|
||||||
boolean arrived=false;
|
|
||||||
for(int tick=0;tick<180;tick++) {
|
|
||||||
cart.tick();
|
|
||||||
double nearest=path.stream().mapToDouble(p->Math.hypot(cart.getX()-p.pos.getX()-.5,cart.getZ()-p.pos.getZ()-.5)).min().orElseThrow();
|
|
||||||
require(nearest<1.1,label+" derailed at "+cart.position());
|
|
||||||
if(cart.position().distanceTo(end)<1.2){arrived=true;break;}
|
|
||||||
}
|
|
||||||
cart.discard();require(arrived,label+" never reached end");
|
|
||||||
}
|
|
||||||
private static void corner(ServerLevel level,int turn,int mirror) {
|
|
||||||
var path=new ArrayList<Track>();
|
|
||||||
for(int x=0;x<8;x++)path.add(new Track(at(x,0,0,turn),rotate(powered(RailShape.EAST_WEST),turn)));
|
|
||||||
path.add(new Track(at(8,0,0,turn),rotate(Blocks.RAIL.defaultBlockState().setValue(RailBlock.SHAPE,mirror==1?RailShape.SOUTH_WEST:RailShape.NORTH_WEST),turn)));
|
|
||||||
for(int z=1;z<=8;z++)path.add(new Track(at(8,0,z*mirror,turn),rotate(powered(RailShape.NORTH_SOUTH),turn)));
|
|
||||||
build(level,path,turn);travel(level,path,turn,"corner "+turn+"/"+mirror);
|
|
||||||
}
|
|
||||||
private static void slope(ServerLevel level,int turn,boolean uphill) {
|
|
||||||
var path=new ArrayList<Track>();
|
|
||||||
for(int x=0;x<=14;x++) {
|
|
||||||
int height=x<5?0:x<8?x-5:3;
|
|
||||||
if(!uphill)height=3-height;
|
|
||||||
if(!uphill && x>=5 && x<8)height--;
|
|
||||||
RailShape shape=x>=5 && x<8?(uphill?RailShape.ASCENDING_EAST:RailShape.ASCENDING_WEST):RailShape.EAST_WEST;
|
|
||||||
path.add(new Track(at(x,height,0,turn),rotate(powered(shape),turn)));
|
|
||||||
}
|
|
||||||
build(level,path,turn);
|
|
||||||
for(var p:path)level.setBlock(p.pos.below(),Blocks.STONE.defaultBlockState(),2);
|
|
||||||
level.setBlock(path.getFirst().pos.below(),Blocks.REDSTONE_BLOCK.defaultBlockState(),2);
|
|
||||||
for(int i=0;i<=8;i++)require(RailSpeed.signal(level,path.get(i).pos)==15,"signal over slope "+turn+"/"+uphill+" at "+i);
|
|
||||||
require(RailSpeed.signal(level,path.get(10).pos)==0,"signal respects eight-rail reach");
|
|
||||||
for(var p:path)level.setBlock(p.pos.below(),Blocks.REDSTONE_BLOCK.defaultBlockState(),2);
|
|
||||||
travel(level,path,turn,"slope "+turn+"/"+uphill);
|
|
||||||
}
|
|
||||||
static List<Track> straight() {
|
|
||||||
var path=new ArrayList<Track>();for(int x=0;x<=14;x++)path.add(new Track(at(x,0,0,0),powered(RailShape.EAST_WEST)));return path;
|
|
||||||
}
|
|
||||||
private static void brakes(ServerLevel level) {
|
|
||||||
var path=straight();build(level,path,-1);
|
|
||||||
for(int x=5;x<=14;x++) {
|
|
||||||
level.setBlock(at(x,-1,0,0),Blocks.STONE.defaultBlockState(),2);
|
|
||||||
level.setBlock(at(x,0,0,0),powered(RailShape.EAST_WEST).setValue(PoweredRailBlock.POWERED,false),2);
|
|
||||||
}
|
|
||||||
// Remove propagated power in this controlled fixture.
|
|
||||||
for(int x=5;x<=14;x++)level.setBlock(at(x,0,0,0),powered(RailShape.EAST_WEST).setValue(PoweredRailBlock.POWERED,false),2);
|
|
||||||
var cart=cart(level,at(0,0,0,0),new Vec3(1.5,0,0));
|
|
||||||
for(int t=0;t<70;t++)cart.tick();
|
|
||||||
require(cart.getDeltaMovement().horizontalDistance()<.01,"unpowered braking");
|
|
||||||
require(cart.getX()<70,"brakes stop cart before track end");cart.discard();
|
|
||||||
}
|
|
||||||
private static void detectors(ServerLevel level) {
|
|
||||||
var path=straight();build(level,path,-1);
|
|
||||||
var detector=at(5,0,0,0);var activator=at(9,0,0,0);
|
|
||||||
level.setBlock(detector,Blocks.DETECTOR_RAIL.defaultBlockState().setValue(DetectorRailBlock.SHAPE,RailShape.EAST_WEST),2);
|
|
||||||
level.setBlock(activator,Blocks.ACTIVATOR_RAIL.defaultBlockState().setValue(PoweredRailBlock.SHAPE,RailShape.EAST_WEST).setValue(PoweredRailBlock.POWERED,true),2);
|
|
||||||
var cart=cart(level,at(0,0,0,0),new Vec3(1.5,0,0));
|
|
||||||
boolean detected=false,activated=false;
|
|
||||||
for(int t=0;t<65;t++) {
|
|
||||||
cart.tick();detected|=level.getBlockState(detector).getValue(DetectorRailBlock.POWERED);
|
|
||||||
activated|=cart.getHurtTime()>0;
|
|
||||||
if(cart.getX()>73)break;
|
|
||||||
}
|
|
||||||
require(detected,"detector rail registers high speed cart");require(activated,"activator rail activates cart");cart.discard();
|
|
||||||
}
|
|
||||||
private static void water(ServerLevel level) {
|
|
||||||
var path=straight();build(level,path,0);
|
|
||||||
for(var rail:path)level.setBlock(rail.pos,rail.state.setValue(BaseRailBlock.WATERLOGGED,true),2);
|
|
||||||
var cart=cart(level,at(3,0,0,0),new Vec3(1.5,0,0));
|
|
||||||
double previousX=cart.getX();
|
|
||||||
for(int t=0;t<5;t++){previousX=cart.getX();cart.tick();}
|
|
||||||
require(cart.isInWater(),"waterlogged track is native water");
|
|
||||||
require(cart.getX()-previousX<=.501,"water speed reduction: "+(cart.getX()-previousX));cart.discard();
|
|
||||||
}
|
|
||||||
private static void cartTypes(ServerLevel level) {
|
|
||||||
build(level,straight(),0);
|
|
||||||
List<net.minecraft.world.entity.EntityType<? extends net.minecraft.world.entity.vehicle.minecart.AbstractMinecart>> types=List.of(
|
|
||||||
EntityTypes.MINECART,EntityTypes.CHEST_MINECART,EntityTypes.HOPPER_MINECART,EntityTypes.FURNACE_MINECART,
|
|
||||||
EntityTypes.TNT_MINECART,EntityTypes.COMMAND_BLOCK_MINECART,EntityTypes.SPAWNER_MINECART);
|
|
||||||
for(var type:types) {
|
|
||||||
var cart=type.create(level,net.minecraft.world.entity.EntitySpawnReason.COMMAND);
|
|
||||||
require(cart!=null,"create "+type);
|
|
||||||
cart.setPos(63.5,100.0625,64.5);cart.setDeltaMovement(2,0,0);level.addFreshEntity(cart);
|
|
||||||
cart.tick();double before=cart.getX();cart.tick();
|
|
||||||
double distance=cart.getX()-before;
|
|
||||||
require(Math.abs(distance-1)<.015,"20 m/s for "+type+": "+distance);cart.discard();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private static void transitions(ServerLevel level) {
|
|
||||||
build(level,straight(),0);
|
|
||||||
for(int x=6;x<=14;x++)Rails.put(level,at(x,0,0,0),new RailKind(3,true));
|
|
||||||
var cart=cart(level,at(2,0,0,0),new Vec3(1.5,0,0));boolean crossed=false;
|
|
||||||
for(int t=0;t<35;t++) {
|
|
||||||
double before=cart.getX();cart.tick();
|
|
||||||
if(before>=66.1) {crossed=true;require(cart.getX()-before<=.415,"20 to 8 transition obeys slower rail");}
|
|
||||||
if(cart.getX()>72)break;
|
|
||||||
}
|
|
||||||
require(crossed,"crossed oxidation boundary");cart.discard();
|
|
||||||
build(level,straight(),-1);
|
|
||||||
// Native rail at the end: approach is limited before the cart leaves the track.
|
|
||||||
cart=cart(level,at(13,0,0,0),new Vec3(1.5,0,0));
|
|
||||||
double before=cart.getX();cart.tick();
|
|
||||||
if(!net.minecraft.world.entity.vehicle.minecart.AbstractMinecart.useExperimentalMovement(level))
|
|
||||||
require(cart.getX()-before<=.415,"end of track safe approach");
|
|
||||||
cart.discard();
|
|
||||||
}
|
|
||||||
private static void require(boolean condition,String message){if(!condition)throw new AssertionError(message);}
|
|
||||||
}
|
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
package online.astradev.content.verification;
|
|
||||||
|
|
||||||
import java.nio.file.*;
|
|
||||||
import java.util.*;
|
|
||||||
import net.minecraft.core.BlockPos;
|
|
||||||
import net.minecraft.server.level.ServerLevel;
|
|
||||||
import net.minecraft.world.InteractionHand;
|
|
||||||
import net.minecraft.world.entity.*;
|
|
||||||
import net.minecraft.world.entity.item.ItemEntity;
|
|
||||||
import net.minecraft.world.entity.vehicle.minecart.*;
|
|
||||||
import net.minecraft.world.item.*;
|
|
||||||
import net.minecraft.world.level.block.*;
|
|
||||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
|
||||||
import net.minecraft.world.phys.*;
|
|
||||||
import net.neoforged.neoforge.common.util.FakePlayerFactory;
|
|
||||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
|
||||||
import online.astradev.content.train.*;
|
|
||||||
import online.astradev.content.transport.SlimeBounce;
|
|
||||||
import static online.astradev.content.verification.TrackVerification.*;
|
|
||||||
|
|
||||||
final class TrainVerification {
|
|
||||||
static void run(ServerLevel level)throws Exception {
|
|
||||||
interaction(level);
|
|
||||||
PlayerTrainVerification.run(level);
|
|
||||||
unloaded(level);
|
|
||||||
for(int turn=0;turn<4;turn++)for(int mirror:new int[]{-1,1})route(level,turn,mirror,false);
|
|
||||||
for(int turn=0;turn<4;turn++)for(int slope:new int[]{-1,1})route(level,turn,slope,true);
|
|
||||||
ring(level);
|
|
||||||
for(int turn=0;turn<4;turn++){buffer(level,turn,true);buffer(level,turn,false);trainBuffer(level,turn);boat(level,turn);}
|
|
||||||
offRailBounce(level);
|
|
||||||
persistence(level);
|
|
||||||
System.out.println("PASS trains: endpoint interactions, refunds, 8 turns, 8 slopes, closed moving ring, four-direction slime/stone and boat collisions");
|
|
||||||
}
|
|
||||||
static void click(ServerLevel level,AbstractMinecart cart,Item item,Vec3 hit){
|
|
||||||
var player=FakePlayerFactory.getMinecraft(level);player.setShiftKeyDown(true);
|
|
||||||
player.setItemInHand(InteractionHand.MAIN_HAND,new ItemStack(item,8));
|
|
||||||
Trains.interact(new PlayerInteractEvent.EntityInteract(player,InteractionHand.MAIN_HAND,cart,hit));
|
|
||||||
}
|
|
||||||
static TrainData.Link link(ServerLevel level,AbstractMinecart a,AbstractMinecart b){
|
|
||||||
var link=new TrainData.Link(a.getUUID(),0,b.getUUID(),1,"minecraft:iron_chain",true,a.position().distanceTo(b.position()));
|
|
||||||
TrainData.get(level).add(link);return link;
|
|
||||||
}
|
|
||||||
static void tick(ServerLevel level,List<? extends AbstractMinecart> carts){
|
|
||||||
Trains.step(level);for(var cart:carts){cart.setOldPosAndRot();cart.tick();SlimeBounce.flush(cart);}Trains.show(level);
|
|
||||||
}
|
|
||||||
static void cleanup(List<? extends Entity> carts){for(var cart:carts)cart.discard();}
|
|
||||||
static void unloaded(ServerLevel level){
|
|
||||||
build(level,straight(),0);var a=cart(level,at(2,0,0,0),new Vec3(1,0,0));var b=cart(level,at(4,0,0,0),Vec3.ZERO);
|
|
||||||
var saved=link(level,a,b);b.remove(Entity.RemovalReason.UNLOADED_TO_CHUNK);
|
|
||||||
var position=a.position();for(int i=0;i<10;i++)tick(level,List.of(a));
|
|
||||||
require(a.position().horizontal().distanceTo(position.horizontal())<.01,"loaded half of train pauses");
|
|
||||||
require(TrainData.get(level).links().contains(saved),"unloading keeps saved chain");
|
|
||||||
TrainData.get(level).remove(saved);a.discard();Trains.step(level);
|
|
||||||
}
|
|
||||||
static void interaction(ServerLevel level){
|
|
||||||
build(level,straight(),0);var a=cart(level,at(2,0,0,0),Vec3.ZERO);var b=cart(level,at(4,0,0,0),Vec3.ZERO);
|
|
||||||
var data=TrainData.get(level);var player=FakePlayerFactory.getMinecraft(level);
|
|
||||||
click(level,a,Items.IRON_CHAIN,new Vec3(0,.2,.49));require(data.links().isEmpty(),"side cannot attach");
|
|
||||||
click(level,a,Items.IRON_CHAIN,new Vec3(.49,.2,0));require(data.links().size()==1,"front auto couples");
|
|
||||||
require(player.getMainHandItem().getCount()==7,"one chain consumed");
|
|
||||||
click(level,a,Items.IRON_CHAIN,new Vec3(.49,.2,0));require(data.links().size()==1 && player.getMainHandItem().getCount()==8,"occupied end rejects");
|
|
||||||
Trains.show(level);Trains.show(level);
|
|
||||||
require(level.getEntitiesOfClass(ChainDisplay.class,a.getBoundingBox().inflate(5)).size()==1,"one visible vanilla chain");
|
|
||||||
int drops=level.getEntitiesOfClass(ItemEntity.class,a.getBoundingBox().inflate(5)).size();
|
|
||||||
click(level,b,Items.IRON_PICKAXE,new Vec3(-.49,.2,0));require(data.links().isEmpty(),"detach from opposite end");
|
|
||||||
require(level.getEntitiesOfClass(ItemEntity.class,a.getBoundingBox().inflate(5)).size()==drops+1,"exactly one refund");
|
|
||||||
click(level,b,Items.IRON_PICKAXE,new Vec3(-.49,.2,0));require(level.getEntitiesOfClass(ItemEntity.class,a.getBoundingBox().inflate(5)).size()==drops+1,"no duplicate refund");
|
|
||||||
link(level,a,b);b.discard();require(data.links().isEmpty(),"destroy removes saved link");a.discard();
|
|
||||||
player.setShiftKeyDown(false);
|
|
||||||
}
|
|
||||||
static void route(ServerLevel level,int turn,int side,boolean slope){
|
|
||||||
var path=new ArrayList<Track>();
|
|
||||||
if(slope){for(int x=0;x<=20;x++){
|
|
||||||
int y=x<8?0:x<11?x-8:3;if(side<0)y=3-y-(x>=8&&x<11?1:0);
|
|
||||||
var shape=x>=8&&x<11?(side>0?RailShape.ASCENDING_EAST:RailShape.ASCENDING_WEST):RailShape.EAST_WEST;
|
|
||||||
path.add(new Track(at(x,y,0,turn),rotate(powered(shape),turn)));
|
|
||||||
}}else{
|
|
||||||
for(int x=0;x<9;x++)path.add(new Track(at(x,0,0,turn),rotate(powered(RailShape.EAST_WEST),turn)));
|
|
||||||
path.add(new Track(at(9,0,0,turn),rotate(Blocks.RAIL.defaultBlockState().setValue(RailBlock.SHAPE,side>0?RailShape.SOUTH_WEST:RailShape.NORTH_WEST),turn)));
|
|
||||||
for(int z=1;z<=12;z++)path.add(new Track(at(9,0,z*side,turn),rotate(powered(RailShape.NORTH_SOUTH),turn)));
|
|
||||||
}
|
|
||||||
build(level,path,0);var carts=new ArrayList<Minecart>();
|
|
||||||
for(int i=0;i<3;i++){var c=cart(level,path.get(1+i*2).pos(),direction(turn,.5));((CartFrame)c).astracontent$front(direction(turn,1));carts.add(c);}
|
|
||||||
link(level,carts.get(0),carts.get(1));link(level,carts.get(1),carts.get(2));boolean reached=false;
|
|
||||||
for(int t=0;t<200;t++){
|
|
||||||
tick(level,carts);
|
|
||||||
for(var c:carts){double nearest=path.stream().mapToDouble(p->c.position().distanceTo(Vec3.atBottomCenterOf(p.pos()).add(0,.1,0))).min().orElseThrow();
|
|
||||||
require(nearest<1.3,"train derailed "+turn+"/"+side+" slope="+slope+" "+c.position());}
|
|
||||||
require(TrainData.get(level).links().size()==2,"train stays coupled on route");
|
|
||||||
if(carts.get(0).position().distanceTo(Vec3.atCenterOf(path.get(path.size()-6).pos()))<1.2){reached=true;break;}
|
|
||||||
}
|
|
||||||
require(reached,"whole train traverses "+turn+"/"+side+" slope="+slope);cleanup(carts);
|
|
||||||
}
|
|
||||||
static void ring(ServerLevel level){
|
|
||||||
var path=new ArrayList<Track>();var positions=new ArrayList<BlockPos>();
|
|
||||||
for(int x=0;x<=8;x++)for(int z=0;z<=8;z++)if(x==0||x==8||z==0||z==8){
|
|
||||||
RailShape shape=z==0||z==8?RailShape.EAST_WEST:RailShape.NORTH_SOUTH;
|
|
||||||
if(x==0&&z==0)shape=RailShape.SOUTH_EAST;if(x==8&&z==0)shape=RailShape.SOUTH_WEST;
|
|
||||||
if(x==8&&z==8)shape=RailShape.NORTH_WEST;if(x==0&&z==8)shape=RailShape.NORTH_EAST;
|
|
||||||
path.add(new Track(at(x,0,z,0),shape.isSlope()||shape==RailShape.EAST_WEST||shape==RailShape.NORTH_SOUTH?powered(shape):Blocks.RAIL.defaultBlockState().setValue(RailBlock.SHAPE,shape)));
|
|
||||||
}
|
|
||||||
for(int x=4;x<=8;x+=2)positions.add(at(x,0,0,0));for(int z=2;z<=8;z+=2)positions.add(at(8,0,z,0));
|
|
||||||
for(int x=6;x>=0;x-=2)positions.add(at(x,0,8,0));for(int z=6;z>=0;z-=2)positions.add(at(0,0,z,0));positions.add(at(2,0,0,0));
|
|
||||||
build(level,path,3);var carts=new ArrayList<Minecart>();
|
|
||||||
for(int i=0;i<positions.size();i++){var dir=Vec3.atCenterOf(positions.get((i+1)%positions.size())).subtract(Vec3.atCenterOf(positions.get(i))).normalize();
|
|
||||||
var c=cart(level,positions.get(i),dir.scale(.3));((CartFrame)c).astracontent$front(dir);carts.add(c);}
|
|
||||||
for(int i=0;i<carts.size()-1;i++)link(level,carts.get(i),carts.get(i+1));
|
|
||||||
click(level,carts.getLast(),Items.IRON_CHAIN,new Vec3(.49,.2,0));
|
|
||||||
require(TrainData.get(level).links().size()==carts.size(),"player closes same train into ring");
|
|
||||||
double traveled=0;
|
|
||||||
for(int t=0;t<100;t++){var before=carts.getFirst().position();tick(level,carts);traveled+=before.distanceTo(carts.getFirst().position());
|
|
||||||
require(TrainData.get(level).links().size()==carts.size(),"closed ring remains intact");
|
|
||||||
for(var c:carts)require(level.getBlockState(c.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock,"ring cart remains on rail "+c.position());}
|
|
||||||
require(traveled>15,"closed ring actually moves: "+traveled);cleanup(carts);
|
|
||||||
}
|
|
||||||
static void buffer(ServerLevel level,int turn,boolean slime){
|
|
||||||
var path=new ArrayList<Track>();for(int x=0;x<=10;x++)path.add(new Track(at(x,0,0,turn),rotate(powered(RailShape.EAST_WEST),turn)));
|
|
||||||
build(level,path,0);level.setBlock(at(11,0,0,turn),(slime?Blocks.SLIME_BLOCK:Blocks.STONE).defaultBlockState(),2);
|
|
||||||
var cart=cart(level,at(8,0,0,turn),direction(turn,1));boolean reflected=false;double speed=0;
|
|
||||||
for(int t=0;t<15;t++){cart.setOldPosAndRot();cart.tick();SlimeBounce.flush(cart);double v=cart.getDeltaMovement().dot(direction(turn,1));if(v<-.1){reflected=true;speed=-v;break;}}
|
|
||||||
if(slime)require(reflected,"slime reflects direction "+turn);
|
|
||||||
else require(speed<.4,"stone retains native slow powered-rail restart: "+speed);
|
|
||||||
if(slime)require(speed>.9,"full impact speed preserved "+turn+": "+speed);cart.discard();
|
|
||||||
}
|
|
||||||
static void boat(ServerLevel level,int turn){
|
|
||||||
clear(level);var wall=at(4,0,0,turn);level.setBlock(wall,Blocks.SLIME_BLOCK.defaultBlockState(),2);
|
|
||||||
var boat=EntityTypes.OAK_BOAT.create(level,EntitySpawnReason.COMMAND);var dir=direction(turn,1);
|
|
||||||
boat.setPos(Vec3.atBottomCenterOf(wall).subtract(dir.scale(1.5)));level.addFreshEntity(boat);boat.setDeltaMovement(dir);
|
|
||||||
boat.move(MoverType.SELF,dir);SlimeBounce.flush(boat);
|
|
||||||
require(boat.getDeltaMovement().dot(dir)<-.99,"boat full speed bounce "+turn);boat.discard();
|
|
||||||
}
|
|
||||||
static void trainBuffer(ServerLevel level,int turn){
|
|
||||||
var path=new ArrayList<Track>();for(int x=0;x<=10;x++)path.add(new Track(at(x,0,0,turn),rotate(powered(RailShape.EAST_WEST),turn)));
|
|
||||||
build(level,path,0);level.setBlock(at(11,0,0,turn),Blocks.SLIME_BLOCK.defaultBlockState(),2);
|
|
||||||
var carts=new ArrayList<Minecart>();var direction=direction(turn,1);
|
|
||||||
for(int x=4;x<=8;x+=2){var c=cart(level,at(x,0,0,turn),direction);((CartFrame)c).astracontent$front(direction);carts.add(c);}
|
|
||||||
link(level,carts.get(0),carts.get(1));link(level,carts.get(1),carts.get(2));boolean bounced=false;
|
|
||||||
for(int i=0;i<15;i++){tick(level,carts);if(carts.getLast().getDeltaMovement().dot(direction)<-.1){bounced=true;break;}}
|
|
||||||
require(bounced,"whole train hits buffer "+turn);
|
|
||||||
for(var c:carts)require(c.getDeltaMovement().dot(direction)<-.85,"whole train reverses at impact speed "+turn);
|
|
||||||
cleanup(carts);
|
|
||||||
}
|
|
||||||
static void offRailBounce(ServerLevel level){
|
|
||||||
clear(level);level.setBlock(at(4,0,0,0),Blocks.SLIME_BLOCK.defaultBlockState(),2);
|
|
||||||
var cart=cart(level,at(3,0,0,0),new Vec3(1,0,.2));
|
|
||||||
cart.move(MoverType.SELF,cart.getDeltaMovement());SlimeBounce.flush(cart);
|
|
||||||
require(Math.abs(cart.getDeltaMovement().x+1)<.001 && Math.abs(cart.getDeltaMovement().z-.2)<.001,"off-rail bounce preserves tangential speed");cart.discard();
|
|
||||||
}
|
|
||||||
static void persistence(ServerLevel level)throws Exception{
|
|
||||||
build(level,straight(),0);var a=cart(level,at(3,0,0,0),Vec3.ZERO);var b=cart(level,at(5,0,0,0),Vec3.ZERO);link(level,a,b);
|
|
||||||
Trains.show(level);Files.writeString(Path.of("saved-train.txt"),a.getUUID()+"\n"+b.getUUID());
|
|
||||||
}
|
|
||||||
static void restart(ServerLevel level)throws Exception{
|
|
||||||
var ids=Files.readAllLines(Path.of("saved-train.txt"));var data=TrainData.get(level);
|
|
||||||
require(data.links().size()==1,"one saved link after restart");
|
|
||||||
var a=(AbstractMinecart)level.getEntity(UUID.fromString(ids.get(0)));var b=(AbstractMinecart)level.getEntity(UUID.fromString(ids.get(1)));
|
|
||||||
require(a!=null&&b!=null&&Trains.connected(a,b),"saved train restored");Trains.show(level);
|
|
||||||
require(level.getEntitiesOfClass(ChainDisplay.class,a.getBoundingBox().inflate(5)).size()==1,"one chain recreated after restart");
|
|
||||||
}
|
|
||||||
static void require(boolean value,String message){if(!value)throw new AssertionError(message);}
|
|
||||||
}
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
$ErrorActionPreference = 'Stop'
|
|
||||||
$root = Join-Path $PSScriptRoot '../src/main/resources/defaults'
|
|
||||||
function Write-Json($relative, $value) {
|
|
||||||
$path = Join-Path $root $relative
|
|
||||||
New-Item -ItemType Directory -Force (Split-Path $path) | Out-Null
|
|
||||||
$value | ConvertTo-Json -Depth 30 | Set-Content -LiteralPath $path -Encoding utf8NoBOM
|
|
||||||
}
|
|
||||||
function Rail-Model($age, $on, $shape) {
|
|
||||||
$slope = $shape.StartsWith('ascending_')
|
|
||||||
$height = if ($slope) { 9.04 } else { 1.04 }
|
|
||||||
$angle = if ($shape -in @('ascending_south','ascending_west')) { -45 } else { 45 }
|
|
||||||
$elements = @()
|
|
||||||
foreach ($strip in @(@(0,16,'#rail'),@(2,4,'#copper'),@(12,14,'#copper'))) {
|
|
||||||
$y = $height + $(if ($strip[2] -eq '#copper') { .02 } else { 0 })
|
|
||||||
$uv = if ($strip[2] -eq '#copper') { @(4,0,6,16) } else { @(0,0,16,16) }
|
|
||||||
$element = @{from=@($strip[0],$y,0);to=@($strip[1],$y,16);faces=@{
|
|
||||||
up=@{uv=$uv;texture=$strip[2]};down=@{uv=$uv;texture=$strip[2]}
|
|
||||||
}}
|
|
||||||
if ($slope) { $element.rotation=@{origin=@(8,9,8);axis='x';angle=$angle;rescale=$true} }
|
|
||||||
$elements += $element
|
|
||||||
}
|
|
||||||
$copper = @('copper_block','exposed_copper','weathered_copper','oxidized_copper')[$age]
|
|
||||||
$rail = if($on) {'powered_rail_on'} else {'powered_rail'}
|
|
||||||
return @{ambientocclusion=$false;textures=@{rail="minecraft:block/$rail";copper="minecraft:block/$copper";particle="minecraft:block/$copper"};elements=$elements}
|
|
||||||
}
|
|
||||||
$prefixes = @('','exposed_','weathered_','oxidized_')
|
|
||||||
$names = @('Медные рельсы','Потемневшие медные рельсы','Состаренные медные рельсы','Окисленные медные рельсы')
|
|
||||||
$english = @('Copper Rail','Exposed Copper Rail','Weathered Copper Rail','Oxidized Copper Rail')
|
|
||||||
$ru=@{}; $en=@{}
|
|
||||||
for($age=0;$age -lt 4;$age++) {
|
|
||||||
for($wax=0;$wax -lt 2;$wax++) {
|
|
||||||
$id = $(if($wax) {'waxed_'} else {''})+$prefixes[$age]+'copper_rail'
|
|
||||||
$name = $(if($wax) {'Вощёные: '} else {''})+$names[$age]
|
|
||||||
$ru["item.astracontent.$id"]=$name
|
|
||||||
$en["item.astracontent.$id"]=$(if($wax){'Waxed '}else{''})+$english[$age]
|
|
||||||
Write-Json "resources/assets/astracontent/items/$id.json" @{model=@{type='minecraft:model';model="astracontent:item/$id"}}
|
|
||||||
$model = Rail-Model $age $false 'north_south'
|
|
||||||
$model.display=@{gui=@{rotation=@(35,0,0);translation=@(0,0,0);scale=@(1,1,1)};fixed=@{rotation=@(90,0,0)}}
|
|
||||||
Write-Json "resources/assets/astracontent/models/item/$id.json" $model
|
|
||||||
}
|
|
||||||
foreach($shape in @('north_south','east_west','ascending_north','ascending_south','ascending_east','ascending_west')) {
|
|
||||||
foreach($on in @($false,$true)) {
|
|
||||||
$id="rail_display/$age/$shape"+$(if($on){'_on'}else{''})
|
|
||||||
Write-Json "resources/assets/astracontent/models/$id.json" (Rail-Model $age $on $shape)
|
|
||||||
Write-Json "resources/assets/astracontent/items/$id.json" @{model=@{type='minecraft:model';model="astracontent:$id"}}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Write-Json 'resources/assets/astracontent/lang/ru_ru.json' $ru
|
|
||||||
Write-Json 'resources/assets/astracontent/lang/en_us.json' $en
|
|
||||||
Write-Json '../data/astracontent/recipe/copper_rail.json' @{
|
|
||||||
type='minecraft:crafting_shaped';pattern=@('X X','X#X','XRX');key=@{X='minecraft:copper_ingot';'#'='minecraft:stick';R='minecraft:redstone'}
|
|
||||||
result=@{id='minecraft:powered_rail';count=6;components=@{
|
|
||||||
'minecraft:custom_data'=@{'astracontent:rail'=0};'minecraft:item_model'='astracontent:copper_rail'
|
|
||||||
'minecraft:item_name'=@{translate='item.astracontent.copper_rail';fallback='Медные рельсы'}
|
|
||||||
}}
|
|
||||||
}
|
|
||||||
Write-Json '../data/astracontent/advancement/recipes/copper_rail.json' @{
|
|
||||||
parent='minecraft:recipes/root';criteria=@{copper=@{trigger='minecraft:inventory_changed';conditions=@{items=@(@{items='minecraft:copper_ingot'})}}}
|
|
||||||
requirements=@(,@('copper'));rewards=@{recipes=@('astracontent:copper_rail')}
|
|
||||||
}
|
|
||||||
$root = (Resolve-Path $root).Path
|
|
||||||
Get-ChildItem -LiteralPath $root -Recurse -File | Where-Object Name -ne 'index.txt' | ForEach-Object { [IO.Path]::GetRelativePath($root,$_.FullName).Replace('\','/') } | Sort-Object | Set-Content -LiteralPath (Join-Path $root 'index.txt') -Encoding utf8NoBOM
|
|
||||||
Reference in New Issue
Block a user