Add chain-coupled minecart trains, closed loops and slime buffers

This commit is contained in:
2026-09-13 09:38:31 +03:00
parent c6c222ef36
commit a1802eb02d
19 changed files with 625 additions and 16 deletions
@@ -16,5 +16,7 @@ public final class AstraContent {
NeoForge.EVENT_BUS.register(Rails.class);
NeoForge.EVENT_BUS.register(Ammunition.class);
NeoForge.EVENT_BUS.register(online.astradev.content.rail.RailCommands.class);
NeoForge.EVENT_BUS.register(online.astradev.content.train.Trains.class);
NeoForge.EVENT_BUS.register(online.astradev.content.transport.SlimeBounce.class);
}
}
@@ -0,0 +1,23 @@
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.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;}
}
}
@@ -0,0 +1,29 @@
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 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();
// Native powered rails can accelerate from zero within this same tick.
if(type==MoverType.SELF && entity instanceof AbstractMinecart cart && Trains.paused(cart)
&& cart.level().getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock){
astra$beforeMove=null;cart.setDeltaMovement(Vec3.ZERO);ci.cancel();
}
}
@Inject(method="move",at=@At("RETURN"))
private void astra$after(MoverType type,Vec3 delta,CallbackInfo ci){
if(astra$beforeMove!=null)SlimeBounce.afterMove((Entity)(Object)this,astra$beforeMove,delta,astra$incoming);
}
}
@@ -0,0 +1,28 @@
package online.astradev.content.mixin;
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;
@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;
}
@Inject(method="push",at=@At("HEAD"),cancellable=true)
private void astra$noInternalCollision(Entity other,CallbackInfo ci){
if(other instanceof AbstractMinecart cart && Trains.connected((AbstractMinecart)(Object)this,cart))ci.cancel();
}
}
@@ -59,7 +59,7 @@ public final class RailSpeed {
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 .4;
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)
@@ -0,0 +1,6 @@
package online.astradev.content.train;
import net.minecraft.world.phys.Vec3;
public interface CartFrame {
Vec3 astracontent$front();
void astracontent$front(Vec3 axis);
}
@@ -0,0 +1,27 @@
package online.astradev.content.train;
import com.mojang.math.Transformation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Display;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.ValueOutput;
import net.minecraft.world.phys.Vec3;
import org.joml.*;
public final class ChainDisplay extends Display.BlockDisplay {
public ChainDisplay(ServerLevel level,BlockState chain){
super(EntityTypes.BLOCK_DISPLAY,level);setBlockState(chain);setNoGravity(true);setInvulnerable(true);setSilent(true);
setPosRotInterpolationDuration(1);setTransformationInterpolationDuration(1);
}
public void update(Vec3 a,Vec3 b){
Vec3 delta=b.subtract(a);float length=(float)delta.length();if(length<.02)return;
var rotation=new Quaternionf().rotateTo(new Vector3f(0,1,0),delta.normalize().toVector3f());
var translation=new Vector3f(-.5f,-length/2,-.5f).rotate(rotation);
Vec3 mid=a.add(b).scale(.5);setPos(mid);
setTransformation(new Transformation(translation,rotation,new Vector3f(1,length,1),new Quaternionf()));
setTransformationInterpolationDelay(0);
}
@Override public boolean shouldBeSaved(){return false;}
@Override public boolean saveAsPassenger(ValueOutput output){return false;}
}
@@ -0,0 +1,29 @@
package online.astradev.content.train;
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
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);
}
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 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));}
}
@@ -0,0 +1,38 @@
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.*;
/** 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;}
}
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;
}
}
@@ -0,0 +1,158 @@
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;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.tags.ItemTags;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
import net.minecraft.world.item.*;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.block.*;
import net.minecraft.world.phys.*;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.entity.EntityLeaveLevelEvent;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
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 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());
}
@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;
}
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;
}
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 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 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);}
}
}
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;
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;
limit=Math.min(limit,cart.getMaxSpeed(level));
}
if(carts.isEmpty())continue;
if(paused){pausedCarts.addAll(carts.keySet());carts.values().forEach(c->c.setDeltaMovement(Vec3.ZERO));continue;}
double speed=Math.clamp(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);
}
for(var pair:carts.entrySet()){
var cart=pair.getValue();double value=Math.clamp(speed+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 double travelScale(AbstractMinecart cart){return !AbstractMinecart.useExperimentalMovement(cart.level())&&cart.isVehicle()?.75:1;}
@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=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();}
}
@@ -0,0 +1,67 @@
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;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.vehicle.boat.AbstractBoat;
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.phys.*;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.tick.EntityTickEvent;
import online.astradev.content.train.Trains;
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){
// 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);
}
}
/** 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;
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));
}
/** 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,2 +1,8 @@
public net.minecraft.world.entity.Display setTransformation(Lcom/mojang/math/Transformation;)V
public net.minecraft.world.entity.Display$ItemDisplay setItemTransform(Lnet/minecraft/world/item/ItemDisplayContext;)V
public net.minecraft.world.entity.Display$BlockDisplay setBlockState(Lnet/minecraft/world/level/block/state/BlockState;)V
public net.minecraft.world.entity.Display setPosRotInterpolationDuration(I)V
public net.minecraft.world.entity.Display setTransformationInterpolationDuration(I)V
public net.minecraft.world.entity.Display setTransformationInterpolationDelay(I)V
public net.minecraft.world.entity.vehicle.minecart.AbstractMinecart getMaxSpeed(Lnet/minecraft/server/level/ServerLevel;)D
public net.minecraft.world.entity.vehicle.minecart.MinecartFurnace getMaxSpeed(Lnet/minecraft/server/level/ServerLevel;)D
+1 -1
View File
@@ -2,6 +2,6 @@
"required": true,
"package": "online.astradev.content.mixin",
"compatibilityLevel": "JAVA_25",
"mixins": ["CrossbowMixin", "RailBlockMixin", "RailChunkMixin", "MinecartMixin", "PayloadMixin", "ExperimentalCartMixin", "FurnaceCartMixin"],
"mixins": ["CrossbowMixin", "RailBlockMixin", "RailChunkMixin", "MinecartMixin", "PayloadMixin", "ExperimentalCartMixin", "FurnaceCartMixin", "TrainCartMixin", "SlimeCollisionMixin", "BoatPacketMixin"],
"injectors": {"defaultRequire": 1}
}
@@ -49,7 +49,8 @@ public final class ContentVerification {
var saved=level.getEntity(UUID.fromString(Files.readString(Path.of("saved-cart.txt"))));
require(saved instanceof AbstractMinecart,"saved minecart restored");
require(Math.abs(((CartSpeed)saved).astracontent$limit(level)-1)<.001,"personal speed survives restart on ordinary rails");
finish(server,"PASS restart: four rail ages and personal cart speed survive reload"); return;
TrainVerification.restart(level);
finish(server,"PASS restart: rail ages, personal speed, train and chain display survive reload"); return;
}
setup(level); ammunition(level);
}
@@ -62,6 +63,7 @@ public final class ContentVerification {
require(Math.abs(actual-expected)<.015,"copper measured speed "+age+": "+actual+" expected "+expected);
}
TrackVerification.run(level);
TrainVerification.run(level);
var saved=new Minecart(EntityTypes.MINECART,level);saved.setPos(2.5,100.0625,.5);saved.setDeltaMovement(.1,0,0);saved.tick();
for(int x=29;x<=33;x++) {
var p=new BlockPos(x,100,40);level.setBlockAndUpdate(p.below(),Blocks.STONE.defaultBlockState());
@@ -20,16 +20,16 @@ final class TrackVerification {
brakes(level); detectors(level); water(level); cartTypes(level); transitions(level);
System.out.println("PASS tracks: 8 corner routes, 8 slope routes, brakes, detector, activator, water, 7 cart types, speed transitions");
}
private static BlockPos at(int x,int y,int z,int turn) {
static BlockPos at(int x,int y,int z,int turn) {
for(int i=0;i<turn;i++){int old=x;x=-z;z=old;}
return new BlockPos(60+x,100+y,64+z);
}
private static BlockState rotate(BlockState state,int turns) { for(int i=0;i<turns;i++)state=state.rotate(Rotation.CLOCKWISE_90);return state; }
private static BlockState powered(RailShape shape) {return Blocks.POWERED_RAIL.defaultBlockState().setValue(PoweredRailBlock.SHAPE,shape).setValue(PoweredRailBlock.POWERED,true);}
private static void clear(ServerLevel level) {
static BlockState rotate(BlockState state,int turns) { for(int i=0;i<turns;i++)state=state.rotate(Rotation.CLOCKWISE_90);return state; }
static BlockState powered(RailShape shape) {return Blocks.POWERED_RAIL.defaultBlockState().setValue(PoweredRailBlock.SHAPE,shape).setValue(PoweredRailBlock.POWERED,true);}
static void clear(ServerLevel level) {
for(int x=43;x<=77;x++)for(int z=47;z<=81;z++)for(int y=98;y<=105;y++)level.setBlock(new BlockPos(x,y,z),Blocks.AIR.defaultBlockState(),2);
}
private static void build(ServerLevel level,List<Track> path,int age) {
static void build(ServerLevel level,List<Track> path,int age) {
clear(level);
for(var p:path)level.setBlock(p.pos.below(),Blocks.REDSTONE_BLOCK.defaultBlockState(),2);
for(var p:path)level.setBlock(p.pos,p.state,2);
@@ -39,11 +39,11 @@ final class TrackVerification {
if(p.state.is(Blocks.POWERED_RAIL) && age>=0)Rails.put(level,p.pos,new RailKind(age,true));
}
}
private static Minecart cart(ServerLevel level,BlockPos start,Vec3 velocity) {
static Minecart cart(ServerLevel level,BlockPos start,Vec3 velocity) {
var cart=new Minecart(EntityTypes.MINECART,level);cart.setPos(start.getX()+.5,start.getY()+.0625,start.getZ()+.5);
cart.setDeltaMovement(velocity);level.addFreshEntity(cart);return cart;
}
private static Vec3 direction(int turns,double speed) {
static Vec3 direction(int turns,double speed) {
return switch(turns){case 0->new Vec3(speed,0,0);case 1->new Vec3(0,0,speed);case 2->new Vec3(-speed,0,0);default->new Vec3(0,0,-speed);};
}
private static void travel(ServerLevel level,List<Track> path,int turn,String label) {
@@ -82,7 +82,7 @@ final class TrackVerification {
for(var p:path)level.setBlock(p.pos.below(),Blocks.REDSTONE_BLOCK.defaultBlockState(),2);
travel(level,path,turn,"slope "+turn+"/"+uphill);
}
private static List<Track> straight() {
static List<Track> straight() {
var path=new ArrayList<Track>();for(int x=0;x<=14;x++)path.add(new Track(at(x,0,0,0),powered(RailShape.EAST_WEST)));return path;
}
private static void brakes(ServerLevel level) {
@@ -0,0 +1,160 @@
package online.astradev.content.verification;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.vehicle.minecart.*;
import net.minecraft.world.item.*;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.state.properties.RailShape;
import net.minecraft.world.phys.*;
import net.neoforged.neoforge.common.util.FakePlayerFactory;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
import online.astradev.content.train.*;
import online.astradev.content.transport.SlimeBounce;
import static online.astradev.content.verification.TrackVerification.*;
final class TrainVerification {
static void run(ServerLevel level)throws Exception {
interaction(level);
unloaded(level);
for(int turn=0;turn<4;turn++)for(int mirror:new int[]{-1,1})route(level,turn,mirror,false);
for(int turn=0;turn<4;turn++)for(int slope:new int[]{-1,1})route(level,turn,slope,true);
ring(level);
for(int turn=0;turn<4;turn++){buffer(level,turn,true);buffer(level,turn,false);trainBuffer(level,turn);boat(level,turn);}
offRailBounce(level);
persistence(level);
System.out.println("PASS trains: endpoint interactions, refunds, 8 turns, 8 slopes, closed moving ring, four-direction slime/stone and boat collisions");
}
static void click(ServerLevel level,AbstractMinecart cart,Item item,Vec3 hit){
var player=FakePlayerFactory.getMinecraft(level);player.setShiftKeyDown(true);
player.setItemInHand(InteractionHand.MAIN_HAND,new ItemStack(item,8));
Trains.interact(new PlayerInteractEvent.EntityInteract(player,InteractionHand.MAIN_HAND,cart,hit));
}
static TrainData.Link link(ServerLevel level,AbstractMinecart a,AbstractMinecart b){
var link=new TrainData.Link(a.getUUID(),0,b.getUUID(),1,"minecraft:iron_chain",true,a.position().distanceTo(b.position()));
TrainData.get(level).add(link);return link;
}
static void tick(ServerLevel level,List<? extends AbstractMinecart> carts){
Trains.step(level);for(var cart:carts){cart.setOldPosAndRot();cart.tick();SlimeBounce.flush(cart);}Trains.show(level);
}
static void cleanup(List<? extends Entity> carts){for(var cart:carts)cart.discard();}
static void unloaded(ServerLevel level){
build(level,straight(),0);var a=cart(level,at(2,0,0,0),new Vec3(1,0,0));var b=cart(level,at(4,0,0,0),Vec3.ZERO);
var saved=link(level,a,b);b.remove(Entity.RemovalReason.UNLOADED_TO_CHUNK);
var position=a.position();for(int i=0;i<10;i++)tick(level,List.of(a));
require(a.position().horizontal().distanceTo(position.horizontal())<.01,"loaded half of train pauses");
require(TrainData.get(level).links().contains(saved),"unloading keeps saved chain");
TrainData.get(level).remove(saved);a.discard();Trains.step(level);
}
static void interaction(ServerLevel level){
build(level,straight(),0);var a=cart(level,at(2,0,0,0),Vec3.ZERO);var b=cart(level,at(4,0,0,0),Vec3.ZERO);
var data=TrainData.get(level);var player=FakePlayerFactory.getMinecraft(level);
click(level,a,Items.IRON_CHAIN,new Vec3(0,.2,.49));require(data.links().isEmpty(),"side cannot attach");
click(level,a,Items.IRON_CHAIN,new Vec3(.49,.2,0));require(data.links().size()==1,"front auto couples");
require(player.getMainHandItem().getCount()==7,"one chain consumed");
click(level,a,Items.IRON_CHAIN,new Vec3(.49,.2,0));require(data.links().size()==1 && player.getMainHandItem().getCount()==8,"occupied end rejects");
Trains.show(level);Trains.show(level);
require(level.getEntitiesOfClass(ChainDisplay.class,a.getBoundingBox().inflate(5)).size()==1,"one visible vanilla chain");
int drops=level.getEntitiesOfClass(ItemEntity.class,a.getBoundingBox().inflate(5)).size();
click(level,b,Items.IRON_PICKAXE,new Vec3(-.49,.2,0));require(data.links().isEmpty(),"detach from opposite end");
require(level.getEntitiesOfClass(ItemEntity.class,a.getBoundingBox().inflate(5)).size()==drops+1,"exactly one refund");
click(level,b,Items.IRON_PICKAXE,new Vec3(-.49,.2,0));require(level.getEntitiesOfClass(ItemEntity.class,a.getBoundingBox().inflate(5)).size()==drops+1,"no duplicate refund");
link(level,a,b);b.discard();require(data.links().isEmpty(),"destroy removes saved link");a.discard();
player.setShiftKeyDown(false);
}
static void route(ServerLevel level,int turn,int side,boolean slope){
var path=new ArrayList<Track>();
if(slope){for(int x=0;x<=20;x++){
int y=x<8?0:x<11?x-8:3;if(side<0)y=3-y-(x>=8&&x<11?1:0);
var shape=x>=8&&x<11?(side>0?RailShape.ASCENDING_EAST:RailShape.ASCENDING_WEST):RailShape.EAST_WEST;
path.add(new Track(at(x,y,0,turn),rotate(powered(shape),turn)));
}}else{
for(int x=0;x<9;x++)path.add(new Track(at(x,0,0,turn),rotate(powered(RailShape.EAST_WEST),turn)));
path.add(new Track(at(9,0,0,turn),rotate(Blocks.RAIL.defaultBlockState().setValue(RailBlock.SHAPE,side>0?RailShape.SOUTH_WEST:RailShape.NORTH_WEST),turn)));
for(int z=1;z<=12;z++)path.add(new Track(at(9,0,z*side,turn),rotate(powered(RailShape.NORTH_SOUTH),turn)));
}
build(level,path,0);var carts=new ArrayList<Minecart>();
for(int i=0;i<3;i++){var c=cart(level,path.get(1+i*2).pos(),direction(turn,.5));((CartFrame)c).astracontent$front(direction(turn,1));carts.add(c);}
link(level,carts.get(0),carts.get(1));link(level,carts.get(1),carts.get(2));boolean reached=false;
for(int t=0;t<200;t++){
tick(level,carts);
for(var c:carts){double nearest=path.stream().mapToDouble(p->c.position().distanceTo(Vec3.atBottomCenterOf(p.pos()).add(0,.1,0))).min().orElseThrow();
require(nearest<1.3,"train derailed "+turn+"/"+side+" slope="+slope+" "+c.position());}
require(TrainData.get(level).links().size()==2,"train stays coupled on route");
if(carts.get(0).position().distanceTo(Vec3.atCenterOf(path.get(path.size()-6).pos()))<1.2){reached=true;break;}
}
require(reached,"whole train traverses "+turn+"/"+side+" slope="+slope);cleanup(carts);
}
static void ring(ServerLevel level){
var path=new ArrayList<Track>();var positions=new ArrayList<BlockPos>();
for(int x=0;x<=8;x++)for(int z=0;z<=8;z++)if(x==0||x==8||z==0||z==8){
RailShape shape=z==0||z==8?RailShape.EAST_WEST:RailShape.NORTH_SOUTH;
if(x==0&&z==0)shape=RailShape.SOUTH_EAST;if(x==8&&z==0)shape=RailShape.SOUTH_WEST;
if(x==8&&z==8)shape=RailShape.NORTH_WEST;if(x==0&&z==8)shape=RailShape.NORTH_EAST;
path.add(new Track(at(x,0,z,0),shape.isSlope()||shape==RailShape.EAST_WEST||shape==RailShape.NORTH_SOUTH?powered(shape):Blocks.RAIL.defaultBlockState().setValue(RailBlock.SHAPE,shape)));
}
for(int x=4;x<=8;x+=2)positions.add(at(x,0,0,0));for(int z=2;z<=8;z+=2)positions.add(at(8,0,z,0));
for(int x=6;x>=0;x-=2)positions.add(at(x,0,8,0));for(int z=6;z>=0;z-=2)positions.add(at(0,0,z,0));positions.add(at(2,0,0,0));
build(level,path,3);var carts=new ArrayList<Minecart>();
for(int i=0;i<positions.size();i++){var dir=Vec3.atCenterOf(positions.get((i+1)%positions.size())).subtract(Vec3.atCenterOf(positions.get(i))).normalize();
var c=cart(level,positions.get(i),dir.scale(.3));((CartFrame)c).astracontent$front(dir);carts.add(c);}
for(int i=0;i<carts.size()-1;i++)link(level,carts.get(i),carts.get(i+1));
click(level,carts.getLast(),Items.IRON_CHAIN,new Vec3(.49,.2,0));
require(TrainData.get(level).links().size()==carts.size(),"player closes same train into ring");
double traveled=0;
for(int t=0;t<100;t++){var before=carts.getFirst().position();tick(level,carts);traveled+=before.distanceTo(carts.getFirst().position());
require(TrainData.get(level).links().size()==carts.size(),"closed ring remains intact");
for(var c:carts)require(level.getBlockState(c.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock,"ring cart remains on rail "+c.position());}
require(traveled>15,"closed ring actually moves: "+traveled);cleanup(carts);
}
static void buffer(ServerLevel level,int turn,boolean slime){
var path=new ArrayList<Track>();for(int x=0;x<=10;x++)path.add(new Track(at(x,0,0,turn),rotate(powered(RailShape.EAST_WEST),turn)));
build(level,path,0);level.setBlock(at(11,0,0,turn),(slime?Blocks.SLIME_BLOCK:Blocks.STONE).defaultBlockState(),2);
var cart=cart(level,at(8,0,0,turn),direction(turn,1));boolean reflected=false;double speed=0;
for(int t=0;t<15;t++){cart.setOldPosAndRot();cart.tick();SlimeBounce.flush(cart);double v=cart.getDeltaMovement().dot(direction(turn,1));if(v<-.1){reflected=true;speed=-v;break;}}
if(slime)require(reflected,"slime reflects direction "+turn);
else require(speed<.4,"stone retains native slow powered-rail restart: "+speed);
if(slime)require(speed>.9,"full impact speed preserved "+turn+": "+speed);cart.discard();
}
static void boat(ServerLevel level,int turn){
clear(level);var wall=at(4,0,0,turn);level.setBlock(wall,Blocks.SLIME_BLOCK.defaultBlockState(),2);
var boat=EntityTypes.OAK_BOAT.create(level,EntitySpawnReason.COMMAND);var dir=direction(turn,1);
boat.setPos(Vec3.atBottomCenterOf(wall).subtract(dir.scale(1.5)));level.addFreshEntity(boat);boat.setDeltaMovement(dir);
boat.move(MoverType.SELF,dir);SlimeBounce.flush(boat);
require(boat.getDeltaMovement().dot(dir)<-.99,"boat full speed bounce "+turn);boat.discard();
}
static void trainBuffer(ServerLevel level,int turn){
var path=new ArrayList<Track>();for(int x=0;x<=10;x++)path.add(new Track(at(x,0,0,turn),rotate(powered(RailShape.EAST_WEST),turn)));
build(level,path,0);level.setBlock(at(11,0,0,turn),Blocks.SLIME_BLOCK.defaultBlockState(),2);
var carts=new ArrayList<Minecart>();var direction=direction(turn,1);
for(int x=4;x<=8;x+=2){var c=cart(level,at(x,0,0,turn),direction);((CartFrame)c).astracontent$front(direction);carts.add(c);}
link(level,carts.get(0),carts.get(1));link(level,carts.get(1),carts.get(2));boolean bounced=false;
for(int i=0;i<15;i++){tick(level,carts);if(carts.getLast().getDeltaMovement().dot(direction)<-.1){bounced=true;break;}}
require(bounced,"whole train hits buffer "+turn);
for(var c:carts)require(c.getDeltaMovement().dot(direction)<-.85,"whole train reverses at impact speed "+turn);
cleanup(carts);
}
static void offRailBounce(ServerLevel level){
clear(level);level.setBlock(at(4,0,0,0),Blocks.SLIME_BLOCK.defaultBlockState(),2);
var cart=cart(level,at(3,0,0,0),new Vec3(1,0,.2));
cart.move(MoverType.SELF,cart.getDeltaMovement());SlimeBounce.flush(cart);
require(Math.abs(cart.getDeltaMovement().x+1)<.001 && Math.abs(cart.getDeltaMovement().z-.2)<.001,"off-rail bounce preserves tangential speed");cart.discard();
}
static void persistence(ServerLevel level)throws Exception{
build(level,straight(),0);var a=cart(level,at(3,0,0,0),Vec3.ZERO);var b=cart(level,at(5,0,0,0),Vec3.ZERO);link(level,a,b);
Trains.show(level);Files.writeString(Path.of("saved-train.txt"),a.getUUID()+"\n"+b.getUUID());
}
static void restart(ServerLevel level)throws Exception{
var ids=Files.readAllLines(Path.of("saved-train.txt"));var data=TrainData.get(level);
require(data.links().size()==1,"one saved link after restart");
var a=(AbstractMinecart)level.getEntity(UUID.fromString(ids.get(0)));var b=(AbstractMinecart)level.getEntity(UUID.fromString(ids.get(1)));
require(a!=null&&b!=null&&Trains.connected(a,b),"saved train restored");Trains.show(level);
require(level.getEntitiesOfClass(ChainDisplay.class,a.getBoundingBox().inflate(5)).size()==1,"one chain recreated after restart");
}
static void require(boolean value,String message){if(!value)throw new AssertionError(message);}
}