Merge branch 'dev' into pr-254

# Conflicts:
#	src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerSelector.java
This commit is contained in:
KAMKEEL committed 2026-08-11 06:29:18 -04:00
commit 22a8ef5036
791 files changed
+117380 -18377

No files matched your search

@@ -7,17 +7,17 @@ import net.minecraft.nbt.NBTTagCompound;
/**
* Client-side cache for auction configuration synced from server.
* Prevents client from using local ConfigMarket which may differ from server settings.
*
* <p>
* IMPORTANT: This class is CLIENT-ONLY. Server-side NBT writing is done in
* AuctionConfigSync to avoid @SideOnly crashes on dedicated servers.
*/
@SideOnly(Side.CLIENT)
public class AuctionClientConfig {
// Cached values from server
private static long listingFee = 0;
private static volatile long listingFee = 0;
private static String currencyName = "Coins";
private static int auctionDurationHours = 24;
private static double minBidIncrement = 0.05;
private static volatile double minBidIncrement = 0.05;
private static int maxActiveListings = 8;
private static int claimExpirationDays = 20;
private static boolean auctionEnabled = false;
@@ -38,7 +38,7 @@ public class AuctionClientConfig {
claimExpirationDays = compound.getInteger("ClaimExpirationDays");
if (currencyName.isEmpty()) {
currencyName = "Gold";
currencyName = "Coins";
}
}
@@ -56,11 +56,31 @@ public class AuctionClientConfig {
}
// Getters
public static boolean isAuctionEnabled() { return auctionEnabled; }
public static long getListingFee() { return listingFee; }
public static String getCurrencyName() { return currencyName; }
public static int getAuctionDurationHours() { return auctionDurationHours; }
public static double getMinBidIncrement() { return minBidIncrement; }
public static int getMaxActiveListings() { return maxActiveListings; }
public static int getClaimExpirationDays() { return claimExpirationDays; }
public static boolean isAuctionEnabled() {
return auctionEnabled;
}
public static long getListingFee() {
return listingFee;
}
public static String getCurrencyName() {
return currencyName;
}
public static int getAuctionDurationHours() {
return auctionDurationHours;
}
public static double getMinBidIncrement() {
return minBidIncrement;
}
public static int getMaxActiveListings() {
return maxActiveListings;
}
public static int getClaimExpirationDays() {
return claimExpirationDays;
}
}
@@ -0,0 +1,65 @@
package noppes.npcs.client;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket;
/**
* Client-side state holder for player ability lock flags.
* Updated by {@link PlayerAbilityStatePacket} from the server.
* Read by {@link ClientTickHandler} to suppress WASD input and enforce rotation.
*/
@SideOnly(Side.CLIENT)
public class ClientAbilityState {
public static boolean movementLocked = false;
public static boolean rotationLocked = false;
public static boolean hasAbilityMovement = false;
public static boolean positionLocked = false;
public static boolean wasFlyingAtLock = false;
public static boolean activePhase = false;
public static float lockedYaw = 0;
public static float lockedPitch = 0;
/**
* Update state from a received packet.
*/
public static void update(byte flags, float yaw, float pitch) {
movementLocked = (flags & PlayerAbilityStatePacket.FLAG_MOVEMENT_LOCKED) != 0;
rotationLocked = (flags & PlayerAbilityStatePacket.FLAG_ROTATION_LOCKED) != 0;
hasAbilityMovement = (flags & PlayerAbilityStatePacket.FLAG_HAS_ABILITY_MOVEMENT) != 0;
positionLocked = (flags & PlayerAbilityStatePacket.FLAG_POSITION_LOCKED) != 0;
wasFlyingAtLock = (flags & PlayerAbilityStatePacket.FLAG_WAS_FLYING_AT_LOCK) != 0;
activePhase = (flags & PlayerAbilityStatePacket.FLAG_ACTIVE_PHASE) != 0;
lockedYaw = yaw;
lockedPitch = pitch;
}
/**
* Whether player WASD movement input should be suppressed.
* True when movement/position is locked or ability has its own movement.
*/
public static boolean shouldSuppressMovementInput() {
return movementLocked || hasAbilityMovement || positionLocked;
}
/**
* Whether player camera rotation should be locked.
*/
public static boolean shouldLockRotation() {
return rotationLocked;
}
/**
* Reset all state. Called on world change / disconnect.
*/
public static void reset() {
movementLocked = false;
rotationLocked = false;
hasAbilityMovement = false;
positionLocked = false;
wasFlyingAtLock = false;
activePhase = false;
lockedYaw = 0;
lockedPitch = 0;
}
}
@@ -1,6 +1,6 @@
package noppes.npcs.client;
import kamkeel.npcs.network.enums.EnumSyncType;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.controllers.MusicController;
@@ -18,8 +18,8 @@ import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.SkinOverlay;
import noppes.npcs.util.CacheHashMap;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
@@ -32,14 +32,14 @@ public class ClientCacheHandler {
private static String activeServerKey = "";
private static String lastServerKey = "";
private static final Map<String, EnumMap<EnumSyncType, Integer>> clientRevisionCache = new HashMap<>();
private static final Map<String, Map<SyncType, Integer>> clientRevisionCache = new HashMap<>();
public static Party party;
public static boolean allowProfiles = true;
public static boolean allowParties = true;
public static void setActiveServer(String serverKey, EnumMap<EnumSyncType, Integer> serverRevisions) {
public static void setActiveServer(String serverKey, Map<SyncType, Integer> serverRevisions) {
String normalizedKey = serverKey == null ? "" : serverKey;
String previousKey = activeServerKey == null ? "" : activeServerKey;
lastServerKey = previousKey;
@@ -54,9 +54,9 @@ public class ClientCacheHandler {
return;
}
EnumMap<EnumSyncType, Integer> cached = clientRevisionCache.computeIfAbsent(
Map<SyncType, Integer> cached = clientRevisionCache.computeIfAbsent(
activeServerKey,
ignored -> new EnumMap<>(EnumSyncType.class)
ignored -> new LinkedHashMap<>()
);
if (serverRevisions != null && !serverRevisions.isEmpty()) {
cached.keySet().retainAll(serverRevisions.keySet());
@@ -67,19 +67,19 @@ public class ClientCacheHandler {
return lastServerKey == null ? "" : lastServerKey;
}
public static EnumMap<EnumSyncType, Integer> getCachedRevisionsForServer(String serverKey) {
public static Map<SyncType, Integer> getCachedRevisionsForServer(String serverKey) {
String key = serverKey == null ? "" : serverKey;
if (key.isEmpty()) {
return new EnumMap<>(EnumSyncType.class);
return new LinkedHashMap<>();
}
EnumMap<EnumSyncType, Integer> revisions = clientRevisionCache.get(key);
Map<SyncType, Integer> revisions = clientRevisionCache.get(key);
if (revisions == null) {
return new EnumMap<>(EnumSyncType.class);
return new LinkedHashMap<>();
}
return new EnumMap<>(revisions);
return new LinkedHashMap<>(revisions);
}
public static void updateClientRevision(EnumSyncType type, int revision) {
public static void updateClientRevision(SyncType type, int revision) {
if (revision < 0) {
return;
}
@@ -87,9 +87,9 @@ public class ClientCacheHandler {
if (key.isEmpty()) {
return;
}
EnumMap<EnumSyncType, Integer> revisions = clientRevisionCache.computeIfAbsent(
Map<SyncType, Integer> revisions = clientRevisionCache.computeIfAbsent(
key,
ignored -> new EnumMap<>(EnumSyncType.class)
ignored -> new LinkedHashMap<>()
);
revisions.put(type, revision);
}
@@ -124,15 +124,13 @@ public class ClientCacheHandler {
ClientCacheHandler.customOverlays.clear();
ClientCacheHandler.skinOverlays.clear();
ClientCacheHandler.playerAnimations.clear();
ProfileClientConfig.reset();
// Clear Texture Caches
GuiSoundSelection.cachedDomains.clear();
GuiTextureSelection.cachedTextures.clear();
// Clear music/bard sounds
MusicController.Instance.stopAllSounds();
// Clear Quest Tracker
HudComponent component = ClientHudManager.getInstance().getHudComponents().get(EnumHudComponent.QuestTracker);
if (component != null) {
component.loadData(new NBTTagCompound());
@@ -145,7 +143,6 @@ public class ClientCacheHandler {
ClientCacheHandler.customOverlays.clear();
ClientCacheHandler.skinOverlays.clear();
// Clear Texture Caches
GuiSoundSelection.cachedDomains.clear();
GuiTextureSelection.cachedTextures.clear();
}
@@ -20,12 +20,14 @@ 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;
import noppes.npcs.client.gui.hud.EnumHudComponent;
import noppes.npcs.client.gui.hud.QuestTrackingComponent;
import noppes.npcs.client.gui.hud.ability.AbilityHotbarComponent;
import noppes.npcs.client.gui.player.AuctionTooltipHandler;
import noppes.npcs.client.KeyPressHandler;
import noppes.npcs.client.renderer.MarkRenderer;
import noppes.npcs.client.renderer.RenderCNPCPlayer;
import noppes.npcs.constants.EnumAnimationPart;
@@ -84,9 +86,43 @@ public class ClientEventHandler {
@SubscribeEvent
public void onMouse(MouseEvent event) {
if (Minecraft.getMinecraft().currentScreen != null)
// Always track mouse button state for KeyPressHandler FIRST.
// Canceled MouseEvents skip FML's MouseInputEvent entirely
// (Minecraft.java: if postMouseEvent() continue), so this is the
// only reliable place to capture mouse button press/release.
if (event.button >= 0) {
KeyPressHandler.trackMouseButton(event.button, event.buttonstate);
}
Minecraft mc = Minecraft.getMinecraft();
if (mc.currentScreen != null)
return;
// Block mouse movement during ability rotation lock.
// Allow clicks (button >= 0) and scroll (dwheel != 0) to pass through.
if (mc.theWorld != null && mc.thePlayer != null
&& ClientAbilityState.shouldLockRotation()
&& (event.dx != 0 || event.dy != 0)
&& event.button == -1 && event.dwheel == 0) {
event.setCanceled(true);
return;
}
// Ability Hotbar: Hold HUD key + scroll wheel to cycle
if (event.dwheel != 0 && KeyPressHandler.isHudKeyHeld()) {
AbilityHotbarComponent comp = (AbilityHotbarComponent) ClientHudManager.getInstance()
.getHudComponents().get(EnumHudComponent.AbilityHotbar);
if (comp != null && comp.hasAnyAbilities()) {
if (event.dwheel > 0) {
comp.onCyclePrev();
} else {
comp.onCycleNext();
}
event.setCanceled(true);
return;
}
}
ArrayList<Integer> removeList = new ArrayList<>();
for (Map.Entry<Integer, Long> entry : disabledButtonTimes.entrySet()) {
if (entry.getValue() > 0) {
@@ -114,6 +150,7 @@ public class ClientEventHandler {
if (ClientHudManager.getInstance().getHudComponents().isEmpty()) {
ClientHudManager.getInstance().registerHud(EnumHudComponent.QuestTracker, new QuestTrackingComponent(Minecraft.getMinecraft()));
ClientHudManager.getInstance().registerHud(EnumHudComponent.QuestCompass, new CompassHudComponent(Minecraft.getMinecraft()));
ClientHudManager.getInstance().registerHud(EnumHudComponent.AbilityHotbar, new AbilityHotbarComponent(Minecraft.getMinecraft()));
}
ClientHudManager.getInstance().renderAllHUDs(event.partialTicks);
+112 -41
View File
@@ -6,8 +6,32 @@ import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import kamkeel.npcs.addon.client.DBCClient;
import kamkeel.npcs.client.command.CommandCNPCDebugger;
import kamkeel.npcs.client.renderer.RenderEnergyBeam;
import kamkeel.npcs.client.renderer.RenderEnergyDisc;
import kamkeel.npcs.client.renderer.RenderEnergyLaser;
import kamkeel.npcs.client.renderer.RenderEnergyOrb;
import kamkeel.npcs.client.renderer.RenderSweeper;
import kamkeel.npcs.client.renderer.RenderZone;
import kamkeel.npcs.client.renderer.RenderEnergyDome;
import kamkeel.npcs.client.renderer.RenderEnergyPanel;
import kamkeel.npcs.client.renderer.EnergyChargePreviewRenderer;
import kamkeel.npcs.client.renderer.RenderEnergyExplosion;
import kamkeel.npcs.client.renderer.RenderEnergySlicer;
import kamkeel.npcs.client.renderer.TelegraphRenderer;
import kamkeel.npcs.client.renderer.lightning.LightningHandler;
import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager;
import kamkeel.npcs.controllers.data.telegraph.TelegraphManager;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityEnergySweeper;
import kamkeel.npcs.entity.EntityAbilityZone;
import kamkeel.npcs.entity.EntityEnergyDome;
import kamkeel.npcs.entity.EntityEnergyPanel;
import kamkeel.npcs.entity.EntityEnergyExplosion;
import kamkeel.npcs.entity.EntityEnergySlicer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.model.ModelBiped;
@@ -30,6 +54,7 @@ import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ReportedException;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.FakePlayer;
@@ -88,12 +113,13 @@ import noppes.npcs.client.gui.global.GuiNPCManageAnimations;
import noppes.npcs.client.gui.global.GuiNPCManageBanks;
import noppes.npcs.client.gui.global.GuiNPCManageDialogs;
import noppes.npcs.client.gui.global.GuiNPCManageEffects;
import noppes.npcs.client.gui.global.GuiNpcManageAbilities;
import noppes.npcs.client.gui.global.GuiNPCManageFactions;
import noppes.npcs.client.gui.global.GuiNPCManageLinked;
import noppes.npcs.client.gui.global.GuiNPCManageQuest;
import noppes.npcs.client.gui.global.GuiNPCManageTags;
import noppes.npcs.client.gui.global.GuiNPCManageTransporters;
import noppes.npcs.client.gui.global.GuiNpcManageAbilities;
import noppes.npcs.client.gui.global.GuiNpcManageAuction;
import noppes.npcs.client.gui.global.GuiNpcManageMagic;
import noppes.npcs.client.gui.global.GuiNpcManageRecipes;
import noppes.npcs.client.gui.global.GuiNpcQuestReward;
@@ -105,15 +131,15 @@ import noppes.npcs.client.gui.mainmenu.GuiNpcAI;
import noppes.npcs.client.gui.mainmenu.GuiNpcAdvanced;
import noppes.npcs.client.gui.mainmenu.GuiNpcDisplay;
import noppes.npcs.client.gui.mainmenu.GuiNpcStats;
import noppes.npcs.client.gui.player.GuiAuctionBidding;
import noppes.npcs.client.gui.player.GuiAuctionListing;
import noppes.npcs.client.gui.player.GuiAuctionSell;
import noppes.npcs.client.gui.player.GuiAuctionTrades;
import noppes.npcs.client.gui.player.GuiBigSign;
import noppes.npcs.client.gui.player.GuiCrate;
import noppes.npcs.client.gui.player.GuiMailbox;
import noppes.npcs.client.gui.player.GuiMailmanWrite;
import noppes.npcs.client.gui.player.GuiNPCBankChest;
import noppes.npcs.client.gui.player.GuiAuctionBidding;
import noppes.npcs.client.gui.player.GuiAuctionTrades;
import noppes.npcs.client.gui.player.GuiAuctionListing;
import noppes.npcs.client.gui.player.GuiAuctionSell;
import noppes.npcs.client.gui.player.GuiNPCTrader;
import noppes.npcs.client.gui.player.GuiNpcAnvil;
import noppes.npcs.client.gui.player.GuiNpcCarpentryBench;
@@ -133,6 +159,8 @@ import noppes.npcs.client.gui.roles.GuiNpcTransporter;
import noppes.npcs.client.gui.script.GuiScriptGlobal;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.gui.util.script.PackageFinder;
import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry;
import noppes.npcs.client.gui.util.script.interpreter.type.ClassIndex;
import noppes.npcs.client.model.ModelNPCGolem;
import noppes.npcs.client.model.ModelNpcCrystal;
import noppes.npcs.client.model.ModelNpcDragon;
@@ -146,17 +174,6 @@ import noppes.npcs.client.renderer.RenderNpcCrystal;
import noppes.npcs.client.renderer.RenderNpcDragon;
import noppes.npcs.client.renderer.RenderNpcSlime;
import noppes.npcs.client.renderer.RenderProjectile;
import kamkeel.npcs.client.renderer.RenderAbilityOrb;
import kamkeel.npcs.client.renderer.RenderAbilityDisc;
import kamkeel.npcs.client.renderer.RenderAbilityLaser;
import kamkeel.npcs.client.renderer.RenderAbilityBeam;
import kamkeel.npcs.client.renderer.RenderAbilitySweeper;
import kamkeel.npcs.client.renderer.lightning.LightningHandler;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import noppes.npcs.client.renderer.blocks.BlockBannerRenderer;
import noppes.npcs.client.renderer.blocks.BlockBarrelRenderer;
import noppes.npcs.client.renderer.blocks.BlockBeamRenderer;
@@ -192,18 +209,22 @@ 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;
import noppes.npcs.config.StringCache;
import noppes.npcs.constants.EnumGuiType;
import noppes.npcs.containers.ContainerAnvilRepair;
import noppes.npcs.containers.ContainerAuctionBidding;
import noppes.npcs.containers.ContainerAuctionListing;
import noppes.npcs.containers.ContainerAuctionSell;
import noppes.npcs.containers.ContainerAuctionTrades;
import noppes.npcs.containers.ContainerCarpentryBench;
import noppes.npcs.containers.ContainerCrate;
import noppes.npcs.containers.ContainerCustomGui;
import noppes.npcs.containers.ContainerMail;
import noppes.npcs.containers.ContainerManageBanks;
import noppes.npcs.containers.ContainerManageAuction;
import noppes.npcs.containers.ContainerManageRecipes;
import noppes.npcs.containers.ContainerNPCBankInterface;
import noppes.npcs.containers.ContainerNPCCompanion;
@@ -211,11 +232,6 @@ import noppes.npcs.containers.ContainerNPCFollower;
import noppes.npcs.containers.ContainerNPCFollowerHire;
import noppes.npcs.containers.ContainerNPCFollowerSetup;
import noppes.npcs.containers.ContainerNPCInv;
import noppes.npcs.containers.ContainerAuction;
import noppes.npcs.containers.ContainerAuctionBidding;
import noppes.npcs.containers.ContainerAuctionTrades;
import noppes.npcs.containers.ContainerAuctionListing;
import noppes.npcs.containers.ContainerAuctionSell;
import noppes.npcs.containers.ContainerNPCTrader;
import noppes.npcs.containers.ContainerNPCTraderSetup;
import noppes.npcs.containers.ContainerNpcItemGiver;
@@ -251,6 +267,9 @@ import java.util.Random;
public class ClientProxy extends CommonProxy {
public static KeyBinding NPCButton;
public static KeyBinding SpecialKey;
public static KeyBinding AbilityHudKey;
public static KeyBinding AbilityNextKey;
public static KeyBinding AbilityPrevKey;
public static final Random RAND = new Random();
public static FontContainer Font;
@@ -265,17 +284,23 @@ public class ClientProxy extends CommonProxy {
RenderingRegistry.registerEntityRenderingHandler(EntityNpcDragon.class, new RenderNpcDragon(new ModelNpcDragon(0.0F), 0.5F));
RenderingRegistry.registerEntityRenderingHandler(EntityNpcSlime.class, new RenderNpcSlime(new ModelNpcSlime(16), new ModelNpcSlime(0), 0.25F));
RenderingRegistry.registerEntityRenderingHandler(EntityProjectile.class, new RenderProjectile());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityOrb.class, new RenderAbilityOrb());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDisc.class, new RenderAbilityDisc());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityLaser.class, new RenderAbilityLaser());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderAbilityBeam());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilitySweeper.class, new RenderAbilitySweeper());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityOrb.class, new RenderEnergyOrb());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDisc.class, new RenderEnergyDisc());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityLaser.class, new RenderEnergyLaser());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderEnergyBeam());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergySweeper.class, new RenderSweeper());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityZone.class, new RenderZone());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergyDome.class, new RenderEnergyDome());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergyPanel.class, new RenderEnergyPanel());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergySlicer.class, new RenderEnergySlicer());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergyExplosion.class, new RenderEnergyExplosion());
RenderingRegistry.registerEntityRenderingHandler(EntityCustomNpc.class, new RenderCustomNpc());
RenderingRegistry.registerEntityRenderingHandler(EntityNPCGolem.class, new RenderNPCHumanMale(
new ModelNPCGolem(0), new ModelNPCGolem(1F), new ModelNPCGolem(0.5F)));
FMLCommonHandler.instance().bus().register(new ClientTickHandler());
FMLCommonHandler.instance().bus().register(new KeyPressHandler());
ClientRegistry.bindTileEntitySpecialRenderer(TileBlockAnvil.class, new BlockCarpentryBenchRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileMailbox.class, new BlockMailboxRenderer());
@@ -321,11 +346,19 @@ public class ClientProxy extends CommonProxy {
}
NPCButton = new KeyBinding("NPC Inventory", Keyboard.KEY_N, "key.categories.customnpc");
SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_B, "key.categories.customnpc");
SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_GRAVE, "key.categories.customnpc");
ClientRegistry.registerKeyBinding(NPCButton);
ClientRegistry.registerKeyBinding(SpecialKey);
AbilityHudKey = new KeyBinding("key.customnpcs.abilityHudKey", Keyboard.KEY_LMENU, "key.categories.customnpc");
ClientRegistry.registerKeyBinding(AbilityHudKey);
AbilityNextKey = new KeyBinding("key.customnpcs.abilityNext", Keyboard.KEY_NONE, "key.categories.customnpc");
AbilityPrevKey = new KeyBinding("key.customnpcs.abilityPrev", Keyboard.KEY_NONE, "key.categories.customnpc");
ClientRegistry.registerKeyBinding(AbilityNextKey);
ClientRegistry.registerKeyBinding(AbilityPrevKey);
new PresetController(CustomNpcs.Dir);
if (ConfigMain.EnableUpdateChecker) {
@@ -337,20 +370,19 @@ public class ClientProxy extends CommonProxy {
ClientTagMapController.Instance = new ClientTagMapController();
MinecraftForge.EVENT_BUS.register(new ClientEventHandler());
// Debug commands
ClientCommandHandler.instance.registerCommand(new CommandCNPCDebugger());
// Telegraph rendering system
TelegraphManager.initClient();
MinecraftForge.EVENT_BUS.register(new TelegraphRenderer());
// Energy charge preview rendering system
EnergyChargePreviewManager.initClient();
MinecraftForge.EVENT_BUS.register(new EnergyChargePreviewRenderer());
// Lightning effect rendering system
MinecraftForge.EVENT_BUS.register(new LightningHandler());
if (ConfigClient.InventoryGuiEnabled) {
MinecraftForge.EVENT_BUS.register(new TabRegistry());
if (TabRegistry.getTabList().isEmpty()) {
TabRegistry.registerTab(new InventoryTabVanilla());
}
TabRegistry.registerTab(new InventoryTabCustomNpc());
}
}
public FakePlayer getCommandPlayer(IWorld world) {
@@ -390,7 +422,8 @@ public class ClientProxy extends CommonProxy {
@Override
public PlayerData getPlayerData(EntityPlayer player) {
if (player.getUniqueID() == Minecraft.getMinecraft().thePlayer.getUniqueID()) {
EntityPlayer local = Minecraft.getMinecraft().thePlayer;
if (local != null && player.getUniqueID().equals(local.getUniqueID())) {
if (ClientCacheHandler.playerData != null) {
if (ClientCacheHandler.playerData.player != player) {
ClientCacheHandler.playerData.player = player;
@@ -486,6 +519,9 @@ public class ClientProxy extends CommonProxy {
else if (gui == EnumGuiType.ManageRecipes)
return new GuiNpcManageRecipes(npc, (ContainerManageRecipes) container);
else if (gui == EnumGuiType.ManageAuction)
return new GuiNpcManageAuction(npc, (ContainerManageAuction) container);
else if (gui == EnumGuiType.ManageDialogs)
return new GuiNPCManageDialogs(npc);
@@ -512,9 +548,7 @@ public class ClientProxy extends CommonProxy {
abilityNpc.width = 0.6f;
}
return new GuiNpcManageAbilities(abilityNpc, npc != null);
}
else if (gui == EnumGuiType.MainMenuGlobal)
} else if (gui == EnumGuiType.MainMenuGlobal)
return new GuiNPCGlobalMainMenu(npc);
else if (gui == EnumGuiType.MainMenuAI)
@@ -816,9 +850,24 @@ public class ClientProxy extends CommonProxy {
return Minecraft.getMinecraft().currentScreen != null;
}
@Override
public void loadComplete() {
// Deferred from load() so TConstruct has registered its own tabs first - registering
// ours before it left the vanilla tab duplicated.
if (ConfigClient.InventoryGuiEnabled) {
MinecraftForge.EVENT_BUS.register(new TabRegistry());
if (TabRegistry.getTabList().isEmpty()) {
TabRegistry.registerTab(new InventoryTabVanilla());
}
TabRegistry.registerTab(new InventoryTabCustomNpc());
}
}
public void buildPackageIndex() {
try {
PackageFinder.init(Thread.currentThread().getContextClassLoader());
ClassIndex.init();
JSTypeRegistry.getInstance().initializeFromResources();
} catch (IOException e) {
}
}
@@ -882,6 +931,28 @@ public class ClientProxy extends CommonProxy {
return Minecraft.getMinecraft().fontRenderer.getStringWidth(text);
}
/**
* Return the width of a string when rendered with the specified font style (bold/italic).
*
* @param text the string to measure
* @param fontStyle combination of {@link java.awt.Font#BOLD} and {@link java.awt.Font#ITALIC},
* or {@link java.awt.Font#PLAIN} for normal style
* @return the width in pixels
*/
public int width(String text, int fontStyle) {
if (useCustomFont)
return textFont.getStringWidth(text, fontStyle);
if (fontStyle == java.awt.Font.PLAIN)
return Minecraft.getMinecraft().fontRenderer.getStringWidth(text);
StringBuilder sb = new StringBuilder();
if ((fontStyle & java.awt.Font.BOLD) != 0)
sb.append('\u00A7').append('l');
if ((fontStyle & java.awt.Font.ITALIC) != 0)
sb.append('\u00A7').append('o');
sb.append(text);
return Minecraft.getMinecraft().fontRenderer.getStringWidth(sb.toString());
}
public FontContainer copy() {
FontContainer font = new FontContainer();
font.textFont = textFont;
@@ -891,7 +962,7 @@ public class ClientProxy extends CommonProxy {
public void drawString(String text, int x, int y, int color) {
if (useCustomFont) {
textFont.renderString(text, x, y, color, true);
// textFont.renderString(text, x, y, color, true);
textFont.renderString(text, x, y, color, false);
} else {
Minecraft.getMinecraft().fontRenderer.drawStringWithShadow(text, x, y, color);
@@ -2,39 +2,34 @@ package noppes.npcs.client;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.relauncher.Side;
import kamkeel.npcs.client.renderer.lightning.LightningBolt;
import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager;
import kamkeel.npcs.controllers.data.telegraph.TelegraphManager;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.player.CheckPlayerValue;
import kamkeel.npcs.network.packets.player.InputDevicePacket;
import kamkeel.npcs.network.packets.player.ScreenSizePacket;
import kamkeel.npcs.network.packets.player.SpecialKeyStatePacket;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ContainerPlayer;
import net.minecraft.world.World;
import noppes.npcs.CustomNpcs;
import noppes.npcs.client.controllers.MusicController;
import noppes.npcs.client.controllers.ScriptSoundController;
import noppes.npcs.client.gui.hud.ClientHudManager;
import noppes.npcs.client.gui.hud.CompassHudComponent;
import noppes.npcs.client.gui.hud.EnumHudComponent;
import noppes.npcs.client.gui.hud.HudComponent;
import noppes.npcs.client.gui.player.inventory.GuiCNPCInventory;
import noppes.npcs.client.renderer.RenderNPCInterface;
import noppes.npcs.constants.EnumRoleType;
import noppes.npcs.constants.MarkType;
import noppes.npcs.CustomNpcs;
import noppes.npcs.controllers.data.MarkData;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.roles.RoleMount;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import tconstruct.client.tabs.InventoryTabCustomNpc;
import java.util.ArrayList;
@@ -45,10 +40,7 @@ public class ClientTickHandler {
private int prevWidth = 0;
private int prevHeight = 0;
private boolean otherContainer = false;
private int buttonPressed = -1;
private long buttonTime = 0L;
private final int[] ignoreKeys = new int[]{157, 29, 54, 42, 184, 56, 220, 219};
private boolean lastSpecialKeyDown = false;
private boolean wasMovementSuppressed = false;
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onClientTick(TickEvent.ClientTickEvent event) {
@@ -56,20 +48,49 @@ public class ClientTickHandler {
if ((this.prevWorld == null || mc.theWorld == null) && this.prevWorld != mc.theWorld) {
if (mc.theWorld == null) {
ClientCacheHandler.clearCache();
ClientAbilityState.reset();
if (EnergyChargePreviewManager.ClientInstance != null) {
EnergyChargePreviewManager.ClientInstance.clear();
}
}
this.prevWorld = mc.theWorld;
}
if (event.phase == Phase.START) {
EntityPlayer player = mc.thePlayer;
if (player != null) {
boolean specialKeyDown = ClientProxy.SpecialKey != null && Keyboard.isKeyDown(ClientProxy.SpecialKey.getKeyCode());
if (specialKeyDown != lastSpecialKeyDown) {
PlayerData data = CustomNpcs.proxy.getPlayerData(player);
if (data != null) {
data.setSpecialKeyDown(specialKeyDown);
}
SpecialKeyStatePacket.send(specialKeyDown);
lastSpecialKeyDown = specialKeyDown;
boolean shouldSuppress = ClientAbilityState.shouldSuppressMovementInput();
boolean suppressInput = mc.currentScreen == null && shouldSuppress;
if (!suppressInput && wasMovementSuppressed) {
syncMovementKeyStates(mc);
}
wasMovementSuppressed = suppressInput;
// Suppress player keyboard input during ability-controlled phases.
// Only suppress key binds when no GUI screen is open (screens already capture input).
if (suppressInput) {
// Unpress movement keybinds at the source BEFORE updatePlayerMoveState() reads them.
KeyBinding.setKeyBindState(mc.gameSettings.keyBindForward.getKeyCode(), false);
KeyBinding.setKeyBindState(mc.gameSettings.keyBindBack.getKeyCode(), false);
KeyBinding.setKeyBindState(mc.gameSettings.keyBindLeft.getKeyCode(), false);
KeyBinding.setKeyBindState(mc.gameSettings.keyBindRight.getKeyCode(), false);
KeyBinding.setKeyBindState(mc.gameSettings.keyBindJump.getKeyCode(), false);
KeyBinding.setKeyBindState(mc.gameSettings.keyBindSneak.getKeyCode(), false);
KeyBinding.setKeyBindState(mc.gameSettings.keyBindSprint.getKeyCode(), false);
}
// Zero movement input regardless of GUI state — the ability lock must
// hold the player in place even when chat or other screens are open.
if (shouldSuppress) {
mc.thePlayer.movementInput.moveForward = 0;
mc.thePlayer.movementInput.moveStrafe = 0;
mc.thePlayer.movementInput.jump = false;
mc.thePlayer.movementInput.sneak = false;
}
if (ClientAbilityState.shouldLockRotation()) {
mc.thePlayer.rotationYaw = ClientAbilityState.lockedYaw;
mc.thePlayer.rotationPitch = ClientAbilityState.lockedPitch;
mc.thePlayer.prevRotationYaw = ClientAbilityState.lockedYaw;
mc.thePlayer.prevRotationPitch = ClientAbilityState.lockedPitch;
}
if (player.ridingEntity instanceof EntityNPCInterface) {
@@ -84,9 +105,63 @@ public class ClientTickHandler {
}
}
if (event.phase == Phase.END) {
if (mc.thePlayer != null && mc.theWorld != null && !mc.isGamePaused() && ClientEventHandler.hasOverlays(mc.thePlayer)) {
renderCNPCPlayer.itemRenderer.updateEquippedItem();
if (mc.thePlayer != null) {
// Re-enforce ability locks AFTER entity update.
// EntityPlayerSP.onLivingUpdate() calls updatePlayerMoveState() which
// overwrites Phase.START suppression with actual keyboard state, causing
// client-predicted movement that fights the server lock. Undo it here.
// Motion zeroing runs regardless of GUI state so the player doesn't fall
// when opening chat or other screens during an ability lock.
if (ClientAbilityState.shouldSuppressMovementInput()) {
mc.thePlayer.movementInput.moveForward = 0;
mc.thePlayer.movementInput.moveStrafe = 0;
mc.thePlayer.movementInput.jump = false;
mc.thePlayer.movementInput.sneak = false;
// Zero all motion — position lock holds the player in place (server is authoritative)
if (!ClientAbilityState.hasAbilityMovement) {
mc.thePlayer.motionX = 0;
mc.thePlayer.motionZ = 0;
}
// Zero vertical motion: grounded players can't jump, flying players are frozen in air
if ((ClientAbilityState.movementLocked || ClientAbilityState.positionLocked)
&& !ClientAbilityState.hasAbilityMovement) {
if (ClientAbilityState.wasFlyingAtLock) {
mc.thePlayer.motionY = 0;
} else {
mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0);
}
}
}
if (ClientAbilityState.shouldLockRotation()) {
mc.thePlayer.rotationYaw = ClientAbilityState.lockedYaw;
mc.thePlayer.rotationPitch = ClientAbilityState.lockedPitch;
mc.thePlayer.prevRotationYaw = ClientAbilityState.lockedYaw;
mc.thePlayer.prevRotationPitch = ClientAbilityState.lockedPitch;
mc.thePlayer.rotationYawHead = ClientAbilityState.lockedYaw;
}
if (mc.theWorld != null && !mc.isGamePaused() && ClientEventHandler.hasOverlays(mc.thePlayer)) {
renderCNPCPlayer.itemRenderer.updateEquippedItem();
}
}
// Tick telegraph manager AFTER entity updates so telegraph positions
// match entity interpolation (Phase.END runs after world tick)
if (TelegraphManager.ClientInstance != null) {
TelegraphManager.ClientInstance.tick(mc.theWorld);
}
// Tick packet-driven energy charge previews
if (EnergyChargePreviewManager.ClientInstance != null) {
EnergyChargePreviewManager.ClientInstance.tick(mc.theWorld);
}
// Update lightning bolts for ability effects
LightningBolt.updateAll();
return;
}
if (mc.thePlayer != null && mc.thePlayer.openContainer instanceof ContainerPlayer) {
@@ -112,13 +187,6 @@ public class ClientTickHandler {
MusicController.Instance.onUpdate();
ScriptSoundController.Instance.onUpdate();
// Tick telegraph manager for ability warnings
if (TelegraphManager.ClientInstance != null) {
TelegraphManager.ClientInstance.tick(mc.theWorld);
}
// Update lightning bolts for ability effects
LightningBolt.updateAll();
if (Minecraft.getMinecraft().thePlayer != null && (prevWidth != mc.displayWidth || prevHeight != mc.displayHeight)) {
prevWidth = mc.displayWidth;
prevHeight = mc.displayHeight;
@@ -133,44 +201,52 @@ public class ClientTickHandler {
}
}
@SubscribeEvent
public void onMouse(InputEvent.MouseInputEvent event) {
if (Mouse.getEventButton() == -1 && Mouse.getEventDWheel() == 0)
/**
* Enforce ability lock motion constraints right before entity update.
* The Phase.END zeroing in onClientTick can be overwritten by other mods'
* ClientTickEvent Phase.START handlers (e.g. flight mods re-applying gravity).
* PlayerTickEvent fires after all ClientTickEvent handlers but before
* player.onUpdate(), making this the definitive point to enforce motion locks.
*/
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerTick(TickEvent.PlayerTickEvent event) {
if (event.phase != Phase.START || event.side != Side.CLIENT)
return;
InputDevicePacket.sendMouse(Mouse.getEventButton(), Mouse.getEventDWheel(), Mouse.isButtonDown(Mouse.getEventButton()));
}
Minecraft mc = Minecraft.getMinecraft();
if (mc.thePlayer == null)
return;
@SubscribeEvent
public void onKey(InputEvent.KeyInputEvent event) {
if (ClientProxy.NPCButton.isPressed()) {
Minecraft mc = Minecraft.getMinecraft();
if (mc.currentScreen == null) {
InventoryTabCustomNpc.tabHelper();
} else if (mc.currentScreen instanceof GuiCNPCInventory)
mc.setIngameFocus();
if (!ClientAbilityState.shouldSuppressMovementInput())
return;
if (!ClientAbilityState.hasAbilityMovement) {
mc.thePlayer.motionX = 0;
mc.thePlayer.motionZ = 0;
}
if (!Keyboard.isRepeatEvent()) {
int key = Keyboard.getEventKey();
boolean keyDown = Keyboard.isKeyDown(key);
InputDevicePacket.sendKeyboard(key, keyDown);
}
}
private boolean isIgnoredKey(int key) {
int[] var2 = this.ignoreKeys;
int var3 = var2.length;
for (int var4 = 0; var4 < var3; ++var4) {
int i = var2[var4];
if (i == key) {
return true;
if ((ClientAbilityState.movementLocked || ClientAbilityState.positionLocked)
&& !ClientAbilityState.hasAbilityMovement) {
if (ClientAbilityState.wasFlyingAtLock) {
mc.thePlayer.motionY = 0;
} else {
mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0);
}
}
}
return false;
private void syncMovementKeyStates(Minecraft mc) {
syncKeyBindingState(mc.gameSettings.keyBindForward);
syncKeyBindingState(mc.gameSettings.keyBindBack);
syncKeyBindingState(mc.gameSettings.keyBindLeft);
syncKeyBindingState(mc.gameSettings.keyBindRight);
syncKeyBindingState(mc.gameSettings.keyBindJump);
syncKeyBindingState(mc.gameSettings.keyBindSneak);
syncKeyBindingState(mc.gameSettings.keyBindSprint);
}
private void syncKeyBindingState(KeyBinding keyBinding) {
KeyBinding.setKeyBindState(keyBinding.getKeyCode(), KeyPressHandler.isKeyBindDown(keyBinding));
}
private final int SCAN_RANGE = 128;
@@ -9,12 +9,13 @@ import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import noppes.npcs.CustomNpcs;
import noppes.npcs.LogWriter;
import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry;
import noppes.npcs.client.gui.util.script.interpreter.token.ScriptColorScheme;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.io.*;
public class CustomNpcResourceListener implements
IResourceManagerReloadListener {
@@ -29,7 +30,15 @@ public class CustomNpcResourceListener implements
SimpleReloadableResourceManager simplemanager = (SimpleReloadableResourceManager) var1;
FolderResourcePack pack = new FolderResourcePack(CustomNpcs.Dir);
LogWriter.info("[ResourceListener] Adding FolderResourcePack (as fallback): " + CustomNpcs.Dir.getAbsolutePath());
simplemanager.reloadResourcePack(pack);
ScriptColorScheme.reloadColorScheme(var1);
// Reload scripting .d.ts files
JSTypeRegistry registry = JSTypeRegistry.getInstance();
registry.clear();
registry.initializeFromResources();
try {
DefaultTextColor = Integer.parseInt(StatCollector.translateToLocal("customnpcs.defaultTextColor"), 16);
@@ -8,6 +8,7 @@ import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.config.ConfigClient;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -101,18 +102,10 @@ public class ImageDownloadAlt extends SimpleTexture {
HttpURLConnection connection = null;
try {
URL url = new URL(ImageDownloadAlt.this.imageUrl);
connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy());
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setRequestProperty("Content-Type", "image/png");
connection.setRequestProperty("Expect", "100-continue");
//connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// Modify Accept Redirect
if (isImgurLink(url)) {
connection.setRequestProperty("Accept", "*/*");
}
// Adding a config so people can switch back if needed.
// TODO: Remove config option if improved works better
connection = ConfigClient.ImprovedImageDownloadConnection ? setupConnectionImproved(url) : setupConnectionOld(url);
connection.connect();
@@ -152,6 +145,44 @@ public class ImageDownloadAlt extends SimpleTexture {
this.imageThread.start();
}
private HttpURLConnection setupConnectionOld(URL url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy());
// setups stuff which basically tells the browser if this a get or post request
connection.setDoInput(true);
connection.setDoOutput(false);
// ??? I believe these are used to tell the receiver what you are sending to them
// Not what you expect to receive from them.
connection.setRequestProperty("Content-Type", "image/png");
connection.setRequestProperty("Expect", "100-continue");
//connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// Modify Accept Redirect
if (isImgurLink(url)) {
connection.setRequestProperty("Accept", "*/*");
}
return connection;
}
private HttpURLConnection setupConnectionImproved(URL url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy());
connection.setRequestMethod("GET");
// Basically redundant because I set it as a GET request?
// Better safe than sorry ig.
connection.setDoInput(true);
connection.setDoOutput(false);
// Random ass user agent I grabbed from my snooping on imgur
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:147.0) Gecko/20100101 Firefox/147.0");
// I tell the server what I want to receive.
// TODO: Should this just accept PNGs?
connection.setRequestProperty("Accept", "image/png,image/*");
return connection;
}
// Check if the URL is an Imgur link
private static boolean isImgurLink(URL url) {
@@ -0,0 +1,223 @@
package noppes.npcs.client;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import kamkeel.npcs.network.packets.player.InputDevicePacket;
import kamkeel.npcs.network.packets.player.SpecialKeyStatePacket;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import noppes.npcs.CustomNpcs;
import noppes.npcs.client.gui.hud.ClientHudManager;
import noppes.npcs.client.gui.hud.EnumHudComponent;
import noppes.npcs.client.gui.hud.ability.AbilityHotbarComponent;
import noppes.npcs.client.gui.player.inventory.GuiCNPCInventory;
import noppes.npcs.controllers.data.PlayerData;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import tconstruct.client.tabs.InventoryTabCustomNpc;
/**
* Centralized input handler for CustomNPC+ keybindings.
* Handles both keyboard and mouse input events so keybinds work
* regardless of whether they're bound to a key or mouse button.
* <p>
* All keybind state queries (pressed, held, released) should go through
* this class to avoid crashes with mouse-bound keys.
* <p>
* Mouse button states are tracked from MouseEvent (Forge bus) via
* {@link #trackMouseButton}, because canceled MouseEvents cause Minecraft
* to skip FML's MouseInputEvent entirely. This is the only reliable source.
*/
public class KeyPressHandler {
// ── Mouse Button Tracking ────────────────────────────────────────────
// Tracked from MouseEvent (Forge bus, via ClientEventHandler.onMouse)
// which fires BEFORE cancellation can skip MouseInputEvent.
private static final boolean[] mouseButtonsDown = new boolean[16];
// ── Tracked Held States ──────────────────────────────────────────────
private static boolean specialKeyHeld = false;
private static boolean hudKeyHeld = false;
// ── Event Handlers ──────────────────────────────────────────────────
@SubscribeEvent
public void onKeyPress(InputEvent.KeyInputEvent event) {
Minecraft mc = Minecraft.getMinecraft();
updateHeldStates(mc);
handleNPCButton(mc);
handleAbilityCycleKeys(mc);
if (!Keyboard.isRepeatEvent()) {
int key = Keyboard.getEventKey();
boolean keyDown = Keyboard.isKeyDown(key);
// Block movement keys during ability lock (only when no GUI is open).
if (mc.theWorld != null && mc.currentScreen == null && keyDown
&& ClientAbilityState.shouldSuppressMovementInput() && isMovementKey(key)) {
KeyBinding.setKeyBindState(key, false);
return;
}
InputDevicePacket.sendKeyboard(key, keyDown);
}
}
@SubscribeEvent
public void onMousePress(InputEvent.MouseInputEvent event) {
Minecraft mc = Minecraft.getMinecraft();
// Button state already tracked by trackMouseButton() from MouseEvent.
// Just update held states and handle keybind actions.
updateHeldStates(mc);
handleNPCButton(mc);
handleAbilityCycleKeys(mc);
int button = Mouse.getEventButton();
if (button == -1 && Mouse.getEventDWheel() == 0)
return;
InputDevicePacket.sendMouse(button, Mouse.getEventDWheel(),
button >= 0 && Mouse.getEventButtonState());
}
/**
* Per-tick safety net: sync tracked mouse button states with hardware
* in case an event was missed (e.g. window focus loss).
*/
@SubscribeEvent
public void onClientTick(TickEvent.ClientTickEvent event) {
if (event.phase != TickEvent.Phase.START) return;
// Correct any stuck mouse buttons from missed release events
for (int i = 0; i < mouseButtonsDown.length; i++) {
if (mouseButtonsDown[i] && i < Mouse.getButtonCount() && !Mouse.isButtonDown(i)) {
mouseButtonsDown[i] = false;
}
}
updateHeldStates(Minecraft.getMinecraft());
}
// ── Mouse Button Tracking (called from Forge MouseEvent) ─────────────
/**
* Called from {@code ClientEventHandler.onMouse(MouseEvent)} at the very
* start, BEFORE any cancellation logic. This is the primary source of
* mouse button state because canceled MouseEvents cause Minecraft to
* skip {@code FMLCommonHandler.fireMouseInput()} entirely, so
* MouseInputEvent never fires for those events.
*/
public static void trackMouseButton(int button, boolean down) {
if (button >= 0 && button < mouseButtonsDown.length) {
mouseButtonsDown[button] = down;
}
updateHeldStates(Minecraft.getMinecraft());
}
// ── State Updates ────────────────────────────────────────────────────
/**
* Refresh all tracked held states.
* Called on every input event and every tick.
*/
private static void updateHeldStates(Minecraft mc) {
boolean noScreen = mc.currentScreen == null;
// ── SpecialKey (edge-detected, sends packet on change) ──
boolean specialDown = noScreen && isKeyBindDown(ClientProxy.SpecialKey);
if (specialDown != specialKeyHeld) {
specialKeyHeld = specialDown;
if (mc.thePlayer != null) {
PlayerData data = CustomNpcs.proxy.getPlayerData(mc.thePlayer);
if (data != null) {
data.setSpecialKeyDown(specialDown);
}
SpecialKeyStatePacket.send(specialDown);
}
}
// ── AbilityHudKey ──
hudKeyHeld = noScreen && isKeyBindDown(ClientProxy.AbilityHudKey);
}
// ── Keybind Actions ─────────────────────────────────────────────────
private static void handleNPCButton(Minecraft mc) {
if (ClientProxy.NPCButton == null) return;
if (ClientProxy.NPCButton.isPressed()) {
if (mc.currentScreen == null) {
InventoryTabCustomNpc.tabHelper();
} else if (mc.currentScreen instanceof GuiCNPCInventory) {
mc.setIngameFocus();
}
}
}
private static void handleAbilityCycleKeys(Minecraft mc) {
if (mc.currentScreen != null || mc.theWorld == null) return;
AbilityHotbarComponent comp = (AbilityHotbarComponent) ClientHudManager.getInstance()
.getHudComponents().get(EnumHudComponent.AbilityHotbar);
if (comp == null || !comp.hasAnyAbilities()) return;
if (ClientProxy.AbilityNextKey != null && ClientProxy.AbilityNextKey.isPressed()) {
comp.onCycleNext();
}
if (ClientProxy.AbilityPrevKey != null && ClientProxy.AbilityPrevKey.isPressed()) {
comp.onCyclePrev();
}
}
// ── Public State Queries ─────────────────────────────────────────────
/**
* Whether the SpecialKey is currently held down.
*/
public static boolean isSpecialKeyHeld() {
return specialKeyHeld;
}
/**
* Whether the AbilityHudKey is currently held down.
*/
public static boolean isHudKeyHeld() {
return hudKeyHeld;
}
/**
* Check if a KeyBinding is currently held down.
* Works for both keyboard keys (positive codes) and mouse buttons (negative codes).
* <p>
* Mouse buttons use event-tracked state (from MouseEvent via trackMouseButton)
* so the result is accurate even when called during keyboard event processing.
*/
public static boolean isKeyBindDown(KeyBinding keyBinding) {
if (keyBinding == null) return false;
int keyCode = keyBinding.getKeyCode();
if (keyCode == 0) return false;
if (keyCode < 0) {
int mouseButton = keyCode + 100;
return mouseButton >= 0 && mouseButton < mouseButtonsDown.length
&& mouseButtonsDown[mouseButton];
}
return keyCode < Keyboard.getKeyCount() && Keyboard.isKeyDown(keyCode);
}
// ── Internal Helpers ────────────────────────────────────────────────
private static boolean isMovementKey(int keyCode) {
Minecraft mc = Minecraft.getMinecraft();
return keyCode == mc.gameSettings.keyBindForward.getKeyCode()
|| keyCode == mc.gameSettings.keyBindBack.getKeyCode()
|| keyCode == mc.gameSettings.keyBindLeft.getKeyCode()
|| keyCode == mc.gameSettings.keyBindRight.getKeyCode()
|| keyCode == mc.gameSettings.keyBindJump.getKeyCode()
|| keyCode == mc.gameSettings.keyBindSneak.getKeyCode()
|| keyCode == mc.gameSettings.keyBindSprint.getKeyCode();
}
}
@@ -0,0 +1,64 @@
package noppes.npcs.client;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.data.profile.Profile;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.config.ConfigMain;
import java.util.HashMap;
import java.util.Map;
public class ProfileClientConfig {
private static volatile Map<Integer, Long> sharedQuestTimestamps = new HashMap<>();
public static void readFromNBT(NBTTagCompound compound) {
if (compound == null) return;
Map<Integer, Long> timestamps = new HashMap<>();
if (compound.hasKey("SharedQuestTimestamps")) {
NBTTagList list = compound.getTagList("SharedQuestTimestamps", 10);
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound entry = list.getCompoundTagAt(i);
timestamps.put(entry.getInteger("Quest"), entry.getLong("Date"));
}
}
sharedQuestTimestamps = timestamps;
}
public static void reset() {
sharedQuestTimestamps = new HashMap<>();
}
/**
* Whether profiles are enabled, checking the correct source for each side.
*/
public static boolean isProfilesEnabled() {
if (ProfileController.Instance != null)
return ConfigMain.ProfilesEnabled;
return ClientCacheHandler.allowProfiles;
}
/**
* Check if a quest has a shared timestamp, resolving from server or client cache.
*/
public static boolean hasSharedQuest(EntityPlayer player, int questId) {
if (ProfileController.Instance != null) {
Profile profile = ProfileController.Instance.getProfile(player);
return profile != null && profile.sharedQuestTimestamps.containsKey(questId);
}
return sharedQuestTimestamps.containsKey(questId);
}
/**
* Get the shared quest timestamp, resolving from server or client cache.
*/
public static Long getSharedQuestTimestamp(EntityPlayer player, int questId) {
if (ProfileController.Instance != null) {
Profile profile = ProfileController.Instance.getProfile(player);
return profile != null ? profile.sharedQuestTimestamps.get(questId) : null;
}
return sharedQuestTimestamps.get(questId);
}
}
@@ -7,7 +7,7 @@ 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.
*
* <p>
* IMPORTANT: This class is CLIENT-ONLY. Server-side NBT writing is done in
* ScriptConfigSync to avoid @SideOnly crashes on dedicated servers.
*/
@@ -46,16 +46,44 @@ public class ScriptClientConfig {
}
// 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; }
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; }
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;
}
}
@@ -84,6 +84,10 @@ public class CustomFX extends EntityFX {
this.imageData = ClientCacheHandler.getImageData(this.directory);
}
public void setMaxAge(int age) {
this.particleMaxAge = age;
}
public static CustomFX fromScriptedParticle(ScriptParticle particle, World worldObj, Entity entity) {
EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer;
if (entity == player) {
@@ -0,0 +1,65 @@
package noppes.npcs.client.fx;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.world.World;
/**
* Simple particle for zone visual effects (Trap/Hazard styles).
* Uses vanilla particle atlas with color tinting. Fades out over lifetime.
*/
@SideOnly(Side.CLIENT)
public class ZoneParticleFX extends EntityFX {
private final float startAlpha;
private final boolean glow;
public ZoneParticleFX(World world, double x, double y, double z,
double motionX, double motionY, double motionZ,
float r, float g, float b, float alpha,
float scale, int maxAge, float gravity, boolean glow) {
super(world, x, y, z, 0, 0, 0);
this.motionX = motionX;
this.motionY = motionY;
this.motionZ = motionZ;
this.particleRed = r;
this.particleGreen = g;
this.particleBlue = b;
this.particleAlpha = alpha;
this.startAlpha = alpha;
this.particleScale = scale;
this.particleMaxAge = maxAge;
this.particleGravity = gravity;
this.glow = glow;
this.noClip = true;
this.setParticleTextureIndex(0);
}
@Override
public int getBrightnessForRender(float partialTick) {
return glow ? 0xF000F0 : super.getBrightnessForRender(partialTick);
}
@Override
public void onUpdate() {
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
if (this.particleAge++ >= this.particleMaxAge) {
this.setDead();
return;
}
// Linear fade out
float lifeRatio = (float) this.particleAge / (float) this.particleMaxAge;
this.particleAlpha = this.startAlpha * (1.0f - lifeRatio);
// Movement
this.motionY -= 0.04D * (double) this.particleGravity;
this.posX += this.motionX;
this.posY += this.motionY;
this.posZ += this.motionZ;
}
}
@@ -74,10 +74,10 @@ public class GuiNpcMobSpawnerFullscreen extends GuiDirectory implements IGuiData
this.posZ = posZ;
// Configure GuiDirectory layout percentages
leftPanelPercent = 0.15f;
leftPanelPercent = 0.15f;
rightPanelPercent = 0.08f;
minLeftPanelW = 120;
minRightPanelW = 62;
minLeftPanelW = 120;
minRightPanelW = 62;
PacketClient.sendClient(new CloneAllTagsPacket());
if (GuiNpcMobSpawner.showingClones == 2) {
@@ -199,7 +199,7 @@ public class GuiNpcMobSpawnerFullscreen extends GuiDirectory implements IGuiData
navScroll.setSelected(getNavSelection());
navScroll.scrollY = Math.min(savedNavScroll, Math.max(0, navScroll.maxScrollY));
// Phase 2: color nav items orange (selectable) or red (current location, not selectable)
// Phase 2: color nav items orange (selectable) or red (current location)
if (movePhase == 2) {
String currentNav = getNavSelection();
for (String name : navNames) {
@@ -8,22 +8,26 @@ import net.minecraft.nbt.NBTTagDouble;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.client.controllers.ClientCloneController;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuSideButton;
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.IGuiData;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.data.CloneFolder;
import java.util.ArrayList;
import java.util.List;
public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiData {
public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiData, ICustomScrollListener {
private GuiCustomScroll scroll;
private GuiCustomScroll navScroll;
private List<String> list;
private List<String> navList = new ArrayList<String>();
private static String search = "";
public int activeTab = 1;
public String activeFolder = null;
public boolean isServer = false;
public GuiNpcMobSpawnerSelector() {
@@ -50,38 +54,62 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
addButton(new GuiNpcButton(0, guiLeft + 171, guiTop + 80, 80, 20, "gui.done"));
addButton(new GuiNpcButton(1, guiLeft + 171, guiTop + 103, 80, 20, "gui.cancel"));
addSideButton(new GuiMenuSideButton(21, guiLeft - 90, this.guiTop + 2, 90, 22, "1"));
addSideButton(new GuiMenuSideButton(22, guiLeft - 90, this.guiTop + 23, 90, 22, "2"));
addSideButton(new GuiMenuSideButton(23, guiLeft - 90, this.guiTop + 44, 90, 22, "3"));
addSideButton(new GuiMenuSideButton(24, guiLeft - 90, this.guiTop + 65, 90, 22, "4"));
addSideButton(new GuiMenuSideButton(25, guiLeft - 90, this.guiTop + 86, 90, 22, "5"));
addSideButton(new GuiMenuSideButton(26, guiLeft - 45, this.guiTop + 107, 45, 22, "6"));
addSideButton(new GuiMenuSideButton(27, guiLeft - 90, this.guiTop + 107, 45, 22, "7"));
addSideButton(new GuiMenuSideButton(28, guiLeft - 45, this.guiTop + 128, 45, 22, "8"));
addSideButton(new GuiMenuSideButton(29, guiLeft - 90, this.guiTop + 128, 45, 22, "9"));
addSideButton(new GuiMenuSideButton(30, guiLeft - 45, this.guiTop + 149, 45, 22, "10"));
addSideButton(new GuiMenuSideButton(31, guiLeft - 90, this.guiTop + 149, 45, 22, "11"));
addSideButton(new GuiMenuSideButton(32, guiLeft - 45, this.guiTop + 170, 45, 22, "12"));
addSideButton(new GuiMenuSideButton(33, guiLeft - 90, this.guiTop + 170, 45, 22, "13"));
addSideButton(new GuiMenuSideButton(34, guiLeft - 45, this.guiTop + 191, 45, 22, "14"));
addSideButton(new GuiMenuSideButton(35, guiLeft - 90, this.guiTop + 191, 45, 22, "15"));
// Navigation scroll (tabs + folders) replacing hardcoded side buttons
buildNavList();
if (navScroll == null) {
navScroll = new GuiCustomScroll(this, 1);
} else {
navScroll.clear();
}
navScroll.setSize(90, 210);
navScroll.guiLeft = guiLeft - 94;
navScroll.guiTop = guiTop + 2;
navScroll.setList(navList);
navScroll.setSelected(getNavSelection());
addScroll(navScroll);
getSideButton(20 + activeTab).active = true;
showClones();
}
private void buildNavList() {
navList.clear();
for (int i = 1; i <= 15; i++) {
navList.add("Tab " + i);
}
if (ClientCloneController.Instance != null) {
for (CloneFolder folder : ClientCloneController.Instance.getFolderList()) {
navList.add(folder.name);
}
}
}
private String getNavSelection() {
if (activeFolder != null) return activeFolder;
if (activeTab >= 1 && activeTab <= 15) return "Tab " + activeTab;
return "Tab 1";
}
public String getSelected() {
return scroll.getSelected();
}
private void showClones() {
if (isServer) {
PacketClient.sendClient(new CloneListPacket(activeTab));
if (activeFolder != null) {
PacketClient.sendClient(new CloneListPacket(activeFolder));
} else {
PacketClient.sendClient(new CloneListPacket(activeTab));
}
return;
}
this.list = new ArrayList<String>(ClientCloneController.Instance.getClones(activeTab));
if (activeFolder != null && ClientCloneController.Instance != null) {
this.list = new ArrayList<String>(ClientCloneController.Instance.getClones(activeFolder));
} else if (ClientCloneController.Instance != null) {
this.list = new ArrayList<String>(ClientCloneController.Instance.getClones(activeTab));
} else {
this.list = new ArrayList<String>();
}
scroll.setList(getSearchList());
}
@@ -95,6 +123,7 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
}
private List<String> getSearchList() {
if (list == null) list = new ArrayList<String>();
if (search.isEmpty())
return new ArrayList<String>(list);
List<String> list = new ArrayList<String>();
@@ -110,8 +139,15 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
if (sel == null)
return null;
NBTTagCompound compound = ClientCloneController.Instance.getCloneData(player, sel, activeTab);
compound.setString("ClonedName", sel);
NBTTagCompound compound;
if (activeFolder != null && ClientCloneController.Instance != null) {
compound = ClientCloneController.Instance.getCloneData(player, sel, activeFolder);
} else {
compound = ClientCloneController.Instance.getCloneData(player, sel, activeTab);
}
if (compound != null) {
compound.setString("ClonedName", sel);
}
return compound;
}
@@ -124,9 +160,28 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
scroll.clear();
close();
}
if (id > 20) {
activeTab = id - 20;
initGui();
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 1) {
String selected = navScroll.getSelected();
if (selected == null) return;
if (selected.startsWith("Tab ")) {
try {
int tabNum = Integer.parseInt(selected.substring(4));
if (tabNum >= 1 && tabNum <= 15) {
activeTab = tabNum;
activeFolder = null;
}
} catch (NumberFormatException ignored) {
}
} else {
activeFolder = selected;
activeTab = -1;
}
showClones();
}
}
@@ -28,7 +28,7 @@ public class GuiNpcPather extends GuiNPCInterface implements IGuiData {
drawDefaultBackground = false;
xSize = 176;
title = "Npc Pather";
setBackground("smallbg.png");
setBackground("menubg.png");
ai = npc.ais;
PacketClient.sendClient(new MovingPathGetPacket());
}
@@ -2,13 +2,15 @@ package noppes.npcs.client.gui;
import kamkeel.npcs.network.packets.request.script.NPCScriptPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.StatCollector;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.util.SubGuiAPISelect;
import noppes.npcs.client.gui.util.SubGuiConfirmLink;
import noppes.npcs.controllers.APIRegistry;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
@@ -16,6 +18,8 @@ import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextArea;
import noppes.npcs.client.gui.util.GuiScriptTextArea;
import noppes.npcs.client.gui.util.script.interpreter.ScriptTextContainer;
import noppes.npcs.constants.EnumScriptType;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
@@ -88,18 +92,25 @@ public class GuiScript extends GuiScriptInterface {
super.initGui();
this.guiTop += 10;
// ==================== TOP BUTTONS (hidden in fullscreen) ====================
if (!isFullscreen) {
GuiMenuTopButton top;
addTopButton(top = new GuiMenuTopButton(13, guiLeft + 4, guiTop - 17, "script.scripts"));
addTopButton(new GuiMenuTopButton(16, guiLeft + (xSize - 102), guiTop - 17, "eventscript.eventScripts"));
addTopButton(new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X"));
top.active = showScript;
addTopButton(top = new GuiMenuTopButton(14, top, "gui.settings"));
top.active = !showScript;
addTopButton(new GuiMenuTopButton(15, top, "gui.website"));
if (isFullscreen) {
FullscreenConfig.paddingTop = 30;
}
// ==================== TOP BUTTONS ====================
boolean isFullscreenView = isFullscreen && showScript;
int menuX = isFullscreenView ? FullscreenConfig.paddingLeft : guiLeft + 4;
int menuY = isFullscreenView ? FullscreenConfig.paddingTop - 20 : guiTop - 17;
int rightX = isFullscreenView ? width - FullscreenConfig.paddingRight : guiLeft + xSize;
GuiMenuTopButton top;
addTopButton(top = new GuiMenuTopButton(13, menuX, menuY, "script.scripts"));
addTopButton(new GuiMenuTopButton(16, rightX - 102, menuY, "eventscript.eventScripts"));
addTopButton(new GuiMenuTopButton(17, rightX - 22, menuY, "X"));
top.active = showScript;
addTopButton(top = new GuiMenuTopButton(14, top, "gui.settings"));
top.active = !showScript;
addTopButton(new GuiMenuTopButton(15, top, "gui.api"));
if (showScript) {
initScriptView();
} else {
@@ -158,8 +169,14 @@ public class GuiScript extends GuiScriptInterface {
container == null ? "" : container.script);
}
activeArea.setLanguage(script.getLanguage());
// Use the container's language for syntax highlighting, fall back to handler default
String language = (container != null) ? container.getLanguage() : script.getLanguage();
activeArea.setLanguage(language);
activeArea.setScriptContext(getScriptContext());
// Set editor globals based on the active NPC hook
String hookName = EnumScriptType.values()[activeTab].function;
applyEditorGlobals(activeArea, hookName);
// Setup fullscreen key binding
GuiScriptTextArea.KEYS.FULLSCREEN.setTask(e -> {
@@ -182,6 +199,14 @@ public class GuiScript extends GuiScriptInterface {
addButton(new GuiNpcButton(100, guiLeft + 315, guiTop + 25, 50, 20, "gui.copy"));
addButton(new GuiNpcButton(107, guiLeft + 315, guiTop + 70, 80, 20, "script.loadscript"));
// Disable all buttons until server data arrives
if (!serverDataReceived) {
for (int btnId : new int[]{100, 101, 102, 107}) {
GuiNpcButton btn = getButton(btnId);
if (btn != null) btn.enabled = false;
}
}
GuiCustomScroll scroll = new GuiCustomScroll(this, 0).setUnselectable();
scroll.setSize(100, 120);
scroll.guiLeft = guiLeft + 315;
@@ -211,11 +236,10 @@ public class GuiScript extends GuiScriptInterface {
addButton(new GuiNpcButton(105, guiLeft + 60, guiTop + 4, 80, 20,
consoleOptions.toArray(new String[0]), activeConsole));
addLabel(new GuiNpcLabel(1, "script.language", guiLeft + 232, guiTop + 30));
addLabel(new GuiNpcLabel(1, "script.default", guiLeft + 232, guiTop + 30));
List<String> languageOptions = getLanguageOptions();
addButton(new GuiNpcButton(103, guiLeft + 294, guiTop + 25, 80, 20,
languageOptions.toArray(new String[0]), getLanguageIndex(languageOptions)));
getButton(103).enabled = languageOptions.size() > 0;
addLabel(new GuiNpcLabel(2, "gui.enabled", guiLeft + 232, guiTop + 53));
addButton(new GuiNpcButton(104, guiLeft + 294, guiTop + 48, 50, 20,
@@ -223,6 +247,29 @@ public class GuiScript extends GuiScriptInterface {
if (MinecraftServer.getServer() != null)
addButton(new GuiNpcButton(106, guiLeft + 232, guiTop + 71, 150, 20, "script.openfolder"));
// Disable all buttons until server data arrives
if (!serverDataReceived) {
for (int btnId : new int[]{100, 102, 103, 104, 105, 106}) {
GuiNpcButton btn = getButton(btnId);
if (btn != null) btn.enabled = false;
}
} else {
getButton(103).enabled = languageOptions.size() > 0;
}
}
// Apply editor globals for the active NPC hook.
private void applyEditorGlobals(GuiScriptTextArea activeArea, String hookName) {
if (activeArea == null)
return;
ScriptTextContainer textContainer = activeArea.getContainer();
if (textContainer == null)
return;
if (script != null)
textContainer.setEditorGlobalsMap(script.getEditorGlobals(hookName));
}
@Override
@@ -240,9 +287,6 @@ public class GuiScript extends GuiScriptInterface {
NoppesUtil.openGUI(player, this);
if (!result)
return;
if (id == 0) {
openLink("https://kamkeel.github.io/CustomNPC-Plus/");
}
if (id == 101) {
getTextField(2).setText(NoppesStringUtils.getClipboardContents());
}
@@ -274,7 +318,12 @@ public class GuiScript extends GuiScriptInterface {
initGui();
}
if (guibutton.id == 15) {
displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true));
if (APIRegistry.Instance.size() == 1) {
String url = APIRegistry.Instance.getEntries().values().iterator().next();
setSubGui(new SubGuiConfirmLink(url));
} else {
setSubGui(new SubGuiAPISelect());
}
}
if (guibutton.id == 16) {
close();
@@ -309,9 +358,13 @@ public class GuiScript extends GuiScriptInterface {
}
if (guibutton.id == 107) {
ScriptContainer container = getCurrentContainer();
if (container == null)
script.setNPCScript(activeTab, container = new ScriptContainer(this.script));
setSubGui(new GuiScriptList(languages.get(script.scriptLanguage), container));
if (container == null) {
container = new ScriptContainer(this.script);
container.setLanguage(script.getLanguage());
script.setNPCScript(activeTab, container);
}
String lang = container.getLanguage();
setSubGui(new GuiScriptList(languages.get(lang), container));
}
}
@@ -319,8 +372,11 @@ public class GuiScript extends GuiScriptInterface {
protected void setScript() {
if (showScript) {
ScriptContainer container = getCurrentContainer();
if (container == null)
script.setNPCScript(activeTab, container = new ScriptContainer(this.script));
if (container == null) {
container = new ScriptContainer(this.script);
container.setLanguage(script.getLanguage());
script.setNPCScript(activeTab, container);
}
String text = getTextField(2).getText();
text = text.replace("\r\n", "\n");
text = text.replace("\r", "\n");
@@ -330,6 +386,11 @@ public class GuiScript extends GuiScriptInterface {
@Override
public void setGuiData(NBTTagCompound compound) {
// Only process the actual NPCScriptPacket response (has ScriptLanguage + Languages)
// Ignore unrelated packets (e.g. script config with ScriptsEnabled/GlobalNPCScriptsEnabled)
if (!compound.hasKey("ScriptLanguage") && !compound.hasKey("Languages")) {
return;
}
script.readFromNBT(compound);
loadLanguagesData(compound);
loaded = true;
@@ -337,7 +398,7 @@ public class GuiScript extends GuiScriptInterface {
@Override
public void save() {
if (loaded) {
if (loaded && serverDataReceived) {
setScript();
NPCScriptPacket.Save(script.writeToNBT(new NBTTagCompound()));
}
@@ -351,24 +412,4 @@ public class GuiScript extends GuiScriptInterface {
initGui();
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
// Draw fullscreen button when in script view (GuiScript uses 0-based activeTab)
if (showScript) {
fullscreenButton.draw(mouseX, mouseY);
}
}
@Override
public void mouseClicked(int mouseX, int mouseY, int mouseButton) {
// Check fullscreen button first when in script view
if (showScript && fullscreenButton.mouseClicked(mouseX, mouseY, mouseButton)) {
return;
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
}
@@ -13,7 +13,7 @@ public class SubGuiAnimationFrame extends SubGuiInterface implements ITextfieldL
public SubGuiAnimationFrame(Frame editingFrame) {
this.editingFrame = editingFrame;
setBackground("smallbg.png");
setBackground("menubg.png");
}
@Override
@@ -11,7 +11,7 @@ public class SubGuiAnimationOptions extends SubGuiInterface {
public SubGuiAnimationOptions(Animation animation) {
this.animation = animation;
setBackground("smallbg.png");
setBackground("menubg.png");
}
@Override
@@ -11,7 +11,7 @@ public class SubGuiEditText extends SubGuiInterface {
public SubGuiEditText(String text) {
this.text = text;
setBackground("extrasmallbg.png");
setBackground("menubg.png");
closeOnEsc = true;
xSize = 176;
ySize = 71;
@@ -6,14 +6,17 @@ import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.gui.global.GuiNPCManageEffects;
import net.minecraft.client.gui.GuiScreen;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.renderer.AnimationHelper;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNpcButtonYesNo;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.GuiScrollWindow;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.SubGuiTagSelect;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.client.renderer.ImageData;
import noppes.npcs.controllers.data.CustomEffect;
@@ -26,13 +29,13 @@ import java.util.List;
import static noppes.npcs.client.gui.player.inventory.GuiCNPCInventory.specialIcons;
public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldListener {
private final GuiNPCManageEffects parent;
private final GuiScreen parent;
public CustomEffect effect;
private final String originalName;
private final List<GuiMenuTopButton> topButtons = new ArrayList<>();
public SubGuiEffectGeneral(GuiNPCManageEffects parent, CustomEffect effect) {
public SubGuiEffectGeneral(GuiScreen parent, CustomEffect effect) {
this.effect = effect;
this.parent = parent;
this.originalName = effect.name;
@@ -62,12 +65,14 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
guiTop += 7;
int y = guiTop + 7;
int x = guiLeft + 4 + 4;
addTextField(new GuiNpcTextField(1, this, this.fontRendererObj, x + 36, y, 280, 20, effect.name));
addTextField(new GuiNpcTextField(1, this, this.fontRendererObj, x + 36, y, 210, 20, effect.name));
getTextField(1).setMaxStringLength(40);
addLabel(new GuiNpcLabel(1, "gui.name", x, y + 5));
addLabel(new GuiNpcLabel(-1, "ID", x + 320, y + 1));
addLabel(new GuiNpcLabel(-2, effect.id + "", x + 320, y + 11));
addLabel(new GuiNpcLabel(-1, "ID", x + 250, y + 1));
addLabel(new GuiNpcLabel(-2, effect.id + "", x + 250, y + 11));
addButton(new GuiNpcButton(40, getTextField(1).xPosition + getTextField(1).width + 30, y, 70, 20, "gui.tags"));
y += 23;
@@ -108,7 +113,8 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
x = oldX - 4;
y += 23;
GuiScrollWindow scrollWindow = new GuiScrollWindow(this, x + 5, y, xSize - 20, ySize - 10 - (y - guiTop), 0) {
int scrollClipHeight = ySize - 10 - (y - guiTop);
GuiScrollWindow scrollWindow = new GuiScrollWindow(this, x + 5, y, xSize - 20, scrollClipHeight, 0) {
@Override
public void drawComponents(int mouseX, int mouseY, float partialTicks) {
super.drawComponents(mouseX, mouseY, partialTicks);
@@ -127,8 +133,14 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
int iconWidth = effect.getWidth();
int iconHeight = effect.getHeight();
int width = data.getTotalWidth();
int height = data.getTotalWidth();
int height = data.getTotalHeight();
// Animation V offset for preview
if (data.isAnimated()) {
iconY += (int) (data.getCurrentFrameVOffset() * height);
} else if (effect.animated && effect.frameCount > 1) {
iconY += (int) (AnimationHelper.getFrameVOffset(height, effect.frameCount, effect.frametime) * height);
}
func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height);
@@ -183,6 +195,36 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
effect.height
));
scrollWindow.addLabel(new GuiNpcLabel(9, "effect.editor.height", scrollWindow.getTextField(9).xPosition - 43, y + 6, 0xFFFFFF));
y += 25;
// Animation controls
scrollWindow.addLabel(new GuiNpcLabel(11, "gui.animated", x, y + 5, 0xFFFFFF));
GuiNpcButtonYesNo animBtn = new GuiNpcButtonYesNo(11, x + 70, y, 50, 20, effect.animated);
animBtn.setHoverText("gui.animated.hover");
scrollWindow.addButton(animBtn);
if (effect.animated) {
y += 23;
scrollWindow.addLabel(new GuiNpcLabel(12, "gui.frameCount", x, y + 6, 0xFFFFFF));
scrollWindow.addTextField(setIntegerOnly(
new GuiNpcTextField(12, this, x + 80, y, 60, 20, "" + effect.frameCount),
1,
256,
effect.frameCount
));
y += 23;
scrollWindow.addLabel(new GuiNpcLabel(13, "gui.frameTime", x, y + 6, 0xFFFFFF));
scrollWindow.addTextField(setIntegerOnly(
new GuiNpcTextField(13, this, x + 80, y, 60, 20, "" + effect.frametime),
1,
100,
effect.frametime
));
}
int contentBottom = y + 20 + 5;
scrollWindow.maxScrollY = Math.max(0, contentBottom - scrollClipHeight);
}
@@ -205,10 +247,19 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
PacketClient.sendClient(new EffectSavePacket(effect.writeToNBT(false), originalName));
GuiScriptInterface.open(parent, new EffectScript(effect.id));
}
if (id == 40) {
setSubGui(new SubGuiTagSelect(effect.tagUUIDs));
return;
}
if (id == 10) {
GuiNpcButtonYesNo button = (GuiNpcButtonYesNo) guibutton;
effect.lossOnDeath = button.getBoolean();
}
if (id == 11) {
GuiNpcButtonYesNo button = (GuiNpcButtonYesNo) guibutton;
effect.animated = button.getBoolean();
initGui();
}
}
@Override
@@ -248,6 +299,12 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
case 9:
effect.height = guiNpcTextField.getInteger();
break;
case 12:
effect.frameCount = Math.max(1, guiNpcTextField.getInteger());
break;
case 13:
effect.frametime = Math.max(1, guiNpcTextField.getInteger());
break;
}
}
@@ -112,19 +112,19 @@ public class SubGuiNpcAvailabilityDialog extends SubGuiInterface implements GuiS
}
if (button.id == 10) {
slot = 1;
setSubGui(new GuiDialogSelection(availabitily.questId));
setSubGui(new GuiDialogSelection(availabitily.dialogId));
}
if (button.id == 11) {
slot = 2;
setSubGui(new GuiDialogSelection(availabitily.quest2Id));
setSubGui(new GuiDialogSelection(availabitily.dialog2Id));
}
if (button.id == 12) {
slot = 3;
setSubGui(new GuiDialogSelection(availabitily.quest3Id));
setSubGui(new GuiDialogSelection(availabitily.dialog3Id));
}
if (button.id == 13) {
slot = 4;
setSubGui(new GuiDialogSelection(availabitily.quest4Id));
setSubGui(new GuiDialogSelection(availabitily.dialog4Id));
}
if (button.id == 20) {
availabitily.dialogId = -1;
@@ -198,6 +198,5 @@ public class SubGuiNpcDialog extends SubGuiInterface implements ISubGuiListener,
}
public void save() {
PacketClient.sendClient(new DialogSavePacket(this.dialogCategoryID, dialog.writeToNBT(new NBTTagCompound()), false));
}
}
@@ -1,9 +1,6 @@
package noppes.npcs.client.gui;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.dialog.DialogSavePacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
@@ -521,8 +518,6 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis
public void save() {
GuiNpcTextField.unfocus();
if (dialog.id >= 0)
PacketClient.sendClient(new DialogSavePacket(((SubGuiNpcDialog) parent).dialogCategoryID, dialog.writeToNBT(new NBTTagCompound()), false));
}
private DialogImage getSelectedImage() {
@@ -12,7 +12,6 @@ import noppes.npcs.constants.EnumPotionType;
public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfieldListener {
private DataStats stats;
private String[] potionNames = new String[]{"gui.none", "tile.fire.name", "potion.poison", "potion.hunger", "potion.weakness", "potion.moveSlowdown", "potion.confusion", "potion.blindness", "potion.wither"};
public SubGuiNpcMeleeProperties(DataStats stats) {
this.stats = stats;
@@ -42,18 +41,34 @@ public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfi
getTextField(4).integersOnly = true;
getTextField(4).setMinMaxDefault(0, Integer.MAX_VALUE, 0);
addLabel(new GuiNpcLabel(5, "stats.meleeeffect", guiLeft + 5, guiTop + 135));
addButton(new GuiButtonBiDirectional(5, guiLeft + 85, guiTop + 130, 100, 20, potionNames, stats.potionType.ordinal()));
addButton(new GuiButtonBiDirectional(5, guiLeft + 85, guiTop + 130, 100, 20, EnumPotionType.getLangKeys(), stats.potionType.ordinal()));
if (stats.potionType == EnumPotionType.Manual) {
addLabel(new GuiNpcLabel(8, "effect.potionid", guiLeft + 198, guiTop + 119));
addTextField(new GuiNpcTextField(8, this, fontRendererObj, guiLeft + 200, guiTop + 132, 40, 18, stats.potionManualId + ""));
getTextField(8).integersOnly = true;
getTextField(8).setMinMaxDefault(0, Integer.MAX_VALUE, 0);
}
int y = guiTop + 160;
if (stats.potionType != EnumPotionType.None) {
addLabel(new GuiNpcLabel(6, "gui.time", guiLeft + 5, guiTop + 165));
addTextField(new GuiNpcTextField(6, this, fontRendererObj, guiLeft + 85, guiTop + 160, 40, 18, stats.potionDuration + ""));
addLabel(new GuiNpcLabel(6, "gui.time", guiLeft + 5, y + 5));
addTextField(new GuiNpcTextField(6, this, fontRendererObj, guiLeft + 85, y, 40, 18, stats.potionDuration + ""));
getTextField(6).integersOnly = true;
getTextField(6).setMinMaxDefault(1, Integer.MAX_VALUE, 5);
if (stats.potionType != EnumPotionType.Fire) {
addLabel(new GuiNpcLabel(7, "stats.amplify", guiLeft + 5, guiTop + 195));
addButton(new GuiButtonBiDirectional(7, guiLeft + 85, guiTop + 190, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.potionAmp));
y += 30;
addLabel(new GuiNpcLabel(7, "stats.amplify", guiLeft + 5, y + 5));
if (stats.potionType == EnumPotionType.Manual) {
addTextField(new GuiNpcTextField(7, this, fontRendererObj, guiLeft + 85, y, 52, 18, stats.potionAmp + ""));
getTextField(7).integersOnly = true;
getTextField(7).setMinMaxDefault(0, 255, 0);
} else {
addButton(new GuiButtonBiDirectional(7, guiLeft + 85, y, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.potionAmp));
}
}
}
addButton(new GuiNpcButton(66, guiLeft + 190, guiTop + 190, 60, 20, "gui.done"));
addButton(new GuiNpcButton(66, guiLeft + 190, guiTop + ySize - 26, 60, 20, "gui.done"));
}
public void unFocused(GuiNpcTextField textfield) {
@@ -67,13 +82,21 @@ public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfi
stats.knockback = textfield.getInteger();
} else if (textfield.id == 6) {
stats.potionDuration = textfield.getInteger();
} else if (textfield.id == 7) {
stats.potionAmp = textfield.getInteger();
} else if (textfield.id == 8) {
stats.potionManualId = textfield.getInteger();
}
}
protected void actionPerformed(GuiButton guibutton) {
GuiNpcButton button = (GuiNpcButton) guibutton;
if (button.id == 5) {
stats.potionType = EnumPotionType.values()[button.getValue()];
EnumPotionType newType = EnumPotionType.fromOrdinal(button.getValue());
if (stats.potionType == EnumPotionType.Manual && newType != EnumPotionType.Manual) {
stats.potionAmp = 0;
}
stats.potionType = newType;
initGui();
}
if (button.id == 7) {
@@ -15,7 +15,6 @@ import noppes.npcs.constants.EnumPotionType;
public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldListener, ISubGuiListener {
private DataStats stats;
private String[] potionNames = new String[]{"gui.none", "tile.fire.name", "potion.poison", "potion.hunger", "potion.weakness", "potion.moveSlowdown", "potion.confusion", "potion.blindness", "potion.wither"};
private String[] trailNames = new String[]{"gui.none", "trail.smoke", "trail.portal", "trail.redstone",
"trail.lightning", "trail.largesmoke", "trail.magic", "trail.enchant", "trail.crit",
"trail.explode", "trail.music", "trail.flame", "trail.lava", "trail.splash",
@@ -76,22 +75,35 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL
}
addLabel(new GuiNpcLabel(7, "stats.rangedeffect", guiLeft + 210, y + 5));
addButton(new GuiButtonBiDirectional(4, guiLeft + 280, y, 100, 20, potionNames, stats.pEffect.ordinal()));
addButton(new GuiButtonBiDirectional(4, guiLeft + 280, y, 100, 20, EnumPotionType.getLangKeys(), stats.pEffect.ordinal()));
if (stats.pEffect != EnumPotionType.None) {
int internalY = y + 30;
if (stats.pEffect == EnumPotionType.Manual) {
addLabel(new GuiNpcLabel(110, "effect.potionid", guiLeft + 210, internalY + 5));
addTextField(new GuiNpcTextField(11, this, fontRendererObj, guiLeft + 330, internalY, 52, 20, stats.pManualId + ""));
getTextField(11).integersOnly = true;
getTextField(11).setMinMaxDefault(0, Integer.MAX_VALUE, 0);
internalY += 30;
}
addLabel(new GuiNpcLabel(50, "gui.time", guiLeft + 210, internalY + 5));
addTextField(new GuiNpcTextField(5, this, fontRendererObj, guiLeft + 330, internalY, 52, 20, stats.pDur + ""));
getTextField(5).integersOnly = true;
getTextField(5).setMinMaxDefault(1, Integer.MAX_VALUE, 5);
if (stats.pEffect != EnumPotionType.Fire) {
internalY += 30;
addLabel(new GuiNpcLabel(70, "stats.amplify", guiLeft + 210, internalY + 5));
addButton(new GuiButtonBiDirectional(10, guiLeft + 280, internalY, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.pEffAmp));
} else {
if (stats.pEffect == EnumPotionType.Fire) {
internalY += 30;
addLabel(new GuiNpcLabel(100, "stats.burnItem", guiLeft + 210, internalY + 5));
addButton(new GuiNpcButtonYesNo(100, guiLeft + 330, internalY, 52, 20, stats.pBurnItem));
} else {
internalY += 30;
addLabel(new GuiNpcLabel(70, "stats.amplify", guiLeft + 210, internalY + 5));
if (stats.pEffect == EnumPotionType.Manual) {
addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 280, internalY, 52, 20, stats.pEffAmp + ""));
getTextField(10).integersOnly = true;
getTextField(10).setMinMaxDefault(0, 255, 0);
} else {
addButton(new GuiButtonBiDirectional(10, guiLeft + 280, internalY, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.pEffAmp));
}
}
}
@@ -126,6 +138,10 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL
stats.pSpeed = textfield.getInteger();
} else if (textfield.id == 5) {
stats.pDur = textfield.getInteger();
} else if (textfield.id == 10) {
stats.pEffAmp = textfield.getInteger();
} else if (textfield.id == 11) {
stats.pManualId = textfield.getInteger();
}
}
@@ -146,7 +162,11 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL
stats.pArea = button.getValue();
}
if (button.id == 4) {
stats.pEffect = EnumPotionType.values()[button.getValue()];
EnumPotionType newType = EnumPotionType.fromOrdinal(button.getValue());
if (stats.pEffect == EnumPotionType.Manual && newType != EnumPotionType.Manual) {
stats.pEffAmp = 0;
}
stats.pEffect = newType;
initGui();
}
if (button.id == 5) {
@@ -239,6 +239,5 @@ public class SubGuiNpcQuest extends SubGuiInterface implements ISubGuiListener,
}
public void save() {
PacketClient.sendClient(new QuestSavePacket(this.questCategoryID, quest.writeToNBT(new NBTTagCompound()), false));
}
}
@@ -5,6 +5,7 @@ import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcButtonYesNo;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.GuiScrollWindow;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.data.SpawnData;
@@ -15,37 +16,97 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield
public SubGuiSpawningOptions(SpawnData data) {
this.data = data;
setBackground("menubg.png");
xSize = 216;
xSize = 256;
ySize = 216;
closeOnEsc = true;
}
public void initGui() {
super.initGui();
int y = guiTop - 15;
int scrollX = guiLeft + 4;
int scrollY = guiTop + 4;
int scrollW = xSize - 8;
int scrollH = ySize - 34;
addButton(new GuiNpcButtonYesNo(10, guiLeft + 120, y += 22, data.animalSpawning));
addLabel(new GuiNpcLabel(10, "spawning.animalSpawning", guiLeft + 4, y + 5));
GuiScrollWindow sw = new GuiScrollWindow(this, scrollX, scrollY, scrollW, scrollH, 0);
sw.drawDefaultBackground = false;
addScrollableGui(0, sw);
addButton(new GuiNpcButtonYesNo(11, guiLeft + 120, y += 22, data.monsterSpawning));
addLabel(new GuiNpcLabel(11, "spawning.monsterSpawning", guiLeft + 4, y + 5));
int labelX = 4;
int controlX = 132;
int y = 6;
addButton(new GuiNpcButtonYesNo(12, guiLeft + 120, y += 22, data.liquidSpawning));
addLabel(new GuiNpcLabel(12, "spawning.liquidSpawning", guiLeft + 4, y + 5));
sw.addButton(new GuiNpcButtonYesNo(10, controlX, y, data.animalSpawning));
sw.addLabel(new GuiNpcLabel(10, "spawning.animalSpawning", labelX, y + 5));
sw.getButton(10).setHoverText("tooltip.naturalspawns.options.animal");
y += 22;
addButton(new GuiNpcButtonYesNo(13, guiLeft + 120, y += 22, data.airSpawning));
addLabel(new GuiNpcLabel(13, "spawning.airSpawning", guiLeft + 4, y + 5));
sw.addButton(new GuiNpcButtonYesNo(11, controlX, y, data.monsterSpawning));
sw.addLabel(new GuiNpcLabel(11, "spawning.monsterSpawning", labelX, y + 5));
sw.getButton(11).setHoverText("tooltip.naturalspawns.options.monster");
y += 22;
addTextField(new GuiNpcTextField(14, this, guiLeft + 120, y += 22, 40, 20, "" + data.spawnHeightMin));
addLabel(new GuiNpcLabel(14, "spawning.minHeight", guiLeft + 4, y + 5));
addTextField(new GuiNpcTextField(15, this, guiLeft + 120, y += 22, 40, 20, "" + data.spawnHeightMax));
addLabel(new GuiNpcLabel(15, "spawning.maxHeight", guiLeft + 4, y + 5));
getTextField(14).integersOnly = true;
getTextField(14).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
getTextField(15).integersOnly = true;
getTextField(15).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
sw.addButton(new GuiNpcButtonYesNo(12, controlX, y, data.liquidSpawning));
sw.addLabel(new GuiNpcLabel(12, "spawning.liquidSpawning", labelX, y + 5));
sw.getButton(12).setHoverText("tooltip.naturalspawns.options.liquid");
y += 22;
addButton(new GuiNpcButton(100, guiLeft + 154, guiTop + 192, 60, 20, "gui.done"));
sw.addButton(new GuiNpcButtonYesNo(13, controlX, y, data.airSpawning));
sw.addLabel(new GuiNpcLabel(13, "spawning.airSpawning", labelX, y + 5));
sw.getButton(13).setHoverText("tooltip.naturalspawns.options.air");
y += 22;
sw.addTextField(new GuiNpcTextField(14, this, controlX, y, 60, 20, "" + data.spawnHeightMin));
sw.addLabel(new GuiNpcLabel(14, "spawning.minHeight", labelX, y + 5));
sw.getTextField(14).integersOnly = true;
sw.getTextField(14).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
sw.getTextField(14).setHoverText("tooltip.naturalspawns.options.minHeight");
y += 22;
sw.addTextField(new GuiNpcTextField(15, this, controlX, y, 60, 20, "" + data.spawnHeightMax));
sw.addLabel(new GuiNpcLabel(15, "spawning.maxHeight", labelX, y + 5));
sw.getTextField(15).integersOnly = true;
sw.getTextField(15).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
sw.getTextField(15).setHoverText("tooltip.naturalspawns.options.maxHeight");
y += 22;
sw.addTextField(new GuiNpcTextField(16, this, controlX, y, 60, 20, "" + data.maxAlive));
sw.addLabel(new GuiNpcLabel(16, "spawning.maxAlive", labelX, y + 5));
sw.getTextField(16).integersOnly = true;
sw.getTextField(16).setMinMaxDefault(0, Integer.MAX_VALUE, 0);
sw.getTextField(16).setHoverText("tooltip.naturalspawns.options.maxAlive");
y += 22;
sw.addTextField(new GuiNpcTextField(17, this, controlX, y, 60, 20, "" + data.cooldownTicks));
sw.addLabel(new GuiNpcLabel(17, "spawning.cooldownTicks", labelX, y + 5));
sw.getTextField(17).integersOnly = true;
sw.getTextField(17).setMinMaxDefault(0, Integer.MAX_VALUE, 0);
sw.getTextField(17).setHoverText("tooltip.naturalspawns.options.cooldownTicks");
y += 22;
sw.addTextField(new GuiNpcTextField(18, this, controlX, y, 60, 20, "" + data.attemptsPerCycle));
sw.addLabel(new GuiNpcLabel(18, "spawning.attemptsPerCycle", labelX, y + 5));
sw.getTextField(18).integersOnly = true;
sw.getTextField(18).setMinMaxDefault(1, Integer.MAX_VALUE, 1);
sw.getTextField(18).setHoverText("tooltip.naturalspawns.options.attemptsPerCycle");
y += 22;
sw.addTextField(new GuiNpcTextField(19, this, controlX, y, 60, 20, "" + data.playerMinDistance));
sw.addLabel(new GuiNpcLabel(19, "spawning.playerMinDistance", labelX, y + 5));
sw.getTextField(19).integersOnly = true;
sw.getTextField(19).setMinMaxDefault(0, Integer.MAX_VALUE, 24);
sw.getTextField(19).setHoverText("tooltip.naturalspawns.options.playerMinDistance");
y += 22;
sw.addButton(new GuiNpcButton(20, controlX, y, 100, 20,
new String[]{"spawning.despawn.forceNatural", "spawning.despawn.preserve", "spawning.despawn.forcePersistent"}, data.despawnMode));
sw.addLabel(new GuiNpcLabel(20, "spawning.despawnMode", labelX, y + 5));
sw.getButton(20).setHoverText("tooltip.naturalspawns.options.despawnMode");
y += 22;
sw.maxScrollY = Math.max(0, y - sw.clipHeight + 8);
addButton(new GuiNpcButton(100, guiLeft + xSize - 64, guiTop + ySize - 24, 60, 20, "gui.done"));
}
@Override
@@ -64,6 +125,9 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield
if (button.id == 13) {
data.airSpawning = button.getValue() == 1;
}
if (button.id == 20) {
data.setDespawnMode(button.getValue());
}
if (button.id == 100) {
close();
}
@@ -77,5 +141,17 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield
if (textfield.id == 15) {
data.spawnHeightMax = textfield.getInteger();
}
if (textfield.id == 16) {
data.setMaxAlive(textfield.getInteger());
}
if (textfield.id == 17) {
data.setCooldownTicks(textfield.getInteger());
}
if (textfield.id == 18) {
data.setAttemptsPerCycle(textfield.getInteger());
}
if (textfield.id == 19) {
data.setPlayerMinDistance(textfield.getInteger());
}
}
}
@@ -0,0 +1,174 @@
package noppes.npcs.client.gui;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.tags.TagsGetPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.StatCollector;
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.IScrollData;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.constants.EnumScrollData;
import noppes.npcs.controllers.TagController;
import noppes.npcs.controllers.data.Tag;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import java.util.Vector;
/**
* Reusable SubGui for selecting tags on any taggable object.
* Pass in the current tagUUIDs, get back the modified set on close.
*/
public class SubGuiTagSelect extends SubGuiInterface implements IScrollData, ICustomScrollListener, ITextfieldListener {
private GuiCustomScroll scrollAllTags;
private GuiCustomScroll scrollSelectedTags;
private final ArrayList<String> allTagNames = new ArrayList<>();
private final ArrayList<String> selectedTagNames = new ArrayList<>();
private final HashSet<UUID> tagUUIDs;
private String search = "";
public SubGuiTagSelect(HashSet<UUID> tagUUIDs) {
this.tagUUIDs = tagUUIDs;
setBackground("menubg.png");
closeOnEsc = true;
xSize = 430;
ySize = 220;
// Populate selected tag names from UUIDs
TagController tc = TagController.getInstance();
if (tc != null) {
for (UUID uuid : tagUUIDs) {
Tag tag = tc.getTagFromUUID(uuid);
if (tag != null) {
selectedTagNames.add(tag.name);
}
}
}
PacketClient.sendClient(new TagsGetPacket());
}
public void initGui() {
super.initGui();
addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("tags.allTags"), guiLeft + 22, guiTop + 11));
if (scrollAllTags == null) {
scrollAllTags = new GuiCustomScroll(this, 0);
scrollAllTags.setSize(150, 155);
}
scrollAllTags.guiLeft = guiLeft + 20;
scrollAllTags.guiTop = guiTop + 24;
this.addScroll(scrollAllTags);
addTextField(new GuiNpcTextField(4, this, fontRendererObj, guiLeft + 20, guiTop + 24 + 160, 150, 20, search));
addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("tags.selectedTags"), guiLeft + 252, guiTop + 11));
if (scrollSelectedTags == null) {
scrollSelectedTags = new GuiCustomScroll(this, 1);
scrollSelectedTags.setSize(150, 180);
}
scrollSelectedTags.guiLeft = guiLeft + 250;
scrollSelectedTags.guiTop = guiTop + 24;
scrollSelectedTags.setList(selectedTagNames);
this.addScroll(scrollSelectedTags);
addButton(new GuiNpcButton(10, guiLeft + 185, guiTop + 90, 55, 20, ">"));
addButton(new GuiNpcButton(11, guiLeft + 185, guiTop + 112, 55, 20, "<"));
addButton(new GuiNpcButton(12, guiLeft + 185, guiTop + 140, 55, 20, ">>"));
addButton(new GuiNpcButton(13, guiLeft + 185, guiTop + 162, 55, 20, "<<"));
}
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 10 && scrollAllTags.hasSelected() && !selectedTagNames.contains(scrollAllTags.getSelected())) {
selectedTagNames.add(scrollAllTags.getSelected());
}
if (guibutton.id == 12) {
selectedTagNames.clear();
selectedTagNames.addAll(allTagNames);
}
if (guibutton.id == 11 && scrollSelectedTags.hasSelected()) {
selectedTagNames.remove(scrollSelectedTags.getSelected());
}
if (guibutton.id == 13) {
selectedTagNames.clear();
}
initGui();
}
@Override
public void setData(Vector<String> list, HashMap<String, Integer> data, EnumScrollData type) {
allTagNames.clear();
allTagNames.addAll(data.keySet());
allTagNames.sort(String.CASE_INSENSITIVE_ORDER);
scrollAllTags.setList(getSearchList());
initGui();
}
@Override
public void save() {
tagUUIDs.clear();
TagController tc = TagController.getInstance();
if (tc != null) {
for (String name : selectedTagNames) {
Tag tag = tc.getTagFromName(name);
if (tag != null) {
tagUUIDs.add(tag.uuid);
}
}
}
}
public void mouseClicked(int i, int j, int k) {
super.mouseClicked(i, j, k);
if (k == 0 && scrollAllTags != null)
scrollAllTags.mouseClicked(i, j, k);
}
@Override
public void setSelected(String selected) {
if (scrollAllTags != null)
scrollAllTags.setSelected(selected);
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
}
public void keyTyped(char c, int i) {
if (i == 1) {
close();
return;
}
super.keyTyped(c, i);
if (getTextField(4) != null) {
if (search.equals(getTextField(4).getText()))
return;
search = getTextField(4).getText().toLowerCase();
scrollAllTags.setList(getSearchList());
}
}
@Override
public void unFocused(GuiNpcTextField guiNpcTextField) {
}
private List<String> getSearchList() {
if (search.isEmpty()) {
return new ArrayList<>(allTagNames);
}
List<String> list = new ArrayList<>();
for (String name : allTagNames) {
if (name.toLowerCase().contains(search))
list.add(name);
}
return list;
}
}
@@ -0,0 +1,92 @@
package noppes.npcs.client.gui;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.SubGuiInterface;
@SideOnly(Side.CLIENT)
public class SubGuiTrapPresetSelector extends SubGuiInterface {
public String selectedPreset = null;
/**
* Builds the trap editor's preset field.
* <p>
* This lives here rather than in AbilityTrap because the lambda below carries this class in
* its method descriptor. AbilityTrap is a both-side class, and @SideOnly does not strip the
* synthetic lambda methods it generates - so anything reflecting over its declared methods
* on a server would resolve that descriptor and fail to find this client-only type.
*/
public static FieldDef createPresetField(java.util.function.Consumer<String> applyPreset) {
return FieldDef.subGuiField("gui.applyPreset",
SubGuiTrapPresetSelector::new,
gui -> {
SubGuiTrapPresetSelector selector = (SubGuiTrapPresetSelector) gui;
if (selector.selectedPreset != null) {
applyPreset.accept(selector.selectedPreset);
}
});
}
private static final String[] PRESET_NAMES = {"HIDDEN", "VENOM", "EXPLOSIVE", "CURSED", "SHOCK", "SNARE"};
private static final String[] PRESET_LABELS = {
"ability.preset.hidden", "ability.preset.venom", "ability.preset.explosive",
"ability.preset.cursed", "ability.preset.shock", "ability.preset.snare"
};
private static final int[] PRESET_COLORS = {0x888888, 0x44DD44, 0xFF6611, 0xAA44FF, 0x4488FF, 0x88CCFF};
public SubGuiTrapPresetSelector() {
xSize = 170;
ySize = 135;
setBackground("menubg.png");
}
@Override
public void initGui() {
super.initGui();
int btnW = 72;
int btnH = 20;
int gapY = 4;
int col1 = guiLeft + 7;
int col2 = col1 + btnW + 6;
int startY = guiTop + 22;
for (int i = 0; i < 6; i++) {
int x = (i % 2 == 0) ? col1 : col2;
int y = startY + (i / 2) * (btnH + gapY);
addButton(new GuiNpcButton(i, x, y, btnW, btnH, PRESET_LABELS[i]));
}
int cancelY = startY + 3 * (btnH + gapY) + 4;
addButton(new GuiNpcButton(10, guiLeft + xSize / 2 - 36, cancelY, 72, btnH, "gui.cancel"));
}
@Override
protected void actionPerformed(GuiButton btn) {
super.actionPerformed(btn);
if (btn.id >= 0 && btn.id < 6) {
selectedPreset = PRESET_NAMES[btn.id];
close();
} else if (btn.id == 10) {
close();
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float f) {
super.drawScreen(mouseX, mouseY, f);
drawCenteredString(fontRendererObj, StatCollector.translateToLocal("gui.applyPreset"), guiLeft + xSize / 2, guiTop + 8, 0xFFFFFF);
for (int i = 0; i < 6; i++) {
GuiNpcButton btn = getButton(i);
if (btn != null && btn.visible) {
int x = btn.xPosition + 4;
int y = btn.yPosition + 5;
drawRect(x, y, x + 10, y + 10, 0xFF000000 | PRESET_COLORS[i]);
}
}
}
}
@@ -0,0 +1,92 @@
package noppes.npcs.client.gui;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.SubGuiInterface;
@SideOnly(Side.CLIENT)
public class SubGuiZonePresetSelector extends SubGuiInterface {
public String selectedPreset = null;
/**
* Builds the zone editor's preset field.
* <p>
* This lives here rather than in AbilityZone because the lambda below carries this class in
* its method descriptor. AbilityZone is a both-side class, and @SideOnly does not strip the
* synthetic lambda methods it generates - so anything reflecting over its declared methods
* on a server would resolve that descriptor and fail to find this client-only type.
*/
public static FieldDef createPresetField(java.util.function.Consumer<String> applyPreset) {
return FieldDef.subGuiField("gui.applyPreset",
SubGuiZonePresetSelector::new,
gui -> {
SubGuiZonePresetSelector selector = (SubGuiZonePresetSelector) gui;
if (selector.selectedPreset != null) {
applyPreset.accept(selector.selectedPreset);
}
});
}
private static final String[] PRESET_NAMES = {"DEFAULT", "TOXIC", "INFERNO", "ARCANE", "ELECTRIC", "FROST"};
private static final String[] PRESET_LABELS = {
"ability.preset.default", "ability.preset.toxic", "ability.preset.inferno",
"ability.preset.arcane", "ability.preset.electric", "ability.preset.frost"
};
private static final int[] PRESET_COLORS = {0xCCCCCC, 0x44DD44, 0xFF6611, 0xAA44FF, 0x4488FF, 0x88CCFF};
public SubGuiZonePresetSelector() {
xSize = 170;
ySize = 135;
setBackground("menubg.png");
}
@Override
public void initGui() {
super.initGui();
int btnW = 72;
int btnH = 20;
int gapY = 4;
int col1 = guiLeft + 7;
int col2 = col1 + btnW + 6;
int startY = guiTop + 22;
for (int i = 0; i < 6; i++) {
int x = (i % 2 == 0) ? col1 : col2;
int y = startY + (i / 2) * (btnH + gapY);
addButton(new GuiNpcButton(i, x, y, btnW, btnH, PRESET_LABELS[i]));
}
int cancelY = startY + 3 * (btnH + gapY) + 4;
addButton(new GuiNpcButton(10, guiLeft + xSize / 2 - 36, cancelY, 72, btnH, "gui.cancel"));
}
@Override
protected void actionPerformed(GuiButton btn) {
super.actionPerformed(btn);
if (btn.id >= 0 && btn.id < 6) {
selectedPreset = PRESET_NAMES[btn.id];
close();
} else if (btn.id == 10) {
close();
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float f) {
super.drawScreen(mouseX, mouseY, f);
drawCenteredString(fontRendererObj, StatCollector.translateToLocal("gui.applyPreset"), guiLeft + xSize / 2, guiTop + 8, 0xFFFFFF);
for (int i = 0; i < 6; i++) {
GuiNpcButton btn = getButton(i);
if (btn != null && btn.visible) {
int x = btn.xPosition + 4;
int y = btn.yPosition + 5;
drawRect(x, y, x + 10, y + 10, 0xFF000000 | PRESET_COLORS[i]);
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,12 +1,15 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.Condition;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.controllers.data.AbilityScript;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.SubGuiTagSelect;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
@@ -20,6 +23,8 @@ import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.ArrayList;
import java.util.List;
import static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS;
public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldListener, ISubGuiListener {
private static final int DECLARATIVE_ID_START = 1000;
@@ -42,6 +47,12 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
private static final int L_LABEL_X = 5;
private static final int ROW_H = 24;
// Condition buttons
private static final int COND_BASE = 50;
private static final int COND_STRIDE = 10;
private static final int COND_END = COND_BASE + MAX_CONDITIONS * COND_STRIDE; // 50 + N*10
private static final int BTN_ADD_COND = COND_END;
private final Ability ability;
private final IAbilityConfigCallback callback;
private int activeTab = TAB_GENERAL;
@@ -49,7 +60,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
private List<FieldDef> fieldDefs;
private List<String> customTabNames;
private List<Condition> conditions;
private List<AbilityCondition> conditions;
private int editingConditionIndex = -1;
private AbilityFieldBuilder builder;
@@ -75,11 +86,11 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
for (FieldDef def : fieldDefs) {
String tab = def.getTab();
if (tab != null
&& !TAB_NAME_GENERAL.equals(tab)
&& !TAB_NAME_TYPE.equals(tab)
&& !TAB_NAME_TARGET.equals(tab)
&& !TAB_NAME_EFFECTS.equals(tab)
&& !customTabNames.contains(tab)) {
&& !TAB_NAME_GENERAL.equals(tab)
&& !TAB_NAME_TYPE.equals(tab)
&& !TAB_NAME_TARGET.equals(tab)
&& !TAB_NAME_EFFECTS.equals(tab)
&& !customTabNames.contains(tab)) {
customTabNames.add(tab);
}
}
@@ -92,6 +103,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
@Override
public void initGui() {
// Commit any focused text field before rebuilding
GuiNpcTextField.unfocus();
// Save scroll position before super clears scroll windows
GuiScrollWindow oldSw = getScrollableGui(0);
if (oldSw != null && activeTab < tabScrollY.length) {
@@ -132,6 +146,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
GuiMenuTopButton closeBtn = new GuiMenuTopButton(-1000, guiLeft + xSize - 22, guiTop - 17, "X");
addTopButton(closeBtn);
GuiMenuTopButton scriptBtn = new GuiMenuTopButton(-999, "script.scripts", closeBtn);
addTopButton(scriptBtn);
// Build scroll window dimensions
int swX = guiLeft + 4;
int swY = guiTop + 5;
@@ -141,9 +158,15 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
int y = 5;
int labelCounter = LABEL_ID_START;
// General tab: type label at top — need to reserve space before building
// General tab: type label + optional info labels at top — reserve space
if (activeTab == TAB_GENERAL) {
y += ROW_H;
if ("ability.cnpc.custom".equals(ability.getTypeId())) {
y += 15;
}
if (ability.isConcurrentCapable()) {
y += 15;
}
}
// Build declarative fields into an auto-created scroll window
@@ -154,10 +177,26 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
GuiScrollWindow sw = builder.buildScrollWindow(tabFields, swX, swY, swW, swH);
// General tab: add type label at top of scroll window
// General tab: add type label + optional info labels at top of scroll window
if (activeTab == TAB_GENERAL) {
sw.addLabel(new GuiNpcLabel(builder.getNextLabelId(), "gui.type", 5, 5 + 5, 0xFFFFFF));
sw.addLabel(new GuiNpcLabel(builder.getNextLabelId() + 1, ability.getTypeId(), 55, 5 + 5, 0xFFFFFF));
int baseId = builder.getNextLabelId();
int infoY = 25;
sw.addLabel(new GuiNpcLabel(baseId, "gui.type", 5, 10, 0xFFFFFF));
sw.addLabel(new GuiNpcLabel(baseId + 1, ability.getTypeId(), 55, 10, 0xFFFFFF));
if ("ability.cnpc.custom".equals(ability.getTypeId())) {
sw.addLabel(new GuiNpcLabel(baseId + 2,
StatCollector.translateToLocal("ability.customScriptInfo"), 5, infoY, 0xFF55FF));
infoY += 15;
}
if (ability.isConcurrentCapable()) {
sw.addLabel(new GuiNpcLabel(baseId + 3,
StatCollector.translateToLocal("ability.concurrentInfo"), 5, infoY, 0x55FFFF));
}
}
// Tags button on general tab
if (activeTab == TAB_GENERAL) {
sw.addButton(new GuiNpcButton(40, sw.clipWidth - 95, 5, 80, 20, "gui.tags"));
}
// Conditions on target tab — appended after field defs
@@ -187,11 +226,21 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
}
} else {
switch (tabIndex) {
case TAB_GENERAL: tabName = TAB_NAME_GENERAL; break;
case TAB_TYPE: tabName = TAB_NAME_TYPE; break;
case TAB_TARGET: tabName = TAB_NAME_TARGET; break;
case TAB_EFFECTS: tabName = TAB_NAME_EFFECTS; break;
default: tabName = TAB_NAME_TYPE; break;
case TAB_GENERAL:
tabName = TAB_NAME_GENERAL;
break;
case TAB_TYPE:
tabName = TAB_NAME_TYPE;
break;
case TAB_TARGET:
tabName = TAB_NAME_TARGET;
break;
case TAB_EFFECTS:
tabName = TAB_NAME_EFFECTS;
break;
default:
tabName = TAB_NAME_TYPE;
break;
}
}
@@ -213,46 +262,29 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55));
y += 15;
for (int i = 0; i < conditions.size() && i < 3; i++) {
Condition cond = conditions.get(i);
for (int i = 0; i < conditions.size() && i < MAX_CONDITIONS; i++) {
AbilityCondition cond = conditions.get(i);
String condName = getConditionDisplayName(cond);
sw.addButton(new GuiNpcButton(50 + i * 10, L_LABEL_X, y, 140, 20, condName));
sw.addButton(new GuiNpcButton(51 + i * 10, L_LABEL_X + 145, y, 40, 20, "gui.edit"));
sw.addButton(new GuiNpcButton(52 + i * 10, L_LABEL_X + 190, y, 20, 20, "X"));
GuiNpcButton condBtn = new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName);
condBtn.hoverableText = cond.getConditionSummary();
sw.addButton(condBtn);
sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit"));
sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X"));
y += 22;
}
if (conditions.size() < 3) {
sw.addButton(new GuiNpcButton(80, L_LABEL_X, y, 50, 20, "gui.add"));
if (conditions.size() < MAX_CONDITIONS) {
sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add"));
y += ROW_H;
}
return y;
}
private String getConditionDisplayName(Condition cond) {
private String getConditionDisplayName(AbilityCondition cond) {
if (cond == null) return "None";
String typeId = cond.getTypeId();
switch (typeId) {
case "hp_above":
return StatCollector.translateToLocal("condition.hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%";
case "hp_below":
return StatCollector.translateToLocal("condition.hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%";
case "target_hp_above":
return StatCollector.translateToLocal("condition.target_hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%";
case "target_hp_below":
return StatCollector.translateToLocal("condition.target_hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%";
case "hit_count":
Condition.ConditionHitCount hc = (Condition.ConditionHitCount) cond;
return StatCollector.translateToLocal("condition.hit_count") + ": " + hc.getRequiredHits() + "/" + hc.getWithinTicks() + "t";
default:
return typeId;
}
}
private float getConditionThreshold(Condition cond) {
NBTTagCompound nbt = cond.writeNBT();
return nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f;
String name = cond.getName();
return StatCollector.translateToLocal(name);
}
// ═══════════════════════════════════════════════════════════════════════════
@@ -264,17 +296,47 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
int id = guibutton.id;
// Tab switching — fixed tabs
if (id == 90) { activeTab = TAB_GENERAL; initGui(); return; }
if (id == 91) { activeTab = TAB_TYPE; initGui(); return; }
if (id == 92) { activeTab = TAB_TARGET; initGui(); return; }
if (id == 93) { activeTab = TAB_EFFECTS; initGui(); return; }
if (id == 90) {
activeTab = TAB_GENERAL;
initGui();
return;
}
if (id == 91) {
activeTab = TAB_TYPE;
initGui();
return;
}
if (id == 92) {
activeTab = TAB_TARGET;
initGui();
return;
}
if (id == 93) {
activeTab = TAB_EFFECTS;
initGui();
return;
}
// Custom tabs (94+)
if (id >= 94 && id < 94 + customTabNames.size()) {
activeTab = 4 + (id - 94);
initGui();
return;
}
if (id == -1000) { close(); return; }
if (id == -999) {
GuiNpcTextField.unfocus();
applyToAbility();
callback.onAbilitySaved(ability);
GuiScriptInterface.open(parent, new AbilityScript(ability.getId()));
return;
}
if (id == 40) {
setSubGui(new SubGuiTagSelect(ability.getTagUUIDs()));
return;
}
if (id == -1000) {
close();
return;
}
// Condition buttons (50-80)
if (handleConditionButton(id)) return;
@@ -291,9 +353,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
}
private boolean handleConditionButton(int id) {
if (id >= 50 && id < 80) {
int condIndex = (id - 50) / 10;
int action = (id - 50) % 10;
if (id >= COND_BASE && id < COND_END) {
int condIndex = (id - COND_BASE) / COND_STRIDE;
int action = (id - COND_BASE) % COND_STRIDE;
if (action == 0 || action == 1) {
if (condIndex < conditions.size()) {
editingConditionIndex = condIndex;
@@ -307,8 +369,8 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
}
return true;
}
if (id == 80) {
if (conditions.size() < 3) {
if (id == BTN_ADD_COND) {
if (conditions.size() < MAX_CONDITIONS) {
editingConditionIndex = conditions.size();
setSubGui(new SubGuiConditionEdit(null));
}
@@ -342,7 +404,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
if (subgui instanceof SubGuiConditionEdit) {
SubGuiConditionEdit condEdit = (SubGuiConditionEdit) subgui;
Condition result = condEdit.getResult();
AbilityCondition result = condEdit.getResult();
if (result != null && editingConditionIndex >= 0) {
if (editingConditionIndex < conditions.size()) {
conditions.set(editingConditionIndex, result);
@@ -369,12 +431,12 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
protected void applyToAbility() {
ability.getConditions().clear();
for (Condition c : conditions) ability.addCondition(c);
for (AbilityCondition c : conditions) ability.addCondition(c);
}
public void loadAbility(Ability loadedAbility) {
if (loadedAbility == null) return;
NBTTagCompound nbt = loadedAbility.writeNBT();
NBTTagCompound nbt = loadedAbility.writeNBT(false);
nbt.setString("typeId", ability.getTypeId());
ability.readNBT(nbt);
@@ -3,18 +3,15 @@ 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;
/**
* Dialog asking the user whether to clone-and-modify (convert to inline) or modify the parent ability.
*/
public class SubGuiAbilityEditMode extends SubGuiInterface {
public class SubGuiAbilityEditMode extends SubGuiSimpleChoice {
public static final int MODE_CLONE_MODIFY = 0;
public static final int MODE_MODIFY_PARENT = 1;
private int result = -1;
public SubGuiAbilityEditMode() {
setBackground("menubg.png");
xSize = 220;
@@ -39,18 +36,13 @@ public class SubGuiAbilityEditMode extends SubGuiInterface {
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0) {
result = MODE_CLONE_MODIFY;
setResult(MODE_CLONE_MODIFY);
close();
} else if (guibutton.id == 1) {
result = MODE_MODIFY_PARENT;
setResult(MODE_MODIFY_PARENT);
close();
} else if (guibutton.id == 2) {
result = -1;
close();
}
}
public int getResult() {
return result;
}
}
@@ -1,7 +1,8 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket;
import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket;
@@ -21,7 +22,7 @@ import noppes.npcs.constants.EnumScrollData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.Map;
import java.util.Vector;
/**
@@ -33,10 +34,8 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
private final SubGuiAbilityConfig parentConfig;
private final GuiNPCAbilities parentAbilities;
private String selectedDisplayName = null;
private String selectedUuid = null;
private String selectedName = null;
/** Maps display name -> UUID for custom abilities. */
private final HashMap<String, String> displayToUuid = new HashMap<>();
private HashMap<String, Integer> rawData = new HashMap<>();
private GuiCustomScroll scroll;
@@ -97,18 +96,22 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "gui.load"));
addButton(new GuiNpcButton(2, guiLeft + 115, y, 95, 20, "gui.cancel"));
getButton(0).setEnabled(selectedUuid != null);
getButton(0).setEnabled(selectedName != null);
}
private List<String> getFilteredList() {
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);
for (Map.Entry<String, Integer> entry : rawData.entrySet()) {
String name = entry.getKey();
// Only show NPC-valid abilities (NPC_ONLY or BOTH)
UserType ut = UserType.fromOrdinal(entry.getValue());
if (!ut.allowsNpc()) continue;
if (!search.isEmpty() && !name.toLowerCase().contains(search.toLowerCase())) {
continue;
}
list.add(name);
}
return list;
}
@@ -117,7 +120,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
if (id == 0 && selectedUuid != null) {
if (id == 0 && selectedName != null) {
if (parentAbilities != null) {
// From NPC abilities GUI - ask clone/reference
setSubGui(new SubGuiAbilityLoadMode());
@@ -125,7 +128,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
// From config GUI - always clone
waitingForLoad = true;
pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE;
PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid));
PacketClient.sendClient(new CustomAbilityGetPacket(selectedName));
}
} else if (id == 2) {
close();
@@ -152,16 +155,16 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
if (mode < 0) return; // cancelled
if (mode == SubGuiAbilityLoadMode.MODE_REFERENCE) {
// Reference mode - just pass the reference ID
if (parentAbilities != null && selectedUuid != null) {
parentAbilities.loadAbilityReference(selectedUuid);
// Reference mode - just pass the reference name
if (parentAbilities != null && selectedName != null) {
parentAbilities.loadAbilityReference(selectedName);
}
close();
} else {
// Clone mode - request full data
waitingForLoad = true;
pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE;
PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid));
PacketClient.sendClient(new CustomAbilityGetPacket(selectedName));
}
}
}
@@ -170,9 +173,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
if (scroll.id == 0) {
selectedDisplayName = scroll.getSelected();
if (selectedDisplayName != null) {
selectedUuid = displayToUuid.get(selectedDisplayName);
}
selectedName = selectedDisplayName;
initGui();
}
}
@@ -181,15 +182,13 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
if (scroll.id == 0 && selection != null && !selection.isEmpty()) {
selectedDisplayName = selection;
selectedUuid = displayToUuid.get(selectedDisplayName);
if (selectedUuid != null) {
if (parentAbilities != null) {
setSubGui(new SubGuiAbilityLoadMode());
} else {
waitingForLoad = true;
pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE;
PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid));
}
selectedName = selection;
if (parentAbilities != null) {
setSubGui(new SubGuiAbilityLoadMode());
} else {
waitingForLoad = true;
pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE;
PacketClient.sendClient(new CustomAbilityGetPacket(selectedName));
}
}
}
@@ -197,22 +196,10 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
@Override
public void setData(Vector<String> list, HashMap<String, Integer> data, EnumScrollData type) {
if (type == EnumScrollData.CUSTOM_ABILITIES) {
displayToUuid.clear();
rawData = data;
for (String key : data.keySet()) {
// key format: "displayName\tUUID"
int tabIndex = key.indexOf('\t');
if (tabIndex > 0) {
String displayName = key.substring(0, tabIndex);
String uuid = key.substring(tabIndex + 1);
displayToUuid.put(displayName, uuid);
} else {
displayToUuid.put(key, key);
}
}
if (scroll != null) {
scroll.setList(getFilteredList());
if (selectedDisplayName != null && displayToUuid.containsKey(selectedDisplayName)) {
if (selectedDisplayName != null && rawData.containsKey(selectedDisplayName)) {
scroll.setSelected(selectedDisplayName);
}
}
@@ -226,15 +213,10 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
waitingForLoad = false;
Ability loaded = AbilityController.Instance.fromNBT(compound);
if (loaded != null) {
if (pendingLoadMode == SubGuiAbilityLoadMode.MODE_CLONE) {
// Give it a new UUID so it's a unique inline copy
loaded.setId(UUID.randomUUID().toString());
}
if (parentConfig != null) {
parentConfig.loadAbility(loaded);
} else if (parentAbilities != null) {
parentAbilities.loadAbility(loaded);
parentAbilities.loadAbility(loaded, selectedName);
}
}
close();
@@ -3,18 +3,15 @@ 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;
/**
* Dialog asking the user whether to Clone (inline copy) or Reference the loaded ability.
*/
public class SubGuiAbilityLoadMode extends SubGuiInterface {
public class SubGuiAbilityLoadMode extends SubGuiSimpleChoice {
public static final int MODE_CLONE = 0;
public static final int MODE_REFERENCE = 1;
private int result = -1;
public SubGuiAbilityLoadMode() {
setBackground("menubg.png");
xSize = 200;
@@ -39,18 +36,13 @@ public class SubGuiAbilityLoadMode extends SubGuiInterface {
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0) {
result = MODE_CLONE;
setResult(MODE_CLONE);
close();
} else if (guibutton.id == 1) {
result = MODE_REFERENCE;
setResult(MODE_REFERENCE);
close();
} else if (guibutton.id == 2) {
result = -1;
close();
}
}
public int getResult() {
return result;
}
}
@@ -0,0 +1,277 @@
package noppes.npcs.client.gui.advanced;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
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.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.MagicController;
import noppes.npcs.controllers.data.Magic;
import noppes.npcs.controllers.data.MagicData;
import noppes.npcs.controllers.data.MagicEntry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Sub-GUI for editing magic splits on an Ability.
* Dual-scroll layout: available magics on left, assigned magics on right.
* Only split values (no flat damage) are editable.
*/
public class SubGuiAbilityMagic extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener {
public MagicData magicData;
private GuiCustomScroll availableScroll;
private GuiCustomScroll assignedScroll;
/** Maps display name → magic ID for all available magics. */
private final HashMap<String, Integer> allMagic = new HashMap<>();
/** Maps formatted display string (right scroll) → base display name. */
private final HashMap<String, String> assignedDisplayToName = new HashMap<>();
private String search = "";
private GuiNpcTextField splitField;
/**
* Builds the ability editor's magic field.
* <p>
* This lives here rather than in Ability because the lambdas below carry this class in
* their method descriptors. Ability is a both-side class, and anything reflecting over its
* declared methods on a server - Nashorn's adapter generator, for one - would resolve those
* descriptors and fail to find this client-only type.
*/
public static FieldDef createMagicField(MagicData magicData) {
return FieldDef.subGuiField("ability.magic.editor",
() -> new SubGuiAbilityMagic(magicData.copy()),
gui -> {
MagicData result = ((SubGuiAbilityMagic) gui).magicData;
magicData.getMagics().clear();
for (Map.Entry<Integer, MagicEntry> e : result.getMagics().entrySet()) {
magicData.getMagics().put(e.getKey(), e.getValue());
}
})
.buttonLabel(() -> magicData.isEmpty()
? StatCollector.translateToLocal("ability.magic.usesCaster")
: magicData.getMagics().size() + " Magic(s)")
.tab("General");
}
public SubGuiAbilityMagic(MagicData data) {
this.magicData = data;
setBackground("menubg.png");
xSize = 420;
ySize = 222;
// Load all available magics from the controller
MagicController controller = MagicController.getInstance();
for (Map.Entry<Integer, Magic> entry : controller.magics.entrySet()) {
allMagic.put(entry.getValue().getDisplayName(), entry.getKey());
}
}
@Override
public void initGui() {
super.initGui();
int scrollW = 150;
int scrollH = 140;
int leftX = guiLeft + 10;
int rightX = guiLeft + 250;
int topY = guiTop + 20;
// Title
addLabel(new GuiNpcLabel(0, "ability.magic.editor", guiLeft + 10, guiTop + 5));
// Left scroll: available magics
if (availableScroll == null) {
availableScroll = new GuiCustomScroll(this, 0);
availableScroll.setSize(scrollW, scrollH);
}
availableScroll.guiLeft = leftX;
availableScroll.guiTop = topY;
availableScroll.setList(getSearchList());
addScroll(availableScroll);
// Search field below left scroll
addTextField(new GuiNpcTextField(4, this, fontRendererObj, leftX, topY + scrollH + 5, scrollW, 20, search));
// Right scroll: assigned magics
if (assignedScroll == null) {
assignedScroll = new GuiCustomScroll(this, 1);
assignedScroll.setSize(scrollW, scrollH);
}
assignedScroll.guiLeft = rightX;
assignedScroll.guiTop = topY;
updateAssignedList();
addScroll(assignedScroll);
// Arrow buttons between scrolls
int midX = guiLeft + 175;
addButton(new GuiNpcButton(70, midX, topY + 40, 55, 20, ">"));
addButton(new GuiNpcButton(71, midX, topY + 62, 55, 20, "<"));
// Standardize button
addButton(new GuiNpcButton(72, midX, topY + 90, 55, 20, "magic.dist"));
getButton(72).setHoverText("magic.distInfo");
// Split field below right scroll
int tfY = topY + scrollH + 5;
addLabel(new GuiNpcLabel(5002, "magic.split", rightX - 57, tfY + 5));
splitField = new GuiNpcTextField(73, this, fontRendererObj, rightX, tfY, 60, 20, "");
splitField.setFloatsOnly();
splitField.setMinMaxDefaultFloat(0, 1, 0);
splitField.enabled = false;
addTextField(splitField);
// Done button
addButton(new GuiNpcButton(80, guiLeft + xSize / 2 - 40, guiTop + ySize - 34, 80, 20, "gui.done"));
}
@Override
public void buttonEvent(GuiButton guibutton) {
// Add magic
if (guibutton.id == 70) {
if (availableScroll.hasSelected()) {
String selected = availableScroll.getSelected();
Integer id = allMagic.get(selected);
if (id != null && !magicData.hasMagic(id)) {
magicData.addMagic(id, 0, 0);
}
}
updateAssignedList();
return;
}
// Remove magic
if (guibutton.id == 71) {
if (assignedScroll.hasSelected()) {
Integer id = resolveAssignedId(assignedScroll.getSelected());
if (id != null && magicData.hasMagic(id)) {
magicData.removeMagic(id);
}
}
updateAssignedList();
if (splitField != null) {
splitField.setText("");
splitField.enabled = false;
}
return;
}
// Standardize splits
if (guibutton.id == 72) {
if (magicData.getMagics().size() > 0) {
int count = magicData.getMagics().size();
float stdSplit = 1.0f / count;
for (Integer key : magicData.getMagics().keySet()) {
magicData.getMagic(key).split = stdSplit;
}
// Update field if something is selected
if (assignedScroll.getSelected() != null && splitField != null) {
Integer id = resolveAssignedId(assignedScroll.getSelected());
if (id != null && magicData.hasMagic(id)) {
splitField.setText(magicData.getMagic(id).split + "");
}
}
updateAssignedList();
}
return;
}
// Done
if (guibutton.id == 80) {
close();
return;
}
}
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(4) != null && getTextField(4).isFocused()) {
if (search.equals(getTextField(4).getText()))
return;
search = getTextField(4).getText().toLowerCase();
availableScroll.setList(getSearchList());
availableScroll.resetScroll();
}
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll == assignedScroll) {
if (assignedScroll.getSelected() != null) {
Integer id = resolveAssignedId(assignedScroll.getSelected());
if (id != null && magicData.hasMagic(id)) {
if (splitField != null) {
splitField.setText(magicData.getMagic(id).split + "");
splitField.enabled = true;
}
}
}
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
}
@Override
public void unFocused(GuiNpcTextField textField) {
if (textField.id == 73) {
if (assignedScroll != null && assignedScroll.getSelected() != null) {
Integer id = resolveAssignedId(assignedScroll.getSelected());
if (id != null && magicData.hasMagic(id)) {
try {
float split = Float.parseFloat(textField.getText());
magicData.getMagic(id).split = split;
updateAssignedList();
} catch (NumberFormatException e) {
}
}
}
}
}
private List<String> getSearchList() {
if (search.isEmpty()) {
return new ArrayList<>(allMagic.keySet());
}
List<String> list = new ArrayList<>();
for (String name : allMagic.keySet()) {
if (name.toLowerCase().contains(search))
list.add(name);
}
return list;
}
/**
* Resolves the magic ID from a right-scroll selection (which may be formatted as "Name - XX%").
*/
private Integer resolveAssignedId(String selection) {
if (selection == null) return null;
String baseName = assignedDisplayToName.get(selection);
if (baseName == null) baseName = selection;
return allMagic.get(baseName);
}
private void updateAssignedList() {
assignedDisplayToName.clear();
List<String> selected = new ArrayList<>();
for (Map.Entry<String, Integer> entry : allMagic.entrySet()) {
if (magicData.hasMagic(entry.getValue())) {
float split = magicData.getMagic(entry.getValue()).split;
String display = entry.getKey() + " - " + Math.round(split * 100) + "%";
assignedDisplayToName.put(display, entry.getKey());
selected.add(display);
}
}
if (assignedScroll != null) {
assignedScroll.setList(selected);
}
}
}
@@ -21,6 +21,7 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGui
private final Ability ability;
private final IAbilityConfigCallback callback;
private final Set<String> existingNames;
private boolean saved = false;
public SubGuiAbilitySaveConfirm(Ability ability) {
this(ability, null, null);
@@ -68,18 +69,27 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGui
}
private void doSave() {
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
saved = true;
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false)));
if (callback != null) {
callback.onAbilitySaved(ability);
}
close();
}
public boolean wasSaved() {
return saved;
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiDuplicateNameConfirm) {
if (((SubGuiDuplicateNameConfirm) subgui).isConfirmed()) {
SubGuiDuplicateNameConfirm confirm = (SubGuiDuplicateNameConfirm) subgui;
if (confirm.isConfirmed()) {
doSave();
} else if (confirm.isBack()) {
// Keep this save-confirm dialog open.
return;
} else {
close();
}
@@ -0,0 +1,186 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket;
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.GuiNpcTextField;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IScrollData;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.constants.EnumScrollData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
/**
* Simple ability name picker with optional filter mode.
* Shows custom, built-in, or all abilities in a scroll list with search.
* Returns the selected ability name.
*/
public class SubGuiAbilitySelect extends SubGuiInterface implements ICustomScrollListener, IScrollData {
/** Show all abilities (custom + built-in). */
public static final int FILTER_ALL = 0;
/** Show only custom abilities. */
public static final int FILTER_CUSTOM_ONLY = 1;
/** Show only built-in abilities. */
public static final int FILTER_BUILTIN_ONLY = 2;
private GuiCustomScroll scroll;
private HashMap<String, Integer> customData = new HashMap<>();
private HashMap<String, Integer> builtInData = new HashMap<>();
private String selectedName = null;
private String search = "";
private final int filterMode;
public SubGuiAbilitySelect() {
this(FILTER_ALL);
}
public SubGuiAbilitySelect(int filterMode) {
this.filterMode = filterMode;
setBackground("menubg.png");
xSize = 220;
ySize = 216;
PacketClient.sendClient(new CustomAbilitiesGetPacket());
}
@Override
public void initGui() {
super.initGui();
int y = guiTop + 5;
addLabel(new GuiNpcLabel(0, "ability.select", guiLeft + 10, y));
y += 14;
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
scroll.setSize(200, 140);
}
scroll.guiLeft = guiLeft + 10;
scroll.guiTop = y;
scroll.setList(getFilteredList());
if (selectedName != null) {
scroll.setSelected(selectedName);
}
addScroll(scroll);
y += 143;
addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 10, y, 200, 20, search));
y += 24;
addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "gui.select"));
addButton(new GuiNpcButton(2, guiLeft + 115, y, 95, 20, "gui.cancel"));
getButton(0).setEnabled(selectedName != null);
}
private List<String> getFilteredList() {
HashMap<String, Integer> merged = new HashMap<>();
if (filterMode != FILTER_BUILTIN_ONLY) {
merged.putAll(customData);
}
if (filterMode != FILTER_CUSTOM_ONLY) {
merged.putAll(builtInData);
}
List<String> list = new ArrayList<>();
for (Map.Entry<String, Integer> entry : merged.entrySet()) {
String name = entry.getKey();
// Only show NPC-valid abilities (NPC_ONLY or BOTH)
UserType ut = UserType.fromOrdinal(entry.getValue());
if (!ut.allowsNpc()) continue;
if (!search.isEmpty() && !name.toLowerCase().contains(search.toLowerCase())) {
continue;
}
list.add(name);
}
return list;
}
@Override
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
if (id == 0 && selectedName != null) {
close();
} else if (id == 2) {
selectedName = null;
close();
}
}
@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 customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
if (scroll.id == 0) {
selectedName = scroll.getSelected();
initGui();
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
if (scroll.id == 0 && selection != null && !selection.isEmpty()) {
selectedName = selection;
close();
}
}
@Override
public void setData(Vector<String> list, HashMap<String, Integer> data, EnumScrollData type) {
if (type == EnumScrollData.CUSTOM_ABILITIES) {
customData = data;
} else if (type == EnumScrollData.BUILTIN_ABILITIES) {
builtInData = data;
}
if (scroll != null) {
scroll.setList(getFilteredList());
if (selectedName != null) {
scroll.setSelected(selectedName);
}
}
initGui();
}
@Override
public void setSelected(String selected) {
this.selectedName = selected;
if (scroll != null) {
scroll.setSelected(selected);
}
}
/**
* Get the selected ability name after the dialog closes.
* Returns null if cancelled.
*/
public String getSelectedName() {
return selectedName;
}
}
@@ -1,6 +1,7 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.util.Register;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.resources.I18n;
import noppes.npcs.client.gui.util.GuiCustomScroll;
@@ -11,6 +12,7 @@ import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -20,6 +22,11 @@ import java.util.Map;
*/
public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener {
private static final int BTN_ADD = 0;
private static final int BTN_CANCEL = 1;
private static final int BTN_SCROLL_TYPE = 2;
private static final int TF_SEARCH = 10;
private GuiCustomScroll scroll;
private final HashMap<String, String> displayNameToTypeId = new HashMap<>();
private final HashMap<String, String> allDisplayNameToTypeId = new HashMap<>();
@@ -36,62 +43,152 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS
public void initGui() {
super.initGui();
addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 5, guiTop + 5, 190, 18, search));
int y = guiTop + 5;
// Scroll type filter button
addButton(new GuiNpcButton(BTN_SCROLL_TYPE, guiLeft + 5, y, 190, 20, GuiNPCAbilities.scrollType.toString()));
y += 24;
// Search bar
addTextField(new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, guiLeft + 5, y, 190, 18, search));
y += 20;
// Scroll list (shortened to fit filter button within original ySize)
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
scroll.setSize(190, 145);
scroll.setSize(190, 121);
}
scroll.guiLeft = guiLeft + 5;
scroll.guiTop = guiTop + 26;
scroll.guiTop = y;
addScroll(scroll);
buildAllTypes();
scroll.setList(getFilteredTypeList());
scroll.setUnsortedList(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"));
addButton(new GuiNpcButton(BTN_ADD, guiLeft + 5, guiTop + 188, 90, 20, "gui.add"));
getButton(BTN_ADD).setEnabled(scroll.hasSelected());
addButton(new GuiNpcButton(BTN_CANCEL, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel"));
}
private void buildAllTypes() {
allDisplayNameToTypeId.clear();
String[] types = AbilityController.Instance.getTypes();
for (String typeId : types) {
// Never show built-in types — they are immutable and cannot be created
if (AbilityController.Instance.isBuiltInType(typeId))
continue;
// Apply scroll type filter
if (!matchesScrollType(typeId))
continue;
String displayName = I18n.format(typeId);
if (typeId.equals("ability.cnpc.custom")) {
displayName = "\u00A7d" + displayName;
} else if (AbilityController.Instance.isConcurrentCapableType(typeId)) {
displayName = "\u00A7b" + displayName;
}
allDisplayNameToTypeId.put(displayName, typeId);
}
}
private boolean matchesScrollType(String typeId) {
GuiNPCAbilities.ScrollType type = GuiNPCAbilities.scrollType;
if (type == GuiNPCAbilities.ScrollType.ALL) {
return true;
} else if (type == GuiNPCAbilities.ScrollType.CNPC) {
return typeId.startsWith("ability.cnpc.");
} else if (type == GuiNPCAbilities.ScrollType.MODDED) {
if (!Register.isEmpty("ability")) {
List<String> registerList = Register.REGISTERED_NAMESPACES.get("ability");
if (!registerList.isEmpty()) {
String namespace = registerList.get(GuiNPCAbilities.modIndex);
return typeId.startsWith("ability." + namespace + ".");
}
}
return false;
}
return true;
}
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)) {
String stripped = displayName.replaceAll("\u00A7.", "");
if (search.isEmpty() || stripped.toLowerCase().contains(search) || entry.getValue().toLowerCase().contains(search)) {
list.add(displayName);
displayNameToTypeId.put(displayName, entry.getValue());
}
}
Collections.sort(list, (a, b) -> String.CASE_INSENSITIVE_ORDER.compare(
a.replaceAll("\u00A7.", ""), b.replaceAll("\u00A7.", "")));
// Pin Custom Ability to top of list
String customEntry = null;
for (String name : list) {
String tid = displayNameToTypeId.get(name);
if (tid != null && tid.equals("ability.cnpc.custom")) {
customEntry = name;
break;
}
}
if (customEntry != null) {
list.remove(customEntry);
list.add(0, customEntry);
}
return list;
}
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0 && scroll.hasSelected()) {
int id = guibutton.id;
if (id == BTN_ADD && scroll.hasSelected()) {
String displayName = scroll.getSelected();
selectedTypeId = displayNameToTypeId.get(displayName);
close();
} else if (guibutton.id == 1) {
} else if (id == BTN_CANCEL) {
selectedTypeId = null;
close();
} else if (id == BTN_SCROLL_TYPE) {
cycleScrollType();
if (scroll != null) {
scroll.resetScroll();
}
initGui();
}
}
private void cycleScrollType() {
if (GuiNPCAbilities.scrollType != GuiNPCAbilities.ScrollType.MODDED) {
GuiNPCAbilities.ScrollType[] values = GuiNPCAbilities.ScrollType.values();
GuiNPCAbilities.ScrollType next = values[(GuiNPCAbilities.scrollType.ordinal() + 1) % values.length];
if (next == GuiNPCAbilities.ScrollType.MODDED && Register.isEmpty("ability")) {
next = GuiNPCAbilities.ScrollType.ALL;
}
GuiNPCAbilities.scrollType = next;
} else {
List<String> list = Register.REGISTERED_NAMESPACES.get("ability");
if (list != null && !list.isEmpty()) {
if (GuiNPCAbilities.modIndex == list.size() - 1) {
GuiNPCAbilities.scrollType = GuiNPCAbilities.ScrollType.ALL;
} else {
GuiNPCAbilities.modIndex = (GuiNPCAbilities.modIndex + 1) % list.size();
}
} else {
GuiNPCAbilities.modIndex = 0;
GuiNPCAbilities.scrollType = GuiNPCAbilities.ScrollType.ALL;
}
}
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 0) {
getButton(0).setEnabled(scroll.hasSelected());
getButton(BTN_ADD).setEnabled(scroll.hasSelected());
}
}
@@ -106,9 +203,9 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS
@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();
if (getTextField(TF_SEARCH) != null && getTextField(TF_SEARCH).isFocused()) {
if (!search.equals(getTextField(TF_SEARCH).getText())) {
search = getTextField(TF_SEARCH).getText().toLowerCase();
scroll.setList(getFilteredTypeList());
scroll.resetScroll();
}
@@ -88,12 +88,15 @@ public class SubGuiAbilityVariantSelect extends SubGuiInterface implements ICust
scroll.setSize(190, 155);
// Mark blank separators and group headers as non-interactive colored entries
scroll.nonInteractive.add("");
scroll.colors.put("", 0x000000);
if (lastGroup != null) {
for (int i = 0; i < variants.size(); i++) {
String group = variants.get(i).getGroup();
if (group != null)
if (group != null) {
scroll.nonInteractive.add(group);
scroll.colors.put(group, 0xFFFF00); // Yellow
}
}
}
@@ -0,0 +1,92 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.AbilityController;
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;
import java.util.Set;
/**
* Selector for chained ability presets. Lists chain names from synced data.
* Returns the selected chain name via {@link #getSelectedName()}.
*/
public class SubGuiChainSelect extends SubGuiInterface implements ICustomScrollListener {
private GuiCustomScroll scroll;
private String selectedName = null;
public SubGuiChainSelect() {
setBackground("menubg.png");
xSize = 220;
ySize = 200;
}
@Override
public void initGui() {
super.initGui();
int y = guiTop + 5;
addLabel(new GuiNpcLabel(0, "ability.loadChain", guiLeft + 10, y));
y += 14;
List<String> names = getChainNames();
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
scroll.setSize(200, 130);
}
scroll.guiLeft = guiLeft + 10;
scroll.guiTop = y;
scroll.setList(names);
if (selectedName != null) {
scroll.setSelected(selectedName);
}
addScroll(scroll);
y += 133;
addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "gui.select"));
addButton(new GuiNpcButton(1, guiLeft + 115, y, 95, 20, "gui.cancel"));
getButton(0).setEnabled(selectedName != null);
}
private List<String> getChainNames() {
Set<String> names = AbilityController.Instance.getChainedAbilityNamesSet();
return new ArrayList<>(names);
}
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0 && selectedName != null) {
close();
} else if (guibutton.id == 1) {
selectedName = null;
close();
}
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 0) {
selectedName = guiCustomScroll.getSelected();
initGui();
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 0 && selection != null && !selection.isEmpty()) {
selectedName = selection;
close();
}
}
public String getSelectedName() {
return selectedName;
}
}
@@ -0,0 +1,945 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityAction;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.controllers.data.ChainedAbilityScript;
import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry;
import kamkeel.npcs.controllers.data.ability.data.AbilityIconData;
import kamkeel.npcs.controllers.data.ability.gui.IChainedAbilityFieldProvider;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.builder.GuiFieldBuilder;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
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.GuiScrollWindow;
import noppes.npcs.client.gui.util.*;
import java.util.ArrayList;
import noppes.npcs.client.gui.util.IChainedAbilityConfigCallback;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BooleanSupplier;
import static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS;
/**
* SubGui for editing a {@link ChainedAbility}.
* Core tabs: General, Entries, Conditions.
* Additional tabs are injected dynamically by {@link IChainedAbilityFieldProvider}s.
*/
public class SubGuiChainedAbilityConfig extends SubGuiInterface implements ITextfieldListener, ISubGuiListener, IAbilityConfigCallback {
// ── Declarative field ID ranges ──────────────────────────────────────────
private static final int DECLARATIVE_ID_START = 1000;
private static final int CLEAR_ID_START = 2000;
private static final int LABEL_ID_START = 3000;
// ── Tab constants (core tabs) ────────────────────────────────────────────
private static final int TAB_GENERAL = 0;
private static final int TAB_ENTRIES = 1;
private static final int TAB_TARGET = 2;
private static final int CORE_TAB_COUNT = 3;
// ── Tab button IDs ────────────────────────────────────────────────────────
private static final int BTN_TAB_GENERAL = 90;
private static final int BTN_TAB_ENTRIES = 91;
private static final int BTN_TAB_TARGET = 92;
private static final int BTN_TAB_EXTRA_BASE = 93;
private static final int BTN_SCRIPT = -999;
private static final int BTN_CLOSE = -1000;
// ── Entries tab: per-entry ID encoding ─────────────────────────────────────
// Actual ID = ENTRY_BASE + i * ENTRY_STRIDE + offset
// offset 0 = name/select button, 1 = delay text field, 2 = up, 3 = down, 4 = delete
private static final int ENTRY_BASE = 100;
private static final int ENTRY_END = 200;
private static final int ENTRY_STRIDE = 10;
private static final int BTN_ADD_ENTRY = 200;
// ── Conditions tab: per-condition ID encoding ─────────────────────────────
// Actual ID = COND_BASE + i * COND_STRIDE + offset
// offset 0 = name/click, 1 = edit, 2 = delete
private static final int COND_BASE = 50;
private static final int COND_STRIDE = 10;
private static final int COND_END = COND_BASE + MAX_CONDITIONS * COND_STRIDE; // 50 + N*10
private static final int BTN_ADD_COND = COND_END;
// ── Layout constants ──────────────────────────────────────────────────────
private static final int L_LABEL_X = 5;
private static final int ROW_H = 24;
private static final int MAX_ENTRIES = 10;
private final ChainedAbility chain;
private final IChainedAbilityConfigCallback callback;
private final boolean npcContext;
private final boolean readOnlyEntries;
private final List<AbilityAction> npcSlots;
private int activeTab = TAB_GENERAL;
private List<FieldDef> fieldDefs;
private List<ChainedAbilityEntry> entries;
private List<AbilityCondition> conditions;
// Dynamic tabs injected by field providers (e.g., "Icon")
private List<String> extraTabs = new ArrayList<>();
private GuiFieldBuilder builder;
private float[] tabScrollY;
// Entry editing
private int editingEntryIndex = -1;
private String pendingTypeId;
private boolean editingParentAbility = false;
// Condition editing
private int editingConditionIndex = -1;
// Save only on explicit X button, not ESC
private boolean saveOnClose = false;
// Track consumed NPC slot indices for deferred removal on save
private final List<Integer> consumedSlotIndices = new ArrayList<>();
public SubGuiChainedAbilityConfig(ChainedAbility chain, IChainedAbilityConfigCallback callback) {
this(chain, callback, false, null, false);
}
public SubGuiChainedAbilityConfig(ChainedAbility chain, IChainedAbilityConfigCallback callback,
boolean npcContext, List<AbilityAction> npcSlots) {
this(chain, callback, npcContext, npcSlots, false);
}
public SubGuiChainedAbilityConfig(ChainedAbility chain, IChainedAbilityConfigCallback callback,
boolean npcContext, List<AbilityAction> npcSlots, boolean readOnlyEntries) {
this.chain = chain;
this.callback = callback;
this.npcContext = npcContext;
this.readOnlyEntries = readOnlyEntries;
this.npcSlots = npcSlots;
this.entries = new ArrayList<>(chain.getEntries());
this.conditions = new ArrayList<>(chain.getConditions());
buildFieldDefs();
setBackground("menubg.png", 217);
xSize = 356;
ySize = 200;
}
private void buildFieldDefs() {
fieldDefs = new ArrayList<>();
fieldDefs.add(FieldDef.stringField("gui.name", chain::getName, chain::setName).tab("General"));
fieldDefs.add(FieldDef.stringField("gui.displayName", chain::getRawDisplayName, chain::setDisplayName).tab("General"));
// Computed "Valid For" label (derived from child abilities)
fieldDefs.add(FieldDef.labelField("ability.validFor", () -> {
UserType ut = computeAllowedBy();
return "\u00A7e" + StatCollector.translateToLocal("ability.userType." + ut.name());
}).tab("General"));
fieldDefs.add(FieldDef.boolField("gui.enabled", chain::isEnabled, chain::setEnabled).tab("General"));
fieldDefs.add(FieldDef.intField("ability.weight", chain::getWeight, chain::setWeight).range(1, 100).tab("General"));
fieldDefs.add(FieldDef.boolField("ability.windUpAll", chain::isWindUpAll, chain::setWindUpAll).tab("General"));
fieldDefs.add(FieldDef.row(
FieldDef.intField("ability.cooldown", chain::getCooldownTicks, chain::setCooldownTicks).range(0, 12000),
FieldDef.boolField("ability.perAbilityCooldown", chain::isPerAbilityCooldown, chain::setPerAbilityCooldown)
).tab("General"));
fieldDefs.add(FieldDef.boolField("ability.ignoreCooldown", chain::isIgnoreCooldown, chain::setIgnoreCooldown).tab("General"));
// ── Target tab ───────────────────────────────────────────────
fieldDefs.add(FieldDef.row(
FieldDef.floatField("ability.minRange", chain::getMinRange, chain::setMinRange).range(0, 64),
FieldDef.floatField("ability.maxRange", chain::getMaxRange, chain::setMaxRange).range(0, 64)
).tab("Target"));
// ── Icon tab ──────────────────────────────────────────────
AbilityIconData chainIcon = AbilityIconData.fromChainedAbility(chain);
BooleanSupplier isCustomIcon = chainIcon::isEnabled;
fieldDefs.add(FieldDef.section("ability.section.icon").tab("Icon"));
fieldDefs.add(FieldDef.boolField("ability.hasIcon", chainIcon::isEnabled, chainIcon::setEnabled).tab("Icon"));
fieldDefs.add(FieldDef.row(
FieldDef.intField("gui.width", chainIcon::getWidth, chainIcon::setWidth).range(1, 256),
FieldDef.intField("gui.height", chainIcon::getHeight, chainIcon::setHeight).range(1, 256)
).tab("Icon").visibleWhen(isCustomIcon));
fieldDefs.add(FieldDef.floatField("gui.scale", chainIcon::getScale, chainIcon::setScale).tab("Icon").range(0.1f, 10.0f).visibleWhen(isCustomIcon));
fieldDefs.add(FieldDef.intField("ability.icon.layers", chainIcon::getLayerCount, chainIcon::setLayerCount)
.tab("Icon").range(1, AbilityIconData.MAX_LAYERS).visibleWhen(isCustomIcon));
for (int i = 0; i < AbilityIconData.MAX_LAYERS; i++) {
final int idx = i;
java.util.function.BooleanSupplier layerVisible = () -> isCustomIcon.getAsBoolean() && chainIcon.getLayerCount() > idx;
String sectionLabel = net.minecraft.util.StatCollector.translateToLocal("ability.icon.layer") + " " + (idx + 1);
fieldDefs.add(FieldDef.section(sectionLabel).tab("Icon").visibleWhen(layerVisible));
fieldDefs.add(FieldDef.textureSubGui("gui.texture",
() -> chainIcon.getLayer(idx).texture,
t -> chainIcon.setLayerTexture(idx, t))
.tab("Icon").visibleWhen(layerVisible));
fieldDefs.add(FieldDef.row(
FieldDef.intField("ability.icon.x",
() -> chainIcon.getLayer(idx).iconX,
x -> chainIcon.setLayerIconX(idx, x)).range(0, 4096),
FieldDef.intField("ability.icon.y",
() -> chainIcon.getLayer(idx).iconY,
y -> chainIcon.setLayerIconY(idx, y)).range(0, 4096)
).tab("Icon").visibleWhen(layerVisible));
fieldDefs.add(FieldDef.colorSubGui("ability.icon.tint",
() -> chainIcon.getLayer(idx).tintColor,
c -> chainIcon.setLayerTintColor(idx, c))
.tab("Icon").visibleWhen(layerVisible));
}
// Animation
fieldDefs.add(FieldDef.section("Animation").tab("Icon").visibleWhen(isCustomIcon));
fieldDefs.add(FieldDef.boolField("gui.animated", chainIcon::isAnimated, chainIcon::setAnimated).tab("Icon").hover("gui.animated.hover").visibleWhen(isCustomIcon));
fieldDefs.add(FieldDef.intField("gui.frameCount", chainIcon::getFrameCount, chainIcon::setFrameCount)
.tab("Icon").range(1, 256).visibleWhen(() -> isCustomIcon.getAsBoolean() && chainIcon.isAnimated()));
fieldDefs.add(FieldDef.intField("gui.frameTime", chainIcon::getFrameTime, chainIcon::setFrameTime)
.tab("Icon").range(1, 100).visibleWhen(() -> isCustomIcon.getAsBoolean() && chainIcon.isAnimated()));
// External field providers (e.g., DBC Addon injecting a "DBC" tab)
if (AbilityController.Instance != null) {
for (IChainedAbilityFieldProvider provider : AbilityController.Instance.getChainedFieldProviders()) {
provider.addFieldDefinitions(chain, fieldDefs);
}
}
// Collect extra tab names from provider-injected fields
Set<String> tabNames = new LinkedHashSet<>();
for (FieldDef def : fieldDefs) {
String tab = def.getTab();
if (tab != null && !tab.isEmpty() && !"General".equals(tab) && !"Target".equals(tab)) {
tabNames.add(tab);
}
}
extraTabs = new ArrayList<>(tabNames);
// Size scroll array for all tabs
tabScrollY = new float[CORE_TAB_COUNT + extraTabs.size()];
}
// ═══════════════════════════════════════════════════════════════════════════
// COMPUTED USERTYPE
// ═══════════════════════════════════════════════════════════════════════════
/**
* Compute the allowed UserType from the current (possibly modified) entries list.
* Mirrors ChainedAbility.getAllowedBy() but uses the local entries.
*/
private UserType computeAllowedBy() {
if (entries.isEmpty()) return UserType.BOTH;
boolean allAllowPlayer = true;
boolean allAllowNpc = true;
for (ChainedAbilityEntry entry : entries) {
Ability a = entry.resolve();
if (a == null) continue;
UserType ut = a.getAllowedBy();
if (!ut.allowsPlayer()) allAllowPlayer = false;
if (!ut.allowsNpc()) allAllowNpc = false;
}
if (allAllowPlayer && allAllowNpc) return UserType.BOTH;
if (allAllowPlayer) return UserType.PLAYER_ONLY;
if (allAllowNpc) return UserType.NPC_ONLY;
return UserType.NONE;
}
// ═══════════════════════════════════════════════════════════════════════════
// INIT GUI
// ═══════════════════════════════════════════════════════════════════════════
@Override
public void initGui() {
// Commit any focused text field before rebuilding
GuiNpcTextField.unfocus();
// Save scroll position
GuiScrollWindow oldSw = getScrollableGui(0);
if (oldSw != null && activeTab < tabScrollY.length) {
tabScrollY[activeTab] = oldSw.nextScrollY;
}
super.initGui();
// Tab buttons — core tabs
GuiMenuTopButton generalTab = new GuiMenuTopButton(BTN_TAB_GENERAL, guiLeft + 4, guiTop - 17, "menu.general");
generalTab.active = (activeTab == TAB_GENERAL);
addTopButton(generalTab);
GuiMenuTopButton entriesTab = new GuiMenuTopButton(BTN_TAB_ENTRIES, generalTab, "ability.entries");
entriesTab.active = (activeTab == TAB_ENTRIES);
addTopButton(entriesTab);
GuiMenuTopButton targetTab = new GuiMenuTopButton(BTN_TAB_TARGET, entriesTab, "script.target");
targetTab.active = (activeTab == TAB_TARGET);
addTopButton(targetTab);
// Dynamic extra tabs from field providers
GuiMenuTopButton prevTab = targetTab;
for (int i = 0; i < extraTabs.size(); i++) {
int tabIndex = CORE_TAB_COUNT + i;
GuiMenuTopButton extraTab = new GuiMenuTopButton(BTN_TAB_EXTRA_BASE + i, prevTab, extraTabs.get(i));
extraTab.active = (activeTab == tabIndex);
addTopButton(extraTab);
prevTab = extraTab;
}
GuiMenuTopButton closeBtn = new GuiMenuTopButton(BTN_CLOSE, guiLeft + xSize - 22, guiTop - 17, "X");
addTopButton(closeBtn);
GuiMenuTopButton scriptBtn = new GuiMenuTopButton(BTN_SCRIPT, "script.scripts", closeBtn);
addTopButton(scriptBtn);
// Scroll window dimensions
int swX = guiLeft + 4;
int swY = guiTop + 5;
int swW = xSize - 8;
int swH = ySize - 10;
if (activeTab == TAB_GENERAL) {
buildFieldDefTab("General", swX, swY, swW, swH);
} else if (activeTab == TAB_ENTRIES) {
buildEntriesTab(swX, swY, swW, swH);
} else if (activeTab == TAB_TARGET) {
buildTargetTab(swX, swY, swW, swH);
} else if (activeTab >= CORE_TAB_COUNT) {
int extraIndex = activeTab - CORE_TAB_COUNT;
if (extraIndex < extraTabs.size()) {
buildFieldDefTab(extraTabs.get(extraIndex), swX, swY, swW, swH);
}
}
}
// ═══════════════════════════════════════════════════════════════════════════
// FIELDDEF-BASED TAB (General + dynamic provider tabs)
// ═══════════════════════════════════════════════════════════════════════════
private void buildFieldDefTab(String tabName, int swX, int swY, int swW, int swH) {
List<FieldDef> tabFields = new ArrayList<>();
for (FieldDef def : fieldDefs) {
if (tabName.equals(def.getTab()) && def.isVisible()) {
tabFields.add(def);
}
}
builder = new GuiFieldBuilder(this, fontRendererObj);
builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, LABEL_ID_START);
builder.startY(5);
GuiScrollWindow sw = builder.buildScrollWindow(tabFields, swX, swY, swW, swH);
restoreScroll(sw);
}
// ═══════════════════════════════════════════════════════════════════════════
// ENTRIES TAB
// ═══════════════════════════════════════════════════════════════════════════
private void buildEntriesTab(int swX, int swY, int swW, int swH) {
GuiScrollWindow sw = new GuiScrollWindow(this, swX, swY, swW, swH, 0);
sw.backgroundColor = 0x88000000;
addScrollableGui(0, sw);
int y = 5;
int labelCounter = 0;
for (int i = 0; i < entries.size() && i < MAX_ENTRIES; i++) {
ChainedAbilityEntry entry = entries.get(i);
// Index label
sw.addLabel(new GuiNpcLabel(labelCounter++, (i + 1) + ".", L_LABEL_X, y + 5, 0xFFFFFF));
// Ability reference/inline button
String btnLabel;
if (entry.isInline()) {
Ability a = entry.getInlineAbility();
btnLabel = a != null ? a.getDisplayName() : "\u00A7cEmpty";
} else {
String refName = entry.getAbilityReference();
if (refName == null || refName.isEmpty()) {
btnLabel = StatCollector.translateToLocal("gui.select") + "...";
} else {
Ability resolved = entry.resolve();
btnLabel = "\u00A7e> " + (resolved != null ? resolved.getDisplayName() : refName);
}
}
GuiNpcButton entryBtn = new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE, L_LABEL_X + 15, y, 140, 20, btnLabel);
if (readOnlyEntries) {
entryBtn.setEnabled(false);
}
sw.addButton(entryBtn);
if (!readOnlyEntries) {
// Check if this entry is concurrent-active (delay disabled)
Ability resolvedAbility = entry.resolve();
boolean isConcurrentActive = resolvedAbility != null
&& resolvedAbility.isConcurrentCapable()
&& entry.isConcurrentEnabled();
// Delay label + field
sw.addLabel(new GuiNpcLabel(labelCounter++, "ability.delay", L_LABEL_X + 160, y + 5,
isConcurrentActive ? 0x555555 : 0xAAAAAA));
GuiNpcTextField delayField = new GuiNpcTextField(ENTRY_BASE + i * ENTRY_STRIDE + 1, this, fontRendererObj,
L_LABEL_X + 195, y, 40, 20, String.valueOf(entry.getDelayTicks()));
delayField.setIntegersOnly();
delayField.setMinMaxDefault(0, 6000, 0);
if (isConcurrentActive) {
delayField.setEnabled(false);
}
sw.addTextField(delayField);
// Up button
if (i > 0) {
sw.addButton(new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 2, L_LABEL_X + 240, y, 20, 20, "\u2191"));
}
// Down button
if (i < entries.size() - 1) {
sw.addButton(new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 3, L_LABEL_X + 263, y, 20, 20, "\u2193"));
}
// Concurrent toggle (only shown if resolved ability is concurrent-capable, never for first entry)
if (i > 0 && resolvedAbility != null && resolvedAbility.isConcurrentCapable()) {
String cLabel = entry.isConcurrentEnabled() ? "\u00A7bC" : "\u00A77C";
GuiNpcButton cBtn = new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 5, L_LABEL_X + 288, y, 20, 20, cLabel);
cBtn.setHoverText("ability.hover.concurrent");
sw.addButton(cBtn);
}
// Delete button
sw.addButton(new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 4, L_LABEL_X + 313, y, 20, 20, "X"));
} else {
// Read-only: show delay as label only
int delay = entry.getDelayTicks();
if (delay > 0) {
sw.addLabel(new GuiNpcLabel(labelCounter++, delay + "t", L_LABEL_X + 165, y + 5, 0x888888));
}
}
y += ROW_H;
}
// Add entry button (hidden in read-only mode)
if (!readOnlyEntries && entries.size() < MAX_ENTRIES) {
sw.addButton(new GuiNpcButton(BTN_ADD_ENTRY, L_LABEL_X, y, 80, 20, "gui.add"));
y += ROW_H;
}
sw.maxScrollY = Math.max(y - swH, 0);
restoreScroll(sw);
}
// ═══════════════════════════════════════════════════════════════════════════
// TARGET TAB (FieldDef fields + conditions list)
// ═══════════════════════════════════════════════════════════════════════════
private void buildTargetTab(int swX, int swY, int swW, int swH) {
// Build FieldDef fields (ranges, Valid For) first
List<FieldDef> tabFields = new ArrayList<>();
for (FieldDef def : fieldDefs) {
if ("Target".equals(def.getTab()) && def.isVisible()) {
tabFields.add(def);
}
}
builder = new GuiFieldBuilder(this, fontRendererObj);
builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, LABEL_ID_START);
builder.startY(5);
GuiScrollWindow sw = builder.buildScrollWindow(tabFields, swX, swY, swW, swH);
// Append conditions list below the FieldDef fields
int y = builder.getLastBuildY();
int condY = renderConditions(sw, y, builder.getNextLabelId());
sw.maxScrollY = Math.max(condY - swH, 0);
restoreScroll(sw);
}
private int renderConditions(GuiScrollWindow sw, int y, int labelCounter) {
y += 3;
sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55));
y += 15;
for (int i = 0; i < conditions.size() && i < MAX_CONDITIONS; i++) {
AbilityCondition cond = conditions.get(i);
String condName = getConditionDisplayName(cond);
sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName));
sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit"));
sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X"));
y += 22;
}
if (conditions.size() < MAX_CONDITIONS) {
sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add"));
y += ROW_H;
}
return y;
}
private String getConditionDisplayName(AbilityCondition cond) {
if (cond == null) return "None";
String name = cond.getName();
return StatCollector.translateToLocal(name);
}
// ═══════════════════════════════════════════════════════════════════════════
// SCROLL RESTORE
// ═══════════════════════════════════════════════════════════════════════════
private void restoreScroll(GuiScrollWindow sw) {
if (activeTab < tabScrollY.length) {
float restored = Math.min(tabScrollY[activeTab], sw.maxScrollY);
sw.nextScrollY = restored;
sw.scrollY = restored;
}
}
// ═══════════════════════════════════════════════════════════════════════════
// BUTTON EVENTS
// ═══════════════════════════════════════════════════════════════════════════
@Override
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
// Tab switching — core tabs
if (id == BTN_TAB_GENERAL) {
activeTab = TAB_GENERAL;
initGui();
return;
}
if (id == BTN_TAB_ENTRIES) {
activeTab = TAB_ENTRIES;
initGui();
return;
}
if (id == BTN_TAB_TARGET) {
activeTab = TAB_TARGET;
initGui();
return;
}
if (id == BTN_SCRIPT) {
GuiScriptInterface.open(parent, new ChainedAbilityScript(chain.getId()));
return;
}
if (id == BTN_CLOSE) {
saveOnClose = true;
close();
return;
}
// Tab switching — extra tabs
if (id >= BTN_TAB_EXTRA_BASE && id < BTN_TAB_EXTRA_BASE + extraTabs.size()) {
activeTab = CORE_TAB_COUNT + (id - BTN_TAB_EXTRA_BASE);
initGui();
return;
}
// Entries tab
if (activeTab == TAB_ENTRIES) {
if (handleEntryButton(id)) return;
}
// Target tab (includes conditions)
if (activeTab == TAB_TARGET) {
if (handleConditionButton(id)) return;
}
// FieldDef-based tabs (General + extra tabs) — declarative field handling
if (isFieldDefTab() && builder != null) {
if (builder.handleButtonEvent(id, guibutton)) {
if (!hasSubGui()) {
initGui();
}
return;
}
}
}
/**
* Whether the current active tab uses the declarative FieldDef system.
*/
private boolean isFieldDefTab() {
return activeTab == TAB_GENERAL || activeTab == TAB_TARGET || activeTab >= CORE_TAB_COUNT;
}
private boolean handleEntryButton(int id) {
// Add entry
if (id == BTN_ADD_ENTRY) {
if (entries.size() < MAX_ENTRIES) {
// Both contexts use entry source selector; hide NPC option in global context
setSubGui(new SubGuiChainedEntrySource(npcContext));
}
return true;
}
// Per-entry buttons (ENTRY_BASE to ENTRY_END)
if (id >= ENTRY_BASE && id < ENTRY_END) {
int entryIndex = (id - ENTRY_BASE) / ENTRY_STRIDE;
int action = (id - ENTRY_BASE) % ENTRY_STRIDE;
if (entryIndex < 0 || entryIndex >= entries.size()) return false;
switch (action) {
case 0: // Entry name button — reference: clone/modify dialog; inline: edit config
ChainedAbilityEntry clickedEntry = entries.get(entryIndex);
if (clickedEntry.isReference()) {
// Built-in abilities are always references — no editing allowed
Ability refResolved = clickedEntry.resolve();
if (refResolved != null && refResolved.isBuiltIn()) return true;
editingEntryIndex = entryIndex;
setSubGui(new SubGuiAbilityEditMode());
} else if (clickedEntry.isInline() && clickedEntry.getInlineAbility() != null) {
Ability inlineAbility = clickedEntry.getInlineAbility();
if (inlineAbility.isBuiltIn()) return true;
editingEntryIndex = entryIndex;
setSubGui(new SubGuiAbilityConfig(inlineAbility, this));
}
return true;
case 2: // Up
if (entryIndex > 0) {
// Commit any focused delay field before reordering
GuiNpcTextField.unfocus();
ChainedAbilityEntry entry = entries.remove(entryIndex);
entries.add(entryIndex - 1, entry);
// Can't be concurrent at position 0
if (entryIndex - 1 == 0) {
entry.setConcurrentEnabled(false);
}
initGui();
}
return true;
case 3: // Down
if (entryIndex < entries.size() - 1) {
// Commit any focused delay field before reordering
GuiNpcTextField.unfocus();
ChainedAbilityEntry entry = entries.remove(entryIndex);
entries.add(entryIndex + 1, entry);
initGui();
}
return true;
case 4: // Delete
// Commit any focused delay field before removing
GuiNpcTextField.unfocus();
entries.remove(entryIndex);
initGui();
return true;
case 5: // Concurrent toggle
ChainedAbilityEntry toggleEntry = entries.get(entryIndex);
boolean newState = !toggleEntry.isConcurrentEnabled();
toggleEntry.setConcurrentEnabled(newState);
if (newState) {
toggleEntry.setDelayTicks(0);
}
initGui();
return true;
}
}
return false;
}
private boolean handleConditionButton(int id) {
if (id >= COND_BASE && id < COND_END) {
int condIndex = (id - COND_BASE) / COND_STRIDE;
int action = (id - COND_BASE) % COND_STRIDE;
if (action == 0 || action == 1) {
if (condIndex < conditions.size()) {
editingConditionIndex = condIndex;
setSubGui(new SubGuiConditionEdit(conditions.get(condIndex)));
}
} else if (action == 2) {
if (condIndex < conditions.size()) {
conditions.remove(condIndex);
initGui();
}
}
return true;
}
if (id == BTN_ADD_COND) {
if (conditions.size() < MAX_CONDITIONS) {
editingConditionIndex = conditions.size();
setSubGui(new SubGuiConditionEdit(null));
}
return true;
}
return false;
}
// ═══════════════════════════════════════════════════════════════════════════
// TEXT FIELD EVENTS
// ═══════════════════════════════════════════════════════════════════════════
@Override
public void unFocused(GuiNpcTextField textField) {
int id = textField.id;
// FieldDef-based tabs — declarative fields
if (isFieldDefTab() && builder != null && id >= DECLARATIVE_ID_START) {
if (builder.handleTextFieldEvent(id, textField)) {
initGui();
}
return;
}
// Entries tab - delay fields (ENTRY_BASE + i * ENTRY_STRIDE + 1)
if (activeTab == TAB_ENTRIES && id >= ENTRY_BASE + 1 && id < ENTRY_END) {
int entryIndex = (id - ENTRY_BASE - 1) / ENTRY_STRIDE;
if (entryIndex >= 0 && entryIndex < entries.size()) {
entries.get(entryIndex).setDelayTicks(textField.getInteger());
}
}
}
// ═══════════════════════════════════════════════════════════════════════════
// SUB GUI CLOSED
// ═══════════════════════════════════════════════════════════════════════════
@Override
public void subGuiClosed(SubGuiInterface subgui) {
// FieldDef-based tabs — declarative sub-gui handling
if (isFieldDefTab() && builder != null) {
if (builder.handleSubGuiClosed(subgui)) {
initGui();
return;
}
}
if (subgui instanceof SubGuiAbilitySelect) {
handleAbilitySelectClosed((SubGuiAbilitySelect) subgui);
initGui();
return;
}
if (subgui instanceof SubGuiChainedEntrySource) {
handleEntrySourceClosed((SubGuiChainedEntrySource) subgui);
return;
}
if (subgui instanceof SubGuiNpcSlotPicker) {
handleSlotPickerClosed((SubGuiNpcSlotPicker) subgui);
initGui();
return;
}
if (subgui instanceof SubGuiAbilityVariantSelect) {
handleVariantSelectClosed((SubGuiAbilityVariantSelect) subgui);
if (!hasSubGui()) initGui();
return;
}
if (subgui instanceof SubGuiAbilityTypeSelect) {
handleTypeSelectClosed((SubGuiAbilityTypeSelect) subgui);
if (!hasSubGui()) initGui();
return;
}
if (subgui instanceof SubGuiAbilityEditMode) {
handleEditModeClosed((SubGuiAbilityEditMode) subgui);
if (!hasSubGui()) initGui();
return;
}
if (subgui instanceof SubGuiAbilityConfig) {
editingEntryIndex = -1;
editingParentAbility = false;
initGui();
return;
}
if (subgui instanceof SubGuiConditionEdit) {
handleConditionEditClosed((SubGuiConditionEdit) subgui);
initGui();
return;
}
}
private void handleAbilitySelectClosed(SubGuiAbilitySelect gui) {
String selectedName = gui.getSelectedName();
if (selectedName != null) {
if (editingEntryIndex >= 0 && editingEntryIndex < entries.size()) {
int delay = entries.get(editingEntryIndex).getDelayTicks();
entries.set(editingEntryIndex, ChainedAbilityEntry.reference(selectedName, delay));
} else {
entries.add(ChainedAbilityEntry.reference(selectedName, 0));
}
}
editingEntryIndex = -1;
}
private void handleEntrySourceClosed(SubGuiChainedEntrySource gui) {
int source = gui.getResult();
if (source == SubGuiChainedEntrySource.SOURCE_NPC_SLOTS) {
setSubGui(new SubGuiNpcSlotPicker(npcSlots));
} else if (source == SubGuiChainedEntrySource.SOURCE_LOAD_PRESET) {
setSubGui(new SubGuiAbilitySelect(SubGuiAbilitySelect.FILTER_CUSTOM_ONLY));
} else if (source == SubGuiChainedEntrySource.SOURCE_CREATE_NEW) {
setSubGui(new SubGuiAbilityTypeSelect());
} else if (source == SubGuiChainedEntrySource.SOURCE_BUILT_IN) {
setSubGui(new SubGuiAbilitySelect(SubGuiAbilitySelect.FILTER_BUILTIN_ONLY));
}
// Don't initGui — we're opening another SubGui
}
private void handleSlotPickerClosed(SubGuiNpcSlotPicker gui) {
int slotIndex = gui.getSelectedIndex();
if (slotIndex >= 0 && npcSlots != null && slotIndex < npcSlots.size()) {
AbilityAction consumed = npcSlots.get(slotIndex);
Ability ability = consumed.getAbility();
if (ability != null) {
if (consumed.getSlotType() == AbilityAction.SlotType.INLINE_ABILITY) {
entries.add(ChainedAbilityEntry.inline(ability, 0));
} else {
entries.add(ChainedAbilityEntry.reference(consumed.getReferenceId(), 0));
}
if (!consumedSlotIndices.contains(slotIndex)) {
consumedSlotIndices.add(slotIndex);
}
}
}
}
private void handleTypeSelectClosed(SubGuiAbilityTypeSelect gui) {
String typeId = gui.getSelectedTypeId();
if (typeId != null) {
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 && !newAbility.isBuiltIn()) {
if (variants.size() == 1) {
variants.get(0).apply(newAbility);
}
newAbility.setId(java.util.UUID.randomUUID().toString());
entries.add(ChainedAbilityEntry.inline(newAbility, 0));
editingEntryIndex = entries.size() - 1;
setSubGui(new SubGuiAbilityConfig(newAbility, this));
}
}
}
private void handleVariantSelectClosed(SubGuiAbilityVariantSelect gui) {
int idx = gui.getSelectedIndex();
if (idx >= 0 && pendingTypeId != null) {
Ability newAbility = AbilityController.Instance.create(pendingTypeId);
if (newAbility != null && !newAbility.isBuiltIn()) {
gui.getVariants().get(idx).apply(newAbility);
newAbility.setId(java.util.UUID.randomUUID().toString());
entries.add(ChainedAbilityEntry.inline(newAbility, 0));
editingEntryIndex = entries.size() - 1;
pendingTypeId = null;
setSubGui(new SubGuiAbilityConfig(newAbility, this));
return;
}
}
pendingTypeId = null;
}
private void handleEditModeClosed(SubGuiAbilityEditMode gui) {
int mode = gui.getResult();
if (mode < 0 || editingEntryIndex < 0 || editingEntryIndex >= entries.size()) {
editingEntryIndex = -1;
return;
}
ChainedAbilityEntry entry = entries.get(editingEntryIndex);
// Block all editing for built-in abilities
Ability preCheck = entry.resolve();
if (preCheck != null && preCheck.isBuiltIn()) {
editingEntryIndex = -1;
return;
}
if (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) {
if (entry.convertToInline()) {
Ability a = entry.getInlineAbility();
if (a != null && !a.isBuiltIn()) {
a.setId(java.util.UUID.randomUUID().toString());
setSubGui(new SubGuiAbilityConfig(a, this));
return;
}
}
editingEntryIndex = -1;
} else if (mode == SubGuiAbilityEditMode.MODE_MODIFY_PARENT) {
Ability resolved = entry.resolve();
if (resolved != null && !resolved.isBuiltIn()) {
editingParentAbility = true;
setSubGui(resolved.createConfigGui(this));
return;
}
editingEntryIndex = -1;
}
}
private void handleConditionEditClosed(SubGuiConditionEdit gui) {
AbilityCondition result = gui.getResult();
if (result != null && editingConditionIndex >= 0) {
if (editingConditionIndex < conditions.size()) {
conditions.set(editingConditionIndex, result);
} else {
conditions.add(result);
}
}
editingConditionIndex = -1;
}
// ═══════════════════════════════════════════════════════════════════════════
// CLOSE / APPLY
// ═══════════════════════════════════════════════════════════════════════════
@Override
public void onAbilitySaved(Ability ability) {
if (editingParentAbility) {
// Persist the global parent ability to the server
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false)));
editingParentAbility = false;
return;
}
// Inline ability mutated in-place; entry already holds the reference
}
@Override
public void close() {
if (saveOnClose) {
GuiNpcTextField.unfocus();
applyToChain();
callback.onChainedAbilitySaved(chain);
}
super.close();
}
private void applyToChain() {
// Entries
chain.getEntries().clear();
for (ChainedAbilityEntry entry : entries) {
chain.addEntry(entry);
}
// Conditions
chain.getConditions().clear();
for (AbilityCondition c : conditions) {
chain.getConditions().add(c);
}
// Remove consumed NPC slots (descending order to preserve indices)
if (npcSlots != null && !consumedSlotIndices.isEmpty()) {
Collections.sort(consumedSlotIndices, Collections.reverseOrder());
for (int idx : consumedSlotIndices) {
if (idx < npcSlots.size()) {
npcSlots.remove(idx);
}
}
}
}
}
@@ -0,0 +1,62 @@
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;
/**
* Choice dialog for adding an entry to a chain.
* Options: By Reference, Create New, Built-in, From NPC Slots (optional).
*/
public class SubGuiChainedEntrySource extends SubGuiSimpleChoice {
public static final int SOURCE_NONE = -1;
public static final int SOURCE_NPC_SLOTS = 0;
public static final int SOURCE_LOAD_PRESET = 1;
public static final int SOURCE_CREATE_NEW = 2;
public static final int SOURCE_BUILT_IN = 3;
private final boolean showNpcOption;
public SubGuiChainedEntrySource() {
this(true);
}
public SubGuiChainedEntrySource(boolean showNpcOption) {
this.showNpcOption = showNpcOption;
setBackground("menubg.png");
xSize = 200;
ySize = showNpcOption ? 132 : 110;
}
@Override
public void initGui() {
super.initGui();
int y = guiTop + 10;
addLabel(new GuiNpcLabel(0, "ability.entrySource", guiLeft + 10, y));
y += 20;
addButton(new GuiNpcButton(SOURCE_LOAD_PRESET, guiLeft + 10, y, 180, 20, "ability.byReference"));
y += 22;
addButton(new GuiNpcButton(SOURCE_CREATE_NEW, guiLeft + 10, y, 180, 20, "ability.createNew"));
y += 22;
addButton(new GuiNpcButton(SOURCE_BUILT_IN, guiLeft + 10, y, 180, 20, "gui.builtin"));
if (showNpcOption) {
y += 22;
addButton(new GuiNpcButton(SOURCE_NPC_SLOTS, guiLeft + 10, y, 180, 20, "ability.fromNpc"));
}
}
@Override
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
if (id >= 0 && id <= 3) {
setResult(id);
close();
}
}
}
@@ -1,190 +1,310 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.Condition;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import kamkeel.npcs.util.Register;
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 net.minecraft.client.resources.I18n;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.util.*;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
/**
* SubGui for editing a single ability condition.
* Allows selecting condition type and configuring its parameters.
* SubGui for editing a single AbilityCondition.
*
* Split-panel layout:
* Left – Mod namespace filter + scrollable condition type list
* Right – FieldDef configuration for the selected condition
*/
public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener {
public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener, ISubGuiListener, ICustomScrollListener {
// Condition types
private static final String[] CONDITION_TYPES = {
"condition.hp_above",
"condition.hp_below",
"condition.target_hp_above",
"condition.target_hp_below",
"condition.hit_count"
};
private static final int DECLARATIVE_ID_START = 1000;
private static final int CLEAR_ID_START = 2000;
private static final int LABEL_ID_START = 3000;
private static final String[] CONDITION_TYPE_IDS = {
"hp_above",
"hp_below",
"target_hp_above",
"target_hp_below",
"hit_count"
};
private static final int BTN_NAMESPACE = 1;
private static final int BTN_CANCEL = 10;
private static final int BTN_DONE = 11;
private static final int TF_SEARCH = 12;
// Current condition being edited
private Condition condition;
private Condition result;
// Left panel
private static final int LEFT_WIDTH = 110;
private static final int LEFT_MARGIN = 5;
// State
private int selectedTypeIndex = 0;
private float threshold = 0.5f; // For HP conditions (0.0-1.0)
private int requiredHits = 3; // For hit_count
private int withinTicks = 60; // For hit_count
// Right panel
private static final int RIGHT_GAP = 5;
public SubGuiConditionEdit(Condition existing) {
this.condition = existing;
private String searchText = "";
private AbilityCondition condition;
private AbilityCondition result;
private String selectedTypeId;
// Namespace filter
private int namespaceFilter = 0; // 0 = ALL, 1 = cnpc, 2+ = modded namespaces
private List<String> modNamespaces;
// Type list
private GuiCustomScroll scroll;
private final HashMap<String, String> displayNameToTypeId = new HashMap<>();
private String[] filteredTypeIds;
private AbilityFieldBuilder builder;
public SubGuiConditionEdit(AbilityCondition existing) {
this.result = null;
this.modNamespaces = getModNamespaces();
if (existing != null) {
String typeId = existing.getTypeId();
for (int i = 0; i < CONDITION_TYPE_IDS.length; i++) {
if (CONDITION_TYPE_IDS[i].equals(typeId)) {
selectedTypeIndex = i;
break;
}
this.condition = existing;
this.selectedTypeId = existing.getTypeId();
// Set namespace filter to match existing condition
setNamespaceForTypeId(selectedTypeId);
} else {
// Default to first available condition
String[] allTypes = AbilityController.Instance.getConditionTypes();
if (allTypes.length > 0) {
this.selectedTypeId = allTypes[0];
this.condition = spawnCondition(selectedTypeId);
}
loadFromCondition(existing);
}
setBackground("menubg.png");
xSize = 220;
ySize = 140;
setBackground("menubg.png", 217);
xSize = 356;
ySize = 200;
}
private void loadFromCondition(Condition cond) {
String typeId = cond.getTypeId();
if (typeId.equals("hit_count")) {
Condition.ConditionHitCount hitCount = (Condition.ConditionHitCount) cond;
requiredHits = hitCount.getRequiredHits();
withinTicks = hitCount.getWithinTicks();
} else {
// HP-based conditions
net.minecraft.nbt.NBTTagCompound nbt = cond.writeNBT();
threshold = nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f;
private List<String> getModNamespaces() {
List<String> result = new ArrayList<>();
List<String> registered = Register.REGISTERED_NAMESPACES.get("condition");
if (registered != null) {
result.addAll(registered);
}
return result;
}
private void setNamespaceForTypeId(String typeId) {
if (typeId == null) return;
String[] parts = typeId.split("\\.", 3);
if (parts.length < 2) return;
String ns = parts[1];
if ("cnpc".equals(ns)) {
namespaceFilter = 1;
} else {
for (int i = 0; i < modNamespaces.size(); i++) {
if (modNamespaces.get(i).equals(ns)) {
namespaceFilter = 2 + i;
return;
}
}
namespaceFilter = 0; // Fallback to ALL
}
}
private String getNamespaceFilterLabel() {
if (namespaceFilter == 0) return "ALL";
if (namespaceFilter == 1) return "CNPC";
int modIdx = namespaceFilter - 2;
if (modIdx >= 0 && modIdx < modNamespaces.size()) {
String ns = modNamespaces.get(modIdx);
String display = Register.NAMESPACE_DISPLAY_NAMES.get(ns);
return display != null ? display : ns.toUpperCase();
}
return "ALL";
}
private void cycleNamespaceFilter() {
namespaceFilter++;
// 0=ALL, 1=CNPC, 2..2+N-1=mod namespaces, then wrap
int max = 2 + modNamespaces.size();
if (namespaceFilter >= max) {
namespaceFilter = 0;
}
// Skip empty mod namespace slots
if (namespaceFilter >= 2) {
int modIdx = namespaceFilter - 2;
if (modIdx >= modNamespaces.size()) {
namespaceFilter = 0;
}
}
}
private String[] getFilteredTypes() {
if (namespaceFilter == 0) {
return AbilityController.Instance.getConditionTypes();
} else if (namespaceFilter == 1) {
return AbilityController.Instance.getConditionTypesByNamespace("cnpc");
} else {
int modIdx = namespaceFilter - 2;
if (modIdx >= 0 && modIdx < modNamespaces.size()) {
return AbilityController.Instance.getConditionTypesByNamespace(modNamespaces.get(modIdx));
}
return AbilityController.Instance.getConditionTypes();
}
}
private AbilityCondition spawnCondition(String typeId) {
if (typeId == null) return null;
Supplier<AbilityCondition> factory = AbilityController.Instance.getConditionType(typeId);
return factory != null ? factory.get() : null;
}
@Override
public void initGui() {
GuiNpcTextField.unfocus();
super.initGui();
int y = guiTop + 8;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 90;
int leftX = guiLeft + LEFT_MARGIN;
int btnY = guiTop + ySize - 26;
// Title
addLabel(new GuiNpcLabel(0, "condition.edit", labelX, y));
y += 18;
// Namespace filter button (above left scroll only)
addButton(new GuiNpcButton(BTN_NAMESPACE, leftX, guiTop + 5, LEFT_WIDTH, 20, getNamespaceFilterLabel()));
// Condition Type selector
addLabel(new GuiNpcLabel(1, "gui.type", labelX, y + 5));
GuiNpcButton typeBtn = new GuiNpcButton(1, fieldX, y, 115, 20, CONDITION_TYPES, selectedTypeIndex);
typeBtn.setHoverText("condition.hover.type");
addButton(typeBtn);
y += 26;
// Type-specific fields
String typeId = CONDITION_TYPE_IDS[selectedTypeIndex];
if (typeId.equals("hit_count")) {
// Hit count fields
addLabel(new GuiNpcLabel(2, "condition.hits", labelX, y + 5));
GuiNpcTextField hitsField = new GuiNpcTextField(2, this, fontRendererObj, fieldX, y, 40, 20, "" + requiredHits);
hitsField.setIntegersOnly();
hitsField.setMinMaxDefault(1, 100, 3);
hitsField.setHoverText("condition.hover.hits");
addTextField(hitsField);
y += 24;
addLabel(new GuiNpcLabel(3, "condition.within", labelX, y + 5));
GuiNpcTextField ticksField = new GuiNpcTextField(3, this, fontRendererObj, fieldX, y, 40, 20, "" + withinTicks);
ticksField.setIntegersOnly();
ticksField.setMinMaxDefault(1, 1200, 60);
ticksField.setHoverText("condition.hover.within");
addTextField(ticksField);
} else {
// HP threshold field (as percentage)
addLabel(new GuiNpcLabel(2, "condition.percent", labelX, y + 5));
int percent = (int) (threshold * 100);
GuiNpcTextField thresholdField = new GuiNpcTextField(4, this, fontRendererObj, fieldX, y, 40, 20, "" + percent);
thresholdField.setIntegersOnly();
thresholdField.setMinMaxDefault(1, 99, 50);
thresholdField.setHoverText("condition.hover.threshold");
addTextField(thresholdField);
addLabel(new GuiNpcLabel(4, "%", fieldX + 45, y + 5));
// Build filtered type list
filteredTypeIds = getFilteredTypes();
displayNameToTypeId.clear();
List<String> scrollList = new ArrayList<>();
for (String typeId : filteredTypeIds) {
Supplier<AbilityCondition> factory = AbilityController.Instance.getConditionType(typeId);
String displayName = factory != null ? I18n.format(factory.get().getName()) : typeId;
if (!searchText.isEmpty() && !displayName.toLowerCase().contains(searchText.toLowerCase())) continue;
scrollList.add(displayName);
displayNameToTypeId.put(displayName, typeId);
}
// Left panel: condition type scroll list (between namespace button and search bar)
int scrollTop = guiTop + 29;
int scrollBottom = btnY - 24;
int scrollHeight = scrollBottom - scrollTop;
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
}
scroll.guiLeft = leftX;
scroll.guiTop = scrollTop;
scroll.setSize(LEFT_WIDTH, scrollHeight);
scroll.setUnsortedList(scrollList);
// Pre-select current condition type in scroll
if (selectedTypeId != null) {
for (int i = 0; i < scrollList.size(); i++) {
String typeId = displayNameToTypeId.get(scrollList.get(i));
if (typeId != null && typeId.equals(selectedTypeId)) {
scroll.selected = i;
break;
}
}
}
addScroll(scroll);
// Search text field (below left scroll)
GuiNpcTextField searchField = new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, leftX, scrollBottom + 2, LEFT_WIDTH, 20, searchText);
searchField.setHoverText("gui.search");
addTextField(searchField);
// Right panel: condition config via FieldDef (full height from top to buttons)
int rightX = leftX + LEFT_WIDTH + RIGHT_GAP;
int rightW = xSize - LEFT_MARGIN * 2 - LEFT_WIDTH - RIGHT_GAP;
int rightTop = guiTop + 5;
int rightHeight = btnY - rightTop - 4;
List<FieldDef> fields = new ArrayList<>();
if (condition != null) {
fields = condition.getAllDefinitions();
}
builder = new AbilityFieldBuilder(this, fontRendererObj);
builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, LABEL_ID_START);
builder.contentRight(rightW);
builder.startY(5);
builder.buildScrollWindow(fields, rightX, rightTop, rightW, rightHeight);
// Bottom buttons
addButton(new GuiNpcButton(10, guiLeft + 8, guiTop + ySize - 28, 60, 20, "gui.cancel"));
addButton(new GuiNpcButton(11, guiLeft + xSize - 68, guiTop + ySize - 28, 60, 20, "gui.done"));
addButton(new GuiNpcButton(BTN_CANCEL, leftX, btnY, 60, 20, "gui.cancel"));
GuiNpcButton doneBtn = new GuiNpcButton(BTN_DONE, guiLeft + xSize - LEFT_MARGIN - 60, btnY, 60, 20, "gui.done");
if (condition == null || !condition.isConfigured()) {
doneBtn.setEnabled(false);
}
addButton(doneBtn);
}
@Override
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
if (id == 1) {
// Type changed
selectedTypeIndex = ((GuiNpcButton) guibutton).getValue();
if (id == BTN_NAMESPACE) {
cycleNamespaceFilter();
initGui();
} else if (id == 10) {
// Cancel - close without saving
return;
}
if (id == BTN_CANCEL) {
result = null;
close();
} else if (id == 11) {
// Done - create condition and close
result = createCondition();
return;
}
if (id == BTN_DONE) {
result = condition;
close();
return;
}
if (builder != null && builder.handleButtonEvent(id, guibutton)) {
if (!hasSubGui()) {
initGui();
}
}
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 0 && scroll.hasSelected()) {
String displayName = scroll.getSelected();
String typeId = displayNameToTypeId.get(displayName);
if (typeId != null && !typeId.equals(selectedTypeId)) {
selectedTypeId = typeId;
condition = spawnCondition(selectedTypeId);
initGui();
}
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) {
// Same as single click — user still needs to configure fields
}
@Override
public void unFocused(GuiNpcTextField textField) {
int id = textField.id;
if (id == 2) {
requiredHits = textField.getInteger();
} else if (id == 3) {
withinTicks = textField.getInteger();
} else if (id == 4) {
int percent = textField.getInteger();
threshold = percent / 100.0f;
if (textField.id == TF_SEARCH) {
String newText = textField.getText();
if (!newText.equals(searchText)) {
searchText = newText;
initGui();
}
return;
}
if (textField.id < DECLARATIVE_ID_START) return;
if (builder != null && builder.handleTextFieldEvent(textField.id, textField)) {
initGui();
}
}
private Condition createCondition() {
String typeId = CONDITION_TYPE_IDS[selectedTypeIndex];
switch (typeId) {
case "hp_above":
return new Condition.ConditionHPAbove(threshold);
case "hp_below":
return new Condition.ConditionHPBelow(threshold);
case "target_hp_above":
return new Condition.ConditionTargetHPAbove(threshold);
case "target_hp_below":
return new Condition.ConditionTargetHPBelow(threshold);
case "hit_count":
return new Condition.ConditionHitCount(requiredHits, withinTicks);
default:
return null;
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (builder != null && builder.handleSubGuiClosed(subgui)) {
initGui();
}
}
/**
* Get the resulting condition after dialog closes.
* Returns null if cancelled or no valid condition.
*/
public Condition getResult() {
public AbilityCondition getResult() {
return result;
}
}
@@ -0,0 +1,247 @@
package noppes.npcs.client.gui.advanced;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.GuiButton;
import kamkeel.npcs.controllers.data.ability.conditions.ConditionHasEffect;
import noppes.npcs.client.gui.builder.FieldDef;
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 noppes.npcs.controllers.CustomEffectController;
import noppes.npcs.controllers.data.CustomEffect;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* SubGui for selecting a custom effect from CustomEffectController.
* Supports switching between effect maps (index 0 = custom, addon indices via toggle button).
*/
@SideOnly(Side.CLIENT)
public class SubGuiCustomEffectSelect extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener {
/**
* Builds the condition editor's effect-select field.
* <p>
* This lives here rather than in ConditionHasEffect because the lambdas below carry this
* class in their method descriptors. The condition is a both-side class, and @SideOnly does
* not strip the synthetic lambda methods it generates - so anything reflecting over its
* declared methods on a server would resolve those descriptors and fail to find this type.
*/
public static FieldDef createSelectField(ConditionHasEffect condition) {
return FieldDef.subGuiField("condition.select_effect",
() -> new SubGuiCustomEffectSelect(condition.getEffectId(), condition.getEffectIndex()),
gui -> {
SubGuiCustomEffectSelect sel = (SubGuiCustomEffectSelect) gui;
if (sel.getSelectedEffectId() >= 0) {
condition.setEffect(sel.getSelectedEffectId(), sel.getSelectedIndex());
}
})
.buttonLabel(() -> {
if (condition.getEffectId() < 0) return "None";
CustomEffect effect = condition.getEffect();
return effect != null ? effect.getName() : "ID:" + condition.getEffectId();
})
.clearable(() -> condition.setEffect(-1, 0));
}
private GuiCustomScroll scroll;
private final HashMap<String, Integer> displayNameToId = new HashMap<>();
private final HashMap<String, Integer> allDisplayNameToId = new HashMap<>();
private int selectedEffectId = -1;
private int selectedIndex = 0;
private String search = "";
private final int preselectedId;
private final int preselectedIndex;
/** The effect map index currently being viewed */
private int viewIndex = 0;
/** Ordered list of available indices for toggling */
private List<Integer> availableIndices;
public SubGuiCustomEffectSelect(int preselectedId) {
this(preselectedId, 0);
}
public SubGuiCustomEffectSelect(int preselectedId, int preselectedIndex) {
this.preselectedId = preselectedId;
this.preselectedIndex = preselectedIndex;
this.viewIndex = preselectedIndex;
setBackground("menubg.png");
xSize = 200;
ySize = 216;
}
@Override
public void initGui() {
super.initGui();
buildAvailableIndices();
addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 5, guiTop + 5, 190, 18, search));
// Toggle button for switching between effect lists (only if addon indices exist)
if (availableIndices.size() > 1) {
String label = getViewLabel();
addButton(new GuiNpcButton(2, guiLeft + 5, guiTop + 26, 190, 20, label));
}
int scrollTop = availableIndices.size() > 1 ? guiTop + 49 : guiTop + 26;
int scrollHeight = availableIndices.size() > 1 ? 122 : 145;
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
}
scroll.setSize(190, scrollHeight);
scroll.guiLeft = guiLeft + 5;
scroll.guiTop = scrollTop;
addScroll(scroll);
buildAllEffects();
List<String> filtered = getFilteredList();
scroll.setUnsortedList(filtered);
// Pre-select current effect (only if viewing the same index)
if (preselectedId >= 0 && viewIndex == preselectedIndex && !scroll.hasSelected()) {
for (String name : filtered) {
Integer id = displayNameToId.get(name);
if (id != null && id == preselectedId) {
scroll.setSelected(name);
break;
}
}
}
addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.select"));
getButton(0).setEnabled(scroll.hasSelected());
addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel"));
}
private void buildAvailableIndices() {
availableIndices = new ArrayList<>();
CustomEffectController controller = CustomEffectController.getInstance();
// Always include index 0
availableIndices.add(0);
// Add any addon indices that have registered labels
HashMap<Integer, String> labels = controller.getIndexLabels();
for (int idx : labels.keySet()) {
if (idx != 0 && controller.getEffectMap(idx) != null) {
availableIndices.add(idx);
}
}
Collections.sort(availableIndices);
// Ensure viewIndex is valid
if (!availableIndices.contains(viewIndex)) {
viewIndex = 0;
}
}
private String getViewLabel() {
if (viewIndex == 0) {
return "Custom Effects";
}
HashMap<Integer, String> labels = CustomEffectController.getInstance().getIndexLabels();
String label = labels.get(viewIndex);
return label != null ? label : "Index " + viewIndex;
}
private void buildAllEffects() {
allDisplayNameToId.clear();
HashMap<Integer, CustomEffect> effects = CustomEffectController.getInstance().getEffectMap(viewIndex);
if (effects == null) return;
for (CustomEffect ce : effects.values()) {
if (ce.getName() != null && !ce.getName().isEmpty()) {
allDisplayNameToId.put(ce.getName(), ce.id);
}
}
}
private List<String> getFilteredList() {
List<String> list = new ArrayList<>();
displayNameToId.clear();
for (Map.Entry<String, Integer> entry : allDisplayNameToId.entrySet()) {
String name = entry.getKey();
if (search.isEmpty() || name.toLowerCase().contains(search)) {
list.add(name);
displayNameToId.put(name, entry.getValue());
}
}
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
return list;
}
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0 && scroll.hasSelected()) {
String name = scroll.getSelected();
Integer id = displayNameToId.get(name);
selectedEffectId = id != null ? id : -1;
selectedIndex = viewIndex;
close();
} else if (guibutton.id == 1) {
selectedEffectId = -1;
close();
} else if (guibutton.id == 2) {
// Toggle to next available index
int currentPos = availableIndices.indexOf(viewIndex);
int nextPos = (currentPos + 1) % availableIndices.size();
viewIndex = availableIndices.get(nextPos);
search = "";
scroll = null;
initGui();
}
}
@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) {
Integer id = displayNameToId.get(selection);
selectedEffectId = id != null ? id : -1;
selectedIndex = viewIndex;
close();
}
}
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(10) != null && getTextField(10).isFocused()) {
String newSearch = getTextField(10).getText().toLowerCase();
if (!search.equals(newSearch)) {
search = newSearch;
scroll.setUnsortedList(getFilteredList());
scroll.resetScroll();
}
}
}
@Override
public void unFocused(GuiNpcTextField textField) {
}
public int getSelectedEffectId() {
return selectedEffectId;
}
public int getSelectedIndex() {
return selectedIndex;
}
}
@@ -10,7 +10,13 @@ import noppes.npcs.client.gui.util.SubGuiInterface;
*/
public class SubGuiDuplicateNameConfirm extends SubGuiInterface {
private boolean confirmed = false;
public enum Result {
CONTINUE,
BACK,
CANCEL
}
private Result result = Result.CANCEL;
public SubGuiDuplicateNameConfirm() {
setBackground("menubg.png");
@@ -26,22 +32,38 @@ public class SubGuiDuplicateNameConfirm extends SubGuiInterface {
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"));
addButton(new GuiNpcButton(0, guiLeft + 10, y, 65, 20, "gui.continue"));
addButton(new GuiNpcButton(1, guiLeft + 78, y, 65, 20, "gui.back"));
addButton(new GuiNpcButton(2, guiLeft + 146, y, 65, 20, "gui.cancel"));
}
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0) {
confirmed = true;
result = Result.CONTINUE;
close();
} else if (guibutton.id == 1) {
confirmed = false;
result = Result.BACK;
close();
} else if (guibutton.id == 2) {
result = Result.CANCEL;
close();
}
}
public Result getResult() {
return result;
}
public boolean isConfirmed() {
return confirmed;
return result == Result.CONTINUE;
}
public boolean isBack() {
return result == Result.BACK;
}
public boolean isCancelled() {
return result == Result.CANCEL;
}
}
@@ -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;
/**
* Choice dialog for the Load button: Load Ability or Load Chain.
*/
public class SubGuiLoadTypeChoice extends SubGuiSimpleChoice {
public static final int RESULT_NONE = -1;
public static final int RESULT_ABILITY = 0;
public static final int RESULT_CHAIN = 1;
public SubGuiLoadTypeChoice() {
setBackground("menubg.png");
xSize = 200;
ySize = 80;
}
@Override
public void initGui() {
super.initGui();
int y = guiTop + 10;
addLabel(new GuiNpcLabel(0, "ability.loadType", guiLeft + 10, y));
y += 20;
addButton(new GuiNpcButton(0, guiLeft + 10, y, 85, 20, "ability.loadAbility"));
addButton(new GuiNpcButton(1, guiLeft + 105, y, 85, 20, "ability.loadChain"));
y += 24;
addButton(new GuiNpcButton(2, guiLeft + 55, y, 90, 20, "gui.cancel"));
}
@Override
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
if (id == 0 || id == 1) {
setResult(id);
close();
} else if (id == 2) {
close();
}
}
}
@@ -0,0 +1,113 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityAction;
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.GuiNpcLabel;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.ArrayList;
import java.util.List;
/**
* Picker for selecting an NPC ability slot to consume into a chain entry.
* Shows standalone (non-chain) ability slots from the NPC's current list.
*/
public class SubGuiNpcSlotPicker extends SubGuiInterface implements ICustomScrollListener {
private final List<AbilityAction> npcSlots;
private final List<Integer> validIndices = new ArrayList<>();
private GuiCustomScroll scroll;
private int selectedIndex = -1;
public SubGuiNpcSlotPicker(List<AbilityAction> npcSlots) {
this.npcSlots = npcSlots;
setBackground("menubg.png");
xSize = 220;
ySize = 200;
}
@Override
public void initGui() {
super.initGui();
int y = guiTop + 5;
addLabel(new GuiNpcLabel(0, "ability.selectSlot", guiLeft + 10, y));
y += 14;
List<String> displayList = new ArrayList<>();
validIndices.clear();
for (int i = 0; i < npcSlots.size(); i++) {
AbilityAction slot = npcSlots.get(i);
// Only show standalone abilities (not chains)
if (slot.isChain()) continue;
Ability ability = slot.getAbility();
if (ability == null) continue;
String typeName = I18n.format(ability.getTypeId());
String customName = ability.getName();
String display;
if (customName != null && !customName.isEmpty() && !customName.equals(typeName)) {
display = (i + 1) + ". " + customName + " (" + typeName + ")";
} else {
display = (i + 1) + ". " + typeName;
}
if (slot.isReference()) {
display = "\u00A7e" + display + " (Ref)";
}
displayList.add(display);
validIndices.add(i);
}
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
scroll.setSize(200, 130);
}
scroll.guiLeft = guiLeft + 10;
scroll.guiTop = y;
scroll.setList(displayList);
addScroll(scroll);
y += 133;
addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "gui.select"));
addButton(new GuiNpcButton(1, guiLeft + 115, y, 95, 20, "gui.cancel"));
getButton(0).setEnabled(selectedIndex >= 0);
}
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0 && selectedIndex >= 0) {
close();
} else if (guibutton.id == 1) {
selectedIndex = -1;
close();
}
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 0 && guiCustomScroll.selected >= 0 && guiCustomScroll.selected < validIndices.size()) {
selectedIndex = validIndices.get(guiCustomScroll.selected);
initGui();
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 0 && selectedIndex >= 0) {
close();
}
}
public int getSelectedIndex() {
return selectedIndex;
}
}
@@ -0,0 +1,23 @@
package noppes.npcs.client.gui.advanced;
import noppes.npcs.client.gui.util.SubGuiInterface;
/**
* Base class for simple choice dialogs that present a few buttons and return an int result.
* Subclasses define their own layout in {@code initGui()} and call {@code setResult()} from {@code buttonEvent()}.
* The parent reads the result via {@code getResult()} in {@code subGuiClosed()}.
*
* <p>Result is -1 by default (cancelled / no selection).</p>
*/
public abstract class SubGuiSimpleChoice extends SubGuiInterface {
private int result = -1;
protected final void setResult(int result) {
this.result = result;
}
public int getResult() {
return result;
}
}
@@ -2,12 +2,13 @@ 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.select.GuiTexturePathSelection;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.AnimationController;
import noppes.npcs.controllers.data.Animation;
import java.util.List;
import java.util.function.BooleanSupplier;
@@ -32,8 +33,8 @@ public class FieldDef {
private String hoverText = null;
// Numeric range
private float min = Float.MIN_VALUE;
private float max = Float.MAX_VALUE;
private float min = 0;
private float max = Float.POSITIVE_INFINITY;
// Enum support
private Class<? extends Enum<?>> enumClass;
@@ -118,10 +119,11 @@ public class FieldDef {
return def;
}
public static FieldDef subGuiField(String label, Supplier<SubGuiInterface> factory, Consumer<SubGuiInterface> resultHandler) {
@SuppressWarnings("unchecked")
public static <T> FieldDef subGuiField(String label, Supplier<T> factory, Consumer<T> resultHandler) {
FieldDef def = new FieldDef(label, FieldType.SUB_GUI);
def.subGuiFactory = factory;
def.subGuiResultHandler = resultHandler;
def.subGuiFactory = (Supplier<SubGuiInterface>) (Supplier<?>) factory;
def.subGuiResultHandler = (Consumer<SubGuiInterface>) (Consumer<?>) resultHandler;
return def;
}
@@ -154,8 +156,8 @@ public class FieldDef {
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))
() -> new SubGuiColorSelector(getter.get() & 0xFFFFFF),
gui -> setter.accept((((SubGuiColorSelector) gui).color & 0x00FFFFFF) | (getter.get() & 0xFF000000)))
.buttonLabel(() -> String.format("%06X", getter.get() & 0xFFFFFF))
.buttonTextColor(() -> getter.get() & 0xFFFFFF);
}
@@ -174,9 +176,21 @@ public class FieldDef {
.clearable(() -> setter.accept(""));
}
public static FieldDef textureSubGui(String label, Supplier<String> getter, Consumer<String> setter) {
FieldDef def = new FieldDef(label, FieldType.STRING_BROWSE);
def.getter = () -> getter.get();
def.setter = v -> setter.accept(v != null ? v.toString() : "");
def.subGuiFactory = () -> new GuiTexturePathSelection(getter.get());
def.subGuiResultHandler = gui -> {
GuiTexturePathSelection t = (GuiTexturePathSelection) gui;
if (t.selectedResource != null) setter.accept(t.selectedResource.toString());
};
return def;
}
public static FieldDef animSubGui(String label,
Supplier<Integer> idGetter, Consumer<Integer> idSetter,
Supplier<String> nameGetter, Consumer<String> nameSetter) {
Supplier<Integer> idGetter, Consumer<Integer> idSetter,
Supplier<String> nameGetter, Consumer<String> nameSetter) {
return subGuiField(label,
() -> new GuiAnimationSelection(idGetter.get(), nameGetter.get()),
gui -> {
@@ -186,23 +200,34 @@ public class FieldDef {
idSetter.accept(-1);
} else {
idSetter.accept(sel.selectedAnimationId);
nameSetter.accept("");
String customName = sel.getSelectedName();
nameSetter.accept(customName != null ? customName : "");
}
})
.buttonLabel(() -> {
String name = nameGetter.get();
if (name != null && !name.isEmpty()) return name;
int id = idGetter.get();
if (id < 0 && name != null && !name.isEmpty()) {
// Built-in animation: show just the name
return name;
}
if (id >= 0) {
// Custom animation: show (X) Name
if (name != null && !name.isEmpty()) {
return "(" + id + ") " + name;
}
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;
? "(" + id + ") " + animName : String.valueOf(id);
}
return "gui.none";
})
.clearable(() -> { idSetter.accept(-1); nameSetter.accept(""); });
.clearable(() -> {
idSetter.accept(-1);
nameSetter.accept("");
});
}
// ═══════════════════════════════════════════════════════════════════
@@ -264,21 +289,65 @@ public class FieldDef {
// 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 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 != 0 || max != Float.POSITIVE_INFINITY;
}
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;
@@ -305,8 +374,13 @@ public class FieldDef {
return buttonTextColorSupplier != null ? buttonTextColorSupplier.get() : null;
}
public FieldDef getLeftChild() { return leftChild; }
public FieldDef getRightChild() { return rightChild; }
public FieldDef getLeftChild() {
return leftChild;
}
public FieldDef getRightChild() {
return rightChild;
}
// ═══════════════════════════════════════════════════════════════════
// LIST MANIPULATION (for mod injection)
@@ -356,7 +430,7 @@ public class FieldDef {
*
* @param fields The field list to modify
* @param targetLabel The label of the field to modify
* @param condition The condition to replace
* @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) {
@@ -15,5 +15,8 @@ public enum FieldType {
SECTION_HEADER,
LABEL,
EFFECTS_LIST,
ROW
CUSTOM_EFFECTS_LIST,
EFFECT_ACTIONS_LIST,
ROW,
STRING_BROWSE
}
@@ -69,13 +69,32 @@ public class GuiFieldBuilder {
// 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 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;
}
public GuiFieldBuilder startY(int y) { this.startY = y; return this; }
public GuiFieldBuilder rowHeight(int h) { this.rowHeight = h; return this; }
// ═══════════════════════════════════════════════════════════════════
// BUILD
@@ -98,6 +117,7 @@ public class GuiFieldBuilder {
/**
* Processes all fields and adds widgets to the scroll window.
*
* @return the final Y position after all fields
*/
protected int build(List<FieldDef> fields) {
@@ -173,8 +193,14 @@ public class GuiFieldBuilder {
}
private int lastHandledIndex = -1;
protected void setLastHandledIndex(int index) { this.lastHandledIndex = index; }
protected int getLastHandledIndex() { return lastHandledIndex; }
protected void setLastHandledIndex(int index) {
this.lastHandledIndex = index;
}
protected int getLastHandledIndex() {
return lastHandledIndex;
}
// ═══════════════════════════════════════════════════════════════════
// FIELD RENDERING
@@ -194,7 +220,7 @@ public class GuiFieldBuilder {
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);
tf.setMinMaxDefaultFloat(def.getMin(), def.getMax(), fVal);
if (!def.isEnabled()) tf.setEnabled(false);
if (hover != null) tf.setHoverText(hover);
sw.addTextField(tf);
@@ -207,7 +233,7 @@ public class GuiFieldBuilder {
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);
tf.setMinMaxDefault((int) def.getMin(), (int) def.getMax(), iVal);
if (!def.isEnabled()) tf.setEnabled(false);
if (hover != null) tf.setHoverText(hover);
sw.addTextField(tf);
@@ -219,6 +245,9 @@ public class GuiFieldBuilder {
case STRING: {
String sVal = def.getValue() != null ? def.getValue().toString() : "";
GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, fieldW, 20, sVal);
if ("gui.name".equals(def.getLabel())) {
tf.setFileNameSafe();
}
if (!def.isEnabled()) tf.setEnabled(false);
if (hover != null) tf.setHoverText(hover);
sw.addTextField(tf);
@@ -268,7 +297,10 @@ public class GuiFieldBuilder {
String curVal = def.getStringEnumValue();
int selected = 0;
for (int i = 0; i < values.length; i++) {
if (values[i].equals(curVal)) { selected = i; break; }
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);
@@ -284,12 +316,12 @@ public class GuiFieldBuilder {
String btnText = def.getButtonLabel();
int btnW;
if (def.hasClearAction()) {
btnW = contentRight - 22 - fieldX;
GuiNpcButton clearBtn = new GuiNpcButton(clearId, contentRight - 20, y, 20, 20, "X");
btnW = fieldW - 22;
GuiNpcButton clearBtn = new GuiNpcButton(clearId, fieldX + fieldW - 20, y, 20, 20, "X");
sw.addButton(clearBtn);
clearFieldMap.put(clearId, def);
} else {
btnW = contentRight - fieldX;
btnW = fieldW;
}
GuiNpcButton btn = new GuiNpcButton(widgetId, fieldX, y, btnW, 20, btnText);
Integer textColor = def.getButtonTextColor();
@@ -302,6 +334,25 @@ public class GuiFieldBuilder {
clearId++;
break;
}
case STRING_BROWSE: {
// Text field for manual input (URLs, paths) + browse button
int btnW = 20;
int tfW = fieldW - btnW - 2;
String sVal = def.getValue() != null ? def.getValue().toString() : "";
GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, tfW, 20, sVal);
if (!def.isEnabled()) tf.setEnabled(false);
if (hover != null) tf.setHoverText(hover);
sw.addTextField(tf);
textFieldMap.put(widgetId, def);
widgetId++;
// Browse button
GuiNpcButton browseBtn = new GuiNpcButton(clearId, fieldX + tfW + 2, y, btnW, 20, "...");
if (!def.isEnabled()) browseBtn.setEnabled(false);
sw.addButton(browseBtn);
buttonFieldMap.put(clearId, def);
clearId++;
break;
}
default:
// Unknown type — skip, incrementing IDs to stay in sync
widgetId++;
@@ -315,20 +366,37 @@ public class GuiFieldBuilder {
String translated = StatCollector.translateToLocal(def.getLabel());
int labelW = fontRenderer.getStringWidth(translated);
int fieldX = colLLabel + labelW + labelPadding;
// Available width before the scrollbar
int maxW = contentRight - fieldX - 15;
if ((def.getType() == FieldType.SUB_GUI || def.getType() == FieldType.STRING_BROWSE) && maxW > 0) {
// SUB_GUI fields fill all available width up to the scrollbar
fieldW = maxW;
} else if (maxW > 0 && fieldW > maxW) {
fieldW = maxW;
}
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 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;
case STRING_ENUM:
return 120;
case SUB_GUI:
return def.hasClearAction() ? 175 : 200;
case STRING_BROWSE:
return 200;
default:
return 80;
}
}
@@ -387,6 +455,15 @@ public class GuiFieldBuilder {
});
}
return true;
case STRING_BROWSE:
if (def.getSubGuiFactory() != null) {
parent.setSubGuiWithResult(def.getSubGuiFactory().get(), sub -> {
if (def.getSubGuiResultHandler() != null) {
def.getSubGuiResultHandler().accept(sub);
}
});
}
return true;
default:
return false;
}
@@ -410,7 +487,8 @@ public class GuiFieldBuilder {
def.setValue(newVal);
return true;
}
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
return false;
case INT:
try {
@@ -421,9 +499,11 @@ public class GuiFieldBuilder {
def.setValue(newVal);
return true;
}
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
return false;
case STRING:
case STRING_BROWSE:
String newVal = field.getText();
Object old = def.getValue();
String oldVal = old != null ? old.toString() : "";
@@ -453,10 +533,27 @@ public class GuiFieldBuilder {
// 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; }
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;
}
}
@@ -7,6 +7,7 @@ import noppes.npcs.api.gui.ICustomGuiComponent;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.gui.custom.GuiCustom;
import noppes.npcs.client.gui.custom.interfaces.IGuiComponent;
import noppes.npcs.client.renderer.AnimationHelper;
import noppes.npcs.client.renderer.ImageData;
import noppes.npcs.scripted.gui.ScriptGuiTexturedRect;
import org.lwjgl.opengl.GL11;
@@ -30,6 +31,11 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent {
float alpha;
float rotation;
// Animation
boolean animated;
int frameCount = 1;
int frametime = 2;
public CustomGuiTexturedRect(int id, String texture, int x, int y, int width, int height) {
this(id, texture, x, y, width, height, 0, 0);
}
@@ -64,10 +70,18 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent {
int totalWidth = this.imageData.getTotalWidth();
int totalHeight = this.imageData.getTotalHeight();
// Animation V offset
float vOff = 0f;
if (this.imageData.isAnimated()) {
vOff = this.imageData.getCurrentFrameVOffset();
} else if (this.animated && this.frameCount > 1) {
vOff = AnimationHelper.getFrameVOffset(totalHeight, this.frameCount, this.frametime);
}
float u1 = (float) textureX / (float) totalWidth;
float u2 = u1 + (float) width / (float) totalWidth;
float v1 = (float) textureY / (float) totalHeight;
float v2 = v1 + (float) height / (float) totalHeight;
float v1 = vOff + (float) textureY / (float) totalHeight;
float v2 = vOff + ((float) textureY + (float) height) / (float) totalHeight;
GL11.glPushMatrix();
float red = (color >> 16 & 255) / 255f;
@@ -104,6 +118,9 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent {
component.setColor(color);
component.setAlpha(alpha);
component.setRotation(rotation);
if (this.animated && this.frameCount > 1) {
component.setAnimation(this.frameCount, this.frametime);
}
return component;
}
@@ -124,6 +141,12 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent {
rect.alpha = component.getAlpha();
rect.rotation = component.getRotation();
if (component.isAnimated()) {
rect.animated = true;
rect.frameCount = component.getFrameCount();
rect.frametime = component.getFrameTime();
}
return rect;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,529 @@
package noppes.npcs.client.gui.global;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.animation.AnimationGetPacket;
import kamkeel.npcs.network.packets.request.animation.AnimationRemovePacket;
import kamkeel.npcs.network.packets.request.animation.AnimationClonePacket;
import kamkeel.npcs.network.packets.request.animation.AnimationSavePacket;
import kamkeel.npcs.network.packets.request.animation.AnimationsGetPacket;
import kamkeel.npcs.network.packets.request.animation.BuiltInAnimationGetPacket;
import kamkeel.npcs.network.packets.request.category.CategoryItemsRequestPacket;
import kamkeel.npcs.network.packets.request.category.CategoryListRequestPacket;
import kamkeel.npcs.network.packets.request.category.CategoryMoveItemPacket;
import kamkeel.npcs.network.packets.request.category.CategoryRemovePacket;
import kamkeel.npcs.network.packets.request.category.CategorySavePacket;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiDirectoryCategorized;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiUtil;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiTexturedButton;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.constants.EnumCategoryType;
import noppes.npcs.constants.EnumScrollData;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.controllers.data.AnimationData;
import noppes.npcs.controllers.data.Category;
import noppes.npcs.controllers.data.Frame;
import noppes.npcs.controllers.data.FramePart;
import noppes.npcs.client.ClientEventHandler;
import noppes.npcs.entity.EntityCustomNpc;
import noppes.npcs.entity.EntityNPCInterface;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import java.util.HashMap;
import java.util.Vector;
public class GuiAnimationDirectory extends GuiDirectoryCategorized {
public Animation animation = new Animation();
public EntityNPCInterface npc;
private EntityNPCInterface originalNpc;
// Animation playback
public boolean playingAnimation = false;
private long prevTick;
// Built-in mode
private boolean showingBuiltIn = false;
private boolean currentIsBuiltIn = false;
private HashMap<String, Integer> builtInData = new HashMap<>();
public GuiAnimationDirectory(EntityNPCInterface npc) {
super();
this.originalNpc = npc;
this.npc = createFakeNPC(npc);
zoomed = 70;
PacketClient.sendClient(new AnimationsGetPacket());
}
private static EntityNPCInterface createFakeNPC(EntityNPCInterface original) {
EntityCustomNpc fake = new EntityCustomNpc(Minecraft.getMinecraft().theWorld);
fake.display.readToNBT(original.display.writeToNBT(new NBTTagCompound()));
fake.display.name = "anim preview";
fake.height = original.height;
fake.width = original.width;
fake.display.animationData.setEnabled(true);
return fake;
}
@Override
protected boolean hasCategories() { return !showingBuiltIn; }
@Override
protected void computeLayout() {
if (showingBuiltIn) {
leftPanelPercent = 0.0f;
minLeftPanelW = 0;
} else {
leftPanelPercent = 0.15f;
minLeftPanelW = 120;
}
super.computeLayout();
}
@Override
protected void drawPanels() {
if (showingBuiltIn) {
if (rightPanelW > 0) {
GuiUtil.drawRectD(rightX - 1, contentY - 1, rightX + rightPanelW + 1, originY + usableH + 1, panelBorder);
}
} else {
super.drawPanels();
}
}
@Override
protected void initLeftPanel() {
if (showingBuiltIn) return;
super.initLeftPanel();
}
@Override
protected String getTitle() {
return showingBuiltIn ? "Animations (Built-in)" : "Animations";
}
@Override
protected void requestCategoryList() {
if (!showingBuiltIn) {
PacketClient.sendClient(new CategoryListRequestPacket(EnumCategoryType.ANIMATION));
}
}
@Override
protected void requestItemsInCategory(int catId) {
if (!showingBuiltIn) {
PacketClient.sendClient(new CategoryItemsRequestPacket(EnumCategoryType.ANIMATION, catId));
}
}
@Override
protected void requestItemData(int itemId) {
PacketClient.sendClient(new AnimationGetPacket(itemId));
}
@Override
protected void onSaveCategory(Category cat) {
PacketClient.sendClient(new CategorySavePacket(EnumCategoryType.ANIMATION, cat.writeNBT(new NBTTagCompound())));
}
@Override
protected void onRemoveCategory(int catId) {
PacketClient.sendClient(new CategoryRemovePacket(EnumCategoryType.ANIMATION, catId));
}
@Override
protected void onAddItem(int catId) {
if (showingBuiltIn) return;
String name = "New";
while (itemData.containsKey(name)) name += "_";
Animation newAnim = new Animation(-1, name);
PacketClient.sendClient(new AnimationSavePacket(newAnim.writeToNBT()));
}
@Override
protected void onRemoveItem(int itemId) {
if (showingBuiltIn) return;
PacketClient.sendClient(new AnimationRemovePacket(itemId));
animation = new Animation();
}
@Override
protected void onEditItem() {
if (animation != null && animation.id >= 0 && !currentIsBuiltIn) {
NoppesUtil.openGUI(player, new GuiNPCEditAnimation(this, animation, npc));
}
}
@Override
protected void onCloneItem() {
if (showingBuiltIn || currentIsBuiltIn) return;
if (animation != null && animation.id >= 0) {
PacketClient.sendClient(new AnimationClonePacket(animation.id));
}
}
@Override
protected void onItemReceived(NBTTagCompound compound) {
animation = new Animation();
animation.readFromNBT(compound);
setPrevItemName(animation.name);
currentIsBuiltIn = compound.hasKey("BuiltIn") && compound.getBoolean("BuiltIn");
playingAnimation = false;
showFirstFrame();
}
private void showFirstFrame() {
if (animation.id != -1 || currentIsBuiltIn) {
AnimationData data = npc.display.animationData;
data.setAnimation(new Animation());
data.animation.smooth = animation.smooth;
data.animation.loop = 0;
if (!animation.frames.isEmpty()) {
Frame firstFrame = new Frame();
firstFrame.parent = data.animation;
firstFrame.readFromNBT(animation.frames.get(0).writeToNBT());
data.animation.addFrame(firstFrame);
}
}
}
@Override
protected boolean hasSelectedItem() {
if (currentIsBuiltIn) return true;
return animation != null && animation.id >= 0;
}
@Override
protected int getSelectedItemId() {
return animation != null ? animation.id : -1;
}
@Override
protected void sendMovePacket(int itemId, int destCatId) {
PacketClient.sendClient(new CategoryMoveItemPacket(EnumCategoryType.ANIMATION, itemId, destCatId));
}
@Override
protected GuiScreen getWindowedVariant() {
return new GuiNPCManageAnimations(originalNpc, false, false);
}
@Override
protected void saveCurrentItem() {
if (!currentIsBuiltIn && animation != null && animation.id >= 0 && prevItemName != null && !prevItemName.isEmpty()) {
PacketClient.sendClient(new AnimationSavePacket(animation.writeToNBT()));
prevItemName = animation.name;
}
}
@Override
protected void onSubGuiClosed(SubGuiInterface subgui) {
if (animation != null && animation.id >= 0) {
setPrevItemName(animation.name);
if (selectedCatId >= 0 && !showingBuiltIn) requestItemsInCategory(selectedCatId);
}
}
// ========== Built-in Toggle ==========
@Override
protected int initExtraTopBarButtons(int x, int topBtnY) {
String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom";
GuiNpcButton toggleBtn = new GuiNpcButton(60, x, topBtnY, 55, btnH, toggleLabel);
toggleBtn.setTextColor(showingBuiltIn ? 0x55FFFF : 0xFFFFFF);
addButton(toggleBtn);
return x + 55 + 2;
}
@Override
protected void initTopBar(int topBtnY) {
super.initTopBar(topBtnY);
// Disable item operations in built-in mode
if (showingBuiltIn) {
if (getButton(50) != null) getButton(50).enabled = false; // Add
if (getButton(54) != null) getButton(54).enabled = false; // Move
}
}
@Override
protected void initRightPanel(int startY) {
// Calculate layout: playback rows + edit/copy + remove rows
int bottomRows = 2; // edit+copy, remove
boolean hasPlayback = animation != null && !animation.frames.isEmpty() && hasSelectedItem();
if (hasPlayback) {
bottomRows++; // playback controls row
if (playingAnimation) bottomRows++; // frame info row
}
int bottomH = bottomRows * (btnH + gap) + 14;
previewX = rightX;
previewY = contentY;
previewW = rightPanelW;
previewH = contentH - bottomH - gap;
// Playback controls
if (hasPlayback) {
int playY = contentY + previewH + gap;
String animTexture = "customnpcs:textures/gui/animation.png";
AnimationData data = npc.display.animationData;
int btnX = rightX + 4;
if (!playingAnimation || (data.animation != null && data.animation.paused)) {
String statusKey = (data.animation != null && data.animation.paused) ? "animation.paused" : "animation.stopped";
addLabel(new GuiNpcLabel(90, statusKey, btnX, playY + 5, 0xFFFFFF));
addButton(new GuiTexturedButton(91, "", btnX + 65, playY, 11, 20, animTexture, 18, 71));
} else {
addLabel(new GuiNpcLabel(90, "animation.playing", btnX, playY + 5, 0xFFFFFF));
addButton(new GuiTexturedButton(92, "", btnX + 65, playY, 14, 20, animTexture, 0, 71));
}
if (playingAnimation) {
addButton(new GuiTexturedButton(93, "", btnX + 85, playY, 14, 20, animTexture, 33, 71));
// Frame info on its own line below playback controls
int frameInfoY = playY + btnH + gap;
addLabel(new GuiNpcLabel(94, "", btnX, frameInfoY + 5, 0xFFFFFF));
}
}
// Edit + Copy on one row, Remove below
int btnY = contentY + contentH - btnH * 2 - gap;
int halfW = (rightPanelW - gap) / 2;
GuiNpcButton editBtn = new GuiNpcButton(51, rightX, btnY, halfW, btnH, "gui.edit");
editBtn.enabled = hasSelectedItem() && movePhase == 0 && !currentIsBuiltIn;
addButton(editBtn);
GuiNpcButton cloneBtn = new GuiNpcButton(52, rightX + halfW + gap, btnY, halfW, btnH, "gui.copy");
cloneBtn.enabled = hasSelectedItem() && movePhase == 0 && !currentIsBuiltIn;
addButton(cloneBtn);
int removeY = btnY + btnH + gap;
GuiNpcButton removeBtn = new GuiNpcButton(53, rightX, removeY, rightPanelW, btnH, "gui.remove");
removeBtn.enabled = hasSelectedItem() && movePhase == 0 && !currentIsBuiltIn;
removeBtn.setTextColor(0xFF5555);
addButton(removeBtn);
}
// ========== Scroll Events Override for Built-in ==========
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
if (scroll.id == 0 && showingBuiltIn) {
String selected = itemScroll.getSelected();
if (selected != null && !selected.equals(prevItemName)) {
PacketClient.sendClient(new BuiltInAnimationGetPacket(selected));
prevItemName = selected;
}
return;
}
super.customScrollClicked(i, j, k, scroll);
}
// ========== Data ==========
@Override
public void setData(Vector<String> list, HashMap<String, Integer> data, EnumScrollData type) {
if (type == EnumScrollData.BUILTIN_ANIMATIONS) {
this.builtInData = data;
if (showingBuiltIn) {
this.itemData = data;
itemScroll.setList(getItemSearchList());
initGui();
}
return;
}
super.setData(list, data, type);
}
// ========== Animation Tick ==========
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
AnimationData data = npc.display.animationData;
if (!data.isActive() && playingAnimation) {
playingAnimation = false;
initGui();
} else if (data.isActive()) {
long time = mc.theWorld.getTotalWorldTime();
if (time != prevTick) {
npc.display.animationData.increaseTime();
GuiNpcLabel label = getLabel(94);
if (label != null && data.animation != null) {
int frameIdx = data.animation.currentFrame;
int frameTime = data.animation.currentFrameTime;
int totalFrames = data.animation.frames.size();
Frame curFrame = (Frame) data.animation.currentFrame();
int duration = curFrame != null ? curFrame.getDuration() : 0;
label.label = (frameIdx + 1) + "/" + totalFrames + " (" + frameTime + "/" + duration + "t)";
}
}
prevTick = time;
}
super.drawScreen(mouseX, mouseY, partialTicks);
}
// ========== Actions ==========
@Override
protected void actionPerformed(GuiButton guibutton) {
int id = guibutton.id;
// Toggle built-in / custom
if (id == 60) {
showingBuiltIn = !showingBuiltIn;
animation = new Animation();
currentIsBuiltIn = false;
playingAnimation = false;
prevItemName = "";
itemSearch = "";
if (showingBuiltIn) {
// Show built-in flat list
this.itemData = builtInData;
selectedCatId = 0; // Ensure list is visible
} else {
// Re-enter category mode
this.itemData = new HashMap<>();
selectedCatId = -1;
requestCategoryList();
}
initGui();
return;
}
// Playback controls
AnimationData data = npc.display.animationData;
if (id == 91) {
if (!playingAnimation || !data.isActive()) {
animation.currentFrame = 0;
animation.currentFrameTime = 0;
for (Frame frame : animation.frames) {
for (FramePart framePart : frame.frameParts.values()) {
framePart.prevRotations = new float[]{0, 0, 0};
framePart.prevPivots = new float[]{0, 0, 0};
}
}
}
playingAnimation = true;
data.setAnimation(this.animation);
data.animation.paused = false;
initGui();
return;
} else if (id == 92) {
data.animation.paused = true;
initGui();
return;
} else if (id == 93) {
playingAnimation = false;
data.animation.paused = false;
showFirstFrame();
initGui();
return;
}
super.actionPerformed(guibutton);
}
// ========== Preview Rendering ==========
@Override
protected void drawItemPreview(int centerX, int centerY, int mouseX, int mouseY, float partialTicks) {
if (animation == null) return;
if (!currentIsBuiltIn && animation.id == -1) return;
// Scale NPC with panel size
float scale = Math.min(previewW, previewH) / 200f;
float renderZoom = zoomed * scale;
GL11.glColor4f(1, 1, 1, 1);
EntityLivingBase entity = this.npc;
GL11.glEnable(GL11.GL_COLOR_MATERIAL);
GL11.glPushMatrix();
GL11.glTranslatef(centerX, centerY, 60F);
GL11.glScalef(-renderZoom, renderZoom, renderZoom);
GL11.glRotatef(180F, 0.0F, 0.0F, 1.0F);
float f2 = entity.renderYawOffset;
float f3 = entity.rotationYaw;
float f4 = entity.rotationPitch;
float f7 = entity.rotationYawHead;
float f5 = (float) centerX - mouseX;
float f6 = (float) (centerY - 50) - mouseY;
GL11.glRotatef(135F, 0.0F, 1.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glRotatef(-135F, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(-(float) Math.atan(f6 / 800F) * 20F, 1.0F, 0.0F, 0.0F);
entity.prevRenderYawOffset = entity.renderYawOffset = rotation;
entity.prevRotationYaw = entity.rotationYaw = (float) Math.atan(f5 / 80F) * 40F + rotation;
entity.rotationPitch = -(float) Math.atan(f6 / 80F) * 20F;
entity.prevRotationYawHead = entity.rotationYawHead = entity.rotationYaw;
GL11.glTranslatef(0.0F, entity.yOffset, 1F);
RenderManager.instance.playerViewY = 180F;
ClientEventHandler.renderingEntityInGUI = true;
try {
RenderManager.instance.renderEntityWithPosYaw(entity, 0.0, 0.0, 0.0, 0.0F, 1.0F);
} catch (Exception ignored) {
}
ClientEventHandler.renderingEntityInGUI = false;
entity.prevRenderYawOffset = entity.renderYawOffset = f2;
entity.prevRotationYaw = entity.rotationYaw = f3;
entity.rotationPitch = f4;
entity.prevRotationYawHead = entity.rotationYawHead = f7;
GL11.glPopMatrix();
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit);
GL11.glDisable(GL11.GL_TEXTURE_2D);
OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit);
GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT);
}
@Override
protected void drawItemDetails(int x, int y, int w) {
if (animation == null) return;
if (!currentIsBuiltIn && animation.id == -1) return;
fontRendererObj.drawString(animation.name, x, y, 0xFFFFFF, true);
y += 14;
fontRendererObj.drawString(StatCollector.translateToLocal("animation.frames") + ": " + animation.frames.size(), x, y, 0xB5B5B5, false);
y += 12;
fontRendererObj.drawString(StatCollector.translateToLocal("stats.speed") + ": " + animation.speed, x, y, 0xB5B5B5, false);
y += 12;
String loopStr = animation.loop == 0 ? StatCollector.translateToLocal("gui.none") : animation.loop == 1 ? StatCollector.translateToLocal("animation.loop") : StatCollector.translateToLocal("animation.mirror");
fontRendererObj.drawString(StatCollector.translateToLocal("animation.loop") + ": " + loopStr, x, y, 0xB5B5B5, false);
if (currentIsBuiltIn) {
y += 12;
fontRendererObj.drawString(StatCollector.translateToLocal("gui.builtin.tag"), x, y, 0x55FF55, false);
}
}
// ========== Cleanup ==========
@Override
public void onGuiClosed() {
if (npc != null) {
npc.display.animationData.setEnabled(false);
}
super.onGuiClosed();
}
}
@@ -0,0 +1,191 @@
package noppes.npcs.client.gui.global;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.category.CategoryItemsRequestPacket;
import kamkeel.npcs.network.packets.request.category.CategoryListRequestPacket;
import kamkeel.npcs.network.packets.request.category.CategoryMoveItemPacket;
import kamkeel.npcs.network.packets.request.category.CategoryRemovePacket;
import kamkeel.npcs.network.packets.request.category.CategorySavePacket;
import kamkeel.npcs.network.packets.request.effects.EffectGetPacket;
import kamkeel.npcs.network.packets.request.effects.EffectRemovePacket;
import kamkeel.npcs.network.packets.request.effects.EffectClonePacket;
import kamkeel.npcs.network.packets.request.effects.EffectSavePacket;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.gui.SubGuiEffectGeneral;
import noppes.npcs.client.gui.util.GuiDirectoryCategorized;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.client.renderer.ImageData;
import noppes.npcs.constants.EnumCategoryType;
import noppes.npcs.controllers.CustomEffectController;
import noppes.npcs.controllers.data.Category;
import noppes.npcs.controllers.data.CustomEffect;
import noppes.npcs.entity.EntityNPCInterface;
import org.lwjgl.opengl.GL11;
import static noppes.npcs.client.gui.player.inventory.GuiCNPCInventory.specialIcons;
public class GuiEffectDirectory extends GuiDirectoryCategorized {
public CustomEffect effect = new CustomEffect();
public EntityNPCInterface npc;
public GuiEffectDirectory(EntityNPCInterface npc) {
super();
this.npc = npc;
}
@Override
protected String getTitle() { return "Effects"; }
@Override
protected void requestCategoryList() {
PacketClient.sendClient(new CategoryListRequestPacket(EnumCategoryType.EFFECT));
}
@Override
protected void requestItemsInCategory(int catId) {
PacketClient.sendClient(new CategoryItemsRequestPacket(EnumCategoryType.EFFECT, catId));
}
@Override
protected void requestItemData(int itemId) {
PacketClient.sendClient(new EffectGetPacket(itemId));
}
@Override
protected void onSaveCategory(Category cat) {
PacketClient.sendClient(new CategorySavePacket(EnumCategoryType.EFFECT, cat.writeNBT(new NBTTagCompound())));
}
@Override
protected void onRemoveCategory(int catId) {
PacketClient.sendClient(new CategoryRemovePacket(EnumCategoryType.EFFECT, catId));
}
@Override
protected void onAddItem(int catId) {
String name = "New";
while (itemData.containsKey(name)) name += "_";
CustomEffect newEffect = new CustomEffect(-1, name);
PacketClient.sendClient(new EffectSavePacket(newEffect.writeToNBT(false), ""));
}
@Override
protected void onRemoveItem(int itemId) {
PacketClient.sendClient(new EffectRemovePacket(itemId));
effect = new CustomEffect();
}
@Override
protected void onEditItem() {
if (effect != null && effect.id >= 0) {
setSubGui(new SubGuiEffectGeneral(this, effect));
}
}
@Override
protected void onCloneItem() {
if (effect != null && effect.id >= 0) {
PacketClient.sendClient(new EffectClonePacket(effect.id));
}
}
@Override
protected void onItemReceived(NBTTagCompound compound) {
effect = new CustomEffect();
effect.readFromNBT(compound);
setPrevItemName(effect.name);
if (effect.id != -1) {
CustomEffectController.getInstance().getCustomEffects().replace(effect.id, effect);
}
}
@Override
protected boolean hasSelectedItem() {
return effect != null && effect.id >= 0;
}
@Override
protected int getSelectedItemId() {
return effect != null ? effect.id : -1;
}
@Override
protected void sendMovePacket(int itemId, int destCatId) {
PacketClient.sendClient(new CategoryMoveItemPacket(EnumCategoryType.EFFECT, itemId, destCatId));
}
@Override
protected GuiScreen getWindowedVariant() {
return new GuiNPCManageEffects(npc);
}
@Override
protected void saveCurrentItem() {
if (effect != null && effect.id >= 0 && prevItemName != null && !prevItemName.isEmpty()) {
PacketClient.sendClient(new EffectSavePacket(effect.writeToNBT(false), prevItemName));
prevItemName = effect.name;
}
}
@Override
protected void onSubGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiEffectGeneral) {
if (effect != null && effect.id >= 0) {
setPrevItemName(effect.name);
if (selectedCatId >= 0) requestItemsInCategory(selectedCatId);
}
}
}
@Override
protected void drawItemPreview(int centerX, int centerY, int mouseX, int mouseY, float partialTicks) {
if (effect == null || effect.id == -1) return;
int iconRenderSize = Math.min(previewW, previewH) / 3;
iconRenderSize = Math.max(32, Math.min(iconRenderSize, 128));
int x = centerX - iconRenderSize / 2;
int y = centerY - iconRenderSize;
TextureManager textureManager = mc.getTextureManager();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
ImageData data = ClientCacheHandler.getImageData(effect.icon);
if (data.imageLoaded()) {
data.bindTexture();
int iconX = effect.iconX;
int iconY = effect.iconY;
int iconWidth = effect.getWidth();
int iconHeight = effect.getHeight();
int width = data.getTotalWidth();
int height = data.getTotalHeight();
func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height);
} else {
textureManager.bindTexture(new ResourceLocation("customnpcs", "textures/marks/question.png"));
func_152125_a(x, y, 0, 0, 1, 1, iconRenderSize, iconRenderSize, 1, 1);
}
GL11.glDisable(GL11.GL_DEPTH_TEST);
textureManager.bindTexture(specialIcons);
func_152125_a(x, y, 0, 224, 16, 16, iconRenderSize, iconRenderSize, 256, 256);
GL11.glEnable(GL11.GL_DEPTH_TEST);
}
@Override
protected void drawItemDetails(int x, int y, int w) {
if (effect == null || effect.id == -1) return;
String drawString = effect.getMenuName();
fontRendererObj.drawString(drawString, x, y, 0xFFFFFF, true);
y += 14;
fontRendererObj.drawString(StatCollector.translateToLocal("gui.name") + ": " + effect.name, x, y, 0xFFFFFF, false);
y += 12;
fontRendererObj.drawString(StatCollector.translateToLocal("effect.runsEveryX") + ": " + effect.everyXTick + "t", x, y, 0xB5B5B5, false);
y += 12;
fontRendererObj.drawString(StatCollector.translateToLocal("effect.defaultLength") + ": " + effect.length + "s", x, y, 0xB5B5B5, false);
}
}
@@ -0,0 +1,282 @@
package noppes.npcs.client.gui.global;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.category.CategoryItemsRequestPacket;
import kamkeel.npcs.network.packets.request.category.CategoryListRequestPacket;
import kamkeel.npcs.network.packets.request.category.CategoryMoveItemPacket;
import kamkeel.npcs.network.packets.request.category.CategoryRemovePacket;
import kamkeel.npcs.network.packets.request.category.CategorySavePacket;
import kamkeel.npcs.network.packets.request.linked.LinkedGetPacket;
import kamkeel.npcs.network.packets.request.linked.LinkedItemBuildPacket;
import kamkeel.npcs.network.packets.request.linked.LinkedItemRemovePacket;
import kamkeel.npcs.network.packets.request.linked.LinkedItemClonePacket;
import kamkeel.npcs.network.packets.request.linked.LinkedItemSavePacket;
import kamkeel.npcs.util.ColorUtil;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.ClientCacheHandler;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.item.SubGuiLinkedItem;
import noppes.npcs.client.gui.util.GuiDirectoryCategorized;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.client.renderer.ImageData;
import noppes.npcs.constants.EnumCategoryType;
import noppes.npcs.controllers.data.Category;
import noppes.npcs.controllers.data.LinkedItem;
import noppes.npcs.entity.EntityNPCInterface;
import org.lwjgl.opengl.GL11;
public class GuiLinkedItemDirectory extends GuiDirectoryCategorized {
public LinkedItem linkedItem = null;
public EntityNPCInterface npc;
public GuiLinkedItemDirectory(EntityNPCInterface npc) {
super();
this.npc = npc;
}
@Override
protected String getTitle() { return "Linked Items"; }
@Override
protected void requestCategoryList() {
PacketClient.sendClient(new CategoryListRequestPacket(EnumCategoryType.LINKED_ITEM));
}
@Override
protected void requestItemsInCategory(int catId) {
PacketClient.sendClient(new CategoryItemsRequestPacket(EnumCategoryType.LINKED_ITEM, catId));
}
@Override
protected void requestItemData(int itemId) {
LinkedGetPacket.GetItem(itemId);
}
@Override
protected void onSaveCategory(Category cat) {
PacketClient.sendClient(new CategorySavePacket(EnumCategoryType.LINKED_ITEM, cat.writeNBT(new NBTTagCompound())));
}
@Override
protected void onRemoveCategory(int catId) {
PacketClient.sendClient(new CategoryRemovePacket(EnumCategoryType.LINKED_ITEM, catId));
}
@Override
protected void onAddItem(int catId) {
String name = "New";
while (itemData.containsKey(name)) name += "_";
LinkedItem newItem = new LinkedItem(name);
PacketClient.sendClient(new LinkedItemSavePacket(newItem.writeToNBT(false), ""));
}
@Override
protected void onRemoveItem(int itemId) {
PacketClient.sendClient(new LinkedItemRemovePacket(itemId));
linkedItem = null;
}
@Override
protected void onEditItem() {
if (linkedItem != null && linkedItem.id >= 0) {
setSubGui(new SubGuiLinkedItem(this, linkedItem));
}
}
@Override
protected void onCloneItem() {
if (linkedItem != null && linkedItem.id >= 0) {
PacketClient.sendClient(new LinkedItemClonePacket(linkedItem.id));
}
}
@Override
protected void onItemReceived(NBTTagCompound compound) {
linkedItem = new LinkedItem();
linkedItem.readFromNBT(compound);
setPrevItemName(linkedItem.name);
}
@Override
protected boolean hasSelectedItem() {
return linkedItem != null && linkedItem.id >= 0;
}
@Override
protected int getSelectedItemId() {
return linkedItem != null ? linkedItem.id : -1;
}
@Override
protected void sendMovePacket(int itemId, int destCatId) {
PacketClient.sendClient(new CategoryMoveItemPacket(EnumCategoryType.LINKED_ITEM, itemId, destCatId));
}
@Override
protected GuiScreen getWindowedVariant() {
return new GuiNPCManageLinked(npc);
}
@Override
protected void saveCurrentItem() {
if (linkedItem != null && linkedItem.id >= 0 && prevItemName != null && !prevItemName.isEmpty()) {
PacketClient.sendClient(new LinkedItemSavePacket(linkedItem.writeToNBT(false), prevItemName));
prevItemName = linkedItem.name;
}
}
@Override
protected void onSubGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiLinkedItem) {
if (linkedItem != null && linkedItem.id >= 0) {
setPrevItemName(linkedItem.name);
if (selectedCatId >= 0) requestItemsInCategory(selectedCatId);
}
}
}
@Override
protected void initRightPanel(int startY) {
// Reserve space for: edit+build row, copy+remove row, ID label
int bottomH = (btnH + gap) * 2 + 14;
previewX = rightX;
previewY = contentY;
previewW = rightPanelW;
previewH = contentH - bottomH - gap;
int halfW = (rightPanelW - gap) / 2;
// Edit + Build on first row
int row1Y = contentY + contentH - btnH * 2 - gap;
GuiNpcButton editBtn = new GuiNpcButton(51, rightX, row1Y, halfW, btnH, "gui.edit");
editBtn.enabled = hasSelectedItem() && movePhase == 0;
addButton(editBtn);
GuiNpcButton buildBtn = new GuiNpcButton(56, rightX + halfW + gap, row1Y, halfW, btnH, "gui.build");
buildBtn.enabled = hasSelectedItem() && movePhase == 0;
addButton(buildBtn);
// Copy + Remove on second row
int row2Y = row1Y + btnH + gap;
GuiNpcButton cloneBtn = new GuiNpcButton(52, rightX, row2Y, halfW, btnH, "gui.copy");
cloneBtn.enabled = hasSelectedItem() && movePhase == 0;
addButton(cloneBtn);
GuiNpcButton removeBtn = new GuiNpcButton(53, rightX + halfW + gap, row2Y, halfW, btnH, "gui.remove");
removeBtn.enabled = hasSelectedItem() && movePhase == 0;
removeBtn.setTextColor(0xFF5555);
addButton(removeBtn);
}
@Override
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == 56 && linkedItem != null && linkedItem.id >= 0) {
PacketClient.sendClient(new LinkedItemBuildPacket(linkedItem.getId()));
return;
}
super.actionPerformed(guibutton);
}
@Override
protected void drawItemPreview(int centerX, int centerY, int mouseX, int mouseY, float partialTicks) {
if (linkedItem == null || linkedItem.id < 0) return;
int iconRenderSize = Math.min(previewW, previewH) / 3;
iconRenderSize = Math.max(32, Math.min(iconRenderSize, 128));
int x = centerX - iconRenderSize / 2;
int y = centerY - iconRenderSize;
TextureManager textureManager = mc.getTextureManager();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
ImageData imageData = ClientCacheHandler.getImageData(linkedItem.display.texture);
if (imageData.imageLoaded()) {
float[] colors = ColorUtil.hexToRGB(linkedItem.display.itemColor);
GL11.glColor3f(colors[0], colors[1], colors[2]);
imageData.bindTexture();
int iconWidth = imageData.getTotalWidth();
int iconHeight = imageData.getTotalHeight();
func_152125_a(x, y, 0, 0, iconWidth, iconHeight, iconRenderSize, iconRenderSize, iconWidth, iconHeight);
} else {
textureManager.bindTexture(new ResourceLocation("customnpcs", "textures/marks/question.png"));
func_152125_a(x, y, 0, 0, 1, 1, iconRenderSize, iconRenderSize, 1, 1);
}
GL11.glColor3f(1.0f, 1.0f, 1.0f);
}
@Override
protected void drawItemDetails(int x, int y, int w) {
if (linkedItem == null || linkedItem.id < 0) return;
fontRendererObj.drawString(linkedItem.name, x, y, 0xFFFFFF, true);
y += 14;
int labelColor = 0xffae0d;
fontRendererObj.drawString(StatCollector.translateToLocal("display.version") + ": " + linkedItem.version, x, y, labelColor, false);
y += 12;
labelColor = 0xff5714;
fontRendererObj.drawString(StatCollector.translateToLocal("display.maxStack") + ": " + linkedItem.stackSize, x, y, labelColor, false);
y += 12;
labelColor = 0xf7ca28;
fontRendererObj.drawString(StatCollector.translateToLocal("display.digSpeed") + ": " + linkedItem.digSpeed, x, y, labelColor, false);
y += 12;
labelColor = 0x29d6b9;
String[] useActions = {
StatCollector.translateToLocal("use_action.none"),
StatCollector.translateToLocal("use_action.block"),
StatCollector.translateToLocal("use_action.eat"),
StatCollector.translateToLocal("use_action.drink"),
StatCollector.translateToLocal("use_action.bow")
};
int useActionIndex;
switch (linkedItem.itemUseAction) {
case 0: useActionIndex = 0; break;
case 1: useActionIndex = 1; break;
case 2: useActionIndex = 4; break;
case 3: useActionIndex = 2; break;
case 4: useActionIndex = 3; break;
default: useActionIndex = 0; break;
}
fontRendererObj.drawString(StatCollector.translateToLocal("display.useAction") + ": " + useActions[useActionIndex], x, y, labelColor, false);
y += 12;
String[] armorOptions = {
StatCollector.translateToLocal("armor_type.none"),
StatCollector.translateToLocal("armor_type.all"),
StatCollector.translateToLocal("armor_type.head"),
StatCollector.translateToLocal("armor_type.chestplate"),
StatCollector.translateToLocal("armor_type.leggings"),
StatCollector.translateToLocal("armor_type.boots")
};
int armorIndex;
if (linkedItem.armorType == -2) armorIndex = 0;
else if (linkedItem.armorType == -1) armorIndex = 1;
else armorIndex = linkedItem.armorType + 2;
fontRendererObj.drawString(StatCollector.translateToLocal("display.armor") + ": " + armorOptions[armorIndex], x, y, labelColor, false);
y += 12;
labelColor = 0x7cff54;
fontRendererObj.drawString(StatCollector.translateToLocal("display.isTool") + ": " + ("" + linkedItem.isTool).toUpperCase(), x, y, labelColor, false);
y += 12;
fontRendererObj.drawString(StatCollector.translateToLocal("display.isNormalItem") + ": " + ("" + linkedItem.isNormalItem).toUpperCase(), x, y, labelColor, false);
y += 12;
labelColor = 0xce75fa;
fontRendererObj.drawString(StatCollector.translateToLocal("model.scale") + ": " + linkedItem.display.scaleX + ", " + linkedItem.display.scaleY + ", " + linkedItem.display.scaleZ, x, y, labelColor, false);
y += 12;
fontRendererObj.drawString(StatCollector.translateToLocal("model.rotate") + ": " + linkedItem.display.rotationX + ", " + linkedItem.display.rotationY + ", " + linkedItem.display.rotationZ, x, y, labelColor, false);
y += 12;
fontRendererObj.drawString(StatCollector.translateToLocal("model.translate") + ": " + linkedItem.display.translateX + ", " + linkedItem.display.translateY + ", " + linkedItem.display.translateZ, x, y, labelColor, false);
}
}
@@ -65,15 +65,22 @@ 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)
// Fullscreen button - FIRST
GuiNpcButton fullBtn = new GuiNpcButton(66, guiLeft + 368, guiTop + 8, 45, 20, "gui.fullscreen");
fullBtn.setTextColor(0x55FF55);
fullBtn.setHoverText("gui.fullscreen.tooltip");
this.addButton(fullBtn);
// Toggle button
String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom";
this.addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 56, 45, 20, toggleLabel));
GuiNpcButton toggleBtn = new GuiNpcButton(10, guiLeft + 368, guiTop + 36, 45, 20, toggleLabel);
toggleBtn.setTextColor(showingBuiltIn ? 0x55FFFF : 0xFFFFFF);
this.addButton(toggleBtn);
// 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"));
this.addButton(new GuiNpcButton(0, guiLeft + 368, guiTop + 60, 45, 20, "gui.add"));
this.addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 84, 45, 20, "gui.remove"));
}
if (scrollAnimations == null) {
@@ -198,6 +205,11 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
protected void actionPerformed(GuiButton guibutton) {
GuiNpcButton button = (GuiNpcButton) guibutton;
if (button.id == 66) {
mc.displayGuiScreen(new GuiAnimationDirectory(npc));
return;
}
// Toggle button
if (button.id == 10) {
showingBuiltIn = !showingBuiltIn;
@@ -411,6 +411,9 @@ public class GuiNPCManageDialogs extends GuiNPCInterface2 implements IScrollData
}
if (subgui instanceof SubGuiNpcDialog) {
saveType(true);
if (dialog != null && dialog.id >= 0) {
setPrevDialogName(dialog.title);
}
}
}
@@ -3,6 +3,7 @@ package noppes.npcs.client.gui.global;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.effects.EffectGetPacket;
import kamkeel.npcs.network.packets.request.effects.EffectRemovePacket;
import kamkeel.npcs.network.packets.request.effects.EffectClonePacket;
import kamkeel.npcs.network.packets.request.effects.EffectSavePacket;
import kamkeel.npcs.network.packets.request.effects.EffectsGetPacket;
import net.minecraft.client.gui.GuiButton;
@@ -57,15 +58,21 @@ public class GuiNPCManageEffects extends GuiNPCInterface2 implements ICustomScro
public void initGui() {
super.initGui();
addButton(new GuiNpcButton(0, guiLeft + 368, guiTop + 8, 45, 20, "gui.add"));
// Fullscreen button - FIRST
GuiNpcButton fullBtn = new GuiNpcButton(66, guiLeft + 368, guiTop + 8, 45, 20, "gui.fullscreen");
fullBtn.setTextColor(0x55FF55);
fullBtn.setHoverText("gui.fullscreen.tooltip");
addButton(fullBtn);
addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 32, 45, 20, "gui.remove"));
addButton(new GuiNpcButton(0, guiLeft + 368, guiTop + 36, 45, 20, "gui.add"));
addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 60, 45, 20, "gui.remove"));
getButton(1).enabled = effect != null && effect.id != -1;
addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 56, 45, 20, "gui.copy"));
addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 84, 45, 20, "gui.copy"));
getButton(2).enabled = effect != null && effect.id != -1;
addButton(new GuiNpcButton(3, guiLeft + 368, guiTop + 80, 45, 20, "gui.edit"));
addButton(new GuiNpcButton(3, guiLeft + 368, guiTop + 108, 45, 20, "gui.edit"));
getButton(3).enabled = effect != null && effect.id != -1;
if (scrollEffects == null) {
@@ -100,10 +107,14 @@ public class GuiNPCManageEffects extends GuiNPCInterface2 implements ICustomScro
displayGuiScreen(guiyesno);
}
} else if (button.id == 2) {
CustomEffect effect = this.effect.cloneEffect();
while (data.containsKey(effect.name))
effect.name += "_";
PacketClient.sendClient(new EffectSavePacket(effect.writeToNBT(false), ""));
if (effect != null && effect.id >= 0) {
PacketClient.sendClient(new EffectClonePacket(effect.id));
}
}
if (button.id == 66) {
mc.displayGuiScreen(new GuiEffectDirectory(npc));
return;
}
if (effect == null)
@@ -173,7 +184,7 @@ public class GuiNPCManageEffects extends GuiNPCInterface2 implements ICustomScro
int iconWidth = effect.getWidth();
int iconHeight = effect.getHeight();
int width = data.getTotalWidth();
int height = data.getTotalWidth();
int height = data.getTotalHeight();
func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height);
@@ -5,6 +5,7 @@ import kamkeel.npcs.network.packets.request.linked.LinkedGetAllPacket;
import kamkeel.npcs.network.packets.request.linked.LinkedGetPacket;
import kamkeel.npcs.network.packets.request.linked.LinkedItemBuildPacket;
import kamkeel.npcs.network.packets.request.linked.LinkedItemRemovePacket;
import kamkeel.npcs.network.packets.request.linked.LinkedItemClonePacket;
import kamkeel.npcs.network.packets.request.linked.LinkedItemSavePacket;
import kamkeel.npcs.network.packets.request.linked.LinkedNPCAddPacket;
import kamkeel.npcs.network.packets.request.linked.LinkedNPCRemovePacket;
@@ -86,6 +87,15 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData,
int y = guiTop + 8;
// Fullscreen button - FIRST (only for Items tab)
if (tab == 1) {
GuiNpcButton fullBtn = new GuiNpcButton(66, guiLeft + 368, y, 45, 20, "gui.fullscreen");
fullBtn.setTextColor(0x55FF55);
fullBtn.setHoverText("gui.fullscreen.tooltip");
this.addButton(fullBtn);
y += 22;
}
this.addButton(new GuiNpcButton(10, guiLeft + 368, y, 45, 20, "gui.npcs"));
this.addButton(new GuiNpcButton(11, guiLeft + 368, y += 22, 45, 20, "gui.items"));
getButton(10).enabled = tab == 1;
@@ -216,6 +226,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData,
}
private List<String> getSearchList() {
if (data == null) return new ArrayList<String>();
if (search.isEmpty()) {
return new ArrayList<String>(this.data.keySet());
}
@@ -265,6 +276,11 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData,
scroll.setSelected("");
}
if (button.id == 66) {
mc.displayGuiScreen(new GuiLinkedItemDirectory(npc));
return;
}
if (linkedItem == null)
return;
@@ -273,13 +289,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData,
}
if (button.id == 4) {
if (data.containsKey(scroll.getSelected()) && linkedItem != null && linkedItem.id >= 0) {
String name = linkedItem.name;
while (data.containsKey(name))
name += "_";
LinkedItem linkedItemClone = this.linkedItem.clone();
linkedItemClone.name = name;
linkedItemClone.id = -1;
PacketClient.sendClient(new LinkedItemSavePacket(linkedItemClone.writeToNBT(false), ""));
PacketClient.sendClient(new LinkedItemClonePacket(this.linkedItem.id));
}
}
if (button.id == 5) {
@@ -401,6 +401,9 @@ public class GuiNPCManageQuest extends GuiNPCInterface2 implements IScrollData,
}
if (subgui instanceof SubGuiNpcQuest) {
saveType(true);
if (quest != null && quest.id >= 0) {
setPrevQuestName(quest.title);
}
}
}
@@ -1,11 +1,18 @@
package noppes.npcs.client.gui.global;
import kamkeel.npcs.client.renderer.TelegraphRenderer;
import kamkeel.npcs.controllers.AbilityController;
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.controllers.data.ability.AbilityVariant;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.network.PacketClient;
import java.util.UUID;
import kamkeel.npcs.network.packets.request.ability.BuiltInAbilityGetPacket;
import kamkeel.npcs.network.packets.request.ability.ChainedAbilitiesGetPacket;
import kamkeel.npcs.network.packets.request.ability.ChainedAbilityGetPacket;
import kamkeel.npcs.network.packets.request.ability.ChainedAbilityRemovePacket;
import kamkeel.npcs.network.packets.request.ability.ChainedAbilitySavePacket;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket;
import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket;
import kamkeel.npcs.network.packets.request.ability.CustomAbilityRemovePacket;
@@ -16,19 +23,19 @@ 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.SubGuiChainedAbilityConfig;
import noppes.npcs.client.gui.advanced.SubGuiDuplicateNameConfirm;
import noppes.npcs.client.gui.util.AbilityPreviewExecutor;
import noppes.npcs.client.gui.util.GuiAbilityInterface;
import kamkeel.npcs.controllers.data.ability.preview.AbilityPreviewExecutor;
import kamkeel.npcs.controllers.data.ability.gui.GuiAbilityInterface;
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.GuiTexturedButton;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.IChainedAbilityConfigCallback;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IScrollData;
@@ -42,33 +49,71 @@ import noppes.npcs.entity.EntityNPCInterface;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
/**
* Global GUI for managing saved ability presets with 3D preview.
*
* <p>
* Features:
* - Left side: 3D preview of NPC with ability effects
* - Right side: Ability list with search
* - Play/Pause/Stop buttons to preview abilities
* - Toggle between Custom and Built-in ability views
*/
public class GuiNpcManageAbilities extends GuiAbilityInterface
implements ICustomScrollListener, ISubGuiListener, IAbilityConfigCallback,
ITextfieldListener, GuiYesNoCallback, IScrollData, IGuiData {
implements ICustomScrollListener, ISubGuiListener, IAbilityConfigCallback,
IChainedAbilityConfigCallback, ITextfieldListener, GuiYesNoCallback,
IScrollData, IGuiData {
// ── Button IDs ────────────────────────────────────────────────────────────
private static final int BTN_REMOVE = 1;
private static final int BTN_ADD = 2;
private static final int BTN_TOGGLE_VIEW = 10;
private static final int BTN_EDIT = 100;
private static final int BTN_PREVIEW_PLAY = 91;
private static final int BTN_PREVIEW_PAUSE = 92;
private static final int BTN_PREVIEW_STOP = 93;
private static final int BTN_USER_TYPE_FILTER = 11;
// ── TextField / Label IDs ─────────────────────────────────────────────────
private static final int TF_SEARCH = 55;
private static final int LBL_PREVIEW_STATUS = 90;
// ── Scroll IDs ────────────────────────────────────────────────────────────
private static final int SCROLL_MAIN = 0;
// ── Confirm dialog IDs ────────────────────────────────────────────────────
private static final int CONFIRM_REMOVE_ABILITY = 1;
private static final int CONFIRM_REMOVE_CHAIN = 2;
// ==================== DATA ====================
private GuiCustomScroll scroll;
private HashMap<String, Integer> abilityData = new HashMap<>();
/** Maps display name -> UUID for custom abilities */
private final HashMap<String, String> displayToUuid = new HashMap<>();
private HashMap<String, Integer> customData = new HashMap<>();
private HashMap<String, Integer> builtInData = new HashMap<>();
private String selected = null;
private String selectedUuid = null;
private String search = "";
private Ability selectedAbility = null;
// ==================== VIEW MODE ====================
// 0 = Custom, 1 = Built-in, 2 = Chained
private int viewMode = 0;
private boolean showingBuiltIn = false;
private boolean showingChained = false;
private boolean currentIsBuiltIn = false;
// ==================== USER TYPE FILTER ====================
// 0 = Both, 1 = NPC Only, 2 = Player Only
private int userTypeFilter = 0;
private static final String[] USER_TYPE_FILTER_LABELS = {"gui.both", "gui.npcs", "gui.players"};
// ==================== CHAINED DATA ====================
private HashMap<String, Integer> chainedData = new HashMap<>();
private ChainedAbility selectedChain = null;
private ChainedAbility pendingSaveChain = null;
// ==================== PENDING SAVE ====================
private Ability pendingSaveAbility = null;
private boolean pendingNewCreation = false;
// ==================== PENDING VARIANT ====================
private String pendingTypeId = null;
@@ -88,7 +133,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
previewExecutor = new AbilityPreviewExecutor();
previewExecutor.setParentGui(this);
// Request ability data from server
// Request ability data from server (sends both custom and built-in)
PacketClient.sendClient(new CustomAbilitiesGetPacket());
// Enable animation data
@@ -100,42 +145,68 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
public void initGui() {
super.initGui();
// Add button
addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 8, 45, 20, "gui.add"));
// Fullscreen button - FIRST
GuiNpcButton fullBtn = new GuiNpcButton(66, guiLeft + 368, guiTop + 8, 45, 20, "gui.fullscreen");
fullBtn.setTextColor(0x55FF55);
fullBtn.setHoverText("gui.fullscreen.tooltip");
addButton(fullBtn);
// Remove button
addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 30, 45, 20, "gui.remove"));
getButton(1).setEnabled(selected != null && !selected.isEmpty() && displayToUuid.containsKey(selected));
// Toggle button — cycles: Custom → Built-in → Chained
String toggleLabel = showingChained ? "gui.chained" : (showingBuiltIn ? "gui.builtin" : "gui.custom");
GuiNpcButton toggleBtn = new GuiNpcButton(BTN_TOGGLE_VIEW, guiLeft + 368, guiTop + 36, 45, 20, toggleLabel);
if (showingChained) toggleBtn.setTextColor(0xFFFF55);
else if (showingBuiltIn) toggleBtn.setTextColor(0x55FFFF);
else toggleBtn.setTextColor(0xFFFFFF);
addButton(toggleBtn);
// Edit button
addButton(new GuiNpcButton(100, guiLeft + 368, guiTop + 52, 45, 20, "gui.edit"));
getButton(100).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null);
if (showingChained) {
// Chained view buttons
addButton(new GuiNpcButton(BTN_ADD, guiLeft + 368, guiTop + 60, 45, 20, "gui.add"));
addButton(new GuiNpcButton(BTN_REMOVE, guiLeft + 368, guiTop + 84, 45, 20, "gui.remove"));
getButton(BTN_REMOVE).setEnabled(selected != null && !selected.isEmpty() && chainedData.containsKey(selected));
addButton(new GuiNpcButton(BTN_EDIT, guiLeft + 368, guiTop + 108, 45, 20, "gui.edit"));
getButton(BTN_EDIT).setEnabled(selected != null && !selected.isEmpty() && selectedChain != null);
} else if (!showingBuiltIn) {
// Custom view buttons
addButton(new GuiNpcButton(BTN_ADD, guiLeft + 368, guiTop + 60, 45, 20, "gui.add"));
addButton(new GuiNpcButton(BTN_REMOVE, guiLeft + 368, guiTop + 84, 45, 20, "gui.remove"));
getButton(BTN_REMOVE).setEnabled(selected != null && !selected.isEmpty() && customData.containsKey(selected));
if (!currentIsBuiltIn) {
addButton(new GuiNpcButton(BTN_EDIT, guiLeft + 368, guiTop + 108, 45, 20, "gui.edit"));
getButton(BTN_EDIT).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null);
}
}
// Scroll list of saved abilities (right side)
// Scroll list (right side)
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
scroll = new GuiCustomScroll(this, SCROLL_MAIN);
scroll.setSize(143, 185);
}
scroll.guiLeft = guiLeft + 220;
scroll.guiTop = guiTop + 4;
addScroll(scroll);
// Update scroll list
scroll.setList(getSearchList());
if (selected != null && displayToUuid.containsKey(selected)) {
if (selected != null) {
scroll.setSelected(selected);
}
// Search bar
addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 220, guiTop + 192, 143, 20, search));
addTextField(new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, guiLeft + 220, guiTop + 192, 143, 20, search));
// Show ability info only if one is selected
if (selectedAbility == null || selected == null) {
return;
// User type filter button (only for Custom and Built-in views)
if (!showingChained) {
addButton(new GuiNpcButton(BTN_USER_TYPE_FILTER, guiLeft + 368, guiTop + 192, 45, 20, USER_TYPE_FILTER_LABELS[userTypeFilter]));
}
// ID/Name label (below search bar)
addLabel(new GuiNpcLabel(10, "ID: " + selectedAbility.getId(), guiLeft + 220, guiTop + 215));
// Check if we have something to preview
if (showingChained) {
if (selectedChain == null || selected == null || selectedChain.getEntries().isEmpty()) {
return;
}
} else if (selectedAbility == null || selected == null) {
return;
}
// Play/Pause/Stop buttons (below model preview area)
String animTexture = "customnpcs:textures/gui/animation.png";
@@ -146,30 +217,42 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
boolean isActive = previewExecutor.isActive();
if (!isPlaying || isPaused) {
// Show Play button
String statusKey = isPaused ? "animation.paused" : "animation.stopped";
addLabel(new GuiNpcLabel(90, statusKey, guiLeft + playButtonOffsetX, guiTop + 198));
addButton(new GuiTexturedButton(91, "", guiLeft + playButtonOffsetX + 70, guiTop + 192, 11, 20, animTexture, 18, 71));
addLabel(new GuiNpcLabel(LBL_PREVIEW_STATUS, statusKey, guiLeft + playButtonOffsetX, guiTop + 198));
addButton(new GuiTexturedButton(BTN_PREVIEW_PLAY, "", guiLeft + playButtonOffsetX + 70, guiTop + 192, 11, 20, animTexture, 18, 71));
} else {
// Show Pause button
addLabel(new GuiNpcLabel(90, "animation.playing", guiLeft + playButtonOffsetX, guiTop + 198));
addButton(new GuiTexturedButton(92, "", guiLeft + playButtonOffsetX + 70, guiTop + 192, 14, 20, animTexture, 0, 71));
addLabel(new GuiNpcLabel(LBL_PREVIEW_STATUS, "animation.playing", guiLeft + playButtonOffsetX, guiTop + 198));
addButton(new GuiTexturedButton(BTN_PREVIEW_PAUSE, "", guiLeft + playButtonOffsetX + 70, guiTop + 192, 14, 20, animTexture, 0, 71));
}
if (isActive) {
// Show Stop button
addButton(new GuiTexturedButton(93, "", guiLeft + playButtonOffsetX + 90, guiTop + 192, 14, 20, animTexture, 33, 71));
addButton(new GuiTexturedButton(BTN_PREVIEW_STOP, "", guiLeft + playButtonOffsetX + 90, guiTop + 192, 14, 20, animTexture, 33, 71));
}
}
private HashMap<String, Integer> getCurrentData() {
if (showingChained) return chainedData;
return showingBuiltIn ? builtInData : customData;
}
private List<String> getSearchList() {
if (search.isEmpty()) {
return new ArrayList<>(displayToUuid.keySet());
}
HashMap<String, Integer> data = getCurrentData();
List<String> list = new ArrayList<>();
for (String name : displayToUuid.keySet()) {
if (name.toLowerCase().contains(search.toLowerCase())) {
list.add(name);
for (Map.Entry<String, Integer> entry : data.entrySet()) {
String name = entry.getKey();
// Apply search filter
if (!search.isEmpty() && !name.toLowerCase().contains(search.toLowerCase())) {
continue;
}
// Apply UserType filter (only for Custom and Built-in views)
if (!showingChained && userTypeFilter != 0) {
UserType ut = UserType.fromOrdinal(entry.getValue());
if (userTypeFilter == 1 && !ut.allowsNpc()) continue;
if (userTypeFilter == 2 && !ut.allowsPlayer()) continue;
}
list.add(name);
}
return list;
}
@@ -227,43 +310,111 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
int id = guibutton.id;
if (id == 2) {
// Fullscreen
if (id == 66) {
previewExecutor.stop();
mc.displayGuiScreen(new GuiAbilityDirectory(npc));
return;
}
// User type filter: Both → NPC → Player → Both
if (id == BTN_USER_TYPE_FILTER) {
userTypeFilter = (userTypeFilter + 1) % 3;
if (scroll != null) {
scroll.setList(getSearchList());
}
initGui();
return;
}
// Toggle: Custom → Built-in → Chained → Custom
if (id == BTN_TOGGLE_VIEW) {
if (!showingBuiltIn && !showingChained) {
// Custom → Built-in
showingBuiltIn = true;
showingChained = false;
} else if (showingBuiltIn) {
// Built-in → Chained
showingBuiltIn = false;
showingChained = true;
} else {
// Chained → Custom
showingChained = false;
showingBuiltIn = false;
}
selected = null;
selectedAbility = null;
selectedChain = null;
currentIsBuiltIn = false;
search = "";
previewExecutor.stop();
if (scroll != null) {
scroll.clear();
}
if (showingChained) {
PacketClient.sendClient(new ChainedAbilitiesGetPacket());
} else {
PacketClient.sendClient(new CustomAbilitiesGetPacket());
}
initGui();
return;
}
// Preview controls (shared across all views)
if (id == BTN_PREVIEW_PLAY) {
if (previewExecutor.isPaused()) {
previewExecutor.play();
} else if (showingChained && selectedChain != null) {
previewExecutor.startChainPreview(selectedChain, npc);
} else if (selectedAbility != null) {
previewExecutor.startPreview(selectedAbility, npc);
}
initGui();
return;
} else if (id == BTN_PREVIEW_PAUSE) {
previewExecutor.pause();
initGui();
return;
} else if (id == BTN_PREVIEW_STOP) {
previewExecutor.stop();
initGui();
return;
}
if (showingChained) {
if (id == BTN_ADD) {
// New chained ability
ChainedAbility newChain = new ChainedAbility("New Chain");
setSubGui(new SubGuiChainedAbilityConfig(newChain, this));
} else if (id == BTN_REMOVE && selected != null) {
GuiYesNo guiyesno = new GuiYesNo(this, selected, StatCollector.translateToLocal("gui.delete"), CONFIRM_REMOVE_CHAIN);
displayGuiScreen(guiyesno);
} else if (id == BTN_EDIT && selectedChain != null) {
previewExecutor.stop();
setSubGui(new SubGuiChainedAbilityConfig(selectedChain, this));
}
return;
}
if (id == BTN_ADD && !showingBuiltIn) {
// 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);
} else if (id == BTN_REMOVE && !showingBuiltIn && selected != null) {
GuiYesNo guiyesno = new GuiYesNo(this, selected, StatCollector.translateToLocal("gui.delete"), CONFIRM_REMOVE_ABILITY);
displayGuiScreen(guiyesno);
} else if (id == 100 && selectedAbility != null) {
} else if (id == BTN_EDIT && !showingBuiltIn && !currentIsBuiltIn && selectedAbility != null) {
// Edit
previewExecutor.stop();
setSubGui(selectedAbility.createConfigGui(this));
} else if (id == 91) {
// Play button
if (selectedAbility != null) {
if (previewExecutor.isPaused()) {
previewExecutor.play();
} else {
previewExecutor.startPreview(selectedAbility, npc);
}
initGui();
}
} else if (id == 92) {
// Pause button
previewExecutor.pause();
initGui();
} else if (id == 93) {
// Stop button
previewExecutor.stop();
initGui();
}
}
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(55) != null && getTextField(55).isFocused()) {
if (!search.equals(getTextField(55).getText())) {
search = getTextField(55).getText();
if (getTextField(TF_SEARCH) != null && getTextField(TF_SEARCH).isFocused()) {
if (!search.equals(getTextField(TF_SEARCH).getText())) {
search = getTextField(TF_SEARCH).getText();
scroll.resetScroll();
scroll.setList(getSearchList());
}
@@ -272,15 +423,20 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
if (scroll.id == 0) {
if (scroll.id == SCROLL_MAIN) {
String newSelection = scroll.getSelected();
if (newSelection != null && !newSelection.equals(selected)) {
previewExecutor.stop();
selected = newSelection;
selectedUuid = displayToUuid.get(selected);
if (selectedUuid != null) {
PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid));
if (showingChained) {
PacketClient.sendClient(new ChainedAbilityGetPacket(selected));
} else if (showingBuiltIn) {
currentIsBuiltIn = true;
PacketClient.sendClient(new BuiltInAbilityGetPacket(selected));
} else {
currentIsBuiltIn = false;
PacketClient.sendClient(new CustomAbilityGetPacket(selected));
}
}
}
@@ -288,9 +444,10 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
if (scroll.id == 0 && selection != null && !selection.isEmpty()) {
// Double-click to edit
if (selectedAbility != null) {
if (scroll.id == SCROLL_MAIN && selection != null && !selection.isEmpty()) {
if (showingChained && selectedChain != null) {
setSubGui(new SubGuiChainedAbilityConfig(selectedChain, this));
} else if (!showingBuiltIn && !showingChained && !currentIsBuiltIn && selectedAbility != null) {
previewExecutor.stop();
setSubGui(selectedAbility.createConfigGui(this));
}
@@ -301,22 +458,29 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
public void setData(Vector<String> list, HashMap<String, Integer> data, EnumScrollData type) {
if (type == EnumScrollData.CUSTOM_ABILITIES) {
String prevSelected = scroll != null ? scroll.getSelected() : null;
this.abilityData = data;
displayToUuid.clear();
for (String key : data.keySet()) {
// key format: "displayName\tUUID"
int tabIndex = key.indexOf('\t');
if (tabIndex > 0) {
String displayName = key.substring(0, tabIndex);
String uuid = key.substring(tabIndex + 1);
displayToUuid.put(displayName, uuid);
} else {
displayToUuid.put(key, key);
this.customData = data;
if (!showingBuiltIn && !showingChained && scroll != null) {
scroll.setList(getSearchList());
if (prevSelected != null && customData.containsKey(prevSelected)) {
scroll.setSelected(prevSelected);
}
}
if (scroll != null) {
initGui();
} else if (type == EnumScrollData.BUILTIN_ABILITIES) {
this.builtInData = data;
if (showingBuiltIn && scroll != null) {
scroll.setList(getSearchList());
if (prevSelected != null && displayToUuid.containsKey(prevSelected)) {
if (selected != null && builtInData.containsKey(selected)) {
scroll.setSelected(selected);
}
}
initGui();
} else if (type == EnumScrollData.CHAINED_ABILITIES) {
String prevSelected = scroll != null ? scroll.getSelected() : null;
this.chainedData = data;
if (showingChained && scroll != null) {
scroll.setList(getSearchList());
if (prevSelected != null && chainedData.containsKey(prevSelected)) {
scroll.setSelected(prevSelected);
}
}
@@ -326,6 +490,21 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
@Override
public void setGuiData(NBTTagCompound compound) {
// Detect chained ability response (has "Entries" tag)
if (showingChained && compound.hasKey("Entries")) {
selectedChain = new ChainedAbility();
selectedChain.readNBT(compound);
selected = selectedChain.getName();
if (scroll != null) {
scroll.setSelected(selected);
}
initGui();
return;
}
// Check if this is a built-in ability response
currentIsBuiltIn = compound.hasKey("BuiltIn") && compound.getBoolean("BuiltIn");
// Received ability data from server
selectedAbility = AbilityController.Instance.fromNBT(compound);
if (selectedAbility != null) {
@@ -348,97 +527,115 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiChainedAbilityConfig) {
handleChainConfigClosed();
initGui();
return;
}
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;
if (handleVariantSelectClosed((SubGuiAbilityVariantSelect) subgui)) return;
} 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;
}
}
if (handleTypeSelectClosed((SubGuiAbilityTypeSelect) subgui)) 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;
}
}
if (handleDuplicateNameClosed((SubGuiDuplicateNameConfirm) subgui)) 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;
if (handlePendingSave()) return;
}
initGui();
}
private void saveAndOpenConfig(Ability ability) {
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
private void handleChainConfigClosed() {
if (pendingSaveChain != null) {
PacketClient.sendClient(new ChainedAbilitySavePacket(pendingSaveChain.writeNBT(false)));
selected = pendingSaveChain.getName();
pendingSaveChain = null;
}
}
/**
* @return true if a SubGui was opened (caller should return early, skipping initGui)
*/
private boolean handleVariantSelectClosed(SubGuiAbilityVariantSelect gui) {
int idx = gui.getSelectedIndex();
if (idx >= 0 && pendingTypeId != null) {
Ability newAbility = AbilityController.Instance.create(pendingTypeId);
if (newAbility != null) {
gui.getVariants().get(idx).apply(newAbility);
newAbility.setId(UUID.randomUUID().toString());
pendingTypeId = null;
openConfig(newAbility);
return true;
}
}
pendingTypeId = null;
return false;
}
/**
* @return true if a SubGui was opened (caller should return early, skipping initGui)
*/
private boolean handleTypeSelectClosed(SubGuiAbilityTypeSelect gui) {
String typeId = gui.getSelectedTypeId();
if (typeId != null) {
java.util.List<AbilityVariant> variants = AbilityController.Instance.getVariantsForType(typeId);
if (variants.size() > 1) {
pendingTypeId = typeId;
setSubGui(new SubGuiAbilityVariantSelect(variants));
return true;
}
Ability newAbility = AbilityController.Instance.create(typeId);
if (newAbility != null) {
if (variants.size() == 1) {
variants.get(0).apply(newAbility);
}
newAbility.setId(UUID.randomUUID().toString());
openConfig(newAbility);
return true;
}
}
return false;
}
/**
* @return true if a SubGui was opened (caller should return early, skipping initGui)
*/
private boolean handleDuplicateNameClosed(SubGuiDuplicateNameConfirm gui) {
if (pendingSaveAbility == null) return false;
if (gui.isConfirmed()) {
PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT(false)));
pendingSaveAbility = null;
return false;
}
if (gui.isBack()) {
Ability ability = pendingSaveAbility;
pendingSaveAbility = null;
setSubGui(ability.createConfigGui(this));
return true;
}
pendingSaveAbility = null;
return false;
}
/**
* @return true if a SubGui was opened (caller should return early, skipping initGui)
*/
private boolean handlePendingSave() {
if (hasDuplicateName(pendingSaveAbility)) {
setSubGui(new SubGuiDuplicateNameConfirm());
return true;
}
PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT(false)));
pendingSaveAbility = null;
return false;
}
private void openConfig(Ability ability) {
if (ability.isBuiltIn()) return; // Built-in abilities are immutable
selectedAbility = ability;
selected = ability.getName();
selectedUuid = ability.getId();
previewExecutor.stop();
setSubGui(ability.createConfigGui(this));
}
@@ -446,12 +643,12 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
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;
if (!customData.containsKey(name)) return false;
// Name exists — check if it belongs to a different ability (by UUID)
String uuid = ability.getId();
if (uuid == null || uuid.isEmpty()) return true; // New ability with conflicting name
Ability existing = AbilityController.Instance.getCustomAbilityByName(name);
return existing == null || !uuid.equals(existing.getId());
}
@Override
@@ -459,13 +656,18 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
NoppesUtil.openGUI(player, this);
if (!result) return;
if (id == 1 && selected != null && selectedUuid != null) {
PacketClient.sendClient(new CustomAbilityRemovePacket(selectedUuid));
if (id == CONFIRM_REMOVE_ABILITY && selected != null) {
PacketClient.sendClient(new CustomAbilityRemovePacket(selected));
scroll.clear();
selected = null;
selectedUuid = null;
selectedAbility = null;
initGui();
} else if (id == CONFIRM_REMOVE_CHAIN && selected != null) {
PacketClient.sendClient(new ChainedAbilityRemovePacket(selected));
scroll.clear();
selected = null;
selectedChain = null;
initGui();
}
}
@@ -475,6 +677,11 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
pendingSaveAbility = ability;
}
@Override
public void onChainedAbilitySaved(ChainedAbility chain) {
pendingSaveChain = chain;
}
@Override
public void unFocused(GuiNpcTextField textfield) {
// Search field handling is done in keyTyped
File diff suppressed because it is too large. Load diff
@@ -62,6 +62,12 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
this.addButton(new GuiNpcButton(1, guiLeft + 358, guiTop + 38, 58, 20, "gui.add"));
this.addButton(new GuiNpcButton(2, guiLeft + 358, guiTop + 61, 58, 20, "gui.remove"));
getButton(1).setHoverText("tooltip.naturalspawns.main.addProfile");
getButton(2).setHoverText("tooltip.naturalspawns.main.removeProfile");
if (getTextField(55) != null) {
getTextField(55).setHoverText("tooltip.naturalspawns.main.search");
}
if (this.spawn.id >= 0)
showSpawn();
@@ -74,15 +80,18 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
int y = guiTop + 30;
addLabel(new GuiNpcLabel(3, "spawning.biomes", guiLeft + 4, y));
addButton(new GuiNpcButton(3, guiLeft + 40, y - 5, 50, 20, "selectServer.edit"));
getButton(3).setHoverText("tooltip.naturalspawns.main.biomes");
addLabel(new GuiNpcLabel(11, StatCollector.translateToLocal("Dimensions"), guiLeft + 95, y));
addButton(new GuiNpcButton(11, guiLeft + 150, y - 5, 50, 20, "selectServer.edit"));
getButton(11).setHoverText("tooltip.naturalspawns.main.dimensions");
addLabel(new GuiNpcLabel(4, "spawning.options", guiLeft + 4, y += 22));
addButton(new GuiNpcButton(4, guiLeft + 90, y - 5, 50, 20, "selectServer.edit"));
getButton(4).setHoverText("tooltip.naturalspawns.main.options");
addSlider(new GuiNpcSlider(this, 5, guiLeft + 4, y += 17, 180, 20, (float) this.spawn.itemWeight / 100));
addExtra(new GuiHoverText(1, "spawning.naturalInfo", guiLeft + 188, y + 5));
addExtra(new GuiHoverText(1, "spawning.naturalInfoPerformance", guiLeft + 188, y + 5));
this.spawnEntryScroll.guiLeft = guiLeft + 4;
this.spawnEntryScroll.guiTop = y + 40;
@@ -96,13 +105,17 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
addScroll(this.spawnEntryScroll);
addButton(new GuiNpcButton(21, guiLeft + 6, y += 20, 20, 20, "+"));
getButton(21).setHoverText("tooltip.naturalspawns.main.addEntry");
if (this.spawnEntryScroll.hasSelected()) {
int selected = Integer.parseInt(this.spawnEntryScroll.getSelected());
addButton(new GuiNpcButton(22, guiLeft + 32, y, 20, 20, "-"));
getButton(22).setHoverText("tooltip.naturalspawns.main.removeEntry");
GuiNpcTextField num = new GuiNpcTextField(25, this, guiLeft + 60, y += 10, 30, 20, "" + selected);
num.integersOnly = true;
addTextField(num);
getTextField(25).setHoverText("tooltip.naturalspawns.main.slot");
addButton(new GuiNpcButton(26, guiLeft + 92, y, 100, 20, this.getTitle(this.spawn.spawnCompounds.get(selected))));
getButton(26).setHoverText("tooltip.naturalspawns.main.selectEntry");
}
}
@@ -81,10 +81,10 @@ public class CompassHudComponent extends HudComponent {
ConfigClient.CompassEnabledProperty.set(ConfigClient.CompassEnabled);
ConfigClient.CompassOverlayX = posX;
ConfigClient.CompassOverlayXProperty.set(ConfigClient.CompassOverlayX);
ConfigClient.CompassOverlayXProperty.set((double) ConfigClient.CompassOverlayX);
ConfigClient.CompassOverlayY = posY;
ConfigClient.CompassOverlayYProperty.set(ConfigClient.CompassOverlayY);
ConfigClient.CompassOverlayYProperty.set((double) ConfigClient.CompassOverlayY);
ConfigClient.CompassOverlayScale = scale;
ConfigClient.CompassOverlayScaleProperty.set(ConfigClient.CompassOverlayScale);
@@ -2,5 +2,6 @@ package noppes.npcs.client.gui.hud;
public enum EnumHudComponent {
QuestTracker,
QuestCompass
QuestCompass,
AbilityHotbar
}
@@ -23,6 +23,7 @@ public class GuiHudEditor extends GuiScreen {
private final int HANDLE_SIZE = 10;
private final int RESET_POSITION_ID = 100;
private final int RESET_SIZE_ID = 104;
// IDs for cycle buttons.
private final int CYCLE_LEFT_ID = 101;
@@ -90,9 +91,11 @@ public class GuiHudEditor extends GuiScreen {
rowHeight += btn.height + spacingY;
}
}
// Always add the Reset Position button below the custom buttons.
GuiButton resetPos = new GuiButton(RESET_POSITION_ID, width / 2 - buttonWidth / 2, height - 70 - rowHeight, buttonWidth, 20, "Reset Position");
// Always add the Reset Position and Reset Size buttons below the custom buttons.
GuiButton resetSize = new GuiButton(RESET_SIZE_ID, startXRight, height - 70 - rowHeight, buttonWidth, 20, "Reset Size");
GuiButton resetPos = new GuiButton(RESET_POSITION_ID, startXLeft, height - 70 - rowHeight, buttonWidth, 20, "Reset Position");
buttonList.add(resetPos);
buttonList.add(resetSize);
}
// Now update (or add if missing) the cycle buttons at the very bottom.
@@ -149,10 +152,11 @@ public class GuiHudEditor extends GuiScreen {
int actualY = (int) (hud.posY / 100F * res.getScaledHeight());
int margin = 5;
int barWidth = 6; // same as WIDTH_BAR_SIZE
int barX = actualX + (int) (hud.overlayWidth * effectiveScale) + margin;
int barX = actualX + (int) ((hud.overlayWidth + margin) * effectiveScale);
int barY = actualY + (int) (((hud.overlayHeight - 20) / 2.0F) * effectiveScale);
int barHeight = (int) (20 * effectiveScale);
if (mouseX >= barX && mouseX <= barX + barWidth &&
int scaledBarWidth = Math.max(6, (int) (barWidth * effectiveScale));
if (mouseX >= barX && mouseX <= barX + scaledBarWidth &&
mouseY >= barY && mouseY <= barY + barHeight) {
resizingWidth = true;
selectedComponent = hud;
@@ -173,7 +177,8 @@ public class GuiHudEditor extends GuiScreen {
int absHeight = (int) (hud.overlayHeight * effectiveScale);
if (mouseX >= actualX && mouseX <= actualX + absWidth &&
mouseY >= actualY && mouseY <= actualY + absHeight) {
if (mouseX >= actualX + absWidth - HANDLE_SIZE && mouseY >= actualY + absHeight - HANDLE_SIZE) {
int scaledHandle = Math.max(8, (int) (HANDLE_SIZE * effectiveScale));
if (mouseX >= actualX + absWidth - scaledHandle && mouseY >= actualY + absHeight - scaledHandle) {
resizing = true;
selectedComponent = hud;
initialScale = hud.scale;
@@ -214,24 +219,33 @@ public class GuiHudEditor extends GuiScreen {
int newY = scaledHeight - (Mouse.getY() * scaledHeight / mc.displayHeight) - dragOffsetY;
if (newX < 0) newX = 0;
if (newY < 0) newY = 0;
if (newX + (int) (selectedComponent.overlayWidth * effectiveScale) > scaledWidth)
newX = scaledWidth - (int) (selectedComponent.overlayWidth * effectiveScale);
if (newY + (int) (selectedComponent.overlayHeight * effectiveScale) > scaledHeight)
newY = scaledHeight - (int) (selectedComponent.overlayHeight * effectiveScale);
selectedComponent.posX = (int) (100F * newX / scaledWidth);
selectedComponent.posY = (int) (100F * newY / scaledHeight);
int compW = (int) Math.ceil(selectedComponent.overlayWidth * effectiveScale);
int compH = (int) Math.ceil(selectedComponent.overlayHeight * effectiveScale);
if (newX + compW > scaledWidth)
newX = scaledWidth - compW;
if (newY + compH > scaledHeight)
newY = scaledHeight - compH;
selectedComponent.posX = 100F * newX / scaledWidth;
selectedComponent.posY = 100F * newY / scaledHeight;
}
if (resizing) {
int currentMouseX = Mouse.getX() * width / mc.displayWidth;
int deltaX = currentMouseX - initialMouseX;
selectedComponent.scale = initialScale + deltaX;
int currentMouseY = scaledHeight - (Mouse.getY() * scaledHeight / mc.displayHeight);
int actualX = (int) (selectedComponent.posX / 100F * scaledWidth);
int actualY = (int) (selectedComponent.posY / 100F * scaledHeight);
// Use diagonal distance ratio so the resize handle tracks the mouse
float initDist = (float) Math.sqrt((double)(initialMouseX - actualX) * (initialMouseX - actualX) + (double)(initialMouseY - actualY) * (initialMouseY - actualY));
float currDist = (float) Math.sqrt((double)(currentMouseX - actualX) * (currentMouseX - actualX) + (double)(currentMouseY - actualY) * (currentMouseY - actualY));
if (initDist > 1) {
selectedComponent.scale = (int) (initialScale * currDist / initDist);
}
if (selectedComponent.scale < 50) selectedComponent.scale = 50;
if (selectedComponent.scale > 300) selectedComponent.scale = 300;
if (selectedComponent.scale > 500) selectedComponent.scale = 500;
}
if (resizingWidth && (selectedComponent instanceof CompassHudComponent)) {
int currentMouseX = Mouse.getX() * width / mc.displayWidth;
int delta = currentMouseX - initialWidthMouseX;
selectedComponent.overlayWidth = initialOverlayWidth + delta;
selectedComponent.overlayWidth = initialOverlayWidth + (int) (delta / effectiveScale);
if (selectedComponent.overlayWidth < 50) selectedComponent.overlayWidth = 50;
if (selectedComponent.overlayWidth > 500) selectedComponent.overlayWidth = 500;
}
@@ -260,8 +274,13 @@ public class GuiHudEditor extends GuiScreen {
}
int centerX = (res.getScaledWidth() - compWidth) / 2;
int centerY = (res.getScaledHeight() - compHeight) / 2;
selectedComponent.posX = (int) (100F * centerX / res.getScaledWidth());
selectedComponent.posY = (int) (100F * centerY / res.getScaledHeight());
selectedComponent.posX = 100F * centerX / res.getScaledWidth();
selectedComponent.posY = 100F * centerY / res.getScaledHeight();
updateCustomButtons();
}
} else if (button.id == RESET_SIZE_ID) {
if (selectedComponent != null) {
selectedComponent.scale = 100;
updateCustomButtons();
}
} else if (button.id == CYCLE_LEFT_ID) {
@@ -8,7 +8,8 @@ import java.util.List;
public abstract class HudComponent {
// Stored as percentages (0-100) of the current screen resolution.
protected int posX = 50, posY = 50, scale = 100, textAlign = 0;
public float posX = 50, posY = 50;
protected int scale = 100, textAlign = 0;
public boolean enabled = true;
public boolean hasData = false;
@@ -39,6 +39,7 @@ public class QuestTrackingComponent extends HudComponent {
if (turnIn != null && !turnIn.isEmpty()) {
turnInLines.add(convertColorCodes(turnIn));
}
updateOverlayHeight();
}
/**
@@ -113,10 +114,10 @@ public class QuestTrackingComponent extends HudComponent {
@Override
public void save() {
ConfigClient.QuestOverlayX = posX;
ConfigClient.QuestOverlayXProperty.set(ConfigClient.QuestOverlayX);
ConfigClient.QuestOverlayXProperty.set((double) ConfigClient.QuestOverlayX);
ConfigClient.QuestOverlayY = posY;
ConfigClient.QuestOverlayYProperty.set(ConfigClient.QuestOverlayY);
ConfigClient.QuestOverlayYProperty.set((double) ConfigClient.QuestOverlayY);
ConfigClient.QuestOverlayScale = scale;
ConfigClient.QuestOverlayScaleProperty.set(ConfigClient.QuestOverlayScale);
@@ -218,8 +219,8 @@ public class QuestTrackingComponent extends HudComponent {
int compHeight = (int) (overlayHeight * effectiveScale);
int centerX = (res.getScaledWidth() - compWidth) / 2;
int centerY = (res.getScaledHeight() - compHeight) / 2;
posX = (int) (100F * centerX / res.getScaledWidth());
posY = (int) (100F * centerY / res.getScaledHeight());
posX = 100F * centerX / res.getScaledWidth();
posY = 100F * centerY / res.getScaledHeight();
} else {
super.onEditorButtonPressed(button);
}
@@ -239,6 +240,19 @@ public class QuestTrackingComponent extends HudComponent {
}
// ---------- Helper rendering methods ----------- (methods unchanged) ...
private void updateOverlayHeight() {
int lineHeight = mc.fontRenderer.FONT_HEIGHT + 4;
int contentHeight = 5;
contentHeight += questTitleLines.size() * lineHeight + 8;
contentHeight += questCategoryLines.size() * lineHeight + 8;
contentHeight += objectiveLines.size() * lineHeight;
if (!turnInLines.isEmpty()) {
contentHeight += 8;
}
contentHeight += turnInLines.size() * lineHeight;
overlayHeight = contentHeight;
}
private int renderTextBlock(List<String> lines, int startY, int align, int color) {
int y = startY;
FontRenderer font = mc.fontRenderer;
@@ -0,0 +1,716 @@
package noppes.npcs.client.gui.hud.ability;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.client.ClientAbilityState;
import noppes.npcs.client.KeyPressHandler;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.gui.hud.HudComponent;
import noppes.npcs.config.ConfigClient;
import noppes.npcs.controllers.data.AbilityHotbarData;
import noppes.npcs.controllers.data.PlayerAbilityHotbarData;
import noppes.npcs.controllers.data.PlayerData;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
@SideOnly(Side.CLIENT)
public class AbilityHotbarComponent extends HudComponent {
public static final int TOTAL_SLOTS = AbilityHotbarData.TOTAL_SLOTS;
private static final int BASE_SLOT_SIZE = 24;
private static final int BASE_SPACING = 28;
private static final int EDIT_HANDLE_SIZE = 10;
private AbilityHotbarSlotRenderer[] slots = new AbilityHotbarSlotRenderer[TOTAL_SLOTS];
// Filtered carousel: only filled slots + one deselect entry
// Each entry is a raw slot index (0-11), or -1 for the deselect slot
private int[] activeIndices = new int[0];
private int activeCenter = 0;
private float scrollOffset = 0f;
private long scrollStartTime = 0;
private static final long SCROLL_DURATION = 150;
private long lastUpdateTime = 0;
private static final long UPDATE_INTERVAL = 500;
// Debounce: delay sending selection packet
private String pendingSelectKey = null;
private long pendingSelectTime = 0;
private static final long SELECT_DEBOUNCE = 300;
// Grace period: don't let server state override local state after user interaction
private long lastUserCycleTime = 0;
private static final long USER_CYCLE_GRACE = 1000;
// Fade: when ShowAlways=false, fade in/out when HUD key is held
private float fadeAlpha = 0f;
private long lastFadeTime = 0;
private static final float FADE_SPEED = 3f; // per second — ~333ms full transition
private Minecraft mc;
public AbilityHotbarComponent(Minecraft mc) {
this.mc = mc;
updateOverlayDimensions();
for (int i = 0; i < TOTAL_SLOTS; i++) {
slots[i] = new AbilityHotbarSlotRenderer(i);
}
load();
}
private int getEffectiveVisibleSlots() {
int configMax = ConfigClient.AbilityHotbarVisibleSlots;
if (configMax != 3 && configMax != 5 && configMax != 7) configMax = 5;
int filledCount = activeIndices.length - 1; // subtract deselect slot
if (filledCount < 0) filledCount = 0;
if (filledCount < 5) return Math.min(configMax, 3);
if (filledCount < 7) return Math.min(configMax, 5);
return configMax;
}
private void updateOverlayDimensions() {
boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal;
int visibleSlots = getEffectiveVisibleSlots();
int span = BASE_SPACING * (visibleSlots - 1) + BASE_SLOT_SIZE;
int thick = BASE_SLOT_SIZE + 4;
if (isHorizontal) {
overlayWidth = span;
overlayHeight = thick;
} else {
overlayWidth = thick;
overlayHeight = span;
}
}
@Override
public void loadData(NBTTagCompound compound) {
}
@Override
public void load() {
posX = ConfigClient.AbilityHotbarX;
posY = ConfigClient.AbilityHotbarY;
scale = ConfigClient.AbilityHotbarScale;
enabled = ConfigClient.AbilityHotbarEnabled;
}
@Override
public void save() {
ConfigClient.AbilityHotbarX = posX;
ConfigClient.AbilityHotbarXProperty.set((double) posX);
ConfigClient.AbilityHotbarY = posY;
ConfigClient.AbilityHotbarYProperty.set((double) posY);
ConfigClient.AbilityHotbarScale = scale;
ConfigClient.AbilityHotbarScaleProperty.set(scale);
ConfigClient.AbilityHotbarEnabled = enabled;
ConfigClient.AbilityHotbarEnabledProperty.set(enabled);
ConfigClient.AbilityHotbarHorizontalProperty.set(ConfigClient.AbilityHotbarHorizontal);
ConfigClient.AbilityHotbarAltTextureProperty.set(ConfigClient.AbilityHotbarAltTexture);
ConfigClient.AbilityHotbarTextPositionProperty.set(ConfigClient.AbilityHotbarTextPosition);
ConfigClient.AbilityHotbarVisibleSlotsProperty.set(ConfigClient.AbilityHotbarVisibleSlots);
ConfigClient.AbilityHotbarShowAlwaysProperty.set(ConfigClient.AbilityHotbarShowAlways);
ConfigClient.AbilityHotbarTextVisibilityProperty.set(ConfigClient.AbilityHotbarTextVisibility);
if (ConfigClient.config.hasChanged()) {
ConfigClient.config.save();
}
}
@Override
public void renderOnScreen(float partialTicks) {
if (!enabled || isEditting) return;
if (mc.thePlayer == null || mc.currentScreen != null) return;
if (!hasAnyAbilities()) return;
// Fade logic: when ShowAlways=false, only show while HUD key is held
boolean showAlways = ConfigClient.AbilityHotbarShowAlways;
long now = Minecraft.getSystemTime();
if (!showAlways) {
boolean hudKeyHeld = isHudKeyHeld();
float dt = lastFadeTime > 0 ? (now - lastFadeTime) / 1000f : 0f;
dt = Math.min(dt, 0.1f); // cap to avoid jumps after pauses
lastFadeTime = now;
if (hudKeyHeld || pendingSelectKey != null || scrollOffset != 0f) {
fadeAlpha = Math.min(1f, fadeAlpha + FADE_SPEED * dt);
} else {
fadeAlpha = Math.max(0f, fadeAlpha - FADE_SPEED * dt);
}
if (fadeAlpha <= 0f) return;
} else {
fadeAlpha = 1f;
lastFadeTime = now;
}
long currentTime = Minecraft.getSystemTime();
if (currentTime - lastUpdateTime > UPDATE_INTERVAL) {
updateAbilities();
lastUpdateTime = currentTime;
}
// Flush debounced selection packet
if (pendingSelectKey != null && currentTime - pendingSelectTime >= SELECT_DEBOUNCE) {
PacketHandler.Instance.sendToServer(new AbilityHotbarSelectPacket(pendingSelectKey));
pendingSelectKey = null;
}
updateScrollAnimation();
updateOverlayDimensions();
if (activeIndices.length == 0) return;
ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal;
float effectiveScale = getEffectiveScale(sr);
int visibleSlots = getEffectiveVisibleSlots();
int half = visibleSlots / 2;
int actualX = (int) (posX / 100.0f * sr.getScaledWidth());
int actualY = (int) (posY / 100.0f * sr.getScaledHeight());
GL11.glPushMatrix();
GL11.glTranslatef(actualX, actualY, 0);
GL11.glScalef(effectiveScale, effectiveScale, 1);
int centerX = overlayWidth / 2;
int centerY = overlayHeight / 2;
boolean activePhase = ClientAbilityState.activePhase;
// Compute text visibility: 0=Shown, 1=Hidden, 2=Held
boolean showText;
int textVis = ConfigClient.AbilityHotbarTextVisibility;
if (textVis == 1) {
showText = false;
} else if (textVis == 2) {
showText = isHudKeyHeld();
} else {
showText = true;
}
for (int i = 0; i < TOTAL_SLOTS; i++) {
slots[i].updateNameFade();
}
for (int offset = -half; offset <= half; offset++) {
int activeIdx = ((activeCenter + offset) % activeIndices.length + activeIndices.length) % activeIndices.length;
int rawSlotIndex = activeIndices[activeIdx];
float visualPos = offset + scrollOffset;
float absDist = Math.abs(visualPos);
float slotScale;
if (absDist <= 1f) {
slotScale = 1.0f - 0.25f * absDist;
} else {
slotScale = 0.75f - 0.15f * (absDist - 1f);
}
slotScale = Math.max(0.1f, slotScale);
int scaledSize = Math.max(1, (int) (BASE_SLOT_SIZE * slotScale));
int cx, cy;
if (isHorizontal) {
cx = centerX + (int) (visualPos * BASE_SPACING);
cy = centerY;
} else {
cx = centerX;
cy = centerY + (int) (visualPos * BASE_SPACING);
}
float maxDist = half + 0.5f;
if (absDist > maxDist) continue;
float edgeAlpha = absDist > half - 0.5f ? 1f - (absDist - (half - 0.5f)) : 1f;
float slotAlpha = edgeAlpha * fadeAlpha;
boolean isCenter = (offset == 0 && scrollOffset == 0f);
// Compute per-slot cooldown progress (all slots, not just center)
float slotCooldown = 0f;
if (rawSlotIndex >= 0 && slots[rawSlotIndex].abilityKey != null) {
slotCooldown = getCooldownProgressForSlot(rawSlotIndex);
}
if (rawSlotIndex == -1) {
// Deselect slot — draw empty marker
drawDeselectSlot(cx, cy, scaledSize, isCenter, slotAlpha, activePhase);
} else {
slots[rawSlotIndex].drawCarousel(mc, sr, slotCooldown, cx, cy, scaledSize, isCenter, slotAlpha, showText, activePhase);
}
}
GL11.glPopMatrix();
}
private void drawDeselectSlot(int cx, int cy, int size, boolean isCenter, float alpha, boolean activePhase) {
float radius = size / 2f;
float baseAlpha = isCenter ? 0.9f : 0.6f;
float a = baseAlpha * alpha;
boolean altTexture = ConfigClient.AbilityHotbarAltTexture;
GL11.glPushMatrix();
GL11.glTranslatef(cx, cy, 0);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if (activePhase) {
if (isCenter) {
GL11.glColor4f(0.65f, 0.14f, 0.14f, a);
} else {
GL11.glColor4f(0.38f, 0.10f, 0.10f, a);
}
} else if (isCenter) {
GL11.glColor4f(0.5f, 0.2f, 0.2f, a);
} else {
GL11.glColor4f(0.3f, 0.3f, 0.3f, a);
}
if (altTexture) {
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(-radius, -radius);
GL11.glVertex2f(radius, -radius);
GL11.glVertex2f(radius, radius);
GL11.glVertex2f(-radius, radius);
GL11.glEnd();
} else {
GL11.glBegin(GL11.GL_TRIANGLE_FAN);
GL11.glVertex2f(0, 0);
for (int i = 0; i <= 32; i++) {
double angle = 2 * Math.PI * i / 32;
GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius));
}
GL11.glEnd();
}
// Draw X mark
if (activePhase) {
if (isCenter) {
GL11.glColor4f(1.0f, 0.45f, 0.35f, alpha);
} else {
GL11.glColor4f(0.75f, 0.30f, 0.30f, alpha * 0.8f);
}
} else if (isCenter) {
GL11.glColor4f(0.8f, 0.4f, 0.4f, alpha);
} else {
GL11.glColor4f(0.5f, 0.5f, 0.5f, alpha * 0.8f);
}
float xSize = radius * 0.4f;
GL11.glLineWidth(2.0f);
GL11.glBegin(GL11.GL_LINES);
GL11.glVertex2f(-xSize, -xSize);
GL11.glVertex2f(xSize, xSize);
GL11.glVertex2f(-xSize, xSize);
GL11.glVertex2f(xSize, -xSize);
GL11.glEnd();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(1, 1, 1, 1);
GL11.glPopMatrix();
}
@Override
public void renderEditing() {
isEditting = true;
updateOverlayDimensions();
ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
float effectiveScale = getEffectiveScale(sr);
boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal;
FontRenderer fr = mc.fontRenderer;
int visibleSlots = getEffectiveVisibleSlots();
int half = visibleSlots / 2;
int actualX = (int) (posX / 100.0f * sr.getScaledWidth());
int actualY = (int) (posY / 100.0f * sr.getScaledHeight());
GL11.glPushMatrix();
GL11.glTranslatef(actualX, actualY, 0);
GL11.glScalef(effectiveScale, effectiveScale, 1);
int centerX = overlayWidth / 2;
int centerY = overlayHeight / 2;
int[] slotCx = new int[visibleSlots];
int[] slotCy = new int[visibleSlots];
int[] slotSizes = new int[visibleSlots];
for (int offset = -half; offset <= half; offset++) {
float absDist = Math.abs(offset);
float slotScale;
if (absDist <= 1f) {
slotScale = 1.0f - 0.25f * absDist;
} else {
slotScale = 0.75f - 0.15f * (absDist - 1f);
}
slotScale = Math.max(0.1f, slotScale);
int scaledSize = Math.max(1, (int) (BASE_SLOT_SIZE * slotScale));
int cx, cy;
if (isHorizontal) {
cx = centerX + offset * BASE_SPACING;
cy = centerY;
} else {
cx = centerX;
cy = centerY + offset * BASE_SPACING;
}
int idx = offset + half;
slotCx[idx] = cx;
slotCy[idx] = cy;
slotSizes[idx] = scaledSize;
float radius = scaledSize / 2f;
boolean altTexture = ConfigClient.AbilityHotbarAltTexture;
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
float alpha = offset == 0 ? 0.9f : 0.6f;
if (offset == 0) {
GL11.glColor4f(0.8f, 0.8f, 0.2f, alpha);
} else {
GL11.glColor4f(0.4f, 0.4f, 0.4f, alpha);
}
if (altTexture) {
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(cx - radius, cy - radius);
GL11.glVertex2f(cx + radius, cy - radius);
GL11.glVertex2f(cx + radius, cy + radius);
GL11.glVertex2f(cx - radius, cy + radius);
GL11.glEnd();
} else {
GL11.glBegin(GL11.GL_TRIANGLE_FAN);
GL11.glVertex2f(cx, cy);
for (int i = 0; i <= 32; i++) {
double angle = 2 * Math.PI * i / 32;
GL11.glVertex2f(cx + (float) (Math.cos(angle) * radius), cy + (float) (Math.sin(angle) * radius));
}
GL11.glEnd();
}
}
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
for (int i = 0; i < visibleSlots; i++) {
String label = String.valueOf(i + 1);
float labelScale = slotSizes[i] / 24.0f;
if (labelScale < 0.4f) continue;
int textColor = (i == half) ? 0xFFFFFFFF : 0xAABBBBBB;
int textW = fr.getStringWidth(label);
GL11.glPushMatrix();
GL11.glTranslatef(slotCx[i], slotCy[i], 0);
GL11.glScalef(labelScale, labelScale, 1);
fr.drawString(label, -textW / 2, -fr.FONT_HEIGHT / 2, textColor);
GL11.glPopMatrix();
}
boolean altTexture = ConfigClient.AbilityHotbarAltTexture;
String modeLabel = altTexture ? "Square" : "Circle";
int modeLabelW = fr.getStringWidth(modeLabel);
fr.drawStringWithShadow(modeLabel, overlayWidth / 2 - modeLabelW / 2, overlayHeight + 2, 0xAA888888);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
net.minecraft.client.gui.Gui.drawRect(0, 0, overlayWidth, overlayHeight, 0x22000000);
drawRectOutline(0, 0, overlayWidth, overlayHeight, 0xCC66CC66);
int handleLeft = overlayWidth - EDIT_HANDLE_SIZE;
int handleTop = overlayHeight - EDIT_HANDLE_SIZE;
net.minecraft.client.gui.Gui.drawRect(handleLeft, handleTop, overlayWidth, overlayHeight, 0xFFE0E0E0);
drawRectOutline(handleLeft, handleTop, overlayWidth, overlayHeight, 0xFF5A5A5A);
net.minecraft.client.gui.Gui.drawRect(handleLeft + 2, handleTop + 7, handleLeft + 8, handleTop + 8, 0xAA666666);
net.minecraft.client.gui.Gui.drawRect(handleLeft + 4, handleTop + 5, handleLeft + 8, handleTop + 6, 0xAA666666);
net.minecraft.client.gui.Gui.drawRect(handleLeft + 6, handleTop + 3, handleLeft + 8, handleTop + 4, 0xAA666666);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(1, 1, 1, 1);
GL11.glPopMatrix();
}
@Override
public void addEditorButtons(List<GuiButton> buttonList) {
super.addEditorButtons(buttonList);
String orientLabel = ConfigClient.AbilityHotbarHorizontal ? "Horizontal" : "Vertical";
buttonList.add(new GuiButton(1, 0, 0, 120, 20, orientLabel));
String texLabel = ConfigClient.AbilityHotbarAltTexture ? "Square" : "Circle";
buttonList.add(new GuiButton(2, 0, 0, 120, 20, texLabel));
buttonList.add(new GuiButton(3, 0, 0, 120, 20, getTextPositionLabel()));
buttonList.add(new GuiButton(4, 0, 0, 120, 20, "Slots: " + ConfigClient.AbilityHotbarVisibleSlots));
buttonList.add(new GuiButton(5, 0, 0, 120, 20, ConfigClient.AbilityHotbarShowAlways ? "Show: Always" : "Show: Hold Key"));
buttonList.add(new GuiButton(6, 0, 0, 120, 20, getTextVisibilityLabel()));
}
@Override
public void onEditorButtonPressed(GuiButton button) {
if (button.id == 1) {
ConfigClient.AbilityHotbarHorizontal = !ConfigClient.AbilityHotbarHorizontal;
button.displayString = ConfigClient.AbilityHotbarHorizontal ? "Horizontal" : "Vertical";
updateOverlayDimensions();
} else if (button.id == 2) {
ConfigClient.AbilityHotbarAltTexture = !ConfigClient.AbilityHotbarAltTexture;
button.displayString = ConfigClient.AbilityHotbarAltTexture ? "Square" : "Circle";
} else if (button.id == 3) {
// Toggle between 1 (Above/Left) and 2 (Below/Right)
ConfigClient.AbilityHotbarTextPosition = ConfigClient.AbilityHotbarTextPosition == 1 ? 2 : 1;
button.displayString = getTextPositionLabel();
} else if (button.id == 4) {
int current = ConfigClient.AbilityHotbarVisibleSlots;
if (current <= 3) ConfigClient.AbilityHotbarVisibleSlots = 5;
else if (current <= 5) ConfigClient.AbilityHotbarVisibleSlots = 7;
else ConfigClient.AbilityHotbarVisibleSlots = 3;
button.displayString = "Slots: " + ConfigClient.AbilityHotbarVisibleSlots;
updateOverlayDimensions();
} else if (button.id == 5) {
ConfigClient.AbilityHotbarShowAlways = !ConfigClient.AbilityHotbarShowAlways;
button.displayString = ConfigClient.AbilityHotbarShowAlways ? "Show: Always" : "Show: Hold Key";
} else if (button.id == 6) {
ConfigClient.AbilityHotbarTextVisibility = (ConfigClient.AbilityHotbarTextVisibility + 1) % 3;
button.displayString = getTextVisibilityLabel();
} else {
super.onEditorButtonPressed(button);
}
}
private String getTextPositionLabel() {
boolean h = ConfigClient.AbilityHotbarHorizontal;
switch (ConfigClient.AbilityHotbarTextPosition) {
case 1: return h ? "Text: Above" : "Text: Left";
case 2: return h ? "Text: Below" : "Text: Right";
default: return h ? "Text: Below" : "Text: Right";
}
}
private String getTextVisibilityLabel() {
switch (ConfigClient.AbilityHotbarTextVisibility) {
case 0: return "Text: Shown";
case 1: return "Text: Hidden";
case 2: return "Text: Held";
default: return "Text: Shown";
}
}
// ═══════════════════════════════════════════════════════════════════
// Ability Update & Scroll
// ═══════════════════════════════════════════════════════════════════
private void updateAbilities() {
PlayerData playerData = ClientCacheHandler.playerData;
if (playerData == null) return;
PlayerAbilityHotbarData hotbarData = playerData.hotbarData;
if (hotbarData == null) return;
EntityPlayer clientPlayer = Minecraft.getMinecraft().thePlayer;
boolean globalBlock = clientPlayer != null && AbilityController.Instance != null
&& !AbilityController.Instance.canPlayerActivate(clientPlayer);
for (int i = 0; i < TOTAL_SLOTS; i++) {
AbilityHotbarData slotData = hotbarData.slots[i];
String key = slotData.isEmpty() ? null : slotData.abilityKey;
Ability ability = null;
IAbilityAction action = null;
if (key != null && AbilityController.Instance != null) {
if (globalBlock) {
key = null;
} else {
if (slotData.isChainKey()) {
action = AbilityController.Instance.resolveChainedAbility(slotData.getResolveKey());
} else {
ability = AbilityController.Instance.resolveAbility(key);
action = ability;
}
if (ability == null && action == null) key = null;
// Hide abilities whose player requirement is not met
if (action != null && clientPlayer != null && !action.isAvailableFor(clientPlayer)) {
key = null;
ability = null;
action = null;
}
}
}
slots[i].setAbility(key, ability, action);
}
// Rebuild active indices: filled slots + one deselect slot (-1)
ArrayList<Integer> active = new ArrayList<>();
for (int i = 0; i < TOTAL_SLOTS; i++) {
if (slots[i].abilityKey != null) {
active.add(i);
}
}
active.add(-1); // Deselect slot at the end
activeIndices = new int[active.size()];
for (int i = 0; i < active.size(); i++) {
activeIndices[i] = active.get(i);
}
// Clamp activeCenter
if (activeCenter >= activeIndices.length) {
activeCenter = 0;
}
// Don't override local selection state while user is scrolling, debounce is pending,
// or within the grace period after the last user interaction.
// This prevents the server state from fighting the local carousel position.
long now = Minecraft.getSystemTime();
if (pendingSelectKey != null || scrollOffset != 0f || (now - lastUserCycleTime < USER_CYCLE_GRACE)) {
return;
}
// Sync selected state and find which active index is selected
if (playerData.abilityData != null) {
String selectedKey = playerData.abilityData.getSelectedAbilityKey();
boolean foundSelected = false;
for (int i = 0; i < TOTAL_SLOTS; i++) {
AbilityHotbarData slotData = hotbarData.slots[i];
boolean sel = selectedKey != null && !slotData.isEmpty()
&& selectedKey.equals(slotData.abilityKey);
slots[i].setSelectedState(sel);
if (sel) {
// Find this slot's position in activeIndices
for (int j = 0; j < activeIndices.length; j++) {
if (activeIndices[j] == i) {
activeCenter = j;
foundSelected = true;
break;
}
}
}
}
if (!foundSelected) {
// No ability selected on server — center on deselect slot
for (int j = 0; j < activeIndices.length; j++) {
if (activeIndices[j] == -1) {
activeCenter = j;
break;
}
}
}
}
}
private boolean isHudKeyHeld() {
return KeyPressHandler.isHudKeyHeld();
}
public boolean hasAnyAbilities() {
PlayerData playerData = ClientCacheHandler.playerData;
if (playerData == null || playerData.hotbarData == null) return false;
return playerData.hotbarData.hasAnyAbilities();
}
/**
* Get cooldown progress for a hotbar slot.
* Per-ability cooldown abilities use their own cooldown; others use global.
* @return 1.0 = fully on cooldown, 0.0 = ready
*/
private float getCooldownProgressForSlot(int slotIndex) {
PlayerData playerData = ClientCacheHandler.playerData;
if (playerData == null || playerData.abilityData == null) return 0f;
String key = slots[slotIndex].abilityKey;
Ability ability = slots[slotIndex].ability;
IAbilityAction action = slots[slotIndex].action;
if (ability != null && ability.isPerAbilityCooldown()) {
return playerData.abilityData.getPerAbilityCooldownProgress(key);
} else if (action instanceof ChainedAbility && ((ChainedAbility) action).isPerAbilityCooldown()) {
return playerData.abilityData.getPerAbilityCooldownProgress(key);
} else {
return playerData.abilityData.getGlobalCooldownProgress();
}
}
public void onCycleNext() {
cycle(1);
}
public void onCyclePrev() {
cycle(-1);
}
private void cycle(int direction) {
if (!enabled) return;
if (mc.thePlayer == null || mc.currentScreen != null) return;
if (activeIndices.length == 0) return;
activeCenter = ((activeCenter + direction) % activeIndices.length + activeIndices.length) % activeIndices.length;
scrollOffset = direction;
long now = Minecraft.getSystemTime();
scrollStartTime = now;
lastUserCycleTime = now;
int rawSlotIndex = activeIndices[activeCenter];
// Update selection states locally
for (int i = 0; i < TOTAL_SLOTS; i++) {
slots[i].setSelectedState(i == rawSlotIndex);
}
// Debounce: queue the selection, don't send immediately
String keyToSend = rawSlotIndex >= 0 && slots[rawSlotIndex].abilityKey != null
? slots[rawSlotIndex].abilityKey : "";
pendingSelectKey = keyToSend;
pendingSelectTime = Minecraft.getSystemTime();
}
private void updateScrollAnimation() {
if (scrollOffset == 0f) return;
long now = Minecraft.getSystemTime();
float t = (float) (now - scrollStartTime) / SCROLL_DURATION;
t = Math.min(t, 1f);
float eased = easeOutCubic(t);
float initialOffset = scrollOffset < 0 ? -1f : 1f;
scrollOffset = initialOffset * (1f - eased);
if (t >= 1f) scrollOffset = 0f;
}
private float easeOutCubic(float x) {
float v = 1 - x;
return 1 - v * v * v;
}
public void refresh() {
updateAbilities();
lastUpdateTime = Minecraft.getSystemTime();
}
private void drawRectOutline(int left, int top, int right, int bottom, int color) {
net.minecraft.client.gui.Gui.drawRect(left, top, right, top + 1, color);
net.minecraft.client.gui.Gui.drawRect(left, bottom - 1, right, bottom, color);
net.minecraft.client.gui.Gui.drawRect(left, top, left + 1, bottom, color);
net.minecraft.client.gui.Gui.drawRect(right - 1, top, right, bottom, color);
}
}
@@ -0,0 +1,345 @@
package noppes.npcs.client.gui.hud.ability;
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.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.ScaledResolution;
import noppes.npcs.config.ConfigClient;
import noppes.npcs.controllers.data.PlayerData;
import org.lwjgl.opengl.GL11;
@SideOnly(Side.CLIENT)
public class AbilityHotbarSlotRenderer extends Gui {
private static final int CIRCLE_SEGMENTS = 32;
private static final long NAME_FADE_DURATION = 180;
public int index;
public String abilityKey = null;
public Ability ability = null;
public IAbilityAction action = null;
private AbilityIcon icon = null;
public boolean isSelected = false;
public float nameAlpha = 0f;
private boolean nameFadingIn = false;
private long nameFadeStartTime = 0;
public AbilityHotbarSlotRenderer(int index) {
this.index = index;
}
public void setAbility(String key, Ability ability, IAbilityAction action) {
this.abilityKey = key;
this.ability = ability;
this.action = action;
if (ability != null) {
this.icon = AbilityIcon.fromAbility(ability);
} else if (action instanceof ChainedAbility) {
this.icon = AbilityIcon.fromChainedAbility((ChainedAbility) action);
} else {
this.icon = null;
}
}
public void drawCarousel(Minecraft mc, ScaledResolution sr, float cooldownProgress,
int cx, int cy, int size, boolean isCenter, float slotAlpha,
boolean showText, boolean activePhase) {
float nameAlpha = this.nameAlpha;
boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal;
if (size <= 0 || slotAlpha <= 0) return;
float radius = size / 2f;
float baseAlpha = isCenter ? 0.9f : 0.6f;
float alpha = baseAlpha * slotAlpha;
GL11.glPushMatrix();
GL11.glTranslatef(cx, cy, 0);
boolean altTexture = ConfigClient.AbilityHotbarAltTexture;
float fillR;
float fillG;
float fillB;
float outlineR;
float outlineG;
float outlineB;
if (activePhase) {
if (isCenter) {
fillR = 0.95f;
fillG = 0.26f;
fillB = 0.22f;
outlineR = 1.0f;
outlineG = 0.52f;
outlineB = 0.28f;
} else {
fillR = 0.36f;
fillG = 0.14f;
fillB = 0.14f;
outlineR = 0.65f;
outlineG = 0.22f;
outlineB = 0.20f;
}
} else if (isCenter) {
fillR = 0.8f;
fillG = 0.8f;
fillB = 0.2f;
outlineR = 0.8f;
outlineG = 0.8f;
outlineB = 0.2f;
} else {
fillR = 0.4f;
fillG = 0.4f;
fillB = 0.4f;
outlineR = 1f;
outlineG = 1f;
outlineB = 1f;
}
if (altTexture) {
float baseR = activePhase ? 0.30f : 0.6f;
float baseG = activePhase ? 0.12f : 0.6f;
float baseB = activePhase ? 0.12f : 0.6f;
drawRoundedRect(-radius, -radius, radius, radius, baseR, baseG, baseB, 0.75f * alpha, false);
drawRoundedRect(-radius, -radius, radius, radius, fillR, fillG, fillB, alpha * 0.8f, true);
} else {
drawCircle(radius, outlineR, outlineG, outlineB, 0.66f * alpha, false);
drawCircle(radius, fillR, fillG, fillB, alpha * 0.8f, true);
}
// Toggle active indicator: subtle green outline
int toggleState = getToggleState();
if (toggleState > 0) {
float glowAlpha = 0.45f * slotAlpha;
if (altTexture) {
drawRoundedRect(-radius, -radius, radius, radius, 0.2f, 0.85f, 0.3f, glowAlpha, true);
} else {
drawCircle(radius, 0.2f, 0.85f, 0.3f, glowAlpha, true);
}
}
// Ability icon
if (icon != null) {
GL11.glPushMatrix();
float targetSize = size * 0.55f;
float iconNaturalSize = Math.max(icon.width, icon.height);
if (iconNaturalSize <= 0) iconNaturalSize = 16f;
float iconScale = targetSize / iconNaturalSize;
GL11.glScalef(iconScale, iconScale, 1);
icon.draw(toggleState, slotAlpha);
GL11.glColor4f(1, 1, 1, 1);
GL11.glPopMatrix();
}
// Cooldown overlay (all slots)
if (cooldownProgress > 0 && abilityKey != null) {
drawCooldownOverlay(radius, cooldownProgress, altTexture, slotAlpha);
}
GL11.glPopMatrix();
// Ability name on center slot (respects text position and visibility config)
int textPos = ConfigClient.AbilityHotbarTextPosition;
if (showText && isCenter && action != null && nameAlpha > 0) {
FontRenderer fr = mc.fontRenderer;
String name = getAbilityName();
if (name != null && !name.isEmpty()) {
int a = (int) (nameAlpha * 255) & 0xFF;
int nameColor = (a << 24) | (getNameColor() & 0x00FFFFFF);
int nameX, nameY;
if (isHorizontal) {
nameX = cx - fr.getStringWidth(name) / 2;
if (textPos == 1) {
nameY = cy - (int) radius - fr.FONT_HEIGHT - 2; // Above
} else {
nameY = cy + (int) radius + 2; // Below
}
} else {
nameY = cy - fr.FONT_HEIGHT / 2;
if (textPos == 1) {
nameX = cx - (int) radius - fr.getStringWidth(name) - 4; // Left
} else {
nameX = cx + (int) radius + 4; // Right
}
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1, 1, 1, nameAlpha);
fr.drawStringWithShadow(name, nameX, nameY, nameColor);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1, 1, 1, 1);
}
}
}
private void drawRoundedRect(float x1, float y1, float x2, float y2,
float r, float g, float b, float a, boolean outline) {
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(r, g, b, a);
if (outline) {
GL11.glLineWidth(2.0f);
GL11.glBegin(GL11.GL_LINE_LOOP);
} else {
GL11.glBegin(GL11.GL_QUADS);
}
GL11.glVertex2f(x1, y1);
GL11.glVertex2f(x2, y1);
GL11.glVertex2f(x2, y2);
GL11.glVertex2f(x1, y2);
GL11.glEnd();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glColor4f(1, 1, 1, 1);
}
private void drawCircle(float radius, float r, float g, float b, float a, boolean outline) {
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(r, g, b, a);
if (outline) {
GL11.glLineWidth(1.5f);
GL11.glBegin(GL11.GL_LINE_LOOP);
} else {
GL11.glBegin(GL11.GL_TRIANGLE_FAN);
GL11.glVertex2f(0, 0);
}
for (int i = 0; i <= CIRCLE_SEGMENTS; i++) {
double angle = 2 * Math.PI * i / CIRCLE_SEGMENTS;
GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius));
}
GL11.glEnd();
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glColor4f(1, 1, 1, 1);
}
/**
* Draw a cooldown overlay on the slot.
* progress: 1.0 = fully on cooldown (just started), 0.0 = ready
* Renders a filled shape covering the entire slot that transitions from red to green.
*/
private void drawCooldownOverlay(float radius, float progress, boolean altTexture, float slotAlpha) {
progress = Math.min(1f, Math.max(0f, progress));
if (progress <= 0f) return;
// Color: red (progress=1.0) → orange → yellow-green → green (progress→0.0)
float cr, cg, cb;
if (progress > 0.5f) {
float t = (progress - 0.5f) * 2f; // 1.0 at progress=1.0, 0.0 at progress=0.5
cr = 0.8f;
cg = 0.15f + 0.25f * (1f - t); // 0.15 → 0.4
cb = 0.1f;
} else if (progress > 0.2f) {
float t = (progress - 0.2f) / 0.3f; // 1.0 at 0.5, 0.0 at 0.2
cr = 0.8f * t + 0.3f * (1f - t); // 0.8 → 0.3
cg = 0.4f * t + 0.7f * (1f - t); // 0.4 → 0.7
cb = 0.1f;
} else {
float t = progress / 0.2f; // 1.0 at 0.2, 0.0 at 0.0
cr = 0.3f * t + 0.1f * (1f - t); // 0.3 → 0.1
cg = 0.7f * t + 0.7f * (1f - t); // 0.7
cb = 0.1f + 0.1f * (1f - t); // 0.1 → 0.2
}
// Semi-transparent so icon is visible underneath; fade out near end
float overlayAlpha = 0.5f * slotAlpha * Math.min(1f, progress * 3f);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(cr, cg, cb, overlayAlpha);
if (altTexture) {
// Square slot: full filled rectangle
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(-radius, -radius);
GL11.glVertex2f(radius, -radius);
GL11.glVertex2f(radius, radius);
GL11.glVertex2f(-radius, radius);
GL11.glEnd();
} else {
// Circle slot: full filled circle
GL11.glBegin(GL11.GL_TRIANGLE_FAN);
GL11.glVertex2f(0, 0);
for (int i = 0; i <= CIRCLE_SEGMENTS; i++) {
double angle = 2 * Math.PI * i / CIRCLE_SEGMENTS;
GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius));
}
GL11.glEnd();
}
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glColor4f(1, 1, 1, 1);
}
private String getAbilityName() {
if (ability != null) {
int state = getToggleState();
if (state > 0) {
String label = ability.getToggleStateLabel(state);
if (label != null) return label;
}
return ability.getDisplayName();
}
if (action instanceof ChainedAbility) return ((ChainedAbility) action).getDisplayName();
return action != null ? action.getName() : "";
}
private int getToggleState() {
if (ability == null || !ability.isToggleable()) return 0;
Minecraft mc = Minecraft.getMinecraft();
if (mc.thePlayer == null) return 0;
PlayerData playerData = PlayerData.get(mc.thePlayer);
if (playerData == null || playerData.abilityData == null) return 0;
return playerData.abilityData.getToggleState(abilityKey);
}
private int getNameColor() {
if (ability != null && ability.isToggleable()) {
return getToggleState() > 0 ? 0xFF55FF55 : 0xFFFF5555;
}
return 0xFFFFFFFF;
}
public void setSelectedState(boolean newSelectState) {
if (!isSelected && newSelectState) {
nameFadingIn = true;
nameFadeStartTime = Minecraft.getSystemTime();
}
if (isSelected && !newSelectState) {
nameFadingIn = false;
nameFadeStartTime = Minecraft.getSystemTime();
}
isSelected = newSelectState;
}
public void updateNameFade() {
long now = Minecraft.getSystemTime();
float t = (float) (now - nameFadeStartTime) / NAME_FADE_DURATION;
t = Math.min(1f, Math.max(0f, t));
if (nameFadingIn) {
nameAlpha = t;
} else {
nameAlpha = 1f - t;
}
}
}
@@ -0,0 +1,214 @@
package noppes.npcs.client.gui.hud.ability;
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.data.AbilityIconData;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.renderer.AnimationHelper;
import noppes.npcs.client.renderer.ImageData;
import org.lwjgl.opengl.GL11;
@SideOnly(Side.CLIENT)
public class AbilityIcon extends Gui {
private static final ResourceLocation FALLBACK_TEXTURE = new ResourceLocation("customnpcs", "textures/gui/ability_fallback.png");
// Backed by AbilityIconData
private final AbilityIconData data;
public int width;
public int height;
// Default icon layers (extracted from ability)
private Ability.DefaultIconLayer[] defaultLayers = null;
private int defaultIconWidth = 48;
private int defaultIconHeight = 48;
private AbilityIcon(AbilityIconData data) {
this.data = data;
this.width = data.width;
this.height = data.height;
}
public static AbilityIcon fromAbility(Ability ability) {
if (ability != null) {
AbilityIcon icon = new AbilityIcon(AbilityIconData.fromAbility(ability));
icon.defaultLayers = ability.getDefaultIconLayers();
icon.defaultIconWidth = ability.getDefaultIconWidth();
icon.defaultIconHeight = ability.getDefaultIconHeight();
return icon;
}
return fromDefaults();
}
public static AbilityIcon fromChainedAbility(ChainedAbility chain) {
if (chain != null) {
return new AbilityIcon(AbilityIconData.fromChainedAbility(chain));
}
return fromDefaults();
}
public static AbilityIcon fromAction(IAbilityAction action) {
if (action instanceof Ability) return fromAbility((Ability) action);
if (action instanceof ChainedAbility) return fromChainedAbility((ChainedAbility) action);
return fromDefaults();
}
private static AbilityIcon fromDefaults() {
return new AbilityIcon(AbilityIconData.fromCustomData(new NBTTagCompound()));
}
public void draw() {
draw(0);
}
public void draw(int state) {
draw(state, 1.0f);
}
public void draw(int state, float alpha) {
TextureManager renderEngine = Minecraft.getMinecraft().renderEngine;
GL11.glPushMatrix();
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if (data.isEnabled()) {
// Path 1: Custom icon — draw each active layer bottom-to-top
GL11.glScalef(data.scale, data.scale, 1);
boolean drewAny = false;
for (int i = 0; i < data.getLayerCount(); i++) {
AbilityIconData.Layer layer = data.getLayer(i);
if (!layer.hasTexture()) continue;
ImageData imageData = ClientCacheHandler.getImageData(layer.texture);
if (imageData != null && imageData.imageLoaded()) {
int tint = layer.tintColor;
float r = ((tint >> 16) & 0xFF) / 255f;
float g = ((tint >> 8) & 0xFF) / 255f;
float b = (tint & 0xFF) / 255f;
GL11.glColor4f(r, g, b, alpha);
renderEngine.bindTexture(imageData.getLocation());
Tessellator t = getLayerTessellator(imageData, layer, i == 0 ? state : 0);
t.draw();
drewAny = true;
}
}
if (!drewAny) {
GL11.glColor4f(1, 1, 1, alpha);
renderEngine.bindTexture(FALLBACK_TEXTURE);
getFallbackTessellator().draw();
}
} else if (hasDefaultLayers()) {
// Path 2: Default layers — draw each layer with its dynamic color
for (Ability.DefaultIconLayer defLayer : defaultLayers) {
String texPath = defLayer.getTextureForState(state);
if (texPath == null || texPath.isEmpty()) continue;
ImageData imageData = ClientCacheHandler.getImageData(texPath);
if (imageData != null && imageData.imageLoaded()) {
int color = defLayer.getColor();
float r = ((color >> 16) & 0xFF) / 255f;
float g = ((color >> 8) & 0xFF) / 255f;
float b = (color & 0xFF) / 255f;
GL11.glColor4f(r, g, b, alpha);
renderEngine.bindTexture(imageData.getLocation());
getDefaultIconTessellator().draw();
}
}
} else {
// Path 3: No custom icon, no default layers — generic fallback
GL11.glColor4f(1, 1, 1, alpha);
renderEngine.bindTexture(FALLBACK_TEXTURE);
getFallbackTessellator().draw();
}
GL11.glPopMatrix();
}
private boolean hasDefaultLayers() {
return defaultLayers != null && defaultLayers.length > 0;
}
private Tessellator getLayerTessellator(ImageData imageData, AbilityIconData.Layer layer, int state) {
float hw = data.width / 2f;
float hh = data.height / 2f;
float texW = imageData.getTotalWidth();
float texH = imageData.getTotalHeight();
// State UV overrides only apply to layer 0
int ix = (state > 0) ? data.getIconXForState(state) : layer.iconX;
int iy = (state > 0) ? data.getIconYForState(state) : layer.iconY;
// Animation V offset
float vOff = 0f;
if (imageData.isAnimated()) {
vOff = imageData.getCurrentFrameVOffset();
} else if (data.isAnimated()) {
vOff = AnimationHelper.getFrameVOffset((int) texH, data.getFrameCount(), data.getFrameTime());
}
float u1 = ix / texW;
float v1 = vOff + iy / texH;
float u2 = (ix + data.width) / texW;
float v2 = vOff + (iy + data.height) / texH;
Tessellator t = Tessellator.instance;
t.startDrawingQuads();
t.addVertexWithUV(-hw, hh, zLevel, u1, v2);
t.addVertexWithUV(hw, hh, zLevel, u2, v2);
t.addVertexWithUV(hw, -hh, zLevel, u2, v1);
t.addVertexWithUV(-hw, -hh, zLevel, u1, v1);
return t;
}
private Tessellator getDefaultIconTessellator() {
float hw = defaultIconWidth / 2f;
float hh = defaultIconHeight / 2f;
Tessellator t = Tessellator.instance;
t.startDrawingQuads();
t.addVertexWithUV(-hw, hh, zLevel, 0, 1);
t.addVertexWithUV(hw, hh, zLevel, 1, 1);
t.addVertexWithUV(hw, -hh, zLevel, 1, 0);
t.addVertexWithUV(-hw, -hh, zLevel, 0, 0);
return t;
}
private Tessellator getFallbackTessellator() {
float hw = 16f;
float hh = 16f;
Tessellator t = Tessellator.instance;
t.startDrawingQuads();
t.addVertexWithUV(-hw, hh, zLevel, 0, 1);
t.addVertexWithUV(hw, hh, zLevel, 1, 1);
t.addVertexWithUV(hw, -hh, zLevel, 1, 0);
t.addVertexWithUV(-hw, -hh, zLevel, 0, 0);
return t;
}
public boolean hasTexture() {
return data.isEnabled() || hasDefaultLayers();
}
/**
* Returns the approximate visual size (max dimension) that draw() produces.
* Custom icon: max(width,height) * scale. Default icon: max(defaultW,defaultH). Fallback: 32.
*/
public float getDrawSize() {
if (data.isEnabled()) {
return Math.max(width, height) * data.scale;
}
if (hasDefaultLayers()) {
return Math.max(defaultIconWidth, defaultIconHeight);
}
return 32f;
}
}
@@ -10,8 +10,10 @@ import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.CustomNpcResourceListener;
import noppes.npcs.client.renderer.AnimationHelper;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.global.GuiNPCManageLinked;
import noppes.npcs.client.gui.SubGuiTagSelect;
import net.minecraft.client.gui.GuiScreen;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.gui.util.GuiButtonBiDirectional;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
@@ -36,7 +38,7 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
private int tab = -1;
private int colorPicked = 0;
public SubGuiLinkedItem(GuiNPCManageLinked parent, LinkedItem linkedItem) {
public SubGuiLinkedItem(GuiScreen parent, LinkedItem linkedItem) {
this.linkedItem = linkedItem;
this.parent = parent;
this.originalName = linkedItem.name;
@@ -158,6 +160,8 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
}
GuiButtonBiDirectional useActionButton = new GuiButtonBiDirectional(6, x + 120, y, 100, 20, useActions, useActionIndex);
addButton(useActionButton);
addButton(new GuiNpcButton(40, x + 230, y, 100, 20, "gui.tags"));
y += spacing;
// Armor Type: BiDirectional button (None, All, Head, Chestplate, Leggings, Boots)
@@ -286,6 +290,31 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
scrollWindow.addLabel(new GuiNpcLabel(70, "display.durabilityShow", x, localY + 5, 0xFFFFFF));
GuiNpcButtonYesNo durabilityButton = new GuiNpcButtonYesNo(26, x + 120, localY, linkedItem.display.durabilityShow);
scrollWindow.addButton(durabilityButton);
localY += 30;
// Animation controls
scrollWindow.addLabel(new GuiNpcLabel(80, "gui.animated", x, localY + 5, 0xFFFFFF));
boolean isAnim = linkedItem.display.animated != null && linkedItem.display.animated;
GuiNpcButtonYesNo animBtn = new GuiNpcButtonYesNo(29, x + 120, localY, isAnim);
animBtn.setHoverText("gui.animated.hover");
scrollWindow.addButton(animBtn);
localY += 25;
if (isAnim) {
scrollWindow.addLabel(new GuiNpcLabel(81, "gui.frameCount", x, localY + 5, 0xFFFFFF));
GuiNpcTextField fcField = new GuiNpcTextField(71, this, x + 120, localY, 60, 20,
"" + (linkedItem.display.frameCount != null ? linkedItem.display.frameCount : 1));
fcField.setIntegersOnly().setMinMaxDefault(1, 256, 1);
scrollWindow.addTextField(fcField);
localY += 25;
scrollWindow.addLabel(new GuiNpcLabel(82, "gui.frameTime", x, localY + 5, 0xFFFFFF));
GuiNpcTextField ftField = new GuiNpcTextField(72, this, x + 120, localY, 60, 20,
"" + (linkedItem.display.frametime != null ? linkedItem.display.frametime : 2));
ftField.setIntegersOnly().setMinMaxDefault(1, 100, 2);
scrollWindow.addTextField(ftField);
localY += 25;
}
scrollWindow.scrollY = 0;
scrollWindow.maxScrollY = Math.max(localY - scrollWindow.clipHeight, 0);
@@ -310,6 +339,9 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
PacketClient.sendClient(new LinkedItemSavePacket(linkedItem.writeToNBT(false), originalName));
GuiScriptInterface.open(this.parent, new LinkedItemScript(linkedItem.id));
return;
} else if (id == 40) {
setSubGui(new SubGuiTagSelect(linkedItem.tagUUIDs));
return;
} else if (id == 20) {
// Open confirmation for version bump.
GuiYesNo guiyesno = new GuiYesNo(this, "Confirm", "Bump version and update all linked items?", 20);
@@ -381,6 +413,9 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
linkedItem.isNormalItem = ((GuiNpcButtonYesNo) guibutton).getBoolean();
} else if (id == 26 && guibutton instanceof GuiNpcButtonYesNo) {
linkedItem.display.durabilityShow = ((GuiNpcButtonYesNo) guibutton).getBoolean();
} else if (id == 29 && guibutton instanceof GuiNpcButtonYesNo) {
linkedItem.display.animated = ((GuiNpcButtonYesNo) guibutton).getBoolean();
initGui();
}
}
@@ -429,6 +464,10 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
linkedItem.display.translateY = textField.getFloat();
} else if (id == 63) {
linkedItem.display.translateZ = textField.getFloat();
} else if (id == 71) {
linkedItem.display.frameCount = Math.max(1, textField.getInteger());
} else if (id == 72) {
linkedItem.display.frametime = Math.max(1, textField.getInteger());
}
}
@@ -472,7 +511,20 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
int iconWidth = data.getTotalWidth();
int iconHeight = data.getTotalWidth();
int width = data.getTotalWidth();
int height = data.getTotalWidth();
int height = data.getTotalHeight();
// Animation V offset for preview
if (data.isAnimated()) {
iconY += (int) (data.getCurrentFrameVOffset() * height);
iconHeight = data.getFrameHeight();
} else if (linkedItem.display.animated != null && linkedItem.display.animated
&& linkedItem.display.frameCount != null && linkedItem.display.frameCount > 1) {
iconY += (int) (AnimationHelper.getFrameVOffset(height, linkedItem.display.frameCount, linkedItem.display.frametime) * height);
iconHeight = height / linkedItem.display.frameCount;
} else {
iconHeight = data.getTotalWidth();
height = data.getTotalWidth();
}
float[] colors = ColorUtil.hexToRGB(linkedItem.display.itemColor);
GL11.glColor3f(colors[0], colors[1], colors[2]);
@@ -247,7 +247,7 @@ public class GuiNPCGlobalMainMenu extends GuiNPCInterface2 {
NoppesUtil.requestOpenGUI(EnumGuiType.ManageAbilities);
}
if (id == 22) {
// NoppesUtil.requestOpenGUI(EnumGuiType.ManageAuction);
NoppesUtil.requestOpenGUI(EnumGuiType.ManageAuction);
}
}
@@ -11,20 +11,23 @@ import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import noppes.npcs.client.AuctionClientConfig;
import noppes.npcs.client.gui.global.GuiNpcManageAuction;
import noppes.npcs.constants.EnumClaimType;
import noppes.npcs.containers.ContainerAuctionListing;
import noppes.npcs.containers.ContainerAuctionSell;
import noppes.npcs.containers.ContainerAuctionTrades;
import noppes.npcs.containers.ContainerManageAuction;
import noppes.npcs.containers.SlotAuctionDisplay;
import noppes.npcs.controllers.data.AuctionClaim;
import noppes.npcs.controllers.data.AuctionListing;
import noppes.npcs.util.AuctionFormatUtil;
import java.util.List;
/**
* Handles adding auction information to item tooltips when viewing auction GUIs.
* Called from ItemTooltipEvent in ClientEventHandler.
*
* <p>
* 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).
*/
@@ -48,6 +51,8 @@ public class AuctionTooltipHandler {
addTradesTooltip((GuiAuctionTrades) screen, event.itemStack, event.toolTip);
} else if (screen instanceof GuiAuctionSell) {
addSellTooltip((GuiAuctionSell) screen, event.itemStack, event.toolTip);
} else if (screen instanceof GuiNpcManageAuction) {
addManageAuctionTooltip((GuiNpcManageAuction) screen, event.itemStack, event.toolTip);
}
}
@@ -88,25 +93,25 @@ public class AuctionTooltipHandler {
// Current bid or starting price
if (listing.hasBids()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.currentBid)));
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.currentBid)));
tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), listing.bidCount));
} else {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.startingPrice")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.startingPrice)));
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.startingPrice)));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.noBids"));
}
// Buyout price
if (listing.hasBuyout()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.buyout")
.replace("%s", EnumChatFormatting.GREEN + formatCurrency(listing.buyoutPrice)));
.replace("%s", EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrencyWithName(listing.buyoutPrice)));
}
// Time remaining
long timeRemaining = listing.getTimeRemaining();
String timeText = StatCollector.translateToLocal("auction.timeLeft")
.replace("%s", formatTimeRemaining(timeRemaining));
tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
.replace("%s", AuctionFormatUtil.formatTimeRemaining(timeRemaining));
tooltip.add((AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
}
// ========== Trades Page ==========
@@ -144,7 +149,7 @@ public class AuctionTooltipHandler {
if (listing.hasBids()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.currentBid)));
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.currentBid)));
tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), listing.bidCount));
} else {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.noBids"));
@@ -152,8 +157,8 @@ public class AuctionTooltipHandler {
long timeRemaining = listing.getTimeRemaining();
String timeText = StatCollector.translateToLocal("auction.timeLeft")
.replace("%s", formatTimeRemaining(timeRemaining));
tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
.replace("%s", AuctionFormatUtil.formatTimeRemaining(timeRemaining));
tooltip.add((AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickToCancel"));
@@ -164,13 +169,13 @@ public class AuctionTooltipHandler {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.bidding"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.currentBid)));
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(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);
.replace("%s", AuctionFormatUtil.formatTimeRemaining(timeRemaining));
tooltip.add((AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.clickToRebid"));
@@ -210,7 +215,7 @@ public class AuctionTooltipHandler {
// Amount for currency claims
if (claim.type.isCurrency()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(claim.currency)));
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(claim.currency)));
}
// Expiration
@@ -254,48 +259,125 @@ public class AuctionTooltipHandler {
}
}
// ========== Formatting Utilities ==========
// ========== Global Manage Auction ==========
private static String formatCurrency(long amount) {
if (amount < 1000) {
return amount + " " + AuctionClientConfig.getCurrencyName();
}
StringBuilder sb = new StringBuilder();
String str = "" + amount;
int count = 0;
for (int i = str.length() - 1; i >= 0; i--) {
if (count > 0 && count % 3 == 0) {
sb.insert(0, ',');
private static void addManageAuctionTooltip(GuiNpcManageAuction gui, ItemStack stack, List<String> tooltip) {
Slot slot = findHoveredSlot(gui, stack);
if (slot == null) return;
ContainerManageAuction container = gui.getManageContainer();
if (container == null) return;
GuiNpcManageAuction.Tab tab = gui.getActiveTab();
if (tab == GuiNpcManageAuction.Tab.LISTINGS && container.isDisplaySlot(slot.slotNumber)) {
int displayIndex = container.toDisplayIndex(slot.slotNumber);
AuctionListing listing = container.getListingAtDisplay(displayIndex);
if (listing == null) return;
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.seller")
.replace("%s", EnumChatFormatting.WHITE + listing.sellerName));
if (listing.hasBids()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.currentBid)));
tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), listing.bidCount));
} else {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.startingPrice")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.startingPrice)));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.noBids"));
}
if (listing.hasBuyout()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.buyout")
.replace("%s", EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrencyWithName(listing.buyoutPrice)));
}
long timeRemaining = listing.getTimeRemaining();
String timeText = StatCollector.translateToLocal("auction.timeLeft")
.replace("%s", AuctionFormatUtil.formatTimeRemaining(timeRemaining));
tooltip.add((AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
tooltip.add("");
tooltip.add(EnumChatFormatting.AQUA + "Left-click: View details");
tooltip.add(EnumChatFormatting.GOLD + "Right-click: Stop player");
tooltip.add(EnumChatFormatting.LIGHT_PURPLE + "Shift+Right-click: Cancel to global");
return;
}
if (tab == GuiNpcManageAuction.Tab.CLAIMS && container.isDisplaySlot(slot.slotNumber)) {
int displayIndex = container.toDisplayIndex(slot.slotNumber);
AuctionClaim claim = container.getClaimAtDisplay(displayIndex);
if (claim != null) {
addGlobalClaimTooltip(claim, tooltip);
return;
}
AuctionListing listing = container.getListingAtDisplay(displayIndex);
if (listing != null) {
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.seller")
.replace("%s", EnumChatFormatting.WHITE + listing.sellerName));
if (listing.hasBids()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.currentBid)));
} else {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.startingPrice")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.startingPrice)));
}
if (listing.hasBuyout()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.buyout")
.replace("%s", EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrencyWithName(listing.buyoutPrice)));
}
tooltip.add("");
tooltip.add(EnumChatFormatting.GOLD + "Right-click: Stop player");
tooltip.add(EnumChatFormatting.LIGHT_PURPLE + "Shift+Right-click: Cancel to global");
}
return;
}
if (tab == GuiNpcManageAuction.Tab.CREATE) {
if (container.isCreateSlot(slot.slotNumber)) {
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.leftClear"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.rightRemove"));
} else if (container.isPlayerSlot(slot.slotNumber)) {
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.leftAdd"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.rightAddOne"));
}
sb.insert(0, str.charAt(i));
count++;
}
return sb.toString() + " " + AuctionClientConfig.getCurrencyName();
}
private static String formatTimeRemaining(long milliseconds) {
if (milliseconds <= 0) {
return StatCollector.translateToLocal("auction.ended");
private static void addGlobalClaimTooltip(AuctionClaim claim, List<String> tooltip) {
tooltip.add("");
if (claim.type == EnumClaimType.ITEM) {
tooltip.add(EnumChatFormatting.AQUA + "Global Item Claim");
} else if (claim.type == EnumClaimType.CURRENCY) {
tooltip.add(EnumChatFormatting.GOLD + "Global Currency Claim");
if (claim.itemName != null && !claim.itemName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.soldItem")
.replace("%s", EnumChatFormatting.WHITE + claim.itemName));
}
if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.buyer")
.replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName));
}
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(claim.currency)));
tooltip.add(EnumChatFormatting.GRAY + "Claiming this does not change your balance.");
} else if (claim.type == EnumClaimType.REFUND) {
tooltip.add(EnumChatFormatting.RED + "Global Refund Claim");
if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.outbidBy")
.replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName));
}
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount")
.replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(claim.currency)));
}
long seconds = (milliseconds / 1000) % 60;
long minutes = (milliseconds / 60000) % 60;
long hours = (milliseconds / 3600000) % 24;
long days = milliseconds / 86400000;
StringBuilder sb = new StringBuilder();
if (days > 0) {
sb.append(days).append("d ");
}
if (hours > 0 || days > 0) {
sb.append(hours).append("h ");
}
if (minutes > 0 || hours > 0 || days > 0) {
sb.append(minutes).append("m");
} else {
sb.append(seconds).append("s");
}
return sb.toString();
tooltip.add("");
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.claim.clickToClaim"));
}
}
@@ -15,6 +15,7 @@ import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.containers.ContainerAuctionBidding;
import noppes.npcs.controllers.data.AuctionListing;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.util.AuctionFormatUtil;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
@@ -36,7 +37,7 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis
private int btnBidY = 110;
private int btnBuyoutX = 82;
private int btnBuyoutY = 110;
private int infoX = 110;
private int infoX = 105;
private int infoY = 50;
// Button IDs
@@ -81,7 +82,9 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis
return -1;
}
/** Update button visibility based on listing state */
/**
* Update button visibility based on listing state
*/
private void updateButtonState() {
if (listing == null) {
if (btnBid != null) btnBid.setVisible(false);
@@ -123,7 +126,7 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis
private void openBidSubGui() {
if (listing == null) return;
long minBid = listing.getMinimumBid(AuctionClientConfig.getMinBidIncrement());
setSubGui(new SubGuiAuctionBid(listing.id, minBid, playerBalance));
setSubGui(new SubGuiAuctionBid(listing.id, minBid, listing.buyoutPrice, playerBalance));
}
private void openBuyNowSubGui() {
@@ -184,9 +187,11 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis
drawAuctionInfo();
}
/** Draw auction listing information on the right side */
/**
* Draw auction listing information on the right side
*/
private void drawAuctionInfo() {
int x = guiLeft + 105;
int x = guiLeft + infoX;
int y = guiTop + infoY;
int xRight = guiLeft + 215;
@@ -206,7 +211,7 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis
String bidLabel = StatCollector.translateToLocal("auction.info.currentBid") + ":";
fontRendererObj.drawString(EnumChatFormatting.YELLOW + bidLabel, x, y, 0xFFFFFF);
label = formatCurrency(listing.currentBid);
label = AuctionFormatUtil.formatCurrency(listing.currentBid);
length = fontRendererObj.getStringWidth(label);
fontRendererObj.drawString(EnumChatFormatting.GOLD + label, xRight - length, y, 0xFFFFFF);
y += lineHeight + 4;
@@ -223,9 +228,9 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis
String startLabel = StatCollector.translateToLocal("auction.info.startingPrice");
fontRendererObj.drawString(EnumChatFormatting.YELLOW + startLabel, x, y, 0xFFFFFF);
label = formatCurrency(listing.startingPrice);
label = AuctionFormatUtil.formatCurrency(listing.startingPrice);
length = fontRendererObj.getStringWidth(label);
fontRendererObj.drawString(EnumChatFormatting.GOLD + label, xRight - length, y, 0xFFFFFF);
fontRendererObj.drawString(EnumChatFormatting.GOLD + label, xRight - length, y, 0xFFFFFF);
y += lineHeight + 4;
}
@@ -234,9 +239,9 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis
String buyoutLabel = StatCollector.translateToLocal("auction.info.buyoutPrice");
fontRendererObj.drawString(EnumChatFormatting.GREEN + buyoutLabel, x, y, 0xFFFFFF);
label = formatCurrency(listing.buyoutPrice);
label = AuctionFormatUtil.formatCurrency(listing.buyoutPrice);
length = fontRendererObj.getStringWidth(label);
fontRendererObj.drawString(EnumChatFormatting.GREEN + label, xRight - length, y, 0xFFFFFF);
fontRendererObj.drawString(EnumChatFormatting.GREEN + label, xRight - length, y, 0xFFFFFF);
y += lineHeight + 4;
}
@@ -244,9 +249,9 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis
String timeLabel = StatCollector.translateToLocal("auction.info.timeLeft");
fontRendererObj.drawString(EnumChatFormatting.GRAY + timeLabel, x, y, 0xFFFFFF);
long timeRemaining = listing.getTimeRemaining();
EnumChatFormatting timeColor = timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE;
EnumChatFormatting timeColor = AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE;
label = timeColor + formatTimeRemaining(timeRemaining);
label = timeColor + AuctionFormatUtil.formatTimeRemaining(timeRemaining);
length = fontRendererObj.getStringWidth(label);
fontRendererObj.drawString(label, xRight - length, y, 0xFFFFFF);
y += lineHeight + 4;
@@ -278,14 +283,14 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis
if (listing != null) {
long minBid = listing.getMinimumBid(AuctionClientConfig.getMinBidIncrement());
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.bid.minimum")
.replace("%s", EnumChatFormatting.WHITE + formatCurrency(minBid) + " " + AuctionClientConfig.getCurrencyName()));
.replace("%s", EnumChatFormatting.WHITE + AuctionFormatUtil.formatCurrency(minBid) + " " + AuctionClientConfig.getCurrencyName()));
}
} else if (btnBuyout != null && btnBuyout.visible && btnBuyout.isHovered()) {
tooltip = new ArrayList<>();
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.bid.buyout"));
if (listing != null && listing.hasBuyout()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.info.buyoutPrice") + ":");
tooltip.add(EnumChatFormatting.GREEN + formatCurrency(listing.buyoutPrice) + " " + AuctionClientConfig.getCurrencyName());
tooltip.add(EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrency(listing.buyoutPrice) + " " + AuctionClientConfig.getCurrencyName());
}
}
@@ -305,5 +310,7 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis
// Block all slot interactions - view only
}
public AuctionListing getListing() { return listing; }
public AuctionListing getListing() {
return listing;
}
}
@@ -34,6 +34,9 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface {
public static final int PAGE_SELL = 1;
public static final int PAGE_CLAIMS = 2;
// Overlay color
protected static final int OVERLAY_DARK = 0xC0000000;
// Navigation button IDs
protected static final int BTN_NAV_LISTINGS = 100;
protected static final int BTN_NAV_SELL = 101;
@@ -66,7 +69,9 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface {
initNavigationButtons();
}
/** Initialize navigation buttons */
/**
* Initialize navigation buttons
*/
protected void initNavigationButtons() {
int page = getCurrentPage();
@@ -86,7 +91,9 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface {
addButton(btnClaims);
}
/** Returns current page constant - implement in subclass */
/**
* Returns current page constant - implement in subclass
*/
protected abstract int getCurrentPage();
@Override
@@ -133,7 +140,9 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface {
}
}
/** Draw navigation button tooltips */
/**
* Draw navigation button tooltips
*/
protected void drawNavButtonTooltips(int mouseX, int mouseY) {
List<String> tooltip = null;
if (btnListings != null && btnListings.isHovered()) tooltip = btnListings.getTooltipLines();
@@ -151,14 +160,18 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface {
// ========== Slot Drawing Utilities ==========
/** Draw auction slot background (18x18) */
/**
* Draw auction slot background (18x18)
*/
protected void drawAuctionSlot(int x, int y) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(AUCTION_SLOT);
Gui.func_146110_a(x, y, 0, 0, 18, 18, 18, 18);
}
/** Draw colored overlay on slot (ARGB format) */
/**
* Draw colored overlay on slot (ARGB format)
*/
protected void drawColoredOverlay(int x, int y, int color) {
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
@@ -170,12 +183,16 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
/** Draw dark overlay for unavailable slots */
/**
* Draw dark overlay for unavailable slots
*/
protected void drawDarkenedOverlay(int x, int y) {
drawColoredOverlay(x, y, 0xC0000000);
drawColoredOverlay(x, y, OVERLAY_DARK);
}
/** Draw icon texture on slot (16x16) */
/**
* Draw icon texture on slot (16x16)
*/
protected void drawIconOverlay(int x, int y, ResourceLocation icon) {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
@@ -189,42 +206,11 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface {
GL11.glPopMatrix();
}
/** Subclasses implement this to draw specific content */
/**
* Subclasses implement this to draw specific content
*/
protected abstract void drawAuctionContent(float partialTicks, int mouseX, int mouseY);
// ========== Formatting Utilities ==========
/** Format currency with commas (e.g., 1000 -> "1,000") */
protected String formatCurrency(long amount) {
if (amount < 1000) return "" + amount;
StringBuilder sb = new StringBuilder();
String str = "" + amount;
int count = 0;
for (int i = str.length() - 1; i >= 0; i--) {
if (count > 0 && count % 3 == 0) sb.insert(0, ',');
sb.insert(0, str.charAt(i));
count++;
}
return sb.toString();
}
/** Format time remaining (e.g., "2d 5h 30m") */
protected String formatTimeRemaining(long ms) {
if (ms <= 0) return "Ended";
long seconds = (ms / 1000) % 60;
long minutes = (ms / 60000) % 60;
long hours = (ms / 3600000) % 24;
long days = ms / 86400000;
StringBuilder sb = new StringBuilder();
if (days > 0) sb.append(days).append("d ");
if (hours > 0 || days > 0) sb.append(hours).append("h ");
if (minutes > 0 || hours > 0 || days > 0) sb.append(minutes).append("m");
else sb.append(seconds).append("s");
return sb.toString();
}
@Override
public void save() {
// Override in subclasses if needed
@@ -58,8 +58,6 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis
private AuctionFilter filter;
private int currentPage = 0;
private int totalPages = 1;
private int totalListings = 0;
private boolean dataLoaded = false;
// Buttons defined on this page
private GuiAuctionNavButton btnFilter;
@@ -100,12 +98,16 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis
return PAGE_LISTINGS;
}
/** Request listings from server */
/**
* Request listings from server
*/
private void requestListings() {
AuctionActionPacket.requestListings(filter, currentPage);
}
/** Update pagination button visibility based on current page state */
/**
* Update pagination button visibility based on current page state
*/
private void updatePaginationVisibility() {
if (btnPageUp != null) {
btnPageUp.setVisible(currentPage > 0);
@@ -195,7 +197,8 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {}
public void subGuiClosed(SubGuiInterface subgui) {
}
// ========== Data Handling ==========
@@ -204,7 +207,6 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis
if (compound.hasKey("ListingsData")) {
currentPage = compound.getInteger("Page");
totalPages = compound.getInteger("TotalPages");
totalListings = compound.getInteger("TotalListings");
// Load listings
listingContainer.displayInventory.clear();
@@ -213,7 +215,7 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis
AuctionListing listing = AuctionListing.fromNBT(list.getCompoundTagAt(i));
listingContainer.displayInventory.setListing(i, listing);
}
dataLoaded = true;
updatePaginationVisibility();
} else if (compound.hasKey("ListingsRefresh")) {
requestListings();
}
@@ -297,6 +299,11 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis
// Block other slot interactions
}
public AuctionFilter getFilter() { return filter; }
public ContainerAuctionListing getListingContainer() { return listingContainer; }
public AuctionFilter getFilter() {
return filter;
}
public ContainerAuctionListing getListingContainer() {
return listingContainer;
}
}
@@ -7,15 +7,17 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.AuctionClientConfig;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.util.GuiAuctionNavButton;
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.AuctionClientConfig;
import noppes.npcs.containers.ContainerAuctionSell;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.util.AuctionFormatUtil;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
@@ -103,7 +105,9 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis
return PAGE_SELL;
}
/** Update visibility of buyout price field based on toggle state */
/**
* Update visibility of buyout price field based on toggle state
*/
private void updateBuyoutVisibility() {
if (lblBuyout != null) {
lblBuyout.enabled = allowBuyout;
@@ -117,7 +121,9 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis
}
}
/** Update the buyout toggle button tooltip */
/**
* Update the buyout toggle button tooltip
*/
private void updateBuyoutTooltip() {
if (btnAllowBuyout == null) return;
@@ -239,7 +245,7 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis
// Draw listing fee info (uses cached config from server)
String feeText = StatCollector.translateToLocal("auction.sell.fee")
.replace("%s", formatCurrency(AuctionClientConfig.getListingFee()) + " " + AuctionClientConfig.getCurrencyName());
.replace("%s", AuctionFormatUtil.formatCurrency(AuctionClientConfig.getListingFee()) + " " + AuctionClientConfig.getCurrencyName());
fontRendererObj.drawString(EnumChatFormatting.GRAY + feeText, guiLeft + contentX, guiTop + contentY + 77, 0xFFFFFF);
// Draw error message if any
@@ -250,7 +256,9 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis
drawSellSlotIndicator(slotX, slotY);
}
/** Draw indicator showing staged vs available items */
/**
* Draw indicator showing staged vs available items
*/
private void drawSellSlotIndicator(int slotX, int slotY) {
ItemStack sellItem = sellContainer.getItemToSell();
if (sellItem != null) {
@@ -308,7 +316,9 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis
drawSellPageTooltips(mouseX, mouseY);
}
/** Draw tooltips for sell page buttons */
/**
* Draw tooltips for sell page buttons
*/
private void drawSellPageTooltips(int mouseX, int mouseY) {
List<String> tooltip = null;
@@ -326,7 +336,11 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis
}
if (tooltip != null && !tooltip.isEmpty()) {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
drawHoveringText(tooltip, mouseX - guiLeft, mouseY - guiTop, fontRendererObj);
GL11.glPopAttrib();
GL11.glPopMatrix();
}
}
}
@@ -50,7 +50,7 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
private int pendingSlot = -1;
private PendingOp pendingOp = PendingOp.NONE;
private enum PendingOp { NONE, CANCEL, CLAIM }
private enum PendingOp {NONE, CANCEL, CLAIM}
public GuiAuctionTrades(EntityNPCInterface npc, ContainerAuctionTrades container) {
super(npc, container);
@@ -88,10 +88,16 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
AuctionListing listing = tradesContainer.getListingAt(slot);
AuctionClaim claim = tradesContainer.getClaimAt(slot);
if (listing != null && tradesContainer.isSellingAt(slot) && mouseButton == 1) {
// Right-click on own listing = show cancel
setPending(slot, PendingOp.CANCEL);
NoppesUtil.clickSound();
if (listing != null && tradesContainer.isSellingAt(slot)) {
if (mouseButton == 0) {
// Left-click on own listing = view details
AuctionActionPacket.openBidding(listing.id);
NoppesUtil.clickSound();
} else if (mouseButton == 1) {
// Right-click on own listing = show cancel
setPending(slot, PendingOp.CANCEL);
NoppesUtil.clickSound();
}
} else if (listing != null && tradesContainer.isBiddingAt(slot) && mouseButton == 0) {
// Left-click on active bid = open bidding GUI to increase bid
AuctionActionPacket.openBidding(listing.id);
@@ -117,7 +123,9 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
}
}
/** Handle click on pending operation slot */
/**
* Handle click on pending operation slot
*/
private void handlePendingClick(int mouseButton) {
if (pendingOp == PendingOp.CANCEL && mouseButton == 1) {
// Right-click confirms cancel
@@ -159,14 +167,18 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
}
}
/** Set pending operation and hide slot item */
/**
* Set pending operation and hide slot item
*/
private void setPending(int slot, PendingOp op) {
pendingSlot = slot;
pendingOp = op;
tradesContainer.setHiddenSlot(slot);
}
/** Clear pending operation and restore slot */
/**
* Clear pending operation and restore slot
*/
private void clearPending() {
if (pendingSlot >= 0) {
tradesContainer.clearHiddenSlot();
@@ -175,13 +187,17 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
pendingOp = PendingOp.NONE;
}
/** Play confirmation sound */
/**
* Play confirmation sound
*/
private void playConfirmSound() {
mc.getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(
new ResourceLocation("random.orb"), 1.0F));
}
/** Get slot index at mouse position */
/**
* Get slot index at mouse position
*/
private int getSlotAt(int mouseX, int mouseY) {
int relX = mouseX - guiLeft - GRID_X;
int relY = mouseY - guiTop - GRID_Y;
@@ -239,7 +255,9 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
}
}
/** Get tint color for slot based on contents */
/**
* Get tint color for slot based on contents
*/
private int getSlotTint(int slot) {
AuctionListing listing = tradesContainer.getListingAt(slot);
AuctionClaim claim = tradesContainer.getClaimAt(slot);
@@ -281,7 +299,9 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
}
}
/** Draw tooltip for a trade slot */
/**
* Draw tooltip for a trade slot
*/
private void drawTradeTooltip(int slot, int x, int y) {
List<String> tooltip = new ArrayList<>();
@@ -301,16 +321,13 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
AuctionListing listing = tradesContainer.getListingAt(slot);
AuctionClaim claim = tradesContainer.getClaimAt(slot);
if (listing != null) {
if (tradesContainer.isSellingAt(slot)) {
tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("auction.trades.activeListing"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickToCancel"));
} else if (tradesContainer.isBiddingAt(slot)) {
tooltip.add(EnumChatFormatting.AQUA + StatCollector.translateToLocal("auction.trades.activeBid"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.winningBid"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.leftClickToIncrease"));
}
} else if (claim != null) {
// Slots with items have tooltips handled by AuctionTooltipHandler via ItemTooltipEvent
if (listing != null) return;
if (claim != null && (claim.type == EnumClaimType.ITEM ||
(claim.type == EnumClaimType.REFUND && claim.item != null))) return;
// Non-item slots (currency claims, refund without item, unavailable)
if (claim != null) {
switch (claim.type) {
case CURRENCY:
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.soldClaim"));
@@ -328,20 +345,6 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.outbidBy") + ": " + EnumChatFormatting.AQUA + claim.otherPlayerName);
}
tooltip.add(EnumChatFormatting.GOLD + String.format("%,d", claim.currency) + " " + AuctionClientConfig.getCurrencyName());
// Show rebid option if item is present (active listing)
if (claim.item != null) {
tooltip.add("");
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.leftClickRebid"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickRefund"));
return; // Skip the generic claim message
}
break;
case ITEM:
if (claim.isReturned) {
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.expiredClaim"));
} else {
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.wonClaim"));
}
break;
}
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.leftClickToClaim"));
@@ -337,18 +337,45 @@ public class GuiNPCTrader extends GuiContainerNPCInterface implements IGuiData {
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.
// Must mirror ALL server-side checks in ContainerNPCTrader.slotClick() to avoid
// predicting a deduction for trades the server will reject.
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)) {
if (sold != null
&& canGivePlayerClient(sold)
&& container.isSlotEnabled(slotId, player)
&& (!stockEnabled || availableStock[slotId] > 0)
&& container.canBuy(slotId, player)) {
playerBalance -= cost;
if (stockEnabled && availableStock[slotId] < Integer.MAX_VALUE) {
availableStock[slotId]--;
}
}
}
}
super.handleMouseClick(slot, slotId, mouseButton, modifier);
}
/**
* Client-side mirror of ContainerNPCTrader.canGivePlayer.
* Checks if the item can be added to the player's cursor stack.
*/
private boolean canGivePlayerClient(ItemStack item) {
ItemStack held = player.inventory.getItemStack();
if (held == null) {
return true;
}
if (NoppesUtilPlayer.compareItems(held, item, false, false)) {
int k1 = item.stackSize;
if (k1 > 0 && k1 + held.stackSize <= held.getMaxStackSize()) {
return true;
}
}
return false;
}
@Override
public void save() {
}
@@ -15,7 +15,7 @@ import org.lwjgl.opengl.GL11;
public class GuiQuestCompletion extends GuiNPCInterface implements ITopButtonListener {
private Quest quest;
private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/smallbg.png");
private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/menubg.png");
public GuiQuestCompletion(Quest quest) {
super();
@@ -20,7 +20,7 @@ import java.util.Vector;
public class GuiTransportSelection extends GuiNPCInterface implements ITopButtonListener, IScrollData {
private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/smallbg.png");
private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/menubg.png");
protected int xSize;
protected int guiLeft;
protected int guiTop;
@@ -10,6 +10,7 @@ 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 noppes.npcs.util.AuctionFormatUtil;
/**
* Sub GUI for placing a bid on an auction.
@@ -22,14 +23,16 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe
private final String listingId;
private final long minimumBid;
private final long buyoutPrice;
private final long playerBalance;
private long bidAmount;
private boolean successful = false;
private String errorMessage = null;
public SubGuiAuctionBid(String listingId, long minimumBid, long playerBalance) {
public SubGuiAuctionBid(String listingId, long minimumBid, long buyoutPrice, long playerBalance) {
this.listingId = listingId;
this.minimumBid = minimumBid;
this.buyoutPrice = buyoutPrice;
this.playerBalance = playerBalance;
this.bidAmount = minimumBid;
@@ -49,13 +52,13 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe
// Minimum bid info
String minText = StatCollector.translateToLocal("auction.bid.minimum")
.replace("%s", EnumChatFormatting.DARK_RED + formatCurrency(minimumBid) + " " + currencyName);
.replace("%s", EnumChatFormatting.DARK_RED + AuctionFormatUtil.formatCurrency(minimumBid) + " " + currencyName);
addLabel(new GuiNpcLabel(1, minText, guiLeft + 15, y));
y += 14;
// Your balance
String balanceText = StatCollector.translateToLocal("auction.bid.yourBalance")
.replace("%s", EnumChatFormatting.DARK_GREEN + formatCurrency(playerBalance) + " " + currencyName);
.replace("%s", EnumChatFormatting.DARK_GREEN + AuctionFormatUtil.formatCurrency(playerBalance) + " " + currencyName);
addLabel(new GuiNpcLabel(2, balanceText, guiLeft + 15, y));
y += 18;
@@ -77,7 +80,7 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe
int totalBtnWidth = btnWidth * 2 + btnSpacing;
int btnX = centerX - totalBtnWidth / 2;
addButton(new GuiNpcButton(btnBidId, btnX, y, btnWidth, 20, "auction.bid.placeBid"));
addButton(new GuiNpcButton(btnBidId, btnX, y, btnWidth, 20, "auction.bid.place"));
addButton(new GuiNpcButton(btnCancelId, btnX + btnWidth + btnSpacing, y, btnWidth, 20, "gui.cancel"));
}
@@ -117,7 +120,7 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe
// Validate
if (bidAmount < minimumBid) {
errorMessage = StatCollector.translateToLocal("auction.error.bidTooLow")
.replace("%s", formatCurrency(minimumBid));
.replace("%s", AuctionFormatUtil.formatCurrency(minimumBid));
updateErrorLabel();
return;
}
@@ -128,6 +131,12 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe
return;
}
if (buyoutPrice > 0 && bidAmount >= buyoutPrice) {
errorMessage = StatCollector.translateToLocal("auction.error.bidExceedsBuyout");
updateErrorLabel();
return;
}
// Send bid packet
AuctionActionPacket.placeBid(listingId, bidAmount);
successful = true;
@@ -144,17 +153,4 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe
public boolean wasSuccessful() {
return successful;
}
private String formatCurrency(long amount) {
if (amount < 1000) return "" + amount;
StringBuilder sb = new StringBuilder();
String str = "" + amount;
int count = 0;
for (int i = str.length() - 1; i >= 0; i--) {
if (count > 0 && count % 3 == 0) sb.insert(0, ',');
sb.insert(0, str.charAt(i));
count++;
}
return sb.toString();
}
}
@@ -8,6 +8,7 @@ import noppes.npcs.client.AuctionClientConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.util.AuctionFormatUtil;
/**
* Sub GUI for confirming a buyout purchase.
@@ -54,14 +55,14 @@ public class SubGuiAuctionBuyNow extends SubGuiInterface {
y += 16;
// Buyout price
String priceText = EnumChatFormatting.DARK_RED + formatCurrency(buyoutPrice) + " " + currencyName;
String priceText = EnumChatFormatting.DARK_RED + AuctionFormatUtil.formatCurrency(buyoutPrice) + " " + currencyName;
int priceWidth = fontRendererObj.getStringWidth(priceText);
addLabel(new GuiNpcLabel(2, priceText, centerX - priceWidth / 2, y));
y += 20;
// Your balance
String balanceLabel = StatCollector.translateToLocal("auction.bid.yourBalance");
String balanceText = balanceLabel.replace("%s", EnumChatFormatting.DARK_GREEN + formatCurrency(playerBalance) + " " + currencyName);
String balanceText = balanceLabel.replace("%s", EnumChatFormatting.DARK_GREEN + AuctionFormatUtil.formatCurrency(playerBalance) + " " + currencyName);
addLabel(new GuiNpcLabel(3, balanceText, guiLeft + 20, y));
y += 14;
@@ -105,17 +106,4 @@ public class SubGuiAuctionBuyNow extends SubGuiInterface {
public boolean wasSuccessful() {
return successful;
}
private String formatCurrency(long amount) {
if (amount < 1000) return "" + amount;
StringBuilder sb = new StringBuilder();
String str = "" + amount;
int count = 0;
for (int i = str.length() - 1; i >= 0; i--) {
if (count > 0 && count % 3 == 0) sb.insert(0, ',');
sb.insert(0, str.charAt(i));
count++;
}
return sb.toString();
}
}
File diff suppressed because it is too large. Load diff
@@ -73,6 +73,14 @@ public class GuiCNPCInventory extends GuiNPCInterface {
addSideButton(profileButton);
}
y += 21;
GuiMenuSideButton abilitiesButton = new GuiMenuSideButton(-105, guiLeft + xSize + 37, this.guiTop + y, 22, 22, "");
abilitiesButton.rightSided = true;
abilitiesButton.active = activeTab == -105;
abilitiesButton.renderIconPosX = 80;
abilitiesButton.renderResource = specialIcons;
addSideButton(abilitiesButton);
y += 21;
GuiMenuSideButton clientButton = new GuiMenuSideButton(-103, guiLeft + xSize + 37, this.guiTop + y, 22, 22, "");
clientButton.rightSided = true;
@@ -154,6 +162,10 @@ public class GuiCNPCInventory extends GuiNPCInterface {
activeTab = -104;
mc.displayGuiScreen(new GuiProfiles());
}
if (guibutton.id == -105 && activeTab != -105) {
activeTab = -105;
mc.displayGuiScreen(new GuiAbilities());
}
}
}
@@ -429,6 +429,9 @@ public class GuiProfiles extends GuiCNPCInventory implements ISubGuiListener, IC
}
private boolean isMouseOverScrollbar(int mouseX, int mouseY) {
if (maxScrollY <= 0)
return false;
int scrollbarX = guiLeft + xSize + 30;
int scrollbarY = guiTop + 27;
int scrollbarHeight = ySize - 35;
@@ -184,8 +184,13 @@ public class GuiNpcSpawner extends GuiNPCInterface2 implements ITextfieldListene
GuiNpcMobSpawnerSelector selector = (GuiNpcMobSpawnerSelector) gui;
if (selector.isServer) {
String selected = selector.getSelected();
if (selected != null)
PacketClient.sendClient(new JobSpawnerAddPacket(selector.isServer, selected, selector.activeTab, slot));
if (selected != null) {
if (selector.activeFolder != null) {
PacketClient.sendClient(new JobSpawnerAddPacket(selector.isServer, selected, selector.activeFolder, slot));
} else {
PacketClient.sendClient(new JobSpawnerAddPacket(selector.isServer, selected, selector.activeTab, slot));
}
}
} else {
NBTTagCompound compound = selector.getCompound();
if (compound != null) {
@@ -21,6 +21,7 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex
private final ResourceLocation slot = new ResourceLocation("customnpcs", "textures/gui/slot.png");
private RoleTrader role;
private boolean marketRelinked = false;
// Currency cost textfield IDs start at 100 (100-117 for slots 0-17)
private static final int CURRENCY_FIELD_ID_START = 100;
@@ -116,8 +117,14 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex
@Override
public void save() {
PacketClient.sendClient(new TraderMarketSavePacket(role.marketName, false));
// Linking to a different market already replaced the server's role with that market's
// data. Pushing this GUI's pre-link state back would overwrite the market being linked to.
if (marketRelinked)
return;
// Save the role first so the market is written from the edited data, not the stale data.
PacketClient.sendClient(new RoleSavePacket(role.writeToNBT(new NBTTagCompound())));
PacketClient.sendClient(new TraderMarketSavePacket(role.marketName, false));
}
@Override
@@ -129,6 +136,7 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex
String name = guiNpcTextField.getText();
if (!name.equalsIgnoreCase(role.marketName)) {
role.marketName = name;
marketRelinked = true;
PacketClient.sendClient(new TraderMarketSavePacket(role.marketName, true));
}
return;
@@ -1,429 +0,0 @@
package noppes.npcs.client.gui.script;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.util.StatCollector;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
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.GuiNpcTextArea;
import noppes.npcs.client.gui.util.GuiScriptTextArea;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.ITextChangeListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.janino.JaninoScript;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GuiJaninoScript extends GuiNPCInterface implements GuiYesNoCallback, ITextChangeListener, ICustomScrollListener, ISubGuiListener {
private GuiScriptTextArea textArea;
private int activeTab = 0;
public List<String> allExternalScripts = new ArrayList<>();
private final int scriptLimit = 1;
public String previousHookClicked = "";
// GUI display list
List<String> hooklist = new ArrayList<>();
// Map from display name (with parameters if overloaded) to Method
Map<String, Method> hookMap = new HashMap<>();
public final GuiScreen parent;
private final JaninoScript container;
public Runnable saveFunction;
public GuiJaninoScript(GuiScreen parent, JaninoScript handler) {
this.drawDefaultBackground = true;
this.closeOnEsc = true;
this.xSize = 420;
this.setBackground("menubg.png");
this.parent = parent;
this.container = handler;
createHookList();
String lang = handler.getLanguage();
allExternalScripts.addAll(ScriptController.Instance.getScripts(lang));
}
public GuiJaninoScript setSave(Runnable run) {
saveFunction = run;
return this;
}
public void createHookList() {
// Group all declared methods of the handler's type by their method name
Map<String, List<Method>> grouped = Arrays.stream(container.type.getDeclaredMethods())
.collect(Collectors.groupingBy(Method::getName));
for (Map.Entry<String, List<Method>> entry : grouped.entrySet()) {
List<Method> methods = entry.getValue();
// Sort overloads by number of parameters (ascending)
// This ensures the simplest overload comes first
methods.sort(Comparator.comparingInt(Method::getParameterCount));
boolean first = true;
for (Method m : methods) {
if (Modifier.isFinal(m.getModifiers()))
continue; //skip finals
String displayName = first ? m.getName() :
m.getName() + "(" + Arrays.stream(m.getParameterTypes())
.map(Class::getSimpleName)
.collect(Collectors.joining(", ")) + ")";
hooklist.add(displayName);
hookMap.put(displayName, m);
first = false;
}
}
}
public void initGui() {
this.ySize = (int) ((double) this.xSize * 0.56);
if ((double) this.ySize > (double) this.height * 0.95) {
this.ySize = (int) ((double) this.height * 0.95);
this.xSize = (int) ((double) this.ySize / 0.56);
}
this.bgScale = (float) this.xSize / 400.0F;
super.initGui();
this.guiTop += 10;
int yoffset = (int) ((double) this.ySize * 0.02);
GuiMenuTopButton top;
addTopButton(new GuiMenuTopButton(-1, guiLeft + xSize - 2, guiTop - 17, "X"));
this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings"));
int topXoffset = 0;
int topYoffset = 0;
if (this.container != null) {
this.addTopButton(top = new GuiMenuTopButton(1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset, "Script"));
} else {
this.addTopButton(new GuiMenuTopButton(this.scriptLimit, top.xPosition + top.width, top.yPosition, "+"));
}
top = this.getTopButton(this.activeTab);
if (top == null) {
this.activeTab = 0;
top = this.getTopButton(0);
}
top.active = true;
if (this.activeTab == 1) {
GuiCustomScroll hooks = new GuiCustomScroll(this, 1);
hooks.allowUserInput = false;
hooks.setSize(108, 198);
hooks.guiLeft = this.guiLeft - 110;
hooks.guiTop = this.guiTop + 14;
hooks.setUnsortedList(this.hooklist);
this.addScroll(hooks);
GuiNpcLabel hookLabel = new GuiNpcLabel(0, "script.hooks", hooks.guiLeft, this.guiTop + 5);
hookLabel.color = 11184810;
this.addLabel(hookLabel);
JaninoScript container = this.container;
if (textArea == null)
textArea = new GuiScriptTextArea(this, 2, this.guiLeft + 1 + yoffset, this.guiTop + yoffset, this.xSize - 108 - yoffset, (int) ((double) this.ySize * 0.96) - yoffset * 2, container == null ? "" : container.script);
else
textArea.init(this.guiLeft + 1 + yoffset, this.guiTop + yoffset, this.xSize - 108 - yoffset, (int) ((double) this.ySize * 0.96) - yoffset * 2, container == null ? "" : container.script);
textArea.enableCodeHighlighting();
textArea.setListener(this);
this.closeOnEsc(textArea::closeOnEsc);
this.addTextField(textArea);
int left1 = this.guiLeft + this.xSize - 104;
this.addButton(new GuiNpcButton(102, left1, this.guiTop + yoffset, 60, 20, "gui.clear"));
this.addButton(new GuiNpcButton(101, left1 + 61, this.guiTop + yoffset, 60, 20, "gui.paste"));
this.addButton(new GuiNpcButton(100, left1, this.guiTop + 21 + yoffset, 60, 20, "gui.copy"));
this.addButton(new GuiNpcButton(105, left1 + 61, this.guiTop + 21 + yoffset, 60, 20, "gui.remove"));
this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript"));
// this.getButton(107).enabled = false;
GuiCustomScroll scroll = (new GuiCustomScroll(this, 0)).setUnselectable();
scroll.setSize(100, (int) ((double) this.ySize * 0.54) - yoffset * 2);
scroll.guiLeft = left1;
scroll.guiTop = this.guiTop + 88 + yoffset;
if (container != null)
scroll.setList(container.externalScripts);
this.addScroll(scroll);
} else {
GuiNpcTextArea var8 = new GuiNpcTextArea(2, this, this.guiLeft + 4 + yoffset, this.guiTop + 6 + yoffset, this.xSize - 160 - yoffset, (int) ((float) this.ySize * 0.92F) - yoffset * 2, this.getConsoleText());
var8.enabled = false;
this.addTextField(var8);
int var9 = this.guiLeft + this.xSize - 150;
this.addButton(new GuiNpcButton(100, var9, this.guiTop + 125, 60, 20, "gui.copy"));
this.addButton(new GuiNpcButton(102, var9, this.guiTop + 146, 60, 20, "gui.clear"));
this.addLabel(new GuiNpcLabel(1, "script.language", var9, this.guiTop + 15));
String containerLang = container.getLanguage();
this.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, new String[]{containerLang.equals("Java") ? "Janino (JVM 8)" : containerLang},
this.getLanguageIndex()));
// this.getButton(103).enabled = !this.languages.isEmpty();
this.addLabel(new GuiNpcLabel(2, "gui.enabled", var9, this.guiTop + 36));
// Note: GuiJaninoScript is deprecated; enabled button disabled
this.addButton(new GuiNpcButton(104, var9 + 60, this.guiTop + 31, 50, 20, new String[]{"gui.no", "gui.yes"}, 0));
this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website"));
this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum"));
this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc"));
this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc"));
}
this.xSize = 420;
this.ySize = 256;
}
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
String hook = scroll.getSelected();
if (this.previousHookClicked.equals(hook)) {
String addString = "";
if (!this.getTextField(2)
.getText()
.isEmpty()) {
addString = addString + "\n";
}
addString = addString + generateMethodStub(hookMap.get(hook));
this.getTextField(2)
.setText(this.getTextField(2)
.getText() + addString);
this.previousHookClicked = "";
} else {
this.previousHookClicked = hook;
}
}
public void confirmClicked(boolean flag, int i) {
if (flag) {
if (i == 0)
this.openLink("https://www.curseforge.com/minecraft/mc-mods/customnpc-plus");
else if (i == 1)
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
else if (i == 2)
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
else if (i == 3)
this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html");
if (i == 10) { //Remove
this.container.setScript("");
this.activeTab = 0;
} else if (i == 101) { //Paste
this.getTextField(2)
.setText(NoppesStringUtils.getClipboardContents());
this.setScript();
} else if (i == 102) { //Clear
if (this.activeTab == 1)
container.script = "";
else
this.container.clearConsole();
this.initGui();
}
}
this.displayGuiScreen(this);
}
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == -1) {
close();
return;
}
if (guibutton.id == 0) {
this.setScript();
this.activeTab = 0;
this.initGui();
container.ensureCompiled();
}
if (guibutton.id == this.scriptLimit) {
// if (container.container == null)
//this.container.container = new ScriptContainer(this.container);
// else
// this.setScript();
this.activeTab = 1;
this.initGui();
}
if (guibutton.id == 109) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true));
} else if (guibutton.id == 110) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/KAMKEEL/CustomNPC-Plus-API", 1, true));
} else if (guibutton.id == 111) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/Noppes/CustomNPCsAPI", 2, true));
} else if (guibutton.id == 112) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "http://www.minecraftforge.net/forum/index.php/board,122.0.html", 3, true));
}
GuiYesNo confirmScreen;
//Copy
if (guibutton.id == 100) {
NoppesStringUtils.setClipboardContents(this.getTextField(2)
.getText());
}
//Paste
else if (guibutton.id == 101) {
GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101);
this.displayGuiScreen(guiyesno);
}
//Clear
else if (guibutton.id == 102) {
confirmScreen = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102);
this.displayGuiScreen(confirmScreen);
}
//Enable
else if (guibutton.id == 104) {
// Deprecated GUI - enabled is now per-handler, not per-unit
}
//Remove
else if (guibutton.id == 105) {
confirmScreen = new GuiYesNo(this, "", guibutton.displayString, 10);
this.displayGuiScreen(confirmScreen);
}
//Load Script
else if (guibutton.id == 107) {
setSubGui(new SubGuiSelectList(allExternalScripts, container.externalScripts, "All Scripts", "Selected Scripts"));
}
}
public void subGuiClosed(SubGuiInterface sub) {
if (sub instanceof SubGuiSelectList)
container.setExternalScripts(((SubGuiSelectList) sub).selected);
}
/**
* Generates a stub string for a given Method.
*/
public static String generateMethodStub(Method method) {
String mods = java.lang.reflect.Modifier.toString(method.getModifiers());
if (!mods.isEmpty())
mods += " ";
String returnTypeStr = method.getReturnType()
.getSimpleName();
String name = method.getName();
Map<String, Integer> typeCount = new HashMap<>();
String params = Arrays.stream(method.getParameters())
.map(p -> {
String typeName = p.getType()
.getSimpleName();
String baseName = Character.toLowerCase(typeName.charAt(0)) + typeName.substring(1);
int count = typeCount.getOrDefault(baseName, 0) + 1;
typeCount.put(baseName, count);
// append number if same type of arg exists
String paramName = count == 1 ? baseName : baseName + (count - 1);
return typeName + " " + paramName;
})
.collect(Collectors.joining(", "));
String body;
Class<?> returnType = method.getReturnType();
if (returnType == void.class)
body = "";
else if (returnType.isPrimitive()) {
if (returnType == boolean.class)
body = " return false;";
else if (returnType == char.class)
body = " return '\\0';";
else
body = " return 0;";
} else {
body = " return null;";
}
return String.format("%s%s %s(%s) {\n%s\n}\n", mods, returnTypeStr, name, params, body);
}
private String getConsoleText() {
Map<Long, String> map = this.container.getConsole();
StringBuilder builder = new StringBuilder();
Iterator var3 = map.entrySet()
.iterator();
while (var3.hasNext()) {
Map.Entry<Long, String> entry = (Map.Entry) var3.next();
builder.insert(0, new Date(entry.getKey()) + entry.getValue() + "\n");
}
return builder.toString();
}
private int getLanguageIndex() {
return 0;
}
private void setScript() {
if (this.activeTab == 1) {
String text = this.getTextField(2)
.getText();
text = text.replace("\r\n", "\n");
text = text.replace("\r", "\n");
container.setScript(text);
}
}
public void save() {
if (saveFunction != null)
saveFunction.run();
else if (parent instanceof GuiNPCInterface)
((GuiNPCInterface) parent).save();
}
public void textUpdate(String text) {
// container.setScript(text);
}
public static GuiJaninoScript create(GuiScreen parent, JaninoScript script, int width, int height) {
GuiJaninoScript gui = new GuiJaninoScript(parent, script);
gui.setWorldAndResolution(Minecraft.getMinecraft(), width, height);
Minecraft.getMinecraft().currentScreen = gui;
gui.initGui();
return gui;
}
@Override
public void close() {
this.save();
this.setScript();
container.ensureCompiled();
parent.setWorldAndResolution(mc, width, height);
parent.initGui();
mc.currentScreen = parent;
}
}
@@ -16,7 +16,7 @@ import org.lwjgl.opengl.GL11;
import java.util.HashMap;
public class GuiScriptGlobal extends GuiNPCInterface implements IGuiData {
private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/smallbg.png");
private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/menubg.png");
private HashMap<Integer, Class<?>> scriptGuiClasses = new HashMap<>();
public GuiScriptGlobal() {
@@ -11,7 +11,10 @@ import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.StatCollector;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.controllers.APIRegistry;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.SubGuiAPISelect;
import noppes.npcs.client.gui.util.SubGuiConfirmLink;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
@@ -25,6 +28,7 @@ import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IJTextAreaListener;
import noppes.npcs.client.gui.util.ITextChangeListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
@@ -32,15 +36,11 @@ import noppes.npcs.controllers.data.ForgeDataScript;
import noppes.npcs.controllers.data.IScriptHandler;
import noppes.npcs.controllers.data.IScriptHandlerPacket;
import noppes.npcs.controllers.data.IScriptUnit;
import noppes.npcs.janino.JaninoScript;
import noppes.npcs.scripted.item.ScriptCustomItem;
import org.lwjgl.opengl.Display;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.Map.Entry;
public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ITextChangeListener, ICustomScrollListener, IJTextAreaListener, ITextfieldListener {
@@ -50,6 +50,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
protected int scriptLimit = 1;
public List<String> hookList = new ArrayList<String>();
protected boolean loaded = false;
protected boolean serverDataReceived = false;
protected Map<Integer, GuiScriptTextArea> textAreas = new HashMap<>();
protected GuiScreen parent;
@@ -104,6 +105,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.drawDefaultBackground = true;
this.closeOnEsc = true;
this.xSize = 420;
this.isPannableGUI = true;
this.setBackground("menubg.png");
}
@@ -119,9 +121,17 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
// Initialize hooks from handler
gui.hookList = new ArrayList<>(handler.getHooks());
JSTypeRegistry registry = JSTypeRegistry.getInstance();
if (!registry.isInitialized()) {
registry.initializeFromResources();
}
registry.syncHooksFromScriptHookControllerIfNeeded();
// Request data from server
if (handler instanceof IScriptHandlerPacket)
((IScriptHandlerPacket) handler).requestData();
else
gui.serverDataReceived = true; // No server data to wait for
return gui;
}
@@ -138,6 +148,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
public void initGui() {
// ==================== BASE LAYOUT CALCULATION ====================
isPanning = false;
this.ySize = (int) ((double) this.xSize * 0.56D);
if ((double) this.ySize > (double) this.height * 0.95D) {
this.ySize = (int) ((double) this.height * 0.95D);
@@ -277,6 +288,9 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
// Set the script context for context-aware hook autocomplete
activeArea.setScriptContext(getScriptContext());
activeArea.enableCodeHighlighting();
updateScriptDocumentImports(activeArea, container);
// Setup fullscreen key binding
GuiScriptTextArea.KEYS.FULLSCREEN.setTask(e -> {
@@ -300,13 +314,24 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.addButton(new GuiNpcButton(100, left1, this.guiTop + 21 + yoffset, 60, 20, "gui.copy"));
this.addButton(new GuiNpcButton(105, left1 + 61, this.guiTop + 21 + yoffset, 60, 20, "gui.remove"));
// Language toggle button (only if handler supports Janino and there is more than one option)
if (handler.supportsJanino() && getLanguageOptions().size() > 1 && container != null) {
this.addButton(new GuiNpcButton(113, left1, this.guiTop + 42 + yoffset, 121, 20, container.getLanguage()));
// Per-tab language button — cycles through all available languages
List<String> langOptions = getLanguageOptions();
if (langOptions.size() > 1 && container != null) {
int langIdx = getContainerLanguageIndex(langOptions, container);
this.addButton(new GuiNpcButton(113, left1, this.guiTop + 42 + yoffset, 121, 20,
langOptions.toArray(new String[0]), langIdx));
}
this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript"));
// Disable all buttons until server data arrives
if (!serverDataReceived) {
for (int btnId : new int[]{100, 101, 102, 105, 107, 113}) {
GuiNpcButton btn = getButton(btnId);
if (btn != null) btn.enabled = false;
}
}
GuiCustomScroll scroll = (new GuiCustomScroll(this, 0)).setUnselectable();
scroll.setSize(100, (int) ((double) this.ySize * 0.54D) - yoffset * 2);
scroll.guiLeft = left1;
@@ -316,8 +341,9 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
}
this.addScroll(scroll);
}
}
computePanBounds(editorX, editorY, editorWidth, editorHeight);
}
/**
* Initialize the settings tab layout (console view).
*/
@@ -331,12 +357,11 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
int var9 = this.guiLeft + this.xSize - 150;
this.addButton(new GuiNpcButton(100, var9, this.guiTop + 125, 60, 20, "gui.copy"));
this.addButton(new GuiNpcButton(102, var9, this.guiTop + 146, 60, 20, "gui.clear"));
this.addLabel(new GuiNpcLabel(1, "script.language", var9, this.guiTop + 15));
this.addLabel(new GuiNpcLabel(1, "script.default", var9, this.guiTop + 15));
List<String> languageOptions = getLanguageOptions();
this.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20,
languageOptions.toArray(new String[0]),
this.getLanguageIndex(languageOptions)));
this.getButton(103).enabled = languageOptions.size() > 0;
this.addLabel(new GuiNpcLabel(2, "gui.enabled", var9, this.guiTop + 36));
this.addButton(new GuiNpcButton(104, var9 + 60, this.guiTop + 31, 50, 20,
new String[]{"gui.no", "gui.yes"}, this.handler.getEnabled() ? 1 : 0));
@@ -346,9 +371,24 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
}
this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website"));
this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum"));
this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc"));
this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc"));
this.addButton(new GuiNpcButton(110, var9 + 81, this.guiTop + 78, 80, 20, "gui.api"));
// Disable all buttons until server data arrives
if (!serverDataReceived) {
for (int btnId : new int[]{100, 102, 103, 104, 106, 109, 110}) {
GuiNpcButton btn = getButton(btnId);
if (btn != null) btn.enabled = false;
}
} else {
// Language button requires options to be available
this.getButton(103).enabled = languageOptions.size() > 0;
}
int consoleX = this.guiLeft + 4 + yoffset;
int consoleY = this.guiTop + 6 + yoffset;
int consoleW = this.xSize - 160 - yoffset;
int consoleH = (int) ((float) this.ySize * 0.92F) - yoffset * 2;
computePanBounds(consoleX, consoleY, consoleW, consoleH);
}
public GuiScriptInterface setDimensions(int x, int y) {
@@ -367,30 +407,34 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
return handler.getContext();
}
// ==================== RENDERING ====================
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
// Draw fullscreen button on top of everything when on script editor tab
// Skip for useSettingsToggle GUIs (like GuiScript) - they handle this themselves
if (this.activeTab > 0 && !useSettingsToggle && !handler.isSingleContainer()) {
fullscreenButton.draw(mouseX, mouseY);
protected boolean isPannableArea(int mx, int my) {
if (activeTab > 0 && fullscreenButton.isMouseOver(mx, my)) {
return false;
}
GuiScriptTextArea activeArea = getActiveScriptArea();
if (activeArea != null && activeArea.isPointOnAutocompleteMenu(mx, my)) {
return false;
}
return super.isPannableArea(mx, my);
}
// ==================== MOUSE HANDLING ====================
@Override
public void mouseClicked(int mouseX, int mouseY, int mouseButton) {
// Check fullscreen button first when on script editor tab
// Skip for useSettingsToggle GUIs (like GuiScript) - they handle this themselves
if (this.activeTab > 0 && !useSettingsToggle && !handler.isSingleContainer() && fullscreenButton.mouseClicked(mouseX, mouseY, mouseButton)) {
public void mouseClicked(int i, int j, int k) {
int adjX = panAdjustedX(i);
int adjY = panAdjustedY(j);
GuiScriptTextArea activeArea = getActiveScriptArea();
boolean isOverAutocomplete = activeArea != null
&& activeArea.isPointOnAutocompleteMenu(adjX, adjY);
if (isOverAutocomplete) {
activeArea.mouseClicked(adjX, adjY, k);
return;
}
super.mouseClicked(mouseX, mouseY, mouseButton);
super.mouseClicked(i, j, k);
}
public String previousHookClicked = "";
@@ -413,11 +457,40 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.getTextField(2).setText(this.getTextField(2).getText() + addString);
previousHookClicked = "";
updateScriptDocumentImports(getActiveScriptArea(), container);
} else {
previousHookClicked = hook;
}
}
public void updateScriptDocumentImports(GuiScriptTextArea activeArea, IScriptUnit container) {
// For JaninoScripts, add implicit imports (default imports + hook signature types)
// These allow the syntax highlighter to resolve types without explicit import statements
if (container instanceof JaninoScript) {
JaninoScript<?> janinoScript = (JaninoScript<?>) container;
ScriptContext ctx = getScriptContext();
// Add default imports (e.g., noppes.npcs.api.*, noppes.npcs.api.entity.*, etc.)
activeArea.addImplicitImports(janinoScript.getDefaultImports());
// Add hook types from signatures (parameters + return types)
// e.g., INpcEvent.InitEvent, Color, String, IOverlayContext, etc.
Set<String> hookTypes = janinoScript.getHookTypes();
activeArea.addImplicitImports(hookTypes.toArray(new String[0]));
// Add wildcard imports for each event class in the script context: INpcEvent.*, IProjectileEvent.*
// so nested types like INpcEvent.CollideEvent resolve without explicit import
Set<String> wildcardImports = new HashSet<>();
for (String fqn : ctx.getNamespaceFQNs())
wildcardImports.add(fqn + ".*");
activeArea.addImplicitImports(wildcardImports.toArray(new String[0]));
// Format to update which implicit imports are actually used
activeArea.formatCodeText();
}
}
@Override
public void unFocused(GuiNpcTextField textfield) {
@@ -467,6 +540,26 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
return 0;
}
/**
* Finds the index of a container's language within the available options.
* Used for the per-tab language button (113).
*
* @param languageOptions The list of available languages.
* @param container The script unit whose language to find.
* @return The 0-based index, or 0 if not found.
*/
protected int getContainerLanguageIndex(List<String> languageOptions, IScriptUnit container) {
if (languageOptions == null || languageOptions.isEmpty() || container == null)
return 0;
String current = container.getLanguage();
for (int i = 0; i < languageOptions.size(); i++) {
if (current != null && languageOptions.get(i).equalsIgnoreCase(current))
return i;
}
return 0;
}
/**
* Retrieves the list of available scripting languages for this handler.
* <p>
@@ -478,19 +571,35 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
*/
protected List<String> getLanguageOptions() {
List<String> options = new ArrayList<>();
// Start with languages known from the server
if (this.languages != null && !this.languages.isEmpty())
options.addAll(this.languages.keySet());
if ((options.isEmpty() || !options.contains("Java")) && this.handler != null && this.handler.supportsJanino()) {
List<String> scripts = new ArrayList<>();
if (ScriptController.Instance != null && ScriptController.Instance.scripts != null) {
scripts.addAll(ScriptController.Instance.scripts.keySet());
if (this.handler != null) {
if (this.handler.supportsJanino()) {
// Handler supports Java — ensure it's in the list
if (!options.contains("Java")) {
List<String> scripts = new ArrayList<>();
if (ScriptController.Instance != null && ScriptController.Instance.scripts != null) {
scripts.addAll(ScriptController.Instance.scripts.keySet());
}
if (this.languages == null)
this.languages = new HashMap();
if (!this.languages.containsKey("Java"))
this.languages.put("Java", scripts);
options.add("Java");
}
} else {
// Handler does not support Java — remove it
options.remove("Java");
}
// Ensure at least the handler's default language is present
String defaultLang = this.handler.getLanguage();
if (defaultLang != null && !defaultLang.isEmpty() && !options.contains(defaultLang)) {
options.add(0, defaultLang);
}
if (this.languages == null)
this.languages = new HashMap();
if (!this.languages.containsKey("Java"))
this.languages.put("Java", scripts);
options.add("Java");
}
return options;
@@ -502,17 +611,6 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.openLink("https://www.curseforge.com/minecraft/mc-mods/customnpc-plus");
}
if (i == 1) {
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
}
if (i == 2) {
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
}
if (i == 3) {
this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html");
}
if (i == 10) {
handler.removeScriptUnit(this.activeTab - 1);
this.activeTab = 0;
@@ -591,13 +689,13 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
if (guibutton.id == scriptLimit) {
if (handler.isSingleContainer()) {
if (handler.getSingleScript() == null) {
handler.addScriptUnit(new ScriptContainer(handler));
handler.addScriptUnit(createDefaultScriptUnit());
} else {
this.setScript();
}
this.activeTab = 1;
} else {
handler.addScriptUnit(new ScriptContainer(this.handler));
handler.addScriptUnit(createDefaultScriptUnit());
this.activeTab = this.handler.getScripts().size();
}
this.initGui();
@@ -608,15 +706,12 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
}
if (guibutton.id == 110) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/KAMKEEL/CustomNPC-Plus-API", 1, true));
}
if (guibutton.id == 111) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/Noppes/CustomNPCsAPI", 2, true));
}
if (guibutton.id == 112) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "http://www.minecraftforge.net/forum/index.php/board,122.0.html", 3, true));
if (APIRegistry.Instance.size() == 1) {
String url = APIRegistry.Instance.getEntries().values().iterator().next();
this.setSubGui(new SubGuiConfirmLink(url));
} else {
this.setSubGui(new SubGuiAPISelect());
}
}
if (guibutton.id == 100) {
@@ -655,43 +750,47 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
if (guibutton.id == 107) {
IScriptUnit container = getCurrentContainer();
if (container == null) {
container = new ScriptContainer(this.handler);
container = createDefaultScriptUnit();
handler.addScriptUnit(container);
}
String language = container != null ? container.getLanguage() : this.handler.getLanguage();
String language = container.getLanguage();
this.setSubGui(new EventGuiScriptList((List) this.languages.get(language), container));
}
// Language toggle button - switch between ECMAScript and Java
// Per-tab language cycling button
if (guibutton.id == 113) {
String selectedLanguage = ((GuiNpcButton) guibutton).displayString;
int idx = getActiveScriptIndex();
if (idx >= 0 && idx < handler.getScripts().size()) {
IScriptUnit currentUnit = handler.getScripts().get(idx);
IScriptUnit newUnit;
boolean currentIsJanino = currentUnit.isJanino();
boolean targetIsJanino = "Java".equals(selectedLanguage);
if (currentUnit.isJanino()) {
// Switch from Java to ECMAScript
newUnit = new ScriptContainer(handler);
if (currentIsJanino && !targetIsJanino) {
// Switch from Java to a non-Java language
IScriptUnit newUnit = new ScriptContainer(handler);
newUnit.setScript(currentUnit.getScript());
newUnit.setExternalScripts(new ArrayList<>(currentUnit.getExternalScripts()));
} else {
// Switch from ECMAScript to Java
newUnit = handler.createJaninoScriptUnit();
handler.replaceScriptUnit(idx, newUnit);
textAreas.remove(idx);
initGui();
} else if (!currentIsJanino && targetIsJanino) {
// Switch from non-Java to Java
IScriptUnit newUnit = handler.createJaninoScriptUnit();
if (newUnit != null) {
newUnit.setScript(currentUnit.getScript());
newUnit.setExternalScripts(new ArrayList<>(currentUnit.getExternalScripts()));
} else {
return; // Handler doesn't support Janino
handler.replaceScriptUnit(idx, newUnit);
textAreas.remove(idx);
initGui();
}
} else if (!currentIsJanino) {
// Switch between non-Java languages (e.g., ECMAScript to Lua)
currentUnit.setLanguage(selectedLanguage);
GuiScriptTextArea area = getActiveScriptArea();
if (area != null) area.setLanguage(selectedLanguage);
}
handler.replaceScriptUnit(idx, newUnit);
// Clear the cached text area so it recreates with new language
textAreas.remove(idx);
// Reinitialize the GUI
initGui();
}
}
}
@@ -701,7 +800,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
IScriptUnit container = getCurrentContainer();
if (container == null) {
container = new ScriptContainer(this.handler);
container = createDefaultScriptUnit();
handler.addScriptUnit(container);
}
@@ -718,6 +817,9 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
public void setGuiData(NBTTagCompound compound) {
if (handler instanceof IScriptHandlerPacket) {
IScriptHandlerPacket.GuiDataResult result = ((IScriptHandlerPacket) handler).setGuiData(compound);
if (result == null) {
return; // Unrelated packet, ignore
}
if (result.kind == IScriptHandlerPacket.GuiDataKind.LOAD_COMPLETE) {
loaded = true;
return;
@@ -733,6 +835,10 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
return;
}
// For non-IScriptHandlerPacket handlers, ignore unrelated packets
if (!compound.hasKey("ScriptLanguage") && !compound.hasKey("Languages")) {
return;
}
loadLanguagesData(compound);
}
@@ -771,11 +877,12 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
}
this.languages = languages;
this.serverDataReceived = true;
this.initGui();
}
public void save() {
if (!loaded)
if (!loaded || !serverDataReceived)
return;
this.setScript();
@@ -820,6 +927,22 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
super.close();
}
/**
* Create a new script unit using the handler's default language.
* If default is Java, creates a JaninoScript; otherwise a ScriptContainer
* with its language set to the handler's default.
*/
protected IScriptUnit createDefaultScriptUnit() {
String defaultLang = handler.getLanguage();
if ("Java".equals(defaultLang)) {
IScriptUnit unit = handler.createJaninoScriptUnit();
if (unit != null) return unit;
}
ScriptContainer sc = new ScriptContainer(handler);
sc.setLanguage(defaultLang);
return sc;
}
// ==================== FULLSCREEN METHODS ====================
/**
@@ -5,7 +5,6 @@ import kamkeel.npcs.network.packets.request.animation.AnimationsGetPacket;
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.GuiNpcTextField;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IScrollData;
@@ -2,6 +2,8 @@ package noppes.npcs.client.gui.select;
import com.google.common.collect.Lists;
import net.minecraft.client.gui.GuiButton;
import kamkeel.npcs.controllers.data.ability.conditions.ConditionQuestCompleted;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
@@ -27,6 +29,31 @@ public class GuiQuestSelection extends SubGuiInterface implements ICustomScrollL
private QuestCategory selectedCategory;
public Quest selectedQuest;
/**
* Builds the condition editor's quest-select field.
* <p>
* This lives here rather than in ConditionQuestCompleted because the lambdas below carry
* this class in their method descriptors. The condition is a both-side class, and @SideOnly
* does not strip the synthetic lambda methods it generates - so anything reflecting over its
* declared methods on a server would resolve those descriptors and fail to find this type.
*/
public static FieldDef createConditionField(ConditionQuestCompleted condition) {
return FieldDef.subGuiField("condition.select_quest",
() -> new GuiQuestSelection(condition.getQuestId()),
gui -> {
GuiQuestSelection sel = (GuiQuestSelection) gui;
if (sel.selectedQuest != null) {
condition.setQuestId(sel.selectedQuest.id);
}
})
.buttonLabel(() -> {
if (condition.getQuestId() < 0) return "None";
Quest q = QuestController.Instance.quests.get(condition.getQuestId());
return q != null ? q.title : "ID:" + condition.getQuestId();
})
.clearable(() -> condition.setQuestId(-1));
}
private GuiSelectionListener listener;
private String catSearch = "";
private String questSearch = "";
@@ -145,11 +145,13 @@ public class GuiSoundSelection extends SubGuiInterface implements ICustomScrollL
scrollSounds.resetScroll();
getTextField(66).setText("");
soundSearch = "";
scrollSounds.setList(domains.get(selectedDomain));
getButton(1).enabled = false;
}
if (guiCustomScroll.id == 1) {
selectedResource = new ResourceLocation(selectedDomain, guiCustomScroll.getSelected());
getButton(1).enabled = true;
}
initGui();
}
@Override
@@ -0,0 +1,319 @@
package noppes.npcs.client.gui.select;
import com.google.common.collect.Lists;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.ClientCacheHandler;
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.SubGuiInterface;
import noppes.npcs.client.renderer.ImageData;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Texture path selector SubGui with a texture preview panel instead of NPC rendering.
* Reuses the cached texture data from {@link GuiTextureSelection}.
*/
public class GuiTexturePathSelection extends SubGuiInterface implements ICustomScrollListener {
private final String up = "..<" + StatCollector.translateToLocal("gui.up") + ">..";
private GuiCustomScroll scrollCategories;
private GuiCustomScroll scrollTextures;
private String location = "";
private String selectedDomain;
public ResourceLocation selectedResource;
private final HashMap<String, List<GuiTextureSelection.TextureData>> domains = new HashMap<>();
private final HashMap<String, GuiTextureSelection.TextureData> textures = new HashMap<>();
private String catSearch = "";
private String texSearch = "";
// Preview
private static final int PREVIEW_SIZE = 90;
public GuiTexturePathSelection(String texture) {
drawDefaultBackground = false;
title = "";
setBackground("menubg.png");
xSize = 366;
ySize = 226;
// Populate from GuiTextureSelection's cache (trigger a scan if needed)
long now = System.currentTimeMillis();
if (GuiTextureSelection.cachedTextures != null && !GuiTextureSelection.cachedTextures.isEmpty()
&& now - GuiTextureSelection.lastCacheTime() < GuiTextureSelection.CACHE_DURATION_MS) {
domains.putAll(GuiTextureSelection.cachedDomains());
} else {
// Force a scan by creating a temporary GuiTextureSelection
GuiTextureSelection temp = new GuiTextureSelection(null, null);
domains.putAll(GuiTextureSelection.cachedDomains());
}
if (texture != null && !texture.isEmpty()) {
selectedResource = new ResourceLocation(texture);
selectedDomain = selectedResource.getResourceDomain();
if (!domains.containsKey(selectedDomain)) {
selectedDomain = null;
}
int i = selectedResource.getResourcePath().lastIndexOf('/');
location = selectedResource.getResourcePath().substring(0, i + 1);
}
}
@Override
public void initGui() {
super.initGui();
if (selectedDomain != null) {
title = selectedDomain + ":" + location;
} else {
title = "";
}
// Buttons
this.addButton(new GuiNpcButton(2, guiLeft + xSize - 46, guiTop + ySize - 28, 42, 20, "gui.done"));
this.addButton(new GuiNpcButton(1, guiLeft + xSize - 92, guiTop + ySize - 28, 42, 20, "gui.cancel"));
// Category scroll
if (scrollCategories == null) {
scrollCategories = new GuiCustomScroll(this, 0);
scrollCategories.setSize(90, 163);
}
if (selectedDomain == null) {
scrollCategories.setList(getCatSearch());
} else {
List<String> list = new ArrayList<>();
list.add(up);
List<GuiTextureSelection.TextureData> data = domains.get(selectedDomain);
if (data != null) {
for (GuiTextureSelection.TextureData td : data) {
if (location.isEmpty() || td.path.startsWith(location) && !td.path.equals(location)) {
String path = td.path.substring(location.length());
int i = path.indexOf('/');
if (i < 0) continue;
path = path.substring(0, i);
if (!path.isEmpty() && !list.contains(path)) {
list.add(path);
}
}
}
}
scrollCategories.setList(list);
}
scrollCategories.guiLeft = guiLeft + 4;
scrollCategories.guiTop = guiTop + 14;
this.addScroll(scrollCategories);
addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 4, guiTop + 179, 90, 20, catSearch));
// Texture scroll
if (scrollTextures == null) {
scrollTextures = new GuiCustomScroll(this, 1);
scrollTextures.setSize(160, 163);
}
if (selectedDomain != null) {
textures.clear();
List<GuiTextureSelection.TextureData> data = domains.get(selectedDomain);
List<String> allList = new ArrayList<>();
String loc = location;
if (scrollCategories.hasSelected() && !scrollCategories.getSelected().equals(up)) {
loc += scrollCategories.getSelected() + '/';
}
if (data != null) {
for (GuiTextureSelection.TextureData td : data) {
if (td.path.equals(loc) && !allList.contains(td.name)) {
allList.add(td.name);
textures.put(td.name, td);
}
}
}
scrollTextures.setList(filterTexSearch(allList));
}
if (selectedResource != null) {
scrollTextures.setSelected(selectedResource.getResourcePath());
}
scrollTextures.guiLeft = guiLeft + 95;
scrollTextures.guiTop = guiTop + 14;
this.addScroll(scrollTextures);
addTextField(new GuiNpcTextField(66, this, fontRendererObj, guiLeft + 95, guiTop + 179, 160, 20, texSearch));
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
drawTexturePreview();
}
private void drawTexturePreview() {
int previewX = guiLeft + 260;
int previewY = guiTop + 14;
// Draw border/background for preview area
drawRect(previewX - 1, previewY - 1, previewX + PREVIEW_SIZE + 1, previewY + PREVIEW_SIZE + 1, 0xFFA0A0A0);
drawRect(previewX, previewY, previewX + PREVIEW_SIZE, previewY + PREVIEW_SIZE, 0xFF000000);
if (selectedResource == null) {
String none = StatCollector.translateToLocal("gui.none");
int w = fontRendererObj.getStringWidth(none);
fontRendererObj.drawString(none, previewX + (PREVIEW_SIZE - w) / 2, previewY + PREVIEW_SIZE / 2 - 4, 0xFF808080);
return;
}
ImageData imageData = ClientCacheHandler.getImageData(selectedResource.toString());
if (imageData == null || !imageData.imageLoaded()) {
String loading = "...";
int w = fontRendererObj.getStringWidth(loading);
fontRendererObj.drawString(loading, previewX + (PREVIEW_SIZE - w) / 2, previewY + PREVIEW_SIZE / 2 - 4, 0xFF808080);
return;
}
int texW = imageData.getTotalWidth();
int texH = imageData.getTotalHeight();
if (texW <= 0 || texH <= 0) return;
// Scale to fit within PREVIEW_SIZE while maintaining aspect ratio
float scale = Math.min((float) PREVIEW_SIZE / texW, (float) PREVIEW_SIZE / texH);
int drawW = (int) (texW * scale);
int drawH = (int) (texH * scale);
int drawX = previewX + (PREVIEW_SIZE - drawW) / 2;
int drawY = previewY + (PREVIEW_SIZE - drawH) / 2;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
imageData.bindTexture();
drawScaledTexture(drawX, drawY, drawW, drawH);
// Draw dimensions label below preview
String dims = texW + " x " + texH;
int dw = fontRendererObj.getStringWidth(dims);
fontRendererObj.drawString(dims, previewX + (PREVIEW_SIZE - dw) / 2, previewY + PREVIEW_SIZE + 4, 0xFFCCCCCC);
// Draw resource path below dimensions
String path = selectedResource.toString();
if (fontRendererObj.getStringWidth(path) > PREVIEW_SIZE + 4) {
// Truncate from the left
while (fontRendererObj.getStringWidth("..." + path) > PREVIEW_SIZE + 4 && path.length() > 1) {
path = path.substring(1);
}
path = "..." + path;
}
int pw = fontRendererObj.getStringWidth(path);
fontRendererObj.drawString(path, previewX + (PREVIEW_SIZE - pw) / 2, previewY + PREVIEW_SIZE + 15, 0xFF999999);
}
private void drawScaledTexture(int x, int y, int width, int height) {
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
tess.addVertexWithUV(x, y + height, zLevel, 0.0, 1.0);
tess.addVertexWithUV(x + width, y + height, zLevel, 1.0, 1.0);
tess.addVertexWithUV(x + width, y, zLevel, 1.0, 0.0);
tess.addVertexWithUV(x, y, zLevel, 0.0, 0.0);
tess.draw();
}
@Override
protected void actionPerformed(GuiButton guibutton) {
super.actionPerformed(guibutton);
if (guibutton.id == 1) {
// Cancel - clear selection
selectedResource = null;
}
close();
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
if (scroll == scrollTextures) {
if (scroll.id == 1) {
GuiTextureSelection.TextureData data = textures.get(scroll.getSelected());
if (data != null) {
selectedResource = new ResourceLocation(selectedDomain, data.absoluteName);
}
}
} else {
initGui();
scrollTextures.resetScroll();
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
if (scroll == scrollCategories) {
if (selectedDomain == null) {
selectedDomain = selection;
} else if (selection.equals(up)) {
int i = location.lastIndexOf('/', location.length() - 2);
if (i < 0) {
if (location.isEmpty()) {
selectedDomain = null;
}
location = "";
} else {
location = location.substring(0, i + 1);
}
} else {
location = location + selection + '/';
}
scrollCategories.selected = -1;
scrollTextures.selected = -1;
initGui();
} else {
// Double-click on texture = confirm
close();
}
}
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(55) != null && getTextField(55).isFocused()) {
if (!catSearch.equals(getTextField(55).getText())) {
catSearch = getTextField(55).getText().toLowerCase();
scrollCategories.resetScroll();
if (selectedDomain == null) {
scrollCategories.setList(getCatSearch());
}
}
}
if (getTextField(66) != null && getTextField(66).isFocused()) {
if (!texSearch.equals(getTextField(66).getText())) {
texSearch = getTextField(66).getText().toLowerCase();
scrollTextures.resetScroll();
initGui();
}
}
}
private List<String> getCatSearch() {
if (catSearch.isEmpty()) {
return new ArrayList<>(domains.keySet());
}
List<String> list = new ArrayList<>();
for (String name : domains.keySet()) {
if (name.toLowerCase().contains(catSearch))
list.add(name);
}
return list;
}
private List<String> filterTexSearch(List<String> source) {
if (texSearch.isEmpty()) {
return source;
}
List<String> list = new ArrayList<>();
for (String name : source) {
if (name.toLowerCase().contains(texSearch))
list.add(name);
}
return list;
}
}
@@ -54,11 +54,21 @@ public class GuiTextureSelection extends SubGuiInterface implements ICustomScrol
private final HashMap<String, TextureData> textures = new HashMap<>();
// --- Cache static fields ---
private static final long CACHE_DURATION = 180000L; // 3 minutes in milliseconds
static final long CACHE_DURATION = 180000L; // 3 minutes in milliseconds
private static long lastCacheTime = 0;
private static HashMap<String, List<TextureData>> cachedDomains = new HashMap<>();
public static HashMap<String, TextureData> cachedTextures = new HashMap<>();
public static final long CACHE_DURATION_MS = CACHE_DURATION;
public static long lastCacheTime() {
return lastCacheTime;
}
public static HashMap<String, List<TextureData>> cachedDomains() {
return cachedDomains;
}
public GuiTextureSelection(EntityNPCInterface npc, String texture) {
this.npc = npc;
drawDefaultBackground = false;
Loaded 100 of 791 files, more files were not shown because too many files have changed in this diff. Show more