Rise 6.2.4 KillAura module 4 files, 1524 lines

Rise 6.2.4 KillAura: Full Source Analysis

Rise 6.2.4's KillAura is the successor of the 5.99 Aura, rebuilt on the event bus and the shared RotationComponent.

Client-release2/Client/src/main/java/com/alan/clients/module/impl/combat/KillAura.java · GitHub source ↗

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

Analysis

Overview

Rise 6.2.4's KillAura is the successor of the 5.99 Aura, rebuilt on the event bus and the shared RotationComponent. It keeps Single, Switch and Multiple attack modes plus Distance/Health/Hurt Time sorting, and expands the bypass surface to fifteen auto-block modes (None, Fake, Vanilla, NCP, Legit, Grim, Intave, Old Intave, Imperfect Vanilla, Vanilla ReBlock, Watchdog 1.17, New NCP, Universal, Watchdog, Watchdog 2), four rotation modes (Legit/Normal, Snap, NCP, Autistic AntiCheat), click-delay modes including 1.9+ weapon-speed scaling, a cps bounds randomization, an EvictingList of past targets for Switch mode, and heavy use of the component system: TargetComponent for target acquisition, RotationComponent for smoothed rotations with a ray-cast predicate, PingSpoofComponent for the Universal/Watchdog block cycles, and BadPacketsComponent to suppress attacks while movement is desynced.

Architecture

The module is event-driven with priority-ordered listeners. onHighPreUpdate (Priorities.HIGH) is the target and rotation pass: it refreshes the mouse over, computes allowAttack from BadPacketsComponent, calls getTargets() (which delegates to TargetComponent.getTargets(range) and applies the Switch-mode pastTargets eviction plus expandRange heuristics), picks targets.get(0), runs preBlock() for the auto-block mode, then rotations(). onMediumPriorityPreUpdate runs after other modules have had their chance to override rotations, and only then calls doAttack(targets) and postAttackBlock(), so the module attacks with the final rotation state. onPreMotionEvent flushes the packetQueue (packets queued by the blink/ping-spoof modes) via sendNoEvent, increments hitTicks, and clears blocking when the held item is not a sword. onPostMotion sends the block packet. onPacketSend tracks swing state (C0A sets swing=true, C03 resets it) and dispatches the Intave packetBlock mode, which cancels the outgoing C03, unblocks, re-sends the C03 without events, and re-blocks.

Rotation and attack logic

rotations() switches on rotationMode. Legit/Normal computes the target rotations with RotationUtil.calculate(target, true, range) and feeds RotationComponent.setRotations with a randomized rotationSpeed from the bounds setting plus a ray-cast predicate: the smoothing loop keeps jittering the target rotations with a random-angle offset (speed = random^3 * 20, offset accumulated via sin/cos of randomAngle) until RayCastUtil.rayCast(rotations, range, -0.1) hits an entity, which keeps every interpolated rotation inside the target's hitbox. NCP mode predicts both the target's position (MoveUtil.predictMovement) and the player's own motion, computes the axis via applySensitivityPatch, and with 10% probability adds a random offset of up to 10 yaw / 3 pitch. Snap mode only applies rotations when lastSafeUnBlockTick() allows, otherwise keeps the current rotations. doAttack() gates on the attackStopWatch/clickStopWatch pair and cps.getRandomBetween() * 1.5, then attacks: with keepSprint it sends C02PacketUseEntity directly, otherwise mc.playerController.attackEntity; Single/Switch also fall through to attack the ray-cast entity when it is not a fireball or item frame, and Multiple attacks every target still within range in one tick.

Auto-block and ping-spoof modes

The autoBlock value selects among fifteen sequences in preBlock()/postBlock()/postAttackBlock()/clickDelayBlock(). Grim and Watchdog 1.17 send a C09 held-item change to a different slot and back before blocking, which desyncs the server's view of the held item while the client still renders the sword. New NCP and Old Intave do the same C09 pair while the sword is blocked to mask the block state. Universal cycles blockTicks 2-3: block on tick 2, unblock on tick 3, with PingSpoofComponent.spoof(99999, ...) inflating the transaction ping during the cycle and dispatch() releasing the buffered packets at the right tick; Watchdog does the same with a random slot id sent every second tick, and Watchdog 2 adds a C09 to a random slot every third tick. clickDelayBlock() returns a 500ms penalty delay for Universal (blockTicks < 4) and Watchdog 1/2 (blockTicks < 2/1), so the module refuses to attack until the block cycle completes. The Fake and None modes cancel the RightClickEvent so the server never sees a use-item, and onRenderItem forces the EnumAction.BLOCK render so the client shows a blocking animation without any packet.

source KillAura.java (module logic)

