Fix player control of coupled carts and copper rail slope overlays
This commit is contained in:
@@ -12,6 +12,7 @@ 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$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"))
|
||||
@@ -21,8 +22,17 @@ public abstract class TrainCartMixin implements CartFrame {
|
||||
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)
|
||||
@Inject(method="push(Lnet/minecraft/world/entity/Entity;)V",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();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,16 +20,13 @@ final class RailDisplay extends Display.ItemDisplay {
|
||||
}
|
||||
void update(RailKind kind, BlockState state) {
|
||||
var shape = state.getValue(PoweredRailBlock.SHAPE);
|
||||
boolean eastWest = shape == net.minecraft.world.level.block.state.properties.RailShape.EAST_WEST
|
||||
|| shape == net.minecraft.world.level.block.state.properties.RailShape.ASCENDING_EAST
|
||||
|| shape == net.minecraft.world.level.block.state.properties.RailShape.ASCENDING_WEST;
|
||||
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(),
|
||||
new org.joml.Quaternionf().rotateY(eastWest ? -(float)Math.PI/2 : 0),new org.joml.Vector3f(1),new org.joml.Quaternionf()));
|
||||
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; }
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||
import org.joml.Quaternionf;
|
||||
|
||||
final class RailDisplayTransform {
|
||||
private RailDisplayTransform(){}
|
||||
static Quaternionf orientation(RailShape shape){
|
||||
boolean eastWest=shape==RailShape.EAST_WEST||shape==RailShape.ASCENDING_EAST||shape==RailShape.ASCENDING_WEST;
|
||||
// ItemDisplayRenderer itself applies Y=180 degrees before drawing an item model.
|
||||
// Cancel that turn so the model's raised end matches the actual rail's raised end.
|
||||
return new Quaternionf().rotateY((float)Math.PI+(eastWest?-(float)Math.PI/2:0));
|
||||
}
|
||||
}
|
||||
@@ -23,8 +23,12 @@ 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());
|
||||
}
|
||||
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
|
||||
@@ -89,6 +93,7 @@ public final class Trains {
|
||||
/** 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;
|
||||
@@ -102,16 +107,23 @@ public final class Trains {
|
||||
}
|
||||
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));
|
||||
}
|
||||
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);
|
||||
// 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());
|
||||
@@ -121,13 +133,27 @@ public final class Trains {
|
||||
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);
|
||||
// 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 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);
|
||||
}
|
||||
@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>();
|
||||
@@ -154,5 +180,5 @@ public final class Trains {
|
||||
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();}
|
||||
@SubscribeEvent public static void stop(ServerStoppedEvent event){for(var key:new ArrayList<>(DISPLAYS.keySet()))discard(key);PAUSED.clear();PLAYER_PUSHES.clear();}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||
import org.joml.Vector3f;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class RailDisplayTransformTest {
|
||||
@Test void everyOverlayVertexMatchesNativeRailPlane()throws Exception{
|
||||
for(int age=0;age<4;age++)for(boolean powered:new boolean[]{false,true})for(var shape:new RailShape[]{
|
||||
RailShape.NORTH_SOUTH,RailShape.EAST_WEST,RailShape.ASCENDING_NORTH,RailShape.ASCENDING_SOUTH,RailShape.ASCENDING_EAST,RailShape.ASCENDING_WEST}){
|
||||
String path="/defaults/resources/assets/astracontent/models/rail_display/"+age+"/"+shape.getSerializedName()+(powered?"_on":"")+".json";
|
||||
try(var stream=getClass().getResourceAsStream(path)){
|
||||
assertNotNull(stream,path);var model=JsonParser.parseReader(new InputStreamReader(stream,StandardCharsets.UTF_8)).getAsJsonObject();
|
||||
for(var value:model.getAsJsonArray("elements")){
|
||||
var element=value.getAsJsonObject();var from=vector(element.getAsJsonArray("from"));var to=vector(element.getAsJsonArray("to"));
|
||||
for(float x:new float[]{from.x,to.x})for(float z:new float[]{from.z,to.z}){
|
||||
var point=new Vector3f(x,from.y,z);
|
||||
if(element.has("rotation")){
|
||||
var rotation=element.getAsJsonObject("rotation");var origin=vector(rotation.getAsJsonArray("origin"));
|
||||
float radians=(float)Math.toRadians(rotation.get("angle").getAsFloat());point.sub(origin);
|
||||
if(rotation.get("rescale").getAsBoolean()){float scale=1/(float)Math.cos(radians);point.mul(1,scale,scale);}
|
||||
point.rotateX(radians).add(origin);
|
||||
}
|
||||
// Item models are centered at .5, then the vanilla item renderer turns them by pi.
|
||||
point.div(16).sub(.5f,.5f,.5f).rotateY((float)Math.PI).rotate(RailDisplayTransform.orientation(shape)).add(.5f,.5f,.5f);
|
||||
float nativeHeight=1f/16+switch(shape){
|
||||
case ASCENDING_NORTH->1-point.z;case ASCENDING_SOUTH->point.z;
|
||||
case ASCENDING_EAST->point.x;case ASCENDING_WEST->1-point.x;default->0;
|
||||
};
|
||||
assertTrue(point.y>nativeHeight && point.y-nativeHeight<.01,path+" vertex="+point+" rail height="+nativeHeight);
|
||||
assertTrue(point.x>-.01 && point.x<1.01 && point.z>-.01 && point.z<1.01,path+" stays inside rail footprint");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private static Vector3f vector(JsonArray a){return new Vector3f(a.get(0).getAsFloat(),a.get(1).getAsFloat(),a.get(2).getAsFloat());}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package online.astradev.content.verification;
|
||||
|
||||
import java.util.*;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.player.Input;
|
||||
import net.minecraft.world.entity.vehicle.minecart.Minecart;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.RailBlock;
|
||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.neoforged.neoforge.common.util.FakePlayerFactory;
|
||||
import static online.astradev.content.verification.TrackVerification.*;
|
||||
import static online.astradev.content.verification.TrainVerification.*;
|
||||
|
||||
final class PlayerTrainVerification {
|
||||
static void run(ServerLevel level){
|
||||
for(int side=0;side<4;side++){
|
||||
double ordinary=push(level,side,1),train=push(level,side,3);
|
||||
require(Math.abs(ordinary)>.02,"ordinary cart reacts to player push");
|
||||
require(Math.abs(train-ordinary)<.005,"same player push reaches whole train side="+side+": "+train+" vs "+ordinary);
|
||||
}
|
||||
for(boolean reverse:new boolean[]{false,true}){
|
||||
double ordinary=ride(level,reverse,1),train=ride(level,reverse,3);
|
||||
require(Math.abs(ordinary)>.1,"ordinary cart responds to seated input");
|
||||
require(Math.signum(train)==Math.signum(ordinary)&&Math.abs(train)>=Math.abs(ordinary)*.8,
|
||||
"seated player controls train reverse="+reverse+": "+train+" vs "+ordinary);
|
||||
}
|
||||
System.out.println("PASS player controls: walking pushes from four sides and seated forward/backward input compared with ordinary cart");
|
||||
}
|
||||
private static List<Minecart> setup(ServerLevel level,int count){
|
||||
var path=new ArrayList<Track>();for(int x=0;x<=14;x++)path.add(new Track(at(x,0,0,0),Blocks.RAIL.defaultBlockState().setValue(RailBlock.SHAPE,RailShape.EAST_WEST)));
|
||||
build(level,path,-1);var carts=new ArrayList<Minecart>();
|
||||
for(int i=0;i<count;i++)carts.add(cart(level,at(4+i*2,0,0,0),Vec3.ZERO));
|
||||
for(int i=0;i<count-1;i++)link(level,carts.get(i),carts.get(i+1));return carts;
|
||||
}
|
||||
private static double push(ServerLevel level,int side,int count){
|
||||
var carts=setup(level,count);var target=carts.getFirst();var player=FakePlayerFactory.getMinecraft(level);
|
||||
player.stopRiding();player.setLastClientInput(Input.EMPTY);player.setShiftKeyDown(false);
|
||||
player.setPos(target.position().add(direction(side,.6)));player.setDeltaMovement(Vec3.ZERO);
|
||||
target.push(player);double before=target.getX();tick(level,carts);double result=target.getX()-before;
|
||||
if(count>1)for(var c:carts)require(c.getDeltaMovement().horizontalDistance()>.01,"every coupled cart receives walking push");
|
||||
cleanup(carts);player.setPos(40,115,35);return result;
|
||||
}
|
||||
private static double ride(ServerLevel level,boolean reverse,int count){
|
||||
var carts=setup(level,count);var target=carts.getFirst();
|
||||
// NeoForge FakePlayer deliberately refuses all riding; use the real ServerPlayer implementation.
|
||||
var player=new net.minecraft.server.level.ServerPlayer(level.getServer(),level,
|
||||
new com.mojang.authlib.GameProfile(UUID.randomUUID(),"TrainRider"),net.minecraft.server.level.ClientInformation.createDefault());
|
||||
player.connection=FakePlayerFactory.getMinecraft(level).connection;
|
||||
player.setShiftKeyDown(false);player.setPos(target.position());require(player.startRiding(target),"player mounts minecart");
|
||||
player.setYRot(-90);player.setLastClientInput(new Input(!reverse,reverse,false,false,false,false,false));
|
||||
double before=target.getX();for(int i=0;i<100;i++)tick(level,carts);double result=target.getX()-before;
|
||||
player.setLastClientInput(Input.EMPTY);player.stopRiding();cleanup(carts);player.setPos(40,115,35);return result;
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import static online.astradev.content.verification.TrackVerification.*;
|
||||
final class TrainVerification {
|
||||
static void run(ServerLevel level)throws Exception {
|
||||
interaction(level);
|
||||
PlayerTrainVerification.run(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);
|
||||
|
||||
Reference in New Issue
Block a user