Подпишитесь на наш Telegram-канал, чтобы всегда быть в курсе важных обновлений! Перейти

Вопрос Фикс ротки зенитх рекод

Начинающий
Начинающий
Статус
Оффлайн
Регистрация
15 Дек 2024
Сообщения
54
Реакции
0
типо запускаю с сурсов и нейро ротация работает нормально билжу и запускаю с легаси то эта нейро ротация после выключения ауры продолжает смотреть в 1 точку помогите зафиксить без негатива
 
типо запускаю с сурсов и нейро ротация работает нормально билжу и запускаю с легаси то эта нейро ротация после выключения ауры продолжает смотреть в 1 точку помогите зафиксить без негатива
ну ты бы хоть скинул ротацию и всё что с ней связано
 
ну ты бы хоть скинул ротацию и всё что с ней связано
AimManager:
Expand Collapse Copy
package zenith.zov.base.rotation;


import lombok.Getter;

import net.minecraft.util.math.MathHelper;
import zenith.zov.base.rotation.mods.AIRotationMode;
import zenith.zov.base.rotation.mods.InstantRotationMode;
import zenith.zov.base.rotation.mods.InterpolationRotationMode;
import zenith.zov.base.rotation.mods.config.AiRotationConfig;
import zenith.zov.base.rotation.mods.config.InstantRotationConfig;
import zenith.zov.base.rotation.mods.config.InterpolationRotationConfig;
import zenith.zov.base.rotation.mods.config.api.RotationConfig;
import zenith.zov.base.rotation.mods.config.api.RotationModeType;
import zenith.zov.utility.game.other.MessageUtil;
import zenith.zov.utility.game.player.rotation.Rotation;
import zenith.zov.utility.game.player.rotation.RotationDelta;
import zenith.zov.utility.interfaces.IClient;

public class AimManager implements IClient {

    private final InterpolationRotationMode interpolationMod = new InterpolationRotationMode();
    private final InstantRotationMode instantMod = new InstantRotationMode();
    private final AIRotationMode smoothMod = new AIRotationMode();
    @Getter
    private final RotationConfig instantSetup = new InstantRotationConfig();
    @Getter
    private final RotationConfig aiSetup = AiRotationConfig.builder().build();


    public Rotation rotate(RotationConfig config, Rotation targetRotation) {
        if (config.getType() != RotationModeType.INSTANT) {
            RotationDelta deltaToTarget = zenith.getRotationManager().getCurrentRotation().rotationDeltaTo(targetRotation);
            float maxInitialDiff = 270f; // 180 + 90
            float progress = MathHelper.clamp(1f - (Math.abs(deltaToTarget.getDeltaYaw()) + Math.abs(deltaToTarget.getDeltaPitch())) / maxInitialDiff, 0, 1);

            RotationDelta offsets = getOffset(deltaToTarget, progress);

            targetRotation = targetRotation.add(offsets);
        }

        Rotation newRotation;

        switch (config.getType()) {
            case INSTANT -> newRotation = instantMod.process(targetRotation);
            case INTERPOLATION -> newRotation = interpolationMod.process((InterpolationRotationConfig) config,zenith.getRotationManager().getCurrentRotation(), targetRotation);
            case AI -> newRotation = interpolationMod.process(((AiRotationConfig) config ).getInterpolationRotationConfig() ,smoothMod.process((AiRotationConfig) config ,targetRotation), targetRotation);
            default -> newRotation = zenith.getRotationManager().getCurrentRotation();
        }

        if(config.getType()!= RotationModeType.AI) {
             smoothMod.resetLerp(targetRotation);
        }
        if(rotationManager.getCurrentRotation().equals(newRotation)) {
            return newRotation;
        }
        return newRotation.normalize(new Rotation(mc.player.lastYaw,mc.player.lastPitch));
    }

    @Getter
    int index = 0;

    public void incrementIndex() {
        index++;
        if (index >= values.length) {
            index = 0;
        }
    }

    public float getDiff(float prevTargetYawDiff, float targetYawDiff) {


        return targetYawDiff * values[index];
    }


    float[] values = new float[]{
            0.0123967f,
            0.053719f,
            0.109504f,
            0.17562f,
            0.21281f,
            0.272727f,
            0.11157f,
            0.0392562f,
            0.0103306f,
            0.0105006f,
            0.0302006f,
            0.0120006f,
            0.0003506f,
            0.101235f,
            0.90125f,
            0.123906f,
            0.00206612f
    };

