ElytraFly module

ElytraFly: Minecraft 26.3 cheat module, full source for every implementation (4 clients: OfflineClient, Combatant, KiwiClient, …).

4 implementationsMOVEMENT

Full module source: 4 implementations

Every implementation below is the complete module file, verbatim. Expand a client to read its code.

OfflineClientMOVEMENTsrc/main/java/com/jellypudding/offlineclient/modules/movement/ElytraFly.javaJava · 1,017 lines · 40.2 KB

Full elytra control without firework rockets.

SettingsModeHorizontal speedVertical speedHold heightLook to diveHover on sneakInstant stopSneak to dropFall multiplierAccelerationAcceleration startAcceleration stepAuto pilotMinimum heightCruise speedAltitudeLower heightUpper heightPitch up speedPitch down speedRocketsRocket delayLock headingHeadingYawLock pitchPitchAuto jumpManual take offSprint alwaysRestartRestart delayInstant dropAuto take offGround startKeep glidingStop in waterChunk guardLook aheadNo crash
ElytraFly.javaJava · Minecraft 26.2 · 1,017 lines · 40.2 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.movement;
2
3
import com.jellypudding.offlineclient.OfflineClient;
4
import com.jellypudding.offlineclient.event.Subscribe;
5
import com.jellypudding.offlineclient.event.events.PacketReceiveEvent;
6
import com.jellypudding.offlineclient.event.events.PostMotionEvent;
7
import com.jellypudding.offlineclient.event.events.TickEvent;
8
import com.jellypudding.offlineclient.module.Category;
9
import com.jellypudding.offlineclient.module.Module;
10
import com.jellypudding.offlineclient.modules.player.ChestSwap;
11
import com.jellypudding.offlineclient.setting.BoolSetting;
12
import com.jellypudding.offlineclient.setting.EnumSetting;
13
import com.jellypudding.offlineclient.setting.NumberSetting;
14
import com.jellypudding.offlineclient.util.ChatUtil;
15
import com.jellypudding.offlineclient.util.InputUtil;
16
import com.jellypudding.offlineclient.util.InventoryUtil;
17
import com.jellypudding.offlineclient.util.Modules;
18
import com.jellypudding.offlineclient.util.MovementUtil;
19
20
import net.minecraft.core.BlockPos;
21
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
22
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
23
import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket;
24
import net.minecraft.util.Mth;
25
import net.minecraft.world.entity.EquipmentSlot;
26
import net.minecraft.world.entity.player.Abilities;
27
import net.minecraft.world.entity.player.Input;
28
import net.minecraft.world.item.ItemStack;
29
import net.minecraft.world.item.Items;
30
import net.minecraft.world.level.ClipContext;
31
import net.minecraft.world.phys.AABB;
32
import net.minecraft.world.phys.HitResult;
33
import net.minecraft.world.phys.Vec3;
34
35
// Control nudges the vanilla glide and Cruise flies a dive and climb cycle on its own.
36
// Packet fakes the glide with packets and Bounce hops along the ground with wings open.
37
public final class ElytraFly extends Module {
38
39
    public enum Mode { CONTROL, CRUISE, PACKET, BOUNCE }
40
    public enum Altitude { TAKE_OFF, BAND, FREE }
41
    public enum Heading { FREE, SNAP, FIXED }
42
    public enum ChestSwapMode { NEVER, ALWAYS, WAIT_FOR_GROUND }
43
44
    // Around forty degrees down is where a glide trades the most height for speed.
45
    private static final float DIVE_PITCH = 40;
46
    private static final float CLIMB_PITCH = -30;
47
48
    // Each acceleration step adds this much speed a tick.
49
    private static final double RAMP_UNIT = 0.1;
50
51
    private static final double TICKS_PER_SECOND = 20;
52
53
    // Below this fraction of the target speed a climb would stall.
54
    private static final double STALL_FRACTION = 0.5;
55
56
    private static final double LOW_DURABILITY = 0.05;
57
58
    private static final double TAKE_OFF_CLEARANCE = 3;
59
60
    // Speed kept each tick whilst waiting for chunks to arrive.
61
    private static final double CHUNK_BRAKE = 0.6;
62
63
    // Ticks after a standing jump in which the glide is forced open.
64
    private static final int TAKE_OFF_WINDOW = 4;
65
66
    // Ticks to leave the server alone after asking for a glide.
67
    private static final int RESTART_COOLDOWN = 5;
68
69
    // Pitched further down than this is a dive and the height is let go when asked.
70
    private static final float HOLD_PITCH_LIMIT = 25;
71
72
    // Ticks of travel the crash check sweeps ahead at the least and at the most.
73
    private static final double CRASH_TICKS = 4;
74
    private static final int CRASH_MAX_TICKS = 40;
75
76
    // Share of the safe speed kept after a brake. Leaves room to add some back.
77
    private static final double CRASH_KEEP = 0.6;
78
79
    // How hard the held height pulls back per block of drift.
80
    // The most it may pull in a single tick.
81
    private static final double HOLD_GAIN = 0.3;
82
    private static final double HOLD_STEP = 0.1;
83
    // How quickly a steady drift is learned and cancelled outright.
84
    private static final double HOLD_LEARN = 0.02;
85
    private static final double HOLD_BIAS_LIMIT = 0.05;
86
87
    private static final double GRAVITY = 0.08;
88
89
    // Auto hover eases down inside this and stops inside the smaller gap.
90
    private static final double HOVER_APPROACH = 2;
91
    private static final double HOVER_GAP = 0.4;
92
    private static final double HOVER_SINK = 0.1;
93
94
    // Bounce turns to the nearest of these headings.
95
    private static final float YAW_SNAP = 45;
96
97
    private final EnumSetting<Mode> mode = new EnumSetting<>("Mode",
98
        "Who does the flying.", Mode.CONTROL)
99
        .describe(Mode.CONTROL, "You steer. The keys push you along and up and down.")
100
        .describe(Mode.CRUISE, "Flies a dive and climb cycle on its own for long trips.")
101
        .describe(Mode.PACKET, "Fakes a glide with packets whilst you fly like creative. Works on some servers.")
102
        .describe(Mode.BOUNCE, "Hops along the ground with the wings open. Fast on the nether roof.");
103
    private final NumberSetting speed = new NumberSetting("Horizontal speed",
104
        "How hard the movement keys push you along.", 1, 0.2, 5, 0.1, "x")
105
        .min(0.1).max(20).under(mode, Mode.CONTROL, Mode.PACKET);
106
    private final NumberSetting climbSpeed = new NumberSetting("Vertical speed",
107
        "How hard jump and sneak push you up and down.", 1, 0.2, 5, 0.1, "x")
108
        .min(0.1).max(20).under(mode, Mode.CONTROL, Mode.PACKET);
109
    private final BoolSetting holdHeight = new BoolSetting("Hold height",
110
        "Holds you at your current height whilst neither jump nor sneak is held.", true)
111
        .under(mode, Mode.CONTROL);
112
    private final BoolSetting lookToDive = new BoolSetting("Look to dive",
113
        "Looking down steeply lets the glide dive as it would without the hold.", false)
114
        .under(holdHeight);
115
    private final BoolSetting autoHover = new BoolSetting("Hover on sneak",
116
        "Sneaking sinks you slowly and stops a block above the ground instead of landing.", false)
117
        .under(mode, Mode.CONTROL);
118
    private final BoolSetting instantStop = new BoolSetting("Instant stop",
119
        "Kills your momentum when you release the keys.", false)
120
        .under(mode, Mode.CONTROL);
121
    private final BoolSetting sneakDrop = new BoolSetting("Sneak to drop",
122
        "Holding sneak ends the glide. Wins over Hover on sneak.", false)
123
        .under(mode, Mode.CONTROL);
124
    private final NumberSetting fallMultiplier = new NumberSetting("Fall multiplier",
125
        "Scales the natural sink whilst Hold height is off. Lower values sink slower.",
126
        1, 0, 1, 0.01, "x").min(0).max(1)
127
        .under(holdHeight, () -> mode.is(Mode.CONTROL) && !holdHeight.isOn());
128
    private final BoolSetting acceleration = new BoolSetting("Acceleration",
129
        "Builds the horizontal speed up over time instead of applying it at once.", false)
130
        .under(mode, Mode.CONTROL, Mode.PACKET);
131
    private final NumberSetting accelerationStart = new NumberSetting("Acceleration start",
132
        "The speed the ramp begins from.", 0, 0, 5, 0.1, "x").min(0).max(20)
133
        .under(acceleration);
134
    private final NumberSetting accelerationStep = new NumberSetting("Acceleration step",
135
        "How quickly the ramp climbs towards the horizontal speed.", 1, 0.1, 5, 0.1, "")
136
        .min(0.1).max(5)
137
        .under(acceleration);
138
    private final BoolSetting autoPilot = new BoolSetting("Auto pilot",
139
        "Holds forward for you whilst you glide above the minimum height.", false)
140
        .under(mode, Mode.CONTROL, Mode.PACKET);
141
    private final NumberSetting autoPilotHeight = new NumberSetting("Minimum height",
142
        "Auto pilot only pushes forward above this height.", 120, -64, 320, 1, "")
143
        .min(-128).max(2000)
144
        .under(autoPilot);
145
    private final NumberSetting cruiseSpeed = new NumberSetting("Cruise speed",
146
        "The speed the dive and climb cycle aims for.", 30, 10, 60, 1, " bps")
147
        .min(5).under(mode, Mode.CRUISE);
148
    private final EnumSetting<Altitude> altitude = new EnumSetting<>("Altitude",
149
        "How the cycle picks the heights it dives and climbs between.", Altitude.TAKE_OFF)
150
        .describe(Altitude.TAKE_OFF, "Cycles around the height you set off from. Jump and sneak nudge it.")
151
        .describe(Altitude.BAND, "Cycles between the two heights you set below.")
152
        .describe(Altitude.FREE, "Speed alone decides when to dive and when to climb.")
153
        .under(mode, Mode.CRUISE);
154
    private final NumberSetting lowerHeight = new NumberSetting("Lower height",
155
        "Starts climbing once you sink to this height.", 180, -64, 320, 1, "")
156
        .min(-128).max(2000)
157
        .under(altitude, Altitude.BAND);
158
    private final NumberSetting upperHeight = new NumberSetting("Upper height",
159
        "Starts diving once you rise to this height.", 220, -64, 320, 1, "")
160
        .min(-128).max(2000)
161
        .under(altitude, Altitude.BAND);
162
    private final NumberSetting pitchUpSpeed = new NumberSetting("Pitch up speed",
163
        "Degrees a tick the nose comes up when a climb starts.", 6, 0.5, 20, 0.05, " degrees")
164
        .min(0.5).max(90)
165
        .under(mode, Mode.CRUISE);
166
    private final NumberSetting pitchDownSpeed = new NumberSetting("Pitch down speed",
167
        "Degrees a tick the nose goes down when a dive starts.", 6, 0.5, 20, 0.05, " degrees")
168
        .min(0.5).max(90)
169
        .under(mode, Mode.CRUISE);
170
    private final BoolSetting rockets = new BoolSetting("Rockets",
171
        "Fires a rocket from your hotbar whenever the cycle runs out of speed.", false)
172
        .under(mode, Mode.CRUISE);
173
    private final NumberSetting rocketDelay = new NumberSetting("Rocket delay",
174
        "Seconds between rockets.", 4, 1, 20, 0.5, "s").min(0.5)
175
        .under(rockets);
176
    private final BoolSetting lockYaw = new BoolSetting("Lock heading",
177
        "Keeps the heading you set off with.", true)
178
        .under(mode, Mode.CRUISE);
179
    private final EnumSetting<Heading> bounceHeading = new EnumSetting<>("Heading",
180
        "How the bounce steers.", Heading.SNAP)
181
        .describe(Heading.FREE, "You steer with the mouse.")
182
        .describe(Heading.SNAP, "Snaps your heading to the nearest 45 degrees.")
183
        .describe(Heading.FIXED, "Holds the yaw you set below.")
184
        .under(mode, Mode.BOUNCE);
185
    private final NumberSetting bounceYaw = new NumberSetting("Yaw",
186
        "The heading held whilst bouncing.", 0, 0, 360, 1, " degrees").min(0).max(360)
187
        .under(bounceHeading, Heading.FIXED);
188
    private final BoolSetting lockPitch = new BoolSetting("Lock pitch",
189
        "Holds the pitch below whilst bouncing. Off leaves the pitch to you.", true)
190
        .under(mode, Mode.BOUNCE);
191
    private final NumberSetting bouncePitch = new NumberSetting("Pitch",
192
        "The pitch held whilst bouncing.", 0, -90, 90, 1, " degrees")
193
        .under(lockPitch);
194
    private final BoolSetting autoJump = new BoolSetting("Auto jump",
195
        "Holds jump for you. Off only holds forward and leaves the jumping to you.", true)
196
        .under(mode, Mode.BOUNCE);
197
    private final BoolSetting manualTakeOff = new BoolSetting("Manual take off",
198
        "Leaves opening the wings to you. The wings still reopen after a pull back.", false)
199
        .under(mode, Mode.BOUNCE);
200
    private final BoolSetting sprintAlways = new BoolSetting("Sprint always",
201
        "Keeps sprint on in the air too. Off sprints on the ground only and stops the view zoom flicker.", true)
202
        .under(mode, Mode.BOUNCE);
203
    private final BoolSetting restart = new BoolSetting("Restart",
204
        "Opens the wings again after the server pulls you back.", true)
205
        .under(mode, Mode.BOUNCE);
206
    private final NumberSetting restartDelay = new NumberSetting("Restart delay",
207
        "Ticks to wait after the server pulls you back before the wings open again.",
208
        20, 0, 100, 1, " ticks").min(0)
209
        .under(restart);
210
    private final BoolSetting instantDrop = new BoolSetting("Instant drop",
211
        "Turning the module off midair ends the glide and drops you at once.", false)
212
        .under(mode, Mode.CONTROL, Mode.CRUISE, Mode.PACKET);
213
    private final BoolSetting autoTakeOff = new BoolSetting("Auto take off",
214
        "Opens the elytra for you as soon as you fall.", true);
215
    private final BoolSetting groundStart = new BoolSetting("Ground start",
216
        "Jump straight into a glide from standing.", true);
217
    private final BoolSetting keepGliding = new BoolSetting("Keep gliding",
218
        "Restarts a glide the game cancels midair.", true);
219
    private final BoolSetting stopInWater = new BoolSetting("Stop in water",
220
        "Does nothing whilst you are in water.", true);
221
    private final BoolSetting chunkGuard = new BoolSetting("Chunk guard",
222
        "Slows you down before you fly into ground the client has not loaded.", true);
223
    private final NumberSetting chunkLookahead = new NumberSetting("Look ahead",
224
        "How far in front to check for loaded ground.", 24, 8, 64, 1, " blocks")
225
        .under(chunkGuard);
226
    private final BoolSetting noCrash = new BoolSetting("No crash",
227
        "Brakes before you fly into a wall or the ground. The faster you go the further ahead it looks.", false);
228
    private final NumberSetting crashLookAhead = new NumberSetting("Crash look ahead",
229
        "The least distance along your flight path to check.", 5, 1, 15, 1, " blocks").min(1).max(32)
230
        .under(noCrash);
231
    private final BoolSetting replaceElytra = new BoolSetting("Replace elytra",
232
        "Swaps in a fresher elytra from your inventory once the worn one runs low.", false);
233
    private final NumberSetting replaceAt = new NumberSetting("Replace at",
234
        "Durability points left that count as run low.", 10, 1, 100, 1).min(1)
235
        .under(replaceElytra);
236
    private final BoolSetting durabilityGuard = new BoolSetting("Durability guard",
237
        "Stops helping and warns you when the elytra is nearly broken.", true);
238
    private final EnumSetting<ChestSwapMode> chestSwap = new EnumSetting<>("Chest swap",
239
        "Runs ChestSwap when the module toggles.", ChestSwapMode.NEVER)
240
        .describe(ChestSwapMode.NEVER, "Leaves your chest slot alone.")
241
        .describe(ChestSwapMode.ALWAYS, "Puts the elytra on when enabled and the chestplate back when disabled.")
242
        .describe(ChestSwapMode.WAIT_FOR_GROUND, "Puts the elytra on when enabled and the chestplate back once you land.");
243
    private final BoolSetting replenishRockets = new BoolSetting("Replenish rockets",
244
        "Moves rockets from your inventory into a hotbar slot once the hotbar has none.", false);
245
    private final NumberSetting rocketSlot = new NumberSetting("Rocket slot",
246
        "The hotbar slot the rockets go to.", 9, 1, 9, 1, "").min(1).max(9)
247
        .under(replenishRockets);
248
249
    // The mode the last tick ran under.
250
    private Mode applied;
251
252
    // The ramped horizontal speed whilst Acceleration is on.
253
    private double ramp;
254
    private boolean pilotHeld;
255
    // The view zoom scale put aside whilst Bounce sprints on the ground only.
256
    private double savedFovScale = -1;
257
    // Set once a Bounce pull back has waited out its delay.
258
    private boolean reopen;
259
260
    // Runs on after the module is off until the glide has ended.
261
    private final Object dropWatcher = new Object() {
262
        @Subscribe
263
        private void onTick(TickEvent event) {
264
            if (isEnabled() || !inGame() || !mc.player.isFallFlying()) {
265
                unwatch(this);
266
                return;
267
            }
268
            mc.player.setDeltaMovement(Vec3.ZERO);
269
            mc.player.connection.send(new ServerboundMovePlayerPacket.StatusOnly(true,
270
                mc.player.horizontalCollision));
271
        }
272
    };
273
274
    // Runs on after the module is off until the player has landed.
275
    private final Object landingWatcher = new Object() {
276
        @Subscribe
277
        private void onTick(TickEvent event) {
278
            if (isEnabled() || !inGame()) {
279
                unwatch(this);
280
                return;
281
            }
282
            if (mc.player.onGround()) {
283
                unwatch(this);
284
                swapChest(true);
285
            }
286
        }
287
    };
288
289
    private int restartCooldown;
290
    // Ticks left to force the elytra open after a standing jump.
291
    private int takeOffWindow;
292
    private boolean wasGliding;
293
    private boolean warned;
294
    // True from a sneak drop until the sneak key is let go.
295
    // Keeps the glide from restarting.
296
    private boolean dropped;
297
298
    // The height held or NaN whilst the keys have it and the drift learned to date.
299
    private double heldY = Double.NaN;
300
    private double holdBias;
301
302
    private double cruiseY;
303
    private float cruiseYaw;
304
    private boolean diving;
305
    private float forcedPitch;
306
    private boolean cruising;
307
    private int rocketTimer;
308
309
    // Bounce keys held down by the module and the wait after a rubberband.
310
    private boolean bounceKeys;
311
    private int bounceRestart;
312
    // Set from the packet thread when the server sends the player back.
313
    private volatile boolean rubberbanded;
314
315
    public ElytraFly() {
316
        super("ElytraFly", "Full elytra control without firework rockets.", Category.MOVEMENT);
317
        addSettings(mode, speed, climbSpeed, holdHeight, lookToDive, fallMultiplier, autoHover,
318
            instantStop, sneakDrop, acceleration, accelerationStart, accelerationStep,
319
            autoPilot, autoPilotHeight,
320
            cruiseSpeed, altitude, lowerHeight, upperHeight, pitchUpSpeed, pitchDownSpeed,
321
            rockets, rocketDelay, lockYaw,
322
            bounceHeading, bounceYaw, lockPitch, bouncePitch, autoJump, manualTakeOff,
323
            sprintAlways, restart, restartDelay, instantDrop,
324
            autoTakeOff, groundStart, keepGliding, stopInWater, chunkGuard, chunkLookahead,
325
            noCrash, crashLookAhead, replaceElytra, replaceAt, durabilityGuard,
326
            chestSwap, replenishRockets, rocketSlot);
327
        searchTags("elytra", "glide", "fly", "cruise", "bounce", "packet fly", "pitch 40");
328
    }
329
330
    public boolean inCruiseMode() {
331
        return mode.is(Mode.CRUISE);
332
    }
333
334
    @Override
335
    public String getSuffix() {
336
        return switch (mode.getValue()) {
337
            case CRUISE -> cruising ? (diving ? "diving" : "climbing") : "cruise";
338
            case PACKET -> "packet";
339
            case BOUNCE -> "bounce";
340
            case CONTROL -> speed.getValueString() + " " + climbSpeed.getValueString();
341
        };
342
    }
343
344
    @Override
345
    protected void onEnable() {
346
        applied = mode.getValue();
347
        restartCooldown = 0;
348
        takeOffWindow = 0;
349
        wasGliding = false;
350
        cruising = false;
351
        warned = false;
352
        dropped = false;
353
        rocketTimer = 0;
354
        bounceRestart = 0;
355
        rubberbanded = false;
356
        heldY = Double.NaN;
357
        holdBias = 0;
358
        ramp = 0;
359
        pilotHeld = false;
360
        reopen = false;
361
        if (inGame() && chestSwap.getValue() != ChestSwapMode.NEVER
362
            && !mc.player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA)) {
363
            swapChest(false);
364
        }
365
    }
