Declare copper rails through AstraPlus and simplify train state
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
# AstraContent 0.2.3
|
||||
# AstraContent 0.2.4
|
||||
|
||||
Серверный мод для Minecraft 26.2, NeoForge 26.2.0.79 и Java 25.
|
||||
**На клиент мод устанавливать не нужно.** Для медного оформления используется обычный
|
||||
серверный ресурспак AstraPlus. AstraPlus 0.9.2+ обязателен для сборки ресурсов;
|
||||
серверный ресурспак AstraPlus. AstraPlus 0.9.3+ обязателен для сборки ресурсов;
|
||||
AstraPacks раздаёт их игрокам, если установлен и настроен.
|
||||
|
||||
## Арбалет и огненный заряд
|
||||
@@ -115,12 +115,20 @@ Shift + ПКМ киркой по выбранному торцу снимает
|
||||
|
||||
## Установка и разработка
|
||||
|
||||
Рабочий JAR: `C:\Users\ScarPC\Documents\NeoForge Server 26.2\mods\AstraContent-0.2.3.jar`.
|
||||
После установки требуется перезапуск сервера. При запуске добавляются только отсутствующие
|
||||
ресурсы в `astraplus/resources/assets/astracontent`; правки администратора не заменяются.
|
||||
Рабочий JAR: `C:\Users\ScarPC\Documents\NeoForge Server 26.2\mods\AstraContent-0.2.4.jar`.
|
||||
После установки требуется перезапуск сервера. Модели и переводы лежат в `src/main/resources/assets`,
|
||||
автоматически включаются AstraPlus в общий ресурспак прямо из JAR.
|
||||
Индекс файлов и регистрация ресурсов не нужны. Файлы администратора в
|
||||
`astraplus/resources/assets/astracontent` заменяют одноимённые встроенные ресурсы;
|
||||
файлы на диске мод не создаёт и не перезаписывает.
|
||||
При выключенной стартовой сборке ресурспака выполнить `/astraplus build`.
|
||||
Конфигурации, миры и исходники AstraPlus установка JAR не заменяет.
|
||||
|
||||
`CopperRailBlock` объявляет основу, предметную модель и выбор модели по форме/питанию.
|
||||
Идентификаторы блоков, сохранение в чанках, дроп и отображение обслуживает AstraPlus.
|
||||
`CopperRailRecipe` задаёт обычный шаблон крафта и результат по ID блока.
|
||||
Старые сохранённые варианты рельсов переводятся в общий реестр при загрузке чанка.
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat build
|
||||
.\gradlew.bat integrationTest
|
||||
|
||||
+10
-3
@@ -3,10 +3,10 @@ plugins {
|
||||
id("net.neoforged.moddev") version "2.0.146"
|
||||
}
|
||||
group = "online.astradev"
|
||||
version = "0.2.3"
|
||||
version = "0.2.4"
|
||||
repositories { mavenCentral() }
|
||||
dependencies {
|
||||
compileOnly(files("../AstraPlus/build/libs/AstraPlus-0.9.2.jar"))
|
||||
compileOnly(files("../AstraPlus/build/libs/AstraPlus-0.9.3.jar"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.11.4")
|
||||
}
|
||||
@@ -23,10 +23,17 @@ tasks.withType<JavaCompile>().configureEach {
|
||||
options.release.set(25)
|
||||
}
|
||||
tasks.processResources {
|
||||
includeEmptyDirs = false
|
||||
inputs.property("modVersion", project.version)
|
||||
filesMatching("META-INF/neoforge.mods.toml") { expand("version" to project.version) }
|
||||
}
|
||||
tasks.test { useJUnitPlatform() }
|
||||
tasks.test {
|
||||
useJUnitPlatform()
|
||||
workingDir = layout.buildDirectory.dir("test-runtime").get().asFile
|
||||
doFirst { workingDir.mkdirs() }
|
||||
}
|
||||
|
||||
tasks.withType<Jar>().configureEach { includeEmptyDirs = false }
|
||||
sourceSets.test {
|
||||
compileClasspath += sourceSets.main.get().compileClasspath
|
||||
runtimeClasspath += sourceSets.main.get().compileClasspath
|
||||
|
||||
+197
-11
@@ -1,8 +1,21 @@
|
||||
package online.astradev.content.verification;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.DisconnectionDetails;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.PacketFlow;
|
||||
import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket;
|
||||
import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket;
|
||||
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.network.CommonListenerCookie;
|
||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||
import net.minecraft.server.network.ServerConfigurationPacketListenerImpl;
|
||||
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
@@ -23,6 +36,8 @@ import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
|
||||
import online.astradev.content.rail.*;
|
||||
import online.astradev.content.weapon.*;
|
||||
import online.astradev.plus.api.AstraPlusApi;
|
||||
import online.astradev.plus.effect.EffectDisplay;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
@@ -56,6 +71,18 @@ public final class ContentVerification {
|
||||
== Boolean.getBoolean("astracontent.expectedExperimental"),
|
||||
"requested movement engine enabled");
|
||||
if (Files.exists(Path.of("first-pass.txt"))) {
|
||||
var migrated = new BlockPos(10, 100, 90);
|
||||
require(
|
||||
AstraPlusApi.world(level)
|
||||
.block(AstraPlusApi.position(migrated))
|
||||
.equals("astracontent:waxed_weathered_copper_rail"),
|
||||
"Previous rail storage migrates to the shared registry on chunk load");
|
||||
require(
|
||||
previousRailData()
|
||||
.get(AstraPlusApi.world(level), AstraPlusApi.position(migrated))
|
||||
.isEmpty(),
|
||||
"Migrated rail no longer has a second identity");
|
||||
railDisplay(level);
|
||||
for (int age = 0; age < 4; age++)
|
||||
require(
|
||||
Rails.find(level, new BlockPos(2, 100, age * 4)).age() == age,
|
||||
@@ -75,11 +102,14 @@ public final class ContentVerification {
|
||||
return;
|
||||
}
|
||||
setup(level);
|
||||
bundledResources();
|
||||
packResponses(level);
|
||||
ammunition(level);
|
||||
}
|
||||
if (ticks == 129)
|
||||
for (int age = 0; age < 4; age++) previousX[age] = carts.get(age).getX();
|
||||
if (ticks == 130) {
|
||||
railDisplay(level);
|
||||
for (int age = 0; age < 4; age++) {
|
||||
var cart = carts.get(age);
|
||||
double actual = cart.getX() - previousX[age];
|
||||
@@ -95,6 +125,10 @@ public final class ContentVerification {
|
||||
}
|
||||
TrackVerification.run(level);
|
||||
TrainVerification.run(level);
|
||||
var legacy = new BlockPos(10, 100, 90);
|
||||
level.setBlockAndUpdate(legacy.below(), Blocks.STONE.defaultBlockState());
|
||||
level.setBlockAndUpdate(legacy, Blocks.POWERED_RAIL.defaultBlockState());
|
||||
previousRailData().put(AstraPlusApi.world(level), AstraPlusApi.position(legacy), 6);
|
||||
var saved = new Minecart(EntityTypes.MINECART, level);
|
||||
saved.setPos(2.5, 100.0625, .5);
|
||||
saved.setDeltaMovement(.1, 0, 0);
|
||||
@@ -129,6 +163,137 @@ public final class ContentVerification {
|
||||
}
|
||||
}
|
||||
|
||||
private static void packResponses(ServerLevel level) throws Exception {
|
||||
Class<?> runtimeType = Class.forName("online.astradev.packs.PackRuntime");
|
||||
Object runtime = runtimeType.getField("INSTANCE").get(null);
|
||||
Object config = runtimeType.getMethod("config").invoke(runtime);
|
||||
var enabled = config.getClass().getField("enabled");
|
||||
boolean previous = enabled.getBoolean(config);
|
||||
var readyField = EffectDisplay.class.getDeclaredField("READY");
|
||||
readyField.setAccessible(true);
|
||||
@SuppressWarnings("unchecked")
|
||||
var ready = (Set<UUID>) readyField.get(null);
|
||||
var profile = new GameProfile(UUID.randomUUID(), "PackResponseTest");
|
||||
var connection = new Connection(PacketFlow.SERVERBOUND);
|
||||
var cookie = CommonListenerCookie.createInitial(profile, false);
|
||||
var configuration =
|
||||
new ServerConfigurationPacketListenerImpl(level.getServer(), connection, cookie);
|
||||
var gamePlayer = FakePlayerFactory.getMinecraft(level);
|
||||
var previousConnection = gamePlayer.connection;
|
||||
var gameConnection = new Connection(PacketFlow.SERVERBOUND);
|
||||
var gameCookie = CommonListenerCookie.createInitial(gamePlayer.getGameProfile(), false);
|
||||
var game =
|
||||
new ServerGamePacketListenerImpl(
|
||||
level.getServer(), gameConnection, gamePlayer, gameCookie);
|
||||
try {
|
||||
enabled.setBoolean(config, true);
|
||||
for (ServerCommonPacketListenerImpl listener : List.of(configuration, game)) {
|
||||
UUID player = listener.getOwner().id();
|
||||
ready.remove(player);
|
||||
UUID request = UUID.randomUUID();
|
||||
var push =
|
||||
new ClientboundResourcePackPushPacket(
|
||||
request,
|
||||
"http://localhost/test.zip",
|
||||
"0".repeat(40),
|
||||
false,
|
||||
Optional.empty());
|
||||
listener.send(push);
|
||||
listener.handleResourcePackResponse(
|
||||
new ServerboundResourcePackPacket(
|
||||
UUID.randomUUID(),
|
||||
ServerboundResourcePackPacket.Action.SUCCESSFULLY_LOADED));
|
||||
require(!ready.contains(player), "Unrelated pack response ignored");
|
||||
var response =
|
||||
new ServerboundResourcePackPacket(
|
||||
request, ServerboundResourcePackPacket.Action.SUCCESSFULLY_LOADED);
|
||||
listener.handleResourcePackResponse(response);
|
||||
require(
|
||||
ready.contains(player),
|
||||
"AstraPacks response reaches effect renderer: "
|
||||
+ listener.getClass().getSimpleName());
|
||||
listener.send(new ClientboundResourcePackPopPacket(Optional.of(request)));
|
||||
require(
|
||||
!ready.contains(player),
|
||||
"Removing resource pack disables effect rendering");
|
||||
listener.handleResourcePackResponse(response);
|
||||
require(
|
||||
!ready.contains(player),
|
||||
"Removed pack cannot be reactivated by a late reply");
|
||||
}
|
||||
UUID disconnectRequest = UUID.randomUUID();
|
||||
configuration.send(
|
||||
new ClientboundResourcePackPushPacket(
|
||||
disconnectRequest,
|
||||
"http://localhost/test.zip",
|
||||
"0".repeat(40),
|
||||
false,
|
||||
Optional.empty()));
|
||||
var disconnectReply =
|
||||
new ServerboundResourcePackPacket(
|
||||
disconnectRequest,
|
||||
ServerboundResourcePackPacket.Action.SUCCESSFULLY_LOADED);
|
||||
configuration.handleResourcePackResponse(disconnectReply);
|
||||
require(ready.contains(profile.id()), "Configuration ready before disconnect");
|
||||
configuration.onDisconnect(
|
||||
new DisconnectionDetails(Component.literal("Test complete")));
|
||||
configuration.handleResourcePackResponse(disconnectReply);
|
||||
require(
|
||||
!ready.contains(profile.id()),
|
||||
"Disconnected configuration leaves no ready state");
|
||||
System.out.println(
|
||||
"PASS pack responses: configuration, gameplay, stale replies and removal");
|
||||
} finally {
|
||||
gamePlayer.connection = previousConnection;
|
||||
enabled.setBoolean(config, previous);
|
||||
ready.remove(profile.id());
|
||||
ready.remove(game.getOwner().id());
|
||||
}
|
||||
}
|
||||
|
||||
private static void bundledResources() throws Exception {
|
||||
try (var zip = new java.util.zip.ZipFile("astraplus/output/AstraPlus.zip")) {
|
||||
String model = "assets/astracontent/models/rail_display/0/ascending_north.json";
|
||||
var entry = zip.getEntry(model);
|
||||
require(entry != null, "Standard mod assets are included without registration");
|
||||
try (var actual = zip.getInputStream(entry);
|
||||
var source =
|
||||
online.astradev.content.AstraContent.class.getResourceAsStream(
|
||||
"/" + model)) {
|
||||
require(
|
||||
Arrays.equals(actual.readAllBytes(), source.readAllBytes()),
|
||||
"Bundled model is copied intact from the mod JAR");
|
||||
}
|
||||
require(
|
||||
zip.getEntry("assets/astracontent/lang/ru_ru.json") != null,
|
||||
"Bundled translations included");
|
||||
require(zip.getEntry("assets.index") == null, "No resource index required");
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static online.astradev.plus.api.content.BlockData<Integer> previousRailData()
|
||||
throws Exception {
|
||||
var field = Rails.class.getDeclaredField("PREVIOUS_VARIANTS");
|
||||
field.setAccessible(true);
|
||||
return (online.astradev.plus.api.content.BlockData<Integer>) field.get(null);
|
||||
}
|
||||
|
||||
private static void railDisplay(ServerLevel level) {
|
||||
var pos = new BlockPos(2, 100, 0);
|
||||
var displays = level.getEntitiesOfClass(Display.ItemDisplay.class, new AABB(pos));
|
||||
require(displays.size() == 1, "API restores exactly one display per copper rail");
|
||||
var display = displays.getFirst();
|
||||
require(
|
||||
display.entityTags().contains("astraplus:block_part"),
|
||||
"Rail display belongs to the API");
|
||||
require(!display.shouldBeSaved(), "Visual does not duplicate saved block identity");
|
||||
var model = display.getSlot(0).get().get(DataComponents.ITEM_MODEL);
|
||||
require(
|
||||
model.toString().equals("astracontent:rail_display/0/east_west_on"),
|
||||
"API selects the powered model for the native rail shape");
|
||||
}
|
||||
|
||||
private void setup(ServerLevel level) {
|
||||
var ingredients =
|
||||
List.of(
|
||||
@@ -154,7 +319,7 @@ public final class ContentVerification {
|
||||
"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,
|
||||
RailItems.find(RailItems.create(RailKind.decode(code), 1)).code() == code,
|
||||
"item variant " + code);
|
||||
for (int age = 0; age < 4; age++) {
|
||||
int z = age * 4;
|
||||
@@ -176,7 +341,7 @@ public final class ContentVerification {
|
||||
}
|
||||
var pos = new BlockPos(5, 100, 24);
|
||||
level.setBlockAndUpdate(pos.below(), Blocks.STONE.defaultBlockState());
|
||||
var item = Rails.stack(new RailKind(2, false), 2);
|
||||
var item = RailItems.create(new RailKind(2, false), 2);
|
||||
var context =
|
||||
new UseOnContext(
|
||||
level,
|
||||
@@ -188,25 +353,46 @@ public final class ContentVerification {
|
||||
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");
|
||||
var world = AstraPlusApi.world(level);
|
||||
var position = AstraPlusApi.position(pos);
|
||||
require(
|
||||
world.block(position).equals("astracontent:weathered_copper_rail"),
|
||||
"Copper rail belongs to the shared block registry");
|
||||
var placedState = level.getBlockState(pos);
|
||||
require(
|
||||
world.replaceBlock(position, "astracontent:exposed_copper_rail"),
|
||||
"Replace a registered block variant");
|
||||
require(
|
||||
level.getBlockState(pos) == placedState,
|
||||
"Variant replacement retains native shape and power");
|
||||
require(
|
||||
world.blocksInChunk(position)
|
||||
.get(position)
|
||||
.equals("astracontent:exposed_copper_rail"),
|
||||
"Chunk exposes the updated registered identity");
|
||||
Rails.put(level, pos, new RailKind(2, false));
|
||||
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));
|
||||
new 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));
|
||||
new 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));
|
||||
new 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);
|
||||
|
||||
+8
-5
@@ -17,6 +17,7 @@ import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
|
||||
import online.astradev.content.train.*;
|
||||
import online.astradev.content.transport.SlimeBounce;
|
||||
import online.astradev.plus.api.BlockLine;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
@@ -108,6 +109,7 @@ final class TrainVerification {
|
||||
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(Trains.connected(a, b), "connected component after coupling");
|
||||
require(player.getMainHandItem().getCount() == 7, "one chain consumed");
|
||||
click(level, a, Items.IRON_CHAIN, new Vec3(.49, .2, 0));
|
||||
require(
|
||||
@@ -116,13 +118,14 @@ final class TrainVerification {
|
||||
Trains.show(level);
|
||||
Trains.show(level);
|
||||
require(
|
||||
level.getEntitiesOfClass(ChainDisplay.class, a.getBoundingBox().inflate(5)).size()
|
||||
level.getEntitiesOfClass(BlockLine.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(!Trains.connected(a, b), "component cache invalidated after uncoupling");
|
||||
require(
|
||||
level.getEntitiesOfClass(ItemEntity.class, a.getBoundingBox().inflate(5)).size()
|
||||
== drops + 1,
|
||||
@@ -176,7 +179,7 @@ final class TrainVerification {
|
||||
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));
|
||||
CouplingGeometry.restoreFront(c, direction(turn, 1));
|
||||
carts.add(c);
|
||||
}
|
||||
link(level, carts.get(0), carts.get(1));
|
||||
@@ -253,7 +256,7 @@ final class TrainVerification {
|
||||
.subtract(Vec3.atCenterOf(positions.get(i)))
|
||||
.normalize();
|
||||
var c = cart(level, positions.get(i), dir.scale(.3));
|
||||
((CartFrame) c).astracontent$front(dir);
|
||||
CouplingGeometry.restoreFront(c, dir);
|
||||
carts.add(c);
|
||||
}
|
||||
for (int i = 0; i < carts.size() - 1; i++) link(level, carts.get(i), carts.get(i + 1));
|
||||
@@ -333,7 +336,7 @@ final class TrainVerification {
|
||||
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);
|
||||
CouplingGeometry.restoreFront(c, direction);
|
||||
carts.add(c);
|
||||
}
|
||||
link(level, carts.get(0), carts.get(1));
|
||||
@@ -385,7 +388,7 @@ final class TrainVerification {
|
||||
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()
|
||||
level.getEntitiesOfClass(BlockLine.class, a.getBoundingBox().inflate(5)).size()
|
||||
== 1,
|
||||
"one chain recreated after restart");
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ spawn-protection=0
|
||||
max-tick-time=120000
|
||||
'@ | Set-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":true},"astraPacks":{"enabled":false},"editor":{"enabled":false}}' | Set-Content "$output/config/astraplus.json"
|
||||
$plusRoot=Join-Path (Split-Path $project -Parent) 'AstraPlus'
|
||||
$plusVersion=[regex]::Match((Get-Content "$plusRoot/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value
|
||||
$plus=Get-Item -LiteralPath "$plusRoot/build/libs/AstraPlus-$plusVersion.jar"
|
||||
|
||||
@@ -1,22 +1,31 @@
|
||||
package online.astradev.content;
|
||||
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.bus.api.IEventBus;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.fml.loading.FMLPaths;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
|
||||
import online.astradev.content.rail.CopperRailBlock;
|
||||
import online.astradev.content.rail.CopperRailRecipe;
|
||||
import online.astradev.content.rail.RailCommands;
|
||||
import online.astradev.content.rail.RailKind;
|
||||
import online.astradev.content.rail.Rails;
|
||||
import online.astradev.content.train.Trains;
|
||||
import online.astradev.content.transport.SlimeBounce;
|
||||
import online.astradev.content.weapon.Ammunition;
|
||||
import online.astradev.plus.api.content.ContentRegistry;
|
||||
|
||||
@Mod(value = "astracontent", dist = Dist.DEDICATED_SERVER)
|
||||
public final class AstraContent {
|
||||
public AstraContent(IEventBus bus) {
|
||||
Defaults.install(FMLPaths.GAMEDIR.get());
|
||||
Rails.register();
|
||||
public AstraContent() {
|
||||
var content = new ContentRegistry("astracontent");
|
||||
for (RailKind kind : RailKind.variants()) {
|
||||
content.block(kind.id().getPath(), new CopperRailBlock(kind));
|
||||
}
|
||||
content.recipe("copper_rail", new CopperRailRecipe());
|
||||
NeoForge.EVENT_BUS.register(new Rails());
|
||||
NeoForge.EVENT_BUS.register(Ammunition.class);
|
||||
NeoForge.EVENT_BUS.register(online.astradev.content.rail.RailCommands.class);
|
||||
NeoForge.EVENT_BUS.register(online.astradev.content.train.Trains.class);
|
||||
NeoForge.EVENT_BUS.register(online.astradev.content.transport.SlimeBounce.class);
|
||||
NeoForge.EVENT_BUS.register(RailCommands.class);
|
||||
NeoForge.EVENT_BUS.register(Trains.class);
|
||||
NeoForge.EVENT_BUS.register(SlimeBounce.class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package online.astradev.content;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
|
||||
/**
|
||||
* Install absent defaults before AstraPlus loads its catalog. Never overwrite administrator edits.
|
||||
*/
|
||||
public final class Defaults {
|
||||
private Defaults() {}
|
||||
|
||||
public static void install(Path root) {
|
||||
try (var index = Defaults.class.getResourceAsStream("/defaults/index.txt")) {
|
||||
if (index == null) throw new IllegalStateException("Missing content index");
|
||||
for (String name :
|
||||
new String(index.readAllBytes(), StandardCharsets.UTF_8).lines().toList()) {
|
||||
if (name.isBlank()) continue;
|
||||
Path target =
|
||||
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())
|
||||
if (Files.isSymbolicLink(part))
|
||||
throw new IllegalStateException("Symbolic link: " + part);
|
||||
if (Files.exists(target)) continue;
|
||||
Files.createDirectories(target.getParent());
|
||||
try (var stream = Defaults.class.getResourceAsStream("/defaults/" + name)) {
|
||||
if (stream == null) throw new IllegalStateException("Missing default: " + name);
|
||||
Files.copy(stream, target);
|
||||
}
|
||||
}
|
||||
} catch (java.io.IOException e) {
|
||||
throw new IllegalStateException("Cannot install AstraContent defaults", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||
import net.minecraft.world.level.storage.*;
|
||||
|
||||
import online.astradev.content.rail.CartSpeed;
|
||||
import online.astradev.content.rail.RailSpeed;
|
||||
|
||||
import org.spongepowered.asm.mixin.*;
|
||||
@@ -11,7 +12,7 @@ import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.*;
|
||||
|
||||
@Mixin(AbstractMinecart.class)
|
||||
public abstract class MinecartMixin implements online.astradev.content.rail.CartSpeed {
|
||||
public abstract class MinecartMixin implements CartSpeed {
|
||||
@Unique private double astra$speed;
|
||||
|
||||
@Inject(method = "getMaxSpeed", at = @At("RETURN"), cancellable = true)
|
||||
|
||||
@@ -7,15 +7,11 @@ import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.*;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.storage.loot.LootParams;
|
||||
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
|
||||
|
||||
import online.astradev.content.rail.Rails;
|
||||
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mixin(PoweredRailBlock.class)
|
||||
public abstract class RailBlockMixin extends BaseRailBlock {
|
||||
protected RailBlockMixin(boolean straight, Properties properties) {
|
||||
@@ -29,31 +25,4 @@ public abstract class RailBlockMixin extends BaseRailBlock {
|
||||
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;
|
||||
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();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ItemStack getCloneItemStack(
|
||||
LevelReader level, BlockPos pos, BlockState state, boolean includeData) {
|
||||
if (level instanceof ServerLevel server && state.is(Blocks.POWERED_RAIL)) {
|
||||
var kind = Rails.find(server, pos);
|
||||
if (kind != null) return Rails.stack(kind, 1);
|
||||
}
|
||||
return super.getCloneItemStack(level, pos, state, includeData);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
|
||||
import online.astradev.content.rail.Rails;
|
||||
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
@Mixin(LevelChunk.class)
|
||||
public abstract class RailChunkMixin {
|
||||
@Inject(method = "setBlockState", at = @At("RETURN"))
|
||||
private void astra$changed(
|
||||
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,6 +1,7 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||
import net.minecraft.world.level.storage.*;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
@@ -12,33 +13,17 @@ import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(AbstractMinecart.class)
|
||||
public abstract class TrainCartMixin implements CartFrame {
|
||||
@Unique private Vec3 astra$front = Vec3.ZERO;
|
||||
public abstract class TrainCartMixin {
|
||||
@Unique private Vec3 astra$beforePlayerPush;
|
||||
|
||||
@Override
|
||||
public Vec3 astracontent$front() {
|
||||
return astra$front;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void astracontent$front(Vec3 axis) {
|
||||
astra$front = axis;
|
||||
}
|
||||
|
||||
@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 output, CallbackInfo ci) {
|
||||
CouplingGeometry.save((AbstractMinecart) (Object) this, output);
|
||||
}
|
||||
|
||||
@Inject(method = "readAdditionalSaveData", at = @At("RETURN"))
|
||||
private void astra$read(ValueInput in, CallbackInfo ci) {
|
||||
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;
|
||||
private void astra$read(ValueInput input, CallbackInfo ci) {
|
||||
CouplingGeometry.load((AbstractMinecart) (Object) this, input);
|
||||
}
|
||||
|
||||
@Inject(
|
||||
@@ -47,19 +32,16 @@ public abstract class TrainCartMixin implements CartFrame {
|
||||
cancellable = true)
|
||||
private void astra$noInternalCollision(Entity other, CallbackInfo ci) {
|
||||
var self = (AbstractMinecart) (Object) this;
|
||||
astra$beforePlayerPush =
|
||||
other instanceof net.minecraft.world.entity.player.Player
|
||||
? self.getDeltaMovement()
|
||||
: null;
|
||||
astra$beforePlayerPush = other instanceof Player ? self.getDeltaMovement() : null;
|
||||
if (other instanceof AbstractMinecart cart && Trains.connected(self, cart)) ci.cancel();
|
||||
}
|
||||
|
||||
@Inject(method = "push(Lnet/minecraft/world/entity/Entity;)V", at = @At("RETURN"))
|
||||
private void astra$playerPush(Entity other, CallbackInfo ci) {
|
||||
var self = (AbstractMinecart) (Object) this;
|
||||
if (astra$beforePlayerPush != null
|
||||
&& self.getDeltaMovement().subtract(astra$beforePlayerPush).horizontalDistanceSqr()
|
||||
> 1e-12) Trains.playerPush(self);
|
||||
if (astra$beforePlayerPush == null) return;
|
||||
Vec3 impulse = self.getDeltaMovement().subtract(astra$beforePlayerPush);
|
||||
astra$beforePlayerPush = null;
|
||||
if (impulse.horizontalDistanceSqr() > 1e-12) Trains.playerPush(self);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import online.astradev.plus.api.content.RailBlock;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Copper variants inherit powered-rail placement, shape, collision and redstone behavior. */
|
||||
public final class CopperRailBlock extends RailBlock {
|
||||
private static final List<String> NAMES =
|
||||
List.of(
|
||||
"Медные рельсы", "Потемневшие медные рельсы",
|
||||
"Состаренные медные рельсы", "Окисленные медные рельсы");
|
||||
private final int age;
|
||||
|
||||
public CopperRailBlock(RailKind kind) {
|
||||
age = kind.age();
|
||||
base("minecraft:powered_rail");
|
||||
String displayName = NAMES.get(age);
|
||||
if (kind.waxed()) displayName = "Вощёные: " + displayName;
|
||||
name(displayName);
|
||||
itemModel(kind.id().toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String model(String shape, boolean powered) {
|
||||
String path = "astracontent:rail_display/" + age + "/" + shape;
|
||||
return powered ? path + "_on" : path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import online.astradev.plus.api.content.Recipe;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public final class CopperRailRecipe extends Recipe {
|
||||
public CopperRailRecipe() {
|
||||
super(Station.CRAFTING);
|
||||
var ingredients =
|
||||
Map.of(
|
||||
'C', "minecraft:copper_ingot",
|
||||
'S', "minecraft:stick",
|
||||
'R', "minecraft:redstone");
|
||||
pattern(ingredients, "C C", "CSC", "CRC");
|
||||
result("astracontent:copper_rail", 6);
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ public final class RailCommands {
|
||||
private static int give(CommandContext<CommandSourceStack> context, RailKind kind)
|
||||
throws CommandSyntaxException {
|
||||
var player = context.getSource().getPlayerOrException();
|
||||
var stack = Rails.stack(kind, 64);
|
||||
var stack = RailItems.create(kind, 64);
|
||||
AstraPlusApi.give(player, stack);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.Display;
|
||||
import net.minecraft.world.entity.EntityTypes;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.block.PoweredRailBlock;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
|
||||
final class RailDisplay extends Display.ItemDisplay {
|
||||
private String previous;
|
||||
|
||||
RailDisplay(ServerLevel level, BlockPos pos) {
|
||||
super(EntityTypes.ITEM_DISPLAY, level);
|
||||
setPos(pos.getX() + .5, pos.getY() + .5, pos.getZ() + .5);
|
||||
setItemTransform(ItemDisplayContext.NONE);
|
||||
setNoGravity(true);
|
||||
setInvulnerable(true);
|
||||
setSilent(true);
|
||||
}
|
||||
|
||||
void update(RailKind kind, BlockState state) {
|
||||
var shape = state.getValue(PoweredRailBlock.SHAPE);
|
||||
String model =
|
||||
"rail_display/"
|
||||
+ kind.age()
|
||||
+ "/"
|
||||
+ state.getValue(PoweredRailBlock.SHAPE).getSerializedName()
|
||||
+ (state.getValue(PoweredRailBlock.POWERED) ? "_on" : "");
|
||||
if (model.equals(previous)) return;
|
||||
var stack = new ItemStack(Items.PAPER);
|
||||
stack.set(
|
||||
DataComponents.ITEM_MODEL, Identifier.fromNamespaceAndPath("astracontent", model));
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||
|
||||
import org.joml.Quaternionf;
|
||||
|
||||
final class RailDisplayTransform {
|
||||
private RailDisplayTransform() {}
|
||||
|
||||
static Quaternionf orientation(RailShape shape) {
|
||||
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.
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.component.CustomData;
|
||||
|
||||
import online.astradev.plus.api.AstraPlusApi;
|
||||
|
||||
/** Vanilla item, vanilla components: native placement prediction without a client mod. */
|
||||
public final class RailItems {
|
||||
@@ -14,6 +13,9 @@ public final class RailItems {
|
||||
|
||||
public static RailKind find(ItemStack stack) {
|
||||
if (!stack.is(Items.POWERED_RAIL)) return null;
|
||||
var api = AstraPlusApi.current().orElseThrow();
|
||||
var entry = api.find(stack);
|
||||
if (entry.isPresent()) return RailKind.fromId(entry.get().id());
|
||||
var data = stack.get(DataComponents.CUSTOM_DATA);
|
||||
if (data == null) return null;
|
||||
int value = data.copyTag().getIntOr(KEY, -1);
|
||||
@@ -21,26 +23,6 @@ public final class RailItems {
|
||||
}
|
||||
|
||||
public static ItemStack create(RailKind kind, int 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));
|
||||
stack.set(DataComponents.ITEM_MODEL, kind.id());
|
||||
stack.set(
|
||||
DataComponents.ITEM_NAME,
|
||||
Component.translatableWithFallback(
|
||||
"item.astracontent." + kind.id().getPath(), name(kind)));
|
||||
return stack;
|
||||
}
|
||||
|
||||
public static String name(RailKind kind) {
|
||||
return (kind.waxed() ? "Вощёные: " : "")
|
||||
+ new String[] {
|
||||
"Медные рельсы",
|
||||
"Потемневшие медные рельсы",
|
||||
"Состаренные медные рельсы",
|
||||
"Окисленные медные рельсы"
|
||||
}
|
||||
[kind.age()];
|
||||
return AstraPlusApi.current().orElseThrow().create(kind.id(), count);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,21 @@ package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record RailKind(int age, boolean waxed) {
|
||||
private static final List<String> PREFIXES = List.of("", "exposed_", "weathered_", "oxidized_");
|
||||
private static final List<RailKind> VARIANTS =
|
||||
List.of(
|
||||
new RailKind(0, false), new RailKind(1, false),
|
||||
new RailKind(2, false), new RailKind(3, false),
|
||||
new RailKind(0, true), new RailKind(1, true),
|
||||
new RailKind(2, true), new RailKind(3, true));
|
||||
|
||||
public static List<RailKind> variants() {
|
||||
return VARIANTS;
|
||||
}
|
||||
|
||||
public RailKind {
|
||||
if (age < 0 || age > 3) throw new IllegalArgumentException("Oxidation: " + age);
|
||||
}
|
||||
@@ -21,14 +35,23 @@ public record RailKind(int age, boolean waxed) {
|
||||
|
||||
public Identifier id() {
|
||||
return Identifier.fromNamespaceAndPath(
|
||||
"astracontent",
|
||||
(waxed ? "waxed_" : "")
|
||||
+ new String[] {"", "exposed_", "weathered_", "oxidized_"}[age]
|
||||
+ "copper_rail");
|
||||
"astracontent", (waxed ? "waxed_" : "") + PREFIXES.get(age) + "copper_rail");
|
||||
}
|
||||
|
||||
public static RailKind fromId(Identifier id) {
|
||||
for (int code = 0; code < 8; code++) if (decode(code).id().equals(id)) return decode(code);
|
||||
return null;
|
||||
if (!id.getNamespace().equals("astracontent")) return null;
|
||||
int code =
|
||||
switch (id.getPath()) {
|
||||
case "copper_rail" -> 0;
|
||||
case "exposed_copper_rail" -> 1;
|
||||
case "weathered_copper_rail" -> 2;
|
||||
case "oxidized_copper_rail" -> 3;
|
||||
case "waxed_copper_rail" -> 4;
|
||||
case "waxed_exposed_copper_rail" -> 5;
|
||||
case "waxed_weathered_copper_rail" -> 6;
|
||||
case "waxed_oxidized_copper_rail" -> 7;
|
||||
default -> -1;
|
||||
};
|
||||
return code < 0 ? null : VARIANTS.get(code);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,14 +4,13 @@ import static online.astradev.plus.api.AstraPlusApi.position;
|
||||
import static online.astradev.plus.api.AstraPlusApi.world;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.neoforged.bus.api.*;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.neoforged.neoforge.event.level.ChunkEvent;
|
||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||
@@ -25,111 +24,95 @@ import java.util.*;
|
||||
|
||||
/** Native powered rails own placement, shape, redstone, collision and destruction. */
|
||||
public final class Rails {
|
||||
private static final BlockData<Integer> DATA =
|
||||
// Read and retire the storage already used by existing worlds. New blocks use API identities.
|
||||
private static final BlockData<Integer> PREVIOUS_VARIANTS =
|
||||
new ContentRegistry("astracontent")
|
||||
.blockData("copper_rails", BlockData.integers("rails", 0, 7));
|
||||
|
||||
private record Position(ServerLevel level, BlockPos pos) {}
|
||||
|
||||
private record Removed(RailKind kind, long tick) {}
|
||||
private static final Set<Position> ACTIVE = new HashSet<>();
|
||||
|
||||
private static final Map<Position, RailDisplay> ACTIVE = new HashMap<>();
|
||||
private static final Map<Position, Removed> REMOVED = new HashMap<>();
|
||||
|
||||
private Rails() {}
|
||||
|
||||
public static void register() {
|
||||
NeoForge.EVENT_BUS.register(Rails.class);
|
||||
}
|
||||
public Rails() {}
|
||||
|
||||
public static RailKind find(ServerLevel level, BlockPos pos) {
|
||||
var chunk = level.getChunkSource().getChunkNow(pos.getX() >> 4, pos.getZ() >> 4);
|
||||
if (chunk == null) return null;
|
||||
Integer code = DATA.get(world(level), position(pos)).orElse(null);
|
||||
return code == null ? null : RailKind.decode(code);
|
||||
}
|
||||
|
||||
public static RailKind loot(ServerLevel level, BlockPos pos) {
|
||||
var kind = find(level, pos);
|
||||
if (!level.getBlockState(pos).is(Blocks.POWERED_RAIL)) return null;
|
||||
String id = world(level).block(position(pos));
|
||||
var kind = RailKind.fromId(Identifier.parse(id));
|
||||
if (kind != null) return kind;
|
||||
var removed = REMOVED.get(new Position(level, pos));
|
||||
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);
|
||||
Integer code = PREVIOUS_VARIANTS.get(world(level), position(pos)).orElse(null);
|
||||
return code == null ? null : RailKind.decode(code);
|
||||
}
|
||||
|
||||
public static void placed(ServerLevel level, BlockPos pos, ItemStack stack) {
|
||||
clear(level, pos);
|
||||
REMOVED.remove(new Position(level, pos));
|
||||
var kind = RailItems.find(stack);
|
||||
if (kind != null) put(level, pos, kind);
|
||||
}
|
||||
|
||||
public static void put(ServerLevel level, BlockPos pos, RailKind kind) {
|
||||
DATA.put(world(level), position(pos), kind.code());
|
||||
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;
|
||||
var kind = find(level, pos);
|
||||
if (kind != null) {
|
||||
REMOVED.put(
|
||||
new Position(level, pos.immutable()), new Removed(kind, level.getGameTime()));
|
||||
clear(level, pos);
|
||||
var world = world(level);
|
||||
var position = position(pos);
|
||||
if (!world.replaceBlock(position, kind.id().toString())) {
|
||||
throw new IllegalStateException("Cannot place copper rail at " + pos);
|
||||
}
|
||||
PREVIOUS_VARIANTS.remove(world, position);
|
||||
ACTIVE.add(new Position(level, pos.immutable()));
|
||||
}
|
||||
|
||||
private static void clear(ServerLevel level, BlockPos pos) {
|
||||
var chunk = level.getChunkSource().getChunkNow(pos.getX() >> 4, pos.getZ() >> 4);
|
||||
if (chunk != null) DATA.remove(world(level), position(pos));
|
||||
var display = ACTIVE.remove(new Position(level, pos));
|
||||
if (display != null) display.discard();
|
||||
if (chunk != null) PREVIOUS_VARIANTS.remove(world(level), position(pos));
|
||||
ACTIVE.remove(new Position(level, pos));
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void load(ChunkEvent.Load event) {
|
||||
public void load(ChunkEvent.Load event) {
|
||||
if (!(event.getLevel() instanceof ServerLevel level)
|
||||
|| !(event.getChunk() instanceof LevelChunk chunk)) return;
|
||||
level.getServer().execute(() -> restoreDisplays(level, chunk));
|
||||
level.getServer().execute(() -> loadRails(level, chunk));
|
||||
}
|
||||
|
||||
private static void restoreDisplays(ServerLevel level, LevelChunk chunk) {
|
||||
private static void loadRails(ServerLevel level, LevelChunk chunk) {
|
||||
var chunkPos = chunk.getPos();
|
||||
if (level.getChunkSource().getChunkNow(chunkPos.x(), chunkPos.z()) != chunk) return;
|
||||
var origin = new BlockPosition(chunkPos.x() << 4, level.getMinY(), chunkPos.z() << 4);
|
||||
for (var saved : DATA.inChunk(world(level), origin).keySet()) {
|
||||
var world = world(level);
|
||||
for (var saved : PREVIOUS_VARIANTS.inChunk(world, origin).entrySet()) {
|
||||
var position = saved.getKey();
|
||||
var pos = new BlockPos(position.x(), position.y(), position.z());
|
||||
if (level.getBlockState(pos).is(Blocks.POWERED_RAIL))
|
||||
put(level, pos, RailKind.decode(saved.getValue()));
|
||||
else PREVIOUS_VARIANTS.remove(world, position);
|
||||
}
|
||||
for (var entry : world.blocksInChunk(origin).entrySet()) {
|
||||
if (RailKind.fromId(Identifier.parse(entry.getValue())) == null) continue;
|
||||
var saved = entry.getKey();
|
||||
var pos = new BlockPos(saved.x(), saved.y(), saved.z());
|
||||
ACTIVE.putIfAbsent(new Position(level, pos), null);
|
||||
ACTIVE.add(new Position(level, pos));
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void unload(ChunkEvent.Unload event) {
|
||||
for (var key : new ArrayList<>(ACTIVE.keySet()))
|
||||
public void unload(ChunkEvent.Unload event) {
|
||||
for (var key : new ArrayList<>(ACTIVE))
|
||||
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();
|
||||
ACTIVE.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void stopped(ServerStoppedEvent event) {
|
||||
ACTIVE.values().stream().filter(Objects::nonNull).forEach(RailDisplay::discard);
|
||||
public void stopped(ServerStoppedEvent event) {
|
||||
ACTIVE.clear();
|
||||
REMOVED.clear();
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void tick(ServerTickEvent.Post event) {
|
||||
for (var key : new ArrayList<>(ACTIVE.keySet())) {
|
||||
public void tick(ServerTickEvent.Post event) {
|
||||
for (var key : new ArrayList<>(ACTIVE)) {
|
||||
var state = key.level.getBlockState(key.pos);
|
||||
var kind = find(key.level, key.pos);
|
||||
if (kind == null || !state.is(Blocks.POWERED_RAIL)) {
|
||||
@@ -140,19 +123,12 @@ public final class Rails {
|
||||
kind = new RailKind(kind.age() + 1, false);
|
||||
put(key.level, key.pos, kind);
|
||||
}
|
||||
var display = ACTIVE.get(key);
|
||||
if (display == null || display.isRemoved()) {
|
||||
display = new RailDisplay(key.level, key.pos);
|
||||
display.update(kind, state);
|
||||
if (key.level.addFreshEntity(display)) ACTIVE.put(key, display);
|
||||
} else display.update(kind, state);
|
||||
}
|
||||
REMOVED.entrySet()
|
||||
.removeIf(entry -> entry.getValue().tick < entry.getKey().level.getGameTime());
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void use(PlayerInteractEvent.RightClickBlock event) {
|
||||
public void use(PlayerInteractEvent.RightClickBlock event) {
|
||||
if (event.isCanceled()) return;
|
||||
if (!(event.getLevel() instanceof ServerLevel level)) return;
|
||||
var kind = find(level, event.getPos());
|
||||
if (kind == null) return;
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
package online.astradev.content.train;
|
||||
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public interface CartFrame {
|
||||
Vec3 astracontent$front();
|
||||
|
||||
void astracontent$front(Vec3 axis);
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package online.astradev.content.train;
|
||||
|
||||
import com.mojang.math.Transformation;
|
||||
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.Display;
|
||||
import net.minecraft.world.entity.EntityTypes;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
import org.joml.*;
|
||||
|
||||
public final class ChainDisplay extends Display.BlockDisplay {
|
||||
public ChainDisplay(ServerLevel level, BlockState chain) {
|
||||
super(EntityTypes.BLOCK_DISPLAY, level);
|
||||
setBlockState(chain);
|
||||
setNoGravity(true);
|
||||
setInvulnerable(true);
|
||||
setSilent(true);
|
||||
setPosRotInterpolationDuration(1);
|
||||
setTransformationInterpolationDuration(1);
|
||||
}
|
||||
|
||||
public void update(Vec3 a, Vec3 b) {
|
||||
Vec3 delta = b.subtract(a);
|
||||
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);
|
||||
Vec3 mid = a.add(b).scale(.5);
|
||||
setPos(mid);
|
||||
setTransformation(
|
||||
new Transformation(
|
||||
translation, rotation, new Vector3f(1, length, 1), new Quaternionf()));
|
||||
setTransformationInterpolationDelay(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldBeSaved() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean saveAsPassenger(ValueOutput output) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2,40 +2,76 @@ package online.astradev.content.train;
|
||||
|
||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||
import net.minecraft.world.level.block.BaseRailBlock;
|
||||
import net.minecraft.world.level.storage.ValueInput;
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.WeakHashMap;
|
||||
|
||||
public final class CouplingGeometry {
|
||||
// Remember physical ends even when movement reverses. Unloaded carts are not retained.
|
||||
private static final Map<AbstractMinecart, Vec3> FRONTS = new WeakHashMap<>();
|
||||
|
||||
private CouplingGeometry() {}
|
||||
|
||||
public static Vec3 axis(AbstractMinecart cart) {
|
||||
var frame = (CartFrame) cart;
|
||||
var previous = frame.astracontent$front();
|
||||
public static Vec3 front(AbstractMinecart cart) {
|
||||
Vec3 previous = FRONTS.getOrDefault(cart, Vec3.ZERO);
|
||||
if (previous.lengthSqr() < 0.5) previous = facing(cart);
|
||||
Vec3 direction = railDirection(cart);
|
||||
if (direction == null) direction = previous;
|
||||
else if (direction.dot(previous) < 0) direction = direction.scale(-1);
|
||||
FRONTS.put(cart, direction);
|
||||
return direction;
|
||||
}
|
||||
|
||||
private static Vec3 facing(AbstractMinecart cart) {
|
||||
double yaw = Math.toRadians(cart.getYRot());
|
||||
if (previous.lengthSqr() < .5)
|
||||
previous =
|
||||
new Vec3(
|
||||
Math.cos(yaw),
|
||||
0,
|
||||
Math.sin(yaw)
|
||||
* (AbstractMinecart.useExperimentalMovement(cart.level())
|
||||
? -1
|
||||
: 1));
|
||||
double x = Math.cos(yaw);
|
||||
double z = Math.sin(yaw);
|
||||
if (AbstractMinecart.useExperimentalMovement(cart.level())) z = -z;
|
||||
return new Vec3(x, 0, z);
|
||||
}
|
||||
|
||||
public static boolean onRail(AbstractMinecart cart) {
|
||||
var position = cart.getCurrentBlockPosOrRailBelow();
|
||||
return cart.level().getBlockState(position).getBlock() instanceof BaseRailBlock;
|
||||
}
|
||||
|
||||
/** Vanilla exit order, without the persistent choice of a front end; null off rails. */
|
||||
public static Vec3 railDirection(AbstractMinecart cart) {
|
||||
var pos = cart.getCurrentBlockPosOrRailBelow();
|
||||
var state = cart.level().getBlockState(pos);
|
||||
Vec3 axis = previous;
|
||||
if (state.getBlock() instanceof BaseRailBlock rail) {
|
||||
var exits =
|
||||
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 (!(state.getBlock() instanceof BaseRailBlock rail)) return null;
|
||||
var shape = rail.getRailDirection(state, cart.level(), pos, cart);
|
||||
var exits = AbstractMinecart.exits(shape);
|
||||
Vec3 start = new Vec3(exits.getFirst());
|
||||
Vec3 end = new Vec3(exits.getSecond());
|
||||
return end.subtract(start).horizontal().normalize();
|
||||
}
|
||||
|
||||
public static void restoreFront(AbstractMinecart cart, Vec3 direction) {
|
||||
if (!Double.isFinite(direction.x) || !Double.isFinite(direction.z)) {
|
||||
FRONTS.remove(cart);
|
||||
return;
|
||||
}
|
||||
frame.astracontent$front(axis);
|
||||
return axis;
|
||||
FRONTS.put(cart, direction.horizontal().normalize());
|
||||
}
|
||||
|
||||
public static void save(AbstractMinecart cart, ValueOutput output) {
|
||||
Vec3 front = FRONTS.getOrDefault(cart, Vec3.ZERO);
|
||||
output.putDouble("AstraTrainFrontX", front.x);
|
||||
output.putDouble("AstraTrainFrontZ", front.z);
|
||||
}
|
||||
|
||||
public static void load(AbstractMinecart cart, ValueInput input) {
|
||||
double x = input.getDoubleOr("AstraTrainFrontX", 0);
|
||||
double z = input.getDoubleOr("AstraTrainFrontZ", 0);
|
||||
restoreFront(cart, new Vec3(x, 0, z));
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
FRONTS.clear();
|
||||
}
|
||||
|
||||
public static int hitEnd(Vec3 axis, Vec3 localHit) {
|
||||
@@ -46,10 +82,13 @@ public final class CouplingGeometry {
|
||||
}
|
||||
|
||||
public static Vec3 outward(AbstractMinecart cart, int end) {
|
||||
return axis(cart).scale(end == 0 ? 1 : -1);
|
||||
Vec3 direction = front(cart);
|
||||
return end == 0 ? direction : direction.scale(-1);
|
||||
}
|
||||
|
||||
public static Vec3 anchor(AbstractMinecart cart, int end) {
|
||||
return cart.position().add(0, .35, 0).add(outward(cart, end).scale(.48));
|
||||
Vec3 center = cart.position().add(0, 0.35, 0);
|
||||
Vec3 offset = outward(cart, end).scale(0.48);
|
||||
return center.add(offset);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@ public final class TrainData extends SavedData {
|
||||
TrainData::new,
|
||||
CODEC);
|
||||
private final List<Link> links = new ArrayList<>();
|
||||
private final Map<UUID, Set<UUID>> components = new HashMap<>();
|
||||
|
||||
public TrainData() {}
|
||||
|
||||
@@ -73,24 +74,30 @@ public final class TrainData extends SavedData {
|
||||
}
|
||||
|
||||
public Link at(UUID cart, int end) {
|
||||
return links.stream()
|
||||
.filter(l -> l.touches(cart) && l.end(cart) == end)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
for (Link link : links) {
|
||||
if (link.touches(cart) && link.end(cart) == end) return link;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void add(Link link) {
|
||||
links.add(link);
|
||||
components.clear();
|
||||
setDirty();
|
||||
}
|
||||
|
||||
public boolean remove(Link link) {
|
||||
boolean removed = links.remove(link);
|
||||
if (removed) setDirty();
|
||||
if (removed) {
|
||||
components.clear();
|
||||
setDirty();
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
public Set<UUID> component(UUID root) {
|
||||
var cached = components.get(root);
|
||||
if (cached != null) return cached;
|
||||
var seen = new HashSet<UUID>();
|
||||
var pending = new ArrayDeque<UUID>();
|
||||
pending.add(root);
|
||||
@@ -99,6 +106,11 @@ public final class TrainData extends SavedData {
|
||||
if (!seen.add(id)) continue;
|
||||
for (var link : links) if (link.touches(id)) pending.add(link.other(id));
|
||||
}
|
||||
return seen;
|
||||
var component = Set.copyOf(seen);
|
||||
// Collision checks reuse topology until a chain changes; ordinary carts are not cached.
|
||||
if (component.size() > 1) {
|
||||
for (UUID cart : component) components.put(cart, component);
|
||||
}
|
||||
return component;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.tags.ItemTags;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
@@ -18,12 +19,14 @@ import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
|
||||
import online.astradev.plus.api.BlockLine;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class Trains {
|
||||
private record DisplayKey(ServerLevel level, TrainData.Link link) {}
|
||||
|
||||
private static final Map<DisplayKey, ChainDisplay> DISPLAYS = new HashMap<>();
|
||||
private static final Map<DisplayKey, BlockLine> DISPLAYS = new HashMap<>();
|
||||
private static final Map<ServerLevel, Set<UUID>> PAUSED = new HashMap<>();
|
||||
private static final Map<ServerLevel, Set<UUID>> PLAYER_PUSHES = new HashMap<>();
|
||||
|
||||
@@ -50,26 +53,27 @@ public final class Trains {
|
||||
|
||||
@SubscribeEvent
|
||||
public static void interact(PlayerInteractEvent.EntityInteract event) {
|
||||
if (!(event.getTarget() instanceof AbstractMinecart cart)
|
||||
|| !(cart.level() instanceof ServerLevel level)
|
||||
|| !event.getEntity().isShiftKeyDown()) return;
|
||||
var player = event.getEntity();
|
||||
if (!(event.getTarget() instanceof AbstractMinecart cart)) return;
|
||||
if (!(event.getEntity() instanceof ServerPlayer player)) return;
|
||||
if (!player.isShiftKeyDown()) return;
|
||||
var level = player.level();
|
||||
var item = event.getItemStack();
|
||||
boolean chain = isChain(item);
|
||||
if (!chain && !item.is(ItemTags.PICKAXES)) return;
|
||||
event.setCanceled(true);
|
||||
event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
if (!player.mayBuild()) return;
|
||||
int end = CouplingGeometry.hitEnd(CouplingGeometry.axis(cart), event.getLocation());
|
||||
int end = CouplingGeometry.hitEnd(CouplingGeometry.front(cart), event.getLocation());
|
||||
if (end < 0) {
|
||||
message(player, "Цепь крепится только к переднему или заднему торцу.");
|
||||
player.sendSystemMessage(
|
||||
Component.literal("Цепь крепится только к переднему или заднему торцу."), true);
|
||||
return;
|
||||
}
|
||||
var data = TrainData.get(level);
|
||||
var existing = data.at(cart.getUUID(), end);
|
||||
if (!chain) {
|
||||
if (existing == null) {
|
||||
message(player, "На этом торце нет цепи.");
|
||||
player.sendSystemMessage(Component.literal("На этом торце нет цепи."), true);
|
||||
return;
|
||||
}
|
||||
unlink(level, existing, cart, true);
|
||||
@@ -77,7 +81,7 @@ public final class Trains {
|
||||
return;
|
||||
}
|
||||
if (existing != null) {
|
||||
message(player, "Этот торец уже сцеплен.");
|
||||
player.sendSystemMessage(Component.literal("Этот торец уже сцеплен."), true);
|
||||
return;
|
||||
}
|
||||
Vec3 outward = CouplingGeometry.outward(cart, end);
|
||||
@@ -93,13 +97,10 @@ public final class Trains {
|
||||
if (distance < 1 || distance > 3.5 || Math.abs(between.y) > 1.5) continue;
|
||||
var direction = between.horizontal().normalize();
|
||||
if (direction.dot(outward) < .90) continue;
|
||||
int otherEnd = CouplingGeometry.axis(other).dot(direction) > 0 ? 1 : 0;
|
||||
int otherEnd = CouplingGeometry.front(other).dot(direction) > 0 ? 1 : 0;
|
||||
if (CouplingGeometry.outward(other, otherEnd).dot(direction) > -.90
|
||||
|| data.at(other.getUUID(), otherEnd) != null) continue;
|
||||
if (!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock()
|
||||
instanceof BaseRailBlock)
|
||||
|| !(level.getBlockState(other.getCurrentBlockPosOrRailBelow()).getBlock()
|
||||
instanceof BaseRailBlock)) continue;
|
||||
if (!CouplingGeometry.onRail(cart) || !CouplingGeometry.onRail(other)) continue;
|
||||
var hit =
|
||||
level.clip(
|
||||
new ClipContext(
|
||||
@@ -119,15 +120,13 @@ public final class Trains {
|
||||
!player.hasInfiniteMaterials(),
|
||||
distance));
|
||||
item.consume(1, player);
|
||||
message(player, "Вагонетки сцеплены.");
|
||||
player.sendSystemMessage(Component.literal("Вагонетки сцеплены."), true);
|
||||
return;
|
||||
}
|
||||
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);
|
||||
player.sendSystemMessage(
|
||||
Component.literal(
|
||||
"У этого торца нет подходящей свободной вагонетки в пределах 3,5 блока."),
|
||||
true);
|
||||
}
|
||||
|
||||
public static void unlink(ServerLevel level, TrainData.Link link, Entity at, boolean refund) {
|
||||
@@ -196,7 +195,8 @@ public final class Trains {
|
||||
var carts = new LinkedHashMap<UUID, AbstractMinecart>();
|
||||
var axes = new HashMap<UUID, Vec3>();
|
||||
boolean paused = false;
|
||||
double momentum = 0, limit = Double.MAX_VALUE;
|
||||
double momentum = 0;
|
||||
double limit = Double.MAX_VALUE;
|
||||
double controlledMomentum = 0;
|
||||
var controls = new HashSet<UUID>();
|
||||
for (var pair : signs.entrySet()) {
|
||||
@@ -206,10 +206,9 @@ public final class Trains {
|
||||
continue;
|
||||
}
|
||||
carts.put(pair.getKey(), cart);
|
||||
Vec3 tangent = CouplingGeometry.axis(cart).scale(pair.getValue());
|
||||
Vec3 tangent = CouplingGeometry.front(cart).scale(pair.getValue());
|
||||
axes.put(pair.getKey(), tangent);
|
||||
if (!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock()
|
||||
instanceof BaseRailBlock)) paused = true;
|
||||
if (!CouplingGeometry.onRail(cart)) paused = true;
|
||||
double scale = travelScale(cart);
|
||||
momentum += cart.getDeltaMovement().dot(tangent) * scale;
|
||||
if (playerControls(cart, playerPushes)) {
|
||||
@@ -226,13 +225,9 @@ public final class Trains {
|
||||
}
|
||||
// Player input drives the train as a unit. Averaging it with idle carts diluted
|
||||
// the tiny vanilla rider impulse; a dot product also erased side-on walking pushes.
|
||||
double speed =
|
||||
Math.clamp(
|
||||
!controls.isEmpty()
|
||||
? controlledMomentum / controls.size()
|
||||
: momentum / carts.size(),
|
||||
-limit,
|
||||
limit);
|
||||
double speed = momentum / carts.size();
|
||||
if (!controls.isEmpty()) speed = controlledMomentum / controls.size();
|
||||
speed = Math.clamp(speed, -limit, limit);
|
||||
var corrections = new HashMap<UUID, Double>();
|
||||
for (var link : links)
|
||||
if (carts.containsKey(link.a()) && carts.containsKey(link.b())) {
|
||||
@@ -252,15 +247,13 @@ public final class Trains {
|
||||
// Followers take up slack; pulling back the driven cart would cancel its 0.001
|
||||
// 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));
|
||||
double cartSpeed = speed;
|
||||
if (!controls.contains(pair.getKey())) {
|
||||
cartSpeed += corrections.getOrDefault(pair.getKey(), 0.0);
|
||||
}
|
||||
cartSpeed = Math.clamp(cartSpeed, -limit, limit);
|
||||
Vec3 direction = axes.get(pair.getKey());
|
||||
Vec3 velocity = direction.scale(cartSpeed / travelScale(cart));
|
||||
cart.setDeltaMovement(velocity.x, cart.getDeltaMovement().y, velocity.z);
|
||||
}
|
||||
}
|
||||
@@ -287,8 +280,7 @@ public final class Trains {
|
||||
|
||||
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;
|
||||
if (!(cart.getFirstPassenger() instanceof ServerPlayer player)) return false;
|
||||
return player.getLastClientMoveIntent().horizontalDistanceSqr() > 0;
|
||||
}
|
||||
|
||||
@@ -302,21 +294,11 @@ public final class Trains {
|
||||
var movement = cart.getDeltaMovement();
|
||||
double along = movement.dot(tangent);
|
||||
if (Math.abs(along) < 1e-9) {
|
||||
var pos = cart.getCurrentBlockPosOrRailBelow();
|
||||
var state = cart.level().getBlockState(pos);
|
||||
if (state.getBlock() instanceof BaseRailBlock rail) {
|
||||
var exits =
|
||||
AbstractMinecart.exits(
|
||||
rail.getRailDirection(state, cart.level(), pos, cart));
|
||||
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);
|
||||
Vec3 railDirection = CouplingGeometry.railDirection(cart);
|
||||
if (railDirection != null) {
|
||||
along = railDirection.dot(tangent);
|
||||
// Vanilla reverses the default exit for perpendicular input in the new engine.
|
||||
if (AbstractMinecart.useExperimentalMovement(cart.level())) along = -along;
|
||||
}
|
||||
}
|
||||
return Math.copySign(movement.horizontalDistance(), along);
|
||||
@@ -336,19 +318,15 @@ public final class Trains {
|
||||
var key = new DisplayKey(level, link);
|
||||
keys.add(key);
|
||||
var display = DISPLAYS.get(key);
|
||||
if (display == null || display.isRemoved()) {
|
||||
display =
|
||||
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);
|
||||
} else
|
||||
display.update(
|
||||
CouplingGeometry.anchor(a, link.endA()),
|
||||
CouplingGeometry.anchor(b, link.endB()));
|
||||
boolean create = display == null || display.isRemoved();
|
||||
if (create) {
|
||||
var chain = (BlockItem) chainItem(link);
|
||||
display = new BlockLine(level, chain.getBlock().defaultBlockState());
|
||||
}
|
||||
Vec3 start = CouplingGeometry.anchor(a, link.endA());
|
||||
Vec3 end = CouplingGeometry.anchor(b, link.endB());
|
||||
display.connect(start, end);
|
||||
if (create && level.addFreshEntity(display)) DISPLAYS.put(key, display);
|
||||
}
|
||||
for (var key : new ArrayList<>(DISPLAYS.keySet()))
|
||||
if (key.level == level && !keys.contains(key)) discard(key);
|
||||
@@ -365,12 +343,12 @@ public final class Trains {
|
||||
// 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.front(hit));
|
||||
for (var id : ids) {
|
||||
var cart = cart(level, id);
|
||||
if (cart != null) {
|
||||
var v =
|
||||
CouplingGeometry.axis(cart)
|
||||
CouplingGeometry.front(cart)
|
||||
.scale(speed * signs.getOrDefault(id, 1) / travelScale(cart));
|
||||
cart.setDeltaMovement(v.x, cart.getDeltaMovement().y, v.z);
|
||||
}
|
||||
@@ -387,5 +365,6 @@ public final class Trains {
|
||||
for (var key : new ArrayList<>(DISPLAYS.keySet())) discard(key);
|
||||
PAUSED.clear();
|
||||
PLAYER_PUSHES.clear();
|
||||
CouplingGeometry.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
public net.minecraft.world.entity.Display setTransformation(Lcom/mojang/math/Transformation;)V
|
||||
public net.minecraft.world.entity.Display$ItemDisplay setItemTransform(Lnet/minecraft/world/item/ItemDisplayContext;)V
|
||||
public net.minecraft.world.entity.Display$BlockDisplay setBlockState(Lnet/minecraft/world/level/block/state/BlockState;)V
|
||||
public net.minecraft.world.entity.Display setPosRotInterpolationDuration(I)V
|
||||
public net.minecraft.world.entity.Display setTransformationInterpolationDuration(I)V
|
||||
public net.minecraft.world.entity.Display setTransformationInterpolationDelay(I)V
|
||||
|
||||
@@ -21,6 +21,6 @@ side="SERVER"
|
||||
[[dependencies.astracontent]]
|
||||
modId="astraplus"
|
||||
type="required"
|
||||
versionRange="[0.9.2,0.10)"
|
||||
versionRange="[0.9.3,0.10)"
|
||||
ordering="AFTER"
|
||||
side="SERVER"
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"item.astracontent.waxed_oxidized_copper_rail": "Waxed Oxidized Copper Rail",
|
||||
"item.astracontent.waxed_exposed_copper_rail": "Waxed Exposed Copper Rail",
|
||||
"item.astracontent.waxed_copper_rail": "Waxed Copper Rail",
|
||||
"item.astracontent.copper_rail": "Copper Rail",
|
||||
"item.astracontent.waxed_weathered_copper_rail": "Waxed Weathered Copper Rail",
|
||||
"item.astracontent.oxidized_copper_rail": "Oxidized Copper Rail",
|
||||
"item.astracontent.weathered_copper_rail": "Weathered Copper Rail",
|
||||
"item.astracontent.exposed_copper_rail": "Exposed Copper Rail",
|
||||
"block.astracontent.waxed_oxidized_copper_rail": "Waxed Oxidized Copper Rail",
|
||||
"block.astracontent.waxed_exposed_copper_rail": "Waxed Exposed Copper Rail",
|
||||
"block.astracontent.waxed_copper_rail": "Waxed Copper Rail",
|
||||
"block.astracontent.copper_rail": "Copper Rail",
|
||||
"block.astracontent.waxed_weathered_copper_rail": "Waxed Weathered Copper Rail",
|
||||
"block.astracontent.oxidized_copper_rail": "Oxidized Copper Rail",
|
||||
"block.astracontent.weathered_copper_rail": "Weathered Copper Rail",
|
||||
"block.astracontent.exposed_copper_rail": "Exposed Copper Rail"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"item.astracontent.waxed_oxidized_copper_rail": "Вощёные: Окисленные медные рельсы",
|
||||
"item.astracontent.waxed_exposed_copper_rail": "Вощёные: Потемневшие медные рельсы",
|
||||
"item.astracontent.waxed_copper_rail": "Вощёные: Медные рельсы",
|
||||
"item.astracontent.copper_rail": "Медные рельсы",
|
||||
"item.astracontent.waxed_weathered_copper_rail": "Вощёные: Состаренные медные рельсы",
|
||||
"item.astracontent.oxidized_copper_rail": "Окисленные медные рельсы",
|
||||
"item.astracontent.weathered_copper_rail": "Состаренные медные рельсы",
|
||||
"item.astracontent.exposed_copper_rail": "Потемневшие медные рельсы",
|
||||
"block.astracontent.waxed_oxidized_copper_rail": "Вощёные: Окисленные медные рельсы",
|
||||
"block.astracontent.waxed_exposed_copper_rail": "Вощёные: Потемневшие медные рельсы",
|
||||
"block.astracontent.waxed_copper_rail": "Вощёные: Медные рельсы",
|
||||
"block.astracontent.copper_rail": "Медные рельсы",
|
||||
"block.astracontent.waxed_weathered_copper_rail": "Вощёные: Состаренные медные рельсы",
|
||||
"block.astracontent.oxidized_copper_rail": "Окисленные медные рельсы",
|
||||
"block.astracontent.weathered_copper_rail": "Состаренные медные рельсы",
|
||||
"block.astracontent.exposed_copper_rail": "Потемневшие медные рельсы"
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user