Aqua 13 Scaffold module 5 files, 2138 lines

Aqua 13 Scaffold: Full Source Analysis

Aqua 13's Scaffold (811 lines) is a full block-placing module driven by one onEvent(Event) dispatcher.

intent/AquaDev/aqua/modules/world/Scaffold.java · GitHub source ↗

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

Analysis

Overview

Aqua 13's Scaffold (811 lines) is a full block-placing module driven by one onEvent(Event) dispatcher. Every tick the update pass runs the block search (find) that picks a support block among the six neighbors of the block below the player, then an 8-cell ring two blocks out, validating each candidate with a 10-step ray trace. The hotbar slot holding the first non-blacklisted ItemBlock is forced through the EventSycItem event, which Aqua's patched PlayerControllerMP turns into a C09PacketHeldItemChange before each placement. Placement goes through the vanilla player controller, which emits C08PacketPlayerBlockPlacement, and the swing is either a local swingItem or a direct C0APacketAnimation. The outgoing rotation is overridden in EventPreMotion: Static mode locks yaw + 180 and pitch 82, Calculated mode uses the inlined rotationrecode2 atan2 aim with mouse-sensitivity snapping and a pitch clamp of 78-80. Six tower modes (Cubecraft, Watchdog, UpdatedNCP, WatchdogNew, IntaveFast, VerusFast) each implement a different jump profile, and VerusFast also spams fake C08 packets. The module carries its own block-count HUD (Glow, Shadow and Jello shader styles), a block ESP overlay, a blacklist of 15 non-placeable block ids, BMCBoost timer abuse at 1.105x, Down and SameY bridging, and a LegitPlace mode that reimplements the vanilla right-click pipeline.

Architecture

Scaffold extends Module and registers 18 settings through Aqua.setmgr with the de.Hero Setting framework: toggles for Sprint, EnableCalculate, EnableSneak, BlockCount, BlockESP, Intave, Swing, Down, SameY, Expand, AutoDisable, BMCBoost, LegitPlace and ReverseYaw, number settings SneakModify, Expandlength and YawPosition, and the RotationMode, Shader and seven-mode Tower lists. All event handling flows through one onEvent(Event) method. EventRenderNameTags draws the BlockESP box around the full block below the player, EventTick maintains the offGround air-tick counter, EventRender2D and EventPostRender2D draw the block-count HUD in the Glow, Shadow and Jello styles, EventSycItem silently forces the block slot, EventUpdate runs the search, tower modes, sprint handling, timer boost and the actual placement, and EventPreMotion overrides the outgoing rotation. The placement result is stored in the static BlockData inner class so every method reads the last (facing, pos) pair without argument passing. The BlackList inner class filters block ids (slabs, banners, chests, trapped chest, anvil, enchanting table, crafting table, furnace, web, sapling) so they are never used as scaffold material, and getBlockCount sums the hotbar stack sizes of ItemBlock items for the HUD. On enable the module optionally holds the sneak key and caches posY, and on disable it resets timerSpeed and releases the sneak key.

Block search and placement

find(Vec3) computes the search origin from the player position. The Expand setting extrapolates the origin along the player's movement delta by the Expandlength multiplier, the y level is the cached posY when SameY or Down is active (with a keyBindForward branch), and the anchor position is the block below the player. The first pass loops the six EnumFacing values and accepts the first neighbor that is not air and whose face point survives rayTrace; the returned BlockData pairs the support block with the inverted facing so the new block lands at the anchor. The second pass scans an 8-cell ring with offsets (-1,0,0), (1,0,0), (0,0,-1), (0,0,1), (0,0,2), (0,0,-2), (2,0,0), (-2,0,0): for each ring cell that is air, its six neighbors are checked the same way, which lets the module bridge onto supports two cells away. getPositionByFace computes the aim point as the block center plus half the facing direction vector, and rayTrace samples 10 points along the line from the player look direction to that point, rejecting the candidate if any solid, non-liquid block's collision bounding box contains a sample. getBlockSlot returns the first hotbar slot whose ItemBlock id is not blacklisted. Placement calls updateController() and then onPlayerRightClick with the support block position, the facing, the held stack and a hit vector at the block center offset by half the facing direction. Vanilla PlayerControllerMP sends C08PacketPlayerBlockPlacement with the hit position, the facing index, the held stack and the three fractional face offsets, then runs the local ItemBlock.onItemUse. With the Swing setting on the module calls swingItem() so the arm animates locally, otherwise it sends C0APacketAnimation directly, which animates only on the server side.

Rotation, slot sync and tower modes

The EventSycItem handler writes the result of getBlockSlot into the event's slot field. Aqua's PlayerControllerMP.syncCurrentPlayItem fires this event with the current hotbar slot and only sends C09PacketHeldItemChange when the event changed the slot, so the held-item update precedes each C08 without moving the real inventory cursor. In EventPreMotion the rotation override is applied only when data is not null. Static mode sets the outgoing yaw to rotationYaw + 180 and pitch to 82, and both modes first copy the head rotations into RotationUtil.yaw and RotationUtil.pitch so other modules and the render pass can read the actual aim. Calculated mode uses rotationrecode2, which aims with atan2 at the support face (block center plus half the facing offset, pitch target at y + 0.6), snaps the result to the mouse-sensitivity grid exactly like vanilla mouse input (yaw -= yaw % f3 with f3 = (sens * 0.6 + 0.2)^3 * 1.2), clamps pitch to 78-80, and applies the ReverseYaw and YawPosition settings. The tower modes are gated on the jump key. Cubecraft sets motionY 0.42 at most once per 50ms and whenever the player is within 0.1 of the ground. Watchdog jumps 0.409 on the ground and at the third air tick damps motionY by (motionY - 0.1) times a random factor from RandomUtil between 0.99089 and 0.99099. UpdatedNCP fires a 0.4196 impulse on air ticks where ticksExisted % 3 == 1 while standing still and falls back to the Watchdog profile while moving. WatchdogNew applies the same 0.4196 profile only while moving, gated by a 2000ms timer. IntaveFast jumps 0.405 with a (motionY - 0.08) damp at the fifth air tick and only runs when the forward key is released. VerusFast spams two fake C08PacketPlayerBlockPlacement packets per tick (one at BlockPos(-1, -1, -1) with direction byte 255 and a water bucket stack, one at the player position 1.5 blocks down with direction 1 and a stone stack) and rides motionY 0.70096 until a 5000ms timer elapses. The sprint logic has a dedicated Intave branch, BMCBoost runs the client timer at 1.105x while a speed potion is active, and LegitPlace replaces the placement path with a copy of the vanilla right-click mouse pipeline, including rightClickDelayTimer = 4, the ENTITY and BLOCK switch on the mouse-over target, and the empty-stack cleanup.

source Scaffold.java

