Spicy Spider module 2 files, 2369 lines

Spicy Spider: Full Source Analysis

Spicy's Spider turns any wall into a ladder.

info/spicyclient/modules/movement/Spider.java · GitHub source ↗

Published 2026-08-13 · Updated 2026-10-14

Packets This Module Uses

Analysis

Overview

Spicy's Spider turns any wall into a ladder. Its only active code is an EventOnLadder post handler: when the player is collided horizontally and the mode setting is 'Vanilla' (the only mode in the ModeSetting), it sets the event's onLadder flag true. The event is dispatched from the fork's EntityLivingBase.isOnLadder(), which computes the vanilla ladder state (the block under the player is ladder or vine, and the player is not a spectator), fires the POST event, and returns the module-modified value whenever it differs from the block check. The client's movement code then applies vanilla ladder physics: horizontal motion clamped to ±0.15, fall distance zeroed, and, while collided horizontally, a 0.2 upward motion per tick, so the player climbs any wall at 0.2 blocks per tick with no ladder present. The wire effect is a C03 stream showing a sustained +0.2 vertical distance next to non-climbable blocks.

The event hook

EntityLivingBase.isOnLadder() (line 1132) reads the block at the player's feet, computes the vanilla ladder boolean, constructs an EventOnLadder, dispatches it with EventType.POST, and returns e.onLadder when the modules changed it. Spider's handler sets onLadder = true exactly when isCollidedHorizontally, so the client believes it is on a climbable while touching any solid wall. The ModeSetting wraps a single option, 'Vanilla', so the mode switch is vestigial: there is no other mode to select.

The climb physics

The ladder motion lives in EntityLivingBase.onLivingUpdate (line 1645): while isOnLadder() is true, motionX and motionZ are clamped to ±0.15, fallDistance resets to zero, and the collided-horizontally branch (line 1667) sets motionY = 0.2. Because isOnLadder() now reports true against plain walls, the player ascends at a constant 0.2 blocks per tick while touching the wall: a vertical profile with no vanilla counterpart, since vanilla only ascends via the jump impulse. Each tick the C03 stream reports that +0.2 y-distance, which is the entire server-visible surface.

source Spider.java (module)

Spider.java60 lines · JavaOriginal ↗
1
package info.spicyclient.modules.movement;
2
3
import org.lwjgl.input.Keyboard;
4
5
import info.spicyclient.events.Event;
6
import info.spicyclient.events.listeners.EventMotion;
7
import info.spicyclient.events.listeners.EventOnLadder;
8
import info.spicyclient.events.listeners.EventUpdate;
9
import info.spicyclient.modules.Module;
10
import info.spicyclient.settings.ModeSetting;
11
import net.minecraft.network.play.client.C03PacketPlayer;
12
import net.minecraft.util.EnumFacing;
13
import net.minecraft.util.MathHelper;
14
15
public class Spider extends Module {
16
	
17
	private ModeSetting mode = new ModeSetting("Mode", "Vanilla", "Vanilla");
18
	
19
	public Spider() {
20
		super("Spider", Keyboard.KEY_NONE, Category.MOVEMENT);
21
		resetSettings();
22
	}
23
	
24
	@Override
25
	public void resetSettings() {
26
		this.settings.clear();
27
		this.addSettings(mode);
28
	}
29
	
30
	public void onEnable() {
31
		
32
	}
33
	
34
	public void onDisable() {
35
		
36
	}
37
	
38
	public void onEvent(Event e) {
39
		
40
		if (e instanceof EventUpdate) {
41
			
42
			if (e.isPre()) {
43
				
44
				this.additionalInformation = mode.getMode();
45
				
46
			}
47
			
48
		}
49
		
50
		if (e instanceof EventOnLadder) {
51
			if (e.isPost()) {
52
				if (mc.thePlayer.isCollidedHorizontally && mode.is("Vanilla")) {
53
					((EventOnLadder) e).onLadder = true;
54
				}
55
			}
56
		}
57
		
58
	}
59
	
60
}

What this file does

The module is two small handlers. The EventUpdate pre branch only writes the current mode into additionalInformation. The EventOnLadder post branch is the exploit: if isCollidedHorizontally and the mode is 'Vanilla', it sets the event's onLadder field true, a single boolean write that the fork's isOnLadder() dispatcher honors.

resetSettings and addSettings show the configuration surface: one ModeSetting with one mode. The Module base class handles the toggle lifecycle; there is no onEnable or onDisable logic, so the module's entire behavior is the flag write.

source EntityLivingBase.java (ladder dispatch and consumption)

EntityLivingBase.java2309 lines · JavaOriginal ↗
1
package net.minecraft.entity;
2
3
import com.google.common.base.Predicate;
4
import com.google.common.base.Predicates;
5
import com.google.common.collect.Maps;
6
7
import info.spicyclient.SpicyClient;
8
import info.spicyclient.events.EventType;
9
import info.spicyclient.events.listeners.EventOnLadder;
10
11
import java.util.Collection;
12
import java.util.Iterator;
13
import java.util.List;
14
import java.util.Map;
15
import java.util.Random;
16
import java.util.UUID;
17
import net.minecraft.block.Block;
18
import net.minecraft.block.material.Material;
19
import net.minecraft.block.state.IBlockState;
20
import net.minecraft.enchantment.EnchantmentHelper;
21
import net.minecraft.entity.ai.attributes.AttributeModifier;
22
import net.minecraft.entity.ai.attributes.BaseAttributeMap;
23
import net.minecraft.entity.ai.attributes.IAttribute;
24
import net.minecraft.entity.ai.attributes.IAttributeInstance;
25
import net.minecraft.entity.ai.attributes.ServersideAttributeMap;
26
import net.minecraft.entity.item.EntityItem;
27
import net.minecraft.entity.item.EntityXPOrb;
28
import net.minecraft.entity.passive.EntityWolf;
29
import net.minecraft.entity.player.EntityPlayer;
30
import net.minecraft.entity.player.EntityPlayerMP;
31
import net.minecraft.entity.projectile.EntityArrow;
32
import net.minecraft.init.Blocks;
33
import net.minecraft.item.Item;
34
import net.minecraft.item.ItemArmor;
35
import net.minecraft.item.ItemStack;
36
import net.minecraft.nbt.NBTBase;
37
import net.minecraft.nbt.NBTTagCompound;
38
import net.minecraft.nbt.NBTTagFloat;
39
import net.minecraft.nbt.NBTTagList;
40
import net.minecraft.nbt.NBTTagShort;
41
import net.minecraft.network.play.server.S04PacketEntityEquipment;
42
import net.minecraft.network.play.server.S0BPacketAnimation;
43
import net.minecraft.network.play.server.S0DPacketCollectItem;
44
import net.minecraft.potion.Potion;
45
import net.minecraft.potion.PotionEffect;
46
import net.minecraft.potion.PotionHelper;
47
import net.minecraft.scoreboard.Team;
48
import net.minecraft.util.AxisAlignedBB;
49
import net.minecraft.util.BlockPos;
50
import net.minecraft.util.CombatTracker;
51
import net.minecraft.util.DamageSource;
52
import net.minecraft.util.EntitySelectors;
53
import net.minecraft.util.EnumParticleTypes;
54
import net.minecraft.util.MathHelper;
55
import net.minecraft.util.Vec3;
56
import net.minecraft.world.World;
57
import net.minecraft.world.WorldServer;
58
59
public abstract class EntityLivingBase extends Entity
60
{
61
    private static final UUID sprintingSpeedBoostModifierUUID = UUID.fromString("662A6B8D-DA3E-4C1C-8813-96EA6097278D");
62
    private static final AttributeModifier sprintingSpeedBoostModifier = (new AttributeModifier(sprintingSpeedBoostModifierUUID, "Sprinting speed boost", 0.30000001192092896D, 2)).setSaved(false);
63
    private BaseAttributeMap attributeMap;
64
    private final CombatTracker _combatTracker = new CombatTracker(this);
65
    private final Map<Integer, PotionEffect> activePotionsMap = Maps.<Integer, PotionEffect>newHashMap();
66
67
    /** The equipment this mob was previously wearing, used for syncing. */
68
    private final ItemStack[] previousEquipment = new ItemStack[5];
69
70
    /** Whether an arm swing is currently in progress. */
71
    public boolean isSwingInProgress;
72
    public int swingProgressInt;
73
    public int arrowHitTimer;
74
75
    /**
76
     * The amount of time remaining this entity should act 'hurt'. (Visual appearance of red tint)
77
     */
78
    public int hurtTime;
79
80
    /** What the hurt time was max set to last. */
81
    public int maxHurtTime;
82
83
    /** The yaw at which this entity was last attacked from. */
84
    public float attackedAtYaw;
85
86
    /**
87
     * The amount of time remaining this entity should act 'dead', i.e. have a corpse in the world.
88
     */
89
    public int deathTime;
90
    public float prevSwingProgress;
91
    public float swingProgress;
92
    public float prevLimbSwingAmount;
93
    public float limbSwingAmount;
94
95
    /**
96
     * Only relevant when limbYaw is not 0(the entity is moving). Influences where in its swing legs and arms currently
97
     * are.
98
     */
99
    public float limbSwing;
100
    public int maxHurtResistantTime = 20;
101
    public float prevCameraPitch;
102
    public float cameraPitch;
103
    public float field_70769_ao;
104
    public float field_70770_ap;
105
    public float renderYawOffset;
106
    public float prevRenderYawOffset;
107
108
    /** Entity head rotation yaw */
109
    public float rotationYawHead;
110
111
    /** Entity head rotation yaw at previous tick */
112
    public float prevRotationYawHead;
113
114
    /**
115
     * A factor used to determine how far this entity will move each tick if it is jumping or falling.
116
     */
117
    public float jumpMovementFactor = 0.02F;
118
119
    /** The most recent player that has attacked this entity */
120
    protected EntityPlayer attackingPlayer;
121
122
    /**
123
     * Set to 60 when hit by the player or the player's wolf, then decrements. Used to determine whether the entity
124
     * should drop items on death.
125
     */
126
    protected int recentlyHit;
127
128
    /**
129
     * This gets set on entity death, but never used. Looks like a duplicate of isDead
130
     */
131
    protected boolean dead;
132
133
    /** The age of this EntityLiving (used to determine when it dies) */
134
    protected int entityAge;
135
    protected float prevOnGroundSpeedFactor;
136
    protected float onGroundSpeedFactor;
137
    protected float movedDistance;
138
    protected float prevMovedDistance;
139
    protected float field_70741_aB;
140
141
    /** The score value of the Mob, the amount of points the mob is worth. */
142
    protected int scoreValue;
143
144
    /**
145
     * Damage taken in the last hit. Mobs are resistant to damage less than this for a short time after taking damage.
146
     */
147
    protected float lastDamage;
148
149
    /** used to check whether entity is jumping. */
150
    protected boolean isJumping;
151
    public float moveStrafing;
152
    public float moveForward;
153
    protected float randomYawVelocity;
154
155
    /**
156
     * The number of updates over which the new position and rotation are to be applied to the entity.
157
     */
158
    protected int newPosRotationIncrements;
159
160
    /** The new X position to be applied to the entity. */
161
    protected double newPosX;
162
163
    /** The new Y position to be applied to the entity. */
164
    protected double newPosY;
165
    protected double newPosZ;
166
167
    /** The new yaw rotation to be applied to the entity. */
168
    protected double newRotationYaw;
169
170
    /** The new yaw rotation to be applied to the entity. */
171
    protected double newRotationPitch;
172
173
    /** Whether the DataWatcher needs to be updated with the active potions */
174
    private boolean potionsNeedUpdate = true;
175
176
    /** is only being set, has no uses as of MC 1.1 */
177
    private EntityLivingBase entityLivingToAttack;
178
    private int revengeTimer;
179
    private EntityLivingBase lastAttacker;
180
181
    /** Holds the value of ticksExisted when setLastAttacker was last called. */
182
    private int lastAttackerTime;
183
184
    /**
185
     * A factor used to determine how far this entity will move each tick if it is walking on land. Adjusted by speed,
186
     * and slipperiness of the current block.
187
     */
188
    private float landMovementFactor;
189
190
    /** Number of ticks since last jump */
191
    private int jumpTicks;
192
    private float absorptionAmount;
193
194
    /**
195
     * Called by the /kill command.
196
     */
197
    public void onKillCommand()
198
    {
199
        this.attackEntityFrom(DamageSource.outOfWorld, Float.MAX_VALUE);
200
    }
201
202
    public EntityLivingBase(World worldIn)
203
    {
204
        super(worldIn);
205
        this.applyEntityAttributes();
206
        this.setHealth(this.getMaxHealth());
207
        this.preventEntitySpawning = true;
208
        this.field_70770_ap = (float)((Math.random() + 1.0D) * 0.009999999776482582D);
209
        this.setPosition(this.posX, this.posY, this.posZ);
210
        this.field_70769_ao = (float)Math.random() * 12398.0F;
211
        this.rotationYaw = (float)(Math.random() * Math.PI * 2.0D);
212
        this.rotationYawHead = this.rotationYaw;
213
        this.stepHeight = 0.6F;
214
    }
215
216
    protected void entityInit()
217
    {
218
        this.dataWatcher.addObject(7, Integer.valueOf(0));
219
        this.dataWatcher.addObject(8, Byte.valueOf((byte)0));
220
        this.dataWatcher.addObject(9, Byte.valueOf((byte)0));
221
        this.dataWatcher.addObject(6, Float.valueOf(1.0F));
222
    }
223
224
    protected void applyEntityAttributes()
225
    {
226
        this.getAttributeMap().registerAttribute(SharedMonsterAttributes.maxHealth);
227
        this.getAttributeMap().registerAttribute(SharedMonsterAttributes.knockbackResistance);
228
        this.getAttributeMap().registerAttribute(SharedMonsterAttributes.movementSpeed);
229
    }
230
231
    protected void updateFallState(double y, boolean onGroundIn, Block blockIn, BlockPos pos)
232
    {
233
        if (!this.isInWater())
234
        {
235
            this.handleWaterMovement();
236
        }
237
238
        if (!this.worldObj.isRemote && this.fallDistance > 3.0F && onGroundIn)
239
        {
240
            IBlockState iblockstate = this.worldObj.getBlockState(pos);
241
            Block block = iblockstate.getBlock();
242
            float f = (float)MathHelper.ceiling_float_int(this.fallDistance - 3.0F);
243
244
            if (block.getMaterial() != Material.air)
245
            {
246
                double d0 = (double)Math.min(0.2F + f / 15.0F, 10.0F);
247
248
                if (d0 > 2.5D)
249
                {
250
                    d0 = 2.5D;
251
                }
252
253
                int i = (int)(150.0D * d0);
254
                ((WorldServer)this.worldObj).spawnParticle(EnumParticleTypes.BLOCK_DUST, this.posX, this.posY, this.posZ, i, 0.0D, 0.0D, 0.0D, 0.15000000596046448D, new int[] {Block.getStateId(iblockstate)});
255
            }
256
        }
257
258
        super.updateFallState(y, onGroundIn, blockIn, pos);
259
    }
260
261
    public boolean canBreatheUnderwater()
262
    {
263
        return false;
264
    }
265
266
    /**
267
     * Gets called every tick from main Entity class
268
     */
269
    public void onEntityUpdate()
270
    {
271
        this.prevSwingProgress = this.swingProgress;
272
        super.onEntityUpdate();
273
        this.worldObj.theProfiler.startSection("livingEntityBaseTick");
274
        boolean flag = this instanceof EntityPlayer;
275
276
        if (this.isEntityAlive())
277
        {
278
            if (this.isEntityInsideOpaqueBlock())
279
            {
280
                this.attackEntityFrom(DamageSource.inWall, 1.0F);
281
            }
282
            else if (flag && !this.worldObj.getWorldBorder().contains(this.getEntityBoundingBox()))
283
            {
284
                double d0 = this.worldObj.getWorldBorder().getClosestDistance(this) + this.worldObj.getWorldBorder().getDamageBuffer();
285
286
                if (d0 < 0.0D)
287
                {
288
                    this.attackEntityFrom(DamageSource.inWall, (float)Math.max(1, MathHelper.floor_double(-d0 * this.worldObj.getWorldBorder().getDamageAmount())));
289
                }
290
            }
291
        }
292
293
        if (this.isImmuneToFire() || this.worldObj.isRemote)
294
        {
295
            this.extinguish();
296
        }
297
298
        boolean flag1 = flag && ((EntityPlayer)this).capabilities.disableDamage;
299
300
        if (this.isEntityAlive())
301
        {
302
            if (this.isInsideOfMaterial(Material.water))
303
            {
304
                if (!this.canBreatheUnderwater() && !this.isPotionActive(Potion.waterBreathing.id) && !flag1)
305
                {
306
                    this.setAir(this.decreaseAirSupply(this.getAir()));
307
308
                    if (this.getAir() == -20)
309
                    {
310
                        this.setAir(0);
311
312
                        for (int i = 0; i < 8; ++i)
313
                        {
314
                            float f = this.rand.nextFloat() - this.rand.nextFloat();
315
                            float f1 = this.rand.nextFloat() - this.rand.nextFloat();
316
                            float f2 = this.rand.nextFloat() - this.rand.nextFloat();
317
                            this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, this.posX + (double)f, this.posY + (double)f1, this.posZ + (double)f2, this.motionX, this.motionY, this.motionZ, new int[0]);
318
                        }
319
320
                        this.attackEntityFrom(DamageSource.drown, 2.0F);
321
                    }
322
                }
323
324
                if (!this.worldObj.isRemote && this.isRiding() && this.ridingEntity instanceof EntityLivingBase)
325
                {
326
                    this.mountEntity((Entity)null);
327
                }
328
            }
329
            else
330
            {
331
                this.setAir(300);
332
            }
333
        }
334
335
        if (this.isEntityAlive() && this.isWet())
336
        {
337
            this.extinguish();
338
        }
339
340
        this.prevCameraPitch = this.cameraPitch;
341
342
        if (this.hurtTime > 0)
343
        {
344
            --this.hurtTime;
345
        }
346
347
        if (this.hurtResistantTime > 0 && !(this instanceof EntityPlayerMP))
348
        {
349
            --this.hurtResistantTime;
350
        }
351
352
        if (this.getHealth() <= 0.0F)
353
        {
354
            this.onDeathUpdate();
355
        }
356
357
        if (this.recentlyHit > 0)
358
        {
359
            --this.recentlyHit;
360
        }
361
        else
362
        {
363
            this.attackingPlayer = null;
364
        }
365
366
        if (this.lastAttacker != null && !this.lastAttacker.isEntityAlive())
367
        {
368
            this.lastAttacker = null;
369
        }
370
371
        if (this.entityLivingToAttack != null)
372
        {
373
            if (!this.entityLivingToAttack.isEntityAlive())
374
            {
375
                this.setRevengeTarget((EntityLivingBase)null);
376
            }
377
            else if (this.ticksExisted - this.revengeTimer > 100)
378
            {
379
                this.setRevengeTarget((EntityLivingBase)null);
380
            }
381
        }
382
383
        this.updatePotionEffects();
384
        this.prevMovedDistance = this.movedDistance;
385
        this.prevRenderYawOffset = this.renderYawOffset;
386
        this.prevRotationYawHead = this.rotationYawHead;
387
        this.prevRotationYaw = this.rotationYaw;
388
        this.prevRotationPitch = this.rotationPitch;
389
        this.worldObj.theProfiler.endSection();
390
    }
