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.
|
Серверный мод для Minecraft 26.2, NeoForge 26.2.0.79 и Java 25.
|
||||||
**На клиент мод устанавливать не нужно.** Для медного оформления используется обычный
|
**На клиент мод устанавливать не нужно.** Для медного оформления используется обычный
|
||||||
серверный ресурспак AstraPlus. AstraPlus 0.9.2+ обязателен для сборки ресурсов;
|
серверный ресурспак AstraPlus. AstraPlus 0.9.3+ обязателен для сборки ресурсов;
|
||||||
AstraPacks раздаёт их игрокам, если установлен и настроен.
|
AstraPacks раздаёт их игрокам, если установлен и настроен.
|
||||||
|
|
||||||
## Арбалет и огненный заряд
|
## Арбалет и огненный заряд
|
||||||
@@ -115,12 +115,20 @@ Shift + ПКМ киркой по выбранному торцу снимает
|
|||||||
|
|
||||||
## Установка и разработка
|
## Установка и разработка
|
||||||
|
|
||||||
Рабочий JAR: `C:\Users\ScarPC\Documents\NeoForge Server 26.2\mods\AstraContent-0.2.3.jar`.
|
Рабочий JAR: `C:\Users\ScarPC\Documents\NeoForge Server 26.2\mods\AstraContent-0.2.4.jar`.
|
||||||
После установки требуется перезапуск сервера. При запуске добавляются только отсутствующие
|
После установки требуется перезапуск сервера. Модели и переводы лежат в `src/main/resources/assets`,
|
||||||
ресурсы в `astraplus/resources/assets/astracontent`; правки администратора не заменяются.
|
автоматически включаются AstraPlus в общий ресурспак прямо из JAR.
|
||||||
|
Индекс файлов и регистрация ресурсов не нужны. Файлы администратора в
|
||||||
|
`astraplus/resources/assets/astracontent` заменяют одноимённые встроенные ресурсы;
|
||||||
|
файлы на диске мод не создаёт и не перезаписывает.
|
||||||
При выключенной стартовой сборке ресурспака выполнить `/astraplus build`.
|
При выключенной стартовой сборке ресурспака выполнить `/astraplus build`.
|
||||||
Конфигурации, миры и исходники AstraPlus установка JAR не заменяет.
|
Конфигурации, миры и исходники AstraPlus установка JAR не заменяет.
|
||||||
|
|
||||||
|
`CopperRailBlock` объявляет основу, предметную модель и выбор модели по форме/питанию.
|
||||||
|
Идентификаторы блоков, сохранение в чанках, дроп и отображение обслуживает AstraPlus.
|
||||||
|
`CopperRailRecipe` задаёт обычный шаблон крафта и результат по ID блока.
|
||||||
|
Старые сохранённые варианты рельсов переводятся в общий реестр при загрузке чанка.
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
.\gradlew.bat build
|
.\gradlew.bat build
|
||||||
.\gradlew.bat integrationTest
|
.\gradlew.bat integrationTest
|
||||||
|
|||||||
+10
-3
@@ -3,10 +3,10 @@ plugins {
|
|||||||
id("net.neoforged.moddev") version "2.0.146"
|
id("net.neoforged.moddev") version "2.0.146"
|
||||||
}
|
}
|
||||||
group = "online.astradev"
|
group = "online.astradev"
|
||||||
version = "0.2.3"
|
version = "0.2.4"
|
||||||
repositories { mavenCentral() }
|
repositories { mavenCentral() }
|
||||||
dependencies {
|
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")
|
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.11.4")
|
testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.11.4")
|
||||||
}
|
}
|
||||||
@@ -23,10 +23,17 @@ tasks.withType<JavaCompile>().configureEach {
|
|||||||
options.release.set(25)
|
options.release.set(25)
|
||||||
}
|
}
|
||||||
tasks.processResources {
|
tasks.processResources {
|
||||||
|
includeEmptyDirs = false
|
||||||
inputs.property("modVersion", project.version)
|
inputs.property("modVersion", project.version)
|
||||||
filesMatching("META-INF/neoforge.mods.toml") { expand("version" to 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 {
|
sourceSets.test {
|
||||||
compileClasspath += sourceSets.main.get().compileClasspath
|
compileClasspath += sourceSets.main.get().compileClasspath
|
||||||
runtimeClasspath += sourceSets.main.get().compileClasspath
|
runtimeClasspath += sourceSets.main.get().compileClasspath
|
||||||
|
|||||||
+197
-11
@@ -1,8 +1,21 @@
|
|||||||
package online.astradev.content.verification;
|
package online.astradev.content.verification;
|
||||||
|
|
||||||
|
import com.mojang.authlib.GameProfile;
|
||||||
|
|
||||||
import net.minecraft.core.*;
|
import net.minecraft.core.*;
|
||||||
import net.minecraft.core.component.DataComponents;
|
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.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.InteractionHand;
|
||||||
import net.minecraft.world.entity.*;
|
import net.minecraft.world.entity.*;
|
||||||
import net.minecraft.world.entity.item.ItemEntity;
|
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.rail.*;
|
||||||
import online.astradev.content.weapon.*;
|
import online.astradev.content.weapon.*;
|
||||||
|
import online.astradev.plus.api.AstraPlusApi;
|
||||||
|
import online.astradev.plus.effect.EffectDisplay;
|
||||||
|
|
||||||
import java.nio.file.*;
|
import java.nio.file.*;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
@@ -56,6 +71,18 @@ public final class ContentVerification {
|
|||||||
== Boolean.getBoolean("astracontent.expectedExperimental"),
|
== Boolean.getBoolean("astracontent.expectedExperimental"),
|
||||||
"requested movement engine enabled");
|
"requested movement engine enabled");
|
||||||
if (Files.exists(Path.of("first-pass.txt"))) {
|
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++)
|
for (int age = 0; age < 4; age++)
|
||||||
require(
|
require(
|
||||||
Rails.find(level, new BlockPos(2, 100, age * 4)).age() == age,
|
Rails.find(level, new BlockPos(2, 100, age * 4)).age() == age,
|
||||||
@@ -75,11 +102,14 @@ public final class ContentVerification {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setup(level);
|
setup(level);
|
||||||
|
bundledResources();
|
||||||
|
packResponses(level);
|
||||||
ammunition(level);
|
ammunition(level);
|
||||||
}
|
}
|
||||||
if (ticks == 129)
|
if (ticks == 129)
|
||||||
for (int age = 0; age < 4; age++) previousX[age] = carts.get(age).getX();
|
for (int age = 0; age < 4; age++) previousX[age] = carts.get(age).getX();
|
||||||
if (ticks == 130) {
|
if (ticks == 130) {
|
||||||
|
railDisplay(level);
|
||||||
for (int age = 0; age < 4; age++) {
|
for (int age = 0; age < 4; age++) {
|
||||||
var cart = carts.get(age);
|
var cart = carts.get(age);
|
||||||
double actual = cart.getX() - previousX[age];
|
double actual = cart.getX() - previousX[age];
|
||||||
@@ -95,6 +125,10 @@ public final class ContentVerification {
|
|||||||
}
|
}
|
||||||
TrackVerification.run(level);
|
TrackVerification.run(level);
|
||||||
TrainVerification.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);
|
var saved = new Minecart(EntityTypes.MINECART, level);
|
||||||
saved.setPos(2.5, 100.0625, .5);
|
saved.setPos(2.5, 100.0625, .5);
|
||||||
saved.setDeltaMovement(.1, 0, 0);
|
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) {
|
private void setup(ServerLevel level) {
|
||||||
var ingredients =
|
var ingredients =
|
||||||
List.of(
|
List.of(
|
||||||
@@ -154,7 +319,7 @@ public final class ContentVerification {
|
|||||||
"native crafting recipe makes six copper rails");
|
"native crafting recipe makes six copper rails");
|
||||||
for (int code = 0; code < 8; code++)
|
for (int code = 0; code < 8; code++)
|
||||||
require(
|
require(
|
||||||
RailItems.find(Rails.stack(RailKind.decode(code), 1)).code() == code,
|
RailItems.find(RailItems.create(RailKind.decode(code), 1)).code() == code,
|
||||||
"item variant " + code);
|
"item variant " + code);
|
||||||
for (int age = 0; age < 4; age++) {
|
for (int age = 0; age < 4; age++) {
|
||||||
int z = age * 4;
|
int z = age * 4;
|
||||||
@@ -176,7 +341,7 @@ public final class ContentVerification {
|
|||||||
}
|
}
|
||||||
var pos = new BlockPos(5, 100, 24);
|
var pos = new BlockPos(5, 100, 24);
|
||||||
level.setBlockAndUpdate(pos.below(), Blocks.STONE.defaultBlockState());
|
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 =
|
var context =
|
||||||
new UseOnContext(
|
new UseOnContext(
|
||||||
level,
|
level,
|
||||||
@@ -188,25 +353,46 @@ public final class ContentVerification {
|
|||||||
require(item.getItem().useOn(context).consumesAction(), "native BlockItem placement");
|
require(item.getItem().useOn(context).consumesAction(), "native BlockItem placement");
|
||||||
require(level.getBlockState(pos).is(Blocks.POWERED_RAIL), "real vanilla carrier");
|
require(level.getBlockState(pos).is(Blocks.POWERED_RAIL), "real vanilla carrier");
|
||||||
require(Rails.find(level, pos).age() == 2, "placement preserves variant");
|
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");
|
require(item.getCount() == 1, "placement consumes exactly one");
|
||||||
var player = FakePlayerFactory.getMinecraft(level);
|
var player = FakePlayerFactory.getMinecraft(level);
|
||||||
player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.HONEYCOMB, 2));
|
player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.HONEYCOMB, 2));
|
||||||
var hit = new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false);
|
var hit = new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false);
|
||||||
Rails.use(
|
new Rails()
|
||||||
new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickBlock(
|
.use(
|
||||||
player, InteractionHand.MAIN_HAND, pos, hit));
|
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(Rails.find(level, pos).waxed(), "waxing native rail");
|
||||||
require(player.getMainHandItem().getCount() == 1, "wax consumes one honeycomb");
|
require(player.getMainHandItem().getCount() == 1, "wax consumes one honeycomb");
|
||||||
player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.IRON_AXE));
|
player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.IRON_AXE));
|
||||||
Rails.use(
|
new Rails()
|
||||||
new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickBlock(
|
.use(
|
||||||
player, InteractionHand.MAIN_HAND, pos, hit));
|
new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent
|
||||||
|
.RightClickBlock(player, InteractionHand.MAIN_HAND, pos, hit));
|
||||||
require(
|
require(
|
||||||
!Rails.find(level, pos).waxed() && Rails.find(level, pos).age() == 2,
|
!Rails.find(level, pos).waxed() && Rails.find(level, pos).age() == 2,
|
||||||
"axe removes wax first");
|
"axe removes wax first");
|
||||||
Rails.use(
|
new Rails()
|
||||||
new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickBlock(
|
.use(
|
||||||
player, InteractionHand.MAIN_HAND, pos, hit));
|
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");
|
require(Rails.find(level, pos).age() == 1, "axe removes one oxidation stage");
|
||||||
Rails.put(level, pos, new RailKind(2, false));
|
Rails.put(level, pos, new RailKind(2, false));
|
||||||
var drops = Block.getDrops(level.getBlockState(pos), level, pos, null);
|
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.train.*;
|
||||||
import online.astradev.content.transport.SlimeBounce;
|
import online.astradev.content.transport.SlimeBounce;
|
||||||
|
import online.astradev.plus.api.BlockLine;
|
||||||
|
|
||||||
import java.nio.file.*;
|
import java.nio.file.*;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
@@ -108,6 +109,7 @@ final class TrainVerification {
|
|||||||
require(data.links().isEmpty(), "side cannot attach");
|
require(data.links().isEmpty(), "side cannot attach");
|
||||||
click(level, a, Items.IRON_CHAIN, new Vec3(.49, .2, 0));
|
click(level, a, Items.IRON_CHAIN, new Vec3(.49, .2, 0));
|
||||||
require(data.links().size() == 1, "front auto couples");
|
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");
|
require(player.getMainHandItem().getCount() == 7, "one chain consumed");
|
||||||
click(level, a, Items.IRON_CHAIN, new Vec3(.49, .2, 0));
|
click(level, a, Items.IRON_CHAIN, new Vec3(.49, .2, 0));
|
||||||
require(
|
require(
|
||||||
@@ -116,13 +118,14 @@ final class TrainVerification {
|
|||||||
Trains.show(level);
|
Trains.show(level);
|
||||||
Trains.show(level);
|
Trains.show(level);
|
||||||
require(
|
require(
|
||||||
level.getEntitiesOfClass(ChainDisplay.class, a.getBoundingBox().inflate(5)).size()
|
level.getEntitiesOfClass(BlockLine.class, a.getBoundingBox().inflate(5)).size()
|
||||||
== 1,
|
== 1,
|
||||||
"one visible vanilla chain");
|
"one visible vanilla chain");
|
||||||
int drops =
|
int drops =
|
||||||
level.getEntitiesOfClass(ItemEntity.class, a.getBoundingBox().inflate(5)).size();
|
level.getEntitiesOfClass(ItemEntity.class, a.getBoundingBox().inflate(5)).size();
|
||||||
click(level, b, Items.IRON_PICKAXE, new Vec3(-.49, .2, 0));
|
click(level, b, Items.IRON_PICKAXE, new Vec3(-.49, .2, 0));
|
||||||
require(data.links().isEmpty(), "detach from opposite end");
|
require(data.links().isEmpty(), "detach from opposite end");
|
||||||
|
require(!Trains.connected(a, b), "component cache invalidated after uncoupling");
|
||||||
require(
|
require(
|
||||||
level.getEntitiesOfClass(ItemEntity.class, a.getBoundingBox().inflate(5)).size()
|
level.getEntitiesOfClass(ItemEntity.class, a.getBoundingBox().inflate(5)).size()
|
||||||
== drops + 1,
|
== drops + 1,
|
||||||
@@ -176,7 +179,7 @@ final class TrainVerification {
|
|||||||
var carts = new ArrayList<Minecart>();
|
var carts = new ArrayList<Minecart>();
|
||||||
for (int i = 0; i < 3; i++) {
|
for (int i = 0; i < 3; i++) {
|
||||||
var c = cart(level, path.get(1 + i * 2).pos(), direction(turn, .5));
|
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);
|
carts.add(c);
|
||||||
}
|
}
|
||||||
link(level, carts.get(0), carts.get(1));
|
link(level, carts.get(0), carts.get(1));
|
||||||
@@ -253,7 +256,7 @@ final class TrainVerification {
|
|||||||
.subtract(Vec3.atCenterOf(positions.get(i)))
|
.subtract(Vec3.atCenterOf(positions.get(i)))
|
||||||
.normalize();
|
.normalize();
|
||||||
var c = cart(level, positions.get(i), dir.scale(.3));
|
var c = cart(level, positions.get(i), dir.scale(.3));
|
||||||
((CartFrame) c).astracontent$front(dir);
|
CouplingGeometry.restoreFront(c, dir);
|
||||||
carts.add(c);
|
carts.add(c);
|
||||||
}
|
}
|
||||||
for (int i = 0; i < carts.size() - 1; i++) link(level, carts.get(i), carts.get(i + 1));
|
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);
|
var direction = direction(turn, 1);
|
||||||
for (int x = 4; x <= 8; x += 2) {
|
for (int x = 4; x <= 8; x += 2) {
|
||||||
var c = cart(level, at(x, 0, 0, turn), direction);
|
var c = cart(level, at(x, 0, 0, turn), direction);
|
||||||
((CartFrame) c).astracontent$front(direction);
|
CouplingGeometry.restoreFront(c, direction);
|
||||||
carts.add(c);
|
carts.add(c);
|
||||||
}
|
}
|
||||||
link(level, carts.get(0), carts.get(1));
|
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");
|
require(a != null && b != null && Trains.connected(a, b), "saved train restored");
|
||||||
Trains.show(level);
|
Trains.show(level);
|
||||||
require(
|
require(
|
||||||
level.getEntitiesOfClass(ChainDisplay.class, a.getBoundingBox().inflate(5)).size()
|
level.getEntitiesOfClass(BlockLine.class, a.getBoundingBox().inflate(5)).size()
|
||||||
== 1,
|
== 1,
|
||||||
"one chain recreated after restart");
|
"one chain recreated after restart");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ spawn-protection=0
|
|||||||
max-tick-time=120000
|
max-tick-time=120000
|
||||||
'@ | Set-Content "$output/server.properties"
|
'@ | Set-Content "$output/server.properties"
|
||||||
if($Experimental){'initial-enabled-packs=vanilla,minecart_improvements' | Add-Content "$output/server.properties"}
|
if($Experimental){'initial-enabled-packs=vanilla,minecart_improvements' | Add-Content "$output/server.properties"}
|
||||||
'{"build":{"onStartup":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'
|
$plusRoot=Join-Path (Split-Path $project -Parent) 'AstraPlus'
|
||||||
$plusVersion=[regex]::Match((Get-Content "$plusRoot/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value
|
$plusVersion=[regex]::Match((Get-Content "$plusRoot/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value
|
||||||
$plus=Get-Item -LiteralPath "$plusRoot/build/libs/AstraPlus-$plusVersion.jar"
|
$plus=Get-Item -LiteralPath "$plusRoot/build/libs/AstraPlus-$plusVersion.jar"
|
||||||
|
|||||||
@@ -1,22 +1,31 @@
|
|||||||
package online.astradev.content;
|
package online.astradev.content;
|
||||||
|
|
||||||
import net.neoforged.api.distmarker.Dist;
|
import net.neoforged.api.distmarker.Dist;
|
||||||
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.neoforge.common.NeoForge;
|
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.rail.Rails;
|
||||||
|
import online.astradev.content.train.Trains;
|
||||||
|
import online.astradev.content.transport.SlimeBounce;
|
||||||
import online.astradev.content.weapon.Ammunition;
|
import online.astradev.content.weapon.Ammunition;
|
||||||
|
import online.astradev.plus.api.content.ContentRegistry;
|
||||||
|
|
||||||
@Mod(value = "astracontent", dist = Dist.DEDICATED_SERVER)
|
@Mod(value = "astracontent", dist = Dist.DEDICATED_SERVER)
|
||||||
public final class AstraContent {
|
public final class AstraContent {
|
||||||
public AstraContent(IEventBus bus) {
|
public AstraContent() {
|
||||||
Defaults.install(FMLPaths.GAMEDIR.get());
|
var content = new ContentRegistry("astracontent");
|
||||||
Rails.register();
|
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(Ammunition.class);
|
||||||
NeoForge.EVENT_BUS.register(online.astradev.content.rail.RailCommands.class);
|
NeoForge.EVENT_BUS.register(RailCommands.class);
|
||||||
NeoForge.EVENT_BUS.register(online.astradev.content.train.Trains.class);
|
NeoForge.EVENT_BUS.register(Trains.class);
|
||||||
NeoForge.EVENT_BUS.register(online.astradev.content.transport.SlimeBounce.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.entity.vehicle.minecart.AbstractMinecart;
|
||||||
import net.minecraft.world.level.storage.*;
|
import net.minecraft.world.level.storage.*;
|
||||||
|
|
||||||
|
import online.astradev.content.rail.CartSpeed;
|
||||||
import online.astradev.content.rail.RailSpeed;
|
import online.astradev.content.rail.RailSpeed;
|
||||||
|
|
||||||
import org.spongepowered.asm.mixin.*;
|
import org.spongepowered.asm.mixin.*;
|
||||||
@@ -11,7 +12,7 @@ import org.spongepowered.asm.mixin.injection.*;
|
|||||||
import org.spongepowered.asm.mixin.injection.callback.*;
|
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 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)
|
||||||
|
|||||||
@@ -7,15 +7,11 @@ import net.minecraft.world.item.ItemStack;
|
|||||||
import net.minecraft.world.level.*;
|
import net.minecraft.world.level.*;
|
||||||
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.storage.loot.LootParams;
|
|
||||||
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) {
|
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)
|
if (state.is(Blocks.POWERED_RAIL) && level instanceof ServerLevel server)
|
||||||
Rails.placed(server, pos, stack);
|
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;
|
package online.astradev.content.mixin;
|
||||||
|
|
||||||
import net.minecraft.world.entity.Entity;
|
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.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;
|
||||||
@@ -12,33 +13,17 @@ import org.spongepowered.asm.mixin.injection.*;
|
|||||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||||
|
|
||||||
@Mixin(AbstractMinecart.class)
|
@Mixin(AbstractMinecart.class)
|
||||||
public abstract class TrainCartMixin implements CartFrame {
|
public abstract class TrainCartMixin {
|
||||||
@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;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Inject(method = "addAdditionalSaveData", at = @At("RETURN"))
|
@Inject(method = "addAdditionalSaveData", at = @At("RETURN"))
|
||||||
private void astra$save(ValueOutput out, CallbackInfo ci) {
|
private void astra$save(ValueOutput output, CallbackInfo ci) {
|
||||||
out.putDouble("AstraTrainFrontX", astra$front.x);
|
CouplingGeometry.save((AbstractMinecart) (Object) this, output);
|
||||||
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 input, CallbackInfo ci) {
|
||||||
double x = in.getDoubleOr("AstraTrainFrontX", 0), z = in.getDoubleOr("AstraTrainFrontZ", 0);
|
CouplingGeometry.load((AbstractMinecart) (Object) this, input);
|
||||||
astra$front =
|
|
||||||
Double.isFinite(x) && Double.isFinite(z)
|
|
||||||
? new Vec3(x, 0, z).normalize()
|
|
||||||
: Vec3.ZERO;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Inject(
|
@Inject(
|
||||||
@@ -47,19 +32,16 @@ public abstract class TrainCartMixin implements CartFrame {
|
|||||||
cancellable = true)
|
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 =
|
astra$beforePlayerPush = other instanceof Player ? self.getDeltaMovement() : null;
|
||||||
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
|
if (astra$beforePlayerPush == null) return;
|
||||||
&& self.getDeltaMovement().subtract(astra$beforePlayerPush).horizontalDistanceSqr()
|
Vec3 impulse = self.getDeltaMovement().subtract(astra$beforePlayerPush);
|
||||||
> 1e-12) Trains.playerPush(self);
|
|
||||||
astra$beforePlayerPush = null;
|
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)
|
private static int give(CommandContext<CommandSourceStack> context, RailKind kind)
|
||||||
throws CommandSyntaxException {
|
throws CommandSyntaxException {
|
||||||
var player = context.getSource().getPlayerOrException();
|
var player = context.getSource().getPlayerOrException();
|
||||||
var stack = Rails.stack(kind, 64);
|
var stack = RailItems.create(kind, 64);
|
||||||
AstraPlusApi.give(player, stack);
|
AstraPlusApi.give(player, stack);
|
||||||
return 1;
|
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;
|
package online.astradev.content.rail;
|
||||||
|
|
||||||
import net.minecraft.core.component.DataComponents;
|
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.*;
|
||||||
import net.minecraft.world.item.component.CustomData;
|
|
||||||
|
import online.astradev.plus.api.AstraPlusApi;
|
||||||
|
|
||||||
/** 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 {
|
||||||
@@ -14,6 +13,9 @@ public final class 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 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);
|
var data = stack.get(DataComponents.CUSTOM_DATA);
|
||||||
if (data == null) return null;
|
if (data == null) return null;
|
||||||
int value = data.copyTag().getIntOr(KEY, -1);
|
int value = data.copyTag().getIntOr(KEY, -1);
|
||||||
@@ -21,26 +23,6 @@ public final class RailItems {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static ItemStack create(RailKind kind, int count) {
|
public static ItemStack create(RailKind kind, int count) {
|
||||||
var stack = new ItemStack(Items.POWERED_RAIL, count);
|
return AstraPlusApi.current().orElseThrow().create(kind.id(), 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()];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,21 @@ package online.astradev.content.rail;
|
|||||||
|
|
||||||
import net.minecraft.resources.Identifier;
|
import net.minecraft.resources.Identifier;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
public record RailKind(int age, boolean waxed) {
|
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 {
|
public RailKind {
|
||||||
if (age < 0 || age > 3) throw new IllegalArgumentException("Oxidation: " + age);
|
if (age < 0 || age > 3) throw new IllegalArgumentException("Oxidation: " + age);
|
||||||
}
|
}
|
||||||
@@ -21,14 +35,23 @@ public record RailKind(int age, boolean waxed) {
|
|||||||
|
|
||||||
public Identifier id() {
|
public Identifier id() {
|
||||||
return Identifier.fromNamespaceAndPath(
|
return Identifier.fromNamespaceAndPath(
|
||||||
"astracontent",
|
"astracontent", (waxed ? "waxed_" : "") + PREFIXES.get(age) + "copper_rail");
|
||||||
(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);
|
if (!id.getNamespace().equals("astracontent")) return null;
|
||||||
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 static online.astradev.plus.api.AstraPlusApi.world;
|
||||||
|
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
|
import net.minecraft.resources.Identifier;
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.world.InteractionResult;
|
import net.minecraft.world.InteractionResult;
|
||||||
import net.minecraft.world.item.*;
|
import net.minecraft.world.item.*;
|
||||||
import net.minecraft.world.level.block.Blocks;
|
import net.minecraft.world.level.block.Blocks;
|
||||||
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.common.NeoForge;
|
|
||||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||||
import net.neoforged.neoforge.event.level.ChunkEvent;
|
import net.neoforged.neoforge.event.level.ChunkEvent;
|
||||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||||
@@ -25,111 +24,95 @@ import java.util.*;
|
|||||||
|
|
||||||
/** 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 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")
|
new ContentRegistry("astracontent")
|
||||||
.blockData("copper_rails", BlockData.integers("rails", 0, 7));
|
.blockData("copper_rails", BlockData.integers("rails", 0, 7));
|
||||||
|
|
||||||
private record Position(ServerLevel level, BlockPos pos) {}
|
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<>();
|
public Rails() {}
|
||||||
private static final Map<Position, Removed> REMOVED = new HashMap<>();
|
|
||||||
|
|
||||||
private Rails() {}
|
|
||||||
|
|
||||||
public static void register() {
|
|
||||||
NeoForge.EVENT_BUS.register(Rails.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
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) return null;
|
if (chunk == null) return null;
|
||||||
Integer code = DATA.get(world(level), position(pos)).orElse(null);
|
if (!level.getBlockState(pos).is(Blocks.POWERED_RAIL)) return null;
|
||||||
return code == null ? null : RailKind.decode(code);
|
String id = world(level).block(position(pos));
|
||||||
}
|
var kind = RailKind.fromId(Identifier.parse(id));
|
||||||
|
|
||||||
public static RailKind loot(ServerLevel level, BlockPos pos) {
|
|
||||||
var kind = find(level, pos);
|
|
||||||
if (kind != null) return kind;
|
if (kind != null) return kind;
|
||||||
var removed = REMOVED.get(new Position(level, pos));
|
Integer code = PREVIOUS_VARIANTS.get(world(level), position(pos)).orElse(null);
|
||||||
if (removed == null || removed.tick != level.getGameTime()) return null;
|
return code == null ? null : RailKind.decode(code);
|
||||||
return removed.kind;
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
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) {
|
||||||
DATA.put(world(level), position(pos), kind.code());
|
var world = world(level);
|
||||||
ACTIVE.putIfAbsent(new Position(level, pos.immutable()), null);
|
var position = position(pos);
|
||||||
}
|
if (!world.replaceBlock(position, kind.id().toString())) {
|
||||||
|
throw new IllegalStateException("Cannot place copper rail at " + pos);
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
PREVIOUS_VARIANTS.remove(world, position);
|
||||||
|
ACTIVE.add(new Position(level, pos.immutable()));
|
||||||
}
|
}
|
||||||
|
|
||||||
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) DATA.remove(world(level), position(pos));
|
if (chunk != null) PREVIOUS_VARIANTS.remove(world(level), position(pos));
|
||||||
var display = ACTIVE.remove(new Position(level, pos));
|
ACTIVE.remove(new Position(level, pos));
|
||||||
if (display != null) display.discard();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeEvent
|
@SubscribeEvent
|
||||||
public static void load(ChunkEvent.Load event) {
|
public void load(ChunkEvent.Load event) {
|
||||||
if (!(event.getLevel() instanceof ServerLevel level)
|
if (!(event.getLevel() instanceof ServerLevel level)
|
||||||
|| !(event.getChunk() instanceof LevelChunk chunk)) return;
|
|| !(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();
|
var chunkPos = chunk.getPos();
|
||||||
if (level.getChunkSource().getChunkNow(chunkPos.x(), chunkPos.z()) != chunk) return;
|
if (level.getChunkSource().getChunkNow(chunkPos.x(), chunkPos.z()) != chunk) return;
|
||||||
var origin = new BlockPosition(chunkPos.x() << 4, level.getMinY(), chunkPos.z() << 4);
|
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());
|
var pos = new BlockPos(saved.x(), saved.y(), saved.z());
|
||||||
ACTIVE.putIfAbsent(new Position(level, pos), null);
|
ACTIVE.add(new Position(level, pos));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeEvent
|
@SubscribeEvent
|
||||||
public static void unload(ChunkEvent.Unload event) {
|
public void unload(ChunkEvent.Unload event) {
|
||||||
for (var key : new ArrayList<>(ACTIVE.keySet()))
|
for (var key : new ArrayList<>(ACTIVE))
|
||||||
if (key.level == event.getLevel()
|
if (key.level == event.getLevel()
|
||||||
&& key.pos.getX() >> 4 == event.getChunk().getPos().x()
|
&& key.pos.getX() >> 4 == event.getChunk().getPos().x()
|
||||||
&& key.pos.getZ() >> 4 == event.getChunk().getPos().z()) {
|
&& key.pos.getZ() >> 4 == event.getChunk().getPos().z()) {
|
||||||
var display = ACTIVE.remove(key);
|
ACTIVE.remove(key);
|
||||||
if (display != null) display.discard();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeEvent
|
@SubscribeEvent
|
||||||
public static void stopped(ServerStoppedEvent event) {
|
public void stopped(ServerStoppedEvent event) {
|
||||||
ACTIVE.values().stream().filter(Objects::nonNull).forEach(RailDisplay::discard);
|
|
||||||
ACTIVE.clear();
|
ACTIVE.clear();
|
||||||
REMOVED.clear();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeEvent
|
@SubscribeEvent
|
||||||
public static void tick(ServerTickEvent.Post event) {
|
public void tick(ServerTickEvent.Post event) {
|
||||||
for (var key : new ArrayList<>(ACTIVE.keySet())) {
|
for (var key : new ArrayList<>(ACTIVE)) {
|
||||||
var state = key.level.getBlockState(key.pos);
|
var state = key.level.getBlockState(key.pos);
|
||||||
var kind = find(key.level, key.pos);
|
var kind = find(key.level, key.pos);
|
||||||
if (kind == null || !state.is(Blocks.POWERED_RAIL)) {
|
if (kind == null || !state.is(Blocks.POWERED_RAIL)) {
|
||||||
@@ -140,19 +123,12 @@ public final class Rails {
|
|||||||
kind = new RailKind(kind.age() + 1, false);
|
kind = new RailKind(kind.age() + 1, false);
|
||||||
put(key.level, key.pos, kind);
|
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
|
@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;
|
if (!(event.getLevel() instanceof ServerLevel level)) return;
|
||||||
var kind = find(level, event.getPos());
|
var kind = find(level, event.getPos());
|
||||||
if (kind == null) return;
|
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.entity.vehicle.minecart.AbstractMinecart;
|
||||||
import net.minecraft.world.level.block.BaseRailBlock;
|
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 net.minecraft.world.phys.Vec3;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.WeakHashMap;
|
||||||
|
|
||||||
public final class CouplingGeometry {
|
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() {}
|
private CouplingGeometry() {}
|
||||||
|
|
||||||
public static Vec3 axis(AbstractMinecart cart) {
|
public static Vec3 front(AbstractMinecart cart) {
|
||||||
var frame = (CartFrame) cart;
|
Vec3 previous = FRONTS.getOrDefault(cart, Vec3.ZERO);
|
||||||
var previous = frame.astracontent$front();
|
if (previous.lengthSqr() < 0.5) previous = facing(cart);
|
||||||
|
Vec3 direction = railDirection(cart);
|
||||||
|
if (direction == null) direction = previous;
|
||||||
|
else if (direction.dot(previous) < 0) direction = direction.scale(-1);
|
||||||
|
FRONTS.put(cart, direction);
|
||||||
|
return direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Vec3 facing(AbstractMinecart cart) {
|
||||||
double yaw = Math.toRadians(cart.getYRot());
|
double yaw = Math.toRadians(cart.getYRot());
|
||||||
if (previous.lengthSqr() < .5)
|
double x = Math.cos(yaw);
|
||||||
previous =
|
double z = Math.sin(yaw);
|
||||||
new Vec3(
|
if (AbstractMinecart.useExperimentalMovement(cart.level())) z = -z;
|
||||||
Math.cos(yaw),
|
return new Vec3(x, 0, z);
|
||||||
0,
|
}
|
||||||
Math.sin(yaw)
|
|
||||||
* (AbstractMinecart.useExperimentalMovement(cart.level())
|
public static boolean onRail(AbstractMinecart cart) {
|
||||||
? -1
|
var position = cart.getCurrentBlockPosOrRailBelow();
|
||||||
: 1));
|
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 pos = cart.getCurrentBlockPosOrRailBelow();
|
||||||
var state = cart.level().getBlockState(pos);
|
var state = cart.level().getBlockState(pos);
|
||||||
Vec3 axis = previous;
|
if (!(state.getBlock() instanceof BaseRailBlock rail)) return null;
|
||||||
if (state.getBlock() instanceof BaseRailBlock rail) {
|
var shape = rail.getRailDirection(state, cart.level(), pos, cart);
|
||||||
var exits =
|
var exits = AbstractMinecart.exits(shape);
|
||||||
AbstractMinecart.exits(rail.getRailDirection(state, cart.level(), pos, cart));
|
Vec3 start = new Vec3(exits.getFirst());
|
||||||
axis =
|
Vec3 end = new Vec3(exits.getSecond());
|
||||||
new Vec3(
|
return end.subtract(start).horizontal().normalize();
|
||||||
exits.getSecond().getX() - exits.getFirst().getX(),
|
|
||||||
0,
|
|
||||||
exits.getSecond().getZ() - exits.getFirst().getZ())
|
|
||||||
.normalize();
|
|
||||||
if (axis.dot(previous) < 0) axis = axis.scale(-1);
|
|
||||||
}
|
}
|
||||||
frame.astracontent$front(axis);
|
|
||||||
return axis;
|
public static void restoreFront(AbstractMinecart cart, Vec3 direction) {
|
||||||
|
if (!Double.isFinite(direction.x) || !Double.isFinite(direction.z)) {
|
||||||
|
FRONTS.remove(cart);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
FRONTS.put(cart, direction.horizontal().normalize());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void save(AbstractMinecart cart, ValueOutput output) {
|
||||||
|
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) {
|
public static int hitEnd(Vec3 axis, Vec3 localHit) {
|
||||||
@@ -46,10 +82,13 @@ public final class CouplingGeometry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static Vec3 outward(AbstractMinecart cart, int end) {
|
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) {
|
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,
|
TrainData::new,
|
||||||
CODEC);
|
CODEC);
|
||||||
private final List<Link> links = new ArrayList<>();
|
private final List<Link> links = new ArrayList<>();
|
||||||
|
private final Map<UUID, Set<UUID>> components = new HashMap<>();
|
||||||
|
|
||||||
public TrainData() {}
|
public TrainData() {}
|
||||||
|
|
||||||
@@ -73,24 +74,30 @@ public final class TrainData extends SavedData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Link at(UUID cart, int end) {
|
public Link at(UUID cart, int end) {
|
||||||
return links.stream()
|
for (Link link : links) {
|
||||||
.filter(l -> l.touches(cart) && l.end(cart) == end)
|
if (link.touches(cart) && link.end(cart) == end) return link;
|
||||||
.findFirst()
|
}
|
||||||
.orElse(null);
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void add(Link link) {
|
public void add(Link link) {
|
||||||
links.add(link);
|
links.add(link);
|
||||||
|
components.clear();
|
||||||
setDirty();
|
setDirty();
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean remove(Link link) {
|
public boolean remove(Link link) {
|
||||||
boolean removed = links.remove(link);
|
boolean removed = links.remove(link);
|
||||||
if (removed) setDirty();
|
if (removed) {
|
||||||
|
components.clear();
|
||||||
|
setDirty();
|
||||||
|
}
|
||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Set<UUID> component(UUID root) {
|
public Set<UUID> component(UUID root) {
|
||||||
|
var cached = components.get(root);
|
||||||
|
if (cached != null) return cached;
|
||||||
var seen = new HashSet<UUID>();
|
var seen = new HashSet<UUID>();
|
||||||
var pending = new ArrayDeque<UUID>();
|
var pending = new ArrayDeque<UUID>();
|
||||||
pending.add(root);
|
pending.add(root);
|
||||||
@@ -99,6 +106,11 @@ public final class TrainData extends SavedData {
|
|||||||
if (!seen.add(id)) continue;
|
if (!seen.add(id)) continue;
|
||||||
for (var link : links) if (link.touches(id)) pending.add(link.other(id));
|
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.network.chat.Component;
|
||||||
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.server.level.ServerPlayer;
|
||||||
import net.minecraft.tags.ItemTags;
|
import net.minecraft.tags.ItemTags;
|
||||||
import net.minecraft.world.InteractionResult;
|
import net.minecraft.world.InteractionResult;
|
||||||
import net.minecraft.world.entity.Entity;
|
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.server.ServerStoppedEvent;
|
||||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||||
|
|
||||||
|
import online.astradev.plus.api.BlockLine;
|
||||||
|
|
||||||
import java.util.*;
|
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, BlockLine> 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<>();
|
||||||
|
|
||||||
@@ -50,26 +53,27 @@ public final class Trains {
|
|||||||
|
|
||||||
@SubscribeEvent
|
@SubscribeEvent
|
||||||
public static void interact(PlayerInteractEvent.EntityInteract event) {
|
public static void interact(PlayerInteractEvent.EntityInteract event) {
|
||||||
if (!(event.getTarget() instanceof AbstractMinecart cart)
|
if (!(event.getTarget() instanceof AbstractMinecart cart)) return;
|
||||||
|| !(cart.level() instanceof ServerLevel level)
|
if (!(event.getEntity() instanceof ServerPlayer player)) return;
|
||||||
|| !event.getEntity().isShiftKeyDown()) return;
|
if (!player.isShiftKeyDown()) return;
|
||||||
var player = event.getEntity();
|
var level = player.level();
|
||||||
var item = event.getItemStack();
|
var item = event.getItemStack();
|
||||||
boolean chain = isChain(item);
|
boolean chain = isChain(item);
|
||||||
if (!chain && !item.is(ItemTags.PICKAXES)) return;
|
if (!chain && !item.is(ItemTags.PICKAXES)) return;
|
||||||
event.setCanceled(true);
|
event.setCanceled(true);
|
||||||
event.setCancellationResult(InteractionResult.SUCCESS);
|
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.front(cart), event.getLocation());
|
||||||
if (end < 0) {
|
if (end < 0) {
|
||||||
message(player, "Цепь крепится только к переднему или заднему торцу.");
|
player.sendSystemMessage(
|
||||||
|
Component.literal("Цепь крепится только к переднему или заднему торцу."), true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var data = TrainData.get(level);
|
var data = TrainData.get(level);
|
||||||
var existing = data.at(cart.getUUID(), end);
|
var existing = data.at(cart.getUUID(), end);
|
||||||
if (!chain) {
|
if (!chain) {
|
||||||
if (existing == null) {
|
if (existing == null) {
|
||||||
message(player, "На этом торце нет цепи.");
|
player.sendSystemMessage(Component.literal("На этом торце нет цепи."), true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
unlink(level, existing, cart, true);
|
unlink(level, existing, cart, true);
|
||||||
@@ -77,7 +81,7 @@ public final class Trains {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (existing != null) {
|
if (existing != null) {
|
||||||
message(player, "Этот торец уже сцеплен.");
|
player.sendSystemMessage(Component.literal("Этот торец уже сцеплен."), true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Vec3 outward = CouplingGeometry.outward(cart, end);
|
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;
|
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.front(other).dot(direction) > 0 ? 1 : 0;
|
||||||
if (CouplingGeometry.outward(other, otherEnd).dot(direction) > -.90
|
if (CouplingGeometry.outward(other, otherEnd).dot(direction) > -.90
|
||||||
|| data.at(other.getUUID(), otherEnd) != null) continue;
|
|| data.at(other.getUUID(), otherEnd) != null) continue;
|
||||||
if (!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock()
|
if (!CouplingGeometry.onRail(cart) || !CouplingGeometry.onRail(other)) continue;
|
||||||
instanceof BaseRailBlock)
|
|
||||||
|| !(level.getBlockState(other.getCurrentBlockPosOrRailBelow()).getBlock()
|
|
||||||
instanceof BaseRailBlock)) continue;
|
|
||||||
var hit =
|
var hit =
|
||||||
level.clip(
|
level.clip(
|
||||||
new ClipContext(
|
new ClipContext(
|
||||||
@@ -119,15 +120,13 @@ public final class Trains {
|
|||||||
!player.hasInfiniteMaterials(),
|
!player.hasInfiniteMaterials(),
|
||||||
distance));
|
distance));
|
||||||
item.consume(1, player);
|
item.consume(1, player);
|
||||||
message(player, "Вагонетки сцеплены.");
|
player.sendSystemMessage(Component.literal("Вагонетки сцеплены."), true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
message(player, "У этого торца нет подходящей свободной вагонетки в пределах 3,5 блока.");
|
player.sendSystemMessage(
|
||||||
}
|
Component.literal(
|
||||||
|
"У этого торца нет подходящей свободной вагонетки в пределах 3,5 блока."),
|
||||||
private static void message(net.minecraft.world.entity.player.Player player, String text) {
|
true);
|
||||||
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) {
|
||||||
@@ -196,7 +195,8 @@ public final class Trains {
|
|||||||
var carts = new LinkedHashMap<UUID, AbstractMinecart>();
|
var carts = new LinkedHashMap<UUID, AbstractMinecart>();
|
||||||
var axes = new HashMap<UUID, Vec3>();
|
var axes = new HashMap<UUID, Vec3>();
|
||||||
boolean paused = false;
|
boolean paused = false;
|
||||||
double momentum = 0, limit = Double.MAX_VALUE;
|
double momentum = 0;
|
||||||
|
double limit = Double.MAX_VALUE;
|
||||||
double controlledMomentum = 0;
|
double controlledMomentum = 0;
|
||||||
var controls = new HashSet<UUID>();
|
var controls = new HashSet<UUID>();
|
||||||
for (var pair : signs.entrySet()) {
|
for (var pair : signs.entrySet()) {
|
||||||
@@ -206,10 +206,9 @@ public final class Trains {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
carts.put(pair.getKey(), cart);
|
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);
|
axes.put(pair.getKey(), tangent);
|
||||||
if (!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock()
|
if (!CouplingGeometry.onRail(cart)) paused = true;
|
||||||
instanceof BaseRailBlock)) paused = true;
|
|
||||||
double scale = travelScale(cart);
|
double scale = travelScale(cart);
|
||||||
momentum += cart.getDeltaMovement().dot(tangent) * scale;
|
momentum += cart.getDeltaMovement().dot(tangent) * scale;
|
||||||
if (playerControls(cart, playerPushes)) {
|
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
|
// 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 =
|
double speed = momentum / carts.size();
|
||||||
Math.clamp(
|
if (!controls.isEmpty()) speed = controlledMomentum / controls.size();
|
||||||
!controls.isEmpty()
|
speed = Math.clamp(speed, -limit, limit);
|
||||||
? controlledMomentum / controls.size()
|
|
||||||
: momentum / carts.size(),
|
|
||||||
-limit,
|
|
||||||
limit);
|
|
||||||
var corrections = new HashMap<UUID, Double>();
|
var corrections = new HashMap<UUID, Double>();
|
||||||
for (var link : links)
|
for (var link : links)
|
||||||
if (carts.containsKey(link.a()) && carts.containsKey(link.b())) {
|
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
|
// Followers take up slack; pulling back the driven cart would cancel its 0.001
|
||||||
// rider impulse.
|
// rider impulse.
|
||||||
var cart = pair.getValue();
|
var cart = pair.getValue();
|
||||||
double value =
|
double cartSpeed = speed;
|
||||||
Math.clamp(
|
if (!controls.contains(pair.getKey())) {
|
||||||
speed
|
cartSpeed += corrections.getOrDefault(pair.getKey(), 0.0);
|
||||||
+ (controls.contains(pair.getKey())
|
}
|
||||||
? 0
|
cartSpeed = Math.clamp(cartSpeed, -limit, limit);
|
||||||
: corrections.getOrDefault(pair.getKey(), 0.0)),
|
Vec3 direction = axes.get(pair.getKey());
|
||||||
-limit,
|
Vec3 velocity = direction.scale(cartSpeed / travelScale(cart));
|
||||||
limit);
|
|
||||||
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -287,8 +280,7 @@ public final class Trains {
|
|||||||
|
|
||||||
private static boolean playerControls(AbstractMinecart cart, Set<UUID> pushes) {
|
private static boolean playerControls(AbstractMinecart cart, Set<UUID> pushes) {
|
||||||
if (pushes.contains(cart.getUUID())) return true;
|
if (pushes.contains(cart.getUUID())) return true;
|
||||||
if (!(cart.getFirstPassenger() instanceof net.minecraft.server.level.ServerPlayer player))
|
if (!(cart.getFirstPassenger() instanceof ServerPlayer player)) return false;
|
||||||
return false;
|
|
||||||
return player.getLastClientMoveIntent().horizontalDistanceSqr() > 0;
|
return player.getLastClientMoveIntent().horizontalDistanceSqr() > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,21 +294,11 @@ public final class Trains {
|
|||||||
var movement = cart.getDeltaMovement();
|
var movement = cart.getDeltaMovement();
|
||||||
double along = movement.dot(tangent);
|
double along = movement.dot(tangent);
|
||||||
if (Math.abs(along) < 1e-9) {
|
if (Math.abs(along) < 1e-9) {
|
||||||
var pos = cart.getCurrentBlockPosOrRailBelow();
|
Vec3 railDirection = CouplingGeometry.railDirection(cart);
|
||||||
var state = cart.level().getBlockState(pos);
|
if (railDirection != null) {
|
||||||
if (state.getBlock() instanceof BaseRailBlock rail) {
|
along = railDirection.dot(tangent);
|
||||||
var exits =
|
// Vanilla reverses the default exit for perpendicular input in the new engine.
|
||||||
AbstractMinecart.exits(
|
if (AbstractMinecart.useExperimentalMovement(cart.level())) along = -along;
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Math.copySign(movement.horizontalDistance(), along);
|
return Math.copySign(movement.horizontalDistance(), along);
|
||||||
@@ -336,19 +318,15 @@ public final class Trains {
|
|||||||
var key = new DisplayKey(level, link);
|
var key = new DisplayKey(level, link);
|
||||||
keys.add(key);
|
keys.add(key);
|
||||||
var display = DISPLAYS.get(key);
|
var display = DISPLAYS.get(key);
|
||||||
if (display == null || display.isRemoved()) {
|
boolean create = display == null || display.isRemoved();
|
||||||
display =
|
if (create) {
|
||||||
new ChainDisplay(
|
var chain = (BlockItem) chainItem(link);
|
||||||
level,
|
display = new BlockLine(level, chain.getBlock().defaultBlockState());
|
||||||
((BlockItem) chainItem(link)).getBlock().defaultBlockState());
|
}
|
||||||
display.update(
|
Vec3 start = CouplingGeometry.anchor(a, link.endA());
|
||||||
CouplingGeometry.anchor(a, link.endA()),
|
Vec3 end = CouplingGeometry.anchor(b, link.endB());
|
||||||
CouplingGeometry.anchor(b, link.endB()));
|
display.connect(start, end);
|
||||||
if (level.addFreshEntity(display)) DISPLAYS.put(key, display);
|
if (create && level.addFreshEntity(display)) DISPLAYS.put(key, display);
|
||||||
} else
|
|
||||||
display.update(
|
|
||||||
CouplingGeometry.anchor(a, link.endA()),
|
|
||||||
CouplingGeometry.anchor(b, link.endB()));
|
|
||||||
}
|
}
|
||||||
for (var key : new ArrayList<>(DISPLAYS.keySet()))
|
for (var key : new ArrayList<>(DISPLAYS.keySet()))
|
||||||
if (key.level == level && !keys.contains(key)) discard(key);
|
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
|
// Propagate reversal through the closed or open graph, preserving each cart's local travel
|
||||||
// direction.
|
// direction.
|
||||||
var signs = directions(hit.getUUID(), data.links());
|
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) {
|
for (var id : ids) {
|
||||||
var cart = cart(level, id);
|
var cart = cart(level, id);
|
||||||
if (cart != null) {
|
if (cart != null) {
|
||||||
var v =
|
var v =
|
||||||
CouplingGeometry.axis(cart)
|
CouplingGeometry.front(cart)
|
||||||
.scale(speed * signs.getOrDefault(id, 1) / travelScale(cart));
|
.scale(speed * signs.getOrDefault(id, 1) / travelScale(cart));
|
||||||
cart.setDeltaMovement(v.x, cart.getDeltaMovement().y, v.z);
|
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);
|
for (var key : new ArrayList<>(DISPLAYS.keySet())) discard(key);
|
||||||
PAUSED.clear();
|
PAUSED.clear();
|
||||||
PLAYER_PUSHES.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 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$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 setPosRotInterpolationDuration(I)V
|
||||||
public net.minecraft.world.entity.Display setTransformationInterpolationDuration(I)V
|
public net.minecraft.world.entity.Display setTransformationInterpolationDuration(I)V
|
||||||
public net.minecraft.world.entity.Display setTransformationInterpolationDelay(I)V
|
public net.minecraft.world.entity.Display setTransformationInterpolationDelay(I)V
|
||||||
|
|||||||
@@ -21,6 +21,6 @@ side="SERVER"
|
|||||||
[[dependencies.astracontent]]
|
[[dependencies.astracontent]]
|
||||||
modId="astraplus"
|
modId="astraplus"
|
||||||
type="required"
|
type="required"
|
||||||
versionRange="[0.9.2,0.10)"
|
versionRange="[0.9.3,0.10)"
|
||||||
ordering="AFTER"
|
ordering="AFTER"
|
||||||
side="SERVER"
|
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