    public static RotationDelta getOffset(RotationDelta deltaToTarget, float progress) {
        float curveStrength = 3.0f;
        float smoothness = 1.0f - (float) Math.cos(progress * Math.PI);

        float yawSign = Math.signum(deltaToTarget.getDeltaYaw());
        float pitchSign = Math.signum(deltaToTarget.getDeltaPitch());

        float offsetYaw = 2;
        float offsetPitch = 2;

        boolean verticalAiming = Math.abs(deltaToTarget.getDeltaYaw()) < 1.5f && Math.abs(deltaToTarget.getDeltaPitch()) > 10f;

        if (verticalAiming) {
            offsetYaw = pitchSign * curveStrength * (1f - progress);
            offsetPitch = 0f;
        } else {

            if (pitchSign > 0 && yawSign >= 0) {
                offsetYaw = -curveStrength * (1f - progress);
                offsetPitch = -curveStrength * smoothness;
            } else if (pitchSign > 0 && yawSign < 0) {
                offsetYaw = curveStrength * (1f - progress);
                offsetPitch = -curveStrength * smoothness;
            } else if (pitchSign < 0 && yawSign >= 0) {
                offsetYaw = -curveStrength * (1f - progress);
                offsetPitch = curveStrength * smoothness;
            } else if (pitchSign < 0 && yawSign < 0) {
                offsetYaw = curveStrength * (1f - progress);
                offsetPitch = curveStrength * smoothness;
            }
        }

        return new RotationDelta(offsetYaw, offsetPitch);
    }

    public void reset() {
        this.index = 0;
    }


}
AiRotationMode:
Expand Collapse Copy
package zenith.zov.base.rotation.mods;


import zenith.zov.base.rotation.deeplearnig.MinaraiModel;
import zenith.zov.base.rotation.mods.api.RotationMode;
import zenith.zov.base.rotation.mods.config.AiRotationConfig;
import zenith.zov.utility.game.player.rotation.Rotation;
import zenith.zov.utility.game.player.rotation.RotationDelta;

public class AIRotationMode extends RotationMode {
    private Rotation lerpTargetRotation = Rotation.ZERO;
    public Rotation process(AiRotationConfig config, Rotation targetRotation) {

        RotationDelta prevDelta = zenith.getRotationManager().getPreviousRotation().rotationDeltaTo(zenith.getRotationManager().getCurrentRotation());

        Rotation currentRotation = zenith.getRotationManager().getCurrentRotation();
        if(Math.abs(targetRotation.rotationDeltaTo(lerpTargetRotation).getDeltaYaw())>80 ){
            lerpTargetRotation = targetRotation;
        }
        for (int i = 0; i < 3; i++) {
            Rotation newOut = process(config, currentRotation, targetRotation, prevDelta, i == config.getTick() - 1);
            prevDelta = currentRotation.rotationDeltaTo(newOut);
            currentRotation = newOut;
        }

        if(currentRotation.rotationDeltaTo(lerpTargetRotation).isInRange(10)){
            lerpTargetRotation = targetRotation;
        }

        return currentRotation;
    }
    private Rotation process(AiRotationConfig config, Rotation currentRotation,Rotation targetRotation,RotationDelta prevDelta, boolean tickUpdate) {


        MinaraiModel model = zenith.getDeepLearningManager().getSlowModel();
        try {

            RotationDelta deltaLerpTarget = currentRotation.rotationDeltaTo(lerpTargetRotation);


            if(Math.copySign(1,prevDelta.getDeltaYaw())!=Math.copySign(1, deltaLerpTarget.getDeltaYaw())) {
                prevDelta = new RotationDelta(prevDelta.getDeltaYaw()*0.2f,prevDelta.getDeltaPitch()*0.2f);
              //   prevDelta = new RotationDelta(MathUtil.lerp(prevDelta.getDeltaYaw(),deltaLerpTarget.getDeltaYaw(),0.1f),MathUtil.lerp(prevDelta.getDeltaPitch(),deltaLerpTarget.getDeltaPitch(),0.1f));
            }


            //float[] input = new float[]{prevDeltaYaw2, prevDeltaPitch2, prevDeltaYaw, prevDeltaPitch, prevTargetDiffYaw, prevTargetDiffPitch, diffa, diffb};
            float[] input = new float[]{prevDelta.getDeltaYaw(), prevDelta.getDeltaPitch(), deltaLerpTarget.getDeltaYaw(), deltaLerpTarget.getDeltaPitch()};

          //  prevTargetDelta = deltaLerpTarget;
            float[] result = model.predict(input);



            float diffYaw = result[0];
            float diffPitch = result[1];

            RotationDelta newDelta = new RotationDelta(diffYaw, diffPitch);



            return  currentRotation.add(newDelta);

        } catch (
                Exception e) {
            e.printStackTrace();
        }
        return currentRotation;
    }