391
392
    /**
393
     * If Animal, checks if the age timer is negative
394
     */
395
    public boolean isChild()
396
    {
397
        return false;
398
    }
399
400
    /**
401
     * handles entity death timer, experience orb and particle creation
402
     */
403
    protected void onDeathUpdate()
404
    {
405
        ++this.deathTime;
406
407
        if (this.deathTime == 20)
408
        {
409
            if (!this.worldObj.isRemote && (this.recentlyHit > 0 || this.isPlayer()) && this.canDropLoot() && this.worldObj.getGameRules().getBoolean("doMobLoot"))
410
            {
411
                int i = this.getExperiencePoints(this.attackingPlayer);
412
413
                while (i > 0)
414
                {
415
                    int j = EntityXPOrb.getXPSplit(i);
416
                    i -= j;
417
                    this.worldObj.spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, j));
418
                }
419
            }
420
421
            this.setDead();
422
423
            for (int k = 0; k < 20; ++k)
424
            {
425
                double d2 = this.rand.nextGaussian() * 0.02D;
426
                double d0 = this.rand.nextGaussian() * 0.02D;
427
                double d1 = this.rand.nextGaussian() * 0.02D;
428
                this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL, this.posX + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, this.posY + (double)(this.rand.nextFloat() * this.height), this.posZ + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, d2, d0, d1, new int[0]);
429
            }
430
        }
431
    }
432
433
    /**
434
     * Entity won't drop items or experience points if this returns false
435
     */
436
    protected boolean canDropLoot()
437
    {
438
        return !this.isChild();
439
    }
440
441
    /**
442
     * Decrements the entity's air supply when underwater
443
     */
444
    protected int decreaseAirSupply(int p_70682_1_)
445
    {
446
        int i = EnchantmentHelper.getRespiration(this);
447
        return i > 0 && this.rand.nextInt(i + 1) > 0 ? p_70682_1_ : p_70682_1_ - 1;
448
    }
449
450
    /**
451
     * Get the experience points the entity currently has.
452
     */
453
    protected int getExperiencePoints(EntityPlayer player)
454
    {
455
        return 0;
456
    }
457
458
    /**
459
     * Only use is to identify if class is an instance of player for experience dropping
460
     */
461
    protected boolean isPlayer()
462
    {
463
        return false;
464
    }
465
466
    public Random getRNG()
467
    {
468
        return this.rand;
469
    }
470
471
    public EntityLivingBase getAITarget()
472
    {
473
        return this.entityLivingToAttack;
474
    }
475
476
    public int getRevengeTimer()
477
    {
478
        return this.revengeTimer;
479
    }
480
481
    public void setRevengeTarget(EntityLivingBase livingBase)
482
    {
483
        this.entityLivingToAttack = livingBase;
484
        this.revengeTimer = this.ticksExisted;
485
    }
486
487
    public EntityLivingBase getLastAttacker()
488
    {
489
        return this.lastAttacker;
490
    }
491
492
    public int getLastAttackerTime()
493
    {
494
        return this.lastAttackerTime;
495
    }
496
497
    public void setLastAttacker(Entity entityIn)
498
    {
499
        if (entityIn instanceof EntityLivingBase)
500
        {
501
            this.lastAttacker = (EntityLivingBase)entityIn;
502
        }
503
        else
504
        {
505
            this.lastAttacker = null;
506
        }
507
508
        this.lastAttackerTime = this.ticksExisted;
509
    }
510
511
    public int getAge()
512
    {
513
        return this.entityAge;
514
    }
515
516
    /**
517
     * (abstract) Protected helper method to write subclass entity data to NBT.
518
     */
519
    public void writeEntityToNBT(NBTTagCompound tagCompound)
520
    {
521
        tagCompound.setFloat("HealF", this.getHealth());
522
        tagCompound.setShort("Health", (short)((int)Math.ceil((double)this.getHealth())));
523
        tagCompound.setShort("HurtTime", (short)this.hurtTime);
524
        tagCompound.setInteger("HurtByTimestamp", this.revengeTimer);
525
        tagCompound.setShort("DeathTime", (short)this.deathTime);
526
        tagCompound.setFloat("AbsorptionAmount", this.getAbsorptionAmount());
527
528
        for (ItemStack itemstack : this.getInventory())
529
        {
530
            if (itemstack != null)
531
            {
532
                this.attributeMap.removeAttributeModifiers(itemstack.getAttributeModifiers());
533
            }
534
        }
535
536
        tagCompound.setTag("Attributes", SharedMonsterAttributes.writeBaseAttributeMapToNBT(this.getAttributeMap()));
537
538
        for (ItemStack itemstack1 : this.getInventory())
539
        {
540
            if (itemstack1 != null)
541
            {
542
                this.attributeMap.applyAttributeModifiers(itemstack1.getAttributeModifiers());
543
            }
544
        }
545
546
        if (!this.activePotionsMap.isEmpty())
547
        {
548
            NBTTagList nbttaglist = new NBTTagList();
549
550
            for (PotionEffect potioneffect : this.activePotionsMap.values())
551
            {
552
                nbttaglist.appendTag(potioneffect.writeCustomPotionEffectToNBT(new NBTTagCompound()));
553
            }
554
555
            tagCompound.setTag("ActiveEffects", nbttaglist);
556
        }
557
    }
558
559
    /**
560
     * (abstract) Protected helper method to read subclass entity data from NBT.
561
     */
562
    public void readEntityFromNBT(NBTTagCompound tagCompund)
563
    {
564
        this.setAbsorptionAmount(tagCompund.getFloat("AbsorptionAmount"));
565
566
        if (tagCompund.hasKey("Attributes", 9) && this.worldObj != null && !this.worldObj.isRemote)
567
        {
568
            SharedMonsterAttributes.func_151475_a(this.getAttributeMap(), tagCompund.getTagList("Attributes", 10));
569
        }
570
571
        if (tagCompund.hasKey("ActiveEffects", 9))
572
        {
573
            NBTTagList nbttaglist = tagCompund.getTagList("ActiveEffects", 10);
574
575
            for (int i = 0; i < nbttaglist.tagCount(); ++i)
576
            {
577
                NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i);
578
                PotionEffect potioneffect = PotionEffect.readCustomPotionEffectFromNBT(nbttagcompound);
579
580
                if (potioneffect != null)
581
                {
582
                    this.activePotionsMap.put(Integer.valueOf(potioneffect.getPotionID()), potioneffect);
583
                }
584
            }
585
        }
586
587
        if (tagCompund.hasKey("HealF", 99))
588
        {
589
            this.setHealth(tagCompund.getFloat("HealF"));
590
        }
591
        else
592
        {
593
            NBTBase nbtbase = tagCompund.getTag("Health");
594
595
            if (nbtbase == null)
596
            {
597
                this.setHealth(this.getMaxHealth());
598
            }
599
            else if (nbtbase.getId() == 5)
600
            {
601
                this.setHealth(((NBTTagFloat)nbtbase).getFloat());
602
            }
603
            else if (nbtbase.getId() == 2)
604
            {
605
                this.setHealth((float)((NBTTagShort)nbtbase).getShort());
606
            }
607
        }
608
609
        this.hurtTime = tagCompund.getShort("HurtTime");
610
        this.deathTime = tagCompund.getShort("DeathTime");
611
        this.revengeTimer = tagCompund.getInteger("HurtByTimestamp");
612
    }
613
614
    protected void updatePotionEffects()
615
    {
616
        Iterator<Integer> iterator = this.activePotionsMap.keySet().iterator();
617
618
        while (iterator.hasNext())
619
        {
620
            Integer integer = (Integer)iterator.next();
621
            PotionEffect potioneffect = (PotionEffect)this.activePotionsMap.get(integer);
622
623
            if (!potioneffect.onUpdate(this))
624
            {
625
                if (!this.worldObj.isRemote)
626
                {
627
                    iterator.remove();
628
                    this.onFinishedPotionEffect(potioneffect);
629
                }
630
            }
631
            else if (potioneffect.getDuration() % 600 == 0)
632
            {
633
                this.onChangedPotionEffect(potioneffect, false);
634
            }
635
        }
636
637
        if (this.potionsNeedUpdate)
638
        {
639
            if (!this.worldObj.isRemote)
640
            {
641
                this.updatePotionMetadata();
642
            }
643
644
            this.potionsNeedUpdate = false;
645
        }
646
647
        int i = this.dataWatcher.getWatchableObjectInt(7);
648
        boolean flag1 = this.dataWatcher.getWatchableObjectByte(8) > 0;
649
650
        if (i > 0)
651
        {
652
            boolean flag = false;
653
654
            if (!this.isInvisible())
655
            {
656
                flag = this.rand.nextBoolean();
657
            }
658
            else
659
            {
660
                flag = this.rand.nextInt(15) == 0;
661
            }
662
663
            if (flag1)
664
            {
665
                flag &= this.rand.nextInt(5) == 0;
666
            }
667
668
            if (flag && i > 0)
669
            {
670
                double d0 = (double)(i >> 16 & 255) / 255.0D;
671
                double d1 = (double)(i >> 8 & 255) / 255.0D;
672
                double d2 = (double)(i >> 0 & 255) / 255.0D;
673
                this.worldObj.spawnParticle(flag1 ? EnumParticleTypes.SPELL_MOB_AMBIENT : EnumParticleTypes.SPELL_MOB, this.posX + (this.rand.nextDouble() - 0.5D) * (double)this.width, this.posY + this.rand.nextDouble() * (double)this.height, this.posZ + (this.rand.nextDouble() - 0.5D) * (double)this.width, d0, d1, d2, new int[0]);
674
            }
675
        }
676
    }
677
678
    /**
679
     * Clears potion metadata values if the entity has no potion effects. Otherwise, updates potion effect color,
680
     * ambience, and invisibility metadata values
681
     */
682
    protected void updatePotionMetadata()
683
    {
684
        if (this.activePotionsMap.isEmpty())
685
        {
686
            this.resetPotionEffectMetadata();
687
            this.setInvisible(false);
688
        }
689
        else
690
        {
691
            int i = PotionHelper.calcPotionLiquidColor(this.activePotionsMap.values());
692
            this.dataWatcher.updateObject(8, Byte.valueOf((byte)(PotionHelper.getAreAmbient(this.activePotionsMap.values()) ? 1 : 0)));
693
            this.dataWatcher.updateObject(7, Integer.valueOf(i));
694
            this.setInvisible(this.isPotionActive(Potion.invisibility.id));
695
        }
696
    }
697
698
    /**
699
     * Resets the potion effect color and ambience metadata values
700
     */
701
    protected void resetPotionEffectMetadata()
702
    {
703
        this.dataWatcher.updateObject(8, Byte.valueOf((byte)0));
704
        this.dataWatcher.updateObject(7, Integer.valueOf(0));
705
    }
706
707
    public void clearActivePotions()
