Skip to content

Commit

Permalink
Fix colony teams assignment behaviour (#10239)
Browse files Browse the repository at this point in the history
Consistently ensure citizens are registered to the correct team
Use the colony team name instead of a per citizen team
Ensure that upon deletion of a colony it's respective team is removed
Fix the colony deletion event not triggering for command based deletion
  • Loading branch information
Raycoms committed Nov 4, 2024
1 parent a2bd611 commit b2252cf
Show file tree
Hide file tree
Showing 18 changed files with 231 additions and 139 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import net.neoforged.neoforge.items.IItemHandler;
import net.minecraft.world.scores.PlayerTeam;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

Expand Down Expand Up @@ -239,6 +240,18 @@ public boolean isNoAi()
return false;
}

@Override
@Nullable
protected PlayerTeam getAssignedTeam()
{
final ICitizenColonyHandler citizenColonyHandler = getCitizenColonyHandler();
if (citizenColonyHandler == null || citizenColonyHandler.getColony() == null)
{
return null;
}
return citizenColonyHandler.getColony().getTeam();
}

/**
* Sets the textures of all citizens and distinguishes between male and female.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,13 @@
import static com.minecolonies.api.util.constant.ColonyManagerConstants.NO_COLONY_ID;
import static com.minecolonies.api.util.constant.NbtTagConstants.*;
import static com.minecolonies.api.util.constant.RaiderConstants.*;
import static com.minecolonies.core.util.TeamUtils.checkOrCreateTeam;

/**
* Abstract for all raider entities.
*/
public abstract class AbstractEntityRaiderMob extends AbstractFastMinecoloniesEntity implements IThreatTableEntity, Enemy
{
/**
* Difficulty at which raiders team up
*/
private static final double TEAM_DIFFICULTY = 2.0d;

/**
* The percent of life taken per damage modifier
*/
Expand Down Expand Up @@ -523,14 +519,14 @@ public SpawnGroupData finalizeSpawn(
final ServerLevelAccessor worldIn,
final DifficultyInstance difficultyIn,
final MobSpawnType reason,
@Nullable final SpawnGroupData p_21437_)
@Nullable final SpawnGroupData spawnDataIn)
{
RaiderMobUtils.setEquipment(this);
return super.finalizeSpawn(worldIn, difficultyIn, reason, p_21437_);
return super.finalizeSpawn(worldIn, difficultyIn, reason, spawnDataIn);
}

