AutoCrystal module

AutoCrystal: Minecraft 26.3 cheat module, full source for every implementation (3 clients: MelaHack (ThunderHack fork), Combatant, Nicotine).

3 implementationsCOMBATCombat

Full module source: 3 implementations

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

MelaHack (ThunderHack fork)COMBATsrc/main/java/thunder/hack/features/modules/combat/AutoCrystal.javaJava · 1,252 lines · 58.8 KB

Automatically places and explodes end crystals.

SettingsPageAwaitTimingSequentialRotateYawStepYawAngleTargetLogicTargetRangeExtrapolationInteractССStrictRayTraceBypass1.12PlaceDelayLowPlaceDelayPlaceRangePlaceWallRangeInhibitBreakDelayLowBreakDelayBreakRangeBreakWallRangeCrystalAgeMiningEatingAuraPistonAuraSurroundMiddleClickInventoryHPSwitchPauseSwitchDelayAssumeBestArmorMinDamageMaxSelfDamageEfficiencyEfficiencyFactorProtectFriends
AutoCrystal.javaJava · Minecraft 26.2 · 1,252 lines · 58.8 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.combat;
2
3
import com.google.common.collect.Lists;
4
import com.mojang.blaze3d.vertex.PoseStack;
5
import meteordevelopment.orbit.EventHandler;
6
import meteordevelopment.orbit.EventPriority;
7
import net.fabricmc.loader.api.FabricLoader;
8
import net.minecraft.world.InteractionHand;
9
import net.minecraft.world.effect.MobEffectInstance;
10
import net.minecraft.world.effect.MobEffects;
11
import net.minecraft.world.entity.Entity;
12
import net.minecraft.world.entity.ExperienceOrb;
13
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
14
import net.minecraft.world.entity.player.Player;
15
import net.minecraft.world.inventory.ContainerInput;
16
import net.minecraft.world.item.*;
17
import net.minecraft.world.level.ClipContext;
18
import net.minecraft.world.level.block.Block;
19
import net.minecraft.world.level.block.Blocks;
20
import net.minecraft.network.protocol.game.*;
21
import net.minecraft.tags.ItemTags;
22
import net.minecraft.util.Mth;
23
import net.minecraft.core.*;
24
import net.minecraft.world.phys.*;
25
import org.jetbrains.annotations.NotNull;
26
import org.jetbrains.annotations.Nullable;
27
import org.lwjgl.glfw.GLFW;
28
import thunder.hack.core.Managers;
29
import thunder.hack.core.manager.client.ModuleManager;
30
import thunder.hack.core.manager.player.CombatManager;
31
import thunder.hack.core.manager.world.CrystalManager;
32
import thunder.hack.events.impl.*;
33
import thunder.hack.features.modules.Module;
34
import thunder.hack.features.modules.client.HudEditor;
35
import thunder.hack.setting.Setting;
36
import thunder.hack.setting.impl.Bind;
37
import thunder.hack.setting.impl.BooleanSettingGroup;
38
import thunder.hack.setting.impl.ColorSetting;
39
import thunder.hack.setting.impl.SettingGroup;
40
import thunder.hack.utility.TickTimer;
41
import thunder.hack.utility.Timer;
42
import thunder.hack.utility.math.MathUtility;
43
import thunder.hack.utility.math.PredictUtility;
44
import thunder.hack.utility.player.InteractionUtility;
45
import thunder.hack.utility.player.InventoryUtility;
46
import thunder.hack.utility.player.PlayerUtility;
47
import thunder.hack.utility.player.SearchInvResult;
48
import thunder.hack.utility.render.Render2DEngine;
49
import thunder.hack.utility.render.Render3DEngine;
50
import thunder.hack.utility.render.animation.CaptureMark;
51
import thunder.hack.utility.world.ExplosionUtility;
52
53
import java.awt.*;
54
import java.lang.reflect.Field;
55
import java.util.ArrayList;
56
import java.util.List;
57
import java.util.Map;
58
import java.util.concurrent.ConcurrentHashMap;
59
60
import static net.minecraft.util.Mth.wrapDegrees;
61
62
public class AutoCrystal extends Module {
63
64
    /*   MAIN   */
65
    private static final Setting<Pages> page = new Setting<>("Page", Pages.Main);
66
    private final Setting<Boolean> await = new Setting<>("Await", true, v -> page.is(Pages.Main));
67
    private final Setting<Timing> timing = new Setting<>("Timing", Timing.NORMAL, v -> page.is(Pages.Main));
68
    private final Setting<Sequential> sequential = new Setting<>("Sequential", Sequential.Strong, v -> page.is(Pages.Main));
69
    private final Setting<Rotation> rotate = new Setting<>("Rotate", Rotation.CC, v -> page.is(Pages.Main));
70
    private final Setting<BooleanSettingGroup> yawStep = new Setting<>("YawStep", new BooleanSettingGroup(false), v -> !rotate.is(Rotation.OFF) && page.is(Pages.Main));
71
    private final Setting<Float> yawAngle = new Setting<>("YawAngle", 180.0f, 1.0f, 180.0f, v -> !rotate.is(Rotation.OFF) && page.is(Pages.Main)).addToGroup(yawStep);
72
    private final Setting<CombatManager.TargetBy> targetLogic = new Setting<>("TargetLogic", CombatManager.TargetBy.Distance, v -> page.is(Pages.Main));
73
    private final Setting<Float> targetRange = new Setting<>("TargetRange", 10.0f, 1.0f, 15f, v -> page.is(Pages.Main));
74
    private final Setting<Integer> extrapolation = new Setting<>("Extrapolation", 0, 0, 20, v -> page.is(Pages.Main));
75
76
    /*   PLACE   */
77
    private final Setting<Interact> interact = new Setting<>("Interact", Interact.Default, v -> page.is(Pages.Place));
78
    private final Setting<Boolean> strictCenter = new Setting<>("ССStrict", true, v -> page.is(Pages.Place) && interact.getValue() == Interact.Strict);
79
    private final Setting<Boolean> rayTraceBypass = new Setting<>("RayTraceBypass", false, v -> page.is(Pages.Place));
80
    private final Setting<Boolean> oldVer = new Setting<>("1.12", false, v -> page.is(Pages.Place));
81
    private final Setting<Integer> placeDelay = new Setting<>("PlaceDelay", 0, 0, 20, v -> page.is(Pages.Place));
82
    private final Setting<Integer> lowPlaceDelay = new Setting<>("LowPlaceDelay", 11, 0, 20, v -> page.is(Pages.Place));
83
    private final Setting<Float> placeRange = new Setting<>("PlaceRange", 5f, 1.0f, 6f, v -> page.is(Pages.Place));
84
    private final Setting<Float> placeWallRange = new Setting<>("PlaceWallRange", 3.5f, 0f, 6f, v -> page.is(Pages.Place));
85
86
    /*   BREAK   */
87
    private final Setting<Boolean> inhibit = new Setting<>("Inhibit", true, v -> page.is(Pages.Break));
88
    private final Setting<Integer> breakDelay = new Setting<>("BreakDelay", 0, 0, 20, v -> page.is(Pages.Break));
89
    private final Setting<Integer> lowBreakDelay = new Setting<>("LowBreakDelay", 11, 0, 20, v -> page.is(Pages.Break));
90
    private final Setting<Float> explodeRange = new Setting<>("BreakRange", 5.0f, 1.0f, 6f, v -> page.is(Pages.Break));
91
    private final Setting<Float> explodeWallRange = new Setting<>("BreakWallRange", 3.5f, 0f, 6f, v -> page.is(Pages.Break));
92
    private final Setting<Integer> crystalAge = new Setting<>("CrystalAge", 0, 0, 20, v -> page.is(Pages.Break));
93
94
    /*   PAUSE   */
95
    private final Setting<Boolean> mining = new Setting<>("Mining", true, v -> page.is(Pages.Pause));
96
    private final Setting<Boolean> eating = new Setting<>("Eating", true, v -> page.is(Pages.Pause));
97
    private final Setting<Boolean> aura = new Setting<>("Aura", false, v -> page.is(Pages.Pause));
98
    private final Setting<Boolean> pistonAura = new Setting<>("PistonAura", true, v -> page.is(Pages.Pause));
99
    private final Setting<Boolean> surround = new Setting<>("Surround", true, v -> page.is(Pages.Pause));
100
    private final Setting<Boolean> middleClick = new Setting<>("MiddleClick", true, v -> page.is(Pages.Pause));
101
    private final Setting<Boolean> inventory = new Setting<>("Inventory", false, v -> page.is(Pages.Pause));
102
    private final Setting<Float> pauseHP = new Setting<>("HP", 8.0f, 2.0f, 10f, v -> page.is(Pages.Pause));
103
    private final Setting<BooleanSettingGroup> switchPause = new Setting<>("SwitchPause", new BooleanSettingGroup(true), v -> page.is(Pages.Pause));
104
    private final Setting<Integer> switchDelay = new Setting<>("SwitchDelay", 100, 0, 1000, v -> page.is(Pages.Pause)).addToGroup(switchPause);
105
106
    /*   DAMAGES   */
107
    public final Setting<Boolean> assumeBestArmor = new Setting<>("AssumeBestArmor", false, v -> page.is(Pages.Damages));
108
    public final Setting<Float> minDamage = new Setting<>("MinDamage", 6.0f, 2.0f, 20f, v -> page.is(Pages.Damages));
109
    public final Setting<Float> maxSelfDamage = new Setting<>("MaxSelfDamage", 10.0f, 2.0f, 20f, v -> page.is(Pages.Damages));
110
    private final Setting<BooleanSettingGroup> efficiency = new Setting<>("Efficiency", new BooleanSettingGroup(false), v -> page.is(Pages.Damages));
111
    private final Setting<Float> efficiencyFactor = new Setting<>("EfficiencyFactor", 1.0f, 0.1f, 5f, v -> page.is(Pages.Damages)).addToGroup(efficiency);
112
    public final Setting<Boolean> protectFriends = new Setting<>("ProtectFriends", true, v -> page.is(Pages.Damages));
113
    private final Setting<BooleanSettingGroup> overrideSelfDamage = new Setting<>("OverrideSelfDamage", new BooleanSettingGroup(true), v -> page.is(Pages.Damages));
114
    public final Setting<Boolean> sacrificeTotem = new Setting<>("SacrificeTotem", true, v -> page.is(Pages.Damages)).addToGroup(overrideSelfDamage);
115
    private final Setting<BooleanSettingGroup> armorBreaker = new Setting<>("ArmorBreaker", new BooleanSettingGroup(true), v -> page.is(Pages.Damages));
116
    private final Setting<Float> armorScale = new Setting<>("Armor %", 5.0f, 0.0f, 40f, v -> page.is(Pages.Damages)).addToGroup(armorBreaker);
117
    private final Setting<Float> facePlaceHp = new Setting<>("FacePlaceHp", 5.0f, 0.0f, 20f, v -> page.is(Pages.Damages));
118
    private final Setting<Bind> facePlaceButton = new Setting<>("FacePlaceBtn", new Bind(GLFW.GLFW_KEY_LEFT_SHIFT, false, false), v -> page.is(Pages.Damages));
119
    public final Setting<Boolean> ignoreTerrain = new Setting<>("IgnoreTerrain", true, v -> page.is(Pages.Damages));
120
121
    /*   SWITCH   */
122
    private final Setting<Boolean> autoGapple = new Setting<>("AutoGapple", true, v -> page.is(Pages.Switch));
123
    private final Setting<Switch> autoSwitch = new Setting<>("Switch", Switch.NORMAL, v -> page.is(Pages.Switch));
124
    private final Setting<Switch> antiWeakness = new Setting<>("AntiWeakness", Switch.SILENT, v -> page.is(Pages.Switch));
125
126
    /*   FAILSAFE   */ // Temp
127
    public final Setting<Boolean> placeFailsafe = new Setting<>("PlaceFailsafe", true, v -> page.is(Pages.FailSafe));
128
    public final Setting<Boolean> breakFailsafe = new Setting<>("BreakFailsafe", true, v -> page.is(Pages.FailSafe));
129
    public final Setting<Integer> attempts = new Setting<>("MaxAttempts", 5, 1, 30, v -> page.is(Pages.FailSafe));
130
131
    /*    ID Predict    */
132
    public final Setting<Boolean> idPredict = new Setting<>("IDPredict", false, v -> page.is(Pages.IDPredict));
133
    public final Setting<Integer> idAttacks = new Setting<>("IDAttacks", 3, 1, 10, v -> page.is(Pages.IDPredict));
134
    public final Setting<Boolean> idPredictOnlyDuels = new Setting<>("IDPredictOnlyDuels", false, v -> page.is(Pages.IDPredict));
135
136
    /*   RENDER   */
137
    public final Setting<Aura.ESP> targetEsp = new Setting<>("TargetESP", Aura.ESP.ThunderHack, v -> page.is(Pages.Render));
138
    public final Setting<SettingGroup> espGroup = new Setting<>("ESPSettings", new SettingGroup(false, 0), v -> targetEsp.is(Aura.ESP.ThunderHackV2) && page.is(Pages.Render));
139
    public final Setting<Integer> espLength = new Setting<>("ESPLength", 14, 1, 40, v -> targetEsp.is(Aura.ESP.ThunderHackV2) && page.is(Pages.Render)).addToGroup(espGroup);
140
    public final Setting<Integer> espFactor = new Setting<>("ESPFactor", 8, 1, 20, v -> targetEsp.is(Aura.ESP.ThunderHackV2) && page.is(Pages.Render)).addToGroup(espGroup);
141
    public final Setting<Float> espShaking = new Setting<>("ESPShaking", 1.8f, 1.5f, 10f, v -> targetEsp.is(Aura.ESP.ThunderHackV2) && page.is(Pages.Render)).addToGroup(espGroup);
142
    public final Setting<Float> espAmplitude = new Setting<>("ESPAmplitude", 3f, 0.1f, 8f, v -> targetEsp.is(Aura.ESP.ThunderHackV2) && page.is(Pages.Render)).addToGroup(espGroup);
143
    private final Setting<Swing> swingMode = new Setting<>("Swing", Swing.Place, v -> page.is(Pages.Render));
144
    private final Setting<Boolean> render = new Setting<>("Render", true, v -> page.is(Pages.Render));
145
    private final Setting<BooleanSettingGroup> renderExtrapolation = new Setting<>("RExtrapolation", new BooleanSettingGroup(false), v -> page.is(Pages.Render));
146
    private final Setting<ColorSetting> extrapolationColor = new Setting<>("ExtrapolationColor", new ColorSetting(Color.white), v -> page.is(Pages.Render)).addToGroup(renderExtrapolation);
147
    private final Setting<BooleanSettingGroup> renderInteractVector = new Setting<>("RInteractVector", new BooleanSettingGroup(true), v -> page.is(Pages.Render));
148
    private final Setting<ColorSetting> interactColor = new Setting<>("InteractColor", new ColorSetting(Color.red), v -> page.is(Pages.Render)).addToGroup(renderInteractVector);
149
    private final Setting<Render> renderMode = new Setting<>("RenderMode", Render.Fade, v -> page.is(Pages.Render));
150
    private final Setting<Boolean> rselfDamage = new Setting<>("SelfDamage", true, v -> page.is(Pages.Render));
151
    private final Setting<Boolean> drawDamage = new Setting<>("RenderDamage", true, v -> page.is(Pages.Render));
152
    private final Setting<ColorSetting> fillColor = new Setting<>("Block Fill Color", new ColorSetting(HudEditor.getColor(0)), v -> page.is(Pages.Render));
153
    private final Setting<ColorSetting> lineColor = new Setting<>("Block Line Color", new ColorSetting(HudEditor.getColor(0)), v -> page.is(Pages.Render));
154
    private final Setting<Integer> lineWidth = new Setting<>("Block Line Width", 2, 1, 10, v -> page.is(Pages.Render));
155
    private final Setting<Integer> slideDelay = new Setting<>("Slide Delay", 200, 1, 1000, v -> page.is(Pages.Render));
156
    private final Setting<ColorSetting> textColor = new Setting<>("Text Color", new ColorSetting(Color.WHITE), v -> page.is(Pages.Render));
157
158
    /*   INFO   */
159
    private final Setting<Boolean> targetName = new Setting<>("TargetName", false, v -> page.is(Pages.Info));
160
    private final Setting<Boolean> currentSide = new Setting<>("CurrentSide", true, v -> page.is(Pages.Info));
161
    private final Setting<Boolean> speed = new Setting<>("Speed", true, v -> page.is(Pages.Info));
162
    private final Setting<Boolean> confirmInfo = new Setting<>("ConfirmTime", true, v -> page.is(Pages.Info));
163
    private final Setting<Boolean> calcInfo = new Setting<>("CalcInfo", false, v -> page.is(Pages.Info));
164
165
    public static Player target;
166
    private PlaceData currentData;
167
    private BlockHitResult bestPosition;
168
    private EndCrystal bestCrystal;
169
    private EndCrystal secondaryCrystal;
170
171
    private final TickTimer placeTimer = new TickTimer();
172
    private final TickTimer breakTimer = new TickTimer();
173
    private final TickTimer calcTimer = new TickTimer();
174
    private final TickTimer placeSyncTimer = new TickTimer();
175
    private final Timer pauseTimer = new Timer();
176
177
    private final CrystalManager crystalManager = new CrystalManager();
178
179
    public float renderDamage, renderSelfDamage, rotationYaw, rotationPitch;
180
181
    private int prevCrystalsAmount, crystalSpeed, invTimer, rotationTicks;
182
183
    private boolean rotated, rotating, facePlacing, placedOnSpawn;
184
185
    private long confirmTime;
186
187
    private long calcTime;
188
189
    private BlockPos renderPos, prevRenderPos;
190
    private long renderMultiplier, currentId;
191
    private final Map<BlockPos, Long> renderPositions = new ConcurrentHashMap<>();
192
193
    private RotationVec rotationVec;
194
195
    public State currentState = State.NoTarget;
196
197
    public AutoCrystal() {
198
        super("AutoCrystal", Category.COMBAT);
199
    }
200
201
    @Override
202
    public void onEnable() {
203
        resetVars();
204
    }
205
206
    @Override
207
    public void onDisable() {
208
        resetVars();
209
    }
210
211
    private void resetVars() {
212
        facePlacing = false;
213
        rotated = false;
214
        renderDamage = 0;
215
        renderSelfDamage = 0;
216
        renderMultiplier = 0;
217
        confirmTime = 0;
218
        renderPositions.clear();
219
        crystalManager.reset();
220
        breakTimer.reset();
221
        placeTimer.reset();
222
        calcTimer.reset();
223
        bestCrystal = null;
224
        bestPosition = null;
225
        currentData = null;
226
        renderPos = null;
227
        prevRenderPos = null;
228
        currentState = State.NoTarget;
229
        target = null;
230
        rotationVec = null;
231
    }
232
233
    @EventHandler
234
    public void onPlayerUpdate(PlayerUpdateEvent event) {
235
        if (!rotate.is(Rotation.OFF)) calcRotations();
236
    }
237
238
    @EventHandler
239
    public void onSync(EventSync e) {
240
        if (mc.player == null || mc.level == null) return;
241
242
        target = Managers.COMBAT.getTarget(targetRange.getValue(), targetLogic.getValue());
243
244
        if (target != null && (target.isDeadOrDying() || target.getHealth() < 0)) {
245
            target = null;
246
            currentState = State.NoTarget;
247
            return;
248
        }
249
250
        if (placeTimer.passedTicks(20)) renderDamage = 0f;
251
252
        if (mc.player.getOffhandItem().getItem() != Items.END_CRYSTAL && autoGapple.getValue() && mc.options.keyUse.isDown() && mc.player.getMainHandItem().getItem() == Items.END_CRYSTAL)
253
            InventoryUtility.findItemInHotBar(Items.ENCHANTED_GOLDEN_APPLE).switchTo();
254
255
        if (invTimer++ >= 20) {
256
            crystalSpeed = MathUtility.clamp(prevCrystalsAmount - InventoryUtility.getItemCount(Items.END_CRYSTAL), 0, 255);
257
            prevCrystalsAmount = InventoryUtility.getItemCount(Items.END_CRYSTAL);
258
            invTimer = 0;
259
        }
260
261
        if (!rotate.is(Rotation.OFF) && mc.player != null && rotating) {
262
263
            boolean hitVisible = bestCrystal == null || PlayerUtility.canSee(bestCrystal.position());
264
            boolean placeVisible = bestPosition == null || PlayerUtility.canSee(bestPosition.getLocation());
265
266
            if (mc.player.tickCount % 5 == 0 && rayTraceBypass.getValue() && (!hitVisible || !placeVisible))
267
                mc.player.setXRot(-90);
268
            else mc.player.setXRot(rotationPitch);
269
            mc.player.setYRot(rotationYaw);
270
        }
271
    }
272
273
    @EventHandler(priority = EventPriority.HIGHEST)
274
    public void onTick(EventTick e) {
275
        if (mc.player == null || mc.level == null) return;
276
277
        if (mc.player != null && (!await.getValue() || placeTimer.passedTicks(20) || calcTimer.passedTicks((long) ((float) Managers.SERVER.getPing() / 25f))))
278
            calcPosition(placeRange.getValue(), mc.player.position());
279
280
        getCrystalToExplode();
281
282
        if (timing.is(Timing.NORMAL)) doAction();
283
    }
284
285
    @EventHandler
286
    public void onPostSync(EventPostSync e) {
287
        if (timing.is(Timing.SEQUENTIAL)) doAction();
288
    }
289
290
    private void doAction() {
291
        if (sequential.is(Sequential.Off) || rotate.is(Rotation.MATRIX)) {
292
            if (bestCrystal != null && breakTimer.passedTicks(facePlacing ? lowBreakDelay.getValue() : breakDelay.getValue()))
293
                attackCrystal(bestCrystal);
294
            else if (bestPosition != null && placeTimer.passedTicks(facePlacing ? lowPlaceDelay.getValue() : placeDelay.getValue()) && !placedOnSpawn /*&& placeSyncTimer.passedTicks(3)*/)
295
                placeCrystal(bestPosition, false, false);
296
        } else {
297
            if (bestCrystal != null && breakTimer.passedTicks(facePlacing ? lowBreakDelay.getValue() : breakDelay.getValue()))
298
                attackCrystal(bestCrystal);
299
            if (bestPosition != null && placeTimer.passedTicks(facePlacing ? lowPlaceDelay.getValue() : placeDelay.getValue()) && !placedOnSpawn /*&& placeSyncTimer.passedTicks(3)*/)
300
                placeCrystal(bestPosition, false, false);
301
        }
302
        placedOnSpawn = false;
303
    }
304
305
    @Override
306
    public String getDisplayInfo() {
307
        StringBuilder info = new StringBuilder();
308
309
        Direction side = bestPosition == null ? null : bestPosition.getDirection();
310
        if (side != null) {
311
            if (targetName.getValue() && target != null) info.append(target.getName().getString()).append(" | ");
312
            if (speed.getValue()) info.append(crystalSpeed).append(" c/s").append(" | ");
313
            if (currentSide.getValue()) info.append(side.toString().toUpperCase()).append(" | ");
314
            if (confirmInfo.getValue()) info.append("c: ").append(confirmTime).append(" | ");
315
            if (calcInfo.getValue()) info.append("calc: ").append(calcTime).append(" | ");
316
        }
317
        return info.length() < 4 ? info.toString() : info.substring(0, info.length() - 3);
318
    }
319
320
    @EventHandler
321
    public void onCrystalSpawn(@NotNull EventEntitySpawnPost e) {
322
        if (e.getEntity() instanceof EndCrystal cr && crystalAge.is(0)) {
323
            long now = System.currentTimeMillis();
324
325
            for (Map.Entry<BlockPos, CrystalManager.Attempt> entry : crystalManager.getAwaitingPositions().entrySet()) {
326
                BlockPos bp = entry.getKey();
327
                CrystalManager.Attempt attempt = entry.getValue();
328
329
                if (cr.distanceToSqr(net.minecraft.world.phys.Vec3.atBottomCenterOf(bp)) < 0.3) {
330
                    confirmTime = now - attempt.getTime();
331
                    ModuleManager.autoCrystalInfo.onSpawn();
332
                    crystalManager.confirmSpawn(bp);
333
334
                    if (breakTimer.passedTicks(facePlacing ? lowBreakDelay.getValue() : breakDelay.getValue()))
335
                        handleSpawn(cr);
336
                }
337
            }
338
        }
339
    }
340
341
    @EventHandler
342
    public void onPacketReceive(PacketEvent.Receive e) {
343
        if (mc.player == null || mc.level == null) return;
344
345
        if (e.getPacket() instanceof ClientboundAddEntityPacket spawn)
346
            processSpawnPacket(spawn.getId());
347
348
        if (e.getPacket() instanceof ClientboundExplodePacket explosion) {
349
            Vec3 center = explosion.center();
350
            for (Entity ent : Lists.newArrayList(mc.level.entitiesForRendering()))
351
                if (ent instanceof EndCrystal crystal && crystal.distanceToSqr(center.x, center.y, center.z) <= 144 && !crystalManager.isDead(crystal.getId()))
352
                    crystalManager.setDead(crystal.getId(), System.currentTimeMillis());
353
        }
354
    }
355
356
    @EventHandler
357
    public void onBlockBreakClient(EventBreakBlock e) {
358
        if (target != null && target.distanceToSqr(net.minecraft.world.phys.Vec3.atBottomCenterOf(e.getPos())) <= 4)
359
            calcPosition(2f, net.minecraft.world.phys.Vec3.atBottomCenterOf(e.getPos()));
360
    }
361
362
    private void handleSpawn(EndCrystal crystal) {
363
        if (mc.player == null || mc.level == null) return;
364
        if (canAttackCrystal(crystal)) {
365
            attackCrystal(crystal);
366
367
            if (sequential.is(Sequential.Strong) && placeTimer.passedTicks(facePlacing ? lowPlaceDelay.getValue() : placeDelay.getValue())) {
368
                Managers.ASYNC.run(()-> {
369
                    calcPosition(placeRange.getValue(), mc.player.position());
370
                    if (bestPosition != null) placeCrystal(bestPosition, false, true);
371
                });
372
            }
373
        }
374
    }
375
376
    public void calcRotations() {
377
        if (!rotate.is(Rotation.OFF) && !shouldPause() && (!rotate.getValue().needSeparate() ? (bestPosition != null || bestCrystal != null) : rotationVec != null) && mc.player != null) {
378
            if (rotationTicks-- < 0 && rotate.getValue().needSeparate()) {
379
                rotationVec = null;
380
                return;
381
            }
382
383
            // Shitty NCP (cc) OK
384
            // Updated NCP (mio test server, constantiam prob) OK
385
            // Shitty Matrix (forcemine) OK
386
            // Grim (mio test server) OK
387
388
            Vec3 vec = !rotate.getValue().needSeparate() ? (bestPosition == null ? bestCrystal.position() : rotate.getValue().getVector(bestPosition)) : (rotationVec.hitVec() == null ? rotationVec.vec() : rotate.getValue().getVector(rotationVec.hitVec()));
389
390
            float yawDelta = wrapDegrees((float) wrapDegrees(Math.toDegrees(Math.atan2(vec.z - mc.player.getZ(), (vec.x - mc.player.getX()))) - 90) - rotationYaw);
391
            float pitchDelta = ((float) (-Math.toDegrees(Math.atan2(vec.y - (mc.player.position().y + mc.player.getEyeHeight(mc.player.getPose())), Math.sqrt(Math.pow((vec.x - mc.player.getX()), 2) + Math.pow(vec.z - mc.player.getZ(), 2))))) - rotationPitch);
392
393
394
            float angleToRad = (float) Math.toRadians(27 * (mc.player.tickCount % 30));
395
            yawDelta = (float) (yawDelta + Math.sin(angleToRad) * 3) + MathUtility.random(-1f, 1f);
396
            pitchDelta = pitchDelta + MathUtility.random(-0.6f, 0.6f);
397
398
            if (yawDelta > 180) yawDelta = yawDelta - 180;
399
400
            float yawStepVal = 180f;
401
402
            if (yawStep.getValue().isEnabled()) yawStepVal = yawAngle.getValue();
403
404
            float clampedYawDelta = Mth.clamp(Mth.abs(yawDelta), -yawStepVal, yawStepVal);
405
            float clampedPitchDelta = Mth.clamp(pitchDelta, -45, 45);
406
407
            rotated = Mth.abs(yawDelta) <= yawStepVal || !yawStep.getValue().isEnabled();
408
409
            float newYaw = rotationYaw + (yawDelta > 0 ? clampedYawDelta : -clampedYawDelta);
410
            float newPitch = Mth.clamp(rotationPitch + clampedPitchDelta, -90.0F, 90.0F);
411
412
            double gcdFix = (Math.pow(mc.options.sensitivity().get() * 0.6 + 0.2, 3.0)) * 1.2;
413
414
            rotationYaw = (float) (newYaw - (newYaw - rotationYaw) % gcdFix);
415
            rotationPitch = (float) (newPitch - (newPitch - rotationPitch) % gcdFix);
416
417
            ModuleManager.rotations.fixRotation = rotationYaw;
418
            rotating = true;
419
        } else {
420
            rotationYaw = mc.player.getYRot();
421
            rotationPitch = mc.player.getXRot();
422
            rotating = false;
423
        }
424
    }
425
426
    @Override
427
    public void onRender3D(PoseStack stack) {
428
        crystalManager.update();
429
430
        if (target != null) switch (targetEsp.getValue()) {
431
            case CelkaPasta -> Render3DEngine.drawOldTargetEsp(stack, target);
432
            case NurikZapen -> CaptureMark.render(target);
433
            case ThunderHackV2 ->
434
                    Render3DEngine.renderGhosts(espLength.getValue(), espFactor.getValue(), espShaking.getValue(), espAmplitude.getValue(), target);
435
            case ThunderHack -> Render3DEngine.drawTargetEsp(stack, target);
436
        }
437
438
        if (render.getValue()) {
439
            Map<BlockPos, Long> cache = new ConcurrentHashMap<>(renderPositions);
440
441
            cache.forEach((pos, time) -> {
442
                if (System.currentTimeMillis() - time > 500) renderPositions.remove(pos);
443
            });
444
445
            String dmg = MathUtility.round2(renderDamage) + (rselfDamage.getValue() ? " / " + MathUtility.round2(renderSelfDamage) : "");
446
447
            if (renderMode.is(Render.Fade)) {
448
                cache.forEach((pos, time) -> {
449
                    if (System.currentTimeMillis() - time < 500) {
450
                        int alpha = (int) (100f * (1f - ((System.currentTimeMillis() - time) / 500f)));
451
452
                        Render3DEngine.FILLED_QUEUE.add(new Render3DEngine.FillAction(new AABB(pos), Render2DEngine.injectAlpha(fillColor.getValue().getColorObject(), alpha)));
453
                        Render3DEngine.OUTLINE_QUEUE.add(new Render3DEngine.OutlineAction(new AABB(pos), Render2DEngine.injectAlpha(lineColor.getValue().getColorObject(), alpha), lineWidth.getValue()));
454
455
                        if (drawDamage.getValue())
456
                            Render3DEngine.drawTextIn3D(dmg, net.minecraft.world.phys.Vec3.atBottomCenterOf(pos), 0, 0.1, 0, Render2DEngine.applyOpacity(textColor.getValue().getColorObject(), alpha / 100f));
457
                    }
458
                });
459
            } else if (renderMode.getValue() == Render.Slide && renderPos != null) {
460
                if (prevRenderPos == null) prevRenderPos = renderPos;
461
                if (renderPositions.isEmpty()) return;
462
                float mult = MathUtility.clamp((System.currentTimeMillis() - renderMultiplier) / (float) slideDelay.getValue(), 0f, 1f);
463
                AABB interpolatedBox = Render3DEngine.interpolateBox(new AABB(prevRenderPos), new AABB(renderPos), mult);
464
465
                renderBox(dmg, interpolatedBox);
466
            } else if (renderPos != null) {
467
                if (renderPositions.isEmpty()) return;
468
469
                renderBox(dmg, new AABB(renderPos));
470
            }
471
        }
472
473
        if (target != null && renderExtrapolation.getValue().isEnabled())
474
            Render3DEngine.OUTLINE_QUEUE.add(new Render3DEngine.OutlineAction(PredictUtility.predictBox(target, extrapolation.getValue()), extrapolationColor.getValue().getColorObject(), 1f));
475
476
        if (target != null && bestPosition != null && renderInteractVector.getValue().isEnabled()) {
477
            Vec3 vec = bestPosition.getLocation();
478
            AABB b = new AABB(vec.x() - .05, vec.y() - .05, vec.z() - .05, vec.x() + .05, vec.y() + .05, vec.z() + .05);
479
            Render3DEngine.OUTLINE_QUEUE.add(new Render3DEngine.OutlineAction(b, interactColor.getValue().getColorObject(), 1f));
480
            Render3DEngine.FILLED_QUEUE.add(new Render3DEngine.FillAction(b, Render2DEngine.applyOpacity(interactColor.getValue().getColorObject(), 0.6f)));
481
        }
482
    }
483
484
    private void renderBox(String dmg, AABB box) {
485
        Render3DEngine.FILLED_QUEUE.add(new Render3DEngine.FillAction(box, fillColor.getValue().getColorObject()));
486
        Render3DEngine.OUTLINE_QUEUE.add(new Render3DEngine.OutlineAction(box, lineColor.getValue().getColorObject(), lineWidth.getValue()));
487
488
        if (drawDamage.getValue())
489
            Render3DEngine.drawTextIn3D(dmg, box.getCenter(), 0, 0.1, 0, textColor.getValue().getColorObject());
490
    }
491
492
    public boolean shouldPause() {
493
        if (mc.player == null || mc.level == null || mc.gameMode == null) return true;
494
495
        boolean offhand = mc.player.getOffhandItem().getItem() instanceof EndCrystalItem;
496
        boolean mainHand = mc.player.getMainHandItem().getItem() instanceof EndCrystalItem;
497
498
        if (!pauseTimer.passedMs(1000)) {
499
            currentState = State.ExternalPause;
500
            return true;
501
        }
502
503
        if (mc.gameMode.isDestroying() && !offhand && mining.getValue()) {
504
            currentState = State.Mining;
505
            return true;
506
        }
507
508
        if (autoSwitch.is(Switch.NONE) && !offhand && !mainHand) {
509
            currentState = State.NoCrystalls;
510
            return true;
511
        }
512
513
        if ((autoSwitch.is(Switch.SILENT) || autoSwitch.is(Switch.NORMAL)) && !InventoryUtility.findItemInHotBar(Items.END_CRYSTAL).found() && !offhand) {
514
            currentState = State.NoCrystalls;
515
            return true;
516
        }
517
518
        if (autoSwitch.is(Switch.INVENTORY) && !InventoryUtility.findItemInInventory(Items.END_CRYSTAL).found() && !offhand) {
519
            currentState = State.NoCrystalls;
520
            return true;
521
        }
522
523
        if (mc.player.isUsingItem() && eating.getValue()) {
524
            currentState = State.Eating;
525
            return true;
526
        }
527
528
        if (rotationMarkedDirty()) {
529
            currentState = State.ExternalPause;
530
            return true;
531
        }
532
533
        if (mc.player.getHealth() + mc.player.getAbsorptionAmount() < pauseHP.getValue()) {
534
            currentState = State.LowHP;
535
            return true;
536
        }
537
538
        if (!offhand && autoGapple.getValue() && mc.options.keyUse.isDown() && mc.player.getMainHandItem().getItem() == Items.ENCHANTED_GOLDEN_APPLE) {
539
            currentState = State.Eating;
540
            return true;
541
        }
542
543
        boolean silentWeakness = antiWeakness.getValue() == Switch.SILENT || antiWeakness.getValue() == Switch.INVENTORY;
544
545
        boolean silent = autoSwitch.getValue() == Switch.SILENT || autoSwitch.getValue() == Switch.INVENTORY;
546
547
        boolean switchPause1 = switchPause.getValue().isEnabled() && !Managers.PLAYER.switchTimer.passedMs(switchDelay.getValue()) && !silent && !silentWeakness;
548
549
        if (!switchPause1) currentState = State.Active;
550
551
        return switchPause1;
552
    }
553
554
    public boolean rotationMarkedDirty() {
555
        if (ModuleManager.surround.isEnabled() && !ModuleManager.surround.inactivityTimer.passedMs(500) && surround.getValue())
556
            return true;
557
558
        if (ModuleManager.middleClick.isEnabled() && mc.options.keyPickItem.isDown() && middleClick.getValue())
559
            return true;
560
        if (inventory.getValue() && Managers.PLAYER.inInventory) return true;
561
562
        if (ModuleManager.autoTrap.isEnabled() && !ModuleManager.surround.inactivityTimer.passedMs(500)) return true;
563
564
        if (ModuleManager.blocker.isEnabled() && !ModuleManager.surround.inactivityTimer.passedMs(500)) return true;
565
566
        if (ModuleManager.holeFill.isEnabled() && !HoleFill.inactivityTimer.passedMs(500)) return true;
567
568
        if (ModuleManager.aura.isEnabled() && Aura.target != null && aura.getValue()) return true;
569
570
        return ModuleManager.pistonAura.isEnabled() && pistonAura.getValue();
571
    }
572
573
    public void attackCrystal(EndCrystal crystal) {
574
        if (mc.player == null || mc.level == null || mc.gameMode == null || crystal == null || (crystalManager.isDead(crystal.getId()) && inhibit.getValue()))
575
            return;
576
577
        if (shouldPause() || target == null) return;
578
579
        MobEffectInstance weaknessEffect = mc.player.getEffect(MobEffects.WEAKNESS);
580
        MobEffectInstance strengthEffect = mc.player.getEffect(MobEffects.STRENGTH);
581
582
        int prevSlot = -1;
583
        SearchInvResult antiWeaknessResult = InventoryUtility.getAntiWeaknessItem();
584
        SearchInvResult antiWeaknessResultInv = InventoryUtility.findInInventory(itemStack -> itemStack.is(ItemTags.SWORDS) || itemStack.is(ItemTags.PICKAXES) || itemStack.getItem() instanceof AxeItem || itemStack.getItem() instanceof ShovelItem);
585
586
        if (antiWeakness.getValue() != Switch.NONE)
587
            if (weaknessEffect != null && (strengthEffect == null || strengthEffect.getAmplifier() < weaknessEffect.getAmplifier()))
588
                prevSlot = switchTo(antiWeaknessResult, antiWeaknessResultInv, antiWeakness);
589
590
        sendPacket(new ServerboundAttackPacket(crystal.getId()));
591
        swingHand(false, true);
592
593
        if (rotate.getValue().needSeparate() && !Managers.PLAYER.checkRtx(rotationYaw, rotationPitch, explodeRange.getValue(), explodeWallRange.getValue(), crystal))
594
            rotationVec = new RotationVec(crystal.getBoundingBox().getCenter(), null, false);
595
596
        breakTimer.reset();
597
598
        crystalManager.onAttack(crystal);
599
600
        rotationTicks = 10;
601
602
        for (Entity ent : Lists.newArrayList(mc.level.entitiesForRendering())) {
603
            if (ent instanceof EndCrystal exCrystal && exCrystal.distanceToSqr(crystal.getX(), crystal.getY(), crystal.getZ()) <= 144 && !crystalManager.isDead(exCrystal.getId())) {
604
                crystalManager.setDead(exCrystal.getId(), System.currentTimeMillis());
605
            }
606
607
            //  if (ent instanceof ItemEntity && ent.distanceToSqr(crystal.getX(), crystal.getY(), crystal.getZ()) <= 144) {
608
            //       sendMessage("item detected");
609
            //    }
610
        }
611
612
        if (prevSlot != -1) {
613
            if (antiWeakness.getValue() == Switch.SILENT) {
614
                mc.player.getInventory().setSelectedSlot(prevSlot);
615
                sendPacket(new ServerboundSetCarriedItemPacket(prevSlot));
616
            }
617
            if (antiWeakness.getValue() == Switch.INVENTORY) {
618
                mc.gameMode.handleContainerInput(mc.player.containerMenu.containerId, prevSlot, mc.player.getInventory().getSelectedSlot(), ContainerInput.SWAP, mc.player);
619
                sendPacket(new ServerboundContainerClosePacket(mc.player.containerMenu.containerId));
620
            }
621
        }
622
    }
623
624
    private boolean canAttackCrystal(EndCrystal cr) {
625
        if (crystalAge.getValue() != 0 && cr.tickCount < crystalAge.getValue()) return false;
626
627
        if (PlayerUtility.squaredDistanceFromEyes(cr.getBoundingBox().getCenter()) > (InteractionUtility.canSee(cr) ? explodeRange.getPow2Value() : explodeWallRange.getPow2Value()))
628
            return false;
629
630
        if (!cr.isAlive()) return false;
631
632
        float damage = ExplosionUtility.getAutoCrystalDamage(cr.position(), target, getPredictTicks(), false);
633
        float selfDamage = ExplosionUtility.getSelfExplosionDamage(cr.position(), getSelfPredictTicks(), false);
634
635
        boolean overrideDamage = shouldOverrideMaxSelfDmg(damage, selfDamage);
636
637
        if (protectFriends.getValue()) {
638
            List<Player> players = Lists.newArrayList(mc.level.players());
639
            for (Player pl : players) {
640
                if (!Managers.FRIEND.isFriend(pl)) continue;
641
                float fdamage = ExplosionUtility.getAutoCrystalDamage(cr.position(), pl, getPredictTicks(), false);
642
                if (fdamage > selfDamage) {
643
                    selfDamage = fdamage;
644
                }
645
            }
646
        }
647
648
        return !(selfDamage > maxSelfDamage.getValue()) || overrideDamage;
649
    }
650
651
    private int switchTo(SearchInvResult result, SearchInvResult resultInv, @NotNull Setting<Switch> switchMode) {
652
        if (mc.player == null || mc.level == null || mc.gameMode == null) return -1;
653
654
        int prevSlot = mc.player.getInventory().getSelectedSlot();
655
656
        switch (switchMode.getValue()) {
657
            case INVENTORY -> {
658
                if (resultInv.found()) {
659
                    prevSlot = resultInv.slot();
660
                    mc.gameMode.handleContainerInput(mc.player.containerMenu.containerId, prevSlot, mc.player.getInventory().getSelectedSlot(), ContainerInput.SWAP, mc.player);
661
                    sendPacket(new ServerboundContainerClosePacket(mc.player.containerMenu.containerId));
662
                }
663
            }
664
            case NORMAL -> result.switchTo();
665
            case SILENT -> result.switchToSilent();
666
            case NONE -> {
667
            }
668
        }
669
        return prevSlot;
670
    }
671
672
    public void placeCrystal(BlockHitResult bhr, boolean packetRotate, boolean onSpawn) {
673
        if (shouldPause() || mc.player == null || bhr == null) return;
674
        int prevSlot = -1;
675
676
        SearchInvResult crystalResult = InventoryUtility.findItemInHotBar(Items.END_CRYSTAL);
677
        SearchInvResult crystalResultInv = InventoryUtility.findItemInInventory(Items.END_CRYSTAL);
678
679
        boolean offhand = mc.player.getOffhandItem().getItem() instanceof EndCrystalItem;
680
        boolean holdingCrystal = mc.player.getMainHandItem().getItem() instanceof EndCrystalItem || offhand;
681
682
        if (!rotate.is(Rotation.OFF)) {
683
            rotationVec = new RotationVec(bhr.getLocation(), bhr, true);
684
            if (packetRotate) {
685
                float[] angle = InteractionUtility.calculateAngle(bhr.getLocation());
686
                sendPacket(new ServerboundMovePlayerPacket.PosRot(mc.player.getX(), mc.player.getY(), mc.player.getZ(), angle[0], angle[1], mc.player.onGround(), mc.player.horizontalCollision));
687
            } else if (!rotated && !rotate.getValue().needSeparate()) // TODO check ray trace
688
                return;
689
        }
690
691
692
        if (isPositionBlockedByEntity(bhr.getBlockPos(), false)) return;
693
694
        if (autoSwitch.getValue() != Switch.NONE && !holdingCrystal)
695
            prevSlot = switchTo(crystalResult, crystalResultInv, autoSwitch);
696
697
        if (!(mc.player.getMainHandItem().getItem() instanceof EndCrystalItem || offhand || autoSwitch.getValue() == Switch.SILENT))
698
            return;
699
700
        sendSequencedPacket(id -> new ServerboundUseItemOnPacket(offhand ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND, bhr, id));
701
        swingHand(offhand, false);
702
703
        if (breakTimer.passedTicks(breakDelay.getValue()) && idPredict.getValue() && (!idPredictOnlyDuels.getValue() || mc.level.getWorldBorder().getSize() == 100))
704
            predictAttack();
705
706
        placeTimer.reset();
707
        rotationTicks = 10;
708
709
        if (!bhr.getBlockPos().equals(renderPos)) {
710
            renderMultiplier = System.currentTimeMillis();
711
            prevRenderPos = renderPos;
712
            renderPos = bhr.getBlockPos();
713
        }
714
715
        crystalManager.addAwaitingPos(bhr.getBlockPos());
716
717
        renderPositions.put(bhr.getBlockPos(), System.currentTimeMillis());
718
        postPlaceSwitch(prevSlot);
719
720
        if (onSpawn) {
721
            placedOnSpawn = true;
722
            placeSyncTimer.reset();
723
        }
724
    }
725
726
    private void postPlaceSwitch(int slot) {
727
        if (mc.player == null || mc.level == null || mc.gameMode == null) return;
728
729
        if (autoSwitch.getValue() == Switch.SILENT && slot != -1) {
730
            mc.player.getInventory().setSelectedSlot(slot);
731
            sendPacket(new ServerboundSetCarriedItemPacket(slot));
732
        }
733
734
        if (autoSwitch.getValue() == Switch.INVENTORY && slot != -1) {
735
            mc.gameMode.handleContainerInput(mc.player.containerMenu.containerId, slot, mc.player.getInventory().getSelectedSlot(), ContainerInput.SWAP, mc.player);
736
            sendPacket(new ServerboundContainerClosePacket(mc.player.containerMenu.containerId));
737
        }
738
    }
739
740
    public void calcPosition(float range, Vec3 center) {
741
        if (mc.player == null || mc.level == null) return;
742
        long currentTime = System.currentTimeMillis();
743
        calcTimer.reset();
744
745
        if (target == null) {
746
            renderPos = null;
747
            prevRenderPos = null;
748
            bestPosition = null;
749
            currentData = null;
750
            return;
751
        }
752
753
        List<PlaceData> list = getPossibleBlocks(target, center, range).stream().filter(data -> isSafe(data.damage, data.selfDamage, data.overrideDamage)).toList();
754
        bestPosition = list.isEmpty() ? null : filterPositions(list);
755
        calcTime = System.currentTimeMillis() - currentTime;
756
    }
757
758
    private @NotNull List<PlaceData> getPossibleBlocks(Player target, Vec3 center, float range) {
759
        List<PlaceData> blocks = new ArrayList<>();
760
        BlockPos playerPos = BlockPos.containing(center);
761
        Vec3 predictedPlayerPos = PredictUtility.predictPosition(mc.player, getSelfPredictTicks());
762
        int r = (int) Math.ceil(range);
763
764
        for (int x = playerPos.getX() - r; x <= playerPos.getX() + r; x++) {
765
            for (int y = playerPos.getY() - r; y <= playerPos.getY() + r; y++) {
766
                for (int z = playerPos.getZ() - r; z <= playerPos.getZ() + r; z++) {
767
                    PlaceData data = getPlaceData(new BlockPos(x, y, z), target, predictedPlayerPos);
768
                    if (data != null) blocks.add(data);
769
                }
770
            }
771
        }
772
773
        return blocks;
774
    }
775
776
    private @NotNull List<CrystalData> getPossibleCrystals(Player target) {
777
        List<CrystalData> crystals = new ArrayList<>();
778
779
        if (mc.player == null || mc.level == null) return crystals;
780
781
        Iterable<Entity> entities = Lists.newArrayList(mc.level.entitiesForRendering());
782
        for (Entity ent : entities) {
783
            if (!(ent instanceof EndCrystal cr)) continue;
784
785
            if (crystalManager.isBlocked(cr.getId())) continue;
786
787
            if (crystalAge.getValue() != 0 && cr.tickCount < crystalAge.getValue()) continue;
788
789
            if (crystalManager.isDead(cr.getId()) && inhibit.getValue()) continue;
790
791
            if (PlayerUtility.squaredDistanceFromEyes(ent.getBoundingBox().getCenter()) > (InteractionUtility.canSee(cr) ? explodeRange.getPow2Value() : explodeWallRange.getPow2Value()))
792
                continue;
793
794
            if (!ent.isAlive()) continue;
795
796
            float damage = ExplosionUtility.getAutoCrystalDamage(ent.position(), target, getPredictTicks(), false);
797
            float selfDamage = ExplosionUtility.getSelfExplosionDamage(ent.position(), getSelfPredictTicks(), false);
798
799
            boolean overrideDamage = shouldOverrideMaxSelfDmg(damage, selfDamage);
800
801
            if (protectFriends.getValue()) {
802
                List<Player> players = Lists.newArrayList(mc.level.players());
803
                for (Player pl : players) {
804
                    if (!Managers.FRIEND.isFriend(pl)) continue;
805
                    float fdamage = ExplosionUtility.getAutoCrystalDamage(ent.position(), pl, getPredictTicks(), false);
806
                    if (fdamage > selfDamage) {
807
                        selfDamage = fdamage;
808
                    }
809
                }
810
            }
811
812
            if (damage < 1.5f) continue;
813
            if (selfDamage > maxSelfDamage.getValue() && !overrideDamage) continue;
814
            crystals.add(new CrystalData((EndCrystal) ent, damage, selfDamage, overrideDamage));
815
        }
816
        return crystals;
817
    }
818
819
    public void getCrystalToExplode() {
820
        if (target == null) {
821
            bestCrystal = null;
822
            return;
823
        }
824
825
        if (secondaryCrystal != null) {
826
            if (canAttackCrystal(secondaryCrystal)) {
827
                bestCrystal = secondaryCrystal;
828
                debug("secondary crystal accepted");
829
            } else debug("secondary crystal declined");
830
            secondaryCrystal = null;
831
            return;
832
        }
833
834
        List<CrystalData> list = getPossibleCrystals(target).stream().filter(data -> isSafe(data.damage, data.selfDamage, data.overrideDamage)).toList();
835
        bestCrystal = list.isEmpty() ? null : filterCrystals(list);
836
    }
837
838
    public boolean isSafe(float damage, float selfDamage, boolean overrideDamage) {
839
        if (mc.player == null || mc.level == null) return false;
840
841
        if (overrideDamage) return true;
842
843
        if (selfDamage + 0.5 > mc.player.getHealth() + mc.player.getAbsorptionAmount())
844
            return false;
845
846
        if (efficiency.getValue().isEnabled())
847
            return damage / selfDamage >= efficiencyFactor.getValue();
848
849
        return true;
850
    }
851
852
    private @Nullable BlockHitResult filterPositions(@NotNull List<PlaceData> clearedList) {
853
        PlaceData bestData = null;
854
        float bestVal = 0f;
855
856
        for (PlaceData data : clearedList) {
857
            if ((shouldOverrideMinDmg(data.damage) || data.damage > minDamage.getValue())) {
858
859
                if (bestData != null && data.overrideDamage && target.getAbsorptionAmount() + target.getHealth() < bestData.damage && bestData.selfDamage < data.selfDamage)
860
                    continue;
861
862
                boolean shouldStopOverride = bestData != null && bestData.overrideDamage && data.damage > target.getHealth() + target.getAbsorptionAmount() && data.selfDamage < bestData.selfDamage;
863
864
                float safetyComparatorDelta = shouldStopOverride ? 10f : 1f;
865
866
                if (bestData != null && Math.abs(bestData.damage - data.damage) < safetyComparatorDelta && Math.abs(bestData.selfDamage - data.selfDamage) > 1f) {
867
                    if (bestData.selfDamage >= data.selfDamage) {
868
                        bestData = data;
869
                        bestVal = data.damage;
870
                    }
871
                } else {
872
                    if (bestVal < data.damage) {
873
                        bestData = data;
874
                        bestVal = data.damage;
875
                    }
876
                }
877
            }
878
        }
879
880
        if (bestData == null) return null;
881
        facePlacing = bestData.damage < minDamage.getValue();
882
        renderDamage = bestData.damage;
883
        renderSelfDamage = bestData.selfDamage;
884
        currentData = bestData;
885
        return bestData.bhr;
886
    }
887
888
    private @Nullable EndCrystal filterCrystals(@NotNull List<CrystalData> clearedList) {
889
        CrystalData bestData = null;
890
        float bestVal = 0f;
891
        for (CrystalData data : clearedList) {
892
            if ((shouldOverrideMinDmg(data.damage) || data.damage > minDamage.getValue())) {
893
                if (bestData != null && data.overrideDamage && target.getAbsorptionAmount() + target.getHealth() < bestData.damage && bestData.selfDamage < data.selfDamage)
894
                    continue;
895
896
                boolean shouldStopOverride = bestData != null && bestData.overrideDamage && data.damage > target.getHealth() + target.getAbsorptionAmount() && data.selfDamage < bestData.selfDamage;
897
898
                float safetyComparatorDelta = shouldStopOverride ? 10f : 1f;
899
900
                if (bestData != null && Math.abs(bestData.damage - data.damage) < safetyComparatorDelta && Math.abs(bestData.selfDamage - data.selfDamage) > 1f) {
901
                    if (bestData.selfDamage >= data.selfDamage) {
902
                        bestData = data;
903
                        bestVal = data.damage;
904
                    }
905
                } else {
906
                    if (bestVal < data.damage) {
907
                        bestData = data;
908
                        bestVal = data.damage;
909
                    }
910
                }
911
            }
912
        }
913
914
        if (bestData == null) return null;
915
        renderDamage = bestData.damage();
916
        renderSelfDamage = bestData.selfDamage();
917
        return bestData.crystal;
918
    }
919
920
    public @Nullable PlaceData getPlaceData(BlockPos bp, Player target, Vec3 predictedPlayerPos) {
921
        if (mc.player == null || mc.level == null) return null;
922
923
        if (crystalManager.isPositionBlocked(bp)) return null;
924
925
        if (!predictCrystalSpawn(bp, predictedPlayerPos)) return null;
926
927
        if (target != null && target.position().distanceToSqr(net.minecraft.world.phys.Vec3.atBottomCenterOf(bp).add(0, 0.5, 0)) > 144) return null;
928
929
        Block base = mc.level.getBlockState(bp).getBlock();
930
931
        if (base != Blocks.OBSIDIAN && base != Blocks.BEDROCK) return null;
932
933
        boolean freeSpace = mc.level.isEmptyBlock(bp.above());
934
935
        if (!(freeSpace && (!oldVer.getValue() || mc.level.isEmptyBlock(bp.above().above())))) return null;
936
937
        if (isPositionBlockedByEntity(bp, true)) return null;
938
939
        Vec3 crystalVec = new Vec3(0.5f + bp.getX(), 1f + bp.getY(), 0.5f + bp.getZ());
940
941
        float damage = target == null ? 10f : ExplosionUtility.getAutoCrystalDamage(crystalVec, target, getPredictTicks(), false);
942
        if (damage < 1.5f) return null;
943
        float selfDamage = ExplosionUtility.getSelfExplosionDamage(crystalVec, getSelfPredictTicks(), false);
944
        boolean overrideDamage = shouldOverrideMaxSelfDmg(damage, selfDamage);
945
946
        if (protectFriends.getValue()) {
947
            List<Player> players = Lists.newArrayList(mc.level.players());
948
            for (Player pl : players) {
949
                if (!Managers.FRIEND.isFriend(pl)) continue;
950
                float fdamage = ExplosionUtility.getAutoCrystalDamage(crystalVec, pl, getPredictTicks(), false);
951
                if (fdamage > selfDamage) {
952
                    selfDamage = fdamage;
953
                }
954
            }
955
        }
956
957
        if (selfDamage > maxSelfDamage.getValue() && !overrideDamage) return null;
958
959
        BlockHitResult interactResult = getInteractResult(bp, crystalVec);
960
        if (interactResult == null) return null;
961
962
        return new PlaceData(interactResult, damage, selfDamage, overrideDamage);
963
    }
964
965
    public boolean predictCrystalSpawn(BlockPos bp, Vec3 predictedPlayerPos) {
966
        Vec3 predictedPos = net.minecraft.world.phys.Vec3.atBottomCenterOf(bp).add(0, 1.5f, 0);
967
968
        float distance = (float) predictedPlayerPos.add(0, mc.player.getEyeHeight(mc.player.getPose()), 0).distanceToSqr(predictedPos);
969
970
        if (InteractionUtility.canSee(predictedPos)) return distance <= explodeRange.getPow2Value();
971
        else return distance <= explodeWallRange.getPow2Value();
972
    }
973
974
    public BlockHitResult getInteractResult(BlockPos bp, Vec3 crystalVec) {
975
        BlockHitResult interactResult = null;
976
        switch (interact.getValue()) {
977
            case Default -> interactResult = getDefaultInteract(crystalVec, bp);
978
            case Strict -> interactResult = getStrictInteract(bp);
979
        }
980
        return interactResult;
981
    }
982
983
    public boolean isPositionBlockedByEntity(@NotNull BlockPos base, boolean calcPhase) {
984
        if (mc.player == null || mc.level == null) return false;
985
986
        AABB box = new AABB(base.above());
987
988
        if (!(mc.getConnection() != null && mc.getConnection().getServerData() != null && mc.getConnection().getServerData().ip.contains("crystalpvp.cc")))
989
            box = box.inflate(0, 1f, 0);
990
991
        for (Entity ent : Lists.newArrayList(mc.level.entitiesForRendering())) {
992
            if (ent == null) continue;
993
994
            if (ent.getBoundingBox().intersects(box)) {
995
996
                if (ent instanceof ExperienceOrb) continue;
997
998
                if (ModuleManager.speedMine.isBlockDrop(ent)) continue;
999
1000
                if (ent instanceof EndCrystal cr) {
1001
                    if (crystalManager.isDead(cr.getId())) continue;
1002
1003
                    if (crystalManager.isBlocked(cr.getId())) return true;
1004
1005
                    if (calcPhase) {
1006
                        if (canAttackCrystal(cr)) continue;
1007
1008
                    } else {
1009
                        if (cr.position().distanceToSqr(box.getCenter()) > 0.3) {
1010
                            secondaryCrystal = cr;
1011
                            debug("secondary crystal created");
1012
                        }
1013
                    }
1014
                }
1015
1016
                return true;
1017
            }
1018
        }
1019
        return false;
1020
    }
1021
1022
    public boolean isPositionBlockedByCrystal(@NotNull BlockPos base) {
1023
        AABB box = new AABB(base.above());
1024
        return Lists.newArrayList(mc.level.entitiesForRendering()).stream().anyMatch(ent -> ent != null && ent.getBoundingBox().intersects(box) && ent instanceof EndCrystal);
1025
    }
1026
1027
    public boolean shouldOverrideMaxSelfDmg(float damage, float selfDamage) {
1028
        if (overrideSelfDamage.getValue().isEnabled() && target != null) {
1029
            if (mc.player == null || mc.level == null) return false;
1030
1031
            boolean targetSafe = (target.getOffhandItem().getItem() == Items.TOTEM_OF_UNDYING || target.getMainHandItem().getItem() == Items.TOTEM_OF_UNDYING);
1032
1033
            boolean playerSafe = (mc.player.getOffhandItem().getItem() == Items.TOTEM_OF_UNDYING || mc.player.getMainHandItem().getItem() == Items.TOTEM_OF_UNDYING);
1034
1035
            float targetHp = target.getHealth() + target.getAbsorptionAmount();
1036
1037
            float playerHp = mc.player.getHealth() + mc.player.getAbsorptionAmount();
1038
1039
            boolean canPop = damage > targetHp && targetSafe;
1040
1041
            boolean canKill = damage > targetHp && !targetSafe;
1042
1043
            boolean canPopSelf = selfDamage > playerHp && playerSafe;
1044
1045
            boolean canKillSelf = selfDamage > playerHp && !playerSafe;
1046
1047
            if (canPopSelf && canKill && sacrificeTotem.getValue()) return true;
1048
1049
            return selfDamage > maxSelfDamage.getValue() && (canPop || canKill) && !canKillSelf && !canPopSelf;
1050
        }
1051
        return false;
1052
    }
1053
1054
    public boolean shouldOverrideMinDmg(float damage) {
1055
        if (target == null)
1056
            return false;
1057
1058
        if (isKeyPressed(facePlaceButton))
1059
            return true;
1060
1061
        if ((target.getHealth() + target.getAbsorptionAmount()) - damage < 0)
1062
            return true;
1063
1064
        if (armorBreaker.getValue().isEnabled())
1065
            for (ItemStack armor : thunder.hack.utility.player.ArmorUtility.getArmorItems(target))
1066
                if (armor != null && !armor.getItem().equals(Items.AIR) && ((armor.getMaxDamage() - armor.getDamageValue()) / (float) armor.getMaxDamage()) * 100 < armorScale.getValue())
1067
                    return true;
1068
1069
        return target.getHealth() + target.getAbsorptionAmount() <= facePlaceHp.getValue();
1070
    }
1071
1072
    private @Nullable BlockHitResult getDefaultInteract(Vec3 crystalVector, BlockPos bp) {
1073
        if (mc.player == null || mc.level == null) return null;
1074
1075
        if (PlayerUtility.squaredDistanceFromEyes(crystalVector) > placeRange.getPow2Value()) return null;
1076
1077
        BlockHitResult wallCheck = mc.level.clip(new ClipContext(InteractionUtility.getEyesPos(mc.player), crystalVector, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, mc.player));
1078
1079
        if (wallCheck != null && wallCheck.getType() == HitResult.Type.BLOCK && wallCheck.getBlockPos() != bp)
1080
            if (PlayerUtility.squaredDistanceFromEyes(crystalVector) > placeWallRange.getPow2Value()) return null;
1081
1082
        return new BlockHitResult(crystalVector, mc.level.isInWorldBounds(bp.above()) ? Direction.UP : Direction.DOWN, bp, false);
1083
    }
1084
1085
    public @Nullable BlockHitResult getStrictInteract(@NotNull BlockPos bp) {
1086
        if (mc.player == null || mc.level == null) return null;
1087
1088
        float bestDistance = Float.MAX_VALUE;
1089
        Direction bestDirection = null;
1090
1091
        float upPoint = strictCenter.getValue() ? (float) net.minecraft.world.phys.Vec3.atBottomCenterOf(bp).y() : bp.above().getY();
1092
1093
        if (mc.player.getEyePosition().y() > upPoint) {
1094
            bestDirection = Direction.UP;
1095
        } else if (mc.player.getEyePosition().y() < bp.getY() && mc.level.isEmptyBlock(bp.below())) {
1096
            bestDirection = Direction.DOWN;
1097
        } else {
1098
            for (Direction dir : InteractionUtility.getStrictBlockDirections(bp)) {
1099
                if (dir == Direction.UP || dir == Direction.DOWN) continue;
1100
1101
                Vec3 directionVec = new Vec3(bp.getX() + 0.5 + dir.getUnitVec3i().getX() * 0.5, bp.getY() + 0.99, bp.getZ() + 0.5 + dir.getUnitVec3i().getZ() * 0.5);
1102
1103
                if (!mc.level.getBlockState(bp.relative(dir)).canBeReplaced()) continue;
1104
1105
                float distance = PlayerUtility.squaredDistanceFromEyes(directionVec);
1106
                if (bestDistance > distance) {
1107
                    bestDirection = dir;
1108
                    bestDistance = distance;
1109
                }
1110
            }
1111
        }
1112
1113
        if (bestDirection == null) return null;
1114
1115
        Vec3 vec = InteractionUtility.getVisibleDirectionPoint(bestDirection, bp, placeWallRange.getValue(), placeRange.getValue());
1116
1117
        if (vec == null) return null;
1118
1119
        return new BlockHitResult(vec, bestDirection, bp, false);
1120
    }
1121
1122
    private void swingHand(boolean offHand, boolean attack) {
1123
        switch (swingMode.getValue()) {
1124
            case Both -> mc.player.swing(offHand ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND);
1125
            case Break -> {
1126
                if (attack) mc.player.swing(InteractionHand.MAIN_HAND);
1127
                else sendPacket(new ServerboundSwingPacket(InteractionHand.MAIN_HAND));
1128
1129
            }
1130
            case Place -> {
1131
                if (!attack) mc.player.swing(offHand ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND);
1132
                else sendPacket(new ServerboundSwingPacket(offHand ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND));
1133
            }
1134
        }
1135
    }
1136
1137
    public void predictAttack() {
1138
        for (int i = 1; i <= idAttacks.getValue(); i++) {
1139
            int id = (int) (currentId + i);
1140
            Entity entity = mc.level.getEntity(id);
1141
            if (entity == null || entity instanceof EndCrystal) {
1142
                sendPacket(new ServerboundAttackPacket(id));
1143
                sendPacket(new ServerboundSwingPacket(InteractionHand.MAIN_HAND));
1144
            }
1145
        }
1146
    }
1147
1148
    public static void changeId(ServerboundInteractPacket packet, int id) {
1149
        try {
1150
            Field field = ServerboundInteractPacket.class.getDeclaredField(FabricLoader.getInstance().isDevelopmentEnvironment() ? "entityId" : "field_12870");
1151
            field.setAccessible(true);
1152
            field.setInt(packet, id);
1153
        } catch (Exception ignored) {
1154
        }
1155
    }
1156
1157
    public void processSpawnPacket(int id) {
1158
        if (id > currentId) currentId = id;
1159
    }
1160
1161
    public PlaceData getCurrentData() {
1162
        return currentData;
1163
    }
1164
1165
    public long getCalcTime() {
1166
        return calcTime;
1167
    }
1168
1169
    public void pause() {
1170
        pauseTimer.reset();
1171
    }
1172
1173
    private int getPredictTicks() {
1174
        // TODO smart
1175
        return extrapolation.getValue();
1176
    }
1177
1178
    private int getSelfPredictTicks() {
1179
        // TESSSSSSSSSST
1180
1181
        // * 1.5 because after the calculation we will receive a response from the server in the form of a crystal appearing via ping,
1182
        // and then our attack will reach the server via ping / 2
1183
1184
        return (int) Math.ceil(((float) Managers.SERVER.getPing() * 1.5f) / 50f);
1185
    }
1186
1187
    public String getPauseState() {
1188
        return currentState.name();
1189
    }
1190
1191
    public record PlaceData(BlockHitResult bhr, float damage, float selfDamage, boolean overrideDamage) {
1192
    }
1193
1194
    private record CrystalData(EndCrystal crystal, float damage, float selfDamage, boolean overrideDamage) {
1195
    }
1196
1197
    private record RotationVec(Vec3 vec, BlockHitResult hitVec, boolean place) {
1198
    }
1199
1200
    private enum Pages {
1201
        Main, Place, Break, Damages, Pause, Render, Switch, FailSafe, Info, IDPredict
1202
    }
1203
1204
    private enum Switch {
1205
        NONE, NORMAL, SILENT, INVENTORY
1206
    }
1207
1208
    private enum Timing {
1209
        NORMAL, SEQUENTIAL
1210
    }
1211
1212
    private enum Interact {
1213
        Default, Strict
1214
    }
1215
1216
    public enum Sequential {
1217
        Off, Strict, Strong
1218
    }
1219
1220
    public enum Render {
1221
        Fade, Slide, Default
1222
    }
1223
1224
    public enum State {
1225
        Active, Eating, LowHP, NoTarget, NoCrystalls, ExternalPause, Mining
1226
    }
1227
1228
    public enum Rotation {
1229
        OFF(false, false), CC(false, true), NCP(false, false), GRIM(false, true), MATRIX(true, true);
1230
1231
        final boolean needSeparate;
1232
        final boolean vecMod;
1233
1234
        Rotation(boolean needSeparate, boolean vecMod) {
1235
            this.needSeparate = needSeparate;
1236
            this.vecMod = vecMod;
1237
        }
1238
1239
        public Vec3 getVector(BlockHitResult vec) {
1240
            return vecMod ? net.minecraft.world.phys.Vec3.atBottomCenterOf(vec.getBlockPos()).add(0, 0.475, 0) : vec.getLocation();
1241
        }
1242
1243
        public boolean needSeparate() {
1244
            return needSeparate;
1245
        }
1246
    }
1247
1248
    public enum Swing {
1249
        Both, Place, Break, ServerSide
1250
    }
1251
}
1252
CombatantCOMBATsrc/main/java/combatant/client/features/module/modules/combat/AutoCrystal.javaJava · 1,529 lines · 57.0 KB
SettingsautocrystalRenderautocrystalRenderModeautocrystalRenderSelfDamageautocrystalRenderDamageautocrystalPlaceautocrystalPlaceDelayautocrystalBreakautocrystalBreakDelayautocrystalPlaceRangeautocrystalPlacementModeautocrystalWallRangeautocrystalBreakRangeautocrystalBreakWallRangeautocrystalTargetsautocrystalPriorityautocrystalMinDamageautocrystalFaceplaceHealthautocrystalMaxSelfDamageautocrystalConfirmTimeautocrystalPredictTicksautocrystalSelfPredictTicksautocrystalIgnoreTerrainautocrystalAttackModeautocrystalMovementCorrectionautocrystalRotationResetTicksautocrystalRotationResetThresholdautocrystalFillColorautocrystalLineColorautocrystalLineWidthautocrystalTextColorautocrystalBillboardSizeautocrystalBillboardDynamicScaleautocrystalBillboardDynamicScaleCoefficientautocrystalSlideDelayautocrystalFadeTimeautocrystalRenderExtrapolationautocrystalExtrapolationColorautocrystalExtrapolationTicksautocrystalRenderInteractVectorautocrystalInteractColor
AutoCrystal.javaJava · Minecraft 26.2 · 1,529 lines · 57.0 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Combatant Client distribution.
3
 * Copyright (c) 2026 pivosos2007.