708
    {
709
        Iterator<Integer> iterator = this.activePotionsMap.keySet().iterator();
710
711
        while (iterator.hasNext())
712
        {
713
            Integer integer = (Integer)iterator.next();
714
            PotionEffect potioneffect = (PotionEffect)this.activePotionsMap.get(integer);
715
716
            if (!this.worldObj.isRemote)
717
            {
718
                iterator.remove();
719
                this.onFinishedPotionEffect(potioneffect);
720
            }
721
        }
722
    }
723
724
    public Collection<PotionEffect> getActivePotionEffects()
725
    {
726
        return this.activePotionsMap.values();
727
    }
728
729
    public boolean isPotionActive(int potionId)
730
    {
731
        return this.activePotionsMap.containsKey(Integer.valueOf(potionId));
732
    }
733
734
    public boolean isPotionActive(Potion potionIn)
735
    {
736
        return this.activePotionsMap.containsKey(Integer.valueOf(potionIn.id));
737
    }
738
739
    /**
740
     * returns the PotionEffect for the supplied Potion if it is active, null otherwise.
741
     */
742
    public PotionEffect getActivePotionEffect(Potion potionIn)
743
    {
744
        return (PotionEffect)this.activePotionsMap.get(Integer.valueOf(potionIn.id));
745
    }
746
747
    /**
748
     * adds a PotionEffect to the entity
749
     */
750
    public void addPotionEffect(PotionEffect potioneffectIn)
751
    {
752
        if (this.isPotionApplicable(potioneffectIn))
753
        {
754
            if (this.activePotionsMap.containsKey(Integer.valueOf(potioneffectIn.getPotionID())))
755
            {
756
                ((PotionEffect)this.activePotionsMap.get(Integer.valueOf(potioneffectIn.getPotionID()))).combine(potioneffectIn);
757
                this.onChangedPotionEffect((PotionEffect)this.activePotionsMap.get(Integer.valueOf(potioneffectIn.getPotionID())), true);
758
            }
759
            else
760
            {
761
                this.activePotionsMap.put(Integer.valueOf(potioneffectIn.getPotionID()), potioneffectIn);
762
                this.onNewPotionEffect(potioneffectIn);
763
            }
764
        }
765
    }
766
767
    public boolean isPotionApplicable(PotionEffect potioneffectIn)
768
    {
769
        if (this.getCreatureAttribute() == EnumCreatureAttribute.UNDEAD)
770
        {
771
            int i = potioneffectIn.getPotionID();
772
773
            if (i == Potion.regeneration.id || i == Potion.poison.id)
774
            {
775
                return false;
776
            }
777
        }
778
779
        return true;
780
    }
781
782
    /**
783
     * Returns true if this entity is undead.
784
     */
785
    public boolean isEntityUndead()
786
    {
787
        return this.getCreatureAttribute() == EnumCreatureAttribute.UNDEAD;
788
    }
789
790
    /**
791
     * Remove the speified potion effect from this entity.
792
     */
793
    public void removePotionEffectClient(int potionId)
794
    {
795
        this.activePotionsMap.remove(Integer.valueOf(potionId));
796
    }
797
798
    /**
799
     * Remove the specified potion effect from this entity.
800
     */
801
    public void removePotionEffect(int potionId)
802
    {
803
        PotionEffect potioneffect = (PotionEffect)this.activePotionsMap.remove(Integer.valueOf(potionId));
804
805
        if (potioneffect != null)
806
        {
807
            this.onFinishedPotionEffect(potioneffect);
808
        }
809
    }
810
811
    protected void onNewPotionEffect(PotionEffect id)
812
    {
813
        this.potionsNeedUpdate = true;
814
815
        if (!this.worldObj.isRemote)
816
        {
817
            Potion.potionTypes[id.getPotionID()].applyAttributesModifiersToEntity(this, this.getAttributeMap(), id.getAmplifier());
818
        }
819
    }
820
821
    protected void onChangedPotionEffect(PotionEffect id, boolean p_70695_2_)
822
    {
823
        this.potionsNeedUpdate = true;
824
825
        if (p_70695_2_ && !this.worldObj.isRemote)
826
        {
827
            Potion.potionTypes[id.getPotionID()].removeAttributesModifiersFromEntity(this, this.getAttributeMap(), id.getAmplifier());
828
            Potion.potionTypes[id.getPotionID()].applyAttributesModifiersToEntity(this, this.getAttributeMap(), id.getAmplifier());
829
        }
830
    }
831
832
    protected void onFinishedPotionEffect(PotionEffect p_70688_1_)
833
    {
834
        this.potionsNeedUpdate = true;
835
836
        if (!this.worldObj.isRemote)
837
        {
838
            Potion.potionTypes[p_70688_1_.getPotionID()].removeAttributesModifiersFromEntity(this, this.getAttributeMap(), p_70688_1_.getAmplifier());
839
        }
840
    }
841
842
    /**
843
     * Heal living entity (param: amount of half-hearts)
844
     */
845
    public void heal(float healAmount)
846
    {
847
        float f = this.getHealth();
848
849
        if (f > 0.0F)
850
        {
851
            this.setHealth(f + healAmount);
852
        }
853
    }
854
855
    public final float getHealth()
856
    {
857
        return this.dataWatcher.getWatchableObjectFloat(6);
858
    }
859
860
    public void setHealth(float health)
861
    {
862
        this.dataWatcher.updateObject(6, Float.valueOf(MathHelper.clamp_float(health, 0.0F, this.getMaxHealth())));
863
    }
864
865
    /**
866
     * Called when the entity is attacked.
867
     */
868
    public boolean attackEntityFrom(DamageSource source, float amount)
869
    {
870
        if (this.isEntityInvulnerable(source))
871
        {
872
            return false;
873
        }
874
        else if (this.worldObj.isRemote)
875
        {
876
            return false;
877
        }
878
        else
879
        {
880
            this.entityAge = 0;
881
882
            if (this.getHealth() <= 0.0F)
883
            {
884
                return false;
885
            }
886
            else if (source.isFireDamage() && this.isPotionActive(Potion.fireResistance))
887
            {
888
                return false;
889
            }
890
            else
891
            {
892
                if ((source == DamageSource.anvil || source == DamageSource.fallingBlock) && this.getEquipmentInSlot(4) != null)
893
                {
894
                    this.getEquipmentInSlot(4).damageItem((int)(amount * 4.0F + this.rand.nextFloat() * amount * 2.0F), this);
895
                    amount *= 0.75F;
896
                }
897
898
                this.limbSwingAmount = 1.5F;
899
                boolean flag = true;
900
901
                if ((float)this.hurtResistantTime > (float)this.maxHurtResistantTime / 2.0F)
902
                {
903
                    if (amount <= this.lastDamage)
904
                    {
905
                        return false;
906
                    }
907
908
                    this.damageEntity(source, amount - this.lastDamage);
909
                    this.lastDamage = amount;
910
                    flag = false;
911
                }
912
                else
913
                {
914
                    this.lastDamage = amount;
915
                    this.hurtResistantTime = this.maxHurtResistantTime;
916
                    this.damageEntity(source, amount);
917
                    this.hurtTime = this.maxHurtTime = 10;
918
                }
919
920
                this.attackedAtYaw = 0.0F;
921
                Entity entity = source.getEntity();
922
923
                if (entity != null)
924
                {
925
                    if (entity instanceof EntityLivingBase)
926
                    {
927
                        this.setRevengeTarget((EntityLivingBase)entity);
928
                    }
929
930
                    if (entity instanceof EntityPlayer)
931
                    {
932
                        this.recentlyHit = 100;
933
                        this.attackingPlayer = (EntityPlayer)entity;
934
                    }
935
                    else if (entity instanceof EntityWolf)
936
                    {
937
                        EntityWolf entitywolf = (EntityWolf)entity;
938
939
                        if (entitywolf.isTamed())
940
                        {
941
                            this.recentlyHit = 100;
942
                            this.attackingPlayer = null;
943
                        }
944
                    }
945
                }
946
947
                if (flag)
948
                {
949
                    this.worldObj.setEntityState(this, (byte)2);
950
951
                    if (source != DamageSource.drown)
952
                    {
953
                        this.setBeenAttacked();
954
                    }
955
956
                    if (entity != null)
957
                    {
958
                        double d1 = entity.posX - this.posX;
959
                        double d0;
960
961
                        for (d0 = entity.posZ - this.posZ; d1 * d1 + d0 * d0 < 1.0E-4D; d0 = (Math.random() - Math.random()) * 0.01D)
962
                        {
963
                            d1 = (Math.random() - Math.random()) * 0.01D;
964
                        }
965
966
                        this.attackedAtYaw = (float)(MathHelper.func_181159_b(d0, d1) * 180.0D / Math.PI - (double)this.rotationYaw);
967
                        this.knockBack(entity, amount, d1, d0);
968
                    }
969
                    else
970
                    {
971
                        this.attackedAtYaw = (float)((int)(Math.random() * 2.0D) * 180);
972
                    }
973
                }
974
975
                if (this.getHealth() <= 0.0F)
976
                {
977
                    String s = this.getDeathSound();
978
979
                    if (flag && s != null)
980
                    {
981
                        this.playSound(s, this.getSoundVolume(), this.getSoundPitch());
982
                    }
983
984
                    this.onDeath(source);
985
                }
986
                else
987
                {
988
                    String s1 = this.getHurtSound();
989
990
                    if (flag && s1 != null)
991
                    {
992
                        this.playSound(s1, this.getSoundVolume(), this.getSoundPitch());
993
                    }
994
                }
995
996
                return true;
997
            }
998
        }
999
    }
1000
1001
    /**
1002
     * Renders broken item particles using the given ItemStack
1003
     */
1004
    public void renderBrokenItemStack(ItemStack stack)