Scaffold.java811 lines · JavaOriginal ↗
1
package intent.AquaDev.aqua.modules.world;
2
3
import de.Hero.settings.Setting;
4
import events.Event;
5
import events.EventType;
6
import events.listeners.EventPostRender2D;
7
import events.listeners.EventPreMotion;
8
import events.listeners.EventRender2D;
9
import events.listeners.EventRenderNameTags;
10
import events.listeners.EventSycItem;
11
import events.listeners.EventTick;
12
import events.listeners.EventUpdate;
13
import intent.AquaDev.aqua.Aqua;
14
import intent.AquaDev.aqua.gui.novolineOld.themesScreen.ThemeScreen;
15
import intent.AquaDev.aqua.modules.Category;
16
import intent.AquaDev.aqua.modules.Module;
17
import intent.AquaDev.aqua.modules.combat.Killaura;
18
import intent.AquaDev.aqua.modules.movement.Fly;
19
import intent.AquaDev.aqua.modules.visual.Blur;
20
import intent.AquaDev.aqua.modules.visual.ShaderMultiplier;
21
import intent.AquaDev.aqua.modules.visual.Shadow;
22
import intent.AquaDev.aqua.utils.RandomUtil;
23
import intent.AquaDev.aqua.utils.RenderUtil;
24
import intent.AquaDev.aqua.utils.RotationUtil;
25
import intent.AquaDev.aqua.utils.TimeUtil;
26
import java.awt.Color;
27
import java.util.ArrayList;
28
import java.util.List;
29
import net.minecraft.block.BlockAir;
30
import net.minecraft.block.BlockLiquid;
31
import net.minecraft.block.material.Material;
32
import net.minecraft.block.state.IBlockState;
33
import net.minecraft.client.Minecraft;
34
import net.minecraft.client.gui.GuiNewChat;
35
import net.minecraft.client.gui.ScaledResolution;
36
import net.minecraft.client.renderer.GlStateManager;
37
import net.minecraft.init.Blocks;
38
import net.minecraft.init.Items;
39
import net.minecraft.item.Item;
40
import net.minecraft.item.ItemBlock;
41
import net.minecraft.item.ItemStack;
42
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
43
import net.minecraft.network.play.client.C0APacketAnimation;
44
import net.minecraft.potion.Potion;
45
import net.minecraft.util.AxisAlignedBB;
46
import net.minecraft.util.BlockPos;
47
import net.minecraft.util.EnumFacing;
48
import net.minecraft.util.MathHelper;
49
import net.minecraft.util.MovingObjectPosition;
50
import net.minecraft.util.Vec3;
51
import org.lwjgl.opengl.GL11;
52
53
public class Scaffold extends Module {
54
   private BlockPos espPos = null;
55
   private final Scaffold.BlackList blackList = new Scaffold.BlackList();
56
   public float[] rots = new float[2];
57
   public float[] lastRots = new float[2];
58
   public int slot;
59
   public MovingObjectPosition objectPosition = null;
60
   private final ArrayList<Vec3> lastPositions = new ArrayList<>();
61
   private double[] xyz = new double[3];
62
   public static Scaffold.BlockData data;
63
   TimeUtil timeUtil = new TimeUtil();
64
   private double posY;
65
   public boolean down;
66
   private int offGround = 0;
67
68
   public Scaffold() {
69
      super("Scaffold", Module.Type.World, "Scaffold", 0, Category.World);
70
      Aqua.setmgr.register(new Setting("Sprint", this, false));
71
      Aqua.setmgr.register(new Setting("EnableCalculate", this, false));
72
      Aqua.setmgr.register(new Setting("EnableSneak", this, false));
73
      Aqua.setmgr.register(new Setting("BlockCount", this, true));
74
      Aqua.setmgr.register(new Setting("BlockESP", this, true));
75
      Aqua.setmgr.register(new Setting("Intave", this, false));
76
      Aqua.setmgr.register(new Setting("Swing", this, false));
77
      Aqua.setmgr.register(new Setting("Down", this, false));
78
      Aqua.setmgr.register(new Setting("SameY", this, false));
79
      Aqua.setmgr.register(new Setting("Expand", this, false));
80
      Aqua.setmgr.register(new Setting("AutoDisable", this, false));
81
      Aqua.setmgr.register(new Setting("BMCBoost", this, false));
82
      Aqua.setmgr.register(new Setting("LegitPlace", this, false));
83
      Aqua.setmgr.register(new Setting("ReverseYaw", this, false));
84
      Aqua.setmgr.register(new Setting("SneakModify", this, 1.0, 0.3, 1.0, false));
85
      Aqua.setmgr.register(new Setting("Expandlength", this, 8.0, 0.0, 25.0, false));
86
      Aqua.setmgr.register(new Setting("YawPosition", this, 90.0, 0.0, 380.0, false));
87
      Aqua.setmgr.register(new Setting("RotationMode", this, "Static", new String[]{"Static", "Calculated"}));
88
      Aqua.setmgr.register(new Setting("Shader", this, "Glow", new String[]{"Glow", "Shadow", "Jello"}));
89
      Aqua.setmgr
90
         .register(new Setting("Tower", this, "None", new String[]{"None", "Watchdog", "VerusFast", "IntaveFast", "Cubecraft", "UpdatedNCP", "WatchdogNew"}));
91
   }
92
93
   @Override
94
   public void onEnable() {
95
      if (Aqua.setmgr.getSetting("ScaffoldEnableCalculate").isState()) {
96
         mc.thePlayer.rotationPitchHead = 82.0F;
97
         mc.thePlayer.rotationYawHead = 180.0F;
98
      }
99
100
      this.offGround = 0;
101
      if (Aqua.setmgr.getSetting("ScaffoldEnableSneak").isState()) {
102
         mc.gameSettings.keyBindSneak.pressed = true;
103
      }
104
105
      this.posY = mc.thePlayer.posY;
106
      super.onEnable();
107
   }
108
109
   @Override
110
   public void onDisable() {
111
      mc.timer.timerSpeed = 1.0F;
112
      mc.gameSettings.keyBindSneak.pressed = false;
113
      super.onDisable();
114
   }
115
116
   @Override
117
   public void onEvent(Event event) {
118
      if (event instanceof EventRenderNameTags && Aqua.setmgr.getSetting("ScaffoldBlockESP").isState()) {
119
         BlockPos pos = new BlockPos(mc.thePlayer.posX, mc.thePlayer.posY - 1.0, mc.thePlayer.posZ);
120
         this.espPos = mc.theWorld.getBlockState(pos).getBlock().isFullBlock() ? pos : this.espPos;
121
         if (this.espPos != null) {
122
            GL11.glEnable(3042);
123
            GL11.glBlendFunc(770, 771);
124
            GL11.glEnable(2848);
125
            GL11.glDisable(2929);
126
            GL11.glDisable(3553);
127
            GlStateManager.disableCull();
128
            GL11.glDepthMask(false);
129
            Color color = new Color(Aqua.setmgr.getSetting("HUDColor").getColor());
130
            Blur.drawBlurred(
131
               () -> RenderUtil.drawBlockESP(
132
                     this.espPos, (float)color.getRed() / 255.0F, (float)color.getGreen() / 255.0F, (float)color.getBlue() / 255.0F, 1.0F, 0.0F, 1.0F
133
                  ),
134
               false
135
            );
136
            RenderUtil.drawBlockESP(
137
               this.espPos, (float)color.getRed() / 255.0F, (float)color.getGreen() / 255.0F, (float)color.getBlue() / 255.0F, 0.39215687F, 0.0F, 1.0F
138
            );
139
            GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
140
            GL11.glDepthMask(true);
141
            GlStateManager.enableCull();
142
            GL11.glEnable(3553);
143
            GL11.glEnable(2929);
144
            GL11.glDisable(3042);
145
            GL11.glBlendFunc(770, 771);
146
            GL11.glDisable(2848);
147
         }
148
      }
149
150
      if (event instanceof EventTick) {
151
         if (mc.thePlayer.onGround) {
152
            this.offGround = 0;
153
         } else {
154
            ++this.offGround;
155
         }
156
      }
157
158
      if (event instanceof EventRender2D && Aqua.setmgr.getSetting("ScaffoldBlockCount").isState()) {
159
         ScaledResolution sr = new ScaledResolution(mc);
160
         if (!GuiNewChat.animatedChatOpen) {
161
            if (Aqua.setmgr.getSetting("ScaffoldShader").getCurrentMode().equalsIgnoreCase("Jello") && !ThemeScreen.themeHero) {
162
               ShaderMultiplier.drawGlowESP(
163
                  () -> RenderUtil.drawRoundedRect2Alpha(
164
                        (double)((float)sr.getScaledWidth() / 2.0F - 18.0F),
165
                        (double)(sr.getScaledHeight() - 85),
166
                        (double)Aqua.INSTANCE.novolineSmall.getStringWidth(getBlockCount() + "     Blocks"),
167
                        15.0,
168
                        3.0,
169
                        new Color(5, 5, 5, 255)
170
                     ),
171
                  false
172
               );
173
               ShaderMultiplier.drawGlowESP(
174
                  () -> RenderUtil.drawTriangleFilled2(
175
                        (float)sr.getScaledWidth() / 2.0F - 4.0F, (float)(sr.getScaledHeight() - 70), 5.0F, 5.0F, new Color(5, 5, 5, 255).getRGB()
176
                     ),
177
                  false
178
               );
179
               RenderUtil.drawRoundedRect2Alpha(
180
                  (double)((float)sr.getScaledWidth() / 2.0F - 18.0F),
181
                  (double)(sr.getScaledHeight() - 85),
182
                  (double)Aqua.INSTANCE.novolineSmall.getStringWidth(getBlockCount() + "     Blocks"),
183
                  15.0,
184
                  3.0,
185
                  new Color(40, 40, 40, 255)
186
               );
187
               RenderUtil.drawTriangleFilled2(
188
                  (float)sr.getScaledWidth() / 2.0F - 4.0F, (float)(sr.getScaledHeight() - 70), 5.0F, 5.0F, new Color(40, 40, 40, 255).getRGB()
189
               );
190
               Aqua.INSTANCE
191
                  .novolineSmall
192
                  .drawString(getBlockCount() + "", (float)sr.getScaledWidth() / 2.0F - 16.0F, (float)sr.getScaledHeight() - 81.0F, -1);
193
               Aqua.INSTANCE
194
                  .novolineSmall
195
                  .drawString(
196
                     "Blocks",
197
                     (float)Aqua.INSTANCE.novolineSmall.getStringWidth(getBlockCount() + "") + (float)sr.getScaledWidth() / 2.0F - 12.0F,
198
                     (float)(sr.getScaledHeight() - 81),
199
                     Color.gray.getRGB()
200
                  );
201
            }
202
         } else if (Aqua.setmgr.getSetting("ScaffoldShader").getCurrentMode().equalsIgnoreCase("Jello") && !ThemeScreen.themeHero) {
203
            Shadow.drawGlow(
204
               () -> RenderUtil.drawRoundedRect2Alpha(
205
                     (double)((float)sr.getScaledWidth() / 2.0F - 18.0F),
206
                     (double)(sr.getScaledHeight() - 80),
207
                     (double)Aqua.INSTANCE.novolineSmall.getStringWidth(getBlockCount() + "     Blocks"),
208
                     15.0,
209
                     3.0,
210
                     new Color(40, 40, 40, 255)
211
                  ),
212
               false
213
            );
214
            Shadow.drawGlow(
215
               () -> RenderUtil.drawTriangleFilled2(
216
                     (float)sr.getScaledWidth() / 2.0F - 4.0F, (float)(sr.getScaledHeight() - 65), 5.0F, 5.0F, new Color(40, 40, 40, 255).getRGB()
217
                  ),
218
               false
219
            );
220
            RenderUtil.drawRoundedRect2Alpha(
221
               (double)((float)sr.getScaledWidth() / 2.0F - 18.0F),
222
               (double)(sr.getScaledHeight() - 80),
223
               (double)Aqua.INSTANCE.novolineSmall.getStringWidth(getBlockCount() + "     Blocks"),
224
               15.0,
225
               3.0,
226
               new Color(40, 40, 40, 255)
227
            );
228
            RenderUtil.drawTriangleFilled2(
229
               (float)sr.getScaledWidth() / 2.0F - 4.0F, (float)(sr.getScaledHeight() - 65), 5.0F, 5.0F, new Color(40, 40, 40, 255).getRGB()
230
            );
231
            Aqua.INSTANCE.novolineSmall.drawString(getBlockCount() + "", (float)sr.getScaledWidth() / 2.0F - 16.0F, (float)sr.getScaledHeight() - 76.5F, -1);
232
            Aqua.INSTANCE
233
               .novolineSmall
234
               .drawString(
235
                  "Blocks",
236
                  (float)Aqua.INSTANCE.novolineSmall.getStringWidth(getBlockCount() + "") + (float)sr.getScaledWidth() / 2.0F - 12.0F,
237
                  (float)sr.getScaledHeight() - 76.5F,
238
                  Color.gray.getRGB()
239
               );
240
         }
241
      }
242
243
      if (event instanceof EventRender2D && Aqua.setmgr.getSetting("ScaffoldBlockCount").isState()) {
244
         ScaledResolution sr = new ScaledResolution(mc);
245
         if (ThemeScreen.themeLoaded && ThemeScreen.themeHero) {
246
            RenderUtil.drawRoundedRect2Alpha(
247
               (double)((int)((float)sr.getScaledWidth() / 2.0F + 10.0F)),
248
               (double)((int)((float)sr.getScaledHeight() / 2.0F - 5.0F)),
249
               (double)(Aqua.INSTANCE.roboto2.getStringWidth(" " + getBlockCount()) + 1),
250
               13.0,
251
               0.0,
252
               new Color(0, 0, 0, 255)
253
            );
254
            RenderUtil.drawRoundedRect2Alpha(
255
               (double)((int)((float)sr.getScaledWidth() / 2.0F + 10.0F)),
256
               (double)((int)((float)sr.getScaledHeight() / 2.0F - 6.0F)),
257
               (double)(Aqua.INSTANCE.roboto2.getStringWidth(" " + getBlockCount()) + 1),
258
               1.0,
259
               0.0,
260
               new Color(6, 226, 70, 160)
261
            );
262
            Aqua.INSTANCE
263
               .roboto2
264
               .drawString(
265
                  getBlockCount() + "",
266
                  (float)((int)((float)sr.getScaledWidth() / 2.0F + 11.0F)),
267
                  (float)((int)((float)sr.getScaledHeight() / 2.0F - 6.0F)),
268
                  -1
269
               );
270
         } else if (!Aqua.setmgr.getSetting("ScaffoldShader").getCurrentMode().equalsIgnoreCase("Jello")
271
            && Aqua.setmgr.getSetting("ScaffoldShader").getCurrentMode().equalsIgnoreCase("Shadow")) {
272
            if (!Aqua.setmgr.getSetting("ScaffoldShader").getCurrentMode().equalsIgnoreCase("Jello")) {
273
               Shadow.drawGlow(
274
                  () -> RenderUtil.drawRoundedRect2Alpha(
275
                        (double)((int)((float)sr.getScaledWidth() / 2.0F - 25.0F)),
276
                        (double)((int)((float)sr.getScaledHeight() / 2.0F + 20.0F)),
277
                        (double)(mc.fontRendererObj.getStringWidth("Blocks: " + getBlockCount()) + 5),
278
                        13.0,
279
                        5.0,
280
                        Color.BLACK
281
                     ),
282
                  false
283
               );
284
            } else {
285
               ShaderMultiplier.drawGlowESP(
286
                  () -> RenderUtil.drawRoundedRect2Alpha(
287
                        (double)((int)((float)sr.getScaledWidth() / 2.0F - 25.0F)),
288
                        (double)((int)((float)sr.getScaledHeight() / 2.0F + 20.0F)),
289
                        (double)(mc.fontRendererObj.getStringWidth("Blocks: " + getBlockCount()) + 5),
290
                        13.0,
291
                        5.0,
292
                        new Color(Aqua.setmgr.getSetting("HUDColor").getColor())
293
                     ),
294
                  false
295
               );
296
            }
297
298
            Blur.drawBlurred(
299
               () -> RenderUtil.drawRoundedRect(
300
                     (double)((int)((float)sr.getScaledWidth() / 2.0F - 25.0F)),
301
                     (double)((int)((float)sr.getScaledHeight() / 2.0F + 20.0F)),
302
                     (double)(mc.fontRendererObj.getStringWidth("Blocks: " + getBlockCount()) + 5),
303
                     13.0,
304
                     5.0,
305
                     new Color(0, 0, 0, 120).getRGB()
306
                  ),
307
               false
308
            );
309
         }
310
      }
311
312
      if (event instanceof EventPostRender2D) {
313
         ScaledResolution sr = new ScaledResolution(mc);
314
         if (Aqua.setmgr.getSetting("ScaffoldBlockCount").isState()
315
            && !Aqua.setmgr.getSetting("ScaffoldShader").getCurrentMode().equalsIgnoreCase("Jello")
316
            && (!ThemeScreen.themeLoaded || !ThemeScreen.themeHero)
317
            && (
318
               Aqua.setmgr.getSetting("ScaffoldShader").getCurrentMode().equalsIgnoreCase("Shadow")
319
                  || Aqua.setmgr.getSetting("ScaffoldShader").getCurrentMode().equalsIgnoreCase("Glow")
320
            )) {
321
            RenderUtil.drawRoundedRect2Alpha(
322
               (double)((int)((float)sr.getScaledWidth() / 2.0F - 25.0F)),
323
               (double)((int)((float)sr.getScaledHeight() / 2.0F + 20.0F)),
324
               (double)(mc.fontRendererObj.getStringWidth("Blocks: " + getBlockCount()) + 5),
325
               13.0,
326
               5.0,
327
               new Color(0, 0, 0, 70)
328
            );
329
            Aqua.INSTANCE
330
               .comfortaa4
331
               .drawString(
332
                  "Blocks : " + getBlockCount(),
333
                  (float)((int)((float)sr.getScaledWidth() / 2.0F - 20.0F)),
334
                  (float)((int)((float)sr.getScaledHeight() / 2.0F + 23.0F)),
335
                  -1
336
               );
337
         }
338
      }
339
340
      if (event instanceof EventSycItem && this.getBlockSlot() != -1) {
341
         ((EventSycItem)event).slot = this.slot = this.getBlockSlot();
342
      }
343
344
      if (event instanceof EventUpdate && event.type == EventType.PRE) {
345
         this.objectPosition = null;
346
         data = this.find(new Vec3(0.0, 0.0, 0.0));
347
      }
348
349
      if (event instanceof EventUpdate) {
350
         data = this.find(new Vec3(0.0, 0.0, 0.0));
351
         if (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed) != null) {
352
            if (Aqua.setmgr.getSetting("ScaffoldBMCBoost").isState()) {
353
               mc.timer.timerSpeed = 1.105F;
354
            }
355
         } else {
356
            mc.timer.timerSpeed = 1.0F;
357
         }
358
359
         if (Aqua.setmgr.getSetting("ScaffoldAutoDisable").isState() && Killaura.target != null) {
360
            Aqua.moduleManager.getModuleByName("Scaffold").setState(false);
361
         }
362
      }
363
364
      if (event instanceof EventUpdate) {
365
         if (Aqua.setmgr.getSetting("ScaffoldTower").getCurrentMode().equalsIgnoreCase("Cubecraft") && mc.gameSettings.keyBindJump.pressed) {
366
            if (this.timeUtil.hasTimePassed(50L)) {
367
               mc.thePlayer.motionY = 0.42;
368
               this.timeUtil.reset();
369
            }
370
371
            if (isOnGround(0.1)) {
372
               mc.thePlayer.motionY = 0.42;
373
            }
374
         }
375
376
         if (Aqua.setmgr.getSetting("ScaffoldTower").getCurrentMode().equalsIgnoreCase("Watchdog") && mc.gameSettings.keyBindJump.pressed) {
377
            if (mc.thePlayer.onGround) {
378
               mc.thePlayer.motionY = 0.409;
379
            }
380
381
            if (this.offGround == 3) {
382
               float random1 = RandomUtil.instance.nextFloat(0.9908900590734863, 0.9909900590734863);
383
               mc.thePlayer.motionY = (mc.thePlayer.motionY - 0.1) * (double)random1;
384
            }
385
         }
386
387
         if (Aqua.setmgr.getSetting("ScaffoldTower").getCurrentMode().equalsIgnoreCase("UpdatedNCP") && mc.gameSettings.keyBindJump.pressed) {
388
            if (!mc.thePlayer.isMoving()) {
389
               if (this.timeUtil.hasReached(2000L)) {
390
                  this.timeUtil.reset();
391
               } else if (mc.thePlayer.ticksExisted % 3 == 1 && this.offGround > 1 && !mc.thePlayer.onGround) {
392
                  mc.thePlayer.motionY = 0.4196;
393
               }
394
395
               this.timeUtil.reset();
396
            } else {
397
               if (mc.thePlayer.onGround) {
398
                  mc.thePlayer.motionY = 0.409;
399
               }
400
401
               if (this.offGround == 3) {
402
                  float random1 = RandomUtil.instance.nextFloat(0.9908900590734863, 0.9909900590734863);
403
                  mc.thePlayer.motionY = (mc.thePlayer.motionY - 0.1) * (double)random1;
404
               }
405
            }
406
         }
407
408
         if (Aqua.setmgr.getSetting("ScaffoldTower").getCurrentMode().equalsIgnoreCase("WatchdogNew")
409
            && mc.gameSettings.keyBindJump.pressed
410
            && mc.thePlayer.isMoving()) {
411
            if (this.timeUtil.hasReached(2000L)) {
412
               this.timeUtil.reset();
413
            } else if (mc.thePlayer.ticksExisted % 3 == 1 && this.offGround > 1 && !mc.thePlayer.onGround) {
414
               mc.thePlayer.motionY = 0.4196;
415
            }
416
417
            this.timeUtil.reset();
418
         }
419
420
         if (Aqua.setmgr.getSetting("ScaffoldTower").getCurrentMode().equalsIgnoreCase("IntaveFast")
421
            && mc.gameSettings.keyBindJump.pressed
422
            && !mc.gameSettings.keyBindForward.pressed) {
423
            if (mc.thePlayer.onGround) {
424
               mc.thePlayer.motionY = 0.405;
425
            }
426
427
            if (this.offGround == 5) {
428
               float random1 = RandomUtil.instance.nextFloat(0.9908900590734863, 0.9909900590734863);
429
               mc.thePlayer.motionY = (mc.thePlayer.motionY - 0.08) * (double)random1;
430
            }
431
         }
432
433
         if (Aqua.setmgr.getSetting("ScaffoldTower").getCurrentMode().equalsIgnoreCase("VerusFast")) {
434
            if (mc.gameSettings.keyBindJump.pressed) {
435
               Fly.sendPacketUnlogged(new C08PacketPlayerBlockPlacement(new BlockPos(-1, -1, -1), 255, new ItemStack(Items.water_bucket), 0.0F, 0.5F, 0.0F));
436
               Fly.sendPacketUnlogged(
437
                  new C08PacketPlayerBlockPlacement(
438
                     new BlockPos(Fly.getX(), Fly.getY() - 1.5, Fly.getZ()),
439
                     1,
440
                     new ItemStack(Blocks.stone.getItem(mc.theWorld, new BlockPos(-1, -1, -1))),
441
                     0.0F,
442
                     0.94F,
443
                     0.0F
444
                  )
445
               );
446
               if (this.timeUtil.hasReached(5000L)) {
447
                  this.timeUtil.reset();
448
               } else {
449
                  mc.thePlayer.motionY = 0.70096;
450
               }
451
            } else {
452
               mc.timer.timerSpeed = 1.0F;
453
            }
454
455
            this.timeUtil.reset();
456
         }
457
458
         if (!Aqua.setmgr.getSetting("DisablerModes").getCurrentMode().equalsIgnoreCase("Intave")) {
459
            if (Aqua.setmgr.getSetting("ScaffoldSprint").isState()) {
460
               mc.gameSettings.keyBindSprint.pressed = true;
461
            } else {
462
               mc.thePlayer.setSprinting(false);
463
            }
464
         } else if (Aqua.setmgr.getSetting("ScaffoldSprint").isState()
465
            && Aqua.setmgr.getSetting("DisablerModes").getCurrentMode().equalsIgnoreCase("Intave")
466
            && !mc.gameSettings.keyBindJump.pressed) {
467
            mc.thePlayer.setSprinting(true);
468
         } else {
469
            mc.thePlayer.setSprinting(false);
470
         }
471
472
         if (!Aqua.setmgr.getSetting("ScaffoldLegitPlace").isState()) {
473
            if (Aqua.setmgr.getSetting("ScaffoldSameY").isState() && mc.thePlayer.onGround) {
474
            }
475
476
            if (Aqua.setmgr.getSetting("ScaffoldDown").isState()) {
477
               if (mc.gameSettings.keyBindSneak.pressed) {
478
                  this.down = true;
479
                  this.posY = mc.thePlayer.posY - 1.0;
480
               } else {
481
                  this.down = false;
482
                  this.posY = mc.thePlayer.posY;
483
               }
484
            }
485
486
            data = this.find(new Vec3(0.0, 0.0, 0.0));
487
            if (data != null && this.getBlockSlot() != -1) {
488
               BlockPos blockpos = mc.objectMouseOver.getBlockPos();
489
               mc.playerController.updateController();
490
               Vec3 hitVec = new Vec3(Scaffold.BlockData.getPos())
491
                  .addVector(0.5, 0.5, 0.5)
492
                  .add(new Vec3(Scaffold.BlockData.getFacing().getDirectionVec()).multi(0.5));
493
               if (this.slot != -1
494
                  && mc.playerController
495
                     .onPlayerRightClick(
496
                        mc.thePlayer,
497
                        mc.theWorld,
498
                        mc.thePlayer.inventory.getStackInSlot(this.slot),
499
                        Scaffold.BlockData.getPos(),
500
                        Scaffold.BlockData.getFacing(),
501
                        hitVec
502
                     )) {
503
                  if (Aqua.setmgr.getSetting("ScaffoldSwing").isState()) {
504
                     mc.thePlayer.swingItem();
505
                  } else {
506
                     mc.getNetHandler().addToSendQueue(new C0APacketAnimation());
507
                  }
508
               }
509
            }
510
511
            BlockPos var11 = mc.objectMouseOver.getBlockPos();
512
         } else {
513
            data = this.find(new Vec3(0.0, 0.0, 0.0));
514
            BlockPos blockPos = new BlockPos(mc.thePlayer.posX, mc.thePlayer.posY - 1.0, mc.thePlayer.posZ);
515
            if (mc.theWorld.getBlockState(blockPos).getBlock() == Blocks.air) {
516
               mc.gameSettings.keyBindSneak.pressed = true;
517
            } else if (!Aqua.setmgr.getSetting("DisablerModes").getCurrentMode().equalsIgnoreCase("Intave")) {
518
               mc.gameSettings.keyBindSneak.pressed = false;
519
            }
520
521
            if (mc.gameSettings.keyBindJump.pressed) {
522
               mc.thePlayer.setSprinting(false);
523
            }
524
525
            if (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed) != null || !Aqua.setmgr.getSetting("ScaffoldSprint").isState()) {
526
               mc.thePlayer.setSprinting(false);
527
               mc.gameSettings.keyBindSprint.pressed = false;
528
            }
529
530
            if (mc.theWorld.getBlockState(blockPos).getBlock() == Blocks.air) {
531
               this.rightClickMouse(mc.thePlayer.inventory.getStackInSlot(this.slot), this.slot);
532
            }
533
534
            if (mc.gameSettings.keyBindJump.pressed) {
535
               mc.gameSettings.keyBindSneak.pressed = true;
536
            } else {
537
               mc.gameSettings.keyBindSneak.pressed = mc.theWorld.getBlockState(blockPos).getBlock() == Blocks.air;
538
            }
539
         }
540
      }