@Override
public void remove(RemovalReason reason)
public void remove(@NotNull final RemovalReason reason)
{
if (!level().isClientSide && colony != null && eventID > 0)
{
Expand Down Expand Up @@ -725,38 +721,15 @@ public void initStatsFor(final double baseHealth, final double difficulty, final
this.setEnvDamageImmunity(true);
}

if (difficulty >= TEAM_DIFFICULTY)
{
level().getScoreboard().addPlayerToTeam(getScoreboardName(), checkOrCreateTeam());
}

this.getAttribute(Attributes.MAX_HEALTH).setBaseValue(baseHealth);
this.setHealth(this.getMaxHealth());
}

/**
* Creates or gets the scoreboard team
*
* @return Scoreboard team
*/
private PlayerTeam checkOrCreateTeam()
{
if (this.level().getScoreboard().getPlayerTeam(getTeamName()) == null)
{
this.level().getScoreboard().addPlayerTeam(getTeamName());
this.level().getScoreboard().getPlayerTeam(getTeamName()).setAllowFriendlyFire(false);
}
return this.level().getScoreboard().getPlayerTeam(getTeamName());
}

/**
* Gets the scoreboard team name
*
* @return
*/
protected String getTeamName()
@Override
@Nullable
protected PlayerTeam getAssignedTeam()
{
return RAID_TEAM;
return checkOrCreateTeam(level(), RAID_TEAM);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.level.portal.DimensionTransition;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.scores.PlayerTeam;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
* Special abstract minecolonies mob that overrides laggy vanilla behaviour.
Expand Down Expand Up @@ -298,6 +300,74 @@ public void updateSwimAmount()

}

/**
* Get the team this entity is assigned to.
*
* @return the team instance.
*/
@Nullable
protected abstract PlayerTeam getAssignedTeam();

@Override
@Nullable
public final PlayerTeam getTeam()
{
final PlayerTeam assignedTeam = getAssignedTeam();
registerToTeamInternal(assignedTeam);
return assignedTeam;
}

/**
* Register this entity to its own assigned team.
*/
public void registerToTeam()
{
registerToTeamInternal(getAssignedTeam());
}

/**
* Internal method for team registration.
*
* @param team the team to register to.
*/
private void registerToTeamInternal(@Nullable final PlayerTeam team)
{
if (team != null && !isInTeam(team))
{
level().getScoreboard().addPlayerToTeam(getScoreboardName(), team);
}
}

/**
* Remove the entity from its own assigned team.
*/
public void removeFromTeam()
{
final PlayerTeam team = getAssignedTeam();
if (team != null && isInTeam(team))
{
level().getScoreboard().removePlayerFromTeam(getScoreboardName(), team);
}
}

/**
* Check if the current entity is assigned to the provided team.
*
* @param team the input team.
* @return true if so.
*/
private boolean isInTeam(@NotNull final PlayerTeam team)
{
return Objects.equals(level().getScoreboard().getPlayersTeam(getScoreboardName()), team);
}

@Override
public void remove(@NotNull final RemovalReason reason)
{
super.remove(reason);
removeFromTeam();
}

/**
* Static Byte values to avoid frequent autoboxing
*/
Expand Down Expand Up @@ -326,9 +396,9 @@ public boolean isShiftKeyDown()
@Override
public void knockback(double power, double xRatio, double zRatio)
{
if (level.getGameTime() - lastKnockBack > 20 * 3)
if (level().getGameTime() - lastKnockBack > 20 * 3)
{
lastKnockBack = level.getGameTime();
lastKnockBack = level().getGameTime();
super.knockback(power, xRatio, zRatio);
}
}
Expand Down
38 changes: 38 additions & 0 deletions src/main/java/com/minecolonies/api/events/ColonyEvents.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.minecolonies.api.events;

import com.minecolonies.api.colony.IColony;
import com.minecolonies.api.colony.event.ColonyDeletedEvent;
import com.minecolonies.api.util.Log;
import net.neoforged.bus.api.Event;
import net.neoforged.neoforge.common.NeoForge;

/**
* Event manager for all forge events.
*/
public class ColonyEvents
{
/**
* Event triggered when a colony is being deleted.
*
* @param colony the colony in question.
*/
public static void deleteColony(final IColony colony)
{
sendEventSafe(new ColonyDeletedEvent(colony));
}

/**
* Underlying logic for transmitting an event.
*/
private static void sendEventSafe(final Event event)
{
try
{
NeoForge.EVENT_BUS.post(event);
}
catch (final Exception e)
{
Log.getLogger().atError().withThrowable(e).log("Exception occurred during {} event", event.getClass().getName());
}
}
}
28 changes: 10 additions & 18 deletions src/main/java/com/minecolonies/core/colony/Colony.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
import static com.minecolonies.api.util.constant.NbtTagConstants.*;
import static com.minecolonies.api.util.constant.TranslationConstants.*;
import static com.minecolonies.core.MineColonies.getConfig;
import static com.minecolonies.core.util.TeamUtils.checkOrCreateTeam;

/**
* This class describes a colony and contains all the data and methods for manipulating a Colony.
Expand Down Expand Up @@ -374,7 +375,7 @@ public class Colony implements IColony
this.colonyFlag = new BannerPatternLayers.Builder().add(Utils.getRegistryValue(BannerPatterns.BASE, world), DyeColor.WHITE).build();
this.dimensionId = world.dimension();
onWorldLoad(world);
checkOrCreateTeam();
checkOrCreateTeam(world, getTeamName(), false);
}

colonyStateMachine = new TickRateStateMachine<>(INACTIVE, e ->
Expand Down Expand Up @@ -635,23 +636,11 @@ public void updateAttackingPlayers()
}

@Override
@Nullable
public PlayerTeam getTeam()
{
// This getter will create the team if it doesn't exist. Could do something different though in the future.
return checkOrCreateTeam();
}

/**
* Check or create the team.
*/
private PlayerTeam checkOrCreateTeam()
{
if (this.world.getScoreboard().getPlayerTeam(getTeamName()) == null)
{
this.world.getScoreboard().addPlayerTeam(getTeamName());
this.world.getScoreboard().getPlayerTeam(getTeamName()).setAllowFriendlyFire(false);
}
return this.world.getScoreboard().getPlayerTeam(getTeamName());
return checkOrCreateTeam(world, getTeamName(), false);
}

/**
Expand All @@ -663,10 +652,13 @@ public void setColonyColor(final ChatFormatting colonyColor)
{
if (this.world != null)
{
checkOrCreateTeam();
this.colonyTeamColor = colonyColor;
this.world.getScoreboard().getPlayerTeam(getTeamName()).setColor(colonyColor);
this.world.getScoreboard().getPlayerTeam(getTeamName()).setPlayerPrefix(Component.literal(colonyColor.toString()));
final PlayerTeam team = getTeam();
if (team != null)
{
team.setColor(colonyColor);
team.setPlayerPrefix(Component.literal(colonyColor.toString()));
}
}
this.markDirty();
}
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/com/minecolonies/core/colony/ColonyManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import com.minecolonies.api.compatibility.CompatibilityManager;
import com.minecolonies.api.compatibility.ICompatibilityManager;
import com.minecolonies.api.crafting.IRecipeManager;
import com.minecolonies.api.events.ColonyEvents;
import com.minecolonies.api.sounds.SoundManager;
import com.minecolonies.api.util.BlockPosUtil;
import com.minecolonies.api.util.ColonyUtils;
Expand Down Expand Up @@ -216,6 +217,7 @@ private void deleteColony(@Nullable final IColony iColony, final boolean canDest
return;
}

ColonyEvents.deleteColony(colony);
cap.deleteColony(id);
BackUpHelper.markColonyDeleted(colony.getID(), colony.getDimension());
colony.getImportantMessageEntityPlayers()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1083,8 +1083,8 @@ public BlockPos getStandingPosition()
final BlockPos currentPos = getPosition().relative(dir);
final BlockState hereState = colony.getWorld().getBlockState(currentPos);
// Check air here and air above.
if ((!hereState.getBlock().properties.hasCollision || hereState.is(BlockTags.WOOL_CARPETS))
&& !colony.getWorld().getBlockState(currentPos.above()).getBlock().properties.hasCollision
if ((!hereState.getBlock().properties().hasCollision || hereState.is(BlockTags.WOOL_CARPETS))
&& !colony.getWorld().getBlockState(currentPos.above()).getBlock().properties().hasCollision
&& BlockUtils.isAnySolid(colony.getWorld().getBlockState(currentPos.below())))
{
int localScore = BEST_STANDING_SCORE;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,10 @@ public void registerCivilian(final AbstractCivilianEntity entity)

final Optional<AbstractEntityCitizen> existingCitizen = data.getEntity();

if (!existingCitizen.isPresent())
if (existingCitizen.isEmpty())
{
data.setEntity(entity);
entity.level().getScoreboard().addPlayerToTeam(entity.getScoreboardName(), colony.getTeam());
entity.registerToTeam();
return;
}

Expand All @@ -159,18 +159,7 @@ public void unregisterCivilian(final AbstractCivilianEntity entity)
final ICitizenData data = citizens.get(entity.getCivilianID());
if (data != null && data.getEntity().isPresent() && data.getEntity().get() == entity)
{
try
{
if (colony.getWorld().getScoreboard().getPlayersTeam(entity.getScoreboardName()) == colony.getTeam())
{
colony.getWorld().getScoreboard().removePlayerFromTeam(entity.getScoreboardName(), colony.getTeam());
}
}
catch (Exception ignored)
{
// For some weird reason we can get an exception here, though the exception is thrown for team != colony team which we check == on before
}

entity.removeFromTeam();
citizens.get(entity.getCivilianID()).setEntity(null);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public String getName()
public LiteralArgumentBuilder<CommandSourceStack> build()
{
final List<String> raidTypes = new ArrayList<>();
for (final ColonyEventTypeRegistryEntry type : IMinecoloniesAPI.getInstance().getColonyEventRegistry().getValues())
for (final ColonyEventTypeRegistryEntry type : IMinecoloniesAPI.getInstance().getColonyEventRegistry())
{
if (!type.getRegistryName().getPath().equals(PirateGroundRaidEvent.PIRATE_GROUND_RAID_EVENT_TYPE_ID.getPath())
&& !type.getRegistryName().getPath().equals(NorsemenShipRaidEvent.NORSEMEN_RAID_EVENT_TYPE_ID.getPath()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public void draw(@NotNull final FloristRecipeCategory.FloristRecipe recipe,
super.draw(recipe, recipeSlotsView, stack, mouseX, mouseY);

final BlockState block = ModBlocks.blockCompostedDirt.defaultBlockState();
RenderHelper.renderBlock(stack.pose(), block, WIDTH - 38, CITIZEN_Y - 20, 100, -30F, 30F, 16F);
RenderHelper.renderBlock(stack, block, WIDTH - 38, CITIZEN_Y - 20, 100, -30F, 30F, 16F);
}

@NotNull
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public void registerRecipeCatalysts(@NotNull final IRecipeCatalystRegistration r
registration.addRecipeCatalyst(ModBlocks.blockBarrel, ModRecipeTypes.COMPOSTING);
registration.addRecipeCatalyst(ModBlocks.blockHutComposter, ModRecipeTypes.COMPOSTING);
registration.addRecipeCatalyst(ModBlocks.blockHutFisherman, ModRecipeTypes.FISHING);
registration.addRecipeCatalyst(new ItemStack(ModBlocks.blockHutFlorist), ModRecipeTypes.FLOWERS);
registration.addRecipeCatalyst(ModBlocks.blockHutFlorist, ModRecipeTypes.FLOWERS);

for (final JobBasedRecipeCategory<?> category : this.categories)
{
Expand Down
Loading

0 comments on commit b2252cf

Please sign in to comment.