1005
    {
1006
        this.playSound("random.break", 0.8F, 0.8F + this.worldObj.rand.nextFloat() * 0.4F);
1007
1008
        for (int i = 0; i < 5; ++i)
1009
        {
1010
            Vec3 vec3 = new Vec3(((double)this.rand.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D);
1011
            vec3 = vec3.rotatePitch(-this.rotationPitch * (float)Math.PI / 180.0F);
1012
            vec3 = vec3.rotateYaw(-this.rotationYaw * (float)Math.PI / 180.0F);
1013
            double d0 = (double)(-this.rand.nextFloat()) * 0.6D - 0.3D;
1014
            Vec3 vec31 = new Vec3(((double)this.rand.nextFloat() - 0.5D) * 0.3D, d0, 0.6D);
1015
            vec31 = vec31.rotatePitch(-this.rotationPitch * (float)Math.PI / 180.0F);
1016
            vec31 = vec31.rotateYaw(-this.rotationYaw * (float)Math.PI / 180.0F);
1017
            vec31 = vec31.addVector(this.posX, this.posY + (double)this.getEyeHeight(), this.posZ);
1018
            this.worldObj.spawnParticle(EnumParticleTypes.ITEM_CRACK, vec31.xCoord, vec31.yCoord, vec31.zCoord, vec3.xCoord, vec3.yCoord + 0.05D, vec3.zCoord, new int[] {Item.getIdFromItem(stack.getItem())});
1019
        }
1020
    }
1021
1022
    /**
1023
     * Called when the mob's health reaches 0.
1024
     */
1025
    public void onDeath(DamageSource cause)
1026
    {
1027
        Entity entity = cause.getEntity();
1028
        EntityLivingBase entitylivingbase = this.func_94060_bK();
1029
1030
        if (this.scoreValue >= 0 && entitylivingbase != null)
1031
        {
1032
            entitylivingbase.addToPlayerScore(this, this.scoreValue);
1033
        }
1034
1035
        if (entity != null)
1036
        {
1037
            entity.onKillEntity(this);
1038
        }
1039
1040
        this.dead = true;
1041
        this.getCombatTracker().reset();
1042
1043
        if (!this.worldObj.isRemote)
1044
        {
1045
            int i = 0;
1046
1047
            if (entity instanceof EntityPlayer)
1048
            {
1049
                i = EnchantmentHelper.getLootingModifier((EntityLivingBase)entity);
1050
            }
1051
1052
            if (this.canDropLoot() && this.worldObj.getGameRules().getBoolean("doMobLoot"))
1053
            {
1054
                this.dropFewItems(this.recentlyHit > 0, i);
1055
                this.dropEquipment(this.recentlyHit > 0, i);
1056
1057
                if (this.recentlyHit > 0 && this.rand.nextFloat() < 0.025F + (float)i * 0.01F)
1058
                {
1059
                    this.addRandomDrop();
1060
                }
1061
            }
1062
        }
1063
1064
        this.worldObj.setEntityState(this, (byte)3);
1065
    }
1066
1067
    /**
1068
     * Drop the equipment for this entity.
1069
     */
1070
    protected void dropEquipment(boolean p_82160_1_, int p_82160_2_)
1071
    {
1072
    }
1073
1074
    /**
1075
     * knocks back this entity
1076
     */
1077
    public void knockBack(Entity entityIn, float p_70653_2_, double p_70653_3_, double p_70653_5_)
1078
    {
1079
    	
1080
        if (this.rand.nextDouble() >= this.getEntityAttribute(SharedMonsterAttributes.knockbackResistance).getAttributeValue())
1081
        {
1082
            this.isAirBorne = true;
1083
            float f = MathHelper.sqrt_double(p_70653_3_ * p_70653_3_ + p_70653_5_ * p_70653_5_);
1084
            float f1 = 0.4F;
1085
            this.motionX /= 2.0D;
1086
            this.motionY /= 2.0D;
1087
            this.motionZ /= 2.0D;
1088
            this.motionX -= p_70653_3_ / (double)f * (double)f1;
1089
            this.motionY += (double)f1;
1090
            this.motionZ -= p_70653_5_ / (double)f * (double)f1;
1091
1092
            if (this.motionY > 0.4000000059604645D)
1093
            {
1094
                this.motionY = 0.4000000059604645D;
1095
            }
1096
        }
1097
    }
1098
1099
    /**
1100
     * Returns the sound this mob makes when it is hurt.
1101
     */
1102
    protected String getHurtSound()
1103
    {
1104
        return "game.neutral.hurt";
1105
    }
1106
1107
    /**
1108
     * Returns the sound this mob makes on death.
1109
     */
1110
    protected String getDeathSound()
1111
    {
1112
        return "game.neutral.die";
1113
    }
1114
1115
    /**
1116
     * Causes this Entity to drop a random item.
1117
     */
1118
    protected void addRandomDrop()
1119
    {
1120
    }
1121
1122
    /**
1123
     * Drop 0-2 items of this living's type
1124
     */
1125
    protected void dropFewItems(boolean p_70628_1_, int p_70628_2_)
1126
    {
1127
    }
1128
1129
    /**
1130
     * returns true if this entity is by a ladder, false otherwise
1131
     */
1132
    public boolean isOnLadder()
1133
    {
1134
        int i = MathHelper.floor_double(this.posX);
1135
        int j = MathHelper.floor_double(this.getEntityBoundingBox().minY);
1136
        int k = MathHelper.floor_double(this.posZ);
1137
        Block block = this.worldObj.getBlockState(new BlockPos(i, j, k)).getBlock();
1138
        EventOnLadder e = new EventOnLadder();
1139
        e.onLadder = (block == Blocks.ladder || block == Blocks.vine) && (!(this instanceof EntityPlayer) || !((EntityPlayer)this).isSpectator());
1140
        e.setType(EventType.POST);
1141
        SpicyClient.onEvent(e);
1142
        if (e.canceled) {
1143
        	
1144
        }else {
1145
        	if (e.onLadder == (block == Blocks.ladder || block == Blocks.vine) && (!(this instanceof EntityPlayer) || !((EntityPlayer)this).isSpectator())) {
1146
        		return (block == Blocks.ladder || block == Blocks.vine) && (!(this instanceof EntityPlayer) || !((EntityPlayer)this).isSpectator());
1147
        	}else {
1148
        		return e.onLadder;
1149
        	}
1150
        }
1151
		return false;
1152
    }
1153
1154
    /**
1155
     * Checks whether target entity is alive.
1156
     */
1157
    public boolean isEntityAlive()
1158
    {
1159
        return !this.isDead && this.getHealth() > 0.0F;
1160
    }
1161
1162
    public void fall(float distance, float damageMultiplier)
1163
    {
1164
        super.fall(distance, damageMultiplier);
1165
        PotionEffect potioneffect = this.getActivePotionEffect(Potion.jump);
1166
        float f = potioneffect != null ? (float)(potioneffect.getAmplifier() + 1) : 0.0F;
1167
        int i = MathHelper.ceiling_float_int((distance - 3.0F - f) * damageMultiplier);
1168
1169
        if (i > 0)
1170
        {
1171
            this.playSound(this.getFallSoundString(i), 1.0F, 1.0F);
1172
            this.attackEntityFrom(DamageSource.fall, (float)i);
1173
            int j = MathHelper.floor_double(this.posX);
1174
            int k = MathHelper.floor_double(this.posY - 0.20000000298023224D);
1175
            int l = MathHelper.floor_double(this.posZ);
1176
            Block block = this.worldObj.getBlockState(new BlockPos(j, k, l)).getBlock();
1177
1178
            if (block.getMaterial() != Material.air)
1179
            {
1180
                Block.SoundType block$soundtype = block.stepSound;
1181
                this.playSound(block$soundtype.getStepSound(), block$soundtype.getVolume() * 0.5F, block$soundtype.getFrequency() * 0.75F);
1182
            }
1183
        }
1184
    }
1185
1186
    protected String getFallSoundString(int damageValue)
1187
    {
1188
        return damageValue > 4 ? "game.neutral.hurt.fall.big" : "game.neutral.hurt.fall.small";
1189
    }
1190
1191
    /**
1192
     * Setups the entity to do the hurt animation. Only used by packets in multiplayer.
1193
     */
1194
    public void performHurtAnimation()
1195
    {
1196
        this.hurtTime = this.maxHurtTime = 10;
1197
        this.attackedAtYaw = 0.0F;
1198
    }
1199
1200
    /**
1201
     * Returns the current armor value as determined by a call to InventoryPlayer.getTotalArmorValue
1202
     */
1203
    public int getTotalArmorValue()
1204
    {
1205
        int i = 0;
1206
1207
        for (ItemStack itemstack : this.getInventory())
1208
        {
1209
            if (itemstack != null && itemstack.getItem() instanceof ItemArmor)
1210
            {
1211
                int j = ((ItemArmor)itemstack.getItem()).damageReduceAmount;
1212
                i += j;
1213
            }
1214
        }
1215
1216
        return i;
1217
    }
1218
1219
    protected void damageArmor(float p_70675_1_)
1220
    {
1221
    }
1222
1223
    /**
1224
     * Reduces damage, depending on armor
1225
     */
1226
    protected float applyArmorCalculations(DamageSource source, float damage)
1227
    {
1228
        if (!source.isUnblockable())
1229
        {
1230
            int i = 25 - this.getTotalArmorValue();
1231
            float f = damage * (float)i;
1232
            this.damageArmor(damage);
1233
            damage = f / 25.0F;
1234
        }
1235
1236
        return damage;
1237
    }
1238
1239
    /**
1240
     * Reduces damage, depending on potions
1241
     */
1242
    protected float applyPotionDamageCalculations(DamageSource source, float damage)
1243
    {
1244
        if (source.isDamageAbsolute())
1245
        {
1246
            return damage;
1247
        }
1248
        else
1249
        {
1250
            if (this.isPotionActive(Potion.resistance) && source != DamageSource.outOfWorld)
1251
            {
1252
                int i = (this.getActivePotionEffect(Potion.resistance).getAmplifier() + 1) * 5;
1253
                int j = 25 - i;
1254
                float f = damage * (float)j;
1255
                damage = f / 25.0F;
1256
            }
1257
1258
            if (damage <= 0.0F)
1259
            {
1260
                return 0.0F;
1261
            }
1262
            else
1263
            {
1264
                int k = EnchantmentHelper.getEnchantmentModifierDamage(this.getInventory(), source);
1265
1266
                if (k > 20)
1267
                {
1268
                    k = 20;
1269
                }
1270
1271
                if (k > 0 && k <= 20)
1272
                {
1273
                    int l = 25 - k;
1274
                    float f1 = damage * (float)l;
1275
                    damage = f1 / 25.0F;
1276
                }
1277
1278
                return damage;
1279
            }
1280
        }
1281
    }
1282
1283
    /**
1284
     * Deals damage to the entity. If its a EntityPlayer then will take damage from the armor first and then health
1285
     * second with the reduced value. Args: damageAmount
1286
     */
1287
    protected void damageEntity(DamageSource damageSrc, float damageAmount)
1288
    {
1289
        if (!this.isEntityInvulnerable(damageSrc))
1290
        {
1291
            damageAmount = this.applyArmorCalculations(damageSrc, damageAmount);
1292
            damageAmount = this.applyPotionDamageCalculations(damageSrc, damageAmount);
1293
            float f = damageAmount;
1294
            damageAmount = Math.max(damageAmount - this.getAbsorptionAmount(), 0.0F);
1295
            this.setAbsorptionAmount(this.getAbsorptionAmount() - (f - damageAmount));
1296
1297
            if (damageAmount != 0.0F)
1298
            {
1299
                float f1 = this.getHealth();
1300
                this.setHealth(f1 - damageAmount);
1301
                this.getCombatTracker().trackDamage(damageSrc, f1, damageAmount);
1302
                this.setAbsorptionAmount(this.getAbsorptionAmount() - damageAmount);
1303
            }
1304
        }
1305
    }
1306
1307
    public CombatTracker getCombatTracker()
1308
    {
1309
        return this._combatTracker;
1310
    }
1311
1312
    public EntityLivingBase func_94060_bK()
1313
    {
1314
        return (EntityLivingBase)(this._combatTracker.func_94550_c() != null ? this._combatTracker.func_94550_c() : (this.attackingPlayer != null ? this.attackingPlayer : (this.entityLivingToAttack != null ? this.entityLivingToAttack : null)));
1315
    }
1316
1317
    public final float getMaxHealth()
1318
    {
1319
        return (float)this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getAttributeValue();
1320
    }
1321
1322
    /**
1323
     * counts the amount of arrows stuck in the entity. getting hit by arrows increases this, used in rendering
1324
     */
1325
    public final int getArrowCountInEntity()
1326
    {
1327
        return this.dataWatcher.getWatchableObjectByte(9);
1328
    }
1329
1330
    /**
1331
     * sets the amount of arrows stuck in the entity. used for rendering those
1332
     */
1333
    public final void setArrowCountInEntity(int count)
1334
    {
1335
        this.dataWatcher.updateObject(9, Byte.valueOf((byte)count));
1336
    }
1337
1338
    /**
1339
     * Returns an integer indicating the end point of the swing animation, used by {@link #swingProgress} to provide a
1340
     * progress indicator. Takes dig speed enchantments into account.
1341
     */
1342
    private int getArmSwingAnimationEnd()
1343
    {
1344
        return this.isPotionActive(Potion.digSpeed) ? 6 - (1 + this.getActivePotionEffect(Potion.digSpeed).getAmplifier()) * 1 : (this.isPotionActive(Potion.digSlowdown) ? 6 + (1 + this.getActivePotionEffect(Potion.digSlowdown).getAmplifier()) * 2 : 6);
1345
    }
1346
1347
    /**
1348
     * Swings the item the player is holding.
1349
     */
1350
    public void swingItem()
1351
    {
1352
        if (!this.isSwingInProgress || this.swingProgressInt >= this.getArmSwingAnimationEnd() / 2 || this.swingProgressInt < 0)
1353
        {
1354
            this.swingProgressInt = -1;
1355
            this.isSwingInProgress = true;
1356
1357
            if (this.worldObj instanceof WorldServer)
1358
            {
1359
                ((WorldServer)this.worldObj).getEntityTracker().sendToAllTrackingEntity(this, new S0BPacketAnimation(this, 0));
1360
            }
1361
        }
1362
    }
1363
1364
    public void handleStatusUpdate(byte id)
1365
    {
1366
        if (id == 2)
1367
        {
1368
            this.limbSwingAmount = 1.5F;
1369
            this.hurtResistantTime = this.maxHurtResistantTime;
1370
            this.hurtTime = this.maxHurtTime = 10;
1371
            this.attackedAtYaw = 0.0F;
1372
            String s = this.getHurtSound();
1373
1374
            if (s != null)
1375
            {
1376
                this.playSound(this.getHurtSound(), this.getSoundVolume(), (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F);
1377
            }
1378
1379
            this.attackEntityFrom(DamageSource.generic, 0.0F);
1380
        }
1381
        else if (id == 3)
1382
        {
1383
            String s1 = this.getDeathSound();
1384
1385
            if (s1 != null)
1386
            {
1387
                this.playSound(this.getDeathSound(), this.getSoundVolume(), (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F);
1388
            }
1389
1390
            this.setHealth(0.0F);
1391
            this.onDeath(DamageSource.generic);
1392
        }
1393
        else
1394
        {
1395
            super.handleStatusUpdate(id);
1396
        }
1397
    }
1398
1399
    /**
1400
     * sets the dead flag. Used when you fall off the bottom of the world.
1401
     */
1402
    protected void kill()
1403
    {
1404
        this.attackEntityFrom(DamageSource.outOfWorld, 4.0F);
1405
    }
1406
1407
    /**
1408
     * Updates the arm swing progress counters and animation progress
1409
     */
1410
    protected void updateArmSwingProgress()
1411
    {
1412
        int i = this.getArmSwingAnimationEnd();
1413
1414
        if (this.isSwingInProgress)
1415
        {
1416
            ++this.swingProgressInt;
1417
1418
            if (this.swingProgressInt >= i)
1419
            {
1420
                this.swingProgressInt = 0;
1421
                this.isSwingInProgress = false;
1422
            }
1423
        }
1424
        else
1425
        {
1426
            this.swingProgressInt = 0;
1427
        }
1428
1429
        this.swingProgress = (float)this.swingProgressInt / (float)i;
1430
    }
1431
1432
    public IAttributeInstance getEntityAttribute(IAttribute attribute)
1433
    {
1434
        return this.getAttributeMap().getAttributeInstance(attribute);
1435
    }
1436
1437
    public BaseAttributeMap getAttributeMap()
1438
    {
1439
        if (this.attributeMap == null)
1440
        {
1441
            this.attributeMap = new ServersideAttributeMap();
1442
        }
1443
1444
        return this.attributeMap;
1445
    }
1446
1447
    /**
1448
     * Get this Entity's EnumCreatureAttribute
1449
     */
1450
    public EnumCreatureAttribute getCreatureAttribute()
1451
    {
1452
        return EnumCreatureAttribute.UNDEFINED;
1453
    }
1454
1455
    /**
1456
     * Returns the item that this EntityLiving is holding, if any.
1457
     */
1458
    public abstract ItemStack getHeldItem();
1459
1460
    /**
1461
     * 0: Tool in Hand; 1-4: Armor
1462
     */
1463
    public abstract ItemStack getEquipmentInSlot(int slotIn);
1464
1465
    public abstract ItemStack getCurrentArmor(int slotIn);
1466
1467
    /**
1468
     * Sets the held item, or an armor slot. Slot 0 is held item. Slot 1-4 is armor. Params: Item, slot
1469
     */
1470
    public abstract void setCurrentItemOrArmor(int slotIn, ItemStack stack);
1471
1472
    /**
1473
     * Set sprinting switch for Entity.
1474
     */
1475
    public void setSprinting(boolean sprinting)
1476
    {
1477
        super.setSprinting(sprinting);
1478
        IAttributeInstance iattributeinstance = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed);
1479
1480
        if (iattributeinstance.getModifier(sprintingSpeedBoostModifierUUID) != null)
1481
        {
1482
            iattributeinstance.removeModifier(sprintingSpeedBoostModifier);
1483
        }
1484
1485
        if (sprinting)
1486
        {
1487
            iattributeinstance.applyModifier(sprintingSpeedBoostModifier);
1488
        }
1489
    }
1490
1491
    /**
1492
     * returns the inventory of this entity (only used in EntityPlayerMP it seems)
1493
     */
1494
    public abstract ItemStack[] getInventory();
1495
1496
    /**
1497
     * Returns the volume for the sounds this mob makes.
1498
     */
1499
    protected float getSoundVolume()
1500
    {
1501
        return 1.0F;
1502
    }
1503
1504
    /**
1505
     * Gets the pitch of living sounds in living entities.
1506
     */
1507
    protected float getSoundPitch()
1508
    {
1509
        return this.isChild() ? (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.5F : (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F;
1510
    }
1511
1512
    /**
1513
     * Dead and sleeping entities cannot move
1514
     */
1515
    protected boolean isMovementBlocked()
1516
    {
1517
        return this.getHealth() <= 0.0F;
1518
    }
1519
1520
    /**
1521
     * Moves the entity to a position out of the way of its mount.
1522
     */
1523
    public void dismountEntity(Entity p_110145_1_)
1524
    {
1525
        double d0 = p_110145_1_.posX;
1526
        double d1 = p_110145_1_.getEntityBoundingBox().minY + (double)p_110145_1_.height;
1527
        double d2 = p_110145_1_.posZ;
1528
        int i = 1;
1529
1530
        for (int j = -i; j <= i; ++j)
1531
        {
1532
            for (int k = -i; k < i; ++k)
1533
            {
1534
                if (j != 0 || k != 0)
1535
                {
1536
                    int l = (int)(this.posX + (double)j);
1537
                    int i1 = (int)(this.posZ + (double)k);
1538
                    AxisAlignedBB axisalignedbb = this.getEntityBoundingBox().offset((double)j, 1.0D, (double)k);
1539
1540
                    if (this.worldObj.func_147461_a(axisalignedbb).isEmpty())
1541
                    {
1542
                        if (World.doesBlockHaveSolidTopSurface(this.worldObj, new BlockPos(l, (int)this.posY, i1)))
1543
                        {
1544
                            this.setPositionAndUpdate(this.posX + (double)j, this.posY + 1.0D, this.posZ + (double)k);
1545
                            return;
1546
                        }
1547
1548
                        if (World.doesBlockHaveSolidTopSurface(this.worldObj, new BlockPos(l, (int)this.posY - 1, i1)) || this.worldObj.getBlockState(new BlockPos(l, (int)this.posY - 1, i1)).getBlock().getMaterial() == Material.water)
1549
                        {
1550
                            d0 = this.posX + (double)j;
1551
                            d1 = this.posY + 1.0D;
1552
                            d2 = this.posZ + (double)k;
1553
                        }
1554
                    }
1555
                }
1556
            }
1557
        }
1558
1559
        this.setPositionAndUpdate(d0, d1, d2);
1560
    }
1561
1562
    public boolean getAlwaysRenderNameTagForRender()
1563
    {
1564
        return false;
1565
    }
1566
1567
    public float getJumpUpwardsMotion()
1568
    {
1569
        return 0.42F;
1570
    }
1571
1572
    /**
1573
     * Causes this entity to do an upwards motion (jumping).
1574
     */
1575
    protected void jump()
1576
    {
1577
        this.motionY = (double)this.getJumpUpwardsMotion();
1578
1579
        if (this.isPotionActive(Potion.jump))
1580
        {
1581
            this.motionY += (double)((float)(this.getActivePotionEffect(Potion.jump).getAmplifier() + 1) * 0.1F);
1582
        }
1583
1584
        if (this.isSprinting())
1585
        {
1586
            float f = this.rotationYaw * 0.017453292F;
1587
            this.motionX -= (double)(MathHelper.sin(f) * 0.2F);
1588
            this.motionZ += (double)(MathHelper.cos(f) * 0.2F);
1589
        }
1590
1591
        this.isAirBorne = true;
1592
    }
1593
1594
    /**
1595
     * main AI tick function, replaces updateEntityActionState
1596
     */
1597
    protected void updateAITick()
1598
    {
1599
        this.motionY += 0.03999999910593033D;
1600
    }
1601
1602
    protected void handleJumpLava()
1603
    {
1604
        this.motionY += 0.03999999910593033D;
1605
    }
1606
1607
    /**
1608
     * Moves the entity based on the specified heading.  Args: strafe, forward
1609
     */
1610
    public void moveEntityWithHeading(float strafe, float forward)
1611
    {
1612
        if (this.isServerWorld())
1613
        {
1614
            if (!this.isInWater() || this instanceof EntityPlayer && ((EntityPlayer)this).capabilities.isFlying)
1615
            {
1616
                if (!this.isInLava() || this instanceof EntityPlayer && ((EntityPlayer)this).capabilities.isFlying)
1617
                {
1618
                    float f4 = 0.91F;
1619
1620
                    if (this.onGround)
1621
                    {
1622
                        f4 = this.worldObj.getBlockState(new BlockPos(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.getEntityBoundingBox().minY) - 1, MathHelper.floor_double(this.posZ))).getBlock().slipperiness * 0.91F;
1623
                    }
1624
1625
                    float f = 0.16277136F / (f4 * f4 * f4);
1626
                    float f5;
1627
1628
                    if (this.onGround)
1629
                    {
1630
                        f5 = this.getAIMoveSpeed() * f;
1631
                    }
1632
                    else
1633
                    {
1634
                        f5 = this.jumpMovementFactor;
1635
                    }
1636
1637
                    this.moveFlying(strafe, forward, f5);
1638
                    f4 = 0.91F;
1639
1640
                    if (this.onGround)
1641
                    {
1642
                        f4 = this.worldObj.getBlockState(new BlockPos(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.getEntityBoundingBox().minY) - 1, MathHelper.floor_double(this.posZ))).getBlock().slipperiness * 0.91F;
1643
                    }
1644
1645
                    if (this.isOnLadder())
1646
                    {
1647
                        float f6 = 0.15F;
1648
                        this.motionX = MathHelper.clamp_double(this.motionX, (double)(-f6), (double)f6);
1649
                        this.motionZ = MathHelper.clamp_double(this.motionZ, (double)(-f6), (double)f6);
1650
                        this.fallDistance = 0.0F;
1651
1652
                        if (this.motionY < -0.15D)
1653
                        {
1654
                            this.motionY = -0.15D;
1655
                        }
1656
1657
                        boolean flag = this.isSneaking() && this instanceof EntityPlayer;
1658
1659
                        if (flag && this.motionY < 0.0D)
1660
                        {
1661
                            this.motionY = 0.0D;
1662
                        }
1663
                    }
1664
1665
                    this.moveEntity(this.motionX, this.motionY, this.motionZ);
1666
1667
                    if (this.isCollidedHorizontally && this.isOnLadder())
1668
                    {
1669
                        this.motionY = 0.2D;
1670
                    }
1671
1672
                    if (this.worldObj.isRemote && (!this.worldObj.isBlockLoaded(new BlockPos((int)this.posX, 0, (int)this.posZ)) || !this.worldObj.getChunkFromBlockCoords(new BlockPos((int)this.posX, 0, (int)this.posZ)).isLoaded()))
1673
                    {
1674
                        if (this.posY > 0.0D)
1675
                        {
1676
                            this.motionY = -0.1D;
1677
                        }
1678
                        else
1679
                        {
1680
                            this.motionY = 0.0D;
1681
                        }
1682
                    }
1683
                    else
1684
                    {
1685
                        this.motionY -= 0.08D;
1686
                    }
1687
1688
                    this.motionY *= 0.9800000190734863D;
1689
                    this.motionX *= (double)f4;
1690
                    this.motionZ *= (double)f4;
1691
                }
1692
                else
1693
                {
1694
                    double d1 = this.posY;
1695
                    this.moveFlying(strafe, forward, 0.02F);
1696
                    this.moveEntity(this.motionX, this.motionY, this.motionZ);
1697
                    this.motionX *= 0.5D;
1698
                    this.motionY *= 0.5D;
1699
                    this.motionZ *= 0.5D;
1700
                    this.motionY -= 0.02D;
1701
1702
                    if (this.isCollidedHorizontally && this.isOffsetPositionInLiquid(this.motionX, this.motionY + 0.6000000238418579D - this.posY + d1, this.motionZ))
1703
                    {
1704
                        this.motionY = 0.30000001192092896D;
1705
                    }
1706
                }
1707
            }
1708
            else
1709
            {
1710
                double d0 = this.posY;
1711
                float f1 = 0.8F;
1712
                float f2 = 0.02F;
1713
                float f3 = (float)EnchantmentHelper.getDepthStriderModifier(this);
1714
1715
                if (f3 > 3.0F)
1716
                {
1717
                    f3 = 3.0F;
1718
                }
1719
1720
                if (!this.onGround)
1721
                {
1722
                    f3 *= 0.5F;
1723
                }
1724
1725
                if (f3 > 0.0F)
1726
                {
1727
                    f1 += (0.54600006F - f1) * f3 / 3.0F;
1728
                    f2 += (this.getAIMoveSpeed() * 1.0F - f2) * f3 / 3.0F;
1729
                }
1730
1731
                this.moveFlying(strafe, forward, f2);
1732
                this.moveEntity(this.motionX, this.motionY, this.motionZ);
1733
                this.motionX *= (double)f1;
1734
                this.motionY *= 0.800000011920929D;
1735
                this.motionZ *= (double)f1;
1736
                this.motionY -= 0.02D;
1737
1738
                if (this.isCollidedHorizontally && this.isOffsetPositionInLiquid(this.motionX, this.motionY + 0.6000000238418579D - this.posY + d0, this.motionZ))
1739
                {
1740
                    this.motionY = 0.30000001192092896D;
1741
                }
1742
            }
1743
        }
1744
1745
        this.prevLimbSwingAmount = this.limbSwingAmount;
1746
        double d2 = this.posX - this.prevPosX;
1747
        double d3 = this.posZ - this.prevPosZ;
1748
        float f7 = MathHelper.sqrt_double(d2 * d2 + d3 * d3) * 4.0F;
1749
1750
        if (f7 > 1.0F)
1751
        {
1752
            f7 = 1.0F;
1753
        }
1754
1755
        this.limbSwingAmount += (f7 - this.limbSwingAmount) * 0.4F;
1756
        this.limbSwing += this.limbSwingAmount;
1757
    }
1758
1759
    /**
1760
     * the movespeed used for the new AI system
1761
     */
1762
    public float getAIMoveSpeed()
1763
    {
1764
        return this.landMovementFactor;
1765
    }
1766
1767
    /**
1768
     * set the movespeed used for the new AI system
1769
     */
1770
    public void setAIMoveSpeed(float speedIn)
1771
    {
1772
        this.landMovementFactor = speedIn;
1773
    }
1774
1775
    public boolean attackEntityAsMob(Entity entityIn)
1776
    {
1777
        this.setLastAttacker(entityIn);
1778
        return false;
1779
    }
1780
1781
    /**
1782
     * Returns whether player is sleeping or not
1783
     */
1784
    public boolean isPlayerSleeping()
1785
    {
1786
        return false;
1787
    }
1788
1789
    /**
1790
     * Called to update the entity's position/logic.
1791
     */
1792
    public void onUpdate()
1793
    {
1794
        super.onUpdate();
1795
1796
        if (!this.worldObj.isRemote)
1797
        {
1798
            int i = this.getArrowCountInEntity();
1799
1800
            if (i > 0)
1801
            {
1802
                if (this.arrowHitTimer <= 0)
1803
                {
1804
                    this.arrowHitTimer = 20 * (30 - i);
1805
                }
1806
1807
                --this.arrowHitTimer;
1808
1809
                if (this.arrowHitTimer <= 0)
1810
                {
1811
                    this.setArrowCountInEntity(i - 1);
1812
                }
1813
            }
1814
1815
            for (int j = 0; j < 5; ++j)
1816
            {
1817
                ItemStack itemstack = this.previousEquipment[j];
1818
                ItemStack itemstack1 = this.getEquipmentInSlot(j);
1819
1820
                if (!ItemStack.areItemStacksEqual(itemstack1, itemstack))
1821
                {
1822
                    ((WorldServer)this.worldObj).getEntityTracker().sendToAllTrackingEntity(this, new S04PacketEntityEquipment(this.getEntityId(), j, itemstack1));
1823
1824
                    if (itemstack != null)
1825
                    {
1826
                        this.attributeMap.removeAttributeModifiers(itemstack.getAttributeModifiers());
1827
                    }
1828
1829
                    if (itemstack1 != null)
1830
                    {
1831
                        this.attributeMap.applyAttributeModifiers(itemstack1.getAttributeModifiers());
1832
                    }
1833
1834
                    this.previousEquipment[j] = itemstack1 == null ? null : itemstack1.copy();
1835
                }
1836
            }
1837
1838
            if (this.ticksExisted % 20 == 0)
1839
            {
1840
                this.getCombatTracker().reset();
1841
            }
1842
        }
1843
1844
        this.onLivingUpdate();
1845
        double d0 = this.posX - this.prevPosX;
1846
        double d1 = this.posZ - this.prevPosZ;
1847
        float f = (float)(d0 * d0 + d1 * d1);
1848
        float f1 = this.renderYawOffset;
1849
        float f2 = 0.0F;
1850
        this.prevOnGroundSpeedFactor = this.onGroundSpeedFactor;
1851
        float f3 = 0.0F;
1852
1853
        if (f > 0.0025000002F)
1854
        {
1855
            f3 = 1.0F;
1856
            f2 = (float)Math.sqrt((double)f) * 3.0F;
1857
            f1 = (float)MathHelper.func_181159_b(d1, d0) * 180.0F / (float)Math.PI - 90.0F;
1858
        }
1859
1860
        if (this.swingProgress > 0.0F)
1861
        {
1862
            f1 = this.rotationYaw;
1863
        }
1864
1865
        if (!this.onGround)
1866
        {
1867
            f3 = 0.0F;
1868
        }
1869
1870
        this.onGroundSpeedFactor += (f3 - this.onGroundSpeedFactor) * 0.3F;
1871
        this.worldObj.theProfiler.startSection("headTurn");
1872
        f2 = this.func_110146_f(f1, f2);
1873
        this.worldObj.theProfiler.endSection();
1874
        this.worldObj.theProfiler.startSection("rangeChecks");
1875
1876
        while (this.rotationYaw - this.prevRotationYaw < -180.0F)
1877
        {
1878
            this.prevRotationYaw -= 360.0F;
1879
        }
1880
1881
        while (this.rotationYaw - this.prevRotationYaw >= 180.0F)
1882
        {
1883
            this.prevRotationYaw += 360.0F;
1884
        }
1885
1886
        while (this.renderYawOffset - this.prevRenderYawOffset < -180.0F)
1887
        {
1888
            this.prevRenderYawOffset -= 360.0F;
1889
        }
1890
1891
        while (this.renderYawOffset - this.prevRenderYawOffset >= 180.0F)
1892
        {
1893
            this.prevRenderYawOffset += 360.0F;
1894
        }
1895
1896
        while (this.rotationPitch - this.prevRotationPitch < -180.0F)
1897
        {
1898
            this.prevRotationPitch -= 360.0F;
1899
        }
1900
1901
        while (this.rotationPitch - this.prevRotationPitch >= 180.0F)
1902
        {
1903
            this.prevRotationPitch += 360.0F;
1904
        }
1905
1906
        while (this.rotationYawHead - this.prevRotationYawHead < -180.0F)
1907
        {
1908
            this.prevRotationYawHead -= 360.0F;
1909
        }
1910
1911
        while (this.rotationYawHead - this.prevRotationYawHead >= 180.0F)
1912
        {
1913
            this.prevRotationYawHead += 360.0F;
1914
        }
1915
1916
        this.worldObj.theProfiler.endSection();
1917
        this.movedDistance += f2;
1918
    }
1919
1920
    protected float func_110146_f(float p_110146_1_, float p_110146_2_)
1921
    {
1922
        float f = MathHelper.wrapAngleTo180_float(p_110146_1_ - this.renderYawOffset);
1923
        this.renderYawOffset += f * 0.3F;
1924
        float f1 = MathHelper.wrapAngleTo180_float(this.rotationYaw - this.renderYawOffset);
1925
        boolean flag = f1 < -90.0F || f1 >= 90.0F;
1926
1927
        if (f1 < -75.0F)
1928
        {
1929
            f1 = -75.0F;
1930
        }
1931
1932
        if (f1 >= 75.0F)
1933
        {
1934
            f1 = 75.0F;
1935
        }
1936
1937
        this.renderYawOffset = this.rotationYaw - f1;
1938
1939
        if (f1 * f1 > 2500.0F)
1940
        {
1941
            this.renderYawOffset += f1 * 0.2F;
1942
        }
1943
1944
        if (flag)
1945
        {
1946
            p_110146_2_ *= -1.0F;
1947
        }
1948
1949
        return p_110146_2_;
1950
    }
1951
1952
    /**
1953
     * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons
1954
     * use this to react to sunlight and start to burn.
1955
     */
1956
    public void onLivingUpdate()
1957
    {
1958
        if (this.jumpTicks > 0)
1959
        {
1960
            --this.jumpTicks;
1961
        }
1962
1963
        if (this.newPosRotationIncrements > 0)
1964
        {
1965
            double d0 = this.posX + (this.newPosX - this.posX) / (double)this.newPosRotationIncrements;
1966
            double d1 = this.posY + (this.newPosY - this.posY) / (double)this.newPosRotationIncrements;
1967
            double d2 = this.posZ + (this.newPosZ - this.posZ) / (double)this.newPosRotationIncrements;
1968
            double d3 = MathHelper.wrapAngleTo180_double(this.newRotationYaw - (double)this.rotationYaw);
1969
            this.rotationYaw = (float)((double)this.rotationYaw + d3 / (double)this.newPosRotationIncrements);
1970
            this.rotationPitch = (float)((double)this.rotationPitch + (this.newRotationPitch - (double)this.rotationPitch) / (double)this.newPosRotationIncrements);
1971
            --this.newPosRotationIncrements;
1972
            this.setPosition(d0, d1, d2);
1973
            this.setRotation(this.rotationYaw, this.rotationPitch);
1974
        }
1975
        else if (!this.isServerWorld())
1976
        {
1977
            this.motionX *= 0.98D;
1978
            this.motionY *= 0.98D;
1979
            this.motionZ *= 0.98D;
1980
        }
1981
1982
        if (Math.abs(this.motionX) < 0.005D)
1983
        {
1984
            this.motionX = 0.0D;
1985
        }
1986
1987
        if (Math.abs(this.motionY) < 0.005D)
1988
        {
1989
            this.motionY = 0.0D;
1990
        }
1991
1992
        if (Math.abs(this.motionZ) < 0.005D)
1993
        {
1994
            this.motionZ = 0.0D;
1995
        }
1996
1997
        this.worldObj.theProfiler.startSection("ai");
1998
1999
        if (this.isMovementBlocked())
2000
        {
2001
            this.isJumping = false;
2002
            this.moveStrafing = 0.0F;
2003
            this.moveForward = 0.0F;
2004
            this.randomYawVelocity = 0.0F;
2005
        }
2006
        else if (this.isServerWorld())
2007
        {
2008
            this.worldObj.theProfiler.startSection("newAi");
2009
            this.updateEntityActionState();
2010
            this.worldObj.theProfiler.endSection();
2011
        }
2012
2013
        this.worldObj.theProfiler.endSection();
2014
        this.worldObj.theProfiler.startSection("jump");
2015
2016
        if (this.isJumping)
2017
        {
2018
            if (this.isInWater())
2019
            {
2020
                this.updateAITick();
2021
            }
2022
            else if (this.isInLava())
2023
            {
2024
                this.handleJumpLava();
2025
            }
2026
            else if (this.onGround && this.jumpTicks == 0)
2027
            {
2028
                this.jump();
2029
                this.jumpTicks = 10;
2030
            }
2031
        }
2032
        else
2033
        {
2034
            this.jumpTicks = 0;
2035
        }
2036
2037
        this.worldObj.theProfiler.endSection();
2038
        this.worldObj.theProfiler.startSection("travel");
2039
        this.moveStrafing *= 0.98F;
2040
        this.moveForward *= 0.98F;
2041
        this.randomYawVelocity *= 0.9F;
2042
        this.moveEntityWithHeading(this.moveStrafing, this.moveForward);
2043
        this.worldObj.theProfiler.endSection();
2044
        this.worldObj.theProfiler.startSection("push");
2045
2046
        if (!this.worldObj.isRemote)
2047
        {
2048
            this.collideWithNearbyEntities();
2049
        }
2050
2051
        this.worldObj.theProfiler.endSection();
2052
    }
2053
2054
    protected void updateEntityActionState()
2055
    {
2056
    }
2057
2058
    protected void collideWithNearbyEntities()
2059
    {
2060
        List<Entity> list = this.worldObj.getEntitiesInAABBexcluding(this, this.getEntityBoundingBox().expand(0.20000000298023224D, 0.0D, 0.20000000298023224D), Predicates.<Entity> and (EntitySelectors.NOT_SPECTATING, new Predicate<Entity>()
2061
        {
2062
            public boolean apply(Entity p_apply_1_)
2063
            {
2064
                return p_apply_1_.canBePushed();
2065
            }
2066
        }));
2067
2068
        if (!list.isEmpty())
2069
        {
2070
            for (int i = 0; i < list.size(); ++i)
2071
            {
2072
                Entity entity = (Entity)list.get(i);
2073
                this.collideWithEntity(entity);
2074
            }
2075
        }
2076
    }
2077
2078
    protected void collideWithEntity(Entity p_82167_1_)
2079
    {
2080
        p_82167_1_.applyEntityCollision(this);
2081
    }
2082
2083
    /**
2084
     * Called when a player mounts an entity. e.g. mounts a pig, mounts a boat.
2085
     */
2086
    public void mountEntity(Entity entityIn)
2087
    {
2088
        if (this.ridingEntity != null && entityIn == null)
2089
        {
2090
            if (!this.worldObj.isRemote)
2091
            {
2092
                this.dismountEntity(this.ridingEntity);
2093
            }
2094
2095
            if (this.ridingEntity != null)
2096
            {
2097
                this.ridingEntity.riddenByEntity = null;
2098
            }
2099
2100
            this.ridingEntity = null;
2101
        }
2102
        else
2103
        {
2104
            super.mountEntity(entityIn);
2105
        }
2106
    }
2107
2108
    /**
2109
     * Handles updating while being ridden by an entity
2110
     */
2111
    public void updateRidden()
2112
    {
2113
        super.updateRidden();
2114
        this.prevOnGroundSpeedFactor = this.onGroundSpeedFactor;
2115
        this.onGroundSpeedFactor = 0.0F;
2116
        this.fallDistance = 0.0F;
2117
    }
2118
2119
    public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_)
2120
    {
2121
        this.newPosX = x;
2122
        this.newPosY = y;
2123
        this.newPosZ = z;
2124
        this.newRotationYaw = (double)yaw;
2125
        this.newRotationPitch = (double)pitch;
2126
        this.newPosRotationIncrements = posRotationIncrements;
2127
    }
2128
2129
    public void setJumping(boolean p_70637_1_)
2130
    {
2131
        this.isJumping = p_70637_1_;
2132
    }
2133
2134
    /**
2135
     * Called whenever an item is picked up from walking over it. Args: pickedUpEntity, stackSize
2136
     */
2137
    public void onItemPickup(Entity p_71001_1_, int p_71001_2_)
2138
    {
2139
        if (!p_71001_1_.isDead && !this.worldObj.isRemote)
2140
        {
2141
            EntityTracker entitytracker = ((WorldServer)this.worldObj).getEntityTracker();
2142
2143
            if (p_71001_1_ instanceof EntityItem)
2144
            {
2145
                entitytracker.sendToAllTrackingEntity(p_71001_1_, new S0DPacketCollectItem(p_71001_1_.getEntityId(), this.getEntityId()));
2146
            }
2147
2148
            if (p_71001_1_ instanceof EntityArrow)
2149
            {
2150
                entitytracker.sendToAllTrackingEntity(p_71001_1_, new S0DPacketCollectItem(p_71001_1_.getEntityId(), this.getEntityId()));
2151
            }
2152
2153
            if (p_71001_1_ instanceof EntityXPOrb)
2154
            {
2155
                entitytracker.sendToAllTrackingEntity(p_71001_1_, new S0DPacketCollectItem(p_71001_1_.getEntityId(), this.getEntityId()));
2156
            }
2157
        }
2158
    }
2159
2160
    /**
2161
     * returns true if the entity provided in the argument can be seen. (Raytrace)
2162
     */
2163
    public boolean canEntityBeSeen(Entity entityIn)
2164
    {
2165
        return this.worldObj.rayTraceBlocks(new Vec3(this.posX, this.posY + (double)this.getEyeHeight(), this.posZ), new Vec3(entityIn.posX, entityIn.posY + (double)entityIn.getEyeHeight(), entityIn.posZ)) == null;
2166
    }
2167
2168
    /**
2169
     * returns a (normalized) vector of where this entity is looking
2170
     */
2171
    public Vec3 getLookVec()
2172
    {
2173
        return this.getLook(1.0F);
2174
    }
2175
2176
    /**
2177
     * interpolated look vector
2178
     */
2179
    public Vec3 getLook(float partialTicks)
2180
    {
2181
        if (partialTicks == 1.0F)
2182
        {
2183
            return this.getVectorForRotation(this.rotationPitch, this.rotationYawHead);
2184
        }
2185
        else
2186
        {
2187
            float f = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * partialTicks;
2188
            float f1 = this.prevRotationYawHead + (this.rotationYawHead - this.prevRotationYawHead) * partialTicks;
2189
            return this.getVectorForRotation(f, f1);
2190
        }
2191
    }
2192
2193
    /**
2194
     * Returns where in the swing animation the living entity is (from 0 to 1).  Args: partialTickTime
2195
     */
2196
    public float getSwingProgress(float partialTickTime)
2197
    {
2198
        float f = this.swingProgress - this.prevSwingProgress;
2199
2200
        if (f < 0.0F)
2201
        {
2202
            ++f;
2203
        }
2204
2205
        return this.prevSwingProgress + f * partialTickTime;
2206
    }
2207
2208
    /**
2209
     * Returns whether the entity is in a server world
2210
     */
2211
    public boolean isServerWorld()
2212
    {
2213
        return !this.worldObj.isRemote;
2214
    }
2215
2216
    /**
2217
     * Returns true if other Entities should be prevented from moving through this Entity.
2218
     */
2219
    public boolean canBeCollidedWith()
2220
    {
2221
        return !this.isDead;
2222
    }
2223
2224
    /**
2225
     * Returns true if this entity should push and be pushed by other entities when colliding.
2226
     */
2227
    public boolean canBePushed()
2228
    {
2229
        return !this.isDead;
2230
    }
2231
2232
    /**
2233
     * Sets that this entity has been attacked.
2234
     */
2235
    protected void setBeenAttacked()
2236
    {
2237
        this.velocityChanged = this.rand.nextDouble() >= this.getEntityAttribute(SharedMonsterAttributes.knockbackResistance).getAttributeValue();
2238
    }
2239
2240
    public float getRotationYawHead()
2241
    {
2242
        return this.rotationYawHead;
2243
    }
2244
2245
    /**
2246
     * Sets the head's yaw rotation of the entity.
2247
     */
2248
    public void setRotationYawHead(float rotation)
2249
    {
2250
        this.rotationYawHead = rotation;
2251
    }
2252
2253
    public void func_181013_g(float p_181013_1_)
2254
    {
2255
        this.renderYawOffset = p_181013_1_;
2256
    }
2257
2258
    public float getAbsorptionAmount()
2259
    {
2260
        return this.absorptionAmount;
2261
    }
2262
2263
    public void setAbsorptionAmount(float amount)
2264
    {
2265
        if (amount < 0.0F)
2266
        {
2267
            amount = 0.0F;
2268
        }
2269
2270
        this.absorptionAmount = amount;
2271
    }
2272
2273
    public Team getTeam()
2274
    {
2275
        return this.worldObj.getScoreboard().getPlayersTeam(this.getUniqueID().toString());
2276
    }
2277
2278
    public boolean isOnSameTeam(EntityLivingBase otherEntity)
2279
    {
2280
        return this.isOnTeam(otherEntity.getTeam());
2281
    }
2282
2283
    /**
2284
     * Returns true if the entity is on a specific team.
2285
     */
2286
    public boolean isOnTeam(Team p_142012_1_)
2287
    {
2288
        return this.getTeam() != null ? this.getTeam().isSameTeam(p_142012_1_) : false;
2289
    }
2290
2291
    /**
2292
     * Sends an ENTER_COMBAT packet to the client
2293
     */
2294
    public void sendEnterCombat()
2295
    {
2296
    }
2297
2298
    /**
2299
     * Sends an END_COMBAT packet to the client
2300
     */
2301
    public void sendEndCombat()
2302
    {
2303
    }
2304
2305
    protected void markPotionsDirty()
2306
    {
2307
        this.potionsNeedUpdate = true;
2308
    }
2309
}