541
542
      if (event instanceof EventPreMotion) {
543
         if (data == null) {
544
            return;
545
         }
546
547
         float[] rotation2 = rotationrecode2(data);
548
         if (Aqua.setmgr.getSetting("ScaffoldRotationMode").getCurrentMode().equalsIgnoreCase("Static")) {
549
            RotationUtil.yaw = mc.thePlayer.rotationYawHead;
550
            RotationUtil.pitch = mc.thePlayer.rotationPitchHead;
551
            ((EventPreMotion)event).setYaw(mc.thePlayer.rotationYaw + 180.0F);
552
            ((EventPreMotion)event).setPitch(82.0F);
553
         }
554
555
         if (Aqua.setmgr.getSetting("ScaffoldRotationMode").getCurrentMode().equalsIgnoreCase("Calculated")) {
556
            RotationUtil.yaw = mc.thePlayer.rotationYawHead;
557
            RotationUtil.pitch = mc.thePlayer.rotationPitchHead;
558
            ((EventPreMotion)event).setYaw(rotation2[0]);
559
            ((EventPreMotion)event).setPitch(rotation2[1]);
560
         }
561
      }
562
   }
563
564
   private Vec3 getPositionByFace(BlockPos position, EnumFacing facing) {
565
      Vec3 offset = new Vec3(
566
         (double)facing.getDirectionVec().getX() / 2.0, (double)facing.getDirectionVec().getY() / 2.0, (double)facing.getDirectionVec().getZ() / 2.0
567
      );
568
      Vec3 point = new Vec3((double)position.getX() + 0.5, (double)position.getY() + 0.5, (double)position.getZ() + 0.5);
569
      return point.add(offset);
570
   }
571
572
   private boolean rayTrace(Vec3 origin, Vec3 position) {
573
      Vec3 difference = position.subtract(origin);
574
      int steps = 10;
575
      double x = difference.xCoord / (double)steps;
576
      double y = difference.yCoord / (double)steps;
577
      double z = difference.zCoord / (double)steps;
578
      Vec3 point = origin;
579
580
      for(int i = 0; i < steps; ++i) {
581
         BlockPos blockPosition = new BlockPos(point = point.addVector(x, y, z));
582
         IBlockState blockState = Minecraft.getMinecraft().theWorld.getBlockState(blockPosition);
583
         if (!(blockState.getBlock() instanceof BlockLiquid) && !(blockState.getBlock() instanceof BlockAir)) {
584
            AxisAlignedBB boundingBox = blockState.getBlock().getCollisionBoundingBox(Minecraft.getMinecraft().theWorld, blockPosition, blockState);
585
            if (boundingBox == null) {
586
               boundingBox = new AxisAlignedBB(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
587
            }
588
589
            if (boundingBox.offset((double)blockPosition.getX(), (double)blockPosition.getY(), (double)blockPosition.getZ()).isVecInside(point)) {
590
               return true;
591
            }
592
         }
593
      }
594
595
      return false;
596
   }
597
598
   private Scaffold.BlockData find(Vec3 offset3) {
599
      double xDiff = mc.thePlayer.posX - mc.thePlayer.prevPosX;
600
      double zDiff = mc.thePlayer.posZ - mc.thePlayer.prevPosZ;
601
      float expand = (float)Aqua.setmgr.getSetting("ScaffoldExpandlength").getCurrentNumber();
602
      double x = Aqua.setmgr.getSetting("ScaffoldExpand").isState() ? mc.thePlayer.posX + xDiff * (double)expand : mc.thePlayer.posX;
603
      double y = !Aqua.setmgr.getSetting("ScaffoldSameY").isState() && !Aqua.setmgr.getSetting("ScaffoldDown").isState()
604
         ? mc.thePlayer.posY
605
         : (mc.gameSettings.keyBindForward.pressed ? this.posY : mc.thePlayer.posY);
606
      double z = Aqua.setmgr.getSetting("ScaffoldExpand").isState() ? mc.thePlayer.posZ + zDiff * (double)expand : mc.thePlayer.posZ;
607
      EnumFacing[] invert = new EnumFacing[]{EnumFacing.UP, EnumFacing.DOWN, EnumFacing.SOUTH, EnumFacing.NORTH, EnumFacing.EAST, EnumFacing.WEST};
608
      BlockPos position = new BlockPos(new Vec3(x, y, z).add(offset3)).offset(EnumFacing.DOWN);
609
610
      for(EnumFacing facing : EnumFacing.values()) {
611
         BlockPos offset = position.offset(facing);
612
         if (!(mc.theWorld.getBlockState(offset).getBlock() instanceof BlockAir)
613
            && !this.rayTrace(mc.thePlayer.getLook(0.0F), this.getPositionByFace(offset, invert[facing.ordinal()]))) {
614
            return new Scaffold.BlockData(invert[facing.ordinal()], offset);
615
         }
616
      }
617
618
      BlockPos[] offsets = new BlockPos[]{
619
         new BlockPos(-1, 0, 0),
620
         new BlockPos(1, 0, 0),
621
         new BlockPos(0, 0, -1),
622
         new BlockPos(0, 0, 1),
623
         new BlockPos(0, 0, 2),
624
         new BlockPos(0, 0, -2),
625
         new BlockPos(2, 0, 0),
626
         new BlockPos(-2, 0, 0)
627
      };
628
629
      for(BlockPos offset : offsets) {
630
         BlockPos offsetPos = position.add(offset.getX(), 0, offset.getZ());
631
         if (mc.theWorld.getBlockState(offsetPos).getBlock() instanceof BlockAir) {
632
            for(EnumFacing facing : EnumFacing.values()) {
633
               BlockPos offset2 = offsetPos.offset(facing);
634
               if (!(mc.theWorld.getBlockState(offset2).getBlock() instanceof BlockAir)
635
                  && !this.rayTrace(mc.thePlayer.getLook(0.01F), this.getPositionByFace(offset, invert[facing.ordinal()]))) {
636
                  return new Scaffold.BlockData(invert[facing.ordinal()], offset2);
637
               }
638
            }
639
         }
640
      }
641
642
      return null;
643
   }
644
645
   public int getBlockSlot() {
646
      for(int i = 0; i < 9; ++i) {
647
         ItemStack s = mc.thePlayer.inventory.getStackInSlot(i);
648
         if (s != null && s.getItem() instanceof ItemBlock) {
649
            Scaffold.BlackList var10000 = this.blackList;
650
            s.getItem();
651
            if (var10000.isNotBlackListed(Item.itemRegistry.getNameForObject(s.getItem()).toString())) {
652
               return i;
653
            }
654
         }
655
      }
656
657
      return -1;
658
   }
659
660
   public static float[] mouseSens(float yaw, float pitch) {
661
      float f2 = Minecraft.getMinecraft().gameSettings.mouseSensitivity * 0.6F + 0.2F;
662
      float f3 = f2 * f2 * f2 * 1.2F;
663
      yaw -= yaw % f3;
664
      pitch -= pitch % (f3 * f2);
665
      return new float[]{yaw, pitch};
666
   }
667
668
   public static float updateRotation(float current, float needed, float speed) {
669
      float f = MathHelper.wrapAngleTo180_float(needed - current);
670
      if (f > speed) {
671
         f = speed;
672
      }
673
674
      if (f < -speed) {
675
         f = -speed;
676
      }
677
678
      return current + f;
679
   }
680
681
   public static float[] rotationrecode2(Scaffold.BlockData blockData) {
682
      double x = (double)Scaffold.BlockData.getPos().getX() + 0.5 - mc.thePlayer.posX + (double)Scaffold.BlockData.getFacing().getFrontOffsetX() / 2.0;
683
      double z = (double)Scaffold.BlockData.getPos().getZ() + 0.5 - mc.thePlayer.posZ + (double)Scaffold.BlockData.getFacing().getFrontOffsetZ() / 2.0;
684
      double y = (double)Scaffold.BlockData.getPos().getY() + 0.6;
685
      double ymax = mc.thePlayer.posY + (double)mc.thePlayer.getEyeHeight() - y;
686
      double allmax = (double)MathHelper.sqrt_double(x * x + z * z);
687
      float yaw = Aqua.setmgr.getSetting("ScaffoldReverseYaw").isState()
688
         ? (float)(Math.atan2(z, x) * 180.0 / Math.PI) - 270.0F
689
         : (float)(Math.atan2(z, x) * 180.0 / Math.PI) - (float)Aqua.setmgr.getSetting("ScaffoldYawPosition").getCurrentNumber();
690
      float pitch = (float)(Math.atan2(ymax, allmax) * 180.0 / Math.PI);
691
      if (yaw < 0.0F) {
692
         yaw += 360.0F;
693
      }
694
695
      float f2 = Minecraft.getMinecraft().gameSettings.mouseSensitivity * 0.6F + 0.2F;
696
      float f3 = f2 * f2 * f2 * 1.2F;
697
      yaw -= yaw % f3;
698
      pitch -= pitch % (f3 * f2);
699
      return new float[]{yaw, MathHelper.clamp_float(pitch, 78.0F, 80.0F)};
700
   }
701
702
   public void rightClickMouse(ItemStack itemstack, int slot) {
703
      if (!mc.playerController.getIsHittingBlock()) {
704
         mc.rightClickDelayTimer = 4;
705
706
         try {
707
            switch(mc.objectMouseOver.typeOfHit) {
708
               case ENTITY:
709
                  if (!mc.playerController.isPlayerRightClickingOnEntity(mc.thePlayer, mc.objectMouseOver.entityHit, mc.objectMouseOver)
710
                     && mc.playerController.interactWithEntitySendPacket(mc.thePlayer, mc.objectMouseOver.entityHit)) {
711
                  }
712
                  break;
713
               case BLOCK:
714
                  BlockPos blockpos = mc.objectMouseOver.getBlockPos();
715
                  if (mc.theWorld.getBlockState(blockpos).getBlock().getMaterial() != Material.air) {
716
                     if (itemstack == null) {
717
                        boolean var10000 = false;
718
                     }
719
720
                     if (mc.playerController
721
                        .onPlayerRightClick(mc.thePlayer, mc.theWorld, itemstack, blockpos, mc.objectMouseOver.sideHit, mc.objectMouseOver.hitVec)) {
722
                        if (!Aqua.setmgr.getSetting("ScaffoldSwing").isState()) {
723
                           mc.thePlayer.sendQueue.addToSendQueue(new C0APacketAnimation());
724
                        } else {
725
                           mc.thePlayer.swingItem();
726
                        }
727
                     }
728
729
                     if (itemstack == null) {
730
                        return;
731
                     }
732
733
                     if (itemstack.stackSize == 0) {
734
                        mc.thePlayer.inventory.mainInventory[slot] = null;
735
                     }
736
                  }
737
            }
738
         } catch (NullPointerException var5) {
739
         }
740
      }
741
   }
742
743
   public static int getBlockCount() {
744
      int itemCount = 0;
745
746
      for(int i = 0; i < 9; ++i) {
747
         ItemStack stack = mc.thePlayer.inventory.getStackInSlot(i);
748
         if (stack != null && stack.getItem() != null && stack.getItem() instanceof ItemBlock) {
749
            itemCount += stack.stackSize;
750
         }
751
      }
752
753
      return itemCount;
754
   }
755
756
   public static boolean isOnGround(double height) {
757
      return !mc.theWorld.getCollidingBoundingBoxes(mc.thePlayer, mc.thePlayer.getEntityBoundingBox().offset(0.0, -height, 0.0)).isEmpty();
758
   }
759
760
   class BlackList {
761
      List<String> stringids = new ArrayList<>();
762
763
      public BlackList() {
764
         this.addID("minecraft:wooden_slab");
765
         this.addID("minecraft:stone_slab");
766
         this.addID("minecraft:banner");
767
         this.addID("minecraft:beacon");
768
         this.addID("minecraft:trapped_chest");
769
         this.addID("minecraft:chest");
770
         this.addID("minecraft:anvil");
771
         this.addID("minecraft:enchanting_table");
772
         this.addID("minecraft:crafting_table");
773
         this.addID("minecraft:furnace");
774
         this.addID("minecraft:banner");
775
         this.addID("minecraft:wall_banner");
776
         this.addID("minecraft:standing_banner");
777
         this.addID("minecraft:web");
778
         this.addID("minecraft:sapling");
779
      }
780
781
      public List<String> getStringids() {
782
         return this.stringids;
783
      }
784
785
      public boolean isNotBlackListed(String blockID) {
786
         return !this.stringids.contains(blockID);
787
      }
788
789
      public void addID(String id) {
790
         this.stringids.add(id);
791
      }
792
   }
793
794
   public static class BlockData {
795
      private static EnumFacing facing;
796
      private static BlockPos pos;
797
798
      public BlockData(EnumFacing facing, BlockPos pos) {
799
         Scaffold.BlockData.facing = facing;
800
         Scaffold.BlockData.pos = pos;
801
      }
802
803
      public static EnumFacing getFacing() {
804
         return facing;
805
      }
806
807
      public static BlockPos getPos() {
808
         return pos;
809
      }
810
   }
811
}

What this file does

The module itself. Everything the scaffold does lives here: the single onEvent(Event) dispatcher, the block search, the ray trace, the placement call, the rotation override, the tower profiles, the HUD rendering and the blacklist. There is no external block-search helper; find(), rayTrace() and getPositionByFace() are private methods of this class, which is why the module only imports four utils from intent.AquaDev.aqua.utils (RotationUtil, RandomUtil, TimeUtil, RenderUtil). Placement state is published through the static BlockData inner class, whose getPos() and getFacing() are read by rotationrecode2() and by the placement branch of the update handler.

The search runs in find(Vec3). The origin x and z come from the player position, extrapolated by the Expand setting using the movement delta times Expandlength, and y is the cached posY when SameY or Down is active. The anchor is the block below the player. Pass one checks the six EnumFacing neighbors and returns the first solid one whose face point is not occluded. Pass two checks the 8-cell ring at offsets of 1 and 2 along the axes; for each ring cell that is air it scans the six neighbors of that cell the same way. The face point used by the occlusion test is the block center plus half the facing direction vector (getPositionByFace), and rayTrace walks 10 evenly spaced samples from the player look direction toward that point, returning true as soon as a sample lands inside the collision bounding box of a block that is neither air nor liquid. The facing stored in BlockData is always the inverted facing, so the new block is placed on the side of the support that faces the anchor spot.

Placement goes through the vanilla pipeline: updateController(), then onPlayerRightClick with the support position, facing, held stack and a hit vector computed as the support block center plus half the facing direction. Vanilla sends C08PacketPlayerBlockPlacement with the position, the facing index, the held stack and the three fractional face offsets, and runs the local ItemBlock.onItemUse so the client world stays in sync. The Swing setting picks between swingItem() (local arm animation plus the animation packet) and a direct C0APacketAnimation (packet only, no local arm swing).

Rotation handling sits in the EventPreMotion branch. Both Static and Calculated modes copy the head rotations into RotationUtil.yaw and RotationUtil.pitch first, then Static writes yaw + 180 and pitch 82 into the event while Calculated writes the output of rotationrecode2(), which aims with atan2 at the placement face, quantizes yaw and pitch to the vanilla mouse-sensitivity grid, clamps pitch to 78-80 and honors the ReverseYaw and YawPosition settings. The six tower profiles, the BMCBoost timer speed of 1.105x while a speed potion is active, the AutoDisable toggle that turns the module off when Killaura has a target, and the LegitPlace reimplementation of Minecraft.rightClickMouse (rightClickDelayTimer = 4, the ENTITY and BLOCK mouse-over switch, C0APacketAnimation on swing) are all in this file as well, along with the block-count HUD, the BlockESP overlay drawn through Blur, and the BlackList inner class with its 15 excluded block ids.

