Add chain-coupled minecart trains, closed loops and slime buffers
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user