366
367
    @Override
368
    protected void onDisable() {
369
        cruising = false;
370
        releaseBounceKeys();
371
        releasePilot();
372
        restoreFovScale();
373
        if (mc.player == null) {
374
            return;
375
        }
376
        if (applied == Mode.PACKET) {
377
            endPacketFlight();
378
        }
379
        if (instantDrop.isOn() && applied != Mode.BOUNCE && mc.player.isFallFlying()) {
380
            watch(dropWatcher);
381
        }
382
        if (chestSwap.is(ChestSwapMode.ALWAYS)) {
383
            swapChest(true);
384
        } else if (chestSwap.is(ChestSwapMode.WAIT_FOR_GROUND)) {
385
            watch(landingWatcher);
386
        }
387
    }
388
389
    private static void watch(Object watcher) {
390
        OfflineClient.INSTANCE.getEventBus().register(watcher);
391
    }
392
393
    private static void unwatch(Object watcher) {
394
        OfflineClient.INSTANCE.getEventBus().unregister(watcher);
395
    }
396
397
    // ChestSwap decides which piece goes on. Taking the elytra off only makes
398
    // sense whilst one is worn.
399
    private void swapChest(boolean takeOff) {
400
        ChestSwap module = Modules.get(ChestSwap.class);
401
        if (module == null) {
402
            return;
403
        }
404
        if (takeOff && !mc.player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA)) {
405
            return;
406
        }
407
        module.swap();
408
    }
409
410
    @Subscribe