KillAura.java1057 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.combat;
2
3
import com.alan.clients.Client;
4
import com.alan.clients.component.impl.player.*;
5
import com.alan.clients.component.impl.player.rotationcomponent.MovementFix;
6
import com.alan.clients.component.impl.render.ESPComponent;
7
import com.alan.clients.component.impl.render.espcomponent.api.ESPColor;
8
import com.alan.clients.component.impl.render.espcomponent.impl.AboveBox;
9
import com.alan.clients.component.impl.render.espcomponent.impl.FullBox;
10
import com.alan.clients.component.impl.render.espcomponent.impl.SigmaRing;
11
import com.alan.clients.event.Listener;
12
import com.alan.clients.event.Priorities;
13
import com.alan.clients.event.annotations.EventLink;
14
import com.alan.clients.event.impl.input.RightClickEvent;
15
import com.alan.clients.event.impl.motion.PostMotionEvent;
16
import com.alan.clients.event.impl.motion.PreMotionEvent;
17
import com.alan.clients.event.impl.motion.PreUpdateEvent;
18
import com.alan.clients.event.impl.motion.SlowDownEvent;
19
import com.alan.clients.event.impl.other.AttackEvent;
20
import com.alan.clients.event.impl.other.WorldChangeEvent;
21
import com.alan.clients.event.impl.packet.PacketSendEvent;
22
import com.alan.clients.event.impl.render.MouseOverEvent;
23
import com.alan.clients.event.impl.render.RenderItemEvent;
24
import com.alan.clients.module.Module;
25
import com.alan.clients.module.api.Category;
26
import com.alan.clients.module.api.ModuleInfo;
27
import com.alan.clients.module.impl.player.Scaffold;
28
import com.alan.clients.util.EvictingList;
29
import com.alan.clients.util.RayCastUtil;
30
import com.alan.clients.util.chat.ChatUtil;
31
import com.alan.clients.util.packet.PacketUtil;
32
import com.alan.clients.util.player.MoveUtil;
33
import com.alan.clients.util.player.PlayerUtil;
34
import com.alan.clients.util.render.RenderUtil;
35
import com.alan.clients.util.rotation.RotationUtil;
36
import com.alan.clients.util.vector.Vector2f;
37
import com.alan.clients.util.vector.Vector3d;
38
import com.alan.clients.value.impl.*;
39
import net.minecraft.entity.EntityLivingBase;
40
import net.minecraft.entity.item.EntityItemFrame;
41
import net.minecraft.entity.projectile.EntityFireball;
42
import net.minecraft.item.*;
43
import net.minecraft.network.Packet;
44
import net.minecraft.network.play.client.*;
45
import net.minecraft.potion.Potion;
46
import net.minecraft.util.*;
47
import rip.vantage.commons.util.time.StopWatch;
48
49
import java.awt.*;
50
import java.util.Comparator;
51
import java.util.List;
52
import java.util.Queue;
53
import java.util.concurrent.ConcurrentLinkedQueue;
54
import java.util.concurrent.ThreadLocalRandom;
55
56
@ModuleInfo(aliases = {"module.combat.killaura.name", "Aura", "Force Field"}, description = "module.combat.killaura.description", category = Category.COMBAT)
57
public final class KillAura extends Module {
58
    private final ModeValue mode = new ModeValue("Attack Mode", this)
59
            .add(new SubMode("Single"))
60
            .add(new SubMode("Switch"))
61
            .add(new SubMode("Multiple"))
62
            .setDefault("Single");
63
64
    private final BoundsNumberValue switchDelay = new BoundsNumberValue("Switch Delay", this, 0, 0, 0, 10, 1, () -> !mode.getValue().getName().equals("Switch"));
65
    public final ModeValue autoBlock = new ModeValue("Auto Block", this)
66
            .add(new SubMode("None"))
67
            .add(new SubMode("Fake"))
68
            .add(new SubMode("Vanilla"))
69
            .add(new SubMode("NCP"))
70
            .add(new SubMode("Legit"))
71
            .add(new SubMode("Grim"))
72
            .add(new SubMode("Intave"))
73
            .add(new SubMode("Old Intave"))
74
            .add(new SubMode("Imperfect Vanilla"))
75
            .add(new SubMode("Vanilla ReBlock"))
76
            .add(new SubMode("Watchdog 1.17"))
77
            .add(new SubMode("New NCP"))
78
            .add(new SubMode("Universal"))
79
            .add(new SubMode("Watchdog"))
80
            .add(new SubMode("Watchdog 2"))
81
            .setDefault("None");
82
83
    private final BooleanValue rightClickOnly = new BooleanValue("Right Click Only", this, false, () -> autoBlock.getValue().getName().equals("None") || autoBlock.getValue().getName().equals("Fake"));
84
    private final BooleanValue preventServerSideBlocking = new BooleanValue("Prevent Serverside Blocking", this, false, () -> !(autoBlock.getValue().getName().equals("None") || autoBlock.getValue().getName().equals("Fake")));
85
86
    private final ModeValue sorting = new ModeValue("Sorting", this)
87
            .add(new SubMode("Distance"))
88
            .add(new SubMode("Health"))
89
            .add(new SubMode("Hurt Time"))
90
            .setDefault("Distance");
91
    private final ModeValue clickMode = new ModeValue("Click Delay Mode", this)
92
            .add(new SubMode("Normal"))
93
            .add(new SubMode("Hit Select"))
94
            .add(new SubMode("1.9+"))
95
            .add(new SubMode("1.9+ With 1.8 Animations"))
96
            .setDefault("Normal");
97
    private final NumberValue range = new NumberValue("Range", this, 3, 3, 6, 0.1);
98
    private final BoundsNumberValue cps = new BoundsNumberValue("CPS", this, 10, 15, 1, 20, 1);
99
    private final BoundsNumberValue rotationSpeed = new BoundsNumberValue("Rotation speed", this, 5, 10, 0, 10, 1);
100
    private final ListValue<MovementFix> movementCorrection = new ListValue<>("Movement correction", this);
101
    private final BooleanValue keepSprint = new BooleanValue("Keep sprint", this, false);
102
103
    private final ModeValue espMode = new ModeValue("Target ESP Mode", this)
104
            .add(new SubMode("Ring"))
105
            .add(new SubMode("Box"))
106
            .add(new SubMode("None"))
107
            .setDefault("Ring");
108
109
    public final ModeValue boxMode = new ModeValue("Box Mode", this, () -> !(espMode.getValue()).getName().equals("Box"))
110
            .add(new SubMode("Above"))
111
            .add(new SubMode("Full"))
112
            .setDefault("Ring");
113
114
    private final BooleanValue rayCast = new BooleanValue("Ray cast", this, false);
115
    private final BooleanValue throughWalls = new BooleanValue("Through Walls", this, false, () -> !rayCast.getValue());
116
117
    private final BooleanValue advanced = new BooleanValue("Advanced", this, false);
118
    private final ModeValue rotationMode = new ModeValue("Rotation Mode", this, () -> !advanced.getValue())
119
            .add(new SubMode("Legit/Normal"))
120
            .add(new SubMode("Snap"))
121
            .add(new SubMode("NCP"))
122
            .add(new SubMode("Autistic AntiCheat"))
123
            .setDefault("Legit/Normal");
124
    private final BooleanValue attackWhilstScaffolding = new BooleanValue("Attack whilst Scaffolding", this, false, () -> !advanced.getValue());
125
    private final BooleanValue noSwing = new BooleanValue("No swing", this, false, () -> !advanced.getValue());
126
    private final BooleanValue autoDisable = new BooleanValue("Auto disable", this, false, () -> !advanced.getValue());
127
    private final BooleanValue badPacketsCheck = new BooleanValue("BadPackets check", this, true, () -> !advanced.getValue());
128
    private final BooleanValue showTargets = new BooleanValue("Targets", this, false);
129
    public final BooleanValue player = new BooleanValue("Player", this, true, () -> !showTargets.getValue());
130
    public final BooleanValue invisibles = new BooleanValue("Invisibles", this, false, () -> !showTargets.getValue());
131
    public final BooleanValue animals = new BooleanValue("Animals", this, false, () -> !showTargets.getValue());
132
    public final BooleanValue mobs = new BooleanValue("Mobs", this, false, () -> !showTargets.getValue());
133
    public final BooleanValue teams = new BooleanValue("Player Teammates", this, true, () -> !showTargets.getValue());
134
135
    private final Queue<Packet<?>> packetQueue = new ConcurrentLinkedQueue<>();
136
137
    private final StopWatch attackStopWatch = new StopWatch();
138
    private final StopWatch clickStopWatch = new StopWatch();
139
140
    private boolean blocking, swing, allowAttack;
141
    private long nextSwing;
142
143
    public List<EntityLivingBase> targets;
144
    public EntityLivingBase target;
145
146
    private int attack, expandRange, blockTicks, switchTicks;
147
    public int hitTicks;
148
    boolean shouldBlink;
149
    public boolean swingg;
150
151
    // Pointless to remember past 9 because hurt resistance is 10 ticks
152
    private final EvictingList<EntityLivingBase> pastTargets = new EvictingList<>(9);
153
154
    public KillAura() {
155
        for (MovementFix movementFix : MovementFix.values()) {
156
            movementCorrection.add(movementFix);
157
        }
158
159
        movementCorrection.setDefault(MovementFix.OFF);
160
    }
161
162
    @EventLink
163
    public final Listener<PreMotionEvent> onPreMotionEvent = event -> {
164
        this.packetQueue.forEach(PacketUtil::sendNoEvent);
165
        this.packetQueue.clear();
166
167
        this.hitTicks++;
168
169
        // Set blocking to false when switching items
170
        if (getComponent(Slot.class).getItemStack() == null || !(getComponent(Slot.class).getItemStack().getItem() instanceof ItemSword)) {
171
            blocking = false;
172
        }
173
174
        if (GUIDetectionComponent.inGUI()) {
175
            return;
176
        }
177
178
        if (target == null || mc.thePlayer.isDead || getModule(Scaffold.class).isEnabled()) {
179
            if (!BadPacketsComponent.bad()) {
180
                this.unblock(false);
181
                target = null;
182
            }
183
        }
184
        Color color = /*getTheme().getFirstColor()*/ Color.WHITE;
185
186
        switch (espMode.getValue().getName()) {
187
            case "Ring":
188
                ESPComponent.add(new SigmaRing(new ESPColor(color, color, color)));
189
                break;
190
            case "Box":
191
                switch (boxMode.getValue().getName()) {
192
                    case "Full":
193
                        ESPComponent.add(new FullBox(new ESPColor(color, color, color)));
194
                        break;
195
                    case "Above":
196
                        ESPComponent.add(new AboveBox(new ESPColor(color, color, color)));
197
                        break;
198
                }
199
                break;
200
        }
201
202
203
    };
204
205
    @Override
206
    public void onEnable() {
207
        this.attack = 0;
208
        this.blockTicks = 0;
209
        this.nextSwing = 0;
210
        //        Client.INSTANCE.setClickGUI(new RiseClickGUI());
211
    }
212
213
    @Override
214
    public void onDisable() {
215
        this.packetQueue.forEach(PacketUtil::sendNoEvent);
216
        this.packetQueue.clear();
217
        BlinkComponent.dispatch();
218
        target = null;
219
220
        this.unblock(false);
221
        mc.gameSettings.keyBindUseItem.setPressed(false);
222
        BlinkComponent.blinking = false;
223
    }
224
225
    @EventLink
226
    public final Listener<WorldChangeEvent> onWorldChange = event -> {
227
        if (this.autoDisable.getValue()) {
228
            this.toggle();
229
        }
230
    };
231
232
    public void getTargets() {
233
        double range = this.range.getValue().doubleValue();
234
235
        targets = TargetComponent.getTargets(range);
236
237
        if (mode.getValue().getName().equals("Switch")) {
238
            targets.removeAll(pastTargets);
239
        }
240
241
        if (targets.isEmpty()) {
242
            pastTargets.clear();
243
            targets = TargetComponent.getTargets(range + expandRange);
244
        }
245
246
        switch (sorting.getValue().getName()) {
247
            case "Health":
248
                targets.sort(Comparator.comparingDouble(EntityLivingBase::getHealth));
249
                sortByTargets();
250
                break;
251
252
            case "Hurt Time":
253
                targets.sort(Comparator.comparingDouble(entity -> entity.hurtTime));
254
                sortByTargets();
255
                break;
256
        }
257
    }
258
259
    private void sortByTargets() {
260
        targets.sort((o1, o2) -> {
261
            boolean isTarget1 = UserFriendAndTargetComponent.isTarget(o1.getCommandSenderName());
262
            boolean isTarget2 = UserFriendAndTargetComponent.isTarget(o2.getCommandSenderName());
263
            if (isTarget1 && !isTarget2) {
264
                return -1;
265
            } else if (!isTarget1 && isTarget2) {
266
                return 1;
267
            }
268
            return 0;
269
        });
270
    }
271
272
    @EventLink(value = Priorities.HIGH)
273
    public final Listener<PreUpdateEvent> onHighPreUpdate = event -> {
274
        if (RotationComponent.isSmoothed()) {
275
            return;
276
        }
277
278
        mc.entityRenderer.getMouseOver(1);
279
280
        this.allowAttack = !BadPacketsComponent.bad(false, false, false, true, true);
281
282
        if (mc.thePlayer.getHealth() <= 0.0 && this.autoDisable.getValue()) {
283
            this.toggle();
284
        }
285
286
        if (getModule(Scaffold.class).isEnabled() && !attackWhilstScaffolding.getValue()) {
287
            return;
288
        }
289
290
        this.attack = Math.max(Math.min(this.attack, this.attack - 2), 0);
291
292
        /*
293
         * Heuristic fix
294
         */
295
        if (mc.thePlayer.ticksExisted % 20 == 0) {
296
            expandRange = (int) (3 + Math.random() * 0.5);
297
        }
298
299
        if (GUIDetectionComponent.inGUI()) {
300
            return;
301
        }
302
303
        /*
304
         * Getting targets and selecting the nearest one
305
         */
306
        this.getTargets();
307
308
        if (targets.isEmpty()) {
309
            target = null;
310
            this.cantPreBlock();
311
            return;
312
        }
313
314
        target = targets.get(0);
315
316
        if (target == null || mc.thePlayer.isDead) {
317
            this.cantPreBlock();
318
            return;
319
        }
320
321
        if (this.canBlock()) {
322
            this.preBlock();
323
        } else {
324
            this.cantPreBlock();
325
        }
326
327
        /*
328
         * Calculating rotations to target
329
         */
330
        this.rotations();
331
    };
332
333
    // We attack on an event after all others, because other modules may have overridden the rotations
334
    // this way we won't attack if a module has overriden the killaura's rotations
335
    @EventLink()
336
    public final Listener<PreUpdateEvent> onMediumPriorityPreUpdate = event -> {
337
        if (target == null || mc.thePlayer.isDead) {
338
            return;
339
        }
340
341
        /*
342
         * Doing the attack
343
         */
344
        this.doAttack(targets);
345
346
        /*
347
         * Blocking
348
         */
349
        if (this.canBlock()) {
350
            this.postAttackBlock();
351
        }
352
    };
353
354
    public void cantPreBlock() {
355
        switch (autoBlock.getValue().getName()) {
356
            case "Universal":
357
                this.blockTicks = -1;
358
                break;
359
360
            case "Watchdog":
361
                this.blockTicks = -1;
362
                break;
363
364
365
        }
366
    }
367
368
    public void rotations() {
369
        final float rotationSpeed = this.rotationSpeed.getRandomBetween().floatValue();
370
371
        switch (rotationMode.getValue().getName()) {
372
            case "Legit/Normal":
373
                Vector2f targetRotations = RotationUtil.calculate(target, true, range.getValue().doubleValue());
374
375
                if (rotationSpeed != 0) RotationComponent.setRotations(targetRotations, rotationSpeed,
376
                        movementCorrection.getValue() == MovementFix.OFF ? MovementFix.OFF : movementCorrection.getValue(),
377
                        rotations -> {
378
                            MovingObjectPosition movingObjectPosition = RayCastUtil.rayCast(rotations, range.getValue().floatValue(), -0.1f);
379
380
                            return movingObjectPosition != null && movingObjectPosition.typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY;
381
                        });
382
                break;
383
384
            case "NCP":
385
                int predict = (int) (Math.random() * 1);
386
                Vector3d position = new Vector3d(target.posX, target.posY, target.posZ);
387
                Vector3d playerPosition = new Vector3d(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ);
388
                Vector3d predictedPosition = MoveUtil.predictMovement(target, new Vector2f(0, 1), predict, mc.thePlayer.isSprinting());
389
                target.setPosition(predictedPosition.x, predictedPosition.y, predictedPosition.z);
390
                mc.thePlayer.setPosition(mc.thePlayer.posX + mc.thePlayer.motionX * predict, mc.thePlayer.posY + (mc.thePlayer.motionY + 0.17) * predict, mc.thePlayer.posZ + mc.thePlayer.motionZ * predict);
391
                final Vector2f axis = RotationUtil.applySensitivityPatch(RotationUtil.calculate(target, true, range.getValue().doubleValue()));
392
                target.setPosition(position.x, position.y, position.z);
393
                mc.thePlayer.setPosition(playerPosition.x, playerPosition.y, playerPosition.z);
394
395
                if (rotationSpeed != 0) {
396
                    if (Math.random() > 0.1) {
397
                        RotationComponent.setRotations(axis, rotationSpeed,
398
                                movementCorrection.getValue() == MovementFix.OFF ? MovementFix.OFF : movementCorrection.getValue());
399
                    } else {
400
                        RotationComponent.setRotations(RotationComponent.targetRotations.add((float) ((Math.random() - 0.5) * 10), (float) ((Math.random() - 0.5) * 3)), rotationSpeed,
401
                                movementCorrection.getValue() == MovementFix.OFF ? MovementFix.OFF : movementCorrection.getValue());
402
403
                    }
404
                }
405
                //ChatUtil.display("Prediction Position: " + position.x + position.y + position.z);
406
                break;
407
408
            case "Snap":
409
                final Vector2f rotations = RotationUtil.calculate(target, true, range.getValue().doubleValue());
410
411
                if (rotationSpeed != 0 && lastSafeUnBlockTick()) {
412
                    RotationComponent.setSmoothed(false);
413
                    RotationComponent.setRotations(rotations, rotationSpeed,
414
                            movementCorrection.getValue() == MovementFix.OFF ? MovementFix.OFF : movementCorrection.getValue());
415
                } else {
416
                    RotationComponent.setRotations(new Vector2f(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch), rotationSpeed, movementCorrection.getValue() == MovementFix.OFF ? MovementFix.OFF : movementCorrection.getValue());
417
                }
418
                break;
419
420
            case "Autistic AntiCheat":
421
                RotationComponent.setRotations(new Vector2f(RotationComponent.rotations.x + rotationSpeed * 10, 0), (rotationSpeed * 10) / 18,
422
                        movementCorrection.getValue() == MovementFix.OFF ? MovementFix.OFF : movementCorrection.getValue());
423
                break;
424
        }
425
426
    }
427
428
    @EventLink
429
    public final Listener<MouseOverEvent> onMouseOver = event ->
430
            event.setRange(event.getRange() + range.getValue().doubleValue() - 3);
431
432
    @EventLink
433
    public final Listener<PostMotionEvent> onPostMotion = event -> {
434
        if (target != null && this.canBlock()) {
435
            this.postBlock();
436
        }
437
    };
438
439
    public Tuple<Boolean, Double> getDelay() {
440
        double delay = -1;
441
        boolean flag = false;
442
443
        switch (clickMode.getValue().getName()) {
444
            case "1.9+ With 1.8 Animations":
445
            case "1.9+": {
446
                if (clickMode.getValue().getName().equals("1.9+ With 1.8 Animations") && Math.random() > 0.2) {
447
                    RenderUtil.renderAttack(target);
448
                }
449
450
                double speed = 4;
451
452
                if (mc.thePlayer.getHeldItem() != null) {
453
                    final Item item = mc.thePlayer.getHeldItem().getItem();
454
455
                    if (item instanceof ItemSword) {
456
                        speed = 1.6;
457
                    } else if (item instanceof ItemSpade) {
458
                        speed = 1;
459
                    } else if (item instanceof ItemPickaxe) {
460
                        speed = 1.2;
461
                    } else if (item instanceof ItemAxe) {
462
                        switch (((ItemAxe) item).getToolMaterial()) {
463
                            case WOOD:
464
                            case STONE:
465
                                speed = 0.8;
466
                                break;
467
468
                            case IRON:
469
                                speed = 0.9;
470
                                break;
471
472
                            default:
473
                                speed = 1;
474
                                break;
475
                        }
476
                    } else if (item instanceof ItemHoe) {
477
                        switch (((ItemHoe) item).getToolMaterial()) {
478
                            case WOOD:
479
                            case GOLD:
480
                                speed = 1;
481
                                break;
482
483
                            case STONE:
484
                                speed = 2;
485
                                break;
486
487
                            case IRON:
488
                                speed = 3;
489
                                break;
490
                        }
491
                    }
492
                }
493
494
                delay = 1 / speed * 20 - 1;
495
                break;
496
            }
497
        }
498
499
        delay = clickDelayBlock(delay);
500
501
        return new Tuple<>(flag, delay);
502
    }
503
504
    private void doAttack(final List<EntityLivingBase> targets) {
505
        Tuple<Boolean, Double> tuple = getDelay();
506
        final double delay = tuple.getSecond();
507
        final boolean flag = tuple.getFirst();
508
509
        if (attackStopWatch.finished(this.nextSwing) && target != null && (clickStopWatch.finished((long) (delay * 50)) || flag)) {
510
            final long clicks = (long) (this.cps.getRandomBetween().longValue() * 1.5);
511
            this.nextSwing = 1000 / clicks;
512
513
            if (Math.sin(nextSwing) + 1 > Math.random() || attackStopWatch.finished(this.nextSwing + 500) || Math.random() > 0.5) {
514
                if (this.allowAttack || !badPacketsCheck.getValue()) {
515
                    /*
516
                     * Attacking target
517
                     */
518
                    final double range = this.range.getValue().doubleValue();
519
                    final Vec3 rotationVector = mc.thePlayer.getVectorForRotation(RotationComponent.rotations.getY(), RotationComponent.rotations.getX());
520
                    MovingObjectPosition movingObjectPosition = RayCastUtil.rayCast(RotationComponent.rotations, range);
521
522
                    if (throughWalls.getValue()) {
523
                        Vec3 eyes = mc.thePlayer.getPositionEyes(1);
524
                        movingObjectPosition = target.getEntityBoundingBox().expand(0.1, 0.1, 0.1).calculateIntercept(eyes,
525
                                eyes.addVector(rotationVector.xCoord * range, rotationVector.yCoord * range, rotationVector.zCoord * range));
526
527
                        if (movingObjectPosition != null) {
528
                            movingObjectPosition.typeOfHit = MovingObjectPosition.MovingObjectType.ENTITY;
529
                            movingObjectPosition.entityHit = target;
530
                        }
531
                    }
532
533
                    switch (this.mode.getValue().getName()) {
534
                        case "Switch":
535
                        case "Single": {
536
                            if ((mc.thePlayer.getDistanceToEntity(target) <= range && !rayCast.getValue()) ||
537
                                    (rayCast.getValue() && movingObjectPosition != null && movingObjectPosition.entityHit == target)) {
538
                                this.attack(target);
539
                            } else if (movingObjectPosition != null && movingObjectPosition.typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY) {
540
                                if (!(movingObjectPosition.entityHit instanceof EntityFireball || movingObjectPosition.entityHit instanceof EntityItemFrame)) {
541
                                    this.attack((EntityLivingBase) movingObjectPosition.entityHit);
542
                                }
543
                            } else {
544
                                switch (clickMode.getValue().getName()) {
545
                                    case "Normal":
546
                                    case "Hit Select":
547
                                        if (mc.playerController.curBlockDamageMP != 0) return;
548
                                        //                                        PacketUtil.send(new C0APacketAnimation());
549
                                        break;
550
                                }
551
                            }
552
                            break;
553
                        }
554
555
                        case "Multiple": {
556
                            targets.removeIf(target -> mc.thePlayer.getDistanceToEntity(target) > range);
557
558
                            if (!targets.isEmpty()) {
559
                                targets.forEach(this::attack);
560
                            }
561
                            break;
562
                        }
563
                    }
564
565
                    this.attackStopWatch.reset();
566
                }
567
            }
568
        }
569
    }
570
571
    private boolean lastSafeUnBlockTick() {
572
        Tuple<Boolean, Double> tuple = getDelay();
573
        final double delay = tuple.getSecond();
574
        final boolean flag = tuple.getFirst();
575
576
        return attackStopWatch.finished(this.nextSwing - 50) && target != null && (clickStopWatch.finished((long) (delay * 50) - 50) || flag) && !(clickMode.getValue().getName().equals("Hit Select") && target.hurtTime > (PingComponent.getPing() / 50 - 1) && mc.thePlayer.ticksSinceVelocity > 11) && allowAttack;
577
    }
578
579
    private void attack(final EntityLivingBase target) {
580
        final AttackEvent event = new AttackEvent(target);
581
        Client.INSTANCE.getEventBus().handle(event);
582
583
        if (this.canBlock()) {
584
            this.attackBlock();
585
        }
586
587
        mc.thePlayer.swingItem();
588
        if (this.keepSprint.getValue()) {
589
            mc.playerController.syncCurrentPlayItem();
590
591
            PacketUtil.send(new C02PacketUseEntity(target, C02PacketUseEntity.Action.ATTACK));
592
593
            if (mc.thePlayer.fallDistance > 0 && !mc.thePlayer.onGround && !mc.thePlayer.isOnLadder() && !mc.thePlayer.isInWater() && !mc.thePlayer.isPotionActive(Potion.blindness) && mc.thePlayer.ridingEntity == null) {
594
                mc.thePlayer.onCriticalHit(target);
595
            }
596
        } else {
597
            mc.playerController.attackEntity(mc.thePlayer, target);
598
        }
599
600
        //        if (target == mc.thePlayer || clickMode.getValue().getName().equals("Hit Select") && target.hurtTime > (PingComponent.getPing() / 50 + 1) && mc.thePlayer.ticksSinceVelocity > 11) {
601
        //            return;
602
        //        }
603
        //
604
        //        switchTicks++;
605
        //        if (switchTicks >= switchDelay.getRandomBetween().intValue()) {
606
        //            pastTargets.add(target);
607
        //            switchTicks = 0;
608
        //        }
609
        //
610
        //        this.attack = Math.min(Math.max(this.attack, this.attack + 2), 5);
611
        //
612
        //        if (!this.noSwing.getValue() && ViaLoadingBase.getInstance().getTargetVersion().olderThanOrEqualTo(ProtocolVersion.v1_8)) {
613
        //            Client.INSTANCE.getEventBus().handle(new ClickEvent());
614
        //            mc.thePlayer.swingItem();
615
        //        }
616
        //
617
        //        final AttackEvent event = new AttackEvent(target);
618
        //        Client.INSTANCE.getEventBus().handle(event);
619
        //
620
        //        if (!event.isCancelled()) {
621
        //            if (this.canBlock()) {
622
        //                this.attackBlock();
623
        //            }
624
        //
625
        //            if (this.keepSprint.getValue()) {
626
        //                mc.playerController.syncCurrentPlayItem();
627
        //
628
        //                PacketUtil.send(new C02PacketUseEntity(event.getTarget(), C02PacketUseEntity.Action.ATTACK));
629
        //
630
        //                if (mc.thePlayer.fallDistance > 0 && !mc.thePlayer.onGround && !mc.thePlayer.isOnLadder() && !mc.thePlayer.isInWater() && !mc.thePlayer.isPotionActive(Potion.blindness) && mc.thePlayer.ridingEntity == null) {
631
        //                    mc.thePlayer.onCriticalHit(target);
632
        //                }
633
        //            } else {
634
        //                mc.playerController.attackEntity(mc.thePlayer, target);
635
        //            }
636
        //        }
637
        //
638
        //        if (!this.noSwing.getValue() && ViaLoadingBase.getInstance().getTargetVersion().newerThan(ProtocolVersion.v1_8)) {
639
        //            Client.INSTANCE.getEventBus().handle(new ClickEvent());
640
        //            mc.thePlayer.swingItem();
641
        //        }
642
        //
643
        this.clickStopWatch.reset();
644
        this.hitTicks = 0;
645
    }
646
647
    private void block(final boolean check, final boolean interact) {
648
        if (!blocking || !check) {
649
            MovingObjectPosition movingObjectPosition = RayCastUtil.rayCast(RotationComponent.lastRotations, 3);
650
651
            if (interact && movingObjectPosition.typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY) {
652
                this.interact(movingObjectPosition);
653
            }
654
655
            //            ChatUtil.display("MC " + mc.thePlayer.getHeldItem());
656
            //            ChatUtil.display("Rise " + getComponent(SlotComponent.class).getItemStack());
657
            PacketUtil.send(new C08PacketPlayerBlockPlacement(getComponent(Slot.class).getItemStack()));
658
659
            blocking = true;
660
        }
661
    }
662
663
    public void interact(MovingObjectPosition mouse) {
664
        if (!mc.playerController.isPlayerRightClickingOnEntity(mc.thePlayer, mouse.entityHit, mouse)) {
665
            mc.playerController.interactWithEntitySendPacket(mc.thePlayer, mouse.entityHit);
666
        }
667
    }
668
669
    private void unblock(final boolean swingCheck) {
670
        if (blocking && (!swingCheck || !swing)) {
671
            PacketUtil.send(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));
672
            blocking = false;
673
        }
674
675
        if (mc.gameSettings.keyBindUseItem.isKeyDown() && getComponent(Slot.class).getItemStack() != null && getComponent(Slot.class).getItemStack().getItem() instanceof ItemSword) {
676
            //mc.gameSettings.keyBindUseItem.setPressed(false);
677
        }
678
    }
679
680
    @EventLink(value = Priorities.HIGH)
681
    public final Listener<RenderItemEvent> onRenderItem = event -> {
682
        if (target != null && !autoBlock.getValue().getName().equals("None") && this.canBlock()) {
683
            event.setEnumAction(EnumAction.BLOCK);
684
            event.setUseItem(true);
685
        }
686
    };
687
688
    int ticks = 0;
689
    @EventLink
690
    public final Listener<PacketSendEvent> onPacketSend = event -> {
691
        if (event.isCancelled()) {
692
            return;
693
        }
694
695
        final Packet<?> packet = event.getPacket();
696
697
        if (packet instanceof C0APacketAnimation) {
698
            swing = true;
699
        } else if (packet instanceof C03PacketPlayer) {
700
            swing = false;
701
        }
702
703
        this.packetBlock(event);
704
    };