    public void resetLerp(Rotation targetRotation) {
        this.lerpTargetRotation = targetRotation;
    }
}
AiRotationConfig:
Expand Collapse Copy
package zenith.zov.base.rotation.mods.config;


import lombok.Builder;
import lombok.Getter;
import zenith.zov.base.rotation.mods.config.api.RotationConfig;
import zenith.zov.base.rotation.mods.config.api.RotationModeType;
import zenith.zov.utility.math.IntRange;

@Getter
@Builder
public class AiRotationConfig extends RotationConfig {
    @Builder.Default
    private int tick = 3;
    @Builder.Default
    private InterpolationRotationConfig interpolationRotationConfig =new InterpolationRotationConfig(new IntRange(2,5),new IntRange(5,8),new IntRange(20,30),0.35f);

    @Override
    public RotationModeType getType() {
        return RotationModeType.AI;
    }
}
RotationManager:
Expand Collapse Copy
package zenith.zov.base.rotation;

import com.darkmagician6.eventapi.EventManager;
import com.darkmagician6.eventapi.EventTarget;
import com.darkmagician6.eventapi.types.Priority;

import lombok.Getter;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.network.packet.c2s.play.PlayerInteractItemC2SPacket;
import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket;
import net.minecraft.network.packet.s2c.play.PlayerPositionLookS2CPacket;
import net.minecraft.network.packet.s2c.play.PlayerRotationS2CPacket;
import net.minecraft.util.math.MathHelper;
import zenith.zov.base.events.impl.other.EventSpawnEntity;
import zenith.zov.base.events.impl.player.EventDirection;
import zenith.zov.base.events.impl.player.EventRotate;
import zenith.zov.base.events.impl.player.EventUpdate;
import zenith.zov.base.events.impl.server.EventPacket;
import zenith.zov.base.request.RequestHandler;
import zenith.zov.client.modules.impl.render.Predictions;
import zenith.zov.utility.game.other.MessageUtil;
import zenith.zov.utility.game.player.rotation.Rotation;
import zenith.zov.utility.interfaces.IMinecraft;
import zenith.zov.client.modules.api.Module;

@Getter
public class RotationManager implements IMinecraft {

    private Rotation currentRotation = new Rotation(0, 0);
    private Rotation previousRotation = new Rotation(0, 0);
    private final RequestHandler<RotationTarget> requestHandler = new RequestHandler<>();
    private final AimManager aimManager = new AimManager();
    private RotationTarget previousRotationTarget = new RotationTarget(currentRotation, () -> currentRotation, aimManager.getInstantSetup());

    private boolean setRotation = true;

    public RotationManager() {
        EventManager.register(this);

    }

    @EventTarget
    public void addLocalPlayer(EventSpawnEntity eventSpawnLocalPlayer) {
        if (eventSpawnLocalPlayer.getEntity() instanceof ClientPlayerEntity player) {


            currentRotation = new Rotation(player.getYaw(), player.getPitch());
            previousRotation = new Rotation(player.getYaw(), player.getPitch());
            previousRotationTarget = new RotationTarget(currentRotation, () -> currentRotation, aimManager.getInstantSetup());
            setRotation = true;
        }
    }

