Merge branch 'dev' into syntax-highlighter-unified

This commit is contained in:
Kam committed 2026-02-23 17:50:20 -05:00
commit 5cf69f90fb
72 files changed
+4861 -538

No files matched your search

@@ -25,6 +25,7 @@ import noppes.npcs.containers.ContainerCrate;
import noppes.npcs.containers.ContainerCustomGui;
import noppes.npcs.containers.ContainerMail;
import noppes.npcs.containers.ContainerManageBanks;
import noppes.npcs.containers.ContainerManageAuction;
import noppes.npcs.containers.ContainerManageRecipes;
import noppes.npcs.containers.ContainerMerchantAdd;
import noppes.npcs.containers.ContainerNPCBankLarge;
@@ -136,6 +137,9 @@ public class CommonProxy implements IGuiHandler {
if (gui == EnumGuiType.ManageBanks)
return new ContainerManageBanks(player);
if (gui == EnumGuiType.ManageAuction)
return new ContainerManageAuction(player);
if (gui == EnumGuiType.MerchantAdd)
return new ContainerMerchantAdd(player, ServerEventsHandler.Merchant, player.worldObj);
+1 -1
View File
@@ -295,7 +295,7 @@ public class CustomNpcs {
registerNewEntity(EntityAbilityOrb.class, "abilityorb", 64, 1, true);
registerNewEntity(EntityAbilityDisc.class, "abilitydisc", 64, 1, true);
registerNewEntity(EntityAbilityLaser.class, "abilitylaser", 64, 1, true);
registerNewEntity(EntityAbilityBeam.class, "abilitybeam", 64, 1, true);
registerNewEntity(EntityAbilityBeam.class, "abilitybeam", 160, 1, true);
registerNewEntity(EntityAbilitySweeper.class, "abilitysweeper", 64, 3, true);
registerNewEntity(EntityAbilityZone.class, "abilityzone", 64, 3, true);
registerNewEntity(EntityAbilityDome.class, "energydome", 64, 3, true);
@@ -69,6 +69,7 @@ public class CustomNpcsPermissions {
public static final Permission GLOBAL_MAGIC = new Permission("customnpcs.global.magic");
public static final Permission GLOBAL_ABILITY = new Permission("customnpcs.global.ability");
public static final Permission GLOBAL_EFFECT = new Permission("customnpcs.global.effect");
public static final Permission GLOBAL_AUCTION = new Permission("customnpcs.global.auction");
public static final Permission SPAWNER_MOB = new Permission("customnpcs.spawner.mob");
public static final Permission SPAWNER_CREATE = new Permission("customnpcs.spawner.create");
+227 -17
View File
@@ -28,28 +28,45 @@ import noppes.npcs.scripted.event.CustomNPCsEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class NPCSpawning {
private static Set<ChunkCoordIntPair> eligibleChunksForSpawning = Sets.newHashSet();
private static final byte CHUNK_SPAWN_RADIUS = 7;
private static final int SPAWN_ATTEMPTS_PER_CHUNK = 3;
private static final int NATURAL_CAP_PER_256_CHUNKS = 70;
private static final long RUNTIME_SPAWN_TICK_INTERVAL = 20L;
private static final int RUNTIME_SPAWN_CYCLE_TICKS = 400;
private static final String NATURAL_SPAWN_ID_TAG = "CNPCNaturalSpawnId";
private static final String NATURAL_SPAWN_NAME_TAG = "CNPCNaturalSpawnName";
private static final String NATURAL_SPAWN_TIME_TAG = "CNPCNaturalSpawnTime";
private static final Map<Long, Long> SPAWN_COOLDOWNS = new HashMap<Long, Long>();
private static final Map<Integer, RuntimeChunkState> RUNTIME_CHUNK_STATES = new HashMap<Integer, RuntimeChunkState>();
private static boolean animalSpawn;
private static boolean monsterSpawn;
private static boolean airSpawn;
private static boolean liquidSpawn;
private static class RuntimeChunkState {
public ArrayList<ChunkCoordIntPair> chunks = new ArrayList<ChunkCoordIntPair>();
public int index = 0;
public int signature = 0;
}
public static void findChunksForSpawning(WorldServer world) {
if (SpawnController.Instance.data.isEmpty() || world.getWorldInfo().getWorldTotalTime() % 400L != 0L)
if (SpawnController.Instance.data.isEmpty() || world.getWorldInfo().getWorldTotalTime() % RUNTIME_SPAWN_TICK_INTERVAL != 0L)
return;
eligibleChunksForSpawning.clear();
for (int i = 0; i < world.playerEntities.size(); ++i) {
EntityPlayer entityplayer = (EntityPlayer) world.playerEntities.get(i);
int j = MathHelper.floor_double(entityplayer.posX / 16.0D);
int k = MathHelper.floor_double(entityplayer.posZ / 16.0D);
byte size = 7;
byte size = CHUNK_SPAWN_RADIUS;
for (int x = -size; x <= size; ++x) {
for (int z = -size; z <= size; ++z) {
@@ -60,22 +77,29 @@ public class NPCSpawning {
}
}
}
if (countNPCs(world) > eligibleChunksForSpawning.size()) {
int cap = getScaledNaturalCap(eligibleChunksForSpawning.size());
int npcCount = countNaturalSpawnedNPCs(world);
if (npcCount >= cap) {
return;
}
ArrayList<ChunkCoordIntPair> tmp = new ArrayList(eligibleChunksForSpawning);
Collections.shuffle(tmp);
Iterator<ChunkCoordIntPair> iterator = tmp.iterator();
HashMap<Integer, Integer> spawnEntryCounts = getNaturalSpawnEntryCounts(world);
int chunkBudget = getRuntimeChunkBudget(eligibleChunksForSpawning.size());
List<ChunkCoordIntPair> chunksToProcess = getRuntimeChunkBatch(world, chunkBudget);
while (iterator.hasNext()) {
ChunkCoordIntPair chunkcoordintpair1 = iterator.next();
for (ChunkCoordIntPair chunkcoordintpair1 : chunksToProcess) {
if (npcCount >= cap) {
return;
}
ChunkPosition chunkposition = getChunk(world, chunkcoordintpair1.chunkXPos, chunkcoordintpair1.chunkZPos);
int j1 = chunkposition.chunkPosX;
int y = chunkposition.chunkPosY;
int l1 = chunkposition.chunkPosZ;
for (int i = 0; i < 3; i++) {
for (int i = 0; i < SPAWN_ATTEMPTS_PER_CHUNK; i++) {
if (npcCount >= cap) {
return;
}
int x = j1;
int z = l1;
byte b1 = 6;
@@ -85,25 +109,71 @@ public class NPCSpawning {
String name = world.getBiomeGenForCoords(x, z).biomeName;
SpawnData data = SpawnController.Instance.getRandomSpawnData(name, world.provider.dimensionId);
if (data == null || !canCreatureTypeSpawnAtLocation(data, world, x, y, z) || world.getClosestPlayer(x, y, z, 24.0D) != null)
if (data == null)
continue;
spawnData(data, world, x, y, z);
if (trySpawnWithEntryConfig(data, world, x, y, z, world.rand, spawnEntryCounts)) {
npcCount++;
}
}
}
}
public static int countNPCs(World world) {
private static int getRuntimeChunkBudget(int eligibleChunkCount) {
if (eligibleChunkCount <= 0) {
return 0;
}
int runsPerCycle = Math.max(1, (int) (RUNTIME_SPAWN_CYCLE_TICKS / RUNTIME_SPAWN_TICK_INTERVAL));
return Math.max(1, (int) Math.ceil((double) eligibleChunkCount / runsPerCycle));
}
private static List<ChunkCoordIntPair> getRuntimeChunkBatch(World world, int chunkBudget) {
ArrayList<ChunkCoordIntPair> result = new ArrayList<ChunkCoordIntPair>();
if (chunkBudget <= 0 || eligibleChunksForSpawning.isEmpty()) {
return result;
}
int dimensionId = world.provider.dimensionId;
RuntimeChunkState state = RUNTIME_CHUNK_STATES.get(dimensionId);
if (state == null) {
state = new RuntimeChunkState();
RUNTIME_CHUNK_STATES.put(dimensionId, state);
}
int signature = eligibleChunksForSpawning.hashCode();
if (state.chunks.isEmpty() || state.signature != signature || state.index >= state.chunks.size()) {
state.chunks = new ArrayList<ChunkCoordIntPair>(eligibleChunksForSpawning);
Collections.shuffle(state.chunks);
state.index = 0;
state.signature = signature;
}
int remaining = state.chunks.size() - state.index;
int count = Math.min(chunkBudget, Math.max(0, remaining));
for (int i = 0; i < count; i++) {
result.add(state.chunks.get(state.index++));
}
return result;
}
private static int countNaturalSpawnedNPCs(World world) {
int count = 0;
List<Entity> list = world.loadedEntityList;
for (Entity entity : list) {
if (entity instanceof EntityNPCInterface) {
if (entity instanceof EntityNPCInterface && !entity.isDead && entity.getEntityData().hasKey(NATURAL_SPAWN_ID_TAG)) {
count++;
}
}
return count;
}
private static int getScaledNaturalCap(int eligibleChunkCount) {
if (eligibleChunkCount <= 0) {
return 0;
}
return Math.max(1, NATURAL_CAP_PER_256_CHUNKS * eligibleChunkCount / 256);
}
protected static ChunkPosition getChunk(World world, int x, int z) {
Chunk chunk = world.getChunkFromChunkCoords(x, z);
int k = x * 16 + world.rand.nextInt(16);
@@ -112,9 +182,134 @@ public class NPCSpawning {
return new ChunkPosition(k, i1, l);
}
private static int getCap(World world) {
Set<ChunkCoordIntPair> chunkSet = Sets.newHashSet();
for (int i = 0; i < world.playerEntities.size(); ++i) {
EntityPlayer entityplayer = (EntityPlayer) world.playerEntities.get(i);
int j = MathHelper.floor_double(entityplayer.posX / 16.0D);
int k = MathHelper.floor_double(entityplayer.posZ / 16.0D);
byte size = CHUNK_SPAWN_RADIUS;
for (int x = -size; x <= size; ++x) {
for (int z = -size; z <= size; ++z) {
chunkSet.add(new ChunkCoordIntPair(x + j, z + k));
}
}
}
return getScaledNaturalCap(chunkSet.size());
}
private static HashMap<Integer, Integer> getNaturalSpawnEntryCounts(World world) {
HashMap<Integer, Integer> counts = new HashMap<Integer, Integer>();
List<Entity> list = world.loadedEntityList;
for (Entity entity : list) {
if (entity == null || entity.isDead || !(entity instanceof EntityNPCInterface)) {
continue;
}
NBTTagCompound entityData = entity.getEntityData();
if (!entityData.hasKey(NATURAL_SPAWN_ID_TAG)) {
continue;
}
int spawnId = entityData.getInteger(NATURAL_SPAWN_ID_TAG);
Integer count = counts.get(spawnId);
counts.put(spawnId, count == null ? 1 : count + 1);
}
return counts;
}
private static long getSpawnCooldownKey(World world, int spawnId) {
return ((long) world.provider.dimensionId << 32) ^ (spawnId & 0xffffffffL);
}
private static boolean isSpawnOnCooldown(World world, SpawnData data) {
if (data.cooldownTicks <= 0 || data.id < 0) {
return false;
}
long key = getSpawnCooldownKey(world, data.id);
Long lastSpawnTick = SPAWN_COOLDOWNS.get(key);
if (lastSpawnTick == null) {
return false;
}
long tickDelta = world.getWorldInfo().getWorldTotalTime() - lastSpawnTick;
if (tickDelta < 0) {
SPAWN_COOLDOWNS.remove(key);
return false;
}
return tickDelta < data.cooldownTicks;
}
private static void markSpawnCooldown(World world, SpawnData data) {
if (data.cooldownTicks <= 0 || data.id < 0) {
return;
}
long key = getSpawnCooldownKey(world, data.id);
SPAWN_COOLDOWNS.put(key, world.getWorldInfo().getWorldTotalTime());
}
private static boolean isSpawnEntryAtCapacity(SpawnData data, Map<Integer, Integer> spawnEntryCounts) {
if (data.maxAlive <= 0 || data.id < 0) {
return false;
}
Integer currentCount = spawnEntryCounts.get(data.id);
return currentCount != null && currentCount >= data.maxAlive;
}
private static void incrementSpawnEntryCount(SpawnData data, Map<Integer, Integer> spawnEntryCounts) {
if (data.id < 0) {
return;
}
Integer currentCount = spawnEntryCounts.get(data.id);
spawnEntryCounts.put(data.id, currentCount == null ? 1 : currentCount + 1);
}
private static boolean hasNearbyPlayer(SpawnData data, World world, int x, int y, int z) {
if (data.playerMinDistance <= 0) {
return false;
}
return world.getClosestPlayer(x, y, z, data.playerMinDistance) != null;
}
private static boolean trySpawnWithEntryConfig(SpawnData data, World world, int x, int y, int z, Random rand, Map<Integer, Integer> spawnEntryCounts) {
if (y < data.spawnHeightMin || y > data.spawnHeightMax) {
return false;
}
if (isSpawnEntryAtCapacity(data, spawnEntryCounts) || isSpawnOnCooldown(world, data)) {
return false;
}
int attempts = Math.max(1, data.attemptsPerCycle);
for (int attempt = 0; attempt < attempts; attempt++) {
int attemptX = x;
int attemptZ = z;
if (attempt > 0) {
attemptX += rand.nextInt(5) - rand.nextInt(5);
attemptZ += rand.nextInt(5) - rand.nextInt(5);
}
if (!canCreatureTypeSpawnAtLocation(data, world, attemptX, y, attemptZ) || hasNearbyPlayer(data, world, attemptX, y, attemptZ)) {
continue;
}
if (spawnData(data, world, attemptX, y, attemptZ)) {
incrementSpawnEntryCount(data, spawnEntryCounts);
markSpawnCooldown(world, data);
return true;
}
}
return false;
}
public static void performWorldGenSpawning(World world, int x, int z, Random rand) {
int cap = getCap(world);
int npcCount = countNaturalSpawnedNPCs(world);
if (npcCount >= cap) {
return;
}
HashMap<Integer, Integer> spawnEntryCounts = getNaturalSpawnEntryCounts(world);
BiomeGenBase biome = world.getBiomeGenForCoords(x + 8, z + 8);
while (rand.nextFloat() < biome.getSpawningChance()) {
if (npcCount >= cap) {
return;
}
SpawnData data = SpawnController.Instance.getRandomSpawnData(biome.biomeName, world.provider.dimensionId);
if (data == null)
continue;
@@ -127,6 +322,9 @@ public class NPCSpawning {
int i2 = k1;
for (int k2 = 0; k2 < 4; ++k2) {
if (npcCount >= cap) {
return;
}
int l2 = world.getTopSolidOrLiquidBlock(j1, k1);
if (l2 > data.spawnHeightMax || l2 < data.spawnHeightMin) {
continue;
@@ -134,14 +332,16 @@ public class NPCSpawning {
l2 = l2 + (int) ((data.spawnHeightMax - l2) * Math.random());
}
if (!canCreatureTypeSpawnAtLocation(data, world, j1, l2, k1)) {
if (!trySpawnWithEntryConfig(data, world, j1, l2, k1, rand, spawnEntryCounts)) {
j1 += rand.nextInt(5) - rand.nextInt(5);
for (k1 += rand.nextInt(5) - rand.nextInt(5); j1 < x || j1 >= x + size || k1 < z || k1 >= z + size; k1 = i2 + rand.nextInt(5) - rand.nextInt(5)) {
j1 = l1 + rand.nextInt(5) - rand.nextInt(5);
}
} else if (spawnData(data, world, j1, l2, k1))
} else {
npcCount++;
break;
}
}
}
@@ -184,12 +384,23 @@ public class NPCSpawning {
if (spawnEntity instanceof EntityCustomNpc) {
EntityCustomNpc npc = (EntityCustomNpc) spawnEntity;
npc.stats.spawnCycle = 3;
if (data.despawnMode == SpawnData.DESPAWN_FORCE_PERSISTENT) {
npc.stats.canDespawn = false;
npc.stats.playerSetCanDespawn = false;
} else if (data.despawnMode == SpawnData.DESPAWN_FORCE_NATURAL) {
npc.stats.canDespawn = true;
npc.stats.playerSetCanDespawn = true;
}
npc.syncDespawnPersistence();
npc.ais.returnToStart = false;
npc.ais.startPos = new int[]{x, y, z};
npc.updateAI = true;
npc.updateClient = true;
npc.getNavigator().clearPathEntity();
}
entityliving.getEntityData().setInteger(NATURAL_SPAWN_ID_TAG, data.id);
entityliving.getEntityData().setString(NATURAL_SPAWN_NAME_TAG, data.name);
entityliving.getEntityData().setLong(NATURAL_SPAWN_TIME_TAG, world.getWorldInfo().getWorldTotalTime());
spawnEntity.setLocationAndAngles(x + 0.5, y, z + 0.5, world.rand.nextFloat() * 360.0F, 0.0F);
} catch (Exception exception) {
exception.printStackTrace();
@@ -239,4 +450,3 @@ public class NPCSpawning {
return animalSpawn || monsterSpawn || caveSpawn || liquidSpawn;
}
}
@@ -10,6 +10,7 @@ import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.util.AttributeAttackUtil;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
@@ -105,7 +106,8 @@ public class ScriptPlayerEventHandler {
// Skip zeroing if the ability has its own movement (Charge/Dash/Slam)
if (playerData.abilityData.isMovementLocked()) {
Ability current = playerData.abilityData.getCurrentAbility();
if (current == null || !current.hasAbilityMovement()) {
if (current == null || !current.hasAbilityMovement()
|| current.getPhase() != AbilityPhase.ACTIVE) {
boolean sFlying = playerData.abilityData.wasFlyingAtLock()
|| AbilityController.Instance.isPlayerFlying(player);
@@ -120,6 +122,17 @@ public class ScriptPlayerEventHandler {
}
}
// Zero WASD input during ability-controlled movement to prevent
// moveEntityWithHeading from interfering with ability velocity
{
Ability current = playerData.abilityData.getCurrentAbility();
if (current != null && current.hasAbilityMovement()
&& current.getPhase() == AbilityPhase.ACTIVE) {
player.moveForward = 0;
player.moveStrafing = 0;
}
}
if (playerData.updateClient) {
SyncController.syncPlayerData((EntityPlayerMP) player, true);
playerData.updateClient = false;
@@ -530,7 +530,7 @@ public class ServerEventsHandler {
@SubscribeEvent
public void populateChunk(PopulateChunkEvent.Post event) {
NPCSpawning.performWorldGenSpawning(event.world, event.chunkX, event.chunkZ, event.rand);
NPCSpawning.performWorldGenSpawning(event.world, event.chunkX << 4, event.chunkZ << 4, event.rand);
}
@SubscribeEvent
@@ -25,6 +25,9 @@ import java.util.Map;
import java.util.Set;
public class FlyPathFinder extends PathFinder {
private static final float STRAIGHT_COST = 1.0F;
private static final float DIAGONAL_2D_COST = 1.4142135F;
private static final float DIAGONAL_3D_COST = 1.7320508F;
/**
* Used to find obstacles
*/
@@ -141,7 +144,7 @@ public class FlyPathFinder extends PathFinder {
private NPCPath addToPath(Entity p_75861_1_, NPCPathPoint p_75861_2_, NPCPathPoint p_75861_3_, NPCPathPoint p_75861_4_, float p_75861_5_) {
p_75861_2_.totalPathDistance = 0.0F;
p_75861_2_.distanceToNext = p_75861_2_.distanceToSquared(p_75861_3_);
p_75861_2_.distanceToNext = this.estimateCostToTarget(p_75861_2_, p_75861_3_);
p_75861_2_.distanceToTarget = p_75861_2_.distanceToNext;
this.path.clearPath();
this.path.addPoint(p_75861_2_);
@@ -161,7 +164,7 @@ public class FlyPathFinder extends PathFinder {
return this.createEntityPath(p_75861_2_, p_75861_3_);
}
if (pathpoint4.distanceToSquared(p_75861_3_) < pathpoint3.distanceToSquared(p_75861_3_)) {
if (this.estimateCostToTarget(pathpoint4, p_75861_3_) < this.estimateCostToTarget(pathpoint3, p_75861_3_)) {
pathpoint3 = pathpoint4;
}
@@ -170,12 +173,13 @@ public class FlyPathFinder extends PathFinder {
for (int j = 0; j < i; ++j) {
NPCPathPoint pathpoint5 = this.pathOptions[j];
float f1 = pathpoint4.totalPathDistance + pathpoint4.distanceToSquared(pathpoint5);
float f1 = pathpoint4.totalPathDistance + this.getTraversalCost(pathpoint4, pathpoint5)
+ this.getDirectionalPenalty(pathpoint4, pathpoint5, p_75861_3_);
if (!pathpoint5.isAssigned() || f1 < pathpoint5.totalPathDistance) {
pathpoint5.previous = pathpoint4;
pathpoint5.totalPathDistance = f1;
pathpoint5.distanceToNext = pathpoint5.distanceToSquared(p_75861_3_);
pathpoint5.distanceToNext = this.estimateCostToTarget(pathpoint5, p_75861_3_);
if (pathpoint5.isAssigned()) {
this.path.changeDistance(pathpoint5, pathpoint5.totalPathDistance + pathpoint5.distanceToNext);
@@ -194,6 +198,50 @@ public class FlyPathFinder extends PathFinder {
}
}
private float getTraversalCost(NPCPathPoint from, NPCPathPoint to) {
int dx = Math.abs(to.xCoord - from.xCoord);
int dy = Math.abs(to.yCoord - from.yCoord);
int dz = Math.abs(to.zCoord - from.zCoord);
int changedAxes = dx + dy + dz;
if (changedAxes <= 1) {
return STRAIGHT_COST;
}
if (changedAxes == 2) {
return DIAGONAL_2D_COST;
}
return DIAGONAL_3D_COST;
}
private float getDirectionalPenalty(NPCPathPoint from, NPCPathPoint to, NPCPathPoint goal) {
int stepX = to.xCoord - from.xCoord;
int stepY = to.yCoord - from.yCoord;
int stepZ = to.zCoord - from.zCoord;
int goalX = goal.xCoord - from.xCoord;
int goalY = goal.yCoord - from.yCoord;
int goalZ = goal.zCoord - from.zCoord;
int stepLen = Math.abs(stepX) + Math.abs(stepY) + Math.abs(stepZ);
int goalLen = Math.abs(goalX) + Math.abs(goalY) + Math.abs(goalZ);
if (stepLen == 0 || goalLen == 0) {
return 0.0F;
}
float alignment = (float) (stepX * goalX + stepY * goalY + stepZ * goalZ) / (float) (stepLen * goalLen);
return (1.0F - alignment) * 0.04F;
}
private float estimateCostToTarget(NPCPathPoint from, NPCPathPoint to) {
float dx = Math.abs(to.xCoord - from.xCoord);
float dy = Math.abs(to.yCoord - from.yCoord);
float dz = Math.abs(to.zCoord - from.zCoord);
float max = Math.max(dx, Math.max(dy, dz));
float min = Math.min(dx, Math.min(dy, dz));
float mid = dx + dy + dz - max - min;
return DIAGONAL_3D_COST * min + DIAGONAL_2D_COST * (mid - min) + STRAIGHT_COST * (max - mid);
}
/**
* populates pathOptions with available points and returns the number of options found (args: unused1, currentPoint,
* unused2, targetPoint, maxDistance)
@@ -7,6 +7,8 @@ import noppes.npcs.entity.EntityNPCFlying;
import noppes.npcs.entity.EntityNPCInterface;
public class FlyingMoveHelper extends EntityMoveHelper {
private static final double CLOSE_ENOUGH_SQ = 0.01D;
private static final float MAX_TURN_PER_TICK = 35.0F;
private final EntityNPCInterface entity;
private double posX;
@@ -38,22 +40,24 @@ public class FlyingMoveHelper extends EntityMoveHelper {
double d5 = MathHelper.sqrt_double(d4);
speed = Math.min(d5 / 5.0D, speed);
// its here louis!
// This is the hurt time that stuns the NPC!!!!!!
// if (this.entity.hurtTime == 0 && d4 > 0.5D) {
if (d4 >= 0.5D) {
this.entity.motionX += (speed * (d0 / d5) - this.entity.motionX) * speed;
this.entity.motionZ += (speed * (d2 / d5) - this.entity.motionZ) * speed;
if (d4 > CLOSE_ENOUGH_SQ && d5 > 1.0E-4D) {
double targetMotionX = speed * (d0 / d5);
double targetMotionZ = speed * (d2 / d5);
double horizontalLerp = Math.min(1.0D, Math.max(0.12D, speed * 0.6D));
this.entity.motionX += (targetMotionX - this.entity.motionX) * horizontalLerp;
this.entity.motionZ += (targetMotionZ - this.entity.motionZ) * horizontalLerp;
if (((EntityNPCFlying) this.entity).flyLimitAllow || !this.entity.ais.hasFlyLimit) {
this.entity.motionY = verticalSpeed * (d1 / d5);
if (this.entity.motionY > 0) {
this.entity.motionY += 0.1D;
double targetMotionY = verticalSpeed * (d1 / d5);
if (targetMotionY > 0.0D) {
targetMotionY += 0.05D;
}
double verticalLerp = Math.min(1.0D, Math.max(0.15D, verticalSpeed * 0.85D));
this.entity.motionY += (targetMotionY - this.entity.motionY) * verticalLerp;
}
this.entity.velocityChanged = true;
this.entity.rotationYaw = this.limitAngle(this.entity.rotationYaw, (float) ((Math.atan2(-d0, -d2) + Math.PI) * -(180F / Math.PI)), 20.0F);
this.entity.rotationYaw = this.limitAngle(this.entity.rotationYaw, (float) ((Math.atan2(-d0, -d2) + Math.PI) * -(180F / Math.PI)), MAX_TURN_PER_TICK);
}
}
}
@@ -21,6 +21,10 @@ import noppes.npcs.entity.EntityNPCInterface;
import javax.annotation.Nullable;
public class PathNavigateFlying extends PathNavigate {
private static final long MIN_REPATH_INTERVAL_TICKS = 8L;
private static final long MAX_REPATH_INTERVAL_TICKS = 30L;
private static final int PATH_REUSE_TARGET_DELTA_SQ = 2;
private static final int FINAL_NODE_REUSE_DELTA_SQ = 3;
private EntityNPCInterface theEntity;
private World worldObj;
@@ -83,16 +87,21 @@ public class PathNavigateFlying extends PathNavigate {
}
public void updatePath() {
if (this.worldObj.getTotalWorldTime() - this.lastTimeUpdated > 20L) {
if (this.targetPos != null) {
this.currentPath = null;
this.currentPath = this.getPathToXYZ(this.targetPos.getX(), this.targetPos.getY(), this.targetPos.getZ());
this.lastTimeUpdated = this.worldObj.getTotalWorldTime();
this.tryUpdatePath = false;
}
} else {
this.tryUpdatePath = true;
if (this.targetPos == null) {
this.tryUpdatePath = false;
return;
}
long now = this.worldObj.getTotalWorldTime();
if (now - this.lastTimeUpdated < this.getAdaptiveRepathInterval()) {
this.tryUpdatePath = true;
return;
}
this.currentPath = null;
this.currentPath = this.getPathToXYZ(this.targetPos.getX(), this.targetPos.getY(), this.targetPos.getZ());
this.lastTimeUpdated = now;
this.tryUpdatePath = false;
}
public void setAvoidsWater(boolean p_75491_1_) {
@@ -156,7 +165,8 @@ public class PathNavigateFlying extends PathNavigate {
BlockPos pos = new BlockPos(x, y, z);
if (!this.canNavigate()) {
return null;
} else if (this.currentPath != null && !this.currentPath.isFinished() && pos.equals(this.targetPos)) {
} else if (this.canReuseCurrentPath(pos)) {
this.targetPos = pos;
return this.currentPath;
} else {
this.targetPos = pos;
@@ -180,7 +190,8 @@ public class PathNavigateFlying extends PathNavigate {
return null;
} else {
BlockPos blockpos = new BlockPos(entity);
if (this.currentPath != null && !this.currentPath.isFinished() && blockpos.equals(this.targetPos)) {
if (this.canReuseCurrentPath(blockpos)) {
this.targetPos = blockpos;
return this.currentPath;
} else {
this.targetPos = blockpos;
@@ -215,6 +226,8 @@ public class PathNavigateFlying extends PathNavigate {
this.removeSunnyPath();
}
this.smoothCurrentPath();
if (this.currentPath.getCurrentPathLength() == 0) {
return false;
} else {
@@ -242,6 +255,72 @@ public class PathNavigateFlying extends PathNavigate {
return !this.isInLiquid() || (this.canSwim && this.isInLiquid());
}
private long getAdaptiveRepathInterval() {
if (this.targetPos == null) {
return MAX_REPATH_INTERVAL_TICKS;
}
double distance = this.theEntity.getDistance(this.targetPos.getX() + 0.5D, this.targetPos.getY(), this.targetPos.getZ() + 0.5D);
return (long) MathHelper.clamp_double(distance * 0.6D, MIN_REPATH_INTERVAL_TICKS, MAX_REPATH_INTERVAL_TICKS);
}
private boolean canReuseCurrentPath(BlockPos newTarget) {
if (this.currentPath == null || this.currentPath.isFinished() || this.targetPos == null) {
return false;
}
if (this.getBlockDistanceSq(this.targetPos, newTarget) <= PATH_REUSE_TARGET_DELTA_SQ) {
return true;
}
NPCPathPoint finalPoint = this.currentPath.getFinalPathPoint();
return finalPoint != null && this.getPointDistanceSq(finalPoint, newTarget) <= FINAL_NODE_REUSE_DELTA_SQ;
}
private int getBlockDistanceSq(BlockPos a, BlockPos b) {
int dx = a.getX() - b.getX();
int dy = a.getY() - b.getY();
int dz = a.getZ() - b.getZ();
return dx * dx + dy * dy + dz * dz;
}
private int getPointDistanceSq(NPCPathPoint point, BlockPos blockPos) {
int dx = point.xCoord - blockPos.getX();
int dy = point.yCoord - blockPos.getY();
int dz = point.zCoord - blockPos.getZ();
return dx * dx + dy * dy + dz * dz;
}
private void smoothCurrentPath() {
if (this.currentPath == null) {
return;
}
int pathLength = this.currentPath.getCurrentPathLength();
if (pathLength < 3) {
return;
}
int width = MathHelper.ceiling_double_int(this.theEntity.width);
int height = MathHelper.ceiling_double_int(this.theEntity.height + 1.0F);
NPCPathPoint[] points = this.currentPath.points;
int writeIndex = 1;
int anchorIndex = 0;
for (int readIndex = 2; readIndex < pathLength; readIndex++) {
Vec3 anchor = this.currentPath.getVectorFromIndex(this.theEntity, anchorIndex);
Vec3 probe = this.currentPath.getVectorFromIndex(this.theEntity, readIndex);
if (!this.isDirectPathBetweenPoints(anchor, probe, width, height)) {
points[writeIndex++] = points[readIndex - 1];
anchorIndex = readIndex - 1;
}
}
points[writeIndex++] = points[pathLength - 1];
this.currentPath.setCurrentPathLength(writeIndex);
if (this.currentPath.getCurrentPathIndex() >= writeIndex) {
this.currentPath.setCurrentPathIndex(Math.max(0, writeIndex - 1));
}
}
public void onUpdateNavigation() {
++this.totalTicks;
@@ -102,7 +102,17 @@ public class ClientEventHandler {
// Ability Hotbar: Hold HUD key + scroll wheel to cycle
if (event.dwheel != 0 && ClientProxy.AbilityHudKey != null) {
int hudKeyCode = ClientProxy.AbilityHudKey.getKeyCode();
if (hudKeyCode != 0 && org.lwjgl.input.Keyboard.isKeyDown(hudKeyCode)) {
boolean hudKeyHeld = false;
if (hudKeyCode > 0) {
hudKeyHeld = hudKeyCode < org.lwjgl.input.Keyboard.getKeyCount()
&& org.lwjgl.input.Keyboard.isKeyDown(hudKeyCode);
} else if (hudKeyCode < 0) {
int mouseButton = hudKeyCode + 100;
hudKeyHeld = mouseButton >= 0
&& mouseButton < org.lwjgl.input.Mouse.getButtonCount()
&& org.lwjgl.input.Mouse.isButtonDown(mouseButton);
}
if (hudKeyHeld) {
AbilityHotbarComponent comp = (AbilityHotbarComponent) ClientHudManager.getInstance()
.getHudComponents().get(EnumHudComponent.AbilityHotbar);
if (comp != null && comp.hasAnyAbilities()) {
@@ -117,6 +117,7 @@ import noppes.npcs.client.gui.global.GuiNPCManageQuest;
import noppes.npcs.client.gui.global.GuiNPCManageTags;
import noppes.npcs.client.gui.global.GuiNPCManageTransporters;
import noppes.npcs.client.gui.global.GuiNpcManageAbilities;
import noppes.npcs.client.gui.global.GuiNpcManageAuction;
import noppes.npcs.client.gui.global.GuiNpcManageMagic;
import noppes.npcs.client.gui.global.GuiNpcManageRecipes;
import noppes.npcs.client.gui.global.GuiNpcQuestReward;
@@ -221,6 +222,7 @@ import noppes.npcs.containers.ContainerCrate;
import noppes.npcs.containers.ContainerCustomGui;
import noppes.npcs.containers.ContainerMail;
import noppes.npcs.containers.ContainerManageBanks;
import noppes.npcs.containers.ContainerManageAuction;
import noppes.npcs.containers.ContainerManageRecipes;
import noppes.npcs.containers.ContainerNPCBankInterface;
import noppes.npcs.containers.ContainerNPCCompanion;
@@ -512,6 +514,9 @@ public class ClientProxy extends CommonProxy {
else if (gui == EnumGuiType.ManageRecipes)
return new GuiNpcManageRecipes(npc, (ContainerManageRecipes) container);
else if (gui == EnumGuiType.ManageAuction)
return new GuiNpcManageAuction(npc, (ContainerManageAuction) container);
else if (gui == EnumGuiType.ManageDialogs)
return new GuiNPCManageDialogs(npc);
@@ -10,6 +10,7 @@ import kamkeel.npcs.client.renderer.lightning.LightningBolt;
import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager;
import kamkeel.npcs.controllers.data.telegraph.TelegraphManager;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.data.RequestProperSpawnData;
import kamkeel.npcs.network.packets.player.CheckPlayerValue;
import kamkeel.npcs.network.packets.player.InputDevicePacket;
import kamkeel.npcs.network.packets.player.ScreenSizePacket;
@@ -61,7 +62,7 @@ public class ClientTickHandler {
if (mc.theWorld == null) {
ClientCacheHandler.clearCache();
ClientAbilityState.reset();
// RequestProperSpawnData.clear();
RequestProperSpawnData.clear();
if (EnergyChargePreviewManager.ClientInstance != null) {
EnergyChargePreviewManager.ClientInstance.clear();
}
@@ -216,8 +217,8 @@ public class ClientTickHandler {
return;
if (mc.theWorld.getTotalWorldTime() % 20 == 0) { // Update every second
// if (RequestProperSpawnData.canDoBatchUpdate())
// RequestProperSpawnData.handleBacklog();
if (RequestProperSpawnData.canDoBatchUpdate())
RequestProperSpawnData.handleBacklog();
updateCompassMarks();
}
}
@@ -5,6 +5,7 @@ import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcButtonYesNo;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.GuiScrollWindow;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.data.SpawnData;
@@ -15,37 +16,97 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield
public SubGuiSpawningOptions(SpawnData data) {
this.data = data;
setBackground("menubg.png");
xSize = 216;
xSize = 256;
ySize = 216;
closeOnEsc = true;
}
public void initGui() {
super.initGui();
int y = guiTop - 15;
int scrollX = guiLeft + 4;
int scrollY = guiTop + 4;
int scrollW = xSize - 8;
int scrollH = ySize - 34;
addButton(new GuiNpcButtonYesNo(10, guiLeft + 120, y += 22, data.animalSpawning));
addLabel(new GuiNpcLabel(10, "spawning.animalSpawning", guiLeft + 4, y + 5));
GuiScrollWindow sw = new GuiScrollWindow(this, scrollX, scrollY, scrollW, scrollH, 0);
sw.drawDefaultBackground = false;
addScrollableGui(0, sw);
addButton(new GuiNpcButtonYesNo(11, guiLeft + 120, y += 22, data.monsterSpawning));
addLabel(new GuiNpcLabel(11, "spawning.monsterSpawning", guiLeft + 4, y + 5));
int labelX = 4;
int controlX = 132;
int y = 6;
addButton(new GuiNpcButtonYesNo(12, guiLeft + 120, y += 22, data.liquidSpawning));
addLabel(new GuiNpcLabel(12, "spawning.liquidSpawning", guiLeft + 4, y + 5));
sw.addButton(new GuiNpcButtonYesNo(10, controlX, y, data.animalSpawning));
sw.addLabel(new GuiNpcLabel(10, "spawning.animalSpawning", labelX, y + 5));
sw.getButton(10).setHoverText("tooltip.naturalspawns.options.animal");
y += 22;
addButton(new GuiNpcButtonYesNo(13, guiLeft + 120, y += 22, data.airSpawning));
addLabel(new GuiNpcLabel(13, "spawning.airSpawning", guiLeft + 4, y + 5));
sw.addButton(new GuiNpcButtonYesNo(11, controlX, y, data.monsterSpawning));
sw.addLabel(new GuiNpcLabel(11, "spawning.monsterSpawning", labelX, y + 5));
sw.getButton(11).setHoverText("tooltip.naturalspawns.options.monster");
y += 22;
addTextField(new GuiNpcTextField(14, this, guiLeft + 120, y += 22, 40, 20, "" + data.spawnHeightMin));
addLabel(new GuiNpcLabel(14, "spawning.minHeight", guiLeft + 4, y + 5));
addTextField(new GuiNpcTextField(15, this, guiLeft + 120, y += 22, 40, 20, "" + data.spawnHeightMax));
addLabel(new GuiNpcLabel(15, "spawning.maxHeight", guiLeft + 4, y + 5));
getTextField(14).integersOnly = true;
getTextField(14).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
getTextField(15).integersOnly = true;
getTextField(15).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
sw.addButton(new GuiNpcButtonYesNo(12, controlX, y, data.liquidSpawning));
sw.addLabel(new GuiNpcLabel(12, "spawning.liquidSpawning", labelX, y + 5));
sw.getButton(12).setHoverText("tooltip.naturalspawns.options.liquid");
y += 22;
addButton(new GuiNpcButton(100, guiLeft + 154, guiTop + 192, 60, 20, "gui.done"));
sw.addButton(new GuiNpcButtonYesNo(13, controlX, y, data.airSpawning));
sw.addLabel(new GuiNpcLabel(13, "spawning.airSpawning", labelX, y + 5));
sw.getButton(13).setHoverText("tooltip.naturalspawns.options.air");
y += 22;
sw.addTextField(new GuiNpcTextField(14, this, controlX, y, 60, 20, "" + data.spawnHeightMin));
sw.addLabel(new GuiNpcLabel(14, "spawning.minHeight", labelX, y + 5));
sw.getTextField(14).integersOnly = true;
sw.getTextField(14).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
sw.getTextField(14).setHoverText("tooltip.naturalspawns.options.minHeight");
y += 22;
sw.addTextField(new GuiNpcTextField(15, this, controlX, y, 60, 20, "" + data.spawnHeightMax));
sw.addLabel(new GuiNpcLabel(15, "spawning.maxHeight", labelX, y + 5));
sw.getTextField(15).integersOnly = true;
sw.getTextField(15).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
sw.getTextField(15).setHoverText("tooltip.naturalspawns.options.maxHeight");
y += 22;
sw.addTextField(new GuiNpcTextField(16, this, controlX, y, 60, 20, "" + data.maxAlive));
sw.addLabel(new GuiNpcLabel(16, "spawning.maxAlive", labelX, y + 5));
sw.getTextField(16).integersOnly = true;
sw.getTextField(16).setMinMaxDefault(0, Integer.MAX_VALUE, 0);
sw.getTextField(16).setHoverText("tooltip.naturalspawns.options.maxAlive");
y += 22;
sw.addTextField(new GuiNpcTextField(17, this, controlX, y, 60, 20, "" + data.cooldownTicks));
sw.addLabel(new GuiNpcLabel(17, "spawning.cooldownTicks", labelX, y + 5));
sw.getTextField(17).integersOnly = true;
sw.getTextField(17).setMinMaxDefault(0, Integer.MAX_VALUE, 0);
sw.getTextField(17).setHoverText("tooltip.naturalspawns.options.cooldownTicks");
y += 22;
sw.addTextField(new GuiNpcTextField(18, this, controlX, y, 60, 20, "" + data.attemptsPerCycle));
sw.addLabel(new GuiNpcLabel(18, "spawning.attemptsPerCycle", labelX, y + 5));
sw.getTextField(18).integersOnly = true;
sw.getTextField(18).setMinMaxDefault(1, Integer.MAX_VALUE, 1);
sw.getTextField(18).setHoverText("tooltip.naturalspawns.options.attemptsPerCycle");
y += 22;
sw.addTextField(new GuiNpcTextField(19, this, controlX, y, 60, 20, "" + data.playerMinDistance));
sw.addLabel(new GuiNpcLabel(19, "spawning.playerMinDistance", labelX, y + 5));
sw.getTextField(19).integersOnly = true;
sw.getTextField(19).setMinMaxDefault(0, Integer.MAX_VALUE, 24);
sw.getTextField(19).setHoverText("tooltip.naturalspawns.options.playerMinDistance");
y += 22;
sw.addButton(new GuiNpcButton(20, controlX, y, 100, 20,
new String[]{"spawning.despawn.forceNatural", "spawning.despawn.preserve", "spawning.despawn.forcePersistent"}, data.despawnMode));
sw.addLabel(new GuiNpcLabel(20, "spawning.despawnMode", labelX, y + 5));
sw.getButton(20).setHoverText("tooltip.naturalspawns.options.despawnMode");
y += 22;
sw.maxScrollY = Math.max(0, y - sw.clipHeight + 8);
addButton(new GuiNpcButton(100, guiLeft + xSize - 64, guiTop + ySize - 24, 60, 20, "gui.done"));
}
@Override
@@ -64,6 +125,9 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield
if (button.id == 13) {
data.airSpawning = button.getValue() == 1;
}
if (button.id == 20) {
data.setDespawnMode(button.getValue());
}
if (button.id == 100) {
close();
}
@@ -77,5 +141,17 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield
if (textfield.id == 15) {
data.spawnHeightMax = textfield.getInteger();
}
if (textfield.id == 16) {
data.setMaxAlive(textfield.getInteger());
}
if (textfield.id == 17) {
data.setCooldownTicks(textfield.getInteger());
}
if (textfield.id == 18) {
data.setAttemptsPerCycle(textfield.getInteger());
}
if (textfield.id == 19) {
data.setPlayerMinDistance(textfield.getInteger());
}
}
}
File diff suppressed because it is too large. Load diff
@@ -62,6 +62,12 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
this.addButton(new GuiNpcButton(1, guiLeft + 358, guiTop + 38, 58, 20, "gui.add"));
this.addButton(new GuiNpcButton(2, guiLeft + 358, guiTop + 61, 58, 20, "gui.remove"));
getButton(1).setHoverText("tooltip.naturalspawns.main.addProfile");
getButton(2).setHoverText("tooltip.naturalspawns.main.removeProfile");
if (getTextField(55) != null) {
getTextField(55).setHoverText("tooltip.naturalspawns.main.search");
}
if (this.spawn.id >= 0)
showSpawn();
@@ -74,15 +80,18 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
int y = guiTop + 30;
addLabel(new GuiNpcLabel(3, "spawning.biomes", guiLeft + 4, y));
addButton(new GuiNpcButton(3, guiLeft + 40, y - 5, 50, 20, "selectServer.edit"));
getButton(3).setHoverText("tooltip.naturalspawns.main.biomes");
addLabel(new GuiNpcLabel(11, StatCollector.translateToLocal("Dimensions"), guiLeft + 95, y));
addButton(new GuiNpcButton(11, guiLeft + 150, y - 5, 50, 20, "selectServer.edit"));
getButton(11).setHoverText("tooltip.naturalspawns.main.dimensions");
addLabel(new GuiNpcLabel(4, "spawning.options", guiLeft + 4, y += 22));
addButton(new GuiNpcButton(4, guiLeft + 90, y - 5, 50, 20, "selectServer.edit"));
getButton(4).setHoverText("tooltip.naturalspawns.main.options");
addSlider(new GuiNpcSlider(this, 5, guiLeft + 4, y += 17, 180, 20, (float) this.spawn.itemWeight / 100));
addExtra(new GuiHoverText(1, "spawning.naturalInfo", guiLeft + 188, y + 5));
addExtra(new GuiHoverText(1, "spawning.naturalInfoPerformance", guiLeft + 188, y + 5));
this.spawnEntryScroll.guiLeft = guiLeft + 4;
this.spawnEntryScroll.guiTop = y + 40;
@@ -96,13 +105,17 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
addScroll(this.spawnEntryScroll);
addButton(new GuiNpcButton(21, guiLeft + 6, y += 20, 20, 20, "+"));
getButton(21).setHoverText("tooltip.naturalspawns.main.addEntry");
if (this.spawnEntryScroll.hasSelected()) {
int selected = Integer.parseInt(this.spawnEntryScroll.getSelected());
addButton(new GuiNpcButton(22, guiLeft + 32, y, 20, 20, "-"));
getButton(22).setHoverText("tooltip.naturalspawns.main.removeEntry");
GuiNpcTextField num = new GuiNpcTextField(25, this, guiLeft + 60, y += 10, 30, 20, "" + selected);
num.integersOnly = true;
addTextField(num);
getTextField(25).setHoverText("tooltip.naturalspawns.main.slot");
addButton(new GuiNpcButton(26, guiLeft + 92, y, 100, 20, this.getTitle(this.spawn.spawnCompounds.get(selected))));
getButton(26).setHoverText("tooltip.naturalspawns.main.selectEntry");
}
}
@@ -31,6 +31,7 @@ public class AbilityHotbarComponent extends HudComponent {
private static final int BASE_SLOT_SIZE = 24;
private static final int BASE_SPACING = 28;
private static final int EDIT_HANDLE_SIZE = 10;
private AbilityHotbarSlotRenderer[] slots = new AbilityHotbarSlotRenderer[TOTAL_SLOTS];
@@ -430,25 +431,18 @@ public class AbilityHotbarComponent extends HudComponent {
int modeLabelW = fr.getStringWidth(modeLabel);
fr.drawStringWithShadow(modeLabel, overlayWidth / 2 - modeLabelW / 2, overlayHeight + 2, 0xAA888888);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(0.2f, 0.8f, 0.2f, 0.8f);
GL11.glLineWidth(1.0f);
GL11.glBegin(GL11.GL_LINE_LOOP);
GL11.glVertex2f(0, 0);
GL11.glVertex2f(overlayWidth, 0);
GL11.glVertex2f(overlayWidth, overlayHeight);
GL11.glVertex2f(0, overlayHeight);
GL11.glEnd();
net.minecraft.client.gui.Gui.drawRect(0, 0, overlayWidth, overlayHeight, 0x22000000);
drawRectOutline(0, 0, overlayWidth, overlayHeight, 0xCC66CC66);
GL11.glColor4f(0.8f, 0.8f, 0.8f, 0.9f);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(overlayWidth - 10, overlayHeight - 10);
GL11.glVertex2f(overlayWidth, overlayHeight - 10);
GL11.glVertex2f(overlayWidth, overlayHeight);
GL11.glVertex2f(overlayWidth - 10, overlayHeight);
GL11.glEnd();
int handleLeft = overlayWidth - EDIT_HANDLE_SIZE;
int handleTop = overlayHeight - EDIT_HANDLE_SIZE;
net.minecraft.client.gui.Gui.drawRect(handleLeft, handleTop, overlayWidth, overlayHeight, 0xFFE0E0E0);
drawRectOutline(handleLeft, handleTop, overlayWidth, overlayHeight, 0xFF5A5A5A);
net.minecraft.client.gui.Gui.drawRect(handleLeft + 2, handleTop + 7, handleLeft + 8, handleTop + 8, 0xAA666666);
net.minecraft.client.gui.Gui.drawRect(handleLeft + 4, handleTop + 5, handleLeft + 8, handleTop + 6, 0xAA666666);
net.minecraft.client.gui.Gui.drawRect(handleLeft + 6, handleTop + 3, handleLeft + 8, handleTop + 4, 0xAA666666);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_TEXTURE_2D);
@@ -610,7 +604,20 @@ public class AbilityHotbarComponent extends HudComponent {
private boolean isHudKeyHeld() {
if (ClientProxy.AbilityHudKey == null) return false;
int keyCode = ClientProxy.AbilityHudKey.getKeyCode();
return keyCode != 0 && org.lwjgl.input.Keyboard.isKeyDown(keyCode);
if (keyCode == 0 || keyCode == -1) return false;
// Mouse bindings are encoded as negative key codes (offset by 100).
if (keyCode < -1) {
int mouseButton = keyCode + 100;
return mouseButton >= 0
&& mouseButton < org.lwjgl.input.Mouse.getButtonCount()
&& org.lwjgl.input.Mouse.isButtonDown(mouseButton);
}
// Guard against invalid/out-of-range keyboard codes to avoid Buffer.checkIndex crashes.
return keyCode > 0
&& keyCode < org.lwjgl.input.Keyboard.getKeyCount()
&& org.lwjgl.input.Keyboard.isKeyDown(keyCode);
}
public boolean hasAnyAbilities() {
@@ -694,4 +701,11 @@ public class AbilityHotbarComponent extends HudComponent {
updateAbilities();
lastUpdateTime = Minecraft.getSystemTime();
}
private void drawRectOutline(int left, int top, int right, int bottom, int color) {
net.minecraft.client.gui.Gui.drawRect(left, top, right, top + 1, color);
net.minecraft.client.gui.Gui.drawRect(left, bottom - 1, right, bottom, color);
net.minecraft.client.gui.Gui.drawRect(left, top, left + 1, bottom, color);
net.minecraft.client.gui.Gui.drawRect(right - 1, top, right, bottom, color);
}
}
@@ -247,7 +247,7 @@ public class GuiNPCGlobalMainMenu extends GuiNPCInterface2 {
NoppesUtil.requestOpenGUI(EnumGuiType.ManageAbilities);
}
if (id == 22) {
// NoppesUtil.requestOpenGUI(EnumGuiType.ManageAuction);
NoppesUtil.requestOpenGUI(EnumGuiType.ManageAuction);
}
}
@@ -11,10 +11,12 @@ import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import noppes.npcs.client.AuctionClientConfig;
import noppes.npcs.client.gui.global.GuiNpcManageAuction;
import noppes.npcs.constants.EnumClaimType;
import noppes.npcs.containers.ContainerAuctionListing;
import noppes.npcs.containers.ContainerAuctionSell;
import noppes.npcs.containers.ContainerAuctionTrades;
import noppes.npcs.containers.ContainerManageAuction;
import noppes.npcs.containers.SlotAuctionDisplay;
import noppes.npcs.controllers.data.AuctionClaim;
import noppes.npcs.controllers.data.AuctionListing;
@@ -49,6 +51,8 @@ public class AuctionTooltipHandler {
addTradesTooltip((GuiAuctionTrades) screen, event.itemStack, event.toolTip);
} else if (screen instanceof GuiAuctionSell) {
addSellTooltip((GuiAuctionSell) screen, event.itemStack, event.toolTip);
} else if (screen instanceof GuiNpcManageAuction) {
addManageAuctionTooltip((GuiNpcManageAuction) screen, event.itemStack, event.toolTip);
}
}
@@ -255,4 +259,125 @@ public class AuctionTooltipHandler {
}
}
// ========== Global Manage Auction ==========
private static void addManageAuctionTooltip(GuiNpcManageAuction gui, ItemStack stack, List<String> tooltip) {
Slot slot = findHoveredSlot(gui, stack);
if (slot == null) return;
ContainerManageAuction container = gui.getManageContainer();
if (container == null) return;
GuiNpcManageAuction.Tab tab = gui.getActiveTab();
if (tab == GuiNpcManageAuction.Tab.LISTINGS && container.isDisplaySlot(slot.slotNumber)) {
int displayIndex = container.toDisplayIndex(slot.slotNumber);
AuctionListing listing = container.getListingAtDisplay(displayIndex);
if (listing == null) return;
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.seller")
.replace("%s", EnumChatFormatting.WHITE + listing.sellerName));
if (listing.hasBids()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.currentBid)));
tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), listing.bidCount));
} else {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.startingPrice")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.startingPrice)));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.noBids"));
}
if (listing.hasBuyout()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.buyout")
.replace("%s", EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrencyWithName(listing.buyoutPrice)));
}
long timeRemaining = listing.getTimeRemaining();
String timeText = StatCollector.translateToLocal("auction.timeLeft")
.replace("%s", AuctionFormatUtil.formatTimeRemaining(timeRemaining));
tooltip.add((AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
tooltip.add("");
tooltip.add(EnumChatFormatting.AQUA + "Left-click: View details");
tooltip.add(EnumChatFormatting.GOLD + "Right-click: Stop player");
tooltip.add(EnumChatFormatting.LIGHT_PURPLE + "Shift+Right-click: Cancel to global");
return;
}
if (tab == GuiNpcManageAuction.Tab.CLAIMS && container.isDisplaySlot(slot.slotNumber)) {
int displayIndex = container.toDisplayIndex(slot.slotNumber);
AuctionClaim claim = container.getClaimAtDisplay(displayIndex);
if (claim != null) {
addGlobalClaimTooltip(claim, tooltip);
return;
}
AuctionListing listing = container.getListingAtDisplay(displayIndex);
if (listing != null) {
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.seller")
.replace("%s", EnumChatFormatting.WHITE + listing.sellerName));
if (listing.hasBids()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.currentBid)));
} else {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.startingPrice")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.startingPrice)));
}
if (listing.hasBuyout()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.buyout")
.replace("%s", EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrencyWithName(listing.buyoutPrice)));
}
tooltip.add("");
tooltip.add(EnumChatFormatting.GOLD + "Right-click: Stop player");
tooltip.add(EnumChatFormatting.LIGHT_PURPLE + "Shift+Right-click: Cancel to global");
}
return;
}
if (tab == GuiNpcManageAuction.Tab.CREATE) {
if (container.isCreateSlot(slot.slotNumber)) {
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.leftClear"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.rightRemove"));
} else if (container.isPlayerSlot(slot.slotNumber)) {
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.leftAdd"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.rightAddOne"));
}
}
}
private static void addGlobalClaimTooltip(AuctionClaim claim, List<String> tooltip) {
tooltip.add("");
if (claim.type == EnumClaimType.ITEM) {
tooltip.add(EnumChatFormatting.AQUA + "Global Item Claim");
} else if (claim.type == EnumClaimType.CURRENCY) {
tooltip.add(EnumChatFormatting.GOLD + "Global Currency Claim");
if (claim.itemName != null && !claim.itemName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.soldItem")
.replace("%s", EnumChatFormatting.WHITE + claim.itemName));
}
if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.buyer")
.replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName));
}
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(claim.currency)));
tooltip.add(EnumChatFormatting.GRAY + "Claiming this does not change your balance.");
} else if (claim.type == EnumClaimType.REFUND) {
tooltip.add(EnumChatFormatting.RED + "Global Refund Claim");
if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.outbidBy")
.replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName));
}
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(claim.currency)));
}
tooltip.add("");
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.claim.clickToClaim"));
}
}
@@ -416,6 +416,12 @@ public abstract class GuiNPCInterface extends GuiScreen {
tf.drawHover(i, j, subGui);
}
for(GuiScrollWindow guiScrollableComponent : scrollWindows.values()) {
if (guiScrollableComponent.isMouseOver(mouseX, mouseY)) {
guiScrollableComponent.drawHoverTexts(mouseX, mouseY);
}
}
for (GuiScreen gui : extra.values())
gui.drawScreen(i, j, f);
@@ -82,7 +82,8 @@ public class GuiNpcButton extends GuiButton {
}
public void setHoverText(String text) {
this.hoverableText = StatCollector.translateToLocal(text);
String translated = StatCollector.translateToLocal(text);
this.hoverableText = translated == null ? "" : translated.replace("\\n", "\n");
}
public int getValue() {
@@ -201,13 +202,30 @@ public class GuiNpcButton extends GuiButton {
Minecraft mc = Minecraft.getMinecraft();
String displayString = StatCollector.translateToLocal(hoverableText);
GL11.glColor4f(1, 1, 1, 1);
List<String> lines = TextSplitter.splitText(displayString, 30);
List<String> lines = splitHoverText(displayString, 30);
drawHoveringText(lines, i, j, mc);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glPopMatrix();
}
}
private List<String> splitHoverText(String text, int maxLineLength) {
List<String> lines = new ArrayList<String>();
if (text == null || text.isEmpty())
return lines;
String normalized = text.replace("\\n", "\n");
String[] explicitLines = normalized.split("\\r?\\n", -1);
for (String line : explicitLines) {
if (line.isEmpty()) {
lines.add("");
continue;
}
lines.addAll(TextSplitter.splitText(line, maxLineLength));
}
return lines;
}
protected void drawHoveringText(List textLines, int x, int y, Minecraft mc) {
if (mc.fontRenderer == null || textLines.isEmpty())
return;
@@ -12,6 +12,7 @@ import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import java.util.ArrayList;
import java.util.List;
public class GuiNpcTextField extends GuiTextField {
@@ -304,7 +305,8 @@ public class GuiNpcTextField extends GuiTextField {
}
public void setHoverText(String text) {
this.hoverableText = StatCollector.translateToLocal(text);
String translated = StatCollector.translateToLocal(text);
this.hoverableText = translated == null ? "" : translated.replace("\\n", "\n");
}
public boolean hasHoverText() {
@@ -317,10 +319,14 @@ public class GuiNpcTextField extends GuiTextField {
}
public void drawHover(int mouseX, int mouseY, boolean hasSubGui) {
drawHover(mouseX, mouseY, mouseX, mouseY, hasSubGui);
}
public void drawHover(int hitMouseX, int hitMouseY, int tooltipMouseX, int tooltipMouseY, boolean hasSubGui) {
if (hasSubGui || !enabled || hoverableText.isEmpty())
return;
boolean isHovered = isMouseOver(mouseX, mouseY);
boolean isHovered = isMouseOver(hitMouseX, hitMouseY);
if (!isHovered) {
wasHovered = false;
hoverCount = 0;
@@ -338,13 +344,30 @@ public class GuiNpcTextField extends GuiTextField {
GL11.glPushMatrix();
Minecraft mc = Minecraft.getMinecraft();
GL11.glColor4f(1, 1, 1, 1);
List<String> lines = TextSplitter.splitText(hoverableText, 30);
drawHoveringText(lines, mouseX, mouseY, mc);
List<String> lines = splitHoverText(hoverableText, 30);
drawHoveringText(lines, tooltipMouseX, tooltipMouseY, mc);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glPopMatrix();
}
}
private List<String> splitHoverText(String text, int maxLineLength) {
List<String> lines = new ArrayList<String>();
if (text == null || text.isEmpty())
return lines;
String normalized = text.replace("\\n", "\n");
String[] explicitLines = normalized.split("\\r?\\n", -1);
for (String line : explicitLines) {
if (line.isEmpty()) {
lines.add("");
continue;
}
lines.addAll(TextSplitter.splitText(line, maxLineLength));
}
return lines;
}
protected void drawHoveringText(List<String> textLines, int x, int y, Minecraft mc) {
if (mc.fontRenderer == null || textLines.isEmpty())
return;
@@ -251,12 +251,6 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC
}
GL11.glPopMatrix();
// Draw hover texts in screen space (after scissor/translation are undone)
// so tooltips are not clipped and are positioned correctly
if (isMouseOver(mouseX, mouseY)) {
drawHoverTexts(mouseX, mouseY);
}
}
public void drawScreen(int mouseX, int mouseY, float partialTicks, int mouseScroll) {
@@ -293,16 +287,21 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC
* Draws hover texts for buttons in screen space (called after GL scissor/translate are undone).
* Hover state was already computed during drawComponents with scroll-local coords.
*/
private void drawHoverTexts(int mouseX, int mouseY) {
public void drawHoverTexts(int mouseX, int mouseY) {
boolean subGui = parent.hasSubGui();
for (GuiNpcButton button : buttons.values()) {
if (!button.hoverableText.isEmpty()) {
button.drawHover(mouseX, mouseY, subGui);
}
}
// Label hover: convert screen mouse to scroll-local coords for hit testing
int localMouseX = mouseX - xPos;
int localMouseY = (int) (mouseY - yPos + scrollY);
for (GuiNpcTextField textField : textfields.values()) {
if (textField.hasHoverText()) {
textField.drawHover(localMouseX, localMouseY, mouseX, mouseY, subGui);
}
}
// Label hover: convert screen mouse to scroll-local coords for hit testing
for (GuiNpcLabel label : labels.values()) {
if (!label.hoverableText.isEmpty()) {
label.drawHover(localMouseX, localMouseY, mouseX, mouseY, subGui, fontRendererObj);
@@ -0,0 +1,384 @@
package noppes.npcs.containers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import noppes.npcs.NoppesUtilPlayer;
import noppes.npcs.constants.EnumClaimType;
import noppes.npcs.controllers.data.AuctionClaim;
import noppes.npcs.controllers.data.AuctionListing;
import java.util.ArrayList;
import java.util.List;
/**
* Global auction management container.
* Uses a 9x5 display grid plus staged/detail slots on the right panel and player inventory below the grid.
*/
public class ContainerManageAuction extends ContainerNpcInterface {
public enum DisplayMode {
LISTINGS,
CLAIMS
}
public static final int DISPLAY_COLS = 9;
public static final int DISPLAY_ROWS = 5;
public static final int DISPLAY_SLOT_COUNT = DISPLAY_COLS * DISPLAY_ROWS;
public static final int DISPLAY_X = 8;
public static final int DISPLAY_Y = 16;
public static final int PLAYER_INV_X = 8;
public static final int PLAYER_INV_Y = 113;
public static final int HOTBAR_Y = 171;
public static final int PLAYER_SLOT_COUNT = 36;
public static final int CREATE_SLOT_X = 188;
public static final int CREATE_SLOT_Y = 156;
public static final int DETAIL_SLOT_X = 194;
public static final int DETAIL_SLOT_Y = 56;
private static final int MAX_STACK = 64;
public static final int DISPLAY_SLOT_START = 0;
public static final int PLAYER_SLOT_START = DISPLAY_SLOT_START + DISPLAY_SLOT_COUNT;
public static final int DETAIL_SLOT_INDEX = PLAYER_SLOT_START + PLAYER_SLOT_COUNT;
public static final int CREATE_SLOT_INDEX = DETAIL_SLOT_INDEX + 1;
private static final int HIDDEN_SLOT_X = -1000;
private static final int HIDDEN_SLOT_Y = -1000;
public final InventoryAuctionDisplay displayInventory;
private final IInventory detailInventory;
private final IInventory createInventory;
private DisplayMode displayMode = DisplayMode.LISTINGS;
private Slot detailSlot;
private Slot createSlot;
private int hiddenDisplaySlot = -1;
public ContainerManageAuction(EntityPlayer player) {
super(player);
this.player = player;
displayInventory = new InventoryAuctionDisplay(DISPLAY_SLOT_COUNT);
detailInventory = new InventoryBasic("GlobalAuctionDetail", false, 1);
createInventory = new InventoryBasic("GlobalAuctionCreate", false, 1);
// 9x5 display grid (listings / global claims)
for (int row = 0; row < DISPLAY_ROWS; row++) {
for (int col = 0; col < DISPLAY_COLS; col++) {
int slotIndex = col + row * DISPLAY_COLS;
int x = DISPLAY_X + col * 18;
int y = DISPLAY_Y + row * 18;
addSlotToContainer(new SlotAuctionDisplay(displayInventory, slotIndex, x, y));
}
}
// Player inventory below display grid
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 9; col++) {
int playerIndex = col + row * 9 + 9;
int x = PLAYER_INV_X + col * 18;
int y = PLAYER_INV_Y + row * 18;
addSlotToContainer(new Slot(player.inventory, playerIndex, x, y));
}
}
for (int col = 0; col < 9; col++) {
int x = PLAYER_INV_X + col * 18;
addSlotToContainer(new Slot(player.inventory, col, x, HOTBAR_Y));
}
// Listing details slot (right panel)
detailSlot = new SlotAuctionDisplay(detailInventory, 0, DETAIL_SLOT_X, DETAIL_SLOT_Y);
addSlotToContainer(detailSlot);
// Staged fake listing slot
createSlot = new Slot(createInventory, 0, CREATE_SLOT_X, CREATE_SLOT_Y) {
@Override
public boolean isItemValid(ItemStack stack) {
return false;
}
@Override
public boolean canTakeStack(EntityPlayer player) {
return false;
}
};
addSlotToContainer(createSlot);
setDetailSlotVisible(false);
setCreateSlotVisible(false);
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) {
return null;
}
@Override
public ItemStack slotClick(int slotIndex, int mouseButton, int mode, EntityPlayer player) {
// Block native container interactions. GUI handles all click behaviors.
return null;
}
public void setDisplayMode(DisplayMode mode) {
this.displayMode = mode != null ? mode : DisplayMode.LISTINGS;
}
public DisplayMode getDisplayMode() {
return displayMode;
}
public void clearDisplay() {
displayInventory.clear();
}
public void setListingsPage(List<AuctionListing> listings) {
displayMode = DisplayMode.LISTINGS;
clearHiddenDisplaySlot();
displayInventory.clear();
if (listings == null) return;
for (int i = 0; i < listings.size() && i < DISPLAY_SLOT_COUNT; i++) {
displayInventory.setListing(i, listings.get(i));
}
}
public void setClaimsPage(List<AuctionClaim> claims) {
displayMode = DisplayMode.CLAIMS;
clearHiddenDisplaySlot();
displayInventory.clear();
if (claims == null) return;
for (int i = 0; i < claims.size() && i < DISPLAY_SLOT_COUNT; i++) {
displayInventory.setClaimItem(i, claims.get(i));
}
}
/**
* Claims page can contain both global claims and active global listings.
* Order mirrors My Trades:
* sold claims, outbid claims, won claims, active listings, expired claims.
*/
public void setClaimsAndListingsPage(List<AuctionClaim> claims, List<AuctionListing> listings) {
displayMode = DisplayMode.CLAIMS;
clearHiddenDisplaySlot();
displayInventory.clear();
List<AuctionClaim> soldClaims = new ArrayList<AuctionClaim>();
List<AuctionClaim> outbidClaims = new ArrayList<AuctionClaim>();
List<AuctionClaim> wonClaims = new ArrayList<AuctionClaim>();
List<AuctionClaim> expiredClaims = new ArrayList<AuctionClaim>();
if (claims != null) {
for (AuctionClaim claim : claims) {
if (claim == null) continue;
if (claim.type == EnumClaimType.CURRENCY) {
soldClaims.add(claim);
} else if (claim.type == EnumClaimType.REFUND) {
outbidClaims.add(claim);
} else if (claim.type == EnumClaimType.ITEM) {
if (claim.isReturned) {
expiredClaims.add(claim);
} else {
wonClaims.add(claim);
}
} else {
wonClaims.add(claim);
}
}
}
int slot = 0;
slot = fillClaims(slot, soldClaims);
slot = fillClaims(slot, outbidClaims);
slot = fillClaims(slot, wonClaims);
if (listings != null) {
for (int i = 0; i < listings.size() && slot < DISPLAY_SLOT_COUNT; i++) {
displayInventory.setListing(slot, listings.get(i));
slot++;
}
}
fillClaims(slot, expiredClaims);
}
private int fillClaims(int slot, List<AuctionClaim> claims) {
if (claims == null) return slot;
for (int i = 0; i < claims.size() && slot < DISPLAY_SLOT_COUNT; i++) {
displayInventory.setClaimItem(slot, claims.get(i));
slot++;
}
return slot;
}
public boolean isDisplaySlot(int containerSlotIndex) {
return containerSlotIndex >= DISPLAY_SLOT_START && containerSlotIndex < DISPLAY_SLOT_START + DISPLAY_SLOT_COUNT;
}
public int toDisplayIndex(int containerSlotIndex) {
if (!isDisplaySlot(containerSlotIndex)) return -1;
return containerSlotIndex - DISPLAY_SLOT_START;
}
public AuctionListing getListingAtDisplay(int displayIndex) {
if (displayIndex < 0 || displayIndex >= DISPLAY_SLOT_COUNT) return null;
return displayInventory.getListing(displayIndex);
}
public AuctionClaim getClaimAtDisplay(int displayIndex) {
if (displayIndex < 0 || displayIndex >= DISPLAY_SLOT_COUNT) return null;
return displayInventory.getClaim(displayIndex);
}
public boolean isPlayerSlot(int containerSlotIndex) {
return containerSlotIndex >= PLAYER_SLOT_START && containerSlotIndex < PLAYER_SLOT_START + PLAYER_SLOT_COUNT;
}
public boolean isCreateSlot(int containerSlotIndex) {
return containerSlotIndex == CREATE_SLOT_INDEX;
}
public boolean isDetailSlot(int containerSlotIndex) {
return containerSlotIndex == DETAIL_SLOT_INDEX;
}
public void setDetailItem(ItemStack stack) {
detailInventory.setInventorySlotContents(0, stack != null ? stack.copy() : null);
}
public void clearDetailItem() {
detailInventory.setInventorySlotContents(0, null);
}
public void setDetailSlotVisible(boolean visible) {
if (detailSlot == null) return;
detailSlot.xDisplayPosition = visible ? DETAIL_SLOT_X : HIDDEN_SLOT_X;
detailSlot.yDisplayPosition = visible ? DETAIL_SLOT_Y : HIDDEN_SLOT_Y;
}
public void setCreateSlotVisible(boolean visible) {
if (createSlot == null) return;
createSlot.xDisplayPosition = visible ? CREATE_SLOT_X : HIDDEN_SLOT_X;
createSlot.yDisplayPosition = visible ? CREATE_SLOT_Y : HIDDEN_SLOT_Y;
}
public void setHiddenDisplaySlot(int displayIndex) {
if (displayIndex < 0 || displayIndex >= DISPLAY_SLOT_COUNT) {
clearHiddenDisplaySlot();
return;
}
if (hiddenDisplaySlot == displayIndex) return;
clearHiddenDisplaySlot();
hiddenDisplaySlot = displayIndex;
displayInventory.setInventorySlotContents(displayIndex, null);
}
public void clearHiddenDisplaySlot() {
if (hiddenDisplaySlot < 0 || hiddenDisplaySlot >= DISPLAY_SLOT_COUNT) {
hiddenDisplaySlot = -1;
return;
}
restoreDisplaySlot(hiddenDisplaySlot);
hiddenDisplaySlot = -1;
}
public int getHiddenDisplaySlot() {
return hiddenDisplaySlot;
}
private void restoreDisplaySlot(int displayIndex) {
if (displayIndex < 0 || displayIndex >= DISPLAY_SLOT_COUNT) return;
AuctionClaim claim = displayInventory.getClaim(displayIndex);
if (claim != null) {
displayInventory.setClaimItem(displayIndex, claim);
return;
}
AuctionListing listing = displayInventory.getListing(displayIndex);
if (listing != null) {
displayInventory.setListing(displayIndex, listing);
return;
}
displayInventory.setInventorySlotContents(displayIndex, null);
}
public ItemStack getCreateItem() {
return createInventory.getStackInSlot(0);
}
public void clearCreateSlot() {
createInventory.setInventorySlotContents(0, null);
}
public void addToCreateSlot(int containerPlayerSlot, boolean fullStack) {
if (!isPlayerSlot(containerPlayerSlot)) return;
Slot slot = (Slot) inventorySlots.get(containerPlayerSlot);
if (slot == null) return;
ItemStack source = slot.getStack();
if (source == null) return;
ItemStack staged = createInventory.getStackInSlot(0);
int toAdd = fullStack ? source.stackSize : 1;
if (staged == null) {
ItemStack copy = source.copy();
copy.stackSize = Math.min(MAX_STACK, toAdd);
createInventory.setInventorySlotContents(0, copy);
return;
}
if (!itemsMatch(staged, source)) {
ItemStack copy = source.copy();
copy.stackSize = Math.min(MAX_STACK, toAdd);
createInventory.setInventorySlotContents(0, copy);
return;
}
int space = MAX_STACK - staged.stackSize;
int add = Math.min(space, toAdd);
if (add > 0) {
staged.stackSize += add;
}
}
public void removeFromCreateSlot(boolean removeAll) {
ItemStack staged = createInventory.getStackInSlot(0);
if (staged == null) return;
if (removeAll || staged.stackSize <= 1) {
createInventory.setInventorySlotContents(0, null);
} else {
staged.stackSize--;
}
}
public int countItemInPlayerInventory(ItemStack target) {
if (target == null || player == null || player.inventory == null) return 0;
int total = 0;
for (int i = 0; i < player.inventory.mainInventory.length; i++) {
ItemStack stack = player.inventory.mainInventory[i];
if (stack != null && itemsMatch(target, stack)) {
total += stack.stackSize;
}
}
return total;
}
private boolean itemsMatch(ItemStack a, ItemStack b) {
return NoppesUtilPlayer.compareItems(a, b, false, false);
}
@Override
public void onContainerClosed(EntityPlayer player) {
super.onContainerClosed(player);
clearHiddenDisplaySlot();
clearDetailItem();
clearCreateSlot();
}
}
@@ -43,6 +43,7 @@ import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
/**
@@ -63,7 +64,8 @@ public class AuctionController implements IAuctionHandler {
// Main data stores - listings only, claims are stored in PlayerData
private final Map<String, AuctionListing> listings = new ConcurrentHashMap<>();
// Claims are now stored in PlayerData.tradeData, not here
// Shared global claims for admin-managed auction actions
private final List<AuctionClaim> globalClaims = new CopyOnWriteArrayList<>();
// =========================================
// Player Indices for O(1) Lookups
@@ -163,9 +165,12 @@ public class AuctionController implements IAuctionHandler {
if (listing.status != EnumAuctionStatus.ACTIVE) return;
listing.status = EnumAuctionStatus.ENDED;
boolean isGlobalListing = listing.isGlobalListing;
// Remove from seller's active listings
removeFromPlayerListings(listing.sellerUUID, listing.id);
if (!isGlobalListing && listing.sellerUUID != null) {
removeFromPlayerListings(listing.sellerUUID, listing.id);
}
// Remove from bidder's active bids if any
if (listing.highBidderUUID != null) {
@@ -188,26 +193,38 @@ public class AuctionController implements IAuctionHandler {
AuctionClaim currencyClaim = AuctionClaim.createCurrencyClaim(
listing.sellerUUID, listing.sellerName, listing.id, sellerReceives,
itemDisplayName, listing.highBidderName);
addClaimToPlayer(listing.sellerUUID, currencyClaim);
if (isGlobalListing) {
addGlobalClaim(currencyClaim);
} else {
addClaimToPlayer(listing.sellerUUID, currencyClaim);
}
// Notifications
sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_WON, listing.id,
"You won the auction for " + itemDisplayName + "!");
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id,
"Your " + itemDisplayName + " sold for " + saleAmount + " " + ConfigMarket.CurrencyName + "!");
if (!isGlobalListing && listing.sellerUUID != null) {
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id,
"Your " + itemDisplayName + " sold for " + saleAmount + " " + ConfigMarket.CurrencyName + "!");
}
logAuction(EnumAuctionLogAction.SOLD, listing.sellerName, itemDisplayName, saleAmount,
"Winner: " + listing.highBidderName + ", Tax: " + tax);
"Winner: " + listing.highBidderName + ", Tax: " + tax + (isGlobalListing ? ", Global listing" : ""));
} else {
// No bids - return item to seller
// No bids - return item to seller/global claims
AuctionClaim returnClaim = AuctionClaim.createItemReturnedClaim(
listing.sellerUUID, listing.sellerName, listing.id, listing.item);
addClaimToPlayer(listing.sellerUUID, returnClaim);
if (isGlobalListing) {
addGlobalClaim(returnClaim);
} else {
addClaimToPlayer(listing.sellerUUID, returnClaim);
if (listing.sellerUUID != null) {
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_EXPIRED, listing.id,
"Your auction for " + itemDisplayName + " expired with no bids.");
}
}
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_EXPIRED, listing.id,
"Your auction for " + itemDisplayName + " expired with no bids.");
logAuction(EnumAuctionLogAction.EXPIRED, listing.sellerName, itemDisplayName, listing.startingPrice, "No bids");
logAuction(EnumAuctionLogAction.EXPIRED, listing.sellerName, itemDisplayName, listing.startingPrice,
"No bids" + (isGlobalListing ? ", Global listing" : ""));
}
}
}
@@ -217,10 +234,12 @@ public class AuctionController implements IAuctionHandler {
// =========================================
private void addToPlayerListings(UUID playerUUID, String listingId) {
if (playerUUID == null || listingId == null || listingId.isEmpty()) return;
playerListingIds.computeIfAbsent(playerUUID, k -> ConcurrentHashMap.newKeySet()).add(listingId);
}
private void removeFromPlayerListings(UUID playerUUID, String listingId) {
if (playerUUID == null || listingId == null || listingId.isEmpty()) return;
Set<String> ids = playerListingIds.get(playerUUID);
if (ids != null) {
ids.remove(listingId);
@@ -231,10 +250,12 @@ public class AuctionController implements IAuctionHandler {
}
private void addToPlayerBids(UUID playerUUID, String listingId) {
if (playerUUID == null || listingId == null || listingId.isEmpty()) return;
playerBidIds.computeIfAbsent(playerUUID, k -> ConcurrentHashMap.newKeySet()).add(listingId);
}
private void removeFromPlayerBids(UUID playerUUID, String listingId) {
if (playerUUID == null || listingId == null || listingId.isEmpty()) return;
Set<String> ids = playerBidIds.get(playerUUID);
if (ids != null) {
ids.remove(listingId);
@@ -259,6 +280,70 @@ public class AuctionController implements IAuctionHandler {
}
}
/**
* Add a claim to the global admin claims pool.
*/
private void addGlobalClaim(AuctionClaim claim) {
if (claim == null || claim.claimed) return;
// Global claims are not tied to a single player.
claim.playerUUID = null;
claim.playerName = "Global";
globalClaims.add(claim);
markDirty();
}
private List<AuctionClaim> getGlobalClaimsSnapshot() {
List<AuctionClaim> result = new ArrayList<>();
for (AuctionClaim claim : globalClaims) {
if (claim != null && !claim.claimed) {
result.add(claim);
}
}
return result;
}
private AuctionClaim getGlobalClaimInternal(String claimId) {
if (claimId == null || claimId.isEmpty()) return null;
for (AuctionClaim claim : globalClaims) {
if (claim != null && !claim.claimed && claimId.equals(claim.id)) {
return claim;
}
}
return null;
}
private boolean claimAndRemoveGlobal(String claimId) {
AuctionClaim claim = getGlobalClaimInternal(claimId);
if (claim == null) return false;
claim.claimed = true;
return globalClaims.remove(claim);
}
/**
* Full list of unclaimed global claims sorted newest-first.
*/
public List<AuctionClaim> getAllGlobalClaims() {
List<AuctionClaim> snapshot = getGlobalClaimsSnapshot();
snapshot.sort((a, b) -> Long.compare(b.createdTime, a.createdTime));
return snapshot;
}
/**
* Full list of active global listings sorted newest-first.
*/
public List<AuctionListing> getActiveGlobalListings() {
List<AuctionListing> result = new ArrayList<>();
for (AuctionListing listing : listings.values()) {
if (listing == null) continue;
if (!listing.isGlobalListing) continue;
if (!listing.isActive()) continue;
result.add(listing);
}
result.sort((a, b) -> Long.compare(b.createdTime, a.createdTime));
return result;
}
// =========================================
// Listing Management
// =========================================
@@ -335,12 +420,57 @@ public class AuctionController implements IAuctionHandler {
return null; // Success
}
/**
* Create a fake/global listing managed through the global auction admin GUI.
* Global listings do not consume player currency and route proceeds to global claims.
*/
public String createGlobalListing(EntityPlayer admin, String sellerName, ItemStack item, long startingPrice, long buyoutPrice, int durationHours) {
if (!ConfigMarket.AuctionEnabled) {
return "Auction is disabled.";
}
if (admin == null) {
return "Admin is missing.";
}
if (item == null) {
return "No item provided.";
}
if (startingPrice < ConfigMarket.MinimumListingPrice) {
return "Starting price must be at least " + ConfigMarket.MinimumListingPrice + " " + ConfigMarket.CurrencyName + ".";
}
if (buyoutPrice > 0 && buyoutPrice < startingPrice) {
return "Buyout price must be higher than starting price.";
}
String cleanSeller = sellerName != null ? sellerName.trim() : "";
if (cleanSeller.isEmpty()) {
cleanSeller = "Server";
}
int hours = durationHours > 0 ? durationHours : ConfigMarket.AuctionDurationHours;
long durationMs = hours * 60L * 60L * 1000L;
// Global listings do not belong to a player UUID, only to the global pool.
AuctionListing listing = new AuctionListing(null, cleanSeller, item, startingPrice, buyoutPrice, durationMs);
listing.isGlobalListing = true;
listings.put(listing.id, listing);
markDirty();
logAuction(EnumAuctionLogAction.CREATED, admin.getCommandSenderName(), item.getDisplayName(), startingPrice,
"Global listing, Seller: " + cleanSeller + ", Buyout: " + (buyoutPrice > 0 ? buyoutPrice : "None") + ", DurationHours: " + hours);
return null;
}
public String cancelListing(String listingId, EntityPlayer player, boolean isAdmin) {
AuctionListing listing = listings.get(listingId);
if (listing == null) {
return "Listing not found.";
}
if (isAdmin && listing.isGlobalListing) {
return adminStopListingToGlobal(listingId, player, true);
}
synchronized (listing) {
if (!listing.status.canCancel()) {
return "This auction cannot be cancelled.";
@@ -616,14 +746,22 @@ public class AuctionController implements IAuctionHandler {
AuctionClaim currencyClaim = AuctionClaim.createCurrencyClaim(
listing.sellerUUID, listing.sellerName, listing.id, sellerReceives,
listing.item.getDisplayName(), playerName);
addClaimToPlayer(listing.sellerUUID, currencyClaim);
if (listing.isGlobalListing) {
addGlobalClaim(currencyClaim);
} else {
addClaimToPlayer(listing.sellerUUID, currencyClaim);
}
// Notifications
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id,
"Your " + listing.item.getDisplayName() + " was bought out for " + saleAmount + " " + ConfigMarket.CurrencyName + "!");
if (!listing.isGlobalListing && listing.sellerUUID != null) {
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id,
"Your " + listing.item.getDisplayName() + " was bought out for " + saleAmount + " " + ConfigMarket.CurrencyName + "!");
}
// Remove from seller's active listings
removeFromPlayerListings(listing.sellerUUID, listing.id);
if (!listing.isGlobalListing && listing.sellerUUID != null) {
removeFromPlayerListings(listing.sellerUUID, listing.id);
}
listing.status = EnumAuctionStatus.ENDED;
listing.highBidderUUID = playerUUID;
@@ -633,7 +771,7 @@ public class AuctionController implements IAuctionHandler {
markDirty();
logAuction(EnumAuctionLogAction.BUYOUT, playerName, listing.item.getDisplayName(), listing.buyoutPrice,
"Seller: " + listing.sellerName + ", Tax: " + tax);
"Seller: " + listing.sellerName + ", Tax: " + tax + (listing.isGlobalListing ? ", Global listing" : ""));
}
return null; // Success
@@ -665,6 +803,77 @@ public class AuctionController implements IAuctionHandler {
return new ArrayList<>();
}
/**
* Paginated global claims used by the global auction admin GUI.
*/
public List<AuctionClaim> getGlobalClaims(int page, int pageSize) {
List<AuctionClaim> snapshot = getGlobalClaimsSnapshot();
snapshot.sort((a, b) -> Long.compare(b.createdTime, a.createdTime));
int safePage = Math.max(0, page);
int safePageSize = Math.max(1, pageSize);
int start = safePage * safePageSize;
if (start >= snapshot.size()) {
return new ArrayList<>();
}
int end = Math.min(start + safePageSize, snapshot.size());
return new ArrayList<>(snapshot.subList(start, end));
}
public int getTotalGlobalClaims() {
return getGlobalClaimsSnapshot().size();
}
public boolean hasGlobalClaims() {
return getTotalGlobalClaims() > 0;
}
public String claimGlobalItem(String claimId, EntityPlayer player) {
AuctionClaim claim = getGlobalClaimInternal(claimId);
if (claim == null) {
return "Global claim not found.";
}
if (!claim.type.isItem()) {
return "This global claim is not an item claim.";
}
if (claim.item == null) {
return "Item data is missing.";
}
if (!player.inventory.addItemStackToInventory(claim.item.copy())) {
return "Your inventory is full.";
}
claimAndRemoveGlobal(claim.id);
cleanupListingIfComplete(claim.listingId);
markDirty();
logAuction(EnumAuctionLogAction.CLAIMED, player.getCommandSenderName(), claim.item.getDisplayName(), 0,
"Global item claim");
return null;
}
/**
* Global currency claims are acknowledged/cleared and do not alter player balances.
*/
public String claimGlobalCurrency(String claimId, EntityPlayer player) {
AuctionClaim claim = getGlobalClaimInternal(claimId);
if (claim == null) {
return "Global claim not found.";
}
if (!claim.type.isCurrency()) {
return "This global claim is not a currency claim.";
}
claimAndRemoveGlobal(claim.id);
cleanupListingIfComplete(claim.listingId);
markDirty();
logAuction(EnumAuctionLogAction.CLAIMED, player.getCommandSenderName(), ConfigMarket.CurrencyName, claim.currency,
"Global currency claim acknowledged (no balance change)");
return null;
}
public String claimItem(String claimId, EntityPlayer player) {
PlayerData playerData = PlayerData.get(player);
if (playerData == null) {
@@ -1119,6 +1328,30 @@ public class AuctionController implements IAuctionHandler {
player.addChatMessage(new ChatComponentText(msg.toString()));
}
// Notify admins with permission about pending global claims.
if (CustomNpcsPermissions.hasCustomPermission(player, "customnpcs.global.auction")) {
List<AuctionClaim> global = getGlobalClaimsSnapshot();
if (!global.isEmpty()) {
int itemClaims = 0;
int currencyClaims = 0;
for (AuctionClaim claim : global) {
if (claim.type.isItem()) {
itemClaims++;
} else {
currencyClaims++;
}
}
StringBuilder msg = new StringBuilder();
msg.append(EnumChatFormatting.GOLD).append("[Auction] ");
msg.append(EnumChatFormatting.AQUA).append("Global claims available: ");
msg.append(EnumChatFormatting.GREEN).append(itemClaims).append(" item claim(s)");
msg.append(EnumChatFormatting.GRAY).append(", ");
msg.append(EnumChatFormatting.YELLOW).append(currencyClaims).append(" currency claim(s)");
player.addChatMessage(new ChatComponentText(msg.toString()));
}
}
}
public void onPlayerLogout(UUID playerUUID) {
@@ -1228,6 +1461,7 @@ public class AuctionController implements IAuctionHandler {
public void load() {
listings.clear();
globalClaims.clear();
playerListingIds.clear();
playerBidIds.clear();
@@ -1270,7 +1504,9 @@ public class AuctionController implements IAuctionHandler {
// Index listings
for (AuctionListing listing : listings.values()) {
if (listing.status == EnumAuctionStatus.ACTIVE) {
addToPlayerListings(listing.sellerUUID, listing.id);
if (!listing.isGlobalListing && listing.sellerUUID != null) {
addToPlayerListings(listing.sellerUUID, listing.id);
}
if (listing.highBidderUUID != null) {
addToPlayerBids(listing.highBidderUUID, listing.id);
}
@@ -1291,22 +1527,42 @@ public class AuctionController implements IAuctionHandler {
}
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
// Listings only - claims are stored in PlayerData
// Listings + global claims (player claims are stored in PlayerData)
NBTTagList listingsList = new NBTTagList();
for (AuctionListing listing : listings.values()) {
listingsList.appendTag(listing.writeToNBT(new NBTTagCompound()));
}
compound.setTag("Listings", listingsList);
NBTTagList globalClaimsList = new NBTTagList();
for (AuctionClaim claim : globalClaims) {
if (claim != null && !claim.claimed) {
globalClaimsList.appendTag(claim.writeToNBT(new NBTTagCompound()));
}
}
compound.setTag("GlobalClaims", globalClaimsList);
return compound;
}
public void readFromNBT(NBTTagCompound compound) {
globalClaims.clear();
NBTTagList listingsList = compound.getTagList("Listings", 10);
for (int i = 0; i < listingsList.tagCount(); i++) {
AuctionListing listing = AuctionListing.fromNBT(listingsList.getCompoundTagAt(i));
listings.put(listing.id, listing);
}
if (compound.hasKey("GlobalClaims")) {
NBTTagList claimsList = compound.getTagList("GlobalClaims", 10);
for (int i = 0; i < claimsList.tagCount(); i++) {
AuctionClaim claim = AuctionClaim.fromNBT(claimsList.getCompoundTagAt(i));
if (!claim.claimed) {
globalClaims.add(claim);
}
}
}
}
// =========================================
@@ -1473,10 +1729,77 @@ public class AuctionController implements IAuctionHandler {
return new ArrayList<>(listings.values());
}
/**
* Admin management flow for listings.
* cancelCompletely=false: stop listing and return assets to the original owners' claim pools.
* cancelCompletely=true: cancel listing and route assets to global claims.
*/
public String adminStopListingToGlobal(String listingId, EntityPlayer admin, boolean cancelCompletely) {
AuctionListing listing = listings.get(listingId);
if (listing == null) {
return "Listing not found.";
}
if (admin == null) {
return "Admin player is missing.";
}
synchronized (listing) {
if (!listing.status.canCancel()) {
return "This auction cannot be managed.";
}
String itemName = listing.item != null ? listing.item.getDisplayName() : "Unknown Item";
// Return active highest bid.
if (listing.hasBids() && listing.highBidderUUID != null) {
AuctionClaim refundClaim;
if (cancelCompletely) {
refundClaim = AuctionClaim.createRefundClaim(
null, "Global", listing.id, listing.currentBid, itemName,
listing.highBidderName, null);
addGlobalClaim(refundClaim);
} else {
refundClaim = AuctionClaim.createRefundClaim(
listing.highBidderUUID, listing.highBidderName, listing.id, listing.currentBid, itemName,
listing.sellerName, null);
addClaimToPlayer(listing.highBidderUUID, refundClaim);
}
removeFromPlayerBids(listing.highBidderUUID, listing.id);
}
// Return the listed item.
if (listing.item != null) {
AuctionClaim itemClaim;
if (cancelCompletely || listing.sellerUUID == null) {
itemClaim = AuctionClaim.createItemReturnedClaim(
null, "Global", listing.id, listing.item);
addGlobalClaim(itemClaim);
} else {
itemClaim = AuctionClaim.createItemReturnedClaim(
listing.sellerUUID, listing.sellerName, listing.id, listing.item);
addClaimToPlayer(listing.sellerUUID, itemClaim);
}
}
if (!listing.isGlobalListing && listing.sellerUUID != null) {
removeFromPlayerListings(listing.sellerUUID, listing.id);
}
listing.status = cancelCompletely ? EnumAuctionStatus.CANCELLED : EnumAuctionStatus.ENDED;
markDirty();
logAuction(EnumAuctionLogAction.CANCELLED, admin.getCommandSenderName(), itemName, listing.currentBid,
(cancelCompletely ? "Admin cancelled to global claims" : "Admin stopped to owner claims") +
", OriginalSeller: " + listing.sellerName);
}
return null;
}
public void adminCancelListing(String listingId, EntityPlayer admin, String reason) {
AuctionListing listing = listings.get(listingId);
String itemName = listing != null && listing.item != null ? listing.item.getDisplayName() : "Unknown";
cancelListing(listingId, admin, true);
adminStopListingToGlobal(listingId, admin, true);
if (reason != null && !reason.isEmpty()) {
logAuction(EnumAuctionLogAction.CANCELLED, admin.getCommandSenderName(), itemName, 0, "Admin cancel - Reason: " + reason);
}
@@ -223,11 +223,14 @@ public class SpawnController implements INaturalSpawnsHandler {
}
public INaturalSpawn[] getSpawns(String biome) {
return getSpawnList(biome).toArray(new INaturalSpawn[]{});
List<SpawnData> biomeSpawns = getSpawnList(biome);
if (biomeSpawns == null)
return new INaturalSpawn[]{};
return biomeSpawns.toArray(new INaturalSpawn[]{});
}
public void addSpawn(INaturalSpawn spawn) {
((SpawnData) spawn).id = 0;
((SpawnData) spawn).id = -1;
this.saveSpawnData((SpawnData) spawn);
}
@@ -24,6 +24,7 @@ public class AuctionListing implements IAuctionListing {
public long createdTime;
public long endTime;
public EnumAuctionStatus status;
public boolean isGlobalListing;
public AuctionListing() {
this.id = UUID.randomUUID().toString();
@@ -31,6 +32,7 @@ public class AuctionListing implements IAuctionListing {
this.bidCount = 0;
this.currentBid = 0;
this.createdTime = System.currentTimeMillis();
this.isGlobalListing = false;
}
public AuctionListing(UUID sellerUUID, String sellerName, ItemStack item, long startingPrice, long buyoutPrice, long durationMs) {
@@ -228,6 +230,7 @@ public class AuctionListing implements IAuctionListing {
compound.setLong("CreatedTime", createdTime);
compound.setLong("EndTime", endTime);
compound.setInteger("Status", status.ordinal());
compound.setBoolean("IsGlobalListing", isGlobalListing);
return compound;
}
@@ -255,6 +258,7 @@ public class AuctionListing implements IAuctionListing {
createdTime = compound.getLong("CreatedTime");
endTime = compound.getLong("EndTime");
status = EnumAuctionStatus.fromOrdinal(compound.getInteger("Status"));
isGlobalListing = compound.getBoolean("IsGlobalListing");
}
public static AuctionListing fromNBT(NBTTagCompound compound) {
@@ -21,6 +21,10 @@ import java.util.Map;
import java.util.Set;
public class SpawnData extends WeightedRandom.Item implements INaturalSpawn {
public static final int DESPAWN_FORCE_NATURAL = INaturalSpawn.DESPAWN_FORCE_NATURAL;
public static final int DESPAWN_PRESERVE_TEMPLATE = INaturalSpawn.DESPAWN_PRESERVE_TEMPLATE;
public static final int DESPAWN_FORCE_PERSISTENT = INaturalSpawn.DESPAWN_FORCE_PERSISTENT;
public List<String> biomes = new ArrayList<>();
public HashSet<Integer> dimensions = new HashSet<>();
public int id = -1;
@@ -35,6 +39,11 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn {
public int spawnHeightMin;
public int spawnHeightMax = 100;
public int maxAlive = 0;
public int cooldownTicks = 0;
public int attemptsPerCycle = 1;
public int playerMinDistance = 24;
public int despawnMode = DESPAWN_FORCE_NATURAL;
public SpawnData() {
super(10);
@@ -74,6 +83,19 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn {
} else {
spawnHeightMax = compound.getInteger("HeightMax");
}
maxAlive = compound.hasKey("MaxAlive") ? Math.max(0, compound.getInteger("MaxAlive")) : 0;
cooldownTicks = compound.hasKey("CooldownTicks") ? Math.max(0, compound.getInteger("CooldownTicks")) : 0;
attemptsPerCycle = compound.hasKey("AttemptsPerCycle") ? Math.max(1, compound.getInteger("AttemptsPerCycle")) : 1;
playerMinDistance = compound.hasKey("PlayerMinDistance") ? Math.max(0, compound.getInteger("PlayerMinDistance")) : 24;
if (compound.hasKey("DespawnMode")) {
despawnMode = compound.getInteger("DespawnMode");
} else {
despawnMode = DESPAWN_FORCE_NATURAL;
}
if (despawnMode < DESPAWN_FORCE_NATURAL || despawnMode > DESPAWN_FORCE_PERSISTENT) {
despawnMode = DESPAWN_FORCE_NATURAL;
}
}
public NBTTagCompound writeNBT(NBTTagCompound compound) {
@@ -98,6 +120,11 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn {
compound.setInteger("HeightMin", spawnHeightMin);
compound.setInteger("HeightMax", spawnHeightMax);
compound.setInteger("MaxAlive", maxAlive);
compound.setInteger("CooldownTicks", cooldownTicks);
compound.setInteger("AttemptsPerCycle", attemptsPerCycle);
compound.setInteger("PlayerMinDistance", playerMinDistance);
compound.setInteger("DespawnMode", despawnMode);
return compound;
}
@@ -204,4 +231,46 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn {
public void setBiomes(String[] biomes) {
this.biomes = new ArrayList<>(Arrays.asList(biomes));
}
public void setMaxAlive(int maxAlive) {
this.maxAlive = Math.max(0, maxAlive);
}
public int getMaxAlive() {
return this.maxAlive;
}
public void setCooldownTicks(int ticks) {
this.cooldownTicks = Math.max(0, ticks);
}
public int getCooldownTicks() {
return this.cooldownTicks;
}
public void setAttemptsPerCycle(int attempts) {
this.attemptsPerCycle = Math.max(1, attempts);
}
public int getAttemptsPerCycle() {
return this.attemptsPerCycle;
}
public void setPlayerMinDistance(int distance) {
this.playerMinDistance = Math.max(0, distance);
}
public int getPlayerMinDistance() {
return this.playerMinDistance;
}
public void setDespawnMode(int mode) {
if (mode < DESPAWN_FORCE_NATURAL || mode > DESPAWN_FORCE_PERSISTENT)
mode = DESPAWN_FORCE_NATURAL;
this.despawnMode = mode;
}
public int getDespawnMode() {
return this.despawnMode;
}
}
@@ -76,13 +76,13 @@ public abstract class EntityNPCFlying extends EntityNPCInterface {
this.flyLimitAllow = true;
setNpcFlyingState(true);
double d3 = this.motionY;
super.moveEntityWithHeading(p_70612_1_, p_70612_2_);
this.motionY = d3;
double desiredMotionY = this.motionY;
if (this.getNavigator().noPath()) {
this.motionY = -Math.abs(this.ais.flyGravity);
desiredMotionY = -Math.abs(this.ais.flyGravity);
}
this.motionY = desiredMotionY;
super.moveEntityWithHeading(p_70612_1_, p_70612_2_);
this.motionY = desiredMotionY;
this.updateLimbSwing();
}
@@ -91,11 +91,13 @@ public abstract class EntityNPCFlying extends EntityNPCInterface {
this.prevLimbSwingAmount = this.limbSwingAmount;
double distanceX = this.posX - this.prevPosX;
double distanceZ = this.posZ - this.prevPosZ;
float distance = MathHelper.sqrt_double(distanceX * distanceX + distanceZ * distanceZ) * 4.0F;
float distance = MathHelper.sqrt_double(distanceX * distanceX + distanceZ * distanceZ);
float swingScale = this.getNavigator().noPath() ? 0.35F : 0.9F;
distance *= swingScale;
if (distance > 1.0F) {
distance = 1.0F;
}
this.limbSwingAmount += (distance - this.limbSwingAmount) * 0.4F;
this.limbSwingAmount += (distance - this.limbSwingAmount) * 0.18F;
this.limbSwing += this.limbSwingAmount;
}
@@ -140,13 +142,13 @@ public abstract class EntityNPCFlying extends EntityNPCInterface {
return;
}
double d3 = this.motionY;
super.performMountedMovement(strafe, forward, moveSpeed);
this.motionY = d3;
double desiredMotionY = this.motionY;
if (this.getNavigator().noPath()) {
this.motionY = -Math.abs(this.ais.flyGravity);
desiredMotionY = -Math.abs(this.ais.flyGravity);
}
this.motionY = desiredMotionY;
super.performMountedMovement(strafe, forward, moveSpeed);
this.motionY = desiredMotionY;
this.updateLimbSwing();
}
@@ -11,6 +11,7 @@ import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumSoundOperation;
import kamkeel.npcs.network.packets.data.ChatBubblePacket;
import kamkeel.npcs.network.packets.data.QuestCompletionPacket;
import kamkeel.npcs.network.packets.data.RequestProperSpawnData;
import kamkeel.npcs.network.packets.data.SoundManagementPacket;
import kamkeel.npcs.network.packets.data.npc.UpdateNpcPacket;
import kamkeel.npcs.network.packets.data.npc.WeaponNpcPacket;
@@ -230,8 +231,8 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
public FlyingMoveHelper flyMoveHelper = new FlyingMoveHelper(this);
public PathNavigate flyNavigator = new PathNavigateFlying(this, worldObj);
// @SideOnly(Side.CLIENT)
// public int immediateSpawnDataFixAttempts = 0;
// For Client-Side Use Only
public int clientFixAttempts = 0;
public EntityNPCInterface(World world) {
super(world);
@@ -254,7 +255,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
setFaction(faction.id);
setSize(1, 1);
this.updateTasks();
this.func_110163_bv();
this.syncDespawnPersistence();
if (!this.isRemote() && this.wrappedNPC == null) {
this.wrappedNPC = new ScriptNpc<>(this);
@@ -1202,7 +1203,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(ConfigMain.NpcNavRange);
this.updateTasks();
this.func_110163_bv();
this.syncDespawnPersistence();
}
@Override
@@ -1403,6 +1404,26 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
field_20062_v += d1 * 0.25D;
}
@Override
protected void despawnEntity() {
syncDespawnPersistence();
super.despawnEntity();
}
public void syncDespawnPersistence() {
if (stats == null) {
if (!this.persistenceRequired) {
this.func_110163_bv();
}
return;
}
if (stats.canDespawn) {
this.persistenceRequired = false;
} else if (!this.persistenceRequired) {
this.func_110163_bv();
}
}
@Override
protected boolean canDespawn() {
return stats.canDespawn;
@@ -1805,6 +1826,11 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
compound.setBoolean("DeadBody", stats.hideKilledBody);
compound.setInteger("StandingState", ais.standingType.ordinal());
compound.setInteger("MovingState", ais.movingType.ordinal());
compound.setInteger("MovingType", ais.movementType);
compound.setDouble("FlySpeed", ais.flySpeed);
compound.setDouble("FlyGravity", ais.flyGravity);
compound.setBoolean("HasFlyLimit", ais.hasFlyLimit);
compound.setInteger("FlyHeightLimit", ais.flyHeightLimit);
compound.setInteger("Orientation", ais.orientation);
compound.setFloat("OffsetY", ais.bodyOffsetY);
compound.setInteger("Role", advanced.role.ordinal());
@@ -1836,25 +1862,38 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
try {
readSpawnData(ByteBufUtils.readNBT(buf));
} catch (IOException e) {
// if (this.worldObj != null && this.worldObj.isRemote) {
// RequestProperSpawnData.reportMissingData(this);
// }
if (this.worldObj != null && this.worldObj.isRemote) {
RequestProperSpawnData.reportMissingData(this);
}
}
}
public void readSpawnData(NBTTagCompound compound) {
// if (this.worldObj != null && this.worldObj.isRemote &&
// (compound.hasNoTags() || !compound.hasKey("MaxHealth", Constants.NBT.TAG_DOUBLE))) {
// RequestProperSpawnData.reportMissingData(this);
// return;
// }
//
// immediateSpawnDataFixAttempts = 0;
if (this.worldObj != null && this.worldObj.isRemote) {
if(requestClientFix(compound))
return;
}
stats.maxHealth = compound.getDouble("MaxHealth");
ais.setWalkingSpeed(compound.getInteger("Speed"));
stats.hideKilledBody = compound.getBoolean("DeadBody");
ais.standingType = EnumStandingType.values()[compound.getInteger("StandingState") % EnumStandingType.values().length];
ais.movingType = EnumMovingType.values()[compound.getInteger("MovingState") % EnumMovingType.values().length];
if (compound.hasKey("MovingType", Constants.NBT.TAG_INT)) {
ais.movementType = compound.getInteger("MovingType");
}
if (compound.hasKey("FlySpeed", Constants.NBT.TAG_DOUBLE)) {
ais.flySpeed = compound.getDouble("FlySpeed");
}
if (compound.hasKey("FlyGravity", Constants.NBT.TAG_DOUBLE)) {
ais.flyGravity = compound.getDouble("FlyGravity");
}
if (compound.hasKey("HasFlyLimit", Constants.NBT.TAG_BYTE)) {
ais.hasFlyLimit = compound.getBoolean("HasFlyLimit");
}
if (compound.hasKey("FlyHeightLimit", Constants.NBT.TAG_INT)) {
ais.flyHeightLimit = compound.getInteger("FlyHeightLimit");
}
ais.orientation = compound.getInteger("Orientation");
ais.bodyOffsetY = compound.getFloat("OffsetY");
@@ -1927,6 +1966,15 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
}
}
public boolean requestClientFix(NBTTagCompound compound){
if((compound.hasNoTags() || !compound.hasKey("MaxHealth", Constants.NBT.TAG_DOUBLE))){
RequestProperSpawnData.reportMissingData(this);
return true;
}
clientFixAttempts = 0;
return false;
}
public boolean canBreatheUnderwater() {
return stats.drowningType != 1;
}
@@ -5,6 +5,7 @@ import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.gui.global.GuiNpcManageAuction;
import noppes.npcs.client.gui.player.GuiAuctionInterface;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@@ -31,7 +32,7 @@ public abstract class MixinItemStack {
@Inject(method = "getTooltip", at = @At("TAIL"), cancellable = true)
public void getAttributeTooltip(EntityPlayer player, boolean advanced, CallbackInfoReturnable<List<String>> cir) {
boolean override = false;
if (Minecraft.getMinecraft().currentScreen instanceof GuiAuctionInterface) {
if (Minecraft.getMinecraft().currentScreen instanceof GuiAuctionInterface || Minecraft.getMinecraft().currentScreen instanceof GuiNpcManageAuction) {
override = true;
}
@@ -86,6 +86,9 @@ public abstract class MixinModelRenderer {
float prevAngleX = this.rotateAngleX;
float prevAngleY = this.rotateAngleY;
float prevAngleZ = this.rotateAngleZ;
float prevOffsetX = this.offsetX;
float prevOffsetY = this.offsetY;
float prevOffsetZ = this.offsetZ;
boolean changedAngles = false;
try {
@@ -149,6 +152,11 @@ public abstract class MixinModelRenderer {
GL11.glPopMatrix();
}
// Mirror vanilla ModelRenderer behavior: always undo offset translation.
// Without this, models that animate via offsetX/Y/Z (e.g. witch nose while drinking)
// leak transforms into subsequent renders.
GL11.glTranslatef(-this.offsetX, -this.offsetY, -this.offsetZ);
if (changedAngles) {
this.rotationPointX = prevPointX;
this.rotationPointY = prevPointY;
@@ -156,6 +164,9 @@ public abstract class MixinModelRenderer {
this.rotateAngleX = prevAngleX;
this.rotateAngleY = prevAngleY;
this.rotateAngleZ = prevAngleZ;
this.offsetX = prevOffsetX;
this.offsetY = prevOffsetY;
this.offsetZ = prevOffsetZ;
}
}
}
@@ -121,6 +121,22 @@ public class ScriptEnergyBarrier<T extends EntityAbilityBarrier> extends ScriptE
entity.getBarrierData().absorbing = absorbing;
}
public boolean isReflect() {
return entity.getBarrierData().reflect;
}
public void setReflect(boolean reflect) {
entity.getBarrierData().reflect = reflect;
}
public float getReflectStrengthPct() {
return entity.getBarrierData().reflectStrengthPct;
}
public void setReflectStrengthPct(float strengthPct) {
entity.getBarrierData().setReflectStrengthPct(strengthPct);
}
public int getBarrierType() {
return entity instanceof EntityAbilityDome ? 0 : 1;
}
@@ -177,6 +177,14 @@ public class ScriptEnergyProjectile<T extends EntityEnergyProjectile> extends Sc
entity.setMultiHitDelayTicks(delayTicks);
}
public int getMaxHits() {
return entity.getMaxHits();
}
public void setMaxHits(int maxHits) {
entity.setMaxHits(maxHits);
}
// ==================== MOVEMENT ====================
public float getSpeed() {
@@ -1109,6 +1109,7 @@ public class ScriptNpc<T extends EntityNPCInterface> extends ScriptLiving<T> imp
public void setNaturallyDespawns(boolean canDespawn) {
npc.stats.canDespawn = canDespawn;
npc.stats.playerSetCanDespawn = canDespawn;
npc.syncDespawnPersistence();
}
public boolean spawnedFromSoulStone() {
@@ -0,0 +1,24 @@
package noppes.npcs.util;
import net.minecraft.util.Vec3;
public class MathUtil {
public static float getYaw(Vec3 vector) {
double x = vector.xCoord;
double z = vector.zCoord;
double yawRad = Math.atan2(z, x);
return 90F - (float) Math.toDegrees(yawRad);
}
public static float getPitch(Vec3 vector) {
double x = vector.xCoord;
double y = vector.yCoord;
double z = vector.zCoord;
double horizontalMag = Math.sqrt(x * x + z * z);
double pitchRad = Math.atan2(y, horizontalMag);
return (float) -Math.toDegrees(pitchRad);
}
}