What this file does

Two regions of this file make the module work. isOnLadder() (line 1132) is the hook point: it computes the vanilla ladder boolean from the block under the player, dispatches EventOnLadder POST, and substitutes the event's onLadder value when modules changed it: the exact contract Spider exploits. onLivingUpdate (line 1645) is the consumer: while isOnLadder() is true it clamps horizontal motion to ±0.15, clears fallDistance, and, under the isCollidedHorizontally branch (line 1667), drives motionY to 0.2.

Because the substitution happens before the movement code reads the ladder state, the module never has to touch motion or packets: the vanilla climb code does all the work once the boolean lies.

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 SurvivalFly (vertical envelope and climbable exemption)

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 rebuilds the allowed vertical from the physics model via vDistRel. The jump envelope (PhysicsEnvelope.isJumpMotion) admits only the initial jump impulse; after that the allowance is momentum-seeded from the previous move and decays by gravity each tick. The climbable exemption (from.isOnClimbable() clamps the allowed descent to -Magic.CLIMBABLE_MAX_SPEED and tags the move 'v_climbable') is gated on the block cache reporting an actual ladder or vine at the player's position.

A spider climb runs against a plain wall: no climbable block sits under the player, so the exemption never applies and the constant +0.2 ascent is measured against a decaying jump allowance that falls below 0.2 within a few ticks. The violation ((max(hDistanceAboveLimit, 0.0) + max(yDistanceAboveLimit, 0.0)) * 100) then fires and handleViolation set-backs the player to the stored location. The module's onGround claims are irrelevant: NCP's ground state comes from its own block scan, not the packet flag.