411
    private void onTick(TickEvent event) {
412
        if (!inGame() || mc.player.isSpectator()) {
413
            return;
414
        }
415
        // A mode change lets go of whatever the old mode was holding.
416
        if (applied != mode.getValue()) {
417
            releaseBounceKeys();
418
            releasePilot();
419
            restoreFovScale();
420
            if (applied == Mode.PACKET) {
421
                endPacketFlight();
422
            }
423
            applied = mode.getValue();
424
        }
425
        if (restartCooldown > 0) {
426
            restartCooldown--;
427
        }
428
        if (rocketTimer > 0) {
429
            rocketTimer--;
430
        }
431
        if (stopInWater.isOn() && (mc.player.isInWater() || mc.player.isUnderWater())) {
432
            cruising = false;
433
            wasGliding = false;
434
            ramp = 0;
435
            releaseBounceKeys();
436
            releasePilot();
437
            return;
438
        }
439
        if (replaceElytra.isOn()) {
440
            replaceWornElytra();
441
        }
442
        if (replenishRockets.isOn()) {
443
            replenishHotbarRockets();
444
        }
445
        if (durabilityGuard.isOn() && checkDurability()) {
446
            cruising = false;
447
            wasGliding = mc.player.isFallFlying();
448
            releaseBounceKeys();
449
            releasePilot();
450
            return;
451
        }
452
        if (dropped && !mc.player.input.keyPresses.shift()) {
453
            dropped = false;
454
        }
455
456
        if (mode.is(Mode.PACKET)) {
457
            pilotTick();
458
            packetTick();
459
            return;
460
        }
461
        if (mode.is(Mode.BOUNCE)) {
462
            bounceTick();
463
            return;
464
        }
465
466
        if (takeOffWindow > 0) {
467
            takeOffWindow--;
468
        }
469
        if (!mc.player.isFallFlying()) {
470
            cruising = false;
471
            heldY = Double.NaN;
472
            ramp = 0;
473
            releasePilot();
474
            if (!dropped) {
475
                jumpOff();
476
                startGlide();
477
            }
478
            wasGliding = false;
479
            return;
480
        }
481
        takeOffWindow = 0;
482
        wasGliding = true;
483
        pilotTick();
484
        if (mode.is(Mode.CONTROL) && sneakDrop.isOn() && mc.player.input.keyPresses.shift()) {
485
            // The same command that opens a glide closes one that is already open.
486
            sendStartGlide();
487
            dropped = true;
488
            return;
489
        }
490
491
        if (mode.is(Mode.CRUISE)) {
492
            cruiseTick();
493
        } else {
494
            cruising = false;
495
            controlTick();
496
        }
497
498
        if (chunkGuard.isOn() && aheadIsUnloaded()) {
499
            brakeForChunks();
500
        }
501
        if (noCrash.isOn()) {
502
            brakeForBlocks();
503
        }
504
    }
505
506
    // Sweeps the body along the flight path a tick at a time and brakes before
507
    // the first tick that would touch a block. A margin covers the glide's added speed.
508
    private void brakeForBlocks() {
509
        Vec3 velocity = mc.player.getDeltaMovement();
510
        double pace = velocity.length();
511
        if (pace < 0.01) {
512
            return;
513
        }
514
        int ticks = (int) Math.ceil(Math.max(crashLookAhead.getValue(), pace * CRASH_TICKS) / pace);
515
        ticks = Math.min(ticks, CRASH_MAX_TICKS);
516
        AABB box = mc.player.getBoundingBox();
517
        for (int step = 1; step <= ticks; step++) {
518
            if (mc.level.noCollision(mc.player, box.move(velocity.scale(step)))) {
519
                continue;
520
            }
521
            // Stop short of the tick that would hit.
522
            // Two ticks out means one tick of travel is left.
523
            double allowed = pace * Math.max(0, step - 1) / ticks * CRASH_KEEP;
524
            if (step <= 2) {
525
                allowed = 0;
526
            }
527
            if (pace > allowed) {
528
                mc.player.setDeltaMovement(velocity.scale(allowed / pace));
529
            }
530
            return;
531
        }
532
    }
533
534
    // A worn elytra at the threshold gives way to the fullest one in the bag.
535
    private void replaceWornElytra() {
536
        ItemStack worn = mc.player.getItemBySlot(EquipmentSlot.CHEST);
537
        if (!worn.is(Items.ELYTRA) || worn.getMaxDamage() - worn.getDamageValue() > replaceAt.getInt()) {
538
            return;
539
        }
540
        if (!InventoryUtil.inventoryFree()) {
541
            return;
542
        }
543
        int best = -1;
544
        int bestLeft = worn.getMaxDamage() - worn.getDamageValue();
545
        for (int i = 0; i < InventoryUtil.WHOLE_INVENTORY; i++) {
546
            ItemStack stack = mc.player.getInventory().getItem(i);
547
            if (!stack.is(Items.ELYTRA)) {
548
                continue;
549
            }
550
            int left = stack.getMaxDamage() - stack.getDamageValue();
551
            if (left > bestLeft) {
552
                bestLeft = left;
553
                best = i;
554
            }
555
        }
556
        if (best != -1) {
557
            InventoryUtil.swap(InventoryUtil.networkSlot(best), InventoryUtil.CHEST_SLOT);
558
        }
559
    }
560
561
    // A stack from the bag fills the chosen slot once the hotbar has run dry.
562
    private void replenishHotbarRockets() {
563
        if (InventoryUtil.hotbarSlot(stack -> stack.is(Items.FIREWORK_ROCKET)) != -1
564
            || !InventoryUtil.inventoryFree()) {
565
            return;
566
        }
567
        int found = InventoryUtil.findSlot(Items.FIREWORK_ROCKET, InventoryUtil.WHOLE_INVENTORY);
568
        if (found == -1) {
569
            return;
570
        }
571
        InventoryUtil.swap(InventoryUtil.networkSlot(found),
572
            InventoryUtil.networkSlot(rocketSlot.getInt() - 1));
573
    }
574
575
    // Holds forward whilst gliding high enough and lets go below that.
576
    private void pilotTick() {
577
        boolean wanted = autoPilot.isOn() && mc.player.isFallFlying()
578
            && mc.player.getY() > autoPilotHeight.getValue();
579
        if (wanted) {
580
            InputUtil.hold(mc.options.keyUp);
581
            pilotHeld = true;
582
        } else {
583
            releasePilot();
584
        }
585
    }
586
587
    private void releasePilot() {
588
        if (!pilotHeld) {
589
            return;
590
        }
591
        pilotHeld = false;
592
        InputUtil.release(mc.options.keyUp);
593
    }
594
595
    // The speed the keys push with this tick. Acceleration ramps it up from a
596
    // start value and the ramp falls back to nothing whilst the keys are idle.
597
    private double rampedSpeed(boolean steering) {
598
        if (!acceleration.isOn()) {
599
            return speed.getValue();
600
        }
601
        if (!steering) {
602
            ramp = 0;
603
            return 0;
604
        }
605
        double from = Math.max(ramp, accelerationStart.getValue());
606
        ramp = Math.min(from + accelerationStep.getValue() * RAMP_UNIT, speed.getValue());
607
        return ramp;
608
    }
609
610
    // Sprinting only on the ground pumps the view zoom on and off every hop.
611
    // The zoom is switched off for the ride and put back after.
612
    private void applyFovScale() {
613
        if (sprintAlways.isOn() || savedFovScale >= 0) {
614
            return;
615
        }
616
        savedFovScale = mc.options.fovEffectScale().get();
617
        mc.options.fovEffectScale().set(0.0);
618
    }
619
620
    private void restoreFovScale() {
621
        if (savedFovScale < 0) {
622
            return;
623
        }
624
        mc.options.fovEffectScale().set(savedFovScale);
625
        savedFovScale = -1;
626
    }
627
628
    // True when the ground ahead has not loaded. The client sees empty air where
629
    // the server has terrain.
630
    private boolean aheadIsUnloaded() {
631
        Vec3 velocity = mc.player.getDeltaMovement();
632
        if (velocity.horizontalDistance() < 0.1) {
633
            return false;
634
        }
635
        Vec3 heading = new Vec3(velocity.x, 0, velocity.z).normalize()
636
            .scale(chunkLookahead.getValue());
637
        BlockPos ahead = BlockPos.containing(mc.player.position().add(heading));
638
        return !mc.level.isLoaded(ahead);
639
    }
640
641
    // Bleeds the speed off each tick. The glide stays controllable.
642
    private void brakeForChunks() {
643
        Vec3 velocity = mc.player.getDeltaMovement();
644
        mc.player.setDeltaMovement(velocity.x * CHUNK_BRAKE, Math.max(velocity.y, -0.1),
645
            velocity.z * CHUNK_BRAKE);
646
    }
647
648
    // Additive nudges. The glide itself stays vanilla.
649
    private void controlTick() {
650
        Input keys = mc.player.input.keyPresses;
651
        Vec3 velocity = mc.player.getDeltaMovement();
652
        boolean steering = keys.forward() || keys.backward() || keys.left() || keys.right();
653
        double accel = GRAVITY * rampedSpeed(steering);
654
655
        double vx = velocity.x;
656
        double vy = velocity.y;
657
        double vz = velocity.z;
658
659
        double yaw = Math.toRadians(mc.player.getYRot());
660
        double forwardX = -Math.sin(yaw);
661
        double forwardZ = Math.cos(yaw);
662
        double rightX = -Math.cos(yaw);
663
        double rightZ = -Math.sin(yaw);
664
665
        if (keys.forward()) {
666
            vx += forwardX * accel;
667
            vz += forwardZ * accel;
668
        }
669
        if (keys.backward()) {
670
            vx -= forwardX * accel;
671
            vz -= forwardZ * accel;
672
        }
673
        if (keys.right()) {
674
            vx += rightX * accel;
675
            vz += rightZ * accel;
676
        }
677
        if (keys.left()) {
678
            vx -= rightX * accel;
679
            vz -= rightZ * accel;
680
        }
681
682
        double climb = climbSpeed.getValue();
683
        float pitch = mc.player.getXRot();
684
        boolean holding = false;
685
        if (keys.jump()) {
686
            vy += GRAVITY * climb;
687
        } else if (keys.shift()) {
688
            vy = autoHover.isOn() ? hover(vy, climb) : vy - GRAVITY / 2 * climb;
689
        } else if (holdHeight.isOn() && pitch < 0 && steering) {
690
            // Looking up whilst moving climbs.
691
            // The lift only stops the sink underneath the climb.
692
            vy = Math.max(vy, glideSink(pitch));
693
        } else if (holdHeight.isOn() && (!lookToDive.isOn() || pitch < HOLD_PITCH_LIMIT)) {
694
            vy = holdHeight(vy);
695
            holding = true;
696
        } else if (!holdHeight.isOn() && vy < 0) {
697
            vy *= fallMultiplier.getValue();
698
        }
699
        if (!holding) {
700
            heldY = Double.NaN;
701
        }
702
703
        if (instantStop.isOn() && !steering) {
704
            vx = 0;
705
            vz = 0;
706
            // The lift that holds the height is not momentum.
707
            if (!keys.jump() && !holding && vy > 0) {
708
                vy = 0;
709
            }
710
        }
711
712
        mc.player.setDeltaMovement(vx, vy, vz);
713
    }
714
715
    // The glide loses this much height a tick at a pitch.
716
    // Zero at the pitch where lift matches gravity.
717
    private static double glideSink(float pitch) {
718
        double cos = Math.cos(Math.toRadians(pitch));
719
        return GRAVITY * (1 - 0.75 * cos * cos);
720
    }
721
722
    // Holds the height the player had when the vertical keys let go.
723
    // Any drift that creeps in is pulled back and slowly learned away.
724
    private double holdHeight(double vy) {
725
        double y = mc.player.getY();
726
        if (Double.isNaN(heldY)) {
727
            heldY = y;
728
            holdBias = 0;
729
        }
730
        double error = heldY - y;
731
        holdBias = Math.clamp(holdBias + error * HOLD_LEARN, -HOLD_BIAS_LIMIT, HOLD_BIAS_LIMIT);
732
        double correction = Math.clamp(error * HOLD_GAIN, -HOLD_STEP, HOLD_STEP);
733
        return glideSink(mc.player.getXRot()) + correction + holdBias;
734
    }
735
736
    // Eases down onto the ground and stops a small gap above it.