705
706
    public double clickDelayBlock(double delay) {
707
        switch (autoBlock.getValue().getName()) {
708
            case "Universal":
709
                delay = blockTicks >= 4 ? -1 : 500;
710
                break;
711
712
713
            case "Watchdog":
714
                if(mc.thePlayer.getHeldItem() != null && mc.thePlayer.getHeldItem().getItem() instanceof ItemSword){
715
                    delay = blockTicks >= 2 ? -1 : 500;
716
                } else if(target != null && mc.thePlayer.getHeldItem() != null){
717
                    delay = 0;
718
                }
719
720
                break;
721
722
            case "Watchdog 2":
723
                delay = blockTicks >= 1 ? -1 : 500;
724
                break;
725
        }
726
727
728
        return delay;
729
    }
730
731
    public void packetBlock(final PacketSendEvent event) {
732
        final Packet<?> p = event.getPacket();
733
734
        switch (autoBlock.getValue().getName()) {
735
            case "Intave": {
736
                if (p instanceof C03PacketPlayer) {
737
                    event.setCancelled();
738
                    this.unblock(false);
739
                    PacketUtil.sendNoEvent(p);
740
                    this.block(false, true);
741
                }
742
                break;
743
            }
744
745
        }
746
    }
747
748
    @EventLink
749
    public final Listener<RightClickEvent> onRightClick = event -> {
750
        if (target == null || getComponent(Slot.class).getItemStack() == null || !(getComponent(Slot.class).getItemStack().getItem() instanceof ItemSword))
751
            return;
752
753
        switch (autoBlock.getValue().getName()) {
754
            case "Fake":
755
            case "None":
756
                if (!preventServerSideBlocking.getValue() || getComponent(Slot.class).getItemStack() == null || !(getComponent(Slot.class).getItemStack().getItem() instanceof ItemSword)) {
757
                    return;
758
                }
759
760
                event.setCancelled();
761
                break;
762
763
            // case "Watchdog":
764
            case "Legit":
765
                break;
766
767
            default:
768
                event.setCancelled();
769
                break;
770
        }
771
    };
772
773
    @EventLink
774
    public final Listener<SlowDownEvent> onSlowDown = event -> {
775
        switch (autoBlock.getValue().getName()) {
776
            case "Legit":
777
                //                event.setStrafeMultiplier(0.2f);
778
                //                event.setForwardMultiplier(0.2f);
779
                //                event.setCancelled(false);
780
                //                event.setUseItem(true);
781
                break;
782
783
            case "Watchdog":
784
                //prevent from noslowing without a target or while using items when killaura is enabled
785
                if (target != null && mc.thePlayer.getHeldItem() != null && mc.thePlayer.getHeldItem().getItem() instanceof ItemSword)
786
                    event.setCancelled();
787
                break;
788
789
            case "Watchdog 2":
790
                //prevent from noslowing without a target or while using items when killaura is enabled
791
                if (target != null && mc.thePlayer.getHeldItem() != null && mc.thePlayer.getHeldItem().getItem() instanceof ItemSword)
792
                    event.setCancelled();
793
                break;
794
        }
795
    };
796
797
    private void attackBlock() {
798
        //        switch (autoBlock.getValue().getName()) {
799
        //            case "Legit":
800
        //                break;
801
        //        }
802
803
    }
804
805
    private void postAttackBlock() {
806
        switch (autoBlock.getValue().getName()) {
807
            case "Legit":
808
809
                break;
810
811
            case "Intave":
812
                this.block(false, false);
813
                break;
814
815
            case "Vanilla":
816
                if (this.hitTicks != 0) {
817
                    this.block(false, true);
818
                }
819
                break;
820
821
822
            case "Watchdog 2":
823
824
                allowAttack = false;
825
                blockTicks++;
826
                PingSpoofComponent.blink();
827
828
                if (blockTicks == 1) {
829
                    if (rayCast.getValue()) {
830
                        mc.clickMouse();
831
                    } else {
832
                        attack(target);
833
                    }
834
                    mc.rightClickMouse();
835
                } else if (blockTicks >= 1) {
836
                    blockTicks = 0;
837
                }
838
839
840
841
842
843
844
845
       /*         blockTicks++;
846
                PingSpoofComponent.blink();
847
848
                if (blockTicks == 1) {
849
                    allowAttack = true;
850
851
                } else if (blockTicks >= 2) {
852
853
                    allowAttack = false;
854
                    this.block(false, true);
855
                    blockTicks = 0;
856
                } */
857
858
859
                break;
860
861
862
            case "Imperfect Vanilla":
863
                if (this.hitTicks == 1 && mc.thePlayer.isSwingInProgress && Math.random() > 0.1) {
864
                    this.block(false, true);
865
                }
866
                break;
867
868
            case "Vanilla ReBlock":
869
                if (this.hitTicks == 1 /*|| !this.blocking*/) {
870
                    this.block(false, true);
871
                }
872
                break;
873
        }
874
    }
875
876
    private void preBlock() {
877
        switch (autoBlock.getValue().getName()) {
878
            case "Legit":
879
                double range = PlayerUtil.calculatePerfectRangeToEntity(target);
880
                mc.gameSettings.keyBindUseItem.setPressed(range < 3 && hitTicks <= 5 && mc.thePlayer.ticksSinceVelocity >= 5);
881
                blockTicks++;
882
                if (mc.gameSettings.keyBindUseItem.isPressed() || mc.thePlayer.isUsingItem()) {
883
                    blockTicks = 0;
884
                }
885
886
                allowAttack = blockTicks >= 2;
887
888
                break;
889
890
            case "NCP":
891
            case "Intave":
892
                allowAttack = true;
893
                this.unblock(false);
894
                break;
895
896
            case "Grim":
897
                PacketUtil.send(new C09PacketHeldItemChange(getComponent(Slot.class).getItemIndex() % 8 + 1));
898
                PacketUtil.send(new C09PacketHeldItemChange(getComponent(Slot.class).getItemIndex()));
899
                this.block(false, false);
900
                break;
901
902
            case "Watchdog 1.17":
903
                PacketUtil.send(new C09PacketHeldItemChange(getComponent(Slot.class).getItemIndex() % 8 + 1));
904
                PacketUtil.send(new C09PacketHeldItemChange(getComponent(Slot.class).getItemIndex()));
905
                this.block(false, false);
906
                break;
907
908
            case "New NCP":
909
                if (this.blocking) {
910
                    PacketUtil.send(new C09PacketHeldItemChange(getComponent(Slot.class).getItemIndex() % 8 + 1));
911
                    PacketUtil.send(new C09PacketHeldItemChange(getComponent(Slot.class).getItemIndex()));
912
                    this.blocking = false;
913
                }
914
                break;
915
916
            case "Old Intave":
917
                //                InventoryDeSyncComponent.setActive("/booster");
918
919
                if (mc.thePlayer.isUsingItem()) {
920
                    PacketUtil.send(new C09PacketHeldItemChange(getComponent(Slot.class).getItemIndex() % 8 + 1));
921
                    PacketUtil.send(new C09PacketHeldItemChange(getComponent(Slot.class).getItemIndex()));
922
                }
923
                break;
924
925
            case "Universal":
926
                if ((mc.playerController.curBlockDamageMP != 0 && mc.objectMouseOver.typeOfHit ==
927
                        MovingObjectPosition.MovingObjectType.BLOCK)) {
928
                    blockTicks = 0;
929
                    return;
930
                }
931
932
                blockTicks++;
933
                if (blockTicks > 5) blockTicks = 2;
934
935
                PingSpoofComponent.spoof(99999, false, false, false, false, true);
936
937
                switch (blockTicks) {
938
                    case 2:
939
                        this.block(false, true);
940
                        break;
941
942
                    case 3:
943
                        this.unblock(false);
944
                        break;
945
                }
946
947
                break;
948
949
            case "Watchdog":
950
                if (mc.playerController.curBlockDamageMP != 0 && mc.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
951
                    blockTicks = 0;
952
953
                }
954
955
                blockTicks++;
956
                if (blockTicks >= 3) blockTicks = 1;
957
958
                switch (blockTicks) {
959
                    case 1:
960
                        this.block(false, true);
961
                        PingSpoofComponent.dispatch();
962
963
964
                    case 2:
965
                        // Submitting the random number generation task to the thread pool
966
967
                        int slotId = ThreadLocalRandom.current().nextInt(7) + 2;
968
                        if (mc.thePlayer.ticksExisted % 2 == 0) {
969
                            PingSpoofComponent.blink();
970
                            //   PacketUtil.send(new C09PacketHeldItemChange(slotId));
971
                            //  PacketUtil.send(new C09PacketHeldItemChange(getComponent(Slot.class).getItemIndex()));
972
                        }
973
974
975
                        break;
976
                }
977
978
                break;
979
980
981
      /*          blockTicks++;
982
                PingSpoofComponent.blink();
983
984
                if (blockTicks == 1) {
985
                    allowAttack = true;
986
                    this.block(false, true);
987
                } else if (blockTicks >= 2) {
988
989
                    allowAttack = false;
990
                    this.block(false, true);
991
                    blockTicks = 0;
992
                }
993
                break; */
994
995
996
            case "Watchdog 2":
997
               // PacketUtil.send(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.START_DESTROY_BLOCK, new BlockPos(mc.thePlayer), EnumFacing.UP));
998
                if (mc.playerController.curBlockDamageMP != 0 && mc.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
999
                    blockTicks = 0;
1000
                    return;
1001
                }
1002
1003
                blockTicks++;
1004
                if (blockTicks >= 3) blockTicks = 1;
1005
1006
                switch (blockTicks) {
1007
                    case 1:
1008
                        this.block(false, true);
1009
                        PingSpoofComponent.dispatch();
1010
                        break;
1011
1012
                    case 2:
1013
1014
                        // Submitting the random number generation task to the thread pool
1015
                        PingSpoofComponent.blink();
1016
                        int slotId = ThreadLocalRandom.current().nextInt(7) + 2;
1017
                        if (mc.thePlayer.ticksExisted % 3 == 0) {
1018
                              PacketUtil.send(new C09PacketHeldItemChange(slotId));
1019
                           PacketUtil.send(new C09PacketHeldItemChange(getComponent(Slot.class).getItemIndex()));
1020
                        }
1021
                       // this.block(false, true);
1022
                }
1023
1024
                break;
1025
1026
1027
        }
1028
    }
1029
1030
    private void postBlock() {
1031
        switch (autoBlock.getValue().getName()) {
1032
            case "NCP":
1033
            case "New NCP":
1034
                this.block(true, false);
1035
                break;
1036
1037
            case "Universal":
1038
                if (this.blockTicks == 2) {
1039
                    PingSpoofComponent.dispatch();
1040
                }
1041
                break;
1042
1043
            case "Watchdog":
1044
1045
                if (this.blockTicks == 2) {
1046
                    //     PingSpoofComponent.dispatch();
1047
                }
1048
                break;
1049
1050
        }
1051
    }
1052
1053
    public boolean canBlock() {
1054
        return (!rightClickOnly.getValue() || mc.gameSettings.keyBindUseItem.isKeyDown()) && getComponent(Slot.class).getItemStack() != null && getComponent(Slot.class).getItemStack().getItem() instanceof ItemSword;
1055
    }
1056
}

What this file does

The 1057-line module file contains everything: the fifteen autoBlock submode values, the four rotation modes, the click-delay calculator (getDelay() scales the attack interval by weapon material: 1.6 speed for swords, 1.0 for spades, per-material axe/hoe speeds, computed as 1/speed*20-1 ticks), the target pipeline (getTargets() with the pastTargets EvictingList of size 9 so Switch mode never re-attacks a recently hit target, and the expandRange heuristic that every 20 ticks sets a random 3-3.5 block range expansion when no targets are found), the attack gate (doAttack() requires attackStopWatch.finished(nextSwing), clickStopWatch.finished(delay*50) or the Hit Select flag, and allowAttack from BadPacketsComponent unless badPacketsCheck is off), and the attack dispatch (keepSprint sends C02PacketUseEntity with syncCurrentPlayItem, otherwise playerController.attackEntity; Single/Switch attack the ray-cast entity when the primary target is out of range and the ray hits something that is not a fireball or item frame; Multiple removes out-of-range targets and attacks the rest). The block/ unblock pair sends C08 block placement and C07 RELEASE_USE_ITEM, and the Grim/Watchdog modes emit the C09 slot-swap pairs. The packetQueue (ConcurrentLinkedQueue) is flushed at the top of onPreMotionEvent, which is how the Universal and Watchdog modes order their spoofed packets relative to the tick boundary.

source RotationComponent.java (shared rotation engine)

RotationComponent.java201 lines · JavaOriginal ↗
1
package com.alan.clients.component.impl.player;
2
3
import com.alan.clients.component.Component;
4
import com.alan.clients.component.impl.player.rotationcomponent.MovementFix;
5
import com.alan.clients.event.Listener;
6
import com.alan.clients.event.Priorities;
7
import com.alan.clients.event.annotations.EventLink;
8
import com.alan.clients.event.impl.input.MoveInputEvent;
9
import com.alan.clients.event.impl.motion.JumpEvent;
10
import com.alan.clients.event.impl.motion.PreMotionEvent;
11
import com.alan.clients.event.impl.motion.PreUpdateEvent;
12
import com.alan.clients.event.impl.motion.StrafeEvent;
13
import com.alan.clients.event.impl.render.LookEvent;
14
import com.alan.clients.util.player.MoveUtil;
15
import com.alan.clients.util.rotation.RotationUtil;
16
import com.alan.clients.util.vector.Vector2f;
17
import lombok.Getter;
18
import lombok.Setter;
19
import net.minecraft.util.MathHelper;
20
21
import java.util.function.Function;
22
23
public final class RotationComponent extends Component {
24
    @Setter@Getter
25
    private static boolean active, smoothed;
26
    public static Vector2f rotations, lastRotations = new Vector2f(0, 0), targetRotations, lastServerRotations;
27
    private static double rotationSpeed;
28
    private static MovementFix correctMovement;
29
    private static Function<Vector2f, Boolean> raycast;
30
    private static float randomAngle;
31
    private static final Vector2f offset = new Vector2f(0, 0);
32
33
    /*
34
     * This method must be called on Pre Update Event to work correctly
35
     */
36
    public static void setRotations(final Vector2f rotations, final double rotationSpeed, final MovementFix correctMovement) {
37
        setRotations(rotations, rotationSpeed, correctMovement, null);
38
    }
39
40
    /*
41
     * This method must be called on Pre Update Event to work correctly
42
     */
43
    public static void setRotations(final Vector2f rotations, final double rotationSpeed, final MovementFix correctMovement, final Function<Vector2f, Boolean> raycast) {
44
        RotationComponent.targetRotations = rotations;
45
        RotationComponent.rotationSpeed = rotationSpeed * 36;
46
        RotationComponent.correctMovement = correctMovement;
47
        RotationComponent.raycast = raycast;
48
        active = true;
49
50
        smooth();
51
    }
52
53
    @EventLink(value = Priorities.VERY_LOW)
54
    public final Listener<PreUpdateEvent> onPreUpdate = event -> {
55
        if (!active || rotations == null || lastRotations == null || targetRotations == null || lastServerRotations == null) {
56
            rotations = lastRotations = targetRotations = lastServerRotations = new Vector2f(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch);
57
        }
58
59
        if (active) {
60
            smooth();
61
        }
62
63
//        mc.thePlayer.rotationYaw = rotations.x;
64
//        mc.thePlayer.rotationPitch = rotations.y;
65
66
        if (correctMovement == MovementFix.BACKWARDS_SPRINT && active) {
67
            if (Math.abs(rotations.x % 360 - Math.toDegrees(MoveUtil.direction()) % 360) > 45) {
68
                mc.gameSettings.keyBindSprint.setPressed(false);
69
                mc.thePlayer.setSprinting(false);
70
            }
71
        }
72
    };
73
74
    @EventLink(value = Priorities.LOW)
75
    public final Listener<MoveInputEvent> onMove = event -> {
76
        if (active && correctMovement == MovementFix.NORMAL && rotations != null) {
77
            /*
78
             * Calculating movement fix
79
             */
80
            final float yaw = rotations.x;
81
            MoveUtil.fixMovement(event, yaw);
82
        }
83
    };
84
85
    @EventLink(value = Priorities.VERY_LOW)
86
    public final Listener<LookEvent> onLook = event -> {
87
        if (active && rotations != null) {
88
            event.setRotation(rotations);
89
        }
90
    };
91
92
    @EventLink(value = Priorities.VERY_LOW)
93
    public final Listener<StrafeEvent> onStrafe = event -> {
94
        if (active && (correctMovement == MovementFix.NORMAL || correctMovement == MovementFix.TRADITIONAL) && rotations != null) {
95
            event.setYaw(rotations.x);
96
        }
97
    };
98
99
    @EventLink(value = Priorities.VERY_LOW)
100
    public final Listener<JumpEvent> onJump = event -> {
101
        if (active && (correctMovement == MovementFix.NORMAL || correctMovement == MovementFix.TRADITIONAL || correctMovement == MovementFix.BACKWARDS_SPRINT) && rotations != null) {
102
            event.setYaw(rotations.x);
103
        }
104
    };
105
106
    @EventLink(value = Priorities.VERY_LOW)
107
    public final Listener<PreMotionEvent> onPreMotionEvent = event -> {
108
        if (active && rotations != null) {
109
            final float yaw = rotations.x;
110
            final float pitch = rotations.y;
111
112
            event.setYaw(yaw);
113
            event.setPitch(pitch);
114
115
          //  mc.thePlayer.renderYawOffset = yaw;
116
            mc.thePlayer.rotationYawHead = yaw;
117
            mc.thePlayer.renderPitchHead = pitch;
118
119
            lastServerRotations = new Vector2f(yaw, pitch);
120
121
            if (Math.abs((rotations.x - mc.thePlayer.rotationYaw) % 360) < 1 && Math.abs((rotations.y - mc.thePlayer.rotationPitch)) < 1) {
122
                active = false;
123
124
                this.correctDisabledRotations();
125
            }
126
127
            lastRotations = rotations;
128
        } else {
129
            lastRotations = new Vector2f(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch);
130
        }
131
132
        targetRotations = new Vector2f(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch);
133
        smoothed = false;
134
    };
135
136
    private void correctDisabledRotations() {
137
        final Vector2f rotations = new Vector2f(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch);
138
        final Vector2f fixedRotations = RotationUtil.resetRotation(RotationUtil.applySensitivityPatch(rotations, lastRotations));
139
140
        mc.thePlayer.rotationYaw = fixedRotations.x;
141
        mc.thePlayer.rotationPitch = fixedRotations.y;
142
    }
143
144
    public static void smooth() {
145
        if (!smoothed) {
146
            float targetYaw = targetRotations.x;
147
            float targetPitch = targetRotations.y;
148
149
            // Randomisation
150
            if (raycast != null && (Math.abs(targetYaw - rotations.x) > 5 || Math.abs(targetPitch - rotations.y) > 5)) {
151
                final Vector2f trueTargetRotations = new Vector2f(targetRotations.getX(), targetRotations.getY());
152
153
                double speed = /*Math.min(*/(Math.random() * Math.random() * Math.random()) * 20/*, MoveUtil.speed() * 30)*/;
154
                randomAngle += (float) ((20 + (float) (Math.random() - 0.5) * (Math.random() * Math.random() * Math.random() * 360)) * (mc.thePlayer.ticksExisted / 10 % 2 == 0 ? -1 : 1));
155
156
                offset.setX((float) (offset.getX() + -MathHelper.sin((float) Math.toRadians(randomAngle)) * speed));
157
                offset.setY((float) (offset.getY() + MathHelper.cos((float) Math.toRadians(randomAngle)) * speed));
158
159
                targetYaw += offset.getX();
160
                targetPitch += offset.getY();
161
162
                if (!raycast.apply(new Vector2f(targetYaw, targetPitch))) {
163
                    randomAngle = (float) Math.toDegrees(Math.atan2(trueTargetRotations.getX() - targetYaw, targetPitch - trueTargetRotations.getY())) - 180;
164
165
                    targetYaw -= offset.getX();
166
                    targetPitch -= offset.getY();
167
168
                    offset.setX((float) (offset.getX() + -MathHelper.sin((float) Math.toRadians(randomAngle)) * speed));
169
                    offset.setY((float) (offset.getY() + MathHelper.cos((float) Math.toRadians(randomAngle)) * speed));
170
171
                    targetYaw = targetYaw + offset.getX();
172
                    targetPitch = targetPitch + offset.getY();
173
                }
174
175
                if (!raycast.apply(new Vector2f(targetYaw, targetPitch))) {
176
                    offset.setX(0);
177
                    offset.setY(0);
178
179
                    targetYaw = (float) (targetRotations.x + Math.random() * 2);
180
                    targetPitch = (float) (targetRotations.y + Math.random() * 2);
181
                }
182
            }
183
184
            rotations = RotationUtil.smooth(new Vector2f(targetYaw, targetPitch),
185
                    rotationSpeed + Math.random());
186
187
            if (correctMovement == MovementFix.NORMAL || correctMovement == MovementFix.TRADITIONAL) {
188
                mc.thePlayer.movementYaw = rotations.x;
189
            }
190
191
            mc.thePlayer.velocityYaw = rotations.x;
192
        }
193
194
        smoothed = true;
195
196
        /*
197
         * Updating MouseOver
198
         */
199
        mc.entityRenderer.getMouseOver(1);
200
    }
201
}