anticheat Flight17 (ascent accumulator)

Flight17.java301 lines · Java
1
package me.vrekt.arc.check.moving.compatibility;
2
3
import me.vrekt.arc.Arc;
4
import me.vrekt.arc.check.Check;
5
import me.vrekt.arc.check.CheckResult;
6
import me.vrekt.arc.check.CheckType;
7
import me.vrekt.arc.data.moving.MovingData;
8
import me.vrekt.arc.utilties.LocationHelper;
9
import org.bukkit.ChatColor;
10
import org.bukkit.Location;
11
import org.bukkit.block.Block;
12
import org.bukkit.block.BlockFace;
13
import org.bukkit.entity.Player;
14
import org.bukkit.material.Step;
15
import org.bukkit.potion.PotionEffectType;
16
17
public class Flight17 extends Check {
18
    private double maxAscendSpeed, maxDescendSpeed, maxHeight, maxHover, maxAscendDistance;
19
    private int maxAscendTime;
20
21
    public Flight17() {
22
        super(CheckType.FLIGHT_17);
23
24
        maxAscendSpeed = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "ascend-ladder");
25
        maxDescendSpeed = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "descend-ladder");
26
        maxHeight = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "max-jump");
27
        maxHover = Arc.getCheckManager().getValueInt(CheckType.FLIGHT, "max-hover-time");
28
        maxAscendDistance = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "ascend-distance");
29
30
        maxAscendTime = Arc.getCheckManager().getValueInt(CheckType.FLIGHT, "ascend-time");
31
    }
32
33
    public boolean hoverCheck(Player player, MovingData data) {
34
        result.reset();
35
36
        // Check if we are actually hovering.
37
        double vertical = data.getVerticalSpeed();
38
        boolean actuallyHovering = data.getLastVerticalSpeed() == 0.0 && vertical == 0.0 && player.getVehicle() == null;
39
40
        if (actuallyHovering) {
41
            // check how long we've been hovering for.
42
            if (data.getAirTicks() >= maxHover) {
43
                // too long, flag.
44
                getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Hover)");
45
                result.set(checkViolation(player, "hovering off the ground, hover"));
46
            }
47
        }
48
49
        return result.failed();
50
    }