737
    private double hover(double vy, double climb) {
738
        double gap = groundGap(HOVER_APPROACH);
739
        if (gap < 0) {
740
            return vy - GRAVITY / 2 * climb;
741
        }
742
        if (gap <= HOVER_GAP) {
743
            return Math.max(vy, glideSink(mc.player.getXRot()));
744
        }
745
        return Math.max(vy, -HOVER_SINK);
746
    }
747
748
    // Blocks of air under the feet up to the reach or minus one for more than that.
749
    private double groundGap(double reach) {
750
        Vec3 feet = mc.player.position();
751
        HitResult hit = mc.level.clip(new ClipContext(feet, feet.subtract(0, reach, 0),
752
            ClipContext.Block.COLLIDER, ClipContext.Fluid.ANY, mc.player));
753
        return hit.getType() == HitResult.Type.MISS ? -1 : feet.y - hit.getLocation().y;
754
    }
755
756
    private void cruiseTick() {
757
        if (!cruising) {
758
            cruising = true;
759
            cruiseY = mc.player.getY();
760
            cruiseYaw = mc.player.getYRot();
761
            diving = true;
762
            forcedPitch = mc.player.getXRot();
763
        }
764
765
        Input keys = mc.player.input.keyPresses;
766
        if (altitude.is(Altitude.TAKE_OFF)) {
767
            if (keys.jump()) {
768
                cruiseY += 1;
769
            } else if (keys.shift()) {
770
                cruiseY -= 1;
771
            }
772
        }
773
774
        Vec3 velocity = mc.player.getDeltaMovement();
775
        double bps = velocity.horizontalDistance() * TICKS_PER_SECOND;
776
        double target = cruiseSpeed.getValue();
777
        double y = mc.player.getY();
778
779
        if (altitude.is(Altitude.BAND)) {
780
            // The two heights alone turn the cycle. A stall still earns a rocket.
781
            if (diving && y <= lowerHeight.getValue()) {
782
                diving = false;
783
            } else if (!diving && y >= upperHeight.getValue()) {
784
                diving = true;
785
            }
786
            if (bps < target * STALL_FRACTION) {
787
                fireRocket();
788
            }
789
        } else if (bps < target * STALL_FRACTION) {
790
            diving = true;
791
            fireRocket();
792
        } else if (bps >= target) {
793
            diving = false;
794
        } else {
795
            diving = altitude.is(Altitude.FREE) || y >= cruiseY;
796
        }
797
798
        float wanted = diving ? DIVE_PITCH : CLIMB_PITCH;
799
        float step = diving ? pitchDownSpeed.getFloat() : pitchUpSpeed.getFloat();
800
        forcedPitch = forcedPitch + Mth.clamp(wanted - forcedPitch, -step, step);
801
    }
802
803
    // The cruise angle goes on after the entity tick has saved the old one. The camera
804
    // then eases between the two over one frame instead of jumping the whole step.
805
    @Subscribe
806
    private void onPostMotion(PostMotionEvent event) {
807
        if (!cruising || !inGame()) {
808
            return;
809
        }
810
        mc.player.setXRot(forcedPitch);
811
        if (lockYaw.isOn()) {
812
            mc.player.setYRot(cruiseYaw);
813
        }
814
    }
815
816
    // ElytraBoost does the swapping and the firing.
817
    // Its own auto mode stands aside whilst cruising.
818
    private void fireRocket() {
819
        if (!rockets.isOn() || rocketTimer > 0) {
820
            return;
821
        }
822
        ElytraBoost boost = Modules.get(ElytraBoost.class);
823
        if (boost == null) {
824
            return;
825
        }
826
        boost.fire();
827
        rocketTimer = (int) Math.round(rocketDelay.getValue() * TICKS_PER_SECOND);
828
    }
829
830
    // Creative style flight with an elytra on.
831
    // The server hears a glide start and a ground flag each tick. Some take it as real.
832
    private void packetTick() {
833
        if (!mc.player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA)) {
834
            endPacketFlight();
835
            return;
836
        }
837
        Abilities abilities = mc.player.getAbilities();
838
        abilities.flying = true;
839
        abilities.setFlyingSpeed(0);
840
841
        Input keys = mc.player.input.keyPresses;
842
        double vertical = MovementUtil.FLY_VERTICAL * climbSpeed.getValue();
843
        double vy = 0;
844
        if (keys.jump()) {
845
            vy += vertical;
846
        }
847
        if (keys.shift()) {
848
            vy -= vertical;
849
        }
850
        Vec3 heading = MovementUtil.inputDirection();
851
        double horizontal = MovementUtil.FLY_HORIZONTAL * rampedSpeed(heading != Vec3.ZERO);
852
        mc.player.setDeltaMovement(heading.x * horizontal, vy, heading.z * horizontal);
853
854
        sendStartGlide();
855
        mc.player.connection.send(new ServerboundMovePlayerPacket.StatusOnly(true,
856
            mc.player.horizontalCollision));
857
    }
858
859
    private void endPacketFlight() {
860
        if (mc.player.isCreative() || mc.player.isSpectator()) {
861
            return;
862
        }
863
        mc.player.getAbilities().flying = false;
864
        mc.player.getAbilities().setFlyingSpeed(MovementUtil.VANILLA_FLY_SPEED);
865
    }
866
867
    // Holds forward and jump and reopens the wings every hop.
868
    // A rubberband closes them for a moment to let the server settle.
869
    private void bounceTick() {
870
        if (rubberbanded) {
871
            rubberbanded = false;
872
            mc.player.stopFallFlying();
873
            if (restart.isOn()) {
874
                bounceRestart = restartDelay.getInt();
875
                reopen = true;
876
            }
877
        }
878
        if (bounceRestart > 0) {
879
            bounceRestart--;
880
            releaseBounceKeys();
881
            return;
882
        }
883
        if (mc.player.isPassenger() || mc.player.getAbilities().flying
884
            || !mc.player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA)) {
885
            releaseBounceKeys();
886
            return;
887
        }
888
        applyFovScale();
889
        bounceKeys = true;
890
        mc.options.keyUp.setDown(true);
891
        if (autoJump.isOn()) {
892
            mc.options.keyJump.setDown(true);
893
        } else {
894
            InputUtil.release(mc.options.keyJump);
895
        }
896
        if (lockPitch.isOn()) {
897
            mc.player.setXRot(bouncePitch.getFloat());
898
        }
899
        switch (bounceHeading.getValue()) {
900
            case SNAP -> mc.player.setYRot(Math.round(mc.player.getYRot() / YAW_SNAP) * YAW_SNAP);
901
            case FIXED -> mc.player.setYRot(bounceYaw.getFloat());
902
            case FREE -> { }
903
        }
904
        // Sprinting in the air upsets some anti cheats.
905
        // Sprint always is for servers that do not mind it.
906
        mc.player.setSprinting(sprintAlways.isOn() || mc.player.onGround()
907
            || !mc.player.isFallFlying());
908
        if (mc.player.isFallFlying() || mc.player.onGround() || restartCooldown > 0) {
909
            return;
910
        }
911
        // A manual take off still reopens the wings once after a pull back.
912
        if (!manualTakeOff.isOn() || reopen) {
913
            reopen = false;
914
            openGlide();
915
        }
916
    }
917
918
    private void releaseBounceKeys() {
919
        if (!bounceKeys) {
920
            return;
921
        }
922
        bounceKeys = false;
923
        InputUtil.release(mc.options.keyUp);
924
        InputUtil.release(mc.options.keyJump);
925
    }
926
927
    // Fired on the netty thread.
928
    @Subscribe
929
    private void onPacketReceive(PacketReceiveEvent event) {
930
        if (!(event.getPacket() instanceof ClientboundPlayerPositionPacket)) {
931
            return;
932
        }
933
        ramp = 0;
934
        if (mode.is(Mode.BOUNCE)) {
935
            rubberbanded = true;
936
        }
937
    }
938
939
    // Leaves the ground to give the glide something to start from.
940
    private void jumpOff() {
941
        if (!groundStart.isOn() || takeOffWindow > 0 || restartCooldown > 0) {
942
            return;
943
        }
944
        if (!mc.player.onGround() || !mc.player.input.keyPresses.jump()
945
            || mc.player.isPassenger() || mc.player.getAbilities().flying
946
            || !mc.player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA)) {
947
            return;
948
        }
949
        mc.player.jumpFromGround();
950
        // The glide has to open whilst still rising. The usual falling test is skipped.
951
        takeOffWindow = TAKE_OFF_WINDOW;
952
    }
953
954
    private void startGlide() {
955
        if (restartCooldown > 0) {
956
            return;
957
        }
958
        if (takeOffWindow > 0) {
959
            if (!mc.player.onGround()
960
                && mc.player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA)) {
961
                openGlide();
962
            }
963
            return;
964
        }
965
        boolean allowed = wasGliding ? keepGliding.isOn() : autoTakeOff.isOn();
966
        if (!allowed) {
967
            return;
968
        }
969
        if (mc.player.onGround() || mc.player.isPassenger() || mc.player.isInWater()
970
            || mc.player.getAbilities().flying
971
            || !mc.player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA)) {
972
            return;
973
        }
974
        if (mc.player.getDeltaMovement().y >= 0) {
975
            return;
976
        }
977
        // Close to the ground a glide stutters between landing and gliding.
978
        double clearance = wasGliding ? 1.5 : TAKE_OFF_CLEARANCE;
979
        if (!mc.level.noCollision(mc.player,
980
            mc.player.getBoundingBox().expandTowards(0, -clearance, 0))) {
981
            return;
982
        }
983
        openGlide();
984
    }
985
986
    private void openGlide() {
987
        sendStartGlide();
988
        restartCooldown = RESTART_COOLDOWN;
989
    }
990
991
    // The server opens the elytra on this packet alone.
992
    static void sendStartGlide() {
993
        mc.player.connection.send(new ServerboundPlayerCommandPacket(mc.player,
994
            ServerboundPlayerCommandPacket.Action.START_FALL_FLYING));
995
    }
996
997
    // Warns once.
998
    private boolean checkDurability() {
999
        ItemStack chest = mc.player.getItemBySlot(EquipmentSlot.CHEST);
1000
        if (!chest.is(Items.ELYTRA) || !chest.isDamageableItem()) {
1001
            warned = false;
1002
            return false;
1003
        }
1004
        int max = chest.getMaxDamage();
1005
        int left = max - chest.getDamageValue();
1006
        if (left > max * LOW_DURABILITY) {
1007
            warned = false;
1008
            return false;
1009
        }
1010
        if (!warned) {
1011
            warned = true;
1012
            ChatUtil.error("Your elytra is nearly broken. ElytraFly has stopped helping.");
1013
        }
1014
        return true;
1015
    }
1016
}
1017
CombatantMOVEMENTsrc/main/java/combatant/client/features/module/modules/movement/ElytraFly.javaJava · 765 lines · 30.6 KB
Settingselytrafly_no_crashelytrafly_modeelytrafly_instant_startelytrafly_instant_stopelytrafly_speedelytrafly_speed_verticalelytrafly_speed_horizontalelytrafly_not_in_fluidelytrafly_durability_exploitelytrafly_static_durability_exploit_not_while_no_moveelytrafly_static_glideelytrafly_static_glide_verticalelytrafly_static_glide_horizontalelytrafly_vanilla_drag_percentelytrafly_vanilla_forward_boostelytrafly_vanilla_pitch_liftelytrafly_boost_speedelytrafly_boost_accelerationelytrafly_boost_auto_boostelytrafly_boost_vertical_controlelytrafly_boost_smart_groundelytrafly_boost_ground_distanceelytrafly_boost_dive_mechanicselytrafly_boost_dive_accelerationelytrafly_boost_dive_efficiencyelytrafly_firework_consider_inventoryelytrafly_firework_cooldown_minelytrafly_firework_cooldown_maxelytrafly_firework_silent_rotationelytrafly_firework_pitchelytrafly_firework_velocity_controlelytrafly_firework_velocity_factorelytrafly_packet_auto_startelytrafly_packet_sub_modeelytrafly_packet_cancel_corrections
ElytraFly.javaJava · Minecraft 26.2 · 765 lines · 30.6 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Combatant Client distribution.
3
 * Copyright (c) 2026 pivosos2007.