source RotationUtil.java (rotation helpers)

RotationUtil.java209 lines · JavaOriginal ↗
1
package intent.AquaDev.aqua.utils;
2
3
import intent.AquaDev.aqua.Aqua;
4
import java.util.Random;
5
import net.minecraft.client.Minecraft;
6
import net.minecraft.client.entity.EntityPlayerSP;
7
import net.minecraft.entity.Entity;
8
import net.minecraft.entity.EntityLivingBase;
9
import net.minecraft.util.MathHelper;
10
11
public class RotationUtil {
12
   public static float yaw;
13
   public static float renderYawOffset;
14
   public static float pitch;
15
   public static boolean RotationInUse;
16
   static Minecraft mc = Minecraft.getMinecraft();
17
18
   public static float[] Intavee(EntityPlayerSP player, EntityLivingBase target) {
19
      float yawRandom = (float)MathHelper.getRandomDoubleInRange(new Random(), -0.2, 0.2);
20
      float pitchRandom = (float)MathHelper.getRandomDoubleInRange(new Random(), -0.02, 0.02);
21
      double posX = Aqua.setmgr.getSetting("KillauraRandom").isState() ? target.posX - player.posX + (double)yawRandom : target.posX - player.posX;
22
      double posY = Aqua.setmgr.getSetting("KillauraClampPitch").isState()
23
         ? MathHelper.clamp_double(player.posY + (double)player.getEyeHeight(), target.getEntityBoundingBox().minY, target.getEntityBoundingBox().maxY)
24
            - (player.posY + (double)player.getEyeHeight())
25
         : (
26
            Aqua.setmgr.getSetting("KillauraRandom").isState()
27
               ? target.posY + (double)target.getEyeHeight() - (player.posY + (double)player.getEyeHeight() - (double)pitchRandom)
28
               : target.posY + (double)target.getEyeHeight() - (player.posY + (double)player.getEyeHeight())
29
         );
30
      double posZ = Aqua.setmgr.getSetting("KillauraRandom").isState() ? target.posZ - player.posZ - (double)yawRandom : target.posZ - player.posZ;
31
      double var14 = (double)MathHelper.sqrt_double(posX * posX + posZ * posZ);
32
      float yaw = (float)(Math.atan2(posZ, posX) * 180.0 / Math.PI) - 90.0F;
33
      float pitch = (float)(-(Math.atan2(posY, var14) * 180.0 / Math.PI));
34
      if (Aqua.setmgr.getSetting("KillauraMouseSensiFix").isState()) {
35
         float f2 = Minecraft.getMinecraft().gameSettings.mouseSensitivity * 0.6F + 0.2F;
36
         float f3 = f2 * f2 * f2 * 1.2F;
37
         yaw -= yaw % f3;
38
         pitch -= pitch % (f3 * f2);
39
      }
40
41
      return new float[]{yaw, pitch};
42
   }
43
44
   public static float[] lookAtPosBed(double x, double y, double z) {
45
      double dirx = mc.thePlayer.posX - x;
46
      double diry = mc.thePlayer.posY - y;
47
      double dirz = mc.thePlayer.posZ - z;
48
      double len = Math.sqrt(dirx * dirx + diry * diry + dirz * dirz);
49
      dirx /= len;
50
      diry /= len;
51
      dirz /= len;
52
      float yaw = (float)Math.atan2(dirz, dirx);
53
      float pitch = (float)((double)((float)Math.asin(diry)) + 0.3);
54
      pitch = (float)((double)pitch * 180.0 / Math.PI);
55
      yaw = (float)((double)yaw * 180.0 / Math.PI);
56
      yaw = (float)((double)yaw + 90.0);
57
      float f2 = Minecraft.getMinecraft().gameSettings.mouseSensitivity * 0.6F + 0.2F;
58
      float f3 = f2 * f2 * f2 * 1.2F;
59
      yaw -= yaw % f3;
60
      pitch -= pitch % (f3 * f2);
61
      return new float[]{yaw, pitch};
62
   }
63
64
   public static void setRotation(float y, float p) {
65
      if (p > 90.0F) {
66
         p = 90.0F;
67
      } else if (p < -90.0F) {
68
         p = -90.0F;
69
      }
70
71
      yaw = y;
72
      pitch = p;
73
      RotationInUse = true;
74
   }
75
76
   public static boolean setYaw(float y, float speed) {
77
      setRotation(yaw, pitch);
78
      if (speed >= 360.0F) {
79
         yaw = y;
80
         return true;
81
      } else if (!isInRange((double)yaw, y, speed) && !(speed >= 360.0F)) {
82
         if (getRotation((double)yaw, y) < 0) {
83
            yaw -= speed;
84
         } else {
85
            yaw += speed;
86
         }
87
88
         return false;
89
      } else {
90
         yaw = y;
91
         return true;
92
      }
93
   }
94
95
   public static int getRotation(double before, float after) {
96
      while(before > 360.0) {
97
         before -= 360.0;
98
      }
99
100
      while(before < 0.0) {
101
         before += 360.0;
102
      }
103
104
      while(after > 360.0F) {
105
         after -= 360.0F;
106
      }
107
108
      while(after < 0.0F) {
109
         after += 360.0F;
110
      }
111
112
      if (before > (double)after) {
113
         return before - (double)after > 180.0 ? 1 : -1;
114
      } else {
115
         return (double)after - before > 180.0 ? -1 : 1;
116
      }
117
   }
118
119
   public static boolean isInRange(double before, float after, float max) {
120
      while(before > 360.0) {
121
         before -= 360.0;
122
      }
123
124
      while(before < 0.0) {
125
         before += 360.0;
126
      }
127
128
      while(after > 360.0F) {
129
         after -= 360.0F;
130
      }
131
132
      while(after < 0.0F) {
133
         after += 360.0F;
134
      }
135
136
      if (before > (double)after) {
137
         if (before - (double)after > 180.0 && 360.0 - before - (double)after <= (double)max) {
138
            return true;
139
         } else {
140
            return before - (double)after <= (double)max;
141
         }
142
      } else if ((double)after - before > 180.0 && (double)(360.0F - after) - before <= (double)max) {
143
         return true;
144
      } else {
145
         return (double)after - before <= (double)max;
146
      }
147
   }
148
149
   public static boolean setPitch(float p, float speed) {
150
      if (p > 90.0F) {
151
         p = 90.0F;
152
      } else if (p < -90.0F) {
153
         p = -90.0F;
154
      }
155
156
      if (!(Math.abs(pitch - p) <= speed) && !(speed >= 360.0F)) {
157
         if (p < pitch) {
158
            pitch -= speed;
159
         } else {
160
            pitch += speed;
161
         }
162
163
         return true;
164
      } else {
165
         pitch = p;
166
         return false;
167
      }
168
   }
169
170
   public static float calculateCorrectYawOffset(float yaw) {
171
      double xDiff = mc.thePlayer.posX - mc.thePlayer.prevPosX;
172
      double zDiff = mc.thePlayer.posZ - mc.thePlayer.prevPosZ;
173
      float dist = (float)(xDiff * xDiff + zDiff * zDiff);
174
      float renderYawOffset = mc.thePlayer.renderYawOffset;
175
      float offset = renderYawOffset;
176
      if (dist > 0.0025000002F) {
177
         offset = (float)MathHelper.func_181159_b(zDiff, xDiff) * 180.0F / (float) Math.PI - 90.0F;
178
      }
179
180
      if (mc.thePlayer != null && mc.thePlayer.swingProgress > 0.0F) {
181
         offset = yaw;
182
      }
183
184
      float offsetDiff = MathHelper.wrapAngleTo180_float(offset - renderYawOffset);
185
      renderYawOffset += offsetDiff * 0.3F;
186
      float yawOffsetDiff = MathHelper.wrapAngleTo180_float(yaw - renderYawOffset);
187
      if (yawOffsetDiff < -75.0F) {
188
         yawOffsetDiff = -75.0F;
189
      }
190
191
      if (yawOffsetDiff >= 75.0F) {
192
         yawOffsetDiff = 75.0F;
193
      }
194
195
      renderYawOffset = yaw - yawOffsetDiff;
196
      if (yawOffsetDiff * yawOffsetDiff > 2500.0F) {
197
         renderYawOffset += yawOffsetDiff * 0.2F;
198
      }
199
200
      return renderYawOffset;
201
   }
202
203
   public static float getAngle(Entity entity) {
204
      double x = RenderUtil.interpolate(entity.posX, entity.lastTickPosX, 1.0) - RenderUtil.interpolate(mc.thePlayer.posX, mc.thePlayer.lastTickPosX, 1.0);
205
      double z = RenderUtil.interpolate(entity.posZ, entity.lastTickPosZ, 1.0) - RenderUtil.interpolate(mc.thePlayer.posZ, mc.thePlayer.lastTickPosZ, 1.0);
206
      float yaw = (float)(-Math.toDegrees(Math.atan2(x, z)));
207
      return (float)((double)yaw - RenderUtil.interpolate((double)mc.thePlayer.rotationYaw, (double)mc.thePlayer.prevRotationYaw, 1.0));
208
   }
209
}

What this file does

The shared rotation state holder for the client. It exposes public static fields yaw, pitch, renderYawOffset and RotationInUse that modules write and read. Scaffold consumes exactly the state half of this class: in both rotation modes the EventPreMotion branch stores the real head rotations into RotationUtil.yaw and RotationUtil.pitch before overriding the outgoing packet values, so every other module and the render pass can read the actual aim the scaffold is holding. The file also carries the aim and smoothing math used elsewhere in the client, most notably by Killaura: Intavee() and lookAtPosBed() compute atan2 yaw and pitch toward a target with the same mouse-sensitivity quantization that Scaffold inlines in rotationrecode2() and mouseSens() (f3 = (sens * 0.6 + 0.2)^3 * 1.2, yaw -= yaw % f3, pitch -= pitch % (f3 * f2)).

The remaining helpers are rotation utilities rather than aim math: setRotation() clamps pitch to the legal -90 to 90 range, setYaw() and setPitch() step the current rotation toward a target at a bounded speed with wraparound-aware comparison via getRotation() and isInRange(), calculateCorrectYawOffset() reconstructs the render yaw offset from movement and swing state, and getAngle() returns the yaw difference to an entity using RenderUtil.interpolate. Scaffold does not call the smoothing helpers, but it relies on the static fields this class provides, which is why the module compiles against it.

source RandomUtil.java

RandomUtil.java80 lines · JavaOriginal ↗
1
package intent.AquaDev.aqua.utils;
2
3
import java.security.SecureRandom;
4
import java.util.concurrent.ThreadLocalRandom;
5
6
public class RandomUtil {
7
   public static RandomUtil instance = new RandomUtil();
8
9
   public int nextInt(int origin, int bound) {
10
      return origin == bound ? origin : ThreadLocalRandom.current().nextInt(origin, bound);
11
   }
12
13
   public int nextInt(double origin, double bound) {
14
      return (int)origin == (int)bound ? (int)origin : ThreadLocalRandom.current().nextInt((int)origin, (int)bound);
15
   }
16
17
   public long nextLong(long origin, long bound) {
18
      return origin == bound ? origin : ThreadLocalRandom.current().nextLong(origin, bound);
19
   }
20
21
   public long nextLong(double origin, double bound) {
22
      return (long)origin == (long)bound ? (long)origin : ThreadLocalRandom.current().nextLong((long)origin, (long)bound);
23
   }
24
25
   public float nextFloat(double origin, double bound) {
26
      return origin == bound ? (float)origin : (float)ThreadLocalRandom.current().nextDouble((double)((float)origin), (double)((float)bound));
27
   }
28
29
   public float nextFloat(float origin, float bound) {
30
      return origin == bound ? origin : (float)ThreadLocalRandom.current().nextDouble((double)origin, (double)bound);
31
   }
32
33
   public double nextDouble(double origin, double bound) {
34
      return origin == bound ? origin : ThreadLocalRandom.current().nextDouble(origin, bound);
35
   }
36
37
   public double nextSecureInt(int origin, int bound) {
38
      if (origin == bound) {
39
         return (double)origin;
40
      } else {
41
         SecureRandom secureRandom = new SecureRandom();
42
         int difference = bound - origin;
43
         return (double)(origin + secureRandom.nextInt(difference));
44
      }
45
   }
46
47
   public double nextSecureInt(double origin, double bound) {
48
      if ((int)origin == (int)bound) {
49
         return origin;
50
      } else {
51
         SecureRandom secureRandom = new SecureRandom();
52
         int difference = (int)bound - (int)origin;
53
         return origin + (double)secureRandom.nextInt(difference);
54
      }
55
   }
56
57
   public double nextSecureDouble(double origin, double bound) {
58
      if (origin == bound) {
59
         return origin;
60
      } else {
61
         SecureRandom secureRandom = new SecureRandom();
62
         double difference = bound - origin;
63
         return origin + secureRandom.nextDouble() * difference;
64
      }
65
   }
66
67
   public float nextSecureFloat(double origin, double bound) {
68
      if (origin == bound) {
69
         return (float)origin;
70
      } else {
71
         SecureRandom secureRandom = new SecureRandom();
72
         float difference = (float)(bound - origin);
73
         return (float)(origin + (double)(secureRandom.nextFloat() * difference));
74
      }
75
   }
76
77
   public double randomSin() {
78
      return Math.sin(instance.nextDouble(0.0, Math.PI * 2));
79
   }
80
}

What this file does

A small random-number singleton around ThreadLocalRandom. The static instance field lets any module call RandomUtil.instance.nextFloat(...) without constructing a generator, and the overloads cover int, long, float and double bounds. SecureRandom-backed nextSecure variants and a randomSin() helper exist for other modules that want cryptographic randomness or a cheap sine wave.

Scaffold uses exactly one call: RandomUtil.instance.nextFloat(0.9908900590734863, 0.9909900590734863), evaluated in the Watchdog, UpdatedNCP-moving and IntaveFast tower profiles when their air-tick counters hit their trigger values. The returned factor, always very close to 1.0, multiplies the damped motionY expression, so the vertical boost loses a tiny randomized amount each cycle. The near-1 range makes the motion look like natural momentum loss rather than a fixed value, which is the anticheat-evasion point of the tower modes.

source TimeUtil.java

TimeUtil.java49 lines · JavaOriginal ↗
1
package intent.AquaDev.aqua.utils;
2
3
public class TimeUtil {
4
   private long lastMS = 0L;
5
6
   public long getCurrentMS() {
7
      return System.currentTimeMillis();
8
   }
9
10
   public boolean hasReached(long milliseconds) {
11
      return this.getCurrentMS() - this.lastMS >= milliseconds;
12
   }
13
14
   public void reset() {
15
      this.lastMS = this.getCurrentMS();
16
   }
17
18
   public int convertToMS(int perSecond) {
19
      return 1000 / perSecond;
20
   }
21
22
   public void setCurrentDifference(int difference) {
23
      this.lastMS = System.currentTimeMillis() - (long)difference;
24
   }
25
26
   public boolean hasTimePassed(long delay) {
27
      return System.currentTimeMillis() >= this.lastMS + delay;
28
   }
29
30
   public void setLastMS() {
31
      this.lastMS = System.currentTimeMillis();
32
   }
33
34
   public boolean hasTimeElapsed(long time, boolean reset) {
35
      if (this.lastMS > System.currentTimeMillis()) {
36
         this.lastMS = System.currentTimeMillis();
37
      }
38
39
      if (System.currentTimeMillis() - this.lastMS > time) {
40
         if (reset) {
41
            this.reset();
42
         }
43
44
         return true;
45
      } else {
46
         return false;
47
      }
48
   }
49
}

What this file does

A millisecond stopwatch wrapper. It tracks a lastMS timestamp and offers hasReached(ms) and hasTimePassed(ms) comparisons against System.currentTimeMillis(), plus reset(), setLastMS(), setCurrentDifference() and a convertToMS() rate helper. The instance Scaffold creates is the timing backbone of the tower modes.

The module's TimeUtil instance gates three different windows. Cubecraft calls hasTimePassed(50L) so the 0.42 jump fires at most once per 50ms. UpdatedNCP stationary and WatchdogNew check hasReached(2000L) before allowing the 0.4196 impulse, which keeps the boost from firing in the first two seconds after a previous boost cycle. VerusFast checks hasReached(5000L) to decide whether the 0.70096 vertical boost may apply: while the 5000ms window is open the motionY is set, and once it elapses the timer resets and the fake C08 spam continues without the boost.

source RenderUtil.java (HUD and ESP rendering)