    @EventTarget(Priority.LOW)
    public void update(EventUpdate event) {

        mc.player.prevHeadYaw = previousRotation.getYaw();
       mc.player.prevPitch = previousRotation.getPitch();
       mc.player.prevBodyYaw = previousRotation.getYaw();

        EventManager.call(new EventRotate());

        RotationTarget targetRotation = requestHandler.getActiveRequestValue();
        if (targetRotation != null) {


            Rotation newRot = targetRotation.rotation().get();
            previousRotation = currentRotation;
            currentRotation = newRot;
            setRotation = false;
            this.previousRotationTarget = targetRotation;
        } else {
            if (setRotation) {
                previousRotation = currentRotation;

                currentRotation = aimManager.rotate(aimManager.getInstantSetup(), new Rotation(mc.player.getYaw(),mc.player.getPitch()));

            } else {
                Rotation back = new Rotation(mc.player.getYaw(), mc.player.getPitch());

                if (currentRotation.rotationDeltaTo(back).isInRange(5)) {
                    previousRotation = currentRotation;
                    currentRotation = aimManager.rotate(aimManager.getInstantSetup(), back);
                    setRotation = true;

                } else {

                    Rotation newRot = aimManager.rotate(previousRotationTarget.rotationConfigBack(), back);

                    previousRotation = currentRotation;
                    currentRotation = newRot;


                }

            }
        }




       if(!setRotation) {
            float delta = currentRotation.getYaw() - mc.player.lastYaw;
            {
                Rotation validing = new Rotation(currentRotation.getYaw(), currentRotation.getPitch());
                if (delta > 320)
                    validing = new Rotation(mc.player.lastYaw + 300, currentRotation.getPitch()).normalize(new Rotation(mc.player.lastYaw, mc.player.lastPitch));
                if (delta < -320)
                    validing = new Rotation(mc.player.lastYaw - 300, currentRotation.getPitch()).normalize(new Rotation(mc.player.lastYaw, mc.player.lastPitch));

                currentRotation = validing;
            }
        }

        //  MessageUtil.displayMessage(MessageUtil.LogLevel.WARN, "valid " + (MathHelper.wrapDegrees(mc.player.getYaw()) + "  " + MathHelper.wrapDegrees(currentRotation.getYaw())));

        currentRotation = new Rotation(currentRotation.getYaw(), MathHelper.clamp(currentRotation.getPitch(), -90, 90));


        requestHandler.tick();

//        mc.player.setYaw(currentRotation.getYaw());
//        mc.player.setPitch(currentRotation.getPitch()


    }

    public void setRotation(RotationTarget targetRotation, int priority, Module module) {
        requestHandler.request(new RequestHandler.Request<>(2, priority, module, targetRotation));
    }

    @EventTarget
    public void direction(EventDirection direction) {

        direction.setYaw(currentRotation.getYaw());
        direction.setPitch(currentRotation.getPitch());
    }

    @EventTarget
    public void packet(EventPacket eventPacket) {


        switch (eventPacket.getPacket()) {
            case PlayerRotationS2CPacket player -> {
                currentRotation = new Rotation(player.xRot(), player.yRot());
                previousRotationTarget = new RotationTarget(currentRotation, () -> currentRotation, aimManager.getInstantSetup());
                setRotation = true;
            }

            case PlayerPositionLookS2CPacket player -> {
                currentRotation = new Rotation(player.change().yaw(), player.change().pitch());

                previousRotationTarget = new RotationTarget(currentRotation, () -> currentRotation, aimManager.getInstantSetup());
                setRotation = true;
            }
            case PlayerInteractItemC2SPacket packetItem -> {
                packetItem.yaw = currentRotation.getYaw();
                packetItem.pitch = currentRotation.getPitch();
            }
            default -> {
            }
        }
    }

}
RotationTarget:
Expand Collapse Copy
package zenith.zov.base.rotation;

import zenith.zov.base.rotation.mods.config.api.RotationConfig;
import zenith.zov.utility.game.player.rotation.Rotation;

import java.util.function.Supplier;

public record RotationTarget(Rotation targetRotation, Supplier<Rotation> rotation, RotationConfig rotationConfigBack) {

    /**
     * Создаёт минимальный RotationTarget только с углами, без кастомного ротатора и конфига.
     * Используется, когда нужно просто повернуть камеру на заданные углы.
     *
     * @param rotation Углы, на которые нужно повернуться
     * @return Новый экземпляр RotationTarget с пустыми rotation и rotationConfigBack
     */
    public RotationTarget(Rotation rotation) {
        this(rotation, null, null);
    }

    /**
     * Создаёт RotationTarget с углами и кастомным поставщиком ротации (например, для AI-поворотов),
     * но без специфичного конфига (используется конфиг по умолчанию).
     *
     * @param targetRotation Целевые углы
     * @param rotation Поставщик динамической ротации (например, AI)
     */
    public RotationTarget(Rotation targetRotation, Supplier<Rotation> rotation) {
        this(targetRotation, rotation, null);
    }

    /**
     * Возвращает true, если этот RotationTarget имеет кастомный поставщик поворота.
     *
     * @return Есть ли активный Supplier<Rotation>
     */
    public boolean hasRotationSupplier() {
        return rotation != null;
    }