4
 *
5
 * Licensed under the GNU General Public License v3.0.
6
 */
7
8
package combatant.client.features.module.modules.combat;
9
10
import combatant.client.render.engine.text.BuiltinFontCatalog;
11
import combatant.client.config.values.*;
12
import combatant.client.features.module.modules.combat.autocrystal.*;
13
import net.minecraft.client.Minecraft;
14
import net.minecraft.client.multiplayer.ClientLevel;
15
import net.minecraft.client.player.LocalPlayer;
16
import net.minecraft.core.BlockPos;
17
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
18
import net.minecraft.util.Mth;
19
import net.minecraft.world.InteractionHand;
20
import net.minecraft.world.entity.Entity;
21
import net.minecraft.world.entity.LivingEntity;
22
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
23
import net.minecraft.world.level.block.Blocks;
24
import net.minecraft.world.phys.AABB;
25
import net.minecraft.world.phys.BlockHitResult;
26
import net.minecraft.world.phys.Vec3;
27
import combatant.client.config.common.CommonSettingSchemas;
28
import combatant.client.config.common.impl.TargetFilters;
29
import combatant.client.events.EventHandler;
30
import combatant.client.events.impl.PacketEvent;
31
import combatant.client.events.impl.RotationUpdateEvent;
32
import combatant.client.features.gui.clickgui.settings.FunctionBindSetting;
33
import combatant.client.features.module.Notifier;
34
import combatant.client.features.module.Module;
35
import combatant.client.features.module.ModuleCategory;
36
import combatant.client.features.module.ModuleInfo;
37
import combatant.client.features.module.WorldPhase;
38
import combatant.client.render.engine.RenderState;
39
import combatant.client.render.engine.color.RenderColor;
40
import combatant.client.render.engine.renderer.Renderer3D;
41
import combatant.client.render.engine.text.TextRenderer;
42
import combatant.client.render.engine.text.WorldTextRenderer;
43
import combatant.client.render.engine.world.WorldUiPresentationService;
44
import combatant.client.util.aiming.RestrictedSingleUseAction;
45
import combatant.client.util.aiming.RotationManager;
46
import combatant.client.util.aiming.RotationTarget;
47
import combatant.client.util.aiming.data.Rotation;
48
import combatant.client.util.aiming.data.RotationWithVector;
49
import combatant.client.util.aiming.features.MovementCorrection;
50
import combatant.client.util.aiming.raytrace.RotationRaytrace;
51
import combatant.client.util.combat.CombatRotationModeUtil;
52
import combatant.client.util.combat.CombatBlockUseUtil;
53
import combatant.client.util.combat.ExplosionRenderUtil;
54
import combatant.client.util.entity.simulation.PositionExtrapolation;
55
import combatant.client.util.player.inventory.InventorySwap;
56
import combatant.client.util.player.simulation.PlayerSimulationCache;
57
import combatant.client.util.target.TargetManager;
58
import combatant.client.util.target.TargetingUtil;
59
import java.util.ArrayList;
60
import java.util.List;
61
import java.util.Map;
62
import java.util.concurrent.ConcurrentHashMap;
63
64
//todo Description
65
@ModuleInfo(
66
        id = "autocrystal",
67
        displayName = "AutoCrystal",
68
        aliases = "CrystalAura",
69
        category = ModuleCategory.COMBAT
70
)
71
public class AutoCrystal extends Module {
72
73
    private static final int ROTATION_PRIORITY = 35;
74
    private static final int HOTBAR_RESET_TICKS = 2;
75
    private static final String ACTION_BASE = "base";
76
77
    private static final double INTERACT_MARKER_RADIUS = 0.05;
78
    private static final long DAMAGE_RESET_MS = 1000L;
79
    private static final int BASE_HOTBAR_RESET_TICKS = 2;
80
    private static final float BASE_INITIATIVE_MIN_DAMAGE = 1.5f;
81
    private static final double TEXT_Y_OFFSET = 0.10;
82
    private static final double TEXT_WORLD_SCALE = 0.025;
83
    private static final double TEXT_SCALE = 1.0;
84
    private static final double TEXT_GAP_SCALE = 1.0;
85
    private static final double TARGET_SEARCH_RANGE = 12.0;
86
87
    private final Minecraft mc = Minecraft.getInstance();
88
89
    private final BooleanValue renderEnabled =
90
            boolCommon(
91
                    "autocrystalRender",
92
                    "render",
93
                    CommonSettingSchemas.PLACEMENT_RENDER,
94
                    true
95
            );
96
    private final EnumValue<RenderMode> renderMode =
97
            enumCommon(
98
                    "autocrystalRenderMode",
99
                    "render_mode",
100
                    CommonSettingSchemas.PLACEMENT_RENDER_MODE,
101
                    RenderMode.FADE,
102
                    RenderMode.values()
103
            );
104
    private final BooleanValue renderSelfDamage = boolCommon("autocrystalRenderSelfDamage", CommonSettingSchemas.RENDER_SELF_DAMAGE, true);
105
    private final BooleanValue drawDamage = boolCommon("autocrystalRenderDamage", CommonSettingSchemas.RENDER_DAMAGE, true);
106
    private final BooleanValue placeEnabled = boolCommon("autocrystalPlace", CommonSettingSchemas.PLACE, true);
107
    private final NumberValue<Integer> placeDelay =
108
            visibleWhen(numCommon(
109
                    "autocrystalPlaceDelay",
110
                    "place_delay",
111
                    CommonSettingSchemas.PLACEMENT_DELAY,
112
                    0,
113
                    0,
114
                    1000
115
            ), placeEnabled::get);
116
    private final BooleanValue breakEnabled = boolCommon("autocrystalBreak", CommonSettingSchemas.BREAK, true);
117
    private final NumberValue<Integer> breakDelay =
118
            visibleWhen(numCommon(
119
                    "autocrystalBreakDelay",
120
                    "break_delay",
121
                    CommonSettingSchemas.PLACEMENT_BREAK_DELAY,
122
                    0,
123
                    0,
124
                    1000
125
            ), breakEnabled::get);
126
    private final NumberValue<Float> placeRange =
127
            numCommon(
128
                    "autocrystalPlaceRange",
129
                    "place_range",
130
                    CommonSettingSchemas.PLACEMENT_RANGE,
131
                    5.0f,
132
                    1.0f,
133
                    6.0f
134
            );
135
    private final EnumValue<AutoCrystalPlacementMode> placementMode =
136
            visibleWhen(enumCommon(
137
                    "autocrystalPlacementMode",
138
                    "placement_mode",
139
                    CommonSettingSchemas.PLACEMENT_MODE,
140
                    AutoCrystalPlacementMode.DEFAULT,
141
                    AutoCrystalPlacementMode.values()
142
            ), placeEnabled::get);
143
    private final NumberValue<Float> wallRange =
144
            visibleWhen(numCommon(
145
                    "autocrystalWallRange",
146
                    "wall_range",
147
                    CommonSettingSchemas.PLACEMENT_WALL_RANGE,
148
                    5.0f,
149
                    0.0f,
150
                    6.0f
151
            ), () -> placeEnabled.get() && placementMode.get() == AutoCrystalPlacementMode.DEFAULT);
152
    private final NumberValue<Float> breakRange =
153
            numCommon(
154
                    "autocrystalBreakRange",
155
                    "break_range",
156
                    CommonSettingSchemas.PLACEMENT_BREAK_RANGE,
157
                    5.0f,
158
                    1.0f,
159
                    6.0f
160
            );
161
    private final NumberValue<Float> breakWallRange =
162
            numCommon(
163
                    "autocrystalBreakWallRange",
164
                    "break_wall_range",
165
                    CommonSettingSchemas.PLACEMENT_BREAK_WALL_RANGE,
166
                    5.0f,
167
                    0.0f,
168
                    6.0f
169
            );
170
    private final BooleanMapValue targetToggles = groupCommon(
171
            "autocrystalTargets",
172
            "targets",
173
            CommonSettingSchemas.TARGET_FILTERS
174
    );
175
    private final EnumValue<TargetingUtil.TargetPriority> priority =
176
            enumCommon(
177
                    "autocrystalPriority",
178
                    "priority",
179
                    CommonSettingSchemas.COMBAT_PRIORITY,
180
                    TargetingUtil.TargetPriority.DISTANCE,
181
                    TargetingUtil.TargetPriority.values()
182
            );
183
    private final NumberValue<Float> minDamage =
184
            numCommon("autocrystalMinDamage", CommonSettingSchemas.MIN_DAMAGE, 4.0f, 0.0f, 36.0f);
185
    private final NumberValue<Float> faceplaceHealth =
186
            numCommon("autocrystalFaceplaceHealth", CommonSettingSchemas.FACEPLACE_HEALTH, 10.0f, 0.0f, 36.0f);
187
    private final NumberValue<Float> maxSelfDamage =
188
            numCommon("autocrystalMaxSelfDamage", CommonSettingSchemas.MAX_SELF_DAMAGE, 8.0f, 0.0f, 36.0f);
189
    private final NumberValue<Integer> confirmTime =
190
            visibleWhen(num("autocrystalConfirmTime", 150, 10, 2000), placeEnabled::get);
191
    private final NumberValue<Integer> predictTicks =
192
            numCommon("autocrystalPredictTicks", CommonSettingSchemas.PLACEMENT_PREDICTION, 0, 0, 20);
193
    private final NumberValue<Integer> selfPredictTicks =
194
            numCommon("autocrystalSelfPredictTicks", CommonSettingSchemas.SELF_PREDICT_TICKS, 0, 0, 20);
195
    private final BooleanValue ignoreTerrain =
196
            bool("autocrystalIgnoreTerrain", true);
197
    private final ModeValue attackMode =
198
            modeCommon(
199
                    "autocrystalAttackMode",
200
                    "attack_mode",
201
                    CommonSettingSchemas.COMBAT_ATTACK_MODE,
202
                    CombatRotationModeUtil.MODE_ROTATIONS,
203
                    CombatRotationModeUtil.MODE_ROTATIONS,
204
                    CombatRotationModeUtil.MODE_NO_ROTATIONS
205
            );
206
    private final EnumValue<MovementCorrection> movementCorrection =
207
            visibleWhen(enumCommon(
208
                    "autocrystalMovementCorrection",
209
                    "movement_correction",
210
                    CommonSettingSchemas.PLACEMENT_MOVEMENT_CORRECTION,
211
                    MovementCorrection.SILENT,
212
                    MovementCorrection.values()
213
            ), () -> placeEnabled.get() && usesRotationSettings());
214
    private final NumberValue<Integer> rotationResetTicks =
215
            visibleWhen(numCommon(
216
                    "autocrystalRotationResetTicks",
217
                    "rotation_reset_ticks",
218
                    CommonSettingSchemas.ROTATION_RESET_TICKS,
219
                    1,
220
                    1,
221
                    20
222
            ), () -> placeEnabled.get() && usesRotationSettings());
223
    private final NumberValue<Float> rotationResetThreshold =
224
            visibleWhen(numCommon(
225
                    "autocrystalRotationResetThreshold",
226
                    "rotation_reset_threshold",
227
                    CommonSettingSchemas.ROTATION_RESET_THRESHOLD,
228
                    2.0f,
229
                    0.1f,
230
                    15.0f
231
            ), () -> placeEnabled.get() && usesRotationSettings());
232
    private final RGBAColorValue fillColor =
233
            common(color("autocrystalFillColor", "#285A9CFF"), CommonSettingSchemas.FILL_COLOR);
234
    private final RGBAColorValue lineColor =
235
            common(color("autocrystalLineColor", "#FF9BE4FF"), CommonSettingSchemas.LINE_COLOR);
236
    private final NumberValue<Float> lineWidth =
237
            numCommon("autocrystalLineWidth", CommonSettingSchemas.LINE_WIDTH, 2.0f, 1.0f, 6.0f);
238
    private final RGBAColorValue textColor =
239
            common(color("autocrystalTextColor", "#FFFFFFFF"), CommonSettingSchemas.TEXT_COLOR);
240
    private final NumberValue<Float> billboardSize = visibleWhen(numCommon(
241
            "autocrystalBillboardSize", "billboard_size", CommonSettingSchemas.BILLBOARD_SIZE, 0.72f, 0.35f, 1.50f),
242
            drawDamage::get);
243
    private final BooleanValue billboardDynamicScale = visibleWhen(boolCommon(
244
            "autocrystalBillboardDynamicScale", "billboard_dynamic_scale", CommonSettingSchemas.BILLBOARD_DYNAMIC_SCALE, true),
245
            drawDamage::get);
246
    private final NumberValue<Float> billboardDynamicScaleCoefficient = visibleWhen(numCommon(
247
            "autocrystalBillboardDynamicScaleCoefficient", "billboard_dynamic_scale_coefficient",
248
            CommonSettingSchemas.BILLBOARD_DYNAMIC_SCALE_COEFFICIENT, 0.25f, 0.0f, 1.0f),
249
            () -> drawDamage.get() && billboardDynamicScale.get());
250
    private final NumberValue<Integer> slideDelay =
251
            visibleWhen(numCommon("autocrystalSlideDelay", CommonSettingSchemas.SLIDE_DELAY, 200, 1, 1000),
252
                    () -> renderMode.get() == RenderMode.SLIDE);
253
    private final NumberValue<Integer> fadeTime =
254
            visibleWhen(numCommon("autocrystalFadeTime", CommonSettingSchemas.FADE_TIME, 500, 100, 2000),
255
                    () -> renderMode.get() == RenderMode.FADE);
256
    private final BooleanValue extrapolationEnabled =
257
            bool("autocrystalRenderExtrapolation", false);
258
    private final RGBAColorValue extrapolationColor =
259
            visibleWhen(color("autocrystalExtrapolationColor", "#FFFFFFFF"), extrapolationEnabled::get);
260
    private final NumberValue<Float> extrapolationTicks =
261
            visibleWhen(num("autocrystalExtrapolationTicks", 1.0f, 0.0f, 20.0f),
262
                    extrapolationEnabled::get);
263
    private final BooleanValue interactEnabled =
264
            bool("autocrystalRenderInteractVector", true);
265
    private final RGBAColorValue interactColor =
266
            visibleWhen(color("autocrystalInteractColor", "#FFFF5555"), interactEnabled::get);
267
    private final FunctionBindSetting baseToggle =
268
            action(ACTION_BASE, "NONE", BindMode.PRESS)
269
                    .hudLabel("AutoCrystalBase")
270
                    .hudToggle(this::isBaseActive);
271
    private final NumberValue<Float> baseMinDamageDelta =
272
            numCommon("autocrystalBaseMinDamageDelta", "base_min_damage_delta", CommonSettingSchemas.MIN_DAMAGE, 5.0f, 0.0f, 20.0f);
273
    private final NumberValue<Integer> basePlaceDelay =
274
            numCommon("autocrystalBasePlaceDelay", "base_place_delay", CommonSettingSchemas.PLACEMENT_DELAY, 0, 0, 3000);
275
    private final NumberValue<Integer> baseCalcDelay =
276
            numCommon("autocrystalBaseCalcDelay", "base_calc_delay", CommonSettingSchemas.CALC_DELAY, 50, 0, 3000);
277
    private final BooleanValue baseNotify =
278
            bool("autocrystalBaseNotify", "base_notify", true);
279
    private final BooleanValue baseDisableNoObby =
280
            bool("autocrystalBaseDisableNoObby", "base_disable_no_obby", false);
281
282
    private final AutoCrystalBasePlanner basePlanner = new AutoCrystalBasePlanner();
283
    private final AutoCrystalBaseContext baseContext = new AutoCrystalBaseContext();
284
    private final AutoCrystalPlacementPlanner placementPlanner = new AutoCrystalPlacementPlanner();
285
    private final AutoCrystalPlacementPlanner.Context placementContext = new AutoCrystalPlacementContext();
286
    private final Map<BlockPos, Long> renderPositions = new ConcurrentHashMap<>();
287
    private final AutoCrystalTracker crystalTracker = new AutoCrystalTracker();
288
    private final AutoCrystalEntityBlocker entityBlocker = new AutoCrystalEntityBlocker();
289
290
    private LivingEntity target;
291
    private AutoCrystalPlaceData bestCandidate;
292
    private AutoCrystalCrystalData bestCrystal;
293
    private EndCrystal secondaryCrystal;
294
    private AutoCrystalPlaceData currentData;
295
    private AutoCrystalBasePlanner.BaseData bestBaseCandidate;
296
    private BlockPos renderPos;
297
    private BlockPos prevRenderPos;
298
    private BlockPos bestPosition;
299
    private Vec3 interactVector;
300
    private int renderTick;
301
    private int renderStartTick;
302
    private long lastDamageUpdateMs;
303
    private long lastPlaceMs;
304
    private long lastBreakMs;
305
    private long lastBaseCalcMs;
306
    private long lastBasePlaceMs;
307
    private float renderDamage;
308
    private float renderSelfDamageValue;
309
    private boolean baseActive;
310
    private long lastDebugStateLogMs;
311
    private int lastPlaceCandidateCount;
312
    private int lastPlaceSafeCount;
313
    private int lastBreakCandidateCount;
314
    private int lastBreakSafeCount;
315
    private int lastPlaceSelfDamageRejectCount;
316
    private int lastBreakSelfDamageRejectCount;
317
    private int lastBaseCandidateCount;
318
    private int lastBaseScannedCount;
319
    private int lastBaseSafeCount;
320
    private int lastBaseWorthCount;
321
    private int lastBaseDeltaCount;
322
323
    private static void debugLog(String pattern, Object... args) {
324
        // if (!DebugLog.isEnabled()) {
325
        //     return;
326
        // }
327
    }
328
329
    @Override
330
    public WorldPhase getWorldPhase() {
331
        return WorldPhase.AFTER_POST_PROCESS;
332
    }
333
334
    @Override
335
    public void onEnable() {
336
        resetVisualState();
337
    }
338
339
    @Override
340
    public void onDisable() {
341
        resetVisualState();
342
        RotationManager.INSTANCE.clear(this);
343
        InventorySwap.INSTANCE.releaseHotbar(this);
344
        TargetManager.setAutoCrystalTarget(null);
345
    }
346
347
    @Override
348
    public void onTick() {
349
        if (!isEnabled()) return;
350
        renderTick++;
351
        if (isActionPressedOnce(ACTION_BASE)) {
352
            baseActive = !baseActive;
353
            bestBaseCandidate = null;
354
            Notifier.state("AutoCrystalBase", baseActive);
355
        }
356
        InventorySwap.INSTANCE.tick();
357
        if (isBaseActive() && baseDisableNoObby.get() && mc.player != null && findObsidianHand(mc.player) == null) {
358
            Notifier.warning("AutoCrystalBase: no obsidian");
359
            baseActive = false;
360
            bestBaseCandidate = null;
361
            return;
362
        }
363
        crystalTracker.tick(mc);
364
        purgeExpiredRenderPositions();
365
        if (System.currentTimeMillis() - lastDamageUpdateMs > DAMAGE_RESET_MS && renderPositions.isEmpty()) {
366
            renderDamage = 0.0f;
367
            renderSelfDamageValue = 0.0f;
368
        }
369
    }
370
371
    @EventHandler
372
    private void onPacketReceivePost(PacketEvent.ReceivePost event) {
373
        if (!isEnabled() || mc.level == null) {
374
            return;
375
        }
376
377
        if (event.getPacket() instanceof ClientboundAddEntityPacket spawn) {
378
            if (spawn.getType() != net.minecraft.world.entity.EntityTypes.END_CRYSTAL) {
379
                return;
380
            }
381
382
            var entity = mc.level.getEntity(spawn.getId());
383
            if (entity instanceof EndCrystal crystal) {
384
                crystalTracker.removeAwaitingPositionsNear(crystal);
385
            }
386
        }
387
    }
388
389
    @EventHandler(priority = 25)
390
    private void onRotationUpdate(RotationUpdateEvent event) {
391
        if (event.getType() != RotationUpdateEvent.Type.PRE) {
392
            return;
393
        }
394
395
        if (!isEnabled()) return;
396
        if (mc.player == null || mc.level == null || mc.gameMode == null) {
397
            clearPlacementState();
398
            TargetManager.setAutoCrystalTarget(null);
399
            return;
400
        }
401
402
        target = findCombatTarget();
403
        TargetManager.setAutoCrystalTarget(target);
404
        updateBestPosition();
405
        updateBestCrystal();
406
        updateBestBasePosition();
407
        debugState();
408
409
        if (tryBreakCrystal()) {
410
            return;
411
        }
412
413
        if (tryPlaceBase()) {
414
            return;
415
        }
416
417
        if (!placeEnabled.get()) {
418
            RotationManager.INSTANCE.clear(this);
419
            return;
420
        }
421
422
        AutoCrystalPlaceData candidate = bestCandidate;
423
        if (candidate == null) {
424
            RotationManager.INSTANCE.clear(this);
425
            return;
426
        }
427
428
        if (!hasPlaceDelayElapsed()) {
429
            return;
430
        }
431
432
        AutoCrystalHand crystalHand = findCrystalHand(mc.player);
433
        if (crystalHand == null) {
434
            return;
435
        }
436
437
        if (!usesRotationSettings()) {
438
            RotationManager.INSTANCE.clear(this);
439
            tryPlaceCrystal(candidate.pos());
440
            return;
441
        }
442
443
        BlockHitResult bestHitResult = candidate.bhr();
444
        if (bestHitResult == null) {
445
            return;
446
        }
447
448
        RotationTarget rotationTarget = new RotationTarget(
449
                Rotation.lookingAt(bestHitResult.getLocation(), mc.player.getEyePosition()).normalize(),
450
                target,
451
                List.of(),
452
                rotationResetTicks.get(),
453
                rotationResetThreshold.get(),
454
                true,
455
                movementCorrection.get(),
456
                new RestrictedSingleUseAction(() -> tryPlaceCrystal(candidate.pos()))
457
        );
458
        RotationManager.INSTANCE.setRotationTarget(rotationTarget, ROTATION_PRIORITY, this);
459
    }
460
461
    @Override
462
    public void onRenderWorldEngine(Renderer3D renderer, Renderer3D depthRenderer, float tickDelta) {
463
        if (!isEnabled() || mc.player == null || mc.level == null) return;
464
465
        if (renderEnabled.get()) {
466
            renderPlacement(renderer, tickDelta);
467
        }
468
469
        if (extrapolationEnabled.get() && target != null) {
470
            renderExtrapolation(renderer, target);
471
        }
472
473
        if (interactEnabled.get() && interactVector != null) {
474
            renderInteractVector(renderer, interactVector, interactColor.getArgb());
475
        }
476
    }
477
478
    public void setRenderCandidate(BlockPos pos, float damage, float selfDamage, Vec3 interactVec) {
479
        bestPosition = pos;
480
        interactVector = interactVec;
481
        renderDamage = Math.max(0.0f, damage);
482
        renderSelfDamageValue = Math.max(0.0f, selfDamage);
483
        lastDamageUpdateMs = System.currentTimeMillis();
484
    }
485
486
    public void clearRenderCandidate() {
487
        bestCandidate = null;
488
        currentData = null;
489
        bestPosition = null;
490
        interactVector = null;
491
        if (renderPositions.isEmpty()) {
492
            renderDamage = 0.0f;
493
            renderSelfDamageValue = 0.0f;
494
            renderPos = null;
495
            prevRenderPos = null;
496
        }
497
    }
498
499
    public void markPlaced(BlockPos pos) {
500
        if (pos == null) return;
501
        long now = System.currentTimeMillis();
502
        if (!pos.equals(renderPos)) {
503
            renderStartTick = renderTick;
504
            prevRenderPos = renderPos;
505
            renderPos = pos;
506
        }
507
        renderPositions.put(pos, now);
508
        lastDamageUpdateMs = now;
509
    }
510
511
    public void markPlaced(BlockPos pos, float damage, float selfDamage, Vec3 interactVec) {
512
        setRenderCandidate(pos, damage, selfDamage, interactVec);
513
        markPlaced(pos);
514
    }
515
516
    private void renderPlacement(Renderer3D renderer, float tickDelta) {
517
        String damageText = buildDamageText();
518
        if (damageText.isEmpty() && renderPositions.isEmpty() && renderPos == null) {
519
            return;
520
        }
521
522
        if (renderMode.get() == RenderMode.FADE) {
523
            renderFade(renderer);
524
            return;
525
        }
526
527
        BlockPos activePos = renderPositions.isEmpty() ? bestPosition : renderPos;
528
        if (activePos == null) {
529
            return;
530
        }
531
532
        if (renderMode.get() == RenderMode.SLIDE) {
533
            BlockPos slideTo = renderPositions.isEmpty() ? bestPosition : renderPos;
534
            BlockPos from = prevRenderPos != null ? prevRenderPos : slideTo;
535
            renderBox(renderer, ExplosionRenderUtil.lerpBox(new AABB(from), new AABB(slideTo), getSlideProgress(tickDelta)), 1.0f);
536
        } else {
537
            renderBox(renderer, new AABB(activePos), 1.0f);
538
        }
539
    }
540
541
542
    private float getSlideProgress(float tickDelta) {
543
        float clampedTickDelta = Mth.clamp(tickDelta, 0.0f, 1.0f);
544
        float durationTicks = Math.max(1.0f, slideDelay.get() / 50.0f);
545
        return Mth.clamp((renderTick - renderStartTick + clampedTickDelta) / durationTicks, 0.0f, 1.0f);
546
    }
547
548
    private void renderFade(Renderer3D renderer) {
549
        long now = System.currentTimeMillis();
550
        int lifetime = Math.max(1, fadeTime.get());
551
        List<Map.Entry<BlockPos, Long>> entries = new ArrayList<>(renderPositions.entrySet());
552
        for (Map.Entry<BlockPos, Long> entry : entries) {
553
            long age = now - entry.getValue();
554
            if (age > lifetime) {
555
                renderPositions.remove(entry.getKey());
556
                continue;
557
            }
558
559
            float alpha = 1.0f - (age / (float) lifetime);
560
            renderBox(renderer, new AABB(entry.getKey()), alpha);
561
        }
562
    }
563
564
    private void renderBox(Renderer3D renderer, AABB box, float alpha) {
565
        int fillArgb = ExplosionRenderUtil.applyOpacity(fillColor.getArgb(), alpha);
566
        int lineArgb = ExplosionRenderUtil.applyOpacity(lineColor.getArgb(), alpha);
567
568
        ExplosionRenderUtil.addFilledBox(renderer, box, fillArgb);
569
570
        float prevWidth = RenderState.lineWidth;
571
        RenderState.lineWidth = Math.max(0.5f, lineWidth.get());
572
        try {
573
            ExplosionRenderUtil.addOutlineBox(renderer, box, lineArgb);
574
        } finally {
575
            RenderState.lineWidth = prevWidth;
576
        }
577
578
        if (drawDamage.get()) {
579
            renderDamageText(renderer, box.getCenter(), alpha);
580
        }
581
    }
582
583
    private void renderDamageText(Renderer3D renderer, Vec3 anchor, float alpha) {
584
        double billboardWorldScale = resolveDamageBillboardScale(anchor);
585
        String mainText = ExplosionRenderUtil.formatDamage(renderDamage);
586
        if (mainText.isEmpty()) return;
587
588
        int mainArgb = ExplosionRenderUtil.applyOpacity(textColor.getArgb(), alpha);
589
        TextRenderer bold = BuiltinFontCatalog.IOSEVKA_BOLD.renderer(TextRenderer.get());
590
        WorldTextRenderer.Options baseOptions = WorldTextRenderer.Options.defaults()
591
                .withScale(TEXT_SCALE)
592
                .withWorldScale(billboardWorldScale)
593
                .withDepthMode(Renderer3D.DepthMode.NONE)
594
                .withShadow(true)
595
                .withOffset(0.0, TEXT_Y_OFFSET);
596
597
        if (!renderSelfDamage.get()) {
598
            WorldTextRenderer.drawBillboard(
599
                    renderer,
600
                    bold,
601
                    mainText,
602
                    anchor,
603
                    baseOptions.withCentered(true).withColor(new RenderColor(mainArgb))
604
            );
605
            return;
606
        }
607
608
        String tailText = " / " + ExplosionRenderUtil.formatDamage(renderSelfDamageValue);
609
        if (renderSelfDamageValue <= 0.0f) {
610
            WorldTextRenderer.drawBillboard(
611
                    renderer,
612
                    bold,
613
                    mainText,
614
                    anchor,
615
                    baseOptions.withCentered(true).withColor(new RenderColor(mainArgb))
616
            );
617
            return;
618
        }
619
620
        TextRenderer medium = BuiltinFontCatalog.IOSEVKA_REGULAR.renderer(TextRenderer.get());
621
        double mainWidth = ExplosionRenderUtil.measureWidth(bold, mainText, TEXT_SCALE);
622
        double tailWidth = ExplosionRenderUtil.measureWidth(medium, tailText, TEXT_GAP_SCALE);
623
        double startX = -(mainWidth + tailWidth) * 0.5;
624
625
        double drawnMain = WorldTextRenderer.drawBillboard(
626
                renderer,
627
                bold,
628
                mainText,
629
                anchor,
630
                baseOptions.withCentered(false)
631
                        .withOffset(startX, TEXT_Y_OFFSET)
632
                        .withColor(new RenderColor(mainArgb))
633
        );
634
635
        WorldTextRenderer.drawBillboard(
636
                renderer,
637
                medium,
638
                tailText,
639
                anchor,
640
                baseOptions.withCentered(false)
641
                        .withScale(TEXT_GAP_SCALE)
642
                        .withOffset(startX + drawnMain, TEXT_Y_OFFSET)
643
                        .withColor(new RenderColor(mainArgb))
644
        );
645
    }
646
647
    private void renderExtrapolation(Renderer3D renderer, LivingEntity living) {
648
        AABB box = PositionExtrapolation.getBestForEntity(living).getBoxInTicks(extrapolationTicks.get());
649
        int argb = extrapolationColor.getArgb();
650
        float prevWidth = RenderState.lineWidth;
651
        RenderState.lineWidth = 1.0f;
652
        try {
653
            ExplosionRenderUtil.addOutlineBox(renderer, box, argb);
654
        } finally {
655
            RenderState.lineWidth = prevWidth;
656
        }
657
    }
658
659
    private void renderInteractVector(Renderer3D renderer, Vec3 vec, int argb) {
660
        AABB box = new AABB(
661
                vec.x - INTERACT_MARKER_RADIUS,
662
                vec.y - INTERACT_MARKER_RADIUS,
663
                vec.z - INTERACT_MARKER_RADIUS,
664
                vec.x + INTERACT_MARKER_RADIUS,
665
                vec.y + INTERACT_MARKER_RADIUS,
666
                vec.z + INTERACT_MARKER_RADIUS
667
        );
668
        ExplosionRenderUtil.addFilledBox(renderer, box, ExplosionRenderUtil.applyOpacity(argb, 0.6f));
669
670
        float prevWidth = RenderState.lineWidth;
671
        RenderState.lineWidth = 1.0f;
672
        try {
673
            ExplosionRenderUtil.addOutlineBox(renderer, box, argb);
674
        } finally {
675
            RenderState.lineWidth = prevWidth;
676
        }
677
    }
678
679
    private double resolveDamageBillboardScale(Vec3 anchor) {
680
        double distance = RenderState.cameraPos != null ? RenderState.cameraPos.distanceTo(anchor) : 0.0;
681
        return WorldUiPresentationService.resolveWorldScale(
682
                TEXT_WORLD_SCALE,
683
                distance,
684
                12.0,
685
                4.0,
686
                billboardSize.get(),
687
                billboardDynamicScale.get(),
688
                billboardDynamicScaleCoefficient.get()
689
        );
690
    }
691
692
    private void purgeExpiredRenderPositions() {
693
        long now = System.currentTimeMillis();
694
        long lifetime = Math.max(1, fadeTime.get());
695
        renderPositions.entrySet().removeIf(entry -> now - entry.getValue() > lifetime);
696
    }
697
698
    private void updateBestPosition() {
699
        if (mc.player == null || mc.level == null || target == null) {
700
            clearRenderCandidate();
701
            currentData = null;
702
            return;
703
        }
704
705
        AutoCrystalPlacementPlanner.PlaceScanResult result = placementPlanner.findBestPlace(
706
                placementContext,
707
                target,
708
                mc.player.position(),
709
                Mth.ceil(placeRange.get())
710
        );
711
        lastPlaceCandidateCount = result.scannedCandidates();
712
        lastPlaceSelfDamageRejectCount = result.selfDamageRejects();
713
        lastPlaceSafeCount = result.safeCandidates();
714
        debugLog("place-candidates total=%d scan=%s", result.safeCandidates(), result.debug());
715
716
        AutoCrystalPlaceData best = result.best();
717
        if (best == null) {
718
            clearRenderCandidate();
719
            currentData = null;
720
            return;
721
        }
722
723
        bestCandidate = best;
724
        currentData = best;
725
        setRenderCandidate(best.pos(), best.damage(), best.selfDamage(), best.bhr().getLocation());
726
    }
727
728
    private void updateBestBasePosition() {
729
        if (!isBaseActive() || !placeEnabled.get() || mc.player == null || mc.level == null || target == null) {
730
            bestBaseCandidate = null;
731
            lastBaseCandidateCount = 0;
732
            return;
733
        }
734
735
        long now = System.currentTimeMillis();
736
        if (now - lastBaseCalcMs < Math.max(0, baseCalcDelay.get())) {
737
            return;
738
        }
739
        lastBaseCalcMs = now;
740
741
        if (findObsidianHand(mc.player) == null) {
742
            bestBaseCandidate = null;
743
            lastBaseCandidateCount = 0;
744
            return;
745
        }
746
747
        bestBaseCandidate = basePlanner.findBest(
748
                baseContext,
749
                target,
750
                List.of(target.position()),
751
                Mth.ceil(placeRange.get()),
752
                baseMinDamageDelta.get()
753
        );
754
        lastBaseScannedCount = basePlanner.lastScanned();
755
        lastBaseCandidateCount = basePlanner.lastCandidates();
756
        lastBaseSafeCount = basePlanner.lastSafeCandidates();
757
        lastBaseWorthCount = basePlanner.lastWorthCandidates();
758
        lastBaseDeltaCount = basePlanner.lastDeltaCandidates();
759
    }
760
761
    private AutoCrystalBasePlanner.BaseData getBasePlaceData(BlockPos pos, LivingEntity currentTarget) {
762
        return AutoCrystalBaseEvaluator.getBaseData(baseContext, pos, currentTarget);
763
    }
764
765
    private boolean canEvaluateBaseAt(BlockPos pos) {
766
        return AutoCrystalBaseEvaluator.canEvaluateBaseAt(mc.level, pos);
767
    }
768
769
    private void updateBestCrystal() {
770
        if (mc.player == null || mc.level == null || target == null) {
771
            bestCrystal = null;
772
            secondaryCrystal = null;
773
            return;
774
        }
775
776
        if (secondaryCrystal != null) {
777
            if (canAttackCrystal(secondaryCrystal)) {
778
                AutoCrystalCrystalData crystalData = placementPlanner.evaluateCrystal(placementContext, target, secondaryCrystal);
779
                bestCrystal = crystalData;
780
                if (crystalData != null) {
781
                    renderDamage = crystalData.damage();
782
                    renderSelfDamageValue = crystalData.selfDamage();
783
                }
784
                lastBreakCandidateCount = crystalData != null ? 1 : 0;
785
                lastBreakSelfDamageRejectCount = crystalData != null
786
                        && crystalData.selfDamage() > maxSelfDamage.get()
787
                        && !crystalData.overrideDamage() ? 1 : 0;
788
                lastBreakSafeCount = crystalData != null
789
                        && isSafe(crystalData.damage(), crystalData.selfDamage(), crystalData.overrideDamage()) ? 1 : 0;
790
            } else {
791
                bestCrystal = null;
792
                lastBreakCandidateCount = 0;
793
                lastBreakSafeCount = 0;
794
                lastBreakSelfDamageRejectCount = 0;
795
            }
796
            secondaryCrystal = null;
797
            debugLog("break-candidates total=%d", bestCrystal != null ? 1 : 0);
798
            return;
799
        }
800
801
        AutoCrystalPlacementPlanner.BreakScanResult result = placementPlanner.findBestCrystal(placementContext, target);
802
        bestCrystal = result.best();
803
        if (bestCrystal != null) {
804
            renderDamage = bestCrystal.damage();
805
            renderSelfDamageValue = bestCrystal.selfDamage();
806
        }
807
        lastBreakCandidateCount = result.scannedCandidates();
808
        lastBreakSafeCount = result.safeCandidates();
809
        debugLog("break-candidates total=%d", result.safeCandidates());
810
    }
811
812
    private AutoCrystalPlaceValidationResult validatePlaceCrystal(BlockPos pos, boolean calcPhase) {
813
        if (mc.level == null) {
814
            return AutoCrystalPlaceValidationResult.INVALID_BASE;
815
        }
816
817
        var state = mc.level.getBlockState(pos);
818
        if (!state.is(Blocks.OBSIDIAN) && !state.is(Blocks.BEDROCK)) {
819
            return AutoCrystalPlaceValidationResult.INVALID_BASE;
820
        }
821
822
        if (!mc.level.isEmptyBlock(pos.above())) {
823
            return AutoCrystalPlaceValidationResult.BLOCKED_AIR;
824
        }
825
826
        if (isPositionBlockedByEntity(pos, calcPhase)) {
827
            return AutoCrystalPlaceValidationResult.BLOCKED_ENTITY;
828
        }
829
830
        return AutoCrystalPlaceValidationResult.OK;
831
    }
832
833
834
    private boolean isPositionBlockedByEntity(BlockPos pos, boolean calcPhase) {
835
        AutoCrystalEntityBlocker.Result result = entityBlocker.check(
836
                mc.level,
837
                mc.player,
838
                pos,
839
                calcPhase,
840
                this::isDeadCrystal,
841
                this::isCrystalBlocked,
842
                this::canAttackCrystal
843
        );
844
        if (result.secondaryCrystal() != null) {
845
            secondaryCrystal = result.secondaryCrystal();
846
        }
847
        return result.blocked();
848
    }
849
850
    private boolean canAttackCrystal(EndCrystal crystal) {
851
        return placementPlanner.canAttackCrystal(placementContext, target, crystal);
852
    }
853
854
    private boolean shouldOverrideMinDamage(LivingEntity currentTarget, float damage) {
855
        return AutoCrystalDamageRules.shouldOverrideMinDamage(currentTarget, damage, faceplaceHealth.get());
856
    }
857
858
    private boolean shouldOverrideMaxSelfDamage(float damage, float selfDamage) {
859
        return AutoCrystalDamageRules.shouldOverrideMaxSelfDamage(
860
                mc.player,
861
                target,
862
                damage,
863
                selfDamage,
864
                maxSelfDamage.get()
865
        );
866
    }
867
868
    private boolean isSafe(float damage, float selfDamage, boolean overrideDamage) {
869
        return AutoCrystalDamageRules.isSafe(mc.player, selfDamage, overrideDamage);
870
    }
871
872
    private boolean tryBreakCrystal() {
873
        if (!breakEnabled.get() || !hasBreakDelayElapsed() || mc.player == null) {
874
            return false;
875
        }
876
877
        AutoCrystalCrystalData candidate = bestCrystal;
878
        if (candidate == null || candidate.crystal() == null || !candidate.crystal().isAlive()) {
879
            debugLog("break-skip reason=no-candidate");
880
            return false;
881
        }
882
883
        EndCrystal crystal = candidate.crystal();
884
        if (!usesRotationSettings()) {
885
            RotationManager.INSTANCE.clear(this);
886
            attackCrystal(crystal, null);
887
            return true;
888
        }
889
890
        RotationWithVector rotation = RotationRaytrace.raytraceBox(
891
                mc.player.getEyePosition(),
892
                crystal.getBoundingBox(),
893
                breakRange.get(),
894
                breakWallRange.get()
895
        );
896
        if (rotation == null) {
897
            rotation = new RotationWithVector(
898
                    Rotation.lookingAt(crystal.position(), mc.player.getEyePosition()).normalize(),
899
                    crystal.position()
900
            );
901
        }
902
903
        Rotation attackRotation = rotation.rotation().normalize();
904
        RotationTarget rotationTarget = new RotationTarget(
905
                attackRotation,
906
                crystal,
907
                List.of(),
908
                rotationResetTicks.get(),
909
                rotationResetThreshold.get(),
910
                true,
911
                movementCorrection.get(),
912
                new RestrictedSingleUseAction(() -> attackCrystal(crystal, attackRotation))
913
        );
914
        RotationManager.INSTANCE.setRotationTarget(rotationTarget, ROTATION_PRIORITY, this);
915
        return true;
916
    }
917
918
    private boolean tryPlaceBase() {
919
        if (!isBaseActive() || !placeEnabled.get() || !hasBasePlaceDelayElapsed() || mc.player == null) {
920
            return false;
921
        }
922
923
        AutoCrystalBasePlanner.BaseData candidate = bestBaseCandidate;
924
        if (candidate == null) {
925
            return false;
926
        }
927
928
        if (findObsidianHand(mc.player) == null) {
929
            return false;
930
        }
931
932
        AutoCrystalBasePlanner.BaseData refreshed = getBasePlaceData(candidate.position(), target);
933
        if (refreshed == null
934
                || !isWorthBaseDamage(refreshed.damage())
935
                || !isEnoughBaseDamageDelta(refreshed.damage(), baseMinDamageDelta.get())) {
936
            return false;
937
        }
938
939
        if (!usesRotationSettings()) {
940
            placeBase(refreshed);
941
            return true;
942
        }
943
944
        RotationTarget rotationTarget = new RotationTarget(
945
                Rotation.lookingAt(refreshed.hitResult().getLocation(), mc.player.getEyePosition()).normalize(),
946
                target,
947
                List.of(),
948
                rotationResetTicks.get(),
949
                rotationResetThreshold.get(),
950
                true,
951
                movementCorrection.get(),
952
                new RestrictedSingleUseAction(() -> placeBase(refreshed))
953
        );
954
        RotationManager.INSTANCE.setRotationTarget(rotationTarget, ROTATION_PRIORITY, this);
955
        return true;
956
    }
957
958
    private void placeBase(AutoCrystalBasePlanner.BaseData data) {
959
        LocalPlayer player = mc.player;
960
        if (player == null || mc.level == null || mc.gameMode == null || data == null) {
961
            return;
962
        }
963
964
        AutoCrystalBasePlanner.BaseData refreshed = getBasePlaceData(data.position(), target);
965
        if (refreshed == null || !hasBasePlaceDelayElapsed()) {
966
            return;
967
        }
968
        if (!isWorthBaseDamage(refreshed.damage())
969
                || !isEnoughBaseDamageDelta(refreshed.damage(), baseMinDamageDelta.get())) {
970
            return;
971
        }
972
973
        AutoCrystalHand hand = findObsidianHand(player);
974
        if (hand == null) {
975
            return;
976
        }
977
978
        if (hand.hotbarSlot() >= 0) {
979
            InventorySwap.INSTANCE.leaseHotbar(this, hand.hotbarSlot(), BASE_HOTBAR_RESET_TICKS);
980
        }
981
982
        float damageDelta = refreshed.damage() - getCurrentCrystalDamage();
983
        CombatBlockUseUtil.useOn(mc, hand.hand(), refreshed.hitResult());
984
        lastBasePlaceMs = System.currentTimeMillis();
985
        bestBaseCandidate = null;
986
        markPlaced(refreshed.position(), refreshed.damage(), refreshed.selfDamage(), refreshed.hitResult().getLocation());
987
988
        if (baseNotify.get()) {
989
            Notifier.info("AutoCrystalBase placed at X:" + refreshed.position().getX()
990
                    + " Y:" + refreshed.position().getY()
991
                    + " Z:" + refreshed.position().getZ()
992
                    + " +" + ExplosionRenderUtil.formatDamage(damageDelta));
993
        }
994
    }
995
996
    private void tryPlaceCrystal(BlockPos pos) {
997
        LocalPlayer player = mc.player;
998
        if (player == null || mc.level == null || mc.gameMode == null || pos == null) {
999
            debugLog("place-skip reason=invalid-state pos=%s", pos);
1000
            return;
1001
        }
1002
1003
        LivingEntity currentTarget = target;
1004
        AutoCrystalPlaceData placeData = currentTarget != null ? getPlaceData(pos, currentTarget) : null;
1005
        if (!hasPlaceDelayElapsed() || placeData == null) {
1006
            debugLog("place-skip reason=delay-or-invalid pos=%s", pos);
1007
            return;
1008
        }
1009
1010
        if (isPositionBlockedByEntity(pos, false)) {
1011
            debugLog("place-skip reason=blocked-entity pos=%s", pos);
1012
            return;
1013
        }
1014
1015
        AutoCrystalHand hand = findCrystalHand(player);
1016
        if (hand == null) {
1017
            debugLog("place-skip reason=no-crystal-hand");
1018
            return;
1019
        }
1020
1021
        BlockHitResult hitResult = placeData.bhr();
1022
        debugLog("place-attempt pos=%s hand=%s slot=%d hit=%s side=%s",
1023
                pos, hand.hand(), hand.hotbarSlot(), hitResult.getBlockPos(), hitResult.getDirection());
1024
1025
        if (hand.hotbarSlot() >= 0) {
1026
            InventorySwap.INSTANCE.leaseHotbar(this, hand.hotbarSlot(), HOTBAR_RESET_TICKS);
1027
        }
1028
1029
        CombatBlockUseUtil.useOn(mc, hand.hand(), hitResult);
1030
        debugLog("place-result pos=%s packet=sent", pos);
1031
        lastPlaceMs = System.currentTimeMillis();
1032
        crystalTracker.addAwaitingPosition(mc, mc.level, pos.immutable());
1033
1034
        markPlaced(pos, placeData.damage(), placeData.selfDamage(), hitResult.getLocation());
1035
    }
1036
1037
    private void attackCrystal(EndCrystal crystal, Rotation attackRotation) {
1038
        LocalPlayer player = mc.player;
1039
        if (player == null || mc.level == null || crystal == null || mc.getConnection() == null) {
1040
            debugLog("break-skip reason=invalid-state");
1041
            return;
1042
        }
1043
1044
        if (!hasBreakDelayElapsed() || !crystal.isAlive() || crystal.isRemoved() || !canAttackCrystal(crystal)) {
1045
            debugLog("break-skip reason=delay-or-dead id=%d", crystal.getId());
1046
            return;
1047
        }
1048
1049
        debugLog("break-attempt id=%d pos=%.2f %.2f %.2f", crystal.getId(), crystal.getX(), crystal.getY(), crystal.getZ());
1050
        mc.gameMode.attack(player, crystal);
1051
        player.swing(InteractionHand.MAIN_HAND);
1052
        lastBreakMs = System.currentTimeMillis();
1053
        crystalTracker.onCrystalAttack(mc, crystal);
1054
        crystalTracker.markNearbyCrystalsDead(mc.level, crystal);
1055
    }
1056
1057
    private boolean isCrystalBlocked(int id) {
1058
        return crystalTracker.isCrystalBlocked(mc, id);
1059
    }
1060
1061
    private boolean isDeadCrystal(int id) {
1062
        return crystalTracker.isDeadCrystal(id);
1063
    }
1064
1065
    private AutoCrystalPlaceData getPlaceData(BlockPos pos, LivingEntity currentTarget) {
1066
        return placementPlanner.getPlaceData(placementContext, pos, currentTarget);
1067
    }
1068
1069
    private BlockHitResult getInteractResult(BlockPos pos, Vec3 crystalVec) {
1070
        return AutoCrystalInteractionUtil.getCrystalInteractResult(
1071
                mc.level,
1072
                mc.player,
1073
                pos,
1074
                crystalVec,
1075
                placementMode.get(),
1076
                placeRange.get(),
1077
                wallRange.get()
1078
        );
1079
    }
1080
1081
    private AutoCrystalHand findCrystalHand(LocalPlayer player) {
1082
        return AutoCrystalInteractionUtil.findCrystalHand(player);
1083
    }
1084
1085
    private AutoCrystalHand findObsidianHand(LocalPlayer player) {
1086
        return AutoCrystalInteractionUtil.findObsidianHand(player);
1087
    }
1088
1089
    private boolean hasPlaceDelayElapsed() {
1090
        return System.currentTimeMillis() - lastPlaceMs >= Math.max(0, placeDelay.get());
1091
    }
1092
1093
    private boolean hasBreakDelayElapsed() {
1094
        return System.currentTimeMillis() - lastBreakMs >= Math.max(0, breakDelay.get());
1095
    }
1096
1097
    private boolean hasBasePlaceDelayElapsed() {
1098
        return System.currentTimeMillis() - lastBasePlaceMs >= Math.max(0, basePlaceDelay.get());
1099
    }
1100
1101
    private long getPlaceDelayRemainingMs() {
1102
        return Math.max(0L, Math.max(0, placeDelay.get()) - (System.currentTimeMillis() - lastPlaceMs));
1103
    }
1104
1105
    private long getBreakDelayRemainingMs() {
1106
        return Math.max(0L, Math.max(0, breakDelay.get()) - (System.currentTimeMillis() - lastBreakMs));
1107
    }
1108
1109
    private long getBasePlaceDelayRemainingMs() {
1110
        return Math.max(0L, Math.max(0, basePlaceDelay.get()) - (System.currentTimeMillis() - lastBasePlaceMs));
1111
    }
1112
1113
    public String getTargetHudStatus(LivingEntity hudTarget) {
1114
        if (!isEnabled() || hudTarget == null) {
1115
            return null;
1116
        }
1117
        if (target == null || hudTarget != target) {
1118
            return null;
1119
        }
1120
        if (mc.player == null || mc.level == null) {
1121
            return "Idle";
1122
        }
1123
1124
        if (breakEnabled.get()) {
1125
            AutoCrystalCrystalData crystalData = bestCrystal;
1126
            EndCrystal crystal = crystalData != null ? crystalData.crystal() : null;
1127
            if (crystal != null && crystal.isAlive() && !crystal.isRemoved()) {
1128
                long breakWait = getBreakDelayRemainingMs();
1129
                if (breakWait > 0L) {
1130
                    return "Attack in " + breakWait + "ms";
1131
                }
1132
                return usesRotationSettings() ? "Rotate -> attack" : "Attacking";
1133
            }
1134
            if (lastBreakSelfDamageRejectCount > 0 || (lastBreakCandidateCount > 0 && lastBreakSafeCount <= 0)) {
1135
                return "Self dmg";
1136
            }
1137
        }
1138
1139
        if (placeEnabled.get()) {
1140
            String baseFailureStatus = null;
1141
            if (isBaseActive()) {
1142
                if (findObsidianHand(mc.player) == null) {
1143
                    return "No obsidian";
1144
                }
1145
                if (bestBaseCandidate != null) {
1146
                    long baseWait = getBasePlaceDelayRemainingMs();
1147
                    if (baseWait > 0L) {
1148
                        return "Base in " + baseWait + "ms";
1149
                    }
1150
                    return usesRotationSettings() ? "Rotate -> base" : "Placing base";
1151
                }
1152
1153
                baseFailureStatus = baseStatus();
1154
                if (shouldShowBaseStatus(baseFailureStatus)) {
1155
                    return baseFailureStatus;
1156
                }
1157
            }
1158
1159
            if (findCrystalHand(mc.player) == null) {
1160
                return "No crystals";
1161
            }
1162
1163
            if (bestCandidate != null) {
1164
                long placeWait = getPlaceDelayRemainingMs();
1165
                if (placeWait > 0L) {
1166
                    return "Attack in " + placeWait + "ms";
1167
                }
1168
                return usesRotationSettings() ? "Rotate -> attack" : "Attacking";
1169
            }
1170
            if (lastPlaceSelfDamageRejectCount > 0 || (lastPlaceCandidateCount > 0 && lastPlaceSafeCount <= 0)) {
1171
                return "Self dmg";
1172
            }
1173
1174
            return baseFailureStatus != null ? baseFallbackStatus(baseFailureStatus) : "No place";
1175
        }
1176
1177
        if (breakEnabled.get()) {
1178
            return "No crystal";
1179
        }
1180
1181
        return "Idle";
1182
    }
1183
1184
    private String baseStatus() {
1185
        if (lastBaseScannedCount <= 0) return "No base scan";
1186
        if (lastBaseCandidateCount <= 0) return "No base interact";
1187
        if (lastBaseSafeCount <= 0) return "Base self dmg";
1188
        if (lastBaseWorthCount <= 0) return "Base low dmg";
1189
        if (lastBaseDeltaCount <= 0) return "Base delta";
1190
        return "No base";
1191
    }
1192
1193
    private boolean shouldShowBaseStatus(String status) {
1194
        return !"Base delta".equals(status);
1195
    }
1196
1197
    private String baseFallbackStatus(String status) {
1198
        return "Base delta".equals(status) ? "No place" : status;
1199
    }
1200
1201
    private LivingEntity findCombatTarget() {
1202
        if (mc.player == null || mc.level == null) {
1203
            return null;
1204
        }
1205
1206
        TargetingUtil.TargetingSettings settings = new TargetingUtil.TargetingSettings(
1207
                TARGET_SEARCH_RANGE,
1208
                180.0f,
1209
                targetToggles.get(TargetFilters.PLAYERS_ONLY),
1210
                targetToggles.get(TargetFilters.IGNORE_FRIENDS),
1211
                targetToggles.get(TargetFilters.IGNORE_STAFF),
1212
                targetToggles.get(TargetFilters.IGNORE_ENEMIES),
1213
                targetToggles.get(TargetFilters.IGNORE_NAKED),
1214
                targetToggles.get(TargetFilters.IGNORE_ENTITIES),
1215
                targetToggles.get(TargetFilters.VISIBLE_ONLY),
1216
                priority.get()
1217
        );
1218
1219
        return TargetingUtil.findBestTarget(mc, settings);
1220
    }
1221
1222
    private void debugState() {
1223
    }
1224
1225
    private boolean isSpawnNearPendingPlace(ClientboundAddEntityPacket spawn, BlockPos pos) {
1226
        AABB crystalBox = AutoCrystalInteractionUtil.predictedCrystalBox(pos);
1227
        return crystalBox.contains(spawn.getX(), spawn.getY(), spawn.getZ());
1228
    }
1229
1230
    private Vec3 resolvePredictedPosition(LivingEntity entity, int ticks) {
1231
        if (entity == null || ticks <= 0) {
1232
            return entity != null ? entity.position() : Vec3.ZERO;
1233
        }
1234
1235
        if (entity instanceof net.minecraft.world.entity.player.Player player) {
1236
            PlayerSimulationCache.SimulatedPlayerCache simulation =
1237
                    player == mc.player
1238
                            ? PlayerSimulationCache.getSimulationForLocalPlayer()
1239
                            : PlayerSimulationCache.getSimulationForOtherPlayers(player);
1240
            if (simulation != null) {
1241
                return simulation.getSnapshotAt(ticks).pos();
1242
            }
1243
        }
1244
1245
        return PositionExtrapolation.getBestForEntity(entity).getPositionInTicks(ticks);
1246
    }
1247
1248
    private void clearPlacementState() {
1249
        clearRenderCandidate();
1250
        bestCrystal = null;
1251
        bestBaseCandidate = null;
1252
        target = null;
1253
        crystalTracker.clear();
1254
        RotationManager.INSTANCE.clear(this);
1255
        lastPlaceCandidateCount = 0;
1256
        lastPlaceSafeCount = 0;
1257
        lastBreakCandidateCount = 0;
1258
        lastBreakSafeCount = 0;
1259
        lastPlaceSelfDamageRejectCount = 0;
1260
        lastBreakSelfDamageRejectCount = 0;
1261
        lastBaseCandidateCount = 0;
1262
        lastBaseScannedCount = 0;
1263
        lastBaseSafeCount = 0;
1264
        lastBaseWorthCount = 0;
1265
        lastBaseDeltaCount = 0;
1266
    }
1267
1268
    private void resetVisualState() {
1269
        target = null;
1270
        bestCandidate = null;
1271
        bestCrystal = null;
1272
        bestBaseCandidate = null;
1273
        renderPos = null;
1274
        prevRenderPos = null;
1275
        bestPosition = null;
1276
        interactVector = null;
1277
        renderTick = 0;
1278
        renderStartTick = 0;
1279
        lastDamageUpdateMs = 0L;
1280
        lastPlaceMs = 0L;
1281
        lastBreakMs = 0L;
1282
        lastBaseCalcMs = 0L;
1283
        lastBasePlaceMs = 0L;
1284
        renderDamage = 0.0f;
1285
        renderSelfDamageValue = 0.0f;
1286
        baseActive = false;
1287
        renderPositions.clear();
1288
        crystalTracker.clear();
1289
        lastPlaceCandidateCount = 0;
1290
        lastPlaceSafeCount = 0;
1291
        lastBreakCandidateCount = 0;
1292
        lastBreakSafeCount = 0;
1293
        lastPlaceSelfDamageRejectCount = 0;
1294
        lastBreakSelfDamageRejectCount = 0;
1295
        lastBaseCandidateCount = 0;
1296
        lastBaseScannedCount = 0;
1297
        lastBaseSafeCount = 0;
1298
        lastBaseWorthCount = 0;
1299
        lastBaseDeltaCount = 0;
1300
    }
1301
1302
    private String buildDamageText() {
1303
        String main = ExplosionRenderUtil.formatDamage(renderDamage);
1304
        if (main.isEmpty()) return "";
1305
        if (!renderSelfDamage.get() || renderSelfDamageValue <= 0.0f) {
1306
            return main;
1307
        }
1308
        return main + " / " + ExplosionRenderUtil.formatDamage(renderSelfDamageValue);
1309
    }
1310
1311
    private float getCurrentCrystalDamage() {
1312
        if (currentData != null) {
1313
            return currentData.damage();
1314
        }
1315
        if (bestCrystal != null) {
1316
            return bestCrystal.damage();
1317
        }
1318
        return 0.0f;
1319
    }
1320
1321
    private boolean hasCurrentCrystalPlan() {
1322
        return currentData != null || bestCrystal != null;
1323
    }
1324
1325
    private boolean isWorthBaseDamage(float damage) {
1326
        if (!hasCurrentCrystalPlan()) {
1327
            return shouldOverrideMinDamage(target, damage) || damage >= BASE_INITIATIVE_MIN_DAMAGE;
1328
        }
1329
        return shouldOverrideMinDamage(target, damage) || damage > minDamage.get();
1330
    }
1331
1332
    private boolean isEnoughBaseDamageDelta(float damage, float minDamageDelta) {
1333
        float delta = Math.max(0.0f, minDamageDelta);
1334
        if (!hasCurrentCrystalPlan()) {
1335
            return damage >= Math.max(BASE_INITIATIVE_MIN_DAMAGE, delta);
1336
        }
1337
        return damage >= getCurrentCrystalDamage() + delta;
1338
    }
1339
1340
    private boolean usesRotationSettings() {
1341
        return CombatRotationModeUtil.usesRotations(attackMode);
1342
    }
1343
1344
    private boolean isBaseActive() {
1345
        return baseActive;
1346
    }
1347
1348
    private final class AutoCrystalBaseContext implements AutoCrystalBasePlanner.Context, AutoCrystalBaseEvaluator.Context {
1349
        @Override
1350
        public boolean canEvaluateBaseAt(BlockPos pos) {
1351
            return AutoCrystal.this.canEvaluateBaseAt(pos);
1352
        }
1353
1354
        @Override
1355
        public AutoCrystalBasePlanner.BaseData getBaseData(BlockPos pos, LivingEntity target) {
1356
            return getBasePlaceData(pos, target);
1357
        }
1358
1359
        @Override
1360
        public boolean isSafe(float damage, float selfDamage, boolean overrideDamage) {
1361
            return AutoCrystal.this.isSafe(damage, selfDamage, overrideDamage);
1362
        }
1363
1364
        @Override
1365
        public boolean hasCurrentCrystalPlan() {
1366
            return AutoCrystal.this.hasCurrentCrystalPlan();
1367
        }
1368
1369
        @Override
1370
        public float currentCrystalDamage() {
1371
            return getCurrentCrystalDamage();
1372
        }
1373
1374
        @Override
1375
        public boolean isWorthBaseDamage(float damage) {
1376
            return AutoCrystal.this.isWorthBaseDamage(damage);
1377
        }
1378
1379
        @Override
1380
        public boolean isEnoughBaseDamageDelta(float damage, float minDamageDelta) {
1381
            return AutoCrystal.this.isEnoughBaseDamageDelta(damage, minDamageDelta);
1382
        }
1383
1384
        @Override
1385
        public LocalPlayer player() {
1386
            return mc.player;
1387
        }
1388
1389
        @Override
1390
        public ClientLevel level() {
1391
            return mc.level;
1392
        }
1393
1394
        @Override
1395
        public Vec3 resolvePredictedPosition(LivingEntity entity, int ticks) {
1396
            return AutoCrystal.this.resolvePredictedPosition(entity, ticks);
1397
        }
1398
1399
        @Override
1400
        public boolean shouldOverrideMaxSelfDamage(float damage, float selfDamage) {
1401
            return AutoCrystal.this.shouldOverrideMaxSelfDamage(damage, selfDamage);
1402
        }
1403
1404
        @Override
1405
        public float placeRange() {
1406
            return placeRange.get();
1407
        }
1408
1409
        @Override
1410
        public float maxSelfDamage() {
1411
            return maxSelfDamage.get();
1412
        }
1413
1414
        @Override
1415
        public int predictTicks() {
1416
            return predictTicks.get();
1417
        }
1418
1419
        @Override
1420
        public int selfPredictTicks() {
1421
            return selfPredictTicks.get();
1422
        }
1423
1424
        @Override
1425
        public boolean ignoreTerrain() {
1426
            return ignoreTerrain.get();
1427
        }
1428
    }
1429
1430
    private final class AutoCrystalPlacementContext implements AutoCrystalPlacementPlanner.Context {
1431
        @Override
1432
        public LocalPlayer player() {
1433
            return mc.player;
1434
        }
1435
1436
        @Override
1437
        public Iterable<Entity> entities() {
1438
            return mc.level != null ? mc.level.entitiesForRendering() : List.<Entity>of();
1439
        }
1440
1441
        @Override
1442
        public Vec3 resolvePredictedPosition(LivingEntity entity, int ticks) {
1443
            return AutoCrystal.this.resolvePredictedPosition(entity, ticks);
1444
        }
1445
1446
        @Override
1447
        public AutoCrystalPlaceValidationResult validatePlaceCrystal(BlockPos pos, boolean calcPhase) {
1448
            return AutoCrystal.this.validatePlaceCrystal(pos, calcPhase);
1449
        }
1450
1451
        @Override
1452
        public BlockHitResult getInteractResult(BlockPos pos, Vec3 crystalVec) {
1453
            return AutoCrystal.this.getInteractResult(pos, crystalVec);
1454
        }
1455
1456
        @Override
1457
        public boolean isDeadCrystal(int id) {
1458
            return AutoCrystal.this.isDeadCrystal(id);
1459
        }
1460
1461
        @Override
1462
        public boolean isCrystalBlocked(int id) {
1463
            return AutoCrystal.this.isCrystalBlocked(id);
1464
        }
1465
1466
        @Override
1467
        public boolean shouldOverrideMinDamage(LivingEntity target, float damage) {
1468
            return AutoCrystal.this.shouldOverrideMinDamage(target, damage);
1469
        }
1470
1471
        @Override
1472
        public boolean shouldOverrideMaxSelfDamage(float damage, float selfDamage) {
1473
            return AutoCrystal.this.shouldOverrideMaxSelfDamage(damage, selfDamage);
1474
        }
1475
1476
        @Override
1477
        public boolean isSafe(float damage, float selfDamage, boolean overrideDamage) {
1478
            return AutoCrystal.this.isSafe(damage, selfDamage, overrideDamage);
1479
        }
1480
1481
        @Override
1482
        public float minDamage() {
1483
            return minDamage.get();
1484
        }
1485
1486
        @Override
1487
        public float faceplaceHealth() {
1488
            return faceplaceHealth.get();
1489
        }
1490
1491
        @Override
1492
        public float maxSelfDamage() {
1493
            return maxSelfDamage.get();
1494
        }
1495
1496
        @Override
1497
        public float breakRange() {
1498
            return breakRange.get();
1499
        }
1500
1501
        @Override
1502
        public float breakWallRange() {
1503
            return breakWallRange.get();
1504
        }
1505
1506
        @Override
1507
        public int predictTicks() {
1508
            return predictTicks.get();
1509
        }
1510
1511
        @Override
1512
        public int selfPredictTicks() {
1513
            return selfPredictTicks.get();
1514
        }
1515
1516
        @Override
1517
        public boolean ignoreTerrain() {
1518
            return ignoreTerrain.get();
1519
        }
1520
    }
1521
1522
    private enum RenderMode {
1523
        FADE,
1524
        SLIDE,
1525
        DEFAULT
1526
    }
1527
1528
}
1529
NicotineCombatsrc/client/java/nicotine/mod/mods/combat/AutoCrystal.javaJava · 285 lines · 10.1 KB

