Spicy Blink module 2 files, 685 lines

Spicy Blink: Full Source Analysis

Spicy's Blink cancels every outgoing packet except C00PacketKeepAlive, C00Handshake and C00PacketLoginStart in the pre stage of EventSendPacket, stores them in a static ArrayList, and replays them…

info/spicyclient/modules/player/Blink.java · GitHub source ↗

Published 2026-08-12 · Updated 2026-08-12

Packets This Module Uses

Analysis

Overview

Spicy's Blink cancels every outgoing packet except C00PacketKeepAlive, C00Handshake and C00PacketLoginStart in the pre stage of EventSendPacket, stores them in a static ArrayList, and replays them through NetHandlerPlayClient.addToSendQueue when disabled. The keepalive exemption is the connection lifeline: buffering the echoes too would starve the server's ping validation and earn a timeout kick, so the module deliberately leaves the keepalive stream intact while freezing everything else. The flush path is the subtle part: addToSendQueue funnels into NetworkManager.sendPacket, which fires EventSendPacket again, but the event dispatcher only invokes onEvent for toggled modules, so the replayed packets pass through unmolested while the module is off. A singleplayer guard toggles the module back off with a warning notification, and the static buffer is cleared on enable.

Buffer scope

The pre check returns early for the three exempt classes and cancels everything else: C03 moves, C02 attacks, C08 placements, C0F confirmations, C0B entity actions, the whole gameplay stream parks in the list. The list is static, so it survives module restarts and is cleared only in onEnable, and the module's own singleplayer check prevents misuse in a world the client controls.

Flush path and re-entrancy

onDisable iterates the buffer and calls addToSendQueue, which delegates to NetworkManager.sendPacket. sendPacket fires EventSendPacket at the top of the method and returns early when cancelled, so the flush re-enters the module's own hook; SpicyClient.onEvent dispatches to onEvent only when the module is toggled on and to onEventWhenDisabled otherwise, and since the module toggled off before the flush, the re-entrant event reaches only the empty disabled handler. The packet is sent, the for-each over the live list never sees a concurrent modification, and nothing re-buffers.

Detection surface

While enabled the server sees a player standing still with keepalives flowing, which is the cleanest fake-lag signature an anticheat can key on. The disable flush replays the whole buffer in one tick, and the longer the blink, the larger the first-move delta from the last server-tracked position; rate checks see the burst and envelope checks see the jump.

source Blink.java

Blink.java75 lines · JavaOriginal ↗
1
package info.spicyclient.modules.player;
2
3
import java.util.ArrayList;
4
5
import org.lwjgl.input.Keyboard;
6
7
import info.spicyclient.chatCommands.Command;
8
import info.spicyclient.events.Event;
9
import info.spicyclient.events.listeners.EventSendPacket;
10
import info.spicyclient.events.listeners.EventUpdate;
11
import info.spicyclient.modules.Module;
12
import info.spicyclient.notifications.Color;
13
import info.spicyclient.notifications.NotificationManager;
14
import info.spicyclient.notifications.Type;
15
import net.minecraft.network.NetworkManager;
16
import net.minecraft.network.Packet;
17
import net.minecraft.network.handshake.client.C00Handshake;
18
import net.minecraft.network.login.client.C00PacketLoginStart;
19
import net.minecraft.network.play.client.C00PacketKeepAlive;
20
import net.minecraft.network.play.client.C03PacketPlayer;
21
22
public class Blink extends Module {
23
	
24
	public static ArrayList<Packet> packets = new ArrayList<Packet>();
25
	
26
	public Blink() {
27
		super("Blink", Keyboard.KEY_NONE, Category.PLAYER);
28
	}
29
	
30
	public void onEnable() {
31
		packets.clear();
32
		
33
		if (mc.isSingleplayer()) {
34
			NotificationManager.getNotificationManager().createNotification("Don't use blink in singleplayer!", "", true, 5000, Type.WARNING, Color.RED);
35
			this.toggle();
36
		}
37
		
38
	}
39
	
40
	public void onDisable() {
41
		
42
		for (Packet p : packets) {
43
			
44
			if (mc.isSingleplayer()) {
45
				
46
			}else {
47
				mc.getNetHandler().addToSendQueue(p);
48
			}
49
			
50
		}
51
		packets.clear();
52
		
53
	}
54
	
55
	public void onEvent(Event e) {
56
		
57
		if (e instanceof EventSendPacket) {
58
			
59
			if (e.isPre()) {
60
				
61
				if (((EventSendPacket)e).packet instanceof C00PacketKeepAlive || ((EventSendPacket)e).packet instanceof C00Handshake || ((EventSendPacket)e).packet instanceof C00PacketLoginStart) {
62
					return;
63
				}
64
				
65
				EventSendPacket sendPacket = (EventSendPacket) e;
66
				packets.add(sendPacket.packet);
67
				sendPacket.setCanceled(true);
68
				
69
			}
70
			
71
		}
72
		
73
	}
74
	
75
}

What this file does

The pre-send hook cancels all packets except C00PacketKeepAlive, C00Handshake and C00PacketLoginStart, which keeps the connection alive while the gameplay stream freezes. onDisable replays the static list through NetHandlerPlayClient.addToSendQueue, onEnable clears the list, and the singleplayer guard shows a warning notification and toggles the module back off. The module never checks its own enabled state inside the hook, which is why the flush relies on the dispatcher routing re-entrant events to the disabled handler.

source NetworkManager.java (send event and flush path)

NetworkManager.java610 lines · JavaOriginal ↗
1
package net.minecraft.network;
2
3
import com.github.creeper123123321.viafabric.ViaFabric;
4
import com.github.creeper123123321.viafabric.handler.CommonTransformer;
5
import com.github.creeper123123321.viafabric.handler.clientside.VRDecodeHandler;
6
import com.github.creeper123123321.viafabric.handler.clientside.VREncodeHandler;
7
import com.github.creeper123123321.viafabric.platform.VRClientSideUserConnection;
8
import com.github.creeper123123321.viafabric.protocol.ViaFabricHostnameProtocol;
9
import com.github.creeper123123321.viafabric.util.ProtocolUtils;
10
import com.google.common.collect.Queues;
11
import com.google.common.util.concurrent.ThreadFactoryBuilder;
12
13
import info.spicyclient.SpicyClient;
14
import info.spicyclient.events.EventDirection;
15
import info.spicyclient.events.EventType;
16
import info.spicyclient.events.listeners.EventPacket;
17
import info.spicyclient.events.listeners.EventSendPacket;
18
import io.netty.bootstrap.Bootstrap;
19
import io.netty.channel.Channel;
20
import io.netty.channel.ChannelException;
21
import io.netty.channel.ChannelFuture;
22
import io.netty.channel.ChannelFutureListener;
23
import io.netty.channel.ChannelHandler;
24
import io.netty.channel.ChannelHandlerContext;
25
import io.netty.channel.ChannelInitializer;
26
import io.netty.channel.ChannelOption;
27
import io.netty.channel.EventLoopGroup;
28
import io.netty.channel.SimpleChannelInboundHandler;
29
import io.netty.channel.epoll.Epoll;
30
import io.netty.channel.epoll.EpollEventLoopGroup;
31
import io.netty.channel.epoll.EpollSocketChannel;
32
import io.netty.channel.local.LocalChannel;
33
import io.netty.channel.local.LocalEventLoopGroup;
34
import io.netty.channel.local.LocalServerChannel;
35
import io.netty.channel.nio.NioEventLoopGroup;
36
import io.netty.channel.socket.SocketChannel;
37
import io.netty.channel.socket.nio.NioSocketChannel;
38
import io.netty.handler.timeout.ReadTimeoutHandler;
39
import io.netty.handler.timeout.TimeoutException;
40
import io.netty.util.AttributeKey;
41
import io.netty.util.concurrent.Future;
42
import io.netty.util.concurrent.GenericFutureListener;
43
import java.net.InetAddress;
44
import java.net.SocketAddress;
45
import java.util.Queue;
46
import java.util.concurrent.locks.ReentrantReadWriteLock;
47
import javax.crypto.SecretKey;
48
import net.minecraft.util.ChatComponentText;
49
import net.minecraft.util.ChatComponentTranslation;
50
import net.minecraft.util.CryptManager;
51
import net.minecraft.util.IChatComponent;
52
import net.minecraft.util.ITickable;
53
import net.minecraft.util.LazyLoadBase;
54
import net.minecraft.util.MessageDeserializer;
55
import net.minecraft.util.MessageDeserializer2;
56
import net.minecraft.util.MessageSerializer;
57
import net.minecraft.util.MessageSerializer2;
58
import us.myles.ViaVersion.api.data.UserConnection;
59
import us.myles.ViaVersion.api.protocol.ProtocolPipeline;
60
import viamcp.utils.ProtocolSorter;
61
import viamcp.utils.Util;
62
63
import org.apache.commons.lang3.ArrayUtils;
64
import org.apache.commons.lang3.Validate;
65
import org.apache.logging.log4j.LogManager;
66
import org.apache.logging.log4j.Logger;
67
import org.apache.logging.log4j.Marker;
68
import org.apache.logging.log4j.MarkerManager;
69
70
public class NetworkManager extends SimpleChannelInboundHandler<Packet>
71
{
72
    private static final Logger logger = LogManager.getLogger();
73
    public static final Marker logMarkerNetwork = MarkerManager.getMarker("NETWORK");
74
    public static final Marker logMarkerPackets = MarkerManager.getMarker("NETWORK_PACKETS", logMarkerNetwork);
75
    public static final AttributeKey<EnumConnectionState> attrKeyConnectionState = AttributeKey.<EnumConnectionState>valueOf("protocol");
76
    public static final LazyLoadBase<NioEventLoopGroup> CLIENT_NIO_EVENTLOOP = new LazyLoadBase<NioEventLoopGroup>()
77
    {
78
        protected NioEventLoopGroup load()
79
        {
80
            return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Client IO #%d").setDaemon(true).build());
81
        }
82
    };
83
    public static final LazyLoadBase<EpollEventLoopGroup> field_181125_e = new LazyLoadBase<EpollEventLoopGroup>()
84
    {
85
        protected EpollEventLoopGroup load()
86
        {
87
            return new EpollEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Epoll Client IO #%d").setDaemon(true).build());
88
        }
89
    };
90
    public static final LazyLoadBase<LocalEventLoopGroup> CLIENT_LOCAL_EVENTLOOP = new LazyLoadBase<LocalEventLoopGroup>()
91
    {
92
        protected LocalEventLoopGroup load()
93
        {
94
            return new LocalEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Local Client IO #%d").setDaemon(true).build());
95
        }
96
    };
97
    private final EnumPacketDirection direction;
98
    private final Queue<NetworkManager.InboundHandlerTuplePacketListener> outboundPacketsQueue = Queues.<NetworkManager.InboundHandlerTuplePacketListener>newConcurrentLinkedQueue();
99
    private final ReentrantReadWriteLock field_181680_j = new ReentrantReadWriteLock();
100
101
    /** The active channel */
102
    private Channel channel;
103
104
    /** The address of the remote party */
105
    private SocketAddress socketAddress;
106
107
    /** The INetHandler instance responsible for processing received packets */
108
    public INetHandler packetListener;
109
110
    /** A String indicating why the network has shutdown. */
111
    private IChatComponent terminationReason;
112
    private boolean isEncrypted;
113
    private boolean disconnected;
114
115
    public NetworkManager(EnumPacketDirection packetDirection)
116
    {
117
        this.direction = packetDirection;
118
    }
119
120
    public void channelActive(ChannelHandlerContext p_channelActive_1_) throws Exception
121
    {
122
        super.channelActive(p_channelActive_1_);
123
        this.channel = p_channelActive_1_.channel();
124
        this.socketAddress = this.channel.remoteAddress();
125
126
        try
127
        {
128
            this.setConnectionState(EnumConnectionState.HANDSHAKING);
129
        }
130
        catch (Throwable throwable)
131
        {
132
            logger.fatal((Object)throwable);
133
        }
134
    }
135
136
    /**
137
     * Sets the new connection state and registers which packets this channel may send and receive
138
     */
139
    public void setConnectionState(EnumConnectionState newState)
140
    {
141
        this.channel.attr(attrKeyConnectionState).set(newState);
142
        this.channel.config().setAutoRead(true);
143
        logger.debug("Enabled auto read");
144
    }
145
146
    public void channelInactive(ChannelHandlerContext p_channelInactive_1_) throws Exception
147
    {
148
        this.closeChannel(new ChatComponentTranslation("disconnect.endOfStream", new Object[0]));
149
    }
150
151
    public void exceptionCaught(ChannelHandlerContext p_exceptionCaught_1_, Throwable p_exceptionCaught_2_) throws Exception
152
    {
153
        ChatComponentTranslation chatcomponenttranslation;
154
155
        if (p_exceptionCaught_2_ instanceof TimeoutException)
156
        {
157
            chatcomponenttranslation = new ChatComponentTranslation("disconnect.timeout", new Object[0]);
158
        }
159
        else
160
        {
161
            chatcomponenttranslation = new ChatComponentTranslation("disconnect.genericReason", new Object[] {"Internal Exception: " + p_exceptionCaught_2_});
162
        }
163
164
        this.closeChannel(chatcomponenttranslation);
165
    }
166
167
    protected void channelRead0(ChannelHandlerContext p_channelRead0_1_, Packet p_channelRead0_2_) throws Exception
168
    {
169
        if (this.channel.isOpen())
170
        {
171
            try
172
            {
173
            	
174
            	EventPacket event = new EventPacket(EventType.PRE, EventDirection.INCOMING, p_channelRead0_2_);
175
            	SpicyClient.onEvent(event);
176
            	
177
            	if (event.isCanceled()) {
178
            		return;
179
            	}
180
            	
181
                p_channelRead0_2_.processPacket(this.packetListener);
182
            }
183
            catch (ThreadQuickExitException var4)
184
            {
185
                ;
186
            }
187
        }
188
    }
189
190
    /**
191
     * Sets the NetHandler for this NetworkManager, no checks are made if this handler is suitable for the particular
192
     * connection state (protocol)
193
     */
194
    public void setNetHandler(INetHandler handler)
195
    {
196
        Validate.notNull(handler, "packetListener", new Object[0]);
197
        logger.debug("Set listener of {} to {}", new Object[] {this, handler});
198
        this.packetListener = handler;
199
    }
200
201
    public void sendPacket(Packet packetIn)
202
    {
203
    	
204
    	EventSendPacket event = new EventSendPacket(packetIn);
205
    	event.setType(EventType.PRE);
206
    	SpicyClient.onEvent(event);
207
    	
208
    	if (event.isCanceled()) {
209
    		return;
210
    	}
211
    	
212
        if (this.isChannelOpen())
213
        {
214
            this.flushOutboundQueue();
215
            this.dispatchPacket(packetIn, (GenericFutureListener <? extends Future <? super Void >> [])null);
216
        }
217
        else
218
        {
219
            this.field_181680_j.writeLock().lock();
220
221
            try
222
            {
223
                this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])null));
224
            }
225
            finally
226
            {
227
                this.field_181680_j.writeLock().unlock();
228
            }
229
        }
230
    }
231
    
232
    public void sendPacket(Packet packetIn, GenericFutureListener <? extends Future <? super Void >> listener, GenericFutureListener <? extends Future <? super Void >> ... listeners)
233
    {
234
    	
235
    	EventSendPacket event = new EventSendPacket(packetIn);
236
    	event.setType(EventType.PRE);
237
    	
238
    	if (event.packet == null || event == null) {
239
    		
240
    	}else {
241
    		SpicyClient.onEvent(event);
242
    	}
243
    	
244
    	if (event.isCanceled()) {
245
    		return;
246
    	}
247
    	
248
        if (this.isChannelOpen())
249
        {
250
            this.flushOutboundQueue();
251
            this.dispatchPacket(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener));
252
        }
253
        else
254
        {
255
            this.field_181680_j.writeLock().lock();
256
257
            try
258
            {
259
                this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener)));
260
            }
261
            finally
262
            {
263
                this.field_181680_j.writeLock().unlock();
264
            }
265
        }
266
    }
267
    
268
    public void sendPacketNoEvent(Packet packet) {
269
        if (channel != null && channel.isOpen()) {
270
            flushOutboundQueue();
271
            dispatchPacket(packet, null);
272
        } else {
273
            outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packet, (GenericFutureListener[]) null));
274
        }
275
    }
276
    
277
    /**
278
     * Will commit the packet to the channel. If the current thread 'owns' the channel it will write and flush the
279
     * packet, otherwise it will add a task for the channel eventloop thread to do that.
280
     */
281
    private void dispatchPacket(final Packet inPacket, final GenericFutureListener <? extends Future <? super Void >> [] futureListeners)
282
    {
283
        final EnumConnectionState enumconnectionstate = EnumConnectionState.getFromPacket(inPacket);
284
        final EnumConnectionState enumconnectionstate1 = (EnumConnectionState)this.channel.attr(attrKeyConnectionState).get();
285
286
        if (enumconnectionstate1 != enumconnectionstate)
287
        {
288
            logger.debug("Disabled auto read");
289
            this.channel.config().setAutoRead(false);
290
        }
291
292
        if (this.channel.eventLoop().inEventLoop())
293
        {
294
            if (enumconnectionstate != enumconnectionstate1)
295
            {
296
                this.setConnectionState(enumconnectionstate);
297
            }
298
299
            ChannelFuture channelfuture = this.channel.writeAndFlush(inPacket);
300
301
            if (futureListeners != null)
302
            {
303
                channelfuture.addListeners(futureListeners);
304
            }
305
306
            channelfuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
307
        }
308
        else
309
        {
310
            this.channel.eventLoop().execute(new Runnable()
311
            {
312
                public void run()
313
                {
314
                    if (enumconnectionstate != enumconnectionstate1)
315
                    {
316
                        NetworkManager.this.setConnectionState(enumconnectionstate);
317
                    }
318
319
                    ChannelFuture channelfuture1 = NetworkManager.this.channel.writeAndFlush(inPacket);
320
321
                    if (futureListeners != null)
322
                    {
323
                        channelfuture1.addListeners(futureListeners);
324
                    }
325
326
                    channelfuture1.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
327
                }
328
            });
329
        }
330
    }
331
332
    /**
333
     * Will iterate through the outboundPacketQueue and dispatch all Packets
334
     */
335
    private void flushOutboundQueue()
336
    {
337
        if (this.channel != null && this.channel.isOpen())
338
        {
339
            this.field_181680_j.readLock().lock();
340
341
            try
342
            {
343
                while (!this.outboundPacketsQueue.isEmpty())
344
                {
345
                    NetworkManager.InboundHandlerTuplePacketListener networkmanager$inboundhandlertuplepacketlistener = (NetworkManager.InboundHandlerTuplePacketListener)this.outboundPacketsQueue.poll();
346
                    this.dispatchPacket(networkmanager$inboundhandlertuplepacketlistener.packet, networkmanager$inboundhandlertuplepacketlistener.futureListeners);
347
                }
348
            }
349
            finally
350
            {
351
                this.field_181680_j.readLock().unlock();
352
            }
353
        }
354
    }
355
356
    /**
357
     * Checks timeouts and processes all packets received
358
     */
359
    public void processReceivedPackets()
360
    {
361
        this.flushOutboundQueue();
362
363
        if (this.packetListener instanceof ITickable)
364
        {
365
            ((ITickable)this.packetListener).update();
366
        }
367
368
        this.channel.flush();
369
    }
370
371
    /**
372
     * Returns the socket address of the remote side. Server-only.
373
     */
374
    public SocketAddress getRemoteAddress()
375
    {
376
        return this.socketAddress;
377
    }
378
379
    /**
380
     * Closes the channel, the parameter can be used for an exit message (not certain how it gets sent)
381
     */
382
    public void closeChannel(IChatComponent message)
383
    {
384
        if (this.channel.isOpen())
385
        {
386
            this.channel.close().awaitUninterruptibly();
387
            this.terminationReason = message;
388
        }
389
    }
390
391
    /**
392
     * True if this NetworkManager uses a memory connection (single player game). False may imply both an active TCP
393
     * connection or simply no active connection at all
394
     */
395
    public boolean isLocalChannel()
396
    {
397
        return this.channel instanceof LocalChannel || this.channel instanceof LocalServerChannel;
398
    }
399
400
    public static NetworkManager func_181124_a(InetAddress p_181124_0_, int p_181124_1_, boolean p_181124_2_)
401
    {
402
        final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
403
        Class <? extends SocketChannel > oclass;
404
        LazyLoadBase <? extends EventLoopGroup > lazyloadbase;
405
406
        if (Epoll.isAvailable() && p_181124_2_)
407
        {
408
            oclass = EpollSocketChannel.class;
409
            lazyloadbase = field_181125_e;
410
        }
411
        else
412
        {
413
            oclass = NioSocketChannel.class;
414
            lazyloadbase = CLIENT_NIO_EVENTLOOP;
415
        }
416
417
        ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
418
        {
419
            protected void initChannel(Channel p_initChannel_1_) throws Exception
420
            {
421
                try
422
                {
423
                    p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
424
                }
425
                catch (ChannelException var3)
426
                {
427
                    ;
428
                }
429
430
                p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new MessageDeserializer2())).addLast((String)"decoder", (ChannelHandler)(new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new MessageSerializer2())).addLast((String)"encoder", (ChannelHandler)(new MessageSerializer(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
431
                
432
                /* ViaVersion */
433
                if (ProtocolUtils.getProtocolName(ViaFabric.clientSideVersion).toLowerCase() != "1.8.x") {
434
                	if (p_initChannel_1_ instanceof SocketChannel) {
435
                    	UserConnection user = new VRClientSideUserConnection(p_initChannel_1_);
436
                    	new ProtocolPipeline(user).add(ViaFabricHostnameProtocol.INSTANCE);
437
438
                    	p_initChannel_1_.pipeline().addBefore("encoder", CommonTransformer.HANDLER_ENCODER_NAME,
439
                    			new VREncodeHandler(user)).addBefore("decoder", CommonTransformer.HANDLER_DECODER_NAME, new VRDecodeHandler(user));
440
                    }
441
                }
442
                /* --------- */
443
                
444
            }
445
        })).channel(oclass)).connect(p_181124_0_, p_181124_1_).syncUninterruptibly();
446
        return networkmanager;
447
    }
448
449
    /**
450
     * Prepares a clientside NetworkManager: establishes a connection to the socket supplied and configures the channel
451
     * pipeline. Returns the newly created instance.
452
     */
453
    public static NetworkManager provideLocalClient(SocketAddress address)
454
    {
455
        final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
456
        ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)CLIENT_LOCAL_EVENTLOOP.getValue())).handler(new ChannelInitializer<Channel>()
457
        {
458
            protected void initChannel(Channel p_initChannel_1_) throws Exception
459
            {
460
                p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
461
            }
462
        })).channel(LocalChannel.class)).connect(address).syncUninterruptibly();
463
        return networkmanager;
464
    }
465
466
    /**
467
     * Adds an encoder+decoder to the channel pipeline. The parameter is the secret key used for encrypted communication
468
     */
469
    public void enableEncryption(SecretKey key)
470
    {
471
        this.isEncrypted = true;
472
        this.channel.pipeline().addBefore("splitter", "decrypt", new NettyEncryptingDecoder(CryptManager.createNetCipherInstance(2, key)));
473
        this.channel.pipeline().addBefore("prepender", "encrypt", new NettyEncryptingEncoder(CryptManager.createNetCipherInstance(1, key)));
474
    }
475
476
    public boolean getIsencrypted()
477
    {
478
        return this.isEncrypted;
479
    }
480
481
    /**
482
     * Returns true if this NetworkManager has an active channel, false otherwise
483
     */
484
    public boolean isChannelOpen()
485
    {
486
        return this.channel != null && this.channel.isOpen();
487
    }
488
489
    public boolean hasNoChannel()
490
    {
491
        return this.channel == null;
492
    }
493
494
    /**
495
     * Gets the current handler for processing packets
496
     */
497
    public INetHandler getNetHandler()
498
    {
499
        return this.packetListener;
500
    }
501
502
    /**
503
     * If this channel is closed, returns the exit message, null otherwise.
504
     */
505
    public IChatComponent getExitMessage()
506
    {
507
        return this.terminationReason;
508
    }
509
510
    /**
511
     * Switches the channel to manual reading modus
512
     */
513
    public void disableAutoRead()
514
    {
515
        this.channel.config().setAutoRead(false);
516
    }
517
518
    public void setCompressionTreshold(int treshold)
519
    {
520
        if (treshold >= 0)
521
        {
522
            if (this.channel.pipeline().get("decompress") instanceof NettyCompressionDecoder)
523
            {
524
                ((NettyCompressionDecoder)this.channel.pipeline().get("decompress")).setCompressionTreshold(treshold);
525
            }
526
            else
527
            {
528
            	
529
            	/* ViaVersion */
530
            	if (ProtocolUtils.getProtocolName(ViaFabric.clientSideVersion).toLowerCase() != "1.8.x") {
531
            		Util.decodeEncodePlacement(channel.pipeline(), "decoder", "decompress", new NettyCompressionDecoder(treshold));
532
            	}else {
533
            		this.channel.pipeline().addBefore("decoder", "decompress", new NettyCompressionDecoder(treshold));
534
            	}
535
            	/* --------- */
536
            	
537
            	// Removed because viaversion
538
                //this.channel.pipeline().addBefore("decoder", "decompress", new NettyCompressionDecoder(treshold));
539
            
540
            }
541
542
            if (this.channel.pipeline().get("compress") instanceof NettyCompressionEncoder)
543
            {
544
                ((NettyCompressionEncoder)this.channel.pipeline().get("decompress")).setCompressionTreshold(treshold);
545
            }
546
            else
547
            {
548
            	
549
            	/* ViaVersion */
550
            	if (ProtocolUtils.getProtocolName(ViaFabric.clientSideVersion).toLowerCase() != "1.8.x") {
551
            		Util.decodeEncodePlacement(channel.pipeline(), "encoder", "compress", new NettyCompressionEncoder(treshold));
552
            	}else {
553
            		this.channel.pipeline().addBefore("encoder", "compress", new NettyCompressionEncoder(treshold));
554
            	}
555
            	/* --------- */
556
            	
557
            	// Removed because viaversion
558
                //this.channel.pipeline().addBefore("encoder", "compress", new NettyCompressionEncoder(treshold));
559
            }
560
        }
561
        else
562
        {
563
            if (this.channel.pipeline().get("decompress") instanceof NettyCompressionDecoder)
564
            {
565
                this.channel.pipeline().remove("decompress");
566
            }
567
568
            if (this.channel.pipeline().get("compress") instanceof NettyCompressionEncoder)
569
            {
570
                this.channel.pipeline().remove("compress");
571
            }
572
        }
573
    }
574
575
    public void checkDisconnected()
576
    {
577
        if (this.channel != null && !this.channel.isOpen())
578
        {
579
            if (!this.disconnected)
580
            {
581
                this.disconnected = true;
582
583
                if (this.getExitMessage() != null)
584
                {
585
                    this.getNetHandler().onDisconnect(this.getExitMessage());
586
                }
587
                else if (this.getNetHandler() != null)
588
                {
589
                    this.getNetHandler().onDisconnect(new ChatComponentText("Disconnected"));
590
                }
591
            }
592
            else
593
            {
594
                logger.warn("handleDisconnection() called twice");
595
            }
596
        }
597
    }
598
599
    static class InboundHandlerTuplePacketListener
600
    {
601
        private final Packet packet;
602
        private final GenericFutureListener <? extends Future <? super Void >> [] futureListeners;
603
604
        public InboundHandlerTuplePacketListener(Packet inPacket, GenericFutureListener <? extends Future <? super Void >> ... inFutureListeners)
605
        {
606
            this.packet = inPacket;
607
            this.futureListeners = inFutureListeners;
608
        }
609
    }
610
}

What this file does

sendPacket fires EventSendPacket at the top of the method and returns early when the event is cancelled; that interception point is what the module hooks to buffer packets, and it is also the reason the flush works. When onDisable replays through addToSendQueue, the network manager fires the same event, but the module is untoggled, so the dispatcher routes it to the no-op onEventWhenDisabled instead of the buffering onEvent, and the packet goes out on the channel.

anticheat Countering Checks

The anticheat code that detects or counters the techniques this module uses. Full source, with the detection mechanism explained below each box.

anticheat MorePackets (flush burst)

MorePackets.java127 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.moving.player;
16
17
import java.util.ArrayList;
18
import java.util.List;
19
20
import org.bukkit.Location;
21
import org.bukkit.entity.Player;
22
23
import fr.neatmonster.nocheatplus.actions.ParameterName;
24
import fr.neatmonster.nocheatplus.checks.Check;
25
import fr.neatmonster.nocheatplus.checks.CheckType;
26
import fr.neatmonster.nocheatplus.checks.ViolationData;
27
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
28
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
29
import fr.neatmonster.nocheatplus.checks.net.NetStatic;
30
import fr.neatmonster.nocheatplus.players.IPlayerData;
31
import fr.neatmonster.nocheatplus.utilities.StringUtil;
32
import fr.neatmonster.nocheatplus.utilities.location.PlayerLocation;
33
34
/**
35
 * The MorePackets check will try to identify players that send more than the usual
36
 * amount of move-packets to the server to be able to move faster than normal, without getting caught by the other
37
 * checks (flying/running).
38
 */
39
public class MorePackets extends Check {
40
41
    private final List<String> tags = new ArrayList<String>();
42
43
    /**
44
     * Instantiates a new more packets check.
45
     */
46
    public MorePackets() {
47
        super(CheckType.MOVING_MOREPACKETS);
48
    }
49
50
    /**
51
     * Check for speeding by sending too many packets. We assume 22 packets per
52
     * second to be legitimate, while 20 would be ideal. See
53
     * PlayerData.morePacketsFreq for the monitored amount of time and the
54
     * resolution. See NetStatic for the actual check code.
55
     * 
56
     * @param player
57
     * @param from
58
     * @param to
59
     * @param allowSetSetBack
60
     *            If to allow setting the set back location.
61
     * @param data
62
     * @param cc
63
     * @return
64
     */
65
    public Location check(final Player player, final PlayerLocation from, final PlayerLocation to, 
66
            final boolean allowSetSetBack, final MovingData data, final MovingConfig cc,
67
            final IPlayerData pData) {
68
        // Take time once, first:
69
        final long time = System.currentTimeMillis();
70
        final boolean debug = pData.isDebugActive(type);
71
72
        //    	if (from.isSamePos(to)) {
73
        //    		// Ignore moves with "just look" for now.
74
        //    		// TODO: Extra ActionFrequency for "just look" + use to burn, maybe also check individually.
75
        //    		return null;
76
        //    	}
77
78
        // Ensure we have a set back location.
79
        if (allowSetSetBack && !data.hasMorePacketsSetBack()){
80
            // TODO: Check if other set back is appropriate or if to set/reset on other events.
81
            if (data.hasSetBack()) {
82
                data.setMorePacketsSetBackFromSurvivalfly();
83
            }
84
            else {
85
                data.setMorePacketsSetBack(from);
86
            }
87
        }
88
89
        // Check for a violation of the set limits.
90
        tags.clear();
91
        final double violation = NetStatic.morePacketsCheck(data.morePacketsFreq, time, 1f, cc.morePacketsEPSMax, cc.morePacketsEPSIdeal, data.morePacketsBurstFreq, cc.morePacketsBurstPackets, cc.morePacketsBurstDirect, cc.morePacketsBurstEPM, tags);
92
93
        // Process violation result.
94
        if (violation > 0.0) {
95
            // Increment violation level.
96
            data.morePacketsVL = violation; // TODO: Accumulate somehow [e.g. always += 1, decrease with continuous moving without violation]?
97
98
            // Violation handling.
99
            final ViolationData vd = new ViolationData(this, player, data.morePacketsVL, violation, cc.morePacketsActions);
100
            if (debug || vd.needsParameters()) {
101
                vd.setParameter(ParameterName.PACKETS, Integer.toString(new Double(violation).intValue()));
102
                vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
103
            }
104
            if (executeActions(vd).willCancel()) {
105
                // Set to cancel the move.
106
                /*
107
                 * TODO: Harmonize with MovingUtil.getApplicableSetBackLocation
108
                 * (somehow include the desired set back type / loc / context).
109
                 */
110
                return data.hasMorePacketsSetBack() ? data.getMorePacketsSetBack() : data.getSetBack(to); // TODO
111
            }
112
        } 
113
        else if (allowSetSetBack && data.getMorePacketsSetBackAge() > cc.morePacketsSetBackAge) {
114
            // Update the set back location. (CHANGED to only update, if not a violation.)
115
            // (Might update whenever newTo == null)
116
            data.setMorePacketsSetBack(from);
117
            if (debug) {
118
                debug(player, "Update set back (morepackets) to from.");
119
            }
120
        }
121
122
        // No set back.
123
        return null;
124
125
    }
126
127
}

How it counteracts this module

NoCheatPlus MorePackets buckets every arriving move into 500ms windows against a 22 packets per second ceiling and a 15-packet half-second burst path. The disable flush delivers the entire blink buffer in one tick: seconds of movement compressed into a single burst, which trips the newest-bucket burst path and pushes the window accumulator above the ceiling, and a blink long enough to accumulate hundreds of packets crosses the direct-violation and kick thresholds. The keepalive exemptions do not help because the movement replay is the entire buffer at once.

anticheat SurvivalFly (stale replay envelope)

SurvivalFly.java2531 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.moving.player;
16
17
import java.util.ArrayList;
18
import java.util.Collection;
19
import java.util.Locale;
20
21
import org.bukkit.ChatColor;
22
import org.bukkit.Location;
23
import org.bukkit.Material;
24
import org.bukkit.entity.LivingEntity;
25
import org.bukkit.entity.Player;
26
import org.bukkit.util.Vector;
27
28
import fr.neatmonster.nocheatplus.NCPAPIProvider;
29
import fr.neatmonster.nocheatplus.actions.ParameterName;
30
import fr.neatmonster.nocheatplus.checks.Check;
31
import fr.neatmonster.nocheatplus.checks.CheckType;
32
import fr.neatmonster.nocheatplus.checks.ViolationData;
33
import fr.neatmonster.nocheatplus.checks.combined.CombinedData;
34
import fr.neatmonster.nocheatplus.checks.combined.Improbable;
35
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
36
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
37
import fr.neatmonster.nocheatplus.checks.moving.envelope.PhysicsEnvelope;
38
import fr.neatmonster.nocheatplus.checks.moving.envelope.PhysicsGroundResolver;
39
import fr.neatmonster.nocheatplus.checks.moving.envelope.workaround.LostGround;
40
import fr.neatmonster.nocheatplus.checks.moving.envelope.workaround.MagicWorkarounds;
41
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerKeyboardInput;
42
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerKeyboardInput.ForwardDirection;
43
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerKeyboardInput.StrafeDirection;
44
import fr.neatmonster.nocheatplus.checks.moving.model.LiftOffEnvelope;
45
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerMoveData;
46
import fr.neatmonster.nocheatplus.checks.workaround.WRPT;
47
import fr.neatmonster.nocheatplus.compat.AlmostBoolean;
48
import fr.neatmonster.nocheatplus.compat.Bridge1_13;
49
import fr.neatmonster.nocheatplus.compat.Bridge1_9;
50
import fr.neatmonster.nocheatplus.compat.BridgeMisc;
51
import fr.neatmonster.nocheatplus.compat.SchedulerHelper;
52
import fr.neatmonster.nocheatplus.compat.blocks.changetracker.BlockChangeTracker;
53
import fr.neatmonster.nocheatplus.compat.blocks.changetracker.BlockChangeTracker.Direction;
54
import fr.neatmonster.nocheatplus.compat.versions.ClientVersion;
55
import fr.neatmonster.nocheatplus.components.modifier.IAttributeAccess;
56
import fr.neatmonster.nocheatplus.components.registry.event.IGenericInstanceHandle;
57
import fr.neatmonster.nocheatplus.logging.Streams;
58
import fr.neatmonster.nocheatplus.players.DataManager;
59
import fr.neatmonster.nocheatplus.players.IPlayerData;
60
import fr.neatmonster.nocheatplus.utilities.CheckUtils;
61
import fr.neatmonster.nocheatplus.utilities.StringUtil;
62
import fr.neatmonster.nocheatplus.utilities.collision.CollisionUtil;
63
import fr.neatmonster.nocheatplus.utilities.collision.supportingblock.SupportingBlockUtils;
64
import fr.neatmonster.nocheatplus.utilities.location.PlayerLocation;
65
import fr.neatmonster.nocheatplus.utilities.map.BlockFlags;
66
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
67
import fr.neatmonster.nocheatplus.utilities.math.MathUtil;
68
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
69
import fr.neatmonster.nocheatplus.utilities.moving.Magic;
70
import fr.neatmonster.nocheatplus.utilities.moving.MovingUtil;
71
72
/**
73
 * The counterpart to the CreativeFly check, designed for ordinary gameplay (Survival/Adventure)
74
 */
75
@SuppressWarnings({"UnstableApiUsage", "StatementWithEmptyBody"})
76
public class SurvivalFly extends Check {
77
78
    // TODO: Unification of vertical and horizontal motion. Also to reduce the number of RichEntityLocation#collide() calls.
79
80
    /** To join some tags with moving check violations. */
81
    private final ArrayList<String> tags = new ArrayList<>(15);
82
    
83
    private final ArrayList<String> justUsedWorkarounds = new ArrayList<>();
84
    
85
    private final BlockChangeTracker blockChangeTracker;
86
    
87
    private final IGenericInstanceHandle<IAttributeAccess> attributeAccess = NCPAPIProvider.getNoCheatPlusAPI().getGenericInstanceHandle(IAttributeAccess.class);
88
    
89
    /**
90
     * The vertical component of liquid push (water/lava).
91
     * This is computed in hdistrel and then used by vidstrel to avoid having to call the getLiquidPush() method twice.
92
     * When computing the horizontal liquid push, the way Mojang coded the function to get the liquid's flowing force
93
     * to calculate horizontal speed with, also affects the vertical speed (See comment in {@link fr.neatmonster.nocheatplus.utilities.location.RichEntityLocation#getFlowForceVector(int, int, int, long)}.
94
     */
95
    private double verticalLiquidPushComponent = 0.0;
96
    
97
    
98
    public SurvivalFly() {
99
        super(CheckType.MOVING_SURVIVALFLY);
100
        blockChangeTracker = NCPAPIProvider.getNoCheatPlusAPI().getBlockChangeTracker();
101
    }
102
    
103
    
104
    /**
105
     * Checks a player
106
     *
107
     * @param multiMoveCount
108
     *            0: Ordinary, 1/2/(...): first/second/(...) part of a split move.
109
     * @param isNormalOrPacketSplitMove
110
     *           Flag to indicate if the packet-based split move mechanic is used instead of the Bukkit-based one (or the move was not split)
111
     *
112
     * @return The Location where to set back the player to. Null in case of no violation.
113
     */
114
    public Location check(final Player player, final PlayerLocation from, final PlayerLocation to,
115
                          final int multiMoveCount, final MovingData data, final MovingConfig cc,
116
                          final IPlayerData pData, final int tick, final long now,
117
                          final boolean useBlockChangeTracker, final boolean isNormalOrPacketSplitMove) {
118
        /*
119
          TODO: Ideally, all this data should really be set outside SurvivalFly (in the MovingListener), since they can be useful
120
          for other checks / stuff.
121
         */
122
        tags.clear();
123
        justUsedWorkarounds.clear();
124
        // Shortcuts:
125
        final boolean debug = pData.isDebugActive(type);
126
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
127
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
128
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
129
        /*
130
         * Actually forgot what this does. But quick guess might be idle move (0,0,0) on count 1 and riptide on count 2.
131
         * TODO: Is this supposed to be here? (Move in MovingListener at the beginning of checkPayerMove?)
132
         */
133
        if (lastMove.tridentRelease.decideOptimistically() && multiMoveCount == 2 && lastMove.yDistance == 0.0) {
134
            thisMove.tridentRelease = AlmostBoolean.YES;
135
            lastMove.tridentRelease = AlmostBoolean.NO;
136
        }
137
        /* Regular and past fromOnGround */
138
        final boolean fromOnGround = from.isOnGround() || useBlockChangeTracker && from.isOnGroundOpportune(cc.yOnGround, 0L, blockChangeTracker, data.blockChangeRef, tick);
139
        /* Regular and past toOnGround */
140
        final boolean toOnGround = to.isOnGround() || useBlockChangeTracker && to.isOnGroundOpportune(cc.yOnGround, 0L, blockChangeTracker, data.blockChangeRef, tick);  // TODO: Work in the past ground stuff differently (thisMove, touchedGround?, from/to ...)
141
        /* Moving onto/into everything that isn't in air (liquids, stuck-speed, ground, ALL) */
142
        final boolean resetTo = toOnGround || to.isResetCond();
143
        /* Moving off from anything that is not air (liquids, stuck-speed, ground, ALL). */
144
        final boolean resetFrom = fromOnGround || from.isResetCond();
145
        // Run lostground checks.
146
        LostGround.runLostGroundChecks(player, from, to, thisMove.hDistance, thisMove.yDistance, lastMove, data, cc, useBlockChangeTracker ? blockChangeTracker : null, tags);
147
148
        // Set workarounds for the registry
149
        data.ws.setJustUsedIds(justUsedWorkarounds);
150
151
        // Recover from data removal (somewhat random insertion point).
152
        if (data.liftOffEnvelope == LiftOffEnvelope.UNKNOWN) {
153
            data.adjustLiftOffEnvelope(from);
154
        }
155
156
        // Adjust block properties (friction, block speed etc...)
157
        data.adjustMediumProperties(player, from);
158
        
159
        // Ground somehow appeared out of thin air (block place).
160
        // This move is registered as "coming from ground" despite the player not having moved onto ground with the previous move, which was fully in air.
161
        if (thisMove.touchedGround) {
162
            if (multiMoveCount == 0 && thisMove.from.onGround && PhysicsEnvelope.inAir(lastMove) 
163
                && TrigUtil.isSamePosAndLook(thisMove.from, lastMove.to)) {
164
                data.setSetBack(from);
165
                if (debug) {
166
                    debug(player, "Ground appeared due to a block-place: adjust set-back location.");
167
                }
168
            }
169
        }
170
171
        // Decrease bunnyhop delay counter
172
        if (data.jumpDelay > 0) {
173
            data.jumpDelay--;
174
        }
175
      
176
177
178
        /////////////////////////////////////
179
        // Horizontal move                ///
180
        /////////////////////////////////////
181
        double hAllowedDistance, hDistanceAboveLimit, hFreedom;
182
        double[] resGlide = processGliding(from, to, pData, data, player, isNormalOrPacketSplitMove, fromOnGround, toOnGround, debug);
183
        // Set the allowed distance and determine the distance above limit
184
        double[] hRes = Bridge1_9.isGliding(player) ? resGlide : prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, false);
185
        hAllowedDistance = hRes[0];
186
        hDistanceAboveLimit = hRes[1];
187
        // Beyond limit? Check if there may have been a reason for this (and try to re-estimate if needed)
188
        if (hDistanceAboveLimit > 0.0) {
189
            double[] res = hDistAfterFailure(player, from, to, hAllowedDistance, hDistanceAboveLimit, thisMove, lastMove, debug, data, cc, pData, tick, useBlockChangeTracker, fromOnGround, toOnGround, isNormalOrPacketSplitMove);
190
            hAllowedDistance = res[0];
191
            hDistanceAboveLimit = res[1];
192
            hFreedom = res[2];
193
        }
194
        else {
195
            // Clear active velocity if the distance is within limit (clearly not needed. :))
196
            //data.clearActiveHorVel();
197
            hFreedom = 0.0;
198
        }
199
200
201
        /////////////////////////////////////
202
        // Vertical move                  ///
203
        /////////////////////////////////////
204
        // Order of checking in EntityLiving.java water -> lava -> gliding -> air
205
        // TODO: Clean-up this left-over bit of the old implementation (respect MC's order)
206
        double yAllowedDistance, yDistanceAboveLimit;
207
        if (Bridge1_9.isGliding(player)) {
208
            yAllowedDistance = resGlide[2];
209
            yDistanceAboveLimit = resGlide[3];
210
        }
211
        else {
212
            final double[] res = vDistRel(player, from, fromOnGround, resetFrom, to, toOnGround, resetTo, thisMove.yDistance, isNormalOrPacketSplitMove, lastMove, data, pData, false, debug, useBlockChangeTracker );
213
            yAllowedDistance = res[0];
214
            yDistanceAboveLimit = res[1];
215
        }
216
217
        ////////////////////////////
218
        // Debug output.          //
219
        ////////////////////////////
220
        final int tagsLength;
221
        if (debug) {
222
            outputDebug(player, to, from, data, thisMove.hDistance, hAllowedDistance, hFreedom, thisMove.yDistance, yAllowedDistance, fromOnGround, resetFrom, toOnGround, resetTo, thisMove);
223
            tagsLength = tags.size();
224
            data.ws.setJustUsedIds(null);
225
        }
226
        else tagsLength = 0; // JIT vs. IDE.
227
228
229
        //////////////////////////////////////
230
        // Handle violations               ///
231
        //////////////////////////////////////
232
        final boolean inAir = PhysicsEnvelope.inAir(thisMove);
233
        final double result = (Math.max(hDistanceAboveLimit, 0.0) + Math.max(yDistanceAboveLimit, 0.0)) * 100D;
234
        if (result > 0.0) {
235
            final Location vLoc = handleViolation(result, player, from, to, data, cc);
236
            if (inAir) {
237
                data.sfVLInAir = true;
238
            }
239
            // Request a new to-location
240
            if (vLoc != null) {
241
                return vLoc;
242
            }
243
        }
244
        else {
245
            if (canRelaxVL(data, cc, inAir, lastMove, thisMove)) {
246
                // Relax VL.
247
                data.survivalFlyVL *= 0.95;
248
            }
249
        }
250
251
252
        //////////////////////////////////////////////////////////////////////////////////////////////
253
        //  Set data for normal move or violation without cancel (cancel would have returned above) //
254
        //////////////////////////////////////////////////////////////////////////////////////////////
255
        // Adjust lift off envelope to medium
256
        if (thisMove.to.inPowderSnow) {
257
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_POWDER_SNOW;
258
        }
259
        else if (thisMove.to.inWeb) {
260
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_WEBS;
261
        }
262
        else if (thisMove.to.inBerryBush) {
263
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_SWEET_BERRY;
264
        }
265
        else if (thisMove.to.onHoneyBlock) {
266
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_HONEY_BLOCK;
267
        }
268
        else if (resetTo) {
269
            data.liftOffEnvelope = LiftOffEnvelope.NORMAL;
270
        }
271
        else if (thisMove.from.inPowderSnow) {
272
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_POWDER_SNOW;
273
        }
274
        else if (thisMove.from.inWeb) {
275
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_WEBS;
276
        }
277
        else if (thisMove.from.inBerryBush) {
278
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_SWEET_BERRY;
279
        }
280
        else if (thisMove.from.onHoneyBlock) {
281
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_HONEY_BLOCK;
282
        }
283
        else if (resetFrom || thisMove.touchedGround) {
284
            data.liftOffEnvelope = LiftOffEnvelope.NORMAL;
285
        }
286
        else {
287
            // Air, Keep medium.
288
        }
289
290
        // Apply reset conditions.
291
        if (resetTo) {
292
            // Reset data.
293
            data.setSetBack(to);
294
            data.sfJumpPhase = 0;
295
        }
296
        // The player moved from ground.
297
        else if (resetFrom) {
298
            data.setSetBack(from);
299
            data.sfJumpPhase = 1; // This event is already in air.
300
        }
301
        else {
302
            data.sfJumpPhase ++;
303
            if (!Double.isInfinite(Bridge1_9.getLevitationAmplifier(player))
304
                || Bridge1_13.isRiptiding(player)
305
                || Bridge1_9.isGliding(player)) {
306
                data.setSetBack(to);
307
            }
308
        }
309
310
        // Adjust not in-air stuff.
311
        if (!inAir) {
312
            data.ws.resetConditions(WRPT.G_RESET_NOTINAIR);
313
            data.sfVLInAir = false;
314
        }
315
316
        // Update unused velocity tracking.
317
        // TODO: Hide and seek with API.
318
        // TODO: Pull down tick / timing data (perhaps add an API object for millis + source + tick + sequence count (+ source of sequence count).
319
        if (debug) {
320
            // TODO: Only update, if velocity is queued at all.
321
            data.getVerticalVelocityTracker().updateBlockedState(tick,
322
                    // Assume blocked with being in web/water, despite not entirely correct.
323
                    thisMove.headObstructed || thisMove.from.resetCond,
324
                    // (Similar here.)
325
                    thisMove.touchedGround || thisMove.to.resetCond);
326
            // TODO: TEST: Check unused velocity here too. (Should have more efficient process, pre-conditions for checking.)
327
            UnusedVelocity.checkUnusedVelocity(player, type, data, cc);
328
        }
329
330
        // Adjust various speed/friction factors (both h/v).
331
        data.lastFrictionVertical = data.nextFrictionVertical;
332
        data.lastFrictionHorizontal = data.nextFrictionHorizontal;
333
        data.lastStuckInBlockVertical = data.nextStuckInBlockVertical;
334
        data.lastStuckInBlockHorizontal = data.nextStuckInBlockHorizontal;
335
        data.lastBlockSpeedMultiplier = data.nextBlockSpeedMultiplier;
336
        data.lastInertia = data.nextInertia;
337
        data.lastLevitationLevel = !Double.isInfinite(Bridge1_9.getLevitationAmplifier(player)) ? Bridge1_9.getLevitationAmplifier(player) + 1 : 0.0;
338
        data.lastGravity = data.nextGravity;
339
        data.lastCollidingEntitiesLocations = CollisionUtil.getCollidingEntitiesLocations(player);
340
        cData.wasSprinting = pData.isSprinting();
341
        cData.wasPressingShift = pData.isShiftKeyPressed();
342
        cData.wasSlowFalling = !Double.isInfinite(Bridge1_13.getSlowfallingAmplifier(player));
343
        cData.wasLevitating = !Double.isInfinite(Bridge1_9.getLevitationAmplifier(player));
344
        // Log tags added after violation handling.
345
        if (debug && tags.size() > tagsLength) {
346
            logPostViolationTags(player);
347
        }
348
        // Nothing to do, newTo (MovingListener) stays null
349
        return null;
350
    }
351
    
352
    
353
    /**
354
     * Check if the violation level may decrease.
355
     * 
356
     * @param data
357
     * @param cc
358
     * @param inAir
359
     * @param lastMove
360
     * @param thisMove
361
     * @return
362
     */
363
    private boolean canRelaxVL(MovingData data, MovingConfig cc, boolean inAir, PlayerMoveData lastMove, PlayerMoveData thisMove) {
364
        // Slowly reduce the level with each event, if violations have not recently happened.
365
        return data.getPlayerMoveCount() - data.sfVLMoveCount > cc.survivalFlyVLFreezeCount
366
                && (!cc.survivalFlyVLFreezeInAir || !inAir
367
                // Favor bunny-hopping slightly: clean descend.
368
                || !data.sfVLInAir
369
                && data.liftOffEnvelope == LiftOffEnvelope.NORMAL
370
                && lastMove.toIsValid
371
                && lastMove.yDistance < -Magic.GRAVITY_MIN
372
                && thisMove.yDistance - lastMove.yDistance < -Magic.GRAVITY_MIN);
373
    }
374
    
375
    
376
    /**
377
     * A check to prevent players from bed-flying.
378
     * To be called on PlayerBedLeaveEvent(s)
379
     * (This increases VL and sets tag only. Setback is done in MovingListener).
380
     *
381
     * @return If to prevent action (use the setback location of survivalfly).
382
     */
383
    public boolean checkBed(final Player player, final MovingConfig cc, final MovingData data) {
384
        boolean cancel = false;
385
        // Check if the player had been in bed at all.
386
        if (!data.wasInBed) {
387
            // Violation ...
388
            tags.add("bedfly");
389
            data.survivalFlyVL += 100D;
390
            Improbable.check(player, (float) 5.0, System.currentTimeMillis(), "moving.survivalfly.bedfly", DataManager.getPlayerData(player));
391
            final ViolationData vd = new ViolationData(this, player, data.survivalFlyVL, 100D, cc.survivalFlyActions);
392
            if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
393
            cancel = executeActions(vd).willCancel();
394
        }
395
        // Nothing detected.
396
        else data.wasInBed = false;
397
        return cancel;
398
    }
399
400
401
    /**
402
     * Check for push/pull by pistons, alter data appropriately (blockChangeId).
403
     */
404
    private double[] getVerticalBlockMoveResult(final double yDistance, final PlayerLocation from, final PlayerLocation to, final MovingData data) {
405
        /*
406
         * TODO: Pistons pushing horizontally allow similar/same upwards
407
         * (downwards?) moves (possibly all except downwards, which is hard to
408
         * test :p).
409
         */
410
        // TODO: Allow push up to 1.0 (or 0.65 something) even beyond block borders, IF COVERED [adapt PlayerLocation].
411
        // TODO: Other conditions/filters ... ?
412
        // Push (/pull) up.
413
        if (yDistance > 0.0) {
414
            if (yDistance <= 1.015) {
415
                /*
416
                 * (Full blocks: slightly more possible, ending up just above
417
                 * the block. Bounce allows other end positions.)
418
                 */
419
                // TODO: Is the air block wich the slime block is pushed onto really in? 
420
                if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, Direction.Y_POS, Math.min(yDistance, 1.0))) {
421
                    if (yDistance > 1.0) {
422
                        if (to.getY() - to.getBlockY() >= 0.015) {
423
                            // Exclude ordinary cases for this condition.
424
                            return null;
425
                        }
426
                    }
427
                    tags.add("blkmv_y_pos");
428
                    final double maxDistYPos = yDistance; //1.0 - (from.getY() - from.getBlockY()); // TODO: Margin ?
429
                    return new double[]{maxDistYPos, 0.0};
430
                }
431
            }
432
        }
433
        // Push (/pull) down.
434
        else if (yDistance < 0.0 && yDistance >= -1.0) {
435
            if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, Direction.Y_NEG, -yDistance)) {
436
                tags.add("blkmv_y_neg");
437
                final double maxDistYNeg = yDistance; // from.getY() - from.getBlockY(); // TODO: Margin ?
438
                return new double[]{maxDistYNeg, 0.0};
439
            }
440
        }
441
        // Nothing found.
442
        return null;
443
    }
444
445
446
    /**
447
     * Determine the allowed h / v distance for gliding.
448
     * Handled in its own method because of vertical and horizontal motion being too intertwined to separate (y-distance changes relate to h-distance changes). <br>
449
     * Consistency checks are done within the {@link fr.neatmonster.nocheatplus.checks.combined.CombinedListener}.<br>
450
     * <li> NOTE: this should be called with {@link Bridge1_9#isGliding(LivingEntity)} not {@link Bridge1_9#isGlidingWithElytra(Player)}, because the client does not check for elytra to apply the corresponding motion (EntityLiving, travel())</li>
451
     *
452
     * @return the allowed xyz distances + distances above limit.
453
     */
454
    private double[] processGliding(final PlayerLocation from, final PlayerLocation to, final IPlayerData pData, final MovingData data,
455
                                    final Player player, boolean isNormalOrPacketSplitMove, final boolean fromOnGround, final boolean toOnGround, final boolean debug) {
456
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
457
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
458
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
459
        double yDistanceAboveLimit = 0.0, hDistanceAboveLimit = 0.0;
460
        // TODO: What with gliding + rocket boosting + riptiding + bouncing on slimes/beds while riptiding? LMAO
461
        // Beats me why Mojang keeps letting players perform such ridiculous moves.
462
        if (!Bridge1_9.isGliding(player)) {
463
            // No Gliding, no deal
464
            return new double[] {thisMove.hDistance, 0.0, thisMove.yDistance, 0.0};
465
        }
466
        // Note: WASD key presses, as well as sneaking and item-use are irrelevant when gliding.
467
        // Initialize speed.
468
        thisMove.xAllowedDistance = lastMove.toIsValid ? lastMove.xDistance : 0.0;
469
        thisMove.yAllowedDistance = lastMove.toIsValid ? lastMove.yDistance : 0.0;
470
        thisMove.zAllowedDistance = lastMove.toIsValid ? lastMove.zDistance : 0.0;
471
        // Reset momentum if collided with something on the previous tick.
472
        doWallCollision(lastMove, thisMove);
473
        // Throttle speed if stuck in a block.
474
        if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) {
475
            if (data.lastStuckInBlockVertical != 1.0) {
476
                thisMove.yAllowedDistance = 0.0;
477
            }
478
            if (data.lastStuckInBlockHorizontal != 1.0) {
479
                thisMove.xAllowedDistance = thisMove.zAllowedDistance = 0.0;
480
            }
481
        }
482
        // Reset speed if judged to be negligible.
483
        checkNegligibleMomentum(pData, thisMove);
484
        checkNegligibleMomentumVertical(pData, thisMove, null);
485
        // Yes, players can glide and riptide at the same time, increasing speed at a faster rate than chunks can load...
486
        // Surely a questionable decision on Mojang's part.
487
        // NOTE: For the elytra, this has to be done before applying gravity and other motion changes.
488
        if (thisMove.tridentRelease.decideOptimistically()) {
489
            thisMove.tridentRelease = AlmostBoolean.YES;
490
            Vector riptideVelocity = to.getRiptideVelocity(false); // Cannot glide while on ground, so no need to check for it.
491
            thisMove.xAllowedDistance += riptideVelocity.getX();
492
            thisMove.yAllowedDistance += riptideVelocity.getY();
493
            thisMove.zAllowedDistance += riptideVelocity.getZ();
494
        }
495
        // TODO: Reduce verbosity (at least, make it easier to look at)
496
        Vector viewVector = TrigUtil.getLookingDirection(to, player);
497
        float radianPitch = to.getPitch() * TrigUtil.toRadians;
498
        // Horizontal length of the look direction
499
        double viewVecHorizontalLength = MathUtil.dist(viewVector.getX(), viewVector.getZ());
500
        // Horizontal length of the movement
501
        double thisMoveHDistance = MathUtil.dist(thisMove.xAllowedDistance, thisMove.zAllowedDistance); // NOTE: MUST BE the ALLOWED distances.
502
        // Overall length of the look direction.
503
        double viewVectorLength = viewVector.length();
504
        // Mojang switched from their own cosine function to the standard Math.cos() one in 1.18.2
505
        double cosPitch = pData.getClientVersion().isAtMost(ClientVersion.V_1_18_2) ? TrigUtil.cos((double)radianPitch) : Math.cos((double)radianPitch);
506
        cosPitch = cosPitch * cosPitch * Math.min(1.0, viewVectorLength / 0.4);
507
        // Base gravity when gliding.
508
        thisMove.yAllowedDistance += (cData.wasSlowFalling && lastMove.yDistance <= 0.0 ? Magic.SLOW_FALL_GRAVITY : Magic.DEFAULT_GRAVITY) * (-1.0 + cosPitch * 0.75);
509
        double baseSpeed;
510
        if (thisMove.yAllowedDistance < 0.0 && viewVecHorizontalLength > 0.0) {
511
            // Slow down.
512
            baseSpeed = thisMove.yAllowedDistance * -0.1 * cosPitch;
513
            thisMove.xAllowedDistance += viewVector.getX() * baseSpeed / viewVecHorizontalLength;
514
            thisMove.yAllowedDistance += baseSpeed;
515
            thisMove.zAllowedDistance += viewVector.getZ() * baseSpeed / viewVecHorizontalLength;
516
        }
517
        if (radianPitch < 0.0 && viewVecHorizontalLength > 0.0) {
518
            // Looking down speeds up the player.
519
            baseSpeed = thisMoveHDistance * (double) (-TrigUtil.sin(radianPitch)) * 0.04;
520
            thisMove.xAllowedDistance += -viewVector.getX() * baseSpeed / viewVecHorizontalLength;
521
            thisMove.yAllowedDistance += baseSpeed * 3.2;
522
            thisMove.zAllowedDistance += -viewVector.getZ() * baseSpeed / viewVecHorizontalLength;
523
        }
524
        if (viewVecHorizontalLength > 0.0) {
525
            // Accelerate
526
            thisMove.xAllowedDistance += (viewVector.getX() / viewVecHorizontalLength * thisMoveHDistance - thisMove.xAllowedDistance) * 0.1;
527
            thisMove.zAllowedDistance += (viewVector.getZ() / viewVecHorizontalLength * thisMoveHDistance - thisMove.zAllowedDistance) * 0.1;
528
        }
529
        // Boosted with a firework: propel the player.
530
        if (data.fireworksBoostDuration > 0) {
531
            // TODO: Firework netcode is horrible (a single firework can tick twice on the same tick, skipping the subsequent one), so simply applying the increase of speed won't cut it.
532
            // Not even sure if we can predict this at all without some kind of hacks / workarounds.
533
            thisMove.xAllowedDistance += viewVector.getX() * 0.1 + (viewVector.getX() * 1.5 - thisMove.xAllowedDistance) * 0.5;
534
            thisMove.yAllowedDistance += viewVector.getY() * 0.1 + (viewVector.getY() * 1.5 - thisMove.yAllowedDistance) * 0.5;
535
            thisMove.zAllowedDistance += viewVector.getZ() * 0.1 + (viewVector.getZ() * 1.5 - thisMove.zAllowedDistance) * 0.5;
536
        }
537
        // Friction here. (TEST)
538
        // Note about inertia: the game assigns the radian pitch to the "f" variable, which is the variable used to apply friction at the end of the tick, _normally_.
539
        // However, with gliding, the game does not use the f variable at the end of the tick, but instead applies the magic value of 0.99.
540
        thisMove.xAllowedDistance *= 0.99;
541
        thisMove.yAllowedDistance *= data.lastFrictionVertical;
542
        thisMove.zAllowedDistance *= 0.99;
543
        // Stuck-speed with the updated multiplier (both at the end)
544
        if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
545
            thisMove.xAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
546
            thisMove.yAllowedDistance *= (double) data.nextStuckInBlockVertical;
547
            thisMove.zAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
548
        }
549
        // Collisions last.
550
        Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, thisMove.yAllowedDistance, thisMove.zAllowedDistance), fromOnGround || thisMove.fromLostGround, from.getBoundingBox());
551
        thisMove.collideX = collisionVector.getX() != thisMove.xAllowedDistance;
552
        thisMove.collideY = collisionVector.getY() != thisMove.yAllowedDistance;
553
        thisMove.collideZ = collisionVector.getZ() != thisMove.zAllowedDistance;
554
        thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
555
        thisMove.xAllowedDistance = collisionVector.getX();
556
        thisMove.yAllowedDistance = collisionVector.getY();
557
        thisMove.zAllowedDistance = collisionVector.getZ();
558
559
        // Can a vertical workaround apply? If so, override the prediction.
560
        if (MagicWorkarounds.checkPostPredictWorkaround(data, fromOnGround, toOnGround, from, to, thisMove.yAllowedDistance, player, isNormalOrPacketSplitMove)) {
561
            thisMove.yAllowedDistance = thisMove.yDistance;
562
        }
563
        
564
        ////////////////////////////
565
        /// Calculate offests     //
566
        ////////////////////////////
567
        /* Expected difference from current to allowed */
568
        final double offsetV = thisMove.yDistance - thisMove.yAllowedDistance;
569
        if (Math.abs(offsetV) < Magic.PREDICTION_EPSILON) {
570
            // Accuracy margin.
571
        }
572
        else {
573
            // If velocity can be used for compensation, use it.
574
            if (data.getOrUseVerticalVelocity(thisMove.yDistance).isEmpty()) {
575
                yDistanceAboveLimit = Math.max(yDistanceAboveLimit, Math.abs(offsetV));
576
                tags.add("vdistrel");
577
            }
578
        }
579
580
        thisMove.hAllowedDistance = MathUtil.dist(thisMove.xAllowedDistance, thisMove.zAllowedDistance);
581
        final double offsetH = thisMove.hDistance - thisMove.hAllowedDistance;
582
        if (offsetH < Magic.PREDICTION_EPSILON) {
583
            // Accuracy margin.
584
        }
585
        else {
586
            hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offsetH);
587
            if (hDistanceAboveLimit > 0.0) {
588
                tags.add("hdistrel");
589
            }
590
        }
591
        if (debug) {
592
            player.sendMessage(ChatColor.RED + "[SurvivalFly] vdistrel: predict=" + StringUtil.fdec6.format(thisMove.yAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.yDistance) + ", offset=" + StringUtil.fdec6.format(offsetV));
593
            player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] hdistrel: predict=" + StringUtil.fdec6.format(thisMove.hAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.hDistance) + ", offset=" + StringUtil.fdec6.format(offsetH));
594
        }
595
        return new double[]{thisMove.hAllowedDistance, hDistanceAboveLimit, thisMove.yAllowedDistance, yDistanceAboveLimit};
596
    }
597
    
598
    /**
599
     * Reset the given speed upon wall collision.
600
     * 
601
     * @param lastMove
602
     * @param thisMove
603
     */
604
    private void doWallCollision(PlayerMoveData lastMove, PlayerMoveData thisMove) {
605
        if (lastMove.collideX) {
606
            thisMove.xAllowedDistance = 0.0;
607
        }
608
        if (lastMove.collideZ) {
609
            thisMove.zAllowedDistance = 0.0;
610
        }
611
    }
612
    
613
    /**
614
     * Check if the allowed speed set in thisMove should be canceled due to it being lower than the negligible speed threshold. <br>
615
     * (Horizontal only)
616
     * 
617
     * @param pData
618
     * @param thisMove
619
     */
620
    private void checkNegligibleMomentum(IPlayerData pData, PlayerMoveData thisMove) {
621
        if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_21_5)) {
622
            // This condition was added on 1.21.5. If the horizontal distance squared is below 0.000009 and the entity is a player, both horizontal momenta are set to 0.0.
623
            // This means that both x/z momenta can be reset even if one of them is above the threshold, as long as the overall horizontal momentum is below the threshold.
624
            // EntityLiving.java -> aiStep
625
            // We use the unchecked hDistance for performance reasons (no sqrt needed).
626
            if (thisMove.hDistance < Magic.NEGLIGIBLE_SPEED_THRESHOLD) {
627
                thisMove.xAllowedDistance = 0.0;
628
                thisMove.zAllowedDistance = 0.0;
629
            }
630
        }
631
        else if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_9)) {
632
            if (Math.abs(thisMove.xAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD) {
633
                thisMove.xAllowedDistance = 0.0;
634
            }
635
            if (Math.abs(thisMove.zAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD) {
636
                thisMove.zAllowedDistance = 0.0;
637
            }
638
        }
639
        else {
640
            // In 1.8 and lower, momentum is compared to 0.005 instead.
641
            if (Math.abs(thisMove.xAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD_LEGACY) {
642
                thisMove.xAllowedDistance = 0.0;
643
            }
644
            if (Math.abs(thisMove.zAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD_LEGACY) {
645
                thisMove.zAllowedDistance = 0.0;
646
            }
647
        }
648
    }
649
    
650
    /**
651
     * Check if the allowed speed set in thisMove should be canceled due to it being lower than the negligible speed threshold. <br>
652
     * (Vertical only).
653
     * 
654
     * @param pData
655
     * @param thisMove
656
     * @param yTheoreticalDistance
657
     */
658
    private void checkNegligibleMomentumVertical(IPlayerData pData, PlayerMoveData thisMove, double[] yTheoreticalDistance) {
659
        final double threshold = pData.getClientVersion().isAtLeast(ClientVersion.V_1_9) ? Magic.NEGLIGIBLE_SPEED_THRESHOLD : Magic.NEGLIGIBLE_SPEED_THRESHOLD_LEGACY;
660
        final boolean direct = yTheoreticalDistance == null;
661
        if (direct) {
662
            if (Math.abs(thisMove.yAllowedDistance) < threshold) {
663
                thisMove.yAllowedDistance = 0.0;
664
            }
665
        } else {
666
            for (int i = 0; i < yTheoreticalDistance.length; i++) {
667
                if (Math.abs(yTheoreticalDistance[i]) < threshold) {
668
                    yTheoreticalDistance[i] = 0.0;
669
                }
670
            }
671
        }
672
    }
673
    
674
    /**
675
     * Prepares the estimation for horizontal speed of the player based on various conditions.
676
     *
677
     * @param forceSetOnGround Whether to forcibly consider the ground status of the player (despite being off ground).
678
     * @param forceSetOffGround Whether to forcibly ignore the ground status of the player (despite being on the ground).
679
     * @param isNormalOrPacketSplitMove Whether this movement has been corrected due to a faulty PlayerMoveEvent or is normal (no correction needed)
680
     *
681
     * @return hAllowedDistance, hDistanceAboveLimit
682
     */
683
    private double[] prepareSpeedEstimation(final PlayerLocation from, final PlayerLocation to, final IPlayerData pData, final Player player,
684
                                            final MovingData data, final PlayerMoveData thisMove, final PlayerMoveData lastMove,
685
                                            final boolean fromOnGround, final boolean toOnGround, final boolean debug,
686
                                            final boolean isNormalOrPacketSplitMove, boolean forceSetOnGround, boolean forceSetOffGround) {
687
        double hDistanceAboveLimit;
688
        //////////////////////////
689
        // Early return(s)      //
690
        //////////////////////////
691
        if (!isNormalOrPacketSplitMove) {
692
            // Bukkit-based split move: predicting the next speed is not possible due to coordinates not being reported correctly by Bukkit (and without ProtocolLib, it's nearly impossible to achieve precision here)
693
            thisMove.xAllowedDistance = thisMove.xDistance;
694
            thisMove.zAllowedDistance = thisMove.zDistance;
695
            thisMove.hAllowedDistance = thisMove.hDistance;
696
            hDistanceAboveLimit = 0.0;
697
            return new double[]{thisMove.hAllowedDistance, hDistanceAboveLimit};
698
        }
699
        
700
        boolean onGround = PhysicsGroundResolver.resolvePhysicsOnGround(from, thisMove, lastMove, forceSetOnGround, forceSetOffGround);
701
        /* All moves are assumed to be predictable, unless there are technical limitations / bugs / glitches that we cannot solve */
702
        boolean isPredictable;
703
        //////////////////////////////////////////////////////////////
704
        // Estimate the horizontal speed (per-move distance check)  //                      
705
        //////////////////////////////////////////////////////////////
706
        // Determine inertia and acceleration to calculate speed with.
707
        // Only check using the 'from' position because it is the current location of the player (NMS-wise)
708
        if (from.isInWater()) {
709
            data.nextInertia = Bridge1_13.isSwimming(player) ? Magic.HORIZONTAL_SWIMMING_INERTIA : Magic.WATER_HORIZONTAL_INERTIA;
710
            /* Per-tick speed gain. */
711
            float acceleration = Magic.LIQUID_ACCELERATION;
712
            float StriderLevel = attributeAccess.getHandle().getWaterMovementEfficiency(player);
713
            if (!onGround) {
714
                StriderLevel *= Magic.STRIDER_OFF_GROUND_MULTIPLIER;
715
            }
716
            if (StriderLevel > 0.0) {
717
                // (Less speed conservation (or in other words, more friction))
718
                data.nextInertia += (0.54600006f - data.nextInertia) * StriderLevel / (pData.getClientVersion().isAtMost(ClientVersion.V_1_20_6) ? 3.0f : 1.0f); // Mojang removed this / by 3 in 1.21 and switched to the WATER_MOVEMENT_EFFICIENCY attribute
719
                // (More per-tick speed gain)
720
                acceleration += (data.walkSpeed - acceleration) * StriderLevel / (pData.getClientVersion().isAtMost(ClientVersion.V_1_20_6) ? 3.0f : 1.0f);
721
            }
722
            if (!Double.isInfinite(Bridge1_13.getDolphinGraceAmplifier(player))) {
723
                // (Much more speed conservation (or in other words, much less friction))
724
                // (Overrides swimming AND depth strider friction)
725
                data.nextInertia = Magic.DOLPHIN_GRACE_INERTIA;
726
            }
727
            // Run through all operations
728
            isPredictable = estimateNextSpeed(player, acceleration, pData, tags, to, from, debug, fromOnGround, toOnGround, onGround, forceSetOffGround);
729
        }
730
        else if (from.isInLava()) {
731
            data.nextInertia = Magic.LAVA_HORIZONTAL_INERTIA;
732
            isPredictable = estimateNextSpeed(player, Magic.LIQUID_ACCELERATION, pData, tags, to, from, debug, fromOnGround, toOnGround, onGround, forceSetOffGround);
733
        }
734
        else {
735
            data.nextInertia = onGround ? data.nextFrictionHorizontal * Magic.AIR_HORIZONTAL_INERTIA : Magic.AIR_HORIZONTAL_INERTIA;
736
            // 1.12 (and below) clients will use cubed inertia, not cubed friction here. The difference isn't significant except for blocking speed and bunnyhopping on soul sand, which are both slower on 1.8
737
            float frictionMediumFactor = pData.getClientVersion().isAtLeast(ClientVersion.V_1_13) ? data.nextFrictionHorizontal : data.nextFrictionHorizontal * Magic.AIR_HORIZONTAL_INERTIA;
738
            float acceleration = onGround ? data.walkSpeed * ((pData.getClientVersion().isAtLeast(ClientVersion.V_1_13) ? Magic.DEFAULT_FRICTION_CUBED : Magic.DEFAULT_FRICTION_MULTIPLIED_BY_091_CUBED) / (frictionMediumFactor * frictionMediumFactor * frictionMediumFactor)) : Magic.AIR_ACCELERATION;
739
            if (pData.isSprinting()) {
740
                // (We don't use the attribute here due to desync issues, just detect when the player is sprinting and apply the multiplier manually)
741
                acceleration += acceleration * 0.3f; // 0.3 is the effective sprinting speed (EntityLiving).
742
            }
743
            isPredictable = estimateNextSpeed(player, acceleration, pData, tags, to, from, debug, fromOnGround, toOnGround, onGround, forceSetOffGround);
744
        }
745
        
746
        /////////////////////////////////////////////////
747
        // Set the combined allowed horizontal speed   //
748
        /////////////////////////////////////////////////
749
        thisMove.hAllowedDistance = MathUtil.dist(thisMove.xAllowedDistance, thisMove.zAllowedDistance);
750
        
751
        ////////////////////////
752
        // Calculate offsets  //
753
        ////////////////////////
754
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
755
        if (isPredictable) {
756
            hDistanceAboveLimit = handlePredictableMove(thisMove, cc.survivalFlyStrictHorizontal); 
757
        }
758
        else hDistanceAboveLimit = handleUnpredictableMove(thisMove, cc.survivalFlyStrictHorizontal);
759
        hDistanceAboveLimit = applyEdgeCornerResolvedTolerance(thisMove, hDistanceAboveLimit, cc.survivalFlyStrictHorizontal);
760
        hDistanceAboveLimit = HiddenMotionReconstructor.applyEdgeSneakBypass(player, pData, data, from, lastMove, thisMove, hDistanceAboveLimit, tags);
761
        if (hDistanceAboveLimit > 0.0) {
762
            tags.add("hdistrel");
763
            if (debug) {
764
                player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] hdistrel: predicted=" + StringUtil.fdec6.format(thisMove.hAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.hDistance));
765
            }
766
        }
767
        return new double[]{thisMove.hAllowedDistance, hDistanceAboveLimit};
768
    }
769
    
770
    
771
    /**
772
     * Estimates the player's horizontal speed based on the given data and Minecraft's movement logic.<br>
773
     * Order of operations is essential. Do not shuffle things around unless you know what you're doing.
774
     *<hr>
775
     * <p>Order of client-movement operations (as per MCP tool):
776
     * <ul>
777
     * <li>{@code EntityLiving.tick()}
778
     * <li>{@code [Entity].tick()}
779
     *   <ul>
780
     *     <li>{@code baseTick()}
781
     *     <li>{@code updateInWaterStateAndDoFluidPushing()}
782
     *   </ul>
783
     * <li>{@code EntityLiving.aiStep()}
784
     *   <ul>
785
     *     <li>Decrease the jump delay counter if it is active ({@code this.noJumpDelay > 0})
786
     *     <li>Negligible speed reset (0.003)
787
     *     <li>Apply liquid motion if the player is pressing the space bar (vertical axis only)
788
     *     <li>Multiply the input vector (= the vector containing the player's WASD impulse) by 0.98</li>
789
     *     <li>{@code jumpFromGround()} is called if the player is on ground and has pressed the space bar.
790
     *   </ul>
791
     * <li>Begin executing {@code EntityLiving.travel()} ({@code In EntityLiving.aiStep()})<p> <b>Note:</b> from 1.21.2 and onwards, Mojang split the travel function into different helper methods to better
792
     * distinguish between media (we now have {@code travelInAir()}, {@code travelInFluid()} and {@code travelFallFlying()})</p><br>
793
     *   <ul>
794
     *     <li>Invoke {@code [Entity].moveRelative()} (WASD inputs are transformed to acceleration vectors, call {@code getInputVector()})
795
     *     <li>If not in liquid or gliding, limit motion when on climbable via {@code handleRelativeFrictionAndCalculateMovement()}
796
     *     <li>Invoke {@code [Entity].move()}
797
     *       <ul>
798
     *         <li>Apply stuck speed multiplier
799
     *         <li>Invoke {@code EntityHuman.maybeBackOffFromEdge()}
800
     *         <li>Handle wall collisions via {@code Entity.collide()} (speed is cut-off and the collision flag is set) <br>
801
     * <em><strong>After {@code [Entity].collide()} is called, the next movement is prepared. Every subsequent operation 
802
     *           applies to the next move for the client.</strong></em>
803
     *         <li>Set the supporting block data; call {@code setGroundWithMovement()}</li>
804
     *         <li>Handle horizontal collisions (speed is now reset to 0 on the colliding axis); <em><strong>NCP STARTS ESTIMATING FROM HERE ON (!)</strong></em>
805
     *         <li>Invoke {@code checkFallDamage()} (apply fluid pushing if not previously in water)
806
     *         <li>Invoke {@code [Block].updateEntityAfterFallOn()} (for slime bouncing)
807
     *         <li>Invoke {@code [Block].stepOn()} (for slime blocks only, currently)
808
     *         <li>Invoke {@code tryCheckInsideBlocks()} (for honey blocks slide-down and bubble columns)
809
     *         <li>Invoke {@code [Entity].getBlockSpeedFactor()} (soul sand, honey blocks)
810
     *       </ul>
811
     *   </ul>
812
     * <li>Complete executing {@code EntityLiving.travel()}
813
     *   <ul>
814
     *     <li>{@code handleRelativeFrictionAndCalculateMovement()} (for snow climbing speed)
815
     *     <li>Apply gravity.
816
     *     <li>Apply friction/inertia.
817
     *     <li>Handle fluid falling function if in liquid (vertical axis only)
818
     *     <li>Handle jumping out of liquids (vertical axis only)
819
     *     <li>Handle entity pushing
820
     *   </ul>
821
     * <li>Complete {@code EntityLiving.aiStep()}
822
     * <li>Complete {@code EntityLiving.tick()}
823
     * <li> Finally, send movement to the server.
824
     * </ul>
825
     * <hr>
826
     * The logic is split into different sections:
827
     * <li>Firstly, we perform some preliminary checks to quickly catch specific ways of cheating.</li>
828
     * <li>If no blatant cheating is detected, the movement speed estimate is calculated starting from the horizontal collision reset, calculating the client’s actions on the next move and then processing the actions performed prior.</li>
829
     * <li>If needed, the player's impulse (acceleration) is brute-forced (see {@link BridgeMisc#isWASDImpulseKnown(Player)}</li>
830
     * @return {@code true}, if the move has been deemed to be predictable. {@code false} otherwise.
831
     */
832
    private boolean estimateNextSpeed(final Player player, float movementSpeed, final IPlayerData pData, final Collection<String> tags,
833
                                      final PlayerLocation to, final PlayerLocation from, final boolean debug,
834
                                      final boolean fromOnGround, final boolean toOnGround, final boolean onGround, boolean forceSetOffGround) {
835
        /*
836
         * TODO: This is a mess, clean-up pending / needed. Get rid of code duplication
837
         */
838
        final MovingData data = pData.getGenericInstance(MovingData.class);
839
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
840
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
841
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
842
        final boolean envelopeFromOnGround = PhysicsGroundResolver.resolveEnvelopeFromOnGround(thisMove, fromOnGround);
843
        final boolean envelopeToOnGround = PhysicsGroundResolver.resolveEnvelopeToOnGround(thisMove, toOnGround);
844
        
845
        // Reference commit of this piece of code: https://github.com/NoCheatPlus/NoCheatPlus/commit/1c024c072c9f6ebe5371c113916c6a2414e635a6
846
        /////////////////////////////////////////////////////
847
        // Horizontal push/pull is put on top priority     //
848
        /////////////////////////////////////////////////////
849
        // With the current implementation, the prediction will run for the axis even if a push/pull is detected on it.
850
        // We'll have to somehow skip predicting that specfic axis, but it requires some refactoring to do it.
851
        // This is not ideal, but it's better than flagging players for being pushed by pistons.
852
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
853
        boolean xPush = false;
854
        boolean zPush = false;
855
        // TODO: Get rid of this config option. Why would someone want to disable piston push detection and cause false positives?
856
        if (cc.trackBlockMove) {
857
            if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, thisMove.xDistance < 0.0 ? Direction.X_NEG : Direction.X_POS, 0.05)) {
858
                tags.add("blkmv_x");
859
                xPush = true;
860
            }
861
            if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, thisMove.zDistance < 0.0 ? Direction.Z_NEG : Direction.Z_POS, 0.05)) {
862
                tags.add("blkmv_z");
863
                zPush = true;
864
            }
865
            if (xPush && zPush) {
866
                thisMove.xAllowedDistance = thisMove.xDistance;
867
                thisMove.zAllowedDistance = thisMove.zDistance;
868
                // A push/pull happened on both axes, no need to continue the prediction.
869
                return true;
870
            }
871
        }
872
        
873
        ////////////////////////////////////////////////////////
874
        // Test for specific cheat implementation types first //
875
        ////////////////////////////////////////////////////////
876
        // These checks don't need specific data from the prediction, so they can be performed ex-ante and save some performance.
877
        if (cData.isHackingRI) {
878
            tags.add("noslowpacket");
879
            cData.isHackingRI = false;
880
            Improbable.check(player, (float) thisMove.hDistance, System.currentTimeMillis(), "moving.survivalfly.noslow", pData);
881
            data.resetHorizontalData();
882
            return true;
883
        }
884
        // If impulses don't need to be inferred from the prediction, illegal sprinting checks can be performed here.
885
        if (BridgeMisc.isWASDImpulseKnown(player) && pData.isSprinting()
886
            && (data.input.getForwardDir() != ForwardDirection.FORWARD && data.input.getStrafeDir() != StrafeDirection.NONE && data.input.getForwardDir() != ForwardDirection.NONE
887
                || player.getFoodLevel() <= 5) // must be checked here as well (besides on toggle sprinting) because players will immediately lose the ability to sprint if food level drops below 5
888
            ) { 
889
            // || inputs[i].getForward() < 0.8 // hasEnoughImpulseToStartSprinting, in LocalPlayer,java -> aiStep()
890
            tags.add("illegalsprint");
891
            Improbable.check(player, (float) thisMove.hDistance, System.currentTimeMillis(), "moving.survivalfly.illegalsprint", pData);
892
            data.resetHorizontalData();
893
            return true;
894
        }
895
        
896
        
897
        //////////////////////////////////////////
898
        // Setup theoretical inputs, if needed  //
899
        //////////////////////////////////////////
900
        PlayerKeyboardInput input = null; // Precise input
901
        PlayerKeyboardInput[] theorInputs = null; // All brute-forced inputs.
902
        /* Index for accessing speed combinations. If you need to perform an operation for/with each speed, set it to 0 and loop until it 8 */
903
        int i = 0;
904
        if (BridgeMisc.isWASDImpulseKnown(player)) {
905
            // Clone for safety as this data is consumed. 
906
            input = data.input.clone();
907
            // In EntityLiving.java -> aiStep() the game multiplies input values by 0.98 before dispatching them to the travel() function.
908
            input.operationToInt(0.98f, 0.98f, 1);
909
            // From KeyboardInput.java and LocalPlayer.java (MC-Reborn tool)
910
            // Sneaking and item-use aren't directly applied to the player's motion. The game reduces the force of the input instead.
911
            if (pData.isInCrouchingPose()) {
912
                // Note that this is determined by player poses, not shift key presses.
913
                input.operationToInt(attributeAccess.getHandle().getPlayerSneakingFactor(player), attributeAccess.getHandle().getPlayerSneakingFactor(player), 1);
914
                tags.add("crouching");
915
            }
916
            // From LocalPlayer.java.aiStep()
917
            if (BridgeMisc.isSlowedDownByUsingAnItem(player)) {
918
                input.operationToInt(Magic.USING_ITEM_MULTIPLIER, Magic.USING_ITEM_MULTIPLIER, 1);
919
                tags.add("usingitem");
920
            }
921
        }
922
        else {
923
            // The input's matrix is: NONE, LEFT, RIGHT, FORWARD, FORWARD_LEFT, FORWARD_RIGHT, BACKWARD, BACKWARD_LEFT, BACKWARD_RIGHT.
924
            theorInputs = new PlayerKeyboardInput[9];
925
            // Loop through all combinations otherwise.
926
            for (int strafe = -1; strafe <= 1; strafe++) {
927
                for (int forward = -1; forward <= 1; forward++) {
928
                    // Multiply all 
929
                    theorInputs[i] = new PlayerKeyboardInput(strafe * 0.98f, forward * 0.98f);
930
                    i++;
931
                }
932
            }
933
            if (pData.isInCrouchingPose()) {
934
                tags.add("crouching");
935
                for (i = 0; i < 9; i++) {
936
                    // Multiply all combinations
937
                    theorInputs[i].operationToInt(attributeAccess.getHandle().getPlayerSneakingFactor(player), attributeAccess.getHandle().getPlayerSneakingFactor(player), 1);
938
                }
939
            }
940
            // From LocalPlayer.java.aiStep()
941
            if (BridgeMisc.isSlowedDownByUsingAnItem(player)) {
942
                tags.add("usingitem");
943
                for (i = 0; i < 9; i++) {
944
                    theorInputs[i].operationToInt(Magic.USING_ITEM_MULTIPLIER, Magic.USING_ITEM_MULTIPLIER, 1);
945
                }
946
            }
947
        }
948
949
        /*
950
         * This bit of vertical distance computation is needed for the supporting block mechanism, which needs Minecraft-calculated on-ground status.
951
         * Normally, these would be computed at the same time, however, since NCP handles horizontal and vertical speed estimation separately, we need to duplicate this bit of code here.
952
         * TODO: Unify predictions somehow.
953
         */
954
        final boolean slimeYbcChain = from.isOnBouncyBlock();
955
        double yDistanceBeforeCollide;
956
        if (slimeYbcChain) {
957
            yDistanceBeforeCollide = lastMove.motionY;
958
        }
959
        else {
960
            yDistanceBeforeCollide = lastMove.toIsValid ? lastMove.yDistance : 0.0;
961
            if (lastMove.yCorrectedDistancePre != 0.0) {
962
                yDistanceBeforeCollide = lastMove.yCorrectedDistancePre;
963
            }
964
            if (envelopeToOnGround) yDistanceBeforeCollide = 0.0;
965
        }
966
        // Refine yDistanceBeforeCollide (seed set above for edge-sneak momentum carry).
967
        if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) {
968
            if (data.lastStuckInBlockVertical != 1.0) {
969
                yDistanceBeforeCollide = 0.0;
970
            }
971
        }
972
        if (!pData.isShiftKeyPressed()) {
973
            if (yDistanceBeforeCollide < 0.0 && thisMove.yDistance >= 0.0) {
974
                if (from.isOnBouncyBlock()) {
975
                    // The effect works by inverting the distance.
976
                    // Beds have a weaker bounce effect (BedBlock.java).
977
                    yDistanceBeforeCollide = from.isOnSlimeBlock() ? -yDistanceBeforeCollide : -yDistanceBeforeCollide * 0.66;
978
                }
979
            }
980
        }
981
        if (lastMove.from.inWater) {
982
            yDistanceBeforeCollide *= data.lastFrictionVertical;
983
            if (BridgeMisc.hasGravity(player)) {
984
                // Legacy: clients older than 1.13 have some kind of gravity effect applied to them even in liquids, if they don't press the space bar.
985
                // On 1.13 and above, only friction gets applied, resulting in a much slower descending speed when not pressing the space bar pressed.
986
                if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
987
                    yDistanceBeforeCollide -= Magic.LEGACY_LIQUID_GRAVITY;
988
                }
989
                else {
990
                    // In 1.13 the gravity effect in liquids was removed and this function got added.
991
                    Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yDistanceBeforeCollide <= 0.0, new Vector(0.0, yDistanceBeforeCollide, 0.0), cData.wasSprinting);
992
                    yDistanceBeforeCollide = fluidFallingAdjustMovement.getY();
993
                }
994
            }
995
        }
996
        else if (lastMove.from.inLava) {
997
            if (data.lastFrictionVertical != Magic.LAVA_VERTICAL_INERTIA) {
998
                yDistanceBeforeCollide *= data.lastFrictionVertical;
999
                if (BridgeMisc.hasGravity(player)) {
1000
                    if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
1001
                        yDistanceBeforeCollide -= Magic.LEGACY_LIQUID_GRAVITY;
1002
                    }
1003
                    else {
1004
                        // In 1.13 the gravity effect in liquids was removed and this function got added.
1005
                        Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yDistanceBeforeCollide <= 0.0, new Vector(0.0, yDistanceBeforeCollide, 0.0), cData.wasSprinting);
1006
                        yDistanceBeforeCollide = fluidFallingAdjustMovement.getY();
1007
                    }
1008
                }
1009
            }
1010
            else {
1011
                yDistanceBeforeCollide *= data.lastFrictionVertical;
1012
            }
1013
            if (data.lastGravity != 0.0) {
1014
                yDistanceBeforeCollide += -data.lastGravity / 4.0;
1015
            }
1016
        }
1017
        else {
1018
            // Air motion
1019
            if (cData.wasLevitating) {
1020
                yDistanceBeforeCollide += (0.05 * data.lastLevitationLevel - yDistanceBeforeCollide) * 0.2;
1021
            }
1022
            else {
1023
                yDistanceBeforeCollide -= data.lastGravity;
1024
            }
1025
            yDistanceBeforeCollide *= data.lastFrictionVertical;
1026
        }
1027
        if (from.isInLiquid() && verticalLiquidPushComponent != 0.0) {
1028
            // Liquid vertical push component calculated in hdistrel.
1029
            yDistanceBeforeCollide += verticalLiquidPushComponent;
1030
        }
1031
        if (from.isInWater() && pData.getClientVersion().isHigherThan(ClientVersion.V_1_12_2)) {
1032
            // *----------LocalPlayer.aiStep(), goDownInWater()----------*
1033
            if (pData.isShiftKeyPressed()) {
1034
                yDistanceBeforeCollide -= Magic.LIQUID_SPEED_GAIN;
1035
            }
1036
        }
1037
        if (Math.abs(yDistanceBeforeCollide) < (pData.getClientVersion().isHigherThan(ClientVersion.V_1_12_2) ? 0.003 : 0.005)) yDistanceBeforeCollide = 0.0;
1038
        if (!from.isInLiquid() && from.isOnClimbable() && from.canClimbUp(data.liftOffEnvelope.getMaxJumpHeight(data.jumpAmplifier))) {
1039
            // Should replicate the condition: !this.getInBlockState().is(Blocks.SCAFFOLDING)
1040
            final Material typeId = from.getBlockType();
1041
            final long theseFlags = BlockFlags.getBlockFlags(typeId);
1042
            yDistanceBeforeCollide = Math.max(yDistanceBeforeCollide, -Magic.CLIMBABLE_MAX_SPEED);
1043
            if (yDistanceBeforeCollide < 0.0 && pData.isShiftKeyPressed() && from.getEntity() instanceof Player
1044
                && (theseFlags & BlockFlags.F_SCAFFOLDING) == 0 && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
1045
                yDistanceBeforeCollide = 0.0;
1046
            }
1047
        }
1048
        thisMove.motionY = yDistanceBeforeCollide;
1049
        //End of yDistanceBeforeCollide getter
1050
1051
        //////////////////////////////////////
1052
        // Next move for the client         //
1053
        //////////////////////////////////////
1054
        /*
1055
          All moves are assumed to be predictable, unless we explicitly state otherwise. 
1056
          A move is considered to be predictable if there aren't any particular client-side issues/limitations that prevent it.
1057
         */
1058
        boolean isPredictable = true;
1059
        final boolean edgeSneakNow = !player.isFlying() && pData.isShiftKeyPressed() && from.isAboveGround() && yDistanceBeforeCollide <= 0.0;
1060
        // Initialize horizontal momentum; at an edge use stored internal momentum while still shift-sneaking.
1061
        if (lastMove.toIsValid) {
1062
            if (edgeSneakNow && lastMove.edgeBackoffApplied) {
1063
                thisMove.xAllowedDistance = lastMove.motionX;
1064
                thisMove.zAllowedDistance = lastMove.motionZ;
1065
            } else if (HiddenMotionReconstructor.shouldUseEdgeHiddenCarry(edgeSneakNow, from, yDistanceBeforeCollide, lastMove)) {
1066
                thisMove.xAllowedDistance = lastMove.motionX;
1067
                thisMove.zAllowedDistance = lastMove.motionZ;
1068
            } else {
1069
                thisMove.xAllowedDistance = lastMove.xDistance;
1070
                thisMove.zAllowedDistance = lastMove.zDistance;
1071
            }
1072
            // Edge: packet may show 0 on a clipped axis while internal momentum (motionX/Z) is still large.
1073
            if (lastMove.edgeBackoffApplied && lastMove.edgeAxisClamped) {
1074
                final double pktSuppressH = HiddenMotionReconstructor.packetSuppressThresholdH(pData);
1075
                if (Math.abs(lastMove.xDistance) < pktSuppressH) {
1076
                    thisMove.xAllowedDistance = lastMove.motionX;
1077
                }
1078
                if (Math.abs(lastMove.zDistance) < pktSuppressH) {
1079
                    thisMove.zAllowedDistance = lastMove.motionZ;
1080
                }
1081
            }
1082
        } else {
1083
            thisMove.xAllowedDistance = 0.0;
1084
            thisMove.zAllowedDistance = 0.0;
1085
        }
1086
        // !lastMove.possibleStopMotion is dummy flag to flip false on failure and retry
1087
        // Check if there had been a hidden move on the prebious tick(s) due to 0.03 threshold.
1088
        // If so, the initial speed is initialized by the corrected distance. xDistance/zDistance would report a wrong speed value.
1089
        if (!lastMove.possibleStopMotion && (lastMove.xCorrectedDistancePre != 0.0 || lastMove.zCorrectedDistancePre != 0.0)) {
1090
            // Edge-sneak internal momentum overrides generic hidden pre-correct when still at an edge.
1091
            if (!(edgeSneakNow && lastMove.edgeBackoffApplied)) {
1092
                thisMove.xAllowedDistance = lastMove.xCorrectedDistancePre;
1093
                thisMove.zAllowedDistance = lastMove.zCorrectedDistancePre;
1094
                // Distinguish source of CorrectedDistance that only come from hidden move not from stop motion
1095
                if (lastMove.hiddenDistanceIndex != -1) {
1096
                    thisMove.possibleStopMotion = true;
1097
                }
1098
                tags.add("hidden");
1099
            }
1100
        }
1101
        // Stuck speed reset (the game resets momentum each tick the player is in a stuck-speed block)
1102
        if (data.lastStuckInBlockHorizontal != 1.0) {
1103
            if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) { // (Vanilla check, don't ask)
1104
                // Throttle speed if stuck in.
1105
                thisMove.xAllowedDistance = thisMove.zAllowedDistance = 0.0;
1106
            }
1107
        }
1108
        // If the player collided with something on the previous tick, start with 0 momentum now.
1109
        doWallCollision(lastMove, thisMove);
1110
        // (The game calls a checkFallDamage() function, which, as you can imagine, handles fall damage. But also handles liquids' flow force, thus we need to apply this 2 times.)
1111
        if (from.isInWater() && !lastMove.from.inWater) {
1112
            Vector liquidFlowVector = from.getLiquidPushingVector(thisMove.xAllowedDistance, thisMove.zAllowedDistance, BlockFlags.F_WATER);
1113
            thisMove.xAllowedDistance += liquidFlowVector.getX();
1114
            thisMove.zAllowedDistance += liquidFlowVector.getZ();
1115
        }
1116
        // Slime stepOn: throttle momentum carried from last tick (client stepOn at end of last tick).
1117
        if (from.isOnSlimeBlock() && thisMove.hasClientFromOnGround && thisMove.clientFromOnGround && Math.abs(lastMove.motionY) < 0.1 && !pData.isShiftKeyPressed()) {
1118
            double slimeStepMul = 0.4 + Math.abs(lastMove.motionY) * 0.2;
1119
            thisMove.xAllowedDistance *= slimeStepMul;
1120
            thisMove.zAllowedDistance *= slimeStepMul;
1121
            tags.add("slime_step");
1122
        }
1123
        // Sliding speed (honey block)
1124
        if (from.isSlidingDown()) { // TODO: lastMove.from.slideDown or something?
1125
            if (lastMove.yDistance < -Magic.SLIDE_START_AT_VERTICAL_MOTION_THRESHOLD) {
1126
                thisMove.xAllowedDistance *= -Magic.SLIDE_SPEED_THROTTLE / lastMove.yDistance;
1127
                thisMove.zAllowedDistance *= -Magic.SLIDE_SPEED_THROTTLE / lastMove.yDistance;
1128
            }
1129
        }
1130
        
1131
        // Block speed
1132
        thisMove.xAllowedDistance *= (double) data.nextBlockSpeedMultiplier;
1133
        thisMove.zAllowedDistance *= (double) data.nextBlockSpeedMultiplier;
1134
        // Friction next, with special case for riptide at the start of the movement tick (when the riptide move is "unified" and not split into two updates; friction of the next move is used here)
1135
        boolean newFriction = false;
1136
        if (lastMove.tridentRelease.decide() && lastMove.toIsValid) {
1137
            final PlayerMoveData secondLastMove = data.playerMoves.getSecondPastMove();
1138
            if (lastMove.from.onGround || secondLastMove.tridentRelease.decideOptimistically() 
1139
                || (secondLastMove.toIsValid && secondLastMove.yDistance <= 0.0 && (secondLastMove.from.onGround || secondLastMove.fromLostGround))) {
1140
                newFriction = true;
1141
            }
1142
        }
1143
        thisMove.xAllowedDistance *= (double) (newFriction ? data.nextInertia : data.lastInertia);
1144
        thisMove.zAllowedDistance *= (double) (newFriction ? data.nextInertia : data.lastInertia);
1145
        // Apply entity-pushing speed
1146
        // From Entity.java.push()
1147
        // The entity's location is in the past.
1148
        if (player.getGameMode() != BridgeMisc.GAME_MODE_SPECTATOR) { // noPhysics check in vanilla.
1149
            Vector push = from.doPush(new Vector(thisMove.xAllowedDistance, 0.0, thisMove.zAllowedDistance));
1150
            thisMove.xAllowedDistance = push.getX();
1151
            thisMove.zAllowedDistance = push.getZ();
1152
            if (data.lastCollidingEntitiesLocations != null && !data.lastCollidingEntitiesLocations.isEmpty()) {
1153
                isPredictable = false;
1154
            }
1155
        }
1156
1157
1158
1159
        //////////////////////////////////
1160
        // Last move for the client     //
1161
        //////////////////////////////////
1162
        // See CombinedListener.java for more details
1163
        // This is done before liquid pushing...
1164
        if (thisMove.hasAttackSlowDown) {
1165
            thisMove.zAllowedDistance *= Magic.ATTACK_SLOWDOWN;
1166
            thisMove.xAllowedDistance *= Magic.ATTACK_SLOWDOWN;
1167
        }
1168
        // Apply liquid pushing speed (2nd call).
1169
        if (from.isInLiquid()) {
1170
            Vector liquidFlowVector = from.getLiquidPushingVector(thisMove.xAllowedDistance, thisMove.zAllowedDistance, from.isInWater() ? BlockFlags.F_WATER : BlockFlags.F_LAVA);
1171
            thisMove.xAllowedDistance += liquidFlowVector.getX();
1172
            verticalLiquidPushComponent = liquidFlowVector.getY();
1173
            thisMove.zAllowedDistance += liquidFlowVector.getZ();
1174
        }
1175
        // Before calculating the acceleration, check if momentum is below the negligible speed threshold and cancel it.
1176
        checkNegligibleMomentum(pData, thisMove);
1177
        // Sprint-jumping...
1178
        // IMPORTANT NOTE: when working **exclusively** with rotations (like in the following cases), you must use the TO location, not the FROM one, as TO contains the most recent rotation. Using FROM lags behind a few ticks, causing false positives when switching looking direction.
1179
        if (PhysicsEnvelope.isBunnyhop(from, to, pData, envelopeFromOnGround, envelopeToOnGround, player, forceSetOffGround)) {
1180
            thisMove.xAllowedDistance += (double) (-TrigUtil.sin(to.getYaw() * TrigUtil.toRadians) * Magic.BUNNYHOP_BOOST);
1181
            thisMove.zAllowedDistance += (double) (TrigUtil.cos(to.getYaw() * TrigUtil.toRadians) * Magic.BUNNYHOP_BOOST);
1182
            thisMove.bunnyHop = true;
1183
            tags.add("bunnyhop");
1184
        }
1185
1186
        // *--------------------------------------------------------------------------------------------------------------------*
1187
        // *--------- If we know the player's impulse, brute-forcing acceleration and everything after it isn't needed ---------* 
1188
        // *--------------------------------------------------------------------------------------------------------------------*
1189
        if (BridgeMisc.isWASDImpulseKnown(player)) {
1190
            // Transform the input into an acceleration vector (getInputVector, entity.java)
1191
            double inputSq = MathUtil.square((double) input.getStrafe()) + MathUtil.square((double) input.getForward()); // Cast to a double because the client does it
1192
            if (inputSq >= 1.0E-7) {
1193
                if (inputSq > 1.0) {
1194
                    double inputForce = Math.sqrt(inputSq);
1195
                    if (inputForce < 1.0E-4) {
1196
                        // Not enough force, reset.
1197
                        input.operationToInt(0, 0, 0);
1198
                    }
1199
                    // Normalize
1200
                    else input.operationToInt(inputForce, inputForce, 2);
1201
                }
1202
                // Multiply the input by movement speed.
1203
                input.operationToInt(movementSpeed, movementSpeed, 1);
1204
                // The acceleration vector is added to the current momentum...
1205
                thisMove.xAllowedDistance += input.getStrafe() * (double) TrigUtil.cos(to.getYaw() * TrigUtil.toRadians) - input.getForward() * (double) TrigUtil.sin(to.getYaw() * TrigUtil.toRadians);
1206
                thisMove.zAllowedDistance += input.getForward() * (double) TrigUtil.cos(to.getYaw() * TrigUtil.toRadians) + input.getStrafe() * (double) TrigUtil.sin(to.getYaw() * TrigUtil.toRadians);
1207
            }
1208
            // Minecraft caps horizontal speed if on climbable, for whatever reason.
1209
            if (from.isOnClimbable() && !from.isInLiquid()) {
1210
                //data.clearActiveHorVel(); // Might want to clear ALL horizontal vel.
1211
                thisMove.xAllowedDistance = MathUtil.clamp(thisMove.xAllowedDistance, -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1212
                thisMove.zAllowedDistance = MathUtil.clamp(thisMove.zAllowedDistance, -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1213
            }
1214
            // Stuck-speed multiplier.
1215
            if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
1216
                thisMove.xAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
1217
                thisMove.zAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
1218
            }
1219
            // Riptide works by propelling the player after releasing the trident (the effect only pushes the player, unless is on ground)
1220
            if (thisMove.tridentRelease.decideOptimistically()) {
1221
                thisMove.tridentRelease = AlmostBoolean.YES;
1222
                Vector riptideVelocity = to.getRiptideVelocity(onGround);
1223
                thisMove.xAllowedDistance += riptideVelocity.getX();
1224
                thisMove.zAllowedDistance += riptideVelocity.getZ();
1225
            }
1226
            // Lunging forward if applicable: the effect only adds the lunging motion on the current delta.
1227
            // TODO: TOTALLY RANDOM PLACEMENT !
1228
            // The addition is called on any left click, provided the player has a Spear in hand with Lunge enchant.
1229
            // NOTE: Does not need to be brute forced, since lunging is supported only by clients that can send WASD inputs.
1230
            if (thisMove.lungingForward) {
1231
                Vector lungeVelocity = to.tryApplyLungingMotion(); // Use to as we're working with rotations here
1232
                thisMove.xAllowedDistance += lungeVelocity.getX();
1233
                thisMove.zAllowedDistance += lungeVelocity.getZ();
1234
            }
1235
            // Try to back off players from edges, if sneaking.
1236
            // NOTE: this is after the riptiding propelling force.
1237
            // NOTE: here the game uses isShiftKeyDown (so this is shifting not sneaking, using Bukkit's isShift is correct)
1238
            if (edgeSneakNow) {
1239
                thisMove.edgeBackoffApplied = true;
1240
                final double preEdgeX = thisMove.xAllowedDistance;
1241
                final double preEdgeZ = thisMove.zAllowedDistance;
1242
                final double pktSuppressH = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1243
                        ? Magic.Minecraft_minMoveSqDistance_legacy : Math.sqrt(Magic.Minecraft_minMoveSqDist_modern);
1244
                Vector backOff = from.maybeBackOffFromEdge(new Vector(preEdgeX, yDistanceBeforeCollide, preEdgeZ));
1245
                HiddenMotionReconstructor.storeEdgeHiddenMotion(thisMove, preEdgeX, preEdgeZ, backOff.getX(), backOff.getZ(), pktSuppressH);
1246
                thisMove.xAllowedDistance = backOff.getX();
1247
                thisMove.zAllowedDistance = backOff.getZ();
1248
                if (!thisMove.edgeAxisClamped) {
1249
                    thisMove.motionX = thisMove.xDistance;
1250
                    thisMove.motionZ = thisMove.zDistance;
1251
                }
1252
            }
1253
            // Collision next.
1254
            // NOTE: Passing the unchecked y-distance is fine in this case. Vertical collision is checked with vdistrel (just separately).
1255
            // TODO: Perhaps after this use collisionVector to store onGround? Also can not restore minecraft ground state with step and jump movement(like stairs)!
1256
            Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, yDistanceBeforeCollide, thisMove.zAllowedDistance), onGround, from.getBoundingBox());
1257
            // Set the supporting block data.
1258
            if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1259
                // This is called with setOnGroundWithMovement at the same time of setting the ground flag but before setting the horizontal collision flags.
1260
                // NOTE: here the bounding box of the TO location must be used.
1261
                pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(thisMove.xAllowedDistance, thisMove.yDistance, thisMove.zAllowedDistance), to.getBoundingBox(), yDistanceBeforeCollide < 0.0 && yDistanceBeforeCollide != collisionVector.getY()));
1262
            }
1263
            // NOTE: Collision flags must be set before setting speed in thisMove.
1264
            thisMove.collideX = thisMove.xAllowedDistance != collisionVector.getX();
1265
            thisMove.collideZ = thisMove.zAllowedDistance != collisionVector.getZ();
1266
            thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
1267
            // Set speed.
1268
            thisMove.xAllowedDistance = collisionVector.getX();
1269
            thisMove.zAllowedDistance = collisionVector.getZ();
1270
            // More edge data...
1271
            thisMove.negligibleHorizontalCollision = thisMove.collidesHorizontally && CollisionUtil.isHorizontalCollisionNegligible(new Vector(thisMove.xAllowedDistance, thisMove.yDistance, thisMove.zAllowedDistance), to, input.getStrafe(), input.getForward());
1272
            // Check for block push.
1273
            // TODO: Unoptimized insertion point... Waste of resources to just override everything at the end. See note at the start of the method.
1274
            if (xPush) {
1275
               thisMove.xAllowedDistance = thisMove.xDistance;
1276
            }
1277
            if (zPush) {
1278
                thisMove.zAllowedDistance = thisMove.zDistance;
1279
            }
1280
            //////////////
1281
            // Set data //
1282
            //////////////
1283
            thisMove.hasImpulse = AlmostBoolean.match(input.getForwardDir() != ForwardDirection.NONE || input.getStrafeDir() != StrafeDirection.NONE);
1284
            thisMove.strafeImpulse = input.getStrafeDir();
1285
            thisMove.forwardImpulse = input.getForwardDir();
1286
            if (debug) {
1287
                player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] (postPredict) Direction: " + input.getForwardDir() +" | "+ input.getStrafeDir());
1288
            }
1289
            // If-else instead of an early return... Matter of preference. This makes code slightly easier to look at, as it avoids yet another indentation
1290
            return isPredictable;
1291
        }
1292
        
1293
        // *----------------------------------------------------------------------------------------------------*
1294
        // *-------Can't know / read player inputs, loop through everything after looping the acceleration------*
1295
        // *----------------------------------------------------------------------------------------------------*
1296
        // Transform theoretical inputs into acceleration vectors (getInputVector, entity.java)
1297
        float sinYaw = TrigUtil.sin(to.getYaw() * TrigUtil.toRadians);
1298
        float cosYaw = TrigUtil.cos(to.getYaw() * TrigUtil.toRadians);
1299
        /* List of predicted X distances. Size is the number of possible inputs (left/right/backwards/forward etc...) */
1300
        double[] xTheoreticalDistance = new double[9];
1301
        /* To keep track which theoretical speed would result in a collision on the X axis */
1302
        boolean[] collideX = new boolean[9];
1303
        /* List of predicted Z distances. Size is the number of possible inputs (left/right/backwards/forward etc...) */
1304
        double[] zTheoreticalDistance = new double[9];
1305
        /* To keep track which theoretical speed would result in a collision on the Z axis */
1306
        boolean[] collideZ = new boolean[9];
1307
        /* To keep track which theoretical speed would result in a collision on the Y axis */
1308
        boolean[] collideY = new boolean[9];
1309
        for (i = 0; i < 9; i++) {
1310
            // Each slot in the array is initialized with the same momentum first.
1311
            xTheoreticalDistance[i] = thisMove.xAllowedDistance;
1312
            zTheoreticalDistance[i] = thisMove.zAllowedDistance;
1313
            // Then we proceed to compute all possible accelerations with all theoretical inputs and apply subsequent modifiers.
1314
            double inputSq = MathUtil.square((double)theorInputs[i].getStrafe()) + MathUtil.square((double)theorInputs[i].getForward());
1315
            if (inputSq >= 1.0E-7) {
1316
                if (inputSq > 1.0) {
1317
                    double inputForce = Math.sqrt(inputSq);
1318
                    if (inputForce < 1.0E-4) {
1319
                        theorInputs[i].operationToInt(0, 0, 0);
1320
                    }
1321
                    else {
1322
                        theorInputs[i].operationToInt(inputForce, inputForce, 2);
1323
                    }
1324
                }
1325
                theorInputs[i].operationToInt(movementSpeed, movementSpeed, 1);
1326
                xTheoreticalDistance[i] += theorInputs[i].getStrafe() * (double)cosYaw - theorInputs[i].getForward() * (double)sinYaw;
1327
                zTheoreticalDistance[i] += theorInputs[i].getForward() * (double)cosYaw + theorInputs[i].getStrafe() * (double)sinYaw;
1328
            }
1329
        }
1330
        // All later modifiers get applied to each theoretical speed...
1331
        if (from.isOnClimbable() && !from.isInLiquid()) {
1332
            for (i = 0; i < 9; i++) {
1333
                xTheoreticalDistance[i] = MathUtil.clamp(xTheoreticalDistance[i], -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1334
                zTheoreticalDistance[i] = MathUtil.clamp(zTheoreticalDistance[i], -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1335
            }
1336
        }
1337
        if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
1338
            for (i = 0; i < 9; i++) {
1339
                xTheoreticalDistance[i] *= (double) data.nextStuckInBlockHorizontal;
1340
                zTheoreticalDistance[i] *= (double) data.nextStuckInBlockHorizontal;
1341
            }
1342
        }
1343
        if (thisMove.tridentRelease.decideOptimistically()) {
1344
            thisMove.tridentRelease = AlmostBoolean.YES;
1345
            Vector riptideVelocity = to.getRiptideVelocity(onGround);
1346
            for (i = 0; i < 9; i++) {
1347
                xTheoreticalDistance[i] += riptideVelocity.getX();
1348
                zTheoreticalDistance[i] += riptideVelocity.getZ();
1349
            }
1350
        }
1351
        
1352
        double[] xMotionBeforeEdge = new double[9];
1353
        double[] zMotionBeforeEdge = new double[9];
1354
        double[] xBackOffAfterEdge = new double[9];
1355
        double[] zBackOffAfterEdge = new double[9];
1356
        for (i = 0; i < 9; i++) {
1357
            xMotionBeforeEdge[i] = xTheoreticalDistance[i];
1358
            zMotionBeforeEdge[i] = zTheoreticalDistance[i];
1359
            xBackOffAfterEdge[i] = xTheoreticalDistance[i];
1360
            zBackOffAfterEdge[i] = zTheoreticalDistance[i];
1361
        }        
1362
        
1363
        final double hiddenThresholdSqBrute = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1364
                ? Magic.Minecraft_minMoveSqDistance_legacy : Magic.Minecraft_minMoveSqDist_modern;
1365
        final double hiddenThresholdHBrute = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1366
                ? hiddenThresholdSqBrute : Math.sqrt(hiddenThresholdSqBrute);
1367
        boolean activeCornerClamp = false;
1368
        if (edgeSneakNow) {
1369
            thisMove.edgeBackoffApplied = true;
1370
            // Single backoff probe replaces back-to-back edgeStillClampsCorner + edgeStillClamps on the same vector.
1371
            final Vector seedBackOff = from.maybeBackOffFromEdge(new Vector(thisMove.xAllowedDistance, yDistanceBeforeCollide, thisMove.zAllowedDistance));
1372
            activeCornerClamp = HiddenMotionReconstructor.edgeStillClampsCornerCached(thisMove.xAllowedDistance,
1373
                    thisMove.zAllowedDistance, seedBackOff.getX(), seedBackOff.getZ());
1374
            if (!HiddenMotionReconstructor.edgeStillClampsCached(thisMove.xAllowedDistance,
1375
                    thisMove.zAllowedDistance, seedBackOff.getX(), seedBackOff.getZ())) {
1376
                thisMove.motionX = thisMove.xDistance;
1377
                thisMove.motionZ = thisMove.zDistance;
1378
            }
1379
            for (i = 0; i < 9; i++) {
1380
                // TODO: Optimize. Brute forcing collisions with all 9 speed combinations will tank performance.
1381
                final double preEdgeX = xTheoreticalDistance[i];
1382
                final double preEdgeZ = zTheoreticalDistance[i];
1383
                Vector backOff = from.maybeBackOffFromEdge(new Vector(preEdgeX, yDistanceBeforeCollide, preEdgeZ));
1384
                HiddenMotionReconstructor.storeEdgeHiddenMotionCandidate(thisMove, xMotionBeforeEdge, zMotionBeforeEdge, i, preEdgeX, preEdgeZ, backOff.getX(), backOff.getZ(),
1385
                        thisMove.xDistance, thisMove.zDistance, hiddenThresholdHBrute);
1386
                xBackOffAfterEdge[i] = backOff.getX();
1387
                zBackOffAfterEdge[i] = backOff.getZ();
1388
                xTheoreticalDistance[i] = backOff.getX();
1389
                zTheoreticalDistance[i] = backOff.getZ();
1390
            }
1391
            if (HiddenMotionReconstructor.anyEdgeCandidateClipped(xMotionBeforeEdge, zMotionBeforeEdge, xBackOffAfterEdge, zBackOffAfterEdge)) {
1392
                thisMove.edgeAxisClamped = true;
1393
            }
1394
        }
1395
        // TODO: Optimize. Brute forcing collisions with all 9 speed combinations will tank performance.
1396
        // TODO: If sprinting detected correctly, Might not need to loop backward, only 6 left to check
1397
        for (i = 0; i < 9; i++) {
1398
            // TODO: Perhaps after this use collisionVector to store onGround?
1399
            Vector collisionVector = from.collide(new Vector(xTheoreticalDistance[i], yDistanceBeforeCollide, zTheoreticalDistance[i]), onGround, from.getBoundingBox());
1400
            if (xTheoreticalDistance[i] != collisionVector.getX()) {
1401
                // This theoretical speed would result in a collision. Remember it.
1402
                collideX[i] = true;
1403
            }
1404
            if (yDistanceBeforeCollide != collisionVector.getY()) {
1405
                // This theoretical speed would result in a collision. Remember it.
1406
                // Only needed for supporting block detection.
1407
                collideY[i] = true;
1408
            }
1409
            if (zTheoreticalDistance[i] != collisionVector.getZ()) {
1410
                // This theoretical speed would result in a collision. Remember it.
1411
                collideZ[i] = true;
1412
            }
1413
            xTheoreticalDistance[i] = collisionVector.getX();
1414
            zTheoreticalDistance[i] = collisionVector.getZ();
1415
            if (lastMove.xCorrectedDistancePost != 0 || lastMove.zCorrectedDistancePost != 0) {
1416
                xTheoreticalDistance[i] += lastMove.xCorrectedDistancePost;
1417
                zTheoreticalDistance[i] += lastMove.zCorrectedDistancePost;
1418
            }
1419
        }
1420
        // Check for block push.
1421
        // TODO: Unoptimized insertion point... Waste of resources to just override everything at the end. See note at the start of the method.
1422
        if (xPush) {
1423
            for (i = 0; i < 9; i++) {
1424
                // Override all theoretical speeds.
1425
                xTheoreticalDistance[i] = thisMove.xDistance;
1426
            }
1427
        }
1428
        if (zPush) {
1429
            for (i = 0; i < 9; i++) {
1430
                zTheoreticalDistance[i] = thisMove.zDistance;
1431
            }
1432
        }
1433
        /////////////////////////////////////////////////////////////////////////////
1434
        // Determine which (and IF) theoretical speed should be set in this move   //
1435
        /////////////////////////////////////////////////////////////////////////////
1436
        /*
1437
           True, if the offset between predicted and actual speed is smaller than the accuracy margin (0.0001).
1438
        */
1439
        boolean found = false;
1440
        /*
1441
           True will check if BOTH axis have an offset smaller than 0.0001 (against strafe-like cheats and anything of that sort that relies on the specific direction of the move).
1442
           Otherwise, only the combined horizontal distance will be checked against the offset.
1443
        */
1444
        boolean strict = cc.survivalFlyStrictHorizontal;
1445
        final double hiddenThresholdSq = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1446
                ? Magic.Minecraft_minMoveSqDistance_legacy : Magic.Minecraft_minMoveSqDist_modern;
1447
        final double hiddenThresholdH = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1448
                ? hiddenThresholdSq : Math.sqrt(hiddenThresholdSq);
1449
        final boolean yDistanceSuppressed = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1450
                ? thisMove.yDistance < hiddenThresholdSq : thisMove.yDistance * thisMove.yDistance < hiddenThresholdSq;
1451
        for (i = 0; i < 9; i++) {
1452
            // If this theoretical candidate results in a post-collision horizontal
1453
            // displacement smaller than the client's packet-suppression threshold,
1454
            // it means that the client may have omitted (suppressed) the intermediate
1455
            // packet(s) for this motion. Record the WASD candidate index so it can
1456
            // be used as a seed for the hidden-tick reconstructor.
1457
            // Note: if multiple candidates match, the last matching index will
1458
            // overwrite earlier ones (thisMove.hiddenDistanceIndex holds only one
1459
            // seed candidate).
1460
            if (!collideX[i] && !collideZ[i] && yDistanceSuppressed) {
1461
                final double postH = MathUtil.dist(xTheoreticalDistance[i], zTheoreticalDistance[i]);
1462
                final boolean suppressedPost = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1463
                        ? postH < hiddenThresholdSq : postH * postH < hiddenThresholdSq;
1464
                final boolean edgeSuppressedPacket = thisMove.edgeBackoffApplied
1465
                        && (thisMove.hDistance < hiddenThresholdH
1466
                                || Math.abs(thisMove.xDistance) < hiddenThresholdH
1467
                                || Math.abs(thisMove.zDistance) < hiddenThresholdH)
1468
                        && i < xBackOffAfterEdge.length
1469
                        && (xBackOffAfterEdge[i] != xMotionBeforeEdge[i] || zBackOffAfterEdge[i] != zMotionBeforeEdge[i]);
1470
                if (suppressedPost || edgeSuppressedPacket) {
1471
                    thisMove.hiddenDistanceIndex = i;
1472
                }
1473
            }
1474
            if (strict) {
1475
                if (MathUtil.almostEqual(thisMove.xDistance, xTheoreticalDistance[i], Magic.PREDICTION_EPSILON) 
1476
                    && MathUtil.almostEqual(thisMove.zDistance, zTheoreticalDistance[i], Magic.PREDICTION_EPSILON)) {
1477
                    found = true;
1478
                }
1479
            }
1480
            else {
1481
                double theoreticalHDistance = MathUtil.dist(xTheoreticalDistance[i], zTheoreticalDistance[i]);
1482
                if (MathUtil.almostEqual(theoreticalHDistance, thisMove.hDistance, Magic.PREDICTION_EPSILON)) {
1483
                    found = true;
1484
                }
1485
            }
1486
            
1487
            /*
1488
               True it will force a violation even if there's a matching theoretical speed.
1489
             */
1490
            boolean forceViolation = false;
1491
            if (found) {
1492
                // These checks must be performed ex-post because they rely on data that is set after the prediction.
1493
                if (pData.isSprinting() 
1494
                    && (theorInputs[i].getForwardDir() != ForwardDirection.FORWARD && theorInputs[i].getStrafeDir() != StrafeDirection.NONE && theorInputs[i].getForwardDir() != ForwardDirection.NONE
1495
                        || player.getFoodLevel() <= 5)) { 
1496
                    tags.add("illegalsprint");
1497
                    Improbable.check(player, (float) thisMove.hDistance, System.currentTimeMillis(), "moving.survivalfly.illegalsprint", pData);
1498
                    // Keep looping
1499
                    forceViolation = true;
1500
                }
1501
                if (thisMove.possibleStopMotion) {
1502
                    double[] result = HiddenMotionReconstructor.simulateStoppingMotion(sinYaw, cosYaw, theorInputs[i], data, pData, from, to, onGround, player.isFlying(), yDistanceBeforeCollide);
1503
                    thisMove.xCorrectedDistancePre = result[0];
1504
                    thisMove.zCorrectedDistancePre = result[1];
1505
                }
1506
                if (!forceViolation) {
1507
                    // Found a candidate to set in this move; these collisions are valid.
1508
                    // Also set the supporting block.
1509
                    if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1510
                        pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to.getBoundingBox(), collideY[i] && yDistanceBeforeCollide < 0.0));
1511
                    }
1512
                    thisMove.collideX = collideX[i];
1513
                    thisMove.collideZ = collideZ[i];
1514
                    thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
1515
                    thisMove.negligibleHorizontalCollision = thisMove.collidesHorizontally && CollisionUtil.isHorizontalCollisionNegligible(new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to, theorInputs[i].getStrafe(), theorInputs[i].getForward());
1516
                    break;
1517
                }
1518
            }
1519
        }
1520
        if (!found) {
1521
            // If we couldn't find a direct match for the observed movement, but
1522
            // we previously recorded a candidate that would have been suppressed
1523
            // by the client (hiddenDistanceIndex), attempt to reconstruct the
1524
            // missing intermediate ticks. The reconstructor is seeded with the
1525
            // selected WASD candidate and its post-collision displacement and
1526
            // will return cumulative displacements for the hidden ticks. Those
1527
            // results are then folded into the theoretical distances or stored
1528
            // in the "corrected distance" fields for use across ticks.
1529
            int hiddenSeed = thisMove.hiddenDistanceIndex;
1530
            if (hiddenSeed < 0 && thisMove.edgeBackoffApplied
1531
                    && (lastMove.edgeAxisClamped || lastMove.edgeCornerResolved
1532
                            || lastMove.xCorrectedDistancePost != 0.0 || lastMove.zCorrectedDistancePost != 0.0
1533
                            || Math.abs(thisMove.xDistance) < hiddenThresholdH
1534
                            || Math.abs(thisMove.zDistance) < hiddenThresholdH)) {
1535
                hiddenSeed = MathUtil.findClosestHorizontalIndex(xTheoreticalDistance, zTheoreticalDistance, thisMove.xDistance, thisMove.zDistance);
1536
            }
1537
            if (hiddenSeed >= 0 && !thisMove.edgeBackoffApplied) {
1538
                final int hiddenResolved = tryFoldHiddenTickExplanation(player, hiddenSeed, xTheoreticalDistance, zTheoreticalDistance,
1539
                        xMotionBeforeEdge, zMotionBeforeEdge, theorInputs, sinYaw, cosYaw, movementSpeed, data, pData, from, onGround,
1540
                        yDistanceBeforeCollide, strict, tags);
1541
                if (hiddenResolved >= 0) {
1542
                    i = hiddenResolved;
1543
                    found = true;
1544
                    if (thisMove.edgeBackoffApplied) {
1545
                        tags.add("edge_hidden");
1546
                    }
1547
                }
1548
            }
1549
            else if (lastMove.hiddenDistanceIndex != -1 && (lastMove.xCorrectedDistancePre != 0 || lastMove.zCorrectedDistancePre != 0)) {
1550
                // Hidden move was found and sum match lastMove but the component of the sum didn't right as there another direction that also make the sum correct!
1551
                isPredictable = false;
1552
            }
1553
            if (!found && thisMove.edgeBackoffApplied && activeCornerClamp) {
1554
                double cornerRefSpeed = thisMove.hDistance;
1555
                for (int c = 0; c < 9; c++) {
1556
                    cornerRefSpeed = Math.max(cornerRefSpeed, MathUtil.dist(xTheoreticalDistance[c], zTheoreticalDistance[c]));
1557
                    cornerRefSpeed = Math.max(cornerRefSpeed, MathUtil.dist(xBackOffAfterEdge[c], zBackOffAfterEdge[c]));
1558
                }
1559
                final double cornerMatchTolerance = HiddenMotionReconstructor.edgeCornerMatchTolerance(cornerRefSpeed);
1560
                final int cornerIdx = HiddenMotionReconstructor.findBestEdgeCornerCandidate(thisMove.xDistance, thisMove.zDistance, thisMove.hDistance,
1561
                        xTheoreticalDistance, zTheoreticalDistance, xBackOffAfterEdge, zBackOffAfterEdge, strict, cornerMatchTolerance);
1562
                if (cornerIdx >= 0) {
1563
                    i = cornerIdx;
1564
                    found = true;
1565
                    isPredictable = false;
1566
                    thisMove.edgeCornerResolved = true;
1567
                    tags.add("edge_corner");
1568
                    if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1569
                        pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to.getBoundingBox(), collideY[i] && yDistanceBeforeCollide < 0.0));
1570
                    }
1571
                    thisMove.collideX = collideX[i];
1572
                    thisMove.collideZ = collideZ[i];
1573
                    thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
1574
                    thisMove.negligibleHorizontalCollision = thisMove.collidesHorizontally && CollisionUtil.isHorizontalCollisionNegligible(new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to, theorInputs[i].getStrafe(), theorInputs[i].getForward());
1575
                }
1576
            }
1577
            // Note: Always set no matter what, prevent desync
1578
            if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1579
                pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(thisMove.xDistance, thisMove.yDistance, thisMove.zDistance), to.getBoundingBox(), from.isOnGround()));
1580
            }
1581
        }
1582
        //////////////////////////////////////////////////////////////
1583
        // Finish. Check if the move had been predictable at all    //
1584
        //////////////////////////////////////////////////////////////
1585
        /* The index representing the input associated with the pair of speed to set in this move. */
1586
        int indexPair = i;
1587
        int xIdx = -1;
1588
        int zIdx = -1;
1589
        if (indexPair >= 9) {
1590
            // Cheating: prevent an index out of bounds (we couldn't find the correct pair of speed to set)
1591
            indexPair = 4;
1592
        }
1593
        // If the move is unpredictable, the x/z speeds cannot be associated to a specific input, thus we set them independently.
1594
        // TODO: How can we know the impulse if the move is uncertain? ...
1595
        if (!isPredictable) {
1596
            // In this case, instead of setting the predicted speed with the smallest delta from the actual speed (0.0001), we select the speed that is closest to the current one, effectively allowing for the maximum predicted speed (just limits speed then).
1597
            if (thisMove.edgeBackoffApplied && activeCornerClamp) {
1598
                // Corner: both axes clipped on the actual seed; one combined candidate for packet match.
1599
                xIdx = MathUtil.findClosestHorizontalIndex(xTheoreticalDistance, zTheoreticalDistance, thisMove.xDistance, thisMove.zDistance);
1600
                zIdx = xIdx;
1601
            } else {
1602
                xIdx = MathUtil.findClosestIndex(xTheoreticalDistance, thisMove.xDistance);
1603
                zIdx = MathUtil.findClosestIndex(zTheoreticalDistance, thisMove.zDistance);
1604
            }
1605
        }
1606
        final int motionIdx = !isPredictable ? xIdx : indexPair;
1607
        int momentumStorageIdx = motionIdx;
1608
        if (thisMove.edgeBackoffApplied) {
1609
            if (found && indexPair >= 0 && indexPair < 9) {
1610
                momentumStorageIdx = indexPair;
1611
            } else if (thisMove.hiddenDistanceIndex >= 0) {
1612
                momentumStorageIdx = thisMove.hiddenDistanceIndex;
1613
            } else {
1614
                final int edgeMomIdx = HiddenMotionReconstructor.findBestEdgeMomentumIndex(
1615
                        xMotionBeforeEdge, zMotionBeforeEdge, xBackOffAfterEdge, zBackOffAfterEdge, motionIdx);
1616
                if (edgeMomIdx >= 0) {
1617
                    momentumStorageIdx = edgeMomIdx;
1618
                }
1619
            }
1620
            // Use cached back-off arrays from the brute loop above instead of recomputing.
1621
            final boolean selectedClipped = momentumStorageIdx >= 0 && momentumStorageIdx < 9
1622
                    && HiddenMotionReconstructor.edgeStillClampsCached(xMotionBeforeEdge[momentumStorageIdx],
1623
                            zMotionBeforeEdge[momentumStorageIdx], xBackOffAfterEdge[momentumStorageIdx], zBackOffAfterEdge[momentumStorageIdx]);
1624
            thisMove.edgeAxisClamped = selectedClipped;
1625
            thisMove.edgeCornerClamp = selectedClipped && momentumStorageIdx >= 0 && momentumStorageIdx < 9
1626
                    && HiddenMotionReconstructor.edgeStillClampsCornerCached(xMotionBeforeEdge[momentumStorageIdx],
1627
                            zMotionBeforeEdge[momentumStorageIdx], xBackOffAfterEdge[momentumStorageIdx], zBackOffAfterEdge[momentumStorageIdx]);
1628
        }
1629
        if (thisMove.edgeBackoffApplied && thisMove.edgeAxisClamped) {
1630
            thisMove.motionX = xMotionBeforeEdge[momentumStorageIdx];
1631
            thisMove.motionZ = zMotionBeforeEdge[momentumStorageIdx];
1632
        } else if (!thisMove.edgeBackoffApplied) {
1633
            thisMove.motionX = xMotionBeforeEdge[motionIdx];
1634
            thisMove.motionZ = zMotionBeforeEdge[motionIdx];
1635
        } else {
1636
            thisMove.motionX = thisMove.xDistance;
1637
            thisMove.motionZ = thisMove.zDistance;
1638
        }
1639
        // Done, set in this move.
1640
        thisMove.xAllowedDistance = xTheoreticalDistance[motionIdx];
1641
        thisMove.zAllowedDistance = zTheoreticalDistance[motionIdx];
1642
        thisMove.hasImpulse = !isPredictable ? AlmostBoolean.MAYBE // We don't know the direction in this case.
1643
                              : AlmostBoolean.match(theorInputs[indexPair].getForwardDir() != ForwardDirection.NONE || theorInputs[indexPair].getStrafeDir() != StrafeDirection.NONE);
1644
        thisMove.strafeImpulse = theorInputs[motionIdx].getStrafeDir();
1645
        thisMove.forwardImpulse = theorInputs[motionIdx].getForwardDir();
1646
        if (debug) {
1647
            player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] (postPredict) " + (!isPredictable ? "Uncertain" : "Predicted") + " direction: " + theorInputs[motionIdx].getForwardDir() +" | "+ theorInputs[motionIdx].getStrafeDir());
1648
        }
1649
        return isPredictable;
1650
    }
1651
    
1652
    
1653
    /**
1654
     * Reconstruct suppressed ticks (including {@code maybeBackOffFromEdge} in the simulator) and fold into prediction.
1655
     *
1656
     * @return Matched candidate index, or {@code -1}.
1657
     */
1658
    private int tryFoldHiddenTickExplanation(final Player player, final int hiddenSeed, final double[] xTheoreticalDistance, final double[] zTheoreticalDistance,
1659
            final double[] xMotionBeforeEdge, final double[] zMotionBeforeEdge, final PlayerKeyboardInput[] theorInputs, final float sinYaw,
1660
            final float cosYaw, final float movementSpeed, final MovingData data, final IPlayerData pData, final PlayerLocation from,
1661
            final boolean onGround, final double yDistanceBeforeCollide, final boolean strict, final Collection<String> tags) {
1662
        if (hiddenSeed < 0 || hiddenSeed >= xTheoreticalDistance.length) {
1663
            return -1;
1664
        }
1665
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
1666
        final double seedX = xMotionBeforeEdge[hiddenSeed];
1667
        final double seedZ = zMotionBeforeEdge[hiddenSeed];
1668
        final double[] result = HiddenMotionReconstructor.findBestHiddenTickExplanation(sinYaw, cosYaw, movementSpeed, theorInputs[hiddenSeed],
1669
                seedX, seedZ, data, pData, from, pData.isInCrouchingPose(),
1670
                attributeAccess.getHandle().getPlayerSneakingFactor(player), BridgeMisc.isSlowedDownByUsingAnItem(player), onGround,
1671
                xTheoreticalDistance[hiddenSeed], zTheoreticalDistance[hiddenSeed], yDistanceBeforeCollide, player.isFlying());
1672
        if (thisMove.xDistance == 0 && thisMove.zDistance == 0) {
1673
            thisMove.xCorrectedDistancePost = xTheoreticalDistance[hiddenSeed];
1674
            thisMove.zCorrectedDistancePost = zTheoreticalDistance[hiddenSeed];
1675
            xTheoreticalDistance[hiddenSeed] = 0.0;
1676
            zTheoreticalDistance[hiddenSeed] = 0.0;
1677
            tags.add("hdistzero");
1678
        } else {
1679
            xTheoreticalDistance[hiddenSeed] += result[0];
1680
            zTheoreticalDistance[hiddenSeed] += result[1];
1681
        }
1682
        final double matchTol = thisMove.edgeBackoffApplied
1683
                ? HiddenMotionReconstructor.edgeCornerMatchTolerance(Math.max(thisMove.hDistance, MathUtil.dist(seedX, seedZ)))
1684
                : Magic.PREDICTION_EPSILON;
1685
        if (strict) {
1686
            if (MathUtil.almostEqual(thisMove.xDistance, xTheoreticalDistance[hiddenSeed], matchTol)
1687
                    && MathUtil.almostEqual(thisMove.zDistance, zTheoreticalDistance[hiddenSeed], matchTol)) {
1688
                thisMove.xCorrectedDistancePre = result[0];
1689
                thisMove.zCorrectedDistancePre = result[1];
1690
                return hiddenSeed;
1691
            }
1692
        } else {
1693
            final double theoreticalHDistance = MathUtil.dist(xTheoreticalDistance[hiddenSeed], zTheoreticalDistance[hiddenSeed]);
1694
            if (MathUtil.almostEqual(theoreticalHDistance, thisMove.hDistance, matchTol)) {
1695
                return hiddenSeed;
1696
            }
1697
        }
1698
        return -1;
1699
    }
1700
1701
    /**
1702
     * After a corner candidate is applied, allow only a speed-scaled offset vs the matched allowed distance
1703
     */
1704
    private static double applyEdgeCornerResolvedTolerance(final PlayerMoveData thisMove, final double hDistanceAboveLimit, final boolean strict) {
1705
        if (hDistanceAboveLimit <= 0.0 || !thisMove.edgeCornerResolved) {
1706
            return hDistanceAboveLimit;
1707
        }
1708
        final double tolerance = HiddenMotionReconstructor.edgeCornerMatchTolerance(
1709
                Math.max(thisMove.hAllowedDistance, thisMove.hDistance));
1710
        if (strict) {
1711
            if (Math.abs(thisMove.xDistance - thisMove.xAllowedDistance) <= tolerance
1712
                    && Math.abs(thisMove.zDistance - thisMove.zAllowedDistance) <= tolerance) {
1713
                return 0.0;
1714
            }
1715
        } else if (Math.abs(thisMove.hDistance - thisMove.hAllowedDistance) <= tolerance) {
1716
            return 0.0;
1717
        }
1718
        return hDistanceAboveLimit;
1719
    }
1720
1721
    /**
1722
     * In case we couldn't predict speed, just ensure that actual speed is below what we estimated.
1723
     * This allows for minor deviations below the allowed speed limit, thus players/cheaters may execute movements 
1724
     * that are technically invalid, but do not provide any [significant] gameplay advantage.
1725
     *
1726
     * @param thisMove
1727
     * @param strict If true, only the combined speed (hDistance) is required to be below the allowed one.
1728
     * @return The horizontal distance above limit.
1729
     */
1730
    private double handleUnpredictableMove(final PlayerMoveData thisMove, boolean strict) {
1731
        double hDistanceAboveLimit = 0.0;
1732
        double offset = thisMove.hDistance - thisMove.hAllowedDistance;
1733
        if (strict) {
1734
            // both axes must be below-allowed distance if strict.
1735
            if (MathUtil.exceedsAllowedDistance(thisMove.xDistance, thisMove.xAllowedDistance) 
1736
                || MathUtil.exceedsAllowedDistance(thisMove.zDistance, thisMove.zAllowedDistance)) {
1737
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1738
            }
1739
        } 
1740
        else {
1741
            // Otherwise, only the combined distance needs to be below the limit.
1742
            if (thisMove.hDistance > thisMove.hAllowedDistance) {
1743
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1744
            }
1745
        }
1746
        return hDistanceAboveLimit;
1747
    }
1748
    
1749
    
1750
    /**
1751
     * If the move was predictable, ensure that the difference between actual and allowed speed is below the {@link Magic#PREDICTION_EPSILON}.
1752
     * 
1753
     * @param thisMove
1754
     * @param strict If true, the offset of each axis (x/z) must be below the epsilon, otherwise, only the combined offset (h) will be checked.
1755
     *               Needed against cheats that rely on the specific direction of a move.
1756
     * @return The horizontal distance above limit.
1757
     */
1758
    private double handlePredictableMove(final PlayerMoveData thisMove, boolean strict) {
1759
        double hDistanceAboveLimit = 0.0;
1760
        double offset = thisMove.hDistance - thisMove.hAllowedDistance;
1761
        if (strict) {
1762
            if (!MathUtil.isOffsetWithinPredictionEpsilon(thisMove.xDistance, thisMove.xAllowedDistance) 
1763
                || !MathUtil.isOffsetWithinPredictionEpsilon(thisMove.zDistance, thisMove.zAllowedDistance)) {
1764
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1765
            }
1766
        } 
1767
        else {
1768
            if (!MathUtil.isOffsetWithinPredictionEpsilon(thisMove.hDistance, thisMove.hAllowedDistance)) {
1769
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1770
            }
1771
        }
1772
        return hDistanceAboveLimit;
1773
    }
1774
    
1775
    private enum Operation {
1776
        SET,
1777
        ADD,
1778
        SUBTRACT,
1779
        MULTIPLY,
1780
        DIVIDE
1781
    }
1782
    private void configVerticalAllowedValue(PlayerMoveData thisMove, double[] yTheoreticalDistance, double value, Operation operation) {
1783
        final boolean direct = yTheoreticalDistance == null;
1784
        if (direct) {
1785
            switch (operation) {
1786
            case ADD:
1787
                thisMove.yAllowedDistance += value;
1788
                break;
1789
            case DIVIDE:
1790
                thisMove.yAllowedDistance /= value;
1791
                break;
1792
            case MULTIPLY:
1793
                thisMove.yAllowedDistance *= value;
1794
                break;
1795
            case SET:
1796
                thisMove.yAllowedDistance = value;
1797
                break;
1798
            case SUBTRACT:
1799
                thisMove.yAllowedDistance -= value;
1800
                break;
1801
            }
1802
        } else {
1803
            switch (operation) {
1804
            case ADD:
1805
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1806
                    yTheoreticalDistance[i] += value;
1807
                }
1808
                break;
1809
            case DIVIDE:
1810
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1811
                    yTheoreticalDistance[i] /= value;
1812
                }
1813
                break;
1814
            case MULTIPLY:
1815
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1816
                    yTheoreticalDistance[i] *= value;
1817
                }
1818
                break;
1819
            case SET:
1820
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1821
                    yTheoreticalDistance[i] = value;
1822
                }
1823
                break;
1824
            case SUBTRACT:
1825
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1826
                    yTheoreticalDistance[i] -= value;
1827
                }
1828
                break;
1829
            }
1830
        }
1831
    }
1832
1833
    /**
1834
     * Relative (to workarounds) vertical distance checking.
1835
     *
1836
     * @param forceResetMomentum    Whether the check should start with 0.0 speed on applying air friction.
1837
     * @param useBlockChangeTracker
1838
     */
1839
    private double[] vDistRel(final Player player, final PlayerLocation from,
1840
                              final boolean fromOnGround, final boolean resetFrom, final PlayerLocation to,
1841
                              final boolean toOnGround, final boolean resetTo,
1842
                              final double yDistance, boolean isNormalOrPacketSplitMove,
1843
                              final PlayerMoveData lastMove,
1844
                              final MovingData data, final IPlayerData pData,
1845
                              boolean forceResetMomentum, final boolean debug, boolean useBlockChangeTracker) {
1846
        double yDistanceAboveLimit = 0.0;
1847
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
1848
        final boolean yDirectionSwitch = lastMove.toIsValid && lastMove.yDistance != yDistance && (yDistance <= 0.0 && lastMove.yDistance >= 0.0 || yDistance >= 0.0 && lastMove.yDistance <= 0.0);
1849
        /* Not on ground, not on climbable, not in liquids, not in stuck-speed, no lostground (...) */
1850
        final boolean fullyInAir = !thisMove.touchedGroundWorkaround && !resetFrom && !resetTo;
1851
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
1852
        final boolean onGround = PhysicsGroundResolver.resolvePhysicsOnGround(from, thisMove, lastMove, false, false);
1853
        /*
1854
         * 1: Simulate the reset of speed that the client should have sent to the server.
1855
         * [Client lands on the ground but does not come to a "rest" on top of the block (and thus, reset the vertical speed), instead they'll immediately descend right after, but with speed that is still based on a previous move of 0.0]
1856
         * Can be noticed when stepping down stair of slabs or noob-towering upwards.
1857
         * See: https://gyazo.com/0f748030296aebc0484564629abe6864
1858
         * After interpolating the ground status, notice how the player immediately proceeds to descend with speed as if they actually landed on the ground with the previous move (-0.0784)
1859
         */
1860
        // After completing a "touch-down" (toOnGround), the next move should always come *from* ground
1861
        // Thus, such cases can be generalised by checking for negative motion and last move landing on ground, but this move not *starting back* from a ground position.
1862
        boolean touchDownIsLost = !thisMove.couldStepUp && thisMove.yDistance < 0.0 && (lastMove.toLostGround || lastMove.to.onGround) && !thisMove.from.onGround;
1863
        
1864
        ///////////////////////////////////////////////////
1865
        // Vertical push/pull is put on top priority     //
1866
        ///////////////////////////////////////////////////
1867
        if (useBlockChangeTracker) {
1868
            double[] res = getVerticalBlockMoveResult(thisMove.yDistance, from, to, data);
1869
            if (res != null) {
1870
                thisMove.yAllowedDistance = res[0];
1871
                yDistanceAboveLimit = res[1];
1872
                // Nothing else to do here; allow the movement as-is.
1873
                return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1874
            }
1875
        }
1876
        
1877
        
1878
        //////////////////////////////////////////////////////////////////////////////
1879
        // Test if this movement can fit into any pre-set envelope                  //
1880
        //////////////////////////////////////////////////////////////////////////////
1881
        // NOTE: order of these checks should be from most common to least common.
1882
        if (thisMove.yDistance == 0.0 && fromOnGround) {
1883
            // No vertical motion in this case, as the player is on ground.
1884
            thisMove.yAllowedDistance = 0.0;
1885
            yDistanceAboveLimit = 0.0;
1886
            tags.add("onground_env");
1887
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1888
        }
1889
        if (PhysicsEnvelope.isJumpMotion(from, to, player, fromOnGround, toOnGround, true)) {
1890
            // After stepping, jumping comes second.
1891
            // Players can jump anywhere through air, so this must be checked before the actual prediction.
1892
            thisMove.yAllowedDistance = thisMove.yDistance;
1893
            yDistanceAboveLimit = 0.0;
1894
            thisMove.isJump = true;
1895
            data.jumpDelay = Magic.MAX_JUMP_DELAY;
1896
            tags.add("jump_env");
1897
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1898
        }
1899
        if (PhysicsEnvelope.isStepUpByNCPDefinition(pData, fromOnGround, toOnGround, player)) {
1900
            // Players can step anywhere, both in liquid and in air, so this must be checked before everything else.
1901
            thisMove.yAllowedDistance = thisMove.yDistance;
1902
            yDistanceAboveLimit = 0.0;
1903
            thisMove.isStepUp = true;
1904
            tags.add("step_env");
1905
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1906
        }
1907
        if (onGround && thisMove.tridentRelease.decideOptimistically() && thisMove.multiMoveCount == 1 
1908
            && !isNormalOrPacketSplitMove && MathUtil.isOffsetWithinPredictionEpsilon(thisMove.yDistance, Magic.RIPTIDE_ON_GROUND_MOVE)) {
1909
            // Riptide from ground launch at the end of the movement stack; the actual riptide push will come next. Allowed this move as-is.
1910
            // IMPORTANT NOTE: this move specifically will always cause NCP to fire a Bukkit-based split move on the first split move, no matter what.
1911
            thisMove.yAllowedDistance = Magic.RIPTIDE_ON_GROUND_MOVE;
1912
            // The riptide move was split into two moves: 1.2 upwards from ground and then the actual riptide push.
1913
            // We can therefore set the flag to YES from here on. The push will be handled below.
1914
            data.setTridentReleaseEvent(AlmostBoolean.YES);
1915
            yDistanceAboveLimit = 0.0;
1916
            tags.add("gnd_riptide_pre");
1917
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1918
        }
1919
        
1920
        
1921
        ///////////////////////////////////////////////////////////////////////////////////
1922
        // Estimate the allowed yDistance (per-move distance check)                      //
1923
        ///////////////////////////////////////////////////////////////////////////////////
1924
        /* 
1925
           0: With space bar pressed. 
1926
           1: with space bar not pressed 
1927
           2: swimming not applied at all
1928
         */
1929
        double[] yTheoreticalDistance = null;
1930
        boolean[] collideLiquidY = null;
1931
        // Initialize with momentum (or lack thereof)
1932
        thisMove.yAllowedDistance = forceResetMomentum || touchDownIsLost 
1933
                                    || (lastMove.yDistance < 0.0 && (fromOnGround || thisMove.fromLostGround))
1934
                                    || !lastMove.toIsValid ? 0.0 : lastMove.yDistance;
1935
        if (lastMove.headObstructed) thisMove.yAllowedDistance = 0.0;
1936
        if (lastMove.yCorrectedDistancePre != 0.0) thisMove.yAllowedDistance = lastMove.yCorrectedDistancePre;
1937
        // *----------stuck-speed-momentum-reset----------*
1938
        if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) {
1939
            if (data.lastStuckInBlockVertical != 1.0) {
1940
                thisMove.yAllowedDistance = 0.0;
1941
            }
1942
        }
1943
        // TODO: Optimize to only split when need detect jump
1944
        if (!BridgeMisc.isSpaceBarImpulseKnown(player)) {
1945
            // *----------------------------------*
1946
            // *--- Loop the space bar impulse ---*
1947
            // *----------------------------------*
1948
            // Initialize with the momentum that has hitherto been calculated.
1949
            yTheoreticalDistance = new double[3];
1950
            collideLiquidY = new boolean[3];
1951
            // With space bar pressed
1952
            yTheoreticalDistance[0] = thisMove.yAllowedDistance;
1953
            // With space bar not pressed
1954
            yTheoreticalDistance[1] = thisMove.yAllowedDistance;
1955
            // With swimming speed not applied
1956
            yTheoreticalDistance[2] = thisMove.yAllowedDistance;
1957
        }
1958
        // *----------updateEntityAfterFallOn()----------*
1959
        // NOTE: pressing space bar on a bouncy block will override the bounce (in that case, vdistrel will fall back to the jump check above).
1960
        // updateEntityAfterFallOn(), this function is called on the next move
1961
        if (pData.isShiftKeyPressed() && lastMove.collideY) {
1962
            if (yTheoreticalDistance != null) {
1963
                boolean bounceUp = false;
1964
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1965
                    if (yTheoreticalDistance[i] < 0.0) { // NOTE: Must be the allowed distance, not the actual one (exploit)
1966
                        if (from.isOnBouncyBlock()) {
1967
                            // The effect works by inverting the distance.
1968
                            // Beds have a weaker bounce effect (BedBlock.java).
1969
                            yTheoreticalDistance[i] = from.isOnSlimeBlock() ? -yTheoreticalDistance[i] : -yTheoreticalDistance[i] * 0.66;
1970
                            bounceUp = true;
1971
                        }
1972
                    }
1973
                }
1974
                if (bounceUp) tags.add("bounceup");
1975
            } else {
1976
                if (thisMove.yAllowedDistance < 0.0) { // NOTE: Must be the allowed distance, not the actual one (exploit)
1977
                    if (from.isOnBouncyBlock()) {
1978
                        // The effect works by inverting the distance.
1979
                        // Beds have a weaker bounce effect (BedBlock.java).
1980
                        thisMove.yAllowedDistance = from.isOnSlimeBlock() ? -thisMove.yAllowedDistance : -thisMove.yAllowedDistance * 0.66;
1981
                        tags.add("bounceup");
1982
                    }
1983
                }
1984
            }
1985
        }
1986
        // *----------tryCheckInsideBlocks()----------*
1987
        // Bubble columns are checked in the tryCheckInsideBlocks method, so it comes after updateEntityAfterFallOn()...
1988
        from.tryApplyBubbleColumnMotion(thisMove, yTheoreticalDistance);
1989
        // Honey block sliding mechanic...
1990
        if (from.isSlidingDown()) {
1991
            // Speed is static in this case
1992
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, -Magic.SLIDE_SPEED_THROTTLE, Operation.SET);
1993
        }
1994
        // *----------Finalization of handleRelativeFrictionAndCalculateMovement; this check/condition is called after having called the move() function. The former method is called only when the player is traveling in air, thus the liquid and gliding checks ----------*
1995
        if (!lastMove.from.inLiquid) {
1996
            // TODO: We have to loop the jumping state for 1.21.1 and below... No other way to put it unfortunately. This will make the code an ugly mess than it already is.
1997
            final boolean jumpedOrCollided = lastMove.collidesHorizontally || data.input.wasSpaceBarPressed() && BridgeMisc.isSpaceBarImpulseKnown(player);
1998
            if (thisMove.from.onClimbable || thisMove.from.touchedPowderSnow && BridgeMisc.canStandOnPowderSnow(player)) {
1999
                if (jumpedOrCollided) {
2000
                    configVerticalAllowedValue(thisMove, yTheoreticalDistance, 0.2, Operation.SET);
2001
                } else if (yTheoreticalDistance != null) {
2002
                    yTheoreticalDistance[0] = 0.2;
2003
                }
2004
            }
2005
        }
2006
        // *----------Gravity, friction and other medium-dependent modifiers in LivingEntity.travel() (water first, then lava and finally air)----------*
2007
        data.nextGravity = attributeAccess.getHandle().getGravity(player);
2008
        if (lastMove.from.inWater) {
2009
            if (lastMove.collidesHorizontally && lastMove.from.onClimbable && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
2010
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, 0.2, Operation.SET);
2011
            }
2012
            // Water applies friction before calling the fluidFalling function.
2013
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2014
            if (BridgeMisc.hasGravity(player)) {
2015
                // Legacy: clients older than 1.13 have some kind of gravity effect applied to them even in liquids, if they don't press the space bar.
2016
                // On 1.13 and above, only friction gets applied, resulting in a much slower descending speed when not pressing the space bar pressed.
2017
                if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
2018
                    configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.LEGACY_LIQUID_GRAVITY, Operation.SUBTRACT);
2019
                } 
2020
                else {
2021
                    // In 1.13 the gravity effect in liquids was removed and this function got added.
2022
                    if (yTheoreticalDistance != null) {
2023
                        for (int i =0; i < yTheoreticalDistance.length; i++) {
2024
                            Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yTheoreticalDistance[i] <= 0.0, new Vector(0.0, yTheoreticalDistance[i], 0.0), cData.wasSprinting);
2025
                            yTheoreticalDistance[i] = fluidFallingAdjustMovement.getY();
2026
                        }
2027
                    }
2028
                }
2029
            }
2030
            tags.add("v_water");
2031
        }
2032
        else if (lastMove.from.inLava) {
2033
            // Lava friction is quite odd. Depending on specified thresholds, it can be 0.5 or 0.8
2034
            if (data.lastFrictionVertical != Magic.LAVA_VERTICAL_INERTIA) { // Note that this condition is not vanilla. It's just a shortcut to avoid replicating the condition contained in BlockProperties.getBlockFrictionFactor.
2035
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2036
                if (BridgeMisc.hasGravity(player)) {
2037
                    if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
2038
                        configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.LEGACY_LIQUID_GRAVITY, Operation.SUBTRACT);
2039
                    } 
2040
                    else {
2041
                        // getFluidFallingAdjustedMovement is only applied if friction is 0.8.
2042
                        if (yTheoreticalDistance != null) {
2043
                            for (int i =0; i < yTheoreticalDistance.length; i++) {
2044
                                Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yTheoreticalDistance[i] <= 0.0, new Vector(0.0, yTheoreticalDistance[i], 0.0), cData.wasSprinting);
2045
                                yTheoreticalDistance[i] = fluidFallingAdjustMovement.getY();
2046
                            }
2047
                        }
2048
                    }
2049
                }
2050
            }
2051
            else {
2052
                // Otherwise, 0.5
2053
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2054
            }
2055
            if (data.lastGravity != 0.0) {
2056
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, -data.lastGravity / 4.0, Operation.ADD);
2057
            }
2058
            tags.add("v_lava");
2059
        }
2060
        else {
2061
            // Air motion
2062
            if (cData.wasLevitating) {
2063
                // Levitation forces players to ascend and does not work in liquids, so thankfully we don't have to account for that, other than stuck-speed.
2064
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, (0.05 * data.lastLevitationLevel - lastMove.yAllowedDistance) * 0.2, Operation.ADD);
2065
            }
2066
            else configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastGravity, Operation.SUBTRACT);
2067
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2068
            tags.add("v_air");
2069
        }
2070
        // *----------Finalize LivingEntity.travel; isFree() check----------*
2071
        // Try making the player jump out of the liquid... 
2072
        // This condition is the same for both lava and water, and is always done at the end of the travel() function.
2073
        //TODO: Still broken as thisMove.collidesHorizontally not working properly!
2074
        if (from.isInLiquid() && lastMove.collidesHorizontally) {
2075
            if (yTheoreticalDistance != null) {
2076
                for (int i =0; i < yTheoreticalDistance.length; i++) {
2077
                    if (from.isUnobstructed(yTheoreticalDistance[i])) yTheoreticalDistance[i] = 0.3;
2078
                }
2079
            } else if (from.isUnobstructed(thisMove.yAllowedDistance)) thisMove.yAllowedDistance = 0.3;
2080
            tags.add("v_exiting_liquid");
2081
        }
2082
        
2083
        
2084
        //////////////////////////////////
2085
        // Last client-tick/move        //
2086
        //////////////////////////////////
2087
        if (from.isInLiquid() && verticalLiquidPushComponent != 0.0) {
2088
            // Liquid vertical push component calculated in hdistrel.
2089
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, verticalLiquidPushComponent, Operation.ADD);
2090
        }
2091
        // *----------TridentItem.releaseUsing(), apply trident motion----------*
2092
        if (thisMove.tridentRelease.decideOptimistically()) {
2093
            thisMove.tridentRelease = AlmostBoolean.YES;
2094
            // Riptide works by propelling the player in air after releasing the trident (the effect only pushes the player, unless is on ground)
2095
            final Vector riptideVelocity = to.getRiptideVelocity(onGround);
2096
            final double fric = getLastYGroundRipTide(from, lastMove, data, cData);
2097
            if (fric != 0.0) {
2098
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, riptideVelocity.getY() + fric, Operation.SET);
2099
            } 
2100
            else {
2101
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, riptideVelocity.getY(), Operation.ADD);
2102
            }
2103
        }
2104
        //  Special case for riptide at the start of the movement tick (when the riptide move is "unified" and not split into two updates; friction of the next move is used here)
2105
        if (lastMove.tridentRelease.decide() && lastMove.toIsValid) {
2106
            final PlayerMoveData secondLastMove = data.playerMoves.getSecondPastMove();
2107
            if (lastMove.from.onGround || (secondLastMove.toIsValid && secondLastMove.yDistance <= 0.0 && (secondLastMove.from.onGround || secondLastMove.fromLostGround))) {
2108
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.RIPTIDE_ON_GROUND_MOVE * data.lastFrictionVertical, Operation.SUBTRACT);
2109
            }
2110
        }
2111
        if (from.isInWater() && pData.getClientVersion().isHigherThan(ClientVersion.V_1_12_2)) {
2112
            // *----------LocalPlayer.aiStep(), goDownInWater()----------*
2113
            if (pData.isShiftKeyPressed()) {
2114
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.LIQUID_SPEED_GAIN, Operation.SUBTRACT);
2115
            }
2116
        }
2117
        // *----------LivingEntity.aiStep(), negligible speed----------*
2118
        checkNegligibleMomentumVertical(pData, thisMove, yTheoreticalDistance);
2119
        // *----------EntityLiving.aiStep(), apply liquid motion----------*
2120
        if (from.isInLiquid()) {
2121
            // *----------------------------------------------------------------------------------------------------------------------------*
2122
            // *----- When in liquid, the game doesn't care about players being on ground, only if they press the space bar.   -------------*
2123
            // *----- When they do press it, the game sets the jumping field to true.   ----------------------------------------------------*
2124
            // *----- However, up until MC 1.21.2 we couldn't know this, because the player used to not send anything about it -------------*
2125
            // *----- Solution: if the client/server does not support input reading/sending, loop the space bar impulse   ------------------*
2126
            // *----------------------------------------------------------------------------------------------------------------------------* 
2127
            if (yTheoreticalDistance == null) {
2128
                // From: EntityLiving.java -> aiStep() and KeyboardInput.java.
2129
                if (data.input.isSpaceBarPressed()) {
2130
                    boolean isSubmergedInWater = from.isInWater() && thisMove.submergedWaterHeight > 0.0;
2131
                    double fluidJumpThreshold = from.getEyeHeight() < 0.4D ? 0.0D : 0.4D;
2132
                    if (isSubmergedInWater && (!onGround || thisMove.submergedWaterHeight > fluidJumpThreshold)) {
2133
                        thisMove.yAllowedDistance += Magic.LIQUID_SPEED_GAIN; // The game distinguishes liquid tagkeys, but the motion is the same...
2134
                    } 
2135
                    else if (from.isInLava() && (!onGround || thisMove.submergedLavaHeight > fluidJumpThreshold)) {
2136
                        thisMove.yAllowedDistance += Magic.LIQUID_SPEED_GAIN;
2137
                    } 
2138
                    else if ((onGround || isSubmergedInWater && thisMove.submergedWaterHeight <= fluidJumpThreshold) && data.jumpDelay == 0) {
2139
                        thisMove.yAllowedDistance = data.liftOffEnvelope.getJumpGain(data.jumpAmplifier) * attributeAccess.getHandle().getJumpGainMultiplier(player);
2140
                        data.jumpDelay = Magic.MAX_JUMP_DELAY;
2141
                        thisMove.hasImpulse = AlmostBoolean.YES; // Minecraft explicitly tells us that there's impulse in this case.
2142
                        thisMove.isJump = true;
2143
                    }
2144
                } 
2145
                else {
2146
                    data.jumpDelay = 0;
2147
                }
2148
                //*--------Player.java, travel(). Apply swimming speed-------*
2149
                // 1.13 swimming speed depends on the looking direction vector of the player.
2150
                // Small note: the game here does NOT explicitly ensure that the player is also in water. Thus, this should be checked outside the from.isInLiquid() condition
2151
                if (Bridge1_13.isSwimming(player) && from.getEntity() instanceof Player) { // inside vehicle checking would always return false, since Sf doesn't run for vehicles, but in the future, we might merge vehicle checks
2152
                    Vector lookVector = TrigUtil.getLookingDirection(to, player);
2153
                    double swimmingScalar = lookVector.getY() < -0.2 ? 0.085 : 0.06;
2154
                    if (lookVector.getY() <= 0.0 || data.input.isSpaceBarPressed()
2155
                        || BlockProperties.getLiquidHeightAt(from.getBlockCache(), Location.locToBlock(from.getX()), Location.locToBlock(from.getY() + 1.0 - 0.1), Location.locToBlock(from.getZ()), BlockFlags.F_WATER, true) != 0.0) {
2156
                        thisMove.yAllowedDistance += (lookVector.getY() - thisMove.yAllowedDistance) * swimmingScalar;
2157
                    }
2158
                }
2159
            }
2160
            else {
2161
                boolean isSubmergedInWater = from.isInWater() && thisMove.submergedWaterHeight > 0.0;
2162
                double fluidJumpThreshold = from.getEyeHeight() < 0.4D ? 0.0D : 0.4D;
2163
                if (isSubmergedInWater && (!onGround || thisMove.submergedWaterHeight > fluidJumpThreshold)) {
2164
                    yTheoreticalDistance[0] += Magic.LIQUID_SPEED_GAIN;
2165
                }
2166
                else if (from.isInLava() && (!onGround || thisMove.submergedLavaHeight > fluidJumpThreshold)) {
2167
                    yTheoreticalDistance[0] += Magic.LIQUID_SPEED_GAIN;
2168
                }
2169
                else if ((onGround || isSubmergedInWater && thisMove.submergedWaterHeight <= fluidJumpThreshold) && data.jumpDelay == 0) {
2170
                    yTheoreticalDistance[0] = data.liftOffEnvelope.getJumpGain(data.jumpAmplifier) * attributeAccess.getHandle().getJumpGainMultiplier(player);
2171
                    data.jumpDelay = Magic.MAX_JUMP_DELAY;
2172
                    thisMove.hasImpulse = AlmostBoolean.YES;
2173
                    // (Can't set thisMove.isJump yet.)
2174
                }
2175
                if (Bridge1_13.isSwimming(player) && !player.isInsideVehicle()) {
2176
                    Vector lookVector = TrigUtil.getLookingDirection(to, player);
2177
                    double swimmingScalar = lookVector.getY() < -0.2 ? 0.085 : 0.06;
2178
                    // Note: Since thisMove.isJump is always false because not been set yet, make these conditions unusable, result in brute force
2179
                    //if (lookVector.getY() <= 0.0 || thisMove.isJump 
2180
                    //    || BlockProperties.getLiquidHeightAt(from.getBlockCache(), Location.locToBlock(from.getX()), Location.locToBlock(from.getY()+1.0-0.1), Location.locToBlock(from.getZ()), BlockFlags.F_WATER, true) != 0.0) {
2181
                    yTheoreticalDistance[0] += (lookVector.getY() - yTheoreticalDistance[0]) * swimmingScalar;
2182
                    yTheoreticalDistance[1] += (lookVector.getY() - yTheoreticalDistance[1]) * swimmingScalar;
2183
                    //}
2184
                }
2185
            }
2186
        }
2187
        // *----------LivingEntity.travel(), handleRelativeFrictionAndCalculateMovement() -> handleOnClimbable()----------*
2188
        if (!from.isInLiquid() && from.isOnClimbable() && from.canClimbUp(data.liftOffEnvelope.getMaxJumpHeight(data.jumpAmplifier))) {
2189
            // Should replicate the condition: !this.getInBlockState().is(Blocks.SCAFFOLDING)
2190
            final Material typeId = from.getBlockType();
2191
            final long theseFlags = BlockFlags.getBlockFlags(typeId);
2192
            if (yTheoreticalDistance != null) {
2193
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
2194
                    yTheoreticalDistance[i] = Math.max(yTheoreticalDistance[i], -Magic.CLIMBABLE_MAX_SPEED);
2195
                    if (yTheoreticalDistance[i] < 0.0 && pData.isShiftKeyPressed() && from.getEntity() instanceof Player
2196
                        && (theseFlags & BlockFlags.F_SCAFFOLDING) == 0 && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
2197
                        yTheoreticalDistance[i] = 0.0;
2198
                    }
2199
                }
2200
            } else {
2201
                thisMove.yAllowedDistance = Math.max(thisMove.yAllowedDistance, -Magic.CLIMBABLE_MAX_SPEED);
2202
                if (thisMove.yAllowedDistance < 0.0 && pData.isShiftKeyPressed() && from.getEntity() instanceof Player
2203
                    && (theseFlags & BlockFlags.F_SCAFFOLDING) == 0 && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
2204
                    thisMove.yAllowedDistance = 0.0;
2205
                }
2206
            }
2207
            tags.add("v_climbable");
2208
        }
2209
        // *----------Beginning call of Entity.move(); apply stuck speed multipliers----------*
2210
        if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
2211
            // If we looped the space bar impulse, all later modifiers are applied to each speed.
2212
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.nextStuckInBlockVertical, Operation.MULTIPLY);
2213
        }
2214
        // *----------Entity.move(), call the collide() function----------*
2215
        // Include horizontal motion to account for stepping: there are cases where NCP's isStep definition fails to catch it.
2216
        // (In which case, isStep will return false and fall-back to friction here)
2217
        // It is imperative that you pass yAllowedDistance as argument here (not the real yDistance), because if the player isn't on ground, the current motion will be used to determine it (collideY && motionY < 0.0). Passing an uncontrolled yDistance will be easily exploitable.
2218
        if (yTheoreticalDistance == null) {
2219
            Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, thisMove.yAllowedDistance, thisMove.zAllowedDistance), fromOnGround || thisMove.fromLostGround && lastMove.yDistance < 0.0, from.getBoundingBox());
2220
            thisMove.headObstructed = thisMove.yAllowedDistance != collisionVector.getY() && thisMove.yDistance >= 0.0 && !fromOnGround;  // New definition of head obstruction: yDistance is checked because Minecraft considers players to be on ground when motion is explicitly negative
2221
            // If this vertical move resulted in a collision, remember it.
2222
            thisMove.collideY = collisionVector.getY() != thisMove.yAllowedDistance;
2223
            thisMove.yAllowedDistance = collisionVector.getY();
2224
        }
2225
        else {
2226
            for (int i = 0; i < yTheoreticalDistance.length; i++) {
2227
                Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, yTheoreticalDistance[i], thisMove.zAllowedDistance), fromOnGround || thisMove.fromLostGround && lastMove.yDistance < 0.0, from.getBoundingBox());
2228
                if (yTheoreticalDistance[i] != collisionVector.getY()) {
2229
                    // This theoretical speed would result in a collision. Remember it.
2230
                    collideLiquidY[i] = true;
2231
                }
2232
                //TODO: Might wrong if underliquid as not all moves are headObstructed
2233
                thisMove.headObstructed = yTheoreticalDistance[i] != collisionVector.getY() && thisMove.yDistance >= 0.0 && !fromOnGround;
2234
                yTheoreticalDistance[i] = collisionVector.getY();
2235
            }
2236
        }
2237
        
2238
        
2239
        ////////////////////////////////////////////////////////////////////////////
2240
        // Calculate the offset: check for velocity and workarounds on violations // 
2241
        ////////////////////////////////////////////////////////////////////////////
2242
        if (yTheoreticalDistance != null) {
2243
            final double hiddenThreshold = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2) ? Magic.Minecraft_minMoveSqDistance_legacy : Magic.Minecraft_minMoveSqDist_modern;
2244
            if (thisMove.hDistance < hiddenThreshold) {
2245
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
2246
                    if (yTheoreticalDistance[i] < hiddenThreshold && !collideLiquidY[i]) {
2247
                        thisMove.hiddenYDistanceIndex = i;
2248
                        break;
2249
                    }
2250
                }
2251
            }
2252
            boolean found = false;
2253
            for (int i = 0; i < yTheoreticalDistance.length; i++) {
2254
                if (MathUtil.isOffsetWithinPredictionEpsilon(thisMove.yDistance, yTheoreticalDistance[i])) {
2255
                    thisMove.yAllowedDistance = yTheoreticalDistance[i];
2256
                    thisMove.collideY = collideLiquidY[i];
2257
                    found = true;
2258
                    break;
2259
                }
2260
            }
2261
            if (!found && thisMove.hiddenYDistanceIndex != -1) {
2262
                final double result[] = HiddenMotionReconstructor.findBestHiddenTickExplanation(yTheoreticalDistance[thisMove.hiddenYDistanceIndex], player, data, cData, pData, from, to, attributeAccess.getHandle().getJumpGainMultiplier(player), 
2263
                                                                                                verticalLiquidPushComponent, onGround, yTheoreticalDistance[thisMove.hiddenYDistanceIndex]);
2264
                yTheoreticalDistance[thisMove.hiddenYDistanceIndex] += result[0];
2265
                if (MathUtil.isOffsetWithinPredictionEpsilon(thisMove.yDistance, yTheoreticalDistance[thisMove.hiddenYDistanceIndex])) {
2266
                    thisMove.yAllowedDistance = yTheoreticalDistance[thisMove.hiddenYDistanceIndex];
2267
                    thisMove.collideY = collideLiquidY[thisMove.hiddenYDistanceIndex];
2268
                    thisMove.yCorrectedDistancePre = result[0];
2269
                    found = true;
2270
                    tags.add("v_hidden");
2271
                }
2272
            }
2273
        }
2274
        /* Expected difference from current to allowed */
2275
        final double offset = thisMove.yDistance - thisMove.yAllowedDistance;
2276
        if (Math.abs(offset) < Magic.PREDICTION_EPSILON) {
2277
            // Accuracy margin.
2278
        }
2279
        else {
2280
            // Check for workarounds at the end and override the prediction if needed (just allow the movement in this case.)
2281
            if (MagicWorkarounds.checkPostPredictWorkaround(data, fromOnGround, toOnGround, from, to, thisMove.yAllowedDistance, player, isNormalOrPacketSplitMove)) {
2282
                thisMove.yAllowedDistance = thisMove.yDistance;
2283
                if (debug) {
2284
                    player.sendMessage("[SurvivalFly] Workaround ID used: " + (!justUsedWorkarounds.isEmpty() ? StringUtil.join(justUsedWorkarounds, " , ") : ""));
2285
                }
2286
            }
2287
            else if (data.getOrUseVerticalVelocity(yDistance).isEmpty()) {
2288
                // If velocity can be used for compensation, use it.
2289
                yDistanceAboveLimit = Math.max(yDistanceAboveLimit, Math.abs(offset));
2290
                tags.add("vdistrel");
2291
                if (debug) {
2292
                    player.sendMessage(ChatColor.RED + "[SurvivalFly] vdistrel: predicted=" + StringUtil.fdec6.format(thisMove.yAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.yDistance) + ", offset=" + StringUtil.fdec6.format(offset));
2293
                }
2294
            }
2295
        }
2296
        return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
2297
    }
2298
2299
    private double getLastYGroundRipTide(PlayerLocation from, PlayerMoveData lastMove, MovingData data, CombinedData cData) {
2300
        double tmp = 0.0;
2301
        if (lastMove.tridentRelease == AlmostBoolean.MAYBE) {
2302
            if (lastMove.from.inWater) {
2303
                return from.getFluidFallingAdjustedMovement(data.lastGravity, true, new Vector(0.0, 0.0, 0.0), false).getY();
2304
            }
2305
            else if (lastMove.from.inLava) {
2306
                // Lava friction is quite odd. Depending on specified thresholds, it can be 0.5 or 0.8
2307
                if (data.lastFrictionVertical != Magic.LAVA_VERTICAL_INERTIA) {
2308
                    tmp = from.getFluidFallingAdjustedMovement(data.lastGravity, true, new Vector(0.0, 0.0, 0.0), false).getY();
2309
                }
2310
                else {
2311
                    // Otherwise, 0.5
2312
                    tmp *= data.lastFrictionVertical;
2313
                }
2314
                if (data.lastGravity != 0.0) {
2315
                    tmp += -data.lastGravity / 4.0;
2316
                }
2317
            }
2318
            else {
2319
                // Air motion
2320
                if (cData.wasLevitating) {
2321
                    // Levitation forces players to ascend and does not work in liquids, so thankfully we don't have to account for that, other than stuck-speed.
2322
                    tmp += (0.05 * data.lastLevitationLevel - lastMove.yAllowedDistance) * 0.2;
2323
                }
2324
                else tmp -= data.lastGravity;
2325
                tmp *= data.lastFrictionVertical;
2326
            }
2327
        }
2328
        return tmp;
2329
    }
2330
2331
2332
    /**
2333
     * After-horizontal-failure checks.
2334
     *
2335
     * @return hAllowedDistance, hDistanceAboveLimit, hFreedom
2336
     */
2337
    private double[] hDistAfterFailure(final Player player,
2338
                                       final PlayerLocation from, final PlayerLocation to,
2339
                                       double hAllowedDistance, double hDistanceAboveLimit,
2340
                                       final PlayerMoveData thisMove, final PlayerMoveData lastMove, final boolean debug,
2341
                                       final MovingData data, final MovingConfig cc, final IPlayerData pData, final int tick,
2342
                                       boolean useBlockChangeTracker, final boolean fromOnGround, final boolean toOnGround,
2343
                                       final boolean isNormalOrPacketSplitMove) {
2344
        /*
2345
         * 0: If we got a speed violation and the player is using an item, assume it to be a "noslowdown" violation.
2346
         */
2347
        if (cc.survivalFlyResetItem && BridgeMisc.isSlowedDownByUsingAnItem(player) && !Bridge1_9.isGliding(player)) {
2348
            // Forcibly release the item in use.
2349
            pData.requestItemUseResync();
2350
            tags.add("itemresync");
2351
            if (!BridgeMisc.isSlowedDownByUsingAnItem(player) && hDistanceAboveLimit > 0.0) {
2352
                // Re-estimate with released item (if it still throws a VL, the player is actually cheating, if the item is still in use, then it wasn't desync'ed).
2353
                double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, false);
2354
                hAllowedDistance = res[0];
2355
                hDistanceAboveLimit = res[1];
2356
            }
2357
        }
2358
        /*
2359
         *  Because this move is not sent by the client and cannot be predicted through normal means, we have to brute force it.
2360
         */
2361
        if (hDistanceAboveLimit > 0.0 && lastMove.possibleStopMotion) {
2362
            lastMove.possibleStopMotion = false;
2363
            tags.add("stop_motion");
2364
            double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, false);
2365
            hAllowedDistance = res[0];
2366
            hDistanceAboveLimit = res[1];
2367
        }
2368
        /*
2369
         * 2: Undetectable jump (must brute force here): player failed with the onGround flag, lets try with off-ground then.
2370
         */
2371
        if (PhysicsEnvelope.isVerticallyConstricted(from, to, pData) && hDistanceAboveLimit > 0.0) {
2372
            tags.add("vert_constricted");
2373
            double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, true);
2374
            hAllowedDistance = res[0];
2375
            hDistanceAboveLimit = res[1];
2376
        }
2377
        /*
2378
         * 3: Above limit again? Check for past onGround states caused by block changes (i.e.: ground was pulled off from the player's feet)
2379
         */
2380
        if (useBlockChangeTracker && hDistanceAboveLimit > 0.0) {
2381
            // Be sure to test this only if the player is seemingly off ground
2382
            if (!thisMove.fromLostGround && !from.isOnGround() && from.isOnGroundOpportune(cc.yOnGround, 0L, blockChangeTracker, data.blockChangeRef, tick)) {
2383
                tags.add("onground_tracked");
2384
                double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, true, false);
2385
                hAllowedDistance = res[0];
2386
                hDistanceAboveLimit = res[1];
2387
            }
2388
        }
2389
        /* 
2390
         * 4: Distance is still above limit; last resort: check if the distance above limit can be covered with velocity
2391
         */
2392
        // TODO: Implement Asofold's fix to prevent too easy abuse:
2393
        // See: https://github.com/NoCheatPlus/Issues/issues/374#issuecomment-296172316
2394
        //double hFreedom = 0.0; // Horizontal velocity used.
2395
        //if (hDistanceAboveLimit > 0.0) {
2396
        //    hFreedom = data.getHorizontalFreedom();
2397
        //    if (hFreedom < hDistanceAboveLimit) {
2398
        //        // Distance above limit is still greater. Try using queued velocity if possible.
2399
        //        hFreedom += data.useHorizontalVelocity(hDistanceAboveLimit - hFreedom);
2400
        //    }
2401
        //    if (hFreedom > 0.0) {
2402
        //        tags.add("hvel");
2403
        //        hDistanceAboveLimit = Math.max(0.0, hDistanceAboveLimit - hFreedom);
2404
        //    }
2405
        //}
2406
        return new double[]{hAllowedDistance, hDistanceAboveLimit, 0.0};
2407
    }
2408
    
2409
    /**
2410
     * Handles a violation for Survivalfly.
2411
     * 
2412
     * @return The Location where the player will be set backed to.
2413
     */
2414
    private Location handleViolation(final double result,
2415
                                     final Player player, final PlayerLocation from, final PlayerLocation to,
2416
                                     final MovingData data, final MovingConfig cc) {
2417
        // Increment violation level.
2418
        data.survivalFlyVL += result;
2419
        data.sfVLMoveCount = data.getPlayerMoveCount();
2420
        final ViolationData vd = new ViolationData(this, player, data.survivalFlyVL, result, cc.survivalFlyActions);
2421
        if (vd.needsParameters()) {
2422
            vd.setParameter(ParameterName.LOCATION_FROM, String.format(Locale.US, "%.2f, %.2f, %.2f", from.getX(), from.getY(), from.getZ()));
2423
            vd.setParameter(ParameterName.LOCATION_TO, String.format(Locale.US, "%.2f, %.2f, %.2f", to.getX(), to.getY(), to.getZ()));
2424
            vd.setParameter(ParameterName.DISTANCE, String.format(Locale.US, "%.2f", TrigUtil.distance(from, to)));
2425
            vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
2426
        }
2427
        // Some resetting is done in MovingListener.
2428
        if (executeActions(vd).willCancel()) {
2429
            // Set back + view direction of to (more smooth).
2430
            return MovingUtil.getApplicableSetBackLocation(player, to.getYaw(), to.getPitch(), to, data, cc);
2431
        }
2432
        else {
2433
            data.sfJumpPhase = 0;
2434
            // Cancelled by other plugin, or no cancel set by configuration.
2435
            return null;
2436
        }
2437
    }
2438
2439
2440
    /**
2441
     * Hover violations have to be handled in this check, because they are handled as SurvivalFly violations (needs executeActions).
2442
     */
2443
    public final void handleHoverViolation(final Player player, final PlayerLocation loc, final MovingConfig cc, final MovingData data) {
2444
        data.survivalFlyVL += cc.sfHoverViolation;
2445
        // TODO: Extra options for set back / kick, like vl?
2446
        data.sfVLMoveCount = data.getPlayerMoveCount();
2447
        data.sfVLInAir = true;
2448
        final ViolationData vd = new ViolationData(this, player, data.survivalFlyVL, cc.sfHoverViolation, cc.survivalFlyActions);
2449
        if (vd.needsParameters()) {
2450
            vd.setParameter(ParameterName.LOCATION_FROM, String.format(Locale.US, "%.2f, %.2f, %.2f", loc.getX(), loc.getY(), loc.getZ()));
2451
            vd.setParameter(ParameterName.LOCATION_TO, "(HOVER)");
2452
            vd.setParameter(ParameterName.DISTANCE, "0.0(HOVER)");
2453
            vd.setParameter(ParameterName.TAGS, "hover");
2454
        }
2455
        if (executeActions(vd).willCancel()) {
2456
            // Set back or kick.
2457
            final Location newTo = MovingUtil.getApplicableSetBackLocation(player, loc.getYaw(), loc.getPitch(), loc, data, cc);
2458
            if (newTo != null) {
2459
                data.prepareSetBack(newTo);
2460
                SchedulerHelper.teleportEntity(player, newTo, BridgeMisc.TELEPORT_CAUSE_CORRECTION_OF_POSITION);
2461
            }
2462
            else {
2463
                // Solve by extra actions ? Special case (probably never happens)?
2464
                player.kickPlayer("Hovering?");
2465
            }
2466
        }
2467
        else {
2468
            // Ignore.
2469
        }
2470
    }
2471
2472
2473
    /**
2474
     * Debug output.
2475
     */
2476
    private void outputDebug(final Player player, final PlayerLocation to, final PlayerLocation from,
2477
                             final MovingData data,
2478
                             final double hDistance, final double hAllowedDistance, final double hFreedom,
2479
                             final double yDistance, final double yAllowedDistance,
2480
                             final boolean fromOnGround, final boolean resetFrom,
2481
                             final boolean toOnGround, final boolean resetTo,
2482
                             final PlayerMoveData thisMove) {
2483
2484
        // TODO: Show player name once (!)
2485
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
2486
        final double yDistDiffEx = yDistance - yAllowedDistance;
2487
        final double hDistDiffEx = thisMove.hDistance - thisMove.hAllowedDistance;
2488
        final StringBuilder builder = new StringBuilder(500);
2489
        builder.append(CheckUtils.getLogMessagePrefix(player, type));
2490
        final String hVelUsed = hFreedom > 0 ? " / hVelUsed: " + StringUtil.fdec3.format(hFreedom) : "";
2491
        builder.append("\nOnGround: " + (thisMove.headObstructed ? "(head obstr.) " : from.isSlidingDown() ? "(sliding down) " : "") + (thisMove.touchedGroundWorkaround ? "(lost ground) " : "") + (fromOnGround ? "onground -> " : (resetFrom ? "resetcond -> " : "--- -> ")) + (toOnGround ? "onground" : (resetTo ? "resetcond" : "---")) + ", jumpPhase: " + data.sfJumpPhase + ", LiftOff: " + data.liftOffEnvelope.name());
2492
        final String dHDist = lastMove.toIsValid ? "(" + StringUtil.formatDiff(hDistance, lastMove.hDistance) + ")" : "";
2493
        final String dYDist = lastMove.toIsValid ? "(" + StringUtil.formatDiff(yDistance, lastMove.yDistance)+ ")" : "";
2494
        builder.append("\n" + " hDist: " + StringUtil.fdec6.format(hDistance) + dHDist + " / offset: " + hDistDiffEx + " / predicted: " + StringUtil.fdec6.format(hAllowedDistance) + hVelUsed +
2495
                "\n" + " vDist: " + StringUtil.fdec6.format(yDistance) + dYDist + " / offset: " + yDistDiffEx + " / predicted: " + StringUtil.fdec6.format(yAllowedDistance) + " , setBackY: " + (data.hasSetBack() ? (data.getSetBackY() + " (jump height: " + StringUtil.fdec3.format(to.getY() - data.getSetBackY()) + " / max jump height: " + data.liftOffEnvelope.getMaxJumpHeight(data.jumpAmplifier) + ")") : "?"));
2496
        if (lastMove.toIsValid) {
2497
            builder.append("\n fdsq: " + StringUtil.fdec3.format(thisMove.distanceSquared / lastMove.distanceSquared));
2498
        }
2499
        if (!lastMove.toIsValid) {
2500
            builder.append("\n Invalid last move (data reset)");
2501
        }
2502
        if (!lastMove.valid) {
2503
            builder.append("\n Invalid last move (missing data)");
2504
        }
2505
        if (!thisMove.verVelUsed.isEmpty()) {
2506
            builder.append(" , vVelUsed: " + thisMove.verVelUsed + " ");
2507
        }
2508
        data.addVerticalVelocity(builder);
2509
        data.addHorizontalVelocity(builder);
2510
        if (player.isSleeping()) {
2511
            tags.add("sleeping");
2512
        }
2513
        if (Bridge1_9.isWearingElytra(player)) {
2514
            // Just wearing (not isGliding).
2515
            tags.add("elytra_off");
2516
        }
2517
        if (!tags.isEmpty()) {
2518
            builder.append("\n" + " Tags: " + StringUtil.join(tags, "+"));
2519
        }
2520
        if (!justUsedWorkarounds.isEmpty()) {
2521
            builder.append("\n" + " Workaround ID: " + StringUtil.join(justUsedWorkarounds, " , "));
2522
        }
2523
        builder.append("\n");
2524
        NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, builder.toString());
2525
    }
2526
2527
2528
    private void logPostViolationTags(final Player player) {
2529
        debug(player, "SurvivalFly Post violation handling tag update:\n" + StringUtil.join(tags, "+"));
2530
    }
2531
}

How it counteracts this module

SurvivalFly builds the allowed envelope from the server-side tracked location, not the packet flags. The first replayed move of the flush is a jump from the last tracked position equal to the whole distance walked while the module was on, and the per-move allowances from prepareSpeedEstimation and vDistRel are physics-sized, so any blink that lasted more than a tick or two produces a first move far over the allowance, a violation, and a set-back teleport. The replayed path after the first move is physically consistent, so the first move is where the check lands.

anticheat MovingListener (set-back teleports)

MovingListener.java2761 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.moving;
16
17
import java.util.ArrayList;
18
import java.util.HashMap;
19
import java.util.List;
20
import java.util.Locale;
21
import java.util.Map;
22
import java.util.Set;
23
import java.util.UUID;
24
import java.util.concurrent.ConcurrentHashMap;
25
26
import org.bukkit.Bukkit;
27
import org.bukkit.GameMode;
28
import org.bukkit.Location;
29
import org.bukkit.Material;
30
import org.bukkit.entity.Entity;
31
import org.bukkit.entity.EntityType;
32
import org.bukkit.entity.Player;
33
import org.bukkit.event.EventHandler;
34
import org.bukkit.event.EventPriority;
35
import org.bukkit.event.entity.EntityDamageEvent;
36
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
37
import org.bukkit.event.entity.EntityExplodeEvent;
38
import org.bukkit.event.entity.PlayerDeathEvent;
39
import org.bukkit.event.player.PlayerBedEnterEvent;
40
import org.bukkit.event.player.PlayerBedLeaveEvent;
41
import org.bukkit.event.player.PlayerChangedWorldEvent;
42
import org.bukkit.event.player.PlayerGameModeChangeEvent;
43
import org.bukkit.event.player.PlayerMoveEvent;
44
import org.bukkit.event.player.PlayerPortalEvent;
45
import org.bukkit.event.player.PlayerRespawnEvent;
46
import org.bukkit.event.player.PlayerTeleportEvent;
47
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
48
import org.bukkit.event.player.PlayerToggleFlightEvent;
49
import org.bukkit.event.player.PlayerVelocityEvent;
50
import org.bukkit.util.Vector;
51
52
import fr.neatmonster.nocheatplus.NCPAPIProvider;
53
import fr.neatmonster.nocheatplus.actions.ActionList;
54
import fr.neatmonster.nocheatplus.actions.ParameterName;
55
import fr.neatmonster.nocheatplus.checks.Check;
56
import fr.neatmonster.nocheatplus.checks.CheckListener;
57
import fr.neatmonster.nocheatplus.checks.CheckType;
58
import fr.neatmonster.nocheatplus.checks.ViolationData;
59
import fr.neatmonster.nocheatplus.checks.combined.Combined;
60
import fr.neatmonster.nocheatplus.checks.combined.CombinedConfig;
61
import fr.neatmonster.nocheatplus.checks.combined.CombinedData;
62
import fr.neatmonster.nocheatplus.checks.combined.Improbable;
63
import fr.neatmonster.nocheatplus.checks.inventory.Open;
64
import fr.neatmonster.nocheatplus.checks.moving.envelope.BounceHandler;
65
import fr.neatmonster.nocheatplus.checks.moving.envelope.PhysicsEnvelope;
66
import fr.neatmonster.nocheatplus.checks.moving.model.BounceType;
67
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerMoveData;
68
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerMoveInfo;
69
import fr.neatmonster.nocheatplus.checks.moving.player.CreativeFly;
70
import fr.neatmonster.nocheatplus.checks.moving.player.MorePackets;
71
import fr.neatmonster.nocheatplus.checks.moving.player.NoFall;
72
import fr.neatmonster.nocheatplus.checks.moving.player.Passable;
73
import fr.neatmonster.nocheatplus.checks.moving.player.PlayerSetBackMethod;
74
import fr.neatmonster.nocheatplus.checks.moving.player.SurvivalFly;
75
import fr.neatmonster.nocheatplus.checks.moving.vehicle.VehicleChecks;
76
import fr.neatmonster.nocheatplus.checks.moving.velocity.SimpleEntry;
77
import fr.neatmonster.nocheatplus.checks.moving.velocity.VelocityFlags;
78
import fr.neatmonster.nocheatplus.checks.net.FlyingQueueHandle;
79
import fr.neatmonster.nocheatplus.checks.net.NetData;
80
import fr.neatmonster.nocheatplus.checks.net.model.DataPacketFlying;
81
import fr.neatmonster.nocheatplus.checks.net.model.DataPacketInput;
82
import fr.neatmonster.nocheatplus.compat.Bridge1_13;
83
import fr.neatmonster.nocheatplus.compat.Bridge1_9;
84
import fr.neatmonster.nocheatplus.compat.BridgeMisc;
85
import fr.neatmonster.nocheatplus.compat.MCAccess;
86
import fr.neatmonster.nocheatplus.compat.SchedulerHelper;
87
import fr.neatmonster.nocheatplus.compat.blocks.changetracker.BlockChangeTracker;
88
import fr.neatmonster.nocheatplus.compat.blocks.changetracker.BlockChangeTracker.BlockChangeEntry;
89
import fr.neatmonster.nocheatplus.compat.blocks.changetracker.BlockChangeTracker.Direction;
90
import fr.neatmonster.nocheatplus.compat.bukkit.BridgeEnchant;
91
import fr.neatmonster.nocheatplus.compat.bukkit.BridgeEntityType;
92
import fr.neatmonster.nocheatplus.compat.bukkit.BridgeHealth;
93
import fr.neatmonster.nocheatplus.compat.bukkit.BridgePotionEffect;
94
import fr.neatmonster.nocheatplus.compat.versions.ClientVersion;
95
import fr.neatmonster.nocheatplus.compat.versions.ServerVersion;
96
import fr.neatmonster.nocheatplus.components.NoCheatPlusAPI;
97
import fr.neatmonster.nocheatplus.components.data.ICheckData;
98
import fr.neatmonster.nocheatplus.components.data.IData;
99
import fr.neatmonster.nocheatplus.components.location.SimplePositionWithLook;
100
import fr.neatmonster.nocheatplus.components.modifier.IAttributeAccess;
101
import fr.neatmonster.nocheatplus.components.registry.event.IGenericInstanceHandle;
102
import fr.neatmonster.nocheatplus.components.registry.factory.IFactoryOne;
103
import fr.neatmonster.nocheatplus.components.registry.feature.IHaveCheckType;
104
import fr.neatmonster.nocheatplus.components.registry.feature.INeedConfig;
105
import fr.neatmonster.nocheatplus.components.registry.feature.IRemoveData;
106
import fr.neatmonster.nocheatplus.components.registry.feature.JoinLeaveListener;
107
import fr.neatmonster.nocheatplus.components.registry.feature.TickListener;
108
import fr.neatmonster.nocheatplus.config.ConfPaths;
109
import fr.neatmonster.nocheatplus.config.ConfigManager;
110
import fr.neatmonster.nocheatplus.logging.StaticLog;
111
import fr.neatmonster.nocheatplus.logging.Streams;
112
import fr.neatmonster.nocheatplus.logging.debug.DebugUtil;
113
import fr.neatmonster.nocheatplus.players.DataManager;
114
import fr.neatmonster.nocheatplus.players.IPlayerData;
115
import fr.neatmonster.nocheatplus.players.PlayerFactoryArgument;
116
import fr.neatmonster.nocheatplus.stats.Counters;
117
import fr.neatmonster.nocheatplus.utilities.CheckUtils;
118
import fr.neatmonster.nocheatplus.utilities.StringUtil;
119
import fr.neatmonster.nocheatplus.utilities.TickTask;
120
import fr.neatmonster.nocheatplus.utilities.build.BuildParameters;
121
import fr.neatmonster.nocheatplus.utilities.entity.PotionUtil;
122
import fr.neatmonster.nocheatplus.utilities.location.LocUtil;
123
import fr.neatmonster.nocheatplus.utilities.location.PlayerLocation;
124
import fr.neatmonster.nocheatplus.utilities.map.BlockFlags;
125
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
126
import fr.neatmonster.nocheatplus.utilities.map.MapUtil;
127
import fr.neatmonster.nocheatplus.utilities.map.MaterialUtil;
128
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
129
import fr.neatmonster.nocheatplus.utilities.moving.AuxMoving;
130
import fr.neatmonster.nocheatplus.utilities.moving.Magic;
131
import fr.neatmonster.nocheatplus.utilities.moving.MovingUtil;
132
import fr.neatmonster.nocheatplus.worlds.WorldFactoryArgument;
133
134
135
/**
136
 * Central location to listen to events that are relevant for the moving checks.
137
 */
138
public class MovingListener extends CheckListener implements TickListener, IRemoveData, IHaveCheckType, INeedConfig, JoinLeaveListener {
139
140
    /** The no fall check. **/
141
    public final NoFall noFall = addCheck(new NoFall());
142
143
    /** The creative fly check. */
144
    private final CreativeFly creativeFly = addCheck(new CreativeFly());
145
146
    /** The more packets check. */
147
    private final MorePackets morePackets = addCheck(new MorePackets());
148
    
149
    /** Vehicle checks */
150
    private final VehicleChecks vehicleChecks = new VehicleChecks();
151
152
    /** The survival fly check. */
153
    private final SurvivalFly survivalFly = addCheck(new SurvivalFly());
154
155
    /** The Passable check. */
156
    private final Passable passable = addCheck(new Passable());
157
    
158
    /** Store events by player name, in order to invalidate moving processing on higher priority level in case of teleports. */
159
    private final Map<String, PlayerMoveEvent> processingEvents = new HashMap<String, PlayerMoveEvent>();
160
161
    /** Player names to check hover for, case-insensitive. */
162
    private final Set<String> hoverTicks = ConcurrentHashMap.newKeySet(30);
163
164
    /** Player names to check enforcing the location for in onTick, case-insensitive. */
165
    private final Set<String> playersEnforce = ConcurrentHashMap.newKeySet(30);
166
167
    private int hoverTicksStep = 5;
168
169
    /** Location (depending on the event) for temporary use with getLocation(useLoc). Always call setWorld(null) after use. Use LocUtil.clone before passing to other API. */
170
    final Location useLoc = new Location(null, 0, 0, 0); 
171
    final Location useBedLeaveLoc = new Location(null, 0, 0, 0);
172
    final Location useChangeWorldLoc = new Location(null, 0, 0, 0);
173
    final Location useDeathLoc = new Location(null, 0, 0, 0);
174
    final Location useFallLoc = new Location(null, 0, 0, 0);
175
    final Location useJoinLoc = new Location(null, 0, 0, 0);
176
    final Location useLeaveLoc = new Location(null, 0, 0, 0);
177
    final Location useToggleFlightLoc = new Location(null, 0, 0, 0);
178
    final Location useTickLoc = new Location(null, 0, 0, 0);
179
180
    /** Auxiliary functionality. */
181
    private final AuxMoving aux = NCPAPIProvider.getNoCheatPlusAPI().getGenericInstance(AuxMoving.class);
182
183
    private final BlockChangeTracker blockChangeTracker;
184
185
    /** Statistics / debugging counters. */
186
    private final Counters counters = NCPAPIProvider.getNoCheatPlusAPI().getGenericInstance(Counters.class);
187
    
188
    /** Access to player's attributes (mainly speed-related) */
189
    private IGenericInstanceHandle<IAttributeAccess> attributeAccess = NCPAPIProvider.getNoCheatPlusAPI().getGenericInstanceHandle(IAttributeAccess.class);
190
191
    private final int idMoveEvent = counters.registerKey("event.player.move");
192
193
    private final boolean ServerIsAtLeast1_19_4 = ServerVersion.isAtLeast("1.19.4");
194
195
    @SuppressWarnings("unchecked")
196
    public MovingListener() {
197
        super(CheckType.MOVING);
198
        // Register vehicleChecks.
199
        final NoCheatPlusAPI api = NCPAPIProvider.getNoCheatPlusAPI();
200
        api.addComponent(vehicleChecks);
201
        blockChangeTracker = NCPAPIProvider.getNoCheatPlusAPI().getBlockChangeTracker();
202
        // Register config and data.
203
        // Should register before creating Check instances ?
204
        api.register(api.newRegistrationContext()
205
                // MovingConfig
206
                .registerConfigWorld(MovingConfig.class)
207
                .factory(new IFactoryOne<WorldFactoryArgument, MovingConfig>() {
208
                    @Override
209
                    public MovingConfig getNewInstance(final WorldFactoryArgument arg) {
210
                        return new MovingConfig(arg.worldData);
211
                    }
212
                })
213
                .registerConfigTypesPlayer(CheckType.MOVING, true)
214
                .context() //
215
                // MovingData
216
                .registerDataPlayer(MovingData.class)
217
                .factory(new IFactoryOne<PlayerFactoryArgument, MovingData>() {
218
                    @Override
219
                    public MovingData getNewInstance(final PlayerFactoryArgument arg) {
220
                        return new MovingData(arg.worldData.getGenericInstance(MovingConfig.class), arg.playerData);
221
                    }
222
                })
223
                .addToGroups(CheckType.MOVING, false, IData.class, ICheckData.class)
224
                .removeSubCheckData(CheckType.MOVING, true)
225
                .context() //
226
        );
227
    }
228
229
230
    /** We listen to this event to remember upon exit if the player had been in a bed. */
231
    @EventHandler(priority = EventPriority.MONITOR)
232
    public void onPlayerSleep(final PlayerBedEnterEvent event) {
233
        DataManager.getGenericInstance(event.getPlayer(), MovingData.class).wasInBed = true;
234
    }
235
236
    
237
    /** On leaving a bed, check if the player had been in it. Prevents flying by faking bed-leave packets */
238
    @EventHandler(priority = EventPriority.MONITOR)
239
    public void onPlayerWake(final PlayerBedLeaveEvent event) {
240
        final Player player = event.getPlayer();
241
        final IPlayerData pData = DataManager.getPlayerData(player);
242
        final MovingData data = pData.getGenericInstance(MovingData.class);
243
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
244
    
245
        if (pData.isCheckActive(CheckType.MOVING_SURVIVALFLY, player) && survivalFly.checkBed(player, cc, data)) {
246
            // Check if the player has to be reset.
247
            // To "cancel" the event, we teleport the player.
248
            Location newTo = null;
249
            final Location loc = player.getLocation(useBedLeaveLoc);
250
            final PlayerMoveInfo moveInfo = aux.usePlayerMoveInfo();
251
            moveInfo.set(player, loc, null, cc.yOnGround);
252
            final boolean sfCheck = MovingUtil.shouldCheckSurvivalFly(player, moveInfo.from, moveInfo.to, data, cc, pData);
253
            aux.returnPlayerMoveInfo(moveInfo);
254
            if (sfCheck) {
255
                newTo = MovingUtil.getApplicableSetBackLocation(player, loc.getYaw(), loc.getPitch(), moveInfo.from, data, cc);
256
            }
257
            if (newTo == null) {
258
                newTo = LocUtil.clone(loc);
259
            }
260
            if (sfCheck && cc.sfSetBackPolicyFallDamage && noFall.isEnabled(player, pData)) {
261
                // Check if to deal damage.
262
                double y = loc.getY();
263
                if (data.hasSetBack()) y = Math.min(y, data.getSetBackY());
264
                noFall.checkDamage(player, y, data, pData);
265
            }
266
            // Cleanup
267
            useBedLeaveLoc.setWorld(null);
268
            // Teleport.
269
            data.prepareSetBack(newTo);  
270
            SchedulerHelper.teleportEntity(player, newTo, BridgeMisc.TELEPORT_CAUSE_CORRECTION_OF_POSITION);
271
        }
272
        // Player was sleeping and is now out of the bed, reset.
273
        else data.wasInBed = false;
274
    }
275
276
277
    /** Temporary fix "stuck" on boat for 1.14-1.19 */
278
    @EventHandler(priority = EventPriority.LOWEST)
279
    public void onUnknowBoatTeleport(final PlayerTeleportEvent event) {
280
        if (!Bridge1_13.hasIsSwimming() || ServerIsAtLeast1_19_4) return;
281
        if (event.getCause() == TeleportCause.UNKNOWN) {
282
            final Player player = event.getPlayer();
283
            final IPlayerData pData = DataManager.getPlayerData(player);
284
            final MovingData data = pData.getGenericInstance(MovingData.class);
285
            if (data.lastVehicleType != null && standsOnEntity(player, player.getLocation().getY())) {
286
                event.setCancelled(true);
287
                player.setSwimming(false);
288
            }
289
        }
290
    }
291
292
293
    private boolean standsOnEntity(final Entity entity, final double minY) {
294
            // TODO: Probably check other ids too before doing this ?
295
            for (final Entity other : entity.getNearbyEntities(1.5, 1.5, 1.5)) {
296
                final EntityType type = other.getType();
297
                if (!MaterialUtil.isBoat(type)) { 
298
                    continue; 
299
                }
300
                final Material m = other.getLocation().getBlock().getType();
301
                final double locY = other.getLocation().getY();
302
                return Math.abs(locY - minY) < 0.7 && BlockProperties.isLiquid(m);
303
            }
304
        return false;
305
    }
306
307
    
308
    /** Reset data on world change */
309
    @EventHandler(priority = EventPriority.MONITOR)
310
    public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) {
311
        final Player player = event.getPlayer();
312
        final IPlayerData pData = DataManager.getPlayerData(player);
313
        final MovingData data = pData.getGenericInstance(MovingData.class);
314
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
315
        data.clearMostMovingCheckData();
316
        final Location loc = player.getLocation(useChangeWorldLoc);
317
        data.setSetBack(loc);
318
        if (cc.loadChunksOnWorldChange) {
319
            MovingUtil.ensureChunksLoaded(player, loc, "world change", data, cc, pData);
320
        }
321
        aux.resetPositionsAndMediumProperties(player, loc, data, cc);
322
        data.resetTrace(player, loc, TickTask.getTick(), mcAccess.getHandle(), cc);
323
        // Just in case.
324
        if (cc.enforceLocation) {
325
            playersEnforce.add(player.getName());
326
        }
327
        useChangeWorldLoc.setWorld(null);
328
    }
329
    
330
    // NOTE: IgnoreCancelled = true?
331
    @EventHandler(priority = EventPriority.MONITOR)
332
    public void onWindChargeExplode(EntityExplodeEvent e) {
333
        if (e.getEntity().getType() == BridgeEntityType.WIND_CHARGE) {
334
            Location loc = e.getLocation();
335
            for (Entity affectedPlayer : loc.getWorld().getNearbyEntities(loc, 1.2, 1.2, 1.2, (entity) -> entity.getType() == EntityType.PLAYER)) {
336
                final Player player = (Player) affectedPlayer;
337
                final IPlayerData pData = DataManager.getPlayerData(player);
338
                final MovingData data = pData.getGenericInstance(MovingData.class);
339
                if (!pData.isCheckActive(CheckType.MOVING, player)) continue;
340
                data.noFallCurrentLocOnWindChargeHit = player.getLocation().clone();
341
            }
342
        }
343
    }
344
    
345
346
    /** (ignoreCancelled = false: we track the bit of vertical extra momentum/thing). */
347
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
348
    public void onPlayerToggleFlight(final PlayerToggleFlightEvent event) {
349
        final Player player = event.getPlayer();
350
        if (player.isFlying() || event.isFlying() && !event.isCancelled())  {
351
            return;
352
        }
353
        final IPlayerData pData = DataManager.getPlayerData(player);
354
        if (!pData.isCheckActive(CheckType.MOVING, player)) {
355
            return;
356
        }
357
        final MovingData data = pData.getGenericInstance(MovingData.class);
358
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
359
        final PlayerMoveInfo moveInfo = aux.usePlayerMoveInfo();
360
        final Location loc = player.getLocation(useToggleFlightLoc);
361
        moveInfo.set(player, loc, null, cc.yOnGround);
362
        if (!MovingUtil.shouldCheckSurvivalFly(player, moveInfo.from, moveInfo.to, data, cc, pData) 
363
            || BlockProperties.isOnGroundOrResetCond(player, loc, cc.yOnGround)) {
364
            useToggleFlightLoc.setWorld(null);
365
            aux.returnPlayerMoveInfo(moveInfo);
366
            return;
367
        }
368
        aux.returnPlayerMoveInfo(moveInfo);
369
        useToggleFlightLoc.setWorld(null);
370
        data.addVelocity(player, cc, 0.0, 0.3, 0.0, VelocityFlags.FAKED);
371
    }
372
373
374
    /** Reset data on gamemode change */
375
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
376
    public void onPlayerGameModeChange(final PlayerGameModeChangeEvent event) {
377
        final Player player = event.getPlayer();
378
        if (player.getGameMode() == GameMode.CREATIVE || event.getNewGameMode() == GameMode.CREATIVE) {
379
            final MovingData data = DataManager.getGenericInstance(player, MovingData.class);
380
            data.clearFlyData();
381
            data.clearPlayerMorePacketsData();
382
            // TODO: Set new set back if any fly check is activated.
383
            // (Keep vehicle data as is.)
384
        }
385
    }
386
387
    
388
    /** Prevent portal use on set back on lowest level */
389
    @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
390
    public void onPlayerPortalLowest(final PlayerPortalEvent event) {
391
        final Player player = event.getPlayer();
392
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
393
        if (MovingUtil.hasScheduledPlayerSetBack(player)) {
394
            if (pData.isDebugActive(checkType)) debug(player, "[PORTAL] Prevent use, due to a scheduled set back.");
395
            event.setCancelled(true);
396
        }
397
    }
398
399
400
    /** Reset data on using a portal. Monitor level */
401
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
402
    public void onPlayerPortalMonitor(final PlayerPortalEvent event) {
403
        final Location to = event.getTo();
404
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
405
        final MovingData data = pData.getGenericInstance(MovingData.class);
406
        if (pData.isDebugActive(checkType)) debug(event.getPlayer(), "[PORTAL] to=" + to);
407
        // TODO: This should be redundant, might remove anyway.
408
        // TODO: Rather add something like setLatencyImmunity(...ms / conditions).
409
        if (to != null) data.clearMostMovingCheckData();
410
        
411
    }
412
413
414
    /** Reset data on death */
415
    @EventHandler(priority = EventPriority.MONITOR)
416
    public void onPlayerDeath(final PlayerDeathEvent event) {
417
        final Player player = event.getEntity();
418
        final IPlayerData pData = DataManager.getPlayerData(player);
419
        final MovingData data = pData.getGenericInstance(MovingData.class);
420
        data.clearMostMovingCheckData();
421
        data.setSetBack(player.getLocation(useDeathLoc)); 
422
        if (pData.isDebugActive(checkType)) debug(player, "Death: " + player.getLocation(useDeathLoc));
423
        useDeathLoc.setWorld(null);
424
    }
425
426
427
    /** LOWEST checks, indicate cancel processing player move. */
428
    @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
429
    public void onPlayerTeleportLowest(final PlayerTeleportEvent event) {
430
        final Player player = event.getPlayer();
431
        // Prevent further moving processing for nested events.
432
        processingEvents.remove(player.getName());
433
        // Various early return conditions.
434
        final TeleportCause cause = event.getCause();
435
        // We care only about these causes.
436
        switch (cause) {
437
            case COMMAND:
438
            case ENDER_PEARL:
439
                break;
440
            default:
441
                return;
442
        }
443
        final IPlayerData pData = DataManager.getPlayerData(player);
444
        final boolean debug = pData.isDebugActive(checkType);
445
        final MovingData data = pData.getGenericInstance(MovingData.class);
446
        final Location to = event.getTo();
447
        if (to == null) {
448
            // Better cancel this one.
449
            if (!event.isCancelled()) {
450
                if (debug) {
451
                    debugTeleportMessage(player, event, "Cancel event, that has no target location (to) set.");
452
                }
453
                event.setCancelled(true);
454
            }
455
            return;
456
        }
457
        if (data.hasTeleported()) {
458
            // More lenient: accept the position.
459
            if (data.isTeleportedPosition(to)) {
460
                return;
461
            }
462
            else {
463
                if (debug) {
464
                    debugTeleportMessage(player, event, "Prevent teleport, due to a scheduled set back: ", to);
465
                }
466
                event.setCancelled(true);
467
                return;
468
            }
469
        }
470
471
        // Run checks.
472
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
473
        boolean cancel = false;
474
        // Ender pearl into blocks.
475
        if (cause == TeleportCause.ENDER_PEARL) {
476
            if (pData.getGenericInstance(CombinedConfig.class).enderPearlCheck && !BlockProperties.isPassable(to)) { // || !BlockProperties.isOnGroundOrResetCond(player, to, 1.0)) {
477
                // Not check on-ground: Check the second throw.
478
                // TODO: Bounding box check or onGround as replacement?
479
                cancel = true;
480
            }
481
        }
482
        // Teleport to untracked locations.
483
        else { 
484
            // Attempt to prevent teleporting to players inside of blocks at untracked coordinates.
485
            if (cc.passableUntrackedTeleportCheck) {
486
                if (cc.loadChunksOnTeleport) {
487
                    MovingUtil.ensureChunksLoaded(player, to, "teleport", data, cc, pData);
488
                }
489
                if (MovingUtil.shouldCheckUntrackedLocation(player, to, pData)) {
490
                    final Location newTo = MovingUtil.checkUntrackedLocation(to);
491
                    if (newTo != null) {
492
                        // Adjust the teleport to go to the last tracked to-location of the other player.
493
                        event.setTo(newTo);
494
                        NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.TRACE_FILE, player.getName() + " correct untracked teleport destination (" + to + " corrected to " + newTo + ").");
495
                    }
496
                }
497
            }
498
        }
499
        // (Here event.setTo might've been called, unless cancel is set.)
500
501
        // Handle cancel.
502
        if (cancel) {
503
            // NCP actively prevents this teleport.
504
            event.setCancelled(true);
505
            if (debug) debug(player, "TP " + cause + " (cancel): " + to);
506
        }
507
    }
508
509
510
    /** HIGHEST: Revert cancel on set back. Done before MONITOR */
511
    @EventHandler(ignoreCancelled = false, priority = EventPriority.HIGHEST)
512
    public void onPlayerTeleportHighest(final PlayerTeleportEvent event) {
513
        if (!event.isCancelled()) {
514
            // Only check cancelled events.
515
            return;
516
        }
517
        final Player player = event.getPlayer();
518
        final IPlayerData pData = DataManager.getPlayerData(player);
519
        final MovingData data = pData.getGenericInstance(MovingData.class);
520
        // Revert cancel on set back (only precise match).
521
        // Teleport by NCP.
522
        // TODO: What if not scheduled.
523
        if (data.hasTeleported()) {
524
            // Prevent cheaters getting rid of flying data (morepackets, other).
525
            // TODO: even more strict enforcing ?
526
            event.setCancelled(false);
527
            if (!data.isTeleported(event.getTo())) {
528
                final Location teleported = data.getTeleported();
529
                event.setTo(teleported);
530
                /*
531
                 * Setting from ... not sure if this is relevant. Idea was to avoid
532
                 * subtleties with other plugins, but it probably can't be
533
                 * estimated, if this means more or less 'subtleties' in the end
534
                 * (amortized).
535
                 */
536
                event.setFrom(teleported);
537
            }
538
            if (pData.isDebugActive(checkType)) {
539
                NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.TRACE_FILE, player.getName() + " TP " + event.getCause()+ " (revert cancel on set back): " + event.getTo());
540
            }
541
        }
542
    }
543
544
545
    /** MONITOR: Adjust data to what happened.*/
546
    @EventHandler(ignoreCancelled = false, priority = EventPriority.MONITOR)
547
    public void onPlayerTeleportMonitor(final PlayerTeleportEvent event) {
548
        // Evaluate result and adjust data.
549
        final Player player = event.getPlayer();
550
        final IPlayerData pData = DataManager.getPlayerData(player);
551
        final MovingData data = pData.getGenericInstance(MovingData.class);
552
        // Invalidate first-move thing.
553
        // TODO: Might conflict with 'moved wrongly' on join.
554
        data.joinOrRespawn = false;
555
        // Special cases.
556
        final Location to = event.getTo();
557
        if (event.isCancelled()) {
558
            onPlayerTeleportMonitorCancelled(player, event, to, data, pData);
559
            return;
560
        }
561
        else if (to == null) {
562
            // Weird event.
563
            onPlayerTeleportMonitorNullTarget(player, event, to, data, pData);
564
            return;
565
        }
566
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
567
        // Detect our own player set backs.
568
        if (data.hasTeleported() && onPlayerTeleportMonitorHasTeleported(player, event, to, data, cc, pData)) {
569
            data.clearWindChargeImpulse(); // Always clear this data.
570
            return;
571
        }
572
573
        boolean skipExtras = false; // Skip extra data adjustments during special teleport, e.g. vehicle set back.
574
        // Detect our own vehicle set backs (...).
575
        if (data.isVehicleSetBack) {
576
            // Uncertain if this is vehicle leave or vehicle enter.
577
            if (event.getCause() != BridgeMisc.TELEPORT_CAUSE_CORRECTION_OF_POSITION) {
578
                // TODO: Unexpected, what now?
579
                NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.STATUS, CheckUtils.getLogMessagePrefix(player, CheckType.MOVING_VEHICLE) + "Unexpected teleport cause on vehicle set back: " + event.getCause());
580
            }
581
            // TODO: Consider to verify, if this is somewhere near the vehicle as expected (might need storing more data for a set back).
582
            skipExtras = true;
583
        }
584
585
        // Normal teleport
586
        final double fallDistance = data.noFallFallDistance;
587
        data.clearFlyData();
588
        data.clearPlayerMorePacketsData();
589
        data.setSetBack(to);
590
        // Important against concurrent modification exception.
591
        data.sfHoverTicks = -1; 
592
        if (cc.loadChunksOnTeleport) MovingUtil.ensureChunksLoaded(player, to, "teleport", data, cc, pData);
593
        aux.resetPositionsAndMediumProperties(player, to, data, cc);
594
        // Reset stuff.
595
        Combined.resetYawRate(player, to.getYaw(), System.currentTimeMillis(), true, pData); 
596
        data.resetTeleported();
597
598
        if (!skipExtras) {
599
            // Adjust fall distance, if set so.
600
            // TODO: How to account for plugins that reset the fall distance here?
601
            // TODO: Detect transition from valid flying that needs resetting the fall distance.
602
            if (event.getCause() == TeleportCause.UNKNOWN || event.getCause() == TeleportCause.COMMAND) {
603
                // Always keep fall damage.
604
                player.setFallDistance((float) fallDistance);
605
                data.noFallFallDistance = (float) fallDistance;
606
                // TEST: Detect jumping on a just placed fence.
607
                // 1. Detect the low correction teleport.
608
                // 2. Detect the fence.
609
                // 3. Verify the past move.
610
                // (4. Check for a block change entry or last placed block.)
611
                // TODO: REMOVE TEST
612
            }
613
            else if (fallDistance > 1.0 && fallDistance - player.getFallDistance() > 0.0) {
614
                // Reset fall distance if set so in the config.
615
                if (!cc.noFallTpReset) {
616
                    // (Set fall distance if set to not reset.)
617
                    player.setFallDistance((float) fallDistance);
618
                    data.noFallFallDistance = (float) fallDistance;
619
                }
620
                else if (fallDistance >= attributeAccess.getHandle().getSafeFallDistance(player)) {
621
                    data.noFallSkipAirCheck = true;
622
                }
623
            }
624
            if (event.getCause() == TeleportCause.ENDER_PEARL) {
625
                // Prevent NoFall violations for ender-pearls.
626
                data.noFallSkipAirCheck = true;
627
            }
628
        }
629
630
        // Cross world teleportation issues with the end.
631
        final Location from = event.getFrom();
632
        if (from != null && event.getCause() == TeleportCause.END_PORTAL // Currently only related to this.
633
            && !from.getWorld().getName().equals(to.getWorld().getName())) { // Less java, though.
634
            // Remember the position teleported from.
635
            data.crossWorldFrom = new SimplePositionWithLook(from.getX(), from.getY(), from.getZ(), from.getYaw(), from.getPitch());
636
            // Force close any inventory.
637
            Open.checkClose(player);
638
        }
639
        else {
640
            // Reset last cross world position.
641
            data.crossWorldFrom = null;
642
        }
643
644
        // Log.
645
        if (pData.isDebugActive(checkType)) {
646
            debugTeleportMessage(player, event, "(normal)", to);
647
        }
648
    }
649
650
651
    /** Add velocity to internal book-keeping */
652
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
653
    public void onPlayerVelocity(final PlayerVelocityEvent event) {
654
        final Player player = event.getPlayer();
655
        final IPlayerData pData = DataManager.getPlayerData(player);
656
        final MovingData data = pData.getGenericInstance(MovingData.class);
657
        // Ignore players who are in vehicles.
658
        if (player.isInsideVehicle()) {
659
            data.removeAllVelocity();
660
            return;
661
        }
662
        // Process velocity.
663
        final Vector velocity = event.getVelocity();
664
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
665
        data.addVelocity(player, cc, velocity.getX(), velocity.getY(), velocity.getZ());
666
    }
667
668
669
    /** Listen to damage events for fall damage */
670
    @EventHandler(priority = EventPriority.LOWEST)
671
    public void onEntityDamage(final EntityDamageEvent event) {
672
        if (event.getCause() != DamageCause.FALL) {
673
            return;
674
        }
675
        final Entity entity = event.getEntity();
676
        if (!(entity instanceof Player)) {
677
            return;
678
        }
679
        checkFallDamageEvent((Player) entity, event);
680
    }
681
682
    
683
    /** Reset and adjust data on join */
684
    @EventHandler(priority = EventPriority.MONITOR)
685
    public void onPlayerRespawn(final PlayerRespawnEvent event) {
686
        final Player player = event.getPlayer();
687
        final IPlayerData pData = DataManager.getPlayerData(player);
688
        final MovingData data = pData.getGenericInstance(MovingData.class);
689
        // TODO: Prevent/cancel scheduled teleport (use PlayerData/task for teleport, or a sequence count).
690
        data.clearMostMovingCheckData();
691
        data.resetSetBack(); // To force dataOnJoin to set it to loc.
692
        // Handle respawn like join.
693
        dataOnJoin(player, event.getRespawnLocation(), true, data, pData.getGenericInstance(MovingConfig.class), pData.isDebugActive(checkType));
694
    }
695
696
697
    /** MONITOR level PlayerMoveEvent. Uses useLoc. */
698
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
699
    public void onPlayerMoveMonitor(final PlayerMoveEvent event) {
700
        // TODO: Use stored move data to verify if from/to have changed (thus a teleport will result, possibly a minor issue due to the teleport).
701
        final long now = System.currentTimeMillis();
702
        final Player player = event.getPlayer();
703
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
704
        // This means moving data has been reset by a teleport.
705
        if (processingEvents.remove(player.getName()) == null) {
706
            return;
707
        }
708
        if (player.isDead() || player.isSleeping()) {
709
            return;
710
        }
711
        // Feed combined check.
712
        final CombinedData data = pData.getGenericInstance(CombinedData.class);
713
        final MovingData mData = pData.getGenericInstance(MovingData.class);
714
        data.lastMoveTime = now; 
715
        mData.mcFallDistance = player.getFallDistance();
716
        final Location from = event.getFrom();
717
        // Feed yawrate and reset moving data positions if necessary.
718
        final int tick = TickTask.getTick();
719
        final MovingConfig mCc = pData.getGenericInstance(MovingConfig.class);
720
        if (!event.isCancelled()) {
721
            final Location pLoc = player.getLocation(useLoc);
722
            onMoveMonitorNotCancelled(player, TrigUtil.isSamePosAndLook(pLoc, from) ? from : pLoc, event.getTo(), now, tick, data, mData, mCc, pData);
723
            useLoc.setWorld(null);
724
        }
725
        else onCancelledMove(player, from, tick, now, mData, mCc, data, pData);
726
    }
727
    
728
729
    /** LOWEST level PlayerMoveEvent: this is the level where checks are executed and most moving data is set */
730
    @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
731
    public void onPlayerMove(final PlayerMoveEvent event) {
732
        counters.add(idMoveEvent, 1);
733
        final Player player = event.getPlayer();
734
        // Store the event for monitor level checks.
735
        processingEvents.put(player.getName(), event);
736
        final IPlayerData pData = DataManager.getPlayerData(player);
737
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
738
        final MovingData data = pData.getGenericInstance(MovingData.class);
739
        final boolean debug = pData.isDebugActive(checkType);
740
        final Location from = event.getFrom().clone();
741
        final Location to = event.getTo().clone();
742
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
743
        /** New "to" location where to set back the player to. Requested by vehicle checks */
744
        Location newTo = null;
745
        data.increasePlayerMoveCount();
746
747
        ////////////////////////////////////////////////////
748
        // Early return tests (no full processing).       //
749
        ////////////////////////////////////////////////////
750
        // TODO: Check illegal moves here anyway (!).
751
        // TODO: Check if vehicle move logs correctly (fake).
752
        final boolean earlyReturn;
753
        final String token;
754
        if (player.isInsideVehicle()) {
755
            // No full processing for players in vehicles.
756
            newTo = vehicleChecks.onPlayerMoveVehicle(player, from, to, data, pData);
757
            earlyReturn = true;
758
            token = "vehicle";
759
        }
760
        else if (data.lastVehicleType == EntityType.MINECART && ServerIsAtLeast1_19_4
761
            // The setback comes from VehicleChecks#onPlayerVehicleLeave
762
            // Don't be confuse with data.getSetBack(from) here, the location "from" is used when the stored setback is null 
763
            && to.distance(data.getSetBack(from)) < 3) {
764
            earlyReturn = true;
765
            token = "minecart-total";
766
            data.lastVehicleType = null;
767
            // Some changes were made in 1.19.4 make PlayerMoveEvent no longer fire while on Minecart
768
            // So when the player leave the vehicle will make PlayerMoveEvent 
769
            // work normal again and update the position so result in the location player start to ride minecart and location player left it
770
        }
771
        else if (data.vehicleLeave && to.distance(from) > 3) {
772
        	earlyReturn = true;
773
            token = "vehicle-leave-sb";
774
            // Set-back for sure
775
            newTo = data.getSetBack(from);
776
            data.vehicleLeave = false;
777
        }
778
        else if (player.isDead()) {
779
            // Ignore dead players.
780
            data.sfHoverTicks = -1;
781
            earlyReturn = true;
782
            token = "dead";
783
        }
784
        else if (player.isSleeping()) {
785
            // Ignore sleeping players.
786
            data.sfHoverTicks = -1;
787
            earlyReturn = true;
788
            token = "sleeping";
789
        }
790
        else if (!from.getWorld().equals(to.getWorld())) {
791
            // Keep hover ticks.
792
            // Ignore changing worlds.
793
            earlyReturn = true;
794
            token = "worldchange";
795
        }
796
        else if (data.hasTeleported()) {
797
            earlyReturn = handleTeleportedOnMove(player, event, data, cc, pData);
798
            token = "awaitsetback";
799
        }
800
        else if (TrigUtil.isSamePos(from, to) && !data.lastMoveNoMove 
801
            && pData.getClientVersion().isAtLeast(ClientVersion.V_1_17)
802
            // This was apparently fixed by mojang in 1.21. 
803
            && pData.getClientVersion().isAtMost(ClientVersion.V_1_20_6)
804
            ) { 
805
            //if (data.sfHoverTicks > 0) data.sfHoverTicks += hoverTicksStep;
806
            earlyReturn = data.lastMoveNoMove = thisMove.hasNoMovementDueToDuplicatePacket = true;
807
            token = "duplicate1.17";
808
            // Ignore 1.17+ duplicate position packets.
809
            // Context: Mojang attempted to fix a bucket placement de-synchronization issue by re-sending the position on right-clicking...
810
            // On the server-side, this translates in a duplicate move which we need to ignore (i.e.: players can have 0 distance in air, MorePackets will trigger due to the extra packet if the button is pressed for long enough etc...)
811
            // Thanks Mojang as always.
812
        }
813
        else {
814
            earlyReturn = false;
815
            token = null;
816
        }
817
        
818
        // (Reset of the flag must be done here.)
819
        if (!TrigUtil.isSamePos(from, to)) {
820
            data.lastMoveNoMove = thisMove.hasNoMovementDueToDuplicatePacket = false;
821
        }
822
823
        if (earlyReturn) {
824
            if (debug) {
825
                debug(player, "Early return" + (token == null ? "" : (" (" + token + ")")) +  " on PlayerMoveEvent: from: " + from + " , to: " + to);
826
            }
827
            if (newTo != null) {
828
                // Illegal Yaw/Pitch.
829
                if (LocUtil.needsYawCorrection(newTo.getYaw())) {
830
                    newTo.setYaw(LocUtil.correctYaw(newTo.getYaw()));
831
                }
832
                if (LocUtil.needsPitchCorrection(newTo.getPitch())) {
833
                    newTo.setPitch(LocUtil.correctPitch(newTo.getPitch()));
834
                }
835
                prepareSetBack(player, event, newTo, data, cc, pData); // Logs set back details.
836
            }
837
            data.joinOrRespawn = false;
838
            data.hasLeatherBoots = BridgeMisc.canStandOnPowderSnow(player);
839
            data.lastY = from.getY();
840
            return;
841
        }
842
        // TODO: Is this right place? Just throw in entity/player in blockcache is better or this one? Too tired for now, maybe later
843
        data.hasLeatherBoots = BridgeMisc.canStandOnPowderSnow(player);
844
        data.lastY = from.getY();
845
        
846
        //////////////////////////////////////////////////////////////////////////////////////////////////////////
847
        // Change world miss on Folia-based servers. Not efficient, requires the first move event fire to know  //
848
        //////////////////////////////////////////////////////////////////////////////////////////////////////////
849
        if (SchedulerHelper.isFoliaServer()) {
850
            if (data.fromMissedWorldChange != null && !data.fromMissedWorldChange.equals(from.getWorld())) {
851
                // Artificially fire the event. Data will be reset onPlayerChangedWorld()
852
                // TODO: Maybe report to Folia?
853
                final PlayerChangedWorldEvent e = new PlayerChangedWorldEvent(player, data.fromMissedWorldChange);
854
                Bukkit.getPluginManager().callEvent(e);
855
            }
856
            data.fromMissedWorldChange = from.getWorld();
857
        }
858
        
859
        // (newTo should be null here)
860
        // TODO: Abstract away this mechanic.
861
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
862
        // Split the event into separate moves and re-map inputs, or correct the looking data, if suitable.          //
863
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
864
        // This mechanic is needed due to Bukkit not always firing PlayerMoveEvent(s) with each flying packet. In some cases, a single PlayerMoveEvent can be the result of multiple flying packets:
865
        // 1) Bukkit has thresholds for firing PlayerMoveEvents (1f/256 for distance and 10f for looking direction - PlayerConnection.java). 
866
        //    This will result in movements that don't have a significant change to be skipped. 
867
        //    With anticheating, this means that micro and very slow moves cannot be checked accurately (or at all, for that matter), as coordinates will not be reported correctly for the subsequent event.
868
        // 2) On MC 1.19.4 and later, PlayerMoveEvents are skipped altogether upon entering a minecart and fired normally when exiting.
869
        // 3) Even on regular movements, the player's look information (pitch/yaw) can be incorrect (idle packet).
870
        // In fact, one could argue that the event's nomenclature is misleading: Bukkit's PlayerMoveEvent doesn't actually monitor move packets but rather *changes* of movement between packets.
871
        // Now, to fix this, we'd need to re-code NCP to run movement checks on packet-level instead. Such an option isn't feasible: it would require a massive re-work which we don't have the manpower for, hence this mechanic which -albeit convoluted- works well.
872
        // Essentially, after Bukkit fires a PlayerMoveEvent, NCP will check if it had been fired normally. If it wasn't, the flying-packet queue is used to know how many moves were skipped on Bukkit-level and reconstruct the correct from/to positions.
873
        // (Overall, this forces NCP to pretty much hard-depend on ProtocolLib, but it's the most sensible choice anyway, as working with Bukkit events has proven to be unreliable on the longer run)
874
        // (For simplicity, the mechanic is internally referred to as "split move", because the event is essentially split by how many moves were lost, with a cap)
875
        final PlayerMoveInfo moveInfo = aux.usePlayerMoveInfo();
876
        final Location loc = player.getLocation(moveInfo.useLoc);
877
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
878
        if (cc.loadChunksOnMove) MovingUtil.ensureChunksLoaded(player, from, to, lastMove, "move", cc, pData);
879
        
880
        if (
881
            // 0: This is how we know if the event was fired correctly; player#getLocaton() and the event's "from" location are the same (More specifically, for Bukkit, from = the current Location of the player).
882
            // If these don't match, player#getLocation() will reflect a skipped move between from and to (for which no event was fired).
883
            TrigUtil.isSamePos(from, loc)
884
            // 0: Special case / bug? (Which/why, which version of MC/spigot?)
885
            // TODO: Omit anyways?
886
            || lastMove.valid && TrigUtil.isSamePos(loc, lastMove.from.getX(), lastMove.from.getY(), lastMove.from.getZ())) {
887
            // TODO: On pistons pulling the player back? Might check
888
            /* From look doesn't correctly reported. Trying to search back. But this is already done in CraftBukkit internally.
889
             * This code just to extra assurance. Zero trusted at that time(have not read the code yet)
890
            */
891
            // Walks backwards through the flying packet queue to fix yaw/pitch.
892
            // - Update yaw/pitch from the most recent packet with look data.
893
            // - Apply these values when matching the "from" position.
894
            // - Stop once the "to" position is found.
895
//            final FlyingQueueHandle flyingHandle = new FlyingQueueHandle(pData);
896
//            final DataPacketFlying[] queue = flyingHandle.getHandle();
897
//            float currentYaw = from.getYaw();
898
//            float currentPitch = from.getPitch();
899
//            int count = 0;
900
//            boolean breakOnFound = false;
901
//            if (queue.length != 0) {
902
//                for (int queueIndex = queue.length -1; queueIndex >=0; queueIndex--) {
903
//                    final DataPacketFlying packetData = queue[queueIndex];
904
//                    if (packetData == null || (!packetData.hasPos && !packetData.hasLook)) {
905
//                        continue;
906
//                    }
907
//                    if (breakOnFound && packetData.hasPos) {
908
//                        break;
909
//                    }
910
//                    if (packetData.hasLook) {
911
//                        currentYaw = packetData.getYaw();
912
//                        currentPitch = packetData.getPitch();
913
//                        if (!packetData.hasPos) {
914
//                            continue;
915
//                        }
916
//                    }
917
//                    if (count < 1 && TrigUtil.isSamePos(from.getX(), from.getY(), from.getZ(), packetData.getX(), packetData.getY(), packetData.getZ())) {
918
//                        from.setYaw(currentYaw);
919
//                        from.setPitch(currentPitch);
920
//                        count++;
921
//                    } 
922
//                    else if (TrigUtil.isSamePos(to.getX(), to.getY(), to.getZ(), packetData.getX(), packetData.getY(), packetData.getZ())) {
923
//                        breakOnFound = true;
924
//                    }
925
//                }
926
//                // To location is always right
927
//                //to.setYaw(currentYaw);
928
//                //to.setPitch(currentPitch);
929
//            }
930
            
931
            // Normal move: fire from -> to (client onGround from Player#isOnGround at to)
932
            if (BridgeMisc.isWASDImpulseKnown(player)) data.input.set(player.getCurrentInput());
933
            {
934
                final NetData netData = pData.getGenericInstance(NetData.class);
935
                final long lastMatchedToSeq = netData.getLastMatchedMoveToSequence();
936
                final DataPacketFlying[] flyingQueue = new FlyingQueueHandle(pData).getHandle();
937
                int scanLimit = flyingQueue.length;
938
                if (lastMatchedToSeq > 0) {
939
                    scanLimit = 0;
940
                    for (int idx = 0; idx < flyingQueue.length; idx++) {
941
                        final DataPacketFlying packetData = flyingQueue[idx];
942
                        if (packetData == null) {
943
                            continue;
944
                        }
945
                        if (packetData.getSequence() <= lastMatchedToSeq) {
946
                            break;
947
                        }
948
                        scanLimit = idx + 1;
949
                    }
950
                }
951
                //int toIndex = -1;
952
                for (int idx = 0; idx < scanLimit; idx++) {
953
                    final DataPacketFlying packetData = flyingQueue[idx];
954
                    if (packetData != null && packetData.hasPos
955
                            && TrigUtil.isSamePos(to.getX(), to.getY(), to.getZ(),
956
                                    packetData.getX(), packetData.getY(), packetData.getZ())) {
957
                        netData.updateLastMatchedMoveToSequence(packetData.getSequence());
958
                        break;
959
                    }
960
                    //if (toIndex >= 0 && flyingQueue[toIndex] != null) {
961
                    //    netData.updateLastMatchedMoveToSequence(flyingQueue[toIndex].getSequence());
962
                        // Best-effort find the matching "from" anchor (older than "to") to store a per-event range.
963
                    //    int fromIndex = -1;
964
                    //    for (int idx = toIndex + 1; idx < flyingQueue.length; idx++) {
965
                    //        final DataPacketFlying packetData = flyingQueue[idx];
966
                    //        if (packetData == null || !packetData.hasPos) {
967
                    //            continue;
968
                    //        }
969
                            //if (TrigUtil.isSamePos(from.getX(), from.getY(), from.getZ(),
970
                            //                      packetData.getX(), packetData.getY(), packetData.getZ())) {
971
                    //        fromIndex = idx;
972
                    //        break;
973
                            //}
974
                    //    }
975
                    //}
976
                    //TODO: We now have some extra look,ground if fromIndex - toIndex > 1. Now how to feed in 0.03 reconstructor if there is, from here? 
977
                }
978
            }
979
            data.setPendingBukkitGround(player, data.playerMoves.getFirstPastMove());
980
            moveInfo.set(player, from, to, cc.yOnGround);
981
            checkPlayerMove(player, from, to, 0, moveInfo, debug, data, cc, pData, event, true);
982
        }
983
        else {
984
            // Something happened: there was a mismatch between the player's location, and the event's location(s)
985
            // Peek into ProtocolLib to recover the movement's actual locations.
986
            final FlyingQueueHandle flyingHandle = new FlyingQueueHandle(pData);
987
            final DataPacketFlying[] flyingQueue = flyingHandle.getHandle();
988
            // 1: Locate Bukkit's 'from' and 'to' locations on packet-level in the flying queue.
989
            if (flyingQueue.length != 0) {
990
                final NetData netData = pData.getGenericInstance(NetData.class);
991
                final long lastMatchedToSeq = netData.getLastMatchedMoveToSequence();
992
                /* Index of Bukkit's "from" location in the flying queue. -1 if already purged out of the queue or cannot be found for any other reason. */
993
                int fromIndex = -1;
994
                /* Index of Bukkit's "to" location in the flying queue. -1 if already purged out of the queue or cannot be found for any other reason.*/
995
                int toIndex = -1;
996
                // Require at least this many packets strictly between to/from. Set 0 if adjacent is allowed.
997
                final int minGap = 1;
998
                // Phase 1 (fast path): Scan only packets newer than the last matched "to" sequence.
999
                // If we can't find the anchors in the new prefix, fall back to scanning the full queue.
1000
                int scanLimit = flyingQueue.length;
1001
                if (lastMatchedToSeq > 0) {
1002
                    scanLimit = 0;
1003
                    for (int idx = 0; idx < flyingQueue.length; idx++) {
1004
                        final DataPacketFlying packetData = flyingQueue[idx];
1005
                        if (packetData == null) {
1006
                            continue;
1007
                        }
1008
                        if (packetData.getSequence() <= lastMatchedToSeq) {
1009
                            break;
1010
                        }
1011
                        scanLimit = idx + 1; // exclusive
1012
                    }
1013
                    // If everything is older/equal, keep scanLimit at 0 -> immediate fallback below.
1014
                }
1015
1016
                // Pass 1: scan the "new" prefix [0..scanLimit).
1017
                for (int idx = 0; idx < scanLimit; idx++) {
1018
                    final DataPacketFlying packetData = flyingQueue[idx];
1019
                    if (packetData == null || !packetData.hasPos) {
1020
                        continue;
1021
                    }
1022
                    if (toIndex == -1 && TrigUtil.isSamePos(to.getX(), to.getY(), to.getZ(), packetData.getX(), packetData.getY(), packetData.getZ())) {
1023
                        toIndex = idx;
1024
                    }
1025
                    else if (fromIndex == -1 && TrigUtil.isSamePos(from.getX(), from.getY(), from.getZ(), packetData.getX(), packetData.getY(), packetData.getZ())) {
1026
                        fromIndex = idx;
1027
                    }
1028
                    if (fromIndex >= 0 && toIndex >= 0) {
1029
                        break;
1030
                    }
1031
                }
1032
1033
                // Pass 2: if needed, continue scanning only the older tail [scanLimit..end).
1034
                if (fromIndex == -1 || toIndex == -1) {
1035
                    for (int idx = scanLimit; idx < flyingQueue.length; idx++) {
1036
                        final DataPacketFlying packetData = flyingQueue[idx];
1037
                        if (packetData == null || !packetData.hasPos) {
1038
                            continue;
1039
                        }
1040
                        if (toIndex == -1 && TrigUtil.isSamePos(to.getX(), to.getY(), to.getZ(), packetData.getX(), packetData.getY(), packetData.getZ())) {
1041
                            toIndex = idx;
1042
                        }
1043
                        else if (fromIndex == -1 && TrigUtil.isSamePos(from.getX(), from.getY(), from.getZ(), packetData.getX(), packetData.getY(), packetData.getZ())) {
1044
                            fromIndex = idx;
1045
                        }
1046
                        if (fromIndex >= 0 && toIndex >= 0) {
1047
                            break;
1048
                        }
1049
                    }
1050
                }
1051
1052
                // If we successfully matched, advance the sequence cursor to the "to" anchor.
1053
                if (toIndex >= 0 && flyingQueue[toIndex] != null) {
1054
                    netData.updateLastMatchedMoveToSequence(flyingQueue[toIndex].getSequence());
1055
                }
1056
                // 1.1: Not found or too few moves were skipped, return to legacy split moves
1057
                if (fromIndex < 0 || toIndex < 0 || fromIndex - toIndex <= minGap) {
1058
                    bukkitSplitMove(player, moveInfo, from, loc, to, debug, data, cc, pData, event);
1059
                    // Cleanup.
1060
                    data.joinOrRespawn = false;
1061
                    aux.returnPlayerMoveInfo(moveInfo);
1062
                    if (debug) {
1063
                        debug(player, "Fallback to Bukkit-based split moves. (Flying queue indices - from: " + fromIndex + ", to: " + toIndex +")");
1064
                    }
1065
                    return;
1066
                }
1067
                // 2: Filter out null and ground only packets; synchronize the input change with the correct flying packet on when it happened
1068
                final DataPacketInput[] inputQueue = netData.copyInputQueue();
1069
                // Prepare array to hold the filtered packets between fromIndex and toIndex (inclusive). 
1070
                final DataPacketFlying[] filteredFlyingQueue = new DataPacketFlying[fromIndex - toIndex + 1];
1071
                int j = 0;
1072
                // NOTE: Inverted from last versions for easier code
1073
                for (int i = toIndex; i <= fromIndex; i++) {
1074
                    // (Let the early return above handle duplicate 1.17 packets)
1075
                    if (flyingQueue[i] != null) {
1076
                        // All valid flying packets are put in their array
1077
                        filteredFlyingQueue[j] = flyingQueue[i];
1078
                        j++;
1079
                    }
1080
                }
1081
                // 3: Actual split
1082
                int count = 1;
1083
                // The maximum amount by which a single PlayerMoveEvent can be split.
1084
                int maxSplit = 20;
1085
                int currentFromIndex = -1;
1086
                int currentToIndex = -1;
1087
                float currentYaw = from.getYaw();
1088
                float currentPitch = from.getPitch();
1089
                Location packet = null;
1090
                DataPacketFlying segmentFromPacket = null;
1091
                final boolean trustPacketHorizontalCollision = false;
1092
                // NOTE: Inverted from last versions to match logic
1093
                for (int i = j - 1; i >= 0; i--) {
1094
                    if (filteredFlyingQueue[i].hasLook) {
1095
                        // If a packet has look data, update yaw/pitch.
1096
                        currentYaw = filteredFlyingQueue[i].getYaw();
1097
                        currentPitch = filteredFlyingQueue[i].getPitch();
1098
                    }
1099
                    // If a packet has position data, we can split.
1100
                    if (filteredFlyingQueue[i].hasPos) {
1101
                        // If from was set...
1102
                        if (packet != null) {
1103
                            // TODO: We now have some extra look,ground if fromIndex - toIndex > 1. Now how to feed in 0.03 reconstructor if there is, from here?
1104
                            currentToIndex = count >= maxSplit ? -1 : i;
1105
                            /* The 'to' location skipped/lost by Bukkit in the flying queue. Use Bukkit's "to" if the maximum split was reached */
1106
                            Location packetTo = count >= maxSplit ? to : new Location(from.getWorld(), filteredFlyingQueue[i].getX(), filteredFlyingQueue[i].getY(), filteredFlyingQueue[i].getZ(), currentYaw, currentPitch);
1107
                            final DataPacketFlying segmentToPacket = count >= maxSplit && toIndex >= 0
1108
                                    ? flyingQueue[toIndex] : filteredFlyingQueue[i];
1109
                            data.setPendingClientPacketGround(segmentFromPacket, segmentToPacket, trustPacketHorizontalCollision);
1110
                            // Finally, set the moving data to be used by checks.
1111
                            moveInfo.set(player, packet, packetTo, cc.yOnGround);
1112
                            // Finally, remap the input for this move.
1113
                            final int inputIdx = i + 1;
1114
                            if (inputQueue[inputIdx] != null) {
1115
                                data.input.set(Boolean.compare(inputQueue[inputIdx].left, inputQueue[inputIdx].right), Boolean.compare(inputQueue[inputIdx].forward, inputQueue[inputIdx].backward), inputQueue[inputIdx].jump, inputQueue[inputIdx].shift, inputQueue[inputIdx].sprint);
1116
                            }
1117
                            if (debug) {
1118
                                final String s1 = count == 1 ? "from" : "loc";
1119
                                final String s2 = i == j - 1 || count >= maxSplit ? "to" : "loc";
1120
                                debug(player, "Split move (packet): " + count + " (" + s1 + " -> " + s2 + ")");
1121
                            }
1122
                            if (!checkPlayerMove(player, packet, packetTo, count++, moveInfo, debug, data, cc, pData, event, true) 
1123
                                && processingEvents.containsKey(player.getName())) {
1124
                                onMoveMonitorNotCancelled(player, packet, packetTo, System.currentTimeMillis(), TickTask.getTick(), pData.getGenericInstance(CombinedData.class), data, cc, pData);
1125
                                data.joinOrRespawn = false;
1126
                            } 
1127
                            else {
1128
                                // Stop processing split moves on set-back.
1129
                                break;
1130
                            }
1131
1132
                            // Split too much!
1133
                            if (count > maxSplit) {
1134
                                break;
1135
                            }
1136
                        }
1137
                        /* The 'from' location skipped/lost by Bukkit in the flying queue */
1138
                        currentFromIndex = i;
1139
                        segmentFromPacket = filteredFlyingQueue[i];
1140
                        packet = new Location(from.getWorld(), filteredFlyingQueue[i].getX(), filteredFlyingQueue[i].getY(), filteredFlyingQueue[i].getZ(), currentYaw, currentPitch);
1141
                    }
1142
                }
1143
            }
1144
            else {
1145
                bukkitSplitMove(player, moveInfo, from, loc, to, debug, data, cc, pData, event);
1146
                if (debug) {
1147
                    debug(player, "Flying queue is empty. Fallback to Bukkit-based split moves.");
1148
                }
1149
            }
1150
        }
1151
        // Cleanup.
1152
        data.joinOrRespawn = false;
1153
        aux.returnPlayerMoveInfo(moveInfo);
1154
    }
1155
    
1156
1157
    /**
1158
     * Split the incoming move event into two different moves, by using player#getLocation() exclusively. <br>
1159
     * This is a really rough split, as without ProtocolLib, we cannot tell how many moves have been skipped between the event#getFrom/To() and player#getLocation().
1160
     * (Which can be much more than 2)
1161
     * So, checking for anything that requires high-precision (like a prediction implementation) during these phases should be avoided.
1162
     */
1163
    private void bukkitSplitMove(final Player player, final PlayerMoveInfo moveInfo, final Location from, final Location loc, final Location to, 
1164
                                 final boolean debug, final MovingData data, final MovingConfig cc, final IPlayerData pData, final PlayerMoveEvent event) {
1165
        // 1: Use player#getLocation() as the "to" location (from->loc).
1166
        data.setPendingBukkitGround(player, data.playerMoves.getFirstPastMove());
1167
        moveInfo.set(player, from, loc, cc.yOnGround);
1168
        if (debug) {
1169
            debug(player, "Split move (bukkit): 1 (from -> loc)");
1170
        }
1171
        if (!checkPlayerMove(player, from, loc, 1, moveInfo, debug, data, cc, pData, event, false) 
1172
            && processingEvents.containsKey(player.getName())) {
1173
            // Between -> set data accordingly (compare: onPlayerMoveMonitor).
1174
            onMoveMonitorNotCancelled(player, from, loc, System.currentTimeMillis(), TickTask.getTick(), pData.getGenericInstance(CombinedData.class), data, cc, pData);
1175
            data.joinOrRespawn = false;
1176
            // 2: Use player#getLocation() as the "from" location (loc -> to).
1177
            data.setPendingBukkitGround(player, data.playerMoves.getFirstPastMove());
1178
            moveInfo.set(player, loc, to, cc.yOnGround);
1179
            checkPlayerMove(player, loc, to, 2, moveInfo, debug, data, cc, pData, event, false);
1180
            if (debug) {
1181
                debug(player, "Split move (bukkit): 2 (loc -> to)");
1182
            }
1183
        }
1184
    }
1185
1186
1187
    /**
1188
     * During early player move handling: data.hasTeleported() returned true.
1189
     */
1190
    private boolean handleTeleportedOnMove(final Player player, final PlayerMoveEvent event, final MovingData data, 
1191
                                           final MovingConfig cc, final IPlayerData pData) {
1192
        // This could also happen with a packet based set back such as with cancelling move events.
1193
        final boolean debug = pData.isDebugActive(checkType);
1194
        if (data.isTeleportedPosition(event.getFrom())) {
1195
            // Treat as ACK (!).
1196
            confirmSetBack(player, false, data, cc, pData, event.getFrom());
1197
            if (debug) debug(player, "Implicitly confirm set back with the start point of a move.");
1198
            return false;
1199
        }
1200
        else if (DataManager.getPlayerData(player).isPlayerSetBackScheduled()) {
1201
            // A set back has been scheduled, but the player is moving randomly.
1202
            // TODO: Instead alter the move from location and let it get through? +- when
1203
            event.setCancelled(true);
1204
            if (debug) debug(player, "Cancel move, due to a scheduled teleport (set back).");
1205
            return true;
1206
        }
1207
        else {
1208
            // Left-over (Demand: schedule or teleport before moving events arrive).
1209
            if (debug) debug(player, "Invalidate left-over teleported (set back) location: " + data.getTeleported());
1210
            data.resetTeleported();
1211
            // TODO: More to do?
1212
            return false;
1213
        }
1214
    }
1215
1216
1217
    /**
1218
     * Run all movement-related core mechanics.
1219
     *
1220
     * @param multiMoveCount
1221
     *        0: represents an ordinary move (not split), 
1222
     *        >= 1: first/second/(...) part of a single move event.
1223
     * @param isNormalOrPacketSplitMove False if bukkitSplitMove is used, true otherwise (even with no split move)
1224
     * @return True, if the move is cancelled, in which case onMoveMonitorNotCancelled won't run.
1225
     */
1226
    private boolean checkPlayerMove(final Player player, final Location from, final Location to, final int multiMoveCount, 
1227
                                    final PlayerMoveInfo moveInfo, final boolean debug, final MovingData data, 
1228
                                    final MovingConfig cc, final IPlayerData pData, final PlayerMoveEvent event,
1229
                                    final boolean isNormalOrPacketSplitMove) {
1230
        Location newTo = null;
1231
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
1232
        final String playerName = player.getName(); // TODO: Could switch to UUID here (needs more changes).
1233
        final long time = System.currentTimeMillis();
1234
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
1235
        // Set up data / caching.
1236
        data.resetTeleported();
1237
        ////////////////////////////
1238
        // Debug.                 //
1239
        ////////////////////////////
1240
        if (debug) {
1241
            outputMoveDebug(player, moveInfo.from, moveInfo.to, Math.max(cc.noFallyOnGround, cc.yOnGround), mcAccess.getHandle());
1242
        }
1243
        
1244
1245
        ////////////////////////////////////////////////////
1246
        // Check for illegal move and bounding box etc.   //
1247
        ///////////////////////////////////////////////////
1248
        if ((moveInfo.from.hasIllegalCoords() || moveInfo.to.hasIllegalCoords()) ||
1249
            !cc.ignoreStance && (moveInfo.from.hasIllegalStance() || moveInfo.to.hasIllegalStance())) {
1250
            MovingUtil.handleIllegalMove(event, player, data, cc);
1251
            return true;
1252
        }
1253
        
1254
1255
        /////////////////////////////////////
1256
        // Check for location consistency. //
1257
        /////////////////////////////////////
1258
        if (cc.enforceLocation && playersEnforce.contains(playerName)) {
1259
            // NOTE: The setback should not be set before this, even if not yet set.
1260
            // Last to vs. from.
1261
            newTo = enforceLocation(player, from, data);
1262
            playersEnforce.remove(playerName);
1263
        }
1264
        
1265
1266
        /////////////////////////////////////
1267
        // Prepare locations for use.      //
1268
        /////////////////////////////////////
1269
        final PlayerLocation pFrom, pTo;
1270
        pFrom = moveInfo.from;
1271
        pTo = moveInfo.to;
1272
        
1273
        
1274
        ////////////////////////////////////
1275
        // Wind Charge handling 1.21+     //
1276
        ////////////////////////////////////
1277
        // TODO: Incorrect but safe for now
1278
        // TODO: Missing case: If player taken another explosion after wind_charge, do reset impulse
1279
        if (data.timeRiptiding + 1500 > System.currentTimeMillis() || pFrom.isInLiquid() || pFrom.isOnClimbable() || Bridge1_9.isGlidingWithElytra(player)) {
1280
            data.clearWindChargeImpulse();
1281
        }
1282
        
1283
        
1284
        //////////////////////////////////////////////
1285
        // HOT FIX - for VehicleLeaveEvent missing. //
1286
        //////////////////////////////////////////////
1287
        if (data.wasInVehicle) {
1288
            vehicleChecks.onVehicleLeaveMiss(player, data, cc, pData);
1289
        }
1290
1291
1292
        ////////////////////////////////////
1293
        // Set some data for this move.   //
1294
        ////////////////////////////////////
1295
        thisMove.set(pFrom, pTo);
1296
        thisMove.multiMoveCount = multiMoveCount;
1297
        thisMove.setBackYDistance = pTo.getY() - data.getSetBackY();
1298
        thisMove.isGliding = Bridge1_9.isGliding(player);
1299
        thisMove.tridentRelease = data.consumeTridentReleaseEvent();
1300
        data.applyPendingClientPacketGround(thisMove);
1301
1302
        ////////////////////////////
1303
        // Potion effect "Jump".  //
1304
        ////////////////////////////
1305
        // TODO: Jump amplifier should be set in PlayerMoveData, and/or only get updated for lift off (?).
1306
        final double jumpAmplifier = aux.getJumpAmplifier(player);
1307
        if (jumpAmplifier > data.jumpAmplifier) {
1308
            data.jumpAmplifier = jumpAmplifier;
1309
        }
1310
1311
1312
        ////////////////////////////////////////////////
1313
        // Velocity tick (decrease + invalidation).   //
1314
        ///////////////////////////////////////////////
1315
        // TODO: Rework to generic (?) queued velocity entries: activation + invalidation
1316
        final int tick = TickTask.getTick();
1317
        data.velocityTick(tick - cc.velocityActivationTicks);
1318
1319
1320
        ////////////////////////////////////
1321
        // Check which fly check to use.  //
1322
        ////////////////////////////////////
1323
        boolean checkCf;
1324
        boolean checkSf;
1325
        float walkSpeed = attributeAccess.getHandle().getMovementSpeed(player);
1326
        if (walkSpeed == Float.MAX_VALUE) {
1327
            if (debug) {
1328
                debug(player, "The player's movement speed attribute couldn't be retrieved. Fallback to manual calculation.");
1329
            }
1330
            // This is basically for 1.5 only. Since that version doesn't support attributes, we have to do things manually. Ugly.
1331
            walkSpeed = player.getWalkSpeed() / 2f;
1332
            if (!Double.isInfinite(mcAccess.getHandle().getFasterMovementAmplifier(player))) {
1333
                walkSpeed += (float)(mcAccess.getHandle().getFasterMovementAmplifier(player) + 1) * 0.2f * walkSpeed;
1334
            }
1335
            if (!Double.isInfinite(PotionUtil.getPotionEffectAmplifier(player, BridgePotionEffect.SLOWNESS))) {
1336
                walkSpeed += (float)(PotionUtil.getPotionEffectAmplifier(player, BridgePotionEffect.SLOWNESS) + 1) * -0.15f * walkSpeed;
1337
            }
1338
        }
1339
        if (MovingUtil.shouldCheckSurvivalFly(player, pFrom, pTo, data, cc, pData)) {
1340
            checkCf = false;
1341
            checkSf = true;
1342
            // NOTE: Fly checking has to be set here to be correctly used by Extreme_Move.
1343
            thisMove.flyCheck = CheckType.MOVING_SURVIVALFLY;
1344
            data.adjustWalkSpeed(walkSpeed, tick, cc.speedGrace);
1345
        }
1346
        else if (pData.isCheckActive(CheckType.MOVING_CREATIVEFLY, player)) {
1347
            checkCf = true;
1348
            checkSf = false;
1349
            thisMove.flyCheck = CheckType.MOVING_CREATIVEFLY;
1350
            prepareCreativeFlyCheck(player, from, to, moveInfo, thisMove, multiMoveCount, tick, data, cc, walkSpeed);
1351
        }
1352
        // (thisMove.flyCheck stays null.)
1353
        else checkCf = checkSf = false;
1354
1355
1356
        ////////////////////////////////////////////////////////////////////////
1357
        // Pre-check checks (hum), either for cf or for sf.                   //
1358
        ////////////////////////////////////////////////////////////////////////
1359
        boolean checkNf = true;
1360
        BounceType verticalBounce = BounceType.NO_BOUNCE;
1361
        final boolean useBlockChangeTracker;
1362
        final double previousSetBackY;
1363
        final boolean checkPassable = pData.isCheckActive(CheckType.MOVING_PASSABLE, player);
1364
        
1365
        // 1: Set time resolutions and various counters.
1366
        // 1.1: Proactive reset of elytraBoost (MC 1.11.2).
1367
        if (data.fireworksBoostDuration > 0) {
1368
            if (!lastMove.valid || data.fireworksBoostTickExpire < tick) {
1369
                data.fireworksBoostDuration = 0;
1370
            }
1371
            else data.fireworksBoostDuration --;
1372
        }
1373
1374
        // 1.3: Set riptiding time.
1375
        if (Bridge1_13.isRiptiding(player)) data.timeRiptiding = System.currentTimeMillis();
1376
        
1377
        // 4: Workaround for 1.14+ exiting vehicles.
1378
        if (data.lastVehicleType != null && thisMove.distanceSquared < 5) {
1379
            data.setSetBack(from);
1380
            //TODO: Fake velocity
1381
            //data.addHorizontalVelocity(new AccountEntry(thisMove.hDistance, 1, 1));
1382
            data.addVerticalVelocity(new SimpleEntry(thisMove.yDistance, 1));
1383
            //data.addVerticalVelocity(new SimpleEntry(-0.16, 2));
1384
            data.lastVehicleType = null;
1385
        }
1386
        
1387
        // 4: Pre-checks relevant to Sf or Cf.
1388
        if (checkSf || checkCf) {
1389
            previousSetBackY = data.hasSetBack() ? data.getSetBackY() : Double.NEGATIVE_INFINITY;
1390
            MovingUtil.checkSetBack(player, pFrom, data, pData, this); // Ensure we have a set back set.
1391
1392
            // 4.1: Check for special cross world teleportation issues with the end.
1393
            if (data.crossWorldFrom != null) {
1394
                if (!TrigUtil.isSamePosAndLook(pFrom, pTo) && TrigUtil.isSamePosAndLook(pTo, data.crossWorldFrom)) {
1395
                    // Assume to (and possibly the player location) to be set to the location the player teleported from within the other world.
1396
                    newTo = data.getSetBack(from); // (OK, cross-world)
1397
                    checkNf = false;
1398
                    // Force close any inventory.
1399
                    Open.checkClose(player);
1400
                    NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.STATUS, CheckUtils.getLogMessagePrefix(player, CheckType.MOVING) + " Player move end point seems to be set wrongly.");
1401
                }
1402
                // Always reset.
1403
                data.crossWorldFrom = null;
1404
            }
1405
            
1406
            // 4.2: Hot fix: Entering end portal from bottom.
1407
            if (lastMove.to.getWorldName() != null && !lastMove.to.getWorldName().equals(thisMove.from.getWorldName())) {
1408
                if (TrigUtil.distance(pFrom, pTo) > 5.5) {
1409
                    newTo = data.getSetBack(from);
1410
                    checkNf = false;
1411
                    // Force close any inventory.
1412
                    Open.checkClose(player);
1413
                    NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.STATUS, CheckUtils.getLogMessagePrefix(player, CheckType.MOVING) + " Player move end point seems to be set wrongly.");
1414
                }
1415
            }
1416
1417
            // 4.3: Extreme move check (sf or cf is precondition, should have their own config/actions later).
1418
            if (newTo == null && ((Math.abs(thisMove.yDistance) > Magic.EXTREME_MOVE_DIST_VERTICAL) || thisMove.hDistance > Magic.EXTREME_MOVE_DIST_HORIZONTAL)) {
1419
                newTo = checkExtremeMove(player, pFrom, pTo, data, cc);
1420
            }
1421
            
1422
            // 4.4: Set BCT
1423
            // NOTE: Block change activity has to be checked *after* the extreme move checks run. Else crash potential (!)
1424
            useBlockChangeTracker = newTo == null && cc.trackBlockMove && blockChangeTracker.hasActivityShuffled(from.getWorld().getUID(), pFrom, pTo, 1.5625);
1425
1426
            // 4.5: Check jumping on things like slime blocks.
1427
            if (newTo == null) {
1428
                if (thisMove.yDistance < 0.0) {
1429
                    // Common pre-conditions.
1430
                    pTo.collectBlockFlags(); // Must be called to avoid NPEs
1431
                    if (PhysicsEnvelope.canBounce(player, pFrom, pTo, data, cc, pData)) {
1432
                        // Classic static bounce.
1433
                        if ((pTo.getBlockFlags() & BlockFlags.F_BOUNCE25) != 0L) {
1434
                            verticalBounce = BounceType.STATIC;
1435
                            checkNf = false; 
1436
                        }
1437
                        if (verticalBounce == BounceType.NO_BOUNCE && useBlockChangeTracker) { 
1438
                            if (BounceHandler.checkPastStateBounceDescend(player, pFrom, pTo, thisMove, lastMove, tick, data, cc, blockChangeTracker) != BounceType.NO_BOUNCE) {
1439
                                // Not set verticalBounce, as this is ascending and it's already force used.
1440
                                checkNf = false;
1441
                            }
1442
                        }
1443
                    }
1444
                }
1445
                else {
1446
                    // Prepared bounce support.
1447
                    if (data.verticalBounce != null && BounceHandler.onPreparedBounceSupport(player, from, to, thisMove, lastMove, tick, data)
1448
                        // Past state bounce (includes prepending velocity / special calls).
1449
                        || useBlockChangeTracker && thisMove.yDistance <= 1.515) {
1450
                        verticalBounce = BounceHandler.checkPastStateBounceAscend(player, pFrom, pTo, thisMove, lastMove, tick, pData, this, data, cc, blockChangeTracker);
1451
                        if (verticalBounce != BounceType.NO_BOUNCE) {
1452
                            checkNf = false;
1453
                        }
1454
                    }
1455
                }
1456
1457
                // 4.5.1: Might a bit tricky when it use to ensure no bounce check is active, not noFall checking here
1458
                if (useBlockChangeTracker && checkNf && !checkPastStateVerticalPush(player, pFrom, pTo, thisMove, lastMove, tick, debug, data, cc)) {
1459
                    checkPastStateHorizontalPush(player, pFrom, pTo, thisMove, lastMove, tick, debug, data, cc);
1460
                }
1461
                
1462
                // 4.5.2: Skip checking NoFall for levitation and slowfall
1463
                if (!Double.isInfinite(Bridge1_13.getSlowfallingAmplifier(player))) {
1464
                    checkNf = false;
1465
                }
1466
                else if (!Double.isInfinite(Bridge1_9.getLevitationAmplifier(player))) {
1467
                    checkNf = false;
1468
               }
1469
            }
1470
        }
1471
        // No Sf or Cf check
1472
        else {
1473
            // TODO: Might still allow block change tracker with only passable enabled.
1474
            useBlockChangeTracker = false;
1475
            previousSetBackY = Double.NEGATIVE_INFINITY;
1476
        }
1477
1478
        // 5: Check passable first to prevent set back override.
1479
        // Passable is checked first to get the original set back locations from the other checks, if needed. 
1480
        // TODO: Redesign to set set backs later (queue + invalidate).
1481
        /* If to skip nofall check on violation of other checks */
1482
        boolean mightSkipNoFall = false; 
1483
        if (newTo == null && checkPassable && player.getGameMode() != BridgeMisc.GAME_MODE_SPECTATOR) {
1484
            newTo = passable.check(player, pFrom, pTo, data, cc, pData, tick, useBlockChangeTracker);
1485
            if (newTo != null) {
1486
                mightSkipNoFall = true;
1487
            }
1488
        }
1489
        
1490
1491
        ////////////////////////////////////////////////////////////////////////
1492
        // Run through the moving checks (Passable is checked above).         //
1493
        ////////////////////////////////////////////////////////////////////////
1494
        // 1: SurvivalFly first
1495
        if (checkSf) {
1496
            // 1.1: Prepare from, to, thisMove for full checking.
1497
            // TODO: Could further differentiate if really needed to (newTo / NoFall).
1498
            MovingUtil.prepareFullCheck(pFrom, pTo, thisMove, Math.max(cc.noFallyOnGround, cc.yOnGround));
1499
1500
            // 1.3: Actual check.
1501
            // Only check if passable has not already set back.
1502
            if (newTo == null) {
1503
                newTo = survivalFly.check(player, pFrom, pTo, multiMoveCount, data, cc, pData, tick, time, useBlockChangeTracker, isNormalOrPacketSplitMove);
1504
            }
1505
            
1506
            // 1.4: Only check NoFall, if not already vetoed.
1507
            if (checkNf) {
1508
                checkNf = noFall.isEnabled(player, pData);
1509
            }
1510
            
1511
            // 1.5: Hover subcheck.
1512
            if (newTo == null) {
1513
                // TODO: Could reset for from-on-ground as well, for not too big moves.
1514
                if (cc.sfHoverCheck && !(lastMove.toIsValid && lastMove.to.extraPropertiesValid && lastMove.to.onGroundOrResetCond) && !pTo.isOnGround()) {
1515
                    // Start counting ticks.
1516
                    hoverTicks.add(playerName);
1517
                    data.sfHoverTicks = 0;
1518
                }
1519
                else data.sfHoverTicks = -1;
1520
1521
                // Still check for NoFall.
1522
                if (checkNf) {
1523
                    noFall.check(player, pFrom, pTo, previousSetBackY, data, cc, pData);
1524
                }
1525
            }
1526
            else {
1527
                if (checkNf && cc.sfSetBackPolicyFallDamage) {
1528
                    if (!noFall.willDealFallDamage(player, from.getY(), previousSetBackY, data)) {
1529
                        mightSkipNoFall = true;
1530
                    }
1531
                    // Check if to really skip.
1532
                    else if (mightSkipNoFall) {
1533
                        if (!pFrom.isOnGround() && !pFrom.isResetCond()) {
1534
                            mightSkipNoFall = false;
1535
                        }
1536
                    }
1537
1538
                    // (Don't deal damage where no fall damage is possible.)
1539
                    if (!mightSkipNoFall && (!pTo.isResetCond() || !pFrom.isResetCond())) {
1540
                        noFall.checkDamage(player, Math.min(from.getY(), to.getY()), data, pData);
1541
                    }
1542
                }
1543
            }
1544
        }
1545
        // 2: Then creativefly
1546
        else if (checkCf) {
1547
            if (newTo == null) {
1548
                newTo = creativeFly.check(player, pFrom, pTo, data, cc, pData, time, tick, useBlockChangeTracker);
1549
                //if (checkNf) {
1550
                //    noFall.check(player, pFrom, pTo, previousSetBackY, data, cc, pData);
1551
                //}
1552
            }
1553
            data.sfHoverTicks = -1;
1554
        }
1555
        // No fly checking :(.
1556
        else data.clearFlyData();
1557
1558
        // 3: Morepackets.
1559
        if (pData.isCheckActive(CheckType.MOVING_MOREPACKETS, player) && (newTo == null || data.isMorePacketsSetBackOldest())) {
1560
            /* Always check morepackets, if there is a chance that setting/overriding newTo is appropriate, to avoid packet speeding using micro-violations. */
1561
            final Location mpNewTo = morePackets.check(player, pFrom, pTo, newTo == null, data, cc, pData);
1562
            if (mpNewTo != null) {
1563
                // Only override set back, if the morepackets set back location is older/-est. 
1564
                if (newTo != null && debug) debug(player, "Override set back by the older morepackets set back.");
1565
                newTo = mpNewTo;
1566
            }
1567
        }
1568
        // Otherwise we need to clear their data.
1569
        else data.clearPlayerMorePacketsData();
1570
        
1571
1572
        ////////////////////////////////////////////
1573
        // Reset jump amplifier if needed.        //
1574
        ////////////////////////////////////////////
1575
        if ((checkSf || checkCf) && jumpAmplifier != data.jumpAmplifier) {
1576
            // TODO: General cool-down for latency?
1577
            if (thisMove.touchedGround || !checkSf && (pFrom.isOnGround() || pTo.isOnGround())) {
1578
                // (No need to check from/to for onGround, if SurvivalFly is to be checked.)
1579
                data.jumpAmplifier = jumpAmplifier;
1580
            }
1581
        }
1582
1583
        
1584
        ////////////////////////////////////////
1585
        // Update BlockChangeTracker          //
1586
        ////////////////////////////////////////
1587
        if (useBlockChangeTracker && data.blockChangeRef.firstSpanEntry != null) {
1588
            if (debug) debug(player, "BlockChangeReference: " + data.blockChangeRef.firstSpanEntry.tick + " .. " + data.blockChangeRef.lastSpanEntry.tick + " / " + tick);
1589
            data.blockChangeRef.updateFinal(pTo);
1590
        }
1591
        
1592
        
1593
        //////////////////////////////////////////////
1594
        // Check if the move is to be allowed       //
1595
        //////////////////////////////////////////////
1596
        // No check has requested a new to-Location (or actions are set not to cancel)
1597
        if (newTo == null) {
1598
1599
            // 1: An external hook has request a setback but actions are set to not cancel (or no check has requested a to loc)
1600
            if (data.hasTeleported()) {
1601
                data.resetTeleported();
1602
                if (debug) debug(player, "Ignore hook-induced set-back: actions not set to cancel.");
1603
            }
1604
1605
            // 2: Process the bounce effect if the move is allowed.
1606
            if (verticalBounce != BounceType.NO_BOUNCE) {
1607
                BounceHandler.processBounce(player, pFrom.getY(), pTo.getY(), verticalBounce, tick, this, data, cc, pData);
1608
            }
1609
1610
            // 3: Finish processing the current move, move it to past ones
1611
            // TODO: More simple: UUID keys or a data flag instead?
1612
            if (processingEvents.containsKey(playerName)) {
1613
                data.playerMoves.finishCurrentMove();
1614
            }
1615
            // Teleport during violation processing, just invalidate thisMove.
1616
            else thisMove.invalidate();
1617
            // Increase time since set back.
1618
            data.timeSinceSetBack ++;
1619
            return false;
1620
        }
1621
        // A check has requested a new to-location.
1622
        else {
1623
1624
            // 1: Setback override, adjust newTo.
1625
            if (data.hasTeleported()) {
1626
                if (debug) {
1627
                    debug(player, "The set back has been overridden from (" + newTo + ") to: " + data.getTeleported());
1628
                }
1629
                newTo = data.getTeleported();
1630
            }
1631
            if (debug) { // TODO: Remove, if not relevant (doesn't look like it was :p).
1632
                if (verticalBounce != BounceType.NO_BOUNCE) {
1633
                    debug(player, "Bounce effect not processed: " + verticalBounce);
1634
                }
1635
                if (data.verticalBounce != null) {
1636
                    debug(player, "Bounce effect not used: " + data.verticalBounce);  
1637
                }
1638
            }
1639
1640
            // 2: Set back handling.
1641
            prepareSetBack(player, event, newTo, data, cc, pData);
1642
            return true;
1643
        }
1644
    }
1645
1646
1647
    private void prepareCreativeFlyCheck(final Player player, final Location from, final Location to, 
1648
                                         final PlayerMoveInfo moveInfo, final PlayerMoveData thisMove, final int multiMoveCount, 
1649
                                         final int tick, final MovingData data, final MovingConfig cc, float walkSpeed) {
1650
        data.adjustFlySpeed(player.getFlySpeed(), tick, cc.speedGrace);
1651
        data.adjustWalkSpeed(walkSpeed, tick, cc.speedGrace);
1652
        // TODO: Adjust height of PlayerLocation more efficiently / fetch model early.
1653
        thisMove.modelFlying = cc.getModelFlying(player, moveInfo.from, data, cc);
1654
    }
1655
1656
    
1657
    /**
1658
     * Vertical block push
1659
     */
1660
    private boolean checkPastStateVerticalPush(final Player player, final PlayerLocation from, final PlayerLocation to,
1661
                                               final PlayerMoveData thisMove, final PlayerMoveData lastMove, final int tick, 
1662
                                               final boolean debug, final MovingData data, final MovingConfig cc) {
1663
        final UUID worldId = from.getWorld().getUID();
1664
        double amount = -1.0;
1665
        boolean addvel = false;
1666
        final BlockChangeEntry entryBelowY_POS = BlockChangeSearch(from, tick, Direction.Y_POS, debug, data, cc, worldId, true);
1667
1668
        if (
1669
                // Center push..
1670
                entryBelowY_POS != null
1671
                // Off center push.
1672
                //|| thisMove.yDistance < 0.6 && from.matchBlockChange(blockChangeTracker, data.blockChangeRef, Direction.Y_POS, Math.min(.415, thisMove.yDistance))
1673
                ) {
1674
1675
            if (debug) {
1676
                final StringBuilder builder = new StringBuilder(150);
1677
                builder.append("Direct block push at (");
1678
                builder.append("x:" + entryBelowY_POS.x);
1679
                builder.append(" y:" + entryBelowY_POS.y);
1680
                builder.append(" z:" + entryBelowY_POS.z);
1681
                builder.append(" direction:" + entryBelowY_POS.direction.name());
1682
                builder.append(")");
1683
                debug(player, builder.toString());
1684
            }
1685
            /*
1686
             * TODO: One case left still not covered, double ascend motions (0.25, 0.649)
1687
             * Mostly happen while jumping into block and piston push!
1688
             */
1689
            if (lastMove.valid && thisMove.yDistance >= 0.0) {
1690
                if ((from.isOnGroundOrResetCond() || thisMove.touchedGroundWorkaround) && from.isOnGround(1.0)) {
1691
                    amount = Math.min(thisMove.yDistance, 0.5625);
1692
                }
1693
                else if (lastMove.yDistance < -Magic.GRAVITY_MAX) {
1694
                    amount = Math.min(thisMove.yDistance, 0.34);
1695
                }
1696
                if (thisMove.yDistance == 0.0) {
1697
                    amount = 0.0;
1698
                }
1699
            }
1700
            if (lastMove.toIsValid && amount < 0.0 && thisMove.yDistance < 0.0 
1701
                && thisMove.yDistance > -1.515 && lastMove.yDistance >= 0.0) {
1702
                amount = thisMove.yDistance;
1703
                addvel = true;
1704
            }
1705
            if (entryBelowY_POS != null) {
1706
                data.blockChangeRef.updateSpan(entryBelowY_POS);
1707
            }
1708
        }
1709
        // Finally add velocity if set.
1710
        if (amount >= 0.0 || addvel) {
1711
            data.removeLeadingQueuedVerticalVelocityByFlag(VelocityFlags.ORIGIN_BLOCK_MOVE);
1712
            /*
1713
             * TODO: Concepts for limiting... max amount based on side
1714
             * conditions such as block height+1.5, max coordinate, max
1715
             * amount per use, ALLOW_ZERO flag/boolean and set in
1716
             * constructor, demand max. 1 zero dist during validity. Bind
1717
             * use to initial xz coordinates... Too precise = better with
1718
             * past move tracking, or a sub-class of SimpleEntry with better
1719
             * access signatures including thisMove.
1720
             */
1721
            final SimpleEntry vel = new SimpleEntry(tick, amount, VelocityFlags.ORIGIN_BLOCK_MOVE, 1);
1722
            data.verticalBounce = vel;
1723
            data.useVerticalBounce(player);
1724
            data.useVerticalVelocity(thisMove.yDistance);
1725
            if (debug) {
1726
                debug(player, "checkPastStateVerticalPush: set velocity: " + vel);
1727
            }
1728
            return true;
1729
        }
1730
        return false;
1731
    }
1732
1733
1734
    /**
1735
     * Search for blockchange entries.
1736
     */
1737
    private BlockChangeEntry BlockChangeSearch(final PlayerLocation from, final int tick, Direction direction,
1738
                                               final boolean debug, final MovingData data, final MovingConfig cc, 
1739
                                               final UUID worldId, final boolean searchBelow) {
1740
        final int iMinX = Location.locToBlock(from.getMinX());
1741
        final int iMaxX = Location.locToBlock(from.getMaxX());
1742
        final int iMinZ = Location.locToBlock(from.getMinZ());
1743
        final int iMaxZ = Location.locToBlock(from.getMaxZ());
1744
        final int belowY = from.getBlockY() - (searchBelow ? 1 : 0);
1745
        for (int x = iMinX; x <= iMaxX; x++) {
1746
            for (int z = iMinZ; z <= iMaxZ; z++) {
1747
                for (int y = belowY; y <= belowY + 1; y++) {
1748
                    BlockChangeEntry entryBelowY_POS = blockChangeTracker.getBlockChangeEntry(
1749
                    data.blockChangeRef, tick, worldId, x, y, z, 
1750
                    direction);
1751
                    if (entryBelowY_POS != null) return entryBelowY_POS;
1752
                }
1753
            }
1754
        }
1755
        return null;
1756
    }
1757
    
1758
1759
    /**
1760
     * Horizontal block push
1761
     */
1762
    private boolean checkPastStateHorizontalPush(final Player player, final PlayerLocation from, final PlayerLocation to,
1763
                                                 final PlayerMoveData thisMove, final PlayerMoveData lastMove, final int tick, 
1764
                                                 final boolean debug, final MovingData data, final MovingConfig cc) {
1765
        final UUID worldId = from.getWorld().getUID();
1766
        final double xDistance = to.getX() - from.getX();
1767
        final double zDistance = to.getZ() - from.getZ();
1768
        final Direction dir;
1769
        if (Math.abs(xDistance) > Math.abs(zDistance)) {
1770
            dir = xDistance > 0.0 ? Direction.X_POS : Direction.X_NEG;
1771
        }
1772
        else dir = zDistance > 0.0 ? Direction.Z_POS : Direction.Z_NEG;
1773
    
1774
        final BlockChangeEntry entry = BlockChangeSearch(from, tick, dir, debug, data, cc, worldId, false);
1775
        if (entry != null) {
1776
            final int count = MovingData.getHorVelValCount(0.6);
1777
            // TODO: Add horizontal vel
1778
            //data.clearActiveHorVel();
1779
            //data.addHorizontalVelocity(new AccountEntry(tick, 0.6, count, count));
1780
            // Stuck in block, Hack
1781
            data.addVerticalVelocity(new SimpleEntry(-0.35, 6));
1782
            data.blockChangeRef.updateSpan(entry);
1783
1784
            if (debug) {
1785
                final StringBuilder builder = new StringBuilder(150);
1786
                builder.append("Direct block push at (");
1787
                builder.append("x:" + entry.x);
1788
                builder.append(" y:" + entry.y);
1789
                builder.append(" z:" + entry.z);
1790
                builder.append(" direction:" + entry.direction.name());
1791
                builder.append(")");
1792
                debug(player, builder.toString());
1793
                debug(player, "checkPastStateHorizontalPush: set velocity: " + 0.6);
1794
            }
1795
            return true;
1796
        }
1797
        return false;
1798
    }
1799
1800
1801
    /**
1802
     * Check for extremely large moves. Initial intention is to prevent cheaters
1803
     * from creating extreme load. SurvivalFly or CreativeFly is needed.
1804
     * On violations, also request an Improbable checking.
1805
     */
1806
    private Location checkExtremeMove(final Player player, final PlayerLocation from, final PlayerLocation to, 
1807
                                      final MovingData data, final MovingConfig cc) {
1808
        // TODO: Recent Minecraft versions allow a lot of unhealthy moves. Observed so far:
1809
        // - Riptide + gliding (+ firework !?)
1810
        // - Really high levitation levels
1811
        // - Bouncing while riptiding
1812
        // (- High jump amplifiers might be a problem as well)
1813
        // One could also let Extreme_move block this stuff anyway, reason being: 
1814
        // 1) we cannot support vanilla Minecraft features to arbitrary depths.
1815
        // 2) Why would one let players perform such moves anyway (which is usually bad news for server-sided chunk loading)? 
1816
        // [In fact, even Mojang attempted to mitigate this: https://www.minecraft.net/en-us/article/new-world-generation-java-available-testing]
1817
        // Thinkble: configurable option to block such moves (cc.blockUnealthyMove / cc.blockLegitExtremeMoves)
1818
1819
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
1820
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove(); 
1821
        // TODO: Latency effects.
1822
        double violation = 0.0;
1823
        // Vertical move.
1824
        final boolean allowVerticalVelocity = false; // TODO: Configurable
1825
        if (Math.abs(thisMove.yDistance) > Magic.EXTREME_MOVE_DIST_VERTICAL) {
1826
            // Exclude valid moves first.
1827
            // About 3.9 seems to be the positive maximum for velocity use in survival mode, regardless jump effect.
1828
            // About -1.85 seems to be the negative maximum for velocity use in survival mode. Falling can result in slightly less than -3.
1829
            if (lastMove.toIsValid && Math.abs(thisMove.yDistance) < Math.abs(lastMove.yDistance)
1830
                && (thisMove.yDistance > 0.0 && lastMove.yDistance > 0.0 || thisMove.yDistance < 0.0 && lastMove.yDistance < 0.0) 
1831
                || allowVerticalVelocity && !data.getOrUseVerticalVelocity(thisMove.yDistance).isEmpty()) {
1832
                // Speed decreased or velocity is present.
1833
            }
1834
            else violation += thisMove.yDistance; // Could subtract lastMove.yDistance.
1835
        }
1836
1837
        // Horizontal move.
1838
        if (thisMove.hDistance > Magic.EXTREME_MOVE_DIST_HORIZONTAL) {
1839
            // Exclude valid moves first.
1840
            // TODO: Attributes might allow unhealthy moves as well.
1841
            // Observed maximum use so far: 5.515
1842
            // TODO: Velocity
1843
            //final double amount = thisMove.hDistance - data.getHorizontalFreedom(); // Will change with model change.
1844
            //if (amount < 0.0 || lastMove.toIsValid && thisMove.hDistance - lastMove.hDistance <= 0.0 
1845
            //    || data.useHorizontalVelocity(amount) >= amount) {
1846
                // Speed decreased or velocity is present.
1847
            //}
1848
            //else 
1849
                violation += thisMove.hDistance; // Could subtract lastMove.hDistance.
1850
        }
1851
1852
        if (violation > 0.0) {
1853
            Improbable.check(player, (float)violation, System.currentTimeMillis(), "extreme.move", DataManager.getPlayerData(player));
1854
            // Ensure a set back location is present.
1855
            if (!data.hasSetBack()) data.setSetBack(from);
1856
            // Process violation as sub check of the appropriate fly check.
1857
            violation *= 100.0;
1858
            final Check check;
1859
            final ActionList actions;
1860
            final double vL;
1861
1862
            if (thisMove.flyCheck == CheckType.MOVING_SURVIVALFLY) {
1863
                check = survivalFly;
1864
                actions = cc.survivalFlyActions;
1865
                data.survivalFlyVL += violation;
1866
                vL = data.survivalFlyVL;
1867
            }
1868
            else {
1869
                check = creativeFly;
1870
                actions = cc.creativeFlyActions;
1871
                data.creativeFlyVL += violation;
1872
                vL = data.creativeFlyVL;
1873
            }
1874
            final ViolationData vd = new ViolationData(check, player, vL, violation, actions);
1875
            // TODO: Reduce copy and paste (method to fill in locations, once using exact coords and latering default actions).
1876
            if (vd.needsParameters()) {
1877
                vd.setParameter(ParameterName.LOCATION_FROM, String.format(Locale.US, "%.2f, %.2f, %.2f", from.getX(), from.getY(), from.getZ()));
1878
                vd.setParameter(ParameterName.LOCATION_TO, String.format(Locale.US, "%.2f, %.2f, %.2f", to.getX(), to.getY(), to.getZ()));
1879
                vd.setParameter(ParameterName.DISTANCE, String.format(Locale.US, "%.2f", TrigUtil.distance(from, to)));
1880
                vd.setParameter(ParameterName.TAGS, "EXTREME_MOVE");
1881
            }
1882
            // Some resetting is done in MovingListener.
1883
            if (check.executeActions(vd).willCancel()) {
1884
                // Set back + view direction of to (more smooth).
1885
                return MovingUtil.getApplicableSetBackLocation(player, to.getYaw(), to.getPitch(), from, data, cc);
1886
            }
1887
        }
1888
        // No cancel intended.
1889
        return null;
1890
    }
1891
1892
1893
    /**
1894
     * Called during PlayerMoveEvent for adjusting to a to-be-done/scheduled set back. <br>
1895
     * NOTE: Meaning differs from data.onSetBack (to be cleaned up).
1896
     * @param newTo
1897
     *            Must be a cloned or new Location instance, free for whatever
1898
     *            other plugins do with it.
1899
     */
1900
    private void prepareSetBack(final Player player, final PlayerMoveEvent event, final Location newTo, 
1901
                                final MovingData data, final MovingConfig cc, final IPlayerData pData) {
1902
        // Illegal Yaw/Pitch.
1903
        if (LocUtil.needsYawCorrection(newTo.getYaw())) {
1904
            newTo.setYaw(LocUtil.correctYaw(newTo.getYaw()));
1905
        }
1906
        if (LocUtil.needsPitchCorrection(newTo.getPitch())) {
1907
            newTo.setPitch(LocUtil.correctPitch(newTo.getPitch()));
1908
        }
1909
        // Reset some data.
1910
        data.prepareSetBack(newTo);
1911
        aux.resetPositionsAndMediumProperties(player, newTo, data, cc); // TODO: Might move into prepareSetBack, experimental here.
1912
1913
        // Set new to-location, distinguish method by settings.
1914
        final PlayerSetBackMethod method = cc.playerSetBackMethod;
1915
        if (method.shouldSetTo()) {
1916
            event.setTo(newTo); // LEGACY: pre-2017-03-24
1917
            if (pData.isDebugActive(checkType)) {
1918
                debug(player, "Set back technique: SET_TO");
1919
            }
1920
        }
1921
        if (method.shouldCancel()) {
1922
            event.setCancelled(true);
1923
            if (pData.isDebugActive(checkType)) {
1924
                debug(player, "Set back technique: CANCEL (schedule:" + method.shouldSchedule() + " updateFrom:" + method.shouldUpdateFrom() + ")");
1925
            }
1926
        } 
1927
        // NOTE: A teleport is scheduled on MONITOR priority, if set so.
1928
        // TODO: enforcelocation?
1929
        // Debug.
1930
        if (pData.isDebugActive(checkType)) {
1931
            debug(player, "Prepare set back to: " + newTo.getWorld().getName() + "/" + LocUtil.simpleFormatPosition(newTo) + " (" + method.getId() + ")");
1932
        }
1933
    }
1934
1935
    /**
1936
     * Adjust data for a cancelled move. No teleport event will fire, but an
1937
     * outgoing position is sent. Note that event.getFrom() may be overridden by
1938
     * a plugin, which the server will ignore, but can lead to confusion.
1939
     */
1940
    private void onCancelledMove(final Player player, final Location from, final int tick, final long now, 
1941
                                 final MovingData mData, final MovingConfig mCc, final CombinedData data,
1942
                                 final IPlayerData pData) {
1943
        final boolean debug = pData.isDebugActive(checkType);
1944
        // Detect our own set back, choice of reference location.
1945
        if (mData.hasTeleported()) {
1946
            final Location ref = mData.getTeleported();
1947
            // Initiate further action depending on settings.
1948
            final PlayerSetBackMethod method = mCc.playerSetBackMethod;
1949
            if (method.shouldUpdateFrom()) {
1950
                // Attempt to do without a PlayerTeleportEvent as follow up.
1951
                // TODO: Doing this on MONITOR priority is problematic, despite optimal.
1952
                LocUtil.set(from, ref);
1953
            }
1954
            if (method.shouldSchedule()) {
1955
                // Schedule the teleport, because it might be faster than the next incoming packet.
1956
                final IPlayerData pd = DataManager.getPlayerData(player);
1957
                if (pd.isPlayerSetBackScheduled()) {
1958
                    debug(player, "Teleport (set back) already scheduled to: " + ref);
1959
                }
1960
                else {
1961
                    if (debug) {
1962
                        debug(player, "Schedule a new teleport (isPlayerSetBackScheduled returned false, with teleported being set - set back) to: " + ref);
1963
                    }
1964
                    pd.requestPlayerSetBack();
1965
                }
1966
            }
1967
            // (Position adaption will happen with the teleport on tick, or with the next move.)
1968
        }
1969
1970
        // Assume the implicit teleport to the from-location (no Bukkit event fires).
1971
        Combined.resetYawRate(player, from.getYaw(), now, false, pData); // Not reset frequency, but do set yaw.
1972
        aux.resetPositionsAndMediumProperties(player, from, mData, mCc); 
1973
        // TODO: Should probably leave this to the teleport event!
1974
        mData.resetTrace(player, from, tick, mcAccess.getHandle(), mCc);
1975
        // Expect a teleport to the from location (packet balance, no Bukkit event will fire).
1976
        pData.getGenericInstance(NetData.class).teleportQueue.onTeleportEvent(from.getX(), from.getY(), from.getZ(), from.getYaw(), from.getPitch());
1977
    }
1978
1979
1980
    /**
1981
     * Uses useLoc if in vehicle.
1982
     * 
1983
     * @param from Might use useLoc, but will reset it, if in vehicle.
1984
     * @param to Do not use useLoc for this.
1985
     */
1986
    private void onMoveMonitorNotCancelled(final Player player, final Location from, final Location to, 
1987
                                           final long now, final long tick, final CombinedData data, 
1988
                                           final MovingData mData, final MovingConfig mCc, final IPlayerData pData) {
1989
        final String toWorldName = to.getWorld().getName();
1990
        final boolean debug = pData.isDebugActive(checkType);
1991
        Combined.feedYawRate(player, to.getYaw(), now, toWorldName, data, pData);
1992
        // TODO: maybe even not count vehicles at all ?
1993
        if (player.isInsideVehicle()) {
1994
            // TODO: refine (!).
1995
            final Location ref = player.getVehicle().getLocation(useLoc);
1996
            aux.resetPositionsAndMediumProperties(player, ref, mData, mCc); // TODO: Consider using to and intercept cheat attempts in another way.
1997
            useLoc.setWorld(null);
1998
            mData.updateTrace(player, to, tick, mcAccess.getHandle()); // TODO: Can you become invincible by sending special moves?
1999
        }
2000
        else if (!from.getWorld().getName().equals(toWorldName)) {
2001
            // A teleport event should follow.
2002
            aux.resetPositionsAndMediumProperties(player, to, mData, mCc);
2003
            mData.resetTrace(player, to, tick, mcAccess.getHandle(), mCc);
2004
        }
2005
        else {
2006
            // TODO: Detect differing location (a teleport event would follow).
2007
            final PlayerMoveData lastMove = mData.playerMoves.getFirstPastMove();
2008
            if (!lastMove.toIsValid || !TrigUtil.isSamePos(to, lastMove.to.getX(), lastMove.to.getY(), lastMove.to.getZ())) {
2009
                // Something odd happened, e.g. a set back.
2010
                aux.resetPositionsAndMediumProperties(player, to, mData, mCc);
2011
            }
2012
            else {
2013
                // Normal move, nothing to do.
2014
            }
2015
            mData.updateTrace(player, to, tick, mcAccess.getHandle());
2016
            if (mData.hasTeleported()) {
2017
                if (mData.isTeleportedPosition(to)) {
2018
                    // Skip resetting, especially if legacy setTo is enabled.
2019
                    // TODO: Might skip this condition, if legacy setTo is not enabled.
2020
                    if (debug) debug(player, "Event not cancelled, with teleported (set back) set, assume legacy behavior.");
2021
                    return;
2022
                }
2023
                else if (pData.isPlayerSetBackScheduled()) {
2024
                    // Skip, because the scheduled teleport has been overridden.
2025
                    // TODO: Only do this, if cancel is set, because it is not an un-cancel otherwise.
2026
                    if (debug) debug(player, "Event not cancelled, despite a set back has been scheduled. Cancel set back.");
2027
                    mData.resetTeleported(); // (PlayerTickListener will notice it's not set.)
2028
                }
2029
                else {
2030
                    if (debug) debug(player, "Inconsistent state (move MONITOR): teleported has been set, but no set back is scheduled. Ignore set back.");
2031
                    mData.resetTeleported();
2032
                }
2033
            }
2034
        }
2035
    }
2036
2037
2038
    /**
2039
     * @return True, if processing the teleport event should be aborted, false
2040
     *         otherwise.
2041
     */
2042
    private boolean onPlayerTeleportMonitorHasTeleported(final Player player, final PlayerTeleportEvent event, 
2043
                                                         final Location to, final MovingData data, final MovingConfig cc, 
2044
                                                         final IPlayerData pData) {
2045
        if (data.isTeleportedPosition(to)) {
2046
            // Set back.
2047
            confirmSetBack(player, true, data, cc, pData, to);
2048
            // Reset some more data.
2049
            data.reducePlayerMorePacketsData(1);
2050
            // Log.
2051
            if (pData.isDebugActive(checkType)) {
2052
                debugTeleportMessage(player, event, "(set back)", to);
2053
            }
2054
            return true;
2055
        }
2056
        else {
2057
            /*
2058
             * In this case another plugin has prevented NCP cancelling that
2059
             * teleport during before this EventPriority stage, or another
2060
             * plugin has altered the target location (to).
2061
             */
2062
            NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.TRACE_FILE, CheckUtils.getLogMessagePrefix(player, CheckType.MOVING) + " TP " + event.getCause() + " (set back was overridden): " + to);
2063
            return false;
2064
        }
2065
    }
2066
2067
2068
    /**
2069
     * A set back has been performed, or applying it got through to
2070
     * EventPriority.MONITOR.
2071
     * 
2072
     * @param fakeNews
2073
     *            True, if it's not really been applied yet (, but should get
2074
     *            applied, due to reaching EventPriority.MONITOR).
2075
     */
2076
    private void confirmSetBack(final Player player, final boolean fakeNews, final MovingData data, 
2077
                                final MovingConfig cc, final IPlayerData pData, final Location fallbackTeleported) {
2078
        // TODO: Find the reason why it can be null even passed the precondition not null.
2079
        final Location teleported = data.getTeleported();
2080
        final PlayerMoveInfo moveInfo = aux.usePlayerMoveInfo();
2081
        moveInfo.set(player, teleported != null ? teleported : fallbackTeleported, null, cc.yOnGround);
2082
        if (cc.loadChunksOnTeleport) {
2083
            MovingUtil.ensureChunksLoaded(player, teleported != null ? teleported : fallbackTeleported, "teleport", data, cc, pData);        
2084
        }
2085
        data.onSetBack(moveInfo.from, teleported, cc, player);
2086
        aux.returnPlayerMoveInfo(moveInfo);
2087
        // Reset stuff.
2088
        Combined.resetYawRate(player, teleported.getYaw(), System.currentTimeMillis(), true, pData); // TODO: Not sure.
2089
        data.resetTeleported();
2090
    }
2091
2092
2093
    private void onPlayerTeleportMonitorCancelled(final Player player, final PlayerTeleportEvent event, 
2094
                                                  final Location to, final MovingData data, final IPlayerData pData) {
2095
        if (data.isTeleported(to)) {
2096
            // (Only precise match.)
2097
            // TODO: Schedule a teleport to set back with PlayerData (+ failure count)?
2098
            // TODO: Log once per player always?
2099
            NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.TRACE_FILE, CheckUtils.getLogMessagePrefix(player, CheckType.MOVING) 
2100
                                                                       +  " TP " + event.getCause() + " (set back was prevented): " + to);
2101
        }
2102
        else {
2103
            if (pData.isDebugActive(checkType)) {
2104
                debugTeleportMessage(player, event, to);
2105
            }
2106
        }
2107
        data.resetTeleported();
2108
    }
2109
2110
2111
    private void onPlayerTeleportMonitorNullTarget(final Player player, 
2112
                                                   final PlayerTeleportEvent event, final Location to, 
2113
                                                   final MovingData data, final IPlayerData pData) {
2114
        final boolean debug = pData.isDebugActive(checkType);
2115
        if (debug) {
2116
            debugTeleportMessage(player, event, "No target location (to) set.");
2117
        }
2118
        if (data.hasTeleported()) {
2119
            if (DataManager.getPlayerData(player).isPlayerSetBackScheduled()) {
2120
                // Assume set back event following later.
2121
                event.setCancelled(true);
2122
                if (debug) debugTeleportMessage(player, event, "Cancel, due to a scheduled set back.");
2123
                
2124
            }
2125
            else {
2126
                data.resetTeleported();
2127
                if (debug) debugTeleportMessage(player, event, "Skip set back, not being scheduled.");
2128
            }
2129
        }
2130
    }
2131
2132
2133
    /**
2134
     * @param extra
2135
     *            Added in the end, with a leading space each.
2136
     */
2137
    private void debugTeleportMessage(final Player player, final PlayerTeleportEvent event, final Object... extra) {
2138
        final StringBuilder builder = new StringBuilder(128);
2139
        builder.append("TP ");
2140
        builder.append(event.getCause());
2141
        if (event.isCancelled()) {
2142
            builder.append(" (cancelled)");
2143
        }
2144
        if (extra != null && extra.length > 0) {
2145
            for (final Object obj : extra) {
2146
                if (obj != null) {
2147
                    builder.append(' ');
2148
                    if (obj instanceof String) {
2149
                        builder.append((String) obj);
2150
                    }
2151
                    else {
2152
                        builder.append(obj.toString());
2153
                    }
2154
                }
2155
            }
2156
        }
2157
        debug(player, builder.toString());
2158
    }
2159
2160
    private void checkFallDamageEvent(final Player player, final EntityDamageEvent event) {
2161
        final IPlayerData pData = DataManager.getPlayerData(player);
2162
        final MovingData data = pData.getGenericInstance(MovingData.class);
2163
        if (player.isInsideVehicle()) {
2164
            // Ignore vehicles (noFallFallDistance will be inaccurate anyway).
2165
            data.clearNoFallData();
2166
            return;
2167
        }
2168
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
2169
        final PlayerMoveInfo moveInfo = aux.usePlayerMoveInfo();
2170
        final double yOnGround = Math.max(cc.noFallyOnGround, cc.yOnGround);
2171
        final Location loc = player.getLocation(useFallLoc);
2172
        moveInfo.set(player, loc, null, yOnGround);
2173
        final PlayerLocation pLoc = moveInfo.from;
2174
        pLoc.collectBlockFlags(yOnGround);
2175
2176
        if (event.isCancelled() || !MovingUtil.shouldCheckSurvivalFly(player, pLoc, moveInfo.to, data, cc, pData) 
2177
            || !noFall.isEnabled(player, pData)) {
2178
            data.clearNoFallData();
2179
            useFallLoc.setWorld(null);
2180
            aux.returnPlayerMoveInfo(moveInfo);
2181
            return;
2182
        }
2183
        final boolean debug = pData.isDebugActive(CheckType.MOVING_NOFALL);
2184
        boolean allowReset = true;
2185
        float fallDistance = player.getFallDistance();
2186
        final double damage = BridgeHealth.getRawDamage(event);
2187
        final float dataDist = (float) NoFall.getApplicableFallHeight(player, loc.getY(), data);
2188
        if (debug) debug(player, "Damage(FALL/PRE): " + damage + " / mc=" + player.getFallDistance() + " nf=" + data.noFallFallDistance + " nfr=" + dataDist);
2189
2190
        // NoFall bypass checks.
2191
        // TODO: data.noFallSkipAirCheck is used to skip checking in general, thus move into that block or not?
2192
        // TODO: Could consider skipping accumulated fall distance for NoFall in general as well.
2193
        final float mult = NoFall.applyBlockDamageMultiplier(player, data);
2194
        if (!data.noFallSkipAirCheck) {
2195
            
2196
            // Cheat: let Minecraft gather and deal fall damage.
2197
            final double dataDamage = NoFall.getDamage(dataDist, mult, player);
2198
            if (damage > dataDamage || dataDamage <= 0.0) {
2199
2200
                // Hot fix: allow fall damage in lava.
2201
                // TODO: Correctly model the half fall distance per in-lava move and taking fall damage in lava. 
2202
                // TODO: Also relate past y-distance(s) to the fall distance (mc).
2203
                // Original issue: https://github.com/NoCheatPlus/Issues/issues/439#issuecomment-299300421
2204
                final PlayerMoveData firstPastMove = data.playerMoves.getFirstPastMove();
2205
                if (pLoc.isOnGround() && pLoc.isInLava() && firstPastMove.toIsValid && firstPastMove.yDistance < 0.0) {
2206
                    if (debug) debug(player, "NoFall/Damage: allow fall damage in lava (hotfix).");
2207
                } 
2208
                // Fix issues when gliding down vines with elytra.
2209
                // Checking for velocity does not work since sometimes it can be applied after this check runs
2210
                else if (moveInfo.from.isOnClimbable() && firstPastMove.isGliding) {
2211
                    if (debug) debug(player, "Ignore fakefall on climbable on elytra move");
2212
                }
2213
                // NOTE: Double violations are possible with the in-air check below.
2214
                // TODO: Differing sub checks, once cancel action...
2215
                else if (noFallVL(player, "fakefall", data, cc)) {
2216
                    player.setFallDistance(dataDist);
2217
                    // There are edge (and hard to reproduce) cases where this may happen due to bugs on NCP's side,
2218
                    // but a legit player should never be able to trigger fakefall many times in a row. So an Improbable check request makes sense.
2219
                    Improbable.check(player, player.getFallDistance(), System.currentTimeMillis(), "nofall.fakefall",pData);
2220
                    if (dataDamage <= 0.0) {
2221
                        // Cancel the event.
2222
                        event.setCancelled(true);
2223
                        useFallLoc.setWorld(null);
2224
                        aux.returnPlayerMoveInfo(moveInfo);
2225
                        return;
2226
                    }
2227
                    else {
2228
                        // Adjust and continue.
2229
                        if (debug) debug(player, "NoFall/Damage: override player fall distance and damage (" + fallDistance + " -> " + dataDist + ").");
2230
                        fallDistance = dataDist;
2231
                        BridgeHealth.setRawDamage(event, dataDamage);
2232
                    }
2233
                }
2234
            }
2235
            // Be sure not to lose that block.
2236
            // TODO: What is this and why is it right here?
2237
            // Answer: https://github.com/NoCheatPlus/NoCheatPlus/commit/50ebbb01fb3998f5e4ebba741ed6cbd318de00c5
2238
            data.noFallFallDistance += 1.0; 
2239
            // TODO: Account for liquid too?
2240
            // Cheat: set ground to true in-air. Cancel the event and restore fall distance. NoFall data will not be reset 
2241
            if (!pLoc.isOnGround(1.0, 0.3, 0.1) && !pLoc.isResetCond() && !pLoc.isAboveLadder()) {
2242
                if (noFallVL(player, "fakeground", data, cc) && data.hasSetBack()) {
2243
                    allowReset = false;
2244
                    Improbable.check(player, 1.0f, System.currentTimeMillis(), "nofall.fakeground",pData);
2245
                }
2246
            }
2247
        }
2248
        aux.returnPlayerMoveInfo(moveInfo);
2249
        // Fall-back check (skip with jump amplifier).
2250
        final double maxD = NoFall.getDamage(Math.max(dataDist, fallDistance), mult, player);
2251
        if (maxD > damage) {
2252
            // TODO: respect dealDamage ?
2253
            double featherFallingCorrection = NoFall.applyFeatherFalling(player, maxD, mcAccess.getHandle().dealFallDamageFiresAnEvent().decide());
2254
            BridgeHealth.setRawDamage(event, featherFallingCorrection);
2255
            if (debug) {
2256
                debug(player, "Adjust fall damage to: " + (featherFallingCorrection != maxD ? featherFallingCorrection : maxD));
2257
            }
2258
        }
2259
2260
        if (allowReset) {
2261
            // Normal fall damage, reset data.
2262
            data.clearNoFallData();
2263
            if (debug) {
2264
                debug(player, "Reset NoFall data on fall damage.");
2265
            }
2266
        }
2267
        else {
2268
            // Minecraft/NCP bug or cheating.
2269
            // (Do not cancel the event, otherwise: "moved too quickly exploit".)
2270
            if (cc.noFallViolationReset) {
2271
                data.clearNoFallData();
2272
            }
2273
            // Add player to hover checks.
2274
            if (cc.sfHoverCheck && data.sfHoverTicks < 0) {
2275
                data.sfHoverTicks = 0;
2276
                hoverTicks.add(player.getName());
2277
            }
2278
        }
2279
        // Entity fall-distance should be reset elsewhere.
2280
        // Cleanup.
2281
        useFallLoc.setWorld(null);
2282
    }
2283
2284
2285
    private boolean noFallVL(final Player player, final String tag, final MovingData data, final MovingConfig cc) {
2286
        data.noFallVL += 1.0;
2287
        final ViolationData vd = new ViolationData(noFall, player, data.noFallVL, 1.0, cc.noFallActions);
2288
        if (tag != null) vd.setParameter(ParameterName.TAGS, tag);
2289
        return noFall.executeActions(vd).willCancel();
2290
    }
2291
2292
2293
    @Override
2294
    public void playerJoins(final Player player) {
2295
        final IPlayerData pData = DataManager.getPlayerData(player);
2296
        dataOnJoin(player, player.getLocation(useJoinLoc), false, pData.getGenericInstance(MovingData.class), pData.getGenericInstance(MovingConfig.class), pData.isDebugActive(checkType));
2297
        // Cleanup.
2298
        useJoinLoc.setWorld(null);
2299
    }
2300
2301
2302
    /**
2303
     * Alter data for players joining (join, respawn).<br>
2304
     * Do before, if necessary:<br>
2305
     * <li>data.clearFlyData()</li>
2306
     * <li>data.setSetBack(...)</li>
2307
     * 
2308
     * @param loc Can be useLoc (!).
2309
     */
2310
    private void dataOnJoin(Player player, Location loc, boolean isRespawn, MovingData data, MovingConfig cc, final boolean debug) {
2311
        final int tick = TickTask.getTick();
2312
        final String tag = isRespawn ? "Respawn" : "Join";
2313
        // Check loaded chunks.
2314
        if (cc.loadChunksOnJoin) {
2315
            // (Don't use past-move heuristic for skipping here.)
2316
            final int loaded = MapUtil.ensureChunksLoaded(loc.getWorld(), loc.getX(), loc.getZ(), Magic.CHUNK_LOAD_MARGIN_MIN);
2317
            if (loaded > 0 && debug) {
2318
                StaticLog.logInfo("Player " + tag + ": Loaded " + loaded + " chunk" + (loaded == 1 ? "" : "s") + " for the world " + loc.getWorld().getName() +  " for player: " + player.getName());
2319
            }
2320
        }
2321
2322
        // Correct set back on join.
2323
        if (!data.hasSetBack() || !data.hasSetBackWorldChanged(loc)) {
2324
            data.clearFlyData();
2325
            data.setSetBack(loc);
2326
            // (resetPositions is called below)
2327
            data.joinOrRespawn = true; // TODO: Review if to always set (!).
2328
        }
2329
        else {
2330
            // TODO: Check consistency/distance.
2331
            //final Location setBack = data.getSetBack(loc);
2332
            //final double d = loc.distanceSquared(setBack);
2333
            // TODO: If to reset positions: relate to previous ones and set back.
2334
            // (resetPositions is called below)
2335
        }
2336
        // (Note: resetPositions resets lastFlyCheck and other.)
2337
        data.clearVehicleData(); // TODO: Uncertain here, what to check.
2338
        data.clearAllMorePacketsData();
2339
        data.removeAllVelocity();
2340
        data.resetTrace(player, loc, tick, mcAccess.getHandle(), cc); // Might reset to loc instead of set back ?
2341
        aux.resetPositionsAndMediumProperties(player, loc, data, cc);
2342
2343
        // Enforcing the location.
2344
        if (cc.enforceLocation) {
2345
            playersEnforce.add(player.getName());
2346
        }
2347
2348
        // Hover.
2349
        initHover(player, data, cc, data.playerMoves.getFirstPastMove().from.onGroundOrResetCond);
2350
        // TODO: Thing are more complicated than just gravity. Friction too and other medium properties when join!
2351
        // TODO: last is use in calculating but doesn't init(because there no last move yet) when first time join leading to false positives
2352
        data.lastGravity = attributeAccess.getHandle().getGravity(player);
2353
2354
        // Check for vehicles.
2355
        // TODO: Order / exclusion of items.
2356
        if (player.isInsideVehicle()) {
2357
            vehicleChecks.onPlayerVehicleEnter(player, player.getVehicle());
2358
        }
2359
        if (debug) {
2360
            debug(player, tag + ": " + loc);
2361
        }
2362
    }
2363
2364
2365
    /**
2366
     * Initialize the hover check for a player (login, respawn).
2367
     */
2368
    private void initHover(final Player player, final MovingData data, final MovingConfig cc, final boolean isOnGroundOrResetCond) {
2369
        
2370
        // Reset hover ticks until a better method is used.
2371
        if (!isOnGroundOrResetCond && cc.sfHoverCheck) {
2372
            // Start as if hovering already.
2373
            // Could check shouldCheckSurvivalFly(player, data, cc), but this should be more sharp (gets checked on violation).
2374
            data.sfHoverTicks = 0;
2375
            data.sfHoverLoginTicks = cc.sfHoverLoginTicks;
2376
            hoverTicks.add(player.getName());
2377
        }
2378
        else {
2379
            data.sfHoverLoginTicks = 0;
2380
            data.sfHoverTicks = -1;
2381
        }
2382
    }
2383
2384
2385
    @Override
2386
    public void playerLeaves(final Player player) {
2387
        final IPlayerData pData = DataManager.getPlayerData(player);
2388
        final MovingData data = pData.getGenericInstance(MovingData.class);
2389
        final Location loc = player.getLocation(useLeaveLoc);
2390
        // Debug logout.
2391
        if (pData.isDebugActive(checkType)) {
2392
            StaticLog.logInfo("Player " + player.getName() + " leaves at location: " + loc.toString());
2393
        }
2394
2395
        if (!player.isSleeping() && !player.isDead()) {
2396
            // Check for missed moves.
2397
            // TODO: Force-load chunks [log if (!)] ?
2398
            // Check only from the old versions, newer SERVER versions don't seem like a problem to account for
2399
            if (!BlockProperties.isPassable(loc) && !Bridge1_13.hasIsSwimming()) {
2400
                final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
2401
                final PlayerMoveData lastMove2 = data.playerMoves.getNumberOfPastMoves() > 1 ? data.playerMoves.getSecondPastMove() : null;
2402
                // Won't use lastMove.toIsValid to prevent players already failed some checks in last move
2403
                if (lastMove.valid) {
2404
                    Location refLoc = lastMove.toIsValid ? new Location(loc.getWorld(), lastMove.to.getX(), lastMove.to.getY(), lastMove.to.getZ()) 
2405
                                                           : new Location(loc.getWorld(), lastMove.from.getX(), lastMove.from.getY(), lastMove.from.getZ());
2406
                    // More likely lastmove location is same with left location, try to check for second lastmove  
2407
                    if (TrigUtil.isSamePos(loc, refLoc) && !lastMove.toIsValid && lastMove2 != null) {
2408
                        refLoc = lastMove2.toIsValid ? new Location(loc.getWorld(), lastMove2.to.getX(), lastMove2.to.getY(), lastMove2.to.getZ()) 
2409
                                                       : new Location(loc.getWorld(), lastMove2.from.getX(), lastMove2.from.getY(), lastMove2.from.getZ());
2410
                    }
2411
                    // Correct position by scan block up
2412
                    // TODO: what about try to phase upward not downward anymore?
2413
                    if (!BlockProperties.isPassable(refLoc) || refLoc.distanceSquared(loc) > 1.25) {
2414
                        double y = Math.ceil(loc.getY());
2415
                        refLoc = loc.clone();
2416
                        refLoc.setY(y);
2417
                        if (!BlockProperties.isPassable(refLoc)) refLoc = loc;
2418
                    }
2419
                    final double d = refLoc.distanceSquared(loc);
2420
                    if (d > 0.0) {
2421
                        // TODO: Consider to always set back here. Might skip on big distances.
2422
                        if (TrigUtil.manhattan(loc, refLoc) > 0 || BlockProperties.isPassable(refLoc)) {
2423
                            if (passable.isEnabled(player, pData)) {
2424
                                StaticLog.logWarning("Potential exploit: Player " + player.getName() + " leaves, having moved into a block (not tracked by moving checks): " + player.getWorld().getName() + " / " + DebugUtil.formatMove(refLoc, loc));
2425
                                // TODO: Actually trigger a passable violation (+tag).
2426
                                if (d > 1.25) {
2427
                                    StaticLog.logWarning("SKIP set back for " + player.getName() + ", because distance is too high (risk of false positives): " + d);
2428
                                }
2429
                                else {
2430
                                    StaticLog.logInfo("Set back player " + player.getName() + ": " + LocUtil.simpleFormat(refLoc));
2431
                                    data.prepareSetBack(refLoc);
2432
                                    if (!SchedulerHelper.teleportEntity(player, refLoc, BridgeMisc.TELEPORT_CAUSE_CORRECTION_OF_POSITION)) {
2433
                                        StaticLog.logWarning("FAILED to set back player " + player.getName());
2434
                                    }
2435
                                }
2436
                            }
2437
                        }
2438
                    }
2439
                }
2440
            }
2441
        }
2442
        useLeaveLoc.setWorld(null);
2443
        noFall.onLeave(player, data, pData);
2444
        // TODO: Add a method for ordinary presence-change resetting (use in join + leave).
2445
        data.onPlayerLeave();
2446
        if (SchedulerHelper.isTaskScheduled(data.vehicleSetBackTaskId)) {
2447
            // Reset the id, assume the task will still teleport the vehicle.
2448
            // TODO: Should rather force teleport (needs storing the task + data).
2449
            data.vehicleSetBackTaskId = null;
2450
        }
2451
        data.vehicleSetPassengerTaskId = null;
2452
    }
2453
2454
    @Override
2455
    public void onTick(final int tick, final long timeLast) {
2456
        // TODO: Change to per world checking (as long as configs are per world).
2457
        // Legacy: enforcing location consistency.
2458
        if (!playersEnforce.isEmpty()) {
2459
            checkOnTickPlayersEnforce();
2460
        }
2461
        // Hover check (SurvivalFly).
2462
        if (tick % hoverTicksStep == 0 && !hoverTicks.isEmpty()) {
2463
            // Only check every so and so ticks.
2464
            checkOnTickHover();
2465
        }
2466
        // Cleanup.
2467
        useTickLoc.setWorld(null);
2468
    }
2469
2470
2471
    /**
2472
     * Check for hovering.<br>
2473
     * NOTE: Makes use of useLoc, without resetting it.
2474
     */
2475
    private void checkOnTickHover() {
2476
        final List<String> rem = new ArrayList<String>(hoverTicks.size()); // Pessimistic.
2477
        final PlayerMoveInfo info = aux.usePlayerMoveInfo();
2478
        for (final String playerName : hoverTicks) {
2479
            // TODO: put players into the set (+- one tick would not matter ?)
2480
            // TODO: might add an online flag to data !
2481
            final Player player = DataManager.getPlayerExact(playerName);
2482
            if (player == null || !player.isOnline()) {
2483
                rem.add(playerName);
2484
                continue;
2485
            }
2486
            final IPlayerData pData = DataManager.getPlayerData(player);
2487
            final MovingData data = pData.getGenericInstance(MovingData.class);
2488
            if (player.isDead() || player.isSleeping() || player.isInsideVehicle()) {
2489
                data.sfHoverTicks = -1;
2490
                // (Removed below.)
2491
            }
2492
            if (data.sfHoverTicks < 0) {
2493
                data.sfHoverLoginTicks = 0;
2494
                rem.add(playerName);
2495
                continue;
2496
            }
2497
            else if (data.sfHoverLoginTicks > 0) {
2498
                // Additional "grace period".
2499
                data.sfHoverLoginTicks --;
2500
                continue;
2501
            }
2502
            final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
2503
            // Check if enabled at all.
2504
            if (!cc.sfHoverCheck) {
2505
                rem.add(playerName);
2506
                data.sfHoverTicks = -1;
2507
                continue;
2508
            }
2509
            // Increase ticks here.
2510
            data.sfHoverTicks += hoverTicksStep;
2511
            if (data.sfHoverTicks < cc.sfHoverTicks) {
2512
                // Don't do the heavier checking here, let moving checks reset these.
2513
                continue;
2514
            }
2515
            if (checkHover(player, data, cc, pData, info)) {
2516
                rem.add(playerName);
2517
            }
2518
        }
2519
        hoverTicks.removeAll(rem);
2520
        aux.returnPlayerMoveInfo(info);
2521
    }
2522
2523
2524
    /**
2525
     * Legacy check: Enforce location of players, in case of inconsistencies.
2526
     * First move exploit / possibly vehicle leave.<br>
2527
     * NOTE: Makes use of useLoc, without resetting it.
2528
     */
2529
    private void checkOnTickPlayersEnforce() {
2530
        final List<String> rem = new ArrayList<String>(playersEnforce.size()); // Pessimistic.
2531
        for (final String playerName : playersEnforce) {
2532
            final Player player = DataManager.getPlayerExact(playerName);
2533
            if (player == null || !player.isOnline()) {
2534
                rem.add(playerName);
2535
                continue;
2536
            } 
2537
            else if (player.isDead() || player.isSleeping() || player.isInsideVehicle()) {
2538
                // Don't remove but also don't check [subject to change].
2539
                continue;
2540
            }
2541
            final MovingData data = DataManager.getGenericInstance(player, MovingData.class);
2542
            final Location newTo = enforceLocation(player, player.getLocation(useTickLoc), data);
2543
            if (newTo != null) {
2544
                data.prepareSetBack(newTo);
2545
                SchedulerHelper.teleportEntity(player, newTo, BridgeMisc.TELEPORT_CAUSE_CORRECTION_OF_POSITION);
2546
            }
2547
        }
2548
        if (!rem.isEmpty()) {
2549
            playersEnforce.removeAll(rem);
2550
        }
2551
    }
2552
2553
2554
    private Location enforceLocation(final Player player, final Location loc, final MovingData data) {
2555
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
2556
        if (lastMove.toIsValid && TrigUtil.distanceSquared(lastMove.to.getX(), lastMove.to.getY(), lastMove.to.getZ(), loc.getX(), loc.getY(), loc.getZ()) > 1.0 / 256.0) {
2557
            // Teleport back. 
2558
            if (data.hasSetBack()) {
2559
                // Might have to re-check all context with playerJoins and keeping old set backs...
2560
                // Could use a flexible set back policy (switch to in-air on login). 
2561
                return data.getSetBack(loc); // (OK? ~ legacy)
2562
            }
2563
            return new Location(player.getWorld(), lastMove.to.getX(), lastMove.to.getY(), lastMove.to.getZ(), loc.getYaw(), loc.getPitch());
2564
        }
2565
        return null;
2566
    }
2567
2568
2569
    /**
2570
     * The heavier checking including onGround etc., check if enabled/valid to check before this.
2571
     */
2572
    private boolean checkHover(final Player player, final MovingData data, final MovingConfig cc, final IPlayerData pData, final PlayerMoveInfo info) {
2573
        // Check if player is on ground.
2574
        final Location loc = player.getLocation(useTickLoc); // useLoc.setWorld(null) is done in onTick.
2575
        info.set(player, loc, null, cc.yOnGround);
2576
        // (Could use useLoc of MoveInfo here. Note orderm though.)
2577
        final boolean res;
2578
        // TODO: Collect flags, more margin ?
2579
        final int loaded = info.from.ensureChunksLoaded();
2580
        if (loaded > 0 && pData.isDebugActive(checkType)) {
2581
            StaticLog.logInfo("Hover check: Needed to load " + loaded + " chunk" + (loaded == 1 ? "" : "s") + " for the world " + loc.getWorld().getName() +  " around " + loc.getBlockX() + "," + loc.getBlockZ() + " in order to check player: " + player.getName());
2582
        }
2583
        if (info.from.isOnGroundOrResetCond() || info.from.isAboveLadder()) {
2584
            res = true;
2585
            data.sfHoverTicks = 0;
2586
        }
2587
        else {
2588
            if (data.sfHoverTicks > cc.sfHoverTicks) {
2589
                // Re-Check if survivalfly can apply at all.
2590
                final PlayerMoveInfo moveInfo = aux.usePlayerMoveInfo();
2591
                moveInfo.set(player, loc, null, cc.yOnGround);
2592
                if (MovingUtil.shouldCheckSurvivalFly(player, moveInfo.from, moveInfo.to, data, cc, pData)) {
2593
                    handleHoverViolation(player, moveInfo.from, cc, data, pData);
2594
                    // Assume the player might still be hovering.
2595
                    res = false;
2596
                    data.sfHoverTicks = 0;
2597
                }
2598
                else {
2599
                    // Reset hover ticks and check next period.
2600
                    res = false;
2601
                    data.sfHoverTicks = 0;
2602
                }
2603
                aux.returnPlayerMoveInfo(moveInfo);
2604
            }
2605
            else res = false;
2606
        }
2607
        info.cleanup();
2608
        return res;
2609
    }
2610
2611
2612
    private void handleHoverViolation(final Player player, final PlayerLocation loc, 
2613
                                      final MovingConfig cc, final MovingData data, final IPlayerData pData) {
2614
        // Check nofall damage (!).
2615
        if (cc.sfHoverFallDamage && noFall.isEnabled(player, pData)) {
2616
            // Consider adding 3/3.5 to fall distance if fall distance > 0?
2617
            noFall.checkDamage(player, loc.getY(), data, pData);
2618
        }
2619
        // Delegate violation handling.
2620
        survivalFly.handleHoverViolation(player, loc, cc, data);
2621
    }
2622
2623
2624
    @Override
2625
    public CheckType getCheckType() {
2626
        // TODO: this is for the hover check only...
2627
        // TODO: ugly.
2628
        return CheckType.MOVING_SURVIVALFLY;
2629
    }
2630
2631
2632
    @Override
2633
    public IData removeData(String playerName) {
2634
        // Let TickListener handle automatically
2635
        //hoverTicks.remove(playerName);
2636
        //playersEnforce.remove(playerName);
2637
        return null;
2638
    }
2639
2640
2641
    @Override
2642
    public void removeAllData() {
2643
        hoverTicks.clear();
2644
        playersEnforce.clear();
2645
        aux.clear();
2646
    }
2647
2648
2649
    @Override
2650
    public void onReload() {
2651
        aux.clear();
2652
        hoverTicksStep = Math.max(1, ConfigManager.getConfigFile().getInt(ConfPaths.MOVING_SURVIVALFLY_HOVER_STEP));
2653
    }
2654
2655
2656
    /**
2657
     * Output information specific to player-move events.
2658
     */
2659
    private void outputMoveDebug(final Player player, final PlayerLocation from, final PlayerLocation to, final double maxYOnGround, final MCAccess mcAccess) {
2660
        final StringBuilder builder = new StringBuilder(250);
2661
        final Location loc = player.getLocation();
2662
        builder.append(CheckUtils.getLogMessagePrefix(player, checkType));
2663
        builder.append("MOVE in world (" + from.getWorld().getName() + ") ------>\n");
2664
        DebugUtil.addMove(from, to, loc, builder);
2665
        final Vector v = player.getVelocity();
2666
        if (v.lengthSquared() > 0.0) {
2667
            builder.append("\n");
2668
            builder.append("Bukkit velocity: " + StringUtil.fdec6.format(v.getX()) + ", " + StringUtil.fdec6.format(v.getY()) + ", " + StringUtil.fdec6.format(v.getZ()));
2669
        }
2670
        final double jump = mcAccess.getJumpAmplifier(player);
2671
        final double speed = mcAccess.getFasterMovementAmplifier(player);
2672
        final double strider = BridgeEnchant.getDepthStriderLevel(player);
2673
        final double swiftSneak = BridgeEnchant.getSwiftSneakLevel(player);
2674
        final IPlayerData pData = DataManager.getPlayerData(player);
2675
        if (BuildParameters.debugLevel > 0) {
2676
            // Note: the block flags are for normal on-ground checking, not with yOnGrond set to 0.5.
2677
            from.collectBlockFlags(maxYOnGround);
2678
            if (from.getBlockFlags() != 0) {
2679
                builder.append("\nFrom flags: " + StringUtil.join(BlockFlags.getFlagNames(from.getBlockFlags()), " + "));
2680
            }
2681
            to.collectBlockFlags(maxYOnGround);
2682
            if (to.getBlockFlags() != 0) {
2683
                builder.append("\nTo flags: " + StringUtil.join(BlockFlags.getFlagNames(to.getBlockFlags()), " + "));
2684
            }
2685
            if (!BlockProperties.isAir(from.getBlockType())) {
2686
                DebugUtil.addBlockInfo(builder, from, "\nFrom");
2687
            }
2688
            if (!BlockProperties.isAir(from.getBlockTypeBelow())) {
2689
                DebugUtil.addBlockBelowInfo(builder, from, "\nFrom");
2690
            }
2691
            if (!from.isOnGround() && from.isOnGround(0.5)) {
2692
                builder.append(" (ground within 0.5)");
2693
            }
2694
            if (!BlockProperties.isAir(to.getBlockType())) {
2695
                DebugUtil.addBlockInfo(builder, to, "\nTo");
2696
            }
2697
            if (!BlockProperties.isAir(to.getBlockTypeBelow())) {
2698
                DebugUtil.addBlockBelowInfo(builder, to, "\nTo");
2699
            }
2700
            if (!to.isOnGround() && to.isOnGround(0.5)) {
2701
                builder.append(" (ground within 0.5)");
2702
            }
2703
        }
2704
        NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, builder.toString());
2705
        if (BuildParameters.debugLevel > 0) {
2706
            builder.setLength(0);
2707
            builder.append("\n(attribute speed= " + attributeAccess.getHandle().getMovementSpeed(player) + ")");
2708
            builder.append("\n(attribute fly speed= " + player.getFlySpeed() + ")");
2709
            if (player.isSprinting()) { 
2710
                builder.append("\n(Bukkit sprinting)");
2711
            }
2712
            if (pData.isSprinting()) {
2713
                builder.append("\n(NCP sprinting)");
2714
            }
2715
            if (pData.isShiftKeyPressed()) {
2716
                builder.append("\n(Shift key down)");
2717
            }
2718
            if (pData.isInCrouchingPose()) {
2719
                builder.append("\n(NCP sneaking)");
2720
            }
2721
            if (BridgeMisc.isUsingItem(player)) {
2722
                builder.append("\n(is using " + BridgeMisc.getItemInUse(player) + " item)");
2723
            }
2724
            if (!Double.isInfinite(speed)) {
2725
                builder.append("\n(e_speed= " + (speed + 1) + ")");
2726
            }
2727
            final double slow = PotionUtil.getPotionEffectAmplifier(player, BridgePotionEffect.SLOWNESS);
2728
            if (!Double.isInfinite(Bridge1_13.getSlowfallingAmplifier(player))) {
2729
                builder.append("\n(e_slowfall= " + (Bridge1_13.getSlowfallingAmplifier(player) + 1) + ")");
2730
            }
2731
            if (!Double.isInfinite(Bridge1_9.getLevitationAmplifier(player))) {
2732
                builder.append("\n(e_levitation= " + (Bridge1_9.getLevitationAmplifier(player) + 1) + ")");
2733
            }
2734
            if (!Double.isInfinite(slow)) {
2735
                builder.append("\n(e_slow= " + (slow + 1) + ")");
2736
            }
2737
            if (!Double.isInfinite(jump)) {
2738
                builder.append("\n(e_jump= " + (jump + 1) + ")");
2739
            }
2740
            if (strider != 0) {
2741
                builder.append("\n(e_depth_strider= " + strider + ")");
2742
            }
2743
            if (swiftSneak != 0) {
2744
                builder.append("\n(swift sneak= " + swiftSneak + ")");
2745
            }
2746
            if (Bridge1_9.isGliding(player)) {
2747
                builder.append("\n(gliding, no elytra-wearing check)");
2748
            }
2749
            if (Bridge1_13.isRiptiding(player)) {
2750
                builder.append("\n(riptiding with Lvl: " + BridgeEnchant.getRiptideLevel(player) + ")");
2751
            }
2752
            if (player.getAllowFlight()) {
2753
                builder.append("\n(allow flight)");
2754
            }
2755
            if (player.isFlying()) {
2756
                builder.append("\n(flying)");
2757
            }
2758
            NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, builder.toString());
2759
        }
2760
    }
2761
}

How it counteracts this module

NoCheatPlus enforces violations by teleporting the player through SchedulerHelper.teleportEntity with the correction-of-position cause while prepareSetBack records the target. If a set-back lands while the client is mid-blink, the client keeps walking locally, and the replay starts from the pre-correction position, so the flushed path diverges from the corrected server position and the envelope flags the same divergence again. The module has no S08 handling at all, so the correction applies and the replay pays for it.

anticheat PlayerEventListener (pending teleport ledger)

PlayerEventListener.java214 lines · Java
1
/*
2
 * This file is part of Hawk Anticheat.
3
 * Copyright (C) 2018 Hawk Development Team
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
package me.islandscout.hawk.module;
20
21
import me.islandscout.hawk.Hawk;
22
import me.islandscout.hawk.HawkPlayer;
23
import me.islandscout.hawk.event.bukkit.HawkAsyncPlayerAbilitiesEvent;
24
import me.islandscout.hawk.event.bukkit.HawkAsyncPlayerMetadataEvent;
25
import me.islandscout.hawk.event.bukkit.HawkAsyncPlayerVelocityChangeEvent;
26
import me.islandscout.hawk.util.Debug;
27
import me.islandscout.hawk.util.Pair;
28
import me.islandscout.hawk.util.ServerUtils;
29
import me.islandscout.hawk.wrap.WrappedWatchableObject;
30
import me.islandscout.hawk.wrap.entity.MetaData;
31
import org.bukkit.Location;
32
import org.bukkit.entity.HumanEntity;
33
import org.bukkit.entity.Player;
34
import org.bukkit.event.EventHandler;
35
import org.bukkit.event.EventPriority;
36
import org.bukkit.event.Listener;
37
import org.bukkit.event.inventory.InventoryCloseEvent;
38
import org.bukkit.event.inventory.InventoryOpenEvent;
39
import org.bukkit.event.player.*;
40
import org.bukkit.event.vehicle.VehicleEnterEvent;
41
import org.bukkit.event.vehicle.VehicleExitEvent;
42
import org.bukkit.util.Vector;
43
44
import java.util.List;
45
46
public class PlayerEventListener implements Listener {
47
48
    private final Hawk hawk;
49
50
    public PlayerEventListener(Hawk hawk) {
51
        this.hawk = hawk;
52
53
        hawk.getHawkSyncTaskScheduler().addRepeatingTask(new Runnable() {
54
            @Override
55
            public void run() {
56
                for(HawkPlayer pp : hawk.getHawkPlayers()) {
57
                    Player p = pp.getPlayer();
58
                    pp.setPing(ServerUtils.getPing(p));
59
                }
60
            }
61
        }, 40);
62
    }
63
64
    @EventHandler(priority = EventPriority.LOWEST)
65
    public void onLogin(PlayerLoginEvent e) {
66
        Player p = e.getPlayer();
67
        hawk.addProfile(p); //This line is necessary since it must get called BEFORE hawk listens to the player's packets
68
        hawk.getHawkPlayer(p).setOnline(true);
69
    }
70
71
    //Set protocol version
72
    @EventHandler
73
    public void onJoin(PlayerJoinEvent e) {
74
        hawk.getHawkPlayer(e.getPlayer()).setClientVersion(ServerUtils.getProtocolVersion(e.getPlayer()));
75
    }
76
77
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
78
    public void onQuit(PlayerQuitEvent e) {
79
        hawk.getHawkPlayer(e.getPlayer()).setOnline(false);
80
        hawk.removeProfile(e.getPlayer().getUniqueId()); //TODO call this elsewhere
81
        hawk.getCheckManager().removeData(e.getPlayer());
82
    }
83
84
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
85
    public void onVelocity(HawkAsyncPlayerVelocityChangeEvent e) {
86
        if(e.isAdditive())
87
            return;
88
        HawkPlayer pp = hawk.getHawkPlayer(e.getPlayer());
89
        Vector vector = e.getVelocity();
90
91
        List<Pair<Vector, Long>> pendingVelocities = pp.getPendingVelocities();
92
        pendingVelocities.add(new Pair<>(vector, System.currentTimeMillis()));
93
        if(pendingVelocities.size() > 20)
94
            pendingVelocities.remove(0);
95
    }
96
97
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
98
    public void onInventoryOpenServerSide(InventoryOpenEvent e) {
99
        HumanEntity hE = e.getPlayer();
100
        if(!(hE instanceof Player))
101
            return;
102
103
        //Fixes issues regarding the client not releasing item usage when a server inventory is opened.
104
        //Consumables may not have this issue.
105
        HawkPlayer pp = hawk.getHawkPlayer((Player) hE);
106
        pp.sendSimulatedAction(new Runnable() {
107
            @Override
108
            public void run() {
109
                pp.setBlocking(false);
110
                pp.setPullingBow(false);
111
                pp.setInventoryOpen((byte)2);
112
            }
113
        });
114
    }
115
116
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
117
    public void onInventoryCloseServerSide(InventoryCloseEvent e) {
118
        HumanEntity hE = e.getPlayer();
119
        if(!(hE instanceof Player))
120
            return;
121
122
        HawkPlayer pp = hawk.getHawkPlayer((Player) hE);
123
        pp.sendSimulatedAction(new Runnable() {
124
            @Override
125
            public void run() {
126
                pp.setInventoryOpen((byte)0);
127
            }
128
        });
129
    }
130
131
    @EventHandler
132
    public void sendMetadataEvent(HawkAsyncPlayerMetadataEvent e) {
133
        List<WrappedWatchableObject> objects = e.getMetaData();
134
        for(WrappedWatchableObject object : objects) {
135
            if(object.getIndex() == 0) {
136
                Player p = e.getPlayer();
137
                HawkPlayer pp = hawk.getHawkPlayer(p);
138
                byte status = (byte)object.getObject();
139
140
                //bitmask
141
                if((status & 16) == 16) {
142
                    pp.addMetaDataUpdate(new MetaData(MetaData.Type.USE_ITEM, true));
143
                } else {
144
                    pp.addMetaDataUpdate(new MetaData(MetaData.Type.USE_ITEM, false));
145
                }
146
                if((status & 8) == 8) {
147
                    pp.addMetaDataUpdate(new MetaData(MetaData.Type.SPRINT, true));
148
                } else {
149
                    pp.addMetaDataUpdate(new MetaData(MetaData.Type.SPRINT, false));
150
                }
151
                /*if((status & 2) == 2) {
152
                    pp.addMetaDataUpdate(new MetaData(MetaData.Type.SNEAK, true));
153
                } else {
154
                    pp.addMetaDataUpdate(new MetaData(MetaData.Type.SNEAK, false));
155
                }*/
156
157
                break;
158
            }
159
        }
160
    }
161
162
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
163
    public void vehicleEnter(VehicleEnterEvent e) {
164
        if(e.getEntered() instanceof Player) {
165
            HawkPlayer pp = hawk.getHawkPlayer((Player)e.getEntered());
166
            pp.sendSimulatedAction(new Runnable() {
167
                @Override
168
                public void run() {
169
                    pp.setInVehicle(true);
170
                }
171
            });
172
        }
173
    }
174
175
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
176
    public void vehicleExit(VehicleExitEvent e) {
177
        if(e.getExited() instanceof Player) {
178
            HawkPlayer pp = hawk.getHawkPlayer((Player)e.getExited());
179
            pp.sendSimulatedAction(new Runnable() {
180
                @Override
181
                public void run() {
182
                    pp.setInVehicle(false);
183
                }
184
            });
185
        }
186
    }
187
188
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
189
    public void abilitiesServerSide(HawkAsyncPlayerAbilitiesEvent e) {
190
        HawkPlayer pp = hawk.getHawkPlayer(e.getPlayer());
191
        pp.sendSimulatedAction(new Runnable() {
192
            @Override
193
            public void run() {
194
                pp.setAllowedToFly(e.isAllowedToFly());
195
                pp.setFlying(e.isFlying());
196
                pp.setInCreative(e.isCreativeMode());
197
            }
198
        });
199
    }
200
201
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
202
    public void teleport(PlayerTeleportEvent e) {
203
        HawkPlayer pp = hawk.getHawkPlayer(e.getPlayer());
204
205
        Location tpLoc = e.getTo().clone();
206
        tpLoc.setYaw(tpLoc.getYaw() % 360F);
207
        tpLoc.setPitch(tpLoc.getPitch() % 360F);
208
209
        pp.addPendingTeleport(tpLoc);
210
211
        //Exception ee = new Exception();
212
        //ee.printStackTrace();
213
    }
214
}

How it counteracts this module

Hawk records every server teleport in a pending list and, in MoveEvent construction, drops moves until one matches the pending teleported location; a move farther than 64 blocks squared from the last accepted position triggers resync, and a pending teleport that is never matched clears after the player's ping plus 40 ticks. The first flushed move after a long blink exceeds the 64-block bound, so Hawk discards the replay and resyncs the player, and every move that precedes the resync is dropped while the pending teleport sits unanswered.

← Back to Analysis Hub