trajectories module

trajectories: Minecraft 26.3 cheat module, full source for every implementation (4 clients: Meteor Client, MelaHack (ThunderHack fork), OfflineClient, …).

4 implementationsRenderRENDER

Full module source: 4 implementations

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

Meteor ClientRendersrc/main/java/meteordevelopment/meteorclient/systems/modules/render/Trajectories.javaJava · 389 lines · 14.9 KB

Predicts the trajectory of throwable items.

Settingsitemsother-playersfired-projectilesignore-wither-skullsaccuratesimulation-stepsignore-rendering-first-ticksshape-modeside-colorline-colorrender-position-boxesposition-box-sizeposition-side-colorposition-line-color
Trajectories.javaJava · Minecraft 26.2 · 389 lines · 14.9 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Meteor Client distribution (https://github.com/MeteorDevelopment/meteor-client).
3
 * Copyright (c) Meteor Development.
4
 */
5
6
package meteordevelopment.meteorclient.systems.modules.render;
7
8
import meteordevelopment.meteorclient.events.render.Render3DEvent;
9
import meteordevelopment.meteorclient.renderer.ShapeMode;
10
import meteordevelopment.meteorclient.settings.*;
11
import meteordevelopment.meteorclient.systems.modules.Categories;
12
import meteordevelopment.meteorclient.systems.modules.Module;
13
import meteordevelopment.meteorclient.utils.Utils;
14
import meteordevelopment.meteorclient.utils.entity.simulator.ProjectileEntitySimulator;
15
import meteordevelopment.meteorclient.utils.entity.simulator.SimulationStep;
16
import meteordevelopment.meteorclient.utils.misc.Pool;
17
import meteordevelopment.meteorclient.utils.render.color.SettingColor;
18
import meteordevelopment.orbit.EventHandler;
19
import net.minecraft.core.Direction;
20
import net.minecraft.core.registries.BuiltInRegistries;
21
import net.minecraft.util.Mth;
22
import net.minecraft.world.entity.Entity;
23
import net.minecraft.world.entity.player.Player;
24
import net.minecraft.world.entity.projectile.Projectile;
25
import net.minecraft.world.entity.projectile.arrow.ThrownTrident;
26
import net.minecraft.world.entity.projectile.hurtingprojectile.WitherSkull;
27
import net.minecraft.world.item.*;
28
import net.minecraft.world.item.enchantment.Enchantments;
29
import net.minecraft.world.phys.AABB;
30
import net.minecraft.world.phys.BlockHitResult;
31
import net.minecraft.world.phys.EntityHitResult;
32
import net.minecraft.world.phys.HitResult;
33
import org.joml.Vector3d;
34
35
import java.util.ArrayList;
36
import java.util.List;
37
38
public class Trajectories extends Module {
39
    private final SettingGroup sgGeneral = settings.getDefaultGroup();
40
    private final SettingGroup sgRender = settings.createGroup("Render");
41
42
    // General
43
44
    private final Setting<List<Item>> items = sgGeneral.add(new ItemListSetting.Builder()
45
        .name("items")
46
        .description("Items to display trajectories for.")
47
        .defaultValue(getDefaultItems())
48
        .filter(this::itemFilter)
49
        .build()
50
    );
51
52
    private final Setting<Boolean> otherPlayers = sgGeneral.add(new BoolSetting.Builder()
53
        .name("other-players")
54
        .description("Calculates trajectories for other players.")
55
        .defaultValue(true)
56
        .build()
57
    );
58
59
    private final Setting<Boolean> firedProjectiles = sgGeneral.add(new BoolSetting.Builder()
60
        .name("fired-projectiles")
61
        .description("Calculates trajectories for already fired projectiles.")
62
        .defaultValue(false)
63
        .build()
64
    );
65
66
    private final Setting<Boolean> ignoreWitherSkulls = sgGeneral.add(new BoolSetting.Builder()
67
        .name("ignore-wither-skulls")
68
        .description("Whether to ignore fired wither skulls.")
69
        .defaultValue(false)
70
        .visible(firedProjectiles::get)
71
        .build()
72
    );
73
74
    private final Setting<Boolean> accurate = sgGeneral.add(new BoolSetting.Builder()
75
        .name("accurate")
76
        .description("Whether or not to calculate more accurate.")
77
        .defaultValue(false)
78
        .build()
79
    );
80
81
    public final Setting<Integer> simulationSteps = sgGeneral.add(new IntSetting.Builder()
82
        .name("simulation-steps")
83
        .description("How many steps to simulate projectiles. Zero for no limit")
84
        .defaultValue(500)
85
        .sliderMax(5000)
86
        .build()
87
    );
88
89
    // Render
90
91
    private final Setting<Integer> ignoreFirstTicks = sgRender.add(new IntSetting.Builder()
92
        .name("ignore-rendering-first-ticks")
93
        .description("Ignores rendering the first given ticks, to make the rest of the path more visible.")
94
        .defaultValue(3)
95
        .min(0)
96
        .build()
97
    );
98
99
    private final Setting<ShapeMode> shapeMode = sgRender.add(new EnumSetting.Builder<ShapeMode>()
100
        .name("shape-mode")
101
        .description("How the shapes are rendered.")
102
        .defaultValue(ShapeMode.Both)
103
        .build()
104
    );
105
106
    private final Setting<SettingColor> sideColor = sgRender.add(new ColorSetting.Builder()
107
        .name("side-color")
108
        .description("The side color.")
109
        .defaultValue(new SettingColor(255, 150, 0, 35))
110
        .build()
111
    );
112
113
    private final Setting<SettingColor> lineColor = sgRender.add(new ColorSetting.Builder()
114
        .name("line-color")
115
        .description("The line color.")
116
        .defaultValue(new SettingColor(255, 150, 0))
117
        .build()
118
    );
119
120
    private final Setting<Boolean> renderPositionBox = sgRender.add(new BoolSetting.Builder()
121
        .name("render-position-boxes")
122
        .description("Renders the actual position the projectile will be at each tick along it's trajectory.")
123
        .defaultValue(false)
124
        .build()
125
    );
126
127
    private final Setting<Double> positionBoxSize = sgRender.add(new DoubleSetting.Builder()
128
        .name("position-box-size")
129
        .description("The size of the box drawn at the simulated positions.")
130
        .defaultValue(0.02)
131
        .sliderRange(0.01, 0.1)
132
        .visible(renderPositionBox::get)
133
        .build()
134
    );
135
136
    private final Setting<SettingColor> positionSideColor = sgRender.add(new ColorSetting.Builder()
137
        .name("position-side-color")
138
        .description("The side color.")
139
        .defaultValue(new SettingColor(255, 150, 0, 35))
140
        .visible(renderPositionBox::get)
141
        .build()
142
    );
143
144
    private final Setting<SettingColor> positionLineColor = sgRender.add(new ColorSetting.Builder()
145
        .name("position-line-color")
146
        .description("The line color.")
147
        .defaultValue(new SettingColor(255, 150, 0))
148
        .visible(renderPositionBox::get)
149
        .build()
150
    );
151
152
    private final ProjectileEntitySimulator simulator = new ProjectileEntitySimulator();
153
154
    private final Pool<Vector3d> vec3s = new Pool<>(Vector3d::new);
155
    private final List<Path> paths = new ArrayList<>();
156
157
    private static final double MULTISHOT_OFFSET = Math.toRadians(10); // accurate-ish offset of crossbow multishot in radians (10° degrees)
158
159
    public Trajectories() {
160
        super(Categories.Render, "trajectories", "Predicts the trajectory of throwable items.");
161
    }
162
163
    private boolean itemFilter(Item item) {
164
        return item instanceof ProjectileWeaponItem || item instanceof FishingRodItem || item instanceof TridentItem ||
165
            item instanceof SnowballItem || item instanceof EggItem || item instanceof EnderpearlItem ||
166
            item instanceof ExperienceBottleItem || item instanceof ThrowablePotionItem || item instanceof WindChargeItem;
167
    }
168
169
    private List<Item> getDefaultItems() {
170
        List<Item> items = new ArrayList<>();
171
172
        for (Item item : BuiltInRegistries.ITEM) {
173
            if (itemFilter(item)) items.add(item);
174
        }
175
176
        return items;
177
    }
178
179
    private Path getEmptyPath() {
180
        for (Path path : paths) {
181
            if (path.points.isEmpty()) return path;
182
        }
183
184
        Path path = new Path();
185
        paths.add(path);
186
        return path;
187
    }
188
189
    private void calculatePath(Player player, float tickDelta) {
190
        // Clear paths
191
        for (Path path : paths) path.clear();
192
193
        // Get item
194
        ItemStack itemStack = player.getMainHandItem();
195
        if (!items.get().contains(itemStack.getItem())) {
196
            itemStack = player.getOffhandItem();
197
            if (!items.get().contains(itemStack.getItem())) return;
198
        }
199
200
        // Calculate paths
201
        if (!simulator.set(player, itemStack, 0, accurate.get(), tickDelta)) return;
202
        Path p = getEmptyPath().calculate();
203
        if (player == mc.player) p.ignoreFirstTicks();
204
205
        if (itemStack.getItem() instanceof CrossbowItem && Utils.hasEnchantment(itemStack, Enchantments.MULTISHOT)) {
206
            if (!simulator.set(player, itemStack, MULTISHOT_OFFSET, accurate.get(), tickDelta))
207
                return; // left multishot arrow
208
            p = getEmptyPath().calculate();
209
            if (player == mc.player) p.ignoreFirstTicks();
210
211
            if (!simulator.set(player, itemStack, -MULTISHOT_OFFSET, accurate.get(), tickDelta))
212
                return; // right multishot arrow
213
            p = getEmptyPath().calculate();
214
            if (player == mc.player) p.ignoreFirstTicks();
215
        }
216
    }
217
218
    private void calculateFiredPath(Entity entity, double tickDelta) {
219
        for (Path path : paths) path.clear();
220
221
        // Calculate paths
222
        if (!simulator.set(entity)) return;
223
        getEmptyPath().setStart(entity, tickDelta).calculate();
224
    }
225
226
    @EventHandler
227
    private void onRender(Render3DEvent event) {
228
        float tickDelta = mc.level.tickRateManager().isFrozen() ? 1 : event.tickDelta;
229
230
        for (Player player : mc.level.players()) {
231
            if (!otherPlayers.get() && player != mc.player) continue;
232
233
            calculatePath(player, tickDelta);
234
            for (Path path : paths) path.render(event);
235
        }
236
237
        if (firedProjectiles.get()) {
238
            for (Entity entity : mc.level.entitiesForRendering()) {
239
                if (entity instanceof Projectile) {
240
                    if (ignoreWitherSkulls.get() && entity instanceof WitherSkull) continue;
241
                    if (entity instanceof ThrownTrident trident && trident.noPhysics)
242
                        continue; // when it's returning via loyalty
243
244
                    calculateFiredPath(entity, tickDelta);
245
                    for (Path path : paths) path.render(event);
246
                }
247
            }
248
        }
249
    }
250
251
    private class Path {
252
        private final List<Vector3d> points = new ArrayList<>();
253
254
        private boolean hitQuad, hitQuadHorizontal;
255
        private double hitQuadX1, hitQuadY1, hitQuadZ1, hitQuadX2, hitQuadY2, hitQuadZ2;
256
257
        private final List<Entity> collidingEntities = new ArrayList<>();
258
        public Vector3d lastPoint;
259
        private int start;
260
261
        public void clear() {
262
            vec3s.freeAll(points);
263
            points.clear();
264
265
            hitQuad = false;
266
            collidingEntities.clear();
267
            lastPoint = null;
268
            start = 0;
269
        }
270
271
        public Path calculate() {
272
            addPoint();
273
274
            for (int i = 0; i < (simulationSteps.get() > 0 ? simulationSteps.get() : Integer.MAX_VALUE); i++) {
275
                SimulationStep result = simulator.tick();
276
277
                processHitResults(result);
278
                if (result.shouldStop) break;
279
280
                addPoint();
281
            }
282
283
            return this;
284
        }
285
286
        public Path setStart(Entity entity, double tickDelta) {
287
            lastPoint = new Vector3d(
288
                Mth.lerp(tickDelta, entity.xOld, entity.getX()),
289
                Mth.lerp(tickDelta, entity.yOld, entity.getY()),
290
                Mth.lerp(tickDelta, entity.zOld, entity.getZ())
291
            );
292
293
            return this;
294
        }
295
296
        private void addPoint() {
297
            points.add(vec3s.get().set(simulator.pos));
298
        }
299
300
        private void processHitResults(SimulationStep step) {
301
            for (int i = 0; i < step.hitResults.length; i++) {
302
                HitResult result = step.hitResults[i];
303
                if (result.getType() == HitResult.Type.BLOCK) {
304
                    BlockHitResult r = (BlockHitResult) result;
305
306
                    hitQuad = true;
307
                    hitQuadX1 = r.getLocation().x;
308
                    hitQuadY1 = r.getLocation().y;
309
                    hitQuadZ1 = r.getLocation().z;
310
                    hitQuadX2 = r.getLocation().x;
311
                    hitQuadY2 = r.getLocation().y;
312
                    hitQuadZ2 = r.getLocation().z;
313
314
                    if (r.getDirection() == Direction.UP || r.getDirection() == Direction.DOWN) {
315
                        hitQuadHorizontal = true;
316
                        hitQuadX1 -= 0.25;
317
                        hitQuadZ1 -= 0.25;
318
                        hitQuadX2 += 0.25;
319
                        hitQuadZ2 += 0.25;
320
                    } else if (r.getDirection() == Direction.NORTH || r.getDirection() == Direction.SOUTH) {
321
                        hitQuadHorizontal = false;
322
                        hitQuadX1 -= 0.25;
323
                        hitQuadY1 -= 0.25;
324
                        hitQuadX2 += 0.25;
325
                        hitQuadY2 += 0.25;
326
                    } else {
327
                        hitQuadHorizontal = false;
328
                        hitQuadZ1 -= 0.25;
329
                        hitQuadY1 -= 0.25;
330
                        hitQuadZ2 += 0.25;
331
                        hitQuadY2 += 0.25;
332
                    }
333
334
                    points.add(Utils.set(vec3s.get(), result.getLocation()));
335
                } else if (result.getType() == HitResult.Type.ENTITY) {
336
                    Entity entity = ((EntityHitResult) result).getEntity();
337
                    collidingEntities.add(entity);
338
339
                    if (step.shouldStop && i == step.hitResults.length - 1) {
340
                        points.add(Utils.set(vec3s.get(), result.getLocation()));
341
                    }
342
                }
343
            }
344
        }
345
346
        public void ignoreFirstTicks() {
347
            start = points.size() <= ignoreFirstTicks.get() ? 0 : ignoreFirstTicks.get();
348
        }
349
350
        public void render(Render3DEvent event) {
351
            // Render path
352
            for (int i = start; i < points.size(); i++) {
353
                Vector3d point = points.get(i);
354
355
                if (lastPoint != null) {
356
                    event.renderer.line(lastPoint.x, lastPoint.y, lastPoint.z, point.x, point.y, point.z, lineColor.get());
357
                    if (renderPositionBox.get()) {
358
                        event.renderer.box(
359
                            point.x - positionBoxSize.get(), point.y - positionBoxSize.get(), point.z - positionBoxSize.get(),
360
                            point.x + positionBoxSize.get(), point.y + positionBoxSize.get(), point.z + positionBoxSize.get(),
361
                            positionSideColor.get(), positionLineColor.get(), shapeMode.get(), 0
362
                        );
363
                    }
364
                }
365
366
                lastPoint = point;
367
            }
368
369
            // Render hit quad
370
            if (hitQuad) {
371
                if (hitQuadHorizontal)
372
                    event.renderer.sideHorizontal(hitQuadX1, hitQuadY1, hitQuadZ1, hitQuadX1 + 0.5, hitQuadZ1 + 0.5, sideColor.get(), lineColor.get(), shapeMode.get());
373
                else
374
                    event.renderer.sideVertical(hitQuadX1, hitQuadY1, hitQuadZ1, hitQuadX2, hitQuadY2, hitQuadZ2, sideColor.get(), lineColor.get(), shapeMode.get());
375
            }
376
377
            // Render entity
378
            for (Entity collidingEntity : collidingEntities) {
379
                double x = (collidingEntity.getX() - collidingEntity.xOld) * event.tickDelta;
380
                double y = (collidingEntity.getY() - collidingEntity.yOld) * event.tickDelta;
381
                double z = (collidingEntity.getZ() - collidingEntity.zOld) * event.tickDelta;
382
383
                AABB box = collidingEntity.getBoundingBox();
384
                event.renderer.box(x + box.minX, y + box.minY, z + box.minZ, x + box.maxX, y + box.maxY, z + box.maxZ, sideColor.get(), lineColor.get(), shapeMode.get(), 0);
385
            }
386
        }
387
    }
388
}
389
MelaHack (ThunderHack fork)RENDERsrc/main/java/thunder/hack/features/modules/render/Trajectories.javaJava · 190 lines · 9.0 KB

Predicts the paths of arrows and pearls.

SettingsColorModeColorLandedColorModeLandedColor
Trajectories.javaJava · Minecraft 26.2 · 190 lines · 9.0 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.render;
2
3
import com.mojang.blaze3d.vertex.PoseStack;
4
import net.minecraft.core.BlockPos;
5
import net.minecraft.core.registries.Registries;
6
import net.minecraft.util.Mth;
7
import net.minecraft.world.InteractionHand;
8
import net.minecraft.world.entity.Entity;
9
import net.minecraft.world.entity.projectile.arrow.Arrow;
10
import net.minecraft.world.item.*;
11
import net.minecraft.world.item.enchantment.EnchantmentHelper;
12
import net.minecraft.world.item.enchantment.Enchantments;
13
import net.minecraft.world.level.ClipContext;
14
import net.minecraft.world.level.block.Blocks;
15
import net.minecraft.world.phys.AABB;
16
import net.minecraft.world.phys.BlockHitResult;
17
import net.minecraft.world.phys.HitResult;
18
import net.minecraft.world.phys.Vec3;
19
import thunder.hack.features.modules.Module;
20
import thunder.hack.features.modules.client.HudEditor;
21
import thunder.hack.setting.Setting;
22
import thunder.hack.setting.impl.ColorSetting;
23
import thunder.hack.utility.render.Render2DEngine;
24
import thunder.hack.utility.render.Render3DEngine;
25
26
public class Trajectories extends Module {
27
    public Trajectories() {
28
        super("Trajectories", Category.RENDER);
29
    }
30
31
    private final Setting<Mode> mode = new Setting<>("ColorMode", Mode.Sync);
32
    private final Setting<ColorSetting> color = new Setting<>("Color", new ColorSetting(0x2250b4b4), v -> mode.getValue() == Mode.Custom);
33
    private final Setting<Mode> lmode = new Setting<>("LandedColorMode", Mode.Sync);
34
    private final Setting<ColorSetting> lcolor = new Setting<>("LandedColor", new ColorSetting(0x2250b4b4), v -> lmode.getValue() == Mode.Custom);
35
36
    private boolean isThrowable(Item item) {
37
        return item instanceof EnderpearlItem || item instanceof TridentItem || item instanceof ExperienceBottleItem || item instanceof SnowballItem || item instanceof EggItem || item instanceof SplashPotionItem || item instanceof LingeringPotionItem;
38
    }
39
40
    private float getDistance(Item item) {
41
        return item instanceof BowItem ? 1.0f : 0.4f;
42
    }
43
44
    private float getThrowVelocity(Item item) {
45
        if (item instanceof SplashPotionItem || item instanceof LingeringPotionItem) return 0.5f;
46
        if (item instanceof ExperienceBottleItem) return 0.59f;
47
        if (item instanceof TridentItem) return 2f;
48
        return 1.5f;
49
    }
50
51
    private int getThrowPitch(Item item) {
52
        if (item instanceof SplashPotionItem || item instanceof LingeringPotionItem || item instanceof ExperienceBottleItem)
53
            return 20;
54
        return 0;
55
    }
56
57
    @Override
58
    public void onRender3D(PoseStack stack) {
59
        if (false) return;
60
        if (mc.player == null || mc.level == null || !mc.options.getCameraType().isFirstPerson())
61
            return;
62
        InteractionHand hand;
63
64
        ItemStack mainHand = mc.player.getMainHandItem();
65
        ItemStack offHand = mc.player.getOffhandItem();
66
67
        if (mainHand.getItem() instanceof BowItem || mainHand.getItem() instanceof CrossbowItem || isThrowable(mainHand.getItem())) {
68
            hand = InteractionHand.MAIN_HAND;
69
        } else if (offHand.getItem() instanceof BowItem || offHand.getItem() instanceof CrossbowItem || isThrowable(offHand.getItem())) {
70
            hand = InteractionHand.OFF_HAND;
71
        } else return;
72
73
        boolean prev_bob = mc.options.bobView().get();
74
        mc.options.bobView().set(false);
75
76
        var enchantments = mc.level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT);
77
        if ((offHand.getItem() instanceof CrossbowItem && EnchantmentHelper.getItemEnchantmentLevel(enchantments.getOrThrow(Enchantments.MULTISHOT), offHand) != 0) ||
78
                (mainHand.getItem() instanceof CrossbowItem && EnchantmentHelper.getItemEnchantmentLevel(enchantments.getOrThrow(Enchantments.MULTISHOT), mainHand) != 0)) {
79
80
            calcTrajectory(hand == InteractionHand.OFF_HAND ? offHand.getItem() : mainHand.getItem(), mc.player.getYRot() - 10);
81
            calcTrajectory(hand == InteractionHand.OFF_HAND ? offHand.getItem() : mainHand.getItem(), mc.player.getYRot());
82
            calcTrajectory(hand == InteractionHand.OFF_HAND ? offHand.getItem() : mainHand.getItem(), mc.player.getYRot() + 10);
83
84
        } else calcTrajectory(hand == InteractionHand.OFF_HAND ? offHand.getItem() : mainHand.getItem(), mc.player.getYRot());
85
        mc.options.bobView().set(prev_bob);
86
    }
87
88
    private void calcTrajectory(Item item, float yaw) {
89
        double x = Render2DEngine.interpolate(mc.player.xo, mc.player.getX(), Render3DEngine.getTickDelta());
90
        double y = Render2DEngine.interpolate(mc.player.yo, mc.player.getY(), Render3DEngine.getTickDelta());
91
        double z = Render2DEngine.interpolate(mc.player.zo, mc.player.getZ(), Render3DEngine.getTickDelta());
92
93
        y = y + mc.player.getEyeHeight(mc.player.getPose()) - 0.1000000014901161;
94
95
        if (item == mc.player.getMainHandItem().getItem()) {
96
            x = x - Mth.cos(yaw / 180.0f * 3.1415927f) * 0.16f;
97
            z = z - Mth.sin(yaw / 180.0f * 3.1415927f) * 0.16f;
98
        } else {
99
            x = x + Mth.cos(yaw / 180.0f * 3.1415927f) * 0.16f;
100
            z = z + Mth.sin(yaw / 180.0f * 3.1415927f) * 0.16f;
101
        }
102
103
        final float maxDist = getDistance(item);
104
        double motionX = -Mth.sin(yaw / 180.0f * 3.1415927f) * Mth.cos(mc.player.getXRot() / 180.0f * 3.1415927f) * maxDist;
105
        double motionY = -Mth.sin((mc.player.getXRot() - getThrowPitch(item)) / 180.0f * 3.141593f) * maxDist;
106
        double motionZ = Mth.cos(yaw / 180.0f * 3.1415927f) * Mth.cos(mc.player.getXRot() / 180.0f * 3.1415927f) * maxDist;
107
108
        float power = mc.player.getTicksUsingItem() / 20.0f;
109
        power = (power * power + power * 2.0f) / 3.0f;
110
111
        if (power > 1.0f || power == 0) {
112
            power = 1.0f;
113
        }
114
115
        final float distance = Mth.sqrt((float) (motionX * motionX + motionY * motionY + motionZ * motionZ));
116
        motionX /= distance;
117
        motionY /= distance;
118
        motionZ /= distance;
119
120
        final float pow = (item instanceof BowItem ? (power * 2.0f) : item instanceof CrossbowItem ? (2.2f) : 1.0f) * getThrowVelocity(item);
121
122
        motionX *= pow;
123
        motionY *= pow;
124
        motionZ *= pow;
125
        if (!mc.player.onGround())
126
            motionY += mc.player.getDeltaMovement().y();
127
128
        Vec3 lastPos;
129
        for (int i = 0; i < 300; i++) {
130
            lastPos = new Vec3(x, y, z);
131
            x += motionX;
132
            y += motionY;
133
            z += motionZ;
134
            if (mc.level.getBlockState(new BlockPos((int) x, (int) y, (int) z)).getBlock() == Blocks.WATER) {
135
                motionX *= 0.8;
136
                motionY *= 0.8;
137
                motionZ *= 0.8;
138
            } else {
139
                motionX *= 0.99;
140
                motionY *= 0.99;
141
                motionZ *= 0.99;
142
            }
143
144
            if (item instanceof BowItem) motionY -= 0.05000000074505806;
145
            else if (mc.player.getMainHandItem().getItem() instanceof CrossbowItem) motionY -= 0.05000000074505806;
146
            else motionY -= 0.03f;
147
148
149
            Vec3 pos = new Vec3(x, y, z);
150
151
            for (Entity ent : mc.level.entitiesForRendering()) {
152
                if (ent instanceof Arrow || ent.equals(mc.player)) continue;
153
                if (ent.getBoundingBox().intersects(new AABB(x - 0.3, y - 0.3, z - 0.3, x + 0.3, y + 0.3, z + 0.3))) {
154
                    Render3DEngine.OUTLINE_QUEUE.add(new Render3DEngine.OutlineAction(
155
                            ent.getBoundingBox(),
156
                            lmode.getValue() == Mode.Sync ? HudEditor.getColor(i * 10) : lcolor.getValue().getColorObject(),
157
                            2f));
158
                    Render3DEngine.FILLED_QUEUE.add(new Render3DEngine.FillAction(
159
                            ent.getBoundingBox(), lmode.getValue() == Mode.Sync ? Render2DEngine.injectAlpha(HudEditor.getColor(i * 10), 100) : lcolor.getValue().getColorObject()
160
                    ));
161
                    break;
162
                }
163
            }
164
165
            BlockHitResult bhr = mc.level.clip(new ClipContext(lastPos, pos, ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, mc.player));
166
            if (bhr != null && bhr.getType() == HitResult.Type.BLOCK) {
167
                Render3DEngine.OUTLINE_SIDE_QUEUE.add(new Render3DEngine.OutlineSideAction(
168
                        new AABB(bhr.getBlockPos()), lmode.getValue() == Mode.Sync ? HudEditor.getColor(i * 10) : lcolor.getValue().getColorObject(), 2f, bhr.getDirection()
169
                ));
170
                Render3DEngine.FILLED_SIDE_QUEUE.add(new Render3DEngine.FillSideAction(
171
                        new AABB(bhr.getBlockPos()), lmode.getValue() == Mode.Sync ? Render2DEngine.injectAlpha(HudEditor.getColor(i * 10), 100) : lcolor.getValue().getColorObject(), bhr.getDirection()
172
                ));
173
174
175
                break;
176
            }
177
178
            if (y <= -65) break;
179
            if (motionX == 0 && motionY == 0 && motionZ == 0) continue;
180
181
            Render3DEngine.drawLine(lastPos, pos, mode.getValue() == Mode.Sync ? HudEditor.getColor(i) : color.getValue().getColorObject());
182
        }
183
    }
184
185
    private enum Mode {
186
        Custom,
187
        Sync
188
    }
189
}
190
OfflineClientRENDERsrc/main/java/com/jellypudding/offlineclient/modules/render/Trajectories.javaJava · 459 lines · 20.8 KB