51
52
    public CheckResult runBlockChecks(Player player, MovingData data) {
53
        result.reset();
54
55
        if (!data.wasOnGround()) {
56
            result.set(hoverCheck(player, data));
57
        }
58
59
        double vertical = data.getVerticalSpeed();
60
61
        // ladder and vertical velocity stuff.
62
        boolean isAscending = data.isAscending();
63
        boolean isDescending = data.isDescending();
64
        boolean isClimbing = data.isClimbing();
65
66
        int airTicks = data.getAirTicks();
67
68
        // make sure we're actually in the air.
69
        boolean actuallyInAir = airTicks >= 20 && data.getLadderTime() == 8;
70
71
        // fastladder check, make sure were ascending, climbing and in-air.
72
        if (isAscending && isClimbing && actuallyInAir) {
73
            // check if we are climbing too fast.
74
            if (vertical > maxAscendSpeed) {
75
                getCheck().setCheckName("Flight " + ChatColor.GRAY + "(FastLadder)");
76
                result.set(checkViolation(player, "ascending too fast, ladder_ascend"), data.getPreviousLocation());
77
            }
78
        }
79
80
        // patch for instant ladder
81
        double difference = vertical - maxAscendSpeed;
82
        if (isAscending && isClimbing && difference > 1.0) {
83
            getCheck().setCheckName("Flight " + ChatColor.GRAY + "(FastLadder)");
84
            result.set(checkViolation(player, "ascending too fast, ladder_instant"), data.getPreviousLocation());
85
        }
86
87
        // descending check.
88
        if (isDescending && isClimbing && actuallyInAir) {
89
            // too fast, flag.
90
            if (vertical > maxDescendSpeed) {
91
                getCheck().setCheckName("Flight " + ChatColor.GRAY + "(FastLadder)");
92
                result.set(checkViolation(player, "descending too fast, ladder_descend"), data.getPreviousLocation());
93
            }
94
        }
95
96
        getCheck().setCheckName("Flight");
97
        return result;
98
    }
99
100
101
    public CheckResult check(Player player, MovingData data) {
102
        result.reset();
103
104
        result.reset();
105
106
        Location from = data.getPreviousLocation();
107
        Location to = data.getCurrentLocation();
108
        Location ground = data.getGroundLocation();
109
        if (ground == null) {
110
            ground = from;
111
        }
112
113
        boolean onGround = data.isOnGround();
114
        boolean isAscending = data.isAscending();
115
        boolean isDescending = data.isDescending();
116
        boolean isClimbing = data.isClimbing();
117
118
        boolean isOnSlab = to.getBlock().getRelative(BlockFace.DOWN).getType().getData().equals(Step.class);
119
        boolean isOnStep = (LocationHelper.isOnSlab(to) || isOnSlab) || LocationHelper.isOnStair(to);
120
        boolean isInLiquid = LocationHelper.isInLiquid(to);
121
122
        double velocity = data.getVelocityData().getCurrentVelocity();
123
        double lastVelocity = data.getVelocityData().getLastVelocity();
124
125
        boolean wasVerticalMove = (isAscending || isDescending);
126
        boolean validVerticalMove = player.getVehicle() == null && !isOnStep && !isClimbing;
127
128
        double lastVertical = data.getLastVerticalSpeed();
129
        double vertical = data.getVerticalSpeed();
130
131
        int ascendingMoves = data.getAscendingMoves();
132
        int descendingMoves = data.getDescendingMoves();
133
        int ladderTime = data.getLadderTime();
134
135
        // if we are on ground lets reset some data.
136
        if (onGround) {
137
            ascendingMoves = 0;
138
            descendingMoves = 0;
139
140
            data.setAscendingMoves(ascendingMoves);
141
            data.setDescendingMoves(descendingMoves);
142
        }
143
144
        // update our ascending data and reset our descending data.
145
        if (isAscending) {
146
            descendingMoves = 0;
147
            data.setDescendingMoves(descendingMoves);
148
            if (!isClimbing) {
149
                ascendingMoves++;
150
                data.setAscendingMoves(ascendingMoves);
151
            }
152
        }
153
154
        // update our descending data and reset the ascending data, also account for slimeblock velocity.
155
        if (isDescending) {
156
            ascendingMoves = 0;
157
            data.setAscendingMoves(ascendingMoves);
158
159
            descendingMoves++;
160
            data.setDescendingMoves(descendingMoves);
161
            data.getVelocityData().clear();
162
        }
163
164
        // update our climbing data.
165
        if (isClimbing) {
166
            if (wasVerticalMove) {
167
                data.setLadderTime(8);
168
            }
169
            data.setLadderTime(4);
170
        } else {
171
            data.setLadderTime(ladderTime > 0 ? ladderTime - 1 : 0);
172
        }
173
174
        if (wasVerticalMove) {
175
            // start with the vclip check, we want this first to make sure nobody is clipping through anything.
176
            if (vertical >= 0.99) {
177
                // update our safe location.
178
                Location safeLocation = data.getSafe();
179
                if (safeLocation == null) {
180
                    data.setSafe(from);
181
                    safeLocation = from;
182
                }
183
184
                // get our locations for checking.
185
                int fromY = safeLocation.getBlockY();
186
                int toY = safeLocation.getBlockY() + 1;
187
                int minY = Math.min(safeLocation.getBlockY(), to.getBlockY());
188
                int maxY = Math.max(safeLocation.getBlockY(), to.getBlockY());
189
190
                for (int yy = fromY; yy <= toY; yy++) {
191
                    for (int y = minY; y <= maxY; y++) {
192
                        // loop through all the possible y coordinates and get the block at that location.
193
                        Block blockFrom = to.getWorld().getBlockAt(to.getBlockX(), yy, to.getBlockZ());
194
                        Block blockTo = to.getWorld().getBlockAt(to.getBlockX(), y, to.getBlockZ());
195
                        if (blockFrom.getType().isSolid() || blockTo.getType().isSolid()) {
196
                            // if its solid flag.
197
                            getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Vertical Clip)");
198
                            boolean failed = checkViolation(player, "clipped through a solid block, vclip_solid");
199
                            result.set(failed, safeLocation);
200
                        }
201
                    }
202
                }
203
            }
204
205
            // reset our safe location.
206
            if (!result.failed()) {
207
                data.setSafe(to);
208
            }
209
210
211
            if (!onGround) {
212
                if (isInLiquid) {
213
                    // check if the client is onGround, if so flag.
214
                    boolean ccGround = data.isPositionClientOnGround();
215
                    if (ccGround && vertical > 0.0) {
216
                        getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Jesus)");
217
                        result.set(checkViolation(player, "walking on water, ccground_liquid"));
218
                    }
219
                }
220
221
            }
222
223
            // check how we are ascending.
224
            boolean walkedOnFence = LocationHelper.walkedOnFence(to);
225
            double distanceFrom = LocationHelper.distanceVertical(ground, to);
226
            if (validVerticalMove && isAscending && !walkedOnFence && ladderTime <= 2) {
227
                // valid move, check.
228
                // first get our distance we have traveled.
229
                if (distanceFrom >= maxAscendDistance) {
230
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Ascension)");
231
                    result.set(checkViolation(player, "ascending too high, ascending_distance"));
232
                }
233
234
                // ascending for too long.
235
                if (ascendingMoves > maxAscendTime) {
236
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Ascension)");
237
                    result.set(checkViolation(player, "ascending for too long, ascending_time"));
238
                }
239
240
                // ascending too fast.
241
                double max = getMaxJump(player);
242
                if (vertical > max) {
243
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Ascension)");
244
                    result.set(checkViolation(player, "Ascending too fast, ascending_vertical"));
245
                }
246
247
            }
248
249
            // check how we are descending.
250
            if (validVerticalMove && isDescending && ladderTime <= 2) {
251
                double glideDelta = Math.abs(vertical - lastVertical);
252
253
                // check if we are descending at the same speed.
254
                if (glideDelta == 0.0) {
255
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Glide)");
256
                    result.set(checkViolation(player, "vertical not changing, descend_difference"));
257
                }
258
259
                // check the speed of how we are descending.
260
                int airTicks = data.getAirTicks();
261
                if (distanceFrom > 1.6 && descendingMoves > 2) {
262
                    double expected;
263
                    // calculate our expected difference based on air.
264
                    if (airTicks > 100) {
265
                        expected = -0.9908 * 1e-6 * Math.pow(airTicks, 2) + 3.4538 * 1e-7 * airTicks + 0.0189;
266
                    } else {
267
                        expected = 5.4246 * 1e-6 * Math.pow(airTicks, 2) - 0.0011 * airTicks + 0.0659;
268
                    }
269
270
                    double difference = Math.abs(glideDelta - expected);
271
                    if (difference > 0.02 || difference < 0.001) {
272
                        getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Glide)");
273
                        result.set(checkViolation(player, "vertical not expected, descend_expected"));
274
                    }
275
                }
276
277
            }
278
279
        }
280
281
        getCheck().setCheckName("Flight");
282
        return result;
283
    }
284
285
    /**
286
     * Return max distance we can ascend.
287
     *
288
     * @param player the player
289
     * @return the max jump height.
290
     */
291
    private double getMaxJump(Player player) {
292
293
        double max = maxHeight;
294
295
        if (player.hasPotionEffect(PotionEffectType.JUMP)) {
296
            max += 0.4;
297
        }
298
        return max;
299
300
    }
301
}

How it counteracts this module

Arc v2's Flight17 distinguishes ladder climbing from generic ascent. isClimbing comes from LocationHelper.isClimbing, which tests the block at the player's position for ladder or vine, so the FastLadder checks (ascend-ladder speed cap, default 0.1176, and the instant-ladder patch) stay silent for a wall climb. The generic ascent branch is what fires: validVerticalMove (no vehicle, not a step, not climbing) with isAscending and ladderTime at 2 or below triggers the ascent accumulator, which compares the vertical distance from the last ground location against ascend-distance (default 1.4) and the sustained ascent count against ascend-time (default 7).

A 0.2-per-tick climb crosses both thresholds around the seventh tick of a continuous ascent and flags 'Flight (Ascension)'. The module's climb has no vanilla counterpart to explain, because vanilla ascends only in short jump impulses. The ladder-specific caps are bypassed by design; the generic accumulator is not.

anticheat Fly (air gravity prediction)