What this file does

KillAura drives all its aiming through this component. setRotations(targetRotations, rotationSpeed, correctMovement, raycast) stores the target, multiplies the speed by 36, and calls smooth(). smooth() is where the anti-detection work happens: when the target differs from the current rotations by more than 5 degrees it generates a random-angle walk (speed = (random*random*random)*20, offset incremented by sin/cos of a randomAngle that flips sign every 10 ticks) and offsets the target; after each offset it applies the raycast predicate supplied by the module, and if the offset misses the entity it inverts the walk direction and retries, finally falling back to targetRotations plus 2 degrees of jitter. This keeps every intermediate rotation on a curved path that still crosses the target hitbox, which defeats checks that only sample the final look while preserving aim. The component's onPreMotionEvent listener writes the smoothed rotations into the outgoing motion event (event.setYaw/Pitch), sets rotationYawHead and renderPitchHead, and records lastServerRotations, while LookEvent, StrafeEvent, MoveInputEvent and JumpEvent apply the movement fix when MovementFix is enabled. correctDisabledRotations() uses RotationUtil.resetRotation and applySensitivityPatch to snap the view back onto the GCD grid when the aura releases the look.

source TargetComponent.java (entity acquisition)

TargetComponent.java85 lines · JavaOriginal ↗
1
package com.alan.clients.component.impl.player;
2
3
import com.alan.clients.Client;
4
import com.alan.clients.component.Component;
5
import com.alan.clients.event.Listener;
6
import com.alan.clients.event.annotations.EventLink;
7
import com.alan.clients.event.impl.other.BackendPacketEvent;
8
import com.alan.clients.event.impl.other.WorldChangeEvent;
9
import com.alan.clients.module.impl.combat.KillAura;
10
import com.alan.clients.util.Accessor;
11
import com.alan.clients.util.player.PlayerUtil;
12
import net.minecraft.entity.Entity;
13
import net.minecraft.entity.EntityCreature;
14
import net.minecraft.entity.EntityLivingBase;
15
import net.minecraft.entity.INpc;
16
import net.minecraft.entity.item.EntityArmorStand;
17
import net.minecraft.entity.monster.EntityMob;
18
import net.minecraft.entity.monster.IMob;
19
import net.minecraft.entity.passive.EntityAmbientCreature;
20
import net.minecraft.entity.passive.EntityAnimal;
21
import net.minecraft.entity.passive.EntityWaterMob;
22
import net.minecraft.entity.passive.IAnimals;
23
import net.minecraft.entity.player.EntityPlayer;
24
import rip.vantage.commons.packet.impl.client.protection.C2SPacketFilterEntities;
25
import rip.vantage.commons.packet.impl.server.protection.S2CPacketEntities;
26
import rip.vantage.commons.util.time.StopWatch;
27
import rip.vantage.network.core.Network;
28
29
import java.util.ArrayList;
30
import java.util.HashMap;
31
import java.util.List;
32
import java.util.stream.Collectors;
33
34
import static org.json.XMLTokener.entity;
35
36
public class TargetComponent extends Component implements Accessor {
37
38
    private static KillAura killAura;
39
40
    public static EntityLivingBase getTarget(double range) {
41
        return getTargets(range).stream().findFirst().orElse(null);
42
    }
43
44
    public static List<EntityLivingBase> getTargets(double range) {
45
        if (killAura == null) {
46
            killAura = Client.INSTANCE.getModuleManager().get(KillAura.class);
47
        }
48
49
        return getTargets(killAura.player.getValue(), killAura.invisibles.getValue(), killAura.animals.getValue(), killAura.mobs.getValue(), killAura.teams.getValue()).stream().filter(entity -> mc.thePlayer.getDistanceToEntity(entity) <= range).collect(Collectors.toList());
50
    }
51
52
    public static List<EntityLivingBase> getTargets(double range, boolean players, boolean invisibles, boolean animals, boolean mobs, boolean teams) {
53
        return getTargets(players, invisibles, animals, mobs, teams).stream().filter(entity -> mc.thePlayer.getDistanceToEntity(entity) <= range).collect(Collectors.toList());
54
    }
55
56
    public static List<EntityLivingBase> getTargets() {
57
        if (killAura == null) {
58
            killAura = Client.INSTANCE.getModuleManager().get(KillAura.class);
59
        }
60
61
        return getTargets(killAura.player.getValue(), killAura.invisibles.getValue(), killAura.animals.getValue(), killAura.mobs.getValue(), killAura.teams.getValue());
62
    }
63
64
    public static List<EntityLivingBase> getTargets(boolean players, boolean invisibles, boolean animals, boolean mobs, boolean teams) {
65
        return getTargets(players, invisibles, animals, mobs, teams, false);
66
    }
67
68
    public static List<EntityLivingBase> getTargets(boolean players, boolean invisibles, boolean animals, boolean mobs, boolean teams, boolean friends) {
69
70
        return mc.theWorld.loadedEntityList.stream()
71
                .filter(entity -> entity instanceof EntityLivingBase
72
                            && !Client.INSTANCE.getBotManager().contains(entity)
73
                            && entity != mc.getRenderViewEntity()
74
                            && (!UserFriendAndTargetComponent.isFriend(entity.getCommandSenderName()) || friends)
75
                            && (!(entity instanceof EntityPlayer) || players)
76
                            && (!(entity instanceof IMob || entity instanceof INpc) || mobs)
77
                            && (!(entity instanceof EntityAnimal || entity instanceof EntityAmbientCreature || entity instanceof EntityWaterMob) || animals)
78
                            && (!entity.isInvisible() || invisibles)
79
                            && !(entity instanceof EntityArmorStand)
80
                )
81
                .map(entity -> ((EntityLivingBase) entity))
82
                .filter(entity -> !(entity instanceof EntityPlayer) || (!PlayerUtil.sameTeam(entity) || teams))
83
                .collect(Collectors.toList());
84
    }
85
}

What this file does

KillAura.getTargets() delegates to TargetComponent.getTargets(range), which streams mc.theWorld.loadedEntityList and filters EntityLivingBase entries by the module's own BooleanValues: the player/invisibles/animals/mobs toggles (invisibles defaults false so invisible players are skipped), teams via PlayerUtil.sameTeam, friends via UserFriendAndTargetComponent, the bot manager blacklist, and armor stands excluded outright. The result is filtered by getDistanceToEntity <= range. The component holds a static reference to the KillAura module instance so the toggles can be read without wiring, and the same filter is shared by other combat modules (KeepRange, TickBase, Mimic) which is why the friend/bot/team logic lives here rather than in the module. For the KillAura this component is the full target-selection surface: the module only adds the Switch-mode pastTargets eviction, the expandRange retry, and the sort order on top of the component's distance-filtered list.

source RotationUtil.java (rotation calculation and sensitivity patch)

RotationUtil.java181 lines · JavaOriginal ↗
1
package com.alan.clients.util.rotation;
2
3
import com.alan.clients.component.impl.player.RotationComponent;
4
import com.alan.clients.util.Accessor;
5
import com.alan.clients.util.RayCastUtil;
6
import com.alan.clients.util.math.MathConst;
7
import com.alan.clients.util.vector.Vector2f;
8
import com.alan.clients.util.vector.Vector3d;
9
import lombok.experimental.UtilityClass;
10
import net.minecraft.client.Minecraft;
11
import net.minecraft.entity.Entity;
12
import net.minecraft.util.*;
13
14
@UtilityClass
15
public class RotationUtil implements Accessor {
16
17
    public Vector2f calculate(final Vector3d from, final Vector3d to) {
18
        final Vector3d diff = to.subtract(from);
19
        final double distance = Math.hypot(diff.getX(), diff.getZ());
20
        final float yaw = (float) (MathHelper.atan2(diff.getZ(), diff.getX()) * MathConst.TO_DEGREES) - 90.0F;
21
        final float pitch = (float) (-(MathHelper.atan2(diff.getY(), distance) * MathConst.TO_DEGREES));
22
        return new Vector2f(yaw, pitch);
23
    }
24
25
    public Vector2f calculate(final Entity entity) {
26
        return calculate(entity.getCustomPositionVector().add(0, Math.max(0, Math.min(mc.thePlayer.posY - entity.posY +
27
                mc.thePlayer.getEyeHeight(), (entity.getEntityBoundingBox().maxY - entity.getEntityBoundingBox().minY) * 0.9)), 0));
28
    }
29
30
    public Vector2f calculate(final Entity entity, final boolean adaptive, final double range) {
31
        Vector2f normalRotations = calculate(entity);
32
        if (!adaptive || RayCastUtil.rayCast(normalRotations, range).typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY) {
33
            return normalRotations;
34
        }
35
36
        for (double yPercent = 1; yPercent >= 0; yPercent -= 0.25 + Math.random() * 0.1) {
37
            for (double xPercent = 1; xPercent >= -0.5; xPercent -= 0.5) {
38
                for (double zPercent = 1; zPercent >= -0.5; zPercent -= 0.5) {
39
                    Vector2f adaptiveRotations = calculate(entity.getCustomPositionVector().add(
40
                            (entity.getEntityBoundingBox().maxX - entity.getEntityBoundingBox().minX) * xPercent,
41
                            (entity.getEntityBoundingBox().maxY - entity.getEntityBoundingBox().minY) * yPercent,
42
                            (entity.getEntityBoundingBox().maxZ - entity.getEntityBoundingBox().minZ) * zPercent));
43
44
                    MovingObjectPosition rayCastResult = RayCastUtil.rayCast(adaptiveRotations, range);
45
                    if (rayCastResult != null && rayCastResult.typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY) {
46
                        return adaptiveRotations;
47
                    }
48
                }
49
            }
50
        }
51
52
        return normalRotations;
53
    }
54
55
    public Vector2f calculate(final Vec3 to, final EnumFacing enumFacing) {
56
        return calculate(new Vector3d(to.xCoord, to.yCoord, to.zCoord), enumFacing);
57
    }
58
59
    public Vector2f calculate(final Vec3 to) {
60
        return calculate(mc.thePlayer.getCustomPositionVector().add(0, mc.thePlayer.getEyeHeight(), 0), new Vector3d(to.xCoord, to.yCoord, to.zCoord));
61
    }
62
63
    public Vector2f calculate(final BlockPos to) {
64
        return calculate(mc.thePlayer.getCustomPositionVector().add(0, mc.thePlayer.getEyeHeight(), 0), new Vector3d(to.getX(), to.getY(), to.getZ()).add(0.5, 0.5, 0.5));
65
    }
66
67
    public Vector2f calculate(final Vector3d to) {
68
        return calculate(mc.thePlayer.getCustomPositionVector().add(0, mc.thePlayer.getEyeHeight(), 0), to);
69
    }
70
71
    public Vector2f calculate(final Vector3d position, final EnumFacing enumFacing) {
72
        double x = position.getX() + 0.5D;
73
        double y = position.getY() + 0.5D;
74
        double z = position.getZ() + 0.5D;
75
76
        x += (double) enumFacing.getDirectionVec().getX() * 0.5D;
77
        y += (double) enumFacing.getDirectionVec().getY() * 0.5D;
78
        z += (double) enumFacing.getDirectionVec().getZ() * 0.5D;
79
        return calculate(new Vector3d(x, y, z));
80
    }
81
82
    public Vector2f applySensitivityPatch(final Vector2f rotation) {
83
        final Vector2f previousRotation = mc.thePlayer.getPreviousRotation();
84
        final float mouseSensitivity = (float) (mc.gameSettings.mouseSensitivity * (1 + Math.random() / 10000000) * 0.6F + 0.2F);
85
        final double multiplier = mouseSensitivity * mouseSensitivity * mouseSensitivity * 8.0F * 0.15D;
86
        final float yaw = previousRotation.x + (float) (Math.round((rotation.x - previousRotation.x) / multiplier) * multiplier);
87
        final float pitch = previousRotation.y + (float) (Math.round((rotation.y - previousRotation.y) / multiplier) * multiplier);
88
        return new Vector2f(yaw, MathHelper.clamp_float(pitch, -90, 90));
89
    }
90
91
    public Vector2f applySensitivityPatch(final Vector2f rotation, final Vector2f previousRotation) {
92
        final float mouseSensitivity = (float) (mc.gameSettings.mouseSensitivity * (1 + Math.random() / 10000000) * 0.6F + 0.2F);
93
        final double multiplier = mouseSensitivity * mouseSensitivity * mouseSensitivity * 8.0F * 0.15D;
94
        final float yaw = previousRotation.x + (float) (Math.round((rotation.x - previousRotation.x) / multiplier) * multiplier);
95
        final float pitch = previousRotation.y + (float) (Math.round((rotation.y - previousRotation.y) / multiplier) * multiplier);
96
        return new Vector2f(yaw, MathHelper.clamp_float(pitch, -90, 90));
97
    }
98
99
    public Vector2f relateToPlayerRotation(final Vector2f rotation) {
100
        final Vector2f previousRotation = mc.thePlayer.getPreviousRotation();
101
        final float yaw = previousRotation.x + MathHelper.wrapAngleTo180_float(rotation.x - previousRotation.x);
102
        final float pitch = MathHelper.clamp_float(rotation.y, -90, 90);
103
        return new Vector2f(yaw, pitch);
104
    }
105
106
    public Vector2f resetRotation(final Vector2f rotation) {
107
        if (rotation == null) {
108
            return null;
109
        }
110
111
        final float yaw = rotation.x + MathHelper.wrapAngleTo180_float(mc.thePlayer.rotationYaw - rotation.x);
112
        final float pitch = mc.thePlayer.rotationPitch;
113
        return new Vector2f(yaw, pitch);
114
    }
115
116
    public Vector2f move(final Vector2f targetRotation, final double speed) {
117
        return move(RotationComponent.lastRotations, targetRotation, speed);
118
    }
119
120
    public Vector2f move(final Vector2f lastRotation, final Vector2f targetRotation, double speed) {
121
        if (speed != 0) {
122
123
            double deltaYaw = MathHelper.wrapAngleTo180_float(targetRotation.x - lastRotation.x);
124
            final double deltaPitch = (targetRotation.y - lastRotation.y);
125
126
            final double distance = Math.sqrt(deltaYaw * deltaYaw + deltaPitch * deltaPitch);
127
            final double distributionYaw = Math.abs(deltaYaw / distance);
128
            final double distributionPitch = Math.abs(deltaPitch / distance);
129
130
            final double maxYaw = speed * distributionYaw;
131
            final double maxPitch = speed * distributionPitch;
132
133
            final float moveYaw = (float) Math.max(Math.min(deltaYaw, maxYaw), -maxYaw);
134
            final float movePitch = (float) Math.max(Math.min(deltaPitch, maxPitch), -maxPitch);
135
136
            return new Vector2f(moveYaw, movePitch);
137
        }
138
139
        return new Vector2f(0, 0);
140
    }
141
142
    public Vector2f smooth(final Vector2f targetRotation, final double speed) {
143
        return smooth(RotationComponent.lastRotations, targetRotation, speed);
144
    }
145
146
    public Vector2f smooth(final Vector2f lastRotation, final Vector2f targetRotation, final double speed) {
147
        float yaw = targetRotation.x;
148
        float pitch = targetRotation.y;
149
        final float lastYaw = lastRotation.x;
150
        final float lastPitch = lastRotation.y;
151
152
        if (speed != 0) {
153
            Vector2f move = move(targetRotation, speed);
154
155
            yaw = lastYaw + move.x;
156
            pitch = lastPitch + move.y;
157
158
            for (int i = 1; i <= (int) (Minecraft.getDebugFPS() / 20f + Math.random() * 10); ++i) {
159
160
                if (Math.abs(move.x) + Math.abs(move.y) > 0.0001) {
161
                    yaw += (Math.random() - 0.5) / 1000;
162
                    pitch -= Math.random() / 200;
163
                }
164
165
                /*
166
                 * Fixing GCD
167
                 */
168
                final Vector2f rotations = new Vector2f(yaw, pitch);
169
                final Vector2f fixedRotations = RotationUtil.applySensitivityPatch(rotations);
170
171
                /*
172
                 * Setting rotations
173
                 */
174
                yaw = fixedRotations.x;
175
                pitch = Math.max(-90, Math.min(90, fixedRotations.y));
176
            }
177
        }
178
179
        return new Vector2f(yaw, pitch);
180
    }
181
}