Shows the path a thrown or shot item will take.

SettingsItemsOther playersFired projectilesIgnore wither skullsSkip first ticksStepsColour by resultLanding markerPosition boxesPosition box size
Trajectories.javaJava · Minecraft 26.2 · 459 lines · 20.8 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.render;
2
3
import com.jellypudding.offlineclient.event.Subscribe;
4
import com.jellypudding.offlineclient.event.events.Render3DEvent;
5
import com.jellypudding.offlineclient.module.Category;
6
import com.jellypudding.offlineclient.module.Module;
7
import com.jellypudding.offlineclient.render.BoxStyle;
8
import com.jellypudding.offlineclient.render.DrawBatch;
9
import com.jellypudding.offlineclient.setting.BoolSetting;
10
import com.jellypudding.offlineclient.setting.NumberSetting;
11
import com.jellypudding.offlineclient.setting.RegistryListSetting;
12
import com.jellypudding.offlineclient.util.EntityUtil;
13
import com.jellypudding.offlineclient.util.ItemUtil;
14
import net.minecraft.core.BlockPos;
15
import net.minecraft.core.Direction;
16
import net.minecraft.core.component.DataComponents;
17
import net.minecraft.core.registries.BuiltInRegistries;
18
import net.minecraft.tags.FluidTags;
19
import net.minecraft.world.entity.Entity;
20
import net.minecraft.world.entity.player.Player;
21
import net.minecraft.world.entity.projectile.Projectile;
22
import net.minecraft.world.entity.projectile.ProjectileUtil;
23
import net.minecraft.world.entity.projectile.arrow.AbstractArrow;
24
import net.minecraft.world.entity.projectile.arrow.ThrownTrident;
25
import net.minecraft.world.entity.projectile.hurtingprojectile.AbstractHurtingProjectile;
26
import net.minecraft.world.entity.projectile.hurtingprojectile.WitherSkull;
27
import net.minecraft.world.entity.projectile.hurtingprojectile.windcharge.AbstractWindCharge;
28
import net.minecraft.world.entity.projectile.throwableitemprojectile.AbstractThrownPotion;
29
import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrowableItemProjectile;
30
import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownExperienceBottle;
31
import net.minecraft.world.item.BowItem;
32
import net.minecraft.world.item.CrossbowItem;
33
import net.minecraft.world.item.EggItem;
34
import net.minecraft.world.item.EnderpearlItem;
35
import net.minecraft.world.item.ExperienceBottleItem;
36
import net.minecraft.world.item.FishingRodItem;
37
import net.minecraft.world.item.Item;
38
import net.minecraft.world.item.ItemStack;
39
import net.minecraft.world.item.Items;
40
import net.minecraft.world.item.ProjectileWeaponItem;
41
import net.minecraft.world.item.SnowballItem;
42
import net.minecraft.world.item.ThrowablePotionItem;
43
import net.minecraft.world.item.TridentItem;
44
import net.minecraft.world.item.WindChargeItem;
45
import net.minecraft.world.item.component.ChargedProjectiles;
46
import net.minecraft.world.item.enchantment.Enchantments;
47
import net.minecraft.world.level.ClipContext;
48
import net.minecraft.world.phys.AABB;
49
import net.minecraft.world.phys.BlockHitResult;
50
import net.minecraft.world.phys.EntityHitResult;
51
import net.minecraft.world.phys.HitResult;
52
import net.minecraft.world.phys.Vec3;
53
54
import java.util.ArrayList;
55
import java.util.List;
56
57
// Uses the same launch speed and gravity and drag as the real projectile.
58
public final class Trajectories extends Module {
59
60
    // How the game moves a projectile each tick. The order matters.
61
    private enum Motion {
62
        // Arrows and tridents. Move first and then slow down and fall.
63
        ARROW,
64
        // Thrown items. Fall and slow down first and then move.
65
        THROWN,
66
        // Fireballs and wind charges. Fall then move then slow down.
67
        HURTING,
68
        // Fishing bobbers. Fall then move then slow down.
69
        BOBBER
70
    }
71
72
    private record Launch(double power, double gravity, double airDrag, double waterDrag,
73
                          double pitchOffset, Motion motion, boolean stopsInWater) {
74
75
        private Launch withPower(double newPower) {
76
            return new Launch(newPower, gravity, airDrag, waterDrag, pitchOffset, motion, stopsInWater);
77
        }
78
79
        private Launch weightless() {
80
            return new Launch(power, 0, airDrag, waterDrag, pitchOffset, motion, stopsInWater);
81
        }
82
    }
83
84
    private static final Launch ARROW = new Launch(3, 0.05, 0.99, 0.6, 0, Motion.ARROW, false);
85
    private static final Launch CROSSBOW_ARROW = new Launch(3.15, 0.05, 0.99, 0.6, 0, Motion.ARROW, false);
86
    private static final Launch FIREWORK = new Launch(1.6, 0, 1, 1, 0, Motion.ARROW, false);
87
    private static final Launch TRIDENT = new Launch(2.5, 0.05, 0.99, 0.99, 0, Motion.ARROW, false);
88
    private static final Launch THROWABLE = new Launch(1.5, 0.03, 0.99, 0.8, 0, Motion.THROWN, false);
89
    private static final Launch POTION = new Launch(0.5, 0.05, 0.99, 0.8, -20, Motion.THROWN, false);
90
    private static final Launch XP_BOTTLE = new Launch(0.7, 0.07, 0.99, 0.8, -20, Motion.THROWN, false);
91
    private static final Launch WIND_CHARGE = new Launch(1.5, 0, 1, 1, 0, Motion.HURTING, false);
92
    private static final Launch EXPLOSIVE = new Launch(0, 0, 0.95, 0.8, 0, Motion.HURTING, false);
93
    private static final Launch BOBBER = new Launch(0, 0.03, 0.92, 0, 0, Motion.BOBBER, true);
94
95
    private static final int COLOR_BLOCK = 0xFF40FF60;
96
    private static final int COLOR_ENTITY = 0xFFFF4040;
97
    // A multishot crossbow fires its side arrows this far off the middle one.
98
    private static final double MULTISHOT_ANGLE = 10;
99
    // Half the width of the landing marker.
100
    private static final double MARKER_HALF = 0.25;
101
    // How thick the flat landing marker is. Its faces need a direction.
102
    private static final double MARKER_DEPTH = 0.005;
103
    // Other players further off than this get no arc.
104
    private static final double OTHER_RANGE_SQ = 64 * 64;
105
106
    private record Path(List<Vec3> points, HitResult.Type type, List<Entity> hits, BlockHitResult landing) {
107
    }
108
109
    // Where a projectile is at one moment in its flight.
110
    private record Shot(Vec3 pos, Vec3 velocity) {
111
    }
112
113
    private final RegistryListSetting<Item> items = new RegistryListSetting<>("Items",
114
        "Which held items get an arc.", BuiltInRegistries.ITEM, throwableItems());
115
    private final BoolSetting otherPlayers = new BoolSetting("Other players",
116
        "Also show where other players are aiming.", true);
117
    private final BoolSetting firedProjectiles = new BoolSetting("Fired projectiles",
118
        "Also predict the rest of the flight of projectiles already in the air.", false);
119
    private final BoolSetting ignoreWitherSkulls = new BoolSetting("Ignore wither skulls",
120
        "Wither skulls get no arc.", false).under(firedProjectiles);
121
    private final NumberSetting skipFirstTicks = new NumberSetting("Skip first ticks",
122
        "Leaves out the first points of your own arc so the line does not start in your face.",
123
        3, 0, 20, 1, " ticks").min(0);
124
    private final NumberSetting steps = new NumberSetting("Steps",
125
        "How many ticks of flight to predict.", 200, 20, 500, 10).min(1).max(2000);
126
    private final BoxStyle style = new BoxStyle(BoxStyle.Shape.BOTH, 35f);
127
    private final BoolSetting resultColour = new BoolSetting("Colour by result",
128
        "The arc turns green when it lands on a block and red when it hits something.", true);
129
    private final BoolSetting landingMarker = new BoolSetting("Landing marker",
130
        "Draw a flat square on the block face the projectile lands on.", true);
131
    private final BoolSetting positionBoxes = new BoolSetting("Position boxes",
132
        "Draw a tiny box at every predicted tick along the arc.", false);
133
    private final NumberSetting positionBoxSize = new NumberSetting("Position box size",
134
        "Half the size of those boxes.", 0.02, 0.01, 0.1, 0.01, " blocks").under(positionBoxes);
135
    private final BoxStyle positionStyle = new BoxStyle("Position", BoxStyle.Shape.BOTH, 35f).under(positionBoxes);
136
137
    public Trajectories() {
138
        super("Trajectories", "Shows the path a thrown or shot item will take.", Category.RENDER);
139
        addSettings(items, otherPlayers, firedProjectiles, ignoreWitherSkulls, skipFirstTicks, steps);
140
        addSettings(style.settings());
141
        addSettings(resultColour, landingMarker, positionBoxes, positionBoxSize);
142
        addSettings(positionStyle.settings());
143
        searchTags("bow", "arrow", "aim");
144
    }
145
146
    // Every item that can be shot or thrown.
147
    private static List<Item> throwableItems() {
148
        List<Item> list = new ArrayList<>();
149
        for (Item item : BuiltInRegistries.ITEM) {
150
            if (item instanceof ProjectileWeaponItem || item instanceof FishingRodItem
151
                || item instanceof TridentItem || item instanceof SnowballItem || item instanceof EggItem
152
                || item instanceof EnderpearlItem || item instanceof ExperienceBottleItem
153
                || item instanceof ThrowablePotionItem || item instanceof WindChargeItem) {
154
                list.add(item);
155
            }
156
        }
157
        return list;
158
    }
159
160
    @Subscribe
161
    private void onRender3D(Render3DEvent event) {
162
        if (!inGame()) {
163
            return;
164
        }
165
        float partialTicks = event.getPartialTicks();
166
        draw(event.getBatch(), mc.player, partialTicks);
167
        if (otherPlayers.isOn()) {
168
            for (Player player : mc.level.players()) {
169
                if (player != mc.player && !player.isSpectator()
170
                    && player.distanceToSqr(mc.player) <= OTHER_RANGE_SQ) {
171
                    draw(event.getBatch(), player, partialTicks);
172
                }
173
            }
174
        }
175
        if (firedProjectiles.isOn()) {
176
            for (Entity entity : mc.level.entitiesForRendering()) {
177
                if (entity instanceof Projectile projectile) {
178
                    drawFired(event.getBatch(), projectile, partialTicks);
179
                }
180
            }
181
        }
182
    }
183
184
    // Also called by BowAimbot for its own arc whilst this module is off.
185
    public void draw(DrawBatch batch, Player player, float partialTicks) {
186
        ItemStack stack = player.getMainHandItem();
187
        Launch launch = launchFor(player, stack);
188
        if (launch == null) {
189
            stack = player.getOffhandItem();
190
            launch = launchFor(player, stack);
191
        }
192
        if (launch == null) {
193
            return;
194
        }
195
        int skip = player == mc.player ? skipFirstTicks.getInt() : 0;
196
        int pierce = stack.getItem() instanceof ProjectileWeaponItem
197
            ? ItemUtil.enchantLevel(Enchantments.PIERCING, stack) : 0;
198
        drawPath(batch, fly(player, launch, leaveHand(player, launch, partialTicks, 0), pierce),
199
            partialTicks, skip);
200
        if (stack.getItem() instanceof CrossbowItem && ItemUtil.enchantLevel(Enchantments.MULTISHOT, stack) > 0) {
201
            for (double angle : new double[] {MULTISHOT_ANGLE, -MULTISHOT_ANGLE}) {
202
                drawPath(batch, fly(player, launch, leaveHand(player, launch, partialTicks, angle), pierce),
203
                    partialTicks, skip);
204
            }
205
        }
206
    }
207
208
    private void drawFired(DrawBatch batch, Projectile projectile, float partialTicks) {
209
        if (ignoreWitherSkulls.isOn() && projectile instanceof WitherSkull) {
210
            return;
211
        }
212
        // A trident flying home on loyalty and an arrow stuck in a block go nowhere new.
213
        if (projectile instanceof AbstractArrow arrow && (arrow.isNoPhysics() || arrow.isInGround())) {
214
            return;
215
        }
216
        Launch launch = launchFor(projectile);
217
        if (launch == null) {
218
            return;
219
        }
220
        if (projectile.isNoGravity()) {
221
            launch = launch.weightless();
222
        }
223
        int pierce = projectile instanceof AbstractArrow arrow ? arrow.getPierceLevel() : 0;
224
        Vec3 start = projectile.getPosition(partialTicks);
225
        Path path = fly(projectile, launch, new Shot(projectile.position(), projectile.getDeltaMovement()), pierce);
226
        if (!path.points().isEmpty()) {
227
            path.points().set(0, start);
228
        }
229
        drawPath(batch, path, partialTicks, 0);
230
    }
231
232
    private void drawPath(DrawBatch batch, Path path, float partialTicks, int skip) {
233
        List<Vec3> points = path.points();
234
        if (points.size() < 2) {
235
            return;
236
        }
237
        int line = style.lineColor();
238
        int fill = line;
239
        if (resultColour.isOn() && path.type() != HitResult.Type.MISS) {
240
            line = path.type() == HitResult.Type.BLOCK ? COLOR_BLOCK : COLOR_ENTITY;
241
            fill = line;
242
        }
243
        int first = points.size() <= skip ? 0 : skip;
244
        for (int i = first + 1; i < points.size(); i++) {
245
            batch.line(points.get(i - 1), points.get(i), line, true);
246
            if (positionBoxes.isOn()) {
247
                double half = positionBoxSize.getValue();
248
                Vec3 point = points.get(i);
249
                positionStyle.draw(batch, new AABB(point.subtract(half, half, half), point.add(half, half, half)), true);
250
            }
251
        }
252
        if (landingMarker.isOn() && path.landing() != null) {
253
            style.draw(batch, marker(path.landing()), line, fill, true);
254
        }
255
        for (Entity hit : path.hits()) {
256
            style.draw(batch, EntityUtil.lerpedBox(hit, partialTicks), COLOR_ENTITY, COLOR_ENTITY, true);
257
        }
258
    }
259
260
    // A half block square lying flat on the face that was hit.
261
    private static AABB marker(BlockHitResult hit) {
262
        Vec3 at = hit.getLocation();
263
        Direction.Axis axis = hit.getDirection().getAxis();
264
        double x = axis == Direction.Axis.X ? MARKER_DEPTH : MARKER_HALF;
265
        double y = axis == Direction.Axis.Y ? MARKER_DEPTH : MARKER_HALF;
266
        double z = axis == Direction.Axis.Z ? MARKER_DEPTH : MARKER_HALF;
267
        return new AABB(at.subtract(x, y, z), at.add(x, y, z));
268
    }
269
270
    // Null if the item cannot be thrown or shot or is not on the list.
271
    private Launch launchFor(Player player, ItemStack stack) {
272
        if (stack.isEmpty() || !items.contains(stack.getItem())) {
273
            return null;
274
        }
275
        Item item = stack.getItem();
276
        if (item instanceof BowItem) {
277
            double charge = 1;
278
            if (player.isUsingItem() && player.getUseItem() == stack) {
279
                charge = BowItem.getPowerForTime(player.getTicksUsingItem());
280
                // A bow this early in the draw does not fire.
281
                if (charge < 0.1) {
282
                    return null;
283
                }
284
            }
285
            return ARROW.withPower(charge * ARROW.power());
286
        }
287
        if (item instanceof CrossbowItem) {
288
            if (!CrossbowItem.isCharged(stack)) {
289
                return null;
290
            }
291
            ChargedProjectiles loaded = stack.get(DataComponents.CHARGED_PROJECTILES);
292
            if (loaded != null && loaded.contains(Items.FIREWORK_ROCKET)) {
293
                return FIREWORK;
294
            }
295
            return CROSSBOW_ARROW;
296
        }
297
        if (item instanceof TridentItem) {
298
            return TRIDENT;
299
        }
300
        if (item instanceof SnowballItem || item instanceof EggItem || item instanceof EnderpearlItem) {
301
            return THROWABLE;
302
        }
303
        if (item instanceof ExperienceBottleItem) {
304
            return XP_BOTTLE;
305
        }
306
        if (item instanceof ThrowablePotionItem) {
307
            return POTION;
308
        }
309
        if (item instanceof WindChargeItem) {
310
            return WIND_CHARGE;
311
        }
312
        if (item instanceof FishingRodItem) {
313
            return BOBBER;
314
        }
315
        return null;
316
    }
317
318
    // The physics of a projectile already in the air. Null for kinds that are not predicted.
319
    private static Launch launchFor(Projectile projectile) {
320
        if (projectile instanceof ThrownTrident) {
321
            return TRIDENT;
322
        }
323
        if (projectile instanceof AbstractArrow) {
324
            return ARROW;
325
        }
326
        if (projectile instanceof ThrownExperienceBottle) {
327
            return XP_BOTTLE;
328
        }
329
        if (projectile instanceof AbstractThrownPotion) {
330
            return POTION;
331
        }
332
        if (projectile instanceof ThrowableItemProjectile) {
333
            return THROWABLE;
334
        }
335
        if (projectile instanceof AbstractWindCharge) {
336
            return WIND_CHARGE;
337
        }
338
        if (projectile instanceof AbstractHurtingProjectile) {
339
            return EXPLOSIVE;
340
        }
341
        return null;
342
    }
343
344
    // The position and speed the projectile starts with. The angle turns the aim left or right.
345
    private Shot leaveHand(Player shooter, Launch launch, float partialTicks, double angle) {
346
        double yaw = shooter.getYRot(partialTicks) + angle;
347
        double pitch = shooter.getXRot(partialTicks);
348
        Vec3 origin = shooter.getPosition(partialTicks);
349
        Vec3 pos;
350
        Vec3 velocity;
351
352
        if (launch.motion() == Motion.BOBBER) {
353
            double sinYaw = Math.sin(Math.toRadians(-yaw) - Math.PI);
354
            double cosYaw = Math.cos(Math.toRadians(-yaw) - Math.PI);
355
            double cosPitch = -Math.cos(Math.toRadians(-pitch));
356
            double sinPitch = Math.sin(Math.toRadians(-pitch));
357
            pos = origin.add(-sinYaw * 0.3, shooter.getEyeHeight(), -cosYaw * 0.3);
358
            velocity = new Vec3(-sinYaw, Math.clamp(-(sinPitch / cosPitch), -5, 5), -cosYaw);
359
            double length = velocity.length();
360
            velocity = velocity.scale(0.6 / length + 0.5);
361
        } else {
362
            pos = origin.add(0, shooter.getEyeHeight() - 0.1, 0);
363
            double radYaw = Math.toRadians(yaw);
364
            double radPitch = Math.toRadians(pitch);
365
            double x = -Math.sin(radYaw) * Math.cos(radPitch);
366
            double y = -Math.sin(Math.toRadians(pitch + launch.pitchOffset()));
367
            double z = Math.cos(radYaw) * Math.cos(radPitch);
368
            velocity = new Vec3(x, y, z).normalize().scale(launch.power());
369
            // The game adds the thrower's own movement to the projectile.
370
            Vec3 movement = shooter.getKnownMovement();
371
            velocity = velocity.add(movement.x, shooter.onGround() ? 0 : movement.y, movement.z);
372
        }
373
        return new Shot(pos, velocity);
374
    }
375
376
    // Steps the projectile forward until it lands or the step budget runs out.
377
    // A piercing arrow passes through that many entities before it stops.
378
    private Path fly(Entity shooter, Launch launch, Shot shot, int pierce) {
379
        Vec3 pos = shot.pos();
380
        Vec3 velocity = shot.velocity();
381
382
        List<Vec3> points = new ArrayList<>();
383
        List<Entity> hits = new ArrayList<>();
384
        points.add(pos);
385
        HitResult.Type type = HitResult.Type.MISS;
386
        BlockHitResult landing = null;
387
        int minY = mc.level.getMinY();
388
        int maxSteps = steps.getInt();
389
        int piercesLeft = pierce;
390
391
        for (int i = 0; i < maxSteps; i++) {
392
            Vec3 previous = pos;
393
            boolean inWater = mc.level.getFluidState(BlockPos.containing(pos)).is(FluidTags.WATER);
394
            double drag = inWater ? launch.waterDrag() : launch.airDrag();
395
396
            Shot next = advance(launch, pos, velocity, drag);
397
            pos = next.pos();
398
            velocity = next.velocity();
399
400
            if (pos.y < minY) {
401
                points.add(pos);
402
                break;
403
            }
404
405
            BlockHitResult blockHit = mc.level.clip(new ClipContext(previous, pos,
406
                ClipContext.Block.COLLIDER,
407
                launch.stopsInWater() ? ClipContext.Fluid.ANY : ClipContext.Fluid.NONE, shooter));
408
            Vec3 end = blockHit.getType() == HitResult.Type.MISS ? pos : blockHit.getLocation();
409
410
            boolean stopped = false;
411
            for (EntityHitResult entityHit : ProjectileUtil.getManyEntityHitResult(mc.level, shooter, previous, end,
412
                new AABB(previous, end).inflate(1),
413
                entity -> entity != shooter && !entity.isSpectator() && entity.isAlive() && entity.isPickable(), false)) {
414
                if (hits.contains(entityHit.getEntity())) {
415
                    continue;
416
                }
417
                hits.add(entityHit.getEntity());
418
                if (piercesLeft <= 0) {
419
                    points.add(entityHit.getLocation());
420
                    type = HitResult.Type.ENTITY;
421
                    stopped = true;
422
                    break;
423
                }
424
                piercesLeft--;
425
            }
426
            if (stopped) {
427
                break;
428
            }
429
            if (blockHit.getType() != HitResult.Type.MISS) {
430
                points.add(blockHit.getLocation());
431
                type = HitResult.Type.BLOCK;
432
                landing = blockHit;
433
                break;
434
            }
435
            points.add(pos);
436
            if (velocity.lengthSqr() < 1.0E-6) {
437
                break;
438
            }
439
        }
440
        return new Path(points, type, hits, landing);
441
    }
442
443
    // One tick of motion. Each projectile applies drag and gravity in its own order.
444
    private static Shot advance(Launch launch, Vec3 pos, Vec3 velocity, double drag) {
445
        return switch (launch.motion()) {
446
            case ARROW -> new Shot(pos.add(velocity),
447
                velocity.scale(drag).subtract(0, launch.gravity(), 0));
448
            case THROWN -> {
449
                Vec3 moved = velocity.subtract(0, launch.gravity(), 0).scale(drag);
450
                yield new Shot(pos.add(moved), moved);
451
            }
452
            case HURTING, BOBBER -> {
453
                Vec3 fallen = velocity.subtract(0, launch.gravity(), 0);
454
                yield new Shot(pos.add(fallen), fallen.scale(drag));
455
            }
456
        };
457
    }
458
}
459
LiquidBounce (Kotlin)RENDERsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/render/trajectories/ModuleTrajectories.ktKotlin · 244 lines · 9.9 KB