    /**
     * Возвращает true, если этот RotationTarget имеет конфигурацию модификаций ротации.
     *
     * @return Есть ли RotationConfig
     */
    public boolean hasRotationConfig() {
        return rotationConfigBack != null;
    }

    /**
     * Упрощённый конструктор-фабрика: создаёт цель вращения только по углам.
     *
     * @param rotation Целевые углы
     * @return Новый RotationTarget
     */
    public static RotationTarget simple(Rotation rotation) {
        return new RotationTarget(rotation);
    }

    /**
     * Фабрика для создания RotationTarget с полной конфигурацией.
     *
     * @param targetRotation Целевые углы
     * @param rotation Поставщик ротации
     * @param rotationConfigBack Конфиг модов ротации
     * @return Новый RotationTarget
     */
    public static RotationTarget of(Rotation targetRotation, Supplier<Rotation> rotation, RotationConfig rotationConfigBack) {
        return new RotationTarget(targetRotation, rotation, rotationConfigBack);
    }

    /**
     * Фабрика для создания RotationTarget с углами и AI-ротацией.
     *
     * @param targetRotation Целевые углы
     * @param rotation Поставщик ротации
     * @return Новый RotationTarget без конфига
     */
    public static RotationTarget of(Rotation targetRotation, Supplier<Rotation> rotation) {
        return new RotationTarget(targetRotation, rotation);
    }
}
DeepLearningManager:
Expand Collapse Copy
package zenith.zov.base.rotation.deeplearnig;


import lombok.Getter;

@Getter
public class DeepLearningManager  {

    private  final MinaraiModel model ;
    private  final MinaraiModel speedModer ;
    private  final MinaraiModel slowModel ;


    public DeepLearningManager()  {
        model = new MinaraiModel("model");
        model.load();
        slowModel = new MinaraiModel("slow");
        slowModel.load();
        speedModer = new MinaraiModel("tf-0100");
        speedModer.load();



    }

}
FloatArrayInAndOutTranslator:
Expand Collapse Copy
package zenith.zov.base.rotation.deeplearnig;

import ai.djl.ndarray.NDList;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorContext;

public class FloatArrayInAndOutTranslator implements Translator<float[], float[]> {

    @Override
    public NDList processInput(TranslatorContext ctx, float[] input) {
        return new NDList(ctx.getNDManager().create(input));
    }

    @Override
    public float[] processOutput(TranslatorContext ctx, NDList list) {
        return list.get(0).toFloatArray();
    }
}
MinaraiModel:
Expand Collapse Copy
package zenith.zov.base.rotation.deeplearnig;

public class MinaraiModel extends ModelWrapper<float[], float[]> {
    public MinaraiModel(String name) {
        super(name, new FloatArrayInAndOutTranslator(), 2);
    }
}
ModelWrapper:
Expand Collapse Copy
package zenith.zov.base.rotation.deeplearnig;


import ai.djl.Model;
import ai.djl.ModelException;
import ai.djl.inference.Predictor;
import ai.djl.ndarray.NDManager;
import ai.djl.ndarray.types.Shape;
import ai.djl.nn.Activation;
import ai.djl.nn.Blocks;
import ai.djl.nn.SequentialBlock;
import ai.djl.nn.core.Linear;
import ai.djl.nn.norm.BatchNorm;
import ai.djl.training.DefaultTrainingConfig;
import ai.djl.training.EasyTrain;
import ai.djl.training.Trainer;
import ai.djl.training.TrainingConfig;
import ai.djl.training.dataset.ArrayDataset;
import ai.djl.training.initializer.XavierInitializer;
import ai.djl.training.listener.TrainingListener;
import ai.djl.training.listener.TrainingListenerAdapter;
import ai.djl.training.loss.Loss;
import ai.djl.training.optimizer.Adam;
import ai.djl.training.tracker.Tracker;
import ai.djl.translate.TranslateException;
import ai.djl.translate.Translator;
import zenith.zov.Zenith;
import zenith.zov.base.font.Fonts;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;

public abstract class ModelWrapper<I, O> implements Closeable {