4
 *
5
 * Licensed under the GNU General Public License v3.0.
6
 */
7
8
package combatant.client.features.module.modules.movement;
9
10
import combatant.client.events.impl.*;
11
import net.minecraft.client.Minecraft;
12
import net.minecraft.client.player.LocalPlayer;
13
import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket;
14
import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket;
15
import net.minecraft.util.Mth;
16
import net.minecraft.world.effect.MobEffects;
17
import net.minecraft.world.entity.EquipmentSlot;
18
import net.minecraft.world.entity.MoverType;
19
import net.minecraft.world.entity.player.Input;
20
import net.minecraft.world.entity.projectile.FireworkRocketEntity;
21
import net.minecraft.world.item.ItemStack;
22
import net.minecraft.world.item.Items;
23
import net.minecraft.world.phys.Vec2;
24
import net.minecraft.world.phys.Vec3;
25
import combatant.client.config.values.BooleanValue;
26
import combatant.client.config.values.EnumValue;
27
import combatant.client.config.values.NumberValue;
28
import combatant.client.events.EventHandler;
29
import combatant.client.events.impl.*;
30
import combatant.client.features.module.Module;
31
import combatant.client.features.module.ModuleCategory;
32
import combatant.client.features.module.ModuleInfo;
33
import combatant.client.features.module.Modules;
34
import combatant.client.features.module.modules.combat.ElytraTarget;
35
import combatant.client.mixins.accessors.InputAccessor;
36
import combatant.client.util.aiming.RotationManager;
37
import combatant.client.util.aiming.RotationTarget;
38
import combatant.client.util.aiming.data.Rotation;
39
import combatant.client.util.aiming.features.MovementCorrection;
40
import combatant.client.util.player.MovementUtil;
41
import combatant.client.util.player.inventory.FireworkUseController;
42
import combatant.client.util.player.inventory.InventorySwap;
43
44
import java.util.List;
45
import java.util.concurrent.ThreadLocalRandom;
46
47
//todo Description
48
@ModuleInfo(id = "elytrafly", displayName = "ElytraFly", aliases = {"elytra", "efly", "elytraflight"}, category = ModuleCategory.MOVEMENT)
49
public class ElytraFly extends Module {
50
51
    private static final int FIREWORK_ROTATION_PRIORITY = 8;
52
    private static final int ROTATION_EVENT_PRIORITY = 60;
53
54
    private static final double GRAVITY_COMPENSATION = 0.008;
55
    private static final double NATURAL_LIFT_FACTOR = 0.005;
56
    private static final float MAX_PITCH_ANGLE = 90.0f;
57
    private static final float MAX_DIVE_SPEED_MULTIPLIER = 1.2f;
58
    private static final float DIVE_SPEED_REDUCTION = 0.01f;
59
    private static final float MIN_ACCELERATION_THRESHOLD = 0.01f;
60
    private static final float DECELERATION_FACTOR = 0.98f;
61
    private static final float SPEED_EFFECT_MULTIPLIER = 0.1f;
62
    private static final double PITCH_REDUCTION_FACTOR = 0.3;
63
    private static final double GROUND_PENALTY_FACTOR = 0.8;
64
    private static final double NEAR_GROUND_HORIZONTAL_BOOST = 1.3;
65
    private static final double NEAR_GROUND_VERTICAL_REDUCTION = 0.3;
66
    private static final float DIVE_THRESHOLD_ANGLE = 15.0f;
67
    private static final double DIVE_BOOST_MULTIPLIER = 2.0;
68
    private static final double PACKET_START_COLLISION_XZ_CONTRACT = 0.25;
69
    private static final double PACKET_START_COLLISION_Y_OFFSET = -0.3;
70
    public final BooleanValue noCrash = bool("elytrafly_no_crash", true);
71
    private final Minecraft mc = Minecraft.getInstance();
72
    private final EnumValue<Mode> mode = enumMode("elytrafly_mode", Mode.BOOST, Mode.values());
73
    private final BooleanValue instantStart = bool("elytrafly_instant_start", false);
74
    private final BooleanValue instantStop = bool("elytrafly_instant_stop", false);
75
    private final BooleanValue speedEnabled =
76
            visibleWhen(bool("elytrafly_speed", true), () -> mode.get() == Mode.STATIC);
77
    private final NumberValue<Float> verticalSpeed =
78
            visibleWhen(num("elytrafly_speed_vertical", 0.0f, 0.0f, 5.0f), () -> mode.get() == Mode.STATIC && speedEnabled.get());
79
    private final NumberValue<Float> horizontalSpeed =
80
            visibleWhen(num("elytrafly_speed_horizontal", 0.0f, 0.0f, 8.0f), () -> mode.get() == Mode.STATIC && speedEnabled.get());
81
    private final BooleanValue notInFluid = bool("elytrafly_not_in_fluid", false);
82
    private final BooleanValue durabilityExploit = bool("elytrafly_durability_exploit", false);
83
    private final BooleanValue staticDurabilityExploitNotWhileNoMove =
84
            visibleWhen(bool("elytrafly_static_durability_exploit_not_while_no_move", false), () -> mode.get() == Mode.STATIC);
85
    private final BooleanValue staticGlide =
86
            visibleWhen(bool("elytrafly_static_glide", false), () -> mode.get() == Mode.STATIC);
87
    private final NumberValue<Float> staticVerticalGlide =
88
            visibleWhen(num("elytrafly_static_glide_vertical", 0.01f, 0.0f, 1.0f), () -> mode.get() == Mode.STATIC && staticGlide.get());
89
    private final NumberValue<Float> staticHorizontalGlide =
90
            visibleWhen(num("elytrafly_static_glide_horizontal", 0.0f, 0.0f, 1.0f), () -> mode.get() == Mode.STATIC && staticGlide.get());
91
    private final NumberValue<Float> vanillaDragPercent =
92
            visibleWhen(num("elytrafly_vanilla_drag_percent", 99.0f, 90.0f, 100.0f), () -> mode.get() == Mode.VANILLA);
93
    private final NumberValue<Float> vanillaForwardBoost =
94
            visibleWhen(num("elytrafly_vanilla_forward_boost", 18.0f, 0.0f, 100.0f), () -> mode.get() == Mode.VANILLA);
95
    private final NumberValue<Float> vanillaPitchLift =
96
            visibleWhen(num("elytrafly_vanilla_pitch_lift", 4.5f, 0.0f, 30.0f), () -> mode.get() == Mode.VANILLA);
97
    private final NumberValue<Float> boostSpeed =
98
            visibleWhen(num("elytrafly_boost_speed", 0.018f, 0.0f, 2.0f), () -> mode.get() == Mode.BOOST);
99
    private final NumberValue<Float> boostAcceleration =
100
            visibleWhen(num("elytrafly_boost_acceleration", 0.018f, 0.001f, 0.1f), () -> mode.get() == Mode.BOOST);
101
    private final BooleanValue boostAutoBoost =
102
            visibleWhen(bool("elytrafly_boost_auto_boost", true), () -> mode.get() == Mode.BOOST);
103
    private final NumberValue<Float> boostVerticalControl =
104
            visibleWhen(num("elytrafly_boost_vertical_control", 0.0f, 0.0f, 1.0f), () -> mode.get() == Mode.BOOST);
105
    private final BooleanValue boostSmartGround =
106
            visibleWhen(bool("elytrafly_boost_smart_ground", true), () -> mode.get() == Mode.BOOST);
107
    private final NumberValue<Float> boostGroundDistance =
108
            visibleWhen(num("elytrafly_boost_ground_distance", 3.0f, 1.5f, 7.0f), () -> mode.get() == Mode.BOOST && boostSmartGround.get());
109
    private final BooleanValue boostDiveMechanics =
110
            visibleWhen(bool("elytrafly_boost_dive_mechanics", false), () -> mode.get() == Mode.BOOST);
111
    private final NumberValue<Float> boostDiveAcceleration =
112
            visibleWhen(num("elytrafly_boost_dive_acceleration", 0.05f, 0.01f, 0.1f), () -> mode.get() == Mode.BOOST && boostDiveMechanics.get());
113
    private final NumberValue<Float> boostDiveEfficiency =
114
            visibleWhen(num("elytrafly_boost_dive_efficiency", 0.8f, 0.4f, 1.5f), () -> mode.get() == Mode.BOOST && boostDiveMechanics.get());
115
    private final BooleanValue fireworkConsiderInventory =
116
            visibleWhen(bool("elytrafly_firework_consider_inventory", false), () -> mode.get() == Mode.FIREWORK);
117
    private final NumberValue<Integer> fireworkCooldownMin =
118
            visibleWhen(num("elytrafly_firework_cooldown_min", 20, 0, 300), () -> mode.get() == Mode.FIREWORK);
119
    private final NumberValue<Integer> fireworkCooldownMax =
120
            visibleWhen(num("elytrafly_firework_cooldown_max", 20, 0, 300), () -> mode.get() == Mode.FIREWORK);
121
    private final BooleanValue fireworkSilentRotation =
122
            visibleWhen(bool("elytrafly_firework_silent_rotation", true), () -> mode.get() == Mode.FIREWORK);
123
    private final NumberValue<Float> fireworkPitch =
124
            visibleWhen(num("elytrafly_firework_pitch", 0.0f, -90.0f, 90.0f), () -> mode.get() == Mode.FIREWORK && fireworkSilentRotation.get());
125
    private final BooleanValue fireworkVelocityControl =
126
            visibleWhen(bool("elytrafly_firework_velocity_control", true), () -> mode.get() == Mode.FIREWORK);
127
    private final NumberValue<Float> fireworkVelocityFactor =
128
            visibleWhen(num("elytrafly_firework_velocity_factor", 0.1f, 0.0f, 2.0f), () -> mode.get() == Mode.FIREWORK && fireworkVelocityControl.get());
129
    private final BooleanValue packetAutoStart =
130
            visibleWhen(bool("elytrafly_packet_auto_start", true), () -> mode.get() == Mode.PACKET);
131
    private final EnumValue<PacketSubMode> packetSubMode =
132
            visibleWhen(enumMode("elytrafly_packet_sub_mode", PacketSubMode.MOTION, PacketSubMode.values()), () -> mode.get() == Mode.PACKET);
133
    private final BooleanValue packetCancelCorrections =
134
            visibleWhen(bool("elytrafly_packet_cancel_corrections", true), () -> mode.get() == Mode.PACKET);
135
    private boolean needsToRestart;
136
    private Mode lastMode = mode.get();
137
    private float currentAcceleration;
138
    private float currentDiveSpeed;
139
    private boolean cachedGroundCheck;
140
    private int groundCheckCooldown;
141
    private int fireworkSkipTicks;
142
    private boolean queuedFireworkUse;
143
144
    {
145
        setDefaultBind("LEFT_ALT+L");
146
    }
147
148
    @Override
149
    public void onEnable() {
150
        resetRuntimeState();
151
        needsToRestart = false;
152
        lastMode = mode.get();
153
    }
154
155
    @Override
156
    public void onDisable() {
157
        RotationManager.INSTANCE.clear(this);
158
        InventorySwap.INSTANCE.releaseHotbar(this);
159
        resetRuntimeState();
160
        needsToRestart = true;
161
    }
162
163
    @Override
164
    public void onTick() {
165
        LocalPlayer player = mc.player;
166
        if (player == null || mc.level == null) {
167
            resetRuntimeState();
168
            return;
169
        }
170
171
        syncModeChange();
172
        tickFireworkCooldown();
173
174
        if (shouldNotOperate(player)) {
175
            needsToRestart = false;
176
            resetModeState(mode.get());
177
            return;
178
        }
179
180
        boolean stop = shouldStopOperating(player);
181
        if (stop && player.isFallFlying()) {
182
            player.stopFallFlying();
183
            sendStartGlidingPacket(player);
184
            needsToRestart = false;
185
            return;
186
        }
187
188
        if (player.isFallFlying()) {
189
            applyTickMode(player);
190
191
            if (durabilityExploit.get() && shouldRunDurabilityExploit()) {
192
                sendStartGlidingPacket(player);
193
                needsToRestart = true;
194
            }
195
        } else if (shouldStartOperating(player)) {
196
            suppressJumpInput(player);
197
            player.startFallFlying();
198
            sendStartGlidingPacket(player);
199
        }
200
    }
201
202
    @EventHandler
203
    private void onMove(PlayerMoveEvent event) {
204
        LocalPlayer player = mc.player;
205
        if (player == null || mc.level == null) return;
206
        if (event.getType() != MoverType.SELF) return;
207
        if (!isEnabled() || !player.isFallFlying()) return;
208
209
        switch (mode.get()) {
210
            case STATIC -> applyStaticMove(event, player);
211
            case BOOST -> applyBoostMove(event, player);
212
            default -> {
213
            }
214
        }
215
    }
216
217
    @EventHandler(priority = ROTATION_EVENT_PRIORITY)
218
    private void onRotationUpdate(RotationUpdateEvent event) {
219
        if (event.getType() != RotationUpdateEvent.Type.PRE) {
220
            return;
221
        }
222
223
        LocalPlayer player = mc.player;
224
        if (player == null || mc.level == null) {
225
            return;
226
        }
227
228
        if (!isEnabled() || shouldNotOperate(player)) {
229
            RotationManager.INSTANCE.clear(this);
230
            return;
231
        }
232
233
        if (mode.get() == Mode.FIREWORK && fireworkSilentRotation.get() && queuedFireworkUse && player.isFallFlying()) {
234
            queueSilentRotation(player, fireworkPitch.get(), FIREWORK_ROTATION_PRIORITY, 3);
235
            return;
236
        }
237
238
        RotationManager.INSTANCE.clear(this);
239
    }
240
241
    private void queueSilentRotation(LocalPlayer player, float pitch, int priority, int resetTicks) {
242
        float yaw = player.getYRot();
243
        Rotation rotation = new Rotation(yaw, Mth.clamp(pitch, -90.0f, 90.0f), false);
244
        RotationTarget plan = new RotationTarget(
245
                rotation,
246
                null,
247
                List.of(),
248
                Math.max(2, resetTicks),
249
                0.5f,
250
                false,
251
                MovementCorrection.SILENT,
252
                null
253
        );
254
        RotationManager.INSTANCE.setRotationTarget(plan, priority, this);
255
    }
256
257
    public boolean shouldNotOperate() {
258
        return mc.player == null || shouldNotOperate(mc.player);
259
    }
260
261
    public boolean shouldApplyVanillaHook(LocalPlayer player) {
262
        return isEnabled()
263
                && mode.get() == Mode.VANILLA
264
                && player != null
265
                && player.isFallFlying();
266
    }
267
268
    public double getVanillaDragFactor() {
269
        return vanillaDragPercent.get() / 100.0;
270
    }
271
272
    public double getVanillaForwardBoostFactor() {
273
        return vanillaForwardBoost.get() / 1000.0;
274
    }
275
276
    public double getVanillaPitchLiftFactor() {
277
        return vanillaPitchLift.get() / 1000.0;
278
    }
279
280
    public Vec3 predictTargetingPos(LocalPlayer player) {
281
        if (player == null) {
282
            return Vec3.ZERO;
283
        }
284
285
        Vec3 velocity = switch (mode.get()) {
286
            case VANILLA -> predictVanillaVelocity(player);
287
            default -> player.getDeltaMovement();
288
        };
289
290
        return player.position().add(velocity);
291
    }
292
293
    private boolean shouldNotOperate(LocalPlayer player) {
294
        if (player == null) return true;
295
        if (player.isPassenger()) return true;
296
        if (player.getAbilities().instabuild || player.hasEffect(MobEffects.LEVITATION)) return true;
297
298
        ItemStack chest = player.getItemBySlot(EquipmentSlot.CHEST);
299
        return !chest.is(Items.ELYTRA) || nextDamageWillBreak(chest);
300
    }
301
302
    private Vec3 predictVanillaVelocity(LocalPlayer player) {
303
        Vec3 velocity = player.getDeltaMovement();
304
        Vec3 look = player.getViewVector(1.0f);
305
        float pitch = player.getXRot();
306
307
        velocity = velocity.scale(getVanillaDragFactor());
308
        velocity = velocity.add(look.scale(getVanillaForwardBoostFactor()));
309
310
        double lift = -Math.sin(Math.toRadians(pitch)) * getVanillaPitchLiftFactor();
311
        return velocity.add(0.0, lift, 0.0);
312
    }
313
314
    private boolean shouldStopOperating(LocalPlayer player) {
315
        if (player == null) return false;
316
        return instantStop.get() && mc.options.keyShift.isDown() && player.onGround()
317
                || notInFluid.get() && isInLiquid(player);
318
    }
319
320
    private boolean shouldStartOperating(LocalPlayer player) {
321
        if (player == null) return false;
322
        return (instantStart.get() && mc.options.keyJump.isDown() && player.getDeltaMovement().y != 0.0)
323
                || needsToRestart;
324
    }
325
326
    private boolean shouldRunDurabilityExploit() {
327
        if (mode.get() == Mode.VANILLA) return false;
328
        if (mode.get() != Mode.STATIC) return true;
329
        return !staticDurabilityExploitNotWhileNoMove.get() || !MovementUtil.isMoving();
330
    }
331
332
    private void applyTickMode(LocalPlayer player) {
333
        switch (mode.get()) {
334
            case VANILLA -> {
335
            }
336
            case BOOST -> applyBoostTick(player);
337
            case FIREWORK -> applyFireworkTick(player);
338
            default -> {
339
            }
340
        }
341
    }
342
343
    private void applyStaticMove(PlayerMoveEvent event, LocalPlayer player) {
344
        Vec3 movement = event.getMovement();
345
        if (movement == null) return;
346
347
        boolean useSpeed = speedEnabled.get();
348
        if (useSpeed && MovementUtil.isMoving()) {
349
            event.setMovement(applyStrafe(movement, player, horizontalSpeed.get(), 1.0));
350
        } else {
351
            double glideX = 0.0;
352
            double glideZ = 0.0;
353
            if (staticGlide.get()) {
354
                double len = Math.hypot(movement.x, movement.z);
355
                if (len > 1.0E-6) {
356
                    glideX = movement.x / len * staticHorizontalGlide.get();
357
                    glideZ = movement.z / len * staticHorizontalGlide.get();
358
                }
359
            }
360
            event.setMovement(new Vec3(glideX, movement.y, glideZ));
361
        }
362
363
        Vec3 updated = event.getMovement();
364
        if (updated == null) return;
365
366
        double newY;
367
        if (mc.options.keyJump.isDown() && useSpeed) {
368
            newY = verticalSpeed.get();
369
        } else if (mc.options.keyShift.isDown() && useSpeed) {
370
            newY = -verticalSpeed.get();
371
        } else {
372
            newY = staticGlide.get() ? -staticVerticalGlide.get() : 0.0;
373
        }
374
375
        event.setMovement(new Vec3(updated.x, newY, updated.z));
376
    }
377
378
    private void applyBoostTick(LocalPlayer player) {
379
        boolean nearGround = isNearGround(player);
380
        float divePullUpBoost = handleDiveMechanics(player);
381
        boolean shouldBoost = mc.options.keyJump.isDown()
382
                || boostAutoBoost.get()
383
                || divePullUpBoost > 0.0f;
384
385
        handleBoostAcceleration(shouldBoost);
386
387
        if (MovementUtil.isMoving()) {
388
            double speed = calculateEffectiveBoostSpeed(player, nearGround);
389
            player.setDeltaMovement(applyStrafe(player.getDeltaMovement(), player, speed, 1.0));
390
        }
391
    }
392
393
    private void applyBoostMove(PlayerMoveEvent event, LocalPlayer player) {
394
        Vec3 movement = event.getMovement();
395
        if (movement == null) return;
396
397
        boolean nearGround = isNearGround(player);
398
        double divePullUpBoost = player.getXRot() < 0.0f && currentDiveSpeed > 0.0f
399
                ? (-player.getXRot() / MAX_PITCH_ANGLE) * boostDiveEfficiency.get() * currentDiveSpeed * SPEED_EFFECT_MULTIPLIER
400
                : 0.0;
401
402
        if (currentAcceleration > 0.0f || currentDiveSpeed > 0.0f) {
403
            movement = movement.add(calculateBoostVector(player, nearGround, divePullUpBoost));
404
        }
405
406
        double newY = calculateBoostVerticalMovement(movement, divePullUpBoost);
407
        event.setMovement(new Vec3(movement.x, newY, movement.z));
408
    }
409
410
    private void applyFireworkTick(LocalPlayer player) {
411
        if (!shouldUseFirework(player)) {
412
            return;
413
        }
414
        queuedFireworkUse = true;
415
    }
416
417
    private boolean canPacketStartGliding(LocalPlayer player) {
418
        if (player == null || mc.level == null) return false;
419
        if (player.onGround() || player.isFallFlying() || player.isInWater() || player.isInLava()) return false;
420
        if (player.getDeltaMovement().y > 0.0) return false;
421
422
        var collisionBox = player.getBoundingBox()
423
                .inflate(-PACKET_START_COLLISION_XZ_CONTRACT, 0.0, -PACKET_START_COLLISION_XZ_CONTRACT)
424
                .move(0.0, PACKET_START_COLLISION_Y_OFFSET, 0.0);
425
        return !mc.level.getBlockCollisions(player, collisionBox).iterator().hasNext();
426
    }
427
428
    private boolean shouldUseFirework(LocalPlayer player) {
429
        if (player == null || !player.isFallFlying() || player.isUsingItem()) return false;
430
        if (fireworkSkipTicks > 0) return false;
431
        if (!hasFireworkRocket(player)) return false;
432
433
        ElytraTarget elytraTarget = Modules.get(ElytraTarget.class);
434
        if (elytraTarget != null && elytraTarget.isManagingFireworks()) {
435
            return false;
436
        }
437
438
        for (var entity : mc.level.entitiesForRendering()) {
439
            if (entity instanceof FireworkRocketEntity firework && firework.getOwner() == player) {
440
                return false;
441
            }
442
        }
443
444
        return true;
445
    }
446
447
    private boolean hasFireworkRocket(LocalPlayer player) {
448
        if (player == null) return false;
449
        if (player.getOffhandItem().is(Items.FIREWORK_ROCKET)
450
                || player.getMainHandItem().is(Items.FIREWORK_ROCKET)) {
451
            return true;
452
        }
453
454
        int max = fireworkConsiderInventory.get() ? player.getInventory().getContainerSize() : 9;
455
        for (int i = 0; i < max; i++) {
456
            if (player.getInventory().getItem(i).is(Items.FIREWORK_ROCKET)) {
457
                return true;
458
            }
459
        }
460
        return false;
461
    }
462
463
    @EventHandler(priority = -1000)
464
    private void onSyncFirework(EventSync event) {
465
        if (!queuedFireworkUse || !isEnabled()) return;
466
467
        LocalPlayer player = mc.player;
468
        queuedFireworkUse = false;
469
        if (player == null || !player.isFallFlying()) return;
470
471
        if (FireworkUseController.INSTANCE.use(
472
                event.getYaw(),
473
                event.getPitch(),
474
                fireworkConsiderInventory.get(),
475
                true,
476
                true,
477
                0,
478
                true
479
        )) {
480
            fireworkSkipTicks = randomFireworkCooldown();
481
        }
482
    }
483
484
    @EventHandler(priority = 20)
485
    private void onSyncPacketMode(EventSync event) {
486
        if (!isEnabled() || mode.get() != Mode.PACKET) return;
487
488
        LocalPlayer player = mc.player;
489
        if (player == null || mc.level == null || shouldNotOperate(player)) return;
490
491
        boolean started = false;
492
        if (packetAutoStart.get() && !player.isFallFlying() && canPacketStartGliding(player)) {
493
            player.startFallFlying();
494
            sendStartGlidingPacket(player);
495
            started = true;
496
        }
497
498
        if (packetSubMode.get() == PacketSubMode.MOTION
499
                && player.isFallFlying()
500
                && !started
501
                && player.tickCount % 3 != 0) {
502
            event.cancel();
503
        }
504
    }
505
506
    @EventHandler
507
    private void onPacketReceive(PacketEvent.Receive event) {
508
        if (!isEnabled() || mode.get() != Mode.PACKET || !packetCancelCorrections.get()) return;
509
510
        LocalPlayer player = mc.player;
511
        if (player == null) return;
512
513
        if (event.getPacket() instanceof ClientboundSetEntityDataPacket(
514
                int id, List<net.minecraft.network.syncher.SynchedEntityData.DataValue<?>> packedItems
515
        )
516
                && id == player.getId()
517
                && !packedItems.isEmpty()) {
518
            event.cancel();
519
        }
520
    }
521
522
    @EventHandler
523
    private void onFirework(FireworkEvent event) {
524
        if (!isEnabled() || mode.get() != Mode.FIREWORK || !fireworkVelocityControl.get()) return;
525
526
        LocalPlayer player = mc.player;
527
        if (player == null || !player.isFallFlying()) return;
528
529
        ElytraTarget elytraTarget = Modules.get(ElytraTarget.class);
530
        if (elytraTarget != null && elytraTarget.isManagingFireworks()) {
531
            return;
532
        }
533
534
        Vec3 currentVelocity = event.getVector();
535
        Rotation moveRotation = RotationManager.INSTANCE.getMovementRotation();
536
        Vec3 lookVector = moveRotation.directionVector();
537
        Vec3 wantedFireworkVelocity = lookVector.scale(1.5);
538
        double factor = fireworkVelocityFactor.get();
539
540
        event.setVector(currentVelocity.add(
541
                lookVector.x * factor + (wantedFireworkVelocity.x - currentVelocity.x) * 0.5,
542
                lookVector.y * factor + (wantedFireworkVelocity.y - currentVelocity.y) * 0.5,
543
                lookVector.z * factor + (wantedFireworkVelocity.z - currentVelocity.z) * 0.5
544
        ));
545
    }
546
547
    private void suppressJumpInput(LocalPlayer player) {
548
        if (player == null || player.input == null) return;
549
550
        Input input = player.input.keyPresses;
551
        ((InputAccessor) player.input).setPlayerInput(new Input(
552
                input.forward(),
553
                input.backward(),
554
                input.left(),
555
                input.right(),
556
                false,
557
                input.shift(),
558
                input.sprint()
559
        ));
560
    }
561
562
    private void sendStartGlidingPacket(LocalPlayer player) {
563
        if (player == null || mc.getConnection() == null) return;
564
        mc.getConnection().send(new ServerboundPlayerCommandPacket(
565
                player,
566
                ServerboundPlayerCommandPacket.Action.START_FALL_FLYING
567
        ));
568
    }
569
570
    private Vec3 applyStrafe(Vec3 currentVelocity, LocalPlayer player, double speed, double strength) {
571
        if (player == null || player.input == null) return currentVelocity;
572
573
        Vec2 input = player.input.getMoveVector();
574
        Vec3 movementInput = new Vec3(input.x, 0.0, input.y);
575
        return MovementUtil.withStrafe(currentVelocity, movementInput, resolveMovementYaw(player), speed, strength);
576
    }
577
578
    private float resolveMovementYaw(LocalPlayer player) {
579
        Rotation rotation = RotationManager.INSTANCE.getCurrentRotation();
580
        var rotationTarget = RotationManager.INSTANCE.getActiveRotationTarget();
581
        if (rotation != null && rotationTarget != null && rotationTarget.movementCorrection != MovementCorrection.OFF) {
582
            return rotation.yaw();
583
        }
584
        return player.getYRot();
585
    }
586
587
    private Vec3 resolveDirectionVector(LocalPlayer player) {
588
        Rotation rotation = RotationManager.INSTANCE.getCurrentRotation();
589
        var rotationTarget = RotationManager.INSTANCE.getActiveRotationTarget();
590
        if (rotation != null && rotationTarget != null && rotationTarget.movementCorrection != MovementCorrection.OFF) {
591
            return rotation.directionVector();
592
        }
593
        return player.getViewVector(1.0f);
594
    }
595
596
    private boolean isNearGround(LocalPlayer player) {
597
        if (!boostSmartGround.get()) return false;
598
599
        groundCheckCooldown--;
600
        if (groundCheckCooldown <= 0) {
601
            cachedGroundCheck = mc.level.getBlockCollisions(
602
                    player,
603
                    player.getBoundingBox().move(0.0, -boostGroundDistance.get(), 0.0)
604
            ).iterator().hasNext();
605
            groundCheckCooldown = 3;
606
        }
607
608
        return cachedGroundCheck;
609
    }
610
611
    private float handleDiveMechanics(LocalPlayer player) {
612
        if (!boostDiveMechanics.get()) {
613
            currentDiveSpeed = Math.max(0.0f, currentDiveSpeed - DIVE_SPEED_REDUCTION);
614
            return 0.0f;
615
        }
616
617
        float oldDiveSpeed = currentDiveSpeed;
618
        if (player.getXRot() > DIVE_THRESHOLD_ANGLE) {
619
            float diveFactor = Math.min(player.getXRot() / MAX_PITCH_ANGLE, 1.0f);
620
            currentDiveSpeed = Math.min(
621
                    currentDiveSpeed + boostDiveAcceleration.get() * diveFactor,
622
                    MAX_DIVE_SPEED_MULTIPLIER
623
            );
624
            return 0.0f;
625
        }
626
627
        currentDiveSpeed = Math.max(0.0f, currentDiveSpeed - DIVE_SPEED_REDUCTION);
628
629
        if (player.getXRot() < 0.0f && oldDiveSpeed > 0.0f) {
630
            return oldDiveSpeed * (-player.getXRot() / MAX_PITCH_ANGLE) * boostDiveEfficiency.get();
631
        }
632
633
        return 0.0f;
634
    }
635
636
    private void handleBoostAcceleration(boolean shouldBoost) {
637
        if (shouldBoost && currentAcceleration < boostSpeed.get()) {
638
            currentAcceleration = Math.min(
639
                    currentAcceleration + boostAcceleration.get() * (1.0f - currentAcceleration / boostSpeed.get()),
640
                    boostSpeed.get()
641
            );
642
            return;
643
        }
644
645
        if (!shouldBoost && currentAcceleration > 0.0f) {
646
            float accelerated = currentAcceleration * (DECELERATION_FACTOR - boostAcceleration.get());
647
            currentAcceleration = accelerated >= MIN_ACCELERATION_THRESHOLD ? accelerated : 0.0f;
648
        }
649
    }
650
651
    private double calculateEffectiveBoostSpeed(LocalPlayer player, boolean nearGround) {
652
        double baseSpeed = horizontalSpeed.get();
653
        double pitchReduction = player.getXRot() < 0.0f
654
                ? Math.abs(player.getXRot() / MAX_PITCH_ANGLE) * PITCH_REDUCTION_FACTOR
655
                : 0.0;
656
        double speedBonus = currentDiveSpeed + getSpeedEffectAmplifier(player) * SPEED_EFFECT_MULTIPLIER;
657
        double groundMultiplier = nearGround ? GROUND_PENALTY_FACTOR : 1.0;
658
        return baseSpeed * (1.0 - pitchReduction + speedBonus) * groundMultiplier;
659
    }
660
661
    private Vec3 calculateBoostVector(LocalPlayer player, boolean nearGround, double divePullUpBoost) {
662
        Vec3 look = resolveDirectionVector(player);
663
        double boostFactor = currentAcceleration
664
                + (player.getXRot() > 0.0f ? currentDiveSpeed : divePullUpBoost * DIVE_BOOST_MULTIPLIER);
665
666
        if (nearGround) {
667
            Vec3 scaled = new Vec3(
668
                    look.x * NEAR_GROUND_HORIZONTAL_BOOST,
669
                    look.y * NEAR_GROUND_VERTICAL_REDUCTION,
670
                    look.z * NEAR_GROUND_HORIZONTAL_BOOST
671
            );
672
            double len = scaled.length();
673
            return len > 1.0E-6 ? scaled.scale(boostFactor / len) : Vec3.ZERO;
674
        }
675
676
        return look.scale(boostFactor);
677
    }
678
679
    private double calculateBoostVerticalMovement(Vec3 movement, double divePullUpBoost) {
680
        double horizontal = Math.hypot(movement.x, movement.z);
681
        double naturalLift = horizontal * NATURAL_LIFT_FACTOR;
682
        double manualVertical = verticalSpeed.get() * boostVerticalControl.get();
683
        double baseY = movement.y - GRAVITY_COMPENSATION + naturalLift + divePullUpBoost;
684
685
        if (mc.options.keyJump.isDown() && !mc.options.keyShift.isDown()) {
686
            return movement.y + manualVertical + divePullUpBoost;
687
        }
688
        if (mc.options.keyShift.isDown() && !mc.options.keyJump.isDown()) {
689
            return movement.y - manualVertical;
690
        }
691
        return baseY;
692
    }
693
694
    private double getSpeedEffectAmplifier(LocalPlayer player) {
695
        var effect = player.getEffect(MobEffects.SPEED);
696
        return effect == null ? 0.0 : effect.getAmplifier() + 1.0;
697
    }
698
699
    private int randomFireworkCooldown() {
700
        int min = Math.min(fireworkCooldownMin.get(), fireworkCooldownMax.get());
701
        int max = Math.max(fireworkCooldownMin.get(), fireworkCooldownMax.get());
702
        return ThreadLocalRandom.current().nextInt(min, max + 1);
703
    }
704
705
    private boolean nextDamageWillBreak(ItemStack stack) {
706
        return stack.isDamageableItem() && (stack.getMaxDamage() - stack.getDamageValue()) <= 1;
707
    }
708
709
    private boolean isInLiquid(LocalPlayer player) {
710
        return player != null && (player.isInWater() || player.isInLava());
711
    }
712
713
    private void tickFireworkCooldown() {
714
        if (fireworkSkipTicks > 0) {
715
            fireworkSkipTicks--;
716
        }
717
    }
718
719
    private void syncModeChange() {
720
        Mode current = mode.get();
721
        if (current == lastMode) {
722
            return;
723
        }
724
725
        resetModeState(lastMode);
726
        lastMode = current;
727
    }
728
729
    private void resetRuntimeState() {
730
        resetBoostState();
731
        fireworkSkipTicks = 0;
732
        queuedFireworkUse = false;
733
    }
734
735
    private void resetModeState(Mode currentMode) {
736
        if (currentMode == Mode.BOOST) {
737
            resetBoostState();
738
        }
739
        if (currentMode == Mode.FIREWORK) {
740
            fireworkSkipTicks = 0;
741
            queuedFireworkUse = false;
742
        }
743
    }
744
745
    private void resetBoostState() {
746
        currentAcceleration = 0.0f;
747
        currentDiveSpeed = 0.0f;
748
        cachedGroundCheck = false;
749
        groundCheckCooldown = 0;
750
    }
751
752
    public enum Mode {
753
        STATIC,
754
        VANILLA,
755
        BOOST,
756
        FIREWORK,
757
        PACKET
758
    }
759
760
    public enum PacketSubMode {
761
        NORMAL,
762
        MOTION
763
    }
764
}
765
KiwiClientMOVEMENTsrc/main/java/com/tangykiwi/kiwiclient/module/movement/ElytraFly.javaJava · 86 lines · 3.9 KB