Allows you to see where projectiles will land.

SettingsMaxSimulatedTicksMaxRenderDistanceCullBehindPlayerShowMultiShotLineWidthActiveLineWidthTrajectoryTypesShow
ModuleTrajectories.ktKotlin · Minecraft 26.2 · 244 lines · 9.9 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
3
 *
4
 * Copyright (c) 2015 - 2026 CCBlueX
5
 *
6
 * LiquidBounce is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * LiquidBounce is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
package net.ccbluex.liquidbounce.features.module.modules.render.trajectories
20
21
import net.ccbluex.liquidbounce.config.types.list.Tagged
22
import net.ccbluex.liquidbounce.event.events.WorldRenderEvent
23
import net.ccbluex.liquidbounce.event.handler
24
import net.ccbluex.liquidbounce.features.module.ClientModule
25
import net.ccbluex.liquidbounce.features.module.ModuleCategories
26
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug.debugParameter
27
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleFreeCam
28
import net.ccbluex.liquidbounce.render.WorldRenderEnvironment
29
import net.ccbluex.liquidbounce.render.engine.type.Color4b
30
import net.ccbluex.liquidbounce.render.renderEnvironment
31
import net.ccbluex.liquidbounce.utils.aiming.RotationManager
32
import net.ccbluex.liquidbounce.utils.aiming.data.Rotation
33
import net.ccbluex.liquidbounce.utils.entity.handItems
34
import net.ccbluex.liquidbounce.utils.entity.rotation
35
import net.ccbluex.liquidbounce.utils.math.dot
36
import net.ccbluex.liquidbounce.utils.math.sq
37
import net.ccbluex.liquidbounce.utils.render.trajectory.EntityTrajectoryResolver
38
import net.ccbluex.liquidbounce.utils.render.trajectory.HeldItemTrajectoryResolver
39
import net.ccbluex.liquidbounce.utils.render.trajectory.TrajectoryInfoRenderer
40
import net.ccbluex.liquidbounce.utils.render.trajectory.TrajectoryDisplayResolver
41
import net.ccbluex.liquidbounce.utils.render.trajectory.TrajectoryType
42
import net.minecraft.world.entity.TraceableEntity
43
import net.minecraft.world.entity.player.Player
44
import net.minecraft.world.item.FishingRodItem
45
import net.minecraft.world.phys.Vec3
46
47
/**
48
 * Trajectories module
49
 *
50
 * Allows you to see where projectile items will land.
51
 */