What this file does

The KillAura calls RotationUtil.calculate(target, true, range) in the Legit/Normal and Snap modes to get the exact yaw/pitch that points at the target's eyes, and RotationUtil.applySensitivityPatch in the NCP mode. calculate() returns the atan2-based look to the entity's position plus eye height, with the range parameter used to clamp the vertical delta. applySensitivityPatch is the 6.2.4 equivalent of the 5.99 getFixedRotation: it rounds the rotation delta to the mouse-sensitivity GCD (gcd = (sensitivity*0.6+0.2)^3 * 1.2) so the yaw/pitch stream sent to the server only contains deltas a real mouse could produce, which is what keeps the module's rotations from tripping rotation-snapping heuristics. The module's NCP rotation mode applies the patch after predicting both entities' motion, and the Legit/Normal mode feeds the unpatched result into RotationComponent where the smoothing walk runs. The utility also carries the resetRotation helper used by RotationComponent.correctDisabledRotations to return the view to the player's real rotations on the GCD grid when the aura stops aiming.

anticheat Countering Checks

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

anticheat Reach (lag-compensated ray trace with hitbox result)

Reach.java404 lines · Java
1
// This file was designed and is an original check for GrimAC
2
// Copyright (C) 2021 DefineOutside
3
//
4
// This program is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// This program is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
package ac.grim.grimac.checks.impl.combat;
17
18
import ac.grim.grimac.api.config.ConfigManager;
19
import ac.grim.grimac.api.storage.verbose.Verbose;
20
import ac.grim.grimac.checks.Check;
21
import ac.grim.grimac.checks.CheckData;
22
import ac.grim.grimac.checks.type.PacketReceiveListener;
23
import ac.grim.grimac.player.GrimPlayer;
24
import ac.grim.grimac.utils.collisions.datatypes.SimpleCollisionBox;
25
import ac.grim.grimac.utils.data.packetentity.PacketEntity;
26
import ac.grim.grimac.utils.data.packetentity.PacketEntitySizeable;
27
import ac.grim.grimac.utils.data.packetentity.dragon.PacketEntityEnderDragonPart;
28
import ac.grim.grimac.utils.math.Vector3dm;
29
import ac.grim.grimac.utils.nmsutil.ReachUtils;
30
import ac.grim.grimac.utils.viaversion.ViaVersionUtil;
31
import com.github.retrooper.packetevents.PacketEvents;
32
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
33
import com.github.retrooper.packetevents.manager.server.ServerVersion;
34
import com.github.retrooper.packetevents.protocol.attribute.Attributes;
35
import com.github.retrooper.packetevents.protocol.component.ComponentTypes;
36
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemAttackRange;
37
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
38
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
39
import com.github.retrooper.packetevents.protocol.item.ItemStack;
40
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
41
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
42
import com.github.retrooper.packetevents.protocol.player.GameMode;
43
import com.github.retrooper.packetevents.protocol.player.InteractionHand;
44
import com.github.retrooper.packetevents.util.Vector3d;
45
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientAttack;
46
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientInteractEntity;
47
import com.viaversion.viaversion.api.Via;
48
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
49
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
50
import org.jetbrains.annotations.NotNull;
51
52
import java.util.ArrayList;
53
import java.util.Arrays;
54
import java.util.Collections;
55
import java.util.List;
56
57
// You may not copy the check unless you are licensed under GPL
58
@CheckData(name = "Reach", stableKey = "grim.combat.reach", description = "Attacked an entity from too far away")
59
public class Reach extends Check implements PacketReceiveListener {
60
    private static final Verbose V = Verbose.of("{f64:%.5f} blocks, type={entity}");
61
62
    private static final List<EntityType> blacklisted = Arrays.asList(
63
            EntityTypes.BOAT,
64
            EntityTypes.CHEST_BOAT,
65
            EntityTypes.SHULKER);
66
    private static final CheckResult NONE = new CheckResult(ResultType.NONE, 0, 0, false);
67
    // Only one flag per reach attack, per entity, per tick.
68
    // We store position because lastX isn't reliable on teleports.
69
    private final Int2ObjectMap<InteractionData> playerAttackQueue = new Int2ObjectOpenHashMap<>();
70
    private boolean cancelImpossibleHits;
71
    private double threshold;
72
    private double cancelBuffer; // For the next 4 hits after using reach, we aggressively cancel reach
73
74
    public Reach(GrimPlayer player) {
75
        super(player);
76
    }
77
78
    @Override
79
    public void onPacketReceive(final PacketReceiveEvent event) {
80
        if (!player.disableGrim && event.getPacketType() == PacketType.Play.Client.ATTACK) {
81
            WrapperPlayClientAttack packet = new WrapperPlayClientAttack(event);
82
            onInteract(event, packet.getEntityId(), InteractionHand.MAIN_HAND);
83
        }
84
85
        if (!player.disableGrim && event.getPacketType() == PacketType.Play.Client.INTERACT_ENTITY) {
86
            WrapperPlayClientInteractEntity packet = new WrapperPlayClientInteractEntity(event);
87
            onInteract(event, packet.getEntityId(), packet.getAction() == WrapperPlayClientInteractEntity.InteractAction.ATTACK ? InteractionHand.MAIN_HAND : packet.getHand());
88
        }
89
90
        // If the player set their look, or we know they have a new tick
91
        if (isUpdate(event.getPacketType())) {
92
            tickBetterReachCheckWithAngle();
93
        }
94
    }
95
96
    private void onInteract(PacketReceiveEvent event, int entityId, InteractionHand hand) {
97
        // Don't let the player teleport to bypass reach
98
        if (player.getSetbackTeleportUtil().shouldBlockMovement()) {
99
            event.setCancelled(true);
100
            player.onPacketCancel();
101
            return;
102
        }
103
104
        PacketEntity entity = player.compensatedEntities.entityMap.get(entityId);
105
        // Stop people from freezing transactions before an entity spawns to bypass reach
106
        // TODO: implement dragon parts?
107
        if (entity == null || entity instanceof PacketEntityEnderDragonPart) {
108
            // Only cancel if and only if we are tracking this entity
109
            // This is because we don't track paintings.
110
            if (shouldModifyPackets() && player.compensatedEntities.serverPositionsMap.containsKey(entityId)) {
111
                event.setCancelled(true);
112
                player.onPacketCancel();
113
            }
114
            return;
115
        }
116
117
        // Dead entities cause false flags (https://github.com/GrimAnticheat/Grim/issues/546)
118
        if (entity.isDead) return;
119
120
        // TODO: Remove when in front of via
121
        if (entity.getType() == EntityTypes.ARMOR_STAND && player.getClientVersion().isOlderThan(ClientVersion.V_1_8))
122
            return;
123
        // Prevents Happy Ghast Reach false on 1.21.6+ servers with ViaBackwards set up
124
        if (entity.getType() == EntityTypes.HAPPY_GHAST && player.getClientVersion().isOlderThan(ClientVersion.V_1_21_6))
125
            return;
126
        if (player.gamemode == GameMode.CREATIVE || player.gamemode == GameMode.SPECTATOR)
127
            return;
128
        if (player.inVehicle()) return;
129
        if (entity.riding != null) return;
130
131
        ItemStack currentStack = player.inventory.getItemInHand(hand);
132
        ItemStack startStack = player.inventory.getStartOfTickStack();
133
134
        boolean hasRange = false;
135
        float maxReach = 0f;
136
        float hitboxMargin = 0f;
137
        Vector3dm attackRangeMovement = null;
138
139
        boolean clientAttackRangeExists = player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_21_11);
140
        boolean clientAndServerAgrees = clientAttackRangeExists && ATTACK_RANGE_COMPONENT_EXISTS;
141
142
        boolean viaVersionAvailable = false;
143
        if (USE_1_8_HITBOX_MARGIN && ViaVersionUtil.isAvailable) {
144
            viaVersionAvailable = Via.getConfig().getValues().containsKey("use-1_8-hitbox-margin") && Via.getConfig().use1_8HitboxMargin();
145
        }
146
147
        boolean clientAndViaVersion = clientAttackRangeExists && viaVersionAvailable;
148
        if (clientAndServerAgrees || clientAndViaVersion) {
149
            ItemAttackRange startRange = startStack.getComponentOr(ComponentTypes.ATTACK_RANGE, null);
150
            ItemAttackRange currentRange = currentStack.getComponentOr(ComponentTypes.ATTACK_RANGE, null);
151
152
            if (clientAndViaVersion) {
153
                if (startStack != ItemStack.EMPTY) {
154
                    startRange = new ItemAttackRange(0F, 3F, 0F, 4F, 0.1F, 1F);
155
                }
156
157
                if (currentStack != ItemStack.EMPTY) {
158
                    currentRange = new ItemAttackRange(0F, 3F, 0F, 4F, 0.1F, 1F);
159
                }
160
            }
161
162
            // If the start stack has no range component, the client defaults to vanilla reach behavior,
163
            // regardless of what the current stack is (No Range -> X = No Range used).
164
            if (startRange != null) {
165
                hasRange = true;
166
                if (currentRange == null) {
167
                    // Range (Start) -> No Range (Current)
168
                    // Client logic uses Start Range, including the attack_range movement projection.
169
                    if (!clientAndViaVersion) {
170
                        attackRangeMovement = player.clientVelocity.clone();
171
                    }
172
                    maxReach = startRange.getMaxRange();
173
                    hitboxMargin = startRange.getHitboxMargin();
174
                } else {
175
                    // Range (Start) -> Range (Current)
176
                    // Client logic requires satisfying BOTH constraints
177
                    maxReach = Math.min(startRange.getMaxRange(), currentRange.getMaxRange());
178
                    hitboxMargin = Math.min(startRange.getHitboxMargin(), currentRange.getHitboxMargin());
179
                }
180
            }
181
        }
182
183
        boolean tooManyAttacks = playerAttackQueue.size() > 10;
184
        if (!tooManyAttacks) {
185
            playerAttackQueue.put(entityId, new InteractionData(
186
                    player.x, player.y, player.z,
187
                    hasRange, maxReach, hitboxMargin, attackRangeMovement
188
            )); // Queue for next tick for very precise check
189
        }
190
191
        boolean knownInvalid = attackRangeMovement == null && isKnownInvalid(entity, hasRange, maxReach, hitboxMargin);
192
193
        if ((shouldModifyPackets() && cancelImpossibleHits && knownInvalid) || tooManyAttacks) {
194
            event.setCancelled(true);
195
            player.onPacketCancel();
196
        }
197
    }
198
199
    // This method finds the most optimal point at which the user should be aiming at
200
    // and then measures the distance between the player's eyes and this target point
201
    //
202
    // It will not cancel every invalid attack but should cancel 3.05+ or so in real-time
203
    // Let the post look check measure the distance, as it will always return equal or higher
204
    // than this method.  If this method flags, the other method WILL flag.
205
    //
206
    // Meaning that the other check should be the only one that flags.
207
    private boolean isKnownInvalid(PacketEntity reachEntity, boolean hasAttackRange, float itemMaxReach, float itemHitboxMargin) {
208
        // If the entity doesn't exist, or if it is exempt, or if it is dead
209
        if ((blacklisted.contains(reachEntity.getType()) || !reachEntity.isLivingEntity) && reachEntity.getType() != EntityTypes.END_CRYSTAL)
210
            return false; // exempt
211
212
        if (player.gamemode == GameMode.CREATIVE || player.gamemode == GameMode.SPECTATOR)
213
            return false;
214
        if (player.inVehicle()) return false;
215
216
        // Filter out what we assume to be cheats
217
        if (cancelBuffer != 0) {
218
            CheckResult result = checkReach(reachEntity, player.x, player.y, player.z, hasAttackRange, itemMaxReach, itemHitboxMargin, null, true);
219
            return result.isFlag();
220
        } else {
221
            SimpleCollisionBox targetBox = getTargetBox(reachEntity);
222
223
            double maxReach = applyReachModifiers(targetBox, hasAttackRange, itemMaxReach, itemHitboxMargin, !player.packetStateData.didLastMovementIncludePosition);
224
            return ReachUtils.getMinReachToBox(player, targetBox) > maxReach;
225
        }
226
    }
227
228
    private void tickBetterReachCheckWithAngle() {
229
        for (Int2ObjectMap.Entry<InteractionData> attack : playerAttackQueue.int2ObjectEntrySet()) {
230
            PacketEntity reachEntity = player.compensatedEntities.entityMap.get(attack.getIntKey());
231
            if (reachEntity == null) continue;
232
233
            InteractionData interactionData = attack.getValue();
234
            CheckResult result = checkReach(reachEntity, interactionData.x, interactionData.y, interactionData.z, interactionData.hasAttackRange, interactionData.maxReach, interactionData.hitboxMargin, interactionData.attackRangeMovement, false);
235
            switch (result.type()) {
236
                case REACH -> flag(
237
                        V.write(verbose()).f64(result.minDistance()).uint(reachEntity.getType().getId(player.getClientVersion())),
238
                        () -> {
239
                            String added = ", type=" + reachEntity.getType().getName().getKey();
240
                            if (reachEntity instanceof PacketEntitySizeable sizeable) {
241
                                added += ", size=" + sizeable.size;
242
                            }
243
                            return result.verbose() + added;
244
                        });
245
                case HITBOX -> {
246
                    String added = "type=" + reachEntity.getType().getName().getKey();
247
                    if (reachEntity instanceof PacketEntitySizeable sizeable) {
248
                        added += ", size=" + sizeable.size;
249
                    }
250
                    player.checkManager.getCheck(Hitboxes.class).flag(result.verbose() + added);
251
                }
252
            }
253
        }
254
255
        playerAttackQueue.clear();
256
    }
257
258
    @NotNull
259
    private CheckResult checkReach(PacketEntity reachEntity, double x, double y, double z, boolean hasAttackRange, float itemMaxReach, float itemHitboxMargin, Vector3dm attackRangeMovement, boolean isPrediction) {
260
        SimpleCollisionBox targetBox = getTargetBox(reachEntity);
261
262
        double movementAllowance = attackRangeMovement == null ? 0 : getAttackRangeMovementAllowance(attackRangeMovement);
263
        double maxReach = applyReachModifiers(targetBox, hasAttackRange, itemMaxReach, itemHitboxMargin, !player.packetStateData.didLastLastMovementIncludePosition) + movementAllowance;
264
        double minDistance = Double.MAX_VALUE;
265
266
        // https://bugs.mojang.com/browse/MC-67665
267
        List<Vector3dm> possibleLookDirs = new ArrayList<>(Collections.singletonList(ReachUtils.getLook(player, player.yaw, player.pitch)));
268
269
        // If we are a tick behind, we don't know their next look so don't bother doing this
270
        if (!isPrediction) {
271
            // 1.7 players do not have any of these issues! They are always on the latest look vector
272
            if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_8)) {
273
                possibleLookDirs.add(ReachUtils.getLook(player, player.lastYaw, player.pitch));
274
275
                // 1.9+ players could be a tick behind because we don't get skipped ticks
276
                if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_9)) {
277
                    possibleLookDirs.add(ReachUtils.getLook(player, player.lastYaw, player.lastPitch));
278
                }