Better elytra flight

SettingsModeBoostMaxBoostControl Speed
ElytraFly.javaJava · Minecraft 26.2 · 86 lines · 3.9 KB · complete file, verbatimOriginal ↗
1
package com.tangykiwi.kiwiclient.module.movement;
2
3
import com.google.common.eventbus.Subscribe;
4
import com.tangykiwi.kiwiclient.event.PlayerMoveEvent;
5
import com.tangykiwi.kiwiclient.event.TickEvent;
6
import com.tangykiwi.kiwiclient.module.Category;
7
import com.tangykiwi.kiwiclient.module.Module;
8
import com.tangykiwi.kiwiclient.module.setting.ModeSetting;
9
import com.tangykiwi.kiwiclient.module.setting.SliderSetting;
10
11
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
12
import net.minecraft.util.Mth;
13
import net.minecraft.world.phys.Vec3;
14
15
import static com.tangykiwi.kiwiclient.KiwiClient.mc;
16
17
public class ElytraFly extends Module {
18
    public ElytraFly() {
19
        super("ElytraFly", "Better elytra flight", Category.MOVEMENT,
20
            new ModeSetting("Mode", "Mode", "Boost", "Control"),
21
            new SliderSetting("Boost", "Boost multiplier", 0, 0.15, 0.05, 2),
22
            new SliderSetting("MaxBoost", "Max boost speed", 0, 5, 2.5, 1),
23
            new SliderSetting("Control Speed", "Control speed multiplier", 0, 5, 0.8, 2)
24
        );
25
    }
26
27
    @Subscribe
28
    public void onPlayerMove(PlayerMoveEvent event) {
29
        if (getSetting(0).asMode().getValue() == 1 && mc.player.isFallFlying()) {
30
            Vec3 currentVec = mc.player.getDeltaMovement();
31
            if (!mc.options.keyJump.isDown() && !mc.options.keyShift.isDown()) {
32
                mc.player.setDeltaMovement(currentVec.x, 0, currentVec.z);
33
                // event.setVec(new Vec3(event.getVec().x, 0, event.getVec().z));
34
            }
35
36
            if (!mc.options.keyDown.isDown() && !mc.options.keyLeft.isDown()
37
                    && !mc.options.keyRight.isDown() && !mc.options.keyUp.isDown()) {
38
                mc.player.setDeltaMovement(0, event.getVec().y, 0);
39
                // event.setVec(new Vec3(0, event.getVec().y, 0));
40
            }
41
        }
42
    }
43
44
    @Subscribe
45
    public void onTick(TickEvent event) {
46
        if (mc.player == null) return;
47
48
        Vec3 vel = new Vec3(0, 0, getSetting(3).asSlider().getValue()).yRot(-(float) Math.toRadians(mc.player.getYRot()));
49
        double currentVel = Math.abs(mc.player.getDeltaMovement().x) + Math.abs(mc.player.getDeltaMovement().y) + Math.abs(mc.player.getDeltaMovement().z);
50
        float radianYaw = (float) Math.toRadians(mc.player.getYRot());
51
52
        float boost = getSetting(1).asSlider().getValueFloat();
53
54
        if(getSetting(0).asMode().getValue() == 0) {
55
            if (mc.player.isFallFlying() && currentVel <= getSetting(2).asSlider().getValue()) {
56
                if (mc.options.keyUp.isDown()) {
57
                    mc.player.addDeltaMovement(new Vec3(Mth.sin(radianYaw) * -boost, 0, Mth.cos(radianYaw) * boost));
58
                } else if (mc.options.keyDown.isDown()) {
59
                    mc.player.addDeltaMovement(new Vec3(Mth.sin(radianYaw) * boost, 0, Mth.cos(radianYaw) * -boost));
60
                } else if (mc.options.keyJump.isDown()) {
61
                    mc.player.addDeltaMovement(new Vec3(0, boost, 0));
62
                }
63
            }
64
        }
65
        else if (mc.player.isFallFlying()) {
66
            if (mc.options.keyDown.isDown()) vel = vel.reverse();
67
            if (mc.options.keyLeft.isDown()) vel = vel.yRot((float) Math.toRadians(90));
68
            else if (mc.options.keyRight.isDown()) vel = vel.yRot(-(float) Math.toRadians(90));
69
            if (mc.options.keyJump.isDown()) vel = vel.add(0, getSetting(3).asSlider().getValue(), 0);
70
            if (mc.options.keyShift.isDown()) vel = vel.add(0, -getSetting(3).asSlider().getValue(), 0);
71
72
            mc.getConnection().send(
73
                new ServerboundMovePlayerPacket.Pos(
74
                    mc.player.getX() + vel.x,
75
                    mc.player.getY() - 0.01,
76
                    mc.player.getZ() + vel.z,
77
                    false,
78
                    mc.player.horizontalCollision
79
                )
80
            );
81
82
            mc.player.setDeltaMovement(vel.x, vel.y, vel.z);
83
        }
84
    }
85
}
86
LiquidBounce (Kotlin)MOVEMENTsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/movement/elytrafly/ModuleElytraFly.ktKotlin · 165 lines · 5.6 KB