52
@Suppress("MagicNumber")
53
object ModuleTrajectories : ClientModule("Trajectories", ModuleCategories.RENDER) {
54
    private val maxSimulatedTicks by int("MaxSimulatedTicks", 240, 1..1000, "ticks")
55
    private val maxRenderDistance by int("MaxRenderDistance", 96, 16..512, "m")
56
    private val cullBehindPlayer by boolean("CullBehindPlayer", false)
57
    private val showMultiShot by boolean("ShowMultiShot", true)
58
    private val lineWidth by float("LineWidth", 1f, 1f..16f)
59
    private val activeLineWidth by float("ActiveLineWidth", 2f, 1f..16f)
60
61
    private val trajectoryTypes by multiEnumChoice("TrajectoryTypes", TrajectoryType.entries, canBeNone = false)
62
63
    private val show by multiEnumChoice(
64
        "Show",
65
        Show.OTHER_PLAYERS,
66
        Show.ACTIVE_TRAJECTORY_ARROW
67
    )
68
69
    private val alwaysShowBow get() = Show.ALWAYS_SHOW_BOW in show
70
    private val otherPlayers get() = Show.OTHER_PLAYERS in show
71
    private val activeTrajectoryArrow get() = Show.ACTIVE_TRAJECTORY_ARROW in show
72
    private val activeTrajectoryOther get() = Show.ACTIVE_TRAJECTORY_OTHER in show
73
74
    init {
75
        tree(TrajectoryDetailedInfoRenderer)
76
    }
77
78
    internal val simulationResults =
79
        mutableListOf<Pair<TrajectoryInfoRenderer, TrajectoryInfoRenderer.SimulationResult>>()
80
81
    override fun onDisabled() {
82
        simulationResults.clear()
83
    }
84
85
    val renderHandler = handler<WorldRenderEvent> { event ->
86
        simulationResults.clear()
87
        event.renderEnvironment {
88
            val viewPos = camera.position()
89
            val viewDirection = camera.forwardVector()
90
            val maxRenderDistanceSq = maxRenderDistance.sq().toDouble()
91
92
            for (entity in world.entitiesForRendering()) {
93
                val delta = entity.position().subtract(viewPos)
94
                val deltaLengthSq = delta.lengthSqr()
95
                if (deltaLengthSq > maxRenderDistanceSq ||
96
                    cullBehindPlayer && delta.dot(viewDirection) < 0.0 && deltaLengthSq > 9.0) {
97
                    continue
98
                }
99
100
                val (trajectoryInfo, trajectoryType) = EntityTrajectoryResolver.resolveEntityTrajectory(
101
                    entity,
102
                    activeTrajectoryArrow,
103
                    activeTrajectoryOther
104
                ) ?: continue
105
106
                if (trajectoryType !in trajectoryTypes) continue
107
108
                val displayOwner = (entity as? TraceableEntity)?.owner
109
                val icon = TrajectoryDisplayResolver.resolveEntityIcon(
110
                    entity, activeTrajectoryArrow, activeTrajectoryOther
111
                )
112
                val trajectoryRenderer = TrajectoryInfoRenderer(
113
                    simulationOwner = displayOwner ?: entity,
114
                    displayOwner = displayOwner,
115
                    icon = icon,
116
                    velocity = entity.deltaMovement,
117
                    pos = entity.position(),
118
                    trajectoryInfo = trajectoryInfo,
119
                    trajectoryType = trajectoryType,
120
                    type = TrajectoryInfoRenderer.Type.REAL,
121
                    renderOffset = Vec3.ZERO,
122
                )
123
124
                val color = TrajectoryDisplayResolver.resolveTrajectoryColor(
125
                    trajectoryType = trajectoryType,
126
                    colorSource = icon,
127
                    entity = entity,
128
                )
129
130
                simulationResults += trajectoryRenderer to trajectoryRenderer.drawTrajectoryForProjectile(
131
                    maxSimulatedTicks,
132
                    event.partialTicks,
133
                    trajectoryColor = color,
134
                    blockHitColor = color,
135
                    entityHitColor = color,
136
                    lineWidth = activeLineWidth,
137
                )
138
            }
139
140
            if (otherPlayers) {
141
                for (otherPlayer in world.players()) {
142
                    if (otherPlayer !== player) {
143
                        val delta = otherPlayer.eyePosition.subtract(viewPos)
144
                        val deltaLengthSq = delta.lengthSqr()
145
                        if (deltaLengthSq > maxRenderDistanceSq) {
146
                            continue
147
                        }
148
                        if (cullBehindPlayer && delta.dot(viewDirection) < 0.0 && deltaLengthSq > 9.0) {
149
                            continue
150
                        }
151
                    }
152
153
                    // Including the user
154
                    drawHypotheticalTrajectory(otherPlayer, event.partialTicks)
155
                }
156
            } else {
157
                drawHypotheticalTrajectory(player, event.partialTicks)
158
            }
159
        }
160
161
        debugParameter("TrajectoryCount") { simulationResults.size }
162
    }
163
164
    /**
165
     * Draws the trajectory for an item in the player's hand
166
     */
167
    private fun WorldRenderEnvironment.drawHypotheticalTrajectory(
168
        otherPlayer: Player,
169
        partialTicks: Float,
170
    ) {
171
        val shouldFilterHeldFishingRod = otherPlayer.fishing != null &&
172
            activeTrajectoryOther &&
173
            TrajectoryType.FishingBobber in trajectoryTypes
174
175
        val (trajectoryShotDescriptors, stack) = otherPlayer.handItems.firstNotNullOfOrNull { stack ->
176
            if (shouldFilterHeldFishingRod && stack.item is FishingRodItem) {
177
                return@firstNotNullOfOrNull null
178
            }
179
180
            HeldItemTrajectoryResolver.resolveHeldItemShots(
181
                otherPlayer,
182
                stack,
183
                alwaysShowBow,
184
                includeMultiShot = showMultiShot
185
            )?.let {
186
                it to stack
187
            }
188
        } ?: return
189
190
        val rotation = if (otherPlayer === player) {
191
            if (ModuleFreeCam.running) {
192
                RotationManager.serverRotation
193
            } else {
194
                RotationManager.activeRotationTarget?.rotation
195
                    ?: RotationManager.currentRotation ?: otherPlayer.rotation
196
            }
197
        } else {
198
            otherPlayer.rotation
199
        }
200
201
        trajectoryShotDescriptors.forEach { shotDescriptor ->
202
            if (shotDescriptor.trajectoryType !in trajectoryTypes) {
203
                return@forEach
204
            }
205
206
            val shotRotation = Rotation(
207
                yaw = rotation.yaw + shotDescriptor.yawOffsetDegrees,
208
                pitch = rotation.pitch,
209
                isNormalized = rotation.isNormalized
210
            )
211
212
            val renderer = TrajectoryInfoRenderer.getHypotheticalTrajectory(
213
                simulationOwner = otherPlayer,
214
                icon = if (shotDescriptor.icon.isEmpty) stack else shotDescriptor.icon,
215
                trajectoryInfo = shotDescriptor.trajectoryInfo,
216
                trajectoryType = shotDescriptor.trajectoryType,
217
                rotation = shotRotation,
218
                partialTicks = partialTicks
219
            )
220
221
            simulationResults += renderer to renderer.drawTrajectoryForProjectile(
222
                maxSimulatedTicks,
223
                partialTicks,
224
                trajectoryColor = TrajectoryDisplayResolver.resolveTrajectoryColor(
225
                    trajectoryType = shotDescriptor.trajectoryType,
226
                    colorSource = shotDescriptor.colorSource,
227
                ),
228
                blockHitColor = Color4b(0, 160, 255, 150),
229
                entityHitColor = Color4b.RED.alpha(100),
230
                lineWidth = lineWidth,
231
            )
232
        }
233
    }
234
235
    private enum class Show(
236
        override val tag: String
237
    ) : Tagged {
238
        ALWAYS_SHOW_BOW("AlwaysShowBow"),
239
        OTHER_PLAYERS("OtherPlayers"),
240
        ACTIVE_TRAJECTORY_ARROW("ActiveTrajectoryArrow"),
241
        ACTIVE_TRAJECTORY_OTHER("ActiveTrajectoryOther"),
242
    }
243
}
244