RenderUtil.java989 lines · JavaOriginal ↗
1
package intent.AquaDev.aqua.utils;
2
3
import intent.AquaDev.aqua.Aqua;
4
import intent.AquaDev.aqua.cape.GIF;
5
import intent.AquaDev.aqua.modules.visual.HUD;
6
import java.awt.Color;
7
import net.minecraft.block.Block;
8
import net.minecraft.client.Minecraft;
9
import net.minecraft.client.gui.Gui;
10
import net.minecraft.client.gui.GuiScreen;
11
import net.minecraft.client.gui.ScaledResolution;
12
import net.minecraft.client.renderer.GlStateManager;
13
import net.minecraft.client.renderer.Tessellator;
14
import net.minecraft.client.renderer.WorldRenderer;
15
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
16
import net.minecraft.entity.Entity;
17
import net.minecraft.entity.EntityLivingBase;
18
import net.minecraft.entity.player.EntityPlayer;
19
import net.minecraft.util.AxisAlignedBB;
20
import net.minecraft.util.BlockPos;
21
import net.minecraft.util.MathHelper;
22
import net.minecraft.util.ResourceLocation;
23
import org.lwjgl.opengl.GL11;
24
25
public class RenderUtil {
26
   private GuiScreen customcape;
27
   static Minecraft mc = Minecraft.getMinecraft();
28
29
   public static void drawBlockESP(BlockPos blockPos, float red, float green, float blue, float alpha, float lineAlpha, float lineWidth) {
30
      GlStateManager.color(red, green, blue, alpha);
31
      float x = (float)((double)blockPos.getX() - mc.getRenderManager().getRenderPosX());
32
      float y = (float)((double)blockPos.getY() - mc.getRenderManager().getRenderPosY());
33
      float z = (float)((double)blockPos.getZ() - mc.getRenderManager().getRenderPosZ());
34
      Block block = mc.theWorld.getBlockState(blockPos).getBlock();
35
      drawBoundingBox(
36
         new AxisAlignedBB(
37
            (double)x,
38
            (double)y,
39
            (double)z,
40
            (double)x + block.getBlockBoundsMaxX(),
41
            (double)y + block.getBlockBoundsMaxY(),
42
            (double)z + block.getBlockBoundsMaxZ()
43
         )
44
      );
45
      GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
46
   }
47
48
   public static void drawBoundingBox(AxisAlignedBB a) {
49
      Tessellator tessellator = Tessellator.getInstance();
50
      WorldRenderer worldrenderer = tessellator.getWorldRenderer();
51
      worldrenderer.begin(7, DefaultVertexFormats.POSITION);
52
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.minY), (double)((float)a.minZ)).endVertex();
53
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.minY), (double)((float)a.maxZ)).endVertex();
54
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.maxY), (double)((float)a.maxZ)).endVertex();
55
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.maxY), (double)((float)a.minZ)).endVertex();
56
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.minY), (double)((float)a.maxZ)).endVertex();
57
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.minY), (double)((float)a.maxZ)).endVertex();
58
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.maxY), (double)((float)a.maxZ)).endVertex();
59
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.maxY), (double)((float)a.maxZ)).endVertex();
60
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.minY), (double)((float)a.maxZ)).endVertex();
61
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.minY), (double)((float)a.minZ)).endVertex();
62
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.maxY), (double)((float)a.minZ)).endVertex();
63
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.maxY), (double)((float)a.maxZ)).endVertex();
64
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.minY), (double)((float)a.minZ)).endVertex();
65
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.minY), (double)((float)a.minZ)).endVertex();
66
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.maxY), (double)((float)a.minZ)).endVertex();
67
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.maxY), (double)((float)a.minZ)).endVertex();
68
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.minY), (double)((float)a.minZ)).endVertex();
69
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.minY), (double)((float)a.maxZ)).endVertex();
70
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.minY), (double)((float)a.maxZ)).endVertex();
71
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.minY), (double)((float)a.minZ)).endVertex();
72
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.maxY), (double)((float)a.minZ)).endVertex();
73
      worldrenderer.pos((double)((float)a.minX), (double)((float)a.maxY), (double)((float)a.maxZ)).endVertex();
74
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.maxY), (double)((float)a.maxZ)).endVertex();
75
      worldrenderer.pos((double)((float)a.maxX), (double)((float)a.maxY), (double)((float)a.minZ)).endVertex();
76
      worldrenderer.endVertex();
77
      tessellator.draw();
78
   }
79
80
   public static void polygon(double x, double y, double sideLength, double amountOfSides, boolean filled, Color color) {
81
      sideLength /= 2.0;
82
      start();
83
      if (color != null) {
84
         setGLColor(color);
85
      }
86
87
      if (!filled) {
88
         GL11.glLineWidth(2.0F);
89
      }
90
91
      GL11.glEnable(2848);
92
      begin(filled ? 6 : 3);
93
94
      for(double i = 0.0; i <= amountOfSides / 4.0; ++i) {
95
         double angle = i * 4.0 * (Math.PI * 2) / 360.0;
96
         vertex(x + sideLength * Math.cos(angle) + sideLength, y + sideLength * Math.sin(angle) + sideLength);
97
      }
98
99
      end();
100
      GL11.glDisable(2848);
101
      stop();
102
   }
103
104
   public static void start() {
105
      GL11.glEnable(3042);
106
      GL11.glBlendFunc(770, 771);
107
      GL11.glDisable(3553);
108
      GL11.glDisable(2884);
109
      GlStateManager.disableAlpha();
110
      GlStateManager.disableDepth();
111
   }
112
113
   public void circle(double x, double y, double radius, boolean filled, Color color) {
114
      polygon(x, y, radius, 360.0, filled, color);
115
   }
116
117
   public void circle(double x, double y, double radius, boolean filled) {
118
      this.polygon(x, y, radius, 360, filled);
119
   }
120
121
   public static void circle(double x, double y, double radius, Color color) {
122
      polygon(x, y, radius, 360, color);
123
   }
124
125
   public static void stop() {
126
      GlStateManager.enableAlpha();
127
      GlStateManager.enableDepth();
128
      GL11.glEnable(2884);
129
      GL11.glEnable(3553);
130
      GL11.glDisable(3042);
131
      color(Color.white);
132
   }
133
134
   public static void vertex(double x, double y) {
135
      GL11.glVertex2d(x, y);
136
   }
137
138
   public static void begin(int glMode) {
139
      GL11.glBegin(glMode);
140
   }
141
142
   public static void end() {
143
      GL11.glEnd();
144
   }
145
146
   public void polygon(double x, double y, double sideLength, int amountOfSides, boolean filled) {
147
      polygon(x, y, sideLength, (double)amountOfSides, filled, null);
148
   }
149
150
   public static void polygon(double x, double y, double sideLength, int amountOfSides, Color color) {
151
      polygon(x, y, sideLength, (double)amountOfSides, true, color);
152
   }
153
154
   public void polygon(double x, double y, double sideLength, int amountOfSides) {
155
      polygon(x, y, sideLength, (double)amountOfSides, true, null);
156
   }
157
158
   public static void drawEntityServerESP(Entity entity, float red, float green, float blue, float alpha, float lineAlpha, float lineWidth) {
159
      double d0 = (double)entity.serverPosX / 32.0;
160
      double d1 = (double)entity.serverPosY / 32.0;
161
      double d2 = (double)entity.serverPosZ / 32.0;
162
      if (entity instanceof EntityLivingBase) {
163
         EntityLivingBase livingBase = (EntityLivingBase)entity;
164
         d0 = livingBase.realPos.xCoord;
165
         d1 = livingBase.realPos.yCoord;
166
         d2 = livingBase.realPos.zCoord;
167
      }
168
169
      float x = (float)(d0 - mc.getRenderManager().getRenderPosX());
170
      float y = (float)(d1 - mc.getRenderManager().getRenderPosY());
171
      float z = (float)(d2 - mc.getRenderManager().getRenderPosZ());
172
      GL11.glColor4f(red, green, blue, alpha);
173
      otherDrawBoundingBox(entity, x, y, z, (double)(entity.width - 0.2F), (double)(entity.height + 0.1F));
174
      if (lineWidth > 0.0F) {
175
         GL11.glLineWidth(lineWidth);
176
         GL11.glColor4f(red, green, blue, lineAlpha);
177
         otherDrawOutlinedBoundingBox(entity, x, y, z, (double)(entity.width - 0.2F), (double)(entity.height + 0.1F));
178
      }
179
180
      GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
181
   }
182
183
   public static void otherDrawOutlinedBoundingBox(Entity entity, float x, float y, float z, double width, double height) {
184
      width *= 1.5;
185
      float yaw1 = MathHelper.wrapAngleTo180_float(entity.getRotationYawHead()) + 45.0F;
186
      float newYaw1;
187
      if (yaw1 < 0.0F) {
188
         newYaw1 = 0.0F;
189
         newYaw1 += 360.0F - Math.abs(yaw1);
190
      } else {
191
         newYaw1 = yaw1;
192
      }
193
194
      newYaw1 *= -1.0F;
195
      newYaw1 = (float)((double)newYaw1 * (Math.PI / 180.0));
196
      float yaw2 = MathHelper.wrapAngleTo180_float(entity.getRotationYawHead()) + 135.0F;
197
      float newYaw2;
198
      if (yaw2 < 0.0F) {
199
         newYaw2 = 0.0F;
200
         newYaw2 += 360.0F - Math.abs(yaw2);
201
      } else {
202
         newYaw2 = yaw2;
203
      }
204
205
      newYaw2 *= -1.0F;
206
      newYaw2 = (float)((double)newYaw2 * (Math.PI / 180.0));
207
      float yaw3 = MathHelper.wrapAngleTo180_float(entity.getRotationYawHead()) + 225.0F;
208
      float newYaw3;
209
      if (yaw3 < 0.0F) {
210
         newYaw3 = 0.0F;
211
         newYaw3 += 360.0F - Math.abs(yaw3);
212
      } else {
213
         newYaw3 = yaw3;
214
      }
215
216
      newYaw3 *= -1.0F;
217
      newYaw3 = (float)((double)newYaw3 * (Math.PI / 180.0));
218
      float yaw4 = MathHelper.wrapAngleTo180_float(entity.getRotationYawHead()) + 315.0F;
219
      float newYaw4;
220
      if (yaw4 < 0.0F) {
221
         newYaw4 = 0.0F;
222
         newYaw4 += 360.0F - Math.abs(yaw4);
223
      } else {
224
         newYaw4 = yaw4;
225
      }
226
227
      newYaw4 *= -1.0F;
228
      newYaw4 = (float)((double)newYaw4 * (Math.PI / 180.0));
229
      float x1 = (float)(Math.sin((double)newYaw1) * width + (double)x);
230
      float z1 = (float)(Math.cos((double)newYaw1) * width + (double)z);
231
      float x2 = (float)(Math.sin((double)newYaw2) * width + (double)x);
232
      float z2 = (float)(Math.cos((double)newYaw2) * width + (double)z);
233
      float x3 = (float)(Math.sin((double)newYaw3) * width + (double)x);
234
      float z3 = (float)(Math.cos((double)newYaw3) * width + (double)z);
235
      float x4 = (float)(Math.sin((double)newYaw4) * width + (double)x);
236
      float z4 = (float)(Math.cos((double)newYaw4) * width + (double)z);
237
      float y2 = (float)((double)y + height);
238
      Tessellator tessellator = Tessellator.getInstance();
239
      WorldRenderer worldrenderer = tessellator.getWorldRenderer();
240
      worldrenderer.begin(3, DefaultVertexFormats.POSITION);
241
      worldrenderer.pos((double)x1, (double)y, (double)z1).endVertex();
242
      worldrenderer.pos((double)x1, (double)y2, (double)z1).endVertex();
243
      worldrenderer.pos((double)x2, (double)y2, (double)z2).endVertex();
244
      worldrenderer.pos((double)x2, (double)y, (double)z2).endVertex();
245
      worldrenderer.pos((double)x1, (double)y, (double)z1).endVertex();
246
      worldrenderer.pos((double)x4, (double)y, (double)z4).endVertex();
247
      worldrenderer.pos((double)x3, (double)y, (double)z3).endVertex();
248
      worldrenderer.pos((double)x3, (double)y2, (double)z3).endVertex();
249
      worldrenderer.pos((double)x4, (double)y2, (double)z4).endVertex();
250
      worldrenderer.pos((double)x4, (double)y, (double)z4).endVertex();
251
      worldrenderer.pos((double)x4, (double)y2, (double)z4).endVertex();
252
      worldrenderer.pos((double)x3, (double)y2, (double)z3).endVertex();
253
      worldrenderer.pos((double)x2, (double)y2, (double)z2).endVertex();
254
      worldrenderer.pos((double)x2, (double)y, (double)z2).endVertex();
255
      worldrenderer.pos((double)x3, (double)y, (double)z3).endVertex();
256
      worldrenderer.pos((double)x4, (double)y, (double)z4).endVertex();
257
      worldrenderer.pos((double)x4, (double)y2, (double)z4).endVertex();
258
      worldrenderer.pos((double)x1, (double)y2, (double)z1).endVertex();
259
      worldrenderer.pos((double)x1, (double)y, (double)z1).endVertex();
260
      worldrenderer.endVertex();
261
      tessellator.draw();
262
   }
263
264
   public static void otherDrawBoundingBox(Entity entity, float x, float y, float z, double width, double height) {
265
      width *= 1.5;
266
      float yaw1 = MathHelper.wrapAngleTo180_float(entity.getRotationYawHead()) + 45.0F;
267
      float newYaw1;
268
      if (yaw1 < 0.0F) {
269
         newYaw1 = 0.0F;
270
         newYaw1 += 360.0F - Math.abs(yaw1);
271
      } else {
272
         newYaw1 = yaw1;
273
      }
274
275
      newYaw1 *= -1.0F;
276
      newYaw1 = (float)((double)newYaw1 * (Math.PI / 180.0));
277
      float yaw2 = MathHelper.wrapAngleTo180_float(entity.getRotationYawHead()) + 135.0F;
278
      float newYaw2;
279
      if (yaw2 < 0.0F) {
280
         newYaw2 = 0.0F;
281
         newYaw2 += 360.0F - Math.abs(yaw2);
282
      } else {
283
         newYaw2 = yaw2;
284
      }
285
286
      newYaw2 *= -1.0F;
287
      newYaw2 = (float)((double)newYaw2 * (Math.PI / 180.0));
288
      float yaw3 = MathHelper.wrapAngleTo180_float(entity.getRotationYawHead()) + 225.0F;
289
      float newYaw3;
290
      if (yaw3 < 0.0F) {
291
         newYaw3 = 0.0F;
292
         newYaw3 += 360.0F - Math.abs(yaw3);
293
      } else {
294
         newYaw3 = yaw3;
295
      }
296
297
      newYaw3 *= -1.0F;
298
      newYaw3 = (float)((double)newYaw3 * (Math.PI / 180.0));
299
      float yaw4 = MathHelper.wrapAngleTo180_float(entity.getRotationYawHead()) + 315.0F;
300
      float newYaw4;
301
      if (yaw4 < 0.0F) {
302
         newYaw4 = 0.0F;
303
         newYaw4 += 360.0F - Math.abs(yaw4);
304
      } else {
305
         newYaw4 = yaw4;
306
      }
307
308
      newYaw4 *= -1.0F;
309
      newYaw4 = (float)((double)newYaw4 * (Math.PI / 180.0));
310
      float x1 = (float)(Math.sin((double)newYaw1) * width + (double)x);
311
      float z1 = (float)(Math.cos((double)newYaw1) * width + (double)z);
312
      float x2 = (float)(Math.sin((double)newYaw2) * width + (double)x);
313
      float z2 = (float)(Math.cos((double)newYaw2) * width + (double)z);
314
      float x3 = (float)(Math.sin((double)newYaw3) * width + (double)x);
315
      float z3 = (float)(Math.cos((double)newYaw3) * width + (double)z);
316
      float x4 = (float)(Math.sin((double)newYaw4) * width + (double)x);
317
      float z4 = (float)(Math.cos((double)newYaw4) * width + (double)z);
318
      float y2 = (float)((double)y + height);
319
      Tessellator tessellator = Tessellator.getInstance();
320
      WorldRenderer worldrenderer = tessellator.getWorldRenderer();
321
      worldrenderer.begin(7, DefaultVertexFormats.POSITION);
322
      worldrenderer.pos((double)x1, (double)y, (double)z1).endVertex();
323
      worldrenderer.pos((double)x1, (double)y2, (double)z1).endVertex();
324
      worldrenderer.pos((double)x2, (double)y2, (double)z2).endVertex();
325
      worldrenderer.pos((double)x2, (double)y, (double)z2).endVertex();
326
      worldrenderer.pos((double)x2, (double)y, (double)z2).endVertex();
327
      worldrenderer.pos((double)x2, (double)y2, (double)z2).endVertex();
328
      worldrenderer.pos((double)x3, (double)y2, (double)z3).endVertex();
329
      worldrenderer.pos((double)x3, (double)y, (double)z3).endVertex();
330
      worldrenderer.pos((double)x3, (double)y, (double)z3).endVertex();
331
      worldrenderer.pos((double)x3, (double)y2, (double)z3).endVertex();
332
      worldrenderer.pos((double)x4, (double)y2, (double)z4).endVertex();
333
      worldrenderer.pos((double)x4, (double)y, (double)z4).endVertex();
334
      worldrenderer.pos((double)x4, (double)y, (double)z4).endVertex();
335
      worldrenderer.pos((double)x4, (double)y2, (double)z4).endVertex();
336
      worldrenderer.pos((double)x1, (double)y2, (double)z1).endVertex();
337
      worldrenderer.pos((double)x1, (double)y, (double)z1).endVertex();
338
      worldrenderer.pos((double)x1, (double)y, (double)z1).endVertex();
339
      worldrenderer.pos((double)x2, (double)y, (double)z2).endVertex();
340
      worldrenderer.pos((double)x3, (double)y, (double)z3).endVertex();
341
      worldrenderer.pos((double)x4, (double)y, (double)z4).endVertex();
342
      worldrenderer.pos((double)x1, (double)y2, (double)z1).endVertex();
343
      worldrenderer.pos((double)x2, (double)y2, (double)z2).endVertex();
344
      worldrenderer.pos((double)x3, (double)y2, (double)z3).endVertex();
345
      worldrenderer.pos((double)x4, (double)y2, (double)z4).endVertex();
346
      worldrenderer.endVertex();
347
      tessellator.draw();
348
   }