Makes controlling an elytra easier.

SettingsInstantVerticalHorizontalNotInFluidDurabilityExploit
ModuleElytraFly.ktKotlin · Minecraft 26.2 · 165 lines · 5.6 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
3
 *
4
 * Copyright (c) 2015 - 2026 CCBlueX
5
 *
6
 * LiquidBounce is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * LiquidBounce is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
package net.ccbluex.liquidbounce.features.module.modules.movement.elytrafly
20
21
import net.ccbluex.liquidbounce.config.types.group.ToggleableValueGroup
22
import net.ccbluex.liquidbounce.config.types.list.Tagged
23
import net.ccbluex.liquidbounce.event.tickHandler
24
import net.ccbluex.liquidbounce.features.module.ClientModule
25
import net.ccbluex.liquidbounce.features.module.ModuleCategories
26
import net.ccbluex.liquidbounce.features.module.modules.movement.elytrafly.modes.ElytraFlyModeBoost
27
import net.ccbluex.liquidbounce.features.module.modules.movement.elytrafly.modes.ElytraFlyModeFirework
28
import net.ccbluex.liquidbounce.features.module.modules.movement.elytrafly.modes.ElytraFlyModePitch40Infinite
29
import net.ccbluex.liquidbounce.features.module.modules.movement.elytrafly.modes.ElytraFlyModeStatic
30
import net.ccbluex.liquidbounce.features.module.modules.movement.elytrafly.modes.ElytraFlyModeVanilla
31
import net.ccbluex.liquidbounce.utils.entity.moving
32
import net.ccbluex.liquidbounce.utils.entity.set
33
import net.ccbluex.liquidbounce.utils.item.isGlider
34
import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket
35
import net.minecraft.world.effect.MobEffects
36
import net.minecraft.world.entity.EquipmentSlot
37
38
/**
39
 * ElytraFly module
40
 *
41
 * Makes elytra flying easier to control.
42
 */