    private static final int NUM_EPOCH = 500;
    private static final int BATCH_SIZE = 32;
    private final Translator<I, O> translator;
    private final long outputs;
    private final Model model;
    private final Predictor<I, O> predictor;
    private final  String name;
    public ModelWrapper(String name, Translator<I, O> translator, long outputs) {
        this.name = name;
        this.translator = translator;
        this.outputs = outputs;


        this.model = Model.newInstance(name);
        this.model.setBlock(createMlpBlock(outputs));
        this.predictor = model.newPredictor(translator);
    }

    public O predict(I input) throws TranslateException {

        return predictor.predict(input);
    }

    public void train(float[][] features, float[][] labels) throws ModelException, IOException {

        if (features.length != labels.length || features.length == 0) {
            throw new IllegalArgumentException("Features and labels must have the same size and be non-empty");
        }

        long inputs = features[0].length;

        TrainingConfig trainingConfig = new DefaultTrainingConfig(Loss.l2Loss())
                .optInitializer(new XavierInitializer(), "weight")
                .optOptimizer(Adam.builder().optLearningRateTracker(Tracker.fixed(0.001f)).build())
                .addTrainingListeners(TrainingListener.Defaults.logging("train"))
                .addTrainingListeners(new TrainingListenerAdapter() {
                    @Override
                    public void onEpoch(Trainer trainer) {

                        System.out.println("Epoch " + trainer.getTrainingResult().getEpoch() + " - Loss: " + trainer.getTrainingResult().getTrainLoss());
                    }

                    @Override
                    public void onTrainingBegin(Trainer trainer) {

                    }

                    @Override
                    public void onTrainingEnd(Trainer trainer) {

                    }
                });


        try (Trainer trainer = model.newTrainer(trainingConfig);
             NDManager manager = NDManager.newBaseManager()) {

            ArrayDataset trainingSet = new ArrayDataset.Builder()
                    .setData(manager.create(features))
                    .optLabels(manager.create(labels))
                    .setSampling(BATCH_SIZE, true)
                    .build();

            trainer.initialize(new Shape(BATCH_SIZE, inputs));
            EasyTrain.fit(trainer, NUM_EPOCH, trainingSet, null);
        } catch (TranslateException e) {

        }
    }

    public void load(InputStream stream) throws IOException, ModelException {
        model.load(stream);

    }

    public void load(Path path) throws IOException, ModelException {
        model.load(path, "tf");
    }