Places and blows up end crystals around players

SettingsDelayPDelayMinDMGSelfDMGManualPlaceRenderPosition
AutoCrystal.javaJava · Minecraft 26.3 · 285 lines · 10.1 KB · complete file, verbatimOriginal ↗
1
package nicotine.mod.mods.combat;
2
3
import com.mojang.blaze3d.platform.InputConstants;
4
import net.minecraft.client.player.AbstractClientPlayer;
5
import net.minecraft.core.BlockPos;
6
import net.minecraft.core.Direction;
7
import net.minecraft.world.entity.Entity;
8
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
9
import net.minecraft.world.item.Items;
10
import net.minecraft.world.level.ServerExplosion;
11
import net.minecraft.world.level.block.Block;
12
import net.minecraft.world.level.block.Blocks;
13
import net.minecraft.world.phys.AABB;
14
import net.minecraft.world.phys.BlockHitResult;
15
import net.minecraft.world.phys.Vec3;
16
import nicotine.events.ClientLevelTickEvent;
17
import nicotine.events.RenderEvent;
18
import nicotine.mod.Mod;
19
import nicotine.mod.ModCategory;
20
import nicotine.mod.option.SliderOption;
21
import nicotine.mod.option.ToggleOption;
22
import nicotine.util.ColorUtil;
23
import nicotine.util.EventBus;
24
import nicotine.util.Player;
25
import nicotine.util.math.BoxUtil;
26
import nicotine.util.math.Boxf;
27
import nicotine.util.render.Render3D;
28
29
import java.util.ArrayList;
30
import java.util.Arrays;
31
import java.util.HashMap;
32
import java.util.List;
33
34
import static nicotine.util.Common.mc;
35
36
public class AutoCrystal extends Mod {
37
38
    private static float delayLeft = 0;
39
    private static float placeDelayLeft = 0;
40
41
    private static BlockPos placementPositionToRender = null;
42
43
    private static final List<Block> validBlocks =  Arrays.asList(Blocks.OBSIDIAN, Blocks.BEDROCK);
44
45
    private final SliderOption delay = new SliderOption(
46
            "Delay",
47
            8,
48
            0,
49
            20
50
    );
51
    private final SliderOption placeDelay = new SliderOption(
52
            "PDelay",
53
            10,
54
            0,
55
            20
56
    );
57
    private final SliderOption minDamage = new SliderOption(
58
            "MinDMG",
59
            20,
60
            1,
61
            75
62
    );
63
    private final SliderOption selfDamage = new SliderOption(
64
            "SelfDMG",
65
            10,
66
            1,
67
            75
68
    );
69
    private final ToggleOption manualPlace = new ToggleOption("ManualPlace");
70
    private final ToggleOption renderPosition = new ToggleOption("RenderPosition");
71
72
    public AutoCrystal() {
73
        super(ModCategory.Combat,"AutoCrystal", "Places and blows up end crystals around players");
74
        this.keybind.keyCode = InputConstants.KEY_R;
75
        this.addOptions(Arrays.asList(delay, placeDelay, minDamage, selfDamage, manualPlace, renderPosition));
76
    }
77
78
    private static float calculateExplosionDamage(Vec3 explosionPos, Entity entity) {
79
        final float power = 12.0F;
80
81
        double distance = Math.sqrt(entity.distanceToSqr(explosionPos));
82
        double d = distance / power;
83
84
        if (d <= 1.0) {
85
            double e = entity.getX() - explosionPos.x;
86
            double g = entity.getEyeY() - explosionPos.y;
87
            double h = entity.getZ() - explosionPos.z;
88
            double o = Math.sqrt(e * e + g * g + h * h);
89
            if (o != 0.0) {
90
                double e2 = (1.0 - d) * (double) ServerExplosion.getSeenPercent(explosionPos, entity);
91
                return (float) ((e2 * e2 + e2) / 2.0 * 7.0 * (double) power + 1.0);
92
            }
93
        }
94
95
        return 0;
96
    }
97
98
    private static List<BlockPos> getPlacementPositions() {
99
        List<BlockPos> placementPositions = new ArrayList<>();
100
101
        BlockPos initPos = mc.player.blockPosition();
102
        int blockRange = (int) Math.ceil(mc.player.blockInteractionRange());
103
104
        for (int x = -blockRange; x <= blockRange; x++) {
105
            for (int y = -blockRange; y <= blockRange; y++) {
106
                for (int z = -blockRange; z <= blockRange; z++) {
107
                    BlockPos pos = initPos.offset(x, y, z);
108
109
                    if (!mc.player.isWithinBlockInteractionRange(pos, 0))
110
                        continue;
111
112
                    Vec3 centerPos = Vec3.atCenterOf(pos);
113
                    EndCrystal endCrystalEntity = new EndCrystal(mc.level, centerPos.x, pos.getY() + 1, centerPos.z);
114
115
                    if (!mc.player.isWithinEntityInteractionRange(endCrystalEntity, 0))
116
                        continue;
117
118
                    if (!validBlocks.contains(mc.level.getBlockState(pos).getBlock()))
119
                        continue;
120
121
                    if (mc.level.getBlockState(pos.offset(0, 1, 0)).getBlock() != Blocks.AIR)
122
                        continue;
123
124
                    placementPositions.add(pos);
125
                }
126
            }
127
        }
128
129
        return placementPositions;
130
    }
131
132
    private static Direction getPlacementDir(BlockPos placementPos) {
133
        Direction placementDir = null;
134
135
        HashMap<BlockPos, Direction> directions = new HashMap<>();
136
137
        directions.put(placementPos.above(), Direction.UP);
138
        directions.put(placementPos.below(), Direction.DOWN);
139
        directions.put(placementPos.north(), Direction.NORTH);
140
        directions.put(placementPos.west(), Direction.WEST);
141
        directions.put(placementPos.south(), Direction.SOUTH);
142
        directions.put(placementPos.east(), Direction.EAST);
143
144
        BlockPos nearestPos = BlockPos.ZERO;
145
        Vec3 playerPos = mc.player.position();
146
147
        for (BlockPos pos : directions.keySet()) {
148
            if (mc.player.isWithinBlockInteractionRange(pos, 0) && mc.level.getBlockState(pos).getBlock() == Blocks.AIR) {
149
                if (Vec3.atCenterOf(pos).distanceTo(playerPos) < Vec3.atCenterOf(nearestPos).distanceTo(playerPos)) {
150
                    nearestPos = pos;
151
                }
152
            }
153
        }
154
155
        if (nearestPos != BlockPos.ZERO) {
156
            placementDir = directions.get(nearestPos);
157
        }
158
159
        return placementDir;
160
    }
161
162
    @Override
163
    protected void init() {
164
        EventBus.register(ClientLevelTickEvent.class, event -> {
165
            if (!this.enabled)
166
                return true;
167
168
            AbstractClientPlayer nearestPlayer = Player.findNearestPlayer(true);
169
170
            if (nearestPlayer == null)
171
                return true;
172
173
            for (Entity entity : mc.level.entitiesForRendering()) {
174
                if (entity instanceof EndCrystal endCrystalEntity) {
175
                    if (Player.isBusy() || !mc.player.isWithinEntityInteractionRange(endCrystalEntity, 0))
176
                        continue;
177
178
                    float dmg = calculateExplosionDamage(endCrystalEntity.position(), nearestPlayer);
179
                    float selfDmg = calculateExplosionDamage(endCrystalEntity.position(), mc.player);
180
181
                    if (dmg < minDamage.value || selfDmg > selfDamage.value)
182
                        continue;
183
184
                    if (delayLeft > 0)
185
                        continue;
186
187
                    Player.lookAndAttack(endCrystalEntity);
188
                    delayLeft = delay.value;
189
190
                    break;
191
                }
192
            }
193
194
            if (!manualPlace.enabled) {
195
196
                List<BlockPos> placementPositions = getPlacementPositions();
197
198
                List<AABB> takenPositions = new ArrayList<>();
199
200
                for (Entity entity : mc.level.entitiesForRendering()) {
201
                    takenPositions.add(entity.getBoundingBox());
202
                }
203
204
                BlockPos bestPlacementPos = BlockPos.ZERO;
205
206
                float bestDamage = -1;
207
208
                for (BlockPos placementPosition : placementPositions) {
209
                    boolean invalidPlacement = false;
210
211
                    Vec3 interSectionPos = new Vec3(placementPosition.getX(), placementPosition.getY() + 1, placementPosition.getZ());
212
213
                    for (AABB takenPosition : takenPositions) {
214
                        if (BoxUtil.get1x1Box(interSectionPos).intersects(takenPosition)) {
215
                            invalidPlacement = true;
216
                            break;
217
                        }
218
                    }
219
220
                    if (invalidPlacement)
221
                        continue;
222
223
                    Vec3 crystalPos = Vec3.atBottomCenterOf(placementPosition).add(0, 1, 0);
224
225
                    float selfDmg = calculateExplosionDamage(crystalPos, mc.player);
226
                    if (selfDmg > selfDamage.value)
227
                        continue;
228
229
230
                    float dmg = calculateExplosionDamage(crystalPos, nearestPlayer);
231
                    if (bestDamage < dmg) {
232
                        bestPlacementPos = placementPosition;
233
                        bestDamage = dmg;
234
                    }
235
                }
236
237
                if (placeDelayLeft <= 0 && !Player.isBusy()) {
238
                    if (bestDamage >= minDamage.value) {
239
240
                        int targetSlot = -1;
241
242
                        for (int i = 0; i < 9; i++) {
243
                            if (mc.player.getInventory().getItem(i).getItem() == Items.END_CRYSTAL) {
244
                                targetSlot = i;
245
                                break;
246
                            }
247
                        }
248
249
                        if (targetSlot != -1) {
250
                            placementPositionToRender = bestPlacementPos;
251
252
                            Direction placementDir = getPlacementDir(bestPlacementPos);
253
254
                            if (placementDir != null) {
255
                                BlockHitResult blockHitResult = new BlockHitResult(new Vec3(bestPlacementPos.getX(), bestPlacementPos.getY(), bestPlacementPos.getZ()), placementDir, bestPlacementPos, false);
256
                                Player.lookAndPlace(blockHitResult, targetSlot, false, false);
257
                                placeDelayLeft = placeDelay.value;
258
                            }
259
                        }
260
                    }
261
                    else {
262
                        placementPositionToRender = null;
263
                    }
264
                }
265
            }
266
267
268
            delayLeft--;
269
            placeDelayLeft--;
270
271
            return true;
272
        });
273
274
        EventBus.register(RenderEvent.class, event -> {
275
            if (!this.enabled || !renderPosition.enabled || placementPositionToRender == null)
276
                return true;
277
278
            Boxf boundingBox = BoxUtil.getBlockBoundingBoxf(placementPositionToRender);
279
            Render3D.drawFilledBox(event.submitNodeStorage, event.camera, event.matrixStack, boundingBox, ColorUtil.ACTIVE_FOREGROUND_COLOR);
280
281
            return true;
282
        });
283
    }
284
}
285