EntityBehaviorManager.java 4.12 KB
Newer Older
1 2
package com.owlmaddie.goals;

3
import com.owlmaddie.network.ServerPackets;
4
import net.minecraft.entity.ai.goal.Goal;
5
import net.minecraft.entity.ai.goal.GoalSelector;
6
import net.minecraft.entity.ai.goal.PrioritizedGoal;
7 8
import net.minecraft.entity.mob.MobEntity;
import net.minecraft.server.world.ServerWorld;
9 10
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
11
import java.util.function.Predicate;
12

13 14 15
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
16 17

/**
18 19
 * The {@code EntityBehaviorManager} class now directly interacts with the goal selectors of entities
 * to manage goals, while avoiding concurrent modification issues.
20 21
 */
public class EntityBehaviorManager {
22
    public static final Logger LOGGER = LoggerFactory.getLogger("creaturechat");
23

24
    public static void addGoal(MobEntity entity, Goal goal, GoalPriority priority) {
25
        if (!(entity.getWorld() instanceof ServerWorld)) {
26
            LOGGER.debug("Attempted to add a goal in a non-server world. Aborting.");
27 28
            return;
        }
29

30 31
        ServerPackets.serverInstance.execute(() -> {
            GoalSelector goalSelector = GoalUtils.getGoalSelector(entity);
32

33
            // First clear any existing goals of the same type to avoid duplicates
34
            clearAndRemove(g -> goal.getClass().equals(g.getClass()), goalSelector);
35

36 37
            // Handle potential priority conflicts before adding the new goal
            moveConflictingGoals(goalSelector, priority);
38

39
            // Now add the new goal at the specified priority
40
            goalSelector.add(priority.getPriority(), goal);
41
            LOGGER.debug("Goal of type {} added with priority {}", goal.getClass().getSimpleName(), priority);
42
        });
43 44
    }

45 46 47 48 49 50 51 52 53 54 55 56
    public static void clearAndRemove(Predicate<Goal> predicate, GoalSelector goalSelector) {
        // Collect all goals that need to be removed
        List<PrioritizedGoal> toBeRemoved = goalSelector.getGoals().stream()
                .filter(prioritizedGoal -> predicate.test(prioritizedGoal.getGoal()))
                .collect(Collectors.toList());

        // Stop if running and remove each goal
        toBeRemoved.forEach(prioritizedGoal -> {
            goalSelector.remove(prioritizedGoal.getGoal());  // Remove the goal
        });
    }

57
    public static void removeGoal(MobEntity entity, Class<? extends Goal> goalClass) {
58 59
        ServerPackets.serverInstance.execute(() -> {
            GoalSelector goalSelector = GoalUtils.getGoalSelector(entity);
60 61
            // First clear any existing goals of the same type to avoid duplicates
            clearAndRemove(g -> goalClass.equals(g.getClass()), goalSelector);
62 63 64
            LOGGER.debug("All goals of type {} removed.", goalClass.getSimpleName());
        });
    }
65

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    public static void moveConflictingGoals(GoalSelector goalSelector, GoalPriority newGoalPriority) {
        // Collect all prioritized goals currently in the selector.
        List<PrioritizedGoal> sortedGoals = goalSelector.getGoals().stream()
                .sorted(Comparator.comparingInt(PrioritizedGoal::getPriority))
                .collect(Collectors.toList());

        // Check if there is an existing goal at the new priority level.
        boolean conflictExists = sortedGoals.stream()
                .anyMatch(pg -> pg.getPriority() == newGoalPriority.getPriority());

        // If there is a conflict, we need to shift priorities of this and all higher priorities.
        if (conflictExists) {
            int shiftPriority = newGoalPriority.getPriority();
            for (PrioritizedGoal pg : sortedGoals) {
                if (pg.getPriority() >= shiftPriority) {
                    // Remove the goal and increment its priority.
                    goalSelector.remove(pg.getGoal());
                    goalSelector.add(shiftPriority + 1, pg.getGoal());
                    shiftPriority++;  // Update the shift priority for the next possible conflict.
85
                }
86 87
            }

88 89 90 91
            LOGGER.debug("Moved conflicting goals starting from priority {}", newGoalPriority);
        } else {
            LOGGER.debug("No conflicting goal at priority {}, no action taken.", newGoalPriority);
        }
92
    }
93
}