279
            }
280
        }
281
282
        // +3 would be 3 + 3 = 6, which is the pre-1.20.5 behaviour, preventing "Missed Hitbox"
283
        final double distance = maxReach + 3;
284
285
        final double[] possibleEyeHeights = player.getPossibleEyeHeights();
286
        for (Vector3dm lookVec : possibleLookDirs) {
287
            lookVec.multiply(distance);
288
289
            for (double eye : possibleEyeHeights) {
290
                final Vector3d eyePos = new Vector3d(x, y + eye, z);
291
                Vector3d endReachPos = eyePos.add(lookVec.getX(), lookVec.getY(), lookVec.getZ());
292
293
                Vector3d intercept = ReachUtils.calculateIntercept(targetBox, eyePos, endReachPos).first();
294
295
                if (ReachUtils.isVecInside(targetBox, eyePos)) {
296
                    minDistance = 0;
297
                    break;
298
                }
299
300
                if (intercept != null) {
301
                    minDistance = Math.min(eyePos.distance(intercept), minDistance);
302
                }
303
            }
304
        }
305
306
        // if the entity is not exempt and the entity is alive
307
        if ((!blacklisted.contains(reachEntity.getType()) && reachEntity.isLivingEntity) || reachEntity.getType() == EntityTypes.END_CRYSTAL) {
308
            if (minDistance == Double.MAX_VALUE) {
309
                cancelBuffer = 1;
310
                return new CheckResult(ResultType.HITBOX, 0, 0, false);
311
            } else if (minDistance > maxReach) {
312
                cancelBuffer = 1;
313
                return new CheckResult(ResultType.REACH, minDistance, movementAllowance, attackRangeMovement != null);
314
            } else {
315
                cancelBuffer = Math.max(0, cancelBuffer - 0.25);
316
            }
317
        }
318
319
        return NONE;
320
    }
321
322
    private SimpleCollisionBox getTargetBox(PacketEntity reachEntity) {
323
        if (reachEntity.getType() == EntityTypes.END_CRYSTAL) { // Hardcode end crystal box
324
            return new SimpleCollisionBox(reachEntity.trackedServerPosition.getPos().subtract(1, 0, 1), reachEntity.trackedServerPosition.getPos().add(1, 2, 1));
325
        }
326
        return reachEntity.getPossibleCollisionBoxes();
327
    }
328
329
    private double getAttackRangeMovementAllowance(Vector3dm attackRangeMovement) {
330
        if (attackRangeMovement.lengthSquared() == 0) {
331
            return 0;
332
        }
333
334
        return getForwardMovement(attackRangeMovement, player.yaw, player.pitch);
335
    }
336
337
    private double getForwardMovement(Vector3dm movement, float yaw, float pitch) {
338
        return Math.max(0, movement.dot(ReachUtils.getLook(player, yaw, pitch)));
339
    }
340
341
    private static final boolean ATTACK_RANGE_COMPONENT_EXISTS = PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_21_11);
342
    private static final boolean USE_1_8_HITBOX_MARGIN = PacketEvents.getAPI().getServerManager().getVersion().isOlderThanOrEquals(ServerVersion.V_1_8_8);
343
344
    private double applyReachModifiers(SimpleCollisionBox targetBox, boolean hasAttackRange, float itemMaxReach, float itemHitboxMargin, boolean giveMovementThreshold) {
345
        double maxReach;
346
        double hitboxMargin = threshold;
347
348
        if (hasAttackRange) {
349
            maxReach = itemMaxReach;
350
            hitboxMargin += itemHitboxMargin;
351
        } else {
352
            maxReach = player.compensatedEntities.self.getAttributeValue(Attributes.ENTITY_INTERACTION_RANGE);
353
            // 1.7 and 1.8 players get a bit of extra hitbox (this is why you should use 1.8 on cross version servers)
354
            // Yes, this is vanilla and not uncertainty.  All reach checks have this or they are wrong.
355
            if (player.getClientVersion().isOlderThan(ClientVersion.V_1_9)) {
356
                hitboxMargin += 0.1f;
357
            }
358
        }
359
360
        // This is better than adding to the reach, as 0.03 can cause a player to miss their target
361
        // Adds some more than 0.03 uncertainty in some cases, but a good trade off for simplicity
362
        //
363
        // Just give the uncertainty on 1.9+ clients as we have no way of knowing whether they had 0.03 movement
364
        // However, on 1.21.2+ we do know if they had 0.03 movement
365
        if (giveMovementThreshold || player.canSkipTicks()) {
366
            hitboxMargin += player.getMovementThreshold();
367
        }
368
369
        targetBox.expand(hitboxMargin);
370
371
        return maxReach;
372
    }
373
374
    @Override
375
    public void onReload(@NotNull ConfigManager config) {
376
        this.cancelImpossibleHits = config.getBooleanElse("Reach.block-impossible-hits", true);
377
        this.threshold = config.getDoubleElse("Reach.threshold", 0.0005);
378
    }
379
380
    private enum ResultType {
381
        REACH, HITBOX, NONE
382
    }
383
384
    private record CheckResult(ResultType type, double minDistance, double extraMovement, boolean hasExtraMovement) {
385
        public boolean isFlag() {
386
            return type != ResultType.NONE;
387
        }
388
389
        public String verbose() {
390
            if (type != ResultType.REACH) {
391
                return "";
392
            }
393
394
            String verbose = String.format("%.5f", minDistance) + " blocks";
395
            if (hasExtraMovement) {
396
                verbose += String.format(", extraMovement=%.5f", extraMovement);
397
            }
398
            return verbose;
399
        }
400
    }
401
402
    private record InteractionData(double x, double y, double z, boolean hasAttackRange,
403
                                   float maxReach, float hitboxMargin, Vector3dm attackRangeMovement) {}
404
}

How it counteracts this module

Grim's Reach is a two-phase check. On the ATTACK or INTERACT_ENTITY packet it queues the player's position with the entity id (onInteract), and on the next look/movement update (tickBetterReachCheckWithAngle) it runs the precise pass: for each possible look direction (current yaw/pitch, lastYaw/pitch for 1.8+ clients because 1.8 sends the attack a tick before the yaw, plus the 1.9 skipped-tick case) and each possible eye height, it casts a ray from the player's position and intersects the packet-entity's collision box; the minimum intercept distance is compared to the reach limit, which for pre-1.9 clients includes the 0.1 hitbox margin plus the movement threshold. A miss with no intersection returns the HITBOX result (routed to the Hitboxes check), and a distance over the limit returns REACH; cancelBuffer then aggressively cancels the next four attacks. KillAura's range setting goes to 6, so every attack beyond the vanilla 3.0-3.1 limit flags the REACH branch the instant the tick-end pass runs. The Multiple mode is hit twice: targets beyond range are removed client-side but the attack packet for each survivor is still measured, and any edge attack whose ray barely clips the box is measured against the limit. The Legit/Normal smoothing walk cannot help because Grim tests the actual look vectors against the server-tracked hitbox, and the module's C09 slot-swap block tricks do not alter the measured distance. On 1.8 servers the USE_1_8_HITBOX_MARGIN flag also mirrors the client-side 0.1 box expansion the module's own distance math relies on, so the client and Grim agree on the geometry and only the true distance decides.

anticheat fight.Reach (survival distance with precision inset)

Reach.java372 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.fight;
16
17
18
import org.bukkit.GameMode;
19
import org.bukkit.Location;
20
import org.bukkit.entity.EnderDragon;
21
import org.bukkit.entity.Entity;
22
import org.bukkit.entity.Giant;
23
import org.bukkit.entity.LivingEntity;
24
import org.bukkit.entity.Player;
25
import org.bukkit.util.Vector;
26
27
import fr.neatmonster.nocheatplus.actions.ParameterName;
28
import fr.neatmonster.nocheatplus.checks.Check;
29
import fr.neatmonster.nocheatplus.checks.CheckType;
30
import fr.neatmonster.nocheatplus.checks.ViolationData;
31
import fr.neatmonster.nocheatplus.checks.combined.Improbable;
32
import fr.neatmonster.nocheatplus.checks.moving.location.tracking.LocationTrace.ITraceEntry;
33
import fr.neatmonster.nocheatplus.permissions.Permissions;
34
import fr.neatmonster.nocheatplus.players.IPlayerData;
35
import fr.neatmonster.nocheatplus.utilities.StringUtil;
36
import fr.neatmonster.nocheatplus.utilities.TickTask;
37
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
38
39
/**
40
 * The Reach check will find out if a player interacts with something that's too far away.
41
 */
42
public class Reach extends Check {
43
44
    /** The maximum distance allowed to interact with an entity in creative mode. */
45
    public static final double CREATIVE_DISTANCE = 6D;
46
47
48
    /** Additum for distance, based on entity. */
49
    private static double getDistMod(final Entity damaged) {
50
        // Handle the EnderDragon differently.
51
        if (damaged instanceof EnderDragon)
52
            return 6.5D;
53
        else if (damaged instanceof Giant){
54
            return 1.5D;
55
        }
56
        else return 0;
57
    }
58
59
60
    /**
61
     * Instantiates a new reach check.
62
     */
63
    public Reach() {
64
        super(CheckType.FIGHT_REACH);
65
    }
66
67
68
    /**
69
     * "Classic" check.
70
     * 
71
     * @param player
72
     *            the player
73
     * @param damaged
74
     *            the damaged
75
     * @return true, if successful
76
     */
77
    public boolean check(final Player player, final Location pLoc, 
78
                         final Entity damaged, final boolean damagedIsFake, final Location dRef, 
79
                         final FightData data, final FightConfig cc, final IPlayerData pData) {
80
81
        boolean cancel = false;
82
        // The maximum distance allowed to interact with an entity in survival mode.
83
        final double SURVIVAL_DISTANCE = cc.reachSurvivalDistance; 
84
        // Amount which can be reduced by reach adaption.
85
        final double DYNAMIC_RANGE = cc.reachReduceDistance; 
86
        // Adaption amount for dynamic range.
87
        final double DYNAMIC_STEP = cc.reachReduceStep / SURVIVAL_DISTANCE; 
88
        final double distanceLimit = player.getGameMode() == GameMode.CREATIVE ? CREATIVE_DISTANCE : SURVIVAL_DISTANCE + getDistMod(damaged);
89
        final double distanceMin = (distanceLimit - DYNAMIC_RANGE) / distanceLimit;
90
        final double height = damagedIsFake ? (damaged instanceof LivingEntity ? ((LivingEntity) damaged).getEyeHeight() : 1.75) : mcAccess.getHandle().getHeight(damaged);
91
        final double width = damagedIsFake ? 0.6 : mcAccess.getHandle().getWidth(damaged);
92
        double centertoedge = 0.0;
93
        
94
        if (cc.reachPrecision) {
95
            centertoedge = getinset(pLoc, dRef, width / 2, 0.0);
96
        }
97
98
        // Refine y position.
99
        final double pY = pLoc.getY() + player.getEyeHeight();
100
        final double dY = dRef.getY();
101
        if (pY <= dY) {
102
            // Keep the foot level y.
103
        } 
104
        // Highest ref y
105
        else if (pY >= dY + height) {
106
             dRef.setY(dY + height);
107
        }
108
        // Level with damaged.
109
        else dRef.setY(pY);
110
111
        final Vector pRel = dRef.toVector().subtract(pLoc.toVector().setY(pY)); // TODO: Run calculations on numbers only :p.
112
        // Distance is calculated from eye location to center of targeted. If the player is further away from their target
113
        // than allowed, the difference will be assigned to "distance".
114
        final double lenpRel = pRel.length() - centertoedge;
115
        double violation = lenpRel - distanceLimit;
116
        final double reachMod = data.reachMod; 
117
118
119
        if (violation > 0) {
120
            if (TickTask.getLag(1000, true) < 1.5f){ // Do not increase the vl in case of server lag (1.5 is a magic value)
121
                data.reachVL += violation;
122
                final ViolationData vd = new ViolationData(this, player, data.reachVL, violation, cc.reachActions);
123
                vd.setParameter(ParameterName.REACH_DISTANCE, StringUtil.fdec3.format(lenpRel));
124
                // Execute whatever actions are associated with this check and the violation level and find out if we should
125
                // cancel the event.
126
                cancel = executeActions(vd).willCancel();
127
            }
128
129
            if (Improbable.check(player, (float) violation / 2f, System.currentTimeMillis(), "fight.reach", pData)){
130
                cancel = true;
131
            }
132
133
            if (cancel && cc.reachPenalty > 0){
134
                // Apply an attack penalty time.
135
                data.attackPenalty.applyPenalty(cc.reachPenalty);
136
            }
137
        }
138
        else if (lenpRel - distanceLimit * reachMod > 0){
139
            // Silent cancel.
140
            if (cc.reachPenalty > 0) {
141
                data.attackPenalty.applyPenalty(cc.reachPenalty / 2);
142
            }
143
            cancel = true;
144
            Improbable.feed(player, (float) (lenpRel - distanceLimit * reachMod) / 4f, System.currentTimeMillis());
145
        }
146
        else data.reachVL *= 0.8D; // Player passed the check, reward them.
147
            
148
149
        if (!cc.reachReduce){
150
            data.reachMod = 1d;
151
        }
152
        else if (lenpRel > distanceLimit - DYNAMIC_RANGE){
153
            data.reachMod = Math.max(distanceMin, data.reachMod - DYNAMIC_STEP);
154
        }
155
        else data.reachMod = Math.min(1.0, data.reachMod + DYNAMIC_STEP);
156
157
        if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)){
158
            player.sendMessage("NC+: Attack/reach " + damaged.getType()+ " height="+ StringUtil.fdec3.format(height) + " dist=" + StringUtil.fdec3.format(lenpRel) +" @" + StringUtil.fdec3.format(reachMod));
159
        }
160
161
        return cancel;
162
    }
163
164
    /**
165
     * Data context for iterating over ITraceEntry instances.
166
     * @param player
167
     * @param pLoc
168
     * @param damaged
169
     * @param damagedLoc
170
     * @param data
171
     * @param cc
172
     * @return
173
     */
174
    public ReachContext getContext(final Player player, final Location pLoc, 
175
                                   final Entity damaged, final Location damagedLoc, 
176
                                   final FightData data, final FightConfig cc) {
177
178
        final ReachContext context = new ReachContext();
179
        context.distanceLimit = player.getGameMode() == GameMode.CREATIVE ? CREATIVE_DISTANCE : cc.reachSurvivalDistance + getDistMod(damaged);
180
        context.distanceMin = (context.distanceLimit - cc.reachReduceDistance) / context.distanceLimit;
181
        //context.eyeHeight = player.getEyeHeight();
182
        context.pY = pLoc.getY() + player.getEyeHeight();
183
        return context;
184
    }
185
186
    /**
187
     * Check if the player fails the reach check, no change of FightData.
188
     * @param player
189
     * @param pLoc
190
     * @param damaged
191
     * @param dRef
192
     * @param context
193
     * @param data
194
     * @param cc
195
     * @return
196
     */
197
    public boolean loopCheck(final Player player, final Location pLoc, final Entity damaged, 
198
                             final ITraceEntry dRef, final ReachContext context, 
199
                             final FightData data, final FightConfig cc) {
200
201
        boolean cancel = false;
202
203
        // Refine y position.
204
        final double dY = dRef.getY();
205
        double y = dRef.getY();
206
207
        if (context.pY <= dY) {
208
            // Keep the foot level y.
209
        }
210
        else if (context.pY >= dY + dRef.getBoxMarginVertical()) {
211
            y = dY + dRef.getBoxMarginVertical(); // Highest ref y.
212
        }
213
        else {
214
            y = context.pY; // Level with damaged.
215
        }
216
217
        double centertoedge = 0.0;
218
        if (cc.reachPrecision) centertoedge = getinset(pLoc, new Location(null, dRef.getX(), dRef.getY(), dRef.getZ()), dRef.getBoxMarginHorizontal(), y - context.pY);
219
        
220
        // Distance is calculated from eye location to center of targeted. If the player is further away from their target
221
        // than allowed, the difference will be assigned to "distance".
222
        // TODO: Run check on squared distances (quite easy to change to stored boundary-sq values).
223
        final double lenpRel = TrigUtil.distance(dRef.getX(), y, dRef.getZ(), pLoc.getX(), context.pY, pLoc.getZ()) - centertoedge;
224
        double violation = lenpRel - context.distanceLimit;
225
226
        if (violation > 0 || lenpRel - context.distanceLimit * data.reachMod > 0){
227
            // TODO: The silent cancel parts should be sen as "no violation" ?
228
            // Set minimum violation in context
229
            context.minViolation = Math.min(context.minViolation, lenpRel);
230
            cancel = true;
231
        }
232
        context.minResult = Math.min(context.minResult, lenpRel);
233
234
        return cancel;
235
236
    }
237
238
    /**
239
     * Apply changes to FightData according to check results (context), trigger violations.
240
     * @param player
241
     * @param pLoc
242
     * @param damaged
243
     * @param context
244
     * @param forceViolation
245
     * @param data
246
     * @param cc
247
     * @return
248
     */
