Simplify train and rail logic and consolidate integration tests
This commit is contained in:
@@ -5,6 +5,7 @@ import net.neoforged.bus.api.IEventBus;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.fml.loading.FMLPaths;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
|
||||
import online.astradev.content.rail.Rails;
|
||||
import online.astradev.content.weapon.Ammunition;
|
||||
|
||||
|
||||
@@ -1,20 +1,31 @@
|
||||
package online.astradev.content;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
|
||||
/** Install absent defaults before AstraPlus loads its catalog. Never overwrite administrator edits. */
|
||||
/**
|
||||
* Install absent defaults before AstraPlus loads its catalog. Never overwrite administrator edits.
|
||||
*/
|
||||
public final class Defaults {
|
||||
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()) {
|
||||
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);
|
||||
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.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)) {
|
||||
@@ -22,6 +33,8 @@ public final class Defaults {
|
||||
Files.copy(stream, target);
|
||||
}
|
||||
}
|
||||
} catch (java.io.IOException e) { throw new IllegalStateException("Cannot install AstraContent defaults", e); }
|
||||
} catch (java.io.IOException e) {
|
||||
throw new IllegalStateException("Cannot install AstraContent defaults", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,43 @@
|
||||
package online.astradev.content.mixin;
|
||||
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
|
||||
import net.minecraft.network.protocol.game.ServerboundMoveVehiclePacket;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
import online.astradev.content.transport.SlimeBounce;
|
||||
|
||||
import org.spongepowered.asm.mixin.*;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ServerGamePacketListenerImpl.class)
|
||||
public abstract class BoatPacketMixin {
|
||||
@Shadow public ServerPlayer player;
|
||||
@Unique private Entity astra$boat;
|
||||
@Unique private Vec3 astra$boatBefore;
|
||||
|
||||
// Run after vanilla's thread check, so packet-thread rescheduling never mutates state.
|
||||
@Inject(method="handleMoveVehicle",at=@At(value="INVOKE",target="Lnet/minecraft/server/level/ServerPlayer;getRootVehicle()Lnet/minecraft/world/entity/Entity;",shift=At.Shift.BEFORE))
|
||||
private void astra$before(ServerboundMoveVehiclePacket packet,CallbackInfo ci){astra$boat=player.getRootVehicle();astra$boatBefore=astra$boat.position();}
|
||||
@Inject(method="handleMoveVehicle",at=@At("RETURN"))
|
||||
private void astra$after(ServerboundMoveVehiclePacket packet,CallbackInfo ci){
|
||||
if(astra$boat!=null&&astra$boatBefore!=null){SlimeBounce.boatPacket(astra$boat,astra$boatBefore);astra$boat=null;astra$boatBefore=null;}
|
||||
@Inject(
|
||||
method = "handleMoveVehicle",
|
||||
at =
|
||||
@At(
|
||||
value = "INVOKE",
|
||||
target =
|
||||
"Lnet/minecraft/server/level/ServerPlayer;getRootVehicle()Lnet/minecraft/world/entity/Entity;",
|
||||
shift = At.Shift.BEFORE))
|
||||
private void astra$before(ServerboundMoveVehiclePacket packet, CallbackInfo ci) {
|
||||
astra$boat = player.getRootVehicle();
|
||||
astra$boatBefore = astra$boat.position();
|
||||
}
|
||||
|
||||
@Inject(method = "handleMoveVehicle", at = @At("RETURN"))
|
||||
private void astra$after(ServerboundMoveVehiclePacket packet, CallbackInfo ci) {
|
||||
if (astra$boat != null && astra$boatBefore != null) {
|
||||
SlimeBounce.boatPacket(astra$boat, astra$boatBefore);
|
||||
astra$boat = null;
|
||||
astra$boatBefore = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.projectile.Projectile;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.Level;
|
||||
|
||||
import online.astradev.content.weapon.Ammunition;
|
||||
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
@Mixin(CrossbowItem.class)
|
||||
public abstract class CrossbowMixin {
|
||||
@Inject(method = {"getSupportedHeldProjectiles()Ljava/util/function/Predicate;", "getAllSupportedProjectiles()Ljava/util/function/Predicate;"}, at = @At("RETURN"), cancellable = true)
|
||||
private void astra$ammo(CallbackInfoReturnable<Predicate<ItemStack>> cir) { cir.setReturnValue(cir.getReturnValue().or(Ammunition::accepts)); }
|
||||
@Inject(
|
||||
method = {
|
||||
"getSupportedHeldProjectiles()Ljava/util/function/Predicate;",
|
||||
"getAllSupportedProjectiles()Ljava/util/function/Predicate;"
|
||||
},
|
||||
at = @At("RETURN"),
|
||||
cancellable = true)
|
||||
private void astra$ammo(CallbackInfoReturnable<Predicate<ItemStack>> cir) {
|
||||
cir.setReturnValue(cir.getReturnValue().or(Ammunition::accepts));
|
||||
}
|
||||
|
||||
@Inject(method = "createProjectile", at = @At("HEAD"), cancellable = true)
|
||||
private void astra$create(Level level, LivingEntity owner, ItemStack weapon, ItemStack ammo, boolean critical, CallbackInfoReturnable<Projectile> cir) {
|
||||
private void astra$create(
|
||||
Level level,
|
||||
LivingEntity owner,
|
||||
ItemStack weapon,
|
||||
ItemStack ammo,
|
||||
boolean critical,
|
||||
CallbackInfoReturnable<Projectile> cir) {
|
||||
if (Ammunition.accepts(ammo)) cir.setReturnValue(Ammunition.create(level, owner, ammo));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,19 +3,25 @@ package online.astradev.content.mixin;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.vehicle.minecart.*;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
import online.astradev.content.rail.CartSpeed;
|
||||
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
@Mixin(NewMinecartBehavior.class)
|
||||
public abstract class ExperimentalCartMixin extends MinecartBehavior {
|
||||
protected ExperimentalCartMixin(AbstractMinecart cart){super(cart);}
|
||||
@Inject(method="calculateTrackSpeed",at=@At("RETURN"),cancellable=true)
|
||||
protected ExperimentalCartMixin(AbstractMinecart cart) {
|
||||
super(cart);
|
||||
}
|
||||
|
||||
@Inject(method = "calculateTrackSpeed", at = @At("RETURN"), cancellable = true)
|
||||
private void astra$exactSpeed(CallbackInfoReturnable<Vec3> cir) {
|
||||
if(!(level() instanceof ServerLevel level))return;
|
||||
double limit=((CartSpeed)minecart).astracontent$limit(level);
|
||||
var movement=cir.getReturnValue();
|
||||
if(limit>0 && movement.horizontalDistance()>limit)cir.setReturnValue(movement.scale(limit/movement.horizontalDistance()));
|
||||
if (!(level() instanceof ServerLevel level)) return;
|
||||
double limit = ((CartSpeed) minecart).astracontent$limit(level);
|
||||
var movement = cir.getReturnValue();
|
||||
if (limit > 0 && movement.horizontalDistance() > limit)
|
||||
cir.setReturnValue(movement.scale(limit / movement.horizontalDistance()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.vehicle.minecart.MinecartFurnace;
|
||||
|
||||
import online.astradev.content.rail.CartSpeed;
|
||||
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
@Mixin(MinecartFurnace.class)
|
||||
public abstract class FurnaceCartMixin {
|
||||
@Inject(method="getMaxSpeed",at=@At("RETURN"),cancellable=true)
|
||||
private void astra$furnace(ServerLevel level,CallbackInfoReturnable<Double> cir) {
|
||||
double limit=((CartSpeed)this).astracontent$limit(level);if(limit>0)cir.setReturnValue(limit);
|
||||
@Inject(method = "getMaxSpeed", at = @At("RETURN"), cancellable = true)
|
||||
private void astra$furnace(ServerLevel level, CallbackInfoReturnable<Double> cir) {
|
||||
double limit = ((CartSpeed) this).astracontent$limit(level);
|
||||
if (limit > 0) cir.setReturnValue(limit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,9 @@ package online.astradev.content.mixin;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||
import net.minecraft.world.level.storage.*;
|
||||
|
||||
import online.astradev.content.rail.RailSpeed;
|
||||
|
||||
import org.spongepowered.asm.mixin.*;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.*;
|
||||
@@ -11,23 +13,31 @@ import org.spongepowered.asm.mixin.injection.callback.*;
|
||||
@Mixin(AbstractMinecart.class)
|
||||
public abstract class MinecartMixin implements online.astradev.content.rail.CartSpeed {
|
||||
@Unique private double astra$speed;
|
||||
@Inject(method="getMaxSpeed",at=@At("RETURN"),cancellable=true)
|
||||
private void astra$limit(ServerLevel level,CallbackInfoReturnable<Double> cir) {
|
||||
double limit=astracontent$limit(level);
|
||||
if(limit>0)cir.setReturnValue(limit);
|
||||
|
||||
@Inject(method = "getMaxSpeed", at = @At("RETURN"), cancellable = true)
|
||||
private void astra$limit(ServerLevel level, CallbackInfoReturnable<Double> cir) {
|
||||
double limit = astracontent$limit(level);
|
||||
if (limit > 0) cir.setReturnValue(limit);
|
||||
}
|
||||
@Override public double astracontent$limit(ServerLevel level) {
|
||||
var cart=(AbstractMinecart)(Object)this;
|
||||
astra$speed=RailSpeed.target(level,cart.getCurrentBlockPosOrRailBelow(),astra$speed);
|
||||
|
||||
@Override
|
||||
public double astracontent$limit(ServerLevel level) {
|
||||
var cart = (AbstractMinecart) (Object) this;
|
||||
astra$speed = RailSpeed.target(level, cart.getCurrentBlockPosOrRailBelow(), astra$speed);
|
||||
// Preserve existing experimental gamerules until this cart reaches a regulator.
|
||||
if(astra$speed==0) return 0;
|
||||
double limit=RailSpeed.safeLimit(cart,level,astra$speed/20);
|
||||
return limit*(cart.isInWater()?.5:1);
|
||||
if (astra$speed == 0) return 0;
|
||||
double limit = RailSpeed.safeLimit(cart, level, astra$speed / 20);
|
||||
return limit * (cart.isInWater() ? .5 : 1);
|
||||
}
|
||||
@Inject(method="addAdditionalSaveData",at=@At("RETURN"))
|
||||
private void astra$save(ValueOutput out,CallbackInfo ci) { if(astra$speed>0)out.putDouble("AstraContentSpeed",astra$speed); }
|
||||
@Inject(method="readAdditionalSaveData",at=@At("RETURN"))
|
||||
private void astra$read(ValueInput in,CallbackInfo ci) {
|
||||
double value=in.getDoubleOr("AstraContentSpeed",0); astra$speed=Double.isFinite(value) && value>0?Math.clamp(value,2,30):0;
|
||||
|
||||
@Inject(method = "addAdditionalSaveData", at = @At("RETURN"))
|
||||
private void astra$save(ValueOutput out, CallbackInfo ci) {
|
||||
if (astra$speed > 0) out.putDouble("AstraContentSpeed", astra$speed);
|
||||
}
|
||||
|
||||
@Inject(method = "readAdditionalSaveData", at = @At("RETURN"))
|
||||
private void astra$read(ValueInput in, CallbackInfo ci) {
|
||||
double value = in.getDoubleOr("AstraContentSpeed", 0);
|
||||
astra$speed = Double.isFinite(value) && value > 0 ? Math.clamp(value, 2, 30) : 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@ package online.astradev.content.mixin;
|
||||
|
||||
import net.minecraft.world.entity.projectile.EyeOfEnder;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
import online.astradev.content.weapon.PayloadProjectile;
|
||||
|
||||
import org.spongepowered.asm.mixin.*;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
@@ -10,8 +12,10 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
@Mixin(EyeOfEnder.class)
|
||||
public abstract class PayloadMixin {
|
||||
@Shadow private boolean surviveAfterDeath;
|
||||
|
||||
@Inject(method = "signalTo", at = @At("RETURN"))
|
||||
private void astra$noDuplicate(Vec3 target, CallbackInfo ci) {
|
||||
if (((EyeOfEnder)(Object)this).entityTags().contains(PayloadProjectile.NO_EYE_DROP)) surviveAfterDeath = false;
|
||||
if (((EyeOfEnder) (Object) this).entityTags().contains(PayloadProjectile.NO_EYE_DROP))
|
||||
surviveAfterDeath = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
@@ -10,26 +9,51 @@ import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.storage.loot.LootParams;
|
||||
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
|
||||
|
||||
import online.astradev.content.rail.Rails;
|
||||
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mixin(PoweredRailBlock.class)
|
||||
public abstract class RailBlockMixin extends BaseRailBlock {
|
||||
protected RailBlockMixin(boolean straight, Properties properties) { super(straight,properties); }
|
||||
@Override public void setPlacedBy(Level level, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
|
||||
super.setPlacedBy(level,pos,state,placer,stack);
|
||||
if (state.is(Blocks.POWERED_RAIL) && level instanceof ServerLevel server) Rails.placed(server,pos,stack);
|
||||
protected RailBlockMixin(boolean straight, Properties properties) {
|
||||
super(straight, properties);
|
||||
}
|
||||
@Override protected List<ItemStack> getDrops(BlockState state, LootParams.Builder params) {
|
||||
var drops = super.getDrops(state,params); var origin = params.getOptionalParameter(LootContextParams.ORIGIN);
|
||||
|
||||
@Override
|
||||
public void setPlacedBy(
|
||||
Level level, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
|
||||
super.setPlacedBy(level, pos, state, placer, stack);
|
||||
if (state.is(Blocks.POWERED_RAIL) && level instanceof ServerLevel server)
|
||||
Rails.placed(server, pos, stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<ItemStack> getDrops(BlockState state, LootParams.Builder params) {
|
||||
var drops = super.getDrops(state, params);
|
||||
var origin = params.getOptionalParameter(LootContextParams.ORIGIN);
|
||||
if (!state.is(Blocks.POWERED_RAIL) || origin == null) return drops;
|
||||
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();
|
||||
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) {
|
||||
|
||||
@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);
|
||||
var kind = Rails.find(server, pos);
|
||||
if (kind != null) return Rails.stack(kind, 1);
|
||||
}
|
||||
return super.getCloneItemStack(level,pos,state,includeData);
|
||||
return super.getCloneItemStack(level, pos, state, includeData);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
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);
|
||||
@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,29 +1,43 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import online.astradev.content.transport.SlimeBounce;
|
||||
import online.astradev.content.train.Trains;
|
||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||
import net.minecraft.world.level.block.BaseRailBlock;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
import online.astradev.content.train.Trains;
|
||||
import online.astradev.content.transport.SlimeBounce;
|
||||
|
||||
import org.spongepowered.asm.mixin.*;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(Entity.class)
|
||||
public abstract class SlimeCollisionMixin {
|
||||
@Unique private Vec3 astra$beforeMove;
|
||||
@Unique private Vec3 astra$incoming;
|
||||
@Inject(method="move",at=@At("HEAD"),cancellable=true)
|
||||
private void astra$before(MoverType type,Vec3 delta,CallbackInfo ci){
|
||||
var entity=(Entity)(Object)this;astra$beforeMove=type==MoverType.SELF&&SlimeBounce.supports(entity)?entity.position():null;
|
||||
astra$incoming=entity.getDeltaMovement();
|
||||
|
||||
@Inject(method = "move", at = @At("HEAD"), cancellable = true)
|
||||
private void astra$before(MoverType type, Vec3 delta, CallbackInfo ci) {
|
||||
var entity = (Entity) (Object) this;
|
||||
astra$beforeMove =
|
||||
type == MoverType.SELF && SlimeBounce.supports(entity) ? entity.position() : null;
|
||||
astra$incoming = entity.getDeltaMovement();
|
||||
// Native powered rails can accelerate from zero within this same tick.
|
||||
if(type==MoverType.SELF && entity instanceof AbstractMinecart cart && Trains.paused(cart)
|
||||
&& cart.level().getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock){
|
||||
astra$beforeMove=null;cart.setDeltaMovement(Vec3.ZERO);ci.cancel();
|
||||
if (type == MoverType.SELF
|
||||
&& entity instanceof AbstractMinecart cart
|
||||
&& Trains.paused(cart)
|
||||
&& cart.level().getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock()
|
||||
instanceof BaseRailBlock) {
|
||||
astra$beforeMove = null;
|
||||
cart.setDeltaMovement(Vec3.ZERO);
|
||||
ci.cancel();
|
||||
}
|
||||
}
|
||||
@Inject(method="move",at=@At("RETURN"))
|
||||
private void astra$after(MoverType type,Vec3 delta,CallbackInfo ci){
|
||||
if(astra$beforeMove!=null)SlimeBounce.afterMove((Entity)(Object)this,astra$beforeMove,delta,astra$incoming);
|
||||
|
||||
@Inject(method = "move", at = @At("RETURN"))
|
||||
private void astra$after(MoverType type, Vec3 delta, CallbackInfo ci) {
|
||||
if (astra$beforeMove != null)
|
||||
SlimeBounce.afterMove((Entity) (Object) this, astra$beforeMove, delta, astra$incoming);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,35 +4,62 @@ import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||
import net.minecraft.world.level.storage.*;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
import online.astradev.content.train.*;
|
||||
|
||||
import org.spongepowered.asm.mixin.*;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(AbstractMinecart.class)
|
||||
public abstract class TrainCartMixin implements CartFrame {
|
||||
@Unique private Vec3 astra$front=Vec3.ZERO;
|
||||
@Unique private Vec3 astra$front = Vec3.ZERO;
|
||||
@Unique private Vec3 astra$beforePlayerPush;
|
||||
@Override public Vec3 astracontent$front(){return astra$front;}
|
||||
@Override public void astracontent$front(Vec3 axis){astra$front=axis;}
|
||||
@Inject(method="addAdditionalSaveData",at=@At("RETURN"))
|
||||
private void astra$save(ValueOutput out,CallbackInfo ci){out.putDouble("AstraTrainFrontX",astra$front.x);out.putDouble("AstraTrainFrontZ",astra$front.z);}
|
||||
@Inject(method="readAdditionalSaveData",at=@At("RETURN"))
|
||||
private void astra$read(ValueInput in,CallbackInfo ci){
|
||||
double x=in.getDoubleOr("AstraTrainFrontX",0),z=in.getDoubleOr("AstraTrainFrontZ",0);
|
||||
astra$front=Double.isFinite(x)&&Double.isFinite(z)?new Vec3(x,0,z).normalize():Vec3.ZERO;
|
||||
|
||||
@Override
|
||||
public Vec3 astracontent$front() {
|
||||
return astra$front;
|
||||
}
|
||||
@Inject(method="push(Lnet/minecraft/world/entity/Entity;)V",at=@At("HEAD"),cancellable=true)
|
||||
private void astra$noInternalCollision(Entity other,CallbackInfo ci){
|
||||
var self=(AbstractMinecart)(Object)this;
|
||||
astra$beforePlayerPush=other instanceof net.minecraft.world.entity.player.Player?self.getDeltaMovement():null;
|
||||
if(other instanceof AbstractMinecart cart && Trains.connected(self,cart))ci.cancel();
|
||||
|
||||
@Override
|
||||
public void astracontent$front(Vec3 axis) {
|
||||
astra$front = axis;
|
||||
}
|
||||
@Inject(method="push(Lnet/minecraft/world/entity/Entity;)V",at=@At("RETURN"))
|
||||
private void astra$playerPush(Entity other,CallbackInfo ci){
|
||||
var self=(AbstractMinecart)(Object)this;
|
||||
if(astra$beforePlayerPush!=null && self.getDeltaMovement().subtract(astra$beforePlayerPush).horizontalDistanceSqr()>1e-12)
|
||||
Trains.playerPush(self);
|
||||
astra$beforePlayerPush=null;
|
||||
|
||||
@Inject(method = "addAdditionalSaveData", at = @At("RETURN"))
|
||||
private void astra$save(ValueOutput out, CallbackInfo ci) {
|
||||
out.putDouble("AstraTrainFrontX", astra$front.x);
|
||||
out.putDouble("AstraTrainFrontZ", astra$front.z);
|
||||
}
|
||||
|
||||
@Inject(method = "readAdditionalSaveData", at = @At("RETURN"))
|
||||
private void astra$read(ValueInput in, CallbackInfo ci) {
|
||||
double x = in.getDoubleOr("AstraTrainFrontX", 0), z = in.getDoubleOr("AstraTrainFrontZ", 0);
|
||||
astra$front =
|
||||
Double.isFinite(x) && Double.isFinite(z)
|
||||
? new Vec3(x, 0, z).normalize()
|
||||
: Vec3.ZERO;
|
||||
}
|
||||
|
||||
@Inject(
|
||||
method = "push(Lnet/minecraft/world/entity/Entity;)V",
|
||||
at = @At("HEAD"),
|
||||
cancellable = true)
|
||||
private void astra$noInternalCollision(Entity other, CallbackInfo ci) {
|
||||
var self = (AbstractMinecart) (Object) this;
|
||||
astra$beforePlayerPush =
|
||||
other instanceof net.minecraft.world.entity.player.Player
|
||||
? self.getDeltaMovement()
|
||||
: null;
|
||||
if (other instanceof AbstractMinecart cart && Trains.connected(self, cart)) ci.cancel();
|
||||
}
|
||||
|
||||
@Inject(method = "push(Lnet/minecraft/world/entity/Entity;)V", at = @At("RETURN"))
|
||||
private void astra$playerPush(Entity other, CallbackInfo ci) {
|
||||
var self = (AbstractMinecart) (Object) this;
|
||||
if (astra$beforePlayerPush != null
|
||||
&& self.getDeltaMovement().subtract(astra$beforePlayerPush).horizontalDistanceSqr()
|
||||
> 1e-12) Trains.playerPush(self);
|
||||
astra$beforePlayerPush = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
|
||||
public interface CartSpeed {
|
||||
/** Blocks per tick, or zero until the cart encounters a powered speed regulator. */
|
||||
double astracontent$limit(ServerLevel level);
|
||||
|
||||
@@ -1,20 +1,32 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
||||
|
||||
public final class RailCommands {
|
||||
private RailCommands() {}
|
||||
@SubscribeEvent public static void register(RegisterCommandsEvent event) {
|
||||
var give=Commands.literal("give");
|
||||
for(int i=0;i<8;i++) {
|
||||
var kind=RailKind.decode(i);
|
||||
give.then(Commands.literal(kind.id().getPath()).executes(ctx->{
|
||||
var player=ctx.getSource().getPlayerOrException();
|
||||
var stack=Rails.stack(kind,64);
|
||||
if(!player.getInventory().add(stack)) player.drop(stack,false);
|
||||
return 1;
|
||||
}));
|
||||
|
||||
@SubscribeEvent
|
||||
public static void register(RegisterCommandsEvent event) {
|
||||
var give = Commands.literal("give");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
var kind = RailKind.decode(i);
|
||||
give.then(
|
||||
Commands.literal(kind.id().getPath())
|
||||
.executes(
|
||||
ctx -> {
|
||||
var player = ctx.getSource().getPlayerOrException();
|
||||
var stack = Rails.stack(kind, 64);
|
||||
if (!player.getInventory().add(stack))
|
||||
player.drop(stack, false);
|
||||
return 1;
|
||||
}));
|
||||
}
|
||||
event.getDispatcher().register(Commands.literal("astracontent").requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS)).then(give));
|
||||
event.getDispatcher()
|
||||
.register(
|
||||
Commands.literal("astracontent")
|
||||
.requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS))
|
||||
.then(give));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,21 +13,45 @@ import net.minecraft.world.level.storage.ValueOutput;
|
||||
|
||||
final class RailDisplay extends Display.ItemDisplay {
|
||||
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);
|
||||
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" : "");
|
||||
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()));
|
||||
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;
|
||||
}
|
||||
@Override public boolean shouldBeSaved() { return false; }
|
||||
@Override public boolean saveAsPassenger(ValueOutput output) { return false; }
|
||||
}
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
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;
|
||||
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));
|
||||
return new Quaternionf().rotateY((float) Math.PI + (eastWest ? -(float) Math.PI / 2 : 0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,22 +8,39 @@ import net.minecraft.world.item.component.CustomData;
|
||||
|
||||
/** Vanilla item, vanilla components: native placement prediction without a client mod. */
|
||||
public final class RailItems {
|
||||
public static final String KEY="astracontent:rail";
|
||||
public static final String KEY = "astracontent:rail";
|
||||
|
||||
private RailItems() {}
|
||||
|
||||
public static RailKind find(ItemStack stack) {
|
||||
if(!stack.is(Items.POWERED_RAIL)) return null;
|
||||
var data=stack.get(DataComponents.CUSTOM_DATA);if(data==null)return null;
|
||||
int value=data.copyTag().getIntOr(KEY,-1);
|
||||
return value>=0 && value<8?RailKind.decode(value):null;
|
||||
if (!stack.is(Items.POWERED_RAIL)) return null;
|
||||
var data = stack.get(DataComponents.CUSTOM_DATA);
|
||||
if (data == null) return null;
|
||||
int value = data.copyTag().getIntOr(KEY, -1);
|
||||
return value >= 0 && value < 8 ? RailKind.decode(value) : null;
|
||||
}
|
||||
public static ItemStack create(RailKind kind,int count) {
|
||||
var stack=new ItemStack(Items.POWERED_RAIL,count);
|
||||
var tag=new CompoundTag();tag.putInt(KEY,kind.code());stack.set(DataComponents.CUSTOM_DATA,CustomData.of(tag));
|
||||
stack.set(DataComponents.ITEM_MODEL,kind.id());
|
||||
stack.set(DataComponents.ITEM_NAME,Component.translatableWithFallback("item.astracontent."+kind.id().getPath(),name(kind)));
|
||||
|
||||
public static ItemStack create(RailKind kind, int count) {
|
||||
var stack = new ItemStack(Items.POWERED_RAIL, count);
|
||||
var tag = new CompoundTag();
|
||||
tag.putInt(KEY, kind.code());
|
||||
stack.set(DataComponents.CUSTOM_DATA, CustomData.of(tag));
|
||||
stack.set(DataComponents.ITEM_MODEL, kind.id());
|
||||
stack.set(
|
||||
DataComponents.ITEM_NAME,
|
||||
Component.translatableWithFallback(
|
||||
"item.astracontent." + kind.id().getPath(), name(kind)));
|
||||
return stack;
|
||||
}
|
||||
|
||||
public static String name(RailKind kind) {
|
||||
return (kind.waxed()?"Вощёные: ":"")+new String[]{"Медные рельсы","Потемневшие медные рельсы","Состаренные медные рельсы","Окисленные медные рельсы"}[kind.age()];
|
||||
return (kind.waxed() ? "Вощёные: " : "")
|
||||
+ new String[] {
|
||||
"Медные рельсы",
|
||||
"Потемневшие медные рельсы",
|
||||
"Состаренные медные рельсы",
|
||||
"Окисленные медные рельсы"
|
||||
}
|
||||
[kind.age()];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,32 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
public record RailKind(int age, boolean waxed) {
|
||||
public RailKind { if (age < 0 || age > 3) throw new IllegalArgumentException("Oxidation: " + age); }
|
||||
public int speed() { return 20 - 4 * age; }
|
||||
public int code() { return age + (waxed ? 4 : 0); }
|
||||
public static RailKind decode(int code) { return new RailKind(code & 3, (code & 4) != 0); }
|
||||
public Identifier id() {
|
||||
return Identifier.fromNamespaceAndPath("astracontent", (waxed ? "waxed_" : "")
|
||||
+ new String[]{"", "exposed_", "weathered_", "oxidized_"}[age] + "copper_rail");
|
||||
public RailKind {
|
||||
if (age < 0 || age > 3) throw new IllegalArgumentException("Oxidation: " + age);
|
||||
}
|
||||
|
||||
public int speed() {
|
||||
return 20 - 4 * age;
|
||||
}
|
||||
|
||||
public int code() {
|
||||
return age + (waxed ? 4 : 0);
|
||||
}
|
||||
|
||||
public static RailKind decode(int code) {
|
||||
return new RailKind(code & 3, (code & 4) != 0);
|
||||
}
|
||||
|
||||
public Identifier id() {
|
||||
return Identifier.fromNamespaceAndPath(
|
||||
"astracontent",
|
||||
(waxed ? "waxed_" : "")
|
||||
+ new String[] {"", "exposed_", "weathered_", "oxidized_"}[age]
|
||||
+ "copper_rail");
|
||||
}
|
||||
|
||||
public static RailKind fromId(Identifier id) {
|
||||
for (int code = 0; code < 8; code++) if (decode(code).id().equals(id)) return decode(code);
|
||||
return null;
|
||||
|
||||
@@ -8,21 +8,28 @@ import net.minecraft.world.level.gamerules.GameRules;
|
||||
/** Match copper's random-tick selection, age neighborhood and oxidation probability. */
|
||||
final class RailOxidation {
|
||||
private RailOxidation() {}
|
||||
static boolean advance(ServerLevel level,BlockPos pos,RailKind kind) {
|
||||
if(kind.waxed() || kind.age()==3 || !level.isPositionEntityTicking(pos))return false;
|
||||
int rate=level.getGameRules().get(GameRules.RANDOM_TICK_SPEED);
|
||||
double chance=1-Math.pow(1-.05688889/4096,rate);
|
||||
if(level.getRandom().nextDouble()>=chance)return false;
|
||||
int older=0,same=0;
|
||||
for(var other:BlockPos.withinManhattan(pos,4,4,4)) {
|
||||
int distance=other.distManhattan(pos);if(distance>4)break;if(distance==0 || !level.hasChunkAt(other))continue;
|
||||
int age=-1;
|
||||
var rail=Rails.find(level,other);
|
||||
if(rail!=null && !rail.waxed())age=rail.age();
|
||||
else if(level.getBlockState(other).getBlock() instanceof WeatheringCopper copper)age=copper.getAge().ordinal();
|
||||
if(age<0)continue;if(age<kind.age())return false;if(age>kind.age())older++;else same++;
|
||||
|
||||
static boolean advance(ServerLevel level, BlockPos pos, RailKind kind) {
|
||||
if (kind.waxed() || kind.age() == 3 || !level.isPositionEntityTicking(pos)) return false;
|
||||
int rate = level.getGameRules().get(GameRules.RANDOM_TICK_SPEED);
|
||||
double chance = 1 - Math.pow(1 - .05688889 / 4096, rate);
|
||||
if (level.getRandom().nextDouble() >= chance) return false;
|
||||
int older = 0, same = 0;
|
||||
for (var other : BlockPos.withinManhattan(pos, 4, 4, 4)) {
|
||||
int distance = other.distManhattan(pos);
|
||||
if (distance > 4) break;
|
||||
if (distance == 0 || !level.hasChunkAt(other)) continue;
|
||||
int age = -1;
|
||||
var rail = Rails.find(level, other);
|
||||
if (rail != null && !rail.waxed()) age = rail.age();
|
||||
else if (level.getBlockState(other).getBlock() instanceof WeatheringCopper copper)
|
||||
age = copper.getAge().ordinal();
|
||||
if (age < 0) continue;
|
||||
if (age < kind.age()) return false;
|
||||
if (age > kind.age()) older++;
|
||||
else same++;
|
||||
}
|
||||
double ratio=(older+1.0)/(older+same+1.0);
|
||||
return level.getRandom().nextDouble()<ratio*ratio*(kind.age()==0?.75:1);
|
||||
double ratio = (older + 1.0) / (older + same + 1.0);
|
||||
return level.getRandom().nextDouble() < ratio * ratio * (kind.age() == 0 ? .75 : 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,71 +1,110 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import java.util.*;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Vec3i;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class RailSpeed {
|
||||
private RailSpeed() {}
|
||||
public static int signalSpeed(int signal) { return Math.clamp(signal,0,15)*2; }
|
||||
public static double target(ServerLevel level, BlockPos pos, double previous) {
|
||||
var state=level.getBlockState(pos);
|
||||
if (!state.is(Blocks.POWERED_RAIL) || !state.getValue(PoweredRailBlock.POWERED)) return previous;
|
||||
var kind=Rails.find(level,pos);
|
||||
return kind != null ? kind.speed() : Math.max(2,signalSpeed(signal(level,pos)));
|
||||
|
||||
public static int signalSpeed(int signal) {
|
||||
return Math.clamp(signal, 0, 15) * 2;
|
||||
}
|
||||
|
||||
public static double target(ServerLevel level, BlockPos pos, double previous) {
|
||||
var state = level.getBlockState(pos);
|
||||
if (!state.is(Blocks.POWERED_RAIL) || !state.getValue(PoweredRailBlock.POWERED))
|
||||
return previous;
|
||||
var kind = Rails.find(level, pos);
|
||||
return kind != null ? kind.speed() : Math.max(2, signalSpeed(signal(level, pos)));
|
||||
}
|
||||
|
||||
/** Mirror the vanilla eight-rail power reach, preserving bends, slopes and highest input. */
|
||||
public static int signal(ServerLevel level, BlockPos origin) {
|
||||
record Step(BlockPos pos,int distance) {}
|
||||
var queue=new ArrayDeque<Step>(); var seen=new HashSet<BlockPos>(); queue.add(new Step(origin,0));
|
||||
int best=0;
|
||||
while(!queue.isEmpty()) {
|
||||
var step=queue.removeFirst(); if(!seen.add(step.pos) || !level.hasChunkAt(step.pos)) continue;
|
||||
var state=level.getBlockState(step.pos);
|
||||
record Step(BlockPos pos, int distance) {}
|
||||
var queue = new ArrayDeque<Step>();
|
||||
var seen = new HashSet<BlockPos>();
|
||||
queue.add(new Step(origin, 0));
|
||||
int best = 0;
|
||||
while (!queue.isEmpty()) {
|
||||
var step = queue.removeFirst();
|
||||
if (!seen.add(step.pos) || !level.hasChunkAt(step.pos)) continue;
|
||||
var state = level.getBlockState(step.pos);
|
||||
if (!state.is(Blocks.POWERED_RAIL)) continue;
|
||||
best=Math.max(best,level.getBestNeighborSignal(step.pos)); if(best==15) return best;
|
||||
if(step.distance==8) continue;
|
||||
var shape=state.getValue(PoweredRailBlock.SHAPE);
|
||||
var exits=AbstractMinecart.exits(shape);
|
||||
for(var exit:List.of(exits.getFirst(),exits.getSecond())) {
|
||||
var adjacent=step.pos.offset(exit.getX(),shape.isSlope()?exit.getY()+1:0,exit.getZ());
|
||||
for(var candidate:List.of(adjacent,adjacent.below())) {
|
||||
if(!level.hasChunkAt(candidate)) continue;
|
||||
var other=level.getBlockState(candidate);
|
||||
if(other.is(Blocks.POWERED_RAIL) && connected(step.pos,shape,candidate,other.getValue(PoweredRailBlock.SHAPE)))
|
||||
queue.add(new Step(candidate,step.distance+1));
|
||||
best = Math.max(best, level.getBestNeighborSignal(step.pos));
|
||||
if (best == 15) return best;
|
||||
if (step.distance == 8) continue;
|
||||
var shape = state.getValue(PoweredRailBlock.SHAPE);
|
||||
var exits = AbstractMinecart.exits(shape);
|
||||
for (var exit : List.of(exits.getFirst(), exits.getSecond())) {
|
||||
var adjacent =
|
||||
step.pos.offset(
|
||||
exit.getX(), shape.isSlope() ? exit.getY() + 1 : 0, exit.getZ());
|
||||
for (var candidate : List.of(adjacent, adjacent.below())) {
|
||||
if (!level.hasChunkAt(candidate)) continue;
|
||||
var other = level.getBlockState(candidate);
|
||||
if (other.is(Blocks.POWERED_RAIL)
|
||||
&& connected(
|
||||
step.pos,
|
||||
shape,
|
||||
candidate,
|
||||
other.getValue(PoweredRailBlock.SHAPE)))
|
||||
queue.add(new Step(candidate, step.distance + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
private static boolean connected(BlockPos a,RailShape sa,BlockPos b,RailShape sb) {
|
||||
var ea=AbstractMinecart.exits(sa); var eb=AbstractMinecart.exits(sb);
|
||||
for(var x:List.of(ea.getFirst(),ea.getSecond())) for(var y:List.of(eb.getFirst(),eb.getSecond()))
|
||||
if(a.getX()+x.getX()==b.getX() && a.getZ()+x.getZ()==b.getZ()
|
||||
&& b.getX()+y.getX()==a.getX() && b.getZ()+y.getZ()==a.getZ()
|
||||
&& a.getY()+(sa.isSlope()?x.getY()+1:0)==b.getY()+(sb.isSlope()?y.getY()+1:0)) return true;
|
||||
|
||||
private static boolean connected(BlockPos a, RailShape sa, BlockPos b, RailShape sb) {
|
||||
var ea = AbstractMinecart.exits(sa);
|
||||
var eb = AbstractMinecart.exits(sb);
|
||||
for (var exitA : List.of(ea.getFirst(), ea.getSecond())) {
|
||||
if (a.getX() + exitA.getX() != b.getX()) continue;
|
||||
if (a.getZ() + exitA.getZ() != b.getZ()) continue;
|
||||
int heightA = exitHeight(a, sa, exitA);
|
||||
for (var exitB : List.of(eb.getFirst(), eb.getSecond())) {
|
||||
if (b.getX() + exitB.getX() != a.getX()) continue;
|
||||
if (b.getZ() + exitB.getZ() != a.getZ()) continue;
|
||||
if (heightA == exitHeight(b, sb, exitB)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static int exitHeight(BlockPos pos, RailShape shape, Vec3i exit) {
|
||||
if (shape.isSlope()) return pos.getY() + exit.getY() + 1;
|
||||
return pos.getY();
|
||||
}
|
||||
|
||||
private static boolean stopsFastTravel(BlockState state) {
|
||||
if (state.is(Blocks.DETECTOR_RAIL) || state.is(Blocks.ACTIVATOR_RAIL)) return true;
|
||||
return state.is(Blocks.POWERED_RAIL) && !state.getValue(PoweredRailBlock.POWERED);
|
||||
}
|
||||
|
||||
/** Old movement needs vanilla speed when approaching bends, slopes or the end of a track. */
|
||||
public static double safeLimit(AbstractMinecart cart,ServerLevel level,double limit) {
|
||||
if(AbstractMinecart.useExperimentalMovement(level) || limit<=.4) return limit;
|
||||
var pos=cart.getCurrentBlockPosOrRailBelow(); var movement=cart.getDeltaMovement();
|
||||
int dx=(int)Math.signum(movement.x), dz=(int)Math.signum(movement.z);
|
||||
for(int i=0;i<=2;i++) {
|
||||
var check=pos.offset(dx*i,0,dz*i);
|
||||
if(!level.hasChunkAt(check)) return .4;
|
||||
BlockState state=level.getBlockState(check);
|
||||
if(!(state.getBlock() instanceof BaseRailBlock rail)) return state.is(Blocks.SLIME_BLOCK)?limit:.4;
|
||||
RailShape shape=rail.getRailDirection(state,level,check,cart);
|
||||
if(shape!=RailShape.NORTH_SOUTH && shape!=RailShape.EAST_WEST) return .4;
|
||||
if (i>0 && (state.is(Blocks.DETECTOR_RAIL) || state.is(Blocks.ACTIVATOR_RAIL)
|
||||
|| state.is(Blocks.POWERED_RAIL) && !state.getValue(PoweredRailBlock.POWERED))) return .4;
|
||||
public static double safeLimit(AbstractMinecart cart, ServerLevel level, double limit) {
|
||||
if (AbstractMinecart.useExperimentalMovement(level) || limit <= .4) return limit;
|
||||
var pos = cart.getCurrentBlockPosOrRailBelow();
|
||||
var movement = cart.getDeltaMovement();
|
||||
int dx = (int) Math.signum(movement.x), dz = (int) Math.signum(movement.z);
|
||||
for (int i = 0; i <= 2; i++) {
|
||||
var check = pos.offset(dx * i, 0, dz * i);
|
||||
if (!level.hasChunkAt(check)) return .4;
|
||||
BlockState state = level.getBlockState(check);
|
||||
if (!(state.getBlock() instanceof BaseRailBlock rail))
|
||||
return state.is(Blocks.SLIME_BLOCK) ? limit : .4;
|
||||
RailShape shape = rail.getRailDirection(state, level, check, cart);
|
||||
if (shape != RailShape.NORTH_SOUTH && shape != RailShape.EAST_WEST) return .4;
|
||||
if (i > 0 && stopsFastTravel(state)) return .4;
|
||||
// Never jump over a single slower regulator.
|
||||
if (i>0) limit=Math.min(limit,target(level,check,limit*20)/20);
|
||||
if (i > 0) limit = Math.min(limit, target(level, check, limit * 20) / 20);
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
@@ -12,104 +11,196 @@ import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.neoforged.bus.api.*;
|
||||
import net.neoforged.neoforge.attachment.AttachmentType;
|
||||
import net.neoforged.neoforge.registries.*;
|
||||
import net.neoforged.neoforge.event.level.ChunkEvent;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
import net.neoforged.neoforge.event.level.ChunkEvent;
|
||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
import net.neoforged.neoforge.registries.*;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Native powered rails own placement, shape, redstone, collision and destruction. */
|
||||
public final class Rails {
|
||||
private static final DeferredRegister<AttachmentType<?>> TYPES = DeferredRegister.create(NeoForgeRegistries.Keys.ATTACHMENT_TYPES, "astracontent");
|
||||
public static final Supplier<AttachmentType<Map<Long, Integer>>> DATA = TYPES.register("copper_rails", () ->
|
||||
AttachmentType.<Map<Long,Integer>>builder(() -> new HashMap<>()).serialize(
|
||||
Codec.unboundedMap(Codec.STRING.xmap(Long::parseLong, String::valueOf), Codec.intRange(0,7))
|
||||
.xmap(map -> (Map<Long,Integer>)new HashMap<>(map), map -> map).fieldOf("rails"), map -> !map.isEmpty()).build());
|
||||
private static final DeferredRegister<AttachmentType<?>> TYPES =
|
||||
DeferredRegister.create(NeoForgeRegistries.Keys.ATTACHMENT_TYPES, "astracontent");
|
||||
public static final Supplier<AttachmentType<Map<Long, Integer>>> DATA =
|
||||
TYPES.register(
|
||||
"copper_rails",
|
||||
() ->
|
||||
AttachmentType.<Map<Long, Integer>>builder(() -> new HashMap<>())
|
||||
.serialize(
|
||||
Codec.unboundedMap(
|
||||
Codec.STRING.xmap(
|
||||
Long::parseLong,
|
||||
String::valueOf),
|
||||
Codec.intRange(0, 7))
|
||||
.xmap(
|
||||
map ->
|
||||
(Map<Long, Integer>)
|
||||
new HashMap<>(map),
|
||||
map -> map)
|
||||
.fieldOf("rails"),
|
||||
map -> !map.isEmpty())
|
||||
.build());
|
||||
|
||||
private record Position(ServerLevel level, BlockPos pos) {}
|
||||
|
||||
private record Removed(RailKind kind, long tick) {}
|
||||
private static final Map<Position,RailDisplay> ACTIVE = new HashMap<>();
|
||||
private static final Map<Position,Removed> REMOVED = new HashMap<>();
|
||||
|
||||
private static final Map<Position, RailDisplay> ACTIVE = new HashMap<>();
|
||||
private static final Map<Position, Removed> REMOVED = new HashMap<>();
|
||||
|
||||
private Rails() {}
|
||||
public static void register(IEventBus bus) { TYPES.register(bus); }
|
||||
|
||||
public static void register(IEventBus bus) {
|
||||
TYPES.register(bus);
|
||||
}
|
||||
|
||||
public static RailKind find(ServerLevel level, BlockPos pos) {
|
||||
var chunk = level.getChunkSource().getChunkNow(pos.getX() >> 4, pos.getZ() >> 4);
|
||||
if (chunk == null || !chunk.hasData(DATA)) return null;
|
||||
Integer code = chunk.getData(DATA).get(pos.asLong());
|
||||
return code == null ? null : RailKind.decode(code);
|
||||
}
|
||||
|
||||
public static RailKind loot(ServerLevel level, BlockPos pos) {
|
||||
var kind = find(level,pos);
|
||||
var removed = REMOVED.get(new Position(level,pos));
|
||||
return kind != null ? kind : removed != null && removed.tick == level.getGameTime() ? removed.kind : null;
|
||||
var kind = find(level, pos);
|
||||
if (kind != null) return kind;
|
||||
var removed = REMOVED.get(new Position(level, pos));
|
||||
if (removed == null || removed.tick != level.getGameTime()) return null;
|
||||
return removed.kind;
|
||||
}
|
||||
public static ItemStack stack(RailKind kind, int count) { return RailItems.create(kind,count); }
|
||||
|
||||
public static ItemStack stack(RailKind kind, int count) {
|
||||
return RailItems.create(kind, count);
|
||||
}
|
||||
|
||||
public static void placed(ServerLevel level, BlockPos pos, ItemStack stack) {
|
||||
clear(level,pos); REMOVED.remove(new Position(level,pos));
|
||||
clear(level, pos);
|
||||
REMOVED.remove(new Position(level, pos));
|
||||
var kind = RailItems.find(stack);
|
||||
if (kind != null) put(level,pos,kind);
|
||||
if (kind != null) put(level, pos, kind);
|
||||
}
|
||||
|
||||
public static void put(ServerLevel level, BlockPos pos, RailKind kind) {
|
||||
var chunk = level.getChunkAt(pos); chunk.getData(DATA).put(pos.asLong(),kind.code()); chunk.markUnsaved();
|
||||
ACTIVE.putIfAbsent(new Position(level,pos.immutable()), null);
|
||||
var chunk = level.getChunkAt(pos);
|
||||
chunk.getData(DATA).put(pos.asLong(), kind.code());
|
||||
chunk.markUnsaved();
|
||||
ACTIVE.putIfAbsent(new Position(level, pos.immutable()), null);
|
||||
}
|
||||
public static void changed(ServerLevel level, BlockPos pos, BlockState before, BlockState after) {
|
||||
if (before == null || !before.is(Blocks.POWERED_RAIL) || after.is(Blocks.POWERED_RAIL)) return;
|
||||
var kind = find(level,pos);
|
||||
if (kind != null) { REMOVED.put(new Position(level,pos.immutable()),new Removed(kind,level.getGameTime())); clear(level,pos); }
|
||||
}
|
||||
private static void clear(ServerLevel level, BlockPos pos) {
|
||||
var chunk = level.getChunkSource().getChunkNow(pos.getX() >> 4,pos.getZ() >> 4);
|
||||
if (chunk != null && chunk.hasData(DATA) && chunk.getData(DATA).remove(pos.asLong()) != null) chunk.markUnsaved();
|
||||
var display = ACTIVE.remove(new Position(level,pos)); if (display != null) display.discard();
|
||||
}
|
||||
@SubscribeEvent public static void load(ChunkEvent.Load event) {
|
||||
if (!(event.getLevel() instanceof ServerLevel level) || !(event.getChunk() instanceof LevelChunk chunk)) return;
|
||||
level.getServer().execute(() -> {
|
||||
if (level.getChunkSource().getChunkNow(chunk.getPos().x(),chunk.getPos().z()) != chunk || !chunk.hasData(DATA)) return;
|
||||
chunk.getData(DATA).forEach((packed,code) -> {
|
||||
var pos = BlockPos.of(packed);
|
||||
if (pos.getX() >> 4 == chunk.getPos().x() && pos.getZ() >> 4 == chunk.getPos().z())
|
||||
ACTIVE.putIfAbsent(new Position(level,pos),null);
|
||||
});
|
||||
});
|
||||
}
|
||||
@SubscribeEvent public static void unload(ChunkEvent.Unload event) {
|
||||
for (var key : new ArrayList<>(ACTIVE.keySet())) if (key.level == event.getLevel()
|
||||
&& key.pos.getX() >> 4 == event.getChunk().getPos().x() && key.pos.getZ() >> 4 == event.getChunk().getPos().z()) {
|
||||
var display = ACTIVE.remove(key); if (display != null) display.discard();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@SubscribeEvent public static void stopped(ServerStoppedEvent event) {
|
||||
ACTIVE.values().stream().filter(Objects::nonNull).forEach(RailDisplay::discard); ACTIVE.clear(); REMOVED.clear();
|
||||
|
||||
private static void clear(ServerLevel level, BlockPos pos) {
|
||||
var chunk = level.getChunkSource().getChunkNow(pos.getX() >> 4, pos.getZ() >> 4);
|
||||
if (chunk != null
|
||||
&& chunk.hasData(DATA)
|
||||
&& chunk.getData(DATA).remove(pos.asLong()) != null) chunk.markUnsaved();
|
||||
var display = ACTIVE.remove(new Position(level, pos));
|
||||
if (display != null) display.discard();
|
||||
}
|
||||
@SubscribeEvent public static void tick(ServerTickEvent.Post event) {
|
||||
|
||||
@SubscribeEvent
|
||||
public static void load(ChunkEvent.Load event) {
|
||||
if (!(event.getLevel() instanceof ServerLevel level)
|
||||
|| !(event.getChunk() instanceof LevelChunk chunk)) return;
|
||||
level.getServer()
|
||||
.execute(
|
||||
() -> {
|
||||
if (level.getChunkSource()
|
||||
.getChunkNow(
|
||||
chunk.getPos().x(), chunk.getPos().z())
|
||||
!= chunk
|
||||
|| !chunk.hasData(DATA)) return;
|
||||
chunk.getData(DATA)
|
||||
.forEach(
|
||||
(packed, code) -> {
|
||||
var pos = BlockPos.of(packed);
|
||||
if (pos.getX() >> 4 == chunk.getPos().x()
|
||||
&& pos.getZ() >> 4 == chunk.getPos().z())
|
||||
ACTIVE.putIfAbsent(
|
||||
new Position(level, pos), null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void unload(ChunkEvent.Unload event) {
|
||||
for (var key : new ArrayList<>(ACTIVE.keySet()))
|
||||
if (key.level == event.getLevel()
|
||||
&& key.pos.getX() >> 4 == event.getChunk().getPos().x()
|
||||
&& key.pos.getZ() >> 4 == event.getChunk().getPos().z()) {
|
||||
var display = ACTIVE.remove(key);
|
||||
if (display != null) display.discard();
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void stopped(ServerStoppedEvent event) {
|
||||
ACTIVE.values().stream().filter(Objects::nonNull).forEach(RailDisplay::discard);
|
||||
ACTIVE.clear();
|
||||
REMOVED.clear();
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void tick(ServerTickEvent.Post event) {
|
||||
for (var key : new ArrayList<>(ACTIVE.keySet())) {
|
||||
var state = key.level.getBlockState(key.pos); var kind = find(key.level,key.pos);
|
||||
if (kind == null || !state.is(Blocks.POWERED_RAIL)) { clear(key.level,key.pos); continue; }
|
||||
if (RailOxidation.advance(key.level,key.pos,kind)) {
|
||||
kind = new RailKind(kind.age()+1,false); put(key.level,key.pos,kind);
|
||||
var state = key.level.getBlockState(key.pos);
|
||||
var kind = find(key.level, key.pos);
|
||||
if (kind == null || !state.is(Blocks.POWERED_RAIL)) {
|
||||
clear(key.level, key.pos);
|
||||
continue;
|
||||
}
|
||||
if (RailOxidation.advance(key.level, key.pos, kind)) {
|
||||
kind = new RailKind(kind.age() + 1, false);
|
||||
put(key.level, key.pos, kind);
|
||||
}
|
||||
var display = ACTIVE.get(key);
|
||||
if (display == null || display.isRemoved()) {
|
||||
display = new RailDisplay(key.level,key.pos); display.update(kind,state);
|
||||
if (key.level.addFreshEntity(display)) ACTIVE.put(key,display);
|
||||
} else display.update(kind,state);
|
||||
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());
|
||||
REMOVED.entrySet()
|
||||
.removeIf(entry -> entry.getValue().tick < entry.getKey().level.getGameTime());
|
||||
}
|
||||
@SubscribeEvent public static void use(PlayerInteractEvent.RightClickBlock event) {
|
||||
|
||||
@SubscribeEvent
|
||||
public static void use(PlayerInteractEvent.RightClickBlock event) {
|
||||
if (!(event.getLevel() instanceof ServerLevel level)) return;
|
||||
var kind = find(level,event.getPos()); if (kind == null) return;
|
||||
var item = event.getItemStack(); RailKind next;
|
||||
var kind = find(level, event.getPos());
|
||||
if (kind == null) return;
|
||||
var item = event.getItemStack();
|
||||
RailKind next;
|
||||
int effect;
|
||||
if (item.is(Items.HONEYCOMB) && !kind.waxed()) { next = new RailKind(kind.age(),true); effect=3003; }
|
||||
else if (item.getItem() instanceof AxeItem && (kind.waxed() || kind.age()>0)) {
|
||||
next = kind.waxed() ? new RailKind(kind.age(),false) : new RailKind(kind.age()-1,false); effect=kind.waxed()?3004:3005;
|
||||
if (item.is(Items.HONEYCOMB) && !kind.waxed()) {
|
||||
next = new RailKind(kind.age(), true);
|
||||
effect = 3003;
|
||||
} else if (item.getItem() instanceof AxeItem && (kind.waxed() || kind.age() > 0)) {
|
||||
next =
|
||||
kind.waxed()
|
||||
? new RailKind(kind.age(), false)
|
||||
: new RailKind(kind.age() - 1, false);
|
||||
effect = kind.waxed() ? 3004 : 3005;
|
||||
} else return;
|
||||
if (!event.getEntity().mayBuild()) return;
|
||||
put(level,event.getPos(),next); level.levelEvent(null,effect,event.getPos(),0);
|
||||
if (item.is(Items.HONEYCOMB)) item.consume(1,event.getEntity());
|
||||
else item.hurtAndBreak(1,event.getEntity(),event.getHand().asEquipmentSlot());
|
||||
event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
put(level, event.getPos(), next);
|
||||
level.levelEvent(null, effect, event.getPos(), 0);
|
||||
if (item.is(Items.HONEYCOMB)) item.consume(1, event.getEntity());
|
||||
else item.hurtAndBreak(1, event.getEntity(), event.getHand().asEquipmentSlot());
|
||||
event.setCanceled(true);
|
||||
event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package online.astradev.content.train;
|
||||
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public interface CartFrame {
|
||||
Vec3 astracontent$front();
|
||||
|
||||
void astracontent$front(Vec3 axis);
|
||||
}
|
||||
|
||||
@@ -1,27 +1,49 @@
|
||||
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 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()));
|
||||
|
||||
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;}
|
||||
|
||||
@Override
|
||||
public boolean shouldBeSaved() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean saveAsPassenger(ValueOutput output) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,25 +5,51 @@ import net.minecraft.world.level.block.BaseRailBlock;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public final class CouplingGeometry {
|
||||
private CouplingGeometry(){}
|
||||
public static Vec3 axis(AbstractMinecart cart){
|
||||
var frame=(CartFrame)cart;var previous=frame.astracontent$front();
|
||||
double yaw=Math.toRadians(cart.getYRot());
|
||||
if(previous.lengthSqr()<.5)previous=new Vec3(Math.cos(yaw),0,Math.sin(yaw)*(AbstractMinecart.useExperimentalMovement(cart.level())?-1:1));
|
||||
var pos=cart.getCurrentBlockPosOrRailBelow();var state=cart.level().getBlockState(pos);
|
||||
Vec3 axis=previous;
|
||||
if(state.getBlock() instanceof BaseRailBlock rail){
|
||||
var exits=AbstractMinecart.exits(rail.getRailDirection(state,cart.level(),pos,cart));
|
||||
axis=new Vec3(exits.getSecond().getX()-exits.getFirst().getX(),0,exits.getSecond().getZ()-exits.getFirst().getZ()).normalize();
|
||||
if(axis.dot(previous)<0)axis=axis.scale(-1);
|
||||
private CouplingGeometry() {}
|
||||
|
||||
public static Vec3 axis(AbstractMinecart cart) {
|
||||
var frame = (CartFrame) cart;
|
||||
var previous = frame.astracontent$front();
|
||||
double yaw = Math.toRadians(cart.getYRot());
|
||||
if (previous.lengthSqr() < .5)
|
||||
previous =
|
||||
new Vec3(
|
||||
Math.cos(yaw),
|
||||
0,
|
||||
Math.sin(yaw)
|
||||
* (AbstractMinecart.useExperimentalMovement(cart.level())
|
||||
? -1
|
||||
: 1));
|
||||
var pos = cart.getCurrentBlockPosOrRailBelow();
|
||||
var state = cart.level().getBlockState(pos);
|
||||
Vec3 axis = previous;
|
||||
if (state.getBlock() instanceof BaseRailBlock rail) {
|
||||
var exits =
|
||||
AbstractMinecart.exits(rail.getRailDirection(state, cart.level(), pos, cart));
|
||||
axis =
|
||||
new Vec3(
|
||||
exits.getSecond().getX() - exits.getFirst().getX(),
|
||||
0,
|
||||
exits.getSecond().getZ() - exits.getFirst().getZ())
|
||||
.normalize();
|
||||
if (axis.dot(previous) < 0) axis = axis.scale(-1);
|
||||
}
|
||||
frame.astracontent$front(axis);return axis;
|
||||
frame.astracontent$front(axis);
|
||||
return axis;
|
||||
}
|
||||
public static int hitEnd(Vec3 axis,Vec3 localHit){
|
||||
double along=localHit.horizontal().dot(axis);
|
||||
double across=Math.abs(localHit.x*axis.z-localHit.z*axis.x);
|
||||
return Math.abs(along)>=.32 && Math.abs(along)>across*1.3?(along>0?0:1):-1;
|
||||
|
||||
public static int hitEnd(Vec3 axis, Vec3 localHit) {
|
||||
double along = localHit.horizontal().dot(axis);
|
||||
double across = Math.abs(localHit.x * axis.z - localHit.z * axis.x);
|
||||
if (Math.abs(along) < .32 || Math.abs(along) <= across * 1.3) return -1;
|
||||
return along > 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
public static Vec3 outward(AbstractMinecart cart, int end) {
|
||||
return axis(cart).scale(end == 0 ? 1 : -1);
|
||||
}
|
||||
|
||||
public static Vec3 anchor(AbstractMinecart cart, int end) {
|
||||
return cart.position().add(0, .35, 0).add(outward(cart, end).scale(.48));
|
||||
}
|
||||
public static Vec3 outward(AbstractMinecart cart,int end){return axis(cart).scale(end==0?1:-1);}
|
||||
public static Vec3 anchor(AbstractMinecart cart,int end){return cart.position().add(0,.35,0).add(outward(cart,end).scale(.48));}
|
||||
}
|
||||
|
||||
@@ -2,37 +2,105 @@ package online.astradev.content.train;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import java.util.*;
|
||||
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.level.saveddata.*;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** One authoritative record per chain, including unloaded carts. No duplicated refunds. */
|
||||
public final class TrainData extends SavedData {
|
||||
public record Link(UUID a,int endA,UUID b,int endB,String item,boolean paid,double length) {
|
||||
private static final Codec<UUID> UUID_CODEC=Codec.STRING.xmap(UUID::fromString,UUID::toString);
|
||||
static final Codec<Link> CODEC=RecordCodecBuilder.create(i->i.group(
|
||||
UUID_CODEC.fieldOf("a").forGetter(Link::a),Codec.intRange(0,1).fieldOf("end_a").forGetter(Link::endA),
|
||||
UUID_CODEC.fieldOf("b").forGetter(Link::b),Codec.intRange(0,1).fieldOf("end_b").forGetter(Link::endB),
|
||||
Codec.STRING.fieldOf("item").forGetter(Link::item),Codec.BOOL.fieldOf("paid").forGetter(Link::paid),
|
||||
Codec.doubleRange(1,4).fieldOf("length").forGetter(Link::length)).apply(i,Link::new));
|
||||
public boolean touches(UUID id){return a.equals(id)||b.equals(id);}
|
||||
public UUID other(UUID id){return a.equals(id)?b:a;}
|
||||
public int end(UUID id){return a.equals(id)?endA:endB;}
|
||||
public record Link(
|
||||
UUID a, int endA, UUID b, int endB, String item, boolean paid, double length) {
|
||||
private static final Codec<UUID> UUID_CODEC =
|
||||
Codec.STRING.xmap(UUID::fromString, UUID::toString);
|
||||
static final Codec<Link> CODEC =
|
||||
RecordCodecBuilder.create(
|
||||
i ->
|
||||
i.group(
|
||||
UUID_CODEC.fieldOf("a").forGetter(Link::a),
|
||||
Codec.intRange(0, 1)
|
||||
.fieldOf("end_a")
|
||||
.forGetter(Link::endA),
|
||||
UUID_CODEC.fieldOf("b").forGetter(Link::b),
|
||||
Codec.intRange(0, 1)
|
||||
.fieldOf("end_b")
|
||||
.forGetter(Link::endB),
|
||||
Codec.STRING.fieldOf("item").forGetter(Link::item),
|
||||
Codec.BOOL.fieldOf("paid").forGetter(Link::paid),
|
||||
Codec.doubleRange(1, 4)
|
||||
.fieldOf("length")
|
||||
.forGetter(Link::length))
|
||||
.apply(i, Link::new));
|
||||
|
||||
public boolean touches(UUID id) {
|
||||
return a.equals(id) || b.equals(id);
|
||||
}
|
||||
|
||||
public UUID other(UUID id) {
|
||||
return a.equals(id) ? b : a;
|
||||
}
|
||||
|
||||
public int end(UUID id) {
|
||||
return a.equals(id) ? endA : endB;
|
||||
}
|
||||
}
|
||||
private static final Codec<TrainData> CODEC=Link.CODEC.listOf().xmap(TrainData::new,d->List.copyOf(d.links)).fieldOf("links").codec();
|
||||
private static final SavedDataType<TrainData> TYPE=new SavedDataType<>(Identifier.fromNamespaceAndPath("astracontent","trains"),TrainData::new,CODEC);
|
||||
private final List<Link> links=new ArrayList<>();
|
||||
public TrainData(){}
|
||||
private TrainData(List<Link> links){this.links.addAll(links);}
|
||||
public static TrainData get(ServerLevel level){return level.getDataStorage().computeIfAbsent(TYPE);}
|
||||
public List<Link> links(){return List.copyOf(links);}
|
||||
public Link at(UUID cart,int end){return links.stream().filter(l->l.touches(cart)&&l.end(cart)==end).findFirst().orElse(null);}
|
||||
public void add(Link link){links.add(link);setDirty();}
|
||||
public boolean remove(Link link){boolean removed=links.remove(link);if(removed)setDirty();return removed;}
|
||||
public Set<UUID> component(UUID root){
|
||||
var seen=new HashSet<UUID>();var pending=new ArrayDeque<UUID>();pending.add(root);
|
||||
while(!pending.isEmpty()){var id=pending.removeFirst();if(!seen.add(id))continue;for(var link:links)if(link.touches(id))pending.add(link.other(id));}
|
||||
|
||||
private static final Codec<TrainData> CODEC =
|
||||
Link.CODEC
|
||||
.listOf()
|
||||
.xmap(TrainData::new, d -> List.copyOf(d.links))
|
||||
.fieldOf("links")
|
||||
.codec();
|
||||
private static final SavedDataType<TrainData> TYPE =
|
||||
new SavedDataType<>(
|
||||
Identifier.fromNamespaceAndPath("astracontent", "trains"),
|
||||
TrainData::new,
|
||||
CODEC);
|
||||
private final List<Link> links = new ArrayList<>();
|
||||
|
||||
public TrainData() {}
|
||||
|
||||
private TrainData(List<Link> links) {
|
||||
this.links.addAll(links);
|
||||
}
|
||||
|
||||
public static TrainData get(ServerLevel level) {
|
||||
return level.getDataStorage().computeIfAbsent(TYPE);
|
||||
}
|
||||
|
||||
public List<Link> links() {
|
||||
return List.copyOf(links);
|
||||
}
|
||||
|
||||
public Link at(UUID cart, int end) {
|
||||
return links.stream()
|
||||
.filter(l -> l.touches(cart) && l.end(cart) == end)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public void add(Link link) {
|
||||
links.add(link);
|
||||
setDirty();
|
||||
}
|
||||
|
||||
public boolean remove(Link link) {
|
||||
boolean removed = links.remove(link);
|
||||
if (removed) setDirty();
|
||||
return removed;
|
||||
}
|
||||
|
||||
public Set<UUID> component(UUID root) {
|
||||
var seen = new HashSet<UUID>();
|
||||
var pending = new ArrayDeque<UUID>();
|
||||
pending.add(root);
|
||||
while (!pending.isEmpty()) {
|
||||
var id = pending.removeFirst();
|
||||
if (!seen.add(id)) continue;
|
||||
for (var link : links) if (link.touches(id)) pending.add(link.other(id));
|
||||
}
|
||||
return seen;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package online.astradev.content.train;
|
||||
|
||||
import java.util.*;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
@@ -19,166 +18,374 @@ import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class Trains {
|
||||
private record DisplayKey(ServerLevel level,TrainData.Link link){}
|
||||
private static final Map<DisplayKey,ChainDisplay> DISPLAYS=new HashMap<>();
|
||||
private static final Map<ServerLevel,Set<UUID>> PAUSED=new HashMap<>();
|
||||
private static final Map<ServerLevel,Set<UUID>> PLAYER_PUSHES=new HashMap<>();
|
||||
private Trains(){}
|
||||
public static boolean paused(AbstractMinecart cart){return PAUSED.getOrDefault(cart.level(),Set.of()).contains(cart.getUUID());}
|
||||
public static void playerPush(AbstractMinecart cart){
|
||||
if(cart.level() instanceof ServerLevel level)PLAYER_PUSHES.computeIfAbsent(level,key->new HashSet<>()).add(cart.getUUID());
|
||||
private record DisplayKey(ServerLevel level, TrainData.Link link) {}
|
||||
|
||||
private static final Map<DisplayKey, ChainDisplay> DISPLAYS = new HashMap<>();
|
||||
private static final Map<ServerLevel, Set<UUID>> PAUSED = new HashMap<>();
|
||||
private static final Map<ServerLevel, Set<UUID>> PLAYER_PUSHES = new HashMap<>();
|
||||
|
||||
private Trains() {}
|
||||
|
||||
public static boolean paused(AbstractMinecart cart) {
|
||||
return PAUSED.getOrDefault(cart.level(), Set.of()).contains(cart.getUUID());
|
||||
}
|
||||
public static boolean isChain(ItemStack stack){return stack.getItem() instanceof BlockItem item && item.getBlock() instanceof ChainBlock;}
|
||||
public static boolean connected(AbstractMinecart a,AbstractMinecart b){
|
||||
return a.level() instanceof ServerLevel level && b.level()==level
|
||||
&& TrainData.get(level).component(a.getUUID()).contains(b.getUUID());
|
||||
|
||||
public static void playerPush(AbstractMinecart cart) {
|
||||
if (cart.level() instanceof ServerLevel level)
|
||||
PLAYER_PUSHES.computeIfAbsent(level, key -> new HashSet<>()).add(cart.getUUID());
|
||||
}
|
||||
@SubscribeEvent public static void interact(PlayerInteractEvent.EntityInteract event){
|
||||
if(!(event.getTarget() instanceof AbstractMinecart cart) || !(cart.level() instanceof ServerLevel level)
|
||||
|| !event.getEntity().isShiftKeyDown())return;
|
||||
var player=event.getEntity();var item=event.getItemStack();boolean chain=isChain(item);
|
||||
if(!chain && !item.is(ItemTags.PICKAXES))return;
|
||||
event.setCanceled(true);event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
if(!player.mayBuild())return;
|
||||
int end=CouplingGeometry.hitEnd(CouplingGeometry.axis(cart),event.getLocation());
|
||||
if(end<0){message(player,"Цепь крепится только к переднему или заднему торцу.");return;}
|
||||
var data=TrainData.get(level);var existing=data.at(cart.getUUID(),end);
|
||||
if(!chain){
|
||||
if(existing==null){message(player,"На этом торце нет цепи.");return;}
|
||||
unlink(level,existing,cart,true);item.hurtAndBreak(1,player,event.getHand().asEquipmentSlot());return;
|
||||
|
||||
public static boolean isChain(ItemStack stack) {
|
||||
return stack.getItem() instanceof BlockItem item && item.getBlock() instanceof ChainBlock;
|
||||
}
|
||||
|
||||
public static boolean connected(AbstractMinecart a, AbstractMinecart b) {
|
||||
return a.level() instanceof ServerLevel level
|
||||
&& b.level() == level
|
||||
&& TrainData.get(level).component(a.getUUID()).contains(b.getUUID());
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void interact(PlayerInteractEvent.EntityInteract event) {
|
||||
if (!(event.getTarget() instanceof AbstractMinecart cart)
|
||||
|| !(cart.level() instanceof ServerLevel level)
|
||||
|| !event.getEntity().isShiftKeyDown()) return;
|
||||
var player = event.getEntity();
|
||||
var item = event.getItemStack();
|
||||
boolean chain = isChain(item);
|
||||
if (!chain && !item.is(ItemTags.PICKAXES)) return;
|
||||
event.setCanceled(true);
|
||||
event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
if (!player.mayBuild()) return;
|
||||
int end = CouplingGeometry.hitEnd(CouplingGeometry.axis(cart), event.getLocation());
|
||||
if (end < 0) {
|
||||
message(player, "Цепь крепится только к переднему или заднему торцу.");
|
||||
return;
|
||||
}
|
||||
if(existing!=null){message(player,"Этот торец уже сцеплен.");return;}
|
||||
Vec3 outward=CouplingGeometry.outward(cart,end);
|
||||
var candidates=level.getEntitiesOfClass(AbstractMinecart.class,cart.getBoundingBox().inflate(3.5),other->other!=cart && other.isAlive());
|
||||
var data = TrainData.get(level);
|
||||
var existing = data.at(cart.getUUID(), end);
|
||||
if (!chain) {
|
||||
if (existing == null) {
|
||||
message(player, "На этом торце нет цепи.");
|
||||
return;
|
||||
}
|
||||
unlink(level, existing, cart, true);
|
||||
item.hurtAndBreak(1, player, event.getHand().asEquipmentSlot());
|
||||
return;
|
||||
}
|
||||
if (existing != null) {
|
||||
message(player, "Этот торец уже сцеплен.");
|
||||
return;
|
||||
}
|
||||
Vec3 outward = CouplingGeometry.outward(cart, end);
|
||||
var candidates =
|
||||
level.getEntitiesOfClass(
|
||||
AbstractMinecart.class,
|
||||
cart.getBoundingBox().inflate(3.5),
|
||||
other -> other != cart && other.isAlive());
|
||||
candidates.sort(Comparator.comparingDouble(cart::distanceToSqr));
|
||||
for(var other:candidates){
|
||||
Vec3 between=other.position().subtract(cart.position());double distance=between.length();
|
||||
if(distance<1 || distance>3.5 || Math.abs(between.y)>1.5)continue;
|
||||
var direction=between.horizontal().normalize();
|
||||
if(direction.dot(outward)<.90)continue;
|
||||
int otherEnd=CouplingGeometry.axis(other).dot(direction)>0?1:0;
|
||||
if(CouplingGeometry.outward(other,otherEnd).dot(direction)>-.90 || data.at(other.getUUID(),otherEnd)!=null)continue;
|
||||
if(!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock)
|
||||
|| !(level.getBlockState(other.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock))continue;
|
||||
var hit=level.clip(new ClipContext(CouplingGeometry.anchor(cart,end),CouplingGeometry.anchor(other,otherEnd),ClipContext.Block.COLLIDER,ClipContext.Fluid.NONE,cart));
|
||||
if(hit.getType()!=HitResult.Type.MISS)continue;
|
||||
data.add(new TrainData.Link(cart.getUUID(),end,other.getUUID(),otherEnd,
|
||||
BuiltInRegistries.ITEM.getKey(item.getItem()).toString(),!player.hasInfiniteMaterials(),distance));
|
||||
item.consume(1,player);message(player,"Вагонетки сцеплены.");return;
|
||||
for (var other : candidates) {
|
||||
Vec3 between = other.position().subtract(cart.position());
|
||||
double distance = between.length();
|
||||
if (distance < 1 || distance > 3.5 || Math.abs(between.y) > 1.5) continue;
|
||||
var direction = between.horizontal().normalize();
|
||||
if (direction.dot(outward) < .90) continue;
|
||||
int otherEnd = CouplingGeometry.axis(other).dot(direction) > 0 ? 1 : 0;
|
||||
if (CouplingGeometry.outward(other, otherEnd).dot(direction) > -.90
|
||||
|| data.at(other.getUUID(), otherEnd) != null) continue;
|
||||
if (!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock()
|
||||
instanceof BaseRailBlock)
|
||||
|| !(level.getBlockState(other.getCurrentBlockPosOrRailBelow()).getBlock()
|
||||
instanceof BaseRailBlock)) continue;
|
||||
var hit =
|
||||
level.clip(
|
||||
new ClipContext(
|
||||
CouplingGeometry.anchor(cart, end),
|
||||
CouplingGeometry.anchor(other, otherEnd),
|
||||
ClipContext.Block.COLLIDER,
|
||||
ClipContext.Fluid.NONE,
|
||||
cart));
|
||||
if (hit.getType() != HitResult.Type.MISS) continue;
|
||||
data.add(
|
||||
new TrainData.Link(
|
||||
cart.getUUID(),
|
||||
end,
|
||||
other.getUUID(),
|
||||
otherEnd,
|
||||
BuiltInRegistries.ITEM.getKey(item.getItem()).toString(),
|
||||
!player.hasInfiniteMaterials(),
|
||||
distance));
|
||||
item.consume(1, player);
|
||||
message(player, "Вагонетки сцеплены.");
|
||||
return;
|
||||
}
|
||||
message(player,"У этого торца нет подходящей свободной вагонетки в пределах 3,5 блока.");
|
||||
message(player, "У этого торца нет подходящей свободной вагонетки в пределах 3,5 блока.");
|
||||
}
|
||||
private static void message(net.minecraft.world.entity.player.Player player,String text){if(player instanceof net.minecraft.server.level.ServerPlayer serverPlayer)serverPlayer.sendSystemMessage(Component.literal(text),true);}
|
||||
public static void unlink(ServerLevel level,TrainData.Link link,Entity at,boolean refund){
|
||||
if(!TrainData.get(level).remove(link))return;
|
||||
discard(new DisplayKey(level,link));
|
||||
if(refund && link.paid())at.spawnAtLocation(level,new ItemStack(chainItem(link)));
|
||||
|
||||
private static void message(net.minecraft.world.entity.player.Player player, String text) {
|
||||
if (player instanceof net.minecraft.server.level.ServerPlayer serverPlayer)
|
||||
serverPlayer.sendSystemMessage(Component.literal(text), true);
|
||||
}
|
||||
private static Item chainItem(TrainData.Link link){
|
||||
var id=Identifier.tryParse(link.item());var item=id==null?Items.IRON_CHAIN:BuiltInRegistries.ITEM.getValue(id);
|
||||
return item!=null && isChain(new ItemStack(item))?item:Items.IRON_CHAIN;
|
||||
|
||||
public static void unlink(ServerLevel level, TrainData.Link link, Entity at, boolean refund) {
|
||||
if (!TrainData.get(level).remove(link)) return;
|
||||
discard(new DisplayKey(level, link));
|
||||
if (refund && link.paid()) at.spawnAtLocation(level, new ItemStack(chainItem(link)));
|
||||
}
|
||||
private static AbstractMinecart cart(ServerLevel level,UUID id){return level.getEntity(id) instanceof AbstractMinecart cart && cart.isAlive()?cart:null;}
|
||||
@SubscribeEvent public static void leave(EntityLeaveLevelEvent event){
|
||||
if(!(event.getEntity() instanceof AbstractMinecart cart) || !(event.getLevel() instanceof ServerLevel level))return;
|
||||
var reason=cart.getRemovalReason();
|
||||
for(var link:TrainData.get(level).links())if(link.touches(cart.getUUID())){
|
||||
// Visibility/unload callbacks can run while vanilla iterates an entity section.
|
||||
// Let the post-tick display pass remove those visuals outside that iteration.
|
||||
if(reason!=null && (reason.shouldDestroy() || reason==Entity.RemovalReason.CHANGED_DIMENSION))unlink(level,link,cart,true);
|
||||
|
||||
private static Item chainItem(TrainData.Link link) {
|
||||
var id = Identifier.tryParse(link.item());
|
||||
var item = id == null ? Items.IRON_CHAIN : BuiltInRegistries.ITEM.getValue(id);
|
||||
return item != null && isChain(new ItemStack(item)) ? item : Items.IRON_CHAIN;
|
||||
}
|
||||
|
||||
private static AbstractMinecart cart(ServerLevel level, UUID id) {
|
||||
return level.getEntity(id) instanceof AbstractMinecart cart && cart.isAlive() ? cart : null;
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void leave(EntityLeaveLevelEvent event) {
|
||||
if (!(event.getEntity() instanceof AbstractMinecart cart)
|
||||
|| !(event.getLevel() instanceof ServerLevel level)) return;
|
||||
var reason = cart.getRemovalReason();
|
||||
for (var link : TrainData.get(level).links())
|
||||
if (link.touches(cart.getUUID())) {
|
||||
// Visibility/unload callbacks can run while vanilla iterates an entity section.
|
||||
// Let the post-tick display pass remove those visuals outside that iteration.
|
||||
if (reason != null
|
||||
&& (reason.shouldDestroy()
|
||||
|| reason == Entity.RemovalReason.CHANGED_DIMENSION))
|
||||
unlink(level, link, cart, true);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void pre(ServerTickEvent.Pre event) {
|
||||
for (var level : event.getServer().getAllLevels()) step(level);
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronize momentum along each cart's rail tangent; springs correct chain slack, never
|
||||
* teleport carts.
|
||||
*/
|
||||
public static void step(ServerLevel level) {
|
||||
var pausedCarts = new HashSet<UUID>();
|
||||
PAUSED.put(level, pausedCarts);
|
||||
var playerPushes = PLAYER_PUSHES.remove(level);
|
||||
if (playerPushes == null) playerPushes = Set.of();
|
||||
var data = TrainData.get(level);
|
||||
var links = data.links();
|
||||
var visited = new HashSet<UUID>();
|
||||
for (var seed : links) {
|
||||
if (visited.contains(seed.a())) continue;
|
||||
var signs = directions(seed.a(), links);
|
||||
visited.addAll(signs.keySet());
|
||||
moveTrain(level, links, signs, pausedCarts, playerPushes);
|
||||
}
|
||||
}
|
||||
@SubscribeEvent public static void pre(ServerTickEvent.Pre event){for(var level:event.getServer().getAllLevels())step(level);}
|
||||
/** Synchronize momentum along each cart's rail tangent; springs correct chain slack, never teleport carts. */
|
||||
public static void step(ServerLevel level){
|
||||
var pausedCarts=new HashSet<UUID>();PAUSED.put(level,pausedCarts);
|
||||
var playerPushes=PLAYER_PUSHES.remove(level);if(playerPushes==null)playerPushes=Set.of();
|
||||
var data=TrainData.get(level);var links=data.links();var visited=new HashSet<UUID>();
|
||||
for(var seed:links){
|
||||
if(visited.contains(seed.a()))continue;
|
||||
var signs=new LinkedHashMap<UUID,Integer>();var pending=new ArrayDeque<UUID>();signs.put(seed.a(),1);pending.add(seed.a());
|
||||
while(!pending.isEmpty()){
|
||||
var id=pending.removeFirst();
|
||||
for(var link:links)if(link.touches(id)){
|
||||
var other=link.other(id);int sign=-signs.get(id)*(link.end(id)==0?1:-1)*(link.end(other)==0?1:-1);
|
||||
if(!signs.containsKey(other)){signs.put(other,sign);pending.add(other);}
|
||||
|
||||
private static void moveTrain(
|
||||
ServerLevel level,
|
||||
List<TrainData.Link> links,
|
||||
Map<UUID, Integer> signs,
|
||||
Set<UUID> pausedCarts,
|
||||
Set<UUID> playerPushes) {
|
||||
var carts = new LinkedHashMap<UUID, AbstractMinecart>();
|
||||
var axes = new HashMap<UUID, Vec3>();
|
||||
boolean paused = false;
|
||||
double momentum = 0, limit = Double.MAX_VALUE;
|
||||
double controlledMomentum = 0;
|
||||
var controls = new HashSet<UUID>();
|
||||
for (var pair : signs.entrySet()) {
|
||||
var cart = cart(level, pair.getKey());
|
||||
if (cart == null) {
|
||||
paused = true;
|
||||
continue;
|
||||
}
|
||||
carts.put(pair.getKey(), cart);
|
||||
Vec3 tangent = CouplingGeometry.axis(cart).scale(pair.getValue());
|
||||
axes.put(pair.getKey(), tangent);
|
||||
if (!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock()
|
||||
instanceof BaseRailBlock)) paused = true;
|
||||
double scale = travelScale(cart);
|
||||
momentum += cart.getDeltaMovement().dot(tangent) * scale;
|
||||
if (playerControls(cart, playerPushes)) {
|
||||
controlledMomentum += alignedSpeed(cart, tangent) * scale;
|
||||
controls.add(cart.getUUID());
|
||||
}
|
||||
limit = Math.min(limit, cart.getMaxSpeed(level));
|
||||
}
|
||||
if (carts.isEmpty()) return;
|
||||
if (paused) {
|
||||
pausedCarts.addAll(carts.keySet());
|
||||
carts.values().forEach(c -> c.setDeltaMovement(Vec3.ZERO));
|
||||
return;
|
||||
}
|
||||
// Player input drives the train as a unit. Averaging it with idle carts diluted
|
||||
// the tiny vanilla rider impulse; a dot product also erased side-on walking pushes.
|
||||
double speed =
|
||||
Math.clamp(
|
||||
!controls.isEmpty()
|
||||
? controlledMomentum / controls.size()
|
||||
: momentum / carts.size(),
|
||||
-limit,
|
||||
limit);
|
||||
var corrections = new HashMap<UUID, Double>();
|
||||
for (var link : links)
|
||||
if (carts.containsKey(link.a()) && carts.containsKey(link.b())) {
|
||||
var a = carts.get(link.a());
|
||||
var b = carts.get(link.b());
|
||||
double distance = a.position().distanceTo(b.position());
|
||||
if (distance > 6) {
|
||||
unlink(level, link, a, true);
|
||||
continue;
|
||||
}
|
||||
double pull = Math.clamp((distance - link.length()) * .22, -.18, .18);
|
||||
double direction = signs.get(link.a()) * (link.endA() == 0 ? 1 : -1);
|
||||
corrections.merge(link.a(), pull * direction, Double::sum);
|
||||
corrections.merge(link.b(), -pull * direction, Double::sum);
|
||||
}
|
||||
visited.addAll(signs.keySet());var carts=new LinkedHashMap<UUID,AbstractMinecart>();
|
||||
var axes=new HashMap<UUID,Vec3>();boolean paused=false;double momentum=0,limit=Double.MAX_VALUE;
|
||||
double controlledMomentum=0;var controls=new HashSet<UUID>();
|
||||
for(var pair:signs.entrySet()){
|
||||
var cart=cart(level,pair.getKey());if(cart==null){paused=true;continue;}carts.put(pair.getKey(),cart);
|
||||
Vec3 tangent=CouplingGeometry.axis(cart).scale(pair.getValue());axes.put(pair.getKey(),tangent);
|
||||
if(!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock))paused=true;
|
||||
double scale=travelScale(cart);momentum+=cart.getDeltaMovement().dot(tangent)*scale;
|
||||
if(playerPushes.contains(cart.getUUID()) || cart.getFirstPassenger() instanceof net.minecraft.server.level.ServerPlayer player
|
||||
&& player.getLastClientMoveIntent().horizontalDistanceSqr()>0){
|
||||
controlledMomentum+=alignedSpeed(cart,tangent)*scale;controls.add(cart.getUUID());
|
||||
}
|
||||
limit=Math.min(limit,cart.getMaxSpeed(level));
|
||||
for (var pair : carts.entrySet()) {
|
||||
// Followers take up slack; pulling back the driven cart would cancel its 0.001
|
||||
// rider impulse.
|
||||
var cart = pair.getValue();
|
||||
double value =
|
||||
Math.clamp(
|
||||
speed
|
||||
+ (controls.contains(pair.getKey())
|
||||
? 0
|
||||
: corrections.getOrDefault(pair.getKey(), 0.0)),
|
||||
-limit,
|
||||
limit);
|
||||
var velocity = axes.get(pair.getKey()).scale(value / travelScale(cart));
|
||||
cart.setDeltaMovement(velocity.x, cart.getDeltaMovement().y, velocity.z);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<UUID, Integer> directions(UUID start, List<TrainData.Link> links) {
|
||||
var signs = new LinkedHashMap<UUID, Integer>();
|
||||
var pending = new ArrayDeque<UUID>();
|
||||
signs.put(start, 1);
|
||||
pending.add(start);
|
||||
while (!pending.isEmpty()) {
|
||||
var id = pending.removeFirst();
|
||||
for (var link : links) {
|
||||
if (!link.touches(id)) continue;
|
||||
var other = link.other(id);
|
||||
if (signs.containsKey(other)) continue;
|
||||
int sign = signs.get(id);
|
||||
if (link.end(id) == link.end(other)) sign = -sign;
|
||||
signs.put(other, sign);
|
||||
pending.add(other);
|
||||
}
|
||||
if(carts.isEmpty())continue;
|
||||
if(paused){pausedCarts.addAll(carts.keySet());carts.values().forEach(c->c.setDeltaMovement(Vec3.ZERO));continue;}
|
||||
// Player input drives the train as a unit. Averaging it with idle carts diluted
|
||||
// the tiny vanilla rider impulse; a dot product also erased side-on walking pushes.
|
||||
double speed=Math.clamp(!controls.isEmpty()?controlledMomentum/controls.size():momentum/carts.size(),-limit,limit);
|
||||
var corrections=new HashMap<UUID,Double>();
|
||||
for(var link:links)if(carts.containsKey(link.a()) && carts.containsKey(link.b())){
|
||||
var a=carts.get(link.a());var b=carts.get(link.b());double distance=a.position().distanceTo(b.position());
|
||||
if(distance>6){unlink(level,link,a,true);continue;}
|
||||
double pull=Math.clamp((distance-link.length())*.22,-.18,.18);
|
||||
double direction=signs.get(link.a())*(link.endA()==0?1:-1);
|
||||
corrections.merge(link.a(),pull*direction,Double::sum);corrections.merge(link.b(),-pull*direction,Double::sum);
|
||||
}
|
||||
return signs;
|
||||
}
|
||||
|
||||
private static boolean playerControls(AbstractMinecart cart, Set<UUID> pushes) {
|
||||
if (pushes.contains(cart.getUUID())) return true;
|
||||
if (!(cart.getFirstPassenger() instanceof net.minecraft.server.level.ServerPlayer player))
|
||||
return false;
|
||||
return player.getLastClientMoveIntent().horizontalDistanceSqr() > 0;
|
||||
}
|
||||
|
||||
private static double travelScale(AbstractMinecart cart) {
|
||||
return !AbstractMinecart.useExperimentalMovement(cart.level()) && cart.isVehicle()
|
||||
? .75
|
||||
: 1;
|
||||
}
|
||||
|
||||
private static double alignedSpeed(AbstractMinecart cart, Vec3 tangent) {
|
||||
var movement = cart.getDeltaMovement();
|
||||
double along = movement.dot(tangent);
|
||||
if (Math.abs(along) < 1e-9) {
|
||||
var pos = cart.getCurrentBlockPosOrRailBelow();
|
||||
var state = cart.level().getBlockState(pos);
|
||||
if (state.getBlock() instanceof BaseRailBlock rail) {
|
||||
var exits =
|
||||
AbstractMinecart.exits(
|
||||
rail.getRailDirection(state, cart.level(), pos, cart));
|
||||
var nativeAxis =
|
||||
new Vec3(exits.getSecond())
|
||||
.subtract(new Vec3(exits.getFirst()))
|
||||
.horizontal();
|
||||
// Vanilla chooses the opposite default exit for a perpendicular input in the new
|
||||
// engine.
|
||||
along =
|
||||
nativeAxis.dot(tangent)
|
||||
* (AbstractMinecart.useExperimentalMovement(cart.level()) ? -1 : 1);
|
||||
}
|
||||
for(var pair:carts.entrySet()){
|
||||
// Followers take up slack; pulling back the driven cart would cancel its 0.001 rider impulse.
|
||||
var cart=pair.getValue();double value=Math.clamp(speed+(controls.contains(pair.getKey())?0:corrections.getOrDefault(pair.getKey(),0.0)),-limit,limit);
|
||||
var velocity=axes.get(pair.getKey()).scale(value/travelScale(cart));
|
||||
cart.setDeltaMovement(velocity.x,cart.getDeltaMovement().y,velocity.z);
|
||||
}
|
||||
return Math.copySign(movement.horizontalDistance(), along);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void post(ServerTickEvent.Post event) {
|
||||
for (var level : event.getServer().getAllLevels()) show(level);
|
||||
}
|
||||
|
||||
public static void show(ServerLevel level) {
|
||||
var keys = new HashSet<DisplayKey>();
|
||||
for (var link : TrainData.get(level).links()) {
|
||||
var a = cart(level, link.a());
|
||||
var b = cart(level, link.b());
|
||||
if (a == null || b == null) continue;
|
||||
var key = new DisplayKey(level, link);
|
||||
keys.add(key);
|
||||
var display = DISPLAYS.get(key);
|
||||
if (display == null || display.isRemoved()) {
|
||||
display =
|
||||
new ChainDisplay(
|
||||
level,
|
||||
((BlockItem) chainItem(link)).getBlock().defaultBlockState());
|
||||
display.update(
|
||||
CouplingGeometry.anchor(a, link.endA()),
|
||||
CouplingGeometry.anchor(b, link.endB()));
|
||||
if (level.addFreshEntity(display)) DISPLAYS.put(key, display);
|
||||
} else
|
||||
display.update(
|
||||
CouplingGeometry.anchor(a, link.endA()),
|
||||
CouplingGeometry.anchor(b, link.endB()));
|
||||
}
|
||||
for (var key : new ArrayList<>(DISPLAYS.keySet()))
|
||||
if (key.level == level && !keys.contains(key)) discard(key);
|
||||
}
|
||||
|
||||
public static void reverse(AbstractMinecart hit, Vec3 reflected) {
|
||||
if (!(hit.level() instanceof ServerLevel level)) return;
|
||||
var data = TrainData.get(level);
|
||||
var ids = data.component(hit.getUUID());
|
||||
if (ids.size() == 1) {
|
||||
hit.setDeltaMovement(reflected.scale(1 / travelScale(hit)));
|
||||
return;
|
||||
}
|
||||
// Propagate reversal through the closed or open graph, preserving each cart's local travel
|
||||
// direction.
|
||||
var signs = directions(hit.getUUID(), data.links());
|
||||
double speed = reflected.dot(CouplingGeometry.axis(hit));
|
||||
for (var id : ids) {
|
||||
var cart = cart(level, id);
|
||||
if (cart != null) {
|
||||
var v =
|
||||
CouplingGeometry.axis(cart)
|
||||
.scale(speed * signs.getOrDefault(id, 1) / travelScale(cart));
|
||||
cart.setDeltaMovement(v.x, cart.getDeltaMovement().y, v.z);
|
||||
}
|
||||
}
|
||||
}
|
||||
private static double travelScale(AbstractMinecart cart){return !AbstractMinecart.useExperimentalMovement(cart.level())&&cart.isVehicle()?.75:1;}
|
||||
private static double alignedSpeed(AbstractMinecart cart,Vec3 tangent){
|
||||
var movement=cart.getDeltaMovement();double along=movement.dot(tangent);
|
||||
if(Math.abs(along)<1e-9){
|
||||
var pos=cart.getCurrentBlockPosOrRailBelow();var state=cart.level().getBlockState(pos);
|
||||
if(state.getBlock() instanceof BaseRailBlock rail){
|
||||
var exits=AbstractMinecart.exits(rail.getRailDirection(state,cart.level(),pos,cart));
|
||||
var nativeAxis=new Vec3(exits.getSecond()).subtract(new Vec3(exits.getFirst())).horizontal();
|
||||
// Vanilla chooses the opposite default exit for a perpendicular input in the new engine.
|
||||
along=nativeAxis.dot(tangent)*(AbstractMinecart.useExperimentalMovement(cart.level())?-1:1);
|
||||
}
|
||||
}
|
||||
return Math.copySign(movement.horizontalDistance(),along);
|
||||
|
||||
private static void discard(DisplayKey key) {
|
||||
var display = DISPLAYS.remove(key);
|
||||
if (display != null) display.discard();
|
||||
}
|
||||
@SubscribeEvent public static void post(ServerTickEvent.Post event){for(var level:event.getServer().getAllLevels())show(level);}
|
||||
public static void show(ServerLevel level){
|
||||
var keys=new HashSet<DisplayKey>();
|
||||
for(var link:TrainData.get(level).links()){
|
||||
var a=cart(level,link.a());var b=cart(level,link.b());if(a==null||b==null)continue;
|
||||
var key=new DisplayKey(level,link);keys.add(key);var display=DISPLAYS.get(key);
|
||||
if(display==null||display.isRemoved()){
|
||||
display=new ChainDisplay(level,((BlockItem)chainItem(link)).getBlock().defaultBlockState());
|
||||
display.update(CouplingGeometry.anchor(a,link.endA()),CouplingGeometry.anchor(b,link.endB()));
|
||||
if(level.addFreshEntity(display))DISPLAYS.put(key,display);
|
||||
}else display.update(CouplingGeometry.anchor(a,link.endA()),CouplingGeometry.anchor(b,link.endB()));
|
||||
}
|
||||
for(var key:new ArrayList<>(DISPLAYS.keySet()))if(key.level==level&&!keys.contains(key))discard(key);
|
||||
|
||||
@SubscribeEvent
|
||||
public static void stop(ServerStoppedEvent event) {
|
||||
for (var key : new ArrayList<>(DISPLAYS.keySet())) discard(key);
|
||||
PAUSED.clear();
|
||||
PLAYER_PUSHES.clear();
|
||||
}
|
||||
public static void reverse(AbstractMinecart hit,Vec3 reflected){
|
||||
if(!(hit.level() instanceof ServerLevel level))return;
|
||||
var data=TrainData.get(level);var ids=data.component(hit.getUUID());
|
||||
if(ids.size()==1){hit.setDeltaMovement(reflected.scale(1/travelScale(hit)));return;}
|
||||
// Propagate reversal through the closed or open graph, preserving each cart's local travel direction.
|
||||
var signs=new HashMap<UUID,Integer>();var pending=new ArrayDeque<UUID>();signs.put(hit.getUUID(),1);pending.add(hit.getUUID());
|
||||
while(!pending.isEmpty()){var id=pending.removeFirst();for(var link:data.links())if(link.touches(id)&&!signs.containsKey(link.other(id))){
|
||||
signs.put(link.other(id),-signs.get(id)*(link.end(id)==0?1:-1)*(link.end(link.other(id))==0?1:-1));pending.add(link.other(id));}}
|
||||
double speed=reflected.dot(CouplingGeometry.axis(hit));
|
||||
for(var id:ids){var cart=cart(level,id);if(cart!=null){var v=CouplingGeometry.axis(cart).scale(speed*signs.getOrDefault(id,1)/travelScale(cart));cart.setDeltaMovement(v.x,cart.getDeltaMovement().y,v.z);}}
|
||||
}
|
||||
private static void discard(DisplayKey key){var display=DISPLAYS.remove(key);if(display!=null)display.discard();}
|
||||
@SubscribeEvent public static void stop(ServerStoppedEvent event){for(var key:new ArrayList<>(DISPLAYS.keySet()))discard(key);PAUSED.clear();PLAYER_PUSHES.clear();}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package online.astradev.content.transport;
|
||||
|
||||
import java.util.*;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
@@ -12,56 +11,105 @@ import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.phys.*;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.neoforge.event.tick.EntityTickEvent;
|
||||
|
||||
import online.astradev.content.train.Trains;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class SlimeBounce {
|
||||
private static final Map<Entity,Vec3> PENDING=new WeakHashMap<>();
|
||||
private static final Map<Entity,Vec3> BOAT_MOTION=new WeakHashMap<>();
|
||||
private SlimeBounce(){}
|
||||
public static boolean supports(Entity entity){return entity.level() instanceof ServerLevel && (entity instanceof AbstractMinecart || entity instanceof AbstractBoat);}
|
||||
public static void afterMove(Entity entity,Vec3 before,Vec3 requested,Vec3 incoming){
|
||||
if(!supports(entity)||entity.noPhysics)return;
|
||||
Vec3 actual=entity.position().subtract(before);
|
||||
boolean x=Math.abs(requested.x-actual.x)>.00001 && touchesSlime(entity,requested.x,0);
|
||||
boolean z=Math.abs(requested.z-actual.z)>.00001 && touchesSlime(entity,0,requested.z);
|
||||
if((x||z)&&requested.horizontalDistance()>.01){
|
||||
private static final Map<Entity, Vec3> PENDING = new WeakHashMap<>();
|
||||
private static final Map<Entity, Vec3> BOAT_MOTION = new WeakHashMap<>();
|
||||
|
||||
private SlimeBounce() {}
|
||||
|
||||
public static boolean supports(Entity entity) {
|
||||
return entity.level() instanceof ServerLevel
|
||||
&& (entity instanceof AbstractMinecart || entity instanceof AbstractBoat);
|
||||
}
|
||||
|
||||
public static void afterMove(Entity entity, Vec3 before, Vec3 requested, Vec3 incoming) {
|
||||
if (!supports(entity) || entity.noPhysics) return;
|
||||
Vec3 actual = entity.position().subtract(before);
|
||||
boolean x =
|
||||
Math.abs(requested.x - actual.x) > .00001 && touchesSlime(entity, requested.x, 0);
|
||||
boolean z =
|
||||
Math.abs(requested.z - actual.z) > .00001 && touchesSlime(entity, 0, requested.z);
|
||||
if ((x || z) && requested.horizontalDistance() > .01) {
|
||||
// Experimental rail movement splits one tick into smaller moves at rail boundaries.
|
||||
if(entity instanceof AbstractMinecart cart && AbstractMinecart.useExperimentalMovement(cart.level()))
|
||||
requested=requested.horizontal().normalize().scale(incoming.horizontalDistance());
|
||||
Vec3 reflected=new Vec3(x?-requested.x:requested.x,entity.getDeltaMovement().y,z?-requested.z:requested.z);
|
||||
PENDING.put(entity,reflected);entity.setDeltaMovement(reflected);
|
||||
if (entity instanceof AbstractMinecart cart
|
||||
&& AbstractMinecart.useExperimentalMovement(cart.level()))
|
||||
requested = requested.horizontal().normalize().scale(incoming.horizontalDistance());
|
||||
Vec3 reflected =
|
||||
new Vec3(
|
||||
x ? -requested.x : requested.x,
|
||||
entity.getDeltaMovement().y,
|
||||
z ? -requested.z : requested.z);
|
||||
PENDING.put(entity, reflected);
|
||||
entity.setDeltaMovement(reflected);
|
||||
}
|
||||
}
|
||||
|
||||
/** Check the actual contacted face, not nearby slime or the block beneath the vehicle. */
|
||||
private static boolean touchesSlime(Entity entity,double dx,double dz){
|
||||
if(dx==0&&dz==0)return false;
|
||||
var box=entity.getBoundingBox();double eps=.015;
|
||||
double x0=dx>0?box.maxX+eps:dx<0?box.minX-eps:box.minX+eps;
|
||||
double x1=dx!=0?x0:box.maxX-eps;
|
||||
double z0=dz>0?box.maxZ+eps:dz<0?box.minZ-eps:box.minZ+eps;
|
||||
double z1=dz!=0?z0:box.maxZ-eps;
|
||||
for(var pos:BlockPos.betweenClosed(BlockPos.containing(x0,box.minY+.05,z0),BlockPos.containing(x1,box.maxY-.05,z1)))
|
||||
if(entity.level().hasChunkAt(pos)&&entity.level().getBlockState(pos).is(Blocks.SLIME_BLOCK))return true;
|
||||
private static boolean touchesSlime(Entity entity, double dx, double dz) {
|
||||
if (dx == 0 && dz == 0) return false;
|
||||
var box = entity.getBoundingBox();
|
||||
double eps = .015;
|
||||
double x0 = contactEdge(dx, box.minX, box.maxX, eps);
|
||||
double x1 = dx != 0 ? x0 : box.maxX - eps;
|
||||
double z0 = contactEdge(dz, box.minZ, box.maxZ, eps);
|
||||
double z1 = dz != 0 ? z0 : box.maxZ - eps;
|
||||
for (var pos :
|
||||
BlockPos.betweenClosed(
|
||||
BlockPos.containing(x0, box.minY + .05, z0),
|
||||
BlockPos.containing(x1, box.maxY - .05, z1)))
|
||||
if (entity.level().hasChunkAt(pos)
|
||||
&& entity.level().getBlockState(pos).is(Blocks.SLIME_BLOCK)) return true;
|
||||
return false;
|
||||
}
|
||||
@SubscribeEvent public static void afterTick(EntityTickEvent.Post event){flush(event.getEntity());}
|
||||
public static void flush(Entity entity){
|
||||
var reflected=PENDING.remove(entity);if(reflected==null||entity.isRemoved())return;
|
||||
if(entity instanceof AbstractMinecart cart)Trains.reverse(cart,reflected);else entity.setDeltaMovement(reflected);
|
||||
entity.hurtMarked=true;
|
||||
if(entity instanceof AbstractBoat)for(var passenger:entity.getPassengers())if(passenger instanceof ServerPlayer player)
|
||||
player.connection.send(new ClientboundSetEntityMotionPacket(entity));
|
||||
|
||||
private static double contactEdge(double movement, double min, double max, double margin) {
|
||||
if (movement > 0) return max + margin;
|
||||
if (movement < 0) return min - margin;
|
||||
return min + margin;
|
||||
}
|
||||
/** A vanilla player steers boats on the client. Detect its reported contact and return a vanilla impulse packet. */
|
||||
public static void boatPacket(Entity entity,Vec3 before){
|
||||
if(!(entity instanceof AbstractBoat)||!(entity.level() instanceof ServerLevel))return;
|
||||
Vec3 motion=entity.position().subtract(before);Vec3 prior=BOAT_MOTION.getOrDefault(entity,motion);
|
||||
Vec3 incoming=prior.horizontalDistance()>motion.horizontalDistance()?prior:motion;
|
||||
boolean x=Math.abs(incoming.x)>.01&&touchesSlime(entity,incoming.x,0);
|
||||
boolean z=Math.abs(incoming.z)>.01&&touchesSlime(entity,0,incoming.z);
|
||||
if(x||z){
|
||||
var reflected=new Vec3(x?-incoming.x:incoming.x,entity.getDeltaMovement().y,z?-incoming.z:incoming.z);
|
||||
PENDING.put(entity,reflected);BOAT_MOTION.put(entity,reflected);flush(entity);
|
||||
}else BOAT_MOTION.put(entity,motion);
|
||||
|
||||
@SubscribeEvent
|
||||
public static void afterTick(EntityTickEvent.Post event) {
|
||||
flush(event.getEntity());
|
||||
}
|
||||
|
||||
public static void flush(Entity entity) {
|
||||
var reflected = PENDING.remove(entity);
|
||||
if (reflected == null || entity.isRemoved()) return;
|
||||
if (entity instanceof AbstractMinecart cart) Trains.reverse(cart, reflected);
|
||||
else entity.setDeltaMovement(reflected);
|
||||
entity.hurtMarked = true;
|
||||
if (entity instanceof AbstractBoat)
|
||||
for (var passenger : entity.getPassengers())
|
||||
if (passenger instanceof ServerPlayer player)
|
||||
player.connection.send(new ClientboundSetEntityMotionPacket(entity));
|
||||
}
|
||||
|
||||
/**
|
||||
* A vanilla player steers boats on the client. Detect its reported contact and return a vanilla
|
||||
* impulse packet.
|
||||
*/
|
||||
public static void boatPacket(Entity entity, Vec3 before) {
|
||||
if (!(entity instanceof AbstractBoat) || !(entity.level() instanceof ServerLevel)) return;
|
||||
Vec3 motion = entity.position().subtract(before);
|
||||
Vec3 prior = BOAT_MOTION.getOrDefault(entity, motion);
|
||||
Vec3 incoming = prior.horizontalDistance() > motion.horizontalDistance() ? prior : motion;
|
||||
boolean x = Math.abs(incoming.x) > .01 && touchesSlime(entity, incoming.x, 0);
|
||||
boolean z = Math.abs(incoming.z) > .01 && touchesSlime(entity, 0, incoming.z);
|
||||
if (x || z) {
|
||||
var reflected =
|
||||
new Vec3(
|
||||
x ? -incoming.x : incoming.x,
|
||||
entity.getDeltaMovement().y,
|
||||
z ? -incoming.z : incoming.z);
|
||||
PENDING.put(entity, reflected);
|
||||
BOAT_MOTION.put(entity, reflected);
|
||||
flush(entity);
|
||||
} else BOAT_MOTION.put(entity, motion);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package online.astradev.content.weapon;
|
||||
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.sounds.*;
|
||||
import net.minecraft.stats.Stats;
|
||||
@@ -8,8 +7,8 @@ import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.projectile.Projectile;
|
||||
import net.minecraft.world.entity.projectile.hurtingprojectile.SmallFireball;
|
||||
import net.minecraft.world.entity.projectile.throwableitemprojectile.*;
|
||||
import net.minecraft.world.entity.projectile.hurtingprojectile.windcharge.WindCharge;
|
||||
import net.minecraft.world.entity.projectile.throwableitemprojectile.*;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
@@ -17,11 +16,18 @@ import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
|
||||
public final class Ammunition {
|
||||
private Ammunition() {}
|
||||
|
||||
public static boolean accepts(ItemStack stack) {
|
||||
return stack.is(Items.ENDER_PEARL) || stack.is(Items.FIRE_CHARGE) || stack.is(Items.ENDER_EYE)
|
||||
|| stack.getItem() instanceof EggItem || stack.is(Items.SNOWBALL) || stack.is(Items.WIND_CHARGE)
|
||||
|| stack.is(Items.EXPERIENCE_BOTTLE) || stack.is(Items.TNT);
|
||||
return stack.is(Items.ENDER_PEARL)
|
||||
|| stack.is(Items.FIRE_CHARGE)
|
||||
|| stack.is(Items.ENDER_EYE)
|
||||
|| stack.getItem() instanceof EggItem
|
||||
|| stack.is(Items.SNOWBALL)
|
||||
|| stack.is(Items.WIND_CHARGE)
|
||||
|| stack.is(Items.EXPERIENCE_BOTTLE)
|
||||
|| stack.is(Items.TNT);
|
||||
}
|
||||
|
||||
public static Projectile create(Level level, LivingEntity owner, ItemStack ammo) {
|
||||
if (ammo.is(Items.ENDER_PEARL)) return new ThrownEnderpearl(level, owner, ammo);
|
||||
if (ammo.getItem() instanceof EggItem) return new ThrownEgg(level, owner, ammo);
|
||||
@@ -29,25 +35,52 @@ public final class Ammunition {
|
||||
if (ammo.is(Items.EXPERIENCE_BOTTLE)) return new ThrownExperienceBottle(level, owner, ammo);
|
||||
if (ammo.is(Items.FIRE_CHARGE)) {
|
||||
var fire = new SmallFireball(level, owner, owner.getLookAngle());
|
||||
fire.setPos(owner.getX(), owner.getEyeY() - .15, owner.getZ()); fire.setItem(ammo); return fire;
|
||||
fire.setPos(owner.getX(), owner.getEyeY() - .15, owner.getZ());
|
||||
fire.setItem(ammo);
|
||||
return fire;
|
||||
}
|
||||
if (ammo.is(Items.WIND_CHARGE)) {
|
||||
var wind = new WindCharge(level, owner.getX(), owner.getEyeY() - .15, owner.getZ(), owner.getLookAngle());
|
||||
wind.setOwner(owner); return wind;
|
||||
var wind =
|
||||
new WindCharge(
|
||||
level,
|
||||
owner.getX(),
|
||||
owner.getEyeY() - .15,
|
||||
owner.getZ(),
|
||||
owner.getLookAngle());
|
||||
wind.setOwner(owner);
|
||||
return wind;
|
||||
}
|
||||
if (ammo.is(Items.TNT) || ammo.is(Items.ENDER_EYE)) return new PayloadProjectile(level, owner, ammo);
|
||||
if (ammo.is(Items.TNT) || ammo.is(Items.ENDER_EYE))
|
||||
return new PayloadProjectile(level, owner, ammo);
|
||||
return null;
|
||||
}
|
||||
@SubscribeEvent public static void fireCharge(PlayerInteractEvent.RightClickItem event) {
|
||||
if (!(event.getLevel() instanceof ServerLevel level) || !event.getItemStack().is(Items.FIRE_CHARGE)) return;
|
||||
var player = event.getEntity(); var stack = event.getItemStack();
|
||||
|
||||
@SubscribeEvent
|
||||
public static void fireCharge(PlayerInteractEvent.RightClickItem event) {
|
||||
if (!(event.getLevel() instanceof ServerLevel level)
|
||||
|| !event.getItemStack().is(Items.FIRE_CHARGE)) return;
|
||||
var player = event.getEntity();
|
||||
var stack = event.getItemStack();
|
||||
if (player.getCooldowns().isOnCooldown(stack)) return;
|
||||
var fire = create(level, player, stack);
|
||||
Projectile.spawnProjectile(fire, level, stack, shot -> shot.shootFromRotation(player, player.getXRot(), player.getYRot(), 0, 1.5f, 1));
|
||||
level.playSound(null, player.blockPosition(), SoundEvents.FIRECHARGE_USE, SoundSource.PLAYERS, 1, 1);
|
||||
Projectile.spawnProjectile(
|
||||
fire,
|
||||
level,
|
||||
stack,
|
||||
shot ->
|
||||
shot.shootFromRotation(
|
||||
player, player.getXRot(), player.getYRot(), 0, 1.5f, 1));
|
||||
level.playSound(
|
||||
null,
|
||||
player.blockPosition(),
|
||||
SoundEvents.FIRECHARGE_USE,
|
||||
SoundSource.PLAYERS,
|
||||
1,
|
||||
1);
|
||||
player.getCooldowns().addCooldown(stack, 10);
|
||||
player.awardStat(Stats.ITEM_USED.get(stack.getItem()));
|
||||
stack.consume(1, player);
|
||||
event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
event.setCanceled(true);
|
||||
event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,20 +14,37 @@ import net.minecraft.world.phys.Vec3;
|
||||
/** One-tick shooting adapter; the payload itself is a vanilla entity understood by every client. */
|
||||
public final class PayloadProjectile extends Snowball {
|
||||
public static final String NO_EYE_DROP = "astracontent:no_eye_drop";
|
||||
public PayloadProjectile(Level level, LivingEntity owner, ItemStack stack) { super(level, owner, stack); }
|
||||
@Override public void tick() {
|
||||
|
||||
public PayloadProjectile(Level level, LivingEntity owner, ItemStack stack) {
|
||||
super(level, owner, stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
if (!(level() instanceof ServerLevel level)) return;
|
||||
if (getItem().is(Items.TNT)) {
|
||||
var tnt = new PrimedTnt(level, getX(), getY(), getZ(), getOwner() instanceof LivingEntity living ? living : null);
|
||||
tnt.setDeltaMovement(getDeltaMovement()); level.addFreshEntity(tnt);
|
||||
var tnt =
|
||||
new PrimedTnt(
|
||||
level,
|
||||
getX(),
|
||||
getY(),
|
||||
getZ(),
|
||||
getOwner() instanceof LivingEntity living ? living : null);
|
||||
tnt.setDeltaMovement(getDeltaMovement());
|
||||
level.addFreshEntity(tnt);
|
||||
} else {
|
||||
var target = level.findNearestMapStructure(StructureTags.EYE_OF_ENDER_LOCATED, blockPosition(), 100, false);
|
||||
var target =
|
||||
level.findNearestMapStructure(
|
||||
StructureTags.EYE_OF_ENDER_LOCATED, blockPosition(), 100, false);
|
||||
if (target != null) {
|
||||
var eye = new EyeOfEnder(level, getX(), getY(), getZ());
|
||||
eye.setItem(getItem());
|
||||
if (getItem().has(DataComponents.INTANGIBLE_PROJECTILE)) eye.addTag(NO_EYE_DROP);
|
||||
eye.signalTo(Vec3.atLowerCornerOf(target)); eye.setDeltaMovement(getDeltaMovement()); level.addFreshEntity(eye);
|
||||
} else if (!getItem().has(DataComponents.INTANGIBLE_PROJECTILE)) spawnAtLocation(level, getItem().copyWithCount(1));
|
||||
eye.signalTo(Vec3.atLowerCornerOf(target));
|
||||
eye.setDeltaMovement(getDeltaMovement());
|
||||
level.addFreshEntity(eye);
|
||||
} else if (!getItem().has(DataComponents.INTANGIBLE_PROJECTILE))
|
||||
spawnAtLocation(level, getItem().copyWithCount(1));
|
||||
}
|
||||
discard();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user