349
350
   public static void drawTriangleFilled(float x, float y, float width, float height, int color) {
351
      GL11.glDisable(3553);
352
      GL11.glEnable(3042);
353
      GL11.glEnable(2848);
354
      GL11.glLineWidth(1.0F);
355
      GL11.glBegin(1);
356
      glColor(color);
357
      GL11.glVertex2d((double)x, (double)y);
358
      GL11.glVertex2d((double)(x + width), (double)(y + height));
359
      GL11.glEnd();
360
      GL11.glBegin(1);
361
      GL11.glVertex2d((double)(x + width), (double)(y + height));
362
      GL11.glVertex2d((double)(x + width * 2.0F), (double)y);
363
      GL11.glEnd();
364
      GL11.glBegin(1);
365
      GL11.glVertex2d((double)x, (double)y);
366
      GL11.glEnd();
367
      GL11.glDisable(2848);
368
      GL11.glDisable(3042);
369
      GL11.glEnable(3553);
370
   }
371
372
   public static void drawTriangleFilledReversed(float x, float y, float width, float height, int color) {
373
      GL11.glDisable(3553);
374
      GL11.glEnable(3042);
375
      GL11.glEnable(2848);
376
      GL11.glLineWidth(1.0F);
377
      GL11.glBegin(1);
378
      glColor(color);
379
      GL11.glVertex2d((double)x, (double)y);
380
      GL11.glVertex2d((double)(x + width), (double)(y - height));
381
      GL11.glEnd();
382
      GL11.glBegin(1);
383
      GL11.glVertex2d((double)(x + width), (double)(y - height));
384
      GL11.glVertex2d((double)(x + width * 2.0F), (double)y);
385
      GL11.glEnd();
386
      GL11.glBegin(1);
387
      GL11.glVertex2d((double)x, (double)y);
388
      GL11.glEnd();
389
      GL11.glDisable(2848);
390
      GL11.glDisable(3042);
391
      GL11.glEnable(3553);
392
   }
393
394
   public static void drawTriangleFilled2(float x, float y, float width, float height, int color) {
395
      GL11.glDisable(3553);
396
      GL11.glEnable(3042);
397
      GL11.glBlendFunc(770, 771);
398
      GL11.glEnable(2848);
399
      GL11.glLineWidth(1.0F);
400
      glColor(color);
401
      GL11.glBegin(9);
402
      GL11.glVertex2d((double)x, (double)y);
403
      GL11.glVertex2d((double)(x + width), (double)(y + height));
404
      GL11.glVertex2d((double)(x + width), (double)(y + height));
405
      GL11.glVertex2d((double)(x + width * 2.0F), (double)y);
406
      GL11.glVertex2d((double)(x + width * 2.0F), (double)y);
407
      GL11.glVertex2d((double)x, (double)y);
408
      GL11.glEnd();
409
      GL11.glDisable(2848);
410
      GL11.glDisable(3042);
411
      GL11.glEnable(3553);
412
   }
413
414
   public static double interpolate(double current, double old, double scale) {
415
      return old + (current - old) * scale;
416
   }
417
418
   public static void drawImage(int x, int y, int width, int height, ResourceLocation resourceLocation) {
419
      GlStateManager.enableAlpha();
420
      mc.getTextureManager().bindTexture(resourceLocation);
421
      GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
422
      Gui.drawModalRectWithCustomSizedTexture(x, y, 0.0F, 0.0F, width, height, (float)width, (float)height);
423
      GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
424
   }
425
426
   public static void drawGif(int x, int y, int width, int height, String getGif) {
427
      GlStateManager.enableAlpha();
428
      GIF gif = Aqua.INSTANCE.GIFmgr.getGIFByName(getGif);
429
      mc.getTextureManager().bindTexture(gif.getNext().getLocation());
430
      GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
431
      Gui.drawModalRectWithCustomSizedTexture(x, y, 0.0F, 0.0F, width, height, (float)width, (float)height);
432
      GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
433
   }
434
435
   public static void drawImageDarker(int x, int y, int width, int height, ResourceLocation resourceLocation) {
436
      mc.getTextureManager().bindTexture(resourceLocation);
437
      GL11.glColor4f(0.19607843F, 0.19607843F, 0.19607843F, 1.0F);
438
      Gui.drawModalRectWithCustomSizedTexture(x, y, 0.0F, 0.0F, width, height, (float)width, (float)height);
439
      GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
440
   }
441
442
   public static void drawImageHUDColor(int x, int y, int width, int height, ResourceLocation resourceLocation) {
443
      mc.getTextureManager().bindTexture(resourceLocation);
444
      Color color = new Color(Aqua.setmgr.getSetting("HUDColor").getColor());
445
      GL11.glColor4f((float)color.getRed() / 255.0F, (float)color.getGreen() / 255.0F, (float)color.getBlue() / 255.0F, 1.0F);
446
      Gui.drawModalRectWithCustomSizedTexture(x, y, 0.0F, 0.0F, width, height, (float)width, (float)height);
447
      GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
448
   }
449
450
   public static void drawImageColored(int x, int y, int width, int height, Color color, ResourceLocation resourceLocation) {
451
      mc.getTextureManager().bindTexture(resourceLocation);
452
      GL11.glColor4f((float)color.getRed() / 255.0F, (float)color.getGreen() / 255.0F, (float)color.getBlue() / 255.0F, 1.0F);
453
      Gui.drawModalRectWithCustomSizedTexture(x, y, 0.0F, 0.0F, width, height, (float)width, (float)height);
454
      GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
455
   }
456
457
   public static void drawRoundedRect2(double x, double y, double width, double height, double cornerRadius, int color) {
458
      drawRoundedRect2(x, y, width, height, cornerRadius, true, true, true, true, color);
459
   }
460
461
   public static void drawRoundedRect(double x, double y, double width, double height, double cornerRadius, int color) {
462
      GL11.glPushMatrix();
463
      GL11.glDisable(3553);
464
      GL11.glEnable(2848);
465
      GL11.glBlendFunc(770, 771);
466
      setGLColor(color);
467
      GL11.glBegin(9);
468
      double cornerX = x + width - cornerRadius;
469
      double cornerY = y + height - cornerRadius;
470
471
      for(int i = 0; i <= 90; i += 30) {
472
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
473
      }
474
475
      cornerX = x + width - cornerRadius;
476
      cornerY = y + cornerRadius;
477
478
      for(int i = 90; i <= 180; i += 30) {
479
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
480
      }
481
482
      cornerX = x + cornerRadius;
483
      cornerY = y + cornerRadius;
484
485
      for(int i = 180; i <= 270; i += 30) {
486
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
487
      }
488
489
      cornerX = x + cornerRadius;
490
      cornerY = y + height - cornerRadius;
491
492
      for(int i = 270; i <= 360; i += 30) {
493
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
494
      }
495
496
      GL11.glEnd();
497
      GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
498
      GL11.glDisable(2848);
499
      GL11.glEnable(3553);
500
      GL11.glPopMatrix();
501
      setGLColor(Color.white);
502
   }
503
504
   public static void drawRoundedRect2(
505
      double x,
506
      double y,
507
      double width,
508
      double height,
509
      double cornerRadius,
510
      boolean leftTop,
511
      boolean rightTop,
512
      boolean rightBottom,
513
      boolean leftBottom,
514
      int color
515
   ) {
516
      GL11.glPushMatrix();
517
      GL11.glDisable(3553);
518
      GL11.glEnable(2848);
519
      GL11.glEnable(3042);
520
      GlStateManager.tryBlendFuncSeparate(770, 771, 0, 1);
521
      setGLColor(color);
522
      GL11.glBegin(9);
523
      double cornerX = x + width - cornerRadius;
524
      double cornerY = y + height - cornerRadius;
525
      if (rightBottom) {
526
         for(int i = 0; i <= 90; ++i) {
527
            GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
528
         }
529
      } else {
530
         GL11.glVertex2d(x + width, y + height);
531
      }
532
533
      if (rightTop) {
534
         cornerX = x + width - cornerRadius;
535
         cornerY = y + cornerRadius;
536
537
         for(int i = 90; i <= 180; ++i) {
538
            GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
539
         }
540
      } else {
541
         GL11.glVertex2d(x + width, y);
542
      }
543
544
      if (leftTop) {
545
         cornerX = x + cornerRadius;
546
         cornerY = y + cornerRadius;
547
548
         for(int i = 180; i <= 270; ++i) {
549
            GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
550
         }
551
      } else {
552
         GL11.glVertex2d(x, y);
553
      }
554
555
      if (leftBottom) {
556
         cornerX = x + cornerRadius;
557
         cornerY = y + height - cornerRadius;
558
559
         for(int i = 270; i <= 360; ++i) {
560
            GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
561
         }
562
      } else {
563
         GL11.glVertex2d(x, y + height);
564
      }
565
566
      GL11.glEnd();
567
      setGLColor(new Color(255, 255, 255, 255));
568
      GL11.glDisable(2848);
569
      GL11.glEnable(3553);
570
      GL11.glPopMatrix();
571
   }
572
573
   public static void setGLColor(Color color) {
574
      float r = (float)color.getRed() / 255.0F;
575
      float g = (float)color.getGreen() / 255.0F;
576
      float b = (float)color.getBlue() / 255.0F;
577
      float a = (float)color.getAlpha() / 255.0F;
578
      GL11.glColor4f(r, g, b, a);
579
   }
580
581
   public static void setGLColor(int color) {
582
      setGLColor(new Color(color));
583
   }
584
585
   public static void drawRoundedRectGradient(double x, double y, double width, double height, double cornerRadius, Color start, Color end) {
586
      GL11.glPushMatrix();
587
      GL11.glDisable(3553);
588
      GL11.glEnable(2848);
589
      GL11.glEnable(3042);
590
      GL11.glBlendFunc(770, 771);
591
      GL11.glShadeModel(7425);
592
      color(start);
593
      GL11.glBegin(9);
594
      double cornerX = x + width - cornerRadius;
595
      double cornerY = y + height - cornerRadius;
596
597
      for(int i = 0; i <= 90; i += 30) {
598
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
599
      }
600
601
      cornerX = x + width - cornerRadius;
602
      cornerY = y + cornerRadius;
603
604
      for(int i = 90; i <= 180; i += 30) {
605
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
606
      }
607
608
      color(end);
609
      cornerX = x + cornerRadius;
610
      cornerY = y + cornerRadius;
611
612
      for(int i = 180; i <= 270; i += 30) {
613
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
614
      }
615
616
      cornerX = x + cornerRadius;
617
      cornerY = y + height - cornerRadius;
618
619
      for(int i = 270; i <= 360; i += 30) {
620
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
621
      }
622
623
      GL11.glEnd();
624
      GL11.glShadeModel(7424);
625
      color(1.0F, 1.0F, 1.0F, 1.0F);
626
      GL11.glDisable(3042);
627
      GL11.glDisable(2848);
628
      GL11.glEnable(3553);
629
      GL11.glPopMatrix();
630
   }
631
632
   public static void drawGradientRectHorizontal(double x, double y, double width, double height, int startColor, int endColor) {
633
      GL11.glDisable(3553);
634
      GL11.glEnable(3042);
635
      GL11.glBlendFunc(770, 771);
636
      GL11.glShadeModel(7425);
637
      GL11.glPushMatrix();
638
      GL11.glBegin(7);
639
      glColor(startColor);
640
      GL11.glVertex2d(x, y);
641
      GL11.glVertex2d(x, y + height);
642
      glColor(endColor);
643
      GL11.glVertex2d(x + width, y + height);
644
      GL11.glVertex2d(x + width, y);
645
      GL11.glEnd();
646
      GL11.glPopMatrix();
647
      GL11.glShadeModel(7424);
648
      GL11.glDisable(3042);
649
      GL11.glEnable(3553);
650
   }
651
652
   public static void glColor(int hex) {
653
      float alpha = (float)(hex >> 24 & 0xFF) / 255.0F;
654
      float red = (float)(hex >> 16 & 0xFF) / 255.0F;
655
      float green = (float)(hex >> 8 & 0xFF) / 255.0F;
656
      float blue = (float)(hex & 0xFF) / 255.0F;
657
      GL11.glColor4f(red, green, blue, alpha);
658
   }
659
660
   public static void color(float red, float green, float blue, float alpha) {
661
      GL11.glColor4f(red / 255.0F, green / 255.0F, blue / 255.0F, alpha / 255.0F);
662
   }
663
664
   public static void color(Color color) {
665
      color((float)color.getRed(), (float)color.getGreen(), (float)color.getBlue(), (float)color.getAlpha());
666
   }
667
668
   public static void drawRoundedRect3(
669
      double x,
670
      double y,
671
      double width,
672
      double height,
673
      double cornerRadius,
674
      boolean leftTop,
675
      boolean rightTop,
676
      boolean rightBottom,
677
      boolean leftBottom,
678
      Color color
679
   ) {
680
      GL11.glPushMatrix();
681
      GL11.glDisable(3553);
682
      GL11.glEnable(2848);
683
      GL11.glEnable(3042);
684
      GL11.glBlendFunc(770, 771);
685
      setGLColor(color);
686
      GL11.glBegin(9);
687
      double cornerX = x + width - cornerRadius;
688
      double cornerY = y + height - cornerRadius;
689
      if (rightBottom) {
690
         for(int i = 0; i <= 90; i += 30) {
691
            GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
692
         }
693
      } else {
694
         GL11.glVertex2d(x + width, y + height);
695
      }
696
697
      if (rightTop) {
698
         cornerX = x + width - cornerRadius;
699
         cornerY = y + cornerRadius;
700
701
         for(int i = 90; i <= 180; i += 30) {
702
            GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
703
         }
704
      } else {
705
         GL11.glVertex2d(x + width, y);
706
      }
707
708
      if (leftTop) {
709
         cornerX = x + cornerRadius;
710
         cornerY = y + cornerRadius;
711
712
         for(int i = 180; i <= 270; i += 30) {
713
            GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
714
         }
715
      } else {
716
         GL11.glVertex2d(x, y);
717
      }
718
719
      if (leftBottom) {
720
         cornerX = x + cornerRadius;
721
         cornerY = y + height - cornerRadius;
722
723
         for(int i = 270; i <= 360; i += 30) {
724
            GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
725
         }
726
      } else {
727
         GL11.glVertex2d(x, y + height);
728
      }
729
730
      GL11.glEnd();
731
      GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
732
      GL11.glDisable(2848);
733
      GL11.glEnable(3553);
734
      GL11.glPopMatrix();
735
      setGLColor(Color.white);
736
   }