    public void load() {
        try (InputStream stream = getClass().getResourceAsStream("/assets/zenith/models/"+name+".params")) {

                load(stream);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public void save(Path path) throws IOException, ModelException {
        model.save(path, "tf");
    }

    @Override
    public void close() {
        predictor.close();
        model.close();
    }

    private static SequentialBlock createMlpBlock(long outputs) {
        return new SequentialBlock()
                .add(Linear.builder().setUnits(128).build())
                .add(Blocks.batchFlattenBlock())
                .add(BatchNorm.builder().build())
                .add(Activation.reluBlock())

                .add(Linear.builder().setUnits(64).build())
                .add(Blocks.batchFlattenBlock())
                .add(BatchNorm.builder().build())
                .add(Activation.reluBlock())

                .add(Linear.builder().setUnits(32).build())
                .add(Blocks.batchFlattenBlock())
                .add(BatchNorm.builder().build())
                .add(Activation.reluBlock())

                .add(Linear.builder().setUnits(outputs).build());
    }

}
Aura:
Expand Collapse Copy
package zenith.zov.client.modules.impl.combat;

import com.darkmagician6.eventapi.EventTarget;
import lombok.Getter;
import net.minecraft.client.util.InputUtil;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.Pair;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;

import zenith.zov.Zenith;
import zenith.zov.base.events.impl.player.EventMoveInput;
import zenith.zov.base.events.impl.player.EventRotate;
import zenith.zov.base.player.AttackUtil;
import zenith.zov.base.rotation.RotationTarget;
import zenith.zov.client.modules.api.Category;
import zenith.zov.client.modules.api.Module;
import zenith.zov.client.modules.api.ModuleAnnotation;
import zenith.zov.client.modules.api.setting.impl.BooleanSetting;
import zenith.zov.client.modules.api.setting.impl.ModeSetting;
import zenith.zov.client.modules.api.setting.impl.MultiBooleanSetting;
import zenith.zov.client.modules.api.setting.impl.NumberSetting;
import zenith.zov.utility.game.other.MessageUtil;
import zenith.zov.utility.game.player.*;
import zenith.zov.utility.game.player.rotation.Rotation;
import zenith.zov.utility.game.player.rotation.RotationUtil;

import java.util.List;

import static zenith.zov.utility.game.player.MovingUtil.fixMovement;

@ModuleAnnotation(name = "Aura", category = Category.COMBAT, description = "Бьет таргета")
public final class Aura extends Module {

    public static final Aura INSTANCE = new Aura();
    private Aura() {}

    // Режимы ротации
    private final ModeSetting rotationMode = new ModeSetting("Ротация");
    private final ModeSetting.Value hvh = new ModeSetting.Value(rotationMode, "ХВХ");
    private final ModeSetting.Value hollyworld = new ModeSetting.Value(rotationMode, "HollyWorld").select();

    // Режимы спринта
    private final ModeSetting sprintMode = new ModeSetting("Бег");
    private final ModeSetting.Value sprintHvh = new ModeSetting.Value(sprintMode, "ХВХ");
    private final ModeSetting.Value sprintNormal = new ModeSetting.Value(sprintMode, "Нормал").select();
    private final ModeSetting.Value sprintLegit = new ModeSetting.Value(sprintMode, "Легит");
    private final ModeSetting.Value sprintNone = new ModeSetting.Value(sprintMode, "Нет");

    // Коррекция движения
    private final ModeSetting correction = new ModeSetting("Коррекция");
    private final ModeSetting.Value correctionFocus = new ModeSetting.Value(correction, "Фокус");
    private final ModeSetting.Value correctionGood = new ModeSetting.Value(correction, "Свободная").select();
    private final ModeSetting.Value correctionNone = new ModeSetting.Value(correction, "Нет");

    // Дистанции
    private final NumberSetting distance = new NumberSetting("Дистанция", 3, 0.5f, 6, 0.1f, "Дистанция атаки");
    private final NumberSetting distanceRotation = new NumberSetting("Пре-дистанция", 0.1f, 0, 6, 0.1f);

    // Прочие настройки
    private final MultiBooleanSetting settings = new MultiBooleanSetting("Настройки");
    private final MultiBooleanSetting.Value shieldBreak = new MultiBooleanSetting.Value(settings, "Ломать щит", true);
    private final MultiBooleanSetting.Value shielRealese = new MultiBooleanSetting.Value(settings, "Отжимать щит", true);
    private final MultiBooleanSetting.Value eatUseAttack = new MultiBooleanSetting.Value(settings, "Бить и есть", true);
    private final MultiBooleanSetting.Value attackIgnoreWals = new MultiBooleanSetting.Value(settings, "Бить через стены", true);

    // Типы целей
    private final MultiBooleanSetting targetTypeSetting = MultiBooleanSetting.create("Атаковать", List.of("Игроков", "Враждебных", "Мирных"));

    // Криты
    private final BooleanSetting onlyCrit = new BooleanSetting("Только криты", true);
    private final BooleanSetting smartCrit = new BooleanSetting("Умные криты", "Бьет критами если зажата кнопка прыжка", false, onlyCrit::isEnabled);

    // private
    private final TargetSelector targetSelector = new TargetSelector();
    private final PointFinder pointFinder = new PointFinder();
    private LivingEntity target = null;
    private boolean legitBackStop = false; //Для легитного спринта бек
    @Getter
    private boolean preAttack =false;
    @Getter
    private boolean isCanAttack =false;
    @EventTarget
    public void eventRotate(EventRotate e) {
        if (legitBackStop) {
            legitBackStop = false;
            mc.options.forwardKey.setPressed(
                    InputUtil.isKeyPressed(mc.getWindow().getHandle(), mc.options.forwardKey.getDefaultKey().getCode())
            );
        }

        target = updateTarget();
        preAttack = false;
        isCanAttack = false;
        if (target == null) return;

        Pair<Vec3d, Box> point = pointFinder.computeVector(
                target,
                distance.getCurrent(),
                rotationManager.getCurrentRotation(),
                new Vec3d(0, 0, 0),
                attackIgnoreWals.isEnabled()
        );

        Vec3d eyes = SimulatedPlayer.simulateLocalPlayer(1).pos.add(0, mc.player.getDimensions(mc.player.getPose()).eyeHeight(), 0);
        Rotation angle = RotationUtil.fromVec3d(point.getLeft().subtract(eyes));

        Box box = point.getRight();
        preAttack = updatePreAttack();
        isCanAttack = isAttack();

        if (RaytracingUtil.rayTrace(rotationManager.getCurrentRotation().toVector(), distance.getCurrent(), box)
                && isCanAttack
                && (!Zenith.getInstance().getServerHandler().isServerSprint() ||mc.player.isGliding() || AttackUtil.hasMovementRestrictions() || sprintHvh.isSelected() || sprintNone.isSelected())) {

            if (sprintHvh.isSelected()) {
                mc.player.setSprinting(false);
                mc.player.sendSprintingPacket();
            }

            AttackUtil.attackEntity(target);

            mc.options.sprintKey.setPressed(true);
        }
        preAttack = updatePreAttack();
        isCanAttack = isAttack();
        if (hvh.isSelected()) {
            rotationManager.setRotation(
                    new RotationTarget(angle, () -> aimManager.rotate(aimManager.getInstantSetup(), angle), aimManager.getInstantSetup()),
                    3, this
            );
        }

        if (hollyworld.isSelected() && (preAttack || isCanAttack )) {
            rotationManager.setRotation(
                    new RotationTarget(angle, () -> aimManager.rotate(aimManager.getInstantSetup(), angle), aimManager.getAiSetup()),
                    3, this
            );
        }

        if (preAttack || isCanAttack) {
            updateSprint();
        }
    }

    private boolean updatePreAttack() {
        SimulatedPlayer simulatedPlayer = SimulatedPlayer.simulateLocalPlayer(1);

        if (mc.player.isUsingItem() && !eatUseAttack.isEnabled()) return false;
        if (mc.player.getAttackCooldownProgress(1) < 0.9) return false;

        if (onlyCrit.isEnabled() && !AttackUtil.hasPreMovementRestrictions(simulatedPlayer)) {
            return AttackUtil.isPrePlayerInCriticalState(simulatedPlayer) || (smartCrit.isEnabled() && !mc.options.jumpKey.isPressed());
        }
        return true;
    }

    private boolean isAttack() {
        if (mc.player.isUsingItem() && !eatUseAttack.isEnabled()) return false;
        if (mc.player.getAttackCooldownProgress(1) < 0.9) return false;

        if (onlyCrit.isEnabled() && !AttackUtil.hasMovementRestrictions()) {
            return AttackUtil.isPlayerInCriticalState() || (smartCrit.isEnabled() && !mc.options.jumpKey.isPressed());
        }
        return true;
    }

    public void updateSprint() {
        if (!hasStopSprint()) return;

        boolean sprint = mc.options.sprintKey.isPressed();
        boolean forward = mc.options.forwardKey.isPressed();

        if (sprintLegit.isSelected()) {
            sprint = false;
            if (mc.player.isSprinting()) {

                forward = false;
                legitBackStop = true;
            }
        }

        if (sprintNormal.isSelected()) {
            if (mc.player.isSprinting()) mc.player.setSprinting(false);
            sprint = false;
        }

        mc.options.sprintKey.setPressed(sprint);
        mc.options.forwardKey.setPressed(forward);
    }

    public boolean hasStopSprint() {
        return !sprintNone.isSelected() && !AttackUtil.hasMovementRestrictions();
    }

    private LivingEntity updateTarget() {
        TargetSelector.EntityFilter filter = new TargetSelector.EntityFilter(targetTypeSetting.getSelectedNames());
        targetSelector.searchTargets(mc.world.getEntities(), distance.getCurrent() + distanceRotation.getCurrent(), attackIgnoreWals.isEnabled());
        targetSelector.validateTarget(filter::isValid);
        return targetSelector.getCurrentTarget();
    }

    @EventTarget
    private void setCorrection(EventMoveInput eventMoveInput) {
        if (correctionNone.isSelected()) return;

        if (correctionFocus.isSelected()) {
            Rotation angle = RotationUtil.fromVec3d(target.getBoundingBox().getCenter().subtract(mc.player.getBoundingBox().getCenter()));
            fixMovement(eventMoveInput, rotationManager.getCurrentRotation().getYaw(), angle.getYaw());
        } else {
            fixMovement(eventMoveInput, rotationManager.getCurrentRotation().getYaw(), mc.player.getYaw());
        }
    }

    public LivingEntity getTarget() {
        return this.isEnabled()?target:null;
    }


}
 
типо запускаю с сурсов и нейро ротация работает нормально билжу и запускаю с легаси то эта нейро ротация после выключения ауры продолжает смотреть в 1 точку помогите зафиксить без негатива
сделай в самом конце твоей ротации сброс при потере таргета ее самой на "обычную"
 
Назад
Сверху Снизу