Fly.java412 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.check.movement.position;
20
21
import me.islandscout.hawk.Hawk;
22
import me.islandscout.hawk.HawkPlayer;
23
import me.islandscout.hawk.check.MovementCheck;
24
import me.islandscout.hawk.event.MoveEvent;
25
import me.islandscout.hawk.util.*;
26
import me.islandscout.hawk.wrap.block.WrappedBlock;
27
import me.islandscout.hawk.wrap.entity.WrappedEntity;
28
import org.bukkit.Location;
29
import org.bukkit.Material;
30
import org.bukkit.block.Block;
31
import org.bukkit.entity.Boat;
32
import org.bukkit.entity.Entity;
33
import org.bukkit.entity.Player;
34
import org.bukkit.util.Vector;
35
36
import java.util.*;
37
38
public class Fly extends MovementCheck {
39
40
    //TODO perhaps have a ground checking mode? clientside vs serverside? doing it server side can allow GroundSpoof to not cancel, yet Gravity will still catch groundspoof-based flys
41
42
    private static final float MIN_VELOCITY = 0.005F;
43
    private static final int MAX_NO_MOVES = 20;
44
    private static final double NO_MOVE_THRESHOLD = 0.03;
45
    private static final float DISCREPANCY_THRESHOLD = 0.0001F;
46
47
    private final Map<UUID, Float> estimatedPositionMap;
48
    private final Map<UUID, Float> estimatedVelocityMap;
49
    private final Map<UUID, Float> estimatedPositionAltMap;
50
    private final Map<UUID, Float> estimatedVelocityAltMap;
51
    private final Map<UUID, Integer> noMovesMap;
52
    private final Map<UUID, Integer> ticksSinceNoPosUpdateMap;
53
    private final Set<UUID> wasFlyingSet;
54
    private final Set<UUID> wasInLavaSet;
55
56
    public Fly() {
57
        super("fly", true, 0, 10, 0.995, 5000, "&7%player% failed fly, VL: %vl%", null);
58
        estimatedPositionMap = new HashMap<>();
59
        estimatedVelocityMap = new HashMap<>();
60
        estimatedPositionAltMap = new HashMap<>();
61
        estimatedVelocityAltMap = new HashMap<>();
62
        noMovesMap = new HashMap<>();
63
        ticksSinceNoPosUpdateMap = new HashMap<>();
64
        wasFlyingSet = new HashSet<>();
65
        wasInLavaSet = new HashSet<>();
66
    }
67
68
    @Override
69
    protected void check(MoveEvent e) {
70
        HawkPlayer pp = e.getHawkPlayer();
71
        Player p = e.getPlayer();
72
73
        Vector from = pp.hasSentPosUpdate() ? e.getFrom().toVector() : pp.getPositionPredicted(); //must predict where a player was previously if they didn't send a pos update then.
74
75
        float dY = (float) (e.getTo().getY() - from.getY());
76
77
        boolean moved = e.isUpdatePos();
78
79
        int noMoves = noMovesMap.getOrDefault(pp.getUuid(), 0);
80
        int ticksSinceNoPosUpdate = ticksSinceNoPosUpdateMap.getOrDefault(pp.getUuid(), 0);
81
82
        float estimatedPosition = estimatedPositionMap.getOrDefault(pp.getUuid(), (float) from.getY()),
83
              prevEstimatedVelocity = estimatedVelocityMap.getOrDefault(pp.getUuid(), (float) pp.getVelocity().getY()),
84
              estimatedPositionAlt = estimatedPositionAltMap.getOrDefault(pp.getUuid(), (float) from.getY()),
85
              prevEstimatedVelocityAlt = estimatedVelocityAltMap.getOrDefault(pp.getUuid(), (float) pp.getVelocity().getY());
86
87
        Set<Material> touchedBlocks = WrappedEntity.getWrappedEntity(p).getCollisionBox(from).getMaterials(pp.getWorld());
88
89
        boolean opposingForce = e.isJump() || e.hasAcceptedKnockback() || e.isTeleportAccept() || e.isStep();
90
91
        boolean wasInLava = wasInLavaSet.contains(p.getUniqueId());
92
93
        if((!e.isOnGround() || !pp.isOnGround()) && !opposingForce && !e.isLiquidExit() &&
94
                !p.isInsideVehicle() && !pp.isFlying() && !wasFlyingSet.contains(p.getUniqueId()) &&
95
                !p.isSleeping() && !isInClimbable(from.toLocation(pp.getWorld())) && //TODO: uh oh! make sure to have a fastladder check, otherwise hackers can "pop" off them
96
                !isOnBoat(p, e.getTo())) {
97
98
            //count "no-moves"
99
            if(!moved) {
100
                noMoves++;
101
            } else {
102
                noMoves = 0;
103
            }
104
105
            float estimatedVelocity;
106
            float estimatedVelocityAlt;
107
            boolean velResetA = false;
108
            boolean velResetB = false;
109
110
            //compute next expected velocity
111
            //TODO make this prediction better, i.e. do liquid/web collision checks. It shouldn't be using the liquid functions when the predicted position gets out of water.
112
            if(pp.isSwimming()) { //water functions
113
114
                estimatedVelocity = (prevEstimatedVelocity * 0.8F) + (float)(-0.02 + computeVerticalWaterFlowForce(estimatedPosition, pp));
115
                estimatedVelocityAlt = (prevEstimatedVelocityAlt * 0.8F) + (float)(-0.02 + computeVerticalWaterFlowForce(estimatedPositionAlt, pp));
116
117
                if(Math.abs(estimatedVelocity) < MIN_VELOCITY) {
118
                    estimatedVelocity = 0;
119
                }
120
                if(Math.abs(estimatedVelocityAlt) < MIN_VELOCITY) {
121
                    estimatedVelocityAlt = 0;
122
                }
123
                estimatedVelocityAlt += 0.04; //add swimming-up force
124
                if(e.isInWeb()) {
125
                    estimatedVelocity *= 0.05;
126
                    estimatedVelocityAlt *= 0.05;
127
                }
128
            } else if(wasInLava) { //lava functions
129
130
                estimatedVelocity = (prevEstimatedVelocity * 0.5F) - 0.02F;
131
                estimatedVelocityAlt = (prevEstimatedVelocityAlt * 0.5F) - 0.02F;
132
133
                if(Math.abs(estimatedVelocity) < MIN_VELOCITY) {
134
                    estimatedVelocity = 0;
135
                }
136
                if(Math.abs(estimatedVelocityAlt) < MIN_VELOCITY) {
137
                    estimatedVelocityAlt = 0;
138
                }
139
                estimatedVelocityAlt += 0.04; //add swimming-up force
140
                if(e.isInWeb()) {
141
                    estimatedVelocity *= 0.05;
142
                    estimatedVelocityAlt *= 0.05;
143
                }
144
            } else { //air function
145
146
                estimatedVelocity = estimatedVelocityAlt = (prevEstimatedVelocity - 0.08F) * 0.98F;
147
148
                if(Math.abs(estimatedVelocity) < MIN_VELOCITY) {
149
                    estimatedVelocity = 0;
150
                }
151
                if(Math.abs(estimatedVelocityAlt) < MIN_VELOCITY) {
152
                    estimatedVelocityAlt = 0;
153
                }
154
                if(e.isInWeb()) {
155
                    estimatedVelocity *= 0.05;
156
                    estimatedVelocityAlt *= 0.05;
157
                }
158
159
                if(pp.isInWater() || pp.isInLava()) { //Entering liquid. You could take two paths depending if you're holding the jump button or not.
160
161
                    estimatedVelocity = (prevEstimatedVelocity + (float)computeVerticalWaterFlowForce(estimatedPosition, pp) - 0.08F) * 0.98F;
162
                    estimatedVelocity += computeVerticalWaterFlowForce(estimatedPosition, pp);
163
164
                    estimatedVelocityAlt = (prevEstimatedVelocityAlt + (float)computeVerticalWaterFlowForce(estimatedPositionAlt, pp) - 0.08F) * 0.98F;
165
                    estimatedVelocityAlt += computeVerticalWaterFlowForce(estimatedPositionAlt, pp);
166
167
                    if(Math.abs(estimatedVelocity) < MIN_VELOCITY) {
168
                        estimatedVelocity = 0;
169
                    }
170
                    if(Math.abs(estimatedVelocityAlt) < MIN_VELOCITY) {
171
                        estimatedVelocityAlt = 0;
172
                    }
173
                    estimatedVelocityAlt += 0.04; //add swimming-up force
174
                    if(e.isInWeb()) {
175
                        estimatedVelocity *= 0.05;
176
                        estimatedVelocityAlt *= 0.05;
177
                    }
178
                }
179
            }
180
181
            //handle teleport
182
            if (pp.getCurrentTick() - pp.getLastTeleportAcceptTick() < 2) {
183
                estimatedVelocity = 0;
184
                estimatedVelocityAlt = 0;
185
                velResetA = true;
186
                velResetB = true;
187
            }
188
189
            //add velocities to expected positions
190
            estimatedPositionAlt += estimatedVelocityAlt;
191
            estimatedPosition += estimatedVelocity;
192
193
            //check if hit head
194
            boolean hasHitHead = pp.getBoxSidesTouchingBlocks().contains(Direction.TOP);
195
            if(e.getTo().getY() < estimatedPosition && (e.isTouchingCeiling() && !hasHitHead)) { //standard pos/vel
196
                estimatedPosition = (float) e.getTo().getY();
197
                estimatedVelocity = 0;
198
                velResetA = true;
199
            }
200
201
            //check if hit head while swimming
202
            if(e.getTo().getY() < estimatedPositionAlt && e.getTo().getY() > estimatedPosition &&
203
                    (pp.isInWater() || pp.isInLava() || pp.isSwimming()) && (e.isTouchingCeiling() || hasHitHead)) { //alt. pos/vel
204
                estimatedPositionAlt = (float) e.getTo().getY();
205
                estimatedVelocityAlt = 0;
206
                velResetB = true;
207
            }
208
209
            //check landing
210
            if(e.isOnGround() && !pp.isOnGround()) {
211
                //Pretty much check if the Y is within reasonable bounds.
212
                //Doesn't need to be so precise i.e. 0.0001 within bounds, leave that for GroundSpoof and Phase.
213
                //However, if it becomes a problem, you know how to expand this code.
214
                float y;
215
216
                if(moved) {
217
                    y = (float) e.getTo().getY();
218
                } else {
219
                    y = (float) pp.getPositionPredicted().getY();
220
                }
221
222
                double fromY = MathPlus.round(from.getY(), 10);
223
224
                float discrepancy = y - estimatedPosition;
225
                //y must be between last Y and estimatedPosition, and dY must be <= 0 (MAYBE that's already inherent with the former, but I have this for redundancy).
226
                if (Math.abs(discrepancy) > DISCREPANCY_THRESHOLD && !e.isPossiblePistonPush() &&
227
                        ((y - pp.getPreviousPositionPredicted().getY()) > 0 || y < Math.min(estimatedPosition, fromY) || y > Math.max(estimatedPosition, fromY))) {
228
                    punishAndTryRubberband(pp, e);
229
                } else {
230
                    reward(pp);
231
                }
232
233
                //If you've landed, then that must mean these should reset.
234
                estimatedPosition = y;
235
                estimatedPositionAlt = y;
236
237
                if(e.isNextSlimeBlockBounce()) {
238
                    prevEstimatedVelocity = -estimatedVelocity;
239
                } else {
240
                    prevEstimatedVelocity = 0;
241
                }
242
243
                prevEstimatedVelocityAlt = prevEstimatedVelocity;
244
            }
245
246
            //check for Y discrepancy in air
247
            else {
248
249
                //bool alt determines if we're using the alternate path for comparison
250
                boolean alt;
251
252
                if(moved || noMoves > MAX_NO_MOVES || (Math.abs(estimatedPosition - e.getTo().getY()) > NO_MOVE_THRESHOLD && Math.abs(estimatedPositionAlt - e.getTo().getY()) > NO_MOVE_THRESHOLD)) {
253
254
                    float discrepancy;
255
256
                    if(ticksSinceNoPosUpdate < 2 && noMoves <= MAX_NO_MOVES) {
257
                        //Handle stupid-moves with a range check.
258
                        //Honestly, I don't care about an error of 0.03 in liquids while the client isn't updating its position.
259
                        float y = (float) e.getTo().getY();
260
                        float max = Math.max(estimatedPositionAlt, estimatedPosition);
261
                        float min = Math.min(estimatedPositionAlt, estimatedPosition);
262
                        if(y > max) {
263
                            discrepancy = y - max;
264
                        } else if(y < min) {
265
                            discrepancy = y - min;
266
                        } else {
267
                            discrepancy = 0;
268
                        }
269
                    } else {
270
                        float discrepancyA = (float) e.getTo().getY() - estimatedPosition;
271
                        float discrepancyB = (float) e.getTo().getY() - estimatedPositionAlt;
272
                        //choose discrepancy closer to 0
273
                        alt = Math.abs(discrepancyA) - Math.abs(discrepancyB) > 0;
274
                        discrepancy = alt ? discrepancyB : discrepancyA;
275
                    }
276
277
                    boolean onSlimeBlock;
278
                    if(Hawk.getServerVersion() > 7) {
279
                        //-0.1 is arbitrary
280
                        Block block = ServerUtils.getBlockAsync(e.getFrom().clone().add(0, -0.2, 0));
281
                        onSlimeBlock = block != null && block.getType() == Material.SLIME_BLOCK
282
                                && Math.abs(dY) < 0.1;
283
                    } else {
284
                        onSlimeBlock = false;
285
                    }
286
287
                    if(Math.abs(discrepancy) > DISCREPANCY_THRESHOLD && !e.isPossiblePistonPush() && !onSlimeBlock) {
288
                        punishAndTryRubberband(pp, e);
289
                    }
290
                    else {
291
                        reward(pp);
292
                    }
293
                }
294
295
                //TODO limit these estimatedVelocities to 0.03 if this is a no-move. Likewise, limit the estimated positions, too.
296
297
                if(moved) {
298
                    //we can use these for next move, since the client has sent a pos update
299
                    estimatedPosition = estimatedPositionAlt = (float) e.getTo().getY();
300
                    if(ticksSinceNoPosUpdate > 0) {
301
                        estimatedVelocity = velResetA ? estimatedVelocity : dY;
302
                        estimatedVelocityAlt = velResetB ? estimatedVelocityAlt : dY;
303
                    }
304
                }
305
306
                //keep estimating
307
                if (e.isInWeb()) {
308
                    prevEstimatedVelocity = prevEstimatedVelocityAlt = 0;
309
                } else {
310
                    prevEstimatedVelocity = estimatedVelocity;
311
                    prevEstimatedVelocityAlt = estimatedVelocityAlt;
312
                }
313
            }
314
        } else {
315
            if(moved) {
316
                estimatedPosition = estimatedPositionAlt = (float) e.getTo().getY();
317
            } else {
318
                estimatedPosition = estimatedPositionAlt = (float) pp.getPositionPredicted().getY();
319
            }
320
321
            if(e.isOnGround() || (e.isTouchingCeiling() && dY > 0) || touchedBlocks.contains(Material.WEB)) {
322
                prevEstimatedVelocity = prevEstimatedVelocityAlt = 0;
323
            } else {
324
                prevEstimatedVelocity = prevEstimatedVelocityAlt = dY;
325
            }
326
        }
327
        //Debug.broadcastMessage((moved ? ChatColor.GREEN : ChatColor.RED) + "" + e.getTo().getY() + " " + estimatedPosition + " " + pp.getPositionPredicted().getY() + " prevEstDY: " + prevEstimatedVelocity);
328
329
        estimatedVelocityMap.put(pp.getUuid(), prevEstimatedVelocity);
330
        estimatedVelocityAltMap.put(pp.getUuid(), prevEstimatedVelocityAlt);
331
        estimatedPositionMap.put(pp.getUuid(), estimatedPosition);
332
        estimatedPositionAltMap.put(pp.getUuid(), estimatedPositionAlt);
333
334
        noMovesMap.put(pp.getUuid(), noMoves);
335
336
        if(!moved) {
337
            ticksSinceNoPosUpdate = 0;
338
        } else {
339
            ticksSinceNoPosUpdate++;
340
        }
341
342
        ticksSinceNoPosUpdateMap.put(p.getUniqueId(), ticksSinceNoPosUpdate);
343
344
        if(pp.isFlying()) {
345
            wasFlyingSet.add(p.getUniqueId());
346
        } else {
347
            wasFlyingSet.remove(p.getUniqueId());
348
        }
349
350
        if(pp.isInLava()) {
351
            wasInLavaSet.add(p.getUniqueId());
352
        } else {
353
            wasInLavaSet.remove(p.getUniqueId());
354
        }
355
    }
356
357
    private boolean isOnBoat(Player p, Location loc) {
358
        Set<Entity> trackedEntities = hawk.getLagCompensator().getPositionTrackedEntities();
359
        int ping = ServerUtils.getPing(p);
360
        for(Entity entity : trackedEntities) {
361
            if (entity instanceof Boat) {
362
                AABB boatBB = WrappedEntity.getWrappedEntity(entity).getCollisionBox(hawk.getLagCompensator().getHistoryLocation(ping, entity).toVector());
363
                AABB feet = new AABB(
364
                        new Vector(-0.3, -0.4, -0.3).add(loc.toVector()),
365
                        new Vector(0.3, 0, 0.3).add(loc.toVector()));
366
                feet.expand(0.5, 0.5, 0.5);
367
                if (feet.isColliding(boatBB))
368
                    return true;
369
            }
370
        }
371
        return false;
372
    }
373
374
    private boolean isInClimbable(Location loc) {
375
        Block b = ServerUtils.getBlockAsync(loc);
376
        return b != null && (b.getType() == Material.VINE || b.getType() == Material.LADDER);
377
    }
378
379
    private double computeVerticalWaterFlowForce(double y, HawkPlayer pp) {
380
        Vector vec = new Vector();
381
        AABB liquidTest = AABB.playerWaterCollisionBox.clone();
382
        liquidTest.translate(new Vector(pp.getPosition().getX(), y, pp.getPosition().getZ()));
383
        List<Block> blocks = liquidTest.getBlocks(pp.getPlayer().getWorld());
384
        Vector waterFlow = new Vector();
385
        for(Block b : blocks) {
386
            if(b.getType() == Material.WATER || b.getType() == Material.STATIONARY_WATER) {
387
                //game version doesn't really matter for this
388
                Vector direction = WrappedBlock.getWrappedBlock(b, 8).getFlowDirection();
389
                waterFlow.add(direction);
390
            }
391
        }
392
        if(waterFlow.lengthSquared() > 0 && !pp.isFlying()) {
393
            waterFlow.normalize();
394
            waterFlow.multiply(0.014);
395
            vec.add(waterFlow);
396
        }
397
        return vec.getY();
398
    }
399
400
401
    @Override
402
    public void removeData(Player p) {
403
        UUID uuid = p.getUniqueId();
404
        estimatedPositionMap.remove(uuid);
405
        estimatedVelocityMap.remove(uuid);
406
        estimatedPositionAltMap.remove(uuid);
407
        estimatedVelocityAltMap.remove(uuid);
408
        noMovesMap.remove(uuid);
409
        ticksSinceNoPosUpdateMap.remove(uuid);
410
        wasFlyingSet.remove(uuid);
411
    }
412
}

How it counteracts this module

Hawk's Fly predicts the player's Y from an air gravity model: each tick the expected velocity is (previous - 0.08) * 0.98, and the check punishes any move whose Y lands more than DISCREPANCY_THRESHOLD (0.0001) away from the predicted position. The check is skipped entirely when the from-location is actually climbable: isInClimbable tests for ladder or vine at the block under the player (line 374), which is the exemption genuine ladder users need.

A spider climb runs against a plain wall, so the exemption never applies and each +0.2 move lands roughly 0.2 above the predicted descending position (a discrepancy thousands of times the threshold), so punishAndTryRubberband fires on the first few moves. The file's own TODO notes that a fast-ladder check is still needed so players cannot 'pop' off real climbables; the wall-climb variant is exactly the case the exemption was never meant to cover.

← Back to Analysis Hub