249
    public boolean loopFinish(final Player player, final Location pLoc, final Entity damaged, 
250
                              final ReachContext context, final ITraceEntry traceEntry, final boolean forceViolation, 
251
                              final FightData data, final FightConfig cc, final IPlayerData pData) {
252
253
        final double lenpRel = forceViolation && context.minViolation != Double.MAX_VALUE ? context.minViolation : context.minResult;
254
255
        if (lenpRel == Double.MAX_VALUE) {
256
            return false;
257
        }
258
259
        double violation = lenpRel - context.distanceLimit;
260
        boolean cancel = false;
261
262
        if (violation > 0) {    
263
            if (TickTask.getLag(1000, true) < 1.5f){
264
                data.reachVL += violation;
265
                final ViolationData vd = new ViolationData(this, player, data.reachVL, violation, cc.reachActions);
266
                vd.setParameter(ParameterName.REACH_DISTANCE, StringUtil.fdec3.format(lenpRel));
267
                // Execute whatever actions are associated with this check and the violation level and find out if we should
268
                // cancel the event.
269
                cancel = executeActions(vd).willCancel();
270
            }
271
            
272
            //if (Improbable.check(player, (float) violation / 2f, System.currentTimeMillis(), 
273
            //        "fight.reach", pData)){
274
            //    cancel = true;
275
            //}
276
            // TODO: New improbable weight calculations so that weight is not inverse to config weight
277
            if (cc.reachImprobableWeight > 0.0f) {
278
                if (!cc.reachImprobableFeedOnly && Improbable.check(player, (float) violation / cc.reachImprobableWeight, System.currentTimeMillis(), "fight.reach", pData)) {
279
                    cancel = true;
280
                }
281
            }
282
283
            if (cancel && cc.reachPenalty > 0){
284
                // Apply an attack penalty time.
285
                data.attackPenalty.applyPenalty(cc.reachPenalty);
286
            }
287
        }
288
        else if (lenpRel - context.distanceLimit * data.reachMod > 0){
289
            // Silent cancel.
290
            if (cc.reachPenalty > 0) {
291
                data.attackPenalty.applyPenalty(cc.reachPenalty / 2);
292
            }
293
294
            cancel = true;
295
296
            if (cc.reachImprobableWeight > 0.0f) {
297
                Improbable.feed(player, (float) (lenpRel - context.distanceLimit * data.reachMod) / cc.reachImprobableWeight, System.currentTimeMillis());
298
            }
299
            // Improbable.feed(player, (float) (lenpRel - context.distanceLimit * data.reachMod) / 4f, System.currentTimeMillis());
300
        }
301
        else {
302
            // Player passed the check, reward them.
303
            data.reachVL *= 0.8D;
304
305
        }
306
307
        // Adaption amount for dynamic range.
308
        final double DYNAMIC_STEP = cc.reachReduceStep / cc.reachSurvivalDistance;
309
310
        if (!cc.reachReduce){
311
            data.reachMod = 1d;
312
        }
313
        else if (lenpRel > context.distanceLimit - cc.reachReduceDistance){
314
            data.reachMod = Math.max(context.distanceMin, data.reachMod - DYNAMIC_STEP);
315
        }
316
        else {
317
            data.reachMod = Math.min(1.0, data.reachMod + DYNAMIC_STEP);
318
        }
319
320
        if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)){
321
            // TODO: Height: remember successful ITraceEntry
322
            player.sendMessage("NC+: Attack/reach " + damaged.getType()+ (traceEntry == null ? "" : (" height=" + traceEntry.getBoxMarginVertical())) + " dist=" + StringUtil.fdec3.format(lenpRel) +" @" + StringUtil.fdec3.format(data.reachMod));
323
        }
324
325
        return cancel;
326
    }
327
328
329
    private boolean isSameXZ(final Location loc1, final Location loc2) {
330
        return loc1.getX() == loc2.getX() && loc1.getZ() == loc2.getZ();
331
    }
332
333
334
    /**
335
     *
336
     * @param pLoc
337
     *            the player location
338
     * @param dRef
339
     *            the target location
340
     * @param damagedBoxMarginHorizontal
341
     *            the target Width / 2
342
     * @param diffY the Y different
343
     * @return the double represent for the distance from target location to the edge of target hitbox
344
     */
345
    private double getinset(final Location pLoc, final Location dRef, final double damagedBoxMarginHorizontal, final double diffY) {
346
347
        if (!isSameXZ(pLoc, dRef)) {
348
            final Location dRefc = dRef.clone();
349
            final Vector vec1 = new Vector(pLoc.getX() - dRef.getX(), diffY , pLoc.getZ() - dRef.getZ());
350
            if (vec1.length() < damagedBoxMarginHorizontal * Math.sqrt(2)) return 0.0;
351
            if (vec1.getZ() > 0.0) {
352
                dRefc.setZ(dRefc.getZ() + damagedBoxMarginHorizontal);
353
            } 
354
            else if (vec1.getZ() < 0.0) {
355
                dRefc.setZ(dRefc.getZ() - damagedBoxMarginHorizontal);
356
            } 
357
            else if (vec1.getX() > 0.0) {
358
                dRefc.setX(dRefc.getX() + damagedBoxMarginHorizontal);
359
            } 
360
            else dRefc.setX(dRefc.getX() - damagedBoxMarginHorizontal);
361
362
            final Vector vec2 = new Vector(dRefc.getX() - dRef.getX(), 0.0 , dRefc.getZ() - dRef.getZ());
363
            double angle = TrigUtil.angle(vec1, vec2);
364
            // Require < 45deg, if not 90deg-angel
365
            if (angle > Math.PI / 4) angle = Math.PI / 2 - angle;
366
            if (angle >= 0.0 && angle <= Math.PI / 4) { // TODO: Dose this one necessary?
367
                return damagedBoxMarginHorizontal / Math.cos(angle);
368
            }
369
        }
370
        return 0.0;
371
    }
372
}

How it counteracts this module

NCP's fight.Reach measures the attack from the server-tracked player position to the victim and compares against reachSurvivalDistance (default 3.0). The check refines the victim y to the eye-height band, subtracts the getinset precision correction (half the victim width projected along the attack direction) when reachPrecision is on, and adds a per-entity size modifier (6.5 for dragons, 1.5 for giants). A positive violation accumulates into reachVL and executes the configured actions; the dynamic reachMod adaption then tightens the limit for repeat offenders: every hit within the reduce band steps reachMod down toward distanceMin, so a KillAura that consistently attacks at 3.1-3.4 gets silently cancelled even though the nominal limit is 3.0 plus inset. KillAura's range value of 3-6 maps directly onto this: the default 3.0 setting is near the limit and the higher settings exceed it outright. The module's client-side distance math subtracts nothing for the victim girth while NCP's inset grants only the half-width, so the server-side measurement is stricter than the client's own gate, and the 6.2.4 C04-less design (unlike the 5.99 Extended Range mode) means the server position cannot be shortened to dodge the measurement.

anticheat fight.Angle (multi-target stream analysis)

Angle.java255 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.fight;
16
17
import java.util.Iterator;
18
import java.util.LinkedList;
19
import java.util.List;
20
import java.util.UUID;
21
22
import org.bukkit.ChatColor;
23
import org.bukkit.Location;
24
import org.bukkit.entity.Entity;
25
import org.bukkit.entity.Player;
26
27
import fr.neatmonster.nocheatplus.actions.ParameterName;
28
import fr.neatmonster.nocheatplus.checks.Check;
29
import fr.neatmonster.nocheatplus.checks.CheckType;
30
import fr.neatmonster.nocheatplus.checks.ViolationData;
31
import fr.neatmonster.nocheatplus.permissions.Permissions;
32
import fr.neatmonster.nocheatplus.players.IPlayerData;
33
import fr.neatmonster.nocheatplus.utilities.StringUtil;
34
import fr.neatmonster.nocheatplus.utilities.TickTask;
35
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
36
37
/**
38
 * A check used to verify if the player isn't using a forcefield in order to attack multiple entities at the same time.
39
 * 
40
 * Thanks @asofold for the original idea!
41
 */
42
public class Angle extends Check {
43
  
44
45
  private final List<String> tags = new LinkedList<String>();
46
47
48
    public static class AttackLocation {
49
        public final double x, y, z;
50
        /** Yaw of the attacker. */
51
        public final float yaw;
52
        public long time;
53
        public final UUID damagedId;
54
        /** Squared distance to the last location (0 if none given). */
55
        public final double distSqLast;
56
        /** Difference in yaw to the last location (0 if none given). */
57
        public final double yawDiffLast;
58
        /** Time difference to the last location (0 if none given). */
59
        public final long timeDiff;
60
        /** If the id differs from the last damaged entity (true if no lastLoc is given). */
61
        public final boolean idDiffLast;
62
        public AttackLocation(final Location loc, final UUID damagedId, final long time, final AttackLocation lastLoc) {
63
            x = loc.getX();
64
            y = loc.getY();
65
            z = loc.getZ();
66
            yaw = loc.getYaw();
67
            this.time = time;
68
            this.damagedId = damagedId;
69
70
            if (lastLoc != null) {
71
                distSqLast = TrigUtil.distanceSquared(x, y, z, lastLoc.x, lastLoc.y, lastLoc.z);
72
                yawDiffLast = TrigUtil.yawDiff(yaw, lastLoc.yaw);
73
                timeDiff = Math.max(0L, time - lastLoc.time);
74
                idDiffLast = !damagedId.equals(lastLoc.damagedId);
75
            } 
76
            else {
77
                distSqLast = 0.0;
78
                yawDiffLast = 0f;
79
                timeDiff = 0L;
80
                idDiffLast = true;
81
            }
82
        }
83
    }
84
    
85
    /** Used to also monitor lag-time */
86
    public static long maxTimeDiff = 1000L;
87
88
89
    /**
90
     * Instantiates a new angle check.
91
     */
92
    public Angle() {
93
        super(CheckType.FIGHT_ANGLE);
94
    }
95
96
97
    /**
98
     * The Angle check.
99
     * @param player
100
     * @param loc Location of the player.
101
     * @param worldChanged
102
     * @param data
103
     * @param cc
104
     * @return
105
     */
106
    public boolean check(final Player player, final Location loc, 
107
                         final Entity damagedEntity, final boolean worldChanged, 
108
                         final FightData data, final FightConfig cc, final IPlayerData pData) {
109
110
        if (worldChanged) {
111
            data.angleHits.clear();
112
        }
113
114
        boolean cancel = false;
115
        tags.clear();
116
117
        // Quick check for expiration of all entries.
118
        final long time = System.currentTimeMillis();
119
        AttackLocation lastLoc = data.angleHits.isEmpty() ? null : data.angleHits.getLast();
120
        if (lastLoc != null && time - lastLoc.time > maxTimeDiff) {
121
            data.angleHits.clear();
122
            lastLoc = null;
123
        }
124
125
        // Add the new location.
126
        data.angleHits.add(new AttackLocation(loc, damagedEntity.getUniqueId(), System.currentTimeMillis(), lastLoc));
127
128
        // Calculate the sums of differences.
129
        double deltaMove = 0D;
130
        long deltaTime = 0L;
131
        float deltaYaw = 0f;
132
        int deltaSwitchTarget = 0;
133
        final Iterator<AttackLocation> it = data.angleHits.iterator();
134
        while (it.hasNext()) {
135
            final AttackLocation refLoc = it.next();
136
            if (time - refLoc.time > maxTimeDiff) {
137
                it.remove();
138
                continue;
139
            }
140
            deltaMove += refLoc.distSqLast;
141
            final double yawDiff = Math.abs(refLoc.yawDiffLast);
142
            deltaYaw += yawDiff;
143
            deltaTime += refLoc.timeDiff;
144
            if (refLoc.idDiffLast && yawDiff > 30.0) {
145
                // TODO: Configurable sensitivity ? Scale with yawDiff?
146
                deltaSwitchTarget += 1;
147
            }
148
        }
149
150
        // Check if there is enough data present.
151
        if (data.angleHits.size() < 2) {
152
            return false;
153
        }
154
155
        final double n = (double) (data.angleHits.size() - 1);
156
157
        // Let's calculate the average move.
158
        double averageMove = deltaMove / n;
159
        // Adjust to server-sided lag
160
        averageMove *= TickTask.getLag(maxTimeDiff, true);
161
162
        // And the average time elapsed.
163
        double averageTime = (double) deltaTime / n;
164
        // Adjust to server-sided lag
165
        averageTime *= TickTask.getLag(maxTimeDiff, true);
166
167
        // And the average yaw delta.
168
        double averageYaw = (double) deltaYaw / n;
169
        // Adjust to server-sided lag
170
        averageYaw /= TickTask.getLag(maxTimeDiff, true);
171
172
        // Average target switching.
173
        double averageSwitching = (double) deltaSwitchTarget / n;
174
        // Adjust to server-sided lag
175
        averageSwitching /= TickTask.getLag(maxTimeDiff, true);
176
177
        // Declare the variables.
178
        double violation = 0.0;
179
        double violationMove = 0.0;
180
        double violationTime = 0.0;
181
        double violationYaw = 0.0;
182
        double violationSwitchSpeed = 0.0;
183
184
        // If the average move is between 0 and 0.2 block(s), add it to the violation.
185
        if (averageMove >= 0.0 && averageMove < 0.2D) {
186
            violationMove += 20.0 * (0.2 - averageMove) / 0.2;
187
            tags.add("avgmove");
188
            if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)) {
189
                player.sendMessage(ChatColor.RED + "NC+ Debug: " + ChatColor.RESET + "avgMove: " + averageMove + " avgMove VL: " + violationMove + "/" + cc.angleMove);
190
            }
191
        }
192
193
        // If the average time elapsed is between 0 and 150 millisecond(s), add it to the violation.
194
        if (averageTime >= 0.0 && averageTime < 150.0) {
195
            violationTime += 30.0 * (150.0 - averageTime) / 150.0;
196
            tags.add("avgtime");
197
            if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)) {
198
                player.sendMessage(ChatColor.RED + "NC+ Debug: " + ChatColor.RESET + "avgTime: " + averageTime + " avgTime VL: " + violationTime + "/" + cc.angleTime);
199
            }
200
        }
201
202
        // If the average difference of yaw is superior to 50 degrees, add it to the violation.
203
        if (averageYaw > 50.0) {
204
            violationYaw += 30.0 * averageYaw / 180.0;
205
            tags.add("avgyaw");
206
            if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)) {
207
                player.sendMessage(ChatColor.RED + "NC+ Debug: " + ChatColor.RESET + "avgYaw: " + averageYaw + " avgYaw VL: " + violationYaw + "/" + cc.angleYaw);
208
            }
209
        }
210
        
211
        // Check for too quick target switch speed
212
        if (averageSwitching > 0.0) {
213
            violationSwitchSpeed += 20.0 * averageSwitching;
214
            tags.add("switchspeed");
215
            if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)) {
216
                player.sendMessage(ChatColor.RED + "NC+ Debug: " + ChatColor.RESET + "avgSwitch: " + averageSwitching + " avgSwitch VL: " + violationSwitchSpeed + "/" + cc.angleSwitch);
217
            }
218
        }
219
220
221
        if (violationMove > cc.angleMove) {
222
            violation = violationMove;
223
            data.angleVL += violation;
224
            final ViolationData vd = new ViolationData(this, player, data.angleVL, violation, cc.angleActions);
225
            if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
226
            cancel = executeActions(vd).willCancel();
227
        }
228
        else if (violationTime > cc.angleTime) {
229
            violation = violationTime;
230
            data.angleVL += violation;
231
            final ViolationData vd = new ViolationData(this, player, data.angleVL, violation, cc.angleActions);
232
            if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
233
            cancel = executeActions(vd).willCancel();
234
        }
235
        else if (violationYaw > cc.angleYaw) {
236
            violation = violationYaw;
237
            data.angleVL += violation;
238
            final ViolationData vd = new ViolationData(this, player, data.angleVL, violation, cc.angleActions);
239
            if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
240
            cancel = executeActions(vd).willCancel();
241
        } 
242
        else if (violationSwitchSpeed > cc.angleSwitch) {
243
            violation = violationSwitchSpeed;
244
            data.angleVL += violation;
245
            final ViolationData vd = new ViolationData(this, player, data.angleVL, violation, cc.angleActions);
246
            if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
247
            cancel = executeActions(vd).willCancel();
248
        } 
249
        else {
250
            // Reward the player by lowering their violation level.
251
            data.angleVL *= 0.98D;  
252
        }
253
        return cancel;
254
    }
255
}

How it counteracts this module

NCP's Angle check scores the attack stream for forcefield behavior. Every C02 appends an AttackLocation with the player position, yaw, victim id and timestamps, kept for maxTimeDiff (1000ms), and the window yields four averages: avgmove (distance moved between attacks, flagged under 0.2 blocks), avgtime (elapsed time between attacks, flagged under 150ms), avgyaw (total yaw change, flagged over 50 degrees), and switchspeed (victim id changes where the yaw diff exceeds 30 degrees). KillAura's Multiple mode attacks every in-range target from the same position in the same tick, which produces avgmove near zero, avgtime near zero, and a switchspeed increment per id change with the yaw rotated across the whole target ring. The Single mode at the default 10-15 CPS bounds keeps avgtime around 66-100ms per hit, under the 150ms threshold. The 1.9+ click-delay mode lowers the rate for swords (1/speed*20-1 ticks = about 11.5 ticks between hits, near the 150ms boundary) but the Snap and Autistic AntiCheat rotation modes blow past the 50-degree average-yaw ceiling: Snap snaps the full angle to the target each tick and Autistic AntiCheat rotates by rotationSpeed*10 continuously. Each signal accumulates its own partial violation and the module is cancelled once angleVL crosses the action thresholds.

anticheat FightHitbox (ray trace to lag-compensated hitbox)