737
738
   public static void drawRoundedRect2Alpha(double x, double y, double width, double height, double cornerRadius, Color color) {
739
      GL11.glPushMatrix();
740
      GL11.glDisable(3553);
741
      GL11.glEnable(3042);
742
      color(color);
743
      GL11.glBegin(9);
744
      double cornerX = x + width - cornerRadius;
745
      double cornerY = y + height - cornerRadius;
746
747
      for(int i = 0; i <= 90; i += 30) {
748
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
749
      }
750
751
      cornerX = x + width - cornerRadius;
752
      cornerY = y + cornerRadius;
753
754
      for(int i = 90; i <= 180; i += 30) {
755
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
756
      }
757
758
      cornerX = x + cornerRadius;
759
      cornerY = y + cornerRadius;
760
761
      for(int i = 180; i <= 270; i += 30) {
762
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
763
      }
764
765
      cornerX = x + cornerRadius;
766
      cornerY = y + height - cornerRadius;
767
768
      for(int i = 270; i <= 360; i += 30) {
769
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
770
      }
771
772
      GL11.glEnd();
773
      GlStateManager.resetColor();
774
      GL11.glDisable(3042);
775
      GL11.glEnable(3553);
776
      GL11.glPopMatrix();
777
   }
778
779
   public static void drawRoundedRectSmooth(double x, double y, double width, double height, double cornerRadius, Color color) {
780
      GL11.glPushMatrix();
781
      GL11.glDisable(3008);
782
      GL11.glEnable(2881);
783
      GL11.glDisable(3553);
784
      GL11.glEnable(3042);
785
      color(color);
786
      GL11.glBegin(9);
787
      double cornerX = x + width - cornerRadius;
788
      double cornerY = y + height - cornerRadius;
789
790
      for(int i = 0; i <= 90; i += 30) {
791
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
792
      }
793
794
      cornerX = x + width - cornerRadius;
795
      cornerY = y + cornerRadius;
796
797
      for(int i = 90; i <= 180; i += 30) {
798
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
799
      }
800
801
      cornerX = x + cornerRadius;
802
      cornerY = y + cornerRadius;
803
804
      for(int i = 180; i <= 270; i += 30) {
805
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
806
      }
807
808
      cornerX = x + cornerRadius;
809
      cornerY = y + height - cornerRadius;
810
811
      for(int i = 270; i <= 360; i += 30) {
812
         GL11.glVertex2d(cornerX + Math.sin((double)i * Math.PI / 180.0) * cornerRadius, cornerY + Math.cos((double)i * Math.PI / 180.0) * cornerRadius);
813
      }
814
815
      GL11.glEnd();
816
      color(1.0F, 1.0F, 1.0F, 1.0F);
817
      GL11.glDisable(2881);
818
      GL11.glDisable(3042);
819
      GL11.glEnable(3553);
820
      GL11.glPopMatrix();
821
   }
822
823
   public static void drawRoundRectTest(
824
      float x1, float y1, float x2, float y2, float radius, int steps, boolean leftTop, boolean rightTop, boolean leftBottom, boolean rightBottom, Color color
825
   ) {
826
      GL11.glPushMatrix();
827
      GlStateManager.enableBlend();
828
      GlStateManager.disableTexture2D();
829
      GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
830
      color(color);
831
      GL11.glBegin(9);
832
      radius = Math.min(Math.min(Math.abs(y2 - y1) / 2.0F, Math.abs(x2 - x1) / 2.0F), radius);
833
      steps = Math.max(1, steps - steps % 3);
834
      if (rightBottom) {
835
         for(int i = 0; i <= 90; i += steps) {
836
            GL11.glVertex2d(
837
               (double)(x2 - radius) + Math.sin(Math.toRadians((double)i)) * (double)radius,
838
               (double)(y2 - radius) + Math.cos(Math.toRadians((double)i)) * (double)radius
839
            );
840
         }
841
      } else {
842
         GL11.glVertex2d((double)x2, (double)y2);
843
      }
844
845
      if (rightTop) {
846
         for(int i = 90; i <= 180; i += steps) {
847
            GL11.glVertex2d(
848
               (double)(x2 - radius) + Math.sin(Math.toRadians((double)i)) * (double)radius,
849
               (double)(y1 + radius) + Math.cos(Math.toRadians((double)i)) * (double)radius
850
            );
851
         }
852
      } else {
853
         GL11.glVertex2d((double)x2, (double)y1);
854
      }
855
856
      if (leftTop) {
857
         for(int i = 180; i <= 270; i += steps) {
858
            GL11.glVertex2d(
859
               (double)(x1 + radius) + Math.sin(Math.toRadians((double)i)) * (double)radius,
860
               (double)(y1 + radius) + Math.cos(Math.toRadians((double)i)) * (double)radius
861
            );
862
         }
863
      } else {
864
         GL11.glVertex2d((double)x1, (double)y1);
865
      }
866
867
      if (leftBottom) {
868
         for(int i = 270; i <= 360; i += steps) {
869
            GL11.glVertex2d(
870
               (double)(x1 + radius) + Math.sin(Math.toRadians((double)i)) * (double)radius,
871
               (double)(y2 - radius) + Math.cos(Math.toRadians((double)i)) * (double)radius
872
            );
873
         }
874
      } else {
875
         GL11.glVertex2d((double)x1, (double)y2);
876
      }
877
878
      GL11.glEnd();
879
      GlStateManager.enableTexture2D();
880
      GlStateManager.disableBlend();
881
      color(Color.white);
882
      GL11.glPopMatrix();
883
   }
884
885
   public static void setupViewBobbing(float partialTicks) {
886
      if (mc.getRenderViewEntity() instanceof EntityPlayer) {
887
         EntityPlayer entityplayer = (EntityPlayer)mc.getRenderViewEntity();
888
         float f = entityplayer.distanceWalkedModified - entityplayer.prevDistanceWalkedModified;
889
         float f1 = -(entityplayer.distanceWalkedModified + f * partialTicks);
890
         float f2 = entityplayer.prevCameraYaw + (entityplayer.cameraYaw - entityplayer.prevCameraYaw) * partialTicks;
891
         float f3 = entityplayer.prevCameraPitch + (entityplayer.cameraPitch - entityplayer.prevCameraPitch) * partialTicks;
892
         GlStateManager.translate(MathHelper.sin(f1 * (float) Math.PI) * f2 * 0.5F, -Math.abs(MathHelper.cos(f1 * (float) Math.PI) * f2), 0.0F);
893
         GlStateManager.rotate(MathHelper.sin(f1 * (float) Math.PI) * f2 * 3.0F, 0.0F, 0.0F, 1.0F);
894
         GlStateManager.rotate(Math.abs(MathHelper.cos(f1 * (float) Math.PI - 0.2F) * f2) * 5.0F, 1.0F, 0.0F, 0.0F);
895
         GlStateManager.rotate(f3, 1.0F, 0.0F, 0.0F);
896
      }
897
   }
898
899
   public static boolean isSliderHovered(float x1, float y1, float x2, float y2, int mouseX, int mouseY) {
900
      return (float)mouseX >= x1 && (float)mouseX <= x2 && (float)mouseY >= y1 && (float)mouseY <= y2;
901
   }
902
903
   public static Color getColorAlpha(int color, int alpha) {
904
      return new Color(new Color(color).getRed(), new Color(color).getGreen(), new Color(color).getBlue(), alpha);
905
   }
906
907
   public static void drawCircle(double x, double y, double radius, int color) {
908
      GL11.glPushMatrix();
909
      GL11.glEnable(3042);
910
      GL11.glDisable(2929);
911
      GL11.glBlendFunc(770, 771);
912
      GL11.glDisable(3553);
913
      GL11.glEnable(2848);
914
      GL11.glShadeModel(7425);
915
      GL11.glBegin(3);
916
917
      for(int i = 0; i < 360; ++i) {
918
         setGLColor(color);
919
         GL11.glVertex2d(x, y);
920
         double sin = Math.sin(Math.toRadians((double)i)) * radius;
921
         double cos = Math.cos(Math.toRadians((double)i)) * radius;
922
         GL11.glVertex2d(x + sin, y + cos);
923
      }
924
925
      GL11.glEnd();
926
      GL11.glEnable(3553);
927
      GL11.glDisable(3042);
928
      GL11.glDisable(2848);
929
      GL11.glShadeModel(7424);
930
      GL11.glEnable(2929);
931
      GL11.glPopMatrix();
932
   }
933
934
   public static void scissor(double x, double y, double width, double height) {
935
      ScaledResolution sr = new ScaledResolution(mc);
936
      double scale = (double)sr.getScaleFactor();
937
      y = (double)sr.getScaledHeight() - y;
938
      x *= scale;
939
      y *= scale;
940
      width *= scale;
941
      height *= scale;
942
      GL11.glScissor((int)x, (int)(y - height), (int)width, (int)height);
943
   }
944
945
   public static void drawRGBLineHorizontal(double x, double y, double width, float linewidth, float colors, boolean reverse) {
946
      GlStateManager.shadeModel(7425);
947
      GlStateManager.enableBlend();
948
      GlStateManager.disableTexture2D();
949
      GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
950
      GL11.glLineWidth(linewidth);
951
      GL11.glBegin(3);
952
      colors = (float)((double)colors * width);
953
      double steps = width / (double)colors;
954
      double cX = x;
955
      double cX2 = x + steps;
956
      if (reverse) {
957
         for(float i = colors; i > 0.0F; --i) {
958
            int argbColor = HUD.rainbow((int)(i * 10.0F));
959
            float a = (float)(argbColor >> 24 & 0xFF) / 255.0F;
960
            float r = (float)(argbColor >> 16 & 0xFF) / 255.0F;
961
            float g = (float)(argbColor >> 8 & 0xFF) / 255.0F;
962
            float b = (float)(argbColor & 0xFF) / 255.0F;
963
            GlStateManager.color(r, g, b, a);
964
            GL11.glVertex2d(cX, y);
965
            GL11.glVertex2d(cX2, y);
966
            cX = cX2;
967
            cX2 += steps;
968
         }
969
      } else {
970
         for(int i = 0; (float)i < colors; ++i) {
971
            int argbColor = HUD.rainbow(i * 10);
972
            float a = (float)(argbColor >> 24 & 0xFF) / 255.0F;
973
            float r = (float)(argbColor >> 16 & 0xFF) / 255.0F;
974
            float g = (float)(argbColor >> 8 & 0xFF) / 255.0F;
975
            float b = (float)(argbColor & 0xFF) / 255.0F;
976
            GlStateManager.color(r, g, b, a);
977
            GL11.glVertex2d(cX, y);
978
            GL11.glVertex2d(cX2, y);
979
            cX = cX2;
980
            cX2 += steps;
981
         }
982
      }
983
984
      GL11.glEnd();
985
      GlStateManager.shadeModel(7424);
986
      GlStateManager.enableTexture2D();
987
      GlStateManager.disableBlend();
988
   }
989
}

What this file does

The client's 989-line drawing helper, imported by Scaffold purely for presentation. drawBlockESP() renders the BlockESP overlay: the EventRenderNameTags branch wraps the call in Blur.drawBlurred(...) for the glow pass, and Scaffold itself toggles GL11 blend, line smoothing, depth, texture and culling state around the two drawBlockESP calls (a bright pass and a semi-transparent pass at alpha 0.392) using the HUDColor setting tint.

The block-count HUD is drawn from EventRender2D and EventPostRender2D with the rounded-rect and triangle primitives drawRoundedRect2Alpha(), drawRoundedRect() and drawTriangleFilled2(). The Shader mode setting selects the compositor: Shadow mode wraps the shapes in Shadow.drawGlow(...), Glow mode uses ShaderMultiplier.drawGlowESP(...) with the HUDColor tint, and Jello mode falls back to plain quads plus a small filled triangle, drawn with the novolineSmall font, or the themeHero variant using roboto2 and comfortaa4. The helper also provides the interpolate() function used by RotationUtil.getAngle(), though Scaffold itself never calls it.

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 NCP Scaffold check (blockplace)

Scaffold.java210 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.blockplace;
16
17
import java.util.LinkedList;
18
import java.util.List;
19
20
import org.bukkit.block.BlockFace;
21
import org.bukkit.entity.Player;
22
import org.bukkit.potion.PotionEffectType;
23
import org.bukkit.util.Vector;
24
25
import fr.neatmonster.nocheatplus.actions.ParameterName;
26
import fr.neatmonster.nocheatplus.checks.Check;
27
import fr.neatmonster.nocheatplus.checks.CheckType;
28
import fr.neatmonster.nocheatplus.checks.ViolationData;
29
import fr.neatmonster.nocheatplus.components.registry.feature.TickListener;
30
import fr.neatmonster.nocheatplus.players.IPlayerData;
31
import fr.neatmonster.nocheatplus.utilities.StringUtil;
32
import fr.neatmonster.nocheatplus.utilities.TickTask;
33
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
34
35
36
/**
37
 * Check for common behavior from a client using the "Scaffold" cheat.
38
 * Each sub-check should cover areas that one sub-check may not cover.
39
 * If the cheat does not flag any other sub-checks, the time sub-check
40
 * Should enforce realistic time between block placements.
41
 * 
42
 * @author CaptainObvious0
43
 */
44
public class Scaffold extends Check {
45
46
    final static double MAX_ANGLE = Math.toRadians(90);
47
    public List<String> tags = new LinkedList<>();
48
    
49
   /*
50
    * Instantiates a new Scaffold check
51
    */
52
    public Scaffold() {
53
        super(CheckType.BLOCKPLACE_SCAFFOLD);
54
    }
55
56
    /**
57
     * Check the player for Scaffold cheats
58
     *
59
     * @param player the player
60
     * @param placedFace blockface player placed against
61
     * @param pData player data
62
     * @param data block place data
63
     * @param cc block place config
64
     * @param isCancelled is the event cancelled
65
     * @param yDistance players current yDistance for this move
66
     * @param jumpPhase players jump phase
67
     * @return
68
     */
69
    public boolean check(final Player player, final BlockFace placedFace, final IPlayerData pData,
70
                         final BlockPlaceData data, final BlockPlaceConfig cc, final boolean isCancelled,
71
                         final double yDistance, final int jumpPhase) {
72
        // NOTE: Looks like there's a legit fast-scaffolding technique called 'god-bridge'
73
        // Would be useful to compare the speed with a skilled player god-bridging VS scaffold cheats.
74
        // TODO: ^ Need testing + debug log + someone who can actually replicate such... :)
75
76
        // TODO: Not too sure about the usefulness of this check these days:
77
        // Angle: like reported in the comment below, this is already covered by BlockInteract.Direction. Why not simply sharpen that one instead of bloating NCP with redundant code?
78
        // Time: Possibly rethink it. Could be moved to FastPlace as a sub-check
79
        //       ...Or just remove it. We already have a FastPlace check (which is ALSO
80
        //       feeding Improbable with too fast block placements on longer time periods...)
81
        // Sprint: Would be best to have our own sprinting handling, and catch the cheat with SurvivalFly instead.
82
        //        (If the player sprints while placing a block: sprinting = false -> cause Sf to enforce walking speed -> the player will then trigger a speed violation)
83
        // ToolSwitch: matter of taste... it may catch badly implemented scaffold cheats but not really much else. 
84
        //             Also clashes with NCP's principle (having long-lasting checks based on deterministic protection, not detecting specific cheat implementations)  
85
        // PitchRotation: this is the only one that I can see being kept. Combined with yawrate, they can nerf the cheat decently.
86
        //                (At that point it should be moved as a subcheck into something else. Wrongturn? A new Combined.PitchRate check? Wouldn't make sense keeping it into the BlockPlace category)      
87
        boolean cancel = false;
88
89
        // Update sneakTime since the player may have unsneaked after the last move.
90
        if (player.isSneaking()) {
91
            data.sneakTime = data.currentTick;
92
        }
93
        data.currentTick = TickTask.getTick();
94
95
        // Angle Check - Check if the player is looking at the block (Should already be covered by BlockInteract.Direction)
96
        if (cc.scaffoldAngle) {
97
            final Vector placedVector = new Vector(placedFace.getModX(), placedFace.getModY(), placedFace.getModZ());
98
            double placedAngle = TrigUtil.angle(player.getLocation().getDirection(), placedVector);
99
            if (placedAngle > MAX_ANGLE) {
100
                cancel = violation("Angle", Math.min(Math.max(1, (int) (placedAngle - MAX_ANGLE) * 10), 10), player, data, pData);
101
            }
102
        }
103
104
        // Time Check - A FastPlace check but for Scaffold type block placements. If all other sub-checks fail to detect the cheat this
105
        // Should ensure the player cannot quickly place blocks below themselves.
106
        if (cc.scaffoldTime && !isCancelled && Math.abs(player.getLocation().getPitch()) > 70
107
            && (data.currentTick - data.sneakTime) > 3 
108
            && !player.hasPotionEffect(PotionEffectType.SPEED)) {
109
            
110
            // TODO: Switch to ActionAccumulator based check.
111
            data.placeTick.add(data.currentTick);
112
            if (data.placeTick.size() > 2) {
113
                long sum = 0;
114
                long lastTick = 0;
115
                for (int i = 0; i < data.placeTick.size(); i++) {
116
                    long tick = data.placeTick.get(i);
117
118
                    if (lastTick != 0) {
119
                        sum += (tick - lastTick);
120
                    }
121
                    lastTick = tick;
122
123
                }
124
125
                double avg = sum / data.placeTick.size();
126
                if (avg < cc.scaffoldTimeAvg) {
127
                    cancel = violation("Time", Math.min((cc.scaffoldTimeAvg - (int) avg), 5), player, data, pData);
128
                    if (data.placeTick.size() > 20) data.placeTick.clear(); // Clear if it gets too big to prevent players being unable to place blocks
129
                } 
130
                else {
131
                    data.placeTick.clear();
132
                }
133
            }
134
        }
135
136
        // Sprint check - Prevent players from sprinting while placing blocks below them
137
        long diff = data.currentTick - data.sprintTime;
138
        if (cc.scaffoldSprint && Math.abs(player.getLocation().getPitch()) > 70
139
            && diff < 8 && yDistance < 0.1 && jumpPhase < 4) { 
140
141
            cancel = violation("Sprint", 1, player, data, pData);
142
        }
143
144
        // Rotate Check - Check for large changes in rotation between block placements
145
        // Note: Yaw speed change is also monitored. (See listener...)
146
        if (cc.scaffoldRotate) {
147
            data.lastYaw = player.getLocation().getYaw();
148
            TickListener yawTick = new TickListener() {
149
                @Override
150
                public void onTick(int tick, long timeLast) {
151
                    // Needs to be run on the next tick
152
                    // Most likely better way to to this with TickTask but this works as well
153
                    if (TickTask.getTick() != data.currentTick) {
154
                        float diff = Math.abs(data.lastYaw - player.getLocation().getYaw());
155
156
                        if (diff > cc.scaffoldRotateDiff) {
157
                            data.cancelNextPlace = violation("Rotate", Math.min((int) (diff - cc.scaffoldRotateDiff) / 10, 5), player, data, pData);
158
                            tags.clear();
159
                        }
160
                        TickTask.removeTickListener(this);
161
                    }
162
                }
163
            };
164
            TickTask.addTickListener(yawTick);
165
        }
166
167
        // Tool Switch - Check if the player is quickly switching inventory slots between block placements
168
        if (cc.scaffoldToolSwitch) {
169
170
            data.lastSlot = player.getInventory().getHeldItemSlot();
171
            TickListener toolSwitchTick = new TickListener() {
172
                @Override
173
                public void onTick(int tick, long timeLast) {
174
                    // Needs to be run on the next tick
175
                    // Most likely better way to to this with TickTask but this works as well
176
                    if (data.currentTick != TickTask.getTick()) {
177
                        if (data.lastSlot != player.getInventory().getHeldItemSlot()) {
178
                            data.cancelNextPlace = violation("ToolSwitch", 1, player, data, pData);
179
                            tags.clear();
180
                        }
181
                        TickTask.removeTickListener(this);
182
                    }
183
                }
184
            };
185
            TickTask.addTickListener(toolSwitchTick);
186
        }
187
        
188
        tags.clear();
189
        return cancel;
190
    }
191
192
    /**
193
     * Create a violation for Scaffold
194
     *
195
     * @param addTags
196
     * @param weight
197
     * @param player
198
     * @param data
199
     * @param pData
200
     * @return
201
     */
202
    private boolean violation(final String addTags, final int weight, final Player player,
203
                              final BlockPlaceData data, final IPlayerData pData) {
204
        ViolationData vd = new ViolationData(this, player, data.scaffoldVL, weight, pData.getGenericInstance(BlockPlaceConfig.class).scaffoldActions);
205
        tags.add(addTags);
206
        if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
207
        data.scaffoldVL += weight;
208
        return executeActions(vd).willCancel();
209
    }
210
}