43
object ModuleElytraFly : ClientModule("ElytraFly", ModuleCategories.MOVEMENT) {
44
45
    private val instant by multiEnumChoice("Instant", Instant.STOP)
46
47
    object Speed : ToggleableValueGroup(this, "Speed", true) {
48
        val vertical by float("Vertical", 0.5f, 0.0f..5f)
49
        val horizontal by float("Horizontal", 1f, 0.0f..8f)
50
    }
51
52
53
54
    private val notInFluid by boolean("NotInFluid", false)
55
56
    /**
57
     * Spams elytra starting so that we switch between falling and gliding all the time and so don't use any elytra
58
     * durability.
59
     */
60
    private val durabilityExploit by boolean("DurabilityExploit", false)
61
62
    init {
63
        tree(Speed)
64
    }
65
66
    internal val modes = choices("Mode", ElytraFlyModeStatic, arrayOf(
67
        ElytraFlyModeStatic,
68
        ElytraFlyModeVanilla,
69
        ElytraFlyModeBoost,
70
        ElytraFlyModeFirework,
71
        ElytraFlyModePitch40Infinite
72
    ))
73
74
    private var needsToRestart = false
75
76
    override fun onEnabled() {
77
        needsToRestart = false
78
    }
79
80
    override fun onDisabled() {
81
        needsToRestart = true
82
    }
83
84
    // checks and start logic
85
    @Suppress("unused", "ComplexCondition")
86
    private val tickHandler = tickHandler {
87
        if (shouldNotOperate()) {
88
            needsToRestart = false
89
            return@tickHandler
90
        }
91
92
        val stop =
93
            mc.options.keyShift.isDown
94
            && Instant.STOP in instant
95
            && player.onGround()
96
            || notInFluid && player.isInLiquid
97
98
        if (stop && player.isFallFlying) {
99
            player.stopFallFlying()
100
            network.send(
101
                ServerboundPlayerCommandPacket(player, ServerboundPlayerCommandPacket.Action.START_FALL_FLYING)
102
            )
103
            needsToRestart = false
104
            return@tickHandler
105
        }
106
107
        if (player.isFallFlying) {
108
            // we're already flying, yay
109
            val activeChoice = modes.activeMode
110
            if (Speed.enabled) {
111
                activeChoice.onTick()
112
            }
113
114
            val modeDoesNotPreventStopping = activeChoice !is ElytraFlyModeStatic ||
115
                !activeChoice.durabilityExploitNotWhileMove || !player.moving
116
            if (durabilityExploit && modeDoesNotPreventStopping) {
117
                network.send(
118
                    ServerboundPlayerCommandPacket(player, ServerboundPlayerCommandPacket.Action.START_FALL_FLYING)
119
                )
120
                needsToRestart = true
121
            }
122
        } else if (
123
            player.input.keyPresses.jump
124
            && player.deltaMovement.y != 0.0
125
            && Instant.START in instant
126
            || needsToRestart
127
        ) {
128
            // If the player has an elytra and wants to fly instead
129
130
            // Jump must be off due to abnormal speed boosts
131
            player.input.set(jump = false)
132
            player.startFallFlying()
133
            network.send(
134
                ServerboundPlayerCommandPacket(player, ServerboundPlayerCommandPacket.Action.START_FALL_FLYING)
135
            )
136
        }
137
    }
138
139
    /**
140
     * @see net.minecraft.world.entity.LivingEntity.canGlideUsing
141
     */
142
    fun shouldNotOperate(): Boolean {
143
        if (player.vehicle != null) {
144
            return true
145
        }
146
147
        if (player.abilities.instabuild || player.hasEffect(MobEffects.LEVITATION)) {
148
            return true
149
        }
150
151
        // Find the chest slot
152
        val chestSlot = player.getItemBySlot(EquipmentSlot.CHEST)
153
154
        // If the player doesn't have an elytra in the chest slot or is in fluids
155
        return !chestSlot.isGlider || chestSlot.nextDamageWillBreak()
156
    }
157
158
    private enum class Instant(
159
        override val tag: String
160
    ) : Tagged {
161
        START("Start"),
162
        STOP("Stop")
163
    }
164
}
165