Merge branch 'dev' into syntax-highlighter-unified

This commit is contained in:
bigguy345 committed 2026-02-21 10:31:10 +02:00
commit bc3a622d1b
92 files changed
+6623 -837

No files matched your search

@@ -14,6 +14,7 @@ import noppes.npcs.controllers.AnimationController;
import noppes.npcs.controllers.data.Animation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@@ -44,10 +45,25 @@ public abstract class AbstractDataAbilities {
protected Ability currentAbility;
/**
* World time when cooldown ends
* World time when global cooldown ends
*/
protected long cooldownEndTime = 0;
/**
* Duration of the current global cooldown in ticks (for progress calculation)
*/
protected int globalCooldownDuration = 0;
/**
* Per-ability cooldown end times. Key = ability key, Value = world time when cooldown ends.
*/
protected HashMap<String, Long> perAbilityCooldownEndTimes = new HashMap<>();
/**
* Per-ability cooldown durations in ticks (for progress calculation).
*/
protected HashMap<String, Integer> perAbilityCooldownDurations = new HashMap<>();
/**
* Rotation lock state
*/
@@ -526,6 +542,106 @@ public abstract class AbstractDataAbilities {
cooldownEndTime = endTime;
}
/**
* Get the global cooldown end time.
*/
public long getCooldownEndTime() {
return cooldownEndTime;
}
/**
* Get the global cooldown duration value.
*/
public int getGlobalCooldownDurationValue() {
return globalCooldownDuration;
}
/**
* Get the per-ability cooldown end times map.
*/
public HashMap<String, Long> getPerAbilityCooldownEndTimes() {
return perAbilityCooldownEndTimes;
}
/**
* Get the per-ability cooldown durations map.
*/
public HashMap<String, Integer> getPerAbilityCooldownDurations() {
return perAbilityCooldownDurations;
}
/**
* Apply cooldown sync data from server. Called on client side.
*/
public void applyCooldownSync(long globalEndTime, int globalDuration,
HashMap<String, Long> perEndTimes,
HashMap<String, Integer> perDurations) {
this.cooldownEndTime = globalEndTime;
this.globalCooldownDuration = globalDuration;
this.perAbilityCooldownEndTimes = perEndTimes;
this.perAbilityCooldownDurations = perDurations;
}
// ═══════════════════════════════════════════════════════════════════
// PER-ABILITY COOLDOWN MANAGEMENT
// ═══════════════════════════════════════════════════════════════════
/**
* Check if a specific ability is on its per-ability cooldown.
*/
public boolean isOnPerAbilityCooldown(String key) {
Long endTime = perAbilityCooldownEndTimes.get(key);
return endTime != null && getWorldTime() < endTime;
}
/**
* Set a per-ability cooldown.
*/
public void setPerAbilityCooldown(String key, long endTime, int duration) {
perAbilityCooldownEndTimes.put(key, endTime);
perAbilityCooldownDurations.put(key, duration);
}
/**
* Reset a specific per-ability cooldown.
*/
public void resetPerAbilityCooldown(String key) {
perAbilityCooldownEndTimes.remove(key);
perAbilityCooldownDurations.remove(key);
}
/**
* Reset all per-ability cooldowns.
*/
public void resetAllPerAbilityCooldowns() {
perAbilityCooldownEndTimes.clear();
perAbilityCooldownDurations.clear();
}
/**
* Get global cooldown progress for HUD rendering.
* @return 1.0 when cooldown just started (fully covered), 0.0 when done
*/
public float getGlobalCooldownProgress() {
if (globalCooldownDuration <= 0) return 0f;
long remaining = cooldownEndTime - getWorldTime();
if (remaining <= 0) return 0f;
return Math.min(1f, (float) remaining / globalCooldownDuration);
}
/**
* Get per-ability cooldown progress for HUD rendering.
* @return 1.0 when cooldown just started (fully covered), 0.0 when done
*/
public float getPerAbilityCooldownProgress(String key) {
Long endTime = perAbilityCooldownEndTimes.get(key);
Integer duration = perAbilityCooldownDurations.get(key);
if (endTime == null || duration == null || duration <= 0) return 0f;
long remaining = endTime - getWorldTime();
if (remaining <= 0) return 0f;
return Math.min(1f, (float) remaining / duration);
}
// ═══════════════════════════════════════════════════════════════════
// POSITION LOCKING
// ═══════════════════════════════════════════════════════════════════
@@ -335,6 +335,14 @@ public class CustomNpcs {
@EventHandler
public void loadComplete(FMLLoadCompleteEvent ev) {
proxy.buildPackageIndex();
// Load built-in animations on the client so they're available for ability preview.
// On dedicated servers, AnimationController.load() only runs on the server JVM,
// leaving the client without built-in animation data. In singleplayer, load()
// runs later during server start and reloads everything, so this is harmless.
if (FMLCommonHandler.instance().getSide().isClient()) {
AnimationController.Instance.loadClientBuiltIns();
}
}
@EventHandler
@@ -422,6 +430,7 @@ public class CustomNpcs {
}
kamkeel.npcs.entity.EntityEnergyProjectile.clearAllProjectiles();
kamkeel.npcs.entity.EntityEnergyBarrier.clearAllBarriers();
if (FMLCommonHandler.instance().getSide().isClient())
clientJaninoCompiler = null;
+17 -3
View File
@@ -222,13 +222,18 @@ public class DataAbilities extends AbstractDataAbilities {
@Override
protected void rollCooldown(Ability ability) {
// Always roll NPC global cooldown (pacing timer)
int baseCooldown = minCooldown;
if (maxCooldown > minCooldown) {
baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1);
}
cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown;
// Add ability-specific cooldown offset
cooldownEndTime += ability.getCooldownTicks();
cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown + ability.getCooldownTicks();
// Additionally set per-ability cooldown if enabled
if (ability.isPerAbilityCooldown() && ability.getCooldownTicks() > 0) {
long endTime = npc.worldObj.getTotalWorldTime() + ability.getCooldownTicks();
setPerAbilityCooldown(ability.getName(), endTime, ability.getCooldownTicks());
}
}
@Override
@@ -482,6 +487,14 @@ public class DataAbilities extends AbstractDataAbilities {
return false;
}
// Per-ability cooldown filter: ability may have its own independent cooldown
if (!action.isChain()) {
Ability ab = (Ability) action;
if (ab.isPerAbilityCooldown() && isOnPerAbilityCooldown(ab.getName())) {
return false;
}
}
return true;
}
@@ -726,6 +739,7 @@ public class DataAbilities extends AbstractDataAbilities {
stopCurrentAbility();
clearActiveToggles();
interruptConcurrentSlots();
resetAllPerAbilityCooldowns();
// Roll cooldown so NPC doesn't immediately attack after reset
rollCooldownOnReset();
@@ -30,6 +30,7 @@ import net.minecraft.util.MathHelper;
import net.minecraft.util.StatCollector;
import net.minecraft.village.MerchantRecipeList;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.living.LivingEvent;
@@ -151,6 +152,52 @@ public class ServerEventsHandler {
}
}
@SubscribeEvent
public void barrierAbsorbDamage(LivingAttackEvent event) {
if (event.entityLiving == null || event.entityLiving.worldObj == null || event.entityLiving.worldObj.isRemote)
return;
EntityEnergyBarrier barrier = EntityEnergyBarrier.getAbsorbingBarrier(event.entityLiving);
if (barrier != null) {
// Redirect the caster's damage to their barrier
barrier.absorbDamage(event.ammount);
event.setCanceled(true);
}
}
@SubscribeEvent
public void domeItemBlacklist(PlayerInteractEvent event) {
if (event.action == PlayerInteractEvent.Action.LEFT_CLICK_BLOCK) return;
EntityPlayer player = event.entityPlayer;
if (player == null || player.worldObj == null || player.worldObj.isRemote) return;
ItemStack held = player.getHeldItem();
if (held == null) return;
String itemId = net.minecraft.item.Item.itemRegistry.getNameForObject(held.getItem());
if (itemId == null) return;
String[] blacklist = noppes.npcs.config.ConfigEnergy.DomeItemBlacklist;
if (blacklist == null) return;
boolean blacklisted = false;
for (String banned : blacklist) {
if (banned.equals(itemId)) {
blacklisted = true;
break;
}
}
if (!blacklisted) return;
List<EntityEnergyBarrier> barriers = EntityEnergyBarrier.getActiveBarriers(player.worldObj);
for (EntityEnergyBarrier barrier : barriers) {
if (barrier instanceof kamkeel.npcs.entity.EntityEnergyDome && barrier.isEntityInside(player)) {
event.setCanceled(true);
return;
}
}
}
@SubscribeEvent
public void partyDamagedEvent(LivingAttackEvent event) {
if (!(event.source != null && event.source.getEntity() instanceof EntityPlayer) || !(event.entityLiving instanceof EntityPlayer) || FMLCommonHandler.instance().getEffectiveSide().isClient())
@@ -25,6 +25,7 @@ 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.renderer.MarkRenderer;
import noppes.npcs.client.renderer.RenderCNPCPlayer;
@@ -98,6 +99,24 @@ public class ClientEventHandler {
return;
}
// Ability Hotbar: Hold HUD key + scroll wheel to cycle
if (event.dwheel != 0 && ClientProxy.AbilityHudKey != null) {
int hudKeyCode = ClientProxy.AbilityHudKey.getKeyCode();
if (hudKeyCode != 0 && org.lwjgl.input.Keyboard.isKeyDown(hudKeyCode)) {
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) {
@@ -125,6 +144,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);
@@ -259,6 +259,7 @@ import java.util.Random;
public class ClientProxy extends CommonProxy {
public static KeyBinding NPCButton;
public static KeyBinding SpecialKey;
public static KeyBinding AbilityHudKey;
public static final Random RAND = new Random();
public static FontContainer Font;
@@ -334,11 +335,14 @@ public class ClientProxy extends CommonProxy {
Minecraft mc = Minecraft.getMinecraft();
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);
new PresetController(CustomNpcs.Dir);
if (ConfigMain.EnableUpdateChecker) {
@@ -5,10 +5,12 @@ 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.AbilityController;
import kamkeel.npcs.controllers.data.telegraph.TelegraphManager;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.data.RequestProperSpawnData;
import kamkeel.npcs.network.packets.player.CheckPlayerValue;
import kamkeel.npcs.network.packets.player.InputDevicePacket;
import kamkeel.npcs.network.packets.player.ScreenSizePacket;
@@ -59,6 +61,7 @@ public class ClientTickHandler {
if (mc.theWorld == null) {
ClientCacheHandler.clearCache();
ClientAbilityState.reset();
RequestProperSpawnData.clear();
}
this.prevWorld = mc.theWorld;
}
@@ -154,6 +157,16 @@ public class ClientTickHandler {
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);
}
// Update lightning bolts for ability effects
LightningBolt.updateAll();
return;
}
if (mc.thePlayer != null && mc.thePlayer.openContainer instanceof ContainerPlayer) {
@@ -179,13 +192,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;
@@ -196,10 +202,46 @@ public class ClientTickHandler {
return;
if (mc.theWorld.getTotalWorldTime() % 20 == 0) { // Update every second
if (RequestProperSpawnData.canDoBatchUpdate())
RequestProperSpawnData.handleBacklog();
updateCompassMarks();
}
}
/**
* 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;
Minecraft mc = Minecraft.getMinecraft();
if (mc.thePlayer == null || mc.currentScreen != null)
return;
if (!ClientAbilityState.shouldSuppressMovementInput())
return;
if (!ClientAbilityState.hasAbilityMovement) {
mc.thePlayer.motionX = 0;
mc.thePlayer.motionZ = 0;
}
if ((ClientAbilityState.movementLocked || ClientAbilityState.positionLocked)
&& !ClientAbilityState.hasAbilityMovement) {
if (ClientAbilityState.wasFlyingAtLock) {
mc.thePlayer.motionY = 0;
} else {
mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0);
}
}
}
@SubscribeEvent
public void onMouse(InputEvent.MouseInputEvent event) {
if (Mouse.getEventButton() == -1 && Mouse.getEventDWheel() == 0)
@@ -127,7 +127,7 @@ 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();
func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height);
@@ -1,7 +1,7 @@
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 net.minecraft.client.gui.GuiButton;
import net.minecraft.nbt.NBTTagCompound;
@@ -20,6 +20,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 +44,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 +57,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;
@@ -234,46 +242,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);
}
// ═══════════════════════════════════════════════════════════════════════════
@@ -331,9 +322,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;
@@ -347,8 +338,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));
}
@@ -382,7 +373,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);
@@ -409,7 +400,7 @@ 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) {
@@ -6,13 +6,13 @@ import kamkeel.npcs.controllers.data.ability.AbilityAction;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.ChainedAbilityEntry;
import kamkeel.npcs.controllers.data.ability.Condition;
import kamkeel.npcs.controllers.data.ability.AbilityIconData;
import kamkeel.npcs.controllers.data.ability.IChainedAbilityFieldProvider;
import kamkeel.npcs.controllers.data.ability.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.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.builder.GuiFieldBuilder;
@@ -21,18 +21,19 @@ 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.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.IChainedAbilityConfigCallback;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
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 static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS;
/**
* SubGui for editing a {@link ChainedAbility}.
* Core tabs: General, Entries, Conditions.
@@ -70,9 +71,9 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
// 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_END = 80;
private static final int COND_STRIDE = 10;
private static final int BTN_ADD_COND = 80;
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;
@@ -88,7 +89,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
private List<FieldDef> fieldDefs;
private List<ChainedAbilityEntry> entries;
private List<Condition> conditions;
private List<AbilityCondition> conditions;
// Dynamic tabs injected by field providers (e.g., "Icon")
private List<String> extraTabs = new ArrayList<>();
@@ -157,7 +158,18 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
FieldDef.floatField("ability.maxRange", chain::getMaxRange, chain::setMaxRange).range(0, 64)
).tab("Target"));
// External field providers (e.g., DBC Addon injecting an "Icon" tab)
// ── Icon tab ──────────────────────────────────────────────
AbilityIconData chainIcon = AbilityIconData.fromChainedAbility(chain);
fieldDefs.add(FieldDef.stringField("gui.texture", chainIcon::getTexture, chainIcon::setTexture).tab("Icon"));
fieldDefs.add(FieldDef.section("ability.icon.section.uv").tab("Icon"));
fieldDefs.add(FieldDef.intField("ability.icon.x", chainIcon::getIconX, chainIcon::setIconX).tab("Icon").range(0, 4096));
fieldDefs.add(FieldDef.intField("ability.icon.y", chainIcon::getIconY, chainIcon::setIconY).tab("Icon").range(0, 4096));
fieldDefs.add(FieldDef.section("gui.size").tab("Icon"));
fieldDefs.add(FieldDef.intField("gui.width", chainIcon::getWidth, chainIcon::setWidth).tab("Icon").range(1, 256));
fieldDefs.add(FieldDef.intField("gui.height", chainIcon::getHeight, chainIcon::setHeight).tab("Icon").range(1, 256));
fieldDefs.add(FieldDef.floatField("gui.scale", chainIcon::getScale, chainIcon::setScale).tab("Icon").range(0.1f, 10.0f));
// 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);
@@ -416,8 +428,8 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
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(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"));
@@ -425,7 +437,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
y += 22;
}
if (conditions.size() < 3) {
if (conditions.size() < MAX_CONDITIONS) {
sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add"));
y += ROW_H;
}
@@ -433,29 +445,10 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
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);
}
// ═══════════════════════════════════════════════════════════════════════════
@@ -623,7 +616,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
return true;
}
if (id == BTN_ADD_COND) {
if (conditions.size() < 3) {
if (conditions.size() < MAX_CONDITIONS) {
editingConditionIndex = conditions.size();
setSubGui(new SubGuiConditionEdit(null));
}
@@ -833,7 +826,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
}
private void handleConditionEditClosed(SubGuiConditionEdit gui) {
Condition result = gui.getResult();
AbilityCondition result = gui.getResult();
if (result != null && editingConditionIndex >= 0) {
if (editingConditionIndex < conditions.size()) {
conditions.set(editingConditionIndex, result);
@@ -879,7 +872,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
// Conditions
chain.getConditions().clear();
for (Condition c : conditions) {
for (AbilityCondition c : conditions) {
chain.getConditions().add(c);
}
@@ -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;
}
}
@@ -344,6 +344,9 @@ public class GuiFieldBuilder {
String translated = StatCollector.translateToLocal(def.getLabel());
int labelW = fontRenderer.getStringWidth(translated);
int fieldX = colLLabel + labelW + labelPadding;
// Clamp field width so it doesn't extend under the scrollbar
int maxW = contentRight - fieldX - 15;
if (maxW > 0 && fieldW > maxW) fieldW = maxW;
renderFieldAt(def, colLLabel, fieldX, fieldW, y);
}
@@ -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
}
@@ -173,7 +173,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,12 +215,14 @@ 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;
@@ -260,8 +263,8 @@ 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 == 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;
@@ -113,10 +113,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 +218,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);
}
@@ -0,0 +1,683 @@
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.IAbilityAction;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket;
import net.minecraft.client.Minecraft;
import noppes.npcs.client.ClientProxy;
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 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;
// 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);
} else {
slots[rawSlotIndex].drawCarousel(mc, sr, slotCooldown, cx, cy, scaledSize, isCenter, slotAlpha, showText);
}
}
GL11.glPopMatrix();
}
private void drawDeselectSlot(int cx, int cy, int size, boolean isCenter, float alpha) {
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 (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 (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.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(0.2f, 0.8f, 0.2f, 0.8f);
GL11.glLineWidth(1.0f);
GL11.glBegin(GL11.GL_LINE_LOOP);
GL11.glVertex2f(0, 0);
GL11.glVertex2f(overlayWidth, 0);
GL11.glVertex2f(overlayWidth, overlayHeight);
GL11.glVertex2f(0, overlayHeight);
GL11.glEnd();
GL11.glColor4f(0.8f, 0.8f, 0.8f, 0.9f);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(overlayWidth - 10, overlayHeight - 10);
GL11.glVertex2f(overlayWidth, overlayHeight - 10);
GL11.glVertex2f(overlayWidth, overlayHeight);
GL11.glVertex2f(overlayWidth - 10, overlayHeight);
GL11.glEnd();
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;
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 (slotData.isChainKey()) {
action = AbilityController.Instance.resolveChainedAbility(slotData.getResolveKey());
} else {
ability = AbilityController.Instance.resolveAbility(key);
action = ability;
}
if (ability == null && action == null) key = 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() {
if (ClientProxy.AbilityHudKey == null) return false;
int keyCode = ClientProxy.AbilityHudKey.getKeyCode();
return keyCode != 0 && org.lwjgl.input.Keyboard.isKeyDown(keyCode);
}
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;
if (ability != null && ability.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();
}
}
@@ -0,0 +1,302 @@
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.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.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) {
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;
if (altTexture) {
drawRoundedRect(-radius, -radius, radius, radius, 0.6f, 0.6f, 0.6f, 0.75f * alpha, false);
if (isCenter) {
drawRoundedRect(-radius, -radius, radius, radius, 0.8f, 0.8f, 0.2f, alpha, true);
} else {
drawRoundedRect(-radius, -radius, radius, radius, 0.4f, 0.4f, 0.4f, alpha * 0.8f, true);
}
} else {
if (isCenter) {
drawCircle(radius, 0.8f, 0.8f, 0.2f, 0.66f * alpha, false);
drawCircle(radius, 0.8f, 0.8f, 0.2f, alpha, true);
} else {
drawCircle(radius, 1f, 1f, 1f, 0.66f * alpha, false);
drawCircle(radius, 0.4f, 0.4f, 0.4f, alpha * 0.8f, 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);
GL11.glColor4f(1, 1, 1, slotAlpha);
icon.draw(getToggleState());
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,140 @@
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.AbilityIconData;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.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.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;
private AbilityIcon(AbilityIconData data) {
this.data = data;
this.width = data.width;
this.height = data.height;
}
public static AbilityIcon fromAbility(Ability ability) {
if (ability != null) {
return new AbilityIcon(AbilityIconData.fromAbility(ability));
}
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) {
TextureManager renderEngine = Minecraft.getMinecraft().renderEngine;
ImageData imageData = null;
if (data.hasTexture()) {
imageData = ClientCacheHandler.getImageData(data.texture);
}
GL11.glPushMatrix();
GL11.glColor4f(1, 1, 1, 1);
Tessellator t;
if (imageData == null || !imageData.imageLoaded()) {
GL11.glScalef(1.0f, 1.0f, 1);
renderEngine.bindTexture(FALLBACK_TEXTURE);
t = getFallbackTessellator();
} else {
GL11.glScalef(data.scale, data.scale, 1);
renderEngine.bindTexture(imageData.getLocation());
t = getTessellator(imageData, state);
}
t.draw();
GL11.glPopMatrix();
}
private Tessellator getTessellator(ImageData imageData, int state) {
float hw = data.width / 2f;
float hh = data.height / 2f;
float texW = imageData.getTotalWidth();
float texH = imageData.getTotalHeight();
int ix = data.getIconXForState(state);
int iy = data.getIconYForState(state);
float u1 = ix / texW;
float v1 = iy / texH;
float u2 = (ix + data.width) / texW;
float v2 = (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 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.hasTexture();
}
/**
* Returns the approximate visual size (max dimension) that draw() produces.
* Textured: max(width,height) * scale. Fallback: 32.
*/
public float getDrawSize() {
if (data.hasTexture()) {
return Math.max(width, height) * data.scale;
}
return 32f;
}
}
@@ -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);
@@ -315,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"));
@@ -342,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"));
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());
}
}
}
@@ -0,0 +1,155 @@
package noppes.npcs.client.gui.player.inventory;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import net.minecraft.client.gui.GuiButton;
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.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.data.AbilityHotbarData;
import noppes.npcs.controllers.data.PlayerData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* SubGui for selecting an ability to assign to a hotbar slot.
*/
public class SubGuiSelectAbilityForSlot extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener {
private HashMap<String, String> displayToKey = new HashMap<>();
private GuiCustomScroll scrollAbilities;
private String selected = null;
private String search = "";
public boolean confirmed = false;
public String selectedAbilityKey = null;
public int slotIndex;
public boolean removeAbility = false;
public SubGuiSelectAbilityForSlot(int slotIndex) {
this.slotIndex = slotIndex;
this.closeOnEsc = true;
this.drawDefaultBackground = true;
guiLeft -= 10;
xSize = 256 + 10;
this.setBackground("menubg.png");
}
@Override
public void initGui() {
super.initGui();
guiTop += 10;
if (scrollAbilities == null) {
scrollAbilities = new GuiCustomScroll(this, 0, 0);
scrollAbilities.setSize(177, 185);
}
scrollAbilities.guiLeft = guiLeft + 4;
scrollAbilities.guiTop = guiTop + 4;
addScroll(scrollAbilities);
loadAbilities();
scrollAbilities.setList(getSearchList());
addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 4, guiTop + 192, 177, 20, search));
addButton(new GuiNpcButton(0, guiLeft + 183, guiTop + 4, 79, 20, "gui.add"));
addButton(new GuiNpcButton(1, guiLeft + 183, guiTop + 26, 79, 20, "gui.cancel"));
addButton(new GuiNpcButton(2, guiLeft + 183, guiTop + 88, 79, 20, "gui.remove"));
}
private void loadAbilities() {
displayToKey.clear();
PlayerData playerData = ClientCacheHandler.playerData;
if (playerData == null || playerData.abilityData == null) {
return;
}
List<String> abilities = playerData.abilityData.getUnlockedAbilityList();
for (String key : abilities) {
String displayName;
if (key.startsWith(AbilityHotbarData.CHAIN_PREFIX)) {
String chainKey = key.substring(AbilityHotbarData.CHAIN_PREFIX.length());
ChainedAbility chain = AbilityController.Instance != null ?
AbilityController.Instance.resolveChainedAbility(chainKey) : null;
displayName = chain != null ? "\u00A76\u2726 " + chain.getDisplayName() : key;
} else {
Ability ability = AbilityController.Instance != null ?
AbilityController.Instance.resolveAbility(key) : null;
displayName = ability != null ? ability.getDisplayName() : key;
}
displayToKey.put(displayName, key);
}
}
@Override
public void actionPerformed(GuiButton button) {
int id = button.id;
if (id == 0 && selected != null) {
confirmed = true;
selectedAbilityKey = displayToKey.get(selected);
this.close();
}
if (id == 1) {
this.close();
}
if (id == 2) {
this.removeAbility = true;
this.close();
}
}
@Override
public void customScrollClicked(int i, int i1, int i2, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll == scrollAbilities)
selected = scrollAbilities.getSelected();
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll == scrollAbilities && selection != null) {
confirmed = true;
selectedAbilityKey = displayToKey.get(selection);
this.close();
}
}
@Override
public void unFocused(GuiNpcTextField guiNpcTextField) {
}
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(55) != null) {
if (getTextField(55).isFocused()) {
if (search.equals(getTextField(55).getText()))
return;
search = getTextField(55).getText().toLowerCase();
scrollAbilities.resetScroll();
scrollAbilities.setList(getSearchList());
}
}
}
private List<String> getSearchList() {
if (search.isEmpty()) {
return new ArrayList<>(displayToKey.keySet());
}
List<String> list = new ArrayList<>();
for (String name : displayToKey.keySet()) {
if (name.toLowerCase().contains(search))
list.add(name);
}
return list;
}
}
@@ -80,9 +80,10 @@ public class GuiEffectBar extends GuiScreen {
int iconWidth = entry.effect.getWidth();
int iconHeight = entry.effect.getHeight();
int texWidth = imageData.getTotalWidth();
int texHeight = imageData.getTotalHeight();
// Use iconYOffset to vertically center the icon
func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texWidth);
func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texHeight);
GL11.glDisable(GL11.GL_DEPTH_TEST);
Minecraft.getMinecraft().getTextureManager().bindTexture(specialIcons);
@@ -190,7 +191,7 @@ public class GuiEffectBar extends GuiScreen {
if (imageData != null && imageData.imageLoaded()) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
imageData.bindTexture();
func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, hoveredEffect.iconY, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), imageData.getTotalWidth());
func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, hoveredEffect.iconY, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), imageData.getTotalHeight());
}
textureManager.bindTexture(specialIcons);
@@ -24,10 +24,21 @@ public class GuiMenuTopButton extends GuiNpcButton {
height = 20;
}
/**
* Place to the RIGHT of the given button.
*/
public GuiMenuTopButton(int i, GuiButton parent, String s) {
this(i, parent.xPosition + parent.width, parent.yPosition, s);
}
/**
* Place to the LEFT of the given button.
*/
public GuiMenuTopButton(int i, String s, GuiButton rightNeighbor) {
this(i, rightNeighbor.xPosition - (Minecraft.getMinecraft().fontRenderer.getStringWidth(StatCollector.translateToLocal(s)) + 12),
rightNeighbor.yPosition, s);
}
public GuiMenuTopButton(int i, GuiButton parent, String s,
IButtonListener listener) {
this(i, parent, s);
@@ -69,10 +69,10 @@ public class ConfigClient {
// HUD PROPERTIES
public static Property QuestOverlayXProperty;
public static int QuestOverlayX = 0;
public static float QuestOverlayX = 0;
public static Property QuestOverlayYProperty;
public static int QuestOverlayY = 31;
public static float QuestOverlayY = 31;
public static Property QuestOverlayScaleProperty;
public static int QuestOverlayScale = 223;
@@ -84,10 +84,10 @@ public class ConfigClient {
public static boolean CompassEnabled = true;
public static Property CompassOverlayXProperty;
public static int CompassOverlayX = 37;
public static float CompassOverlayX = 37;
public static Property CompassOverlayYProperty;
public static int CompassOverlayY = 0;
public static float CompassOverlayY = 0;
public static Property CompassOverlayScaleProperty;
public static int CompassOverlayScale = 276;
@@ -95,6 +95,41 @@ public class ConfigClient {
public static Property CompassOverlayWidthProperty;
public static int CompassOverlayWidth = 200;
// Ability Hotbar HUD
public static Property AbilityHotbarEnabledProperty;
public static boolean AbilityHotbarEnabled = true;
public static Property AbilityHotbarXProperty;
public static float AbilityHotbarX = 3;
public static Property AbilityHotbarYProperty;
public static float AbilityHotbarY = 50;
public static Property AbilityHotbarScaleProperty;
public static int AbilityHotbarScale = 100;
public static Property AbilityHotbarHorizontalProperty;
public static boolean AbilityHotbarHorizontal = false;
public static Property AbilityHotbarAltTextureProperty;
public static boolean AbilityHotbarAltTexture = false;
// 1=Above(H)/Left(V), 2=Below(H)/Right(V)
public static Property AbilityHotbarTextPositionProperty;
public static int AbilityHotbarTextPosition = 2;
// Max visible slots: 3, 5, or 7
public static Property AbilityHotbarVisibleSlotsProperty;
public static int AbilityHotbarVisibleSlots = 5;
// Show Always: true = always visible, false = only visible while HUD key held
public static Property AbilityHotbarShowAlwaysProperty;
public static boolean AbilityHotbarShowAlways = true;
// Text Visibility: 0=Shown, 1=Hidden, 2=Held (only while HUD key held)
public static Property AbilityHotbarTextVisibilityProperty;
public static int AbilityHotbarTextVisibility = 0;
/**
* Texture Properties
**/
@@ -125,11 +160,11 @@ public class ConfigClient {
config.load();
// Hud Quest Overlay settings
QuestOverlayXProperty = config.get(HUD, "Quest Hud X", 0, "X position of the quest overlay.");
QuestOverlayX = QuestOverlayXProperty.getInt(0);
QuestOverlayXProperty = config.get(HUD, "Quest Hud X", 0.0, "X position of the quest overlay.");
QuestOverlayX = (float) QuestOverlayXProperty.getDouble(0);
QuestOverlayYProperty = config.get(HUD, "Quest Hud Y", 31, "Y position of the quest overlay.");
QuestOverlayY = QuestOverlayYProperty.getInt(31);
QuestOverlayYProperty = config.get(HUD, "Quest Hud Y", 31.0, "Y position of the quest overlay.");
QuestOverlayY = (float) QuestOverlayYProperty.getDouble(31);
QuestOverlayScaleProperty = config.get(HUD, "Quest Hud Scale", 223, "Scale percentage of the quest overlay.");
QuestOverlayScale = QuestOverlayScaleProperty.getInt(223);
@@ -149,22 +184,18 @@ public class ConfigClient {
CompassOverlayXProperty = config.get(
HUD,
"Compass Hud X",
37,
"Horizontal position of compass overlay (0-100 percentage)",
0,
100
37.0,
"Horizontal position of compass overlay (0-100 percentage)"
);
CompassOverlayX = CompassOverlayXProperty.getInt();
CompassOverlayX = (float) CompassOverlayXProperty.getDouble();
CompassOverlayYProperty = config.get(
HUD,
"Compass Hud Y",
0,
"Vertical position of compass overlay (0-100 percentage)",
0,
100
0.0,
"Vertical position of compass overlay (0-100 percentage)"
);
CompassOverlayY = CompassOverlayYProperty.getInt();
CompassOverlayY = (float) CompassOverlayYProperty.getDouble();
CompassOverlayScaleProperty = config.get(
HUD,
@@ -186,6 +217,36 @@ public class ConfigClient {
);
CompassOverlayWidth = CompassOverlayWidthProperty.getInt();
// Ability Hotbar HUD Configs
AbilityHotbarEnabledProperty = config.get(HUD, "Ability Hotbar Enabled", true, "Enable Ability Hotbar HUD Component");
AbilityHotbarEnabled = AbilityHotbarEnabledProperty.getBoolean();
AbilityHotbarXProperty = config.get(HUD, "Ability Hotbar X", 3.0, "Horizontal position (0-100 percentage)");
AbilityHotbarX = (float) AbilityHotbarXProperty.getDouble();
AbilityHotbarYProperty = config.get(HUD, "Ability Hotbar Y", 50.0, "Vertical position (0-100 percentage)");
AbilityHotbarY = (float) AbilityHotbarYProperty.getDouble();
AbilityHotbarScaleProperty = config.get(HUD, "Ability Hotbar Scale", 100, "Scale percentage", 50, 300);
AbilityHotbarScale = AbilityHotbarScaleProperty.getInt();
AbilityHotbarHorizontalProperty = config.get(HUD, "Ability Hotbar Horizontal", false, "Display horizontally instead of vertically");
AbilityHotbarHorizontal = AbilityHotbarHorizontalProperty.getBoolean();
AbilityHotbarAltTextureProperty = config.get(HUD, "Ability Hotbar Alt Texture", false, "Use rounded square instead of circle slots");
AbilityHotbarAltTexture = AbilityHotbarAltTextureProperty.getBoolean();
AbilityHotbarTextPositionProperty = config.get(HUD, "Ability Hotbar Text Position", 2, "Text label position (1=Above/Left, 2=Below/Right)");
AbilityHotbarTextPosition = AbilityHotbarTextPositionProperty.getInt(2);
AbilityHotbarVisibleSlotsProperty = config.get(HUD, "Ability Hotbar Visible Slots", 5, "Max visible slots in hotbar (3, 5, or 7)");
AbilityHotbarVisibleSlots = AbilityHotbarVisibleSlotsProperty.getInt(5);
AbilityHotbarShowAlwaysProperty = config.get(HUD, "Ability Hotbar Show Always", true, "Always show hotbar (false = only while HUD key is held)");
AbilityHotbarShowAlways = AbilityHotbarShowAlwaysProperty.getBoolean(true);
AbilityHotbarTextVisibilityProperty = config.get(HUD, "Ability Hotbar Text Visibility", 0, "Text visibility (0=Shown, 1=Hidden, 2=Held)");
AbilityHotbarTextVisibility = AbilityHotbarTextVisibilityProperty.getInt(0);
// General
AllowClientScriptsProperty = config.get(GENERAL, "Allow Client Scripts", true, "Allow the server to run scripts on the client. If disabled, no server scripts will execute client-side.");
@@ -0,0 +1,37 @@
package noppes.npcs.config;
import cpw.mods.fml.common.FMLLog;
import net.minecraftforge.common.config.Configuration;
import org.apache.logging.log4j.Level;
import java.io.File;
public class ConfigEnergy {
public static Configuration config;
public final static String DOMES = "Domes";
public static String[] DomeItemBlacklist;
public static void init(File configFile) {
config = new Configuration(configFile);
try {
config.load();
DomeItemBlacklist = config.getStringList(
"Item Blacklist", DOMES,
new String[]{"minecraft:ender_pearl"},
"Items that cannot be used while inside an Energy Dome.\n"
+ "Format: modid:itemname (e.g., minecraft:ender_pearl)"
);
} catch (Exception e) {
FMLLog.log(Level.ERROR, e, "CustomNPC+ has had a problem loading its energy configuration");
} finally {
if (config.hasChanged()) {
config.save();
}
}
}
}
@@ -10,6 +10,7 @@ public class LoadConfiguration {
public static File clientConfigFile;
public static File experimentalConfigFile;
public static File marketConfigFile;
public static File energyConfigFile;
public static void init(String configpath) {
mainConfigFile = new File(configpath + "main.cfg");
@@ -19,6 +20,7 @@ public class LoadConfiguration {
debugConfigFile = new File(configpath + "debug.cfg");
experimentalConfigFile = new File(configpath + "experimental.cfg");
marketConfigFile = new File(configpath + "market.cfg");
energyConfigFile = new File(configpath + "energy.cfg");
ConfigMain.init(mainConfigFile);
ConfigItem.init(itemConfigFile);
@@ -27,5 +29,6 @@ public class LoadConfiguration {
ConfigDebug.init(debugConfigFile);
ConfigExperimental.init(experimentalConfigFile);
ConfigMarket.init(marketConfigFile);
ConfigEnergy.init(energyConfigFile);
}
}
@@ -213,6 +213,18 @@ public class AnimationController implements IAnimationHandler {
}
}
/**
* Loads built-in animations for client-side usage.
* On dedicated servers, AnimationController.load() never runs on the client JVM,
* so built-in animations would be missing for client-only systems like ability preview.
* This method loads just the built-in animations (from assets and registered addons)
* without touching user animations or world save data.
*/
public void loadClientBuiltIns() {
loadBuiltInAnimations();
loadRegisteredBuiltIns();
}
private File getDir() {
return new File(CustomNpcs.getWorldSaveDirectory(), "animations");
}
@@ -0,0 +1,47 @@
package noppes.npcs.controllers.data;
import net.minecraft.nbt.NBTTagCompound;
public class AbilityHotbarData {
public static final String CHAIN_PREFIX = "chain:";
public static final int TOTAL_SLOTS = 12;
public int slot = -1;
public String abilityKey = "";
public AbilityHotbarData() {
}
public AbilityHotbarData(int slot) {
this.slot = slot;
}
public boolean isChainKey() {
return abilityKey != null && abilityKey.startsWith(CHAIN_PREFIX);
}
public String getResolveKey() {
if (isChainKey()) return abilityKey.substring(CHAIN_PREFIX.length());
return abilityKey;
}
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
NBTTagCompound tag = new NBTTagCompound();
tag.setInteger("slot", slot);
tag.setString("abilityKey", abilityKey != null ? abilityKey : "");
compound.setTag("AbilityHotbar" + slot, tag);
return compound;
}
public void readFromNBT(NBTTagCompound compound) {
abilityKey = compound.getString("abilityKey");
}
public void reset() {
abilityKey = "";
}
public boolean isEmpty() {
return abilityKey == null || abilityKey.isEmpty();
}
}
@@ -8,6 +8,7 @@ import kamkeel.npcs.controllers.data.ability.IAbilityAction;
import kamkeel.npcs.controllers.data.ability.ToggleEntry;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket;
import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket;
import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket;
import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket;
@@ -22,6 +23,7 @@ import net.minecraft.util.DamageSource;
import noppes.npcs.AbstractDataAbilities;
import noppes.npcs.EventHooks;
import noppes.npcs.LogWriter;
import noppes.npcs.NoppesUtilPlayer;
import noppes.npcs.api.ability.IPlayerAbilityData;
import noppes.npcs.api.entity.IPlayer;
import noppes.npcs.controllers.ScriptController;
@@ -225,14 +227,30 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
@Override
protected void rollCooldown(Ability ability) {
if (!ability.isIgnoreCooldown()) {
cooldownEndTime = getWorldTime() + ability.getCooldownTicks();
if (ability.isIgnoreCooldown()) return;
int duration = ability.getCooldownTicks();
long endTime = getWorldTime() + duration;
if (ability.isPerAbilityCooldown()) {
// Per-ability: only this ability goes on cooldown
if (currentAbilityKey != null) {
setPerAbilityCooldown(currentAbilityKey, endTime, duration);
}
} else {
// Global: all global-cooldown abilities share this cooldown
cooldownEndTime = endTime;
globalCooldownDuration = duration;
}
syncCooldownToClient();
}
@Override
protected void rollChainCooldown(ChainedAbility chain) {
cooldownEndTime = getWorldTime() + chain.getCooldownTicks();
int duration = chain.getCooldownTicks();
cooldownEndTime = getWorldTime() + duration;
globalCooldownDuration = duration;
syncCooldownToClient();
}
@Override
@@ -250,6 +268,8 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
@Override
protected void onInterruptComplete() {
// Player clears state immediately (unlike NPC which ticks through DAZED)
// Stop the dazed animation that was started in interruptCurrentAbility()
stopAbilityAnimation();
currentAbility = null;
currentAbilityKey = null;
currentTarget = null;
@@ -278,6 +298,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
// Apply rotation and position locks after ability tick
applyRotationControl(player);
applyPositionLock(player);
applyAnimationRotationSync(player);
// Sync lock state to client (only sends when flags change)
syncAbilityStateIfNeeded(player);
@@ -364,8 +385,20 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
// Regular ability activation
Ability ability = (Ability) action;
// Check universal cooldown (abilities can optionally ignore it)
if (!ability.isIgnoreCooldown() && isOnCooldown()) return false;
// Toggle abilities cycle state instead of executing
if (ability.isToggleable()) {
toggleAbility(key);
return true;
}
// Check cooldown (per-ability cooldowns are independent from global)
if (!ability.isIgnoreCooldown()) {
if (ability.isPerAbilityCooldown()) {
if (isOnPerAbilityCooldown(key)) return false;
} else {
if (isOnCooldown()) return false;
}
}
// Fire extender start hook (e.g., resource cost checks)
if (!AbilityController.Instance.fireOnAbilityStart(ability, player, null)) {
@@ -420,6 +453,18 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
EntityPlayer player = playerData.player;
if (player instanceof EntityPlayerMP) {
PlayerAbilitySyncPacket.sendToPlayer((EntityPlayerMP) player);
syncCooldownToClient();
}
}
/**
* Sync cooldown state (global + per-ability) to the client.
* Sent as a lightweight packet separate from full ability sync.
*/
public void syncCooldownToClient() {
EntityPlayer player = playerData.player;
if (player instanceof EntityPlayerMP) {
AbilityCooldownSyncPacket.sendToPlayer((EntityPlayerMP) player);
}
}
@@ -460,7 +505,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
}
public void setSelectedIndex(int index) {
if (index >= 0 && index < unlockedAbilities.size()) {
if (index == -1 || (index >= 0 && index < unlockedAbilities.size())) {
this.selectedIndex = index;
syncToClient();
}
@@ -539,9 +584,15 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
/**
* Check if a specific ability key is on cooldown.
* Currently uses universal cooldown (same for all abilities).
* Respects per-ability cooldown if the ability has it enabled.
*/
public boolean isOnCooldown(String key, EntityPlayer player) {
if (AbilityController.Instance != null) {
Ability ability = AbilityController.Instance.resolveAbility(key);
if (ability != null && ability.isPerAbilityCooldown()) {
return isOnPerAbilityCooldown(key);
}
}
return isOnCooldown(player);
}
@@ -552,17 +603,21 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
/**
* Reset cooldown for a specific ability key.
* Currently resets the universal cooldown.
* Resets per-ability cooldown if applicable, and global cooldown.
*/
public void resetCooldown(String key) {
resetPerAbilityCooldown(key);
cooldownEndTime = 0;
syncCooldownToClient();
}
/**
* Reset all cooldowns.
* Reset all cooldowns (global + all per-ability).
*/
public void resetAllCooldowns() {
cooldownEndTime = 0;
resetAllPerAbilityCooldowns();
syncCooldownToClient();
}
// ═══════════════════════════════════════════════════════════════════
@@ -596,6 +651,8 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
@Override
public void resetCooldown() {
cooldownEndTime = 0;
resetAllPerAbilityCooldowns();
syncCooldownToClient();
}
// ═══════════════════════════════════════════════════════════════════
@@ -648,6 +705,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
if (clearCooldowns) {
cooldownEndTime = 0;
resetAllPerAbilityCooldowns();
}
interruptCooldownRolled = false;
@@ -788,6 +846,17 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
}
}
private void applyAnimationRotationSync(EntityPlayer player) {
if (rotationLocked || currentAbility == null) return;
if (currentAbility.getPhase() == AbilityPhase.IDLE || currentAbility.getPhase() == AbilityPhase.DAZED)
return;
// TODO This is a temporary duct-tape solution to fix the animation not rotating with head rotation
if (!currentAbility.isRotationLockedForCurrentPhase() && player instanceof EntityPlayerMP) {
NoppesUtilPlayer.swingPlayerArm((EntityPlayerMP) player);
}
}
// ═══════════════════════════════════════════════════════════════════
// POSITION LOCKING (Player-specific application)
// ═══════════════════════════════════════════════════════════════════
@@ -935,8 +1004,9 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
}
/**
* Remove any unlocked ability keys that can no longer be resolved.
* Called during load to clean up references to deleted abilities.
* Remove any unlocked ability keys that can no longer be resolved or
* are no longer allowed for players (e.g. NPC-only abilities).
* Called during load to clean up references to deleted/restricted abilities.
* Supports both regular ability keys and "chain:" prefixed chained ability keys.
*/
private void validateUnlockedAbilities() {
@@ -949,6 +1019,9 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
if (resolved == null) {
it.remove();
LogWriter.info("Removed invalid ability reference from player data: " + key);
} else if (!resolved.getAllowedBy().allowsPlayer()) {
it.remove();
LogWriter.info("Removed non-player ability from player data: " + key);
}
}
}
@@ -0,0 +1,84 @@
package noppes.npcs.controllers.data;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
public class PlayerAbilityHotbarData {
public AbilityHotbarData[] slots = new AbilityHotbarData[AbilityHotbarData.TOTAL_SLOTS];
public PlayerAbilityHotbarData() {
for (int i = 0; i < slots.length; i++) {
slots[i] = new AbilityHotbarData(i);
}
}
public AbilityHotbarData getSlot(int index) {
if (index < 0 || index >= slots.length) return null;
return slots[index];
}
public void setSlot(int index, String abilityKey) {
if (index < 0 || index >= slots.length) return;
slots[index].abilityKey = abilityKey != null ? abilityKey : "";
}
public void clearSlot(int index) {
if (index < 0 || index >= slots.length) return;
slots[index].reset();
}
public boolean hasAnyAbilities() {
for (AbilityHotbarData slot : slots) {
if (!slot.isEmpty()) return true;
}
return false;
}
public void writeToNBT(NBTTagCompound compound) {
for (int i = 0; i < slots.length; i++) {
slots[i].writeToNBT(compound);
}
}
public void readFromNBT(NBTTagCompound compound) {
for (int i = 0; i < slots.length; i++) {
NBTTagCompound slotTag = compound.getCompoundTag("AbilityHotbar" + i);
slots[i].readFromNBT(slotTag);
}
validateSlots();
}
public void validateSlots() {
if (AbilityController.Instance == null) return;
for (AbilityHotbarData slot : slots) {
if (slot.isEmpty()) continue;
boolean valid;
if (slot.isChainKey()) {
valid = AbilityController.Instance.canResolveChainedAbility(slot.getResolveKey());
} else {
valid = AbilityController.Instance.canResolveAbility(slot.abilityKey);
// Also check that resolved ability allows player usage
if (valid) {
Ability ability = AbilityController.Instance.resolveAbility(slot.abilityKey);
if (ability != null && !ability.getAllowedBy().allowsPlayer()) {
valid = false;
}
}
}
if (!valid) {
slot.reset();
}
}
}
public void syncToClient(EntityPlayer player) {
if (player instanceof EntityPlayerMP) {
AbilityHotbarSyncPacket.sendToPlayer((EntityPlayerMP) player);
}
}
}
@@ -65,6 +65,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
public PlayerTradeData tradeData = new PlayerTradeData(this);
public PlayerAbilityData abilityData = new PlayerAbilityData(this);
public PlayerAbilityHotbarData hotbarData = new PlayerAbilityHotbarData();
public ActionManager actionManager = new ActionManager();
public PlayerDataScript scriptData;
@@ -119,6 +120,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
// Sync player ability data to client
abilityData.syncToClient();
// Sync hotbar data to client
hotbarData.syncToClient(player);
}
public void onLogout() {
@@ -151,6 +155,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
magicData.readToNBT(data);
tradeData.readFromNBT(data);
abilityData.readFromNBT(data);
hotbarData.readFromNBT(data);
if (player != null) {
playername = player.getCommandSenderName();
@@ -195,6 +200,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
magicData.writeToNBT(compound);
tradeData.writeToNBT(compound);
abilityData.writeToNBT(compound);
hotbarData.writeToNBT(compound);
compound.setString("PlayerName", playername);
compound.setString("UUID", uuid);
@@ -11,6 +11,7 @@ import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumSoundOperation;
import kamkeel.npcs.network.packets.data.ChatBubblePacket;
import kamkeel.npcs.network.packets.data.QuestCompletionPacket;
import kamkeel.npcs.network.packets.data.RequestProperSpawnData;
import kamkeel.npcs.network.packets.data.SoundManagementPacket;
import kamkeel.npcs.network.packets.data.npc.UpdateNpcPacket;
import kamkeel.npcs.network.packets.data.npc.WeaponNpcPacket;
@@ -68,6 +69,7 @@ import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.event.ServerChatEvent;
import noppes.npcs.CustomItems;
@@ -229,6 +231,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
public FlyingMoveHelper flyMoveHelper = new FlyingMoveHelper(this);
public PathNavigate flyNavigator = new PathNavigateFlying(this, worldObj);
@SideOnly(Side.CLIENT)
public int immediateSpawnDataFixAttempts = 0;
public EntityNPCInterface(World world) {
super(world);
try {
@@ -1829,10 +1834,17 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
try {
readSpawnData(ByteBufUtils.readNBT(buf));
} catch (IOException e) {
RequestProperSpawnData.reportMissingData(this);
}
}
public void readSpawnData(NBTTagCompound compound) {
if ((compound.hasNoTags() || !compound.hasKey("MaxHealth", Constants.NBT.TAG_DOUBLE))) {
RequestProperSpawnData.reportMissingData(this);
return;
}
immediateSpawnDataFixAttempts = 0;
stats.maxHealth = compound.getDouble("MaxHealth");
ais.setWalkingSpeed(compound.getInteger("Speed"));
stats.hideKilledBody = compound.getBoolean("DeadBody");
@@ -1,9 +1,11 @@
package noppes.npcs.mixin;
import kamkeel.npcs.util.AttributeItemUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.gui.player.GuiAuctionInterface;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
@@ -28,9 +30,14 @@ public abstract class MixinItemStack {
@Inject(method = "getTooltip", at = @At("TAIL"), cancellable = true)
public void getAttributeTooltip(EntityPlayer player, boolean advanced, CallbackInfoReturnable<List<String>> cir) {
boolean override = false;
if (Minecraft.getMinecraft().currentScreen instanceof GuiAuctionInterface) {
override = true;
}
List<String> tooltip = cir.getReturnValue();
if (hasTagCompound() && getTagCompound().hasKey(TAG_RPGCORE)) {
cir.setReturnValue(AttributeItemUtil.getToolTip(tooltip, getTagCompound()));
cir.setReturnValue(AttributeItemUtil.getToolTip(tooltip, getTagCompound(), override));
}
}
}
@@ -89,6 +89,14 @@ public class ScriptEnergyBarrier<T extends EntityEnergyBarrier> extends ScriptEn
entity.getBarrierData().defaultMultiplier = multiplier;
}
public boolean isSolid() {
return entity.getBarrierData().solid;
}
public void setSolid(boolean solid) {
entity.getBarrierData().solid = solid;
}
public boolean isKnockbackEnabled() {
return entity.getBarrierData().knockbackEnabled;
}
@@ -105,12 +113,12 @@ public class ScriptEnergyBarrier<T extends EntityEnergyBarrier> extends ScriptEn
entity.getBarrierData().knockbackStrength = strength;
}
public int getKnockbackTarget() {
return entity.getBarrierData().knockbackTarget;
public boolean isAbsorbing() {
return entity.getBarrierData().absorbing;
}
public void setKnockbackTarget(int target) {
entity.getBarrierData().knockbackTarget = target;
public void setAbsorbing(boolean absorbing) {
entity.getBarrierData().absorbing = absorbing;
}
public int getBarrierType() {