How it counteracts this module

The blockplace package's Scaffold check is NoCheatPlus's dedicated behavioral detector for the scaffold cheat: one class with five independently configurable sub-checks (scaffold.angle, scaffold.time.active, scaffold.sprint, scaffold.rotate.active, scaffold.tool-switch). BlockPlaceListener gates the whole check on the bridging profile: the placement face must be horizontal (SOUTH, WEST, EAST or NORTH), the placed block must land 1 to 2 blocks below the player's previous y, be solid, and sit within 2.0 blocks of the player. That gate is the first thing to understand about Aqua 13's module: Down, SameY, Expand and plain forward bridging all produce horizontal contact faces and are checked, while a straight vertical tower places with a DOWN contact face and is skipped, which is why the tower modes are fought by movement checks instead.

Angle compares the player's look direction (the C03 rotation Aqua overrides in EventPreMotion) with the placed face normal and flags when it exceeds MAX_ANGLE, 90 degrees. Aqua's Static mode holds pitch at 82 and Calculated mode clamps pitch to 78-80, so the look vector points nearly straight down while the placement face is horizontal; the angle to the face normal exceeds the threshold on essentially every placement. Time records the placement tick whenever the pitch is over 70, the player is not sneaking and has no speed potion, then averages the recent intervals: Aqua places once per tick, an average of about one tick, which trips the configured average ceiling (scaffold.time.average) immediately. The sneaking exemption (placement must be more than 3 ticks after sneakTime) is exactly the bypass the EnableSneak setting buys. Sprint flags a placement while the player is sprinting (pitch over 70, sprint within 8 ticks, yDistance under 0.1, jumpPhase under 4): Aqua's Sprint toggle, on by default, fires it during forward bridging, and turning Sprint off or enabling EnableSneak dodges it. ToolSwitch re-reads the held slot on the next tick and flags any change: Aqua's EventSycItem handler writes the block slot into the event and the patched PlayerControllerMP then sends C09PacketHeldItemChange before each C08, so whenever the block is not already selected the slot visibly changes and the sub-check fires; holding the block pre-selected suppresses the C09 and passes.

Violations are weighted per sub-check (1 to 10) and accumulate into scaffoldVL; crossing the configured action threshold cancels the placement and requestUpdateInventory re-syncs the client, which also undoes the silent slot-switch desync the module relies on. The author's own TODOs concede that Angle duplicates the Direction check and that ToolSwitch is a cheat-specific heuristic, so hardened configs lean on Time, Sprint and Rotate. The practical bypass surface is the sneak exemption, the Sprint toggle, pre-selected block slots, and keeping yaw changes under scaffold.rotate.difference between placements, which Static mode with a still mouse does.

anticheat NCP Direction check (blockplace)

Direction.java52 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.blockplace;
16
17
import org.bukkit.entity.Player;
18
19
import fr.neatmonster.nocheatplus.actions.ActionList;
20
import fr.neatmonster.nocheatplus.checks.CheckType;
21
import fr.neatmonster.nocheatplus.checks.generic.block.AbstractBlockDirectionCheck;
22
23
/**
24
 * The Direction check will find out if a player tried to interact with
25
 * something that's not in their field of view.
26
 */
27
public class Direction extends AbstractBlockDirectionCheck<BlockPlaceData, BlockPlaceConfig> {
28
29
    /**
30
     * Instantiates a new direction check.
31
     */
32
    public Direction() {
33
        super(CheckType.BLOCKPLACE_DIRECTION);
34
    }
35
36
    @Override
37
    protected double addVL(Player player, double distance, BlockPlaceData data, BlockPlaceConfig cc) {
38
        data.directionVL += distance;
39
        return data.directionVL;
40
    }
41
42
    @Override
43
    protected ActionList getActions(BlockPlaceConfig cc) {
44
        return cc.directionActions;
45
    }
46
47
    @Override
48
    protected void cooldown(Player player, BlockPlaceData data, BlockPlaceConfig cc) {
49
        data.directionVL *= 0.9D;
50
    }
51
52
}

How it counteracts this module

Direction is a thin subclass; the detection lives in AbstractBlockDirectionCheck. For every BlockPlaceEvent the listener casts a ray from the player's eye position (foot location plus eye height, 1.62 for a player) along the look direction of the latest C03, against the placed block's AABB padded by 0.1 on the 1.8 path. If the ray intersects the block the placement passes and the violation level decays by 0.9; if it misses, the closest distance between the ray and the AABB is squared, square-rooted and added to directionVL. A FlyingQueueLookBlockChecker replays the queued recent flying packets, so a placement immediately after a rotation or teleport is judged against the position the server actually saw.

This check splits Aqua's two rotation modes cleanly. Calculated mode (rotationrecode2) aims at the support face point, which is the block center plus half the facing offset and therefore lies inside the placed block's AABB, so the ray intersects and the placement passes; the mouse-sensitivity snapping (yaw -= yaw % f3 with f3 from the sensitivity formula) quantizes the aim but does not break the intersection. Static mode sets the outgoing yaw to rotationYaw + 180 and pitch to 82. Bridging forward, the ray points backward and down while the placed block is ahead, so every placement contributes its miss distance to directionVL until the configured actions start cancelling placements. The C08 payload gives the cheater no help: the hit vector comes from getPositionByFace, not from the look ray, so the server accepts the placement while the check accumulates.

The bypass surface is directional: Static mode is safe only for vertical placements, where the pitch-82 ray still clips the block directly below the feet; any horizontal bridging while the static rotation is held flags. Calculated mode is direction-clean, which is exactly why the module offers it as the default aim and exposes Static as a mode for servers without a direction check. The price of Calculated mode is the steep pitch profile, which the Scaffold Angle and Time sub-checks then attack.

anticheat NCP FastPlace check (blockplace)

FastPlace.java103 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.blockplace;
16
17
import org.bukkit.block.Block;
18
import org.bukkit.entity.Player;
19
20
import fr.neatmonster.nocheatplus.checks.Check;
21
import fr.neatmonster.nocheatplus.checks.CheckType;
22
import fr.neatmonster.nocheatplus.players.IPlayerData;
23
import fr.neatmonster.nocheatplus.utilities.TickTask;
24
25
/**
26
 * A check used to verify if the player isn't placing blocks too quickly.
27
 */
28
public class FastPlace extends Check {
29
30
    /**
31
     * Instantiates a new fast place check.
32
     */
33
    public FastPlace() {
34
        super(CheckType.BLOCKPLACE_FASTPLACE);
35
    }
36
37
    /**
38
     * Checks a player.
39
     * 
40
     * @param player
41
     *            the player
42
     * @param block
43
     *            the block
44
     * @param tick
45
     * @param data
46
     * @param cc
47
     * @param pData
48
     * @return true, if successful
49
     */
50
    public boolean check(final Player player, final Block block, final int tick, final BlockPlaceData data, 
51
                         final BlockPlaceConfig cc, final IPlayerData pData) {
52
53
        data.fastPlaceBuckets.add(System.currentTimeMillis(), 1f);
54
        final boolean lag = pData.getCurrentWorldData().shouldAdjustToLag(type);
55
        // Full period frequency.
56
        final float fullScore = data.fastPlaceBuckets.score(1f);
57
58
        // Short term limit.
59
        if (tick < data.fastPlaceShortTermTick) {
60
            // TickTask got reset.
61
            data.fastPlaceShortTermTick = tick;
62
            data.fastPlaceShortTermCount = 1;
63
        }
64
        else if (tick - data.fastPlaceShortTermTick < cc.fastPlaceShortTermTicks) {
65
            // Account for server side lag.
66
            if (!lag || TickTask.getLag(50L * (tick - data.fastPlaceShortTermTick), true) < 1.2f) {
67
                // Within range, add.
68
                data.fastPlaceShortTermCount ++;
69
            }
70
            else {
71
                // Too much lag, reset.
72
                data.fastPlaceShortTermTick = tick;
73
                data.fastPlaceShortTermCount = 1;
74
            }
75
        }
76
        else { 
77
            data.fastPlaceShortTermTick = tick;
78
            data.fastPlaceShortTermCount = 1;
79
        }
80
81
        // Find out if one of both are violations:
82
        final float fullViolation;
83
        if (fullScore > cc.fastPlaceLimit) {
84
            // Account for server side lag.
85
            fullViolation = lag ? fullScore / TickTask.getLag(data.fastPlaceBuckets.bucketDuration() * data.fastPlaceBuckets.numberOfBuckets(), true) - cc.fastPlaceLimit
86
                                : fullScore - cc.fastPlaceLimit;
87
        }
88
        else fullViolation = 0;
89
        final float shortTermViolation = data.fastPlaceShortTermCount - cc.fastPlaceShortTermLimit; 
90
        final float violation = Math.max(fullViolation, shortTermViolation);
91
        boolean cancel = false;
92
93
        if (violation > 0.0) {
94
            final double change = (double) violation;
95
            data.fastPlaceVL += change;
96
            cancel = executeActions(player, data.fastPlaceVL, change, cc.fastPlaceActions).willCancel();
97
        }
98
        else if (data.fastPlaceVL > 0D && fullScore < cc.fastPlaceLimit * .75) {
99
            data.fastPlaceVL *= 0.95;
100
        }
101
        return cancel;
102
    }
103
}

How it counteracts this module

FastPlace is a rate check on the placement stream. Every placement adds a timestamp to a frequency bucket, the full-period score over the whole window is compared against fastplace.limit, and a short-term counter counts placements inside fastPlaceShortTermTicks against fastPlaceShortTermLimit. The violation is the larger of the two excesses and accumulates into fastPlaceVL; server-side lag is scaled out through TickTask so delays do not false-positive, and the score feeds the combined Improbable statistical check via fastplace.improbable.weight.

Aqua's module places once per tick, about 20 placements per second at full tick rate, which sits at the stock limit: on a clean 20 TPS server the module runs right at the boundary and is caught by the short-term window, which allows only a few placements within a few ticks. VerusFast is the hard hit: on top of the real placement it spams two fake C08PacketPlayerBlockPlacement packets per tick, one at BlockPos(-1,-1,-1) with direction byte 255 and a water bucket stack, one at the player position 1.5 blocks down with a stone stack. That triples the placement event rate to roughly 60 per second, blowing through both the full-period score and the short-term counter within the first second, regardless of what the fake payloads mean to other checks.

The bypass surface is thin: the module has no rate spreader (AutoDisable stops the module, it does not pace it), so the only practical ways under FastPlace are a tower mode that places less often or a server whose lag adjustment masks the burst. The listener also runs FastPlace before the Scaffold check, so a cancelled FastPlace violation prevents the more specific sub-checks from ever seeing the event.

anticheat NCP SurvivalFly (tower counter)

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 is NoCheatPlus's flagship movement check, run on every C03 flying packet. It reconstructs the move with full collision and ground modeling: ground state comes from isOnGround plus the BlockChangeTracker opportune-ground lookup, so a block the player just placed below himself counts as ground the same tick (the code comments call this ground appearing out of thin air from a block place). Vertical motion is predicted through the LiftOffEnvelope model: at lift-off from ground the allowed upward distance is the jump gain (the NORMAL envelope is 0.42, the EntityLiving BASE_JUMP_POWER, scaled by jump boost), afterwards gravity and friction model each air tick, and the actual vertical delta is compared against the prediction as offset = yDistance - yAllowedDistance. A positive offset that no workaround or stored velocity explains becomes the yDistanceAboveLimit, accumulates the violation level, and the check returns a set-back location that teleports the player back.

The six tower modes are tuned against exactly this envelope. Cubecraft's motionY 0.42 equals the legal lift-off gain, so the per-move speed is legal; its 50 ms gate caps jump frequency. Watchdog jumps 0.409, under the gain, and damps the third air tick with a RandomUtil factor between 0.99089 and 0.99099 so the arc reads as natural momentum loss; per-move it is legal. UpdatedNCP fires 0.4196, 0.0004 under the gain, at air ticks where ticksExisted % 3 == 1 while standing still: the vertical speed is legal but the timing is not, because mid-air the envelope expects falling motion, so a re-boost on the third air tick exceeds the prediction and accumulates vdistrel violations; this is the exact fight the mode's name documents. IntaveFast's 0.405 with the 0.08 damp at the fifth air tick is the same shape. VerusFast's 0.70096 exceeds the 0.42 gain by two-thirds, so the first boosted move is already beyond the prediction and flags immediately; the fake C08 spam is useless against a movement check, which is why the mode rides a 5000 ms timer before resetting.

The envelope mirrors vanilla exactly (the jump gain scales with jump boost through the attribute jumpGainMultiplier), so there is no tuning headroom on the gain itself. The evasion surface is the timing dimension: jumpDelay enforces one lift-off per tick, and sfJumpPhase tracks consecutive air moves and feeds the blockplace Scaffold Sprint sub-check through the jumpPhase < 4 gate. Set-backs interrupt the tower rhythm, which is what the damped Watchdog and IntaveFast profiles try to smooth over; a scaffold tower is a series of legal lift-offs from its own blocks, and the check's grip is the mid-air re-boost and anything above the 0.42 gain.

← Back to Analysis Hub