FightHitbox.java232 lines · Java
1
/*
2
 * This file is part of Hawk Anticheat.
3
 * Copyright (C) 2018 Hawk Development Team
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
package me.islandscout.hawk.check.combat;
20
21
import me.islandscout.hawk.HawkPlayer;
22
import me.islandscout.hawk.check.Cancelless;
23
import me.islandscout.hawk.check.CustomCheck;
24
import me.islandscout.hawk.event.Event;
25
import me.islandscout.hawk.event.InteractEntityEvent;
26
import me.islandscout.hawk.event.MoveEvent;
27
import me.islandscout.hawk.util.*;
28
import me.islandscout.hawk.wrap.block.WrappedBlock;
29
import me.islandscout.hawk.wrap.entity.WrappedEntity;
30
import org.bukkit.GameMode;
31
import org.bukkit.Location;
32
import org.bukkit.Material;
33
import org.bukkit.block.Block;
34
import org.bukkit.entity.Entity;
35
import org.bukkit.entity.Player;
36
import org.bukkit.util.BlockIterator;
37
import org.bukkit.util.Vector;
38
39
import java.util.HashMap;
40
import java.util.Map;
41
import java.util.UUID;
42
43
/**
44
 * The hit detection in Minecraft is mostly determined by the client,
45
 * thus servers are left to trust the client. (There are a few exceptions
46
 * for the unmodified Notchian server such as preventing hits exceeding 6
47
 * blocks from the target entity). This poses a problem for players and
48
 * server owners since players can modify the client to manipulate hit
49
 * detection and allow for cheating when in combat with other players.
50
 *
51
 * Hawk’s hitbox checking aims to detect cheating during player vs.
52
 * player combat by validating hits on the server. When the server
53
 * receives an interaction packet from the client, Hawk gets the client’s
54
 * last known position and next direction, and uses it to perform a ray
55
 * trace test on the victim’s hitbox. Before the ray-trace test begins,
56
 * though, Hawk must factor in latency by rewinding the victim’s hitbox
57
 * to an appropriate time based on the client’s ping latency. To
58
 * accomplish this, Hawk keeps a history of players’ positions and
59
 * timestamps in a table and it retrieves a position that best
60
 * approximates where it appeared to the client when the client attacked
61
 * it. Hawk then performs the ray-trace test to determine whether the
62
 * client landed the hit or not. Although the system may produce false
63
 * positives with clients on unstable connections, it is a fair tradeoff
64
 * between user experience and cheat prevention.
65
 *
66
 * There are other sources of error which will probably not be accounted
67
 * for in Hawk anytime soon. Other sources of error include:
68
 *   - The client receives entity relative moves in 1/32 block precision.
69
 *   - The client holds off one tick to smoothly animate other players
70
 *     on the screen in the case of slight network jitter. It will
71
 *     linearly interpolate from the last position to the latest
72
 *     position up to 3 ticks if it doesn't receive a relative move
73
 *     packet to update the player's position.
74
 *   - The client will predict the motion of some entities, such as
75
 *     arrows. If there is latency and something unexpected happens
76
 *     to the entity, the client may desynchronize from the server.
77
 *
78
 * In most cases, the client uses the current frame's yaw and pitch to
79
 * compute the direction vector for the attack hit-scan. Fortunately,
80
 * ticking and rendering is done in the same thread. Unfortunately, in
81
 * the tick stack, attacking is done before sending yaw/pitch updates
82
 * to the server, which means that we must wait until the next flying
83
 * packet to get the direction of the hit-scan.
84
 *
85
 * For realtime protection, it's best to use the EntityInteractDirection
86
 * check. It actively enforces directions, but it extrapolates the
87
 * yaw/pitch because of how the client hit-scanning works.
88
 */
89
public class FightHitbox extends CustomCheck implements Cancelless {
90
91
    private final double MAX_REACH;
92
    private final int PING_LIMIT;
93
    private final boolean CHECK_OTHER_ENTITIES;
94
    private final boolean LAG_COMPENSATION;
95
    private final boolean DEBUG_HITBOX;
96
    private final boolean DEBUG_RAY;
97
    private final boolean CHECK_OCCLUSION;
98
    private final boolean CHECK_BOX_INTERSECTION;
99
    private final double BOX_EPSILON = 0.005;
100
101
    private Map<UUID, InteractEntityEvent> lastInteractionMap;
102
103
    public FightHitbox() {
104
        super("fighthitbox", false, 5, 10000, 0.95, 5000, "%player% failed combat hitbox. %type% VL: %vl%", null);
105
        CHECK_BOX_INTERSECTION = (boolean) customSetting("checkBoxIntersection", "", true);
106
        CHECK_OCCLUSION = (boolean) customSetting("checkOccluding", "", false);
107
        MAX_REACH = (double) customSetting("maxReach", "", 3.1);
108
        CHECK_OTHER_ENTITIES = (boolean) customSetting("checkOtherEntities", "", false);
109
        LAG_COMPENSATION = (boolean) customSetting("lagCompensation", "", true);
110
        PING_LIMIT = (int) customSetting("pingLimit", "", -1);
111
        DEBUG_HITBOX = (boolean) customSetting("hitbox", "debug", false);
112
        DEBUG_RAY = (boolean) customSetting("ray", "debug", false);
113
        lastInteractionMap = new HashMap<>();
114
    }
115
116
    @Override
117
    protected void check(Event event) {
118
        if(event instanceof InteractEntityEvent)
119
            processHit((InteractEntityEvent)event);
120
        else if(event instanceof MoveEvent) {
121
            InteractEntityEvent interactEntityEvent = lastInteractionMap.get(event.getHawkPlayer().getUuid());
122
            if(interactEntityEvent != null) {
123
                MoveEvent move = (MoveEvent) event;
124
125
                float yaw;
126
                float pitch;
127
                //In 1.8, the yaw of the cursor is behind by one tick.
128
                if(event.getHawkPlayer().getClientVersion() == 8) {
129
                    yaw = event.getHawkPlayer().getYaw();
130
                } else {
131
                    yaw = move.getTo().getYaw();
132
                }
133
                pitch = move.getTo().getPitch();
134
135
                processDirection(interactEntityEvent, yaw, pitch);
136
            }
137
            lastInteractionMap.put(event.getHawkPlayer().getUuid(), null);
138
        }
139
    }
140
141
    private void processHit(InteractEntityEvent e) {
142
        lastInteractionMap.put(e.getHawkPlayer().getUuid(), e);
143
    }
144
145
    private void processDirection(InteractEntityEvent e, float yaw, float pitch) {
146
        Entity entity = e.getEntity();
147
        if (!(entity instanceof Player) && !CHECK_OTHER_ENTITIES)
148
            return;
149
        Player attacker = e.getPlayer();
150
        int ping = ServerUtils.getPing(attacker);
151
        if (ping > PING_LIMIT && PING_LIMIT != -1)
152
            return;
153
154
        HawkPlayer att = e.getHawkPlayer();
155
        Location attackerEyeLocation = att.getPosition().clone().add(new Vector(0, 1.62, 0)).toLocation(att.getWorld());
156
        Vector attackerDirection = MathPlus.getDirection(yaw, pitch);
157
158
        double maxReach = MAX_REACH;
159
        if (attacker.getGameMode() == GameMode.CREATIVE)
160
            maxReach += 1.9;
161
162
        Vector victimLocation;
163
        if (LAG_COMPENSATION)
164
            //No need to add 50ms; the move and attack are already chronologically so close together
165
            victimLocation = hawk.getLagCompensator().getHistoryLocation(ping, e.getEntity()).toVector();
166
        else
167
            victimLocation = e.getEntity().getLocation().toVector();
168
169
        Vector eyePos;
170
        if(e.getHawkPlayer().isInVehicle()) {
171
            eyePos = hawk.getLagCompensator().getHistoryLocation(ping, e.getPlayer()).toVector();
172
            eyePos.setY(eyePos.getY() + e.getPlayer().getEyeHeight());
173
        }
174
        else {
175
            eyePos = new Vector(attackerEyeLocation.getX(), attacker.isSneaking() ? attackerEyeLocation.getY() - 0.08 : attackerEyeLocation.getY(), attackerEyeLocation.getZ());
176
        }
177
        Vector direction = new Vector(attackerDirection.getX(), attackerDirection.getY(), attackerDirection.getZ());
178
        Ray attackerRay = new Ray(eyePos, direction);
179
180
        AABB victimAABB;
181
        victimAABB = WrappedEntity.getWrappedEntity(entity).getHitbox(victimLocation);
182
        victimAABB.expand(BOX_EPSILON, BOX_EPSILON, BOX_EPSILON);
183
184
        Vector intersectVec3d = victimAABB.intersectsRay(attackerRay, 0, Float.MAX_VALUE);
185
186
        if (DEBUG_HITBOX) {
187
            victimAABB.highlight(hawk, attacker.getWorld(), 0.29);
188
        }
189
190
        if (DEBUG_RAY) {
191
            attackerRay.highlight(hawk, attacker.getWorld(), maxReach, 0.1);
192
        }
193
194
        if (intersectVec3d != null) {
195
            Location intersect = new Location(attacker.getWorld(), intersectVec3d.getX(), intersectVec3d.getY(), intersectVec3d.getZ());
196
            double interDistance = intersect.distance(attackerEyeLocation);
197
            if (interDistance > maxReach) {
198
                punish(att, 1, true, e, new Placeholder("type", "Reach: " + MathPlus.round(interDistance, 2) + "m"));
199
                return;
200
            }
201
            if (CHECK_OCCLUSION && interDistance > 1D) {
202
                BlockIterator iter = new BlockIterator(attacker.getWorld(), eyePos, attackerDirection, 0, (int) interDistance + 1);
203
                while (iter.hasNext()) {
204
                    Block bukkitBlock = iter.next();
205
206
                    if (bukkitBlock.getType() == Material.AIR || bukkitBlock.isLiquid())
207
                        continue;
208
209
                    WrappedBlock b = WrappedBlock.getWrappedBlock(bukkitBlock, att.getClientVersion());
210
                    Vector intersection = b.getHitBox().intersectsRay(new Ray(attackerEyeLocation.toVector(), attackerDirection), 0, Float.MAX_VALUE);
211
                    if (intersection != null) {
212
                        if (intersection.distance(eyePos) < interDistance) {
213
                            punish(att, 1, true, e, new Placeholder("type", "Interacted through " + b.getBukkitBlock().getType()));
214
                            return;
215
                        }
216
                    }
217
                }
218
219
            }
220
        } else if (CHECK_BOX_INTERSECTION) {
221
            punish(att, 1, true, e, new Placeholder("type", "Did not hit hitbox."));
222
            return;
223
        }
224
225
        reward(att); //reward player
226
    }
227
228
    @Override
229
    public void removeData(Player p) {
230
        lastInteractionMap.remove(p.getUniqueId());
231
    }
232
}

How it counteracts this module

Hawk's FightHitbox replays each attack from the packet-observed yaw/pitch. Because 1.8 sends the C02 before the yaw update, Hawk defers the ray trace to the next MoveEvent, then builds the direction from the stored yaw/pitch, rewinds the victim to its ping-ago position via the lag compensator, expands the victim AABB by 0.005, and ray-casts from the attacker eye (with the sneaking -0.08 offset and vehicle handling). No intersection punishes 'Did not hit hitbox.'; an intersection beyond MAX_REACH (3.1 survival, 5.0 creative) punishes as reach; with checkOccluding a BlockIterator flags hits through walls. KillAura's throughWalls mode is the direct target: when throughWalls is on (and rayCast off) the module expands the target's bounding box by 0.1 and attacks on any intercept, which is precisely the geometry Hawk re-derives from the server direction; the check's own epsilon and the lag-compensated victim position do not include the module's 0.1 expansion, so wall hits either miss the box entirely or exceed the reach limit. The Multiple mode attacking several entities in one tick fails the direction requirement for all but the one the look vector happens to cross. The module's rayCast-on mode (RayCastUtil.rayCast with -0.1f expansion) survives only when the server-observed rotations genuinely cross the rewound victim box within 3.1, which is the Legit/Normal rotation mode at default range.

anticheat combat.KillAura (direction, multi, noswing, reach, speed)

KillAura.java114 lines · Java
1
package me.vrekt.arc.check.combat;
2
3
import me.vrekt.arc.Arc;
4
import me.vrekt.arc.check.Check;
5
import me.vrekt.arc.check.CheckType;
6
import me.vrekt.arc.data.combat.FightData;
7
import me.vrekt.arc.utilties.LocationHelper;
8
import org.bukkit.ChatColor;
9
import org.bukkit.entity.Entity;
10
import org.bukkit.entity.Player;
11
import org.bukkit.util.Vector;
12
13
public class KillAura extends Check {
14
15
    private double maxAngle, maxReach;
16
    private int maxSwingTime, maxAttacks, maxAttackPackets;
17
18
    public KillAura() {
19
        super(CheckType.KILLAURA);
20
21
        maxAngle = Arc.getCheckManager().getValueDouble(CheckType.KILLAURA, "max-direction-angle");
22
        maxSwingTime = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-swing-time");
23
        maxReach = Arc.getCheckManager().getValueDouble(CheckType.KILLAURA, "max-reach");
24
        maxAttacks = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-attacks");
25
        maxAttackPackets = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-attack-packets");
26
27
    }
28
29
    public boolean check(FightData data, Player player) {
30
        result.reset();
31
32
        Entity last = data.getLastAttackedEntity();
33
        Entity entity = data.getAttackedEntity();
34
35
        // Calculate angle stuff.
36
        Vector playerLocation = player.getLocation().toVector();
37
        Vector entityLocation = entity.getLocation().toVector();
38
        double angle = entityLocation.subtract(playerLocation).angle(player.getLocation().getDirection());
39
40
        if (last != null && !entity.equals(last)) {
41
            // check the angle between the two entities
42
            Vector lastLocation = last.getLocation().toVector();
43
            double angleToLast = lastLocation.subtract(playerLocation).angle(player.getLocation().getDirection());
44
            double angleDifference = Math.abs(angleToLast - angle);
45
            double distanceDifference = LocationHelper.distance(last.getLocation(), entity.getLocation());
46
            if (angleDifference > maxAngle && distanceDifference <= maxReach) {
47
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Multi)");
48
                result.set(checkViolation(player, "Angle difference greater than allowed. a=" + angleDifference + " e=" + maxAngle));
49
            }
50
        }
51
52
        // check yaw difference.
53
        if (angle > maxAngle) {
54
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Direction)");
55
            result.set(checkViolation(player, "Angle distance greater than allowed. a=" + angle + " e=" + maxAngle));
56
        }
57
58
        // check swing time.
59
        long time = System.currentTimeMillis() - data.getLastArmSwing();
60
        if (time > maxSwingTime) {
61
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(NoSwing)");
62
            result.set(checkViolation(player, "Player did not swing their arm in time."));
63
        }
64
65
        // distance to entity excluding knockback.
66
        double distance = LocationHelper.distance(player.getLocation(), entity.getLocation().subtract(entity.getVelocity()));
67
        // check for reach
68
        if (distance > maxReach) {
69
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Reach)");
70
            result.set(checkViolation(player, "Entity is out of players range. d=" + distance + " e=" + maxReach));
71
        }
72
73
        // check max attacks
74
        if (data.getLastAttackCheck() == 0) {
75
            data.setLastAttackCheck(System.currentTimeMillis());
76
        }
77
        long lastAttack = System.currentTimeMillis() - data.getLastAttackCheck();
78
        if (lastAttack >= 1000) {
79
            // check if we exceeded the max attacks in the last second.
80
            int totalAttacks = data.getTotalAttacks();
81
            if (totalAttacks > maxAttacks) {
82
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Speed)");
83
                result.set(checkViolation(player, "Attacking too fast. a=" + totalAttacks + " e=" + maxAttacks));
84
            }
85
            // reset data for next check.
86
            data.setTotalAttacks(0);
87
            data.setLastAttackCheck(System.currentTimeMillis());
88
        }
89
90
        getCheck().setCheckName("KillAura");
91
        return result.failed();
92
    }
93
94
    public boolean checkFrequency(FightData data, Player player) {
95
        if (data.getLastAttackCheck() == 0) {
96
            data.setLastAttackCheck(System.currentTimeMillis());
97
            return false;
98
        }
99
100
        long time = System.currentTimeMillis() - data.getLastAttackCheck();
101
        if (time >= 1000) {
102
            data.setLastAttackCheck(System.currentTimeMillis());
103
            int totalPackets = data.getAttackPackets();
104
            if (totalPackets > maxAttackPackets) {
105
                data.setAttackPackets(0);
106
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Speed)");
107
                return checkViolation(player, "Attacking too fast a=" + totalPackets + " e=" + maxAttackPackets);
108
            }
109
        }
110
111
        return false;
112
    }
113
114
}

How it counteracts this module

Arc's KillAura check runs from the FightListener on every C02 and combines five detectors. Direction computes the angle between the player's look direction and the vector to the attacked entity and flags over max-direction-angle; Multi compares the angles to the current and previous attacked entity and flags when the angle difference exceeds the limit while both entities are within maxReach of each other; NoSwing flags when maxSwingTime passes without an arm swing; Reach measures the distance to the entity minus its current velocity (so knockback does not false-flag) against maxReach; Speed counts attacks per second against maxAttacks and raw attack packets per second against maxAttackPackets via checkFrequency. KillAura's Multiple mode is the clean hit: attacking several entities in one tick means the single look vector can only satisfy the Direction check for one of them, and the angle difference between the attacked entities trips the Multi branch. The module's noSwing option (noSwing BooleanValue, default false) when enabled removes the C0A entirely, tripping NoSwing. The cps bounds up to 20 with the Normal click-delay mode exceed maxAttacks and maxAttackPackets per second. The Autistic AntiCheat rotation mode, which rotates yaw by rotationSpeed*10 per tick, is caught by the Direction angle since the look vector is usually far from the target when the attack fires.

← Back to Analysis Hub