Merge branch 'KAMKEEL:dev' into dev

This commit is contained in:
Kirill Epifanov authored and GitHub committed 2026-02-09 22:55:44 +03:00
commit 9b52c8088e
224 files changed
+17351 -8292

No files matched your search

@@ -43,6 +43,7 @@ import noppes.npcs.containers.ContainerNpcQuestReward;
import noppes.npcs.containers.ContainerNpcQuestTypeItem;
import noppes.npcs.controllers.data.AnimationData;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.entity.EntityNPCInterface;
public class CommonProxy implements IGuiHandler {
@@ -220,4 +221,24 @@ public class CommonProxy implements IGuiHandler {
public void buildPackageIndex() {
}
public boolean isScriptingEnabled() {
return ConfigScript.ScriptingEnabled;
}
public boolean isRunLoadedScriptsFirst() {
return ConfigScript.RunLoadedScriptsFirst;
}
public boolean isGlobalPlayerScripts() {
return ConfigScript.GlobalPlayerScripts;
}
public boolean isGlobalForgeScripts() {
return ConfigScript.GlobalForgeScripts;
}
public boolean isGlobalNPCScripts() {
return ConfigScript.GlobalNPCScripts;
}
}
+7 -1
View File
@@ -158,7 +158,13 @@ public class CustomNpcs {
@SideOnly(Side.CLIENT)
private static IDynamicCompiler clientJaninoCompiler;
@SideOnly(Side.CLIENT)
private final static Set<Consumer<AdvancedClassFilter>> clientClassFilterConsumer = new HashSet<>();
private static Set<Consumer<AdvancedClassFilter>> clientClassFilterConsumer;
static {
if (FMLCommonHandler.instance().getEffectiveSide().isClient()) {
clientClassFilterConsumer = new HashSet<>();
}
}
@SideOnly(Side.CLIENT)
public static void addClassesToClientClassFilter(Consumer<AdvancedClassFilter> consumer) {
@@ -66,8 +66,8 @@ public class CustomNpcsPermissions {
public static final Permission GLOBAL_NATURALSPAWN = new Permission("customnpcs.global.naturalspawn");
public static final Permission GLOBAL_TAG = new Permission("customnpcs.global.tag");
public static final Permission GLOBAL_ANIMATION = new Permission("customnpcs.global.animation");
public static final Permission GLOBAL_ABILITY = new Permission("customnpcs.global.ability");
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 SPAWNER_MOB = new Permission("customnpcs.spawner.mob");
@@ -111,9 +111,6 @@ public class CustomNpcsPermissions {
public static final Permission PROFILE_REGION_BYPASS = new Permission("customnpcs.profile.region-bypass");
public static final Permission PROFILE_MAX = new Permission("customnpcs.profile.max.*");
// Auction
public static final Permission AUCTION_TRADES_MAX = new Permission("customnpcs.auction.trades.*");
public static CustomNpcsPermissions Instance;
private Method hasPermission;
+348 -53
View File
@@ -18,6 +18,7 @@ import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.event.AbilityEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@@ -43,7 +44,7 @@ public class DataAbilities {
/**
* Whether the ability system is enabled for this NPC
*/
public boolean enabled = false;
public boolean enabled = true;
/**
* Minimum cooldown ticks between abilities (global minimum)
@@ -89,6 +90,24 @@ public class DataAbilities {
private transient float lockedRenderYawOffset = 0;
private transient float lockedPitch = 0;
/**
* Locked position values for movement lock.
* Stored when entering a locked phase, applied after super.onLivingUpdate()
* to override any position changes from AI/physics.
*/
private transient boolean positionLocked = false;
private transient double lockedPosX = 0;
private transient double lockedPosY = 0;
private transient double lockedPosZ = 0;
/**
* Hit scan state - forces NPC to face target.
* Set during tickCurrentAbility(), applied after super.onLivingUpdate()
* to override AI look helper rotation.
*/
private transient boolean hitScanActive = false;
private transient EntityLivingBase hitScanTarget = null;
// ═══════════════════════════════════════════════════════════════════
// CONSTRUCTOR
// ═══════════════════════════════════════════════════════════════════
@@ -106,10 +125,33 @@ public class DataAbilities {
* Should be called every tick from onLivingUpdate().
*/
public void tick() {
if (!enabled || npc.worldObj.isRemote || npc.isKilled()) {
if (npc.worldObj.isRemote) {
return;
}
// Force-stop any running ability when NPC is killed or abilities are disabled
if (!enabled || npc.isKilled()) {
if (currentAbility != null) {
removeTelegraph(currentAbility);
stopAbilityAnimation();
releaseRotationControl();
releaseLockedPosition();
currentAbility = null;
lastTarget = null;
} else {
// No ability but locks could be orphaned
if (rotationLocked || hitScanActive) releaseRotationControl();
if (positionLocked) releaseLockedPosition();
}
return;
}
// Safety: release orphaned locks if no ability is actively executing
if (currentAbility == null || !currentAbility.isExecuting()) {
if (rotationLocked || hitScanActive) releaseRotationControl();
if (positionLocked) releaseLockedPosition();
}
// Tick current ability if executing
if (currentAbility != null && currentAbility.isExecuting()) {
tickCurrentAbility();
@@ -132,11 +174,23 @@ public class DataAbilities {
// Handle phase-specific logic
switch (currentAbility.getPhase()) {
case WINDUP:
if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) {
// Burst replay: re-enter windup - set up telegraph, sound, animation, locks
if (currentAbility.isRotationLockedDuringWindup()) {
captureLockedRotation();
}
if (currentAbility.isMovementLockedDuringWindup() && !currentAbility.hasAbilityMovement()) {
captureLockedPosition();
}
spawnTelegraph(currentAbility, target);
playAbilitySound(currentAbility.getWindUpSound());
playAbilityAnimation(currentAbility.getWindUpAnimation());
}
currentAbility.onWindUpTick(npc, target, npc.worldObj, currentAbility.getCurrentTick());
break;
case ACTIVE:
if (phaseChanged && oldPhase == AbilityPhase.WINDUP) {
if (phaseChanged && (oldPhase == AbilityPhase.WINDUP || oldPhase == AbilityPhase.BURST_DELAY)) {
// Just entered ACTIVE phase - lock telegraph position if it was following
// This commits the ability to its current target position
TelegraphInstance telegraph = currentAbility.getTelegraphInstance();
@@ -147,16 +201,38 @@ public class DataAbilities {
// Remove telegraph - it has served its purpose
removeTelegraph(currentAbility);
// Lock rotation if movement is locked during ACTIVE phase
// Capture current rotation values to force them every tick
if (currentAbility.isMovementLockedDuringActive()) {
captureLockedRotation();
// Handle rotation control transition from WINDUP to ACTIVE
if (currentAbility.isRotationLockedDuringActive()) {
if (!rotationLocked) {
captureLockedRotation();
}
} else if (rotationLocked) {
releaseRotationControl();
}
// Handle position lock transition from WINDUP to ACTIVE
if (currentAbility.isMovementLockedDuringActive() && !currentAbility.hasAbilityMovement()) {
if (!positionLocked) {
captureLockedPosition();
}
} else if (positionLocked) {
releaseLockedPosition();
}
// Burst re-fire without replay: let entity-spawning abilities spawn+fire in one step
if (oldPhase == AbilityPhase.BURST_DELAY && !currentAbility.isBurstReplayAnimations()) {
currentAbility.onBurstRefire(npc, target, npc.worldObj);
}
// Play active sound and animation
playAbilitySound(currentAbility.getActiveSound());
playAbilityAnimation(currentAbility.getActiveAnimation());
// Snap NPC to face target before execute so startMoving() reads correct rotation
if (currentAbility.isHitScanForCurrentPhase() && target != null) {
faceTarget(target);
}
// Fire execute event (cancelable)
AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent(
npc.wrappedNPC, currentAbility, target);
@@ -181,6 +257,31 @@ public class DataAbilities {
handleAbilityCompletion(target);
return;
}
// Auto-complete for burst overlap mode (entities fly independently)
// This allows entity-spawning abilities to immediately chain next burst
// without each type needing to check burst state in their onActiveTick()
// Wait until all staggered projectiles have been fired before auto-completing
if (currentAbility.isBurstEnabled() && currentAbility.isBurstOverlap()
&& currentAbility.getBurstIndex() < currentAbility.getBurstAmount()
&& currentAbility.getPhase() == AbilityPhase.ACTIVE
&& currentAbility.isReadyForBurstCompletion(currentAbility.getCurrentTick())) {
currentAbility.signalCompletion();
}
// Check if ability entered burst delay during onActiveTick or overlap auto-complete
if (currentAbility.getPhase() == AbilityPhase.BURST_DELAY) {
// Release all locks - free movement/rotation during delay
if (rotationLocked) releaseRotationControl();
if (positionLocked) releaseLockedPosition();
if (hitScanActive) releaseRotationControl();
}
break;
case BURST_DELAY:
// Free movement and rotation during burst delay
if (rotationLocked) releaseRotationControl();
if (positionLocked) releaseLockedPosition();
break;
case DAZED:
@@ -193,6 +294,15 @@ public class DataAbilities {
break;
}
// Update hit scan state - actual facing is deferred to applyRotationControl()
// which runs AFTER super.onLivingUpdate() to override AI look helper
if (currentAbility != null && currentAbility.isExecuting()
&& currentAbility.isHitScanForCurrentPhase() && target != null) {
enableHitScan(target);
} else if (hitScanActive) {
releaseRotationControl();
}
// Apply movement control if ability is still executing
if (currentAbility != null && currentAbility.isExecuting()) {
applyMovementControl();
@@ -237,8 +347,9 @@ public class DataAbilities {
npc.wrappedNPC, currentAbility, target);
NpcAPI.EVENT_BUS.post(completeEvent);
// Release rotation lock before cleanup
releaseLockedRotation();
// Release locks before cleanup
releaseRotationControl();
releaseLockedPosition();
// Clean up and roll cooldown (this sets currentAbility to null)
onAbilityComplete();
@@ -253,8 +364,9 @@ public class DataAbilities {
// Stop any ability animation
stopAbilityAnimation();
// Release rotation lock
releaseLockedRotation();
// Release locks
releaseRotationControl();
releaseLockedPosition();
// Calculate cooldown: random(min, max) + ability offset
int abilityCooldownOffset = currentAbility.getCooldownTicks();
@@ -343,6 +455,11 @@ public class DataAbilities {
* Check if a specific ability is eligible for use.
*/
private boolean isAbilityEligible(Ability ability, EntityLivingBase target) {
// Check UserType allows NPCs
if (!ability.getAllowedBy().allowsNpc()) {
return false;
}
// Check enabled
if (!ability.isEnabled()) {
return false;
@@ -385,18 +502,58 @@ public class DataAbilities {
lastTarget = target;
ability.start(target);
// Spawn telegraph and send to clients
spawnTelegraph(ability, target);
// Play wind up sound if configured
playAbilitySound(ability.getWindUpSound());
// Play wind up animation if configured
playAbilityAnimation(ability.getWindUpAnimation());
if (ability.getPhase() == AbilityPhase.ACTIVE) {
// Windup was 0 — skip telegraph/windup and go straight to active
executeImmediate(ability, target);
} else {
// Normal windup flow
if (ability.isRotationLockedDuringWindup()) {
captureLockedRotation();
}
if (ability.isMovementLockedDuringWindup() && !ability.hasAbilityMovement()) {
captureLockedPosition();
}
spawnTelegraph(ability, target);
playAbilitySound(ability.getWindUpSound());
playAbilityAnimation(ability.getWindUpAnimation());
}
return true;
}
/**
* Execute an ability immediately (no windup).
* Called when windUpTicks is 0.
*/
private void executeImmediate(Ability ability, EntityLivingBase target) {
// Lock rotation if rotation is locked during ACTIVE phase
if (ability.isRotationLockedDuringActive()) {
captureLockedRotation();
}
if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) {
captureLockedPosition();
}
// Play active sound and animation
playAbilitySound(ability.getActiveSound());
playAbilityAnimation(ability.getActiveAnimation());
// Fire execute event (cancelable)
AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent(
npc.wrappedNPC, ability, target);
if (NpcAPI.EVENT_BUS.post(executeEvent)) {
return;
}
// Call onExecute
ability.onExecute(npc, target, npc.worldObj);
// Check if ability completed during onExecute
if (ability.getPhase() == AbilityPhase.IDLE) {
handleAbilityCompletion(target);
}
}
/**
* Play a sound at the NPC's location.
*/
@@ -429,6 +586,14 @@ public class DataAbilities {
playAbilityAnimation((Animation) AnimationController.Instance.get(animation));
}
public void playAbilityAnimation(String animation) {
if (animation.isEmpty()) return;
if (AnimationController.Instance == null) return;
if (AnimationController.Instance.get(animation, true) == null) return;
playAbilityAnimation((Animation) AnimationController.Instance.get(animation, true));
}
/**
* Stop any currently playing ability animation.
*/
@@ -501,18 +666,12 @@ public class DataAbilities {
// Track hit for hit count condition
recordHit();
// Check if currently executing a Guard ability and notify it of damage taken
if (currentAbility instanceof AbilityGuard) {
AbilityGuard guard = (AbilityGuard) currentAbility;
if (guard.isGuarding() && source.getEntity() instanceof EntityLivingBase) {
guard.onDamageTaken(npc, (EntityLivingBase) source.getEntity(), source, amount);
}
}
if (currentAbility == null || !currentAbility.isExecuting()) {
return false;
}
currentAbility.onDamageTaken(npc, (EntityLivingBase) source.getEntity(), source, amount);
if (currentAbility.canInterrupt(source)) {
interruptCurrentAbility(source, amount);
return true;
@@ -583,8 +742,9 @@ public class DataAbilities {
// Stop any ability animation
stopAbilityAnimation();
// Release rotation lock
releaseLockedRotation();
// Release locks
releaseRotationControl();
releaseLockedPosition();
// Fire interrupt event
AbilityEvent.InterruptEvent interruptEvent = new AbilityEvent.InterruptEvent(
@@ -606,7 +766,8 @@ public class DataAbilities {
if (currentAbility != null) {
removeTelegraph(currentAbility);
stopAbilityAnimation();
releaseLockedRotation();
releaseRotationControl();
releaseLockedPosition();
currentAbility.interrupt();
currentAbility = null;
lastTarget = null;
@@ -626,6 +787,11 @@ public class DataAbilities {
return false;
}
// Check UserType allows NPCs
if (!ability.getAllowedBy().allowsNpc()) {
return false;
}
// Stop any currently executing ability
stopCurrentAbility();
@@ -898,12 +1064,15 @@ public class DataAbilities {
}
// ═══════════════════════════════════════════════════════════════════
// ROTATION LOCKING
// ROTATION CONTROL
// ═══════════════════════════════════════════════════════════════════
/** Bit flag for rotation control (LOCKED or TRACK) in data watcher slot 15 */
private static final int ROTATION_CONTROLLED_FLAG = 16;
/**
* Capture current rotation values to lock NPC's look direction.
* Called when entering ACTIVE phase with movement locked during active.
* Called when entering a LOCKED rotation phase.
*/
private void captureLockedRotation() {
lockedYaw = npc.rotationYaw;
@@ -911,44 +1080,170 @@ public class DataAbilities {
lockedRenderYawOffset = npc.renderYawOffset;
lockedPitch = npc.rotationPitch;
rotationLocked = true;
npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG);
}
/**
* Release the rotation lock.
* Called when leaving ACTIVE phase or ability completes.
* Release rotation control (both locked and hit scan).
*/
private void releaseLockedRotation() {
private void releaseRotationControl() {
rotationLocked = false;
hitScanActive = false;
hitScanTarget = null;
npc.setBoolFlag(false, ROTATION_CONTROLLED_FLAG);
}
/**
* Apply locked rotation values to the NPC.
* Called AFTER super.onLivingUpdate() in EntityNPCInterface to override
* any rotation changes made by the look helper or AI tasks.
* Enable hit scan tracking for the given target.
*/
public void applyLockedRotation() {
if (!rotationLocked) {
private void enableHitScan(EntityLivingBase target) {
if (!hitScanActive) {
hitScanActive = true;
npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG);
}
hitScanTarget = target;
}
/**
* Snap the NPC to face the target instantly.
*/
private void faceTarget(EntityLivingBase target) {
double dx = target.posX - npc.posX;
double dz = target.posZ - npc.posZ;
double dy = (target.posY + target.getEyeHeight() * 0.5) - (npc.posY + npc.getEyeHeight());
double distXZ = Math.sqrt(dx * dx + dz * dz);
float yaw = (float) (Math.atan2(-dx, dz) * 180.0 / Math.PI);
float pitch = (float) (-(Math.atan2(dy, distXZ)) * 180.0 / Math.PI);
npc.rotationYaw = yaw;
npc.rotationYawHead = yaw;
npc.renderYawOffset = yaw;
npc.rotationPitch = pitch;
npc.prevRotationYaw = yaw;
npc.prevRotationYawHead = yaw;
npc.prevRenderYawOffset = yaw;
npc.prevRotationPitch = pitch;
}
/**
* Apply rotation control after super.onLivingUpdate() and super.onUpdate().
* Handles both LOCKED (freeze at captured values) and TRACK (face target) modes.
*
* Server: computes the correct rotation (locked values or target facing).
* Client: trusts the server-synced rotation values and prevents body smoothing override.
*/
public void applyRotationControl() {
if (npc.worldObj.isRemote) {
// Client: check single flag for any rotation control
if (!npc.getBoolFlag(ROTATION_CONTROLLED_FLAG)) {
rotationLocked = false;
return;
}
// Trust server rotation, prevent body smoothing from overriding
npc.prevRotationYaw = npc.rotationYaw;
npc.prevRotationYawHead = npc.rotationYawHead;
npc.renderYawOffset = npc.rotationYawHead;
npc.prevRenderYawOffset = npc.rotationYawHead;
npc.prevRotationPitch = npc.rotationPitch;
return;
}
// Force rotation back to locked values
npc.rotationYaw = lockedYaw;
npc.rotationYawHead = lockedYawHead;
npc.renderYawOffset = lockedRenderYawOffset;
npc.rotationPitch = lockedPitch;
// Also set prev values to prevent interpolation jitter
npc.prevRotationYaw = lockedYaw;
npc.prevRotationYawHead = lockedYawHead;
npc.prevRenderYawOffset = lockedRenderYawOffset;
npc.prevRotationPitch = lockedPitch;
// Server: apply the appropriate rotation
if (hitScanActive && hitScanTarget != null && !hitScanTarget.isDead) {
faceTarget(hitScanTarget);
} else if (rotationLocked) {
npc.rotationYaw = lockedYaw;
npc.rotationYawHead = lockedYawHead;
npc.renderYawOffset = lockedRenderYawOffset;
npc.rotationPitch = lockedPitch;
npc.prevRotationYaw = lockedYaw;
npc.prevRotationYawHead = lockedYawHead;
npc.prevRenderYawOffset = lockedRenderYawOffset;
npc.prevRotationPitch = lockedPitch;
}
}
/**
* Check if rotation is currently locked.
* Check if rotation is currently controlled (locked or tracking target).
* Used by AI tasks to determine if they should try to change NPC look direction.
*/
public boolean isRotationLocked() {
return rotationLocked;
return rotationLocked || hitScanActive;
}
// ═══════════════════════════════════════════════════════════════════
// POSITION LOCKING
// ═══════════════════════════════════════════════════════════════════
/** Bit flag for position lock in data watcher slot 15 */
private static final int POSITION_LOCKED_FLAG = 32;
/**
* Capture current position to lock NPC in place.
* Called when entering a phase with movement lock.
*/
private void captureLockedPosition() {
lockedPosX = npc.posX;
lockedPosY = npc.posY;
lockedPosZ = npc.posZ;
positionLocked = true;
npc.setBoolFlag(true, POSITION_LOCKED_FLAG);
}
/**
* Release the position lock.
* Called when leaving the locked phase or ability completes.
*/
private void releaseLockedPosition() {
positionLocked = false;
npc.setBoolFlag(false, POSITION_LOCKED_FLAG);
}
/**
* Apply locked position values to the NPC.
* Called AFTER super.onLivingUpdate() in EntityNPCInterface to override
* any position changes from AI pathfinding, physics, or entity collisions.
* Runs on both client and server.
*/
public void applyLockedPosition() {
if (npc.worldObj.isRemote) {
// Client-side: check flag via data watcher
boolean flagActive = npc.getBoolFlag(POSITION_LOCKED_FLAG);
if (!flagActive) {
positionLocked = false;
return;
}
// First tick the flag is active: capture current position
if (!positionLocked) {
lockedPosX = npc.posX;
lockedPosY = npc.posY;
lockedPosZ = npc.posZ;
positionLocked = true;
}
// Snap position back and set prev to prevent interpolation jitter
npc.setPosition(lockedPosX, lockedPosY, lockedPosZ);
npc.prevPosX = lockedPosX;
npc.prevPosY = lockedPosY;
npc.prevPosZ = lockedPosZ;
npc.motionX = 0;
npc.motionY = 0;
npc.motionZ = 0;
return;
}
// Server-side: use stored locked values
if (!positionLocked) {
return;
}
npc.setPosition(lockedPosX, lockedPosY, lockedPosZ);
npc.prevPosX = lockedPosX;
npc.prevPosY = lockedPosY;
npc.prevPosZ = lockedPosZ;
npc.motionX = 0;
npc.motionY = 0;
npc.motionZ = 0;
}
// ═══════════════════════════════════════════════════════════════════
@@ -2,6 +2,8 @@ package noppes.npcs;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.packets.data.ParticlePacket;
import kamkeel.npcs.network.packets.data.PlayerDataInfoPacket;
@@ -748,7 +750,7 @@ public class NoppesUtilServer {
public static void sendAbilityTypesInfo(EntityPlayerMP player) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
kamkeel.npcs.controllers.data.ability.AbilityController controller = kamkeel.npcs.controllers.data.ability.AbilityController.Instance;
AbilityController controller = AbilityController.Instance;
if (controller != null) {
int index = 0;
for (String typeId : controller.getTypes()) {
@@ -764,6 +766,9 @@ public class NoppesUtilServer {
if (controller != null) {
int index = 0;
for (String uuid : controller.getCustomAbilityIds()) {
Ability ability = controller.getCustomAbility(uuid);
if (ability == null || !ability.getAllowedBy().allowsNpc()) continue;
String name = controller.getCustomAbilityName(uuid);
if (name == null || name.isEmpty()) name = uuid;
map.put(name + "\t" + uuid, index++);
@@ -1,6 +1,7 @@
package noppes.npcs.ai;
import kamkeel.npcs.addon.DBCAddon;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
@@ -80,13 +81,14 @@ public class CombatHandler {
}
// Handle guard counter before interruption
if (npc.abilities.getCurrentAbility() instanceof kamkeel.npcs.controllers.data.ability.type.AbilityGuard) {
kamkeel.npcs.controllers.data.ability.type.AbilityGuard guard =
(kamkeel.npcs.controllers.data.ability.type.AbilityGuard) npc.abilities.getCurrentAbility();
if (guard.isGuarding() && e instanceof EntityLivingBase) {
guard.onDamageTaken(npc, (EntityLivingBase) e, source, damageAmount);
}
}
// if (npc.abilities.getCurrentAbility() instanceof AbilityGuard) {
// AbilityGuard guard =
// (AbilityGuard) npc.abilities.getCurrentAbility();
// if (guard.isGuarding() && e instanceof EntityLivingBase) {
// guard.onDamageTaken(npc, (EntityLivingBase) e, source, damageAmount);
// }
// }
// Check for ability interruption
npc.abilities.onDamage(source, damageAmount);
@@ -93,7 +93,9 @@ public class EntityAIAmbushTarget extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
if (!this.theEntity.abilities.isRotationLocked()) {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
}
}
private Vec3 findHidingSpot() {
@@ -118,7 +118,9 @@ public class EntityAIAttackTarget extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.npc.getLookHelper().setLookPositionWithEntity(this.entityTarget, 30.0F, 30.0F);
if (!this.npc.abilities.isRotationLocked()) {
this.npc.getLookHelper().setLookPositionWithEntity(this.entityTarget, 30.0F, 30.0F);
}
// Skip pathfinding updates if ability is controlling movement
if (!navOverride && !this.npc.abilities.isAbilityControllingMovement() && --this.field_75445_i <= 0) {
@@ -63,7 +63,7 @@ public class EntityAIDodgeShoot extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
if (this.entity.getAttackTarget() != null)
if (this.entity.getAttackTarget() != null && !this.entity.abilities.isRotationLocked())
this.entity.getLookHelper().setLookPositionWithEntity(this.entity.getAttackTarget(), 30.0F, 30.0F);
}
}
@@ -55,7 +55,9 @@ public class EntityAIFollow extends EntityAIBase {
if (updateTick < 10)
return;
updateTick = 0;
this.npc.getLookHelper().setLookPositionWithEntity(owner, 10.0F, (float) this.npc.getVerticalFaceSpeed());
if (!this.npc.abilities.isRotationLocked()) {
this.npc.getLookHelper().setLookPositionWithEntity(owner, 10.0F, (float) this.npc.getVerticalFaceSpeed());
}
double speed = 1 + distance / 150;
if (speed > 3)
@@ -26,7 +26,7 @@ public class EntityAILook extends EntityAIBase {
*/
@Override
public boolean shouldExecute() {
return !npc.isAttacking() && npc.getNavigator().noPath() && !npc.isPlayerSleeping() && npc.isEntityAlive();
return !npc.abilities.isRotationLocked() && !npc.isAttacking() && npc.getNavigator().noPath() && !npc.isPlayerSleeping() && npc.isEntityAlive();
}
/**
@@ -91,7 +91,9 @@ public class EntityAIOrbitTarget extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
if (!this.theEntity.abilities.isRotationLocked()) {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
}
if (this.theEntity.getNavigator().noPath() && this.tick >= 0) {
if (this.theEntity.onGround && !this.theEntity.isInWater()) {
double d0 = this.targetDistance * (double) (MathHelper.cos(angle / 180.0F * (float) Math.PI));
@@ -100,7 +100,9 @@ public class EntityAIRangedAttack extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.entityHost.getLookHelper().setLookPositionWithEntity(this.attackTarget, 30.0F, 30.0F);
if (!this.entityHost.abilities.isRotationLocked()) {
this.entityHost.getLookHelper().setLookPositionWithEntity(this.attackTarget, 30.0F, 30.0F);
}
double var1 = this.entityHost.getDistanceSq(this.attackTarget.posX, this.attackTarget.boundingBox.minY, this.attackTarget.posZ);
float field_82642_h = this.entityHost.stats.rangedRange * this.entityHost.stats.rangedRange;
@@ -68,7 +68,9 @@ public class EntityAIStalkTarget extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
if (!this.theEntity.abilities.isRotationLocked()) {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
}
if (this.theEntity.getNavigator().noPath() || this.overRide) {
if (this.isLookingAway()) {
@@ -31,7 +31,7 @@ public class EntityAIWatchClosest extends EntityAIBase {
*/
@Override
public boolean shouldExecute() {
if (this.theWatcher.getRNG().nextFloat() >= this.field_75331_e || theWatcher.isInteracting()) {
if (this.theWatcher.abilities.isRotationLocked() || this.theWatcher.getRNG().nextFloat() >= this.field_75331_e || theWatcher.isInteracting()) {
return false;
} else {
if (this.theWatcher.getAttackTarget() != null) {
@@ -8,6 +8,7 @@ import net.minecraft.pathfinding.PathPoint;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import noppes.npcs.constants.AiMutex;
import noppes.npcs.entity.EntityNPCInterface;
public class EntityAIZigZagTarget extends EntityAIBase {
private EntityCreature theEntity;
@@ -82,6 +83,8 @@ public class EntityAIZigZagTarget extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
if (!(this.theEntity instanceof EntityNPCInterface) || !((EntityNPCInterface) this.theEntity).abilities.isRotationLocked()) {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
}
}
}
@@ -19,6 +19,8 @@ import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderHandEvent;
import net.minecraftforge.client.event.RenderLivingEvent;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import noppes.npcs.client.gui.player.AuctionTooltipHandler;
import noppes.npcs.client.gui.customoverlay.OverlayCustom;
import noppes.npcs.client.gui.hud.ClientHudManager;
import noppes.npcs.client.gui.hud.CompassHudComponent;
@@ -75,6 +77,11 @@ public class ClientEventHandler {
}
}
@SubscribeEvent
public void onItemTooltip(ItemTooltipEvent event) {
AuctionTooltipHandler.onItemTooltip(event);
}
@SubscribeEvent
public void onMouse(MouseEvent event) {
if (Minecraft.getMinecraft().currentScreen != null)
@@ -76,6 +76,7 @@ import noppes.npcs.client.gui.GuiBorderBlock;
import noppes.npcs.client.gui.GuiMerchantAdd;
import noppes.npcs.client.gui.GuiNpcDimension;
import noppes.npcs.client.gui.GuiNpcMobSpawner;
import noppes.npcs.client.gui.GuiNpcMobSpawnerFullscreen;
import noppes.npcs.client.gui.GuiNpcMobSpawnerMounter;
import noppes.npcs.client.gui.GuiNpcPather;
import noppes.npcs.client.gui.GuiNpcRedstoneBlock;
@@ -191,6 +192,7 @@ import noppes.npcs.client.renderer.items.ItemShortLampRenderer;
import noppes.npcs.client.renderer.items.ItemTallLampRenderer;
import noppes.npcs.client.renderer.items.ItemToolRenderer;
import noppes.npcs.client.renderer.items.ScriptedBlockItemRenderer;
import noppes.npcs.client.ScriptClientConfig;
import noppes.npcs.config.ConfigClient;
import noppes.npcs.config.ConfigItem;
import noppes.npcs.config.ConfigMain;
@@ -333,7 +335,6 @@ public class ClientProxy extends CommonProxy {
ClientCloneController.Instance = new ClientCloneController();
ClientTagMapController.Instance = new ClientTagMapController();
MinecraftForge.EVENT_BUS.register(new ClientEventHandler());
// Telegraph rendering system
@@ -472,7 +473,7 @@ public class ClientProxy extends CommonProxy {
animNpc.display.texture = "customnpcs:textures/entity/humanmale/AnimationBody.png";
save = false;
}
return new GuiNPCManageAnimations(animNpc, save);
return new GuiNPCManageAnimations(animNpc, save, npc != null);
} else if (gui == EnumGuiType.ManageLinked)
return new GuiNPCManageLinked(npc);
@@ -507,8 +508,10 @@ public class ClientProxy extends CommonProxy {
} else {
abilityNpc = new EntityCustomNpc(Minecraft.getMinecraft().theWorld);
abilityNpc.display.texture = "customnpcs:textures/entity/humanmale/AnimationBody.png";
abilityNpc.height = 1.8f;
abilityNpc.width = 0.6f;
}
return new GuiNpcManageAbilities(abilityNpc);
return new GuiNpcManageAbilities(abilityNpc, npc != null);
}
else if (gui == EnumGuiType.MainMenuGlobal)
@@ -602,7 +605,9 @@ public class ClientProxy extends CommonProxy {
return new GuiNpcRedstoneBlock(x, y, z);
else if (gui == EnumGuiType.Cloner)
return new GuiNpcMobSpawner(x, y, z);
return GuiNpcMobSpawner.isFullscreen
? new GuiNpcMobSpawnerFullscreen(x, y, z)
: new GuiNpcMobSpawner(x, y, z);
else if (gui == EnumGuiType.MobSpawnerMounter)
return new GuiNpcMobSpawnerMounter(x, y, z);
@@ -818,6 +823,31 @@ public class ClientProxy extends CommonProxy {
}
}
@Override
public boolean isScriptingEnabled() {
return ConfigClient.AllowClientScripts && ScriptClientConfig.isScriptingEnabled();
}
@Override
public boolean isRunLoadedScriptsFirst() {
return ScriptClientConfig.isRunLoadedScriptsFirst();
}
@Override
public boolean isGlobalPlayerScripts() {
return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalPlayerScripts();
}
@Override
public boolean isGlobalForgeScripts() {
return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalForgeScripts();
}
@Override
public boolean isGlobalNPCScripts() {
return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalNPCScripts();
}
public static class FontContainer {
public StringCache textFont = null;
public boolean useCustomFont = true;
@@ -0,0 +1,61 @@
package noppes.npcs.client;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.nbt.NBTTagCompound;
/**
* Client-side cache for script configuration synced from server.
* Prevents client from using local ConfigScript which may differ from server settings.
*
* IMPORTANT: This class is CLIENT-ONLY. Server-side NBT writing is done in
* ScriptConfigSync to avoid @SideOnly crashes on dedicated servers.
*/
@SideOnly(Side.CLIENT)
public class ScriptClientConfig {
// Cached values from server
private static boolean scriptingEnabled = true;
private static boolean runLoadedScriptsFirst = true;
private static boolean globalPlayerScripts = true;
private static boolean globalForgeScripts = true;
private static boolean globalNPCScripts = false;
/**
* Update cached config from server NBT data.
* Called when receiving login packet or script sync packets.
*/
public static void readFromNBT(NBTTagCompound compound) {
if (compound == null) return;
scriptingEnabled = compound.getBoolean("ScriptingEnabled");
runLoadedScriptsFirst = compound.getBoolean("RunLoadedScriptsFirst");
globalPlayerScripts = compound.getBoolean("GlobalPlayerScripts");
globalForgeScripts = compound.getBoolean("GlobalForgeScripts");
globalNPCScripts = compound.getBoolean("GlobalNPCScripts");
}
/**
* Reset to defaults (called on disconnect).
*/
public static void reset() {
scriptingEnabled = true;
runLoadedScriptsFirst = true;
globalPlayerScripts = true;
globalForgeScripts = true;
globalNPCScripts = false;
}
// Setters for individual packet updates
public static void setScriptingEnabled(boolean value) { scriptingEnabled = value; }
public static void setRunLoadedScriptsFirst(boolean value) { runLoadedScriptsFirst = value; }
public static void setGlobalPlayerScripts(boolean value) { globalPlayerScripts = value; }
public static void setGlobalForgeScripts(boolean value) { globalForgeScripts = value; }
public static void setGlobalNPCScripts(boolean value) { globalNPCScripts = value; }
// Getters
public static boolean isScriptingEnabled() { return scriptingEnabled; }
public static boolean isRunLoadedScriptsFirst() { return runLoadedScriptsFirst; }
public static boolean isGlobalPlayerScripts() { return globalPlayerScripts; }
public static boolean isGlobalForgeScripts() { return globalForgeScripts; }
public static boolean isGlobalNPCScripts() { return globalNPCScripts; }
}
@@ -41,6 +41,26 @@ public class ClientCloneController extends ServerCloneController {
return true;
}
@Override
public boolean addToTagMap(NBTTagCompound nbttagcompound, String name, String folderName) {
HashSet<UUID> tagUUIDs = new HashSet<>();
if (nbttagcompound.hasKey("TagUUIDs")) {
NBTTagList nbtTagList = nbttagcompound.getTagList("TagUUIDs", 8);
for (int i = 0; i < nbtTagList.tagCount(); i++) {
tagUUIDs.add(UUID.fromString(nbtTagList.getStringTagAt(i)));
}
}
TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName);
if (!tagUUIDs.isEmpty()) {
tagMap.putClone(name, tagUUIDs);
} else {
tagMap.removeClone(name);
}
ClientTagMapController.Instance.saveTagMap(tagMap);
return true;
}
@Override
public boolean removeFromTagMap(String name, int tab) {
TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab);
@@ -51,4 +71,43 @@ public class ClientCloneController extends ServerCloneController {
return false;
}
@Override
public boolean removeFromTagMap(String name, String folderName) {
TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName);
if (tagMap.removeClone(name)) {
ClientTagMapController.Instance.saveTagMap(tagMap);
return true;
}
return false;
}
@Override
protected HashSet<UUID> getTagUUIDsFromTab(String cloneName, int tab) {
TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab);
HashSet<UUID> uuids = tagMap.getUUIDs(cloneName);
return uuids != null ? new HashSet<>(uuids) : new HashSet<>();
}
@Override
protected HashSet<UUID> getTagUUIDsFromFolder(String cloneName, String folderName) {
TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName);
HashSet<UUID> uuids = tagMap.getUUIDs(cloneName);
return uuids != null ? new HashSet<>(uuids) : new HashSet<>();
}
@Override
protected void setTagUUIDsForTab(String cloneName, int tab, HashSet<UUID> tagUUIDs) {
if (tagUUIDs == null || tagUUIDs.isEmpty()) return;
TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab);
tagMap.putClone(cloneName, tagUUIDs);
ClientTagMapController.Instance.saveTagMap(tagMap);
}
@Override
protected void setTagUUIDsForFolder(String cloneName, String folderName, HashSet<UUID> tagUUIDs) {
if (tagUUIDs == null || tagUUIDs.isEmpty()) return;
TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName);
tagMap.putClone(cloneName, tagUUIDs);
ClientTagMapController.Instance.saveTagMap(tagMap);
}
}
@@ -2,6 +2,7 @@ package noppes.npcs.client.gui;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.clone.CloneAllTagsPacket;
import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket;
import kamkeel.npcs.network.packets.request.clone.CloneListPacket;
import kamkeel.npcs.network.packets.request.clone.CloneRemovePacket;
import kamkeel.npcs.network.packets.request.clone.CloneTagListPacket;
@@ -26,6 +27,8 @@ import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IClonerGui;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.controllers.data.Tag;
import noppes.npcs.controllers.data.TagMap;
@@ -38,52 +41,84 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData, ICustomScrollListener, IClonerGui {
// ==================== STATIC STATE (persists across GUI opens, shared with fullscreen) ====================
public static boolean isFullscreen = false;
public static int activeTab = 1;
public static String activeFolder = null;
public static int showingClones = 0; // 0=Clones, 1=Entities, 2=Server, 3=Filters
public static String search = "";
public static String tagSearch = "";
public static HashMap<UUID, Tag> tags = new HashMap<>();
public static HashMap<String, UUID> tagNames = new HashMap<>();
public static HashSet<String> tagFilters = new HashSet<>();
public static byte displayTags = 0;
// 0 - Any, 1 - All, 2 - Not Any, 3 - Not All
public static byte filterCondition = 0;
public static byte ascending = 0;
// 0 - By Name, 1 - By Date
public static byte sortType = 0;
public TagMap tagMap;
// Scroll position preservation (shared with fullscreen)
public static int savedContentScrollY = 0;
public static int savedNavScrollY = 0;
// ==================== INSTANCE STATE ====================
public TagMap tagMap;
private final GuiCustomScrollCloner scroll = new GuiCustomScrollCloner(this, 0);
private final GuiCustomScroll filterScroll = new GuiCustomScroll(this, 1);
private int posX, posY, posZ;
public int posX, posY, posZ;
private List<String> list;
private List<String> rawList;
private List<String> tagList;
private static int showingClones = 0;
private static String search = "";
private static String tagSearch = "";
private int activeTab = 1;
// ==================== CONSTRUCTOR ====================
public GuiNpcMobSpawner(int i, int j, int k) {
super();
xSize = 354;
posX = i;
posY = j;
posZ = k;
this.closeOnEsc = true;
closeOnEsc = true;
xSize = 354;
setBackground("menubg.png");
PacketClient.sendClient(new CloneAllTagsPacket());
if (showingClones == 2) {
PacketClient.sendClient(new CloneFolderListPacket());
}
// Minimized view doesn't support folders — ensure we're on a tab
if (activeFolder != null) {
if (activeTab < 1 || activeTab > 15) {
activeTab = 1;
}
activeFolder = null;
}
}
// ==================== IClonerGui ====================
@Override
public int getShowingClones() {
return showingClones;
}
@Override
public HashMap<UUID, Tag> getTags() {
return tags;
}
@Override
public TagMap getTagMap() {
return tagMap;
}
// ==================== INIT GUI ====================
public void initGui() {
// Save scroll position before clear
savedContentScrollY = scroll.scrollY;
super.initGui();
guiTop += 10;
guiLeft += 30;
@@ -92,6 +127,7 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
scroll.setSize(293, 188);
scroll.guiLeft = guiLeft + 4;
scroll.guiTop = guiTop + 26;
filterScroll.clear();
filterScroll.setSize(140, 166);
filterScroll.guiLeft = guiLeft + 4;
@@ -99,112 +135,133 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
filterScroll.multipleSelection = true;
filterScroll.setSelectedList(tagFilters);
GuiMenuTopButton button;
addTopButton(button = new GuiMenuTopButton(3, guiLeft + 4, guiTop - 17, "spawner.clones"));
button.active = showingClones == 0;
addTopButton(button = new GuiMenuTopButton(5, button, "gui.server"));
button.active = showingClones == 2;
addTopButton(button = new GuiMenuTopButton(4, button, "spawner.entities"));
button.active = showingClones == 1;
addTopButton(button = new GuiMenuTopButton(16, guiLeft + (xSize - 67), guiTop - 17, "gui.filters"));
button.active = showingClones == 3;
addTopButton(button = new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X"));
// Top buttons — build right-to-left to avoid overlap
GuiMenuTopButton closeBtn = new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X");
addTopButton(closeBtn);
// Position "+" dynamically to the left of "X"
int plusX = closeBtn.xPosition - (fontRendererObj.getStringWidth("+") + 12) - 2;
GuiMenuTopButton fullscreenBtn = new GuiMenuTopButton(61, plusX, guiTop - 17, "+");
addTopButton(fullscreenBtn);
// Position "Filters" dynamically to the left of "+"
int filterBtnW = fontRendererObj.getStringWidth(StatCollector.translateToLocal("gui.filters")) + 12;
int filterX = fullscreenBtn.xPosition - filterBtnW - 2;
GuiMenuTopButton filterBtn = new GuiMenuTopButton(16, filterX, guiTop - 17, "gui.filters");
filterBtn.active = showingClones == 3;
addTopButton(filterBtn);
// Mode buttons from left
GuiMenuTopButton btn;
addTopButton(btn = new GuiMenuTopButton(3, guiLeft + 4, guiTop - 17, "spawner.clones"));
btn.active = showingClones == 0;
addTopButton(btn = new GuiMenuTopButton(5, btn, "gui.server"));
btn.active = showingClones == 2;
addTopButton(btn = new GuiMenuTopButton(4, btn, "spawner.entities"));
btn.active = showingClones == 1;
if (showingClones < 3) {
addScroll(scroll);
addTextField(new GuiNpcTextField(1, this, fontRendererObj, guiLeft + 4, guiTop + 4, 293, 20, search));
addButton(new GuiNpcButton(1, guiLeft + 298, guiTop + 6, 52, 20, "item.monsterPlacer.name"));
addButton(new GuiNpcButton(2, guiLeft + 298, guiTop + 140, 52, 20, "spawner.mobspawner"));
if (showingClones == 0 || showingClones == 2) {
addSideButton(new GuiMenuSideButton(21, guiLeft - 70, this.guiTop + 2, 70, 22, "1"));
addSideButton(new GuiMenuSideButton(22, guiLeft - 70, this.guiTop + 23, 70, 22, "2"));
addSideButton(new GuiMenuSideButton(23, guiLeft - 70, this.guiTop + 44, 70, 22, "3"));
addSideButton(new GuiMenuSideButton(24, guiLeft - 70, this.guiTop + 65, 70, 22, "4"));
addSideButton(new GuiMenuSideButton(25, guiLeft - 70, this.guiTop + 86, 70, 22, "5"));
addSideButton(new GuiMenuSideButton(26, guiLeft - 70, this.guiTop + 107, 35, 22, "6"));
addSideButton(new GuiMenuSideButton(27, guiLeft - 35, this.guiTop + 107, 35, 22, "7"));
addSideButton(new GuiMenuSideButton(28, guiLeft - 70, this.guiTop + 128, 35, 22, "8"));
addSideButton(new GuiMenuSideButton(29, guiLeft - 35, this.guiTop + 128, 35, 22, "9"));
addSideButton(new GuiMenuSideButton(30, guiLeft - 70, this.guiTop + 149, 35, 22, "10"));
addSideButton(new GuiMenuSideButton(31, guiLeft - 35, this.guiTop + 149, 35, 22, "11"));
addSideButton(new GuiMenuSideButton(32, guiLeft - 70, this.guiTop + 170, 35, 22, "12"));
addSideButton(new GuiMenuSideButton(33, guiLeft - 35, this.guiTop + 170, 35, 22, "13"));
addSideButton(new GuiMenuSideButton(34, guiLeft - 70, this.guiTop + 191, 35, 22, "14"));
addSideButton(new GuiMenuSideButton(35, guiLeft - 35, this.guiTop + 191, 35, 22, "15"));
addButton(new GuiNpcButton(6, guiLeft + 298, guiTop + 190, 52, 20, "gui.remove"));
getSideButton(20 + activeTab).active = true;
initTabSideButtons();
showClones();
// Restore scroll position
scroll.scrollY = Math.min(savedContentScrollY, Math.max(0, scroll.maxScrollY));
} else {
showEntities();
scroll.scrollY = Math.min(savedContentScrollY, Math.max(0, scroll.maxScrollY));
}
} else {
// Show Filters
addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("cloner.tagFilters"), guiLeft + 7, guiTop + 7));
addScroll(filterScroll);
addTextField(new GuiNpcTextField(2, this, fontRendererObj, guiLeft + 4, guiTop + 190, 140, 20, tagSearch));
addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("cloner.tagVisibility"), guiLeft + 150, guiTop + 27));
addButton(new GuiNpcButton(12, guiLeft + 215, guiTop + 20, new String[]{"display.show", "display.all", "display.hide"}, displayTags));
addLabel(new GuiNpcLabel(3, StatCollector.translateToLocal("filter.contains"), guiLeft + 150, guiTop + 50));
addButton(new GuiNpcButton(13, guiLeft + 215, guiTop + 43, new String[]{"filter.any", "filter.all", "filter.notany", "filter.notall"}, filterCondition));
addButton(new GuiNpcButton(11, guiLeft + 150, guiTop + 66, 130, 20, "gui.deselectAll"));
addLabel(new GuiNpcLabel(4, StatCollector.translateToLocal("cloner.order"), guiLeft + 150, guiTop + 112));
addButton(new GuiNpcButton(14, guiLeft + 215, guiTop + 105, new String[]{"cloner.ascending", "cloner.descending"}, ascending));
addLabel(new GuiNpcLabel(5, StatCollector.translateToLocal("cloner.type"), guiLeft + 150, guiTop + 135));
addButton(new GuiNpcButton(15, guiLeft + 215, guiTop + 128, new String[]{"cloner.name", "cloner.date"}, sortType));
getButton(12).width = 65;
getButton(12).height = 20;
getButton(13).width = 65;
getButton(13).height = 20;
getButton(14).width = 65;
getButton(14).height = 20;
getButton(15).width = 65;
getButton(15).height = 20;
showFilters();
showFiltersPage();
}
}
public int getShowingClones() {
return showingClones;
private void initTabSideButtons() {
// Tabs 1-5: full width (70px)
addSideButton(new GuiMenuSideButton(21, guiLeft - 70, guiTop + 2, 70, 22, "1"));
addSideButton(new GuiMenuSideButton(22, guiLeft - 70, guiTop + 23, 70, 22, "2"));
addSideButton(new GuiMenuSideButton(23, guiLeft - 70, guiTop + 44, 70, 22, "3"));
addSideButton(new GuiMenuSideButton(24, guiLeft - 70, guiTop + 65, 70, 22, "4"));
addSideButton(new GuiMenuSideButton(25, guiLeft - 70, guiTop + 86, 70, 22, "5"));
// Tabs 6-15: half width (35px), 2-column grid
addSideButton(new GuiMenuSideButton(26, guiLeft - 70, guiTop + 107, 35, 22, "6"));
addSideButton(new GuiMenuSideButton(27, guiLeft - 35, guiTop + 107, 35, 22, "7"));
addSideButton(new GuiMenuSideButton(28, guiLeft - 70, guiTop + 128, 35, 22, "8"));
addSideButton(new GuiMenuSideButton(29, guiLeft - 35, guiTop + 128, 35, 22, "9"));
addSideButton(new GuiMenuSideButton(30, guiLeft - 70, guiTop + 149, 35, 22, "10"));
addSideButton(new GuiMenuSideButton(31, guiLeft - 35, guiTop + 149, 35, 22, "11"));
addSideButton(new GuiMenuSideButton(32, guiLeft - 70, guiTop + 170, 35, 22, "12"));
addSideButton(new GuiMenuSideButton(33, guiLeft - 35, guiTop + 170, 35, 22, "13"));
addSideButton(new GuiMenuSideButton(34, guiLeft - 70, guiTop + 191, 35, 22, "14"));
addSideButton(new GuiMenuSideButton(35, guiLeft - 35, guiTop + 191, 35, 22, "15"));
if (activeTab >= 1 && activeTab <= 15) {
GuiMenuSideButton active = getSideButton(20 + activeTab);
if (active != null) active.active = true;
}
}
public void showFilters() {
// ==================== FILTERS PAGE ====================
private void showFiltersPage() {
int baseY = guiTop;
addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("cloner.tagFilters"),
guiLeft + 7, baseY + 7));
filterScroll.clear();
filterScroll.setSize(140, 166);
filterScroll.guiLeft = guiLeft + 4;
filterScroll.guiTop = baseY + 19;
filterScroll.multipleSelection = true;
filterScroll.setSelectedList(tagFilters);
addScroll(filterScroll);
addTextField(new GuiNpcTextField(2, this, fontRendererObj,
guiLeft + 4, baseY + 190, 140, 20, tagSearch));
addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("cloner.tagVisibility"),
guiLeft + 150, baseY + 27));
addButton(new GuiNpcButton(12, guiLeft + 215, baseY + 20,
new String[]{"display.show", "display.all", "display.hide"}, displayTags));
addLabel(new GuiNpcLabel(3, StatCollector.translateToLocal("filter.contains"),
guiLeft + 150, baseY + 50));
addButton(new GuiNpcButton(13, guiLeft + 215, baseY + 43,
new String[]{"filter.any", "filter.all", "filter.notany", "filter.notall"}, filterCondition));
addButton(new GuiNpcButton(11, guiLeft + 150, baseY + 66, 130, 20, "gui.deselectAll"));
addLabel(new GuiNpcLabel(4, StatCollector.translateToLocal("cloner.order"),
guiLeft + 150, baseY + 112));
addButton(new GuiNpcButton(14, guiLeft + 215, baseY + 105,
new String[]{"cloner.ascending", "cloner.descending"}, ascending));
addLabel(new GuiNpcLabel(5, StatCollector.translateToLocal("cloner.type"),
guiLeft + 150, baseY + 135));
addButton(new GuiNpcButton(15, guiLeft + 215, baseY + 128,
new String[]{"cloner.name", "cloner.date"}, sortType));
getButton(12).width = 65;
getButton(12).height = 20;
getButton(13).width = 65;
getButton(13).height = 20;
getButton(14).width = 65;
getButton(14).height = 20;
getButton(15).width = 65;
getButton(15).height = 20;
filterScroll.setList(getTagList());
}
private void showEntities() {
Map<?, ?> data = EntityList.stringToClassMapping;
ArrayList<String> list = new ArrayList<String>();
for (Object name : data.keySet()) {
Class<?> c = (Class<?>) data.get(name);
try {
if (EntityLiving.class.isAssignableFrom(c) && c.getConstructor(new Class[]{World.class}) != null && !Modifier.isAbstract(c.getModifiers()))
list.add(name.toString());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
}
}
this.list = list;
this.rawList = new ArrayList<String>(this.list);
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
// ==================== CLONE / ENTITY DISPLAY ====================
private void showClones() {
if (showingClones == 2) {
PacketClient.sendClient(new CloneTagListPacket(activeTab));
@@ -219,16 +276,41 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
this.tagMap = ClientTagMapController.Instance.getTagMap(activeTab);
populateRawListWithTags();
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
private void showEntities() {
Map<?, ?> data = EntityList.stringToClassMapping;
ArrayList<String> list = new ArrayList<String>();
for (Object name : data.keySet()) {
Class<?> c = (Class<?>) data.get(name);
try {
if (EntityLiving.class.isAssignableFrom(c)
&& c.getConstructor(new Class[]{World.class}) != null
&& !Modifier.isAbstract(c.getModifiers()))
list.add(name.toString());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
}
}
this.list = list;
this.rawList = new ArrayList<String>(this.list);
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
private void populateRawListWithTags() {
this.rawList = new ArrayList<>(this.list);
if (this.tagMap != null) {
if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) {
if (displayTags == 0 || displayTags == 1) {
for (int i = 0; i < this.list.size(); i++) {
StringBuilder npcName = new StringBuilder(list.get(i));
if (this.tagMap.hasClone(list.get(i))) {
for (UUID tagUUID : this.tagMap.getUUIDsList(list.get(i))) {
Tag tag = tags.get(tagUUID);
if (tag != null) {
if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) {
if (displayTags == 1 || !tag.getIsHidden()) {
npcName.append(" [" + tag.name + "]");
}
}
@@ -238,27 +320,26 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
}
}
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(1) != null) {
if (search.equals(getTextField(1).getText()))
return;
search = getTextField(1).getText().toLowerCase();
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
if (getTextField(2) != null) {
if (tagSearch.equals(getTextField(2).getText()))
return;
tagSearch = getTextField(2).getText().toLowerCase();
filterScroll.setList(getTagList());
}
private NBTTagCompound getCompound() {
String sel = scroll.getSelected();
if (sel == null)
return null;
if (showingClones == 0) {
return ClientCloneController.Instance.getCloneData(player, sel, activeTab);
} else {
Entity entity = EntityList.createEntityByName(sel, Minecraft.getMinecraft().theWorld);
if (entity == null)
return null;
NBTTagCompound compound = new NBTTagCompound();
entity.writeToNBTOptional(compound);
return compound;
}
}
// ==================== SEARCH / FILTER ====================
private List<String> getSearchList() {
if (this.list == null) {
this.list = new ArrayList<String>();
@@ -269,10 +350,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
// No Filters - or - Entities
if (tagFilters.size() == 0 || showingClones == 1) {
// No Search
if (search.isEmpty())
return new ArrayList<String>(this.list);
// Yes Search
else {
List<String> list = new ArrayList<String>();
for (int i = 0; i < this.list.size(); i++) {
@@ -284,10 +363,7 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
}
////////////////////////
//// WITH FILTERS
// No Search
// With Filters
if (search.isEmpty()) {
List<String> list = new ArrayList<String>();
for (String name : this.list) {
@@ -300,7 +376,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
return list;
}
// Yes Search
List<String> list = new ArrayList<String>();
for (int i = 0; i < this.list.size(); i++) {
if (this.rawList.get(i).toLowerCase().contains(search)) {
@@ -311,7 +386,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
}
}
}
return list;
}
@@ -346,7 +420,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
}
}
return conditionMet;
}
@@ -354,10 +427,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
if (this.tagList == null) {
this.tagList = new ArrayList<String>();
}
// No Search // No Filters - or - Entities
if (tagSearch.isEmpty())
return new ArrayList<String>(tagNames.keySet());
// Yes Search // No Filters - or - Entities
List<String> list = new ArrayList<String>();
for (String name : this.tagList) {
@@ -367,125 +438,162 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
return list;
}
private NBTTagCompound getCompound() {
String sel = scroll.getSelected();
if (sel == null)
return null;
if (showingClones == 0) {
return ClientCloneController.Instance.getCloneData(player, sel, activeTab);
} else {
Entity entity = EntityList.createEntityByName(sel, Minecraft.getMinecraft().theWorld);
if (entity == null)
return null;
NBTTagCompound compound = new NBTTagCompound();
entity.writeToNBTOptional(compound);
return compound;
}
// ==================== MOUSE / KEYBOARD EVENTS ====================
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) {
}
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
GuiNpcTextField searchField = getTextField(1);
if (searchField != null) {
String newText = searchField.getText().toLowerCase();
if (!search.equals(newText)) {
search = newText;
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
}
GuiNpcTextField tagSearchField = getTextField(2);
if (tagSearchField != null) {
String newText = tagSearchField.getText().toLowerCase();
if (!tagSearch.equals(newText)) {
tagSearch = newText;
filterScroll.setList(getTagList());
}
}
}
// ==================== BUTTON ACTIONS ====================
@Override
protected void actionPerformed(GuiButton guibutton) {
int id = guibutton.id;
if (id == 0) {
close();
}
if (id == 1) {
if (showingClones == 2) {
String sel = scroll.getSelected();
if (sel == null)
return;
SpawnMobPacket.Server(posX, posY, posZ, sel, activeTab);
close();
} else {
NBTTagCompound compound = getCompound();
if (compound == null)
return;
SpawnMobPacket.Client(posX, posY, posZ, compound);
close();
}
}
if (id == 2) {
if (showingClones == 2) {
String sel = scroll.getSelected();
if (sel == null)
return;
MobSpawnerPacket.Server(posX, posY, posZ, sel, activeTab);
close();
} else {
NBTTagCompound compound = getCompound();
if (compound == null)
return;
MobSpawnerPacket.Client(posX, posY, posZ, compound);
close();
}
// Tab side buttons (IDs 21-35)
if (id >= 21 && id <= 35) {
activeTab = id - 20;
activeFolder = null;
initGui();
return;
}
// Mode buttons
if (id == 3) {
savedContentScrollY = 0;
showingClones = 0;
initGui();
}
if (id == 4) {
savedContentScrollY = 0;
showingClones = 1;
initGui();
}
if (id == 5) {
savedContentScrollY = 0;
showingClones = 2;
PacketClient.sendClient(new CloneFolderListPacket());
initGui();
}
if (id == 16) {
savedContentScrollY = 0;
showingClones = 3;
initGui();
}
if (id == 17) {
close();
}
// Open fullscreen GUI
if (id == 61) {
isFullscreen = true;
Minecraft.getMinecraft().displayGuiScreen(
new GuiNpcMobSpawnerFullscreen(posX, posY, posZ));
}
// Spawn
if (id == 1) {
if (showingClones == 2) {
String sel = scroll.getSelected();
if (sel == null) return;
SpawnMobPacket.Server(posX, posY, posZ, sel, activeTab);
close();
} else {
NBTTagCompound compound = getCompound();
if (compound == null) return;
SpawnMobPacket.Client(posX, posY, posZ, compound);
close();
}
}
// Mob Spawner
if (id == 2) {
if (showingClones == 2) {
String sel = scroll.getSelected();
if (sel == null) return;
MobSpawnerPacket.Server(posX, posY, posZ, sel, activeTab);
close();
} else {
NBTTagCompound compound = getCompound();
if (compound == null) return;
MobSpawnerPacket.Client(posX, posY, posZ, compound);
close();
}
}
// Remove
if (id == 6) {
if (scroll.getSelected() != null) {
int prevSelected = scroll.selected;
if (showingClones == 2) {
PacketClient.sendClient(new CloneRemovePacket(activeTab, scroll.getSelected()));
return;
}
ClientCloneController.Instance.removeClone(scroll.getSelected(), activeTab);
scroll.selected = -1;
initGui();
if (scroll.list != null && !scroll.list.isEmpty()) {
scroll.selected = Math.min(prevSelected, scroll.list.size() - 1);
} else {
scroll.selected = -1;
}
}
}
// Filter controls
if (id == 11) {
tagFilters = new HashSet<>();
filterScroll.setSelectedList(tagFilters);
initGui();
}
if (id == 12) {
GuiNpcButton button = (GuiNpcButton) guibutton;
displayTags = (byte) button.getValue();
displayTags = (byte) ((GuiNpcButton) guibutton).getValue();
}
if (id == 13) {
GuiNpcButton button = (GuiNpcButton) guibutton;
filterCondition = (byte) button.getValue();
filterCondition = (byte) ((GuiNpcButton) guibutton).getValue();
}
if (id == 14) {
GuiNpcButton button = (GuiNpcButton) guibutton;
ascending = (byte) button.getValue();
ascending = (byte) ((GuiNpcButton) guibutton).getValue();
}
if (id == 15) {
GuiNpcButton button = (GuiNpcButton) guibutton;
sortType = (byte) button.getValue();
}
if (id > 20) {
activeTab = id - 20;
initGui();
sortType = (byte) ((GuiNpcButton) guibutton).getValue();
}
}
// ==================== DATA FROM SERVER ====================
@Override
public void save() {
}
@Override
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("CloneTags")) {
if (compound.hasKey("CloneFolders")) {
// Minimized doesn't use folders, but still handle the packet
initGui();
} else if (compound.hasKey("CloneTags")) {
this.tagMap = new TagMap(activeTab);
NBTTagCompound cloneTags = compound.getCompoundTag("CloneTags");
this.tagMap.readNBT(cloneTags);
@@ -521,29 +629,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
this.list = list;
this.rawList = new ArrayList<String>(this.list);
if (this.tagMap != null) {
if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) {
for (int i = 0; i < this.list.size(); i++) {
StringBuilder npcName = new StringBuilder(list.get(i));
if (this.tagMap.hasClone(list.get(i))) {
for (UUID tagUUID : this.tagMap.getUUIDsList(list.get(i))) {
Tag tag = tags.get(tagUUID);
if (tag != null) {
if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) {
npcName.append(" [" + tag.name + "]");
}
}
}
}
this.rawList.set(i, npcName.toString());
}
}
}
populateRawListWithTags();
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
}
}
@@ -2,6 +2,7 @@ package noppes.npcs.client.gui;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.clone.CloneAllTagsShortPacket;
import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket;
import kamkeel.npcs.network.packets.request.clone.ClonePreSavePacket;
import kamkeel.npcs.network.packets.request.clone.CloneSavePacket;
import net.minecraft.client.Minecraft;
@@ -22,12 +23,14 @@ import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.data.CloneFolder;
import noppes.npcs.controllers.data.Tag;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ISubGuiListener {
@@ -35,9 +38,16 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
private Entity toClone;
private NBTTagCompound compound;
private static boolean serverSide = false;
private static int saveMode = 0; // 0=Tab, 1=Folder
private static int tab = 1;
private static String folder = null;
public boolean isNPC = false;
// Client-side folder names
private ArrayList<String> clientFolderNames = new ArrayList<>();
// Server-side folder names (populated via CloneFolderListPacket)
private static ArrayList<String> serverFolderNames = new ArrayList<>();
// Selected Tags to Add
public static NBTTagList tagsCompound;
public static HashSet<String> addTags;
@@ -68,6 +78,37 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
if (isNPC) {
PacketClient.sendClient(new CloneAllTagsShortPacket());
}
buildClientFolderNames();
// Request server folders if in server mode
if (serverSide) {
PacketClient.sendClient(new CloneFolderListPacket());
}
// Validate saved folder selection
validateFolder();
}
private void buildClientFolderNames() {
clientFolderNames.clear();
if (ClientCloneController.Instance != null) {
for (CloneFolder f : ClientCloneController.Instance.getFolderList()) {
clientFolderNames.add(f.name);
}
}
}
private List<String> getActiveFolderList() {
return serverSide ? serverFolderNames : clientFolderNames;
}
private void validateFolder() {
if (saveMode == 1 && folder != null) {
if (!getActiveFolderList().contains(folder)) {
folder = null;
}
}
}
@Override
@@ -77,61 +118,138 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
addLabel(new GuiNpcLabel(0, "Save as", guiLeft + 4, guiTop + 6));
addTextField(new GuiNpcTextField(0, this, fontRendererObj, guiLeft + 4, guiTop + 18, 200, 20, name));
// Tab/Folder toggle
addButton(new GuiNpcButton(6, guiLeft + 4, guiTop + 45, 50, 20,
new String[]{"Tab", "Folder"}, saveMode));
addLabel(new GuiNpcLabel(1, "Tab", guiLeft + 10, guiTop + 50));
addButton(new GuiButtonBiDirectional(2, guiLeft + 40, guiTop + 45, 60, 20, new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"}, tab - 1));
// Destination selector based on saveMode
if (saveMode == 0) {
// Tab selector: 1-15
String[] tabLabels = new String[15];
for (int i = 0; i < 15; i++) tabLabels[i] = String.valueOf(i + 1);
int selectedTab = (tab >= 1 && tab <= 15) ? tab - 1 : 0;
addButton(new GuiButtonBiDirectional(2, guiLeft + 56, guiTop + 45, 90, 20, tabLabels, selectedTab));
} else {
// Folder selector button — opens SubGuiFolderSelect
String btnText = folder != null ? folder : "Select a Folder";
addButton(new GuiNpcButton(2, guiLeft + 56, guiTop + 45, 148, 20, btnText));
}
addButton(new GuiNpcButton(3, guiLeft + 4, guiTop + 95, new String[]{"Client side", "Server side"}, serverSide ? 1 : 0));
addLabel(new GuiNpcLabel(1, "Tab", guiLeft + 10, guiTop + 50));
addButton(new GuiNpcButton(0, guiLeft + 4, guiTop + 70, 80, 20, "gui.save"));
// Save / Cancel
GuiNpcButton saveBtn = new GuiNpcButton(0, guiLeft + 4, guiTop + 70, 80, 20, "gui.save");
if (saveMode == 1 && folder == null) {
saveBtn.enabled = false;
}
addButton(saveBtn);
addButton(new GuiNpcButton(1, guiLeft + 86, guiTop + 70, 80, 20, "gui.cancel"));
// Client / Server toggle
addButton(new GuiNpcButton(3, guiLeft + 4, guiTop + 95, new String[]{"Client side", "Server side"}, serverSide ? 1 : 0));
if (isNPC) {
addButton(new GuiNpcButton(4, guiLeft + 4, guiTop + 120, 99, 20, "cloner.wandTags"));
addButton(new GuiNpcButton(5, guiLeft + 106, guiTop + 120, 99, 20, "cloner.npcTags"));
if (addTags.size() > 0) {
addLabel(new GuiNpcLabel(6, "cloner.wandtagsapplied", guiLeft + 10, guiTop + 160));
addLabel(new GuiNpcLabel(8, "cloner.wandtagsapplied", guiLeft + 10, guiTop + 160));
}
}
}
private void updateDestinationFromSelector() {
if (saveMode == 0) {
GuiNpcButton selector = getButton(2);
if (selector == null) return;
tab = selector.getValue() + 1;
folder = null;
}
// In folder mode, folder is already set via SubGuiFolderSelect
}
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
// Save
if (id == 0) {
updateDestinationFromSelector();
String name = getTextField(0).getText();
if (name.isEmpty())
return;
int tab = ((GuiNpcButton) guibutton).getValue() + 1;
if (saveMode == 1 && folder == null)
return;
if (!serverSide) {
if (ClientCloneController.Instance.getCloneData(null, name, tab) != null)
boolean exists;
if (saveMode == 1 && folder != null && ClientCloneController.Instance != null) {
exists = ClientCloneController.Instance.getCloneData(null, name, folder) != null;
} else {
exists = ClientCloneController.Instance.getCloneData(null, name, tab) != null;
}
if (exists)
displayGuiScreen(new GuiYesNo(this, "Warning", "You are about to overwrite a clone", 1));
else
confirmClicked(true, 0);
} else
PacketClient.sendClient(new ClonePreSavePacket(name, tab));
} else {
if (saveMode == 1 && folder != null) {
PacketClient.sendClient(new ClonePreSavePacket(name, folder));
} else {
PacketClient.sendClient(new ClonePreSavePacket(name, tab));
}
}
}
// Cancel
if (id == 1) {
close();
}
// Destination selector
if (id == 2) {
tab = ((GuiNpcButton) guibutton).getValue() + 1;
if (saveMode == 0) {
// Tab mode — update from BiDirectional
updateDestinationFromSelector();
} else {
// Folder mode — open folder selector Sub GUI
List<String> folders = getActiveFolderList();
setSubGui(new SubGuiFolderSelect(folders, folder));
}
}
// Client / Server toggle
if (id == 3) {
boolean wasServerSide = serverSide;
serverSide = ((GuiNpcButton) guibutton).getValue() == 1;
if (serverSide && !wasServerSide) {
// Switching to server mode — request fresh folder list
PacketClient.sendClient(new CloneFolderListPacket());
}
// Validate folder exists on the new side
validateFolder();
initGui();
}
// Wand Tags
if (id == 4) {
if (isNPC) {
this.setSubGui(new SubGuiClonerQuickTags(this));
}
}
// NPC Tags
if (id == 5) {
if (isNPC) {
this.setSubGui(new SubGuiClonerNPCTags((EntityNPCInterface) toClone, this));
}
}
}
// Tab/Folder mode toggle
if (id == 6) {
saveMode = ((GuiNpcButton) guibutton).getValue();
initGui();
}
}
@Override
public void confirmClicked(boolean confirm, int id) {
@@ -145,13 +263,21 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
if (isNPC) {
compound.setTag("TagUUIDs", tagsCompound);
}
ClientCloneController.Instance.addClone(compound, name, tab, extraTags);
if (saveMode == 1 && folder != null && ClientCloneController.Instance != null) {
ClientCloneController.Instance.addClone(compound, name, folder, extraTags);
} else {
ClientCloneController.Instance.addClone(compound, name, tab, extraTags);
}
} else {
NBTTagCompound compounder = new NBTTagCompound();
if (isNPC) {
compounder.setTag("TagUUIDs", tagsCompound);
}
PacketClient.sendClient(new CloneSavePacket(name, tab, extraTags, compounder));
if (saveMode == 1 && folder != null) {
PacketClient.sendClient(new CloneSavePacket(name, folder, extraTags, compounder));
} else {
PacketClient.sendClient(new CloneSavePacket(name, tab, extraTags, compounder));
}
}
close();
@@ -159,7 +285,6 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
displayGuiScreen(this);
}
@Override
public void save() {
}
@@ -171,6 +296,17 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
displayGuiScreen(new GuiYesNo(this, "Warning", "You are about to overwrite a clone", 1));
else
confirmClicked(true, 0);
} else if (compound.hasKey("CloneFolders")) {
// Server folder list arrived
NBTTagList folderList = compound.getTagList("CloneFolders", 10);
serverFolderNames.clear();
for (int i = 0; i < folderList.tagCount(); i++) {
CloneFolder f = new CloneFolder();
f.readNBT(folderList.getCompoundTagAt(i));
serverFolderNames.add(f.name);
}
validateFolder();
initGui();
} else if (compound.hasKey("ShortTags")) {
NBTTagList validTags = compound.getTagList("ShortTags", 10);
tagMap.clear();
@@ -193,6 +329,12 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiFolderSelect) {
SubGuiFolderSelect sel = (SubGuiFolderSelect) subgui;
if (sel.selectedFolder != null) {
folder = sel.selectedFolder;
}
}
initGui();
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,67 @@
package noppes.npcs.client.gui;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.data.CloneFolder;
public class SubGuiCloneFolderName extends SubGuiInterface {
private String originalName;
public boolean cancelled = true;
private String folderName = "";
public SubGuiCloneFolderName(String existingName) {
this.originalName = existingName;
this.folderName = existingName;
xSize = 200;
ySize = 80;
this.closeOnEsc = true;
}
@Override
public void initGui() {
super.initGui();
String title = isRename() ? "Rename Folder" : "New Folder";
addLabel(new GuiNpcLabel(0, title, guiLeft + 5, guiTop + 5));
addTextField(new GuiNpcTextField(0, this, fontRendererObj, guiLeft + 5, guiTop + 20, 190, 20, folderName));
addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 50, 90, 20, "gui.done"));
addButton(new GuiNpcButton(1, guiLeft + 100, guiTop + 50, 90, 20, "gui.cancel"));
}
@Override
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == 0) {
// Done
folderName = getTextField(0).getText().trim();
if (CloneFolder.isValidName(folderName)) {
cancelled = false;
close();
}
}
if (guibutton.id == 1) {
// Cancel
cancelled = true;
close();
}
}
public boolean isRename() {
return originalName != null && !originalName.isEmpty();
}
public String getFolderName() {
return folderName;
}
public String getOriginalName() {
return originalName;
}
@Override
public void save() {
}
}
@@ -0,0 +1,74 @@
package noppes.npcs.client.gui;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.ArrayList;
import java.util.List;
public class SubGuiFolderSelect extends SubGuiInterface implements ICustomScrollListener {
public String selectedFolder;
private final List<String> folderList;
private GuiCustomScroll folderScroll;
public SubGuiFolderSelect(List<String> folders, String currentSelection) {
this.folderList = new ArrayList<>(folders);
this.selectedFolder = currentSelection;
setBackground("menubg.png");
xSize = 200;
ySize = 220;
closeOnEsc = true;
}
@Override
public void initGui() {
super.initGui();
folderScroll = new GuiCustomScroll(this, 0);
folderScroll.setSize(xSize - 8, ySize - 50);
folderScroll.guiLeft = guiLeft + 4;
folderScroll.guiTop = guiTop + 4;
folderScroll.setList(new ArrayList<>(folderList));
if (selectedFolder != null) {
folderScroll.setSelected(selectedFolder);
}
addScroll(folderScroll);
int btnW = (xSize - 12) / 2;
addButton(new GuiNpcButton(0, guiLeft + 4, guiTop + ySize - 44, btnW, 20, "gui.done"));
addButton(new GuiNpcButton(1, guiLeft + 4 + btnW + 4, guiTop + ySize - 44, btnW, 20, "gui.cancel"));
getButton(0).enabled = folderScroll.hasSelected();
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
getButton(0).enabled = folderScroll.hasSelected();
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) {
selectedFolder = selection;
close();
}
@Override
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == 0) {
selectedFolder = folderScroll.getSelected();
close();
}
if (guibutton.id == 1) {
selectedFolder = null;
close();
}
}
@Override
public void save() {
}
}
@@ -0,0 +1,57 @@
package noppes.npcs.client.gui;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.SubGuiInterface;
public class SubGuiMoveConfirm extends SubGuiInterface {
public boolean confirmed = false;
private final int count;
public final int destTab;
public final String destFolder;
public SubGuiMoveConfirm(int count, int destTab, String destFolder) {
this.count = count;
this.destTab = destTab;
this.destFolder = destFolder;
xSize = 220;
ySize = 90;
closeOnEsc = true;
}
@Override
public void initGui() {
super.initGui();
String line1 = "Move " + count + " clone" + (count != 1 ? "s" : "") + " to:";
addLabel(new GuiNpcLabel(0, line1, guiLeft + 10, guiTop + 10, 0xFFFFFF));
String dest;
if (destFolder != null) {
dest = "Folder: \"" + destFolder + "\"";
} else {
dest = "Tab: " + destTab;
}
addLabel(new GuiNpcLabel(1, " " + dest, guiLeft + 10, guiTop + 25, 0xFFFFFF));
addButton(new GuiNpcButton(0, guiLeft + 10, guiTop + 55, 95, 20, "gui.yes"));
addButton(new GuiNpcButton(1, guiLeft + 115, guiTop + 55, 95, 20, "gui.cancel"));
}
@Override
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == 0) {
confirmed = true;
close();
}
if (guibutton.id == 1) {
close();
}
}
@Override
public void save() {
}
}
@@ -3,10 +3,14 @@ package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.ability.AbilitySlot;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.AbilitiesGetAllPacket;
import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcGetPacket;
import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcSavePacket;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket;
import kamkeel.npcs.util.Register;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.resources.I18n;
import net.minecraft.nbt.NBTTagCompound;
@@ -26,11 +30,7 @@ import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.constants.EnumScrollData;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.Vector;
import java.util.*;
/**
* GUI for managing NPC abilities.
@@ -43,6 +43,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
// All available ability types (typeId -> index)
private final HashMap<String, Integer> allAbilityTypes = new HashMap<>();
private final HashMap<String, Integer> filteredAbilityTypes = new HashMap<>();
// Display name to typeId mapping for the available types scroll
private final HashMap<String, String> displayNameToTypeId = new HashMap<>();
@@ -58,10 +59,42 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
private String search = "";
private int selectedAbilityIndex = -1;
// Existing preset names for duplicate checking
private final Set<String> existingPresetNames = new HashSet<>();
// Pending variant selection
private String pendingTypeId = null;
public static int modIndex = 0;
public static ScrollType scrollType = ScrollType.CNPC;
public GuiNPCAbilities(EntityNPCInterface npc) {
super(npc);
PacketClient.sendClient(new AbilitiesGetAllPacket());
PacketClient.sendClient(new AbilitiesNpcGetPacket());
PacketClient.sendClient(new CustomAbilitiesGetPacket());
}
public enum ScrollType {
CNPC,
MODDED,
ALL;
@Override
public String toString() {
switch (this) {
case CNPC: return "CustomNPCs";
case MODDED:
if (Register.isEmpty("ability"))
return "modded";
String namespace = Register.REGISTERED_NAMESPACES.get("ability").get(modIndex);
String displayName = Register.NAMESPACE_DISPLAY_NAMES.get(namespace);
return displayName != null ? displayName : namespace;
case ALL: return "filter.all";
default: return name();
}
}
}
@Override
@@ -70,25 +103,27 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
int y = guiTop + 10;
// Enabled checkbox
addLabel(new GuiNpcLabel(100, "gui.enabled", guiLeft + 5, y + 5));
addButton(new GuiNpcButton(100, guiLeft + 55, y, 50, 20, new String[]{"gui.no", "gui.yes"}, abilitiesEnabled ? 1 : 0));
addButton(new GuiNpcButton(50, guiLeft + 5, y, 140, 20, scrollType.toString()));
// Cooldown range: Min Cooldown and Max Cooldown (spaced apart more)
addLabel(new GuiNpcLabel(101, "ability.minCooldown", guiLeft + 115, y + 5));
GuiNpcTextField minField = new GuiNpcTextField(101, this, fontRendererObj, guiLeft + 165, y, 40, 20, "" + minCooldown);
addLabel(new GuiNpcLabel(101, "ability.minCooldown", guiLeft + 210, y + 5));
GuiNpcTextField minField = new GuiNpcTextField(101, this, fontRendererObj, guiLeft + 260, y, 40, 20, "" + minCooldown);
minField.setIntegersOnly();
minField.setMinMaxDefault(0, 10000, 20);
addTextField(minField);
addLabel(new GuiNpcLabel(102, "ability.maxCooldown", guiLeft + 260, y + 5));
GuiNpcTextField maxField = new GuiNpcTextField(102, this, fontRendererObj, guiLeft + 310, y, 40, 20, "" + maxCooldown);
addLabel(new GuiNpcLabel(102, "ability.maxCooldown", guiLeft + 320, y + 5));
GuiNpcTextField maxField = new GuiNpcTextField(102, this, fontRendererObj, guiLeft + 370, y, 40, 20, "" + maxCooldown);
maxField.setIntegersOnly();
maxField.setMinMaxDefault(0, 10000, 60);
addTextField(maxField);
y += 28;
// Enabled checkbox
addButton(new GuiNpcButton(100, guiLeft + 334, y + 145, 76, 20, new String[]{"gui.disabled", "gui.enabled"}, abilitiesEnabled ? 1 : 0));
getButton(100).packedFGColour = abilitiesEnabled ? 0x00FF00 : 0xFF0000;
// Left scroll: available ability types
addLabel(new GuiNpcLabel(1, "ability.availableTypes", guiLeft + 5, y));
if (availableTypesScroll == null) {
@@ -107,9 +142,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
addLabel(new GuiNpcLabel(2, "ability.npcAbilities", guiLeft + 210, y));
if (npcAbilitiesScroll == null) {
npcAbilitiesScroll = new GuiCustomScroll(this, 1);
npcAbilitiesScroll.setSize(160, 130);
npcAbilitiesScroll.setSize(200, 130);
} else {
npcAbilitiesScroll.setSize(160, 130);
npcAbilitiesScroll.setSize(200, 130);
}
npcAbilitiesScroll.guiLeft = guiLeft + 210;
npcAbilitiesScroll.guiTop = y + 12;
@@ -118,11 +153,12 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
// Center buttons: Add/Remove
int centerX = guiLeft + 158;
addButton(new GuiNpcButton(70, centerX, y + 40, 40, 20, ">>>")); // Add
addButton(new GuiNpcButton(71, centerX, y + 62, 40, 20, "<<<")); // Remove
addButton(new GuiNpcButton(70, centerX, y + 15, 40, 20, ">>>")); // Add
addButton(new GuiNpcButton(71, centerX, y + 37, 40, 20, "<<<")); // Remove
getButton(71).setEnabled(selectedAbilityIndex >= 0);
// Load button (under the add/remove arrows)
addButton(new GuiNpcButton(75, centerX, y + 90, 40, 20, "gui.load"));
addButton(new GuiNpcButton(75, centerX, y + 60, 40, 20, "gui.load"));
// On/Off toggle for selected ability (under Load button)
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) {
@@ -143,7 +179,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
getButton(74).setEnabled(selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size() - 1);
// Save button (to the right of carrots, only enabled when ability is selected)
addButton(new GuiNpcButton(76, guiLeft + 320, y + 145, 50, 20, "gui.save"));
addButton(new GuiNpcButton(76, centerX, y + 82, 40, 20, "gui.save"));
getButton(76).setEnabled(selectedAbilityIndex >= 0);
}
@@ -154,6 +190,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
// Enabled toggle
if (id == 100) {
abilitiesEnabled = ((GuiNpcButton) guibutton).getValue() == 1;
initGui();
save();
return;
}
@@ -164,8 +201,17 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
String displayName = availableTypesScroll.getSelected();
String typeId = displayNameToTypeId.get(displayName);
if (typeId != null) {
java.util.List<AbilityVariant> variants = AbilityController.Instance.getVariantsForType(typeId);
if (variants.size() > 1) {
pendingTypeId = typeId;
setSubGui(new SubGuiAbilityVariantSelect(variants));
return;
}
Ability newAbility = AbilityController.Instance.create(typeId);
if (newAbility != null) {
if (variants.size() == 1) {
variants.get(0).apply(newAbility);
}
newAbility.setId(UUID.randomUUID().toString());
npcSlots.add(AbilitySlot.inline(newAbility));
selectedAbilityIndex = npcSlots.size() - 1;
@@ -252,7 +298,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
if (abilityToSave.getName() == null || abilityToSave.getName().isEmpty()) {
setSubGui(abilityToSave.createConfigGui(this));
} else {
setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave));
setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave, null, existingPresetNames));
}
}
}
@@ -274,6 +320,40 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
return;
}
if (id == 50) {
if (scrollType != ScrollType.MODDED) {
ScrollType[] values = ScrollType.values();
ScrollType next = values[(scrollType.ordinal() + 1) % values.length];
// Skip MODDED if no namespaces are registered
if (next == ScrollType.MODDED && Register.isEmpty("ability")) {
next = ScrollType.ALL;
}
scrollType = next;
} else {
List<String> list = Register.REGISTERED_NAMESPACES.get("ability");
if (list != null && !list.isEmpty()) {
if (modIndex == list.size() - 1) {
scrollType = ScrollType.ALL;
} else {
modIndex = (modIndex + 1) % list.size();
}
} else {
modIndex = 0;
scrollType = ScrollType.ALL;
}
}
Map<String, Integer> dummyMap = new HashMap<>(allAbilityTypes);
filteredAbilityTypes.clear();
filteredAbilityTypes.putAll(getFilteredData(dummyMap));
// Reset scroll position when changing category
if (availableTypesScroll != null) {
availableTypesScroll.resetScroll();
}
}
initGui();
}
@@ -282,9 +362,21 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
if (type == EnumScrollData.ABILITY_TYPES) {
allAbilityTypes.clear();
allAbilityTypes.putAll(data);
filteredAbilityTypes.putAll(getFilteredData(allAbilityTypes));
if (availableTypesScroll != null) {
availableTypesScroll.setList(getFilteredTypeList());
}
} else if (type == EnumScrollData.CUSTOM_ABILITIES) {
existingPresetNames.clear();
for (String key : data.keySet()) {
int tabIndex = key.indexOf('\t');
if (tabIndex > 0) {
existingPresetNames.add(key.substring(0, tabIndex));
} else {
existingPresetNames.add(key);
}
}
}
initGui();
}
@@ -340,10 +432,35 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
}
}
private HashMap<String, Integer> getFilteredData(Map<String, Integer> data) {
HashMap<String, Integer> filteredData = new HashMap<>();
if (scrollType == ScrollType.CNPC) {
data.entrySet().stream()
.filter(e -> e.getKey().startsWith("ability.cnpc."))
.forEach(e -> filteredData.put(e.getKey(), e.getValue()));
} else if (scrollType == ScrollType.MODDED) {
if (!Register.isEmpty("ability")) {
List<String> registerList = Register.REGISTERED_NAMESPACES.get("ability");
if (!registerList.isEmpty()) {
String namespace = registerList.get(modIndex);
data.entrySet().stream()
.filter(e -> e.getKey().startsWith("ability." + namespace + "."))
.forEach(e -> filteredData.put(e.getKey(), e.getValue()));
}
}
} else {
filteredData.putAll(data);
}
return filteredData;
}
private List<String> getFilteredTypeList() {
List<String> list = new ArrayList<>();
displayNameToTypeId.clear();
for (String typeId : allAbilityTypes.keySet()) {
for (String typeId : filteredAbilityTypes.keySet()) {
String displayName = I18n.format(typeId);
// Search matches either the display name or the typeId
if (search.isEmpty() || displayName.toLowerCase().contains(search) || typeId.toLowerCase().contains(search)) {
@@ -529,7 +646,24 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiAbilityEditMode) {
if (subgui instanceof SubGuiAbilityVariantSelect) {
SubGuiAbilityVariantSelect variantGui = (SubGuiAbilityVariantSelect) subgui;
int idx = variantGui.getSelectedIndex();
if (idx >= 0 && pendingTypeId != null) {
Ability newAbility = AbilityController.Instance.create(pendingTypeId);
if (newAbility != null) {
variantGui.getVariants().get(idx).apply(newAbility);
newAbility.setId(UUID.randomUUID().toString());
npcSlots.add(AbilitySlot.inline(newAbility));
selectedAbilityIndex = npcSlots.size() - 1;
updateNpcAbilitiesList();
selectAbilityByIndex(selectedAbilityIndex);
save();
}
}
pendingTypeId = null;
initGui();
} else if (subgui instanceof SubGuiAbilityEditMode) {
int mode = ((SubGuiAbilityEditMode) subgui).getResult();
if (mode < 0) return; // cancelled
@@ -568,7 +702,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
AbilitySlot slot = npcSlots.get(selectedAbilityIndex);
if (slot.isReference()) {
// For reference slots, save back to controller
// (The resolved copy was edited in-place)
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
} else {
// For inline slots, replace with the updated ability
npcSlots.set(selectedAbilityIndex, AbilitySlot.inline(ability));
File diff suppressed because it is too large. Load diff
@@ -10,6 +10,7 @@ import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IScrollData;
@@ -39,6 +40,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
private HashMap<String, Integer> rawData = new HashMap<>();
private GuiCustomScroll scroll;
private String search = "";
private boolean waitingForLoad = false;
private int pendingLoadMode = -1;
@@ -48,7 +50,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
setBackground("menubg.png");
xSize = 220;
ySize = 180;
ySize = 216;
PacketClient.sendClient(new CustomAbilitiesGetPacket());
}
@@ -59,7 +61,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
setBackground("menubg.png");
xSize = 220;
ySize = 180;
ySize = 216;
PacketClient.sendClient(new CustomAbilitiesGetPacket());
}
@@ -75,7 +77,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
scroll.setSize(200, 110);
scroll.setSize(200, 140);
}
scroll.guiLeft = guiLeft + 10;
scroll.guiTop = y;
@@ -85,7 +87,12 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
}
addScroll(scroll);
y += 115;
y += 143;
// Search bar
addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 10, y, 200, 20, search));
y += 24;
addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "gui.load"));
addButton(new GuiNpcButton(2, guiLeft + 115, y, 95, 20, "gui.cancel"));
@@ -94,7 +101,16 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
}
private List<String> getFilteredList() {
return new ArrayList<>(displayToUuid.keySet());
if (search.isEmpty()) {
return new ArrayList<>(displayToUuid.keySet());
}
List<String> list = new ArrayList<>();
for (String name : displayToUuid.keySet()) {
if (name.toLowerCase().contains(search.toLowerCase())) {
list.add(name);
}
}
return list;
}
@Override
@@ -116,6 +132,19 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
}
}
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(10) != null && getTextField(10).isFocused()) {
String newSearch = getTextField(10).getText();
if (!search.equals(newSearch)) {
search = newSearch;
scroll.resetScroll();
scroll.setList(getFilteredList());
}
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiAbilityLoadMode) {
@@ -7,24 +7,29 @@ import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.Set;
/**
* Confirmation dialog for saving an ability preset.
* Uses packet-based communication for proper client-server architecture.
*/
public class SubGuiAbilitySaveConfirm extends SubGuiInterface {
public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGuiListener {
private final Ability ability;
private final IAbilityConfigCallback callback;
private final Set<String> existingNames;
public SubGuiAbilitySaveConfirm(Ability ability) {
this(ability, null);
this(ability, null, null);
}
public SubGuiAbilitySaveConfirm(Ability ability, IAbilityConfigCallback callback) {
public SubGuiAbilitySaveConfirm(Ability ability, IAbilityConfigCallback callback, Set<String> existingNames) {
this.ability = ability;
this.callback = callback;
this.existingNames = existingNames;
setBackground("menubg.png");
xSize = 200;
@@ -52,14 +57,32 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface {
int id = guibutton.id;
if (id == 0) {
// Save the ability via packet
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
if (callback != null) {
callback.onAbilitySaved(ability);
if (existingNames != null && existingNames.contains(ability.getName())) {
setSubGui(new SubGuiDuplicateNameConfirm());
return;
}
close();
doSave();
} else if (id == 1) {
close();
}
}
private void doSave() {
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
if (callback != null) {
callback.onAbilitySaved(ability);
}
close();
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiDuplicateNameConfirm) {
if (((SubGuiDuplicateNameConfirm) subgui).isConfirmed()) {
doSave();
} else {
close();
}
}
}
}
@@ -0,0 +1,125 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.resources.I18n;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* SubGui for selecting an ability type when creating a new ability.
*/
public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener {
private GuiCustomScroll scroll;
private final HashMap<String, String> displayNameToTypeId = new HashMap<>();
private final HashMap<String, String> allDisplayNameToTypeId = new HashMap<>();
private String selectedTypeId = null;
private String search = "";
public SubGuiAbilityTypeSelect() {
setBackground("menubg.png");
xSize = 200;
ySize = 216;
}
@Override
public void initGui() {
super.initGui();
addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 5, guiTop + 5, 190, 18, search));
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
scroll.setSize(190, 145);
}
scroll.guiLeft = guiLeft + 5;
scroll.guiTop = guiTop + 26;
addScroll(scroll);
buildAllTypes();
scroll.setList(getFilteredTypeList());
addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.add"));
getButton(0).setEnabled(scroll.hasSelected());
addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel"));
}
private void buildAllTypes() {
allDisplayNameToTypeId.clear();
String[] types = AbilityController.Instance.getTypes();
for (String typeId : types) {
String displayName = I18n.format(typeId);
allDisplayNameToTypeId.put(displayName, typeId);
}
}
private List<String> getFilteredTypeList() {
List<String> list = new ArrayList<>();
displayNameToTypeId.clear();
for (Map.Entry<String, String> entry : allDisplayNameToTypeId.entrySet()) {
String displayName = entry.getKey();
if (search.isEmpty() || displayName.toLowerCase().contains(search) || entry.getValue().toLowerCase().contains(search)) {
list.add(displayName);
displayNameToTypeId.put(displayName, entry.getValue());
}
}
return list;
}
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0 && scroll.hasSelected()) {
String displayName = scroll.getSelected();
selectedTypeId = displayNameToTypeId.get(displayName);
close();
} else if (guibutton.id == 1) {
selectedTypeId = null;
close();
}
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 0) {
getButton(0).setEnabled(scroll.hasSelected());
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 0 && selection != null) {
selectedTypeId = displayNameToTypeId.get(selection);
close();
}
}
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(10) != null && getTextField(10).isFocused()) {
if (!search.equals(getTextField(10).getText())) {
search = getTextField(10).getText().toLowerCase();
scroll.setList(getFilteredTypeList());
scroll.resetScroll();
}
}
}
@Override
public void unFocused(GuiNpcTextField textField) {
}
public String getSelectedTypeId() {
return selectedTypeId;
}
}
@@ -0,0 +1,154 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.ArrayList;
import java.util.List;
/**
* SubGui for selecting a variant/template when creating a new ability.
* Uses a scroll list with group headers for external addon variants.
*/
public class SubGuiAbilityVariantSelect extends SubGuiInterface implements ICustomScrollListener {
private final List<AbilityVariant> variants;
private int selectedIndex = -1;
// Maps each scroll list index to a variant list index (-1 for non-selectable entries)
private final List<Integer> scrollToVariantIndex = new ArrayList<>();
public SubGuiAbilityVariantSelect(List<AbilityVariant> variants) {
this.variants = variants;
setBackground("menubg.png");
xSize = 200;
ySize = 216;
}
@Override
public void initGui() {
super.initGui();
addLabel(new GuiNpcLabel(0, "ability.selectVariant", guiLeft + 10, guiTop + 8));
// Build the unsorted scroll list with group headers
List<String> scrollList = new ArrayList<>();
scrollToVariantIndex.clear();
boolean hasBaseVariants = false;
boolean hasGroupedVariants = false;
for (AbilityVariant v : variants) {
if (v.getGroup() == null)
hasBaseVariants = true;
else
hasGroupedVariants = true;
}
// Add base (non-grouped) variants first
for (int i = 0; i < variants.size(); i++) {
if (variants.get(i).getGroup() == null) {
scrollList.add(variants.get(i).getDisplayKey());
scrollToVariantIndex.add(i);
}
}
// Blank separator between base and grouped variants
if (hasBaseVariants && hasGroupedVariants) {
scrollList.add("");
scrollToVariantIndex.add(-1);
}
// Add grouped variants with group headers
String lastGroup = null;
for (int i = 0; i < variants.size(); i++) {
AbilityVariant v = variants.get(i);
if (v.getGroup() == null)
continue;
if (!v.getGroup().equals(lastGroup)) {
scrollList.add(v.getGroup());
scrollToVariantIndex.add(-1);
lastGroup = v.getGroup();
}
scrollList.add(v.getDisplayKey());
scrollToVariantIndex.add(i);
}
GuiCustomScroll scroll = new GuiCustomScroll(this, 0);
scroll.guiLeft = guiLeft + 5;
scroll.guiTop = guiTop + 22;
scroll.setUnsortedList(scrollList);
scroll.setSize(190, 155);
// Mark blank separators and group headers as non-interactive colored entries
scroll.colors.put("", 0x000000);
if (lastGroup != null) {
for (int i = 0; i < variants.size(); i++) {
String group = variants.get(i).getGroup();
if (group != null)
scroll.colors.put(group, 0xFFFF00); // Yellow
}
}
// Restore selection in scroll
if (selectedIndex >= 0) {
for (int s = 0; s < scrollToVariantIndex.size(); s++) {
if (scrollToVariantIndex.get(s) == selectedIndex) {
scroll.selected = s;
break;
}
}
}
addScroll(scroll);
// Select / Cancel buttons
addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.select"));
getButton(0).setEnabled(selectedIndex >= 0);
addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel"));
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
if (scroll.id == 0 && scroll.selected >= 0 && scroll.selected < scrollToVariantIndex.size()) {
int variantIdx = scrollToVariantIndex.get(scroll.selected);
if (variantIdx >= 0) {
selectedIndex = variantIdx;
getButton(0).setEnabled(true);
}
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
if (selectedIndex >= 0) {
close();
}
}
@Override
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
if (id == 0 && selectedIndex >= 0) {
close();
} else if (id == 1) {
selectedIndex = -1;
close();
}
}
public int getSelectedIndex() {
return selectedIndex;
}
public List<AbilityVariant> getVariants() {
return variants;
}
}
@@ -0,0 +1,47 @@
package noppes.npcs.client.gui.advanced;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.SubGuiInterface;
/**
* Confirmation dialog shown when saving an ability preset with a name that already exists.
*/
public class SubGuiDuplicateNameConfirm extends SubGuiInterface {
private boolean confirmed = false;
public SubGuiDuplicateNameConfirm() {
setBackground("menubg.png");
xSize = 220;
ySize = 80;
}
@Override
public void initGui() {
super.initGui();
int y = guiTop + 10;
addLabel(new GuiNpcLabel(0, "ability.duplicate.name", guiLeft + 10, y));
y += 30;
addButton(new GuiNpcButton(0, guiLeft + 20, y, 80, 20, "gui.continue"));
addButton(new GuiNpcButton(1, guiLeft + 120, y, 80, 20, "gui.cancel"));
}
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0) {
confirmed = true;
close();
} else if (guibutton.id == 1) {
confirmed = false;
close();
}
}
public boolean isConfirmed() {
return confirmed;
}
}
@@ -1,92 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilityCharge;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Charge ability type-specific settings.
*/
public class SubGuiAbilityCharge extends SubGuiAbilityConfig {
private final AbilityCharge charge;
public SubGuiAbilityCharge(AbilityCharge ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.charge = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Speed
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, charge.getDamage()));
addLabel(new GuiNpcLabel(101, "stats.speed", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, charge.getChargeSpeed()));
y += 24;
// Row 2: Knockback
addLabel(new GuiNpcLabel(102, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, charge.getKnockback()));
y += 24;
// Row 3: Hit Width + Effects
addLabel(new GuiNpcLabel(104, "ability.hitWidth", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, charge.getHitWidth()));
addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects"));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
if (id == 150) {
setSubGui(new SubGuiAbilityEffects(charge.getEffects()));
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
super.subGuiClosed(subgui);
if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
charge.setEffects(result);
}
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
charge.setDamage(parseFloat(field, charge.getDamage()));
break;
case 101:
charge.setChargeSpeed(parseFloat(field, charge.getChargeSpeed()));
break;
case 102:
charge.setKnockback(parseFloat(field, charge.getKnockback()));
break;
case 104:
charge.setHitWidth(parseFloat(field, charge.getHitWidth()));
break;
}
}
}
@@ -1,141 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilityCutter;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Cutter ability type-specific settings.
*/
public class SubGuiAbilityCutter extends SubGuiAbilityConfig {
private final AbilityCutter cutter;
public SubGuiAbilityCutter(AbilityCutter ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.cutter = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Range
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, cutter.getDamage()));
addLabel(new GuiNpcLabel(101, "gui.range", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, cutter.getRange()));
y += 24;
// Row 2: Arc Angle + Inner Radius
addLabel(new GuiNpcLabel(102, "ability.arcAngle", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, cutter.getArcAngle()));
addLabel(new GuiNpcLabel(103, "ability.innerRadius", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, cutter.getInnerRadius()));
y += 24;
// Row 3: Knockback + Sweep Speed
addLabel(new GuiNpcLabel(104, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, cutter.getKnockback()));
addLabel(new GuiNpcLabel(105, "ability.sweepSpeed", col2LabelX, y + 5));
addTextField(createFloatField(105, col2FieldX, y, 50, cutter.getSweepSpeed()));
y += 24;
// Row 4: Sweep Mode + Piercing
addLabel(new GuiNpcLabel(106, "ability.sweepMode", labelX, y + 5));
String[] sweepModes = {"Swipe", "Spin"};
GuiNpcButton sweepModeBtn = new GuiNpcButton(106, fieldX, y, 70, 20, sweepModes, cutter.getSweepModeEnum().ordinal());
sweepModeBtn.setHoverText("ability.hover.sweepMode");
addButton(sweepModeBtn);
addLabel(new GuiNpcLabel(107, "ability.piercing", col2LabelX, y + 5));
GuiNpcButton piercingBtn = new GuiNpcButton(107, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, cutter.isPiercing() ? 1 : 0);
piercingBtn.setHoverText("ability.hover.piercing");
addButton(piercingBtn);
y += 24;
// Row 5: Spin Duration (only for SPIN mode) + Effects button
if (cutter.getSweepModeEnum() == AbilityCutter.SweepMode.SPIN) {
addLabel(new GuiNpcLabel(108, "ability.duration", labelX, y + 5));
GuiNpcTextField durationField = createIntField(108, fieldX, y, 50, cutter.getSpinDurationTicks());
durationField.setMinMaxDefault(1, 1000, 60);
addTextField(durationField);
}
addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects"));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 106:
cutter.setSweepModeEnum(AbilityCutter.SweepMode.values()[value]);
initGui(); // Refresh to show/hide duration field
break;
case 107:
cutter.setPiercing(value == 1);
break;
case 150:
setSubGui(new SubGuiAbilityEffects(cutter.getEffects()));
break;
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
super.subGuiClosed(subgui);
if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
cutter.setEffects(result);
}
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
cutter.setDamage(parseFloat(field, cutter.getDamage()));
break;
case 101:
cutter.setRange(parseFloat(field, cutter.getRange()));
break;
case 102:
cutter.setArcAngle(parseFloat(field, cutter.getArcAngle()));
break;
case 103:
cutter.setInnerRadius(parseFloat(field, cutter.getInnerRadius()));
break;
case 104:
cutter.setKnockback(parseFloat(field, cutter.getKnockback()));
break;
case 105:
cutter.setSweepSpeed(parseFloat(field, cutter.getSweepSpeed()));
break;
case 108:
cutter.setSpinDurationTicks(field.getInteger());
break;
}
}
}
@@ -1,65 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityDash;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Dash ability type-specific settings.
*/
public class SubGuiAbilityDash extends SubGuiAbilityConfig {
private final AbilityDash dash;
public SubGuiAbilityDash(AbilityDash ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.dash = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Dash Mode
addLabel(new GuiNpcLabel(100, "ability.mode", labelX, y + 5));
String[] dashModes = {"Aggressive", "Defensive"};
GuiNpcButton modeBtn = new GuiNpcButton(100, fieldX, y, 80, 20, dashModes, dash.getDashModeEnum().ordinal());
modeBtn.setHoverText("ability.hover.dashMode");
addButton(modeBtn);
y += 24;
// Row 2: Dash Distance + Dash Speed
addLabel(new GuiNpcLabel(101, "ability.dashDist", labelX, y + 5));
addTextField(createFloatField(101, fieldX, y, 50, dash.getDashDistance()));
addLabel(new GuiNpcLabel(102, "ability.dashSpeed", col2LabelX, y + 5));
addTextField(createFloatField(102, col2FieldX, y, 50, dash.getDashSpeed()));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
if (id == 100) {
dash.setDashModeEnum(AbilityDash.DashMode.values()[button.getValue()]);
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 101:
dash.setDashDistance(parseFloat(field, dash.getDashDistance()));
break;
case 102:
dash.setDashSpeed(parseFloat(field, dash.getDashSpeed()));
break;
}
}
}
@@ -1,323 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.type.AbilityDisc;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Disc ability type-specific settings.
*/
public class SubGuiAbilityDisc extends SubGuiAbilityConfig {
private final AbilityDisc disc;
private int editingVisualColorId = 0;
public SubGuiAbilityDisc(AbilityDisc ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.disc = ability;
}
@Override
protected boolean hasVisualSettings() {
return true;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Speed
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, disc.getDamage()));
addLabel(new GuiNpcLabel(101, "stats.speed", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, disc.getSpeed()));
y += 24;
// Row 2: Disc Radius + Disc Thickness
addLabel(new GuiNpcLabel(102, "ability.discRadius", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, disc.getDiscRadius()));
addLabel(new GuiNpcLabel(103, "ability.discThickness", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, disc.getDiscThickness()));
y += 24;
// Row 3: Homing + Homing Strength (only show strength if homing)
addLabel(new GuiNpcLabel(104, "ability.homing", labelX, y + 5));
GuiNpcButton homingBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, disc.isHoming() ? 1 : 0);
homingBtn.setHoverText("ability.hover.homing");
addButton(homingBtn);
if (disc.isHoming()) {
addLabel(new GuiNpcLabel(105, "ability.homingStr", col2LabelX, y + 5));
addTextField(createFloatField(105, col2FieldX, y, 50, disc.getHomingStrength()));
}
y += 24;
// Row 4: Boomerang + Boomerang Delay (only show delay if boomerang)
addLabel(new GuiNpcLabel(106, "ability.boomerang", labelX, y + 5));
GuiNpcButton boomerangBtn = new GuiNpcButton(106, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, disc.isBoomerang() ? 1 : 0);
boomerangBtn.setHoverText("ability.hover.boomerang");
addButton(boomerangBtn);
if (disc.isBoomerang()) {
addLabel(new GuiNpcLabel(107, "ability.boomerangDelay", col2LabelX, y + 5));
addTextField(createIntField(107, col2FieldX, y, 50, disc.getBoomerangDelay()));
}
y += 24;
// Row 5: Explosive + Explosion Radius (only show radius if explosive)
addLabel(new GuiNpcLabel(108, "ability.explosive", labelX, y + 5));
GuiNpcButton explosiveBtn = new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, disc.isExplosive() ? 1 : 0);
explosiveBtn.setHoverText("ability.hover.explosive");
addButton(explosiveBtn);
if (disc.isExplosive()) {
addLabel(new GuiNpcLabel(109, "ability.explosionRad", col2LabelX, y + 5));
addTextField(createFloatField(109, col2FieldX, y, 50, disc.getExplosionRadius()));
}
y += 24;
// Row 6: Knockback + Max Distance
addLabel(new GuiNpcLabel(110, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(110, fieldX, y, 50, disc.getKnockback()));
addLabel(new GuiNpcLabel(111, "ability.maxDist", col2LabelX, y + 5));
addTextField(createFloatField(111, col2FieldX, y, 50, disc.getMaxDistance()));
y += 24;
// Row 7: Max Lifetime + Effects button
addLabel(new GuiNpcLabel(112, "ability.lifetime", labelX, y + 5));
addTextField(createIntField(112, fieldX, y, 50, disc.getMaxLifetime()));
addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects"));
}
@Override
protected void initVisualTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 180;
int col2FieldX = guiLeft + 260;
// Row 1: Anchor Point
addLabel(new GuiNpcLabel(210, "ability.anchorPoint", labelX, y + 5));
GuiNpcButton anchorBtn = new GuiNpcButton(210, fieldX, y, 80, 20, AnchorPoint.getDisplayNames(), disc.getAnchorPointEnum().ordinal());
anchorBtn.setHoverText("ability.hover.anchorPoint");
addButton(anchorBtn);
y += 24;
// Row 2: Inner Color + Outer Color
addLabel(new GuiNpcLabel(200, "ability.innerColor", labelX, y + 5));
String innerHex = String.format("%06X", disc.getInnerColor() & 0xFFFFFF);
GuiNpcButton innerColorBtn = new GuiNpcButton(200, fieldX, y, 55, 20, innerHex);
innerColorBtn.setTextColor(disc.getInnerColor() & 0xFFFFFF);
addButton(innerColorBtn);
addLabel(new GuiNpcLabel(201, "ability.outerColor", col2LabelX, y + 5));
String outerHex = String.format("%06X", disc.getOuterColor() & 0xFFFFFF);
GuiNpcButton outerColorBtn = new GuiNpcButton(201, col2FieldX, y, 55, 20, outerHex);
outerColorBtn.setTextColor(disc.getOuterColor() & 0xFFFFFF);
outerColorBtn.setEnabled(disc.isOuterColorEnabled());
addButton(outerColorBtn);
y += 24;
// Row 2: Outer Color Enabled + Outer Color Width
addLabel(new GuiNpcLabel(202, "ability.outerEnabled", labelX, y + 5));
addButton(new GuiNpcButton(202, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, disc.isOuterColorEnabled() ? 1 : 0));
addLabel(new GuiNpcLabel(203, "ability.outerWidth", col2LabelX, y + 5));
GuiNpcTextField widthField = createFloatField(203, col2FieldX, y, 55, disc.getOuterColorWidth());
widthField.setEnabled(disc.isOuterColorEnabled());
addTextField(widthField);
y += 24;
// Row 3: Outer Color Alpha
addLabel(new GuiNpcLabel(204, "ability.outerAlpha", labelX, y + 5));
GuiNpcTextField alphaField = createFloatField(204, fieldX, y, 55, disc.getOuterColorAlpha());
alphaField.setEnabled(disc.isOuterColorEnabled());
alphaField.setMinMaxDefaultFloat(0, 1, 0.5f);
addTextField(alphaField);
y += 24;
// Row 4: Rotation Speed
addLabel(new GuiNpcLabel(205, "ability.rotationSpeed", labelX, y + 5));
addTextField(createFloatField(205, fieldX, y, 50, disc.getRotationSpeed()));
y += 24;
// Row 5: Lightning Effect Enabled
addLabel(new GuiNpcLabel(206, "ability.lightning", labelX, y + 5));
GuiNpcButton lightningBtn = new GuiNpcButton(206, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, disc.hasLightningEffect() ? 1 : 0);
lightningBtn.setHoverText("ability.hover.lightning");
addButton(lightningBtn);
// Only show Lightning settings if Lightning is enabled
if (disc.hasLightningEffect()) {
y += 24;
// Row 6: Density + Radius
addLabel(new GuiNpcLabel(207, "ability.lightningDensity", labelX, y + 5));
GuiNpcTextField densityField = new GuiNpcTextField(207, this, fontRendererObj, fieldX, y, 55, 18, "" + disc.getLightningDensity());
densityField.setMinMaxDefaultFloat(0.01f, 5.0f, 0.15f);
addTextField(densityField);
addLabel(new GuiNpcLabel(208, "ability.lightningRadius", col2LabelX, y + 5));
GuiNpcTextField radiusField = new GuiNpcTextField(208, this, fontRendererObj, col2FieldX, y, 55, 18, "" + disc.getLightningRadius());
radiusField.setMinMaxDefaultFloat(0.1f, 10.0f, 0.5f);
addTextField(radiusField);
}
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 104:
disc.setHoming(value == 1);
initGui();
break;
case 106:
disc.setBoomerang(value == 1);
initGui();
break;
case 108:
disc.setExplosive(value == 1);
initGui();
break;
case 150:
setSubGui(new SubGuiAbilityEffects(disc.getEffects()));
break;
}
}
@Override
protected void handleVisualButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 200:
editingVisualColorId = 200;
setSubGui(new SubGuiColorSelector(disc.getInnerColor()));
break;
case 201:
editingVisualColorId = 201;
setSubGui(new SubGuiColorSelector(disc.getOuterColor()));
break;
case 202:
disc.setOuterColorEnabled(value == 1);
initGui();
break;
case 206:
disc.setLightningEffect(value == 1);
initGui();
break;
case 210:
disc.setAnchorPointEnum(AnchorPoint.fromOrdinal(value));
break;
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiColorSelector && editingVisualColorId != 0) {
SubGuiColorSelector colorSelector = (SubGuiColorSelector) subgui;
int rgb = colorSelector.color & 0x00FFFFFF;
if (editingVisualColorId == 200) {
disc.setInnerColor(rgb);
} else if (editingVisualColorId == 201) {
disc.setOuterColor(rgb);
}
editingVisualColorId = 0;
initGui();
} else if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
disc.setEffects(result);
}
} else {
super.subGuiClosed(subgui);
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
disc.setDamage(parseFloat(field, disc.getDamage()));
break;
case 101:
disc.setSpeed(parseFloat(field, disc.getSpeed()));
break;
case 102:
disc.setDiscRadius(parseFloat(field, disc.getDiscRadius()));
break;
case 103:
disc.setDiscThickness(parseFloat(field, disc.getDiscThickness()));
break;
case 105:
disc.setHomingStrength(parseFloat(field, disc.getHomingStrength()));
break;
case 107:
disc.setBoomerangDelay(field.getInteger());
break;
case 109:
disc.setExplosionRadius(parseFloat(field, disc.getExplosionRadius()));
break;
case 110:
disc.setKnockback(parseFloat(field, disc.getKnockback()));
break;
case 111:
disc.setMaxDistance(parseFloat(field, disc.getMaxDistance()));
break;
case 112:
disc.setMaxLifetime(field.getInteger());
break;
}
}
@Override
protected void handleVisualTextField(int id, GuiNpcTextField field) {
switch (id) {
case 203:
disc.setOuterColorWidth(parseFloat(field, disc.getOuterColorWidth()));
break;
case 204:
disc.setOuterColorAlpha(parseFloat(field, disc.getOuterColorAlpha()));
break;
case 205:
disc.setRotationSpeed(parseFloat(field, disc.getRotationSpeed()));
break;
case 207:
disc.setLightningDensity(parseFloat(field, disc.getLightningDensity()));
break;
case 208:
disc.setLightningRadius(parseFloat(field, disc.getLightningRadius()));
break;
}
}
}
@@ -1,202 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.ArrayList;
import java.util.List;
/**
* SubGui for editing ability effects (potion effects that apply to targets).
* Allows adding/removing effects and configuring type, duration, and amplifier.
*/
public class SubGuiAbilityEffects extends SubGuiInterface implements ITextfieldListener {
private static final int MAX_EFFECTS = 5;
// Effect type names for display
private static final String[] EFFECT_TYPE_NAMES = {
"gui.none",
"potion.moveSlowdown",
"potion.weakness",
"potion.poison",
"potion.wither",
"potion.blindness",
"potion.confusion",
"potion.hunger",
"potion.digSlowDown"
};
// Working copy of effects
private List<AbilityEffect> effects;
private boolean cancelled = false;
public SubGuiAbilityEffects(List<AbilityEffect> existingEffects) {
// Create working copies of effects
this.effects = new ArrayList<>();
if (existingEffects != null) {
for (AbilityEffect effect : existingEffects) {
this.effects.add(effect.copy());
}
}
setBackground("menubg.png");
xSize = 280;
ySize = 180;
}
@Override
public void initGui() {
super.initGui();
int y = guiTop + 8;
int labelX = guiLeft + 8;
// Title
addLabel(new GuiNpcLabel(0, "ability.effects", labelX, y));
y += 16;
// Column headers
addLabel(new GuiNpcLabel(1, "gui.type", guiLeft + 10, y));
addLabel(new GuiNpcLabel(2, "gui.duration", guiLeft + 115, y));
addLabel(new GuiNpcLabel(3, "gui.amp", guiLeft + 175, y));
y += 14;
// Effect rows
for (int i = 0; i < effects.size() && i < MAX_EFFECTS; i++) {
AbilityEffect effect = effects.get(i);
int baseId = 1 + i * 10;
// Type selector button
int typeIndex = effect.getType().ordinal();
GuiNpcButton typeBtn = new GuiNpcButton(baseId, guiLeft + 8, y, 100, 20, EFFECT_TYPE_NAMES, typeIndex);
typeBtn.setHoverText("effect.hover.type");
addButton(typeBtn);
// Duration text field
GuiNpcTextField durField = new GuiNpcTextField(baseId + 1, this, fontRendererObj,
guiLeft + 112, y, 50, 20, "" + effect.getDurationTicks());
durField.setIntegersOnly();
durField.setMinMaxDefault(1, 12000, 60);
durField.setHoverText("effect.hover.duration");
addTextField(durField);
// Amplifier selector (0-10)
String[] ampValues = new String[11];
for (int a = 0; a <= 10; a++) {
ampValues[a] = "" + a;
}
GuiNpcButton ampBtn = new GuiNpcButton(baseId + 2, guiLeft + 168, y, 40, 20, ampValues, effect.getAmplifier());
ampBtn.setHoverText("effect.hover.amplifier");
addButton(ampBtn);
// Delete button
addButton(new GuiNpcButton(baseId + 3, guiLeft + 215, y, 20, 20, "X"));
y += 24;
}
// Add button (if space available)
if (effects.size() < MAX_EFFECTS) {
addButton(new GuiNpcButton(100, guiLeft + 8, y, 50, 20, "gui.add"));
}
// Bottom buttons
addButton(new GuiNpcButton(65, guiLeft + 8, guiTop + ySize - 28, 60, 20, "gui.cancel"));
addButton(new GuiNpcButton(66, guiLeft + xSize - 68, guiTop + ySize - 28, 60, 20, "gui.done"));
}
@Override
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
// Add button
if (id == 100) {
if (effects.size() < MAX_EFFECTS) {
// Add new effect with default values (Slowness, 60 ticks, amp 0)
effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 60, 0));
initGui();
}
return;
}
// Cancel button
if (id == 65) {
cancelled = true;
close();
return;
}
// Done button
if (id == 66) {
// Remove any NONE effects before saving
effects.removeIf(e -> !e.isValid());
cancelled = false;
close();
return;
}
// Effect row buttons (id >= 1 and < 100)
if (id >= 1 && id < 100) {
int effectIndex = (id - 1) / 10;
int action = (id - 1) % 10;
if (effectIndex >= 0 && effectIndex < effects.size()) {
AbilityEffect effect = effects.get(effectIndex);
switch (action) {
case 0: // Type selector
int typeIndex = ((GuiNpcButton) guibutton).getValue();
effect.setType(AbilityEffect.EffectType.fromOrdinal(typeIndex));
break;
case 2: // Amplifier selector
int amp = ((GuiNpcButton) guibutton).getValue();
effect.setAmplifier(amp);
break;
case 3: // Delete button
effects.remove(effectIndex);
initGui();
break;
}
}
}
}
@Override
public void unFocused(GuiNpcTextField textField) {
int id = textField.id;
// Duration text fields (baseId + 1)
if (id >= 2 && id < 100) {
int effectIndex = (id - 1) / 10;
int action = (id - 1) % 10;
if (action == 1 && effectIndex >= 0 && effectIndex < effects.size()) {
effects.get(effectIndex).setDurationTicks(textField.getInteger());
}
}
}
/**
* Returns the resulting effects list after the dialog closes.
* Returns null if cancelled.
*/
public List<AbilityEffect> getResult() {
if (cancelled) {
return null;
}
return effects;
}
/**
* Returns true if the dialog was cancelled.
*/
public boolean wasCancelled() {
return cancelled;
}
}
@@ -1,312 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.type.AbilityEnergyBeam;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Energy Beam ability type-specific settings.
* Energy Beam is a homing head with trailing path (DBZ-style).
*/
public class SubGuiAbilityEnergyBeam extends SubGuiAbilityConfig {
private final AbilityEnergyBeam beam;
private int editingVisualColorId = 0;
public SubGuiAbilityEnergyBeam(AbilityEnergyBeam ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.beam = ability;
}
@Override
protected boolean hasVisualSettings() {
return true;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Speed
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, beam.getDamage()));
addLabel(new GuiNpcLabel(101, "stats.speed", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, beam.getSpeed()));
y += 24;
// Row 2: Beam Width + Head Size
addLabel(new GuiNpcLabel(102, "ability.beamWidth", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, beam.getBeamWidth()));
addLabel(new GuiNpcLabel(103, "ability.headSize", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, beam.getHeadSize()));
y += 24;
// Row 3: Homing + Homing Strength (only show strength if homing)
addLabel(new GuiNpcLabel(104, "ability.homing", labelX, y + 5));
GuiNpcButton homingBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, beam.isHoming() ? 1 : 0);
homingBtn.setHoverText("ability.hover.homing");
addButton(homingBtn);
if (beam.isHoming()) {
addLabel(new GuiNpcLabel(105, "ability.homingStr", col2LabelX, y + 5));
addTextField(createFloatField(105, col2FieldX, y, 50, beam.getHomingStrength()));
}
y += 24;
// Row 4: Max Distance (+ Homing Range only if homing)
if (beam.isHoming()) {
addLabel(new GuiNpcLabel(106, "ability.homingRange", labelX, y + 5));
addTextField(createFloatField(106, fieldX, y, 50, beam.getHomingRange()));
}
addLabel(new GuiNpcLabel(107, "ability.maxDist", beam.isHoming() ? col2LabelX : labelX, y + 5));
addTextField(createFloatField(107, beam.isHoming() ? col2FieldX : fieldX, y, 50, beam.getMaxDistance()));
y += 24;
// Row 5: Explosive + Explosion Radius (only show radius if explosive)
addLabel(new GuiNpcLabel(108, "ability.explosive", labelX, y + 5));
GuiNpcButton explosiveBtn = new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, beam.isExplosive() ? 1 : 0);
explosiveBtn.setHoverText("ability.hover.explosive");
addButton(explosiveBtn);
if (beam.isExplosive()) {
addLabel(new GuiNpcLabel(109, "ability.explosionRad", col2LabelX, y + 5));
addTextField(createFloatField(109, col2FieldX, y, 50, beam.getExplosionRadius()));
}
y += 24;
// Row 6: Knockback + Max Lifetime
addLabel(new GuiNpcLabel(110, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(110, fieldX, y, 50, beam.getKnockback()));
addLabel(new GuiNpcLabel(111, "ability.lifetime", col2LabelX, y + 5));
addTextField(createIntField(111, col2FieldX, y, 50, beam.getMaxLifetime()));
y += 24;
// Row 7: Effects button
addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects"));
}
@Override
protected void initVisualTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 180;
int col2FieldX = guiLeft + 260;
// Row 1: Anchor Point
addLabel(new GuiNpcLabel(210, "ability.anchorPoint", labelX, y + 5));
GuiNpcButton anchorBtn = new GuiNpcButton(210, fieldX, y, 80, 20, AnchorPoint.getDisplayNames(), beam.getAnchorPointEnum().ordinal());
anchorBtn.setHoverText("ability.hover.anchorPoint");
addButton(anchorBtn);
y += 24;
// Row 2: Inner Color + Outer Color
addLabel(new GuiNpcLabel(200, "ability.innerColor", labelX, y + 5));
String innerHex = String.format("%06X", beam.getInnerColor() & 0xFFFFFF);
GuiNpcButton innerColorBtn = new GuiNpcButton(200, fieldX, y, 55, 20, innerHex);
innerColorBtn.setTextColor(beam.getInnerColor() & 0xFFFFFF);
addButton(innerColorBtn);
addLabel(new GuiNpcLabel(201, "ability.outerColor", col2LabelX, y + 5));
String outerHex = String.format("%06X", beam.getOuterColor() & 0xFFFFFF);
GuiNpcButton outerColorBtn = new GuiNpcButton(201, col2FieldX, y, 55, 20, outerHex);
outerColorBtn.setTextColor(beam.getOuterColor() & 0xFFFFFF);
outerColorBtn.setEnabled(beam.isOuterColorEnabled());
addButton(outerColorBtn);
y += 24;
// Row 2: Outer Color Enabled + Outer Color Width
addLabel(new GuiNpcLabel(202, "ability.outerEnabled", labelX, y + 5));
addButton(new GuiNpcButton(202, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, beam.isOuterColorEnabled() ? 1 : 0));
addLabel(new GuiNpcLabel(203, "ability.outerWidth", col2LabelX, y + 5));
GuiNpcTextField widthField = createFloatField(203, col2FieldX, y, 55, beam.getOuterColorWidth());
widthField.setEnabled(beam.isOuterColorEnabled());
addTextField(widthField);
y += 24;
// Row 3: Rotation Speed
addLabel(new GuiNpcLabel(204, "ability.outerAlpha", labelX, y + 5));
GuiNpcTextField alphaField = createFloatField(204, fieldX, y, 55, beam.getOuterColorAlpha());
alphaField.setEnabled(beam.isOuterColorEnabled());
alphaField.setMinMaxDefaultFloat(0, 1, 0.5f);
addTextField(alphaField);
addLabel(new GuiNpcLabel(205, "ability.rotationSpeed", col2LabelX, y + 5));
addTextField(createFloatField(205, col2FieldX, y, 50, beam.getRotationSpeed()));
y += 24;
// Row 4: Lightning Effect Enabled (only affects head)
addLabel(new GuiNpcLabel(206, "ability.lightning", labelX, y + 5));
GuiNpcButton lightningBtn = new GuiNpcButton(206, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, beam.hasLightningEffect() ? 1 : 0);
lightningBtn.setHoverText("ability.hover.lightning");
addButton(lightningBtn);
// Only show Lightning settings if Lightning is enabled
if (beam.hasLightningEffect()) {
y += 24;
// Row 5: Density + Radius
addLabel(new GuiNpcLabel(207, "ability.lightningDensity", labelX, y + 5));
GuiNpcTextField densityField = new GuiNpcTextField(207, this, fontRendererObj, fieldX, y, 55, 18, "" + beam.getLightningDensity());
densityField.setMinMaxDefaultFloat(0.01f, 5.0f, 0.15f);
addTextField(densityField);
addLabel(new GuiNpcLabel(208, "ability.lightningRadius", col2LabelX, y + 5));
GuiNpcTextField radiusField = new GuiNpcTextField(208, this, fontRendererObj, col2FieldX, y, 55, 18, "" + beam.getLightningRadius());
radiusField.setMinMaxDefaultFloat(0.1f, 10.0f, 0.5f);
addTextField(radiusField);
}
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 104:
beam.setHoming(value == 1);
initGui();
break;
case 108:
beam.setExplosive(value == 1);
initGui();
break;
case 150:
setSubGui(new SubGuiAbilityEffects(beam.getEffects()));
break;
}
}
@Override
protected void handleVisualButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 200:
editingVisualColorId = 200;
setSubGui(new SubGuiColorSelector(beam.getInnerColor()));
break;
case 201:
editingVisualColorId = 201;
setSubGui(new SubGuiColorSelector(beam.getOuterColor()));
break;
case 202:
beam.setOuterColorEnabled(value == 1);
initGui();
break;
case 206:
beam.setLightningEffect(value == 1);
initGui();
break;
case 210:
beam.setAnchorPointEnum(AnchorPoint.fromOrdinal(value));
break;
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiColorSelector && editingVisualColorId != 0) {
SubGuiColorSelector colorSelector = (SubGuiColorSelector) subgui;
int rgb = colorSelector.color & 0x00FFFFFF;
if (editingVisualColorId == 200) {
beam.setInnerColor(rgb);
} else if (editingVisualColorId == 201) {
beam.setOuterColor(rgb);
}
editingVisualColorId = 0;
initGui();
} else if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
beam.setEffects(result);
}
} else {
super.subGuiClosed(subgui);
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
beam.setDamage(parseFloat(field, beam.getDamage()));
break;
case 101:
beam.setSpeed(parseFloat(field, beam.getSpeed()));
break;
case 102:
beam.setBeamWidth(parseFloat(field, beam.getBeamWidth()));
break;
case 103:
beam.setHeadSize(parseFloat(field, beam.getHeadSize()));
break;
case 105:
beam.setHomingStrength(parseFloat(field, beam.getHomingStrength()));
break;
case 106:
beam.setHomingRange(parseFloat(field, beam.getHomingRange()));
break;
case 107:
beam.setMaxDistance(parseFloat(field, beam.getMaxDistance()));
break;
case 109:
beam.setExplosionRadius(parseFloat(field, beam.getExplosionRadius()));
break;
case 110:
beam.setKnockback(parseFloat(field, beam.getKnockback()));
break;
case 111:
beam.setMaxLifetime(field.getInteger());
break;
}
}
@Override
protected void handleVisualTextField(int id, GuiNpcTextField field) {
switch (id) {
case 203:
beam.setOuterColorWidth(parseFloat(field, beam.getOuterColorWidth()));
break;
case 204:
beam.setOuterColorAlpha(parseFloat(field, beam.getOuterColorAlpha()));
break;
case 205:
beam.setRotationSpeed(parseFloat(field, beam.getRotationSpeed()));
break;
case 207:
beam.setLightningDensity(parseFloat(field, beam.getLightningDensity()));
break;
case 208:
beam.setLightningRadius(parseFloat(field, beam.getLightningRadius()));
break;
}
}
}
@@ -1,143 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Guard ability type-specific settings.
*/
public class SubGuiAbilityGuard extends SubGuiAbilityConfig {
private final AbilityGuard guard;
public SubGuiAbilityGuard(AbilityGuard ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.guard = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 105;
int col2LabelX = guiLeft + 165;
int col2FieldX = guiLeft + 225;
// Row 1: Duration + Damage Reduction
addLabel(new GuiNpcLabel(99, "ability.duration", labelX, y + 5));
GuiNpcTextField durationField = createIntField(99, fieldX, y, 50, guard.getDurationTicks());
durationField.setMinMaxDefault(1, 1000, 60);
addTextField(durationField);
addLabel(new GuiNpcLabel(100, "ability.dmgReduce", col2LabelX, y + 5));
addTextField(createFloatField(100, col2FieldX, y, 50, guard.getDamageReduction()));
y += 24;
// Row 2: Can Counter + Counter Type
addLabel(new GuiNpcLabel(101, "ability.canCounter", labelX, y + 5));
GuiNpcButton canCounterBtn = new GuiNpcButton(101, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, guard.isCanCounter() ? 1 : 0);
canCounterBtn.setHoverText("ability.hover.canCounter");
addButton(canCounterBtn);
addLabel(new GuiNpcLabel(102, "ability.counterType", col2LabelX, y + 5));
String[] types = {"Flat", "Percent"};
GuiNpcButton counterTypeButton = new GuiNpcButton(102, col2FieldX, y, 60, 20, types, guard.getCounterTypeEnum().ordinal());
counterTypeButton.setHoverText("ability.hover.counterType");
counterTypeButton.setEnabled(guard.isCanCounter());
addButton(counterTypeButton);
y += 24;
// Row 3: Counter Value + Counter Chance
addLabel(new GuiNpcLabel(103, "ability.counterValue", labelX, y + 5));
GuiNpcTextField counterValueField = createFloatField(103, fieldX, y, 50, guard.getCounterValue());
counterValueField.setEnabled(guard.isCanCounter());
addTextField(counterValueField);
addLabel(new GuiNpcLabel(104, "ability.counterChance", col2LabelX, y + 5));
GuiNpcTextField counterChanceField = createFloatField(104, col2FieldX, y, 50, guard.getCounterChance());
counterChanceField.setEnabled(guard.isCanCounter());
addTextField(counterChanceField);
y += 24;
// Row 4: Counter Sound + Counter Animation
addLabel(new GuiNpcLabel(105, "ability.counterSound", labelX, y + 5));
GuiNpcTextField counterSoundField = new GuiNpcTextField(105, this, fontRendererObj, fieldX, y, 100, 20, guard.getCounterSound());
counterSoundField.setEnabled(guard.isCanCounter());
addTextField(counterSoundField);
addLabel(new GuiNpcLabel(106, "ability.counterAnim", col2LabelX, y + 5));
GuiNpcTextField counterAnimField = createIntField(106, col2FieldX, y, 50, guard.getCounterAnimationId());
counterAnimField.setEnabled(guard.isCanCounter());
addTextField(counterAnimField);
y += 24;
// Row 5: Effects button (applies on counter)
GuiNpcButton effectsBtn = new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects");
effectsBtn.setEnabled(guard.isCanCounter());
addButton(effectsBtn);
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
switch (id) {
case 101:
guard.setCanCounter(button.getValue() == 1);
initGui();
break;
case 102:
guard.setCounterTypeEnum(AbilityGuard.CounterType.values()[button.getValue()]);
break;
case 150:
setSubGui(new SubGuiAbilityEffects(guard.getEffects()));
break;
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
super.subGuiClosed(subgui);
if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
guard.setEffects(result);
}
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 99:
guard.setDurationTicks(field.getInteger());
break;
case 100:
guard.setDamageReduction(parseFloat(field, guard.getDamageReduction()));
break;
case 103:
guard.setCounterValue(parseFloat(field, guard.getCounterValue()));
break;
case 104:
guard.setCounterChance(parseFloat(field, guard.getCounterChance()));
break;
case 105:
guard.setCounterSound(field.getText());
break;
case 106:
guard.setCounterAnimationId(field.getInteger());
break;
}
}
}
@@ -1,159 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilityHazard;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Hazard ability type-specific settings.
*/
public class SubGuiAbilityHazard extends SubGuiAbilityConfig {
private final AbilityHazard hazard;
public SubGuiAbilityHazard(AbilityHazard ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.hazard = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Duration + Shape
addLabel(new GuiNpcLabel(99, "ability.duration", labelX, y + 5));
GuiNpcTextField durationField = createIntField(99, fieldX, y, 50, hazard.getDurationTicks());
durationField.setMinMaxDefault(1, 2000, 100);
addTextField(durationField);
addLabel(new GuiNpcLabel(100, "ability.shape", col2LabelX, y + 5));
String[] shapes = {"Circle", "Ring", "Cone"};
GuiNpcButton shapeBtn = new GuiNpcButton(100, col2FieldX, y, 55, 20, shapes, hazard.getShapeEnum().ordinal());
shapeBtn.setHoverText("ability.hover.shape");
addButton(shapeBtn);
y += 24;
// Row 2: Placement
addLabel(new GuiNpcLabel(101, "ability.placement", labelX, y + 5));
String[] placements = {"Caster", "Target", "FollowCast", "FollowTgt"};
GuiNpcButton placementBtn = new GuiNpcButton(101, fieldX, y, 70, 20, placements, hazard.getPlacementEnum().ordinal());
placementBtn.setHoverText("ability.hover.placement");
addButton(placementBtn);
y += 24;
// Row 2: Radius + Inner Radius
addLabel(new GuiNpcLabel(102, "ability.radius", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, hazard.getRadius()));
addLabel(new GuiNpcLabel(103, "ability.innerRadius", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, hazard.getInnerRadius()));
y += 24;
// Row 3: Damage Per Second + Damage Interval
addLabel(new GuiNpcLabel(104, "ability.dmgPerSec", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, hazard.getDamagePerSecond()));
addLabel(new GuiNpcLabel(105, "ability.dmgInterval", col2LabelX, y + 5));
addTextField(createIntField(105, col2FieldX, y, 50, hazard.getDamageInterval()));
y += 24;
// Row 4: Slowness Level + Debuff Duration
addLabel(new GuiNpcLabel(106, "ability.slownessLvl", labelX, y + 5));
addTextField(createIntField(106, fieldX, y, 50, hazard.getSlownessLevel()));
addLabel(new GuiNpcLabel(107, "ability.debuffDur", col2LabelX, y + 5));
addTextField(createIntField(107, col2FieldX, y, 50, hazard.getDebuffDuration()));
y += 24;
// Row 5: Poison Level + Affects Caster
addLabel(new GuiNpcLabel(108, "ability.poisonLvl", labelX, y + 5));
addTextField(createIntField(108, fieldX, y, 50, hazard.getPoisonLevel()));
addLabel(new GuiNpcLabel(109, "ability.affectsCaster", col2LabelX, y + 5));
GuiNpcButton affectsCasterBtn = new GuiNpcButton(109, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, hazard.isAffectsCaster() ? 1 : 0);
affectsCasterBtn.setHoverText("ability.hover.affectsCaster");
addButton(affectsCasterBtn);
y += 24;
// Row 6: Effects button
addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects"));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 100:
hazard.setShapeEnum(AbilityHazard.HazardShape.values()[value]);
break;
case 101:
hazard.setPlacementEnum(AbilityHazard.PlacementMode.values()[value]);
break;
case 109:
hazard.setAffectsCaster(value == 1);
break;
case 150:
setSubGui(new SubGuiAbilityEffects(hazard.getEffects()));
break;
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
super.subGuiClosed(subgui);
if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
hazard.setEffects(result);
}
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 99:
hazard.setDurationTicks(field.getInteger());
break;
case 102:
hazard.setRadius(parseFloat(field, hazard.getRadius()));
break;
case 103:
hazard.setInnerRadius(parseFloat(field, hazard.getInnerRadius()));
break;
case 104:
hazard.setDamagePerSecond(parseFloat(field, hazard.getDamagePerSecond()));
break;
case 105:
hazard.setDamageInterval(field.getInteger());
break;
case 106:
hazard.setSlownessLevel(field.getInteger());
break;
case 107:
hazard.setDebuffDuration(field.getInteger());
break;
case 108:
hazard.setPoisonLevel(field.getInteger());
break;
}
}
}
@@ -1,106 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityHeal;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Heal ability type-specific settings.
*/
public class SubGuiAbilityHeal extends SubGuiAbilityConfig {
private final AbilityHeal heal;
public SubGuiAbilityHeal(AbilityHeal ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.heal = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Instant Heal + Duration (only shown if not instant)
addLabel(new GuiNpcLabel(103, "dialog.instant", labelX, y + 5));
GuiNpcButton instantBtn = new GuiNpcButton(103, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, heal.isInstantHeal() ? 1 : 0);
instantBtn.setHoverText("ability.hover.instant");
addButton(instantBtn);
if (!heal.isInstantHeal()) {
addLabel(new GuiNpcLabel(99, "ability.duration", col2LabelX, y + 5));
GuiNpcTextField durationField = createIntField(99, col2FieldX, y, 50, heal.getDurationTicks());
durationField.setMinMaxDefault(1, 1000, 60);
addTextField(durationField);
}
y += 24;
// Row 2: Heal Amount + Heal Percent
addLabel(new GuiNpcLabel(100, "ability.healAmount", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, heal.getHealAmount()));
addLabel(new GuiNpcLabel(101, "ability.healPercent", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, heal.getHealPercent()));
y += 24;
// Row 3: Heal Radius
addLabel(new GuiNpcLabel(102, "ability.healRadius", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, heal.getHealRadius()));
y += 24;
// Row 4: Heal Self + Heal Allies
addLabel(new GuiNpcLabel(104, "ability.healSelf", labelX, y + 5));
GuiNpcButton healSelfBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, heal.isHealSelf() ? 1 : 0);
healSelfBtn.setHoverText("ability.hover.healSelf");
addButton(healSelfBtn);
addLabel(new GuiNpcLabel(105, "ability.healAllies", col2LabelX, y + 5));
GuiNpcButton healAlliesBtn = new GuiNpcButton(105, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, heal.isHealAllies() ? 1 : 0);
healAlliesBtn.setHoverText("ability.hover.healAllies");
addButton(healAlliesBtn);
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 103:
heal.setInstantHeal(value == 1);
initGui(); // Refresh to show/hide duration field
break;
case 104:
heal.setHealSelf(value == 1);
break;
case 105:
heal.setHealAllies(value == 1);
break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 99:
heal.setDurationTicks(field.getInteger());
break;
case 100:
heal.setHealAmount(parseFloat(field, heal.getHealAmount()));
break;
case 101:
heal.setHealPercent(parseFloat(field, heal.getHealPercent()));
break;
case 102:
heal.setHealRadius(parseFloat(field, heal.getHealRadius()));
break;
}
}
}
@@ -1,76 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilityHeavyHit;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Heavy Hit ability type-specific settings.
*/
public class SubGuiAbilityHeavyHit extends SubGuiAbilityConfig {
private final AbilityHeavyHit heavyHit;
public SubGuiAbilityHeavyHit(AbilityHeavyHit ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.heavyHit = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
// Row 1: Damage + Knockback
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, heavyHit.getDamage()));
addLabel(new GuiNpcLabel(102, "ability.knockback", col2LabelX, y + 5));
addTextField(createFloatField(102, guiLeft + 205, y, 50, heavyHit.getKnockback()));
y += 24;
// Row 2: Effects button
addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects"));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
if (id == 150) {
setSubGui(new SubGuiAbilityEffects(heavyHit.getEffects()));
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
super.subGuiClosed(subgui);
if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
heavyHit.setEffects(result);
}
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
heavyHit.setDamage(parseFloat(field, heavyHit.getDamage()));
break;
case 102:
heavyHit.setKnockback(parseFloat(field, heavyHit.getKnockback()));
break;
}
}
}
@@ -1,268 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilityLaserShot;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Laser Shot ability type-specific settings.
*/
public class SubGuiAbilityLaserShot extends SubGuiAbilityConfig {
private final AbilityLaserShot laser;
private int editingVisualColorId = 0;
public SubGuiAbilityLaserShot(AbilityLaserShot ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.laser = ability;
}
@Override
protected boolean hasVisualSettings() {
return true;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Laser Width
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, laser.getDamage()));
addLabel(new GuiNpcLabel(101, "ability.laserWidth", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, laser.getLaserWidth()));
y += 24;
// Row 2: Expansion Speed + Linger Ticks
addLabel(new GuiNpcLabel(102, "ability.expansionSpeed", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, laser.getExpansionSpeed()));
addLabel(new GuiNpcLabel(103, "ability.lingerTicks", col2LabelX, y + 5));
addTextField(createIntField(103, col2FieldX, y, 50, laser.getLingerTicks()));
y += 24;
// Row 3: Max Distance + Max Lifetime
addLabel(new GuiNpcLabel(104, "ability.maxDist", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, laser.getMaxDistance()));
addLabel(new GuiNpcLabel(105, "ability.lifetime", col2LabelX, y + 5));
addTextField(createIntField(105, col2FieldX, y, 50, laser.getMaxLifetime()));
y += 24;
// Row 4: Explosive + Explosion Radius (only show radius if explosive)
addLabel(new GuiNpcLabel(106, "ability.explosive", labelX, y + 5));
GuiNpcButton explosiveBtn = new GuiNpcButton(106, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, laser.isExplosive() ? 1 : 0);
explosiveBtn.setHoverText("ability.hover.explosive");
addButton(explosiveBtn);
if (laser.isExplosive()) {
addLabel(new GuiNpcLabel(107, "ability.explosionRad", col2LabelX, y + 5));
addTextField(createFloatField(107, col2FieldX, y, 50, laser.getExplosionRadius()));
}
y += 24;
// Row 5: Knockback + Knockback Up
addLabel(new GuiNpcLabel(108, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(108, fieldX, y, 50, laser.getKnockback()));
addLabel(new GuiNpcLabel(109, "ability.knockbackUp", col2LabelX, y + 5));
addTextField(createFloatField(109, col2FieldX, y, 50, laser.getKnockbackUp()));
y += 24;
// Row 6: Effects button
addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects"));
}
@Override
protected void initVisualTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 180;
int col2FieldX = guiLeft + 260;
// Row 1: Inner Color + Outer Color
addLabel(new GuiNpcLabel(200, "ability.innerColor", labelX, y + 5));
String innerHex = String.format("%06X", laser.getInnerColor() & 0xFFFFFF);
GuiNpcButton innerColorBtn = new GuiNpcButton(200, fieldX, y, 55, 20, innerHex);
innerColorBtn.setTextColor(laser.getInnerColor() & 0xFFFFFF);
addButton(innerColorBtn);
addLabel(new GuiNpcLabel(201, "ability.outerColor", col2LabelX, y + 5));
String outerHex = String.format("%06X", laser.getOuterColor() & 0xFFFFFF);
GuiNpcButton outerColorBtn = new GuiNpcButton(201, col2FieldX, y, 55, 20, outerHex);
outerColorBtn.setTextColor(laser.getOuterColor() & 0xFFFFFF);
outerColorBtn.setEnabled(laser.isOuterColorEnabled());
addButton(outerColorBtn);
y += 24;
// Row 2: Outer Color Enabled + Outer Color Width
addLabel(new GuiNpcLabel(202, "ability.outerEnabled", labelX, y + 5));
addButton(new GuiNpcButton(202, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, laser.isOuterColorEnabled() ? 1 : 0));
addLabel(new GuiNpcLabel(203, "ability.outerWidth", col2LabelX, y + 5));
GuiNpcTextField widthField = createFloatField(203, col2FieldX, y, 55, laser.getOuterColorWidth());
widthField.setEnabled(laser.isOuterColorEnabled());
addTextField(widthField);
y += 24;
// Row 3: Lightning Effect Enabled
addLabel(new GuiNpcLabel(204, "ability.outerAlpha", labelX, y + 5));
GuiNpcTextField alphaField = createFloatField(204, fieldX, y, 55, laser.getOuterColorAlpha());
alphaField.setEnabled(laser.isOuterColorEnabled());
alphaField.setMinMaxDefaultFloat(0, 1, 0.5f);
addTextField(alphaField);
addLabel(new GuiNpcLabel(205, "ability.lightning", col2LabelX, y + 5));
GuiNpcButton lightningBtn = new GuiNpcButton(205, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, laser.hasLightningEffect() ? 1 : 0);
lightningBtn.setHoverText("ability.hover.lightning");
addButton(lightningBtn);
// Only show Lightning settings if Lightning is enabled
if (laser.hasLightningEffect()) {
y += 24;
// Row 4: Density + Radius
addLabel(new GuiNpcLabel(206, "ability.lightningDensity", labelX, y + 5));
GuiNpcTextField densityField = new GuiNpcTextField(206, this, fontRendererObj, fieldX, y, 55, 18, "" + laser.getLightningDensity());
densityField.setMinMaxDefaultFloat(0.01f, 5.0f, 0.15f);
addTextField(densityField);
addLabel(new GuiNpcLabel(207, "ability.lightningRadius", col2LabelX, y + 5));
GuiNpcTextField radiusField = new GuiNpcTextField(207, this, fontRendererObj, col2FieldX, y, 55, 18, "" + laser.getLightningRadius());
radiusField.setMinMaxDefaultFloat(0.1f, 10.0f, 0.5f);
addTextField(radiusField);
}
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 106:
laser.setExplosive(value == 1);
initGui();
break;
case 150:
setSubGui(new SubGuiAbilityEffects(laser.getEffects()));
break;
}
}
@Override
protected void handleVisualButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 200:
editingVisualColorId = 200;
setSubGui(new SubGuiColorSelector(laser.getInnerColor()));
break;
case 201:
editingVisualColorId = 201;
setSubGui(new SubGuiColorSelector(laser.getOuterColor()));
break;
case 202:
laser.setOuterColorEnabled(value == 1);
initGui();
break;
case 205:
laser.setLightningEffect(value == 1);
initGui();
break;
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiColorSelector && editingVisualColorId != 0) {
SubGuiColorSelector colorSelector = (SubGuiColorSelector) subgui;
int rgb = colorSelector.color & 0x00FFFFFF;
if (editingVisualColorId == 200) {
laser.setInnerColor(rgb);
} else if (editingVisualColorId == 201) {
laser.setOuterColor(rgb);
}
editingVisualColorId = 0;
initGui();
} else if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
laser.setEffects(result);
}
} else {
super.subGuiClosed(subgui);
}
}
@Override
protected void handleVisualTextField(int id, GuiNpcTextField field) {
switch (id) {
case 203:
laser.setOuterColorWidth(parseFloat(field, laser.getOuterColorWidth()));
break;
case 204:
laser.setOuterColorAlpha(parseFloat(field, laser.getOuterColorAlpha()));
break;
case 206:
laser.setLightningDensity(parseFloat(field, laser.getLightningDensity()));
break;
case 207:
laser.setLightningRadius(parseFloat(field, laser.getLightningRadius()));
break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
laser.setDamage(parseFloat(field, laser.getDamage()));
break;
case 101:
laser.setLaserWidth(parseFloat(field, laser.getLaserWidth()));
break;
case 102:
laser.setExpansionSpeed(parseFloat(field, laser.getExpansionSpeed()));
break;
case 103:
laser.setLingerTicks(field.getInteger());
break;
case 104:
laser.setMaxDistance(parseFloat(field, laser.getMaxDistance()));
break;
case 105:
laser.setMaxLifetime(field.getInteger());
break;
case 107:
laser.setExplosionRadius(parseFloat(field, laser.getExplosionRadius()));
break;
case 108:
laser.setKnockback(parseFloat(field, laser.getKnockback()));
break;
case 109:
laser.setKnockbackUp(parseFloat(field, laser.getKnockbackUp()));
break;
}
}
}
@@ -1,294 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.type.AbilityOrb;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Orb ability type-specific settings.
*/
public class SubGuiAbilityOrb extends SubGuiAbilityConfig {
private final AbilityOrb orb;
private int editingVisualColorId = 0;
public SubGuiAbilityOrb(AbilityOrb ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.orb = ability;
}
@Override
protected boolean hasVisualSettings() {
return true;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Speed
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, orb.getDamage()));
addLabel(new GuiNpcLabel(101, "stats.speed", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, orb.getOrbSpeed()));
y += 24;
// Row 2: Orb Size + Max Distance
addLabel(new GuiNpcLabel(102, "stats.size", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, orb.getOrbSize()));
addLabel(new GuiNpcLabel(103, "ability.maxDist", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, orb.getMaxDistance()));
y += 24;
// Row 3: Homing + Homing Strength (only show strength if homing)
addLabel(new GuiNpcLabel(104, "ability.homing", labelX, y + 5));
GuiNpcButton homingBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, orb.isHoming() ? 1 : 0);
homingBtn.setHoverText("ability.hover.homing");
addButton(homingBtn);
if (orb.isHoming()) {
addLabel(new GuiNpcLabel(105, "ability.homingStr", col2LabelX, y + 5));
addTextField(createFloatField(105, col2FieldX, y, 50, orb.getHomingStrength()));
}
y += 24;
// Row 4: Explosive + Explosion Radius (only show radius if explosive)
addLabel(new GuiNpcLabel(106, "ability.explosive", labelX, y + 5));
GuiNpcButton explosiveBtn = new GuiNpcButton(106, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, orb.isExplosive() ? 1 : 0);
explosiveBtn.setHoverText("ability.hover.explosive");
addButton(explosiveBtn);
if (orb.isExplosive()) {
addLabel(new GuiNpcLabel(107, "ability.explosionRad", col2LabelX, y + 5));
addTextField(createFloatField(107, col2FieldX, y, 50, orb.getExplosionRadius()));
}
y += 24;
// Row 5: Knockback + Max Lifetime
addLabel(new GuiNpcLabel(108, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(108, fieldX, y, 50, orb.getKnockback()));
addLabel(new GuiNpcLabel(109, "ability.lifetime", col2LabelX, y + 5));
addTextField(createIntField(109, col2FieldX, y, 50, orb.getMaxLifetime()));
y += 24;
// Row 6: Effects button
addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects"));
}
@Override
protected void initVisualTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 180;
int col2FieldX = guiLeft + 260;
// Row 1: Anchor Point
addLabel(new GuiNpcLabel(210, "ability.anchorPoint", labelX, y + 5));
GuiNpcButton anchorBtn = new GuiNpcButton(210, fieldX, y, 80, 20, AnchorPoint.getDisplayNames(), orb.getAnchorPointEnum().ordinal());
anchorBtn.setHoverText("ability.hover.anchorPoint");
addButton(anchorBtn);
y += 24;
// Row 2: Inner Color + Rotation Speed
addLabel(new GuiNpcLabel(200, "ability.innerColor", labelX, y + 5));
String innerHex = String.format("%06X", orb.getInnerColor() & 0xFFFFFF);
GuiNpcButton innerColorBtn = new GuiNpcButton(200, fieldX, y, 55, 20, innerHex);
innerColorBtn.setTextColor(orb.getInnerColor() & 0xFFFFFF);
addButton(innerColorBtn);
addLabel(new GuiNpcLabel(205, "ability.rotationSpeed", col2LabelX, y + 5));
addTextField(createFloatField(205, col2FieldX, y, 55, orb.getRotationSpeed()));
y += 24;
// Row 3: Outer Glow Enabled
addLabel(new GuiNpcLabel(202, "ability.outerEnabled", labelX, y + 5));
addButton(new GuiNpcButton(202, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, orb.isOuterColorEnabled() ? 1 : 0));
// Only show Outer Color and Width if Outer Glow is enabled
if (orb.isOuterColorEnabled()) {
addLabel(new GuiNpcLabel(204, "ability.outerAlpha", col2LabelX, y + 5));
GuiNpcTextField alphaField = createFloatField(204, col2FieldX, y, 55, orb.getOuterColorAlpha());
alphaField.setEnabled(orb.isOuterColorEnabled());
alphaField.setMinMaxDefaultFloat(0, 1, 0.5f);
addTextField(alphaField);
y += 24;
// Row 4: Outer Color + Outer Width
addLabel(new GuiNpcLabel(201, "ability.outerColor", labelX, y + 5));
String outerHex = String.format("%06X", orb.getOuterColor() & 0xFFFFFF);
GuiNpcButton outerColorBtn = new GuiNpcButton(201, fieldX, y, 55, 20, outerHex);
outerColorBtn.setTextColor(orb.getOuterColor() & 0xFFFFFF);
addButton(outerColorBtn);
addLabel(new GuiNpcLabel(203, "ability.outerWidth", col2LabelX, y + 5));
addTextField(createFloatField(203, col2FieldX, y, 55, orb.getOuterColorWidth()));
}
y += 24;
// Row 5: Lightning Effect Enabled
addLabel(new GuiNpcLabel(206, "ability.lightning", labelX, y + 5));
GuiNpcButton lightningBtn = new GuiNpcButton(206, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, orb.hasLightningEffect() ? 1 : 0);
lightningBtn.setHoverText("ability.hover.lightning");
addButton(lightningBtn);
// Only show Lightning settings if Lightning is enabled
if (orb.hasLightningEffect()) {
y += 24;
// Row 61: Density + Radius
addLabel(new GuiNpcLabel(207, "ability.lightningDensity", labelX, y + 5));
GuiNpcTextField densityField = new GuiNpcTextField(207, this, fontRendererObj, fieldX, y, 55, 18, "" + orb.getLightningDensity());
densityField.setMinMaxDefaultFloat(0.01f, 5.0f, 0.15f);
addTextField(densityField);
addLabel(new GuiNpcLabel(208, "ability.lightningRadius", col2LabelX, y + 5));
GuiNpcTextField radiusField = new GuiNpcTextField(208, this, fontRendererObj, col2FieldX, y, 55, 18, "" + orb.getLightningRadius());
radiusField.setMinMaxDefaultFloat(0.1f, 10.0f, 0.5f);
addTextField(radiusField);
}
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 104:
orb.setHoming(value == 1);
initGui();
break;
case 106:
orb.setExplosive(value == 1);
initGui();
break;
case 150:
setSubGui(new SubGuiAbilityEffects(orb.getEffects()));
break;
}
}
@Override
protected void handleVisualButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 200:
editingVisualColorId = 200;
setSubGui(new SubGuiColorSelector(orb.getInnerColor()));
break;
case 201:
editingVisualColorId = 201;
setSubGui(new SubGuiColorSelector(orb.getOuterColor()));
break;
case 202:
orb.setOuterColorEnabled(value == 1);
initGui();
break;
case 206:
orb.setLightningEffect(value == 1);
initGui();
break;
case 210:
orb.setAnchorPointEnum(AnchorPoint.fromOrdinal(value));
break;
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiColorSelector && editingVisualColorId != 0) {
SubGuiColorSelector colorSelector = (SubGuiColorSelector) subgui;
int rgb = colorSelector.color & 0x00FFFFFF;
if (editingVisualColorId == 200) {
orb.setInnerColor(rgb);
} else if (editingVisualColorId == 201) {
orb.setOuterColor(rgb);
}
editingVisualColorId = 0;
initGui();
} else if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
orb.setEffects(result);
}
} else {
super.subGuiClosed(subgui);
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
orb.setDamage(parseFloat(field, orb.getDamage()));
break;
case 101:
orb.setOrbSpeed(parseFloat(field, orb.getOrbSpeed()));
break;
case 102:
orb.setOrbSize(parseFloat(field, orb.getOrbSize()));
break;
case 103:
orb.setMaxDistance(parseFloat(field, orb.getMaxDistance()));
break;
case 105:
orb.setHomingStrength(parseFloat(field, orb.getHomingStrength()));
break;
case 107:
orb.setExplosionRadius(parseFloat(field, orb.getExplosionRadius()));
break;
case 108:
orb.setKnockback(parseFloat(field, orb.getKnockback()));
break;
case 109:
orb.setMaxLifetime(field.getInteger());
break;
}
}
@Override
protected void handleVisualTextField(int id, GuiNpcTextField field) {
switch (id) {
case 203:
orb.setOuterColorWidth(parseFloat(field, orb.getOuterColorWidth()));
break;
case 204:
orb.setOuterColorAlpha(parseFloat(field, orb.getOuterColorAlpha()));
break;
case 205:
orb.setRotationSpeed(parseFloat(field, orb.getRotationSpeed()));
break;
case 207:
orb.setLightningDensity(parseFloat(field, orb.getLightningDensity()));
break;
case 208:
orb.setLightningRadius(parseFloat(field, orb.getLightningRadius()));
break;
}
}
}
@@ -1,145 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilityProjectile;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Projectile ability type-specific settings.
*/
public class SubGuiAbilityProjectile extends SubGuiAbilityConfig {
private final AbilityProjectile projectile;
public SubGuiAbilityProjectile(AbilityProjectile ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.projectile = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Speed
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, projectile.getDamage()));
addLabel(new GuiNpcLabel(101, "stats.speed", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, projectile.getSpeed()));
y += 24;
// Row 2: Knockback + Projectile Type
addLabel(new GuiNpcLabel(102, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, projectile.getKnockback()));
addLabel(new GuiNpcLabel(103, "ability.projType", col2LabelX, y + 5));
String[] projTypes = {"fireball", "arrow", "magic"};
int typeIdx = 0;
String currType = projectile.getProjectileType();
for (int i = 0; i < projTypes.length; i++) {
if (projTypes[i].equals(currType)) {
typeIdx = i;
break;
}
}
addButton(new GuiNpcButton(103, col2FieldX, y, 60, 20, projTypes, typeIdx));
y += 24;
// Row 3: Explosive + Explosion Radius (only show radius if explosive)
addLabel(new GuiNpcLabel(104, "ability.explosive", labelX, y + 5));
GuiNpcButton explosiveBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, projectile.isExplosive() ? 1 : 0);
explosiveBtn.setHoverText("ability.hover.explosive");
addButton(explosiveBtn);
if (projectile.isExplosive()) {
addLabel(new GuiNpcLabel(105, "ability.explosionRad", col2LabelX, y + 5));
addTextField(createFloatField(105, col2FieldX, y, 50, projectile.getExplosionRadius()));
}
y += 24;
// Row 4: Homing + Homing Strength (only show strength if homing)
addLabel(new GuiNpcLabel(106, "ability.homing", labelX, y + 5));
GuiNpcButton homingBtn = new GuiNpcButton(106, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, projectile.isHoming() ? 1 : 0);
homingBtn.setHoverText("ability.hover.homing");
addButton(homingBtn);
if (projectile.isHoming()) {
addLabel(new GuiNpcLabel(107, "ability.homingStr", col2LabelX, y + 5));
addTextField(createFloatField(107, col2FieldX, y, 50, projectile.getHomingStrength()));
}
y += 24;
// Row 5: Effects button
addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects"));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 103:
String[] projTypes = {"fireball", "arrow", "magic"};
projectile.setProjectileType(projTypes[value]);
break;
case 104:
projectile.setExplosive(value == 1);
initGui();
break;
case 106:
projectile.setHoming(value == 1);
initGui();
break;
case 150:
setSubGui(new SubGuiAbilityEffects(projectile.getEffects()));
break;
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
super.subGuiClosed(subgui);
if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
projectile.setEffects(result);
}
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
projectile.setDamage(parseFloat(field, projectile.getDamage()));
break;
case 101:
projectile.setSpeed(parseFloat(field, projectile.getSpeed()));
break;
case 102:
projectile.setKnockback(parseFloat(field, projectile.getKnockback()));
break;
case 105:
projectile.setExplosionRadius(parseFloat(field, projectile.getExplosionRadius()));
break;
case 107:
projectile.setHomingStrength(parseFloat(field, projectile.getHomingStrength()));
break;
}
}
}
@@ -1,95 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilityShockwave;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Shockwave ability type-specific settings.
*/
public class SubGuiAbilityShockwave extends SubGuiAbilityConfig {
private final AbilityShockwave shockwave;
public SubGuiAbilityShockwave(AbilityShockwave ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.shockwave = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Push Radius
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, shockwave.getDamage()));
addLabel(new GuiNpcLabel(101, "ability.pushRadius", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, shockwave.getPushRadius()));
y += 24;
// Row 2: Push Strength
addLabel(new GuiNpcLabel(102, "ability.pushStrength", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, shockwave.getPushStrength()));
y += 24;
// Row 3: Max Targets + Effects button
addLabel(new GuiNpcLabel(104, "ability.maxTargets", labelX, y + 5));
addTextField(createIntField(104, fieldX, y, 50, shockwave.getMaxTargets()));
addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects"));
y += 24;
addLabel(new GuiNpcLabel(105, "ability.shockwaveFalloff", labelX, y + 5));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
if (id == 150) {
setSubGui(new SubGuiAbilityEffects(shockwave.getEffects()));
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
super.subGuiClosed(subgui);
if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
shockwave.setEffects(result);
}
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
shockwave.setDamage(parseFloat(field, shockwave.getDamage()));
break;
case 101:
shockwave.setPushRadius(parseFloat(field, shockwave.getPushRadius()));
break;
case 102:
shockwave.setPushStrength(parseFloat(field, shockwave.getPushStrength()));
break;
case 104:
shockwave.setMaxTargets(field.getInteger());
break;
}
}
}
@@ -1,98 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilitySlam;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Slam ability type-specific settings.
*/
public class SubGuiAbilitySlam extends SubGuiAbilityConfig {
private final AbilitySlam slam;
public SubGuiAbilitySlam(AbilitySlam ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.slam = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Radius
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, slam.getDamage()));
addLabel(new GuiNpcLabel(101, "ability.radius", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, slam.getRadius()));
y += 24;
// Row 2: Knockback + Leap Speed
addLabel(new GuiNpcLabel(102, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, slam.getKnockbackStrength()));
addLabel(new GuiNpcLabel(103, "ability.leapSpeed", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, slam.getLeapSpeed()));
y += 24;
// Row 3: Leap Height + Effects
addLabel(new GuiNpcLabel(104, "ability.leapHeight", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, slam.getLeapHeight()));
addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects"));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
if (id == 150) {
setSubGui(new SubGuiAbilityEffects(slam.getEffects()));
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
super.subGuiClosed(subgui);
if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
slam.setEffects(result);
}
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
slam.setDamage(parseFloat(field, slam.getDamage()));
break;
case 101:
slam.setRadius(parseFloat(field, slam.getRadius()));
break;
case 102:
slam.setKnockbackStrength(parseFloat(field, slam.getKnockbackStrength()));
break;
case 103:
slam.setLeapSpeed(parseFloat(field, slam.getLeapSpeed()));
break;
case 104:
slam.setLeapHeight(parseFloat(field, slam.getLeapHeight()));
break;
}
}
}
@@ -1,219 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilitySweeper;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Sweeper ability type-specific settings.
* Sweeper is a low rotating beam that players can jump over.
*/
public class SubGuiAbilitySweeper extends SubGuiAbilityConfig {
private final AbilitySweeper sweeper;
private int editingVisualColorId = 0;
public SubGuiAbilitySweeper(AbilitySweeper ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.sweeper = ability;
}
@Override
protected boolean hasVisualSettings() {
return true;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Damage Interval
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, sweeper.getDamage()));
addLabel(new GuiNpcLabel(101, "ability.dmgInterval", col2LabelX, y + 5));
addTextField(createIntField(101, col2FieldX, y, 50, sweeper.getDamageInterval()));
y += 24;
// Row 2: Beam Length + Beam Width
addLabel(new GuiNpcLabel(102, "ability.beamLength", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, sweeper.getBeamLength()));
addLabel(new GuiNpcLabel(103, "ability.beamWidth", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, sweeper.getBeamWidth()));
y += 24;
// Row 3: Beam Height + Sweep Speed
addLabel(new GuiNpcLabel(104, "ability.beamHeight", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, sweeper.getBeamHeight()));
addLabel(new GuiNpcLabel(105, "ability.sweepSpeed", col2LabelX, y + 5));
addTextField(createFloatField(105, col2FieldX, y, 50, sweeper.getSweepSpeed()));
y += 24;
// Row 4: Number of Rotations + Piercing
addLabel(new GuiNpcLabel(106, "ability.rotations", labelX, y + 5));
addTextField(createIntField(106, fieldX, y, 50, sweeper.getNumberOfRotations()));
addLabel(new GuiNpcLabel(107, "ability.piercing", col2LabelX, y + 5));
GuiNpcButton piercingBtn = new GuiNpcButton(107, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, sweeper.isPiercing() ? 1 : 0);
piercingBtn.setHoverText("ability.hover.piercing");
addButton(piercingBtn);
y += 24;
// Row 5: Lock On Target
addLabel(new GuiNpcLabel(108, "ability.lockTarget", labelX, y + 5));
GuiNpcButton lockTargetBtn = new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, sweeper.isLockOnTarget() ? 1 : 0);
lockTargetBtn.setHoverText("ability.hover.lockTarget");
addButton(lockTargetBtn);
y += 24;
// Row 6: Effects button
addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects"));
}
@Override
protected void initVisualTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 180;
int col2FieldX = guiLeft + 260;
// Row 1: Inner Color + Outer Color
addLabel(new GuiNpcLabel(200, "ability.innerColor", labelX, y + 5));
String innerHex = String.format("%06X", sweeper.getInnerColor() & 0xFFFFFF);
GuiNpcButton innerColorBtn = new GuiNpcButton(200, fieldX, y, 55, 20, innerHex);
innerColorBtn.setTextColor(sweeper.getInnerColor() & 0xFFFFFF);
addButton(innerColorBtn);
addLabel(new GuiNpcLabel(201, "ability.outerColor", col2LabelX, y + 5));
String outerHex = String.format("%06X", sweeper.getOuterColor() & 0xFFFFFF);
GuiNpcButton outerColorBtn = new GuiNpcButton(201, col2FieldX, y, 55, 20, outerHex);
outerColorBtn.setTextColor(sweeper.getOuterColor() & 0xFFFFFF);
outerColorBtn.setEnabled(sweeper.isOuterColorEnabled());
addButton(outerColorBtn);
y += 24;
// Row 2: Outer Color Enabled + Outer Color Width
addLabel(new GuiNpcLabel(202, "ability.outerEnabled", labelX, y + 5));
addButton(new GuiNpcButton(202, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, sweeper.isOuterColorEnabled() ? 1 : 0));
addLabel(new GuiNpcLabel(203, "ability.outerWidth", col2LabelX, y + 5));
GuiNpcTextField widthField = createFloatField(203, col2FieldX, y, 55, sweeper.getOuterColorWidth());
widthField.setEnabled(sweeper.isOuterColorEnabled());
addTextField(widthField);
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 107:
sweeper.setPiercing(value == 1);
break;
case 108:
sweeper.setLockOnTarget(value == 1);
break;
case 150:
setSubGui(new SubGuiAbilityEffects(sweeper.getEffects()));
break;
}
}
@Override
protected void handleVisualButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 200:
editingVisualColorId = 200;
setSubGui(new SubGuiColorSelector(sweeper.getInnerColor()));
break;
case 201:
editingVisualColorId = 201;
setSubGui(new SubGuiColorSelector(sweeper.getOuterColor()));
break;
case 202:
sweeper.setOuterColorEnabled(value == 1);
initGui();
break;
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiColorSelector && editingVisualColorId != 0) {
SubGuiColorSelector colorSelector = (SubGuiColorSelector) subgui;
int rgb = colorSelector.color & 0x00FFFFFF;
if (editingVisualColorId == 200) {
sweeper.setInnerColor(rgb);
} else if (editingVisualColorId == 201) {
sweeper.setOuterColor(rgb);
}
editingVisualColorId = 0;
initGui();
} else if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
sweeper.setEffects(result);
}
} else {
super.subGuiClosed(subgui);
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
sweeper.setDamage(parseFloat(field, sweeper.getDamage()));
break;
case 101:
sweeper.setDamageInterval(field.getInteger());
break;
case 102:
sweeper.setBeamLength(parseFloat(field, sweeper.getBeamLength()));
break;
case 103:
sweeper.setBeamWidth(parseFloat(field, sweeper.getBeamWidth()));
break;
case 104:
sweeper.setBeamHeight(parseFloat(field, sweeper.getBeamHeight()));
break;
case 105:
sweeper.setSweepSpeed(parseFloat(field, sweeper.getSweepSpeed()));
break;
case 106:
sweeper.setNumberOfRotations(field.getInteger());
break;
}
}
@Override
protected void handleVisualTextField(int id, GuiNpcTextField field) {
switch (id) {
case 203:
sweeper.setOuterColorWidth(parseFloat(field, sweeper.getOuterColorWidth()));
break;
}
}
}
@@ -1,165 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilityTeleport;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Teleport ability type-specific settings.
*/
public class SubGuiAbilityTeleport extends SubGuiAbilityConfig {
private final AbilityTeleport teleport;
public SubGuiAbilityTeleport(AbilityTeleport ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.teleport = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Mode
addLabel(new GuiNpcLabel(100, "ability.mode", labelX, y + 5));
String[] modes = {"Blink", "Behind", "Single"};
addButton(new GuiNpcButton(100, fieldX, y, 80, 20, modes, teleport.getModeEnum().ordinal()));
y += 24;
switch (teleport.getModeEnum()) {
case BLINK:
// Row 2: Blink Radius + Blink Count
addLabel(new GuiNpcLabel(101, "ability.blinkRadius", labelX, y + 5));
addTextField(createFloatField(101, fieldX, y, 50, teleport.getBlinkRadius()));
addLabel(new GuiNpcLabel(102, "ability.blinkCount", col2LabelX, y + 5));
addTextField(createIntField(102, col2FieldX, y, 50, teleport.getBlinkCount()));
y += 24;
// Row 3: Blink Delay + Line of Sight
addLabel(new GuiNpcLabel(103, "ability.blinkDelay", labelX, y + 5));
addTextField(createIntField(103, fieldX, y, 50, teleport.getBlinkDelayTicks()));
addLabel(new GuiNpcLabel(105, "ability.lineOfSight", col2LabelX, y + 5));
GuiNpcButton losBtn1 = new GuiNpcButton(105, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isRequireLineOfSight() ? 1 : 0);
losBtn1.setHoverText("ability.hover.lineOfSight");
addButton(losBtn1);
y += 24;
break;
case SINGLE:
// Row 2: Blink Radius + Line of Sight
addLabel(new GuiNpcLabel(101, "ability.blinkRadius", labelX, y + 5));
addTextField(createFloatField(101, fieldX, y, 50, teleport.getBlinkRadius()));
addLabel(new GuiNpcLabel(105, "ability.lineOfSight", col2LabelX, y + 5));
GuiNpcButton losBtn2 = new GuiNpcButton(105, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isRequireLineOfSight() ? 1 : 0);
losBtn2.setHoverText("ability.hover.lineOfSight");
addButton(losBtn2);
y += 24;
break;
case BEHIND:
// Row 2: Behind Distance
addLabel(new GuiNpcLabel(104, "ability.behindDistance", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, teleport.getBehindDistance()));
y += 24;
break;
}
// Damage + Damage Radius
addLabel(new GuiNpcLabel(106, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(106, fieldX, y, 50, teleport.getDamage()));
addLabel(new GuiNpcLabel(107, "ability.dmgRadius", col2LabelX, y + 5));
addTextField(createFloatField(107, col2FieldX, y, 50, teleport.getDamageRadius()));
y += 24;
// Damage at Start/End
addLabel(new GuiNpcLabel(108, "ability.dmgAtStart", labelX, y + 5));
GuiNpcButton dmgStartBtn = new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isDamageAtStart() ? 1 : 0);
dmgStartBtn.setHoverText("ability.hover.dmgAtStart");
addButton(dmgStartBtn);
addLabel(new GuiNpcLabel(109, "ability.dmgAtEnd", col2LabelX, y + 5));
GuiNpcButton dmgEndBtn = new GuiNpcButton(109, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isDamageAtEnd() ? 1 : 0);
dmgEndBtn.setHoverText("ability.hover.dmgAtEnd");
addButton(dmgEndBtn);
y += 24;
// Effects button
addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects"));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 100:
teleport.setModeEnum(AbilityTeleport.TeleportMode.values()[value]);
initGui();
break;
case 105:
teleport.setRequireLineOfSight(value == 1);
break;
case 108:
teleport.setDamageAtStart(value == 1);
break;
case 109:
teleport.setDamageAtEnd(value == 1);
break;
case 150:
setSubGui(new SubGuiAbilityEffects(teleport.getEffects()));
break;
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
super.subGuiClosed(subgui);
if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
teleport.setEffects(result);
}
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 101:
teleport.setBlinkRadius(parseFloat(field, teleport.getBlinkRadius()));
break;
case 102:
teleport.setBlinkCount(field.getInteger());
break;
case 103:
teleport.setBlinkDelayTicks(field.getInteger());
break;
case 104:
teleport.setBehindDistance(parseFloat(field, teleport.getBehindDistance()));
break;
case 106:
teleport.setDamage(parseFloat(field, teleport.getDamage()));
break;
case 107:
teleport.setDamageRadius(parseFloat(field, teleport.getDamageRadius()));
break;
}
}
}
@@ -1,126 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilityTrap;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Trap ability type-specific settings.
*/
public class SubGuiAbilityTrap extends SubGuiAbilityConfig {
private final AbilityTrap trap;
public SubGuiAbilityTrap(AbilityTrap ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.trap = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Duration + Placement
addLabel(new GuiNpcLabel(99, "ability.duration", labelX, y + 5));
GuiNpcTextField durationField = createIntField(99, fieldX, y, 50, trap.getDurationTicks());
durationField.setMinMaxDefault(1, 2000, 200);
addTextField(durationField);
addLabel(new GuiNpcLabel(100, "ability.placement", col2LabelX, y + 5));
String[] placements = {"Caster", "Target", "Ahead"};
GuiNpcButton placementBtn = new GuiNpcButton(100, col2FieldX, y, 55, 20, placements, trap.getPlacementEnum().ordinal());
placementBtn.setHoverText("ability.hover.placement");
addButton(placementBtn);
y += 24;
// Row 2: Trigger Radius
addLabel(new GuiNpcLabel(101, "ability.triggerRad", labelX, y + 5));
addTextField(createFloatField(101, fieldX, y, 50, trap.getTriggerRadius()));
y += 24;
// Row 2: Damage + Damage Radius
addLabel(new GuiNpcLabel(102, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, trap.getDamage()));
addLabel(new GuiNpcLabel(103, "ability.dmgRadius", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, trap.getDamageRadius()));
y += 24;
// Row 3: Arm Time + Max Triggers
addLabel(new GuiNpcLabel(104, "ability.armTime", labelX, y + 5));
addTextField(createIntField(104, fieldX, y, 50, trap.getArmTime()));
addLabel(new GuiNpcLabel(105, "ability.maxTriggers", col2LabelX, y + 5));
addTextField(createIntField(105, col2FieldX, y, 50, trap.getMaxTriggers()));
y += 24;
// Row 4: Knockback + Effects button
addLabel(new GuiNpcLabel(108, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(108, fieldX, y, 50, trap.getKnockback()));
addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects"));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
if (id == 100) {
trap.setPlacementEnum(AbilityTrap.TrapPlacement.values()[button.getValue()]);
} else if (id == 150) {
setSubGui(new SubGuiAbilityEffects(trap.getEffects()));
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
super.subGuiClosed(subgui);
if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
trap.setEffects(result);
}
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 99:
trap.setDurationTicks(field.getInteger());
break;
case 101:
trap.setTriggerRadius(parseFloat(field, trap.getTriggerRadius()));
break;
case 102:
trap.setDamage(parseFloat(field, trap.getDamage()));
break;
case 103:
trap.setDamageRadius(parseFloat(field, trap.getDamageRadius()));
break;
case 104:
trap.setArmTime(field.getInteger());
break;
case 105:
trap.setMaxTriggers(field.getInteger());
break;
case 108:
trap.setKnockback(parseFloat(field, trap.getKnockback()));
break;
}
}
}
@@ -1,129 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.type.AbilityVortex;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
/**
* GUI for configuring Vortex ability type-specific settings.
*/
public class SubGuiAbilityVortex extends SubGuiAbilityConfig {
private final AbilityVortex vortex;
public SubGuiAbilityVortex(AbilityVortex ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.vortex = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Pull Radius + Pull Strength
addLabel(new GuiNpcLabel(100, "ability.pullRadius", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, vortex.getPullRadius()));
addLabel(new GuiNpcLabel(101, "ability.pullStrength", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, vortex.getPullStrength()));
y += 24;
// Row 2: Damage + Knockback
addLabel(new GuiNpcLabel(102, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, vortex.getDamage()));
addLabel(new GuiNpcLabel(103, "ability.knockback", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, vortex.getKnockback()));
y += 24;
// Row 3: AOE + Max Targets
addLabel(new GuiNpcLabel(104, "ability.aoe", labelX, y + 5));
GuiNpcButton aoeBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, vortex.isAoe() ? 1 : 0);
aoeBtn.setHoverText("ability.hover.aoe");
addButton(aoeBtn);
addLabel(new GuiNpcLabel(105, "ability.maxTargets", col2LabelX, y + 5));
addTextField(createIntField(105, col2FieldX, y, 50, vortex.getMaxTargets()));
y += 24;
// Row 4: Effects button
addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects"));
y += 24;
// Row 5: Damage on Pull + Pull Damage
addLabel(new GuiNpcLabel(108, "ability.dmgOnPull", labelX, y + 5));
GuiNpcButton dmgOnPullBtn = new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, vortex.isDamageOnPull() ? 1 : 0);
dmgOnPullBtn.setHoverText("ability.hover.dmgOnPull");
addButton(dmgOnPullBtn);
addLabel(new GuiNpcLabel(109, "ability.pullDamage", col2LabelX, y + 5));
addTextField(createFloatField(109, col2FieldX, y, 50, vortex.getPullDamage()));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 104:
vortex.setAoe(value == 1);
break;
case 108:
vortex.setDamageOnPull(value == 1);
break;
case 150:
setSubGui(new SubGuiAbilityEffects(vortex.getEffects()));
break;
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
super.subGuiClosed(subgui);
if (subgui instanceof SubGuiAbilityEffects) {
SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui;
List<AbilityEffect> result = effectsGui.getResult();
if (result != null) {
vortex.setEffects(result);
}
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100:
vortex.setPullRadius(parseFloat(field, vortex.getPullRadius()));
break;
case 101:
vortex.setPullStrength(parseFloat(field, vortex.getPullStrength()));
break;
case 102:
vortex.setDamage(parseFloat(field, vortex.getDamage()));
break;
case 103:
vortex.setKnockback(parseFloat(field, vortex.getKnockback()));
break;
case 105:
vortex.setMaxTargets(field.getInteger());
break;
case 109:
vortex.setPullDamage(parseFloat(field, vortex.getPullDamage()));
break;
}
}
}
@@ -0,0 +1,381 @@
package noppes.npcs.client.gui.builder;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import noppes.npcs.controllers.AnimationController;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.select.GuiAnimationSelection;
import noppes.npcs.client.gui.select.GuiSoundSelection;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.List;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Declarative field definition for GUI rendering.
* Built via static factories and chaining methods.
* Client-side only — never instantiate or reference on the server.
*/
@SideOnly(Side.CLIENT)
public class FieldDef {
private final String label;
private final FieldType type;
private String tab = null;
private Supplier<Object> getter;
private Consumer<Object> setter;
private BooleanSupplier visibleWhen = () -> true;
private BooleanSupplier enabledWhen = () -> true;
private String hoverText = null;
// Numeric range
private float min = Float.MIN_VALUE;
private float max = Float.MAX_VALUE;
// Enum support
private Class<? extends Enum<?>> enumClass;
private String[] stringEnumValues;
private Supplier<String> stringEnumGetter;
private Consumer<String> stringEnumSetter;
// Sub-gui support
private Supplier<SubGuiInterface> subGuiFactory;
private Consumer<SubGuiInterface> subGuiResultHandler;
// Button display
private Supplier<String> buttonLabelSupplier;
private Supplier<Integer> buttonTextColorSupplier;
private Runnable clearAction;
// Row pairing (ROW type only)
private FieldDef leftChild;
private FieldDef rightChild;
private FieldDef(String label, FieldType type) {
this.label = label;
this.type = type;
}
// ═══════════════════════════════════════════════════════════════════
// STATIC FACTORIES
// ═══════════════════════════════════════════════════════════════════
public static FieldDef section(String label) {
return new FieldDef(label, FieldType.SECTION_HEADER);
}
public static FieldDef floatField(String label, Supplier<Float> getter, Consumer<Float> setter) {
FieldDef def = new FieldDef(label, FieldType.FLOAT);
def.getter = () -> getter.get();
def.setter = v -> setter.accept(((Number) v).floatValue());
return def;
}
public static FieldDef intField(String label, Supplier<Integer> getter, Consumer<Integer> setter) {
FieldDef def = new FieldDef(label, FieldType.INT);
def.getter = () -> getter.get();
def.setter = v -> setter.accept(((Number) v).intValue());
return def;
}
public static FieldDef boolField(String label, Supplier<Boolean> getter, Consumer<Boolean> setter) {
FieldDef def = new FieldDef(label, FieldType.BOOLEAN);
def.getter = () -> getter.get();
def.setter = v -> setter.accept((Boolean) v);
return def;
}
@SuppressWarnings("unchecked")
public static <E extends Enum<E>> FieldDef enumField(String label, Class<E> enumClass, Supplier<E> getter, Consumer<E> setter) {
FieldDef def = new FieldDef(label, FieldType.ENUM);
def.enumClass = enumClass;
def.getter = () -> getter.get();
def.setter = v -> setter.accept((E) v);
return def;
}
public static FieldDef stringEnumField(String label, String[] values, Supplier<String> getter, Consumer<String> setter) {
FieldDef def = new FieldDef(label, FieldType.STRING_ENUM);
def.stringEnumValues = values;
def.stringEnumGetter = getter;
def.stringEnumSetter = setter;
return def;
}
public static FieldDef stringField(String label, Supplier<String> getter, Consumer<String> setter) {
FieldDef def = new FieldDef(label, FieldType.STRING);
def.getter = () -> getter.get();
def.setter = v -> setter.accept((String) v);
return def;
}
public static FieldDef labelField(String label, Supplier<String> textSupplier) {
FieldDef def = new FieldDef(label, FieldType.LABEL);
def.getter = () -> textSupplier.get();
return def;
}
public static FieldDef subGuiField(String label, Supplier<SubGuiInterface> factory, Consumer<SubGuiInterface> resultHandler) {
FieldDef def = new FieldDef(label, FieldType.SUB_GUI);
def.subGuiFactory = factory;
def.subGuiResultHandler = resultHandler;
return def;
}
/**
* Creates a FieldDef with a custom FieldType. Used by extension code
* (e.g. AbilityFieldDefs) to create fields with types like EFFECTS_LIST
* that the base GuiFieldBuilder does not handle.
*/
public static FieldDef custom(String label, FieldType type, Supplier<Object> getter, Consumer<Object> setter) {
FieldDef def = new FieldDef(label, type);
def.getter = getter;
def.setter = setter;
return def;
}
/**
* Creates a two-column row pairing two fields side by side.
* If one child is hidden (via visibleWhen), the other renders full-width.
*/
public static FieldDef row(FieldDef left, FieldDef right) {
FieldDef def = new FieldDef("", FieldType.ROW);
def.leftChild = left;
def.rightChild = right;
return def;
}
// ═══════════════════════════════════════════════════════════════════
// CONVENIENCE FACTORIES (SUB_GUI wrappers)
// ═══════════════════════════════════════════════════════════════════
public static FieldDef colorSubGui(String label, Supplier<Integer> getter, Consumer<Integer> setter) {
return subGuiField(label,
() -> new SubGuiColorSelector(getter.get()),
gui -> setter.accept(((SubGuiColorSelector) gui).color & 0x00FFFFFF))
.buttonLabel(() -> String.format("%06X", getter.get() & 0xFFFFFF))
.buttonTextColor(() -> getter.get() & 0xFFFFFF);
}
public static FieldDef soundSubGui(String label, Supplier<String> getter, Consumer<String> setter) {
return subGuiField(label,
() -> new GuiSoundSelection(getter.get()),
gui -> {
GuiSoundSelection s = (GuiSoundSelection) gui;
if (s.selectedResource != null) setter.accept(s.selectedResource.toString());
})
.buttonLabel(() -> {
String s = getter.get();
return s == null || s.isEmpty() ? "gui.none" : s;
})
.clearable(() -> setter.accept(""));
}
public static FieldDef animSubGui(String label,
Supplier<Integer> idGetter, Consumer<Integer> idSetter,
Supplier<String> nameGetter, Consumer<String> nameSetter) {
return subGuiField(label,
() -> new GuiAnimationSelection(idGetter.get(), nameGetter.get()),
gui -> {
GuiAnimationSelection sel = (GuiAnimationSelection) gui;
if (sel.isBuiltInSelected()) {
nameSetter.accept(sel.selectedBuiltInName);
idSetter.accept(-1);
} else {
idSetter.accept(sel.selectedAnimationId);
nameSetter.accept("");
}
})
.buttonLabel(() -> {
String name = nameGetter.get();
if (name != null && !name.isEmpty()) return name;
int id = idGetter.get();
if (id >= 0) {
Animation anim = AnimationController.Instance != null
? (Animation) AnimationController.Instance.get(id) : null;
String animName = anim != null ? anim.getName() : "";
return animName != null && !animName.isEmpty()
? "(ID: " + id + ") " + animName : "ID: " + id;
}
return "gui.none";
})
.clearable(() -> { idSetter.accept(-1); nameSetter.accept(""); });
}
// ═══════════════════════════════════════════════════════════════════
// CHAINING METHODS
// ═══════════════════════════════════════════════════════════════════
public FieldDef tab(String tabName) {
this.tab = tabName;
return this;
}
public FieldDef range(float min, float max) {
this.min = min;
this.max = max;
return this;
}
public FieldDef min(float min) {
this.min = min;
return this;
}
public FieldDef max(float max) {
this.max = max;
return this;
}
public FieldDef visibleWhen(BooleanSupplier condition) {
this.visibleWhen = condition;
return this;
}
public FieldDef enabledWhen(BooleanSupplier condition) {
this.enabledWhen = condition;
return this;
}
public FieldDef hover(String hoverText) {
this.hoverText = hoverText;
return this;
}
public FieldDef buttonLabel(Supplier<String> supplier) {
this.buttonLabelSupplier = supplier;
return this;
}
public FieldDef buttonTextColor(Supplier<Integer> supplier) {
this.buttonTextColorSupplier = supplier;
return this;
}
public FieldDef clearable(Runnable action) {
this.clearAction = action;
return this;
}
// ═══════════════════════════════════════════════════════════════════
// GETTERS
// ═══════════════════════════════════════════════════════════════════
public String getLabel() { return label; }
public FieldType getType() { return type; }
public String getTab() { return tab; }
public boolean isVisible() { return visibleWhen.getAsBoolean(); }
public boolean isEnabled() { return enabledWhen.getAsBoolean(); }
public String getHoverText() { return hoverText; }
public float getMin() { return min; }
public float getMax() { return max; }
public boolean hasRange() { return min != Float.MIN_VALUE || max != Float.MAX_VALUE; }
public Class<? extends Enum<?>> getEnumClass() { return enumClass; }
public String[] getStringEnumValues() { return stringEnumValues; }
public Supplier<SubGuiInterface> getSubGuiFactory() { return subGuiFactory; }
public Consumer<SubGuiInterface> getSubGuiResultHandler() { return subGuiResultHandler; }
public boolean hasClearAction() { return clearAction != null; }
public Runnable getClearAction() { return clearAction; }
public Object getValue() {
return getter != null ? getter.get() : null;
}
public void setValue(Object value) {
if (setter != null) setter.accept(value);
}
public String getStringEnumValue() {
return stringEnumGetter != null ? stringEnumGetter.get() : null;
}
public void setStringEnumValue(String value) {
if (stringEnumSetter != null) stringEnumSetter.accept(value);
}
public String getButtonLabel() {
if (buttonLabelSupplier != null) return buttonLabelSupplier.get();
return label;
}
public Integer getButtonTextColor() {
return buttonTextColorSupplier != null ? buttonTextColorSupplier.get() : null;
}
public FieldDef getLeftChild() { return leftChild; }
public FieldDef getRightChild() { return rightChild; }
// ═══════════════════════════════════════════════════════════════════
// LIST MANIPULATION (for mod injection)
// ═══════════════════════════════════════════════════════════════════
/**
* Insert a field before the first field matching the target label.
* Searches top-level labels and ROW children.
*
* @param fields The field list to modify
* @param targetLabel The label of the field to insert before
* @param newField The field to insert
* @return true if the target was found and the field was inserted
*/
public static boolean insertBefore(java.util.List<FieldDef> fields, String targetLabel, FieldDef newField) {
for (int i = 0; i < fields.size(); i++) {
if (matchesLabel(fields.get(i), targetLabel)) {
fields.add(i, newField);
return true;
}
}
return false;
}
/**
* Insert a field after the first field matching the target label.
* Searches top-level labels and ROW children.
*
* @param fields The field list to modify
* @param targetLabel The label of the field to insert after
* @param newField The field to insert
* @return true if the target was found and the field was inserted
*/
public static boolean insertAfter(List<FieldDef> fields, String targetLabel, FieldDef newField) {
for (int i = 0; i < fields.size(); i++) {
if (matchesLabel(fields.get(i), targetLabel)) {
fields.add(i + 1, newField);
return true;
}
}
return false;
}
/**
* Modify the visibility condition of a field.
* Searches top-level labels and ROW children.
*
* @param fields The field list to modify
* @param targetLabel The label of the field to modify
* @param condition The condition to replace
* @return true if the target was found and the condition was modified
*/
public static boolean modifyVisibility(List<FieldDef> fields, String targetLabel, BooleanSupplier condition) {
for (FieldDef field : fields) {
if (matchesLabel(field, targetLabel)) {
field.visibleWhen(condition);
return true;
}
}
return false;
}
private static boolean matchesLabel(FieldDef def, String targetLabel) {
if (targetLabel.equals(def.label)) return true;
if (def.type == FieldType.ROW) {
if (def.leftChild != null && targetLabel.equals(def.leftChild.label)) return true;
if (def.rightChild != null && targetLabel.equals(def.rightChild.label)) return true;
}
return false;
}
}
@@ -0,0 +1,19 @@
package noppes.npcs.client.gui.builder;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public enum FieldType {
FLOAT,
INT,
BOOLEAN,
ENUM,
STRING_ENUM,
SUB_GUI,
STRING,
SECTION_HEADER,
LABEL,
EFFECTS_LIST,
ROW
}
@@ -0,0 +1,462 @@
package noppes.npcs.client.gui.builder;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.util.GuiNPCInterface;
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.SubGuiInterface;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* General-purpose builder that converts a list of {@link FieldDef} into positioned
* GUI widgets inside a {@link GuiScrollWindow}.
* <p>
* Uses {@link FieldDef#row(FieldDef, FieldDef)} for two-column layouts.
* Subclasses can override {@link #buildField} to handle custom field types.
*/
@SideOnly(Side.CLIENT)
public class GuiFieldBuilder {
// Layout defaults (2-column mode)
protected int contentRight = 330;
protected int colLLabel = 5;
protected int colLField = 75;
protected int colLWidth = 70;
protected int colRLabel = 178;
protected int colRField = 248;
protected int colRWidth = 70;
protected int rowHeight = 24;
protected int labelPadding = 8;
// Dependencies
protected final GuiNPCInterface parent;
protected GuiScrollWindow sw;
protected final FontRenderer fontRenderer;
// Scroll window ID
protected int scrollWindowId = 0;
// ID counters
protected int widgetId;
protected int clearId;
protected int labelId;
// Starting Y
protected int startY = 5;
protected int lastBuildY = 0;
// Output maps
protected final Map<Integer, FieldDef> buttonFieldMap = new HashMap<>();
protected final Map<Integer, FieldDef> textFieldMap = new HashMap<>();
protected final Map<Integer, FieldDef> clearFieldMap = new HashMap<>();
public GuiFieldBuilder(GuiNPCInterface parent, FontRenderer fontRenderer) {
this.parent = parent;
this.fontRenderer = fontRenderer;
}
// ═══════════════════════════════════════════════════════════════════
// CONFIG CHAINING
// ═══════════════════════════════════════════════════════════════════
public GuiFieldBuilder scrollWindowId(int id) { this.scrollWindowId = id; return this; }
public GuiFieldBuilder contentRight(int v) { this.contentRight = v; return this; }
public GuiFieldBuilder startIds(int widget, int clear, int label) {
this.widgetId = widget; this.clearId = clear; this.labelId = label; return this;
}
public GuiFieldBuilder startY(int y) { this.startY = y; return this; }
public GuiFieldBuilder rowHeight(int h) { this.rowHeight = h; return this; }
// ═══════════════════════════════════════════════════════════════════
// BUILD
// ═══════════════════════════════════════════════════════════════════
/**
* Creates a {@link GuiScrollWindow} at the given position/size, builds all fields into it,
* and sets maxScrollY automatically. The returned window is ready to use.
*/
public GuiScrollWindow buildScrollWindow(List<FieldDef> fields, int x, int y, int width, int height) {
this.sw = new GuiScrollWindow(parent, x, y, width, height, 0);
sw.backgroundColor = 0x88000000;
// Register with parent first — this calls initGui() which clears widget lists,
// so we must add widgets AFTER this point
parent.addScrollableGui(scrollWindowId, sw);
int finalY = build(fields);
sw.maxScrollY = Math.max(finalY - height, 0);
return sw;
}
/**
* Processes all fields and adds widgets to the scroll window.
* @return the final Y position after all fields
*/
protected int build(List<FieldDef> fields) {
buttonFieldMap.clear();
textFieldMap.clear();
clearFieldMap.clear();
int y = startY;
for (int i = 0; i < fields.size(); i++) {
FieldDef def = fields.get(i);
// Let subclasses handle custom types; returns -1 if not handled
int customResult = buildField(def, y, fields, i);
if (customResult >= 0) {
// Subclass handled it, check if index was advanced
int newIndex = getLastHandledIndex();
if (newIndex > i) i = newIndex;
y = customResult;
continue;
}
// Skip invisible fields
if (!def.isVisible()) continue;
// Section header
if (def.getType() == FieldType.SECTION_HEADER) {
y += 3;
GuiNpcLabel sectionLabel = new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55);
if (def.getHoverText() != null && !def.getHoverText().isEmpty()) {
sectionLabel.setHoverText(def.getHoverText());
}
sw.addLabel(sectionLabel);
y += 15;
continue;
}
// ROW: explicit two-column pair
if (def.getType() == FieldType.ROW) {
FieldDef left = def.getLeftChild();
FieldDef right = def.getRightChild();
boolean leftVis = left != null && left.isVisible();
boolean rightVis = right != null && right.isVisible();
if (leftVis && rightVis) {
renderFieldAt(left, colLLabel, colLField, colLWidth, y);
renderFieldAt(right, colRLabel, colRField, colRWidth, y);
} else if (leftVis) {
renderFullWidth(left, y);
} else if (rightVis) {
renderFullWidth(right, y);
}
if (leftVis || rightVis) y += rowHeight;
continue;
}
// Full-width field
renderFullWidth(def, y);
y += rowHeight;
}
lastBuildY = y;
return y;
}
/**
* Hook for subclasses to handle custom field types (e.g. EFFECTS_LIST).
* Return the new Y position if handled, or -1 if not handled (base class will process it).
* If handling advances the field index, call {@link #setLastHandledIndex(int)}.
*/
protected int buildField(FieldDef def, int y, List<FieldDef> fields, int index) {
return -1;
}
private int lastHandledIndex = -1;
protected void setLastHandledIndex(int index) { this.lastHandledIndex = index; }
protected int getLastHandledIndex() { return lastHandledIndex; }
// ═══════════════════════════════════════════════════════════════════
// FIELD RENDERING
// ═══════════════════════════════════════════════════════════════════
@SuppressWarnings({"unchecked", "rawtypes"})
protected void renderFieldAt(FieldDef def, int labelX, int fieldX, int fieldW, int y) {
GuiNpcLabel fieldLabel = new GuiNpcLabel(labelId++, def.getLabel(), labelX, y + 5, 0xFFFFFF);
String hover = def.getHoverText();
if (hover != null && !hover.isEmpty()) {
fieldLabel.setHoverText(hover);
}
sw.addLabel(fieldLabel);
switch (def.getType()) {
case FLOAT: {
float fVal = def.getValue() instanceof Number ? ((Number) def.getValue()).floatValue() : 0f;
GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, fieldW, 20, String.valueOf(fVal));
tf.setFloatsOnly();
if (def.hasRange()) tf.setMinMaxDefaultFloat(def.getMin(), def.getMax(), fVal);
if (!def.isEnabled()) tf.setEnabled(false);
if (hover != null) tf.setHoverText(hover);
sw.addTextField(tf);
textFieldMap.put(widgetId, def);
widgetId++;
clearId++;
break;
}
case INT: {
int iVal = def.getValue() instanceof Number ? ((Number) def.getValue()).intValue() : 0;
GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, fieldW, 20, String.valueOf(iVal));
tf.setIntegersOnly();
if (def.hasRange()) tf.setMinMaxDefault((int) def.getMin(), (int) def.getMax(), iVal);
if (!def.isEnabled()) tf.setEnabled(false);
if (hover != null) tf.setHoverText(hover);
sw.addTextField(tf);
textFieldMap.put(widgetId, def);
widgetId++;
clearId++;
break;
}
case STRING: {
String sVal = def.getValue() != null ? def.getValue().toString() : "";
GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, fieldW, 20, sVal);
if (!def.isEnabled()) tf.setEnabled(false);
if (hover != null) tf.setHoverText(hover);
sw.addTextField(tf);
textFieldMap.put(widgetId, def);
widgetId++;
clearId++;
break;
}
case LABEL: {
String text = def.getValue() != null ? def.getValue().toString() : "";
sw.addLabel(new GuiNpcLabel(labelId++, text, fieldX, y + 5, 0xAAAAAA));
widgetId++;
clearId++;
break;
}
case BOOLEAN: {
boolean bVal = def.getValue() instanceof Boolean ? (Boolean) def.getValue() : false;
GuiNpcButtonYesNo btn = new GuiNpcButtonYesNo(widgetId, fieldX, y, fieldW, 20, bVal);
if (!def.isEnabled()) btn.setEnabled(false);
if (hover != null) btn.setHoverText(hover);
sw.addButton(btn);
buttonFieldMap.put(widgetId, def);
widgetId++;
clearId++;
break;
}
case ENUM: {
Class<? extends Enum<?>> enumClass = def.getEnumClass();
if (enumClass != null) {
Enum<?>[] constants = enumClass.getEnumConstants();
String[] names = new String[constants.length];
for (int i = 0; i < constants.length; i++) names[i] = constants[i].toString();
int selected = def.getValue() instanceof Enum ? ((Enum<?>) def.getValue()).ordinal() : 0;
GuiNpcButton btn = new GuiNpcButton(widgetId, fieldX, y, fieldW, 20, names, selected);
if (!def.isEnabled()) btn.setEnabled(false);
if (hover != null) btn.setHoverText(hover);
sw.addButton(btn);
buttonFieldMap.put(widgetId, def);
}
widgetId++;
clearId++;
break;
}
case STRING_ENUM: {
String[] values = def.getStringEnumValues();
if (values != null && values.length > 0) {
String curVal = def.getStringEnumValue();
int selected = 0;
for (int i = 0; i < values.length; i++) {
if (values[i].equals(curVal)) { selected = i; break; }
}
GuiNpcButton btn = new GuiNpcButton(widgetId, fieldX, y, fieldW, 20, values, selected);
if (!def.isEnabled()) btn.setEnabled(false);
if (hover != null) btn.setHoverText(hover);
sw.addButton(btn);
buttonFieldMap.put(widgetId, def);
}
widgetId++;
clearId++;
break;
}
case SUB_GUI: {
String btnText = def.getButtonLabel();
int btnW;
if (def.hasClearAction()) {
btnW = contentRight - 22 - fieldX;
GuiNpcButton clearBtn = new GuiNpcButton(clearId, contentRight - 20, y, 20, 20, "X");
sw.addButton(clearBtn);
clearFieldMap.put(clearId, def);
} else {
btnW = contentRight - fieldX;
}
GuiNpcButton btn = new GuiNpcButton(widgetId, fieldX, y, btnW, 20, btnText);
Integer textColor = def.getButtonTextColor();
if (textColor != null) btn.setTextColor(textColor);
if (!def.isEnabled()) btn.setEnabled(false);
if (hover != null) btn.setHoverText(hover);
sw.addButton(btn);
buttonFieldMap.put(widgetId, def);
widgetId++;
clearId++;
break;
}
default:
// Unknown type — skip, incrementing IDs to stay in sync
widgetId++;
clearId++;
break;
}
}
private void renderFullWidth(FieldDef def, int y) {
int fieldW = getFullFieldWidth(def);
String translated = StatCollector.translateToLocal(def.getLabel());
int labelW = fontRenderer.getStringWidth(translated);
int fieldX = colLLabel + labelW + labelPadding;
renderFieldAt(def, colLLabel, fieldX, fieldW, y);
}
protected int getFullFieldWidth(FieldDef def) {
switch (def.getType()) {
case FLOAT:
case INT: return 60;
case STRING: return 200;
case BOOLEAN: return 50;
case LABEL: return 60;
case ENUM:
case STRING_ENUM: return 120;
case SUB_GUI: return def.hasClearAction() ? 175 : 200;
default: return 80;
}
}
// ═══════════════════════════════════════════════════════════════════
// EVENT HANDLING
// ═══════════════════════════════════════════════════════════════════
/**
* Handles button events for declarative fields.
* Call from parent GUI's buttonEvent(). Returns true if the event was handled.
* <p>
* For SUB_GUI fields, the sub-gui is opened directly via {@code parent.setSubGuiWithResult()},
* so the result handler survives initGui() rebuilds. After this returns true, check
* {@code parent.hasSubGui()} to determine if initGui() should be called.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public boolean handleButtonEvent(int buttonId, GuiButton button) {
// Check clear buttons first
if (clearFieldMap.containsKey(buttonId)) {
FieldDef def = clearFieldMap.get(buttonId);
if (def != null && def.hasClearAction()) {
def.getClearAction().run();
return true;
}
}
// Check field buttons
FieldDef def = buttonFieldMap.get(buttonId);
if (def == null) return false;
switch (def.getType()) {
case BOOLEAN:
def.setValue(((GuiNpcButton) button).getValue() == 1);
return true;
case ENUM: {
int idx = ((GuiNpcButton) button).getValue();
Class<? extends Enum<?>> ec = def.getEnumClass();
if (ec != null) {
Enum<?>[] constants = ec.getEnumConstants();
if (idx >= 0 && idx < constants.length) def.setValue(constants[idx]);
}
return true;
}
case STRING_ENUM: {
int idx = ((GuiNpcButton) button).getValue();
String[] values = def.getStringEnumValues();
if (values != null && idx >= 0 && idx < values.length) def.setStringEnumValue(values[idx]);
return true;
}
case SUB_GUI:
if (def.getSubGuiFactory() != null) {
parent.setSubGuiWithResult(def.getSubGuiFactory().get(), sub -> {
if (def.getSubGuiResultHandler() != null) {
def.getSubGuiResultHandler().accept(sub);
}
});
}
return true;
default:
return false;
}
}
/**
* Handles text field unfocus events for declarative fields.
* Call from parent GUI's unFocused(). Returns true if the value actually changed.
*/
public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) {
FieldDef def = textFieldMap.get(textFieldId);
if (def == null) return false;
switch (def.getType()) {
case FLOAT:
try {
float newVal = Float.parseFloat(field.getText());
Object old = def.getValue();
float oldVal = old instanceof Number ? ((Number) old).floatValue() : 0f;
if (newVal != oldVal) {
def.setValue(newVal);
return true;
}
} catch (NumberFormatException ignored) {}
return false;
case INT:
try {
int newVal = Integer.parseInt(field.getText());
Object old = def.getValue();
int oldVal = old instanceof Number ? ((Number) old).intValue() : 0;
if (newVal != oldVal) {
def.setValue(newVal);
return true;
}
} catch (NumberFormatException ignored) {}
return false;
case STRING:
String newVal = field.getText();
Object old = def.getValue();
String oldVal = old != null ? old.toString() : "";
if (!newVal.equals(oldVal)) {
def.setValue(newVal);
return true;
}
return false;
default:
return false;
}
}
/**
* Handles sub-gui close events. Call from parent GUI's subGuiClosed().
* <p>
* Note: SUB_GUI fields opened via handleButtonEvent use
* {@code parent.setSubGuiWithResult()}, so their results are handled
* automatically by {@code GuiNPCInterface.closeSubGui()}. This method
* only handles sub-guis opened through other means.
*/
public boolean handleSubGuiClosed(SubGuiInterface subgui) {
return false;
}
// ═══════════════════════════════════════════════════════════════════
// GETTERS
// ═══════════════════════════════════════════════════════════════════
public Map<Integer, FieldDef> getButtonFieldMap() { return buttonFieldMap; }
public Map<Integer, FieldDef> getTextFieldMap() { return textFieldMap; }
public Map<Integer, FieldDef> getClearFieldMap() { return clearFieldMap; }
public GuiScrollWindow getScrollWindow() { return sw; }
public int getLastBuildY() { return lastBuildY; }
public int getNextLabelId() { return labelId; }
}
@@ -51,8 +51,8 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
// Track if current animation is built-in
private boolean currentIsBuiltIn = false;
public GuiNPCManageAnimations(EntityNPCInterface npc, boolean save) {
super(npc);
public GuiNPCManageAnimations(EntityNPCInterface npc, boolean save, boolean hasMenuNpc) {
super(npc, hasMenuNpc);
this.setSave(save);
this.xOffset = -148 + 70;
this.yOffset = -170 + 137;
@@ -65,16 +65,17 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
public void initGui() {
super.initGui();
// Toggle button - added FIRST to maintain stable buttonList index
// (prevents double-toggle when initGui() is called from actionPerformed)
String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom";
this.addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 56, 45, 20, toggleLabel));
// Add/Remove buttons - only show for custom animations
if (!showingBuiltIn) {
this.addButton(new GuiNpcButton(0, guiLeft + 368, guiTop + 8, 45, 20, "gui.add"));
this.addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 32, 45, 20, "gui.remove"));
}
// Toggle button for Custom/Built-in - under Remove button
String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom";
this.addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 56, 45, 20, toggleLabel));
if (scrollAnimations == null) {
scrollAnimations = new GuiCustomScroll(this, 0, 0);
scrollAnimations.setSize(143, 185);
@@ -200,11 +201,15 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
// Toggle button
if (button.id == 10) {
showingBuiltIn = !showingBuiltIn;
// Clear selection when switching views
// Clear selection and search when switching views
selected = null;
search = "";
animation = new Animation();
currentIsBuiltIn = false;
playingAnimation = false;
scrollAnimations.clear();
// Re-request data to ensure both lists are populated
PacketClient.sendClient(new AnimationsGetPacket());
initGui();
return;
}
@@ -85,11 +85,13 @@ public class GuiNPCManageFactions extends GuiNPCInterface2 implements IScrollDat
addLabel(new GuiNpcLabel(3, "faction.hidden", guiLeft + 8, y + 5));
this.addButton(new GuiNpcButton(3, guiLeft + 100, y, 45, 20, new String[]{"gui.no", "gui.yes"}, faction.hideFaction ? 1 : 0));
getButton(3).setHoverText("faction.hidden.hover");
y += 23;
addLabel(new GuiNpcLabel(4, "faction.attacked", guiLeft + 8, y + 5));
this.addButton(new GuiNpcButton(4, guiLeft + 100, y, 45, 20, new String[]{"gui.no", "gui.yes"}, faction.getsAttacked ? 1 : 0));
getButton(4).setHoverText("faction.attacked.hover");
y += 23;
@@ -3,6 +3,7 @@ package noppes.npcs.client.gui.global;
import kamkeel.npcs.client.renderer.TelegraphRenderer;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import java.util.UUID;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket;
@@ -15,6 +16,11 @@ import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.NoppesUtil;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.SubGuiAbilityTypeSelect;
import noppes.npcs.client.gui.advanced.SubGuiAbilityVariantSelect;
import noppes.npcs.client.gui.advanced.SubGuiDuplicateNameConfirm;
import noppes.npcs.client.gui.util.AbilityPreviewExecutor;
import noppes.npcs.client.gui.util.GuiAbilityInterface;
import noppes.npcs.client.gui.util.GuiCustomScroll;
@@ -60,12 +66,19 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
private String search = "";
private Ability selectedAbility = null;
// ==================== PENDING SAVE ====================
private Ability pendingSaveAbility = null;
private boolean pendingNewCreation = false;
// ==================== PENDING VARIANT ====================
private String pendingTypeId = null;
// ==================== PREVIEW ====================
private AbilityPreviewExecutor previewExecutor;
private long prevTick = 0;
public GuiNpcManageAbilities(EntityNPCInterface npc) {
super(npc);
public GuiNpcManageAbilities(EntityNPCInterface npc, boolean hasMenuNpc) {
super(npc, hasMenuNpc);
// Layout offset
this.xOffset = -148 + 110;
@@ -87,14 +100,17 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
public void initGui() {
super.initGui();
// Edit button (above Remove)
addButton(new GuiNpcButton(100, guiLeft + 368, guiTop + 8, 45, 20, "gui.edit"));
getButton(100).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null);
// Add button
addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 8, 45, 20, "gui.add"));
// Remove button
addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 30, 45, 20, "gui.remove"));
getButton(1).setEnabled(selected != null && !selected.isEmpty() && displayToUuid.containsKey(selected));
// Edit button
addButton(new GuiNpcButton(100, guiLeft + 368, guiTop + 52, 45, 20, "gui.edit"));
getButton(100).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null);
// Scroll list of saved abilities (right side)
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
@@ -211,7 +227,10 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
int id = guibutton.id;
if (id == 1 && selected != null && selectedUuid != null) {
if (id == 2) {
// Add — open type selection
setSubGui(new SubGuiAbilityTypeSelect());
} else if (id == 1 && selected != null && selectedUuid != null) {
GuiYesNo guiyesno = new GuiYesNo(this, selected, StatCollector.translateToLocal("gui.delete"), 1);
displayGuiScreen(guiyesno);
} else if (id == 100 && selectedAbility != null) {
@@ -329,9 +348,112 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiAbilityVariantSelect) {
SubGuiAbilityVariantSelect variantGui = (SubGuiAbilityVariantSelect) subgui;
int idx = variantGui.getSelectedIndex();
if (idx >= 0 && pendingTypeId != null) {
Ability newAbility = AbilityController.Instance.create(pendingTypeId);
if (newAbility != null) {
variantGui.getVariants().get(idx).apply(newAbility);
newAbility.setId(UUID.randomUUID().toString());
if (hasDuplicateName(newAbility)) {
pendingSaveAbility = newAbility;
pendingNewCreation = true;
pendingTypeId = null;
setSubGui(new SubGuiDuplicateNameConfirm());
return;
}
pendingTypeId = null;
saveAndOpenConfig(newAbility);
return;
}
}
pendingTypeId = null;
} else if (subgui instanceof SubGuiAbilityTypeSelect) {
String typeId = ((SubGuiAbilityTypeSelect) subgui).getSelectedTypeId();
if (typeId != null) {
java.util.List<AbilityVariant> variants = AbilityController.Instance.getVariantsForType(typeId);
if (variants.size() > 1) {
pendingTypeId = typeId;
setSubGui(new SubGuiAbilityVariantSelect(variants));
return;
}
Ability newAbility = AbilityController.Instance.create(typeId);
if (newAbility != null) {
if (variants.size() == 1) {
variants.get(0).apply(newAbility);
}
newAbility.setId(UUID.randomUUID().toString());
if (hasDuplicateName(newAbility)) {
pendingSaveAbility = newAbility;
pendingNewCreation = true;
setSubGui(new SubGuiDuplicateNameConfirm());
return;
}
saveAndOpenConfig(newAbility);
return;
}
}
} else if (subgui instanceof SubGuiDuplicateNameConfirm) {
SubGuiDuplicateNameConfirm confirm = (SubGuiDuplicateNameConfirm) subgui;
if (confirm.isConfirmed() && pendingSaveAbility != null) {
if (pendingNewCreation) {
saveAndOpenConfig(pendingSaveAbility);
pendingSaveAbility = null;
pendingNewCreation = false;
return;
} else {
PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT()));
PacketClient.sendClient(new CustomAbilitiesGetPacket());
pendingSaveAbility = null;
}
} else if (pendingSaveAbility != null) {
if (pendingNewCreation) {
// Cancel new creation - discard
pendingSaveAbility = null;
pendingNewCreation = false;
} else {
// Cancel edit save - re-open config GUI to change name
Ability ability = pendingSaveAbility;
pendingSaveAbility = null;
setSubGui(ability.createConfigGui(this));
return;
}
}
} else if (pendingSaveAbility != null) {
// Config GUI closed with a pending save (set by onAbilitySaved)
if (hasDuplicateName(pendingSaveAbility)) {
pendingNewCreation = false;
setSubGui(new SubGuiDuplicateNameConfirm());
return;
}
PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT()));
PacketClient.sendClient(new CustomAbilitiesGetPacket());
pendingSaveAbility = null;
}
initGui();
}
private void saveAndOpenConfig(Ability ability) {
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
selectedAbility = ability;
selected = ability.getName();
selectedUuid = ability.getId();
previewExecutor.stop();
setSubGui(ability.createConfigGui(this));
}
private boolean hasDuplicateName(Ability ability) {
String name = ability.getName();
if (name == null || name.isEmpty()) return false;
for (java.util.Map.Entry<String, String> entry : displayToUuid.entrySet()) {
if (entry.getKey().equals(name) && !entry.getValue().equals(ability.getId())) {
return true;
}
}
return false;
}
@Override
public void confirmClicked(boolean result, int id) {
NoppesUtil.openGUI(player, this);
@@ -349,7 +471,8 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
@Override
public void onAbilitySaved(Ability ability) {
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
// Defer save until subGuiClosed where we can check for duplicate names
pendingSaveAbility = ability;
}
@Override
@@ -4,14 +4,18 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
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.constants.EnumClaimType;
import noppes.npcs.containers.ContainerAuctionListing;
import noppes.npcs.containers.ContainerAuctionSell;
import noppes.npcs.containers.ContainerAuctionTrades;
import noppes.npcs.containers.SlotAuctionDisplay;
import noppes.npcs.controllers.data.AuctionClaim;
import noppes.npcs.controllers.data.AuctionListing;
@@ -19,45 +23,60 @@ import java.util.List;
/**
* Handles adding auction information to item tooltips when viewing auction GUIs.
* Called from MixinItem when Item.addInformation is invoked.
* Called from ItemTooltipEvent in ClientEventHandler.
*
* Uses slot-based lookup (slot index) instead of ItemStack comparison to correctly
* handle duplicate items with different auction data (e.g., two porkchops at different prices).
*/
@SideOnly(Side.CLIENT)
public class AuctionTooltipHandler {
/**
* Add auction information to an item's tooltip if we're in an auction GUI.
* Handle ItemTooltipEvent - append auction info to the end of the tooltip.
*/
public static void addAuctionInfo(ItemStack stack, List<String> tooltip) {
if (stack == null || tooltip == null) return;
public static void onItemTooltip(ItemTooltipEvent event) {
if (event.itemStack == null) return;
Minecraft mc = Minecraft.getMinecraft();
if (mc == null || mc.currentScreen == null) return;
GuiScreen screen = mc.currentScreen;
// Check if we're in an auction listing GUI
if (screen instanceof GuiAuctionListing) {
addListingTooltip((GuiAuctionListing) screen, stack, tooltip);
}
// Check if we're in the trades GUI
else if (screen instanceof GuiAuctionTrades) {
addTradesTooltip((GuiAuctionTrades) screen, stack, tooltip);
}
// Check if we're in the sell GUI
else if (screen instanceof GuiAuctionSell) {
addSellTooltip((GuiAuctionSell) screen, stack, tooltip);
addListingTooltip((GuiAuctionListing) screen, event.itemStack, event.toolTip);
} else if (screen instanceof GuiAuctionTrades) {
addTradesTooltip((GuiAuctionTrades) screen, event.itemStack, event.toolTip);
} else if (screen instanceof GuiAuctionSell) {
addSellTooltip((GuiAuctionSell) screen, event.itemStack, event.toolTip);
}
}
/**
* Add auction info when viewing the main listings page.
* Find the slot in the container whose getStack() returns the exact same ItemStack reference.
* This avoids the duplicate item bug where ItemStack.areItemStacksEqual matches the wrong listing.
*/
private static Slot findHoveredSlot(GuiContainer gui, ItemStack stack) {
if (stack == null) return null;
for (Object obj : gui.inventorySlots.inventorySlots) {
Slot slot = (Slot) obj;
if (slot.getHasStack() && slot.getStack() == stack) {
return slot;
}
}
return null;
}
// ========== Listing Page ==========
private static void addListingTooltip(GuiAuctionListing gui, ItemStack stack, List<String> tooltip) {
ContainerAuctionListing container = (ContainerAuctionListing) gui.inventorySlots;
Slot slot = findHoveredSlot(gui, stack);
if (slot == null || !(slot instanceof SlotAuctionDisplay)) return;
ContainerAuctionListing container = gui.getListingContainer();
if (container == null) return;
// Find the listing that matches this ItemStack
AuctionListing listing = container.getListingForItem(stack);
int displayIndex = slot.getSlotIndex();
AuctionListing listing = container.getListingAt(displayIndex);
if (listing == null) return;
tooltip.add("");
@@ -90,149 +109,153 @@ public class AuctionTooltipHandler {
tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
}
/**
* Add auction info when viewing the trades page.
*/
// ========== Trades Page ==========
private static void addTradesTooltip(GuiAuctionTrades gui, ItemStack stack, List<String> tooltip) {
ContainerAuctionTrades container = (ContainerAuctionTrades) gui.inventorySlots;
Slot slot = findHoveredSlot(gui, stack);
if (slot == null || !(slot instanceof SlotAuctionDisplay)) return;
ContainerAuctionTrades container = gui.getTradesContainer();
if (container == null) return;
// Check if it's an item I'm selling
AuctionListing sellingListing = container.getSellingListingForItem(stack);
if (sellingListing != null) {
tooltip.add("");
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.selling"));
int displayIndex = slot.getSlotIndex();
if (sellingListing.hasBids()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(sellingListing.currentBid)));
tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), sellingListing.bidCount));
} else {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.noBids"));
// Check listings first (selling or bidding)
AuctionListing listing = container.getListingAt(displayIndex);
if (listing != null) {
if (container.isSellingAt(displayIndex)) {
addSellingTooltip(listing, tooltip);
} else if (container.isBiddingAt(displayIndex)) {
addBiddingTooltip(listing, tooltip);
}
long timeRemaining = sellingListing.getTimeRemaining();
String timeText = StatCollector.translateToLocal("auction.timeLeft")
.replace("%s", formatTimeRemaining(timeRemaining));
tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickToCancel"));
return;
}
// Check if it's an item I'm bidding on
AuctionListing biddingListing = container.getBiddingListingForItem(stack);
if (biddingListing != null) {
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.bidding"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(biddingListing.currentBid)));
tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), biddingListing.bidCount));
long timeRemaining = biddingListing.getTimeRemaining();
String timeText = StatCollector.translateToLocal("auction.timeLeft")
.replace("%s", formatTimeRemaining(timeRemaining));
tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.clickToRebid"));
return;
}
// Check if it's a claim
AuctionClaim claim = container.getClaimForItem(stack);
// Check claims
AuctionClaim claim = container.getClaimAt(displayIndex);
if (claim != null) {
tooltip.add("");
// Title based on claim type
switch (claim.type) {
case ITEM:
if (claim.isReturned) {
// Expired - returned to seller
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.expired"));
} else {
// Won item
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.won"));
}
break;
case CURRENCY:
// Sold - money to claim
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.sold"));
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));
}
break;
case REFUND:
// Outbid - refund available
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.outbid"));
if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.outbidBy")
.replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName));
}
break;
}
// Amount for currency claims (including REFUND)
if (claim.type.isCurrency()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(claim.currency)));
}
// Expiration
int expirationDays = AuctionClientConfig.getClaimExpirationDays();
long daysLeft = claim.getDaysUntilExpiration(expirationDays);
if (daysLeft <= 1) {
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.claim.expiresSoon"));
} else {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.expires")
.replace("%s", "" + daysLeft));
}
tooltip.add("");
// Show rebid option for REFUND claims with item (active auction)
if (claim.type == EnumClaimType.REFUND && claim.item != null) {
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.leftClickRebid"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickRefund"));
} else {
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.claim.clickToClaim"));
}
addClaimTooltip(claim, tooltip);
}
}
/**
* Add sell page tooltip info.
*/
private static void addSellingTooltip(AuctionListing listing, List<String> tooltip) {
tooltip.add("");
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.selling"));
if (listing.hasBids()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.currentBid)));
tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), listing.bidCount));
} else {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.noBids"));
}
long timeRemaining = listing.getTimeRemaining();
String timeText = StatCollector.translateToLocal("auction.timeLeft")
.replace("%s", formatTimeRemaining(timeRemaining));
tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickToCancel"));
}
private static void addBiddingTooltip(AuctionListing listing, List<String> tooltip) {
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.bidding"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.currentBid)));
tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), listing.bidCount));
long timeRemaining = listing.getTimeRemaining();
String timeText = StatCollector.translateToLocal("auction.timeLeft")
.replace("%s", formatTimeRemaining(timeRemaining));
tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.clickToRebid"));
}
private static void addClaimTooltip(AuctionClaim claim, List<String> tooltip) {
tooltip.add("");
switch (claim.type) {
case ITEM:
if (claim.isReturned) {
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.expired"));
} else {
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.won"));
}
break;
case CURRENCY:
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.sold"));
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));
}
break;
case REFUND:
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.outbid"));
if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.outbidBy")
.replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName));
}
break;
}
// Amount for currency claims
if (claim.type.isCurrency()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(claim.currency)));
}
// Expiration
int expirationDays = AuctionClientConfig.getClaimExpirationDays();
long daysLeft = claim.getDaysUntilExpiration(expirationDays);
if (daysLeft <= 1) {
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.claim.expiresSoon"));
} else {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.expires")
.replace("%s", "" + daysLeft));
}
tooltip.add("");
// Rebid option for REFUND claims with item
if (claim.type == EnumClaimType.REFUND && claim.item != null) {
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.leftClickRebid"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickRefund"));
} else {
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.claim.clickToClaim"));
}
}
// ========== Sell Page ==========
private static void addSellTooltip(GuiAuctionSell gui, ItemStack stack, List<String> tooltip) {
Slot slot = findHoveredSlot(gui, stack);
if (slot == null) return;
ContainerAuctionSell container = (ContainerAuctionSell) gui.inventorySlots;
if (container == null) return;
// Check if this is the sell slot item
ItemStack sellItem = container.getItemToSell();
if (sellItem != null && ItemStack.areItemStacksEqual(stack, sellItem)) {
// This is the item in the sell slot
if (container.isSellSlot(slot.slotNumber)) {
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.leftClear"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.rightRemove"));
return;
} else if (container.isPlayerInventorySlot(slot.slotNumber)) {
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.leftAdd"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.rightAddOne"));
}
// This is an inventory item - show add controls
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.leftAdd"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.rightAddOne"));
}
/**
* Format currency with commas.
*/
// ========== Formatting Utilities ==========
private static String formatCurrency(long amount) {
if (amount < 1000) {
return amount + " " + AuctionClientConfig.getCurrencyName();
@@ -250,9 +273,6 @@ public class AuctionTooltipHandler {
return sb.toString() + " " + AuctionClientConfig.getCurrencyName();
}
/**
* Format time remaining.
*/
private static String formatTimeRemaining(long milliseconds) {
if (milliseconds <= 0) {
return StatCollector.translateToLocal("auction.ended");
@@ -112,16 +112,16 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface {
mc.renderEngine.bindTexture(AUCTION_BACKGROUND);
drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
drawAuctionContent(partialTicks, mouseX, mouseY);
RenderHelper.enableGUIStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_COLOR_MATERIAL);
GL11.glEnable(GL11.GL_LIGHTING);
drawAuctionContent(partialTicks, mouseX, mouseY);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
RenderHelper.enableStandardItemLighting();
super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
}
@@ -167,12 +167,12 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface {
Gui.drawRect(x + 1, y + 1, x + 17, y + 17, color);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
/** Draw dark overlay for unavailable slots */
protected void drawDarkenedOverlay(int x, int y) {
drawColoredOverlay(x, y, 0x80000000);
drawColoredOverlay(x, y, 0xC0000000);
}
/** Draw icon texture on slot (16x16) */
@@ -38,10 +38,10 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
private static final int TOTAL_SLOTS = COLS * ROWS;
// Slot tint colors (ARGB)
private static final int TINT_BLUE = 0x303060FF; // Active listing/bid (selling)
private static final int TINT_GREEN = 0x3030FF30; // Sold (currency claim) or Won (item claim)
private static final int TINT_YELLOW = 0x30FFFF30; // Outbid (refund claim)
private static final int TINT_RED = 0x30FF3030; // Expired/Returned (item returned to seller)
private static final int TINT_BLUE = 0x605080FF; // Active listing/bid (selling)
private static final int TINT_GREEN = 0x6050FF50; // Sold (currency claim) or Won (item claim)
private static final int TINT_YELLOW = 0x60FFFF50; // Outbid (refund claim)
private static final int TINT_RED = 0x60FF5050; // Expired/Returned (item returned to seller)
private final ContainerAuctionTrades tradesContainer;
private int maxTradeSlots;
@@ -3,6 +3,7 @@ package noppes.npcs.client.gui.player;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.player.GetTraderData;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
@@ -332,6 +333,22 @@ public class GuiNPCTrader extends GuiContainerNPCInterface implements IGuiData {
return sb.toString();
}
@Override
protected void handleMouseClick(Slot slot, int slotId, int mouseButton, int modifier) {
// Client-side balance prediction: immediately subtract currency cost on click
// so the displayed balance updates instantly without waiting for server response.
if (slotId >= 0 && slotId < 18 && mouseButton == 0) {
long cost = currencyCost[slotId];
if (cost > 0 && playerBalance >= cost) {
ItemStack sold = role.inventorySold.items.get(slotId);
if (sold != null && container.canBuy(slotId, player)) {
playerBalance -= cost;
}
}
}
super.handleMouseClick(slot, slotId, mouseButton, modifier);
}
@Override
public void save() {
}
@@ -55,7 +55,6 @@ public class GuiAnimationSelection extends SubGuiInterface implements ICustomScr
* Constructor for selecting by name (built-in) or ID (user).
*/
public GuiAnimationSelection(int animationId, String animationName) {
drawDefaultBackground = false;
title = "";
setBackground("menubg.png");
xSize = 220;
@@ -39,7 +39,6 @@ public class GuiSoundSelection extends SubGuiInterface implements ICustomScrollL
public static HashMap<String, List<String>> cachedDomains = new HashMap<>();
public GuiSoundSelection(String sound) {
drawDefaultBackground = false;
title = "";
setBackground("menubg.png");
xSize = 366;
@@ -4,15 +4,10 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.PreviewEntityHandler;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityAbilityProjectile;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.world.World;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.controllers.data.AnimationData;
import noppes.npcs.entity.EntityCustomNpc;
@@ -25,38 +20,39 @@ import java.util.List;
/**
* Client-side executor for previewing abilities in the GUI.
*
* Lifecycle:
* 1. WINDUP phase - plays windup animation, entities spawn and charge
* 2. ACTIVE phase - plays active animation, entities fire and move
* 3. EXTENDED phase - continues for +100 ticks after animations to see results
* 4. IDLE - preview complete
* Uses unified execution: calls the REAL ability methods (onWindUpTick, onExecute, onActiveTick)
* with previewMode=true. Abilities skip damage/effects/sounds when isPreview() returns true.
*
* Features:
* - Invisible fake target NPC placed in front of the preview NPC for targeting
* - NPC movement tracking for abilities that move the NPC (e.g. slam)
* Lifecycle:
* 1. WINDUP phase - real onWindUpTick() called, telegraph shown, entities may spawn
* 2. ACTIVE phase - real onExecute() then onActiveTick() called, physics simulated
* 3. EXTENDED phase - 100 extra ticks to observe results (entities continue updating)
* 4. IDLE - preview complete
*/
@SideOnly(Side.CLIENT)
public class AbilityPreviewExecutor {
public class AbilityPreviewExecutor implements PreviewEntityHandler {
// ==================== PREVIEW STATE ====================
private Ability previewAbility;
private EntityNPCInterface previewNpc;
private AbilityPhase phase = AbilityPhase.IDLE;
/** Executor's own phase tracking (separate from ability.getPhase()) */
private enum ExecutorPhase { IDLE, WINDUP, ACTIVE, EXTENDED }
private ExecutorPhase executorPhase = ExecutorPhase.IDLE;
private int currentTick = 0;
private boolean playing = false;
private boolean paused = false;
// ==================== TIMING ====================
private static final int EXTENDED_DURATION = 100;
private int activeDuration = 40;
private int maxPreviewDuration = 200;
// ==================== FAKE TARGET ====================
/** Invisible fake target NPC for ability targeting (placed 5 blocks in front of preview NPC) */
private EntityNPCInterface fakeTarget;
private static final double TARGET_DISTANCE = 5.0;
// ==================== NPC START POSITION ====================
/** Saved NPC position for restoring after movement abilities */
private double npcStartX, npcStartY, npcStartZ;
// ==================== PREVIEW CONTENT ====================
@@ -74,63 +70,69 @@ public class AbilityPreviewExecutor {
}
/**
* Start previewing an ability.
* Start previewing an ability using unified execution.
* Sets previewMode=true on the ability, then calls its real methods.
*/
public void startPreview(Ability ability, EntityNPCInterface npc) {
stop();
this.previewAbility = ability;
this.previewNpc = npc;
this.phase = AbilityPhase.WINDUP;
this.currentTick = 0;
this.playing = true;
this.paused = false;
this.activeDuration = ability.getPreviewActiveDuration();
this.maxPreviewDuration = ability.getMaxPreviewDuration();
// Save NPC start position for restoring later
this.npcStartX = npc.posX;
this.npcStartY = npc.posY;
this.npcStartZ = npc.posZ;
// Enable preview mode on the ability
ability.setPreviewMode(true);
ability.setPreviewEntityHandler(this);
// Create invisible fake target NPC for targeting
createFakeTarget(npc);
// Set preview target on the ability
ability.setPreviewTarget(fakeTarget);
// Start tracking NPC movement
if (parentGui != null) {
parentGui.startTrackingMovement();
}
// Create telegraph for preview
previewTelegraph = ability.createTelegraph(npc, fakeTarget);
// Use the ability's real start() method with the fake target
ability.start(fakeTarget);
// Start windup animation
Animation windUpAnim = ability.getWindUpAnimation();
if (windUpAnim != null) {
AnimationData data = npc.display.animationData;
data.setEnabled(true);
data.setAnimation(windUpAnim);
data.animation.paused = false;
}
if (ability.getWindUpTicks() <= 0) {
// No windup — go straight to active
this.executorPhase = ExecutorPhase.ACTIVE;
transitionToActive();
} else {
// Normal windup flow
this.executorPhase = ExecutorPhase.WINDUP;
// Spawn preview entity on first tick if ability spawns during windup
if (ability.spawnPreviewDuringWindup()) {
spawnPreviewEntity();
// Create telegraph for preview
previewTelegraph = ability.createTelegraph(npc, fakeTarget);
// Start windup animation
Animation windUpAnim = ability.getWindUpAnimation();
if (windUpAnim != null) {
AnimationData data = npc.display.animationData;
data.setEnabled(true);
data.setAnimation(windUpAnim);
data.animation.paused = false;
}
}
}
/**
* Create an invisible fake target NPC placed in front of the preview NPC.
* This entity is NOT rendered - it only exists for ability targeting logic.
*/
private void createFakeTarget(EntityNPCInterface npc) {
if (npc.worldObj == null) return;
try {
fakeTarget = new EntityCustomNpc(npc.worldObj);
// Position target in front of NPC based on its facing direction
float facingYaw = GuiAbilityInterface.NPC_FACING_YAW;
double yawRad = Math.toRadians(facingYaw);
double targetX = npc.posX - Math.sin(yawRad) * TARGET_DISTANCE;
@@ -145,15 +147,12 @@ public class AbilityPreviewExecutor {
}
}
/**
* Get the fake target entity for abilities that need a target.
*/
public EntityLivingBase getFakeTarget() {
return fakeTarget;
}
public void play() {
if (previewAbility == null || phase == AbilityPhase.IDLE) {
if (previewAbility == null || executorPhase == ExecutorPhase.IDLE) {
return;
}
playing = true;
@@ -170,6 +169,9 @@ public class AbilityPreviewExecutor {
public void pause() {
paused = true;
// Immediately sync prevPos to pos for NPC and all entities to prevent interpolation jitter
syncPrevPositions();
if (previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
if (data.animation != null) {
@@ -178,10 +180,37 @@ public class AbilityPreviewExecutor {
}
}
/**
* Sync prevPos to pos for the NPC and all preview entities.
* Prevents rendering interpolation jitter when standing still or paused.
*/
private void syncPrevPositions() {
if (previewNpc != null) {
previewNpc.prevPosX = previewNpc.posX;
previewNpc.prevPosY = previewNpc.posY;
previewNpc.prevPosZ = previewNpc.posZ;
}
for (Entity entity : previewEntities) {
if (entity != null && !entity.isDead) {
entity.prevPosX = entity.posX;
entity.prevPosY = entity.posY;
entity.prevPosZ = entity.posZ;
}
}
}
public void stop() {
// Clean up the ability
if (previewAbility != null) {
previewAbility.cleanup();
previewAbility.setPreviewMode(false);
previewAbility.setPreviewEntityHandler(null);
previewAbility.reset();
}
playing = false;
paused = false;
phase = AbilityPhase.IDLE;
executorPhase = ExecutorPhase.IDLE;
currentTick = 0;
previewTelegraph = null;
@@ -203,9 +232,11 @@ public class AbilityPreviewExecutor {
previewNpc.prevPosX = npcStartX;
previewNpc.prevPosY = npcStartY;
previewNpc.prevPosZ = npcStartZ;
previewNpc.motionX = 0;
previewNpc.motionY = 0;
previewNpc.motionZ = 0;
}
// Remove fake target
fakeTarget = null;
if (previewNpc != null) {
@@ -216,13 +247,24 @@ public class AbilityPreviewExecutor {
}
/**
* Tick the preview forward.
* Tick the preview forward. Calls real ability methods.
*/
public void tick() {
if (!playing || paused || previewAbility == null || previewNpc == null) {
if (!playing || previewAbility == null || previewNpc == null) {
return;
}
if (paused) {
// Sync prevPos to pos for NPC and all entities to prevent interpolation jitter while paused
syncPrevPositions();
return;
}
// Sync NPC's prevPos to current pos BEFORE any updates to prevent jitter when standing still
previewNpc.prevPosX = previewNpc.posX;
previewNpc.prevPosY = previewNpc.posY;
previewNpc.prevPosZ = previewNpc.posZ;
currentTick++;
if (previewTelegraph != null) {
@@ -231,14 +273,14 @@ public class AbilityPreviewExecutor {
tickEntities();
switch (phase) {
switch (executorPhase) {
case WINDUP:
tickWindup();
break;
case ACTIVE:
tickActive();
break;
case IDLE:
case EXTENDED:
tickExtended();
break;
default:
@@ -247,7 +289,8 @@ public class AbilityPreviewExecutor {
}
private void tickWindup() {
previewAbility.onPreviewWindUpTick(previewNpc, currentTick);
// Call the REAL windup tick method
previewAbility.onWindUpTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick);
if (currentTick >= previewAbility.getWindUpTicks()) {
transitionToActive();
@@ -255,35 +298,41 @@ public class AbilityPreviewExecutor {
}
private void tickActive() {
previewAbility.onPreviewActiveTick(previewNpc, currentTick);
// Call the REAL active tick method
previewAbility.onActiveTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick);
if (currentTick == 1 && !previewAbility.spawnPreviewDuringWindup()) {
spawnPreviewEntity();
fireEntities();
// Simulate physics for movement abilities
simulatePhysics();
// Check if the ability signaled completion (phase went to IDLE)
if (previewAbility.getPhase() == AbilityPhase.IDLE) {
transitionToExtended();
return;
}
if (currentTick >= activeDuration) {
// Safety timeout
if (currentTick >= maxPreviewDuration) {
transitionToExtended();
}
}
private void tickExtended() {
// Continue ticking entities so they can finish their animations
if (currentTick >= EXTENDED_DURATION) {
playing = false;
}
}
private void transitionToActive() {
phase = AbilityPhase.ACTIVE;
executorPhase = ExecutorPhase.ACTIVE;
currentTick = 0;
previewTelegraph = null;
// Notify ability of execution (for movement abilities like Slam/Charge/Dash)
previewAbility.onPreviewExecute(previewNpc);
fireEntities();
// Call the REAL onExecute method (fires entities, initiates movement, etc.)
previewAbility.onExecute(previewNpc, fakeTarget, previewNpc.worldObj);
// Start active animation
Animation activeAnim = previewAbility.getActiveAnimation();
if (activeAnim != null && previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
@@ -293,7 +342,7 @@ public class AbilityPreviewExecutor {
}
private void transitionToExtended() {
phase = AbilityPhase.IDLE;
executorPhase = ExecutorPhase.EXTENDED;
currentTick = 0;
if (previewNpc != null) {
@@ -302,26 +351,40 @@ public class AbilityPreviewExecutor {
}
}
private void spawnPreviewEntity() {
Entity entity = previewAbility.createPreviewEntity(previewNpc);
if (entity != null) {
previewEntities.add(entity);
if (parentGui != null) {
parentGui.addPreviewEntity(entity);
}
}
}
/**
* Simulate basic physics for movement abilities (Slam, Charge, Dash).
* Applies gravity, drag, and ground clamping to NPC position.
*/
private void simulatePhysics() {
if (!previewAbility.hasAbilityMovement()) return;
if (previewNpc == null) return;
private void fireEntities() {
for (Entity entity : previewEntities) {
if (entity instanceof EntityAbilityOrb) {
((EntityAbilityOrb) entity).startPreviewFiring();
} else if (entity instanceof EntityAbilityBeam) {
((EntityAbilityBeam) entity).startPreviewFiring();
} else if (entity instanceof EntityAbilityDisc) {
((EntityAbilityDisc) entity).startPreviewFiring();
}
// Save previous position for interpolation
previewNpc.prevPosX = previewNpc.posX;
previewNpc.prevPosY = previewNpc.posY;
previewNpc.prevPosZ = previewNpc.posZ;
// Apply velocity
previewNpc.posX += previewNpc.motionX;
previewNpc.posY += previewNpc.motionY;
previewNpc.posZ += previewNpc.motionZ;
// Apply gravity
previewNpc.motionY -= 0.08;
previewNpc.motionY *= 0.98;
// Apply horizontal drag
previewNpc.motionX *= 0.91;
previewNpc.motionZ *= 0.91;
// Ground clamp: if below start position and falling, stop
if (previewNpc.posY < npcStartY && previewNpc.motionY < 0) {
previewNpc.posY = npcStartY;
previewNpc.motionY = 0;
previewNpc.onGround = true;
}
previewNpc.fallDistance = 0;
}
private void tickEntities() {
@@ -339,12 +402,38 @@ public class AbilityPreviewExecutor {
}
}
// ==================== PreviewEntityHandler ====================
@Override
public void onEntitySpawned(Entity entity) {
if (entity == null) return;
previewEntities.add(entity);
if (parentGui != null) {
parentGui.addPreviewEntity(entity);
}
}
@Override
public void onEntityRemoved(Entity entity) {
if (entity == null) return;
previewEntities.remove(entity);
if (parentGui != null) {
parentGui.removePreviewEntity(entity);
}
}
// ==================== GETTERS ====================
public boolean isPlaying() { return playing; }
public boolean isPaused() { return paused; }
public boolean isActive() { return playing || paused; }
public AbilityPhase getPhase() { return phase; }
public AbilityPhase getPhase() {
switch (executorPhase) {
case WINDUP: return AbilityPhase.WINDUP;
case ACTIVE: return AbilityPhase.ACTIVE;
default: return AbilityPhase.IDLE;
}
}
public int getCurrentTick() { return currentTick; }
public TelegraphInstance getTelegraph() { return previewTelegraph; }
public List<Entity> getPreviewEntities() { return previewEntities; }
@@ -356,11 +445,11 @@ public class AbilityPreviewExecutor {
return "Stopped";
} else if (paused) {
return "Paused";
} else if (phase == AbilityPhase.WINDUP) {
} else if (executorPhase == ExecutorPhase.WINDUP) {
return "Windup: " + currentTick + "/" + (previewAbility != null ? previewAbility.getWindUpTicks() : 0);
} else if (phase == AbilityPhase.ACTIVE) {
return "Active: " + currentTick + "/" + activeDuration;
} else if (phase == AbilityPhase.IDLE && playing) {
} else if (executorPhase == ExecutorPhase.ACTIVE) {
return "Active: " + currentTick + "/" + maxPreviewDuration;
} else if (executorPhase == ExecutorPhase.EXTENDED) {
return "Extended: " + currentTick + "/" + EXTENDED_DURATION;
}
return "";
@@ -11,10 +11,7 @@ import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import noppes.npcs.client.ClientEventHandler;
import noppes.npcs.client.EntityUtil;
import noppes.npcs.entity.EntityCustomNpc;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.entity.data.ModelData;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
@@ -50,7 +47,6 @@ public class GuiAbilityInterface extends GuiNPCInterface2 {
private GuiNpcButton btnLeft, btnRight;
// ==================== NPC STATE ====================
public ModelData playerdata;
public EntityNPCInterface npc;
/** NPC starting position (saved when preview starts, used to track movement) */
@@ -74,9 +70,17 @@ public class GuiAbilityInterface extends GuiNPCInterface2 {
public int yOffset = 0;
public GuiAbilityInterface(EntityNPCInterface npc) {
super(npc);
this(npc, true);
}
/**
* @param npc The NPC for preview rendering
* @param hasMenuNpc If false, the top menu tabs (Display, Stats, etc.) are hidden.
* Use false when opened from the global menu without a real NPC.
*/
public GuiAbilityInterface(EntityNPCInterface npc, boolean hasMenuNpc) {
super(hasMenuNpc ? npc : null);
this.npc = npc;
this.playerdata = ((EntityCustomNpc) npc).modelData;
this.drawDefaultBackground = false;
CAMERA_ZOOM = 30f;
@@ -126,20 +130,17 @@ public class GuiAbilityInterface extends GuiNPCInterface2 {
* Draw the 3D preview with NPC and entities.
*/
protected void drawPreview(int mouseX, int mouseY, float partialTicks) {
if (hasSubGui())
return;
GL11.glColor4f(1, 1, 1, 1);
// Enable scissor to clip rendering to preview area
GL11.glEnable(GL11.GL_SCISSOR_TEST);
setScissorClip(previewX, previewY, previewWidth, previewHeight);
// Get the entity to render (could be transformed player model)
EntityLivingBase renderEntity = playerdata.getEntity(npc);
if (renderEntity == null) {
renderEntity = this.npc;
}
// Sync NPC properties to render entity
EntityUtil.Copy(npc, renderEntity);
// Always use the standard NPC animation renderer for ability preview
EntityLivingBase renderEntity = this.npc;
// Set NPC facing direction (affects anchor points and visual facing)
npc.prevRenderYawOffset = npc.renderYawOffset = NPC_FACING_YAW;
@@ -195,11 +196,7 @@ public class GuiAbilityInterface extends GuiNPCInterface2 {
ClientEventHandler.renderingEntityInGUI = true;
// Render the NPC at its position delta (for movement like slam jumps)
try {
RenderManager.instance.renderEntityWithPosYaw(renderEntity, npcDeltaX, npcDeltaY, npcDeltaZ, 0.0F, partialTicks);
} catch (Exception e) {
playerdata.setEntityClass(null);
}
RenderManager.instance.renderEntityWithPosYaw(renderEntity, npcDeltaX, npcDeltaY, npcDeltaZ, 0.0F, partialTicks);
// Render preview entities at their positions relative to NPC start position
renderPreviewEntities(partialTicks);
@@ -246,7 +246,10 @@ public abstract class GuiContainerNPCInterface extends GuiContainer {
}
public void closeSubGui(SubGuiInterface gui) {
subgui = null;
// Only null out subgui if it wasn't replaced by a new one during subGuiClosed
if (subgui == gui) {
subgui = null;
}
}
public boolean hasSubGui() {
@@ -104,8 +104,10 @@ public class GuiCustomScroll extends GuiScreen {
GL11.glTranslatef(guiLeft, guiTop, 0.0F);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
if (selectable)
if (selectable && !hasSubGUI)
hover = getMouseOver(i, j);
else if (hasSubGUI)
hover = -1;
drawItems();
@@ -198,7 +200,8 @@ public class GuiCustomScroll extends GuiScreen {
int k = (14 * i + 4) - scrollY;
if (k >= 4 && k + 12 < ySize) {
int xOffset = scrollHeight < ySize - 8 ? 0 : 10;
String displayString = StatCollector.translateToLocal(list.get(i));
String rawEntry = list.get(i);
String displayString = StatCollector.translateToLocal(rawEntry);
String text = "";
float maxWidth = (xSize + xOffset - 8) * 0.8f;
@@ -213,7 +216,13 @@ public class GuiCustomScroll extends GuiScreen {
text += "...";
} else
text = displayString;
if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) {
// Entries with a custom color are non-interactive (headers/separators)
Integer customColor = colors.get(rawEntry);
if (customColor != null) {
if (!text.isEmpty())
fontRendererObj.drawString(text, j, k, customColor);
} else if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) {
drawVerticalLine(j - 2, k - 4, k + 10, 0xffffffff);
drawVerticalLine(j + xSize - 18 + xOffset, k - 4, k + 10, 0xffffffff);
drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k - 3, 0xffffffff);
@@ -237,13 +246,17 @@ public class GuiCustomScroll extends GuiScreen {
private int getMouseOver(int i, int j) {
i -= guiLeft;
j -= guiTop;
//fontRenderer.drawString(".", i , j, 0xffffff);
if (i >= 4 && i < xSize - 4 && j >= 4 && j < ySize) {
for (int j1 = 0; j1 < list.size(); j1++) {
if (!mouseInOption(i, j, j1)) {
continue;
}
// Skip non-interactive entries (colored headers/separators)
if (colors.containsKey(list.get(j1))) {
continue;
}
return j1;
}
@@ -365,6 +378,13 @@ public class GuiCustomScroll extends GuiScreen {
return this;
}
public void setSelectable(boolean selectable) {
this.selectable = selectable;
if (!selectable) {
hover = -1;
}
}
public boolean isMouseOver(int x, int y) {
return x >= this.guiLeft && x <= this.guiLeft + this.xSize && y >= this.guiTop && y <= this.guiTop + this.ySize;
}
@@ -1,5 +1,6 @@
package noppes.npcs.client.gui.util;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.GuiNpcMobSpawner;
import noppes.npcs.controllers.data.Tag;
@@ -7,10 +8,10 @@ import noppes.npcs.controllers.data.Tag;
import java.util.UUID;
public class GuiCustomScrollCloner extends GuiCustomScroll {
private final GuiNpcMobSpawner parent;
private final IClonerGui parent;
public GuiCustomScrollCloner(GuiNpcMobSpawner parent, int id) {
super(parent, id);
public GuiCustomScrollCloner(IClonerGui parent, int id) {
super((GuiScreen) parent, id);
this.parent = parent;
}
@@ -38,24 +39,25 @@ public class GuiCustomScrollCloner extends GuiCustomScroll {
text += "...";
} else
text = displayString;
if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) {
int itemColor = this.colors.getOrDefault(list.get(i), 0xffffff);
if ((multipleSelection && selectedList.contains(list.get(i))) || (!multipleSelection && selected == i)) {
drawVerticalLine(j - 2, k - 4, k + 10, 0xffffffff);
drawVerticalLine(j + xSize - 18 + xOffset, k - 4, k + 10, 0xffffffff);
drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k - 3, 0xffffffff);
drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k + 10, 0xffffffff);
fontRendererObj.drawString(text, j, k, this.colors.getOrDefault(text, 0xffffff));
fontRendererObj.drawString(text, j, k, itemColor);
} else if (i == hover) {
fontRendererObj.drawString(text, j, k, 0x00ff00);
} else {
fontRendererObj.drawString(text, j, k, this.colors.getOrDefault(text, 0xffffff));
fontRendererObj.drawString(text, j, k, itemColor);
}
if ((this.parent.getShowingClones() == 0 || this.parent.getShowingClones() == 2) && this.parent.tagMap != null) {
if ((parent.getShowingClones() == 0 || parent.getShowingClones() == 2) && parent.getTagMap() != null) {
int tagStartX = j + fontRendererObj.getStringWidth(displayString) + 3;
if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) {
if (this.parent.tagMap.hasClone(list.get(i))) {
for (UUID tagUUID : this.parent.tagMap.getUUIDsList(list.get(i))) {
Tag tag = this.parent.tags.get(tagUUID);
if (parent.getTagMap().hasClone(list.get(i))) {
for (UUID tagUUID : parent.getTagMap().getUUIDsList(list.get(i))) {
Tag tag = parent.getTags().get(tagUUID);
if (tag != null) {
if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) {
fontRendererObj.drawString("[" + tag.name + "]", tagStartX, k, tag.color);
@@ -0,0 +1,108 @@
package noppes.npcs.client.gui.util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
public class GuiCustomScrollIcons extends GuiCustomScroll {
public static final int ICON_NONE = 0;
public static final int ICON_TAB = 1;
public static final int ICON_FOLDER = 2;
private static final ResourceLocation TAB_TEXTURE = new ResourceLocation("customnpcs", "textures/gui/cloner/tab.png");
private static final ResourceLocation FOLDER_TEXTURE = new ResourceLocation("customnpcs", "textures/gui/cloner/folder.png");
private static final int ICON_RENDER_SIZE = 10;
private static final int ICON_PADDING = 14;
private List<Integer> iconTypes = new ArrayList<>();
public GuiCustomScrollIcons(GuiScreen parent, int id) {
super(parent, id);
}
public void setListWithIcons(List<String> names, List<Integer> icons) {
this.setUnsortedList(names);
this.iconTypes = new ArrayList<>(icons);
}
@Override
protected void drawItems() {
Minecraft mc = Minecraft.getMinecraft();
for (int i = 0; i < list.size(); i++) {
int j = 4;
int k = (14 * i + 4) - scrollY;
if (k >= 4 && k + 12 < ySize) {
int xOffset = scrollHeight < ySize - 8 ? 0 : 10;
int iconType = (i < iconTypes.size()) ? iconTypes.get(i) : ICON_NONE;
int textX = j;
if (iconType != ICON_NONE) {
textX = j + ICON_PADDING;
}
// Draw icon texture
if (iconType == ICON_FOLDER || iconType == ICON_TAB) {
ResourceLocation tex = (iconType == ICON_FOLDER) ? FOLDER_TEXTURE : TAB_TEXTURE;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.getTextureManager().bindTexture(tex);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
drawFullTexture(j, k - 1, ICON_RENDER_SIZE, ICON_RENDER_SIZE);
GL11.glDisable(GL11.GL_BLEND);
}
// Draw text
String displayString = StatCollector.translateToLocal(list.get(i));
String text = "";
float maxWidth = (xSize + xOffset - 8 - (iconType != ICON_NONE ? ICON_PADDING : 0)) * 0.8f;
if (fontRendererObj.getStringWidth(displayString) > maxWidth) {
for (int h = 0; h < displayString.length(); h++) {
char c = displayString.charAt(h);
text += c;
if (fontRendererObj.getStringWidth(text) > maxWidth)
break;
}
if (displayString.length() > text.length())
text += "...";
} else {
text = displayString;
}
int itemColor = this.colors.getOrDefault(list.get(i), 0xffffff);
if ((multipleSelection && selectedList.contains(list.get(i))) || (!multipleSelection && selected == i)) {
drawVerticalLine(j - 2, k - 4, k + 10, 0xffffffff);
drawVerticalLine(j + xSize - 18 + xOffset, k - 4, k + 10, 0xffffffff);
drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k - 3, 0xffffffff);
drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k + 10, 0xffffffff);
fontRendererObj.drawString(text, textX, k, itemColor);
} else if (i == hover) {
fontRendererObj.drawString(text, textX, k, 0x00ff00);
} else {
fontRendererObj.drawString(text, textX, k, itemColor);
}
}
}
}
/**
* Draw a full texture (UV 0,0 to 1,1) scaled to the given width/height.
* Works with any texture size (not just 256x256).
*/
private void drawFullTexture(int x, int y, int w, int h) {
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(x, y + h, 0, 0, 1);
tessellator.addVertexWithUV(x + w, y + h, 0, 1, 1);
tessellator.addVertexWithUV(x + w, y, 0, 1, 0);
tessellator.addVertexWithUV(x, y, 0, 0, 0);
tessellator.draw();
}
}
@@ -0,0 +1,206 @@
package noppes.npcs.client.gui.util;
/**
* Abstract base class for fullscreen directory-browsing GUIs.
* Provides a configurable three-panel layout (left nav, center content, right actions)
* with percentage-based sizing, panel backgrounds/borders, and an optional resizable divider.
*
* Subclasses override abstract hooks to populate each panel region.
* Designed for reuse across Cloner, Quest Manager, Dialog Manager, etc.
*/
public abstract class GuiDirectory extends GuiNPCInterface implements ICustomScrollListener, ISubGuiListener {
// ===== LAYOUT CONFIG (subclasses may override in constructor) =====
protected float leftPanelPercent = 0.20f;
protected float rightPanelPercent = 0.10f;
protected int minLeftPanelW = 80;
protected int minRightPanelW = 40;
protected int minCenterW = 100;
// ===== LAYOUT CONSTANTS =====
protected int pad = 10;
protected int topBarH = 24;
protected int gap = 4;
protected int btnH = 20;
// ===== PANEL COLORS =====
protected int panelBg = 0xC0101010;
protected int panelBorder = 0xFF333333;
protected int topBarBg = 0xC0181818;
// ===== COMPUTED LAYOUT (populated by computeLayout) =====
protected int originX, originY, usableW, usableH;
protected int leftPanelW, rightPanelW;
protected int contentX, contentY, contentW, contentH;
protected int rightX;
// ===== OPTIONAL RESIZABLE DIVIDER (between left and center) =====
protected boolean enableDivider = false;
protected int dividerWidth = 5;
protected int dividerLineHeight = 20;
protected int minDividerPanelW = 50;
private int dividerOffset;
private boolean isDragging = false;
private int dragStartX;
// ===== CONSTRUCTOR =====
public GuiDirectory() {
super();
closeOnEsc = true;
drawDefaultBackground = true;
}
// ===== LAYOUT COMPUTATION =====
protected void computeLayout() {
originX = pad;
originY = pad;
usableW = width - 2 * pad;
usableH = height - 2 * pad;
leftPanelW = Math.max(minLeftPanelW, (int)(usableW * leftPanelPercent));
rightPanelW = Math.max(minRightPanelW, (int)(usableW * rightPanelPercent));
if (rightPanelPercent <= 0) {
rightPanelW = 0;
}
int gapCount = rightPanelW > 0 ? 3 : 2;
contentW = usableW - leftPanelW - rightPanelW - gapCount * gap;
if (contentW < minCenterW) {
contentW = minCenterW;
}
contentX = originX + leftPanelW + gap;
contentY = originY + topBarH + gap;
contentH = usableH - topBarH - gap;
rightX = contentX + contentW + gap;
if (enableDivider && dividerOffset == 0) {
dividerOffset = leftPanelW;
}
}
// ===== INIT GUI =====
@Override
public void initGui() {
super.initGui();
computeLayout();
initTopBar(originY + 2);
initLeftPanel();
initCenterPanel();
if (rightPanelW > 0) {
initRightPanel(contentY + 4);
}
}
// ===== DRAWING =====
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
drawTopBar();
drawPanels();
if (enableDivider) {
drawDivider(mouseX, mouseY);
}
super.drawScreen(mouseX, mouseY, partialTicks);
drawOverlay(mouseX, mouseY, partialTicks);
}
protected void drawTopBar() {
GuiUtil.drawRectD(originX, originY, originX + usableW, originY + topBarH, topBarBg);
}
protected void drawPanels() {
// Left nav panel border
GuiUtil.drawRectD(originX - 1, contentY - 1, originX + leftPanelW + 1, originY + usableH + 1, panelBorder);
// Right action panel border (if present)
if (rightPanelW > 0) {
GuiUtil.drawRectD(rightX - 1, contentY - 1, rightX + rightPanelW + 1, originY + usableH + 1, panelBorder);
}
}
protected void drawDivider(int mouseX, int mouseY) {
if (!enableDivider) return;
int divX = originX + dividerOffset;
int regionTop = contentY;
int regionHeight = contentH;
int handleTop = regionTop + (regionHeight - dividerLineHeight) / 2;
drawRect(divX + 1, handleTop, divX + dividerWidth - 1, handleTop + dividerLineHeight, 0xFF707070);
}
/** Override for extra drawing after super.drawScreen (e.g. status text) */
protected void drawOverlay(int mouseX, int mouseY, float partialTicks) {
}
// ===== DIVIDER MOUSE HANDLING =====
@Override
public void mouseClicked(int mouseX, int mouseY, int mouseButton) {
if (enableDivider && !hasSubGui()) {
int divX = originX + dividerOffset;
int regionTop = contentY;
int handleTop = regionTop + (contentH - dividerLineHeight) / 2;
int handleBottom = handleTop + dividerLineHeight;
if (mouseX >= divX && mouseX <= divX + dividerWidth &&
mouseY >= handleTop && mouseY <= handleBottom) {
isDragging = true;
resizingActive = true;
dragStartX = mouseX;
return;
}
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
@Override
public void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
if (isDragging) {
int dx = mouseX - dragStartX;
dragStartX = mouseX;
dividerOffset += dx;
int maxOffset = (usableW - (rightPanelW > 0 ? rightPanelW + gap : 0)) - dividerWidth - minDividerPanelW;
dividerOffset = Math.max(minDividerPanelW, Math.min(dividerOffset, maxOffset));
onDividerMoved(dividerOffset);
return;
}
super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick);
}
@Override
protected void mouseMovedOrUp(int mouseX, int mouseY, int state) {
if (isDragging) {
isDragging = false;
resizingActive = false;
return;
}
super.mouseMovedOrUp(mouseX, mouseY, state);
}
/** Called when divider is dragged. Override to update scroll sizes. */
protected void onDividerMoved(int newOffset) {
}
// Accessors for divider offset
protected int getDividerOffset() {
return dividerOffset;
}
protected void setDividerOffset(int offset) {
this.dividerOffset = offset;
}
// ===== ABSTRACT HOOKS (subclass must implement) =====
/** Populate top bar buttons. topBtnY is the y-coordinate for the button row. */
protected abstract void initTopBar(int topBtnY);
/** Populate the left navigation panel (scrolls, search fields, buttons). */
protected abstract void initLeftPanel();
/** Populate the center content panel (main scroll list). */
protected abstract void initCenterPanel();
/** Populate the right action panel. startY is the first button y-coordinate. */
protected abstract void initRightPanel(int startY);
}
@@ -15,6 +15,7 @@ public class GuiMenuSideButton extends GuiNpcButton {
public boolean active;
public boolean rightSided;
public int textColor = -1;
public ItemStack renderStack;
public ResourceLocation renderResource;
public int renderIconPosX = 0;
@@ -96,13 +97,15 @@ public class GuiMenuSideButton extends GuiNpcButton {
text += "...";
} else
text = displayString;
if (active) {
drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, 0xffffa0);
} else if (field_146123_n) {
drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, 0xffffa0);
int color;
if (textColor != -1) {
color = textColor;
} else if (active || field_146123_n) {
color = 0xffffa0;
} else {
drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, 0xe0e0e0);
color = 0xe0e0e0;
}
drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, color);
}
@Override
@@ -30,10 +30,18 @@ public class GuiModelInterface2 extends GuiNPCInterface2 {
public EntityNPCInterface npc;
public GuiModelInterface2(EntityNPCInterface npc) {
super(npc);
this(npc, true);
}
/**
* @param npc The NPC for preview rendering
* @param hasMenuNpc If false, the top menu tabs (Display, Stats, etc.) are hidden.
* Use false when opened from the global menu without a real NPC.
*/
public GuiModelInterface2(EntityNPCInterface npc, boolean hasMenuNpc) {
super(hasMenuNpc ? npc : null);
this.npc = npc;
playerdata = ((EntityCustomNpc) npc).modelData;
//xSize = 380;
drawDefaultBackground = false;
}
@@ -27,6 +27,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Supplier;
public abstract class GuiNPCInterface extends GuiScreen {
@@ -52,6 +53,7 @@ public abstract class GuiNPCInterface extends GuiScreen {
public Supplier<Boolean> closeOnEscSupplier = null;
public int guiLeft, guiTop, xSize, ySize;
private SubGuiInterface subgui;
private Consumer<SubGuiInterface> pendingSubGuiResult;
public int mouseX, mouseY, mouseScroll;
public float bgScale = 1;
public float bgScaleX = 1;
@@ -519,8 +521,25 @@ public abstract class GuiNPCInterface extends GuiScreen {
initGui();
}
/**
* Open a sub-gui with a result handler that will be called when the sub-gui closes.
* The handler survives initGui() rebuilds since it lives on the parent, not the builder.
*/
public void setSubGuiWithResult(SubGuiInterface gui, Consumer<SubGuiInterface> resultHandler) {
this.pendingSubGuiResult = resultHandler;
setSubGui(gui);
}
public void closeSubGui(SubGuiInterface gui) {
subgui = null;
if (pendingSubGuiResult != null) {
Consumer<SubGuiInterface> handler = pendingSubGuiResult;
pendingSubGuiResult = null;
handler.accept(gui);
}
// Only null out subgui if it wasn't replaced by a new one during subGuiClosed
if (subgui == gui) {
subgui = null;
}
initGui();
}
@@ -2,6 +2,7 @@ package noppes.npcs.client.gui.util;
import kamkeel.npcs.util.TextSplitter;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.RenderHelper;
@@ -151,8 +152,23 @@ public class GuiNpcButton extends GuiButton {
public void drawButton(Minecraft mc, int mouseX, int mouseY) {
if (!this.visible)
return;
// Auto-truncate display text if wider than button
String original = this.displayString;
FontRenderer fr = mc.fontRenderer;
if (fr != null) {
int maxTextWidth = this.width - 6;
if (fr.getStringWidth(original) > maxTextWidth) {
String ellipsis = "...";
int targetWidth = maxTextWidth - fr.getStringWidth(ellipsis);
if (targetWidth > 0) {
this.displayString = fr.trimStringToWidth(original, targetWidth) + ellipsis;
}
}
}
// First, draw the button normally using the superclass method.
super.drawButton(mc, mouseX, mouseY);
// Restore original display string
this.displayString = original;
// Then, if an icon texture is set, draw it.
if (iconTexture != null) {
mc.getTextureManager().bindTexture(iconTexture);
@@ -1,18 +1,32 @@
package noppes.npcs.client.gui.util;
import kamkeel.npcs.util.TextSplitter;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.CustomNpcResourceListener;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
public class GuiNpcLabel {
import java.util.Iterator;
import java.util.List;
public class GuiNpcLabel extends Gui {
public String label;
public int x, y, color;
public boolean enabled = true;
public int id;
public boolean drawShadow = false;
// Hover text support
public String hoverableText = "";
private boolean wasHovered = false;
private int hoverCount = 0;
public GuiNpcLabel(int id, Object label, int x, int y, int color) {
this.id = id;
this.label = StatCollector.translateToLocal(label.toString());
@@ -25,6 +39,10 @@ public class GuiNpcLabel {
this(id, label, x, y, CustomNpcResourceListener.DefaultTextColor);
}
public void setHoverText(String text) {
this.hoverableText = text;
}
public void drawLabel(GuiScreen gui, FontRenderer fontRenderer) {
if (enabled)
fontRenderer.drawString(label, x, y, color, drawShadow);
@@ -34,4 +52,119 @@ public class GuiNpcLabel {
int size = Minecraft.getMinecraft().fontRenderer.getStringWidth(label);
x += (width - size) / 2;
}
public boolean isMouseOver(int mouseX, int mouseY, FontRenderer fr) {
int width = fr.getStringWidth(label);
return mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + 10;
}
/**
* Draws hover tooltip if the mouse is over this label.
* @param localMouseX Mouse X in scroll-local coordinates (for hit testing)
* @param localMouseY Mouse Y in scroll-local coordinates (for hit testing)
* @param screenMouseX Mouse X in screen coordinates (for tooltip positioning)
* @param screenMouseY Mouse Y in screen coordinates (for tooltip positioning)
* @param hasSubGui Whether a sub-gui is open
* @param fr FontRenderer for measuring label width
*/
public void drawHover(int localMouseX, int localMouseY, int screenMouseX, int screenMouseY, boolean hasSubGui, FontRenderer fr) {
if (hasSubGui || hoverableText.isEmpty()) return;
boolean hovered = isMouseOver(localMouseX, localMouseY, fr);
if (!hovered) {
wasHovered = false;
hoverCount = 0;
return;
}
if (!wasHovered) {
wasHovered = true;
hoverCount = 0;
}
if (hoverCount < 65) hoverCount++;
if (hoverCount > 60) {
GL11.glPushMatrix();
Minecraft mc = Minecraft.getMinecraft();
String displayString = StatCollector.translateToLocal(hoverableText);
GL11.glColor4f(1, 1, 1, 1);
List<String> lines = TextSplitter.splitText(displayString, 30);
drawHoveringText(lines, screenMouseX, screenMouseY, mc);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glPopMatrix();
}
}
@SuppressWarnings("rawtypes")
protected void drawHoveringText(List textLines, int x, int y, Minecraft mc) {
if (mc.fontRenderer == null || textLines.isEmpty())
return;
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
int maxWidth = 0;
Iterator iterator = textLines.iterator();
while (iterator.hasNext()) {
String s = (String) iterator.next();
int lineWidth = mc.fontRenderer.getStringWidth(s);
if (lineWidth > maxWidth) {
maxWidth = lineWidth;
}
}
int j2 = x + 12;
int k2 = y - 12;
int maxHeight = 8;
if (textLines.size() > 1) {
maxHeight += 2 + (textLines.size() - 1) * 10;
}
ScaledResolution scaledRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
int screenWidth = scaledRes.getScaledWidth();
int screenHeight = scaledRes.getScaledHeight();
if (j2 + maxWidth + 6 > screenWidth) {
j2 = x - maxWidth - 16;
}
if (j2 < 4) {
j2 = 4;
}
if (k2 + maxHeight + 6 > screenHeight) {
k2 = screenHeight - maxHeight - 6;
}
if (k2 < 4) {
k2 = 4;
}
this.zLevel = 300.0F;
int j1 = -267386864;
this.drawGradientRect(j2 - 3, k2 - 4, j2 + maxWidth + 3, k2 - 3, j1, j1);
this.drawGradientRect(j2 - 3, k2 + maxHeight + 3, j2 + maxWidth + 3, k2 + maxHeight + 4, j1, j1);
this.drawGradientRect(j2 - 3, k2 - 3, j2 + maxWidth + 3, k2 + maxHeight + 3, j1, j1);
this.drawGradientRect(j2 - 4, k2 - 3, j2 - 3, k2 + maxHeight + 3, j1, j1);
this.drawGradientRect(j2 + maxWidth + 3, k2 - 3, j2 + maxWidth + 4, k2 + maxHeight + 3, j1, j1);
int k1 = 1347420415;
int l1 = (k1 & 16711422) >> 1 | k1 & -16777216;
this.drawGradientRect(j2 - 3, k2 - 3 + 1, j2 - 3 + 1, k2 + maxHeight + 3 - 1, k1, l1);
this.drawGradientRect(j2 + maxWidth + 2, k2 - 3 + 1, j2 + maxWidth + 3, k2 + maxHeight + 3 - 1, k1, l1);
this.drawGradientRect(j2 - 3, k2 - 3, j2 + maxWidth + 3, k2 - 3 + 1, k1, k1);
this.drawGradientRect(j2 - 3, k2 + maxHeight + 2, j2 + maxWidth + 3, k2 + maxHeight + 3, l1, l1);
for (int i2 = 0; i2 < textLines.size(); ++i2) {
String s1 = (String) textLines.get(i2);
mc.fontRenderer.drawStringWithShadow(s1, j2, k2, -1);
if (i2 == 0) {
k2 += 2;
}
k2 += 10;
}
this.zLevel = 0.0F;
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
RenderHelper.enableStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
}
}
@@ -97,6 +97,11 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC
}
public void mouseClicked(int i, int j, int k) {
// Ignore clicks outside the visible scroll window area
if (i < xPos || i > xPos + clipWidth || j < yPos || j > yPos + clipHeight) {
return;
}
i = i - xPos;
j = (int) (j - yPos + scrollY);
@@ -246,6 +251,12 @@ 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) {
@@ -275,8 +286,26 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC
}
for (GuiNpcButton button : buttons.values()) {
button.updateSubGUI(subGui);
}
}
/**
* 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) {
boolean subGui = parent.hasSubGui();
for (GuiNpcButton button : buttons.values()) {
if (!button.hoverableText.isEmpty()) {
button.drawHover(i, j, subGui);
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 (GuiNpcLabel label : labels.values()) {
if (!label.hoverableText.isEmpty()) {
label.drawHover(localMouseX, localMouseY, mouseX, mouseY, subGui, fontRendererObj);
}
}
}
@@ -0,0 +1,13 @@
package noppes.npcs.client.gui.util;
import noppes.npcs.controllers.data.Tag;
import noppes.npcs.controllers.data.TagMap;
import java.util.HashMap;
import java.util.UUID;
public interface IClonerGui {
int getShowingClones();
HashMap<UUID, Tag> getTags();
TagMap getTagMap();
}
@@ -26,8 +26,8 @@ public class BlockBeamRenderer extends BlockRendererInterface {
public void renderTileEntityAt(TileEntity var1, double var2, double var4,
double var6, float var8) {
TileVariant tile = (TileVariant) var1;
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glPushMatrix();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glTranslatef((float) var2 + 0.5f, (float) var4 + 1.5f, (float) var6 + 0.5f);
//GL11.glScalef(1.2f, 1.1f, 1.2f);
GL11.glRotatef(180, 0, 0, 1);
@@ -22,6 +22,9 @@ public class ConfigClient {
/**
* General Properties
**/
public static Property AllowClientScriptsProperty;
public static boolean AllowClientScripts = true;
public static Property CacheLifeProperty;
public static int CacheLife = 10;
@@ -185,6 +188,9 @@ public class ConfigClient {
// General
AllowClientScriptsProperty = config.get(GENERAL, "Allow Client Scripts", true, "Allow the server to run scripts on the client. If disabled, no server scripts will execute client-side.");
AllowClientScripts = AllowClientScriptsProperty.getBoolean(true);
CacheLifeProperty = config.get(GENERAL, "Cache Life", 10, "How long should downloaded imagery data be saved client side? (In minutes)");
CacheLife = CacheLifeProperty.getInt(10);
@@ -127,15 +127,11 @@ public class ContainerNPCTrader extends ContainerNpcInterface {
givePlayer(soldItem, entityplayer);
role.addPurchase(i, entityplayer.getDisplayName());
// Sync updated data after purchase
// For per-player stocks: sync only to the purchasing player
// For shared stocks: consumeStock() handles sync (market-wide or local)
// Always sync the purchasing player's data (balance + stock) after trade.
// For shared stocks, consumeStock() syncs stock to other viewers,
// but the purchasing player's balance still needs an explicit sync.
if (entityplayer instanceof EntityPlayerMP) {
if (role.stock.perPlayer) {
// Per-player: only sync to purchasing player (their own stock/balance)
role.syncToPlayer((EntityPlayerMP) entityplayer);
}
// Shared stock sync is already handled in consumeStock()
role.syncToPlayer((EntityPlayerMP) entityplayer);
}
return soldItem;
@@ -120,12 +120,9 @@ public class AnimationController implements IAnimationHandler {
}
}
/**
* Load a single built-in animation by name from assets folder.
*/
private void loadBuiltInAnimation(String animName) throws Exception {
String resourcePath = BUILTIN_ANIMATIONS_PATH + "/" + animName + ".json";
try (InputStream stream = CustomNpcs.class.getResourceAsStream(resourcePath)) {
public void loadBuiltInAnimation(Class<?> modClass, String path, String animName) throws Exception {
String resourcePath = path + "/" + animName + ".json";
try (InputStream stream = modClass.getResourceAsStream(resourcePath)) {
if (stream == null) {
return;
}
@@ -150,6 +147,13 @@ public class AnimationController implements IAnimationHandler {
}
}
/**
* Load a single built-in animation by name from assets folder.
*/
private void loadBuiltInAnimation(String animName) throws Exception {
loadBuiltInAnimation(CustomNpcs.class, BUILTIN_ANIMATIONS_PATH, animName);
}
private void loadAnimations() {
animations.clear();
@@ -314,6 +318,10 @@ public class AnimationController implements IAnimationHandler {
}
public IAnimation get(String name) {
return get(name, false);
}
public IAnimation get(String name, boolean builtIn) {
// Check user/custom animations first (allows overriding built-in)
for (Map.Entry<Integer, Animation> entry : animations.entrySet()) {
if (entry.getValue().name.equalsIgnoreCase(name)) {
@@ -321,10 +329,13 @@ public class AnimationController implements IAnimationHandler {
}
}
// Then check built-in animations
BuiltInAnimation builtIn = builtInAnimations.get(name.toLowerCase());
if (builtIn != null) {
return builtIn;
if (builtIn) {
BuiltInAnimation builtInAnim = builtInAnimations.get(name.toLowerCase());
if (builtInAnim != null) {
return builtInAnim;
}
}
return null;
}
@@ -0,0 +1,25 @@
package noppes.npcs.controllers;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.config.ConfigScript;
/**
* Server-side utility for syncing script configuration to clients.
*
* This class is SERVER-SIDE ONLY. Client reads via ScriptClientConfig.
*/
public class ScriptConfigSync {
/**
* Write script config to NBT for sending to client.
* Called on server side when building login packet.
*/
public static NBTTagCompound writeToNBT(NBTTagCompound compound) {
compound.setBoolean("ScriptingEnabled", ConfigScript.ScriptingEnabled);
compound.setBoolean("RunLoadedScriptsFirst", ConfigScript.RunLoadedScriptsFirst);
compound.setBoolean("GlobalPlayerScripts", ConfigScript.GlobalPlayerScripts);
compound.setBoolean("GlobalForgeScripts", ConfigScript.GlobalForgeScripts);
compound.setBoolean("GlobalNPCScripts", ConfigScript.GlobalNPCScripts);
return compound;
}
}
@@ -3,6 +3,7 @@ package noppes.npcs.controllers;
import cpw.mods.fml.common.eventhandler.Event;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcs;
import noppes.npcs.NBTTags;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.constants.EnumScriptType;
@@ -104,7 +105,7 @@ public class ScriptContainer implements IScriptUnit {
if (!this.evaluated) {
// build includes first depending on config setting
StringBuilder sb = new StringBuilder();
if (ConfigScript.RunLoadedScriptsFirst) {
if (CustomNpcs.proxy.isRunLoadedScriptsFirst()) {
this.appendExternalScripts(sb);
}
@@ -114,7 +115,7 @@ public class ScriptContainer implements IScriptUnit {
}
// build includes last if not built first
if (!ConfigScript.RunLoadedScriptsFirst) {
if (!CustomNpcs.proxy.isRunLoadedScriptsFirst()) {
this.appendExternalScripts(sb);
}
this.fullscript = sb.toString();
@@ -158,14 +159,14 @@ public class ScriptContainer implements IScriptUnit {
}
public void run(EnumScriptType type, Event event) {
if (!ConfigScript.ScriptingEnabled)
if (!CustomNpcs.proxy.isScriptingEnabled())
return;
this.run((String) type.function, (Object) event);
}
public void run(String type, Object event) {
if (!ConfigScript.ScriptingEnabled || errored || !hasCode() || unknownFunctions.contains(type))
if (!CustomNpcs.proxy.isScriptingEnabled() || errored || !hasCode() || unknownFunctions.contains(type))
return;
this.setEngine(handler.getLanguage());
@@ -342,5 +343,10 @@ public class ScriptContainer implements IScriptUnit {
public void setErrored(boolean errored) {
this.errored = errored;
}
@Override
public boolean isJanino() {
return false;
}
}
@@ -73,7 +73,7 @@ public class ScriptController {
public ScriptController() {
Instance = this;
manager = new ScriptEngineManager();
if (!ConfigScript.ScriptingEnabled)
if (!CustomNpcs.proxy.isScriptingEnabled())
return;
LogWriter.info("Script Engines Available:");
@@ -15,6 +15,7 @@ import noppes.npcs.api.IPos;
import noppes.npcs.api.IWorld;
import noppes.npcs.api.entity.IEntity;
import noppes.npcs.api.handler.ICloneHandler;
import noppes.npcs.controllers.data.CloneFolder;
import noppes.npcs.controllers.data.TagMap;
import noppes.npcs.scripted.CustomNPCsException;
import noppes.npcs.scripted.NpcAPI;
@@ -27,6 +28,7 @@ import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -34,8 +36,11 @@ import java.util.UUID;
public class ServerCloneController implements ICloneHandler {
public static ServerCloneController Instance;
protected Map<String, CloneFolder> folders = new LinkedHashMap<>();
public ServerCloneController() {
loadClones();
loadFolders();
}
private void loadClones() {
@@ -103,6 +108,8 @@ public class ServerCloneController implements ICloneHandler {
return clones;
}
// ==================== Tab-Based Clone Operations ====================
public NBTTagCompound getCloneData(ICommandSender player, String name, int tab) {
File file = new File(new File(getDir(), tab + ""), name + ".json");
if (!file.exists()) {
@@ -194,6 +201,250 @@ public class ServerCloneController implements ICloneHandler {
return name;
}
// ==================== Folder Registry ====================
public void loadFolders() {
folders.clear();
File dir = getDir();
File[] files = dir.listFiles();
if (files != null) {
List<File> folderDirs = new ArrayList<>();
for (File f : files) {
if (!f.isDirectory()) continue;
String name = f.getName();
if (name.startsWith("___")) continue;
try {
Integer.parseInt(name);
continue;
} catch (NumberFormatException ignored) {
}
folderDirs.add(f);
}
folderDirs.sort(Comparator.comparing(File::getName));
for (File f : folderDirs) {
CloneFolder folder = new CloneFolder(f.getName());
folder.createdDate = f.lastModified();
folders.put(f.getName(), folder);
}
}
}
public List<CloneFolder> getFolderList() {
return new ArrayList<>(folders.values());
}
public List<String> getFolderNames() {
return new ArrayList<>(folders.keySet());
}
public boolean hasFolder(String name) {
return folders.containsKey(name);
}
// ==================== Folder CRUD ====================
public CloneFolder createFolder(String name) {
if (!CloneFolder.isValidName(name) || folders.containsKey(name)) {
return null;
}
CloneFolder folder = new CloneFolder(name);
File dir = getFolderDir(name);
if (!dir.exists()) {
dir.mkdir();
}
folders.put(name, folder);
return folder;
}
public boolean renameFolder(String oldName, String newName) {
if (!folders.containsKey(oldName) || !CloneFolder.isValidName(newName) || folders.containsKey(newName)) {
return false;
}
CloneFolder folder = folders.get(oldName);
File oldDir = getFolderDir(oldName);
File newDir = new File(getDir(), newName);
if (!oldDir.renameTo(newDir)) {
return false;
}
folders.remove(oldName);
folder.name = newName;
folders.put(newName, folder);
return true;
}
public boolean deleteFolder(String name) {
if (!folders.containsKey(name)) {
return false;
}
List<String> clones = getClones(name);
if (!clones.isEmpty()) {
return false;
}
File dir = getFolderDir(name);
if (dir.exists()) {
File tagMapFile = new File(dir, "___tagmap.dat");
if (tagMapFile.exists()) tagMapFile.delete();
File tagMapOld = new File(dir, "___tagmap.dat_old");
if (tagMapOld.exists()) tagMapOld.delete();
File tagMapNew = new File(dir, "___tagmap.dat_new");
if (tagMapNew.exists()) tagMapNew.delete();
dir.delete();
}
folders.remove(name);
return true;
}
// ==================== Folder-Based Clone Operations ====================
public File getFolderDir(String folderName) {
return new File(getDir(), folderName);
}
public List<String> getClones(String folderName) {
List<String> list = new ArrayList<>();
File dir = getFolderDir(folderName);
if (!dir.exists() || !dir.isDirectory())
return list;
for (String file : dir.list()) {
if (file.endsWith(".json"))
list.add(file.substring(0, file.length() - 5));
}
return list;
}
public List<String> getClonesDate(String folderName) {
List<String> list = new ArrayList<>();
File dir = getFolderDir(folderName);
if (!dir.exists() || !dir.isDirectory())
return list;
File[] files = dir.listFiles();
if (files == null) return list;
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.compare(f1.lastModified(), f2.lastModified());
}
});
for (File file : files) {
String fileName = file.getName();
if (fileName.endsWith(".json"))
list.add(fileName.substring(0, fileName.length() - 5));
}
return list;
}
public NBTTagCompound getCloneData(ICommandSender player, String name, String folderName) {
File file = new File(getFolderDir(folderName), name + ".json");
if (!file.exists()) {
if (player != null)
player.addChatMessage(new ChatComponentText("Could not find clone file"));
return null;
}
try {
return NBTJsonUtil.LoadFile(file);
} catch (Exception e) {
LogWriter.error("Error loading: " + file.getAbsolutePath(), e);
if (player != null)
player.addChatMessage(new ChatComponentText(e.getMessage()));
}
return null;
}
public void saveClone(String folderName, String name, NBTTagCompound compound) {
try {
File dir = getFolderDir(folderName);
if (!dir.exists()) dir.mkdir();
String filename = name + ".json";
File file = new File(dir, filename + "_new");
File file2 = new File(dir, filename);
NBTJsonUtil.SaveFile(file, compound);
addToTagMap(compound, name, folderName);
if (file2.exists()) {
file2.delete();
}
file.renameTo(file2);
} catch (Exception e) {
LogWriter.except(e);
}
}
public boolean removeClone(String name, String folderName) {
File file = new File(getFolderDir(folderName), name + ".json");
if (!file.exists())
return false;
file.delete();
removeFromTagMap(name, folderName);
return true;
}
public String addClone(NBTTagCompound nbttagcompound, String name, String folderName) {
cleanTags(nbttagcompound);
saveClone(folderName, name, nbttagcompound);
return name;
}
public String addClone(NBTTagCompound nbttagcompound, String name, String folderName, NBTTagCompound tempTags) {
cleanTagList(nbttagcompound, tempTags);
cleanTags(nbttagcompound);
saveClone(folderName, name, nbttagcompound);
return name;
}
// ==================== Move Operations ====================
public boolean moveClone(String cloneName, int fromTab, String toFolder) {
NBTTagCompound data = getCloneData(null, cloneName, fromTab);
if (data == null) return false;
HashSet<UUID> tagUUIDs = getTagUUIDsFromTab(cloneName, fromTab);
saveClone(toFolder, cloneName, data);
setTagUUIDsForFolder(cloneName, toFolder, tagUUIDs);
removeClone(cloneName, fromTab);
return true;
}
public boolean moveClone(String cloneName, String fromFolder, int toTab) {
NBTTagCompound data = getCloneData(null, cloneName, fromFolder);
if (data == null) return false;
HashSet<UUID> tagUUIDs = getTagUUIDsFromFolder(cloneName, fromFolder);
saveClone(toTab, cloneName, data);
setTagUUIDsForTab(cloneName, toTab, tagUUIDs);
removeClone(cloneName, fromFolder);
return true;
}
public boolean moveClone(String cloneName, String fromFolder, String toFolder) {
NBTTagCompound data = getCloneData(null, cloneName, fromFolder);
if (data == null) return false;
HashSet<UUID> tagUUIDs = getTagUUIDsFromFolder(cloneName, fromFolder);
saveClone(toFolder, cloneName, data);
setTagUUIDsForFolder(cloneName, toFolder, tagUUIDs);
removeClone(cloneName, fromFolder);
return true;
}
public boolean moveClone(String cloneName, int fromTab, int toTab) {
NBTTagCompound data = getCloneData(null, cloneName, fromTab);
if (data == null) return false;
HashSet<UUID> tagUUIDs = getTagUUIDsFromTab(cloneName, fromTab);
saveClone(toTab, cloneName, data);
setTagUUIDsForTab(cloneName, toTab, tagUUIDs);
removeClone(cloneName, fromTab);
return true;
}
// ==================== Tag Utilities ====================
public NBTTagCompound cleanTagList(NBTTagCompound nbttagcompound, NBTTagCompound tempTags) {
HashSet<UUID> tagUUIDs = new HashSet<UUID>();
if (nbttagcompound.hasKey("TagUUIDs")) {
@@ -243,6 +494,25 @@ public class ServerCloneController implements ICloneHandler {
return true;
}
public boolean addToTagMap(NBTTagCompound nbttagcompound, String name, String folderName) {
HashSet<UUID> tagUUIDs = new HashSet<>();
if (nbttagcompound.hasKey("TagUUIDs")) {
NBTTagList nbtTagList = nbttagcompound.getTagList("TagUUIDs", 8);
for (int i = 0; i < nbtTagList.tagCount(); i++) {
tagUUIDs.add(UUID.fromString(nbtTagList.getStringTagAt(i)));
}
}
TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName);
if (!tagUUIDs.isEmpty()) {
tagMap.putClone(name, tagUUIDs);
} else {
tagMap.removeClone(name);
}
ServerTagMapController.Instance.saveTagMap(tagMap);
return true;
}
public boolean removeFromTagMap(String name, int tab) {
TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab);
if (tagMap.removeClone(name)) {
@@ -252,6 +522,41 @@ public class ServerCloneController implements ICloneHandler {
return false;
}
public boolean removeFromTagMap(String name, String folderName) {
TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName);
if (tagMap.removeClone(name)) {
ServerTagMapController.Instance.saveTagMap(tagMap);
return true;
}
return false;
}
protected HashSet<UUID> getTagUUIDsFromTab(String cloneName, int tab) {
TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab);
HashSet<UUID> uuids = tagMap.getUUIDs(cloneName);
return uuids != null ? new HashSet<>(uuids) : new HashSet<>();
}
protected HashSet<UUID> getTagUUIDsFromFolder(String cloneName, String folderName) {
TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName);
HashSet<UUID> uuids = tagMap.getUUIDs(cloneName);
return uuids != null ? new HashSet<>(uuids) : new HashSet<>();
}
protected void setTagUUIDsForTab(String cloneName, int tab, HashSet<UUID> tagUUIDs) {
if (tagUUIDs == null || tagUUIDs.isEmpty()) return;
TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab);
tagMap.putClone(cloneName, tagUUIDs);
ServerTagMapController.Instance.saveTagMap(tagMap);
}
protected void setTagUUIDsForFolder(String cloneName, String folderName, HashSet<UUID> tagUUIDs) {
if (tagUUIDs == null || tagUUIDs.isEmpty()) return;
TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName);
tagMap.putClone(cloneName, tagUUIDs);
ServerTagMapController.Instance.saveTagMap(tagMap);
}
public void cleanTags(NBTTagCompound nbttagcompound) {
if (nbttagcompound.hasKey("ItemGiverId"))
nbttagcompound.setInteger("ItemGiverId", 0);
@@ -288,6 +593,8 @@ public class ServerCloneController implements ICloneHandler {
}
}
// ==================== API Methods (ICloneHandler) ====================
public IEntity spawn(double x, double y, double z, int tab, String name, IWorld world, boolean ignoreProtection) {
NBTTagCompound compound = this.getCloneData((ICommandSender) null, name, tab);
if (compound == null) {
@@ -327,7 +634,7 @@ public class ServerCloneController implements ICloneHandler {
for (File file : dir.listFiles()) {
if (file.getName().endsWith(".json")) {
NBTTagCompound compound = NBTJsonUtil.LoadFile(file);
Instance.cleanTags(compound);
cleanTags(compound);
Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld());
arrayList.add(entity == null ? null : NpcAPI.Instance().getIEntity(entity));
}
@@ -343,7 +650,7 @@ public class ServerCloneController implements ICloneHandler {
if (compound == null) {
throw new CustomNPCsException("Unknown clone tab:" + tab + " name:" + name, new Object[0]);
} else {
Instance.cleanTags(compound);
cleanTags(compound);
Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld());
return entity == null ? null : NpcAPI.Instance().getIEntity(entity);
}
@@ -354,7 +661,6 @@ public class ServerCloneController implements ICloneHandler {
return compound != null;
}
public void set(int tab, String name, IEntity entity) {
NBTTagCompound compound = new NBTTagCompound();
if (!entity.getMCEntity().writeMountToNBT(compound))
@@ -367,4 +673,85 @@ public class ServerCloneController implements ICloneHandler {
public void remove(int tab, String name) {
this.removeClone(name, tab);
}
// --- Folder API Methods ---
public String[] getFolders() {
return getFolderNames().toArray(new String[0]);
}
public IEntity spawn(double x, double y, double z, String folderName, String name, IWorld world, boolean ignoreProtection) {
NBTTagCompound compound = getCloneData(null, name, folderName);
if (compound == null) {
throw new CustomNPCsException("Unknown clone folder:" + folderName + " name:" + name, new Object[0]);
}
Entity entity;
if (!ignoreProtection) {
entity = NoppesUtilServer.spawnCloneWithProtection(compound, (int) x, (int) y, (int) z, world.getMCWorld());
} else {
entity = NoppesUtilServer.spawnClone(compound, (int) x, (int) y, (int) z, world.getMCWorld());
}
return entity == null ? null : NpcAPI.Instance().getIEntity(entity);
}
public IEntity spawn(IPos pos, String folderName, String name, IWorld world, boolean ignoreProtection) {
return this.spawn(pos.getX(), pos.getY(), pos.getZ(), folderName, name, world, ignoreProtection);
}
public IEntity spawn(double x, double y, double z, String folderName, String name, IWorld world) {
return spawn(x, y, z, folderName, name, world, true);
}
public IEntity spawn(IPos pos, String folderName, String name, IWorld world) {
return this.spawn(pos.getX(), pos.getY(), pos.getZ(), folderName, name, world);
}
public IEntity[] getFolder(String folderName, IWorld world) {
File dir = getFolderDir(folderName);
if (!dir.exists() || !dir.isDirectory() || dir.listFiles() == null) {
return new IEntity[]{};
}
ArrayList<IEntity> arrayList = new ArrayList<>();
try {
for (File file : dir.listFiles()) {
if (file.getName().endsWith(".json")) {
NBTTagCompound compound = NBTJsonUtil.LoadFile(file);
cleanTags(compound);
Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld());
arrayList.add(entity == null ? null : NpcAPI.Instance().getIEntity(entity));
}
}
} catch (Exception ignored) {
}
return arrayList.toArray(new IEntity[]{});
}
public IEntity get(String folderName, String name, IWorld world) {
NBTTagCompound compound = getCloneData(null, name, folderName);
if (compound == null) {
throw new CustomNPCsException("Unknown clone folder:" + folderName + " name:" + name, new Object[0]);
}
cleanTags(compound);
Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld());
return entity == null ? null : NpcAPI.Instance().getIEntity(entity);
}
public boolean has(String folderName, String name) {
NBTTagCompound compound = getCloneData(null, name, folderName);
return compound != null;
}
public void set(String folderName, String name, IEntity entity) {
NBTTagCompound compound = new NBTTagCompound();
if (!entity.getMCEntity().writeMountToNBT(compound))
throw new CustomNPCsException("Cannot save dead entities", new Object[0]);
this.cleanTags(compound);
this.saveClone(folderName, name, compound);
}
public void remove(String folderName, String name) {
this.removeClone(name, folderName);
}
}
@@ -35,6 +35,13 @@ public class ServerTagMapController {
return dir;
}
public File getCloneFolderDir(String folderName) {
File dir = new File(getDir(), folderName);
if (!dir.exists())
dir.mkdir();
return dir;
}
public TagMap getTagMap(int tab) {
this.tagMap = new TagMap(tab);
try {
@@ -65,9 +72,33 @@ public class ServerTagMapController {
this.tagMap.readNBT(nbtCompound);
}
public TagMap getTagMap(String folderName) {
this.tagMap = new TagMap(folderName);
try {
File file = new File(getCloneFolderDir(folderName), "___tagmap.dat");
if (file.exists()) {
loadTagMapFile(file);
}
} catch (Exception e) {
try {
File file = new File(getCloneFolderDir(folderName), "___tagmap.dat_old");
if (file.exists()) {
loadTagMapFile(file);
}
} catch (Exception ignored) {
}
}
return this.tagMap;
}
public void saveTagMap(TagMap tagMap) {
try {
File saveDir = getCloneTabDir(tagMap.cloneTab);
File saveDir;
if (tagMap.cloneFolder != null) {
saveDir = getCloneFolderDir(tagMap.cloneFolder);
} else {
saveDir = getCloneTabDir(tagMap.cloneTab);
}
File file = new File(saveDir, "___tagmap.dat_new");
File file1 = new File(saveDir, "___tagmap.dat_old");
File file2 = new File(saveDir, "___tagmap.dat");
@@ -0,0 +1,61 @@
package noppes.npcs.controllers.data;
import net.minecraft.nbt.NBTTagCompound;
public class CloneFolder {
public String name;
public long createdDate;
public CloneFolder() {
this.name = "";
this.createdDate = System.currentTimeMillis();
}
public CloneFolder(String name) {
this.name = name;
this.createdDate = System.currentTimeMillis();
}
public void readNBT(NBTTagCompound compound) {
name = compound.getString("Name");
createdDate = compound.getLong("Created");
}
public NBTTagCompound writeNBT(NBTTagCompound compound) {
compound.setString("Name", name);
compound.setLong("Created", createdDate);
return compound;
}
public static boolean isValidName(String name) {
if (name == null || name.isEmpty()) {
return false;
}
if (name.length() > 32) {
return false;
}
if (!name.equals(name.trim())) {
return false;
}
if (name.equals(".") || name.equals("..")) {
return false;
}
if (name.startsWith("___")) {
return false;
}
try {
Integer.parseInt(name);
return false;
} catch (NumberFormatException ignored) {
}
for (char c : name.toCharArray()) {
if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
return false;
}
if (c < 32) {
return false;
}
}
return true;
}
}
@@ -9,13 +9,13 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import noppes.npcs.CustomNpcs;
import noppes.npcs.EventHooks;
import noppes.npcs.LogWriter;
import noppes.npcs.NBTTags;
import noppes.npcs.api.IWorld;
import noppes.npcs.api.entity.ICustomNpc;
import noppes.npcs.config.ConfigDebug;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.constants.EnumScriptType;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptContainer;
@@ -74,7 +74,7 @@ public class DataScript implements IScriptHandlerPacket {
public void readFromNBT(NBTTagCompound compound) {
scripts = readScript(compound.getTagList("ScriptsContainers", 10));
this.scriptLanguage = compound.getString("ScriptLanguage");
if (!ScriptController.Instance.languages.containsKey(scriptLanguage)) {
if (scriptLanguage == null || scriptLanguage.isEmpty()) {
if (!ScriptController.Instance.languages.isEmpty()) {
this.scriptLanguage = (String) ScriptController.Instance.languages.keySet().toArray()[0];
} else {
@@ -209,7 +209,7 @@ public class DataScript implements IScriptHandlerPacket {
}
public boolean isEnabled() {
return enabled && ScriptController.HasStart && !npc.worldObj.isRemote && !scripts.isEmpty() && ConfigScript.ScriptingEnabled;
return enabled && ScriptController.HasStart && !npc.worldObj.isRemote && !scripts.isEmpty() && CustomNpcs.proxy.isScriptingEnabled();
}
@Override
@@ -12,8 +12,8 @@ import net.minecraftforge.event.world.ChunkDataEvent;
import net.minecraftforge.event.world.ChunkEvent;
import net.minecraftforge.event.world.ChunkWatchEvent;
import net.minecraftforge.event.world.WorldEvent;
import noppes.npcs.CustomNpcs;
import noppes.npcs.EventHooks;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
@@ -36,7 +36,7 @@ public class ForgeDataScript extends MultiScriptHandler {
}
public boolean isEnabled() {
return this.enabled && ConfigScript.GlobalForgeScripts && ScriptController.HasStart && this.scripts.size() > 0;
return this.enabled && CustomNpcs.proxy.isGlobalForgeScripts() && ScriptController.HasStart && this.scripts.size() > 0;
}
@Override
@@ -3,8 +3,8 @@ package noppes.npcs.controllers.data;
import kamkeel.npcs.network.packets.request.script.GlobalNPCScriptPacket;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import noppes.npcs.CustomNpcs;
import noppes.npcs.api.entity.ICustomNpc;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.entity.EntityNPCInterface;
@@ -28,7 +28,7 @@ public class GlobalNPCDataScript extends MultiScriptHandler {
}
public boolean isEnabled() {
return ConfigScript.GlobalNPCScripts && this.enabled && ScriptController.HasStart && this.scripts.size() > 0;
return CustomNpcs.proxy.isGlobalNPCScripts() && this.enabled && ScriptController.HasStart && this.scripts.size() > 0;
}
@Override
@@ -55,7 +55,7 @@ public abstract class MultiScriptHandler extends ScriptHandler implements IScrip
* Normalize the language to a valid one if the current language is not available.
*/
protected void normalizeLanguage() {
if (!ScriptController.Instance.languages.containsKey(this.scriptLanguage)) {
if (this.scriptLanguage == null || this.scriptLanguage.isEmpty()) {
if (!ScriptController.Instance.languages.isEmpty()) {
this.scriptLanguage = (String) ScriptController.Instance.languages.keySet().toArray()[0];
} else {
@@ -229,16 +229,37 @@ public class PlayerAbilityData implements IPlayerAbilityData {
currentTarget = null; // Players don't have auto-targets
ability.start(null);
// Spawn telegraph
spawnTelegraph(ability, player, null);
// Play wind up sound and animation
playAbilitySound(player, ability.getWindUpSound());
playAbilityAnimation(ability.getWindUpAnimation());
if (ability.getPhase() == AbilityPhase.ACTIVE) {
// Windup was 0 — skip telegraph/windup and go straight to active
executeImmediate(ability, player);
} else {
// Normal windup flow
spawnTelegraph(ability, player, null);
playAbilitySound(player, ability.getWindUpSound());
playAbilityAnimation(ability.getWindUpAnimation());
}
return true;
}
/**
* Execute an ability immediately (no windup).
* Called when windUpTicks is 0.
*/
private void executeImmediate(Ability ability, EntityPlayer player) {
// Play active sound and animation
playAbilitySound(player, ability.getActiveSound());
playAbilityAnimation(ability.getActiveAnimation());
// Call onExecute
ability.onExecute(player, currentTarget, player.worldObj);
// Check if ability completed during onExecute
if (ability.getPhase() == AbilityPhase.IDLE) {
handleAbilityCompletion(player);
}
}
// ═══════════════════════════════════════════════════════════════════
// CLIENT SYNC
// ═══════════════════════════════════════════════════════════════════
@@ -453,13 +474,29 @@ public class PlayerAbilityData implements IPlayerAbilityData {
// ANIMATION
// ═══════════════════════════════════════════════════════════════════
private void playAbilityAnimation(Animation animation) {
public void playAbilityAnimation(Animation animation) {
if (animation == null || AnimationController.Instance == null) return;
playerData.animationData.setEnabled(true);
playerData.animationData.setAnimation(animation);
playerData.animationData.updateClient();
}
public void playAbilityAnimation(int animation) {
if (animation < 0) return;
if (AnimationController.Instance == null) return;
if (AnimationController.Instance.get(animation) == null) return;
playAbilityAnimation((Animation) AnimationController.Instance.get(animation));
}
public void playAbilityAnimation(String animation) {
if (animation.isEmpty()) return;
if (AnimationController.Instance == null) return;
if (AnimationController.Instance.get(animation, true) == null) return;
playAbilityAnimation((Animation) AnimationController.Instance.get(animation, true));
}
private void stopAbilityAnimation() {
playerData.animationData.setAnimation(null);
playerData.animationData.updateClient();
@@ -5,6 +5,7 @@ import kamkeel.npcs.network.packets.request.script.PlayerScriptPacket;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import noppes.npcs.CustomNpcs;
import noppes.npcs.EventHooks;
import noppes.npcs.NBTTags;
import noppes.npcs.api.entity.IPlayer;
@@ -60,7 +61,7 @@ public class PlayerDataScript extends MultiScriptHandler {
}
public boolean isEnabled() {
return ConfigScript.GlobalPlayerScripts && ScriptController.Instance.playerScripts.enabled && ScriptController.HasStart && (this.player == null || !this.player.worldObj.isRemote);
return CustomNpcs.proxy.isGlobalPlayerScripts() && ScriptController.Instance.playerScripts.enabled && ScriptController.HasStart && (this.player == null || !this.player.worldObj.isRemote);
}
@Override
@@ -1,7 +1,7 @@
package noppes.npcs.controllers.data;
import cpw.mods.fml.common.eventhandler.Event;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.CustomNpcs;
import noppes.npcs.controllers.ScriptController;
import java.util.ArrayList;
@@ -14,7 +14,7 @@ public abstract class ScriptHandler implements IScriptHandler {
protected long lastInited = -1;
protected boolean canRunScripts() {
return enabled && ScriptController.HasStart && ConfigScript.ScriptingEnabled && scripts != null && !scripts.isEmpty();
return enabled && ScriptController.HasStart && CustomNpcs.proxy.isScriptingEnabled() && scripts != null && !scripts.isEmpty();
}
@Override
@@ -5,7 +5,7 @@ import io.netty.buffer.ByteBuf;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.Constants;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.CustomNpcs;
import noppes.npcs.controllers.ScriptController;
import java.io.IOException;
@@ -32,7 +32,7 @@ public abstract class SingleScriptHandler extends ScriptHandler {
}
protected boolean canRunScripts() {
return enabled && ScriptController.HasStart && ConfigScript.ScriptingEnabled && container != null;
return enabled && ScriptController.HasStart && CustomNpcs.proxy.isScriptingEnabled() && container != null;
}
@Override
@@ -142,7 +142,7 @@ public abstract class SingleScriptHandler extends ScriptHandler {
* Normalize the language to a valid one if the current language is not available.
*/
protected void normalizeLanguage() {
if (!ScriptController.Instance.languages.containsKey(this.getLanguage())) {
if (this.getLanguage() == null || this.getLanguage().isEmpty()) {
if (!ScriptController.Instance.languages.isEmpty()) {
this.setLanguage((String) ScriptController.Instance.languages.keySet().toArray()[0]);
} else {
@@ -13,10 +13,18 @@ import java.util.UUID;
public class TagMap {
public int cloneTab;
public String cloneFolder;
public HashMap<String, HashSet<UUID>> tagMap;
public TagMap(int tab) {
this.cloneTab = tab;
this.cloneFolder = null;
this.tagMap = new HashMap<String, HashSet<UUID>>();
}
public TagMap(String folder) {
this.cloneTab = -1;
this.cloneFolder = folder;
this.tagMap = new HashMap<String, HashSet<UUID>>();
}
@@ -308,6 +308,13 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
@Override
public void onUpdate() {
super.onUpdate();
// Re-apply locks after super.onUpdate() to override body rotation smoothing
// in EntityLivingBase.onUpdate() (func_110146_f) which runs AFTER onLivingUpdate()
// and overwrites renderYawOffset, causing a visible twitch each frame.
abilities.applyRotationControl();
abilities.applyLockedPosition();
if (!isRemote()) {
if (this.ticksExisted % 10 == 0) {
EventHooks.onNPCUpdate(this);
@@ -481,8 +488,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
super.onLivingUpdate();
// Apply locked rotation after super.onLivingUpdate() to override look helper changes
abilities.applyLockedRotation();
// Apply locks after super.onLivingUpdate() to override AI/physics changes
abilities.applyRotationControl();
abilities.applyLockedPosition();
handleMountRiderState();
@@ -670,6 +678,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
if (entity instanceof EntityLivingBase)
attackingEntity = (EntityLivingBase) entity;
if (faction.isPassive)
return false;
if (attackingEntity != null && attackingEntity == getOwner())
return false;
else if (attackingEntity instanceof EntityNPCInterface) {
@@ -1693,7 +1704,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
}
/**
* 1: walking, 2:interacting, 4:attacking, 8:killed
* 1: walking, 2:interacting, 4:attacking, 8:killed, 16:rotationLocked
*/
public boolean getBoolFlag(int id) {
return (dataWatcher.getWatchableObjectInt(15) & id) != 0;
@@ -16,6 +16,7 @@ public class ItemElementalStaff extends ItemStaff {
public ItemElementalStaff(int par1, EnumNpcToolMaterial material) {
super(par1, material);
setHasSubtypes(true);
this.color = OrbColor.GENERIC;
}
@Override
+104 -37
View File
@@ -1,32 +1,39 @@
package noppes.npcs.items;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.data.*;
import kamkeel.npcs.entity.EntityAbilityOrb;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import noppes.npcs.CustomItems;
import noppes.npcs.CustomNpcs;
import noppes.npcs.constants.EnumNpcToolMaterial;
import noppes.npcs.enchants.EnchantInterface;
import noppes.npcs.entity.EntityMagicProjectile;
import noppes.npcs.entity.EntityProjectile;
import noppes.npcs.util.IProjectileCallback;
import org.lwjgl.opengl.GL11;
import java.awt.*;
public class ItemStaff extends ItemNpcInterface implements IProjectileCallback {
private EnumNpcToolMaterial material;
protected OrbColor color;
public ItemStaff(int par1, EnumNpcToolMaterial material) {
super(par1);
this.material = material;
this.color = OrbColor.get(material.ordinal());;
setCreativeTab(CustomItems.tabWeapon);
}
@@ -36,70 +43,93 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback {
}
@Override
public void onPlayerStoppedUsing(ItemStack stack, World worldObj, EntityPlayer player, int par4) {
if (worldObj.isRemote) {
public void onPlayerStoppedUsing(ItemStack stack, World world, EntityPlayer player, int par4) {
if (world.isRemote)
return;
}
if (stack.stackTagCompound == null)
return;
Entity entity = ((WorldServer) player.worldObj).getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile"));
if (entity == null || !(entity instanceof EntityProjectile))
Entity entity = ((WorldServer) world)
.getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile"));
if (!(entity instanceof EntityAbilityOrb))
return;
EntityProjectile item = (EntityProjectile) entity;
item.callback = this;
item.callbackItem = stack;
item.explosive = true;
item.explosiveDamage = false;
item.explosiveRadius = 1;
item.prevRotationYaw = item.rotationYaw = player.rotationYaw;
item.prevRotationPitch = item.rotationPitch = player.rotationPitch;
item.shoot(2);
player.worldObj.playSoundAtEntity(player, "customnpcs:magic.shot", 1.0F, 1);
EntityAbilityOrb orb = (EntityAbilityOrb) entity;
orb.startMoving(null);
world.playSoundAtEntity(
player,
"customnpcs:magic.shot",
1.0F,
1.0F
);
}
@Override
public void onUsingTick(ItemStack stack, EntityPlayer player, int count) {
int tick = getMaxItemUseDuration(stack) - count;
if (player.worldObj.isRemote) {
spawnParticle(stack, player);
return;
}
int chargeTime = 20 + material.getHarvestLevel() * 8;
if (tick == chargeTime) {
if (!player.capabilities.isCreativeMode && !hasInfinite(stack)) {
if (!hasItem(player, CustomItems.mana))
return;
consumeItem(player, CustomItems.mana);
}
player.worldObj.playSoundAtEntity(player, "customnpcs:magic.charge", 1.0F, 1);
player.worldObj.playSoundAtEntity(
player,
"customnpcs:magic.charge",
1.0F,
1.0F
);
if (stack.stackTagCompound == null) {
stack.stackTagCompound = new NBTTagCompound();
}
int damage = 6 + material.getDamageVsEntity() + player.worldObj.rand.nextInt(4);
damage += damage * EnchantInterface.getLevel(EnchantInterface.Damage, stack) * 0.5f;
EntityProjectile projectile = new EntityMagicProjectile(player.worldObj, player, getProjectile(stack), false);
projectile.damage = damage;
projectile.setSpeed(25);
double dx = -MathHelper.sin((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI));
double dz = MathHelper.cos((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI));
projectile.setPosition(player.posX + dx * 0.8, player.posY + 1.5 - player.rotationPitch / 80, player.posZ + dz * 0.8);
player.worldObj.spawnEntityInWorld(projectile);
stack.stackTagCompound.setInteger("MagicProjectile", projectile.getEntityId());//entityid
}
if (tick > chargeTime && stack.stackTagCompound != null) {
Entity entity = ((WorldServer) player.worldObj).getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile"));
if (entity == null || !(entity instanceof EntityProjectile))
return;
EntityProjectile item = (EntityProjectile) entity;
item.ticksInAir = 0;
double dx = -MathHelper.sin((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI));
double dz = MathHelper.cos((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI));
item.setPosition(player.posX + dx * 0.8, player.posY + 1.5 - player.rotationPitch / 80, player.posZ + dz * 0.8);
}
EnergyCombatData combat = new EnergyCombatData();
combat.damage = damage;
combat.explosive = true;
EnergyDisplayData colorData = new EnergyDisplayData(getOrbColor(stack, false), getOrbColor(stack, true));
EnergyLightningData lightning = new EnergyLightningData();
EnergyLifespanData lifespan = new EnergyLifespanData(100, 72000);
EnergyHomingData homing = new EnergyHomingData();
EnergyTrajectoryData trajectory = new EnergyTrajectoryData();
homing.speed = 0.5f;
homing.homingStrength = 0.35f;
homing.homingRange = 20f;
EntityAbilityOrb orb = new EntityAbilityOrb(
player.worldObj, player, null,
player.posX, player.posY + player.getEyeHeight(), player.posZ,
1.0f, colorData, combat, homing, lightning, lifespan, trajectory
);
orb.setupCharging(
new EnergyAnchorData(AnchorPoint.FRONT, 0, -1, 0),
chargeTime
);
player.worldObj.spawnEntityInWorld(orb);
stack.stackTagCompound.setInteger("MagicProjectile", orb.getEntityId());
}
}
@Override
@@ -118,6 +148,15 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback {
return EnumAction.bow;
}
public int getOrbColor(ItemStack stack, boolean outer) {
if (color == OrbColor.GENERIC) {
float[] color = EntitySheep.fleeceColorTable[stack.getItemDamage()];
return new Color(color[0], color[1], color[2]).getRGB();
}
return outer ? color.outer : color.inner;
}
public ItemStack getProjectile(ItemStack stack) {
if (stack.getItem() == CustomItems.staffWood) {
return new ItemStack(CustomItems.spellNature);
@@ -196,4 +235,32 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback {
public boolean hasInfinite(ItemStack stack) {
return EnchantInterface.getLevel(EnchantInterface.Infinite, stack) > 0;
}
public enum OrbColor {
WOOD(0x7cc818, 0x644a32),
STONE(0x532d5b, 0x515151),
BRONZE(0x83F7F6, 0x5CF0FF),
IRON(0xf7fac5, 0xeafa94),
DIA(0x44B6FF, 0x94DFED),
GOLD(0xb3011e, 0xd47c32),
EMERALD(0xdd6df7, 0xcf1dfa),
DEMONIC(0xb8144a, 0x422643),
FROST(0xffffff, 0xaccbfe),
MITHRIL(0xf7fac5, 0xffffff),
GENERIC(0xFFFFFF, 0x88FFFF);
public final int inner;
public final int outer;
OrbColor(int inner, int outer) {
this.inner = inner;
this.outer = outer;
}
public static OrbColor get(int id) {
if (id >= OrbColor.values().length || id < 0) return GENERIC;
return OrbColor.values()[id];
}
}
}
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff. Show more