Merge branch 'dev' into pr-254

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

No files matched your search

+2 -1
View File
@@ -6,6 +6,7 @@ import foxz.commandhelper.annotations.SubCommand;
import foxz.commandhelper.permissions.OpOnly;
import foxz.commandhelper.permissions.ParamCheck;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.command.CommandBase;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.NoppesUtilServer;
@@ -90,7 +91,7 @@ public class CmdDialog extends ChMcLogger {
)
public boolean reload(String args[]) {
new DialogController().load();
SyncController.syncAllDialogs();
SyncController.syncAll(SyncType.DIALOG_CATEGORY);
return true;
}
+1 -1
View File
@@ -142,7 +142,7 @@ public class CmdNpc extends ChMcLogger {
EntityCustomNpc npc = new EntityCustomNpc(pw);
if (args.length > 0)
npc.display.name = args[0];
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch);
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.rotationYaw, 0);
npc.ais.startPos = new int[]{MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)};
pw.spawnEntityInWorld(npc);
npc.setHealth(npc.getMaxHealth());
+2 -1
View File
@@ -6,6 +6,7 @@ import foxz.commandhelper.annotations.SubCommand;
import foxz.commandhelper.permissions.OpOnly;
import foxz.commandhelper.permissions.ParamCheck;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.enums.SyncType;
import kamkeel.npcs.network.packets.data.AchievementPacket;
import kamkeel.npcs.network.packets.data.ChatAlertPacket;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -170,7 +171,7 @@ public class CmdQuest extends ChMcLogger {
)
public boolean reload(String args[]) {
new QuestController().load();
SyncController.syncAllQuests();
SyncController.syncAll(SyncType.QUEST_CATEGORY);
return true;
}
}
@@ -37,6 +37,15 @@ public class DBCAddon {
public void doDBCDamage(EntityNPCInterface npc, float attackStrength, Entity receiver) {
}
/**
* Returns the pre-calculated DBC attack damage of the current attacker,
* or the vanilla damage if DBC damage was not calculated.
* Used by Counter (PERCENT mode) to base counter damage on the full DBC attack, not vanilla base.
*/
public float getAttackerDBCDamage(float vanillaDamage) {
return vanillaDamage;
}
public boolean isKO(EntityNPCInterface npc, EntityPlayer player) {
return false;
}
@@ -0,0 +1,42 @@
package kamkeel.npcs.client.command;
import kamkeel.npcs.util.CNPCDebug;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
/**
* Client-only command to toggle debug logging.
* Registered via ClientCommandHandler so it runs entirely on the client
* without sending a packet to the server.
*/
public class CommandCNPCDebugger extends CommandBase {
@Override
public String getCommandName() {
return "cnpcdebugger";
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "/cnpcdebugger <type> - Toggle client debug logging for a type (e.g. energy)";
}
@Override
public int getRequiredPermissionLevel() {
return 0;
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args.length == 0) {
sender.addChatMessage(new ChatComponentText("\u00A7cUsage: /cnpcdebugger <type>"));
return;
}
String type = args[0].toLowerCase();
boolean newState = CNPCDebug.toggleClient(type);
String stateText = newState ? "\u00A7aENABLED" : "\u00A7cDISABLED";
sender.addChatMessage(new ChatComponentText("\u00A77[CNPC+] \u00A7eClient debug '" + type + "' " + stateText));
}
}
@@ -0,0 +1,38 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager;
import kamkeel.npcs.entity.EntityEnergyProjectile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.client.event.RenderWorldLastEvent;
/**
* Renders packet-driven charging previews through RenderManager.
*/
public class EnergyChargePreviewRenderer {
@SubscribeEvent
public void onRenderWorldLast(RenderWorldLastEvent event) {
if (EnergyChargePreviewManager.ClientInstance == null || !EnergyChargePreviewManager.ClientInstance.hasPreviews()) {
return;
}
Minecraft mc = Minecraft.getMinecraft();
EntityPlayer player = mc.thePlayer;
if (player == null) return;
float partialTicks = event.partialTicks;
for (EntityEnergyProjectile entity : EnergyChargePreviewManager.ClientInstance.getPreviews()) {
if (entity == null || entity.isDead) continue;
double x = entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks - RenderManager.renderPosX;
double y = entity.prevPosY + (entity.posY - entity.prevPosY) * partialTicks - RenderManager.renderPosY;
double z = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks - RenderManager.renderPosZ;
RenderManager.instance.renderEntityWithPosYaw(entity, x, y, z, entity.rotationYaw, partialTicks);
}
}
}
@@ -1,259 +0,0 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
/**
* Base renderer for ability projectiles.
* Provides common GL state setup and rendering utilities.
*
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public abstract class RenderAbilityProjectile extends Render {
protected static final ResourceLocation WHITE_TEXTURE = new ResourceLocation("customnpcs", "textures/entity/white.png");
public RenderAbilityProjectile() {
this.shadowSize = 0.0f;
}
/**
* Setup GL state for translucent, self-illuminated rendering.
* Forces full brightness so world lighting does not affect projectiles.
*/
protected void setupRenderState() {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glAlphaFunc(GL11.GL_GREATER, 0.003921569F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_TEXTURE_2D);
// Force full brightness - prevents world lighting from darkening projectiles
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f);
}
/**
* Restore GL state after rendering.
*/
protected void restoreRenderState() {
GL11.glPopAttrib();
GL11.glPopMatrix();
}
/**
* Extract RGB components from color int.
*/
protected float[] extractRGB(int color) {
float r = ((color >> 16) & 0xFF) / 255.0f;
float g = ((color >> 8) & 0xFF) / 255.0f;
float b = (color & 0xFF) / 255.0f;
return new float[]{r, g, b};
}
/**
* Render a cube centered at origin with given color and alpha.
*/
protected void renderCube(int color, float alpha, float halfSize) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
Tessellator tess = Tessellator.instance;
// Front face (z+)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 0, 1);
tess.addVertex(-halfSize, -halfSize, halfSize);
tess.addVertex(halfSize, -halfSize, halfSize);
tess.addVertex(halfSize, halfSize, halfSize);
tess.addVertex(-halfSize, halfSize, halfSize);
tess.draw();
// Back face (z-)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 0, -1);
tess.addVertex(halfSize, -halfSize, -halfSize);
tess.addVertex(-halfSize, -halfSize, -halfSize);
tess.addVertex(-halfSize, halfSize, -halfSize);
tess.addVertex(halfSize, halfSize, -halfSize);
tess.draw();
// Top face (y+)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 1, 0);
tess.addVertex(-halfSize, halfSize, halfSize);
tess.addVertex(halfSize, halfSize, halfSize);
tess.addVertex(halfSize, halfSize, -halfSize);
tess.addVertex(-halfSize, halfSize, -halfSize);
tess.draw();
// Bottom face (y-)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, -1, 0);
tess.addVertex(-halfSize, -halfSize, -halfSize);
tess.addVertex(halfSize, -halfSize, -halfSize);
tess.addVertex(halfSize, -halfSize, halfSize);
tess.addVertex(-halfSize, -halfSize, halfSize);
tess.draw();
// Right face (x+)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(1, 0, 0);
tess.addVertex(halfSize, -halfSize, halfSize);
tess.addVertex(halfSize, -halfSize, -halfSize);
tess.addVertex(halfSize, halfSize, -halfSize);
tess.addVertex(halfSize, halfSize, halfSize);
tess.draw();
// Left face (x-)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(-1, 0, 0);
tess.addVertex(-halfSize, -halfSize, -halfSize);
tess.addVertex(-halfSize, -halfSize, halfSize);
tess.addVertex(-halfSize, halfSize, halfSize);
tess.addVertex(-halfSize, halfSize, -halfSize);
tess.draw();
}
/**
* Render a flat disc (cylinder with very small height) centered at origin.
* The disc lies flat on the XZ plane.
*/
protected void renderDisc(int color, float alpha, float radius, float thickness, int segments) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
Tessellator tess = Tessellator.instance;
float halfThick = thickness * 0.5f;
// Top face
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 1, 0);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
tess.addVertex(0, halfThick, 0);
tess.addVertex(x1, halfThick, z1);
tess.addVertex(x2, halfThick, z2);
tess.addVertex(0, halfThick, 0);
}
tess.draw();
// Bottom face
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, -1, 0);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
tess.addVertex(0, -halfThick, 0);
tess.addVertex(x2, -halfThick, z2);
tess.addVertex(x1, -halfThick, z1);
tess.addVertex(0, -halfThick, 0);
}
tess.draw();
// Edge
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
// Normal pointing outward
float nx = (float) Math.cos((angle1 + angle2) * 0.5);
float nz = (float) Math.sin((angle1 + angle2) * 0.5);
tess.setNormal(nx, 0, nz);
tess.addVertex(x1, -halfThick, z1);
tess.addVertex(x2, -halfThick, z2);
tess.addVertex(x2, halfThick, z2);
tess.addVertex(x1, halfThick, z1);
}
tess.draw();
}
/**
* Render a line segment as a quad billboard facing the camera.
*/
protected void renderLineSegment(double x1, double y1, double z1,
double x2, double y2, double z2,
float width, int color, float alpha) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
// Calculate direction
double dx = x2 - x1;
double dy = y2 - y1;
double dz = z2 - z1;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len < 0.001) return;
// Perpendicular vectors for billboard
double perpX, perpY, perpZ;
if (Math.abs(dy) < 0.9) {
// Cross with up vector
perpX = -dz;
perpY = 0;
perpZ = dx;
} else {
// Cross with right vector
perpX = 0;
perpY = dz;
perpZ = -dy;
}
double perpLen = Math.sqrt(perpX * perpX + perpY * perpY + perpZ * perpZ);
if (perpLen > 0) {
perpX = perpX / perpLen * width * 0.5;
perpY = perpY / perpLen * width * 0.5;
perpZ = perpZ / perpLen * width * 0.5;
}
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.addVertex(x1 - perpX, y1 - perpY, z1 - perpZ);
tess.addVertex(x2 - perpX, y2 - perpY, z2 - perpZ);
tess.addVertex(x2 + perpX, y2 + perpY, z2 + perpZ);
tess.addVertex(x1 + perpX, y1 + perpY, z1 + perpZ);
tess.draw();
}
@Override
protected ResourceLocation getEntityTexture(Entity entity) {
return WHITE_TEXTURE;
}
}
@@ -0,0 +1,410 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityEnergyAbility;
import kamkeel.npcs.entity.EntityEnergyProjectile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.config.ConfigClient;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
/**
* Base renderer for ability projectiles.
* Provides common GL state setup and rendering utilities.
* <p>
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public abstract class RenderEnergy extends Render {
protected static final ResourceLocation WHITE_TEXTURE = new ResourceLocation("customnpcs", "textures/entity/white.png");
protected static final int HIDE_INITIAL_ACTIVE_TICKS = 1;
public RenderEnergy() {
this.shadowSize = 0.0f;
}
/**
* Hide the first active tick to avoid the visible spawn-frame pause at fire time.
* Charging previews are never hidden.
*/
protected boolean shouldSkipInitialActiveRender(Entity entity) {
if (!(entity instanceof EntityEnergyAbility)) return false;
EntityEnergyAbility ability = (EntityEnergyAbility) entity;
return !ability.isPreviewMode() && !ability.isCharging() && ability.ticksExisted <= HIDE_INITIAL_ACTIVE_TICKS;
}
/**
* Setup GL state for translucent, self-illuminated rendering.
* Forces full brightness so world lighting does not affect projectiles.
*/
protected void setupRenderState() {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glAlphaFunc(GL11.GL_GREATER, 0.003921569F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_TEXTURE_2D);
// Force full brightness - prevents world lighting from darkening projectiles
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f);
}
/**
* Restore GL state after rendering.
*/
protected void restoreRenderState() {
GL11.glPopAttrib();
GL11.glPopMatrix();
}
/**
* Extract RGB components from color int.
*/
protected float[] extractRGB(int color) {
float r = ((color >> 16) & 0xFF) / 255.0f;
float g = ((color >> 8) & 0xFF) / 255.0f;
float b = (color & 0xFF) / 255.0f;
return new float[]{r, g, b};
}
/**
* Render a cube centered at origin with given color and alpha.
*/
protected void renderCube(int color, float alpha, float halfSize) {
Tessellator tess = Tessellator.instance;
float r = ((color >> 16) & 0xFF) / 255.0f;
float g = ((color >> 8) & 0xFF) / 255.0f;
float b = (color & 0xFF) / 255.0f;
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
addCubeVertices(tess, 0, 0, 0, halfSize);
tess.draw();
}
// ==================== BATCHED CUBE RENDERING ====================
/**
* Begin a batched cube draw call. All cubes added via {@link #addBatchedCube}
* will be drawn in a single tessellator pass when {@link #endCubeBatch} is called.
*/
protected void beginCubeBatch() {
Tessellator.instance.startDrawingQuads();
}
/**
* Add a cube to the current batch at the given position with per-cube color/alpha.
* Must be called between {@link #beginCubeBatch} and {@link #endCubeBatch}.
*/
protected void addBatchedCube(float px, float py, float pz, float halfSize,
float r, float g, float b, float alpha) {
Tessellator tess = Tessellator.instance;
tess.setColorRGBA_F(r, g, b, alpha);
addCubeVertices(tess, px, py, pz, halfSize);
}
/**
* End the batched cube draw call, flushing all queued cubes in one draw.
*/
protected void endCubeBatch() {
Tessellator.instance.draw();
}
/**
* Add the 24 vertices (6 faces) of a cube centered at (px,py,pz) to the tessellator.
* Color must be set before calling. Used by both single and batched cube rendering.
*/
private static void addCubeVertices(Tessellator tess, float px, float py, float pz, float h) {
float x0 = px - h, x1 = px + h;
float y0 = py - h, y1 = py + h;
float z0 = pz - h, z1 = pz + h;
// Front (z+)
tess.setNormal(0, 0, 1);
tess.addVertex(x0, y0, z1);
tess.addVertex(x1, y0, z1);
tess.addVertex(x1, y1, z1);
tess.addVertex(x0, y1, z1);
// Back (z-)
tess.setNormal(0, 0, -1);
tess.addVertex(x1, y0, z0);
tess.addVertex(x0, y0, z0);
tess.addVertex(x0, y1, z0);
tess.addVertex(x1, y1, z0);
// Top (y+)
tess.setNormal(0, 1, 0);
tess.addVertex(x0, y1, z1);
tess.addVertex(x1, y1, z1);
tess.addVertex(x1, y1, z0);
tess.addVertex(x0, y1, z0);
// Bottom (y-)
tess.setNormal(0, -1, 0);
tess.addVertex(x0, y0, z0);
tess.addVertex(x1, y0, z0);
tess.addVertex(x1, y0, z1);
tess.addVertex(x0, y0, z1);
// Right (x+)
tess.setNormal(1, 0, 0);
tess.addVertex(x1, y0, z1);
tess.addVertex(x1, y0, z0);
tess.addVertex(x1, y1, z0);
tess.addVertex(x1, y1, z1);
// Left (x-)
tess.setNormal(-1, 0, 0);
tess.addVertex(x0, y0, z0);
tess.addVertex(x0, y0, z1);
tess.addVertex(x0, y1, z1);
tess.addVertex(x0, y1, z0);
}
/**
* Render a flat disc (cylinder with very small height) centered at origin.
* The disc lies flat on the XZ plane.
*/
protected void renderDisc(int color, float alpha, float radius, float thickness, int segments) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
Tessellator tess = Tessellator.instance;
float halfThick = thickness * 0.5f;
// Top face
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 1, 0);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
tess.addVertex(0, halfThick, 0);
tess.addVertex(x1, halfThick, z1);
tess.addVertex(x2, halfThick, z2);
tess.addVertex(0, halfThick, 0);
}
tess.draw();
// Bottom face
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, -1, 0);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
tess.addVertex(0, -halfThick, 0);
tess.addVertex(x2, -halfThick, z2);
tess.addVertex(x1, -halfThick, z1);
tess.addVertex(0, -halfThick, 0);
}
tess.draw();
// Edge
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
// Normal pointing outward
float nx = (float) Math.cos((angle1 + angle2) * 0.5);
float nz = (float) Math.sin((angle1 + angle2) * 0.5);
tess.setNormal(nx, 0, nz);
tess.addVertex(x1, -halfThick, z1);
tess.addVertex(x2, -halfThick, z2);
tess.addVertex(x2, halfThick, z2);
tess.addVertex(x1, halfThick, z1);
}
tess.draw();
}
/**
* Render a line segment as a quad billboard facing the camera.
*/
protected void renderLineSegment(double x1, double y1, double z1,
double x2, double y2, double z2,
float width, int color, float alpha) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
// Calculate direction
double dx = x2 - x1;
double dy = y2 - y1;
double dz = z2 - z1;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len < 0.001) return;
// Perpendicular vectors for billboard
double perpX, perpY, perpZ;
if (Math.abs(dy) < 0.9) {
// Cross with up vector
perpX = -dz;
perpY = 0;
perpZ = dx;
} else {
// Cross with right vector
perpX = 0;
perpY = dz;
perpZ = -dy;
}
double perpLen = Math.sqrt(perpX * perpX + perpY * perpY + perpZ * perpZ);
if (perpLen > 0) {
perpX = perpX / perpLen * width * 0.5;
perpY = perpY / perpLen * width * 0.5;
perpZ = perpZ / perpLen * width * 0.5;
}
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.addVertex(x1 - perpX, y1 - perpY, z1 - perpZ);
tess.addVertex(x2 - perpX, y2 - perpY, z2 - perpZ);
tess.addVertex(x2 + perpX, y2 + perpY, z2 + perpZ);
tess.addVertex(x1 + perpX, y1 + perpY, z1 + perpZ);
tess.draw();
}
// ==================== SHARED LIGHTNING ====================
/**
* Get or create the lightning state for an energy entity.
* Uses the lightningState field on EntityEnergyAbility (stored as Object
* to avoid client class loading on server).
*/
protected AttachedLightningRenderer.LightningState getLightningState(EntityEnergyAbility entity) {
if (entity.lightningState == null) {
entity.lightningState = new AttachedLightningRenderer.LightningState();
}
return (AttachedLightningRenderer.LightningState) entity.lightningState;
}
/**
* Render attached lightning arcs around an energy entity.
*
* @param entity the energy entity
* @param innerScale multiplier for inner radius (e.g. 0.3f for projectiles, 0.95f for dome)
* @param baseSize the entity's current render size/scale
*/
protected void renderAttachedLightning(EntityEnergyAbility entity, float innerScale, float baseSize) {
AttachedLightningRenderer.LightningState state = getLightningState(entity);
float density = entity.getLightningDensity();
float innerRadius = innerScale * baseSize;
float radius = innerRadius + entity.getLightningRadius() * baseSize;
int outerColor = entity.getOuterColor();
int innerColor = entity.getInnerColor();
int fadeTime = entity.getLightningFadeTime();
// Barrier impact spark: briefly force brighter white crackles at the contact point.
if (entity instanceof EntityEnergyProjectile) {
int sparkTicks = ((EntityEnergyProjectile) entity).getBarrierSparkTicks();
if (sparkTicks > 0) {
density = Math.max(density, 4.0f + sparkTicks * 0.6f);
radius = Math.max(radius, innerRadius + Math.max(0.35f, baseSize * 0.65f));
outerColor = 0xF0F6FF;
innerColor = 0xFFFFFF;
fadeTime = Math.max(fadeTime, 6);
}
}
state.update(density, radius, outerColor, innerColor, fadeTime);
state.render();
}
// ==================== PROXIMITY ALPHA ====================
/**
* Calculate a proximity-based alpha multiplier for owner's energy projectiles.
* Returns a factor between ProximityAlphaMin and 1.0 based on:
* - Distance from camera (close = faded, far = full)
* - Entity age (young = faded, old = full; ignored while charging)
* <p>
* Only applies to the owning player's client. Non-owners always get 1.0.
*
* @param entity the energy projectile entity
* @param x camera-relative X (from doRender)
* @param y camera-relative Y (from doRender)
* @param z camera-relative Z (from doRender)
* @return alpha multiplier between ProximityAlphaMin and 1.0
*/
protected float getProximityAlphaFactor(EntityEnergyAbility entity, double x, double y, double z) {
return getProximityAlphaFactor(entity, x, y, z, false);
}
/**
* Overload that allows forcing proximity-only fade (no age fade-out).
* Used for attached beams and lasers that stay connected to the owner.
*
* @param alwaysUseProximity if true, age factor is ignored (proximity fade never expires)
*/
protected float getProximityAlphaFactor(EntityEnergyAbility entity, double x, double y, double z, boolean alwaysUseProximity) {
float minAlpha = ConfigClient.ProximityAlphaMin;
if (minAlpha >= 1.0f) return 1.0f;
// Only apply to the owner's client
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
if (player == null || entity.getOwnerEntityId() != player.getEntityId()) {
return 1.0f;
}
// Distance factor: ramp from minAlpha at 0 to 1.0 at maxDist
float maxDist = ConfigClient.ProximityAlphaDistance;
float dist = (float) Math.sqrt(x * x + y * y + z * z);
float distFactor = Math.min(1.0f, dist / maxDist);
// Age factor: ramp from 0 to 1.0 over ageTicks
// Charging, attached beams/lasers, and alwaysUseProximity skip age fade
float ageFactor;
if (entity.isCharging() || alwaysUseProximity) {
ageFactor = 0.0f; // Always apply full proximity fade
} else {
int ageTicks = ConfigClient.ProximityAlphaAgeTicks;
if (ageTicks <= 0) {
ageFactor = 1.0f; // Age fade disabled
} else {
ageFactor = Math.min(1.0f, (float) entity.ticksExisted / ageTicks);
}
}
// Combined: take the max of both factors (either being far OR being old restores alpha)
float combinedFactor = Math.max(distFactor, ageFactor);
// Lerp between minAlpha and 1.0
return minAlpha + (1.0f - minAlpha) * combinedFactor;
}
@Override
protected ResourceLocation getEntityTexture(Entity entity) {
return WHITE_TEXTURE;
}
}
@@ -0,0 +1,23 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityEnergyBarrier;
/**
* Intermediate renderer base for energy barrier entities (Dome, Panel).
* Provides shared hit flash alpha computation.
*/
@SideOnly(Side.CLIENT)
public abstract class RenderEnergyBarrier extends RenderEnergy {
/**
* Compute the alpha boost from a hit flash effect.
* Flash value decays from 4 to 0, producing alpha from 0.3 to 0.
*/
protected float computeFlashAlpha(EntityEnergyBarrier barrier) {
byte flash = barrier.getHitFlash();
if (flash <= 0) return 0.0f;
return flash / 4.0f * 0.3f;
}
}
@@ -2,9 +2,9 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityBeam;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.util.Vec3;
import org.lwjgl.opengl.GL11;
@@ -15,26 +15,32 @@ import java.util.List;
/**
* Renders the AbilityBeam entity with a head, tail orb, and curving trail.
* The trail shows the path the head has traveled using laser-style rectangular segments.
*
* <p>
* IMPORTANT: Trail points are stored RELATIVE to the origin position.
* We render by translating to the origin first, then drawing all points relative to that.
*
* <p>
* Trail segments now share vertices at connection points to prevent gaps during curves.
*
* <p>
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityBeam extends RenderAbilityProjectile {
public class RenderEnergyBeam extends RenderEnergy {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityAbilityBeam beam = (EntityAbilityBeam) entity;
setupRenderState();
// Proximity alpha fade for owner (attached beams always use proximity, never age out)
float proximityAlpha = getProximityAlphaFactor(beam, x, y, z, beam.isAttachedToOwner());
// Handle charging state (windup phase) - render only growing orb
if (beam.isCharging()) {
renderChargingOrb(beam, x, y, z, partialTicks);
renderChargingOrb(beam, x, y, z, partialTicks, proximityAlpha);
restoreRenderState();
return;
}
@@ -46,24 +52,25 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
return;
}
// Get interpolated head offset
// Get interpolated head offset (for head/trail rendering relative to origin)
double headOffsetX = beam.getInterpolatedHeadOffsetX(partialTicks);
double headOffsetY = beam.getInterpolatedHeadOffsetY(partialTicks);
double headOffsetZ = beam.getInterpolatedHeadOffsetZ(partialTicks);
// The render system passes x,y,z as the position to render the entity at
// Entity position = origin + headOffset (in world coords)
// So origin render position = x,y,z - headOffset
double renderOriginX = x - headOffsetX;
double renderOriginY = y - headOffsetY;
double renderOriginZ = z - headOffsetZ;
// Compute render origin directly from the world origin and camera position.
// We can't derive it from MC's x,y,z because syncPositionStateToCurrent() snaps
// lastTickPos = posX on every sync packet, killing MC's position interpolation.
// The headOffset interpolation then mismatches, causing the origin to wobble.
double renderOriginX = beam.getOriginX() - RenderManager.renderPosX;
double renderOriginY = beam.getOriginY() - RenderManager.renderPosY;
double renderOriginZ = beam.getOriginZ() - RenderManager.renderPosZ;
// Get beam properties
float beamWidth = beam.getBeamWidth();
float headSize = beam.getHeadSize();
// Get beam properties (lerp-smoothed for smooth size transitions)
float beamWidth = beam.getInterpolatedBeamWidth(partialTicks);
float headSize = beam.getInterpolatedHeadSize(partialTicks);
int innerColor = beam.getInnerColor();
int outerColor = beam.getOuterColor();
float outerAlpha = beam.getOuterColorAlpha();
float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha;
// Render everything relative to origin position
GL11.glPushMatrix();
@@ -72,21 +79,24 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Calculate head distance from origin (for overlap check)
double headDistFromOrigin = Math.sqrt(headOffsetX * headOffsetX + headOffsetY * headOffsetY + headOffsetZ * headOffsetZ);
// Render tail orb at origin (0,0,0) - only in anchored mode
// Don't render if head is too close to origin (would cause overlap/extra orb appearance)
if (beam.shouldRenderTailOrb() && headDistFromOrigin > headSize * 0.5) {
renderTailOrb(headSize * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha);
float innerAlpha = beam.getInnerAlpha() * proximityAlpha;
// Render trail segments first (with fading for non-anchored)
if (beam.hasFadingTrail()) {
renderFadingTrail(beam, trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha);
} else {
renderSmoothTrail(trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha);
}
// Render trail segments with smooth connections (with fading for non-anchored)
if (beam.hasFadingTrail()) {
renderFadingTrail(beam, trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth());
} else {
renderSmoothTrail(trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth());
// Render tail orb at origin (0,0,0) AFTER trail so it draws on top
// Don't render if head is too close to origin (would cause overlap/extra orb appearance)
// Use target headSize (not lerped) so the threshold isn't inflated by lerp lag
if (beam.shouldRenderTailOrb() && headDistFromOrigin > beam.getHeadSize() * 0.5) {
renderTailOrb(beam.getHeadSize() * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha, innerAlpha);
}
// Render head at interpolated offset position
renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, partialTicks);
renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, innerAlpha, partialTicks);
GL11.glPopMatrix();
@@ -97,8 +107,8 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Render the charging orb during windup phase.
* Grows from 0 to headSize based on charge progress.
*/
private void renderChargingOrb(EntityAbilityBeam beam, double x, double y, double z, float partialTicks) {
float headSize = beam.getHeadSize();
private void renderChargingOrb(EntityAbilityBeam beam, double x, double y, double z, float partialTicks, float proximityAlpha) {
float headSize = beam.getInterpolatedHeadSize(partialTicks);
float chargeProgress = beam.getInterpolatedChargeProgress(partialTicks);
float size = headSize * chargeProgress;
@@ -117,7 +127,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render lightning during charging if enabled
if (beam.hasLightningEffect()) {
renderAttachedLightning(beam, scale);
renderAttachedLightning(beam, 0.6f * 0.5f, scale);
}
GL11.glPushMatrix();
@@ -129,7 +139,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render outer glow only if enabled
if (beam.isOuterColorEnabled()) {
float outerScale = innerScale + beam.getOuterColorWidth();
float outerAlpha = beam.getOuterColorAlpha();
float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha;
GL11.glDepthMask(false);
GL11.glPushMatrix();
GL11.glScalef(outerScale, outerScale, outerScale);
@@ -140,7 +150,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render inner core
GL11.glScalef(innerScale, innerScale, innerScale);
renderCube(innerColor, 1.0f, 0.5f);
renderCube(innerColor, beam.getInnerAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -150,7 +160,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Render the tail orb at the origin (where the beam emanates from).
* This orb does not rotate - it's a stable anchor point.
*/
private void renderTailOrb(float size, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth, float outerAlpha) {
private void renderTailOrb(float size, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth, float outerAlpha, float innerAlpha) {
GL11.glPushMatrix();
// Already at origin (0,0,0)
@@ -172,7 +182,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render inner core (solid)
GL11.glPushMatrix();
GL11.glScalef(size * innerScale, size * innerScale, size * innerScale);
renderCube(innerColor, 1.0f, 0.5f);
renderCube(innerColor, innerAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -183,7 +193,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Uses averaged perpendicular vectors at connection points to prevent gaps.
*/
private void renderSmoothTrail(List<Vec3> trail, float width, int innerColor, int outerColor,
boolean outerColorEnabled, float outerColorWidth) {
boolean outerColorEnabled, float outerColorWidth, float innerAlpha) {
if (trail.size() < 2) return;
int trailSize = trail.size();
@@ -206,7 +216,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
}
// Render inner core trail
renderTrailTube(trail, perpFrames, innerWidth, innerColor, 0.9f, false);
renderTrailTube(trail, perpFrames, innerWidth, innerColor, innerAlpha, false);
}
/**
@@ -214,7 +224,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Older trail points fade out based on their age.
*/
private void renderFadingTrail(EntityAbilityBeam beam, List<Vec3> trail, float width, int innerColor, int outerColor,
boolean outerColorEnabled, float outerColorWidth) {
boolean outerColorEnabled, float outerColorWidth, float innerAlpha) {
if (trail.size() < 2) return;
List<Integer> ages = beam.getTrailPointAges();
@@ -236,14 +246,14 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
}
// Render inner core trail with fading
renderFadingTrailTube(trail, perpFrames, ages, fadeTime, innerWidth, innerColor, 0.9f);
renderFadingTrailTube(trail, perpFrames, ages, fadeTime, innerWidth, innerColor, innerAlpha);
}
/**
* Render trail tube with age-based fading.
*/
private void renderFadingTrailTube(List<Vec3> trail, List<double[]> perpFrames, List<Integer> ages,
int fadeTime, float width, int color, float baseAlpha) {
int fadeTime, float width, int color, float baseAlpha) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
float halfWidth = width * 0.5f;
@@ -261,8 +271,8 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Calculate alpha based on age (older = more faded)
float age1 = i < ages.size() ? ages.get(i) : 0;
float age2 = (i + 1) < ages.size() ? ages.get(i + 1) : 0;
float fade1 = 1.0f - Math.min(1.0f, age1 / fadeTime);
float fade2 = 1.0f - Math.min(1.0f, age2 / fadeTime);
float fade1 = fadeTime > 0 ? (1.0f - Math.min(1.0f, age1 / fadeTime)) : 0.0f;
float fade2 = fadeTime > 0 ? (1.0f - Math.min(1.0f, age2 / fadeTime)) : 0.0f;
float alpha1 = baseAlpha * fade1;
float alpha2 = baseAlpha * fade2;
@@ -393,13 +403,17 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
dy /= len;
dz /= len;
} else {
dx = 0; dy = 0; dz = 1;
dx = 0;
dy = 0;
dz = 1;
}
// Calculate perpendicular vectors using consistent up reference
double upX = 0, upY = 1, upZ = 0;
if (Math.abs(dy) > 0.9) {
upX = 1; upY = 0; upZ = 0;
upX = 1;
upY = 0;
upZ = 0;
}
// Cross product for horizontal perpendicular
@@ -418,8 +432,12 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
double vertY = dz * horzX - dx * horzZ;
double vertZ = dx * horzY - dy * horzX;
frame[0] = horzX; frame[1] = horzY; frame[2] = horzZ;
frame[3] = vertX; frame[4] = vertY; frame[5] = vertZ;
frame[0] = horzX;
frame[1] = horzY;
frame[2] = horzZ;
frame[3] = vertX;
frame[4] = vertY;
frame[5] = vertZ;
frames.add(frame);
}
@@ -430,7 +448,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Render the trail as a continuous tube using pre-computed perpendicular frames.
*/
private void renderTrailTube(List<Vec3> trail, List<double[]> perpFrames,
float width, int color, float baseAlpha, boolean fadeFromStart) {
float width, int color, float baseAlpha, boolean fadeFromStart) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
float halfWidth = width * 0.5f;
@@ -534,7 +552,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Coordinates are relative to origin.
*/
private void renderHead(EntityAbilityBeam beam, double x, double y, double z,
float size, int innerColor, int outerColor, float outerAlpha, float partialTicks) {
float size, int innerColor, int outerColor, float outerAlpha, float innerAlpha, float partialTicks) {
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
@@ -545,7 +563,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render lightning BEFORE rotation so it crackles in all directions (only on head)
if (beam.hasLightningEffect()) {
renderAttachedLightning(beam, scale);
renderAttachedLightning(beam, 0.6f * 0.5f, scale);
}
// Rotation
@@ -573,37 +591,10 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render inner core
GL11.glScalef(innerScale, innerScale, innerScale);
renderCube(innerColor, 1.0f, 0.5f);
renderCube(innerColor, innerAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
}
/**
* Render fading lightning arcs attached to the beam head (in local space).
*/
private void renderAttachedLightning(EntityAbilityBeam beam, float headScale) {
AttachedLightningRenderer.LightningState state = getLightningState(beam);
float density = beam.getLightningDensity();
// Lightning radius extends outward from inner surface (innerScale = 0.6)
float innerRadius = 0.6f * headScale * 0.5f;
float radius = innerRadius + beam.getLightningRadius() * headScale;
int outerColor = beam.getOuterColor();
int innerColor = beam.getInnerColor();
int fadeTime = beam.getLightningFadeTime();
state.update(density, radius, outerColor, innerColor, fadeTime);
state.render();
}
/**
* Get or create the lightning state for an entity.
*/
private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityBeam beam) {
if (beam.lightningState == null) {
beam.lightningState = new AttachedLightningRenderer.LightningState();
}
return (AttachedLightningRenderer.LightningState) beam.lightningState;
}
}
@@ -2,22 +2,26 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityDisc;
import net.minecraft.entity.Entity;
import net.minecraft.util.Vec3;
import noppes.npcs.util.MathUtil;
import org.lwjgl.opengl.GL11;
/**
* Renders the AbilityDisc entity as a flat spinning square.
* Rotates only on Y axis (flat spin like a saw blade).
*
* <p>
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityDisc extends RenderAbilityProjectile {
public class RenderEnergyDisc extends RenderEnergy {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityAbilityDisc disc = (EntityAbilityDisc) entity;
setupRenderState();
@@ -27,8 +31,8 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
// Get interpolated values
float size = disc.getInterpolatedSize(partialTicks);
float radius = disc.getDiscRadius() * size;
float thickness = disc.getDiscThickness() * size;
float radius = disc.getInterpolatedDiscRadius(partialTicks) * size;
float thickness = disc.getInterpolatedDiscThickness(partialTicks) * size;
// Subtle pulsing effect
float pulseTime = entity.ticksExisted + partialTicks;
@@ -37,7 +41,7 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
// Render lightning BEFORE rotation so it crackles in all directions
if (disc.hasLightningEffect()) {
renderAttachedLightning(disc, radius * scale);
renderAttachedLightning(disc, 0.6f * 0.5f, radius * scale);
}
GL11.glPushMatrix();
@@ -52,23 +56,41 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
}
double motionX = entity.motionX;
double motionY = entity.motionY;
double motionZ = entity.motionZ;
double speedSq = motionX * motionX + motionY * motionY + motionZ * motionZ;
// Only apply motion-based facing when speed is meaningful.
// Near-zero motion makes atan2 unstable, producing jittery angles.
if (speedSq > 0.0001) {
Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ);
float motionYaw = MathUtil.getYaw(motionVec);
float motionPitch = MathUtil.getPitch(motionVec);
GL11.glRotatef(motionYaw, 0, 1, 0);
GL11.glRotatef(motionPitch, 1, 0, 0);
}
// Apply Y-axis rotation for spin
GL11.glRotatef(disc.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f);
// Inner scale defines the core size
float innerScale = 0.6f;
// Proximity alpha fade for owner
float proximityAlpha = getProximityAlphaFactor(disc, x, y, z);
// Render outer square (translucent) - only if enabled
// outerColorWidth is an additive offset from inner size
if (disc.isOuterColorEnabled()) {
float outerScale = innerScale + disc.getOuterColorWidth();
GL11.glDepthMask(false);
renderFlatSquare(disc.getOuterColor(), disc.getOuterColorAlpha(), radius * outerScale, thickness);
renderFlatSquare(disc.getOuterColor(), disc.getOuterColorAlpha() * proximityAlpha, radius * outerScale, thickness);
GL11.glDepthMask(true);
}
// Render inner square (solid)
renderFlatSquare(disc.getInnerColor(), 1.0f, radius * innerScale, thickness * 1.2f);
renderFlatSquare(disc.getInnerColor(), disc.getInnerAlpha() * proximityAlpha, radius * innerScale, thickness * 1.2f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -76,34 +98,6 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
restoreRenderState();
}
/**
* Render fading lightning arcs attached to the disc (in local space).
*/
private void renderAttachedLightning(EntityAbilityDisc disc, float discSize) {
AttachedLightningRenderer.LightningState state = getLightningState(disc);
float density = disc.getLightningDensity();
// Lightning radius extends outward from inner surface (innerScale = 0.6)
float innerRadius = 0.6f * discSize * 0.5f;
float radius = innerRadius + disc.getLightningRadius() * discSize;
int outerColor = disc.getOuterColor();
int innerColor = disc.getInnerColor();
int fadeTime = disc.getLightningFadeTime();
state.update(density, radius, outerColor, innerColor, fadeTime);
state.render();
}
/**
* Get or create the lightning state for an entity.
*/
private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityDisc disc) {
if (disc.lightningState == null) {
disc.lightningState = new AttachedLightningRenderer.LightningState();
}
return (AttachedLightningRenderer.LightningState) disc.lightningState;
}
/**
* Render a flat square (thin cube) centered at origin.
* The square lies flat on the XZ plane with thin Y height.
@@ -0,0 +1,111 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityEnergyDome;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import org.lwjgl.opengl.GL11;
/**
* Renders the Dome entity as a translucent sphere.
* Inner layer solid, outer layer translucent glow.
*/
@SideOnly(Side.CLIENT)
public class RenderEnergyDome extends RenderEnergyBarrier {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityEnergyDome dome = (EntityEnergyDome) entity;
float radius = dome.getDomeRadius();
float healthPercent = dome.getHealthPercent();
setupRenderState();
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
// Lightning BEFORE any rotation (uniform spread)
if (dome.hasLightningEffect()) {
renderAttachedLightning(dome, 0.95f, radius);
}
// Hit flash effect
float flashAlpha = computeFlashAlpha(dome);
float innerScale = 1.0f;
// Render outer dome (translucent glow)
if (dome.isOuterColorEnabled()) {
float outerScale = 1.0f + dome.getOuterColorWidth() * 0.1f;
float outerAlpha = dome.getOuterColorAlpha() * healthPercent;
GL11.glDepthMask(false);
renderSphere(dome.getOuterColor(), outerAlpha + (dome.getOuterColorAlpha() > 0 ? flashAlpha : 0), radius * outerScale, 8);
}
GL11.glDepthMask(true);
// Render inner dome (depth write enabled so inner sphere properly occludes)
renderSphere(dome.getInnerColor(), dome.getInnerAlpha() * healthPercent, radius * innerScale, 8);
GL11.glPopMatrix();
restoreRenderState();
}
/**
* Render a sphere made of quad panels.
* Uses latitude/longitude segments to form a full sphere.
*/
private void renderSphere(int color, float alpha, float radius, int segments) {
float[] rgb = extractRGB(color);
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
tess.setColorRGBA_F(rgb[0], rgb[1], rgb[2], alpha);
for (int lat = 0; lat < segments; lat++) {
float theta1 = (float) (Math.PI * lat / segments - Math.PI * 0.5);
float theta2 = (float) (Math.PI * (lat + 1) / segments - Math.PI * 0.5);
float y1 = (float) Math.sin(theta1) * radius;
float y2 = (float) Math.sin(theta2) * radius;
float r1 = (float) Math.cos(theta1) * radius;
float r2 = (float) Math.cos(theta2) * radius;
for (int lon = 0; lon < segments; lon++) {
float phi1 = (float) (2 * Math.PI * lon / segments);
float phi2 = (float) (2 * Math.PI * (lon + 1) / segments);
float x1 = (float) Math.cos(phi1) * r1;
float z1 = (float) Math.sin(phi1) * r1;
float x2 = (float) Math.cos(phi2) * r1;
float z2 = (float) Math.sin(phi2) * r1;
float x3 = (float) Math.cos(phi2) * r2;
float z3 = (float) Math.sin(phi2) * r2;
float x4 = (float) Math.cos(phi1) * r2;
float z4 = (float) Math.sin(phi1) * r2;
float nx = (x1 + x2 + x3 + x4) * 0.25f;
float ny = (y1 + y1 + y2 + y2) * 0.25f;
float nz = (z1 + z2 + z3 + z4) * 0.25f;
float nLen = (float) Math.sqrt(nx * nx + ny * ny + nz * nz);
if (nLen > 0) {
nx /= nLen;
ny /= nLen;
nz /= nLen;
}
tess.setNormal(nx, ny, nz);
tess.addVertex(x1, y1, z1);
tess.addVertex(x2, y1, z2);
tess.addVertex(x3, y2, z3);
tess.addVertex(x4, y2, z4);
}
}
tess.draw();
}
}
@@ -0,0 +1,211 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityEnergyExplosion;
import net.minecraft.entity.Entity;
import noppes.npcs.config.ConfigClient;
import org.lwjgl.opengl.GL11;
/**
* Voxel-style renderer for {@link EntityEnergyExplosion}.
* Draws expanding cubic shells with a short fade-out.
* Uses batched cube rendering for performance — all cubes of each layer
* are drawn in a single tessellator pass instead of per-cube draw calls.
*/
@SideOnly(Side.CLIENT)
public class RenderEnergyExplosion extends RenderEnergy {
private static final float MAX_OUTER_ALPHA = 0.85f;
private static final float MAX_INNER_ALPHA = 1.0f;
private static final float MAX_SMOKE_CUBE_ALPHA = 0.55f;
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) return;
if (!(entity instanceof EntityEnergyExplosion)) return;
if (ConfigClient.LowResExplosion) return;
EntityEnergyExplosion explosion = (EntityEnergyExplosion) entity;
setupRenderState();
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
float radius = explosion.getInterpolatedRadius(partialTicks);
float life = explosion.getLifeProgress(partialTicks);
if (radius > 0.01f && life < 1.0f) {
renderVoxelBurst(explosion, radius, life);
if (explosion.hasLightningEffect()) {
renderAttachedLightning(explosion, 0.55f, Math.max(0.7f, radius * 0.45f));
}
}
GL11.glPopMatrix();
restoreRenderState();
}
private void renderVoxelBurst(EntityEnergyExplosion explosion, float radius, float life) {
int outerColor = explosion.getOuterColor();
int innerColor = explosion.getInnerColor();
boolean hasOuter = explosion.isOuterColorEnabled();
float fade = 1.0f - life;
float outerAlpha = Math.min(MAX_OUTER_ALPHA, (0.25f + fade * 0.75f) * explosion.getOuterColorAlpha());
float innerAlpha = Math.min(MAX_INNER_ALPHA, (0.30f + fade * 0.80f) * explosion.getInnerAlpha());
int steps = Math.max(2, Math.min(6, (int) Math.ceil(radius * 0.65f) + 1));
float cell = radius / steps;
float cubeHalf = Math.max(0.04f, cell * 0.22f * (0.90f - life * 0.25f));
float outerScale = hasOuter ? 1.0f + explosion.getOuterColorWidth() * 0.35f : 1.0f;
long seed = explosion.getRenderSeed();
// Pre-extract RGB for batched rendering
float outerR = ((outerColor >> 16) & 0xFF) / 255.0f;
float outerG = ((outerColor >> 8) & 0xFF) / 255.0f;
float outerB = (outerColor & 0xFF) / 255.0f;
float innerR = ((innerColor >> 16) & 0xFF) / 255.0f;
float innerG = ((innerColor >> 8) & 0xFF) / 255.0f;
float innerB = (innerColor & 0xFF) / 255.0f;
GL11.glDepthMask(false);
// Smoke layer — single batched pass
renderSmokeVoxelShell(radius, life, seed);
// Outer color layer — single batched pass
if (hasOuter) {
float outerHalf = cubeHalf * outerScale;
float oa = outerAlpha * fade;
beginCubeBatch();
for (int ix = -steps; ix <= steps; ix++) {
for (int iy = -steps; iy <= steps; iy++) {
for (int iz = -steps; iz <= steps; iz++) {
int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz)));
if (edge != steps) continue;
if (!shouldRenderVoxel(ix, iy, iz, steps, seed, life)) continue;
float px = ix * cell + jitter(ix, iy, iz, seed, 1) * cell * 0.18f;
float py = iy * cell + jitter(ix, iy, iz, seed, 2) * cell * 0.18f;
float pz = iz * cell + jitter(ix, iy, iz, seed, 3) * cell * 0.18f;
addBatchedCube(px, py, pz, outerHalf, outerR, outerG, outerB, oa);
}
}
}
endCubeBatch();
}
// Inner color layer — single batched pass
{
float innerHalf = cubeHalf * 0.9f;
float ia = innerAlpha * fade;
beginCubeBatch();
for (int ix = -steps; ix <= steps; ix++) {
for (int iy = -steps; iy <= steps; iy++) {
for (int iz = -steps; iz <= steps; iz++) {
int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz)));
if (edge != steps) continue;
if (!shouldRenderVoxel(ix, iy, iz, steps, seed, life)) continue;
float px = ix * cell + jitter(ix, iy, iz, seed, 1) * cell * 0.18f;
float py = iy * cell + jitter(ix, iy, iz, seed, 2) * cell * 0.18f;
float pz = iz * cell + jitter(ix, iy, iz, seed, 3) * cell * 0.18f;
addBatchedCube(px, py, pz, innerHalf, innerR, innerG, innerB, ia);
}
}
}
endCubeBatch();
}
renderCoreFlash(innerColor, innerAlpha, radius, cubeHalf, life);
GL11.glDepthMask(true);
}
/**
* Adds large translucent white/gray cubes to fake a smoky volumetric expansion.
* All smoke cubes are batched into a single draw call.
*/
private void renderSmokeVoxelShell(float radius, float life, long seed) {
int smokeSteps = Math.max(2, Math.min(5, (int) Math.ceil(radius * 0.5f) + 1));
float smokeCell = radius / smokeSteps * 1.2f;
float smokeJitter = smokeCell * 0.28f;
float smokeCubeHalf = Math.max(0.07f, smokeCell * 0.24f * (0.95f - life * 0.25f));
float smokeAlpha = Math.min(MAX_SMOKE_CUBE_ALPHA, (0.15f + (1.0f - life) * 0.55f));
// White = 1,1,1 Gray (0xDCDCDC) = 0.863,0.863,0.863
beginCubeBatch();
for (int ix = -smokeSteps; ix <= smokeSteps; ix++) {
for (int iy = -smokeSteps; iy <= smokeSteps; iy++) {
for (int iz = -smokeSteps; iz <= smokeSteps; iz++) {
int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz)));
if (edge < smokeSteps - 1) continue;
int h = hash(ix * 5, iy * 7, iz * 11, seed ^ 0x4f1bbcdcL);
if ((h & 3) != 0) continue;
if (life > 0.72f && ((h >>> 5) & 7) > 2) continue;
float px = ix * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 1) * smokeJitter;
float py = iy * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 2) * smokeJitter;
float pz = iz * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 3) * smokeJitter;
boolean isWhite = ((h >>> 9) & 1) == 0;
float gray = isWhite ? 1.0f : 0.863f;
float alpha = smokeAlpha * (0.78f + (((h >>> 10) & 15) / 15.0f) * 0.22f);
addBatchedCube(px, py, pz, smokeCubeHalf, gray, gray, gray, alpha);
}
}
}
endCubeBatch();
}
/**
* White-hot core flash pass for the initial frames.
*/
private void renderCoreFlash(int innerColor, float innerAlpha, float radius, float cubeHalf, float life) {
float flash = saturate((0.60f - life) / 0.60f);
if (flash <= 0.0f) return;
float coreHalf = Math.max(cubeHalf, radius * 0.07f) * (1.0f + flash * 0.55f);
float whiteAlpha = Math.min(1.0f, 0.25f + flash * 0.95f);
float innerFlashAlpha = Math.min(1.0f, innerAlpha * (0.45f + flash * 0.95f));
renderCube(0xFFFFFF, whiteAlpha, coreHalf * 1.45f);
renderCube(innerColor, innerFlashAlpha, coreHalf * 0.82f);
}
private float saturate(float value) {
if (value < 0.0f) return 0.0f;
if (value > 1.0f) return 1.0f;
return value;
}
private boolean shouldRenderVoxel(int ix, int iy, int iz, int steps, long seed, float life) {
int h = hash(ix, iy, iz, seed);
int keepMask = steps >= 5 ? 3 : 1;
if ((h & keepMask) != 0) return false;
if (life > 0.55f) {
int decay = (h >>> 3) & 7;
if (decay > 2) return false;
}
return true;
}
private float jitter(int ix, int iy, int iz, long seed, int channel) {
int h = hash(ix + channel * 17, iy - channel * 31, iz + channel * 47, seed);
return (((h >>> 8) & 1023) / 1023.0f) - 0.5f;
}
private int hash(int x, int y, int z, long seed) {
long h = seed;
h ^= (long) x * 73428767L;
h ^= (long) y * 912931L;
h ^= (long) z * 19349663L;
h ^= (h >>> 33);
h *= 0xff51afd7ed558ccdL;
h ^= (h >>> 33);
return (int) h;
}
}
@@ -3,19 +3,23 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityLaser;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import org.lwjgl.opengl.GL11;
import java.util.HashMap;
import java.util.Map;
/**
* Renders the AbilityLaser entity as a rectangular beam with clear inner/outer colors.
*
* <p>
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityLaser extends RenderAbilityProjectile {
public class RenderEnergyLaser extends RenderEnergy {
private final Map<Integer, AttachedLightningRenderer.LightningState> tipLightningStates = new HashMap<>();
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
@@ -23,21 +27,24 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
setupRenderState();
// Proximity alpha fade for owner (lasers are always attached, never age out)
float proximityAlpha = getProximityAlphaFactor(laser, x, y, z, true);
if (laser.isCharging()) {
renderChargingOrb(laser, x, y, z, partialTicks);
renderChargingOrb(laser, x, y, z, partialTicks, proximityAlpha);
restoreRenderState();
return;
}
// Get laser parameters
double startX = laser.getStartX();
double startY = laser.getStartY();
double startZ = laser.getStartZ();
double endX = laser.getEndX();
double endY = laser.getEndY();
double endZ = laser.getEndZ();
float width = laser.getLaserWidth();
float alpha = laser.getLingerAlpha();
// Get interpolated laser positions for smooth rendering between ticks
double startX = laser.getInterpolatedStartX(partialTicks);
double startY = laser.getInterpolatedStartY(partialTicks);
double startZ = laser.getInterpolatedStartZ(partialTicks);
double endX = laser.getInterpolatedEndX(partialTicks);
double endY = laser.getInterpolatedEndY(partialTicks);
double endZ = laser.getInterpolatedEndZ(partialTicks);
float width = laser.getInterpolatedLaserWidth(partialTicks);
float alpha = 1.0f;
// Calculate render offset (entity position is used as reference)
double offsetX = x - laser.posX;
@@ -70,7 +77,9 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Calculate perpendicular vectors (one horizontal, one vertical relative to beam)
double upX = 0, upY = 1, upZ = 0;
if (Math.abs(dy) > 0.9) {
upX = 1; upY = 0; upZ = 0;
upX = 1;
upY = 0;
upZ = 0;
}
// Cross product for horizontal perpendicular
@@ -89,6 +98,25 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
double vertY = dz * horzX - dx * horzZ;
double vertZ = dx * horzY - dy * horzX;
// Rotate perpendicular vectors around beam axis (Rodrigues' rotation)
float rotationSpeed = laser.getRotationSpeed();
if (rotationSpeed != 0.0f) {
double angle = (laser.ticksExisted + partialTicks) * rotationSpeed * Math.PI / 180.0;
double cosA = Math.cos(angle);
double sinA = Math.sin(angle);
double rHorzX = horzX * cosA + vertX * sinA;
double rHorzY = horzY * cosA + vertY * sinA;
double rHorzZ = horzZ * cosA + vertZ * sinA;
double rVertX = -horzX * sinA + vertX * cosA;
double rVertY = -horzY * sinA + vertY * cosA;
double rVertZ = -horzZ * sinA + vertZ * cosA;
horzX = rHorzX; horzY = rHorzY; horzZ = rHorzZ;
vertX = rVertX; vertY = rVertY; vertZ = rVertZ;
}
// Inner scale defines the core width
float innerScale = 0.6f;
float innerWidth = width * innerScale;
@@ -99,36 +127,36 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
float outerWidth = innerWidth + laser.getOuterColorWidth() * width;
GL11.glDepthMask(false);
renderBeamRectangle(renderStartX, renderStartY, renderStartZ,
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
outerWidth, laser.getOuterColor(), alpha * 0.4f);
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
outerWidth, laser.getOuterColor(), alpha * 0.4f * proximityAlpha);
// Render middle layer (halfway between inner and outer)
float midWidth = innerWidth + (outerWidth - innerWidth) * 0.5f;
renderBeamRectangle(renderStartX, renderStartY, renderStartZ,
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
midWidth, laser.getOuterColor(), alpha * 0.7f);
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
midWidth, laser.getOuterColor(), alpha * 0.7f * proximityAlpha);
GL11.glDepthMask(true);
}
// Render inner core (solid)
renderBeamRectangle(renderStartX, renderStartY, renderStartZ,
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
innerWidth, laser.getInnerColor(), alpha);
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
innerWidth, laser.getInnerColor(), alpha * laser.getInnerAlpha() * proximityAlpha);
// Render lightning along the laser beam
if (laser.hasLightningEffect() && laser.getCurrentLength() > 0.1f) {
renderLaserLightning(laser, renderStartX, renderStartY, renderStartZ,
renderEndX, renderEndY, renderEndZ, width);
renderEndX, renderEndY, renderEndZ, width);
}
restoreRenderState();
}
private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks) {
float headSize = laser.getLaserWidth() * 1.5f;
private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks, float proximityAlpha) {
float headSize = laser.getInterpolatedLaserWidth(partialTicks) * 0.5f;
float chargeProgress = laser.getInterpolatedChargeProgress(partialTicks);
float size = headSize * chargeProgress;
@@ -147,7 +175,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Render lightning during charging if enabled
if (laser.hasLightningEffect()) {
renderAttachedLightning(laser, scale);
renderAttachedLightning(laser, 0.6f * 0.5f, scale);
}
GL11.glPushMatrix();
@@ -159,7 +187,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Render outer glow only if enabled
if (laser.isOuterColorEnabled()) {
float outerScale = innerScale + laser.getOuterColorWidth();
float outerAlpha = laser.getOuterColorAlpha();
float outerAlpha = laser.getOuterColorAlpha() * proximityAlpha;
GL11.glDepthMask(false);
GL11.glPushMatrix();
GL11.glScalef(outerScale, outerScale, outerScale);
@@ -170,7 +198,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Render inner core
GL11.glScalef(innerScale, innerScale, innerScale);
renderCube(innerColor, 1.0f, 0.5f);
renderCube(innerColor, laser.getInnerAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -180,8 +208,8 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
* Render lightning effects along the laser beam at multiple points.
*/
private void renderLaserLightning(EntityAbilityLaser laser,
double startX, double startY, double startZ,
double endX, double endY, double endZ, float width) {
double startX, double startY, double startZ,
double endX, double endY, double endZ, float width) {
AttachedLightningRenderer.LightningState state = getLightningState(laser);
float density = laser.getLightningDensity();
@@ -215,50 +243,28 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
}
private void renderAttachedLightning(EntityAbilityLaser laser, float headScale) {
AttachedLightningRenderer.LightningState state = getLightningState(laser);
float density = laser.getLightningDensity();
// Lightning radius extends outward from inner surface (innerScale = 0.6)
float innerRadius = 0.6f * headScale * 0.5f;
float radius = innerRadius + laser.getLightningRadius() * headScale;
int outerColor = laser.getOuterColor();
int innerColor = laser.getInnerColor();
int fadeTime = laser.getLightningFadeTime();
state.update(density, radius, outerColor, innerColor, fadeTime);
state.render();
}
/**
* Get or create the main lightning state for the laser.
*/
private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityLaser laser) {
if (laser.lightningState == null) {
laser.lightningState = new AttachedLightningRenderer.LightningState();
}
return (AttachedLightningRenderer.LightningState) laser.lightningState;
}
/**
* Get or create the tip lightning state for the laser.
* Stored as a secondary object in lightningState2.
* Persisted per entity ID so arcs accumulate and fade properly across frames.
*/
private AttachedLightningRenderer.LightningState getTipLightningState(EntityAbilityLaser laser) {
// Use a simple approach - store in a transient field
// Since lightningState is already used, we'll create a new state each time
// This works because we're updating and rendering immediately
return new AttachedLightningRenderer.LightningState();
int id = laser.getEntityId();
AttachedLightningRenderer.LightningState state = tipLightningStates.get(id);
if (state == null) {
state = new AttachedLightningRenderer.LightningState();
tipLightningStates.put(id, state);
}
return state;
}
/**
* Render a beam as a 3D rectangular prism (box along a line).
*/
private void renderBeamRectangle(double x1, double y1, double z1,
double x2, double y2, double z2,
double horzX, double horzY, double horzZ,
double vertX, double vertY, double vertZ,
float width, int color, float alpha) {
double x2, double y2, double z2,
double horzX, double horzY, double horzZ,
double vertX, double vertY, double vertZ,
float width, int color, float alpha) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
@@ -2,9 +2,10 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityOrb;
import net.minecraft.entity.Entity;
import net.minecraft.util.Vec3;
import noppes.npcs.util.MathUtil;
import org.lwjgl.opengl.GL11;
/**
@@ -12,7 +13,7 @@ import org.lwjgl.opengl.GL11;
* Minecraft-style blocky appearance using Tessellator.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityOrb extends RenderAbilityProjectile {
public class RenderEnergyOrb extends RenderEnergy {
private static final int LIGHTNING_FADE_TICKS = 6;
@@ -20,6 +21,10 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
EntityAbilityOrb orb = (EntityAbilityOrb) entity;
if (shouldSkipInitialActiveRender(entity)) {
return;
}
setupRenderState();
GL11.glPushMatrix();
@@ -35,7 +40,22 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
// Render lightning BEFORE rotation so it crackles in all directions
if (orb.hasLightningEffect()) {
renderAttachedLightning(orb, scale);
renderAttachedLightning(orb, 0.6f * 0.5f, scale);
}
double motionX = entity.motionX;
double motionY = entity.motionY;
double motionZ = entity.motionZ;
double speedSq = motionX * motionX + motionY * motionY + motionZ * motionZ;
// Only apply motion-based facing when speed is meaningful.
// Near-zero motion makes atan2 unstable, producing jittery angles.
if (speedSq > 0.0001) {
Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ);
float motionYaw = MathUtil.getYaw(motionVec);
float motionPitch = MathUtil.getPitch(motionVec);
GL11.glRotatef(motionYaw, 0, 1, 0);
GL11.glRotatef(motionPitch, 1, 0, 0);
}
// Use entity's interpolated rotation for smooth spinning
@@ -49,6 +69,9 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
// Inner scale defines the core size
float innerScale = 0.6f;
// Proximity alpha fade for owner
float proximityAlpha = getProximityAlphaFactor(orb, x, y, z);
// Render outer cube (translucent) - only if enabled
// outerColorWidth is an additive offset from inner size
if (orb.isOuterColorEnabled()) {
@@ -56,14 +79,14 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
GL11.glDepthMask(false);
GL11.glPushMatrix();
GL11.glScalef(outerScale, outerScale, outerScale);
renderCube(orb.getOuterColor(), orb.getOuterColorAlpha(), 0.5f);
renderCube(orb.getOuterColor(), orb.getOuterColorAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glDepthMask(true);
}
// Render inner cube (solid)
GL11.glScalef(innerScale, innerScale, innerScale);
renderCube(orb.getInnerColor(), 1.0f, 0.5f);
renderCube(orb.getInnerColor(), orb.getInnerAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -71,36 +94,4 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
restoreRenderState();
}
/**
* Render fading lightning arcs attached to the orb (in local space).
* Arcs persist for a few ticks and fade out, while staying attached to the orb.
*/
private void renderAttachedLightning(EntityAbilityOrb orb, float orbScale) {
// Get or create the lightning state for this entity
AttachedLightningRenderer.LightningState state = getLightningState(orb);
float density = orb.getLightningDensity();
// Lightning radius extends outward from inner surface (innerScale = 0.6)
float innerRadius = 0.6f * orbScale * 0.5f; // Half size of inner cube
float radius = innerRadius + orb.getLightningRadius() * orbScale;
int outerColor = orb.getOuterColor();
int innerColor = orb.getInnerColor();
int fadeTime = orb.getLightningFadeTime();
// Update: age existing arcs, spawn new ones based on density
state.update(density, radius, outerColor, innerColor, fadeTime);
// Render all active arcs in local space (they move with the orb)
state.render();
}
/**
* Get or create the lightning state for an entity.
*/
private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityOrb orb) {
if (orb.lightningState == null) {
orb.lightningState = new AttachedLightningRenderer.LightningState();
}
return (AttachedLightningRenderer.LightningState) orb.lightningState;
}
}
@@ -0,0 +1,143 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityEnergyPanel;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import org.lwjgl.opengl.GL11;
/**
* Renders the Energy Panel entity as a flat translucent rectangle.
* Used by both Energy Wall and Energy Shield abilities.
* Voxel-blocky style with inner/outer layers.
*/
@SideOnly(Side.CLIENT)
public class RenderEnergyPanel extends RenderEnergyBarrier {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityEnergyPanel panel = (EntityEnergyPanel) entity;
float width = panel.getPanelData().panelWidth;
float height = panel.getPanelData().panelHeight;
float healthPercent = panel.getHealthPercent();
// Interpolate panel yaw for smooth rotation between ticks
float prevYaw = panel.getPrevPanelYaw();
float currentYaw = panel.getPanelYaw();
float yawDelta = currentYaw - prevYaw;
// Wrap angle delta to -180..180 for shortest rotation path
while (yawDelta > 180.0f) yawDelta -= 360.0f;
while (yawDelta < -180.0f) yawDelta += 360.0f;
float renderYaw = prevYaw + yawDelta * partialTicks;
setupRenderState();
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
// Lightning BEFORE rotation for uniform spread (like Orb pattern)
if (panel.hasLightningEffect()) {
renderAttachedLightning(panel, 0.9f, Math.max(width, height) * 0.5f);
}
// Rotate panel to face the correct direction (interpolated)
GL11.glRotatef(-renderYaw, 0.0f, 1.0f, 0.0f);
// Hit flash
float flashAlpha = computeFlashAlpha(panel);
// Subtle pulsing
float pulseTime = entity.ticksExisted + partialTicks;
float pulse = (float) Math.sin(pulseTime * 0.08f) * 0.02f;
float scale = 1.0f + pulse;
GL11.glPushMatrix();
GL11.glScalef(scale, scale, scale);
float innerScale = 1.0f;
float panelThickness = 0.1f;
// Render outer panel (translucent glow)
if (panel.isOuterColorEnabled()) {
float outerScale = 1.0f + panel.getOuterColorWidth() * 0.15f;
float outerAlpha = panel.getOuterColorAlpha() * healthPercent;
GL11.glDepthMask(false);
renderPanel(panel.getOuterColor(), outerAlpha + (panel.getOuterColorAlpha() > 0 ? flashAlpha : 0),
width * 0.5f * outerScale, height * 0.5f * outerScale, panelThickness * 1.5f);
GL11.glDepthMask(true);
}
// Render inner panel (uses configurable innerAlpha for semi-transparency)
renderPanel(panel.getInnerColor(), panel.getInnerAlpha(),
width * 0.5f * innerScale, height * 0.5f * innerScale, panelThickness);
GL11.glPopMatrix();
GL11.glPopMatrix();
restoreRenderState();
}
/**
* Render a flat panel (thin box) centered at origin.
* Panel faces along the Z axis (width on X, height on Y).
* All 6 faces batched into a single draw call.
*/
private void renderPanel(int color, float alpha, float halfWidth, float halfHeight, float halfThickness) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
// Front face (z+)
tess.setNormal(0, 0, 1);
tess.addVertex(-halfWidth, -halfHeight, halfThickness);
tess.addVertex(halfWidth, -halfHeight, halfThickness);
tess.addVertex(halfWidth, halfHeight, halfThickness);
tess.addVertex(-halfWidth, halfHeight, halfThickness);
// Back face (z-)
tess.setNormal(0, 0, -1);
tess.addVertex(halfWidth, -halfHeight, -halfThickness);
tess.addVertex(-halfWidth, -halfHeight, -halfThickness);
tess.addVertex(-halfWidth, halfHeight, -halfThickness);
tess.addVertex(halfWidth, halfHeight, -halfThickness);
// Top edge (y+)
tess.setNormal(0, 1, 0);
tess.addVertex(-halfWidth, halfHeight, halfThickness);
tess.addVertex(halfWidth, halfHeight, halfThickness);
tess.addVertex(halfWidth, halfHeight, -halfThickness);
tess.addVertex(-halfWidth, halfHeight, -halfThickness);
// Bottom edge (y-)
tess.setNormal(0, -1, 0);
tess.addVertex(-halfWidth, -halfHeight, -halfThickness);
tess.addVertex(halfWidth, -halfHeight, -halfThickness);
tess.addVertex(halfWidth, -halfHeight, halfThickness);
tess.addVertex(-halfWidth, -halfHeight, halfThickness);
// Right edge (x+)
tess.setNormal(1, 0, 0);
tess.addVertex(halfWidth, -halfHeight, halfThickness);
tess.addVertex(halfWidth, -halfHeight, -halfThickness);
tess.addVertex(halfWidth, halfHeight, -halfThickness);
tess.addVertex(halfWidth, halfHeight, halfThickness);
// Left edge (x-)
tess.setNormal(-1, 0, 0);
tess.addVertex(-halfWidth, -halfHeight, -halfThickness);
tess.addVertex(-halfWidth, -halfHeight, halfThickness);
tess.addVertex(-halfWidth, halfHeight, halfThickness);
tess.addVertex(-halfWidth, halfHeight, -halfThickness);
tess.draw();
}
}
@@ -0,0 +1,131 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityEnergySlicer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import org.lwjgl.opengl.GL11;
/**
* Renders the Energy Slicer entity as a thin wide blade.
* Oriented perpendicular to travel direction.
* Inner solid core with outer translucent glow.
*/
@SideOnly(Side.CLIENT)
public class RenderEnergySlicer extends RenderEnergy {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityEnergySlicer slicer = (EntityEnergySlicer) entity;
float width = slicer.getSliceWidth();
float thickness = slicer.getSliceThickness();
// During charging, width/thickness grow from 0.01 to target via updateCharging().
// Use current dimensions directly - no separate sizeRatio needed.
if (width <= 0.01f) return;
setupRenderState();
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
// Lightning BEFORE rotation for uniform spread (like Orb pattern)
if (slicer.hasLightningEffect()) {
renderAttachedLightning(slicer, 0.7f, width * 0.5f);
}
// Orient perpendicular to travel direction
float travelYaw = slicer.getTravelYaw();
float travelPitch = slicer.getTravelPitch();
GL11.glRotatef(travelYaw, 0.0f, 1.0f, 0.0f);
GL11.glRotatef(travelPitch, 1.0f, 0.0f, 0.0f);
float innerScale = 0.7f;
// Proximity alpha fade for owner
float proximityAlpha = getProximityAlphaFactor(slicer, x, y, z);
// Render outer blade (translucent glow)
if (slicer.isOuterColorEnabled()) {
float outerScale = 1.0f + slicer.getOuterColorWidth() * 0.2f;
GL11.glDepthMask(false);
renderBlade(slicer.getOuterColor(), slicer.getOuterColorAlpha() * proximityAlpha,
width * 0.5f * outerScale, thickness * 2.0f, 0.05f);
GL11.glDepthMask(true);
}
// Render inner blade (solid core)
renderBlade(slicer.getInnerColor(), slicer.getInnerAlpha() * proximityAlpha,
width * 0.5f * innerScale, thickness, 0.03f);
GL11.glPopMatrix();
restoreRenderState();
}
/**
* Render a thin wide blade shape.
* The blade extends along X (width), thin on Y (thickness), and very thin on Z (depth).
* All 6 faces batched into a single draw call.
*/
private void renderBlade(int color, float alpha, float halfWidth, float halfHeight, float halfDepth) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
// Front face (z+)
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 0, 1);
tess.addVertex(-halfWidth, -halfHeight, halfDepth);
tess.addVertex(halfWidth, -halfHeight, halfDepth);
tess.addVertex(halfWidth, halfHeight, halfDepth);
tess.addVertex(-halfWidth, halfHeight, halfDepth);
// Back face (z-)
tess.setNormal(0, 0, -1);
tess.addVertex(halfWidth, -halfHeight, -halfDepth);
tess.addVertex(-halfWidth, -halfHeight, -halfDepth);
tess.addVertex(-halfWidth, halfHeight, -halfDepth);
tess.addVertex(halfWidth, halfHeight, -halfDepth);
// Top edge (y+)
tess.setColorRGBA_F(r, g, b, alpha * 0.8f);
tess.setNormal(0, 1, 0);
tess.addVertex(-halfWidth, halfHeight, halfDepth);
tess.addVertex(halfWidth, halfHeight, halfDepth);
tess.addVertex(halfWidth, halfHeight, -halfDepth);
tess.addVertex(-halfWidth, halfHeight, -halfDepth);
// Bottom edge (y-)
tess.setNormal(0, -1, 0);
tess.addVertex(-halfWidth, -halfHeight, -halfDepth);
tess.addVertex(halfWidth, -halfHeight, -halfDepth);
tess.addVertex(halfWidth, -halfHeight, halfDepth);
tess.addVertex(-halfWidth, -halfHeight, halfDepth);
// Right edge (x+)
tess.setColorRGBA_F(r, g, b, alpha * 0.6f);
tess.setNormal(1, 0, 0);
tess.addVertex(halfWidth, -halfHeight, halfDepth);
tess.addVertex(halfWidth, -halfHeight, -halfDepth);
tess.addVertex(halfWidth, halfHeight, -halfDepth);
tess.addVertex(halfWidth, halfHeight, halfDepth);
// Left edge (x-)
tess.setNormal(-1, 0, 0);
tess.addVertex(-halfWidth, -halfHeight, -halfDepth);
tess.addVertex(-halfWidth, -halfHeight, halfDepth);
tess.addVertex(-halfWidth, halfHeight, halfDepth);
tess.addVertex(-halfWidth, halfHeight, -halfDepth);
tess.draw();
}
}
@@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import kamkeel.npcs.entity.EntityEnergySweeper;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
@@ -15,16 +15,17 @@ import org.lwjgl.opengl.GL11;
* Uses similar rendering style to the Beam trail for visual consistency.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilitySweeper extends Render {
public class RenderSweeper extends Render {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
EntityAbilitySweeper sweeper = (EntityAbilitySweeper) entity;
EntityEnergySweeper sweeper = (EntityEnergySweeper) entity;
setupRenderState();
float beamLength = sweeper.getBeamLength();
float beamWidth = sweeper.getBeamWidth();
float beamHeight = sweeper.getBeamHeight();
int innerColor = sweeper.getInnerColor();
int outerColor = sweeper.getOuterColor();
boolean outerColorEnabled = sweeper.isOuterColorEnabled();
@@ -38,7 +39,7 @@ public class RenderAbilitySweeper extends Render {
GL11.glRotatef(-angle, 0, 1, 0); // Negative for correct direction
// Render the beam extending in the +Z direction (like beam trail segments)
renderBeam(beamLength, beamWidth, innerColor, outerColor, outerColorEnabled, outerColorWidth);
renderBeam(beamLength, beamWidth, beamHeight, innerColor, outerColor, outerColorEnabled, outerColorWidth);
GL11.glPopMatrix();
@@ -70,8 +71,10 @@ public class RenderAbilitySweeper extends Render {
/**
* Render beam using the same style as the Beam entity trail.
* Three layers: outer glow, middle, inner core.
* outerColorWidth is an additive offset from inner width (consistent with other renderers).
* Width and height control the rectangular cross-section independently.
*/
private void renderBeam(float length, float width, int innerColor, int outerColor,
private void renderBeam(float length, float width, float height, int innerColor, int outerColor,
boolean outerColorEnabled, float outerColorWidth) {
// Extract colors
float outerR = ((outerColor >> 16) & 0xFF) / 255.0f;
@@ -82,30 +85,40 @@ public class RenderAbilitySweeper extends Render {
float innerG = ((innerColor >> 8) & 0xFF) / 255.0f;
float innerB = (innerColor & 0xFF) / 255.0f;
// Inner scale defines the core size (consistent with other renderers)
float innerScale = 0.6f;
float innerWidth = width * innerScale;
float innerHeight = height * innerScale;
// Render from origin (0,0,0) to (0,0,length) in local coords
// After rotation this extends in the correct world direction
// Outer glow (wider, translucent) - like beam trail - only if enabled
// Outer glow (wider, translucent) - only if enabled
// outerColorWidth is additive offset from inner size
if (outerColorEnabled) {
float outerWidth = innerWidth + outerColorWidth * width;
float outerHeight = innerHeight + outerColorWidth * height;
GL11.glDepthMask(false);
renderBeamSegment(0, 0, 0, 0, 0, length, width * outerColorWidth, outerR, outerG, outerB, 0.3f);
renderBeamSegment(0, 0, 0, 0, 0, length, outerWidth, outerHeight, outerR, outerG, outerB, 0.3f);
GL11.glDepthMask(true);
// Middle layer
renderBeamSegment(0, 0, 0, 0, 0, length, width * 1.3f, outerR, outerG, outerB, 0.6f);
// Middle layer (halfway between inner and outer)
float midWidth = innerWidth + (outerWidth - innerWidth) * 0.5f;
float midHeight = innerHeight + (outerHeight - innerHeight) * 0.5f;
renderBeamSegment(0, 0, 0, 0, 0, length, midWidth, midHeight, outerR, outerG, outerB, 0.6f);
}
// Inner core (solid) - like beam trail inner
renderBeamSegment(0, 0, 0, 0, 0, length, width * 0.6f, innerR, innerG, innerB, 1.0f);
// Inner core (solid)
renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerHeight, innerR, innerG, innerB, 1.0f);
}
/**
* Render a beam segment as a 3D rectangular prism.
* Uses the same approach as RenderAbilityBeam.renderBeamRectangle.
* Render a beam segment as a 3D rectangular prism with independent width and height.
* Uses the same approach as RenderEnergyBeam.renderBeamRectangle.
*/
private void renderBeamSegment(double x1, double y1, double z1,
double x2, double y2, double z2,
float width, float r, float g, float b, float a) {
double x2, double y2, double z2,
float width, float height, float r, float g, float b, float a) {
// Calculate direction
double dx = x2 - x1;
double dy = y2 - y1;
@@ -121,7 +134,9 @@ public class RenderAbilitySweeper extends Render {
// Calculate perpendicular vectors
double upX = 0, upY = 1, upZ = 0;
if (Math.abs(dy) > 0.9) {
upX = 1; upY = 0; upZ = 0;
upX = 1;
upY = 0;
upZ = 0;
}
// Cross product for horizontal perpendicular
@@ -141,39 +156,40 @@ public class RenderAbilitySweeper extends Render {
double vertZ = dx * horzY - dy * horzX;
float halfWidth = width * 0.5f;
float halfHeight = height * 0.5f;
// Calculate 8 corners of the box
double s1x = x1 - horzX * halfWidth - vertX * halfWidth;
double s1y = y1 - horzY * halfWidth - vertY * halfWidth;
double s1z = z1 - horzZ * halfWidth - vertZ * halfWidth;
// Calculate 8 corners of the box (horz scaled by halfWidth, vert scaled by halfHeight)
double s1x = x1 - horzX * halfWidth - vertX * halfHeight;
double s1y = y1 - horzY * halfWidth - vertY * halfHeight;
double s1z = z1 - horzZ * halfWidth - vertZ * halfHeight;
double s2x = x1 + horzX * halfWidth - vertX * halfWidth;
double s2y = y1 + horzY * halfWidth - vertY * halfWidth;
double s2z = z1 + horzZ * halfWidth - vertZ * halfWidth;
double s2x = x1 + horzX * halfWidth - vertX * halfHeight;
double s2y = y1 + horzY * halfWidth - vertY * halfHeight;
double s2z = z1 + horzZ * halfWidth - vertZ * halfHeight;
double s3x = x1 + horzX * halfWidth + vertX * halfWidth;
double s3y = y1 + horzY * halfWidth + vertY * halfWidth;
double s3z = z1 + horzZ * halfWidth + vertZ * halfWidth;
double s3x = x1 + horzX * halfWidth + vertX * halfHeight;
double s3y = y1 + horzY * halfWidth + vertY * halfHeight;
double s3z = z1 + horzZ * halfWidth + vertZ * halfHeight;
double s4x = x1 - horzX * halfWidth + vertX * halfWidth;
double s4y = y1 - horzY * halfWidth + vertY * halfWidth;
double s4z = z1 - horzZ * halfWidth + vertZ * halfWidth;
double s4x = x1 - horzX * halfWidth + vertX * halfHeight;
double s4y = y1 - horzY * halfWidth + vertY * halfHeight;
double s4z = z1 - horzZ * halfWidth + vertZ * halfHeight;
double e1x = x2 - horzX * halfWidth - vertX * halfWidth;
double e1y = y2 - horzY * halfWidth - vertY * halfWidth;
double e1z = z2 - horzZ * halfWidth - vertZ * halfWidth;
double e1x = x2 - horzX * halfWidth - vertX * halfHeight;
double e1y = y2 - horzY * halfWidth - vertY * halfHeight;
double e1z = z2 - horzZ * halfWidth - vertZ * halfHeight;
double e2x = x2 + horzX * halfWidth - vertX * halfWidth;
double e2y = y2 + horzY * halfWidth - vertY * halfWidth;
double e2z = z2 + horzZ * halfWidth - vertZ * halfWidth;
double e2x = x2 + horzX * halfWidth - vertX * halfHeight;
double e2y = y2 + horzY * halfWidth - vertY * halfHeight;
double e2z = z2 + horzZ * halfWidth - vertZ * halfHeight;
double e3x = x2 + horzX * halfWidth + vertX * halfWidth;
double e3y = y2 + horzY * halfWidth + vertY * halfWidth;
double e3z = z2 + horzZ * halfWidth + vertZ * halfWidth;
double e3x = x2 + horzX * halfWidth + vertX * halfHeight;
double e3y = y2 + horzY * halfWidth + vertY * halfHeight;
double e3z = z2 + horzZ * halfWidth + vertZ * halfHeight;
double e4x = x2 - horzX * halfWidth + vertX * halfWidth;
double e4y = y2 - horzY * halfWidth + vertY * halfWidth;
double e4z = z2 - horzZ * halfWidth + vertZ * halfWidth;
double e4x = x2 - horzX * halfWidth + vertX * halfHeight;
double e4y = y2 - horzY * halfWidth + vertY * halfHeight;
double e4z = z2 - horzZ * halfWidth + vertZ * halfHeight;
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
@@ -0,0 +1,797 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityZone;
import kamkeel.npcs.entity.EntityAbilityZone.AccentStyle;
import kamkeel.npcs.entity.EntityAbilityZone.ParticleMotion;
import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape;
import kamkeel.npcs.entity.EntityAbilityZone.ZoneType;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.fx.CustomFX;
import noppes.npcs.client.fx.ZoneParticleFX;
import org.lwjgl.opengl.GL11;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
@SideOnly(Side.CLIENT)
public class RenderZone extends Render {
private static final int CIRCLE_SEGMENTS = 32;
private static final int ACCENT_LINE_COUNT = 12;
private static final Random RANDOM = new Random();
private final Map<Integer, Integer> lastParticleTick = new HashMap<>();
private final Map<Integer, AttachedLightningRenderer.LightningState> lightningStates = new HashMap<>();
private static final int TRIGGER_REVEAL_TICKS = 10;
private static class Ctx {
EntityAbilityZone zone;
ZoneShape shape;
float radius, height;
float ir, ig, ib;
float outerR, outerG, outerB;
boolean outerEnabled;
float time, pulse, rotation, brightness;
boolean flash, newTick;
float particleDensity, particleScale, animSpeed, lightningDensity;
boolean groundFill, rings, border, accents, lightning, particles;
float groundAlpha, borderSpeed;
int ringCount, accentStyle, particleMotion, particleSize;
boolean particleGlow;
String particleDir;
boolean trapVisible;
boolean triggerReveal;
float revealFade;
}
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
EntityAbilityZone zone = (EntityAbilityZone) entity;
Ctx c = new Ctx();
c.zone = zone;
c.shape = zone.getShape();
c.radius = zone.getRadius();
c.height = zone.getZoneHeight();
int inner = zone.getInnerColor();
c.ir = ((inner >> 16) & 0xFF) / 255.0f;
c.ig = ((inner >> 8) & 0xFF) / 255.0f;
c.ib = (inner & 0xFF) / 255.0f;
int outer = zone.getOuterColor();
c.outerR = ((outer >> 16) & 0xFF) / 255.0f;
c.outerG = ((outer >> 8) & 0xFF) / 255.0f;
c.outerB = (outer & 0xFF) / 255.0f;
c.outerEnabled = zone.isOuterColorEnabled();
c.particleDensity = zone.getParticleDensity();
c.particleScale = zone.getParticleScale();
c.animSpeed = zone.getAnimSpeed();
c.lightningDensity = zone.getLightningDensity();
c.groundFill = zone.isGroundFill();
c.groundAlpha = zone.getGroundAlpha();
c.rings = zone.isRings();
c.ringCount = zone.getRingCount();
c.border = zone.isBorder();
c.borderSpeed = zone.getBorderSpeed();
c.accents = zone.isAccents();
c.accentStyle = zone.getAccentStyle();
c.lightning = zone.isLightning();
c.particles = zone.isParticles();
c.particleMotion = zone.getParticleMotion();
c.particleDir = zone.getParticleDir();
c.particleSize = zone.getParticleSize();
c.particleGlow = zone.isParticleGlow();
c.time = zone.ticksExisted + partialTicks;
c.pulse = c.time * 0.1f * c.animSpeed;
c.rotation = c.time * 1.5f * c.animSpeed;
c.brightness = 1.0f;
c.trapVisible = true;
c.triggerReveal = false;
c.revealFade = 0.0f;
if (zone.getZoneType() == ZoneType.TRAP) {
c.trapVisible = zone.isVisible();
// Trigger reveal: 10-tick full visual burst that fades out
if (zone.getTriggerFlashTick() >= 0) {
float ticksSinceTrigger = zone.ticksExisted - zone.getTriggerFlashTick() + partialTicks;
if (ticksSinceTrigger < TRIGGER_REVEAL_TICKS) {
c.triggerReveal = true;
c.revealFade = Math.max(0.0f, 1.0f - ticksSinceTrigger / TRIGGER_REVEAL_TICKS);
}
}
// Skip render entirely if invisible and not in reveal
if (!c.trapVisible && !c.triggerReveal) {
return;
}
if (!zone.isArmed()) {
c.brightness = 0.4f;
} else {
c.pulse = c.time * 0.2f;
}
}
// White flash during first 2 ticks of reveal
c.flash = c.triggerReveal && c.revealFade > 0.8f;
c.newTick = isNewTick(zone);
setupRenderState();
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
GL11.glDepthMask(false);
renderZone(c);
GL11.glDepthMask(true);
GL11.glPopMatrix();
restoreRenderState();
}
private boolean isNewTick(EntityAbilityZone zone) {
int id = zone.getEntityId();
int tick = zone.ticksExisted;
Integer last = lastParticleTick.get(id);
if (last == null || last != tick) {
lastParticleTick.put(id, tick);
return true;
}
return false;
}
private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityZone zone) {
int id = zone.getEntityId();
AttachedLightningRenderer.LightningState state = lightningStates.get(id);
if (state == null) {
state = new AttachedLightningRenderer.LightningState();
lightningStates.put(id, state);
}
return state;
}
private void renderZone(Ctx c) {
// During trigger reveal, override visual layers for dramatic burst
if (c.triggerReveal) {
c.brightness = c.revealFade;
c.groundFill = true;
c.groundAlpha = 0.35f * c.revealFade;
c.rings = true;
c.ringCount = 3;
c.accents = true;
c.accentStyle = 2; // FLICKERING
c.border = true;
}
float rR = ringR(c), rG = ringG(c), rB = ringB(c);
if (c.groundFill) {
if (c.flash) {
renderShapeFill(c.shape, c.radius, 1, 1, 1, 0.5f);
} else {
renderShapeFill(c.shape, c.radius,
c.ir, c.ig, c.ib, c.groundAlpha * c.brightness);
}
}
if (c.rings) {
int count = Math.max(1, Math.min(5, c.ringCount));
for (int i = 0; i < count; i++) {
float frac = (i + 1.0f) / (count + 1);
float ra = (0.4f + 0.3f * sin(c.pulse + i * Math.PI / 3)) * c.brightness;
float yOff = 0.02f + i * 0.01f;
renderRingLine(c.shape, c.radius * frac,
rR, rG, rB, ra, yOff);
}
float edgeA = (0.5f + 0.4f * sin(c.pulse + count * Math.PI / 3)) * c.brightness;
renderRingLine(c.shape, c.radius, rR, rG, rB, edgeA, 0.02f + count * 0.01f);
}
if (c.border) {
renderRotatingBorder(c.shape, c.radius, rR, rG, rB,
0.7f * c.brightness, c.rotation * c.borderSpeed, 0.05f);
}
if (c.accents) {
float aa = 0.5f * c.brightness * (0.3f + 0.2f * sin(c.pulse * 0.7f));
AccentStyle style = AccentStyle.values()[Math.max(0, Math.min(c.accentStyle, AccentStyle.values().length - 1))];
switch (style) {
case SWAYING:
renderSwayingAccents(c, c.ir, c.ig, c.ib, aa, c.height);
break;
case FLICKERING:
renderFlickeringAccents(c, c.ir, c.ig, c.ib, aa, c.height);
break;
default:
renderVerticalAccents(c.shape, c.radius, c.ir, c.ig, c.ib, aa, c.height, c.rotation * 0.3f);
break;
}
}
if (c.lightning) {
int innerColor = c.zone.getInnerColor();
int outerColor = c.outerEnabled ? c.zone.getOuterColor() : innerColor;
AttachedLightningRenderer.LightningState state = getLightningState(c.zone);
if (c.newTick) {
state.tick();
float density = 0.4f * c.brightness * c.lightningDensity;
if (RANDOM.nextFloat() < density) {
double[] p1 = randomPosInZone(c);
double[] p2 = randomPosInZone(c);
double y1 = RANDOM.nextDouble() * c.height * 0.4;
double y2 = RANDOM.nextDouble() * c.height * 0.4;
float disp = c.radius * 0.15f;
state.addArc(AttachedLightningRenderer.createArcBetween(
p1[0], y1, p1[2], p2[0], y2, p2[2], disp, outerColor, innerColor, 6));
}
if (RANDOM.nextFloat() < density * 0.5f * c.lightningDensity) {
double[] edgePos = randomEdgePos(c);
double ex = edgePos[0];
double ez = edgePos[1];
float disp = c.radius * 0.12f;
state.addArc(AttachedLightningRenderer.createArcBetween(
ex, 0, ez, ex + (RANDOM.nextDouble() - 0.5) * 0.5,
c.height * (0.3 + RANDOM.nextDouble() * 0.4),
ez + (RANDOM.nextDouble() - 0.5) * 0.5,
disp, outerColor, innerColor, 5));
}
}
state.render();
GL11.glDepthMask(false);
}
if (c.particles && c.newTick && c.particleDensity > 0) {
if (c.particleDir != null && !c.particleDir.isEmpty()) {
if (c.particleDir.startsWith("mc:")) {
spawnVanillaParticle(c);
} else {
spawnCustomFXParticle(c);
}
} else {
spawnDefaultParticles(c);
}
}
}
private void spawnVanillaParticle(Ctx c) {
String particleName = c.particleDir.substring(3);
int count = Math.round(3 * c.particleDensity);
for (int i = 0; i < count; i++) {
double[] pos = randomPosInZone(c);
double[] motion = getMotionForStyle(c.particleMotion);
c.zone.worldObj.spawnParticle(particleName,
c.zone.posX + pos[0], c.zone.posY + pos[1], c.zone.posZ + pos[2],
motion[0], motion[1], motion[2]);
}
}
private void spawnCustomFXParticle(Ctx c) {
int count = Math.round(3 * c.particleDensity);
for (int i = 0; i < count; i++) {
double[] pos = randomPosInZone(c);
double[] motion = getMotionForStyle(c.particleMotion);
CustomFX fx = new CustomFX(c.zone.worldObj, null, c.particleDir,
c.zone.posX + pos[0], c.zone.posY + pos[1], c.zone.posZ + pos[2],
0, 0, 0);
fx.motionX = motion[0];
fx.motionY = motion[1];
fx.motionZ = motion[2];
fx.setMaxAge(20 + RANDOM.nextInt(20));
fx.width = -1;
fx.height = -1;
fx.scaleX1 = c.particleScale * 10.0f;
fx.scaleY1 = c.particleScale * 10.0f;
fx.scaleX2 = fx.scaleX1;
fx.scaleY2 = fx.scaleY1;
fx.scaleXRate = 0;
fx.scaleYRate = 0;
fx.HEXColor = c.zone.getInnerColor();
fx.facePlayer = true;
fx.glows = c.particleGlow;
fx.noClip = true;
fx.alpha1 = 0.8f;
fx.alpha2 = 0.0f;
fx.alphaRate = -0.04f;
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
}
}
private void spawnDefaultParticles(Ctx c) {
int count = Math.round(3 * c.particleDensity);
ParticleMotion motion = ParticleMotion.values()[Math.max(0, Math.min(c.particleMotion, ParticleMotion.values().length - 1))];
for (int i = 0; i < count; i++) {
double[] pos = randomPosInZone(c);
double mx, my, mz;
float gravity;
int age;
switch (motion) {
case DRIFTING:
mx = (RANDOM.nextDouble() - 0.5) * 0.005;
my = 0.005 + RANDOM.nextDouble() * 0.01;
mz = (RANDOM.nextDouble() - 0.5) * 0.005;
gravity = 0;
age = 40 + RANDOM.nextInt(20);
break;
case SPARKS:
mx = (RANDOM.nextDouble() - 0.5) * 0.08;
my = RANDOM.nextDouble() * 0.06;
mz = (RANDOM.nextDouble() - 0.5) * 0.08;
gravity = 0;
age = 4 + RANDOM.nextInt(6);
break;
default: // RISING
mx = (RANDOM.nextDouble() - 0.5) * 0.01;
my = 0.01 + RANDOM.nextDouble() * 0.02;
mz = (RANDOM.nextDouble() - 0.5) * 0.01;
gravity = -0.01f;
age = 30 + RANDOM.nextInt(20);
break;
}
float scale = (1.5f + RANDOM.nextFloat() * 1.0f) * c.particleScale;
spawnParticle(c.zone, pos[0], pos[1], pos[2], mx, my, mz,
c.ir, c.ig, c.ib, 0.7f, scale, age, gravity, c.particleGlow);
}
}
private double[] getMotionForStyle(int motionOrdinal) {
ParticleMotion motion = ParticleMotion.values()[Math.max(0, Math.min(motionOrdinal, ParticleMotion.values().length - 1))];
switch (motion) {
case DRIFTING:
return new double[]{
(RANDOM.nextDouble() - 0.5) * 0.005,
0.005 + RANDOM.nextDouble() * 0.01,
(RANDOM.nextDouble() - 0.5) * 0.005
};
case SPARKS:
return new double[]{
(RANDOM.nextDouble() - 0.5) * 0.08,
RANDOM.nextDouble() * 0.06,
(RANDOM.nextDouble() - 0.5) * 0.08
};
default: // RISING
return new double[]{
(RANDOM.nextDouble() - 0.5) * 0.01,
0.01 + RANDOM.nextDouble() * 0.02,
(RANDOM.nextDouble() - 0.5) * 0.01
};
}
}
private float ringR(Ctx c) {
return c.outerEnabled ? c.outerR : c.ir;
}
private float ringG(Ctx c) {
return c.outerEnabled ? c.outerG : c.ig;
}
private float ringB(Ctx c) {
return c.outerEnabled ? c.outerB : c.ib;
}
private static float sin(double v) {
return (float) Math.sin(v);
}
private void renderSwayingAccents(Ctx c, float r, float g, float b, float a, float height) {
if (height <= 0.1f) return;
float rotRad = (float) Math.toRadians(c.rotation * 0.2f);
Tessellator tess = Tessellator.instance;
if (c.shape == ZoneShape.SQUARE) {
renderSquareSwayingAccents(c, r, g, b, a, height, rotRad, tess);
} else {
for (int i = 0; i < ACCENT_LINE_COUNT; i++) {
float baseAngle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad;
double lx = Math.cos(baseAngle) * c.radius;
double lz = Math.sin(baseAngle) * c.radius;
float swayX = 0.15f * sin(c.time * 0.08f + i * 1.7f);
float swayZ = 0.15f * sin(c.time * 0.06f + i * 2.3f);
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx + swayX, height, lz + swayZ);
tess.draw();
}
}
}
private void renderSquareSwayingAccents(Ctx c, float r, float g, float b, float a, float height, float rotRad, Tessellator tess) {
int perSide = Math.max(1, ACCENT_LINE_COUNT / 4);
int idx = 0;
for (int side = 0; side < 4; side++) {
for (int j = 0; j < perSide; j++) {
float frac = (j + 0.5f) / perSide;
double lx, lz;
switch (side) {
case 0:
lx = -c.radius + frac * 2 * c.radius;
lz = -c.radius;
break;
case 1:
lx = c.radius;
lz = -c.radius + frac * 2 * c.radius;
break;
case 2:
lx = c.radius - frac * 2 * c.radius;
lz = c.radius;
break;
default:
lx = -c.radius;
lz = c.radius - frac * 2 * c.radius;
break;
}
float swayX = 0.15f * sin(c.time * 0.08f + idx * 1.7f);
float swayZ = 0.15f * sin(c.time * 0.06f + idx * 2.3f);
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx + swayX, height, lz + swayZ);
tess.draw();
idx++;
}
}
}
private void renderFlickeringAccents(Ctx c, float r, float g, float b, float baseAlpha, float height) {
if (height <= 0.1f) return;
float rotRad = (float) Math.toRadians(c.rotation * 0.4f);
Tessellator tess = Tessellator.instance;
if (c.shape == ZoneShape.SQUARE) {
renderSquareFlickeringAccents(c, r, g, b, baseAlpha, height, tess);
} else {
for (int i = 0; i < ACCENT_LINE_COUNT; i++) {
float baseAngle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad;
double lx = Math.cos(baseAngle) * c.radius;
double lz = Math.sin(baseAngle) * c.radius;
float flicker = 0.3f + 0.7f * Math.abs(sin(c.time * 0.7f + i * 3.14f));
float lineAlpha = baseAlpha * flicker;
float lineHeight = height * (0.6f + 0.4f * flicker);
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, lineAlpha);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx, lineHeight, lz);
tess.draw();
}
}
}
private void renderSquareFlickeringAccents(Ctx c, float r, float g, float b, float baseAlpha, float height, Tessellator tess) {
int perSide = Math.max(1, ACCENT_LINE_COUNT / 4);
int idx = 0;
for (int side = 0; side < 4; side++) {
for (int j = 0; j < perSide; j++) {
float frac = (j + 0.5f) / perSide;
double lx, lz;
switch (side) {
case 0:
lx = -c.radius + frac * 2 * c.radius;
lz = -c.radius;
break;
case 1:
lx = c.radius;
lz = -c.radius + frac * 2 * c.radius;
break;
case 2:
lx = c.radius - frac * 2 * c.radius;
lz = c.radius;
break;
default:
lx = -c.radius;
lz = c.radius - frac * 2 * c.radius;
break;
}
float flicker = 0.3f + 0.7f * Math.abs(sin(c.time * 0.7f + idx * 3.14f));
float lineAlpha = baseAlpha * flicker;
float lineHeight = height * (0.6f + 0.4f * flicker);
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, lineAlpha);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx, lineHeight, lz);
tess.draw();
idx++;
}
}
}
private double[] randomPosInZone(Ctx c) {
if (c.shape == ZoneShape.SQUARE) {
double px = (RANDOM.nextDouble() * 2 - 1) * c.radius;
double pz = (RANDOM.nextDouble() * 2 - 1) * c.radius;
return new double[]{px, 0, pz};
} else {
double angle = RANDOM.nextDouble() * Math.PI * 2;
double dist = Math.sqrt(RANDOM.nextDouble()) * c.radius;
double px = Math.cos(angle) * dist;
double pz = Math.sin(angle) * dist;
return new double[]{px, 0, pz};
}
}
private double[] randomEdgePos(Ctx c) {
if (c.shape == ZoneShape.SQUARE) {
int side = RANDOM.nextInt(4);
double frac = RANDOM.nextDouble() * 2 - 1;
switch (side) {
case 0:
return new double[]{frac * c.radius, -c.radius};
case 1:
return new double[]{frac * c.radius, c.radius};
case 2:
return new double[]{-c.radius, frac * c.radius};
default:
return new double[]{c.radius, frac * c.radius};
}
} else {
double angle = RANDOM.nextDouble() * Math.PI * 2;
double dist = c.radius * (0.5 + RANDOM.nextDouble() * 0.5);
return new double[]{Math.cos(angle) * dist, Math.sin(angle) * dist};
}
}
private void spawnParticle(EntityAbilityZone zone, double offsetX, double offsetY, double offsetZ,
double mx, double my, double mz,
float r, float g, float b, float alpha,
float scale, int maxAge, float gravity, boolean glow) {
ZoneParticleFX particle = new ZoneParticleFX(
zone.worldObj,
zone.posX + offsetX, zone.posY + offsetY, zone.posZ + offsetZ,
mx, my, mz, r, g, b, alpha, scale, maxAge, gravity, glow);
Minecraft.getMinecraft().effectRenderer.addEffect(particle);
}
private void setupRenderState() {
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
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.glDisable(GL11.GL_LIGHTING);
GL11.glShadeModel(GL11.GL_SMOOTH);
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f);
}
private void restoreRenderState() {
GL11.glShadeModel(GL11.GL_FLAT);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glPopAttrib();
}
private void renderShapeFill(ZoneShape shape, float radius, float r, float g, float b, float a) {
GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
GL11.glPolygonOffset(-1.0f, -1.0f);
switch (shape) {
case CIRCLE:
renderCircleFill(radius, r, g, b, a);
break;
case SQUARE:
renderSquareFill(radius, r, g, b, a);
break;
}
GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
}
private void renderCircleFill(float radius, float r, float g, float b, float a) {
Tessellator tess = Tessellator.instance;
tess.startDrawing(GL11.GL_TRIANGLE_FAN);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(0, 0, 0);
for (int i = 0; i <= CIRCLE_SEGMENTS; i++) {
double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
tess.addVertex(Math.cos(angle) * radius, 0, Math.sin(angle) * radius);
}
tess.draw();
}
private void renderSquareFill(float radius, float r, float g, float b, float a) {
Tessellator tess = Tessellator.instance;
tess.startDrawing(GL11.GL_QUADS);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(-radius, 0, -radius);
tess.addVertex(radius, 0, -radius);
tess.addVertex(radius, 0, radius);
tess.addVertex(-radius, 0, radius);
tess.draw();
}
private void renderRingLine(ZoneShape shape, float radius,
float r, float g, float b, float a, float yOffset) {
switch (shape) {
case CIRCLE:
renderCircleRingLine(radius, r, g, b, a, yOffset);
break;
case SQUARE:
renderSquareRingLine(radius, r, g, b, a, yOffset);
break;
}
}
private void renderCircleRingLine(float radius, float r, float g, float b, float a, float yOffset) {
Tessellator tess = Tessellator.instance;
tess.startDrawing(GL11.GL_LINE_LOOP);
tess.setColorRGBA_F(r, g, b, a);
for (int i = 0; i < CIRCLE_SEGMENTS; i++) {
double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
tess.addVertex(Math.cos(angle) * radius, yOffset, Math.sin(angle) * radius);
}
tess.draw();
}
private void renderSquareRingLine(float radius, float r, float g, float b, float a, float yOffset) {
Tessellator tess = Tessellator.instance;
tess.startDrawing(GL11.GL_LINE_LOOP);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(-radius, yOffset, -radius);
tess.addVertex(radius, yOffset, -radius);
tess.addVertex(radius, yOffset, radius);
tess.addVertex(-radius, yOffset, radius);
tess.draw();
}
private void renderRotatingBorder(ZoneShape shape, float radius,
float r, float g, float b, float a,
float rotationDeg, float yOffset) {
int dashCount = 16;
if (shape == ZoneShape.SQUARE) {
float perimeter = radius * 8;
float dashLen = perimeter / dashCount;
float offset = (rotationDeg % 360.0f) / 360.0f * perimeter;
Tessellator tess = Tessellator.instance;
for (int i = 0; i < dashCount; i += 2) {
float startDist = (i * dashLen + offset) % perimeter;
float endDist = startDist + dashLen;
tess.startDrawing(GL11.GL_LINE_STRIP);
tess.setColorRGBA_F(r, g, b, a);
int steps = 4;
for (int s = 0; s <= steps; s++) {
float d = startDist + (endDist - startDist) * s / steps;
double[] pos = perimeterPos(d % perimeter, radius);
tess.addVertex(pos[0], yOffset, pos[1]);
}
tess.draw();
}
} else {
float dashAngle = (float) (Math.PI * 2) / dashCount;
float rotRad = (float) Math.toRadians(rotationDeg);
Tessellator tess = Tessellator.instance;
for (int i = 0; i < dashCount; i += 2) {
float startAngle = i * dashAngle + rotRad;
float endAngle = startAngle + dashAngle;
tess.startDrawing(GL11.GL_LINE_STRIP);
tess.setColorRGBA_F(r, g, b, a);
int steps = 4;
for (int s = 0; s <= steps; s++) {
float segAngle = startAngle + (endAngle - startAngle) * s / steps;
tess.addVertex(Math.cos(segAngle) * radius, yOffset, Math.sin(segAngle) * radius);
}
tess.draw();
}
}
}
private double[] perimeterPos(float dist, float radius) {
float sideLen = radius * 2;
if (dist < sideLen) {
// Bottom edge: (-radius, -radius) to (radius, -radius)
return new double[]{-radius + dist, -radius};
}
dist -= sideLen;
if (dist < sideLen) {
// Right edge: (radius, -radius) to (radius, radius)
return new double[]{radius, -radius + dist};
}
dist -= sideLen;
if (dist < sideLen) {
// Top edge: (radius, radius) to (-radius, radius)
return new double[]{radius - dist, radius};
}
dist -= sideLen;
// Left edge: (-radius, radius) to (-radius, -radius)
return new double[]{-radius, radius - dist};
}
private void renderVerticalAccents(ZoneShape shape, float radius,
float r, float g, float b, float a,
float height, float rotationDeg) {
if (height <= 0.1f) return;
Tessellator tess = Tessellator.instance;
if (shape == ZoneShape.SQUARE) {
int perSide = Math.max(1, ACCENT_LINE_COUNT / 4);
for (int side = 0; side < 4; side++) {
for (int j = 0; j < perSide; j++) {
float frac = (j + 0.5f) / perSide;
double lx, lz;
switch (side) {
case 0:
lx = -radius + frac * 2 * radius;
lz = -radius;
break;
case 1:
lx = radius;
lz = -radius + frac * 2 * radius;
break;
case 2:
lx = radius - frac * 2 * radius;
lz = radius;
break;
default:
lx = -radius;
lz = radius - frac * 2 * radius;
break;
}
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx, height, lz);
tess.draw();
}
}
float[][] corners = {{-radius, -radius}, {radius, -radius}, {radius, radius}, {-radius, radius}};
for (float[] corner : corners) {
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(corner[0], 0.01, corner[1]);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(corner[0], height, corner[1]);
tess.draw();
}
} else {
float rotRad = (float) Math.toRadians(rotationDeg);
for (int i = 0; i < ACCENT_LINE_COUNT; i++) {
float angle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad;
double lx = Math.cos(angle) * radius;
double lz = Math.sin(angle) * radius;
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx, height, lz);
tess.draw();
}
}
}
@Override
protected ResourceLocation getEntityTexture(Entity entity) {
return null;
}
}
@@ -105,11 +105,14 @@ public class TelegraphRenderer {
renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha);
break;
case CONE:
renderCone(telegraph.getLength(), telegraph.getAngle(), red, green, blue, alpha);
renderCone(telegraph.getLength(), telegraph.getAngle(), telegraph.getInnerRadius(), red, green, blue, alpha);
break;
case POINT:
renderPoint(red, green, blue, alpha);
break;
case SQUARE:
renderSquare(telegraph.getRadius(), red, green, blue, alpha);
break;
default:
break;
}
@@ -204,42 +207,98 @@ public class TelegraphRenderer {
tessellator.draw();
}
private void renderCone(float length, float angle, float r, float g, float b, float a) {
private void renderCone(float length, float angle, float innerRadius, float r, float g, float b, float a) {
float halfAngleRad = (float) Math.toRadians(angle / 2);
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawing(GL11.GL_TRIANGLE_FAN);
tessellator.setColorRGBA_F(r, g, b, a);
// Origin point
tessellator.addVertex(0, 0, 0);
if (innerRadius <= 0) {
// Standard cone: triangle fan from origin
tessellator.startDrawing(GL11.GL_TRIANGLE_FAN);
tessellator.setColorRGBA_F(r, g, b, a);
// Arc points
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
double x = Math.sin(segmentAngle) * length;
double z = Math.cos(segmentAngle) * length;
tessellator.addVertex(x, 0, z);
tessellator.addVertex(0, 0, 0);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
double x = Math.sin(segmentAngle) * length;
double z = Math.cos(segmentAngle) * length;
tessellator.addVertex(x, 0, z);
}
tessellator.draw();
// Border
tessellator.startDrawing(GL11.GL_LINE_STRIP);
tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2));
tessellator.addVertex(0, 0.01, 0);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
double x = Math.sin(segmentAngle) * length;
double z = Math.cos(segmentAngle) * length;
tessellator.addVertex(x, 0.01, z);
}
tessellator.addVertex(0, 0.01, 0);
tessellator.draw();
} else {
// Truncated cone: strip between inner and outer arcs
tessellator.startDrawing(GL11.GL_TRIANGLE_STRIP);
tessellator.setColorRGBA_F(r, g, b, a);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
double sinA = Math.sin(segmentAngle);
double cosA = Math.cos(segmentAngle);
tessellator.addVertex(sinA * length, 0, cosA * length);
tessellator.addVertex(sinA * innerRadius, 0, cosA * innerRadius);
}
tessellator.draw();
// Border: outer arc
float borderAlpha = Math.min(1.0f, a * 2);
tessellator.startDrawing(GL11.GL_LINE_STRIP);
tessellator.setColorRGBA_F(r, g, b, borderAlpha);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
tessellator.addVertex(Math.sin(segmentAngle) * length, 0.01, Math.cos(segmentAngle) * length);
}
tessellator.draw();
// Border: inner arc
tessellator.startDrawing(GL11.GL_LINE_STRIP);
tessellator.setColorRGBA_F(r, g, b, borderAlpha);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
tessellator.addVertex(Math.sin(segmentAngle) * innerRadius, 0.01, Math.cos(segmentAngle) * innerRadius);
}
tessellator.draw();
// Border: side edges connecting inner and outer arcs
tessellator.startDrawing(GL11.GL_LINES);
tessellator.setColorRGBA_F(r, g, b, borderAlpha);
double sinStart = Math.sin(-halfAngleRad);
double cosStart = Math.cos(-halfAngleRad);
tessellator.addVertex(sinStart * innerRadius, 0.01, cosStart * innerRadius);
tessellator.addVertex(sinStart * length, 0.01, cosStart * length);
double sinEnd = Math.sin(halfAngleRad);
double cosEnd = Math.cos(halfAngleRad);
tessellator.addVertex(sinEnd * innerRadius, 0.01, cosEnd * innerRadius);
tessellator.addVertex(sinEnd * length, 0.01, cosEnd * length);
tessellator.draw();
}
tessellator.draw();
// Draw border
tessellator.startDrawing(GL11.GL_LINE_STRIP);
tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2));
tessellator.addVertex(0, 0.01, 0);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
double x = Math.sin(segmentAngle) * length;
double z = Math.cos(segmentAngle) * length;
tessellator.addVertex(x, 0.01, z);
}
tessellator.addVertex(0, 0.01, 0);
tessellator.draw();
}
private void renderPoint(float r, float g, float b, float a) {
@@ -258,6 +317,30 @@ public class TelegraphRenderer {
tessellator.draw();
}
private void renderSquare(float radius, float r, float g, float b, float a) {
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.setColorRGBA_F(r, g, b, a);
tessellator.addVertex(-radius, 0, -radius);
tessellator.addVertex(radius, 0, -radius);
tessellator.addVertex(radius, 0, radius);
tessellator.addVertex(-radius, 0, radius);
tessellator.draw();
// Draw border
tessellator.startDrawing(GL11.GL_LINE_LOOP);
tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2));
tessellator.addVertex(-radius, 0.01, -radius);
tessellator.addVertex(radius, 0.01, -radius);
tessellator.addVertex(radius, 0.01, radius);
tessellator.addVertex(-radius, 0.01, radius);
tessellator.draw();
}
// ==================== GUI PREVIEW RENDERING ====================
/**
@@ -272,8 +355,8 @@ public class TelegraphRenderer {
* @param partialTicks Partial ticks for interpolation
*/
public void renderTelegraphInGUI(TelegraphInstance instance,
double centerX, double centerY, double centerZ,
float scale, float partialTicks) {
double centerX, double centerY, double centerZ,
float scale, float partialTicks) {
if (instance == null) return;
Telegraph telegraph = instance.getTelegraph();
@@ -317,11 +400,14 @@ public class TelegraphRenderer {
renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha);
break;
case CONE:
renderCone(telegraph.getLength(), telegraph.getAngle(), red, green, blue, alpha);
renderCone(telegraph.getLength(), telegraph.getAngle(), telegraph.getInnerRadius(), red, green, blue, alpha);
break;
case POINT:
renderPoint(red, green, blue, alpha);
break;
case SQUARE:
renderSquare(telegraph.getRadius(), red, green, blue, alpha);
break;
default:
break;
}
@@ -3,7 +3,6 @@ package kamkeel.npcs.client.renderer.lightning;
import net.minecraft.client.renderer.Tessellator;
import org.lwjgl.opengl.GL11;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -37,6 +36,7 @@ public class AttachedLightningRenderer {
public float getAlphaMultiplier() {
// Fade out over lifetime
if (maxAge <= 0) return 0.0f;
return 1.0f - ((float) age / (float) maxAge);
}
@@ -85,6 +85,28 @@ public class AttachedLightningRenderer {
}
}
/**
* Age existing arcs and remove dead ones without spawning new arcs.
* Use with addArc() for custom arc generation.
*/
public void tick() {
Iterator<LightningArc> iter = arcs.iterator();
while (iter.hasNext()) {
LightningArc arc = iter.next();
arc.tick();
if (arc.isDead()) {
iter.remove();
}
}
}
/**
* Add a custom arc to the state.
*/
public void addArc(LightningArc arc) {
arcs.add(arc);
}
/**
* Render all active arcs in local space.
* Call this after glTranslated to entity position.
@@ -143,8 +165,8 @@ public class AttachedLightningRenderer {
* Generate a jagged lightning path between two points.
*/
private static List<double[]> generateLightningPath(double x1, double y1, double z1,
double x2, double y2, double z2,
int segments, float displacement) {
double x2, double y2, double z2,
int segments, float displacement) {
List<double[]> points = new ArrayList<>();
points.add(new double[]{x1, y1, z1});
@@ -186,10 +208,9 @@ public class AttachedLightningRenderer {
private static void renderBoltPath(Tessellator tess, List<double[]> points, int color, float width, float alpha) {
if (alpha <= 0.01f) return;
Color c = new Color(color);
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
int r = (color >> 16) & 0xFF;
int g = (color >> 8) & 0xFF;
int b = color & 0xFF;
int a = Math.min(255, Math.max(0, (int) (alpha * 255)));
for (int i = 0; i < points.size() - 1; i++) {
@@ -231,6 +252,17 @@ public class AttachedLightningRenderer {
}
}
/**
* Create a lightning arc between two arbitrary points.
*/
public static LightningArc createArcBetween(double x1, double y1, double z1,
double x2, double y2, double z2,
float displacement, int outerColor, int innerColor, int maxAge) {
int segments = 4 + rand.nextInt(3);
List<double[]> points = generateLightningPath(x1, y1, z1, x2, y2, z2, segments, displacement);
return new LightningArc(points, maxAge, outerColor, innerColor);
}
// ==================== INSTANT RENDERING (no persistence) ====================
/**
@@ -56,7 +56,7 @@ public class LightningBolt {
this.numSegments0 = 1;
this.length = end.copy().subtract(start).mag();
this.particleMaxAge = FADE_TIME + rand.nextInt(FADE_TIME) - FADE_TIME / 2;
this.particleMaxAge = Math.max(1, FADE_TIME + rand.nextInt(FADE_TIME) - FADE_TIME / 2);
this.particleAge = -(int) (length * speed);
segments.add(new Segment(start, end));
@@ -243,7 +243,7 @@ public class LightningBolt {
public Segment(Vec3d start, Vec3d end) {
this(new BoltPoint(start, new Vec3d(0, 0, 0)),
new BoltPoint(end, new Vec3d(0, 0, 0)), 1, 0, 0);
new BoltPoint(end, new Vec3d(0, 0, 0)), 1, 0, 0);
}
public void calcDiff() {
@@ -5,7 +5,6 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.LightningBolt.Segment;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ActiveRenderInfo;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.entity.Entity;
@@ -19,7 +18,7 @@ import java.awt.Color;
/**
* Handles rendering of lightning bolts in the world.
* Adapted from Botania's LightningHandler by Vazkii/ChickenBones.
*
* <p>
* Register this handler with: MinecraftForge.EVENT_BUS.register(new LightningHandler());
*/
@SideOnly(Side.CLIENT)
@@ -168,13 +167,13 @@ public class LightningHandler {
/**
* Spawn a lightning bolt between two points.
*
* @param world The world
* @param start Start position
* @param end End position
* @param world The world
* @param start Start position
* @param end End position
* @param ticksPerMeter Speed of bolt expansion
* @param seed Random seed for consistent appearance
* @param colorOuter Outer glow color (ARGB)
* @param colorInner Inner core color (ARGB)
* @param seed Random seed for consistent appearance
* @param colorOuter Outer glow color (ARGB)
* @param colorInner Inner core color (ARGB)
*/
public static void spawnLightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, long seed, int colorOuter, int colorInner) {
LightningBolt bolt = new LightningBolt(world, start, end, ticksPerMeter, seed, colorOuter, colorInner);
@@ -1,12 +1,14 @@
package kamkeel.npcs.command;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.ability.UserType;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import noppes.npcs.NoppesUtilServer;
import noppes.npcs.controllers.PlayerDataController;
import noppes.npcs.controllers.data.PlayerAbilityData;
import noppes.npcs.controllers.data.PlayerData;
import java.util.ArrayList;
@@ -33,20 +35,19 @@ public class AbilityCommand extends CommandKamkeelBase {
desc = "List all custom abilities"
)
public void list(ICommandSender sender, String[] args) {
Set<String> uuids = AbilityController.Instance.getCustomAbilityIds();
if (uuids.isEmpty()) {
Set<String> names = AbilityController.Instance.getCustomAbilityNames();
if (names.isEmpty()) {
sendResult(sender, "No custom abilities found.");
return;
}
sendResult(sender, "Custom Abilities (" + uuids.size() + "):");
for (String uuid : uuids) {
Ability ability = AbilityController.Instance.getCustomAbility(uuid);
sendResult(sender, "Custom Abilities (" + names.size() + "):");
for (String name : names) {
Ability ability = AbilityController.Instance.getCustomAbility(name);
if (ability != null) {
String name = ability.getName() != null ? ability.getName() : uuid;
sendResult(sender, " - \u00A7b" + name + "\u00A77 (" + ability.getTypeId() + ") [" + uuid + "]");
sendResult(sender, " - \u00A7b" + name + "\u00A77 (" + ability.getTypeId() + ")");
} else {
sendResult(sender, " - \u00A7b" + uuid);
sendResult(sender, " - \u00A7b" + name);
}
}
}
@@ -78,27 +79,27 @@ public class AbilityCommand extends CommandKamkeelBase {
)
public void reload(ICommandSender sender, String[] args) {
AbilityController.Instance.load();
sendResult(sender, "Abilities reloaded from disk.");
sendResult(sender, "Abilities and chained abilities reloaded from disk.");
}
@SubCommand(
desc = "Delete a custom ability by UUID",
usage = "<uuid>"
desc = "Delete a custom ability by name",
usage = "<name>"
)
public void delete(ICommandSender sender, String[] args) {
if (args.length < 1) {
sendError(sender, "Usage: /kam ability delete <uuid>");
sendError(sender, "Usage: /kam ability delete <name>");
return;
}
String uuid = args[0];
if (!AbilityController.Instance.hasCustomAbility(uuid)) {
sendError(sender, "No custom ability with UUID: " + uuid);
String name = joinArgs(args, 0);
if (!AbilityController.Instance.hasCustomAbilityName(name)) {
sendError(sender, "No custom ability with name: " + name);
return;
}
AbilityController.Instance.deleteCustomAbility(uuid);
sendResult(sender, "Deleted ability: \u00A7b" + uuid);
AbilityController.Instance.deleteCustomAbility(name);
sendResult(sender, "Deleted ability: \u00A7b" + name);
}
@SubCommand(
@@ -111,14 +112,15 @@ public class AbilityCommand extends CommandKamkeelBase {
return;
}
String key = args[0];
String key = joinArgs(args, 0);
Ability ability = AbilityController.Instance.resolveAbility(key);
if (ability == null) {
sendError(sender, "No ability found for: " + key);
return;
}
sendResult(sender, "Ability: \u00A7b" + ability.getName());
sendResult(sender, "Ability: \u00A7b" + ability.getDisplayName());
sendResult(sender, " Name: \u00A77" + ability.getName());
sendResult(sender, " Type: \u00A7d" + ability.getTypeId());
sendResult(sender, " Cooldown: \u00A7e" + ability.getCooldownTicks() + " ticks");
sendResult(sender, " Wind Up: \u00A7e" + ability.getWindUpTicks() + " ticks");
@@ -163,26 +165,24 @@ public class AbilityCommand extends CommandKamkeelBase {
}
@SubCommand(
desc = "Unlock an ability for a player",
desc = "Give an ability to a player",
usage = "<player> <ability>"
)
public void unlock(ICommandSender sender, String[] args) {
public void give(ICommandSender sender, String[] args) {
if (args.length < 2) {
sendError(sender, "Usage: /kam ability unlock <player> <ability>");
sendError(sender, "Usage: /kam ability give <player> <ability>");
return;
}
String playerName = args[0];
String abilityKey = joinArgs(args, 1);
// Find player
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
// Resolve ability
Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
if (ability == null) {
sendError(sender, "Ability not found: " + abilityKey);
@@ -192,17 +192,15 @@ public class AbilityCommand extends CommandKamkeelBase {
// Use the ability's canonical ID for storage (registry key for built-in, UUID for custom)
String canonicalKey = ability.getId();
if (canonicalKey == null || canonicalKey.isEmpty()) {
canonicalKey = abilityKey; // Fallback to user-provided key
canonicalKey = abilityKey;
}
String displayName = ability.getName() != null ? ability.getName() : canonicalKey;
String displayName = ability.getDisplayName();
// Check if ability allows players
if (!ability.getAllowedBy().allowsPlayer()) {
sendError(sender, "Ability '\u00A7b" + displayName + "\u00A7c' is NPC-only and cannot be given to players.");
return;
}
// Get player data and unlock
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (data.abilityData.hasUnlockedAbility(canonicalKey)) {
sendError(sender, "Player already has ability: " + displayName);
@@ -210,39 +208,36 @@ public class AbilityCommand extends CommandKamkeelBase {
}
data.abilityData.unlockAbility(canonicalKey);
sendResult(sender, "Unlocked ability '\u00A7b" + displayName + "\u00A77' for player \u00A7a" + playerName);
sendResult(sender, "Gave ability '\u00A7b" + displayName + "\u00A77' to player \u00A7a" + playerName);
}
@SubCommand(
desc = "Lock (revoke) an ability from a player",
desc = "Remove an ability from a player",
usage = "<player> <ability>"
)
public void lock(ICommandSender sender, String[] args) {
public void remove(ICommandSender sender, String[] args) {
if (args.length < 2) {
sendError(sender, "Usage: /kam ability lock <player> <ability>");
sendError(sender, "Usage: /kam ability remove <player> <ability>");
return;
}
String playerName = args[0];
String abilityKey = joinArgs(args, 1);
// Find player
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
// Resolve ability to get canonical key
Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
String canonicalKey = abilityKey;
String displayName = abilityKey;
if (ability != null) {
canonicalKey = ability.getId() != null ? ability.getId() : abilityKey;
displayName = ability.getName() != null ? ability.getName() : canonicalKey;
if (ability == null) {
sendError(sender, "Ability not found: " + abilityKey);
return;
}
String canonicalKey = ability.getId() != null ? ability.getId() : abilityKey;
String displayName = ability.getDisplayName();
// Get player data and lock
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (!data.abilityData.hasUnlockedAbility(canonicalKey)) {
sendError(sender, "Player doesn't have ability: " + displayName);
@@ -250,7 +245,98 @@ public class AbilityCommand extends CommandKamkeelBase {
}
data.abilityData.lockAbility(canonicalKey);
sendResult(sender, "Locked ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName);
sendResult(sender, "Removed ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName);
}
@SubCommand(
desc = "Give a chained ability to a player",
usage = "<player> <chain>"
)
public void giveChain(ICommandSender sender, String[] args) {
if (args.length < 2) {
sendError(sender, "Usage: /kam ability giveChain <player> <chain>");
return;
}
String playerName = args[0];
String chainKey = joinArgs(args, 1);
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainKey);
if (chain == null) {
sendError(sender, "Chained ability not found: " + chainKey);
return;
}
if (!chain.getAllowedBy().allowsPlayer()) {
sendError(sender, "Chained ability '\u00A7b" + chain.getDisplayName() + "\u00A7c' is NPC-only and cannot be given to players.");
return;
}
String chainId = chain.getId();
if (chainId == null || chainId.isEmpty()) {
sendError(sender, "Chained ability has no ID: " + chain.getDisplayName());
return;
}
// Store by UUID: chain:<uuid>
String storageKey = PlayerAbilityData.CHAIN_PREFIX + chainId;
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (data.abilityData.hasUnlockedAbility(storageKey)) {
sendError(sender, "Player already has chained ability: " + chain.getDisplayName());
return;
}
data.abilityData.unlockAbility(storageKey);
sendResult(sender, "Gave chained ability '\u00A7b" + chain.getDisplayName() + "\u00A77' to player \u00A7a" + playerName);
}
@SubCommand(
desc = "Remove a chained ability from a player",
usage = "<player> <chain>"
)
public void removeChain(ICommandSender sender, String[] args) {
if (args.length < 2) {
sendError(sender, "Usage: /kam ability removeChain <player> <chain>");
return;
}
String playerName = args[0];
String chainKey = joinArgs(args, 1);
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainKey);
if (chain == null) {
sendError(sender, "Chained ability not found: " + chainKey);
return;
}
String chainId = chain.getId();
if (chainId == null || chainId.isEmpty()) {
sendError(sender, "Chained ability has no ID: " + chain.getDisplayName());
return;
}
// Storage uses UUID: chain:<uuid>
String storageKey = PlayerAbilityData.CHAIN_PREFIX + chainId;
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (!data.abilityData.hasUnlockedAbility(storageKey)) {
sendError(sender, "Player doesn't have chained ability: " + chain.getDisplayName());
return;
}
data.abilityData.lockAbility(storageKey);
sendResult(sender, "Removed chained ability '\u00A7b" + chain.getDisplayName() + "\u00A77' from player \u00A7a" + playerName);
}
@SubCommand(
@@ -284,14 +370,23 @@ public class AbilityCommand extends CommandKamkeelBase {
int selected = data.abilityData.getSelectedIndex();
for (int i = 0; i < abilityKeys.length; i++) {
String key = abilityKeys[i];
Ability ability = AbilityController.Instance.resolveAbility(key);
String displayName = ability != null && ability.getName() != null ? ability.getName() : key;
String prefix = (i == selected) ? "\u00A7e> " : " ";
// Show display name and key if different
if (!displayName.equals(key)) {
sendResult(sender, prefix + "\u00A7b" + displayName + " \u00A78[" + key + "]");
if (key.startsWith(PlayerAbilityData.CHAIN_PREFIX)) {
// Chained ability
String chainName = key.substring(PlayerAbilityData.CHAIN_PREFIX.length());
ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainName);
String display = chain != null ? chain.getDisplayName() : chainName;
sendResult(sender, prefix + "\u00A7d[Chain] \u00A7b" + display);
} else {
sendResult(sender, prefix + "\u00A7b" + displayName);
// Regular ability
Ability ability = AbilityController.Instance.resolveAbility(key);
String displayName = ability != null ? ability.getDisplayName() : key;
if (!displayName.equals(key)) {
sendResult(sender, prefix + "\u00A7b" + displayName + " \u00A78[" + key + "]");
} else {
sendResult(sender, prefix + "\u00A7b" + displayName);
}
}
}
}
@@ -306,13 +401,34 @@ public class AbilityCommand extends CommandKamkeelBase {
}
/**
* Get list of player-usable ability keys (for tab completion).
* Uses registry keys for built-in abilities (no spaces) and UUIDs for custom.
* Used by CommandKamkeel for <ability> usage token.
* Get list of player-usable ability names (for tab completion).
* Resolves UUIDs to names so tab completion shows human-readable names.
* Used by CommandKamkeel for {@code <ability>} usage token.
*/
public static List<String> getPlayerAbilityNames() {
List<String> keys = new ArrayList<>(AbilityController.Instance.getPlayerAbilityKeys());
Collections.sort(keys);
return keys;
Set<String> keys = AbilityController.Instance.getPlayerAbilityKeys();
List<String> names = new ArrayList<>();
for (String key : keys) {
Ability a = AbilityController.Instance.resolveAbility(key);
names.add(a != null ? a.getName() : key);
}
Collections.sort(names);
return names;
}
/**
* Get list of player-usable chained ability names (for tab completion).
* Used by CommandKamkeel for {@code <chain>} usage token.
*/
public static List<String> getPlayerChainNames() {
List<String> names = new ArrayList<>();
for (String chainName : AbilityController.Instance.getChainedAbilityNamesSet()) {
ChainedAbility chain = AbilityController.Instance.getChainedAbility(chainName);
if (chain != null && chain.getAllowedBy().allowsPlayer()) {
names.add(chainName);
}
}
Collections.sort(names);
return names;
}
}
@@ -20,6 +20,7 @@ import static kamkeel.npcs.util.ColorUtil.sendMessage;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class AuctionCommand extends CommandKamkeelBase {
private static final int COMMAND_PAGE_SIZE = 10;
public AuctionCommand() {
super();
@@ -62,9 +63,10 @@ public class AuctionCommand extends CommandKamkeelBase {
}
}
List<AuctionListing> listings = controller.getActiveListings(null, page - 1, 10);
page = Math.max(1, page);
List<AuctionListing> listings = controller.getActiveListings(null, page - 1, COMMAND_PAGE_SIZE);
int total = controller.getTotalActiveListings(null);
int totalPages = Math.max(1, (int) Math.ceil((double) total / 10));
int totalPages = Math.max(1, (int) Math.ceil((double) total / COMMAND_PAGE_SIZE));
if (listings.isEmpty()) {
sendMessage(sender, "\u00A77No active auctions found");
@@ -98,6 +100,10 @@ public class AuctionCommand extends CommandKamkeelBase {
return;
}
if (args.length < 1) {
throw new CommandException("Usage: /auction view <player>");
}
String playername = args[0];
List<PlayerData> dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
@@ -21,6 +21,7 @@ import java.util.List;
import java.util.Map;
import static kamkeel.npcs.command.AbilityCommand.getPlayerAbilityNames;
import static kamkeel.npcs.command.AbilityCommand.getPlayerChainNames;
import static kamkeel.npcs.command.EffectCommand.getSortedEffectNames;
public class CommandKamkeel extends CommandBase {
@@ -51,6 +52,7 @@ public class CommandKamkeel extends CommandBase {
registerCommand(new AuctionCommand());
if (ConfigMain.AttributesEnabled)
registerCommand(new AttributeCommand());
registerCommand(new DebugCommand());
}
public void registerCommand(CommandKamkeelBase command) {
@@ -134,10 +136,13 @@ public class CommandKamkeel extends CommandBase {
List<String> keys = new ArrayList<>(RequirementCheckerRegistry.getAllKeys());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
} else if (usage.equals("<effectName>")) {
List<String> keys = getSortedEffectNames();
List<String> keys = stripColorCodes(getSortedEffectNames());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
} else if (usage.equals("<ability>")) {
List<String> keys = getPlayerAbilityNames();
List<String> keys = stripColorCodes(getPlayerAbilityNames());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
} else if (usage.equals("<chain>")) {
List<String> keys = stripColorCodes(getPlayerChainNames());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
}
}
@@ -145,6 +150,14 @@ public class CommandKamkeel extends CommandBase {
return command.addTabCompletionOptions(sender, Arrays.copyOfRange(args, 1, args.length));
}
private static List<String> stripColorCodes(List<String> list) {
List<String> result = new ArrayList<>(list.size());
for (String s : list) {
result.add(s.replaceAll("\u00A7[0-9a-fk-or]", ""));
}
return result;
}
public CommandKamkeelBase getCommand(String[] args) {
if (args.length == 0)
return null;
@@ -11,7 +11,13 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public abstract class CommandKamkeelBase extends CommandBase {
public Map<String, Method> subcommands = new HashMap<String, Method>();
@@ -0,0 +1,41 @@
package kamkeel.npcs.command;
import kamkeel.npcs.util.CNPCDebug;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class DebugCommand extends CommandKamkeelBase {
@Override
public String getCommandName() {
return "debug";
}
@Override
public String getDescription() {
return "Toggle debug logging types";
}
@Override
public String getUsage() {
return "<type>";
}
@Override
public boolean runSubCommands() {
return false;
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (args.length == 0) {
throw new CommandException("Usage: /kam debug <type> (e.g. energy)");
}
String type = args[0].toLowerCase();
boolean newState = CNPCDebug.toggleServer(type);
sendResult(sender, "Server debug '" + type + "' " + (newState ? "\u00A7aENABLED" : "\u00A7cDISABLED"));
}
}
@@ -1,6 +1,7 @@
package kamkeel.npcs.command;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
@@ -93,7 +94,7 @@ public class DialogCommand extends CommandKamkeelBase {
)
public void reload(ICommandSender sender, String args[]) {
new DialogController().load();
SyncController.syncAllDialogs();
SyncController.syncAll(SyncType.DIALOG_CATEGORY);
sendResult(sender, "Dialogs Reloaded");
}
@@ -308,6 +308,7 @@ public class EffectCommand extends CommandKamkeelBase {
// Helper method to find effects by name.
private List<EffectEntry> findEffectsByName(String name) {
String strippedName = stripColorCodes(name);
List<EffectEntry> matches = new ArrayList<>();
CustomEffectController controller = CustomEffectController.getInstance();
for (Map.Entry<Integer, HashMap<Integer, CustomEffect>> entry : controller.indexMapper.entrySet()) {
@@ -317,11 +318,12 @@ public class EffectCommand extends CommandKamkeelBase {
for (Map.Entry<Integer, CustomEffect> effectEntry : effects.entrySet()) {
int id = effectEntry.getKey();
CustomEffect effect = effectEntry.getValue();
if (effect.getName().equalsIgnoreCase(name)) {
String effectName = stripColorCodes(effect.getName());
if (effectName.equalsIgnoreCase(strippedName)) {
List<EffectEntry> exact = new ArrayList<>();
exact.add(new EffectEntry(idx, id, effect));
return exact;
} else if (effect.getName().toLowerCase().contains(name.toLowerCase())) {
} else if (effectName.toLowerCase().contains(strippedName.toLowerCase())) {
matches.add(new EffectEntry(idx, id, effect));
}
}
@@ -329,6 +331,10 @@ public class EffectCommand extends CommandKamkeelBase {
return matches;
}
private static String stripColorCodes(String s) {
return s.replaceAll("\u00A7[0-9a-fk-or]", "");
}
public static List<String> getSortedEffectNames() {
List<EffectEntry> entries = new ArrayList<>();
CustomEffectController controller = CustomEffectController.getInstance();
@@ -200,7 +200,7 @@ public class NpcCommand extends CommandKamkeelBase {
EntityCustomNpc npc = new EntityCustomNpc(pw);
if (args.length > 0)
npc.display.name = args[0];
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch);
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.rotationYaw, 0);
npc.ais.startPos = new int[]{MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)};
pw.spawnEntityInWorld(npc);
npc.setHealth(npc.getMaxHealth());
@@ -99,7 +99,9 @@ public class QuestCategoryCommand extends CommandKamkeelBase {
playerdata.questData.finishedQuests.put(quest.id, completeTime);
}
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared)
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions
&& (quest.profileOptions.completeControl == EnumProfileSync.Shared
|| quest.profileOptions.cooldownControl == EnumProfileSync.Shared))
ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime);
;
@@ -2,6 +2,7 @@ package kamkeel.npcs.command;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.enums.SyncType;
import kamkeel.npcs.network.packets.data.AchievementPacket;
import kamkeel.npcs.network.packets.data.ChatAlertPacket;
import net.minecraft.command.CommandException;
@@ -115,7 +116,9 @@ public class QuestCommand extends CommandKamkeelBase {
playerdata.questData.finishedQuests.put(quest.id, completeTime);
}
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared)
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions
&& (quest.profileOptions.completeControl == EnumProfileSync.Shared
|| quest.profileOptions.cooldownControl == EnumProfileSync.Shared))
ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime);
playerdata.save();
@@ -391,7 +394,7 @@ public class QuestCommand extends CommandKamkeelBase {
)
public void reload(ICommandSender sender, String args[]) {
new QuestController().load();
SyncController.syncAllQuests();
SyncController.syncAll(SyncType.QUEST_CATEGORY);
sendResult(sender, "Quests Reloaded");
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,209 @@
package kamkeel.npcs.controllers;
import kamkeel.npcs.controllers.data.energy.IEnergyExtender;
import kamkeel.npcs.entity.*;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import noppes.npcs.api.IEnergyHandler;
import noppes.npcs.api.IWorld;
import noppes.npcs.api.entity.*;
import noppes.npcs.api.entity.IEnergyExplosion;
import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.entity.ScriptEnergyExplosion;
import java.util.ArrayList;
import java.util.List;
/**
* Central controller for script-created energy entities and handler registration.
* Provides factory methods for creating all energy entity types and routes
* damage through registered handlers when entities have customDamageData
* but no sourceAbility.
*/
public class EnergyController implements IEnergyHandler {
public static EnergyController Instance = new EnergyController();
private final List<IEnergyExtender> extenders = new ArrayList<>();
// ═══════════════════════════════════════════════════════════════════
// HANDLER REGISTRATION
// ═══════════════════════════════════════════════════════════════════
public void registerExtender(IEnergyExtender handler) {
extenders.add(handler);
}
public List<IEnergyExtender> getExtenders() {
return extenders;
}
// ═══════════════════════════════════════════════════════════════════
// DAMAGE ROUTING
// ═══════════════════════════════════════════════════════════════════
/**
* Fire onEnergyDamage on all handlers. Chain of responsibility — first true wins.
*/
public boolean fireOnEnergyDamage(Entity energyEntity, EntityLivingBase owner,
EntityLivingBase target, float damage,
float knockback, float knockbackUp,
double kbDirX, double kbDirZ,
float damageMultiplier,
NBTTagCompound damageData) {
for (IEnergyExtender handler : extenders) {
if (handler.onEnergyDamage(energyEntity, owner, target, damage,
knockback, knockbackUp, kbDirX, kbDirZ, damageMultiplier, damageData)) {
return true;
}
}
return false;
}
/**
* Fire modifyEnergyDamage on all handlers. Cumulative — each handler's output feeds the next.
*/
public float fireModifyEnergyDamage(Entity energyEntity, EntityLivingBase owner,
float baseDamage, NBTTagCompound damageData) {
float damage = baseDamage;
for (IEnergyExtender handler : extenders) {
damage = handler.modifyEnergyDamage(energyEntity, owner, damage, damageData);
}
return damage;
}
// ═══════════════════════════════════════════════════════════════════
// INTERNAL FACTORY METHODS (MC types)
// ═══════════════════════════════════════════════════════════════════
public EntityAbilityOrb createOrbInternal(World world, Entity owner, double x, double y, double z, float size) {
EntityAbilityOrb entity = new EntityAbilityOrb(world);
entity.setPosition(x, y, z);
entity.setStartPosition(x, y, z);
entity.setOwnerEntityId(owner.getEntityId());
entity.setProjectileSize(size);
return entity;
}
public EntityAbilityBeam createBeamInternal(World world, Entity owner, double x, double y, double z,
float beamWidth, float headSize) {
EntityAbilityBeam entity = new EntityAbilityBeam(world);
entity.setPosition(x, y, z);
entity.setStartPosition(x, y, z);
entity.setOwnerEntityId(owner.getEntityId());
entity.setBeamWidth(beamWidth);
entity.setHeadSize(headSize);
return entity;
}
public EntityAbilityDisc createDiscInternal(World world, Entity owner, double x, double y, double z,
float radius, float thickness) {
EntityAbilityDisc entity = new EntityAbilityDisc(world);
entity.setPosition(x, y, z);
entity.setStartPosition(x, y, z);
entity.setOwnerEntityId(owner.getEntityId());
entity.setDiscRadius(radius);
entity.setDiscThickness(thickness);
return entity;
}
public EntityAbilityLaser createLaserInternal(World world, Entity owner, double x, double y, double z,
float laserWidth) {
EntityAbilityLaser entity = new EntityAbilityLaser(world);
entity.setPosition(x, y, z);
entity.setStartPosition(x, y, z);
entity.setOwnerEntityId(owner.getEntityId());
entity.setLaserWidth(laserWidth);
return entity;
}
public EntityAbilityZone createHazardInternal(World world, Entity owner, double x, double y, double z) {
EntityAbilityZone entity = new EntityAbilityZone(world);
entity.initAsHazard(owner, x, y, z);
return entity;
}
public EntityAbilityZone createTrapInternal(World world, Entity owner, double x, double y, double z) {
EntityAbilityZone entity = new EntityAbilityZone(world);
entity.initAsTrap(owner, x, y, z);
return entity;
}
public EntityEnergySweeper createSweeperInternal(World world, Entity owner, double x, double y, double z) {
EntityEnergySweeper entity = new EntityEnergySweeper(world);
entity.setPosition(x, y, z);
entity.setOwnerEntityId(owner.getEntityId());
return entity;
}
public EntityEnergyPanel createPanelInternal(World world, Entity owner, double x, double y, double z) {
EntityEnergyPanel entity = new EntityEnergyPanel(world);
entity.setPosition(x, y, z);
entity.setOwnerEntityId(owner.getEntityId());
return entity;
}
public EntityEnergyExplosion createExplosionInternal(World world, Entity owner, double x, double y, double z, float radius) {
return new EntityEnergyExplosion(world, owner, x, y, z, radius);
}
// ═══════════════════════════════════════════════════════════════════
// IEnergyHandler (Script API methods)
// ═══════════════════════════════════════════════════════════════════
@Override
public IEnergyOrb createOrb(IWorld world, IEntity owner, double x, double y, double z, float size) {
EntityAbilityOrb entity = createOrbInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, size);
return (IEnergyOrb) NpcAPI.Instance().getIEntity(entity);
}
@Override
public IEnergyBeam createBeam(IWorld world, IEntity owner, double x, double y, double z, float beamWidth, float headSize) {
EntityAbilityBeam entity = createBeamInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, beamWidth, headSize);
return (IEnergyBeam) NpcAPI.Instance().getIEntity(entity);
}
@Override
public IEnergyDisc createDisc(IWorld world, IEntity owner, double x, double y, double z, float radius, float thickness) {
EntityAbilityDisc entity = createDiscInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, radius, thickness);
return (IEnergyDisc) NpcAPI.Instance().getIEntity(entity);
}
@Override
public IEnergyLaser createLaser(IWorld world, IEntity owner, double x, double y, double z, float laserWidth) {
EntityAbilityLaser entity = createLaserInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, laserWidth);
return (IEnergyLaser) NpcAPI.Instance().getIEntity(entity);
}
@Override
public IEnergyZone createHazard(IWorld world, IEntity owner, double x, double y, double z) {
EntityAbilityZone entity = createHazardInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
return (IEnergyZone) NpcAPI.Instance().getIEntity(entity);
}
@Override
public IEnergyZone createTrap(IWorld world, IEntity owner, double x, double y, double z) {
EntityAbilityZone entity = createTrapInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
return (IEnergyZone) NpcAPI.Instance().getIEntity(entity);
}
@Override
public IEnergySweeper createSweeper(IWorld world, IEntity owner, double x, double y, double z) {
EntityEnergySweeper entity = createSweeperInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
return (IEnergySweeper) NpcAPI.Instance().getIEntity(entity);
}
@Override
public IEnergyPanel createPanel(IWorld world, IEntity owner, double x, double y, double z) {
EntityEnergyPanel entity = createPanelInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
return (IEnergyPanel) NpcAPI.Instance().getIEntity(entity);
}
@Override
public IEnergyExplosion createExplosion(IWorld world, IEntity owner, double x, double y, double z, float radius) {
EntityEnergyExplosion entity = createExplosionInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, radius);
return new ScriptEnergyExplosion<>(entity);
}
}
@@ -7,7 +7,9 @@ import kamkeel.npcs.controllers.data.profile.Profile;
import kamkeel.npcs.controllers.data.profile.ProfileInfoEntry;
import kamkeel.npcs.controllers.data.profile.ProfileOperation;
import kamkeel.npcs.controllers.data.profile.Slot;
import kamkeel.npcs.network.packets.data.ProfileSharedQuestPacket;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcs;
@@ -453,6 +455,9 @@ public class ProfileController implements IProfileHandler {
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(profile.player);
verifySlotQuests(profile.player);
save(profile.player, profile);
if (profile.player instanceof EntityPlayerMP) {
ProfileSharedQuestPacket.sendToPlayer((EntityPlayerMP) profile.player);
}
IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(profile.player);
EventHooks.onProfileCreate(handler, scriptPlayer, profile, newSlotId, true);
@@ -523,6 +528,10 @@ public class ProfileController implements IProfileHandler {
// overwrite the destination slot with stale data.
saveSlotData(profile.player, profile, prevSlot);
loadSlotData(profile.player, profile, newSlotId);
syncSharedQuestsToPlayer(profile.player);
if (profile.player instanceof EntityPlayerMP) {
ProfileSharedQuestPacket.sendToPlayer((EntityPlayerMP) profile.player);
}
EventHooks.onProfileChange(handler, scriptPlayer, profile, newSlotId, prevSlot, true);
} else {
@@ -832,15 +841,6 @@ public class ProfileController implements IProfileHandler {
else
compound = (NBTTagCompound) compound.copy();
playerData.setNBT(compound);
// Trade data is shared across all profile slots - copy from player's live data
PlayerData liveData = PlayerData.get(player);
if (liveData != null) {
NBTTagCompound tradeCompound = new NBTTagCompound();
liveData.tradeData.writeToNBT(tradeCompound);
playerData.tradeData.readFromNBT(tradeCompound);
}
return playerData;
}
@@ -869,6 +869,9 @@ public class ProfileController implements IProfileHandler {
}
}
// Update the profile cache
profile.sharedQuestTimestamps = universalFinished;
// Push the universal shared completion times into every slot.
for (ISlot slot : profile.getSlots().values()) {
IPlayerData data = getSlotPlayerData(player, slot.getId());
@@ -881,22 +884,33 @@ public class ProfileController implements IProfileHandler {
}
}
public void syncSharedQuestsToPlayer(EntityPlayer player) {
Profile profile = getProfile(player);
if (profile == null || profile.sharedQuestTimestamps.isEmpty()) {
return;
}
PlayerQuestData questData = PlayerData.get(player).questData;
for (Map.Entry<Integer, Long> entry : profile.sharedQuestTimestamps.entrySet()) {
Long existing = questData.finishedQuests.get(entry.getKey());
if (existing == null || entry.getValue() > existing) {
questData.finishedQuests.put(entry.getKey(), entry.getValue());
}
}
}
public void shareQuestCompletion(EntityPlayer player, int questId, long completeTime) {
Profile profile = getProfile(player);
if (profile == null) {
return;
}
for (ISlot slot : profile.getSlots().values()) {
IPlayerData playerData = getSlotPlayerData(player, slot.getId());
if (playerData != null) {
PlayerQuestData questData = (PlayerQuestData) playerData.getQuestData();
Long existing = questData.finishedQuests.get(questId);
if (existing == null || completeTime > existing) {
questData.finishedQuests.put(questId, completeTime);
}
playerData.save();
}
Long existing = profile.sharedQuestTimestamps.get(questId);
if (existing == null || completeTime > existing) {
profile.sharedQuestTimestamps.put(questId, completeTime);
}
save(player, profile);
if (player instanceof EntityPlayerMP) {
ProfileSharedQuestPacket.sendToPlayer((EntityPlayerMP) player);
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -308,6 +308,11 @@ public class TelegraphController implements ITelegraphHandler {
return new ScriptTelegraph(Telegraph.cone(length, angle));
}
@Override
public ITelegraph createSquare(float radius) {
return new ScriptTelegraph(Telegraph.square(radius));
}
@Override
public ITelegraph createPoint() {
return new ScriptTelegraph(Telegraph.point());
@@ -332,6 +337,9 @@ public class TelegraphController implements ITelegraphHandler {
case CONE:
telegraph = Telegraph.cone(5.0f, 45.0f);
break;
case SQUARE:
telegraph = Telegraph.square(3.0f);
break;
case POINT:
telegraph = Telegraph.point();
break;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,323 @@
package kamkeel.npcs.controllers.data.ability;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import net.minecraft.nbt.NBTTagCompound;
import java.util.UUID;
/**
* Unified slot for storing any combat action: inline ability, ability reference, or chain reference.
* Support for all {@link IAbilityAction} types.
* <p>
* References are lazy-resolved via their respective controllers and cached until
* the controller revision changes.
*/
public class AbilityAction {
public enum SlotType {
INLINE_ABILITY,
ABILITY_REFERENCE,
CHAIN_REFERENCE,
INLINE_CHAIN
}
private SlotType slotType;
private Ability inlineAbility;
private ChainedAbility inlineChain;
private String referenceId;
/**
* Per-slot enabled override for reference slots (null = use master's default).
*/
private Boolean enabledOverride;
// Cache
private transient IAbilityAction cachedAction;
private transient int cachedRevision = -1;
private AbilityAction() {
}
// ═══════════════════════════════════════════════════════════════════
// FACTORY METHODS
// ═══════════════════════════════════════════════════════════════════
public static AbilityAction inline(Ability ability) {
AbilityAction slot = new AbilityAction();
slot.slotType = SlotType.INLINE_ABILITY;
slot.inlineAbility = ability;
return slot;
}
public static AbilityAction abilityReference(String referenceId) {
AbilityAction slot = new AbilityAction();
slot.slotType = SlotType.ABILITY_REFERENCE;
slot.referenceId = referenceId;
return slot;
}
public static AbilityAction chainReference(String referenceId) {
AbilityAction slot = new AbilityAction();
slot.slotType = SlotType.CHAIN_REFERENCE;
slot.referenceId = referenceId;
return slot;
}
public static AbilityAction inlineChain(ChainedAbility chain) {
AbilityAction slot = new AbilityAction();
slot.slotType = SlotType.INLINE_CHAIN;
slot.inlineChain = chain;
return slot;
}
// ═══════════════════════════════════════════════════════════════════
// QUERIES
// ═══════════════════════════════════════════════════════════════════
public SlotType getSlotType() {
return slotType;
}
public boolean isReference() {
return slotType == SlotType.ABILITY_REFERENCE || slotType == SlotType.CHAIN_REFERENCE;
}
public boolean isChainReference() {
return slotType == SlotType.CHAIN_REFERENCE;
}
public boolean isInlineChain() {
return slotType == SlotType.INLINE_CHAIN;
}
public boolean isChain() {
return slotType == SlotType.CHAIN_REFERENCE || slotType == SlotType.INLINE_CHAIN;
}
public boolean isAbilityReference() {
return slotType == SlotType.ABILITY_REFERENCE;
}
public String getReferenceId() {
return referenceId;
}
// ═══════════════════════════════════════════════════════════════════
// RESOLUTION
// ═══════════════════════════════════════════════════════════════════
/**
* Resolve the action. Inline returns directly; references resolve
* from the appropriate controller with version-based caching.
*/
public IAbilityAction getAction() {
switch (slotType) {
case INLINE_ABILITY:
return inlineAbility;
case INLINE_CHAIN:
return inlineChain;
case ABILITY_REFERENCE: {
AbilityController ctrl = AbilityController.Instance;
if (ctrl == null) return null;
int rev = ctrl.getCustomAbilityRevision();
if (cachedAction != null && cachedRevision == rev) {
return cachedAction;
}
Ability resolved = ctrl.resolveAbility(referenceId);
cachedAction = resolved;
cachedRevision = rev;
return cachedAction;
}
case CHAIN_REFERENCE: {
AbilityController ctrl = AbilityController.Instance;
if (ctrl == null) return null;
int rev = ctrl.getChainedAbilityRevision();
if (cachedAction != null && cachedRevision == rev) {
return cachedAction;
}
ChainedAbility resolved = ctrl.resolveChainedAbility(referenceId);
cachedAction = resolved;
cachedRevision = rev;
return cachedAction;
}
default:
return null;
}
}
/**
* Get as Ability (returns null if this is a chain slot or resolution fails).
*/
public Ability getAbility() {
IAbilityAction action = getAction();
return (action instanceof Ability) ? (Ability) action : null;
}
/**
* Get as ChainedAbility (returns null if this is an ability slot or resolution fails).
*/
public ChainedAbility getChainedAbility() {
IAbilityAction action = getAction();
return (action instanceof ChainedAbility) ? (ChainedAbility) action : null;
}
// ═══════════════════════════════════════════════════════════════════
// ENABLED OVERRIDE
// ═══════════════════════════════════════════════════════════════════
public void setEnabled(boolean enabled) {
if (slotType == SlotType.INLINE_ABILITY) {
if (inlineAbility != null) {
inlineAbility.setEnabled(enabled);
}
} else if (slotType == SlotType.INLINE_CHAIN) {
if (inlineChain != null) {
inlineChain.setEnabled(enabled);
}
} else {
this.enabledOverride = enabled;
}
}
/**
* Check if this slot is enabled. For inline slots, delegates to the action directly.
* For reference slots, uses enabledOverride if set, otherwise the resolved action's own state.
* This avoids mutating the shared controller instance.
*/
public boolean isSlotEnabled() {
if (enabledOverride != null) {
return enabledOverride;
}
IAbilityAction action = getAction();
return action != null && action.isEnabled();
}
// ═══════════════════════════════════════════════════════════════════
// INLINE CONVERSION (ability references only)
// ═══════════════════════════════════════════════════════════════════
public Ability getInlineAbility() {
return inlineAbility;
}
public ChainedAbility getInlineChain() {
return inlineChain;
}
/**
* Convert this reference slot to an inline slot by copying the resolved data.
* Works for ability references (→ INLINE_ABILITY) and chain references (→ INLINE_CHAIN).
* Chain entries are kept as-is (not auto-converted to inline).
*/
public boolean convertToInline() {
if (slotType == SlotType.ABILITY_REFERENCE) {
Ability resolved = getAbility();
if (resolved == null) return false;
NBTTagCompound nbt = resolved.writeNBT(true);
nbt.setString("id", UUID.randomUUID().toString());
inlineAbility = AbilityController.Instance.fromNBT(nbt);
slotType = SlotType.INLINE_ABILITY;
referenceId = null;
cachedAction = null;
cachedRevision = -1;
return true;
}
if (slotType == SlotType.CHAIN_REFERENCE) {
ChainedAbility resolved = getChainedAbility();
if (resolved == null) return false;
inlineChain = new ChainedAbility();
NBTTagCompound chainNbt = resolved.writeNBT(true);
chainNbt.setString("Id", UUID.randomUUID().toString());
inlineChain.readNBT(chainNbt);
slotType = SlotType.INLINE_CHAIN;
referenceId = null;
cachedAction = null;
cachedRevision = -1;
return true;
}
return false;
}
// ═══════════════════════════════════════════════════════════════════
// NBT
// ═══════════════════════════════════════════════════════════════════
public NBTTagCompound writeNBT(boolean saveScripts) {
switch (slotType) {
case INLINE_CHAIN: {
NBTTagCompound nbt = new NBTTagCompound();
if (inlineChain != null) {
nbt.setTag("InlineChain", inlineChain.writeNBT(saveScripts));
}
return nbt;
}
case CHAIN_REFERENCE: {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("ChainReference", referenceId);
if (enabledOverride != null) {
nbt.setBoolean("RefEnabled", enabledOverride);
}
return nbt;
}
case ABILITY_REFERENCE: {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("Reference", referenceId);
if (enabledOverride != null) {
nbt.setBoolean("RefEnabled", enabledOverride);
}
return nbt;
}
case INLINE_ABILITY:
default:
return inlineAbility != null ? inlineAbility.writeNBT(saveScripts) : new NBTTagCompound();
}
}
public static AbilityAction fromNBT(NBTTagCompound nbt) {
if (nbt == null) return null;
// Inline chain (new format)
if (nbt.hasKey("InlineChain")) {
ChainedAbility chain = new ChainedAbility();
chain.readNBT(nbt.getCompoundTag("InlineChain"));
return inlineChain(chain);
}
// Chain reference
if (nbt.hasKey("ChainReference")) {
AbilityAction slot = chainReference(nbt.getString("ChainReference"));
if (nbt.hasKey("RefEnabled")) {
slot.enabledOverride = nbt.getBoolean("RefEnabled");
}
return slot;
}
// Ability reference
if (nbt.hasKey("Reference")) {
AbilityAction slot = abilityReference(nbt.getString("Reference"));
if (nbt.hasKey("RefEnabled")) {
slot.enabledOverride = nbt.getBoolean("RefEnabled");
}
return slot;
}
// Inline ability
if (AbilityController.Instance == null) return null;
Ability ability = AbilityController.Instance.fromNBT(nbt);
if (ability == null) return null;
return inline(ability);
}
}
@@ -1,529 +0,0 @@
package kamkeel.npcs.controllers.data.ability;
import kamkeel.npcs.controllers.data.ability.type.*;
import kamkeel.npcs.controllers.SyncController;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcs;
import noppes.npcs.LogWriter;
import noppes.npcs.api.handler.IAbilityHandler;
import noppes.npcs.util.NBTJsonUtil;
import java.io.File;
import java.util.*;
import java.util.function.Supplier;
/**
* Central controller for ability types and presets.
* <p>
* Three maps:
* <ul>
* <li>{@code typeFactories} — keyed by typeId (lang key), creates new instances of each ability type</li>
* <li>{@code abilities} — built-in pre-configured abilities, keyed by unique name</li>
* <li>{@code customAbilities} — user-created presets, keyed by UUID</li>
* </ul>
*/
public class AbilityController implements IAbilityHandler {
public static AbilityController Instance = new AbilityController();
/** Type factories keyed by typeId (lang key, e.g. "ability.cnpc.slam"). */
private final Map<String, Supplier<Ability>> typeFactories = new LinkedHashMap<>();
/** Built-in pre-configured abilities keyed by unique name. */
private final Map<String, Ability> abilities = new LinkedHashMap<>();
/** User-created custom ability presets keyed by UUID. */
private final Map<String, Ability> customAbilities = new LinkedHashMap<>();
/** Version counter — incremented on any custom ability add/modify/delete.
* Used by AbilitySlot for cache invalidation. */
private int version = 0;
/** External damage handler (e.g., DBC Addon). */
private IAbilityDamageHandler damageHandler = null;
/** External field providers for ability GUI (e.g., DBC Addon). Client-side only. */
private final List<IAbilityFieldProvider> fieldProviders = new ArrayList<>();
/** External variant definitions registered by addons, keyed by typeId. */
private final Map<String, List<AbilityVariant>> externalVariants = new LinkedHashMap<>();
public AbilityController() {
registerBuiltinTypes();
}
// ═══════════════════════════════════════════════════════════════════════════
// LOADING / SAVING CUSTOM ABILITIES
// ═══════════════════════════════════════════════════════════════════════════
/**
* Load custom ability presets from world directory.
* Called when world loads. Files are named {@code <uuid>.json}.
*/
public void load() {
customAbilities.clear();
File dir = getDir();
if (!dir.exists()) {
return;
}
File[] files = dir.listFiles();
if (files == null) return;
for (File file : files) {
if (!file.isFile() || !file.getName().endsWith(".json")) continue;
try {
String filename = file.getName();
String uuid = filename.substring(0, filename.length() - 5); // strip .json
NBTTagCompound nbt = NBTJsonUtil.LoadFile(file);
Ability ability = fromNBT(nbt);
if (ability != null) {
ability.setId(uuid);
customAbilities.put(uuid, ability);
}
} catch (Exception e) {
LogWriter.error("Error loading custom ability: " + file.getAbsolutePath(), e);
}
}
LogWriter.info("Loaded " + customAbilities.size() + " custom abilities");
}
private File getDir() {
File dir = new File(CustomNpcs.getWorldSaveDirectory(), "abilities");
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
/**
* Save a custom ability preset. If the ability has no id, generates a UUID.
* Stores in customAbilities map and writes to disk.
*/
public boolean saveCustomAbility(Ability ability) {
if (ability == null) return false;
String uuid = ability.getId();
if (uuid == null || uuid.isEmpty()) {
uuid = UUID.randomUUID().toString();
ability.setId(uuid);
}
File dir = getDir();
File fileNew = new File(dir, uuid + ".json_new");
File fileCurrent = new File(dir, uuid + ".json");
try {
NBTTagCompound nbt = ability.writeNBT();
NBTJsonUtil.SaveFile(fileNew, nbt);
if (fileCurrent.exists()) {
fileCurrent.delete();
}
fileNew.renameTo(fileCurrent);
if (fileNew.exists()) {
fileNew.delete();
}
customAbilities.put(uuid, ability);
version++;
LogWriter.info("Saved custom ability: " + ability.getName() + " [" + uuid + "]");
SyncController.syncAllCustomAbilities();
return true;
} catch (Exception e) {
LogWriter.error("Error saving custom ability: " + uuid, e);
return false;
}
}
/**
* Delete a custom ability preset by UUID.
*/
public boolean deleteCustomAbility(String uuid) {
if (uuid == null || uuid.isEmpty()) return false;
Ability removed = customAbilities.remove(uuid);
if (removed == null) return false;
File dir = getDir();
File file = new File(dir, uuid + ".json");
if (file.exists()) {
file.delete();
}
version++;
LogWriter.info("Deleted custom ability: " + uuid);
SyncController.syncAllCustomAbilities();
return true;
}
// ═══════════════════════════════════════════════════════════════════════════
// BUILT-IN ABILITY REGISTRY
// ═══════════════════════════════════════════════════════════════════════════
/**
* Register a pre-configured built-in ability by name.
* These are looked up by name in {@link #resolveAbility(String)}.
*
* @param name Unique name (e.g., "Jump Attack", "Ki Blast")
* @param ability Pre-configured ability instance
*/
public void registerAbility(String name, Ability ability) {
if (abilities.containsKey(name)) {
LogWriter.info("AbilityController: Overwriting built-in ability: " + name);
}
ability.setName(name);
abilities.put(name, ability);
LogWriter.info("Registered ability: " + name);
}
// ═══════════════════════════════════════════════════════════════════════════
// RESOLUTION (used by AbilitySlot, PlayerAbilityData, etc.)
// ═══════════════════════════════════════════════════════════════════════════
/**
* Resolve an ability by key. Checks built-in abilities first (by name or registry key),
* then custom abilities (by UUID or name). Returns a copy safe to modify for
* custom abilities, or the singleton instance for built-in abilities.
*
* @param key The ability name, registry key (built-in) or UUID (custom)
* @return The resolved ability, or null if not found
*/
public Ability resolveAbility(String key) {
if (key == null || key.isEmpty()) return null;
// Check built-in abilities first (exact match by name)
Ability builtIn = abilities.get(key);
if (builtIn != null) {
return builtIn;
}
// Check built-in abilities by name (case-insensitive)
for (Map.Entry<String, Ability> entry : abilities.entrySet()) {
if (entry.getKey().equalsIgnoreCase(key)) {
return entry.getValue();
}
}
// Check built-in abilities by registry key / ID
for (Ability ability : abilities.values()) {
if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) {
return ability;
}
}
// Check custom abilities (exact UUID match)
Ability custom = customAbilities.get(key);
if (custom != null) {
return fromNBT(custom.writeNBT());
}
// Check custom abilities by name (case-insensitive)
for (Ability ability : customAbilities.values()) {
if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) {
return fromNBT(ability.writeNBT());
}
}
return null;
}
/**
* Get all keys that can be used to look up abilities (for tab completion).
* Returns registry keys for built-in abilities (no spaces) and UUIDs for custom.
*/
public Set<String> getAbilityKeys() {
Set<String> keys = new LinkedHashSet<>();
// Built-in abilities - use the ID (registry key for BuiltInAbility)
for (Ability ability : abilities.values()) {
String id = ability.getId();
if (id != null && !id.isEmpty()) {
keys.add(id);
}
}
// Custom abilities - use UUID
keys.addAll(customAbilities.keySet());
return keys;
}
/**
* Get keys for player-usable abilities only (for tab completion).
*/
public Set<String> getPlayerAbilityKeys() {
Set<String> keys = new LinkedHashSet<>();
// Built-in abilities - use the ID (registry key for BuiltInAbility)
for (Ability ability : abilities.values()) {
if (ability.getAllowedBy().allowsPlayer()) {
String id = ability.getId();
if (id != null && !id.isEmpty()) {
keys.add(id);
}
}
}
// Custom abilities - use UUID (if player-usable)
for (Map.Entry<String, Ability> entry : customAbilities.entrySet()) {
if (entry.getValue().getAllowedBy().allowsPlayer()) {
keys.add(entry.getKey());
}
}
return keys;
}
/**
* Check if an ability key exists (either built-in or custom).
*/
public boolean hasAbility(String key) {
return abilities.containsKey(key) || customAbilities.containsKey(key);
}
// ═══════════════════════════════════════════════════════════════════════════
// ACCESSORS
// ═══════════════════════════════════════════════════════════════════════════
/** Get a built-in ability by name. Returns the stored instance (not a copy). */
public Ability getAbility(String name) {
return abilities.get(name);
}
/** Get all built-in ability names. */
public Set<String> getAbilityNames() {
return new LinkedHashSet<>(abilities.keySet());
}
/** Get a custom ability by UUID. Returns the stored instance (not a copy). */
public Ability getCustomAbility(String uuid) {
return customAbilities.get(uuid);
}
/** Check if a custom ability exists by UUID. */
public boolean hasCustomAbility(String uuid) {
return customAbilities.containsKey(uuid);
}
/** Get all custom ability UUIDs. */
public Set<String> getCustomAbilityIds() {
return new LinkedHashSet<>(customAbilities.keySet());
}
/** Get the display name for a custom ability by UUID. */
public String getCustomAbilityName(String uuid) {
Ability a = customAbilities.get(uuid);
return a != null ? a.getName() : null;
}
/** Get the custom abilities map (used by SyncController). */
public Map<String, Ability> getCustomAbilities() {
return customAbilities;
}
/** Replace the custom abilities map (used by client-side sync). */
public void setCustomAbilities(Map<String, Ability> synced) {
customAbilities.clear();
customAbilities.putAll(synced);
version++;
}
/** Get the version counter (incremented on custom ability changes). */
public int getVersion() {
return version;
}
// ═══════════════════════════════════════════════════════════════════════════
// IAbilityHandler INTERFACE IMPLEMENTATION
// ═══════════════════════════════════════════════════════════════════════════
@Override
public String[] getTypes() {
return typeFactories.keySet().toArray(new String[0]);
}
@Override
public boolean hasType(String typeId) {
return typeFactories.containsKey(typeId);
}
@Override
public String[] getAbilityNameArray() {
return abilities.keySet().toArray(new String[0]);
}
@Override
public boolean hasAbilityName(String name) {
return abilities.containsKey(name);
}
@Override
public String[] getCustomAbilityIdArray() {
return customAbilities.keySet().toArray(new String[0]);
}
@Override
public boolean hasCustomAbilityId(String uuid) {
return customAbilities.containsKey(uuid);
}
@Override
public boolean deleteCustomAbilityById(String uuid) {
return deleteCustomAbility(uuid);
}
// ═══════════════════════════════════════════════════════════════════════════
// TYPE REGISTRATION
// ═══════════════════════════════════════════════════════════════════════════
/**
* Register a new ability type.
* Extracts the typeId from a temporary instance and stores in typeFactories.
*
* @param factoryKey Unused legacy key — the typeId from the created instance is used
* @param factory Factory lambda that creates a new instance
*/
public void registerType(String factoryKey, Supplier<Ability> factory) {
Ability temp = factory.get();
String typeId = temp.getTypeId();
if (typeFactories.containsKey(typeId)) {
LogWriter.info("AbilityController: Overwriting type: " + typeId);
}
typeFactories.put(typeId, factory);
}
/**
* Create an ability from NBT data.
* Uses the "typeId" field to look up in typeFactories.
*/
public Ability fromNBT(NBTTagCompound nbt) {
if (nbt == null || !nbt.hasKey("typeId")) {
return null;
}
String typeId = nbt.getString("typeId");
Supplier<Ability> factory = typeFactories.get(typeId);
if (factory == null) {
LogWriter.info("AbilityController: Unknown ability type: " + typeId);
return null;
}
Ability ability = factory.get();
ability.readNBT(nbt);
return ability;
}
/**
* Create a new empty ability of the given type.
*
* @param typeId The ability typeId (e.g., "ability.cnpc.slam")
*/
public Ability create(String typeId) {
Supplier<Ability> factory = typeFactories.get(typeId);
if (factory == null) {
return null;
}
return factory.get();
}
/**
* Register built-in ability types.
*/
private void registerBuiltinTypes() {
// Melee/AOE damage abilities
registerType("cnpc:slam", AbilitySlam::new);
registerType("cnpc:heavy_hit", AbilityHeavyHit::new);
registerType("cnpc:cutter", AbilityCutter::new);
// Ranged/Projectile abilities
registerType("cnpc:sweeper", AbilitySweeper::new);
registerType("cnpc:projectile", AbilityProjectile::new);
registerType("cnpc:orb", AbilityOrb::new);
registerType("cnpc:disc", AbilityDisc::new);
registerType("cnpc:laser_shot", AbilityLaserShot::new);
registerType("cnpc:beam", AbilityBeam::new);
// Movement abilities
registerType("cnpc:charge", AbilityCharge::new);
registerType("cnpc:dash", AbilityDash::new);
registerType("cnpc:teleport", AbilityTeleport::new);
registerType("cnpc:vortex", AbilityVortex::new);
registerType("cnpc:shockwave", AbilityShockwave::new);
// Defensive abilities
registerType("cnpc:guard", AbilityGuard::new);
registerType("cnpc:heal", AbilityHeal::new);
// Zone/Trap abilities
registerType("cnpc:hazard", AbilityHazard::new);
registerType("cnpc:trap", AbilityTrap::new);
}
// ═══════════════════════════════════════════════════════════════════════════
// EXTERNAL DAMAGE HANDLER
// ═══════════════════════════════════════════════════════════════════════════
/**
* Register an external damage handler for abilities.
* When set, the handler is called before default damage application.
* If the handler returns true, default damage is skipped.
*/
public void registerDamageHandler(IAbilityDamageHandler handler) {
this.damageHandler = handler;
}
/** Get the registered damage handler, or null if none. */
public IAbilityDamageHandler getDamageHandler() {
return damageHandler;
}
// ═══════════════════════════════════════════════════════════════════════════
// EXTERNAL FIELD PROVIDERS
// ═══════════════════════════════════════════════════════════════════════════
/**
* Register an external field provider for ability GUIs.
* Providers are called during getAllDefinitions() to inject custom tabs/fields.
*/
public void registerFieldProvider(IAbilityFieldProvider provider) {
fieldProviders.add(provider);
}
/** Get all registered field providers. */
public List<IAbilityFieldProvider> getFieldProviders() {
return fieldProviders;
}
// ═══════════════════════════════════════════════════════════════════════════
// EXTERNAL VARIANT REGISTRY
// ═══════════════════════════════════════════════════════════════════════════
/**
* Register an external variant for an ability type.
* External mods can call this to add variant presets that appear
* alongside built-in variants in the variant selection SubGui.
*
* @param typeId The ability typeId (e.g., "ability.cnpc.beam")
* @param variant The variant to register
*/
public void registerVariant(String typeId, AbilityVariant variant) {
externalVariants.computeIfAbsent(typeId, k -> new ArrayList<>()).add(variant);
}
/**
* Get all variants for a given ability type (built-in + external).
* Returns the combined list of variants from the ability's getVariants()
* and any externally registered variants.
*
* @param typeId The ability typeId
* @return Combined list of variants, empty if none
*/
public List<AbilityVariant> getVariantsForType(String typeId) {
List<AbilityVariant> result = new ArrayList<>();
Ability temp = create(typeId);
if (temp != null) {
result.addAll(temp.getVariants());
}
List<AbilityVariant> ext = externalVariants.get(typeId);
if (ext != null) {
result.addAll(ext);
}
return result;
}
}
@@ -1,153 +0,0 @@
package kamkeel.npcs.controllers.data.ability;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
/**
* Represents a configurable potion effect that can be applied by abilities.
* Provides a unified system for managing debuffs like slowness, weakness, poison, etc.
*/
public class AbilityEffect {
public enum EffectType {
NONE("gui.none", -1),
SLOWNESS("potion.moveSlowdown", Potion.moveSlowdown.id),
WEAKNESS("potion.weakness", Potion.weakness.id),
POISON("potion.poison", Potion.poison.id),
WITHER("potion.wither", Potion.wither.id),
BLINDNESS("potion.blindness", Potion.blindness.id),
NAUSEA("potion.confusion", Potion.confusion.id),
HUNGER("potion.hunger", Potion.hunger.id),
MINING_FATIGUE("potion.digSlowDown", Potion.digSlowdown.id);
private final String langKey;
private final int potionId;
EffectType(String langKey, int potionId) {
this.langKey = langKey;
this.potionId = potionId;
}
public String getLangKey() {
return langKey;
}
public int getPotionId() {
return potionId;
}
public static String[] getLangKeys() {
EffectType[] types = values();
String[] keys = new String[types.length];
for (int i = 0; i < types.length; i++) keys[i] = types[i].langKey;
return keys;
}
public static EffectType fromOrdinal(int ordinal) {
EffectType[] values = values();
if (ordinal >= 0 && ordinal < values.length) {
return values[ordinal];
}
return NONE;
}
}
private EffectType type = EffectType.NONE;
private int durationTicks = 60;
private int amplifier = 0; // 0-10
public AbilityEffect() {
}
public AbilityEffect(EffectType type, int durationTicks, int amplifier) {
this.type = type;
this.durationTicks = Math.max(1, durationTicks);
this.amplifier = Math.max(0, Math.min(10, amplifier));
}
/**
* Creates a copy of this effect.
*/
public AbilityEffect copy() {
return new AbilityEffect(type, durationTicks, amplifier);
}
/**
* Applies this effect to the given entity.
* Does nothing if type is NONE.
*/
public void apply(EntityLivingBase entity) {
if (entity == null || type == EffectType.NONE) {
return;
}
int potionId = type.getPotionId();
if (potionId >= 0) {
entity.addPotionEffect(new PotionEffect(potionId, durationTicks, amplifier));
}
}
/**
* Writes this effect to NBT.
*/
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setInteger("type", type.ordinal());
nbt.setInteger("duration", durationTicks);
nbt.setInteger("amplifier", amplifier);
return nbt;
}
/**
* Reads this effect from NBT.
*/
public void readNBT(NBTTagCompound nbt) {
this.type = EffectType.fromOrdinal(nbt.getInteger("type"));
this.durationTicks = nbt.hasKey("duration") ? nbt.getInteger("duration") : 60;
this.amplifier = nbt.hasKey("amplifier") ? nbt.getInteger("amplifier") : 0;
}
/**
* Creates an AbilityEffect from NBT.
*/
public static AbilityEffect fromNBT(NBTTagCompound nbt) {
AbilityEffect effect = new AbilityEffect();
effect.readNBT(nbt);
return effect;
}
// Getters & Setters
public EffectType getType() {
return type;
}
public void setType(EffectType type) {
this.type = type != null ? type : EffectType.NONE;
}
public int getDurationTicks() {
return durationTicks;
}
public void setDurationTicks(int durationTicks) {
this.durationTicks = Math.max(1, durationTicks);
}
public int getAmplifier() {
return amplifier;
}
public void setAmplifier(int amplifier) {
this.amplifier = Math.max(0, Math.min(10, amplifier));
}
/**
* Returns true if this effect is configured (not NONE).
*/
public boolean isValid() {
return type != EffectType.NONE;
}
}
@@ -1,124 +0,0 @@
package kamkeel.npcs.controllers.data.ability;
import net.minecraft.nbt.NBTTagCompound;
/**
* Wrapper that stores either an inline ability (full NBT) or a reference
* to a built-in/custom ability (by name or UUID).
* <p>
* References are lazy-resolved via {@link AbilityController#resolveAbility(String)}
* and cached until the controller version changes.
*/
public class AbilitySlot {
private Ability inlineAbility;
private String referenceId;
private transient Ability cachedAbility;
private transient int cachedVersion = -1;
private AbilitySlot() {}
/**
* Create a slot with an inline (embedded) ability.
*/
public static AbilitySlot inline(Ability ability) {
AbilitySlot slot = new AbilitySlot();
slot.inlineAbility = ability;
slot.referenceId = null;
return slot;
}
/**
* Create a slot that references a built-in ability (by name) or custom ability (by UUID).
*/
public static AbilitySlot reference(String referenceId) {
AbilitySlot slot = new AbilitySlot();
slot.inlineAbility = null;
slot.referenceId = referenceId;
return slot;
}
public boolean isReference() {
return referenceId != null;
}
public String getReferenceId() {
return referenceId;
}
/**
* Get the resolved ability. For inline slots, returns the ability directly.
* For reference slots, lazily resolves from AbilityController and caches.
* Returns null if the reference cannot be resolved (broken ref).
*/
public Ability getAbility() {
if (!isReference()) {
return inlineAbility;
}
// Lazy resolve with version-based cache invalidation
AbilityController controller = AbilityController.Instance;
if (controller == null) return null;
int currentVersion = controller.getVersion();
if (cachedAbility != null && cachedVersion == currentVersion) {
return cachedAbility;
}
cachedAbility = controller.resolveAbility(referenceId);
cachedVersion = currentVersion;
return cachedAbility;
}
/**
* Get the inline ability directly (null for reference slots).
*/
public Ability getInlineAbility() {
return inlineAbility;
}
/**
* Convert this reference slot to an inline slot by copying the resolved ability.
* No-op if already inline. Returns false if resolution fails.
*/
public boolean convertToInline() {
if (!isReference()) return true;
Ability resolved = getAbility();
if (resolved == null) return false;
// Deep copy via NBT round-trip
inlineAbility = AbilityController.Instance.fromNBT(resolved.writeNBT());
referenceId = null;
cachedAbility = null;
cachedVersion = -1;
return true;
}
// ═══════════════════════════════════════════════════════════════════
// NBT
// ═══════════════════════════════════════════════════════════════════
public NBTTagCompound writeNBT() {
if (isReference()) {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("Reference", referenceId);
return nbt;
}
return inlineAbility != null ? inlineAbility.writeNBT() : new NBTTagCompound();
}
public static AbilitySlot fromNBT(NBTTagCompound nbt) {
if (nbt == null) return null;
if (nbt.hasKey("Reference")) {
return reference(nbt.getString("Reference"));
}
// Inline ability
Ability ability = AbilityController.Instance.fromNBT(nbt);
if (ability == null) return null;
return inline(ability);
}
}
@@ -6,7 +6,7 @@ import java.util.function.Consumer;
* Represents a variant/template for an ability type.
* When a user creates an ability that has registered variants,
* they are presented with a selection dialog before the ability is created.
*
* <p>
* Each variant has a display name (lang key) and a configurator that
* applies preset values to the newly created ability.
*/
@@ -1,55 +0,0 @@
package kamkeel.npcs.controllers.data.ability;
import net.minecraft.nbt.NBTTagCompound;
/**
* Abstract base class for built-in (non-customizable) abilities.
* Built-in abilities are registered by key, have fixed configurations,
* and cannot be modified through the preset GUI system.
* <p>
* Examples: simple utility abilities like Jump, Sprint, etc.
* Third-party mods can extend this class to create their own built-in abilities.
*/
public abstract class BuiltInAbility extends Ability {
/**
* The registry key used to look up this ability (e.g., "cnpc:jump", "dbc:ki_blast").
*/
private final String registryKey;
public BuiltInAbility(String registryKey) {
this.registryKey = registryKey;
this.id = registryKey;
this.name = registryKey;
this.typeId = registryKey;
}
/**
* Get the registry key for this built-in ability.
*/
public String getRegistryKey() {
return registryKey;
}
/**
* Built-in abilities do not write type-specific NBT (they have fixed configs).
*/
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
// No-op: built-in abilities have fixed configurations
}
/**
* Built-in abilities do not read type-specific NBT.
*/
@Override
public void readTypeNBT(NBTTagCompound nbt) {
// No-op: built-in abilities have fixed configurations
}
/**
* Get the duration of the active phase in ticks.
* Built-in abilities must define their own active duration.
*/
public abstract int getActiveDurationTicks();
}
@@ -0,0 +1,110 @@
package kamkeel.npcs.controllers.data.ability;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import net.minecraft.entity.EntityLivingBase;
/**
* Wraps a concurrent ability execution with its own independent lifecycle.
* Concurrent abilities skip animations, sounds, and movement/rotation locks.
* They run their execute/tick logic in parallel with the primary ability.
* <p>
* Used by the chain system when an entry is concurrent-capable and concurrent-enabled.
*/
public class ConcurrentSlot {
private final Ability ability;
private boolean started = false;
private boolean completed = false;
public ConcurrentSlot(Ability ability) {
this.ability = ability;
}
public Ability getAbility() {
return ability;
}
public boolean isCompleted() {
return completed;
}
/**
* Start the concurrent ability. Skips windup — goes straight to ACTIVE.
* Called once when the slot is activated.
*/
public void start(EntityLivingBase caster, EntityLivingBase target) {
// Skip windup for concurrent execution — fire immediately
ability.setWindUpTicks(0);
ability.start(target);
started = true;
// Ability should now be in ACTIVE phase (0 windup → immediate)
if (ability.getPhase() == AbilityPhase.ACTIVE) {
ability.onExecute(caster, target);
}
// Check if ability completed during onExecute (instant abilities like signalCompletion)
if (ability.getPhase() == AbilityPhase.IDLE) {
completed = true;
}
}
/**
* Tick the concurrent ability. Called every game tick from AbstractDataAbilities.
* Handles phase transitions including burst delay → re-execute cycles.
*/
public void tick(EntityLivingBase caster, EntityLivingBase target) {
if (completed || !started) return;
AbilityPhase oldPhase = ability.getPhase();
boolean phaseChanged = ability.tick();
AbilityPhase newPhase = ability.getPhase();
switch (newPhase) {
case ACTIVE:
if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) {
// Re-entering ACTIVE after burst delay → re-execute (burst re-fire)
ability.onExecute(caster, target);
if (ability.getPhase() == AbilityPhase.IDLE) {
completed = true;
return;
}
}
// Normal active tick
ability.onActiveTick(caster, target, ability.getCurrentTick());
if (ability.getPhase() == AbilityPhase.IDLE) {
completed = true;
}
break;
case BURST_DELAY:
// Waiting between bursts — nothing to do, tick() handles countdown
break;
case WINDUP:
// Burst replay with windup — for concurrent, skip it by advancing
// (windUpTicks was set to 0 at start, but burst replay may re-enter WINDUP)
// The next tick() call will transition to ACTIVE
break;
case IDLE:
completed = true;
break;
case DAZED:
// Concurrent abilities don't get dazed — treat as completed
completed = true;
break;
}
}
/**
* Force cleanup on interrupt. Called when the NPC is interrupted or combat ends.
*/
public void interrupt() {
if (!completed) {
ability.interrupt();
completed = true;
}
}
}
@@ -1,313 +0,0 @@
package kamkeel.npcs.controllers.data.ability;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.entity.EntityNPCInterface;
/**
* Interface for ability usage conditions.
* Conditions determine when an ability is eligible to be used.
*/
public interface Condition {
/**
* Check if this condition is met.
*
* @param caster The entity that would use the ability (NPC or Player)
* @param target The current target (may be null for self-targeting abilities or players)
* @return true if the condition is satisfied
*/
boolean check(EntityLivingBase caster, EntityLivingBase target);
/**
* Whether this condition requires a target entity to evaluate.
* Conditions that return true here will be skipped for player ability checks.
*/
default boolean requiresTarget() {
return false;
}
/**
* Get the condition type ID for serialization.
*/
String getTypeId();
/**
* Write this condition to NBT.
*/
NBTTagCompound writeNBT();
/**
* Read this condition from NBT.
*/
void readNBT(NBTTagCompound nbt);
/**
* Create a Condition from NBT data.
* Uses the "type" field to determine which implementation to create.
*/
static Condition fromNBT(NBTTagCompound nbt) {
if (nbt == null || !nbt.hasKey("type")) {
return null;
}
String type = nbt.getString("type");
Condition condition = null;
switch (type) {
case "hp_above":
condition = new ConditionHPAbove();
break;
case "hp_below":
condition = new ConditionHPBelow();
break;
case "target_hp_above":
condition = new ConditionTargetHPAbove();
break;
case "target_hp_below":
condition = new ConditionTargetHPBelow();
break;
case "hit_count":
condition = new ConditionHitCount();
break;
default:
return null;
}
condition.readNBT(nbt);
return condition;
}
// ═══════════════════════════════════════════════════════════════════
// BUILT-IN CONDITION IMPLEMENTATIONS
// ═══════════════════════════════════════════════════════════════════
/**
* Condition: Caster HP is above a percentage threshold.
*/
class ConditionHPAbove implements Condition {
private float threshold = 0.5f; // 50%
public ConditionHPAbove() {
}
public ConditionHPAbove(float threshold) {
this.threshold = threshold;
}
@Override
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
return caster.getHealth() / caster.getMaxHealth() > threshold;
}
@Override
public String getTypeId() {
return "hp_above";
}
@Override
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("type", getTypeId());
nbt.setFloat("threshold", threshold);
return nbt;
}
@Override
public void readNBT(NBTTagCompound nbt) {
threshold = nbt.getFloat("threshold");
}
}
/**
* Condition: Caster HP is below a percentage threshold.
*/
class ConditionHPBelow implements Condition {
private float threshold = 0.5f;
public ConditionHPBelow() {
}
public ConditionHPBelow(float threshold) {
this.threshold = threshold;
}
@Override
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
return caster.getHealth() / caster.getMaxHealth() < threshold;
}
@Override
public String getTypeId() {
return "hp_below";
}
@Override
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("type", getTypeId());
nbt.setFloat("threshold", threshold);
return nbt;
}
@Override
public void readNBT(NBTTagCompound nbt) {
threshold = nbt.getFloat("threshold");
}
}
/**
* Condition: Target HP is above a percentage threshold.
* Requires a target - will be skipped for player ability checks.
*/
class ConditionTargetHPAbove implements Condition {
private float threshold = 0.5f;
public ConditionTargetHPAbove() {
}
public ConditionTargetHPAbove(float threshold) {
this.threshold = threshold;
}
@Override
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
if (target == null) return false;
return target.getHealth() / target.getMaxHealth() > threshold;
}
@Override
public boolean requiresTarget() {
return true;
}
@Override
public String getTypeId() {
return "target_hp_above";
}
@Override
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("type", getTypeId());
nbt.setFloat("threshold", threshold);
return nbt;
}
@Override
public void readNBT(NBTTagCompound nbt) {
threshold = nbt.getFloat("threshold");
}
}
/**
* Condition: Target HP is below a percentage threshold.
* Requires a target - will be skipped for player ability checks.
*/
class ConditionTargetHPBelow implements Condition {
private float threshold = 0.5f;
public ConditionTargetHPBelow() {
}
public ConditionTargetHPBelow(float threshold) {
this.threshold = threshold;
}
@Override
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
if (target == null) return false;
return target.getHealth() / target.getMaxHealth() < threshold;
}
@Override
public boolean requiresTarget() {
return true;
}
@Override
public String getTypeId() {
return "target_hp_below";
}
@Override
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("type", getTypeId());
nbt.setFloat("threshold", threshold);
return nbt;
}
@Override
public void readNBT(NBTTagCompound nbt) {
threshold = nbt.getFloat("threshold");
}
}
/**
* Condition: Caster has been hit X times within a time window.
* Useful for reactive abilities that trigger after receiving multiple hits.
* Currently only works for NPCs (requires DataAbilities hit tracking).
*/
class ConditionHitCount implements Condition {
private int requiredHits = 3;
private int withinTicks = 60;
public ConditionHitCount() {
}
public ConditionHitCount(int requiredHits, int withinTicks) {
this.requiredHits = requiredHits;
this.withinTicks = withinTicks;
}
@Override
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
// Check NPC's recent hit count from DataAbilities
if (caster instanceof EntityNPCInterface) {
EntityNPCInterface npc = (EntityNPCInterface) caster;
if (npc.abilities != null) {
return npc.abilities.getRecentHitCount(withinTicks) >= requiredHits;
}
}
// For players, hit count tracking is not yet supported
return false;
}
@Override
public String getTypeId() {
return "hit_count";
}
@Override
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("type", getTypeId());
nbt.setInteger("requiredHits", requiredHits);
nbt.setInteger("withinTicks", withinTicks);
return nbt;
}
@Override
public void readNBT(NBTTagCompound nbt) {
requiredHits = nbt.getInteger("requiredHits");
withinTicks = nbt.getInteger("withinTicks");
}
public int getRequiredHits() {
return requiredHits;
}
public void setRequiredHits(int hits) {
this.requiredHits = hits;
}
public int getWithinTicks() {
return withinTicks;
}
public void setWithinTicks(int ticks) {
this.withinTicks = ticks;
}
}
}
@@ -0,0 +1,486 @@
package kamkeel.npcs.controllers.data.ability;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.enums.LockMode;
import kamkeel.npcs.controllers.data.ability.enums.TargetingMode;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.ICustomAbility;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.List;
/**
* A blank-slate ability that does nothing by itself.
* All behavior is driven by script event hooks (abilityStart, abilityTick, abilityComplete,
* abilityToggle, abilityToggleTick).
* <p>
* Supports two modes based on toggle configuration:
* <ul>
* <li><b>Instant mode</b> (toggleStates = 0): Uses standard execution lifecycle with
* configurable duration. Script hooks: abilityStart, abilityTick, abilityComplete.</li>
* <li><b>Toggle mode</b> (toggleStates >= 1): Uses toggle lifecycle.
* Script hooks: abilityToggle, abilityToggleTick.</li>
* </ul>
*/
public class CustomAbility extends Ability implements ICustomAbility {
private int durationTicks = 20;
// Telegraph dimension fields
private float tRadius = 5.0f;
private float tInnerRadius = 0.0f;
private float tLength = 5.0f;
private float tWidth = 2.0f;
private float tAngle = 45.0f;
// Telegraph timing
private int telegraphActiveTicks = 0;
private boolean syncTelegraphWithDuration = true;
public CustomAbility() {
this.typeId = "ability.cnpc.custom";
this.name = "Custom";
this.targetingMode = TargetingMode.SELF;
this.lockMovement = LockMode.NO;
this.cooldownTicks = 0;
this.windUpTicks = 0;
this.telegraphType = TelegraphType.NONE;
this.showTelegraph = false;
}
// ==================== EXECUTION ====================
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target) {
if (durationTicks <= 0) {
signalCompletion();
}
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) {
if (durationTicks > 0 && tick >= durationTicks) {
signalCompletion();
}
}
// ==================== PROPERTIES ====================
@Override
public boolean hasDamage() {
return false;
}
@Override
public boolean isConcurrentCapable() {
return true;
}
@Override
public boolean isTargetingModeLocked() {
return false;
}
@Override
public boolean allowFreeOnCast() {
return true;
}
@Override
public boolean hasOwnTelegraphControls() {
return true;
}
// ==================== TELEGRAPH OVERRIDES ====================
@Override
public boolean keepTelegraphDuringActive() {
return getResolvedTelegraphActiveTicks() > 0;
}
/**
* Returns the effective telegraph active ticks: synced from duration or manual value.
*/
public int getResolvedTelegraphActiveTicks() {
if (syncTelegraphWithDuration) {
return durationTicks;
}
return telegraphActiveTicks;
}
@Override
public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) {
if (!isShowTelegraph() || getTelegraphType() == TelegraphType.NONE) {
return null;
}
Telegraph telegraph;
double x, y, z;
float yaw = caster.rotationYaw;
TelegraphType tType = getTelegraphType();
boolean positionAtCaster = targetingMode == TargetingMode.AOE_SELF ||
targetingMode == TargetingMode.SELF ||
tType == TelegraphType.LINE ||
tType == TelegraphType.CONE;
if (positionAtCaster) {
x = caster.posX;
y = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ);
z = caster.posZ;
} else if (target != null) {
x = target.posX;
y = findGroundLevel(caster.worldObj, target.posX, target.posY, target.posZ);
z = target.posZ;
} else {
x = caster.posX;
y = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ);
z = caster.posZ;
}
switch (tType) {
case CIRCLE:
telegraph = Telegraph.circle(tRadius);
break;
case RING:
telegraph = Telegraph.ring(tRadius, tInnerRadius);
break;
case LINE:
telegraph = Telegraph.line(tLength, tWidth);
break;
case CONE:
telegraph = Telegraph.cone(tLength, tAngle, tInnerRadius);
break;
case POINT:
telegraph = new Telegraph("", TelegraphType.POINT);
break;
case SQUARE:
telegraph = Telegraph.square(tRadius);
break;
default:
return null;
}
int activeTicks = getResolvedTelegraphActiveTicks();
int totalDuration = windUpTicks + activeTicks;
telegraph.setDurationTicks(Math.max(1, totalDuration));
telegraph.setColor(windUpColor);
telegraph.setWarningColor(activeColor);
if (windUpTicks > 0) {
telegraph.setWarningStartTick(windUpTicks);
} else {
telegraph.setWarningStartTick(0);
}
telegraph.setHeightOffset(telegraphHeightOffset);
TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw);
instance.setCasterEntityId(caster.getEntityId());
if (positionAtCaster) {
instance.setEntityIdToFollow(caster.getEntityId());
if (tType == TelegraphType.LINE || tType == TelegraphType.CONE) {
if (!isRotationLockedDuringWindup()) {
if (target != null) {
instance.setTargetEntityId(target.getEntityId());
} else {
instance.setTrackFollowedEntityYaw(true);
}
}
}
} else if (target != null) {
instance.setEntityIdToFollow(target.getEntityId());
}
return instance;
}
@Override
public float getTelegraphRadius() {
return tRadius;
}
@Override
public float getTelegraphInnerRadius() {
return tInnerRadius;
}
@Override
public float getTelegraphLength() {
return tLength;
}
@Override
public float getTelegraphWidth() {
return tWidth;
}
@Override
public float getTelegraphAngle() {
return tAngle;
}
// ==================== FIELDS ====================
@Override
public int getDurationTicks() {
return durationTicks;
}
@Override
public void setDurationTicks(int ticks) {
this.durationTicks = Math.max(0, ticks);
}
public float getTRadius() {
return tRadius;
}
public void setTRadius(float radius) {
this.tRadius = Math.max(0, radius);
}
public float getTInnerRadius() {
return tInnerRadius;
}
public void setTInnerRadius(float innerRadius) {
this.tInnerRadius = Math.max(0, innerRadius);
}
public float getTLength() {
return tLength;
}
public void setTLength(float length) {
this.tLength = Math.max(0, length);
}
public float getTWidth() {
return tWidth;
}
public void setTWidth(float width) {
this.tWidth = Math.max(0, width);
}
public float getTAngle() {
return tAngle;
}
public void setTAngle(float angle) {
this.tAngle = Math.max(0, angle);
}
public int getTelegraphActiveTicks() {
return telegraphActiveTicks;
}
public void setTelegraphActiveTicks(int ticks) {
this.telegraphActiveTicks = Math.max(0, ticks);
}
public boolean isSyncTelegraphWithDuration() {
return syncTelegraphWithDuration;
}
public void setSyncTelegraphWithDuration(boolean sync) {
this.syncTelegraphWithDuration = sync;
}
// ==================== ICustomAbility ====================
@Override
public int getTelegraphShapeType() {
return getTelegraphType().ordinal();
}
@Override
public void setTelegraphShapeType(int type) {
TelegraphType[] values = TelegraphType.values();
if (type >= 0 && type < values.length) {
setTelegraphType(values[type]);
}
}
@Override
public void setTelegraphRadius(float radius) {
this.tRadius = Math.max(0, radius);
}
@Override
public void setTelegraphInnerRadius(float innerRadius) {
this.tInnerRadius = Math.max(0, innerRadius);
}
@Override
public void setTelegraphLength(float length) {
this.tLength = Math.max(0, length);
}
@Override
public void setTelegraphWidth(float width) {
this.tWidth = Math.max(0, width);
}
@Override
public void setTelegraphAngle(float angle) {
this.tAngle = Math.max(0, angle);
}
@Override
public int getTargetingModeType() {
return getTargetingMode().ordinal();
}
@Override
public void setTargetingModeType(int type) {
TargetingMode[] values = TargetingMode.values();
if (type >= 0 && type < values.length) {
setTargetingMode(values[type]);
}
}
// ==================== NBT ====================
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setInteger("durationTicks", durationTicks);
nbt.setFloat("tRadius", tRadius);
nbt.setFloat("tInnerRadius", tInnerRadius);
nbt.setFloat("tLength", tLength);
nbt.setFloat("tWidth", tWidth);
nbt.setFloat("tAngle", tAngle);
nbt.setInteger("telegraphActiveTicks", telegraphActiveTicks);
nbt.setBoolean("syncTelegraphWithDuration", syncTelegraphWithDuration);
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.durationTicks = Math.max(0, nbt.getInteger("durationTicks"));
this.tRadius = nbt.hasKey("tRadius") ? nbt.getFloat("tRadius") : 5.0f;
this.tInnerRadius = nbt.hasKey("tInnerRadius") ? nbt.getFloat("tInnerRadius") : 0.0f;
this.tLength = nbt.hasKey("tLength") ? nbt.getFloat("tLength") : 5.0f;
this.tWidth = nbt.hasKey("tWidth") ? nbt.getFloat("tWidth") : 2.0f;
this.tAngle = nbt.hasKey("tAngle") ? nbt.getFloat("tAngle") : 45.0f;
this.telegraphActiveTicks = nbt.hasKey("telegraphActiveTicks") ? nbt.getInteger("telegraphActiveTicks") : 0;
this.syncTelegraphWithDuration = nbt.hasKey("syncTelegraphWithDuration") ? nbt.getBoolean("syncTelegraphWithDuration") : true;
}
// ==================== GUI ====================
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
// User Type (NPC / Player / Both)
defs.add(FieldDef.enumField("ability.allowedBy", UserType.class,
this::getAllowedBy, this::setAllowedBy));
// Targeting Mode
defs.add(FieldDef.enumField("ability.targetingMode", TargetingMode.class,
this::getTargetingMode, this::setTargetingMode));
// Toggle section
defs.add(FieldDef.section("ability.section.toggle"));
defs.add(FieldDef.boolField("ability.toggleEnabled",
this::isToggleable, enabled -> setToggleStates(enabled ? Math.max(1, getToggleStates()) : 0)));
defs.add(FieldDef.intField("ability.toggleStates", this::getToggleStates, this::setToggleStates)
.range(1, 10)
.visibleWhen(this::isToggleable));
defs.add(FieldDef.boolField("ability.hasActiveToggle", this::hasActiveToggle, this::setHasActiveToggle)
.visibleWhen(this::isToggleable));
// Duration (instant mode only)
defs.add(FieldDef.section("ability.section.execution")
.visibleWhen(() -> !this.isToggleable()));
defs.add(FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks)
.range(0, 6000)
.visibleWhen(() -> !this.isToggleable()));
// ── Telegraph Controls (Effects tab) ─────────────────────────
defs.add(FieldDef.section("ability.section.telegraph").tab("Effects"));
defs.add(FieldDef.enumField("ability.telegraphShape", TelegraphType.class,
this::getTelegraphType, this::setTelegraphType).tab("Effects")
.hover("ability.hover.telegraphShape"));
defs.add(FieldDef.boolField("ability.showTelegraph", this::isShowTelegraph, this::setShowTelegraph)
.tab("Effects").visibleWhen(this::hasTelegraphShape)
.hover("ability.hover.showTelegraph"));
defs.add(FieldDef.colorSubGui("ability.windUpColor", this::getWindUpColor, this::setWindUpColor)
.tab("Effects").visibleWhen(this::isTelegraphVisible)
.hover("ability.hover.windUpColor"));
defs.add(FieldDef.colorSubGui("ability.activeColor", this::getActiveColor, this::setActiveColor)
.tab("Effects").visibleWhen(this::isTelegraphVisible)
.hover("ability.hover.activeColor"));
defs.add(FieldDef.floatField("ability.telegraphHeight", this::getTelegraphHeightOffset, this::setTelegraphHeightOffset)
.tab("Effects").visibleWhen(this::isTelegraphVisible)
.hover("ability.hover.telegraphHeight"));
// Telegraph active duration with sync toggle (mirrors windup sync pattern)
defs.add(FieldDef.row(
FieldDef.intField("ability.telegraphActiveTicks", this::getTelegraphActiveTicks, this::setTelegraphActiveTicks).range(0, 6000)
.hover("ability.hover.telegraphActiveTicks"),
FieldDef.boolField("ability.syncTelegraph", this::isSyncTelegraphWithDuration, this::setSyncTelegraphWithDuration)
.hover("ability.hover.syncTelegraph")
).tab("Effects").visibleWhen(() -> isTelegraphVisible() && !isSyncTelegraphWithDuration()));
defs.add(FieldDef.row(
FieldDef.labelField("ability.telegraphActiveTicks", () -> getResolvedTelegraphActiveTicks() + "t"),
FieldDef.boolField("ability.syncTelegraph", this::isSyncTelegraphWithDuration, this::setSyncTelegraphWithDuration)
.hover("ability.hover.syncTelegraph")
).tab("Effects").visibleWhen(() -> isTelegraphVisible() && isSyncTelegraphWithDuration()));
// Shape-specific dimension fields
defs.add(FieldDef.floatField("ability.telegraphRadius", this::getTRadius, this::setTRadius)
.tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsRadius())
.hover("ability.hover.telegraphRadius"));
defs.add(FieldDef.floatField("ability.telegraphInnerRadius", this::getTInnerRadius, this::setTInnerRadius)
.tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsInnerRadius())
.hover("ability.hover.telegraphInnerRadius"));
defs.add(FieldDef.floatField("ability.telegraphLength", this::getTLength, this::setTLength)
.tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsLength())
.hover("ability.hover.telegraphLength"));
defs.add(FieldDef.floatField("ability.telegraphWidth", this::getTWidth, this::setTWidth)
.tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsWidth())
.hover("ability.hover.telegraphWidth"));
defs.add(FieldDef.floatField("ability.telegraphAngle", this::getTAngle, this::setTAngle)
.tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsAngle())
.hover("ability.hover.telegraphAngle"));
}
// ==================== TELEGRAPH VISIBILITY HELPERS ====================
private boolean hasTelegraphShape() {
return getTelegraphType() != TelegraphType.NONE;
}
private boolean isTelegraphVisible() {
return hasTelegraphShape() && isShowTelegraph();
}
private boolean needsRadius() {
TelegraphType t = getTelegraphType();
return t == TelegraphType.CIRCLE || t == TelegraphType.RING || t == TelegraphType.SQUARE;
}
private boolean needsInnerRadius() {
TelegraphType t = getTelegraphType();
return t == TelegraphType.RING || t == TelegraphType.CONE;
}
private boolean needsLength() {
TelegraphType t = getTelegraphType();
return t == TelegraphType.LINE || t == TelegraphType.CONE;
}
private boolean needsWidth() {
return getTelegraphType() == TelegraphType.LINE;
}
private boolean needsAngle() {
return getTelegraphType() == TelegraphType.CONE;
}
}
@@ -1,27 +0,0 @@
package kamkeel.npcs.controllers.data.ability;
import net.minecraft.entity.EntityLivingBase;
/**
* External damage handler for abilities.
* When registered, called AFTER script events but BEFORE default attackEntityFrom.
* If handleDamage returns true, default damage is skipped.
*/
public interface IAbilityDamageHandler {
/**
* Handle damage from an ability.
*
* @param ability The ability dealing damage
* @param caster The entity executing the ability
* @param target The entity being hit
* @param damage The damage amount (after script event modifications)
* @param knockback The horizontal knockback
* @param knockbackUp The vertical knockback
* @param knockbackDirX The X component of knockback direction
* @param knockbackDirZ The Z component of knockback direction
* @return true if damage was handled (skip default), false to use default damage
*/
boolean handleDamage(Ability ability, EntityLivingBase caster, EntityLivingBase target,
float damage, float knockback, float knockbackUp,
double knockbackDirX, double knockbackDirZ);
}
@@ -1,47 +0,0 @@
package kamkeel.npcs.controllers.data.ability;
/**
* Defines what an ability locks when Lock Position is enabled.
*/
public enum LockType {
MOVEMENT,
ROTATION,
BOTH;
public boolean locksMovement() {
return this == MOVEMENT || this == BOTH;
}
public boolean locksRotation() {
return this == ROTATION || this == BOTH;
}
public String getDisplayKey() {
switch (this) {
case MOVEMENT:
return "ability.lockType.movement";
case ROTATION:
return "ability.lockType.rotation";
case BOTH:
return "ability.lockType.both";
default:
return "ability.lockType.both";
}
}
public static String[] getDisplayKeys() {
return new String[]{
"ability.lockType.movement",
"ability.lockType.rotation",
"ability.lockType.both"
};
}
public static LockType fromOrdinal(int ordinal) {
LockType[] values = values();
if (ordinal >= 0 && ordinal < values.length) {
return values[ordinal];
}
return BOTH;
}
}
@@ -0,0 +1,127 @@
package kamkeel.npcs.controllers.data.ability.conditions;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.LogWriter;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public abstract class AbilityCondition {
public static final int MAX_CONDITIONS = 5;
protected String typeId = "";
protected String name = "";
protected UserType userType = UserType.BOTH;
protected ConditionFilter conditionFilter = ConditionFilter.CASTER;
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
switch (getFilter()) {
case CASTER:
return checkEntity(caster);
case TARGET:
return target != null && checkEntity(target);
case BOTH:
return checkEntity(caster) && (target != null && checkEntity(target));
default:
return checkEntity(caster);
}
}
protected abstract boolean checkEntity(EntityLivingBase entity);
public boolean requiresTarget() {
return false;
}
/**
* Returns true if all required fields are filled in.
* Used to disable the Done button in SubGuiConditionEdit when incomplete.
*/
public boolean isConfigured() {
return true;
}
public UserType getUserType() {
return userType;
}
public String getTypeId() {
return typeId;
}
public String getName() {
return name;
}
public ConditionFilter getFilter() {
return conditionFilter;
}
public void setFilter(ConditionFilter filter) {
this.conditionFilter = filter;
}
@SideOnly(Side.CLIENT)
public abstract void getConditionDefinitions(List<FieldDef> defs);
/**
* Returns a human-readable summary of this condition's configuration.
* Used for tooltips when hovering over condition buttons.
*/
@SideOnly(Side.CLIENT)
public abstract String getConditionSummary();
@SideOnly(Side.CLIENT)
public final List<FieldDef> getAllDefinitions() {
List<FieldDef> defs = new ArrayList<>();
defs.add(FieldDef.labelField("ability.validFor", () ->
"\u00A7e" + StatCollector.translateToLocal("ability.userType." + getUserType().name())));
defs.add(FieldDef.enumField("condition.filter", ConditionFilter.class, this::getFilter, this::setFilter));
getConditionDefinitions(defs);
return defs;
}
public final NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("typeId", getTypeId());
nbt.setString("name", getName());
nbt.setInteger("userType", getUserType().ordinal());
nbt.setInteger("filter", getFilter().ordinal());
writeTypeNBT(nbt);
return nbt;
}
public abstract void writeTypeNBT(NBTTagCompound nbt);
public abstract void readTypeNBT(NBTTagCompound nbt);
public final void readNBT(NBTTagCompound nbt) {
typeId = nbt.getString("typeId");
name = nbt.getString("name");
userType = UserType.fromOrdinal(nbt.getInteger("userType"));
conditionFilter = ConditionFilter.fromOrdinal(nbt.getInteger("filter"));
readTypeNBT(nbt);
}
public static AbilityCondition fromNBT(NBTTagCompound nbt) {
String typeId = nbt.getString("typeId");
Supplier<AbilityCondition> factory = AbilityController.Instance.getConditionType(typeId);
if (factory == null) {
LogWriter.info("AbilityController: Unknown condition type: " + typeId);
return null;
}
AbilityCondition condition = factory.get();
condition.readNBT(nbt);
return condition;
}
}
@@ -0,0 +1,118 @@
package kamkeel.npcs.controllers.data.ability.conditions;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.List;
/**
* Abstract base for float comparison-based conditions.
* Provides shared CompareType enum, NBT serialization, and FieldDef generation.
*/
public abstract class ConditionCompare extends AbilityCondition {
public enum CompareType {
ABOVE {
@Override
public boolean test(float value, float threshold) {
return value >= threshold;
}
},
BELOW {
@Override
public boolean test(float value, float threshold) {
return value <= threshold;
}
},
EQUAL {
@Override
public boolean test(float value, float threshold) {
return value == threshold;
}
};
public abstract boolean test(float value, float threshold);
public static CompareType fromOrdinal(int ordinal) {
CompareType[] values = values();
return (ordinal >= 0 && ordinal < values.length) ? values[ordinal] : ABOVE;
}
@Override
public String toString() {
return "condition." + name().toLowerCase();
}
}
protected CompareType compareType = CompareType.ABOVE;
/**
* Returns the value to be compared for this entity (e.g. level, skill level).
* Return -1 to indicate the condition should fail immediately.
*/
protected abstract float getEntityValue(EntityLivingBase entity);
/**
* Returns the threshold that getEntityValue() is compared against.
*/
protected abstract float getThreshold();
/**
* Appends subclass-specific FieldDefs (e.g. skill picker, level input).
* Called before the shared compareType field is added.
*/
@SideOnly(Side.CLIENT)
protected abstract void getExtraDefinitions(List<FieldDef> defs);
/**
* Subclasses write their own NBT fields here.
*/
protected abstract void writeExtraNBT(NBTTagCompound nbt);
/**
* Subclasses read their own NBT fields here.
*/
protected abstract void readExtraNBT(NBTTagCompound nbt);
@Override
protected boolean checkEntity(EntityLivingBase entity) {
float value = getEntityValue(entity);
if (value < 0) return false;
return compareType.test(value, getThreshold());
}
@SideOnly(Side.CLIENT)
@Override
public void getConditionDefinitions(List<FieldDef> defs) {
defs.add(FieldDef.enumField("condition.compare_type", CompareType.class, this::getCompareType, this::setCompareType));
getExtraDefinitions(defs);
}
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setInteger("compareType", compareType.ordinal());
writeExtraNBT(nbt);
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
compareType = CompareType.fromOrdinal(nbt.getInteger("compareType"));
readExtraNBT(nbt);
}
// ═══════════════════════════════════════════════════════════════════
// GETTERS / SETTERS
// ═══════════════════════════════════════════════════════════════════
public CompareType getCompareType() {
return compareType;
}
public void setCompareType(CompareType compareType) {
this.compareType = compareType;
}
}
@@ -0,0 +1,37 @@
package kamkeel.npcs.controllers.data.ability.conditions;
public enum ConditionFilter {
CASTER,
TARGET,
BOTH;
public boolean checksCaster() {
return this == CASTER || this == BOTH;
}
public boolean checksTarget() {
return this == TARGET || this == BOTH;
}
public static ConditionFilter fromOrdinal(int ordinal) {
ConditionFilter[] values = values();
if (ordinal >= 0 && ordinal < values.length) {
return values[ordinal];
}
return BOTH;
}
@Override
public String toString() {
switch (this) {
case BOTH:
return "condition.filter.both";
case CASTER:
return "condition.filter.caster";
case TARGET:
return "condition.filter.target";
default:
return name();
}
}
}
@@ -0,0 +1,26 @@
package kamkeel.npcs.controllers.data.ability.conditions;
import net.minecraft.entity.EntityLivingBase;
public class ConditionHPThreshold extends ConditionThreshold {
public ConditionHPThreshold() {
this.typeId = "condition.cnpc.hp_threshold";
this.name = "condition.hp_threshold";
}
@Override
protected float getEntityValue(EntityLivingBase entity) {
return entity.getHealth();
}
@Override
protected float getEntityMaxValue(EntityLivingBase entity) {
return entity.getMaxHealth();
}
@Override
protected String getStatName() {
return "HP";
}
}
@@ -0,0 +1,97 @@
package kamkeel.npcs.controllers.data.ability.conditions;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.advanced.SubGuiCustomEffectSelect;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.controllers.CustomEffectController;
import noppes.npcs.controllers.data.CustomEffect;
import java.util.HashMap;
import java.util.List;
public class ConditionHasEffect extends AbilityCondition {
private int effectId = -1;
private int effectIndex = 0;
public ConditionHasEffect() {
this.typeId = "condition.cnpc.has_effect";
this.name = "condition.has_effect";
this.userType = UserType.PLAYER_ONLY;
}
@Override
protected boolean checkEntity(EntityLivingBase entity) {
if (!(entity instanceof EntityPlayer)) return false;
if (effectId < 0) return false;
EntityPlayer player = (EntityPlayer) entity;
return CustomEffectController.getInstance().hasEffect(player, effectId, effectIndex);
}
public void setEffect(int effectId, int effectIndex) {
this.effectId = effectId;
this.effectIndex = effectIndex;
}
@SideOnly(Side.CLIENT)
@Override
public void getConditionDefinitions(List<FieldDef> defs) {
defs.add(SubGuiCustomEffectSelect.createSelectField(this));
}
@SideOnly(Side.CLIENT)
@Override
public String getConditionSummary() {
String filterLabel = StatCollector.translateToLocal(getFilter().toString());
String effectName = "None";
if (effectId >= 0) {
CustomEffect effect = getEffect();
effectName = effect != null ? effect.getName() : "ID:" + effectId;
}
return "[" + filterLabel + "] Effect: " + effectName;
}
@Override
public boolean isConfigured() {
return effectId >= 0;
}
public CustomEffect getEffect() {
HashMap<Integer, CustomEffect> map = CustomEffectController.getInstance().getEffectMap(effectIndex);
return map != null ? map.get(effectId) : null;
}
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setInteger("effectId", effectId);
nbt.setInteger("effectIndex", effectIndex);
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
effectId = nbt.getInteger("effectId");
effectIndex = nbt.getInteger("effectIndex");
}
public int getEffectId() {
return effectId;
}
public void setEffectId(int effectId) {
this.effectId = effectId;
}
public int getEffectIndex() {
return effectIndex;
}
public void setEffectIndex(int effectIndex) {
this.effectIndex = effectIndex;
}
}
@@ -0,0 +1,82 @@
package kamkeel.npcs.controllers.data.ability.conditions;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.List;
public class ConditionHitCount extends AbilityCondition {
private int requiredHits = 3;
private int withinTicks = 60;
public ConditionHitCount() {
this.typeId = "condition.cnpc.hit_count";
this.name = "condition.hit_count";
this.conditionFilter = ConditionFilter.CASTER;
}
@Override
protected boolean checkEntity(EntityLivingBase entity) {
// Not used — this condition overrides check() directly
return false;
}
@Override
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
if (caster instanceof EntityNPCInterface) {
EntityNPCInterface npc = (EntityNPCInterface) caster;
if (npc.abilities != null) {
return npc.abilities.getRecentHitCount(withinTicks) >= requiredHits;
}
}
// For players, hit count tracking is not yet supported
return false;
}
public int getRequiredHits() {
return requiredHits;
}
public void setRequiredHits(int requiredHits) {
this.requiredHits = Math.max(0, requiredHits);
}
public int getWithinTicks() {
return withinTicks;
}
public void setWithinTicks(int withinTicks) {
this.withinTicks = Math.max(0, withinTicks);
}
@SideOnly(Side.CLIENT)
@Override
public void getConditionDefinitions(List<FieldDef> defs) {
defs.add(FieldDef.intField("condition.required_hits", this::getRequiredHits, this::setRequiredHits).min(1));
defs.add(FieldDef.intField("condition.within_ticks", this::getWithinTicks, this::setWithinTicks).min(0));
}
@SideOnly(Side.CLIENT)
@Override
public String getConditionSummary() {
return "[Caster] Hit " + requiredHits + " times in " + withinTicks + " ticks";
}
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setInteger("requiredHits", requiredHits);
nbt.setInteger("withinTicks", withinTicks);
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
requiredHits = Math.max(0, nbt.getInteger("requiredHits"));
withinTicks = Math.max(0, nbt.getInteger("withinTicks"));
}
}
@@ -0,0 +1,191 @@
package kamkeel.npcs.controllers.data.ability.conditions;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.List;
public class ConditionItem extends AbilityCondition {
public enum UsageType {
ARMOR, HOLDING, COUNT, OFFHAND;
public static UsageType fromOrdinal(int ordinal) {
UsageType[] values = values();
return (ordinal >= 0 && ordinal < values.length) ? values[ordinal] : HOLDING;
}
}
public enum ArmorSlot {
BOOTS, LEGS, CHEST, HELMET;
public static ArmorSlot fromOrdinal(int ordinal) {
ArmorSlot[] values = values();
return (ordinal >= 0 && ordinal < values.length) ? values[ordinal] : BOOTS;
}
}
// Shared
private UsageType usageType = UsageType.HOLDING;
private String itemName = "";
// ARMOR only
private ArmorSlot armorSlot = ArmorSlot.BOOTS;
private boolean fullArmorSet = false;
// COUNT + PLAYER only
private int requiredCount = 1;
public ConditionItem() {
this.typeId = "condition.cnpc.item";
this.name = "condition.item";
}
@Override
protected boolean checkEntity(EntityLivingBase entity) {
switch (usageType) {
case HOLDING:
return checkHolding(entity);
case ARMOR:
return checkArmor(entity);
case COUNT:
return checkCount(entity);
case OFFHAND:
return checkOffhand(entity);
default:
return false;
}
}
private boolean checkHolding(EntityLivingBase entity) {
ItemStack held = entity.getHeldItem();
return matchesItem(held);
}
private boolean checkArmor(EntityLivingBase entity) {
// MC getEquipmentInSlot: 1=boots, 2=legs, 3=chest, 4=helmet
int slot = armorSlot.ordinal() + 1; // BOOTS=0, LEGS=1, CHEST=2, HELMET=3
return matchesItem(entity.getEquipmentInSlot(slot));
}
private boolean checkCount(EntityLivingBase entity) {
if (entity instanceof EntityPlayer) {
return checkPlayerInventoryCount((EntityPlayer) entity);
}
if (entity instanceof EntityNPCInterface) {
return checkNPCProjectile((EntityNPCInterface) entity);
}
return false;
}
private boolean checkOffhand(EntityLivingBase entity) {
// No offhand for players
if (entity instanceof EntityPlayer) return false;
if (!(entity instanceof EntityNPCInterface)) return false;
ItemStack item = ((EntityNPCInterface) entity).getOffHand();
return matchesItem(item);
}
private boolean checkPlayerInventoryCount(EntityPlayer player) {
int count = 0;
for (ItemStack stack : player.inventory.mainInventory) {
if (matchesItem(stack)) {
count += stack.stackSize;
}
}
return count >= requiredCount;
}
private boolean checkNPCProjectile(EntityNPCInterface npc) {
ItemStack projectile = npc.inventory.getProjectile();
return matchesItem(projectile);
}
private boolean matchesItem(ItemStack stack) {
if (stack == null || itemName == null || itemName.isEmpty()) return false;
String registryName = net.minecraft.item.Item.itemRegistry.getNameForObject(stack.getItem());
return itemName.equals(registryName);
}
@SideOnly(Side.CLIENT)
@Override
public void getConditionDefinitions(List<FieldDef> defs) {
defs.add(FieldDef.enumField("condition.usage_type", UsageType.class,
this::getUsageType, this::setUsageType));
defs.add(FieldDef.stringField("condition.item_name",
this::getItemName, this::setItemName)
.hover("condition.hover.item_name"));
defs.add(FieldDef.enumField("condition.armor_slot", ArmorSlot.class,
this::getArmorSlot, this::setArmorSlot)
.visibleWhen(() -> usageType == UsageType.ARMOR)
.hover("condition.hover.armor_slots"));
defs.add(FieldDef.intField("condition.item_count",
this::getRequiredCount, this::setRequiredCount)
.range(1, 64)
.visibleWhen(() -> usageType == UsageType.COUNT && userType.allowsPlayer())
.hover("condition.hover.required_count"));
}
@SideOnly(Side.CLIENT)
@Override
public String getConditionSummary() {
String filterLabel = StatCollector.translateToLocal(getFilter().toString());
String usage = usageType.name();
String item = itemName.isEmpty() ? "None" : itemName;
return "[" + filterLabel + "] " + usage + ": " + item;
}
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setString("itemName", itemName);
nbt.setInteger("usageType", usageType.ordinal());
nbt.setInteger("armorSlot", armorSlot.ordinal());
nbt.setInteger("requiredCount", requiredCount);
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
itemName = nbt.getString("itemName");
usageType = UsageType.fromOrdinal(nbt.getInteger("usageType"));
armorSlot = ArmorSlot.fromOrdinal(nbt.getInteger("armorSlot"));
requiredCount = Math.max(1, nbt.getInteger("requiredCount"));
}
@Override
public boolean isConfigured() {
return itemName != null && !itemName.isEmpty();
}
public UsageType getUsageType() { return usageType; }
public void setUsageType(UsageType usageType) { this.usageType = usageType; }
public String getItemName() { return itemName; }
public void setItemName(String itemName) { this.itemName = itemName; }
public ArmorSlot getArmorSlot() { return armorSlot; }
public void setArmorSlot(ArmorSlot armorSlot) { this.armorSlot = armorSlot; }
public boolean isFullArmorSet() {
return fullArmorSet;
}
public void setFullArmorSet(boolean fullArmorSet) {
this.fullArmorSet = fullArmorSet;
}
public int getRequiredCount() { return requiredCount; }
public void setRequiredCount(int requiredCount) { this.requiredCount = Math.max(1, requiredCount); }
}
@@ -0,0 +1,78 @@
package kamkeel.npcs.controllers.data.ability.conditions;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.select.GuiQuestSelection;
import noppes.npcs.controllers.QuestController;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.Quest;
import java.util.List;
public class ConditionQuestCompleted extends AbilityCondition {
private int questId = -1;
public ConditionQuestCompleted() {
this.typeId = "condition.cnpc.quest_completed";
this.name = "condition.quest_completed";
this.userType = UserType.PLAYER_ONLY;
}
@Override
protected boolean checkEntity(EntityLivingBase entity) {
if (!(entity instanceof EntityPlayer)) return false;
if (questId < 0) return false;
EntityPlayer player = (EntityPlayer) entity;
PlayerData data = PlayerData.get(player);
if (data == null || data.questData == null) return false;
return data.questData.hasFinishedQuest(questId);
}
@SideOnly(Side.CLIENT)
@Override
public void getConditionDefinitions(List<FieldDef> defs) {
defs.add(GuiQuestSelection.createConditionField(this));
}
@SideOnly(Side.CLIENT)
@Override
public String getConditionSummary() {
String filterLabel = StatCollector.translateToLocal(getFilter().toString());
String questName = "None";
if (questId >= 0) {
Quest q = QuestController.Instance.quests.get(questId);
questName = q != null ? q.title : "ID:" + questId;
}
return "[" + filterLabel + "] Quest: " + questName;
}
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setInteger("questId", questId);
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
questId = nbt.getInteger("questId");
}
@Override
public boolean isConfigured() {
return questId >= 0;
}
public int getQuestId() {
return questId;
}
public void setQuestId(int questId) {
this.questId = questId;
}
}
@@ -0,0 +1,175 @@
package kamkeel.npcs.controllers.data.ability.conditions;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.List;
/**
* Abstract base for threshold-based conditions (HP, Ki, etc.).
* Provides shared percent/flat toggle, ThresholdType enum, and FieldDef generation.
*/
public abstract class ConditionThreshold extends AbilityCondition {
public enum ThresholdType {
ABOVE {
@Override
public boolean test(float value, float threshold) {
return value >= threshold;
}
},
BELOW {
@Override
public boolean test(float value, float threshold) {
return value <= threshold;
}
},
EQUAL {
@Override
public boolean test(float value, float threshold) {
return Math.abs(value - threshold) < 0.001f;
}
};
public abstract boolean test(float value, float threshold);
public static ThresholdType fromOrdinal(int ordinal) {
ThresholdType[] values = values();
if (ordinal >= 0 && ordinal < values.length) {
return values[ordinal];
}
return ABOVE;
}
@Override
public String toString() {
switch (this) {
case ABOVE:
return "condition.above";
case BELOW:
return "condition.below";
case EQUAL:
return "condition.equal";
default:
return name();
}
}
}
protected float thresholdFlat = 100f;
protected float thresholdPercent = 0.5f;
protected boolean percent = true;
protected ThresholdType thresholdType = ThresholdType.ABOVE;
/**
* Returns the raw stat value for the entity (e.g. current HP, current Ki).
*/
protected abstract float getEntityValue(EntityLivingBase entity);
/**
* Returns the maximum stat value for the entity (e.g. max HP, max Ki).
* Used to compute the percentage ratio.
*/
protected abstract float getEntityMaxValue(EntityLivingBase entity);
/**
* Returns the display name for the stat being checked (e.g. "HP", "Ki").
* Used in getConditionSummary().
*/
protected abstract String getStatName();
@Override
protected boolean checkEntity(EntityLivingBase entity) {
float value;
float threshold;
if (percent) {
float max = getEntityMaxValue(entity);
value = max > 0 ? getEntityValue(entity) / max : 0;
threshold = thresholdPercent;
} else {
value = getEntityValue(entity);
threshold = thresholdFlat;
}
return thresholdType.test(value, threshold);
}
@SideOnly(Side.CLIENT)
@Override
public void getConditionDefinitions(List<FieldDef> defs) {
defs.add(FieldDef.floatField("condition.threshold_flat", this::getThresholdFlat, this::setThresholdFlat)
.min(0).visibleWhen(() -> !isPercent()));
defs.add(FieldDef.floatField("condition.threshold_percent", this::getThresholdPercent, this::setThresholdPercent)
.min(0).max(1).visibleWhen(this::isPercent));
defs.add(FieldDef.boolField("condition.percent", this::isPercent, this::setIsPercent));
defs.add(FieldDef.enumField("condition.threshold_type", ThresholdType.class,
this::getThresholdType, this::setThresholdType));
}
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setFloat("thresholdFlat", thresholdFlat);
nbt.setFloat("thresholdPercent", thresholdPercent);
nbt.setBoolean("percent", percent);
nbt.setInteger("thresholdType", thresholdType.ordinal());
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
thresholdFlat = nbt.getFloat("thresholdFlat");
thresholdPercent = nbt.getFloat("thresholdPercent");
percent = nbt.getBoolean("percent");
thresholdType = ThresholdType.fromOrdinal(nbt.getInteger("thresholdType"));
}
@SideOnly(Side.CLIENT)
@Override
public String getConditionSummary() {
String filterLabel = StatCollector.translateToLocal(getFilter().toString());
String typeName = getStatName();
String typeLabel = StatCollector.translateToLocal(thresholdType.toString());
String value = percent
? String.format("%.0f%%", thresholdPercent * 100)
: String.format("%.0f", thresholdFlat);
return "[" + filterLabel + "] " + typeName + " " + typeLabel + " " + value;
}
// ═══════════════════════════════════════════════════════════════════
// GETTERS / SETTERS
// ═══════════════════════════════════════════════════════════════════
public float getThresholdFlat() {
return thresholdFlat;
}
public void setThresholdFlat(float value) {
this.thresholdFlat = Math.max(0, value);
}
public float getThresholdPercent() {
return thresholdPercent;
}
public void setThresholdPercent(float value) {
this.thresholdPercent = Math.max(0, Math.min(1, value));
}
public boolean isPercent() {
return percent;
}
public void setIsPercent(boolean percent) {
this.percent = percent;
}
public ThresholdType getThresholdType() {
return thresholdType;
}
public void setThresholdType(ThresholdType type) {
this.thresholdType = type;
}
}
@@ -0,0 +1,338 @@
package kamkeel.npcs.controllers.data.ability.data;
import kamkeel.npcs.controllers.data.ability.Ability;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
/**
* Icon data for abilities, stored in the ability's customData NBT under "AbilityIcon".
* Supports up to 3 layers, each with its own texture, UV coordinates, and tint color.
* Width, height, and scale are shared across all layers.
*/
public class AbilityIconData {
public static final String NBT_KEY = "AbilityIcon";
public static final int MAX_LAYERS = 3;
private final NBTTagCompound customData;
// Shared across all layers
public int width = 32;
public int height = 32;
public float scale = 1.0f;
/** Whether a custom icon override is active. Default false = use type's default icon. */
private boolean enabled = false;
/** Number of active layers (1-3). */
private int layerCount = 1;
/** Layer data (always 3 slots allocated). */
private Layer[] layers = { new Layer(), new Layer(), new Layer() };
/** Per-state icon UV overrides for layer 0 (0-indexed, maps to toggle states 1, 2, ...). */
private int[][] stateIcons = null;
// Animation
private boolean animated = false;
private int frameCount = 1;
private int frametime = 2;
// ═══════════════════════════════════════════════════════════════════
// LAYER INNER CLASS
// ═══════════════════════════════════════════════════════════════════
public static class Layer {
public String texture = "";
public int iconX = 0;
public int iconY = 0;
public int tintColor = 0xFFFFFF;
public Layer() {}
public boolean hasTexture() {
return texture != null && !texture.isEmpty();
}
public void writeToNBT(NBTTagCompound nbt) {
nbt.setString("Texture", texture);
nbt.setInteger("IconX", iconX);
nbt.setInteger("IconY", iconY);
nbt.setInteger("TintColor", tintColor);
}
public void readFromNBT(NBTTagCompound nbt) {
texture = nbt.getString("Texture");
iconX = nbt.getInteger("IconX");
iconY = nbt.getInteger("IconY");
tintColor = nbt.hasKey("TintColor") ? nbt.getInteger("TintColor") : 0xFFFFFF;
}
}
// ═══════════════════════════════════════════════════════════════════
// CONSTRUCTION
// ═══════════════════════════════════════════════════════════════════
private AbilityIconData(NBTTagCompound customData) {
this.customData = customData;
}
/**
* Create an AbilityIconData instance from a raw customData compound.
* Reads existing values if present, otherwise uses defaults.
*/
public static AbilityIconData fromCustomData(NBTTagCompound customData) {
AbilityIconData icon = new AbilityIconData(customData);
if (customData.hasKey(NBT_KEY)) {
icon.readFromNBT(customData.getCompoundTag(NBT_KEY));
}
return icon;
}
/**
* Create an AbilityIconData instance from an ability's customData.
*/
public static AbilityIconData fromAbility(Ability ability) {
return fromCustomData(ability.getCustomData());
}
/**
* Create an AbilityIconData instance from a chained ability's customData.
*/
public static AbilityIconData fromChainedAbility(ChainedAbility chain) {
return fromCustomData(chain.getCustomData());
}
// ═══════════════════════════════════════════════════════════════════
// NBT SERIALIZATION
// ═══════════════════════════════════════════════════════════════════
/**
* Write current state back to the customData NBT.
*/
public void save() {
NBTTagCompound tag = new NBTTagCompound();
writeToNBT(tag);
customData.setTag(NBT_KEY, tag);
}
public void writeToNBT(NBTTagCompound nbt) {
nbt.setBoolean("Enabled", enabled);
nbt.setInteger("Width", width);
nbt.setInteger("Height", height);
nbt.setFloat("Scale", scale);
nbt.setInteger("LayerCount", layerCount);
NBTTagList layerList = new NBTTagList();
for (int i = 0; i < MAX_LAYERS; i++) {
NBTTagCompound layerNBT = new NBTTagCompound();
layers[i].writeToNBT(layerNBT);
layerList.appendTag(layerNBT);
}
nbt.setTag("Layers", layerList);
nbt.setBoolean("Animated", animated);
nbt.setInteger("FrameCount", frameCount);
nbt.setInteger("FrameTime", frametime);
if (stateIcons != null && stateIcons.length > 0) {
NBTTagList list = new NBTTagList();
for (int[] pair : stateIcons) {
NBTTagCompound comp = new NBTTagCompound();
comp.setInteger("IconX", pair[0]);
comp.setInteger("IconY", pair[1]);
list.appendTag(comp);
}
nbt.setTag("StateIcons", list);
}
}
public void readFromNBT(NBTTagCompound nbt) {
enabled = nbt.getBoolean("Enabled");
width = nbt.getInteger("Width");
if (width <= 0) width = 32;
height = nbt.getInteger("Height");
if (height <= 0) height = 32;
scale = nbt.getFloat("Scale");
if (scale <= 0) scale = 1.0f;
layerCount = nbt.getInteger("LayerCount");
if (layerCount < 1) layerCount = 1;
if (layerCount > MAX_LAYERS) layerCount = MAX_LAYERS;
if (nbt.hasKey("Animated"))
animated = nbt.getBoolean("Animated");
if (nbt.hasKey("FrameCount"))
frameCount = Math.max(1, nbt.getInteger("FrameCount"));
if (nbt.hasKey("FrameTime"))
frametime = Math.max(1, nbt.getInteger("FrameTime"));
if (nbt.hasKey("Layers")) {
NBTTagList layerList = nbt.getTagList("Layers", 10);
for (int i = 0; i < MAX_LAYERS; i++) {
layers[i] = new Layer();
if (i < layerList.tagCount()) {
layers[i].readFromNBT(layerList.getCompoundTagAt(i));
}
}
}
if (nbt.hasKey("StateIcons")) {
NBTTagList list = nbt.getTagList("StateIcons", 10);
stateIcons = new int[list.tagCount()][2];
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound comp = list.getCompoundTagAt(i);
stateIcons[i][0] = comp.getInteger("IconX");
stateIcons[i][1] = comp.getInteger("IconY");
}
}
}
// ═══════════════════════════════════════════════════════════════════
// LAYER API
// ═══════════════════════════════════════════════════════════════════
public int getLayerCount() {
return layerCount;
}
public void setLayerCount(int count) {
this.layerCount = Math.max(1, Math.min(MAX_LAYERS, count));
save();
}
public Layer getLayer(int index) {
return (index >= 0 && index < MAX_LAYERS) ? layers[index] : layers[0];
}
public void setLayerTexture(int index, String tex) {
if (index >= 0 && index < MAX_LAYERS) {
layers[index].texture = tex != null ? tex : "";
save();
}
}
public void setLayerIconX(int index, int x) {
if (index >= 0 && index < MAX_LAYERS) {
layers[index].iconX = Math.max(0, x);
save();
}
}
public void setLayerIconY(int index, int y) {
if (index >= 0 && index < MAX_LAYERS) {
layers[index].iconY = Math.max(0, y);
save();
}
}
public void setLayerTintColor(int index, int color) {
if (index >= 0 && index < MAX_LAYERS) {
layers[index].tintColor = color & 0xFFFFFF;
save();
}
}
// ═══════════════════════════════════════════════════════════════════
// SHARED PROPERTY GETTERS/SETTERS (with auto-save)
// ═══════════════════════════════════════════════════════════════════
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
save();
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = Math.max(1, width);
save();
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = Math.max(1, height);
save();
}
public float getScale() {
return scale;
}
public void setScale(float scale) {
this.scale = Math.max(0.1f, scale);
save();
}
// ═══════════════════════════════════════════════════════════════════
// ANIMATION
// ═══════════════════════════════════════════════════════════════════
public boolean isAnimated() {
return animated;
}
public void setAnimated(boolean animated) {
this.animated = animated;
save();
}
public int getFrameCount() {
return frameCount;
}
public void setFrameCount(int frameCount) {
this.frameCount = Math.max(1, frameCount);
save();
}
public int getFrameTime() {
return frametime;
}
public void setFrameTime(int frametime) {
this.frametime = Math.max(1, frametime);
save();
}
// ═══════════════════════════════════════════════════════════════════
// PER-STATE ICON OVERRIDES (applies to layer 0)
// ═══════════════════════════════════════════════════════════════════
public void setStateIcons(int[][] stateIcons) {
this.stateIcons = stateIcons;
save();
}
/**
* Get iconX for a specific toggle state (layer 0).
* Falls back to layer 0 iconX if no state override exists.
* @param state 1-indexed toggle state (0 = off/default)
*/
public int getIconXForState(int state) {
if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) {
return stateIcons[state - 1][0];
}
return layers[0].iconX;
}
/**
* Get iconY for a specific toggle state (layer 0).
* Falls back to layer 0 iconY if no state override exists.
* @param state 1-indexed toggle state (0 = off/default)
*/
public int getIconYForState(int state) {
if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) {
return stateIcons[state - 1][1];
}
return layers[0].iconY;
}
}
@@ -0,0 +1,561 @@
package kamkeel.npcs.controllers.data.ability.data;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import noppes.npcs.controllers.data.ChainedAbilityScript;
import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.api.ability.IChainedAbility;
import noppes.npcs.controllers.data.IScriptUnit;
import kamkeel.npcs.util.FileNameHelper;
import java.util.ArrayList;
import java.util.List;
/**
* A chained ability is an ordered sequence of ability references that execute
* one after another. It has its own conditions, cooldown, weight, and per-entry
* delay configuration. Individual ability conditions are skipped during chain execution.
* <p>
* All entries must be ability references (by name/key). Inline abilities are not supported.
* When saving, all references are validated against {@link AbilityController}.
*/
public class ChainedAbility implements IChainedAbility, IAbilityAction {
// ═══════════════════════════════════════════════════════════════════
// CONFIGURATION (saved to NBT)
// ═══════════════════════════════════════════════════════════════════
private String id = ""; // UUID (stable persistent reference)
private String name = ""; // Unique file key / identifier
private String displayName = ""; // Cosmetic name (falls back to name when empty)
private boolean enabled = true;
/**
* Weight for NPC weighted random selection.
*/
private int weight = 10;
/**
* Whether each ability in the chain uses its own windup phase.
*/
private boolean windUpAll = true;
/**
* Chain-level cooldown in ticks (applied after entire chain completes).
*/
private int cooldownTicks = 100;
/**
* If true, only this chain goes on cooldown (not the global cooldown).
*/
private boolean perAbilityCooldown = false;
/**
* If true, skip cooldown entirely after chain completes.
*/
private boolean ignoreCooldown = false;
/**
* Minimum range for NPC eligibility check.
*/
private float minRange = 0;
/**
* Maximum range for NPC eligibility check.
*/
private float maxRange = 20;
/**
* Chain-level conditions (individual ability conditions are ignored).
*/
private List<AbilityCondition> conditions = new ArrayList<>();
/**
* Ordered list of ability entries to execute.
*/
private List<ChainedAbilityEntry> entries = new ArrayList<>();
/**
* Extension data for external mods (e.g., icons, DBC stats).
*/
private NBTTagCompound customData = new NBTTagCompound();
// Per-instance script (isolated per execution, not saved to NBT)
private transient ChainedAbilityScript instanceScript;
public ChainedAbility() {
}
public ChainedAbility(String name) {
setName(name);
}
// ═══════════════════════════════════════════════════════════════════
// GETTERS / SETTERS
// ═══════════════════════════════════════════════════════════════════
public String getId() {
return id;
}
public void setId(String id) {
this.id = id != null ? id : "";
}
public String getName() {
return name;
}
public void setName(String name) {
String fallback = (this.name != null && !this.name.isEmpty()) ? this.name : "Chain";
this.name = FileNameHelper.sanitizeName(name, fallback);
}
/**
* Get the display name for this chained ability.
* Returns displayName if set, otherwise falls back to name.
* Converts &amp; color codes to § for rendering.
*/
public String getDisplayName() {
String result = (displayName != null && !displayName.isEmpty())
? displayName
: FileNameHelper.toDisplayName(name);
return result != null ? result.replaceAll("&([0-9a-fk-or])", "\u00A7$1") : "";
}
public String getRawDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName != null ? displayName : "";
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = Math.max(1, weight);
}
public boolean isWindUpAll() {
return windUpAll;
}
public void setWindUpAll(boolean windUpAll) {
this.windUpAll = windUpAll;
}
public int getCooldownTicks() {
return cooldownTicks;
}
public void setCooldownTicks(int cooldownTicks) {
this.cooldownTicks = Math.max(0, cooldownTicks);
}
public boolean isPerAbilityCooldown() {
return perAbilityCooldown;
}
public void setPerAbilityCooldown(boolean perAbilityCooldown) {
this.perAbilityCooldown = perAbilityCooldown;
}
public boolean isIgnoreCooldown() {
return ignoreCooldown;
}
public void setIgnoreCooldown(boolean ignoreCooldown) {
this.ignoreCooldown = ignoreCooldown;
}
public float getMinRange() {
return minRange;
}
public void setMinRange(float minRange) {
this.minRange = Math.max(0, minRange);
}
public float getMaxRange() {
return maxRange;
}
public void setMaxRange(float maxRange) {
this.maxRange = Math.max(0, maxRange);
}
/**
* Compute the allowed user type from child abilities.
* A chain allows players if ALL resolved entries allow players.
* A chain allows NPCs if ALL resolved entries allow NPCs.
* Unresolvable entries are skipped (don't restrict).
*/
public UserType getAllowedBy() {
if (entries.isEmpty()) return UserType.BOTH;
boolean allAllowPlayer = true;
boolean allAllowNpc = true;
for (ChainedAbilityEntry entry : entries) {
Ability a = entry.resolve();
if (a == null) continue;
UserType ut = a.getAllowedBy();
if (!ut.allowsPlayer()) allAllowPlayer = false;
if (!ut.allowsNpc()) allAllowNpc = false;
}
if (allAllowPlayer && allAllowNpc) return UserType.BOTH;
if (allAllowPlayer) return UserType.PLAYER_ONLY;
if (allAllowNpc) return UserType.NPC_ONLY;
return UserType.NONE;
}
public List<AbilityCondition> getConditions() {
return conditions;
}
public void setConditions(List<AbilityCondition> conditions) {
this.conditions = conditions != null ? conditions : new ArrayList<>();
}
public List<ChainedAbilityEntry> getEntries() {
return entries;
}
public void setEntries(List<ChainedAbilityEntry> entries) {
this.entries = entries != null ? entries : new ArrayList<>();
}
public NBTTagCompound getCustomData() {
return customData;
}
// ═══════════════════════════════════════════════════════════════════
// IChainedAbility INTERFACE
// ═══════════════════════════════════════════════════════════════════
@Override
public int getEntryCount() {
return entries.size();
}
@Override
public String getEntryReference(int index) {
if (index < 0 || index >= entries.size()) return null;
ChainedAbilityEntry entry = entries.get(index);
if (entry.isInline()) {
Ability a = entry.getInlineAbility();
return a != null ? a.getName() : "";
}
return entry.getAbilityReference();
}
@Override
public boolean isEntryInline(int index) {
if (index < 0 || index >= entries.size()) return false;
return entries.get(index).isInline();
}
@Override
public int getEntryDelay(int index) {
if (index < 0 || index >= entries.size()) return 0;
return entries.get(index).getDelayTicks();
}
// ═══════════════════════════════════════════════════════════════════
// ENTRY MANAGEMENT
// ═══════════════════════════════════════════════════════════════════
public void addEntry(ChainedAbilityEntry entry) {
if (entry != null) {
entries.add(entry);
}
}
public void addEntry(String abilityReference, int delayTicks) {
entries.add(new ChainedAbilityEntry(abilityReference, delayTicks));
}
public void removeEntry(int index) {
if (index >= 0 && index < entries.size()) {
entries.remove(index);
}
}
public void moveEntryUp(int index) {
if (index > 0 && index < entries.size()) {
ChainedAbilityEntry entry = entries.remove(index);
entries.add(index - 1, entry);
}
}
public void moveEntryDown(int index) {
if (index >= 0 && index < entries.size() - 1) {
ChainedAbilityEntry entry = entries.remove(index);
entries.add(index + 1, entry);
}
}
// ═══════════════════════════════════════════════════════════════════
// CONDITIONS
// ═══════════════════════════════════════════════════════════════════
/**
* Check all chain-level conditions against the caster and target.
*/
public boolean checkConditions(EntityLivingBase caster, EntityLivingBase target) {
for (AbilityCondition c : conditions) {
if (!c.getUserType().allowsNpc()) continue;
Boolean extendedCondition = AbilityController.Instance.fireCheckConditions(c, caster, target);
if (extendedCondition != null) {
if (!extendedCondition) return false;
continue;
}
if (!c.check(caster, target)) return false;
}
return true;
}
/**
* Check conditions for player use (skip target-requiring conditions).
*/
public boolean checkConditionsForPlayer(EntityLivingBase caster) {
for (AbilityCondition c : conditions) {
if (!c.getUserType().allowsPlayer()) continue;
if (c.requiresTarget()) continue;
Boolean extendedCondition = AbilityController.Instance.fireCheckConditionsForPlayer(c, caster);
if (extendedCondition != null) {
if (!extendedCondition) return false;
continue;
}
if (!c.check(caster, null)) return false;
}
return true;
}
// ═══════════════════════════════════════════════════════════════════
// VALIDATION
// ═══════════════════════════════════════════════════════════════════
/**
* Validate this chained ability. Returns a list of error messages.
* An empty list means valid.
*/
public List<String> validate() {
List<String> errors = new ArrayList<>();
if (name == null || name.isEmpty()) {
errors.add("Name is required");
}
if (entries.isEmpty()) {
errors.add("At least one ability entry is required");
}
AbilityController controller = AbilityController.Instance;
if (controller != null) {
for (int i = 0; i < entries.size(); i++) {
ChainedAbilityEntry entry = entries.get(i);
if (entry.isInline()) {
if (entry.getInlineAbility() == null) {
errors.add("Entry " + (i + 1) + ": inline ability is null");
}
} else {
String ref = entry.getAbilityReference();
if (ref == null || ref.isEmpty()) {
errors.add("Entry " + (i + 1) + ": ability reference is empty");
} else if (!controller.canResolveAbility(ref)) {
errors.add("Entry " + (i + 1) + ": cannot resolve ability '" + ref + "'");
}
}
}
}
return errors;
}
// ═══════════════════════════════════════════════════════════════════
// DEEP COPY
// ═══════════════════════════════════════════════════════════════════
/**
* Create a deep copy via NBT round-trip.
*/
public ChainedAbility deepCopy() {
ChainedAbility copy = new ChainedAbility();
copy.readNBT(this.writeNBT(false));
return copy;
}
@Override
public boolean isChain() {
return true;
}
@Override
public IAbilityAction deepCopyAction() {
return deepCopy();
}
// ═══════════════════════════════════════════════════════════════════
// NBT SERIALIZATION
// ═══════════════════════════════════════════════════════════════════
public NBTTagCompound writeNBT(boolean saveScripts) {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("Id", id);
nbt.setString("Name", name);
nbt.setString("DisplayName", displayName);
nbt.setBoolean("Enabled", enabled);
nbt.setInteger("Weight", weight);
nbt.setBoolean("WindUpAll", windUpAll);
nbt.setInteger("CooldownTicks", cooldownTicks);
nbt.setBoolean("PerAbilityCooldown", perAbilityCooldown);
nbt.setBoolean("IgnoreCooldown", ignoreCooldown);
nbt.setFloat("MinRange", minRange);
nbt.setFloat("MaxRange", maxRange);
// Conditions
NBTTagList condList = new NBTTagList();
for (AbilityCondition c : conditions) {
condList.appendTag(c.writeNBT());
}
nbt.setTag("Conditions", condList);
// Entries
NBTTagList entryList = new NBTTagList();
for (ChainedAbilityEntry entry : entries) {
entryList.appendTag(entry.writeNBT(saveScripts));
}
nbt.setTag("Entries", entryList);
// Custom data (for external mods)
nbt.setTag("customData", (NBTTagCompound) customData.copy());
// Script handler data (matching CustomEffect.writeToNBT pattern)
if (saveScripts) {
ChainedAbilityScript handler = getScriptHandler();
if (handler != null) {
NBTTagCompound scriptData = new NBTTagCompound();
handler.writeToNBT(scriptData);
nbt.setTag("ScriptData", scriptData);
}
}
return nbt;
}
public void readNBT(NBTTagCompound nbt) {
id = nbt.getString("Id");
setName(nbt.getString("Name"));
displayName = nbt.getString("DisplayName");
enabled = !nbt.hasKey("Enabled") || nbt.getBoolean("Enabled");
weight = nbt.hasKey("Weight") ? nbt.getInteger("Weight") : 10;
windUpAll = !nbt.hasKey("WindUpAll") || nbt.getBoolean("WindUpAll");
cooldownTicks = nbt.hasKey("CooldownTicks") ? nbt.getInteger("CooldownTicks") : 100;
perAbilityCooldown = nbt.getBoolean("PerAbilityCooldown");
ignoreCooldown = nbt.getBoolean("IgnoreCooldown");
minRange = nbt.getFloat("MinRange");
maxRange = nbt.hasKey("MaxRange") ? nbt.getFloat("MaxRange") : 20;
// AllowedBy is computed from child abilities
// Conditions
conditions.clear();
NBTTagList condList = nbt.getTagList("Conditions", 10);
for (int i = 0; i < condList.tagCount(); i++) {
AbilityCondition c = AbilityCondition.fromNBT(condList.getCompoundTagAt(i));
if (c != null) {
conditions.add(c);
}
}
// Entries
entries.clear();
NBTTagList entryList = nbt.getTagList("Entries", 10);
for (int i = 0; i < entryList.tagCount(); i++) {
ChainedAbilityEntry entry = ChainedAbilityEntry.fromNBT(entryList.getCompoundTagAt(i));
if (entry != null) {
entries.add(entry);
}
}
// Custom data (for external mods)
customData = (NBTTagCompound) nbt.getCompoundTag("customData").copy();
// Script handler data (matching CustomEffect.readFromNBT pattern)
if (nbt.hasKey("ScriptData", 10)) {
if (getScriptHandler() == null) {
ChainedAbilityScript handler = new ChainedAbilityScript(this.id);
handler.readFromNBT(nbt.getCompoundTag("ScriptData"));
setScriptHandler(handler);
}
}
}
// ═══════════════════════════════════════════════════════════════════
// SCRIPT HANDLER
// ═══════════════════════════════════════════════════════════════════
public ChainedAbilityScript getScriptHandler() {
return AbilityController.Instance.chainedAbilityScriptHandlers.get(this.id);
}
public void setScriptHandler(ChainedAbilityScript handler) {
AbilityController.Instance.chainedAbilityScriptHandlers.put(this.id, handler);
}
public ChainedAbilityScript getOrCreateScriptHandler() {
ChainedAbilityScript handler = getScriptHandler();
if (handler == null) {
handler = new ChainedAbilityScript(this.id);
AbilityController.Instance.chainedAbilityScriptHandlers.put(this.id, handler);
}
return handler;
}
/**
* Get or create a per-instance script handler for this chain execution.
* Shares the template's engine but creates isolated Bindings for variable state.
* Returns null if no script is configured on the template.
*/
public ChainedAbilityScript getOrCreateInstanceScript() {
if (instanceScript != null) return instanceScript;
ChainedAbilityScript template = getScriptHandler();
if (template == null || !template.getEnabled() || template.container == null) return null;
instanceScript = new ChainedAbilityScript(this.id);
instanceScript.setLanguage(template.getLanguage());
instanceScript.setEnabled(true);
IScriptUnit clone = template.container.createInstanceScope(instanceScript);
instanceScript.addScriptUnit(clone);
return instanceScript;
}
/**
* Clear the per-instance script handler (call on chain completion/reset).
*/
public void clearInstanceScript() {
this.instanceScript = null;
}
}
@@ -1,112 +0,0 @@
package kamkeel.npcs.controllers.data.ability.data;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyCombatData;
/**
* Groups combat properties shared by energy projectile abilities.
* Used as a parameter object for entity constructors and ability configuration.
*/
public class EnergyCombatData implements IEnergyCombatData {
public float damage = 7.0f;
public float knockback = 1.0f;
public float knockbackUp = 0.1f;
public boolean explosive = false;
public float explosionRadius = 3.0f;
public float explosionDamageFalloff = 0.5f;
public EnergyCombatData() {}
public EnergyCombatData(float damage, float knockback, float knockbackUp,
boolean explosive, float explosionRadius, float explosionDamageFalloff) {
this.damage = damage;
this.knockback = knockback;
this.knockbackUp = knockbackUp;
this.explosive = explosive;
this.explosionRadius = explosionRadius;
this.explosionDamageFalloff = explosionDamageFalloff;
}
@Override
public float getDamage() {
return damage;
}
@Override
public void setDamage(float damage) {
this.damage = damage;
}
@Override
public float getKnockback() {
return knockback;
}
@Override
public void setKnockback(float knockback) {
this.knockback = knockback;
}
@Override
public float getKnockbackUp() {
return knockbackUp;
}
@Override
public void setKnockbackUp(float knockbackUp) {
this.knockbackUp = knockbackUp;
}
@Override
public boolean isExplosive() {
return explosive;
}
@Override
public void setExplosive(boolean explosive) {
this.explosive = explosive;
}
@Override
public float getExplosionRadius() {
return explosionRadius;
}
@Override
public void setExplosionRadius(float explosionRadius) {
this.explosionRadius = explosionRadius;
}
@Override
public float getExplosionDamageFalloff() {
return explosionDamageFalloff;
}
@Override
public void setExplosionDamageFalloff(float explosionDamageFalloff) {
this.explosionDamageFalloff = explosionDamageFalloff;
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setFloat("damage", damage);
nbt.setFloat("knockback", knockback);
nbt.setFloat("knockbackUp", knockbackUp);
nbt.setBoolean("explosive", explosive);
nbt.setFloat("explosionRadius", explosionRadius);
nbt.setFloat("explosionDamageFalloff", explosionDamageFalloff);
}
public void readNBT(NBTTagCompound nbt) {
damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 7.0f;
knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 1.0f;
knockbackUp = nbt.hasKey("knockbackUp") ? nbt.getFloat("knockbackUp") : 0.1f;
explosive = nbt.hasKey("explosive") && nbt.getBoolean("explosive");
explosionRadius = nbt.hasKey("explosionRadius") ? nbt.getFloat("explosionRadius") : 3.0f;
explosionDamageFalloff = nbt.hasKey("explosionDamageFalloff") ? nbt.getFloat("explosionDamageFalloff") : 0.5f;
}
public EnergyCombatData copy() {
return new EnergyCombatData(damage, knockback, knockbackUp,
explosive, explosionRadius, explosionDamageFalloff);
}
}
@@ -1,288 +0,0 @@
package kamkeel.npcs.controllers.data.ability.data;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.Constants;
import noppes.npcs.api.IPos;
import noppes.npcs.api.ability.data.IEnergyTrajectoryData;
import noppes.npcs.scripted.NpcAPI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
public class EnergyTrajectoryData implements IEnergyTrajectoryData {
public int currentPath = 0;
private final List<Path> trajectory = new ArrayList<>();
public EnergyTrajectoryData() {}
public EnergyTrajectoryData(int startingPath, Path... paths) {
trajectory.addAll(Arrays.asList(paths));
this.currentPath = startingPath < trajectory.size() && startingPath >= 0 ? startingPath : 0;
}
@Override
public int getCurrentPath() {
return currentPath;
}
@Override
public void setCurrentPath(int currentPath) {
this.currentPath = currentPath;
}
@Override
public int getDelay(int path) {
if (getPath(path) == null) return -1;
return getPath(path).getDelay();
}
@Override
public void setDelay(int path, int ticks) {
if (getPath(path) == null) return;
getPath(path).setDelay(ticks);
}
@Override
public IPos getPos(int path) {
IPath p = getPath(path);
return p == null ? null : p.getPos();
}
@Override
public void setPos(int path, IPos pos) {
IPath p = getPath(path);
if (p != null) p.setPos(pos);
}
@Override
public boolean isConcluded(int path) {
IPath p = getPath(path);
return p != null && p.isConcluded();
}
@Override
public void setConcluded(int path, boolean concluded) {
IPath p = getPath(path);
if (p != null) p.setConcluded(concluded);
}
@Override
public double getX(int path) {
IPath p = getPath(path);
return p == null ? 0 : p.getX();
}
@Override
public double getY(int path) {
IPath p = getPath(path);
return p == null ? 0 : p.getY();
}
@Override
public double getZ(int path) {
IPath p = getPath(path);
return p == null ? 0 : p.getZ();
}
@Override
public void setX(int path, double x) {
IPath p = getPath(path);
if (p != null) p.setX(x);
}
@Override
public void setY(int path, double y) {
IPath p = getPath(path);
if (p != null) p.setY(y);
}
@Override
public void setZ(int path, double z) {
IPath p = getPath(path);
if (p != null) p.setZ(z);
}
public IPath getPath(int path) {
if (path < 0 || path >= trajectory.size()) return null;
return trajectory.get(path);
}
@Override
public void setPath(int path, IPos pos) {
setPath(path, pos, 0);
}
@Override
public void setPath(int path, IPos pos, int delay) {
setPath(path, pos.getX(), pos.getY(), pos.getZ(), delay);
}
@Override
public void setPath(int path, double x, double y, double z) {
setPath(path, x, y, z, 0);
}
@Override
public void setPath(int path, double x, double y, double z, int delay) {
Path newPath = new Path(
NpcAPI.Instance().getIPos(x, y, z),
delay
);
while (trajectory.size() <= path) {
trajectory.add(null);
}
trajectory.set(path, newPath);
}
@Override
public IPath createPath(IPos pos) {
return new Path(pos, 0);
}
@Override
public IPath createPath(IPos pos, int delay) {
return new Path(pos, delay);
}
@Override
public IPath createPath(double x, double y, double z) {
return createPath(x, y, z, 0);
}
@Override
public IPath createPath(double x, double y, double z, int delay) {
return new Path(NpcAPI.Instance().getIPos(x, y, z), delay);
}
@Override
public void forEach(BiConsumer<Integer, IPath> lambda) {
for (int i = 0; i < trajectory.size(); i++) {
lambda.accept(i, trajectory.get(i));
}
}
public int size() {
return trajectory.size();
}
public boolean isEmpty() {
return trajectory.isEmpty();
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setInteger("currentPath", currentPath);
for (int i = 0; i < trajectory.size(); i++) {
Path path = trajectory.get(i);
NBTTagCompound pathNbt = new NBTTagCompound();
path.writeNBT(pathNbt);
nbt.setTag("Path_" + i, pathNbt);
}
}
public void readNBT(NBTTagCompound nbt) {
this.currentPath = nbt.hasKey("currentPath") ? nbt.getInteger("currentPath") : 0;
int i = 0;
while (nbt.hasKey("Path_" + i, Constants.NBT.TAG_COMPOUND)) {
NBTTagCompound pathNbt = nbt.getCompoundTag("Path_" + i);
Path path = (Path) createPath(0, 0, 0);
path.readNBT(pathNbt);
trajectory.add(path);
i++;
}
}
public static class Path implements IEnergyTrajectoryData.IPath{
public IPos pos;
public int delayTicks;
public boolean concluded;
public Path(IPos pos, int delayTicks) {
this.pos = pos;
this.delayTicks = delayTicks;
}
@Override
public IPos getPos() {
return pos;
}
@Override
public void setPos(IPos pos) {
this.pos = pos;
}
@Override
public int getDelay() {
return delayTicks;
}
@Override
public void setDelay(int delayTicks) {
this.delayTicks = delayTicks;
}
@Override
public boolean isConcluded() {
return concluded;
}
@Override
public void setConcluded(boolean concluded) {
this.concluded = concluded;
}
@Override
public double getX() {
return pos.getX();
}
@Override
public void setX(double x) {
this.pos = NpcAPI.Instance().getIPos(x, getY(), getZ());
}
@Override
public double getY() {
return pos.getY();
}
@Override
public void setY(double y) {
this.pos = NpcAPI.Instance().getIPos(getX(), y, getZ());
}
@Override
public double getZ() {
return pos.getZ();
}
@Override
public void setZ(double z) {
this.pos = NpcAPI.Instance().getIPos(pos.getX(), pos.getY(), z);
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setInteger("delay", delayTicks);
nbt.setBoolean("concluded", concluded);
nbt.setDouble("X", getX());
nbt.setDouble("Y", getY());
nbt.setDouble("Z", getZ());
}
public void readNBT(NBTTagCompound nbt) {
this.delayTicks = nbt.hasKey("delay") ? nbt.getInteger("delay") : 0;
this.concluded = nbt.hasKey("concluded") && nbt.getBoolean("concluded");
double x = nbt.getDouble("X");
double y = nbt.getDouble("Y");
double z = nbt.getDouble("Z");
this.pos = NpcAPI.Instance().getIPos(x, y, z);
}
}
}
@@ -0,0 +1,64 @@
package kamkeel.npcs.controllers.data.ability.data;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityAction;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import java.util.List;
/**
* Common interface for all combat actions that can be assigned to NPCs or players.
* Implemented by {@link Ability} (individual ability) and {@link ChainedAbility} (sequence).
* <p>
* This enables unified storage via {@link AbilityAction}, unified weighted random selection,
* and unified eligibility checking without instanceof or separate codepaths.
*/
public interface IAbilityAction {
String getName();
boolean isEnabled();
void setEnabled(boolean enabled);
int getWeight();
int getCooldownTicks();
float getMinRange();
float getMaxRange();
UserType getAllowedBy();
List<AbilityCondition> getConditions();
boolean checkConditions(EntityLivingBase caster, EntityLivingBase target);
boolean checkConditionsForPlayer(EntityLivingBase caster);
/**
* Check if this action is available for the given player.
* Used for visibility filtering (HUD, selection) and activation gating.
* Returns true by default (no requirement).
*/
default boolean isAvailableFor(EntityPlayer player) {
return true;
}
/**
* Whether this action is a chained ability (sequence of abilities) vs an individual ability.
*/
boolean isChain();
/**
* Create a deep copy of this action.
*/
IAbilityAction deepCopyAction();
NBTTagCompound writeNBT(boolean saveScripts);
}
@@ -1,6 +1,8 @@
package kamkeel.npcs.controllers.data.ability.data;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.enums.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyAnchorData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import net.minecraft.nbt.NBTTagCompound;
/**
@@ -24,10 +26,12 @@ public class ProjectileData {
* If colorOverride is true, returns a copy with overridden inner/outer colors.
*/
public EnergyDisplayData resolveDisplay(EnergyDisplayData primary) {
if (!colorOverride) return primary;
// Always return a copy so entity mutations never bleed back into the ability template.
EnergyDisplayData resolved = primary.copy();
resolved.innerColor = this.innerColor;
resolved.outerColor = this.outerColor;
if (colorOverride) {
resolved.innerColor = this.innerColor;
resolved.outerColor = this.outerColor;
}
return resolved;
}
@@ -44,8 +48,8 @@ public class ProjectileData {
anchor.readNBT(nbt);
colorOverride = nbt.getBoolean("colorOverride");
if (colorOverride) {
innerColor = nbt.hasKey("overrideInnerColor") ? nbt.getInteger("overrideInnerColor") : 0xFFFFFF;
outerColor = nbt.hasKey("overrideOuterColor") ? nbt.getInteger("overrideOuterColor") : 0x8888FF;
innerColor = nbt.getInteger("overrideInnerColor");
outerColor = nbt.getInteger("overrideOuterColor");
}
}
@@ -0,0 +1,112 @@
package kamkeel.npcs.controllers.data.ability.data.effect;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.controllers.CustomEffectController;
import noppes.npcs.util.ValueUtil;
/**
* Represents a custom effect reference that can be applied by abilities.
* Wraps the CustomEffectController system (player-only effects with script callbacks).
*/
public class AbilityCustomEffect {
private int effectId = -1;
private int durationTicks = 60;
private byte level = 0;
private int index = 0;
public AbilityCustomEffect() {
}
public AbilityCustomEffect(int effectId, int durationTicks, byte level) {
this.effectId = effectId;
this.durationTicks = Math.max(1, durationTicks);
this.level = (byte) Math.max(0, Math.min(10, level));
this.index = 0;
}
public AbilityCustomEffect(int effectId, int durationTicks, byte level, int index) {
this(effectId, durationTicks, level);
this.index = index;
}
public AbilityCustomEffect copy() {
return new AbilityCustomEffect(effectId, durationTicks, level, index);
}
/**
* Applies this custom effect to the given entity.
* Only works on players (CustomEffectController is player-only).
*/
public void apply(EntityLivingBase entity) {
if (entity == null || effectId <= 0) return;
if (entity instanceof EntityPlayer) {
CustomEffectController.getInstance().applyEffect(
(EntityPlayer) entity, effectId, durationTicks, level, index);
}
}
public boolean isValid() {
return effectId > 0;
}
// ── NBT ──
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setInteger("effectId", effectId);
nbt.setInteger("duration", durationTicks);
nbt.setByte("level", level);
nbt.setInteger("index", index);
return nbt;
}
public void readNBT(NBTTagCompound nbt) {
this.effectId = nbt.getInteger("effectId");
this.durationTicks = nbt.getInteger("duration");
this.level = nbt.getByte("level");
this.index = nbt.getInteger("index");
}
public static AbilityCustomEffect fromNBT(NBTTagCompound nbt) {
AbilityCustomEffect e = new AbilityCustomEffect();
e.readNBT(nbt);
return e;
}
// ── Getters/Setters ──
public int getEffectId() {
return effectId;
}
public void setEffectId(int effectId) {
this.effectId = effectId;
}
public int getDurationTicks() {
return durationTicks;
}
public void setDurationTicks(int durationTicks) {
this.durationTicks = Math.max(1, durationTicks);
}
public byte getLevel() {
return level;
}
public void setLevel(byte level) {
this.level = (byte) ValueUtil.clamp(level, 0, 10);
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = Math.max(0, index);
}
}
@@ -0,0 +1,132 @@
package kamkeel.npcs.controllers.data.ability.data.effect;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.PotionEffect;
import noppes.npcs.constants.EnumPotionType;
/**
* Represents a configurable potion effect that can be applied by abilities.
* Uses the unified EnumPotionType enum shared across melee, ranged, and ability systems.
*/
public class AbilityPotionEffect {
private EnumPotionType type = EnumPotionType.None;
private int manualPotionId = 0;
private int durationTicks = 60;
private int amplifier = 0; // 0-255 (Manual), 0-10 (preset)
public AbilityPotionEffect() {
}
public AbilityPotionEffect(EnumPotionType type, int durationTicks, int amplifier) {
this.type = type;
this.durationTicks = Math.max(1, durationTicks);
this.amplifier = Math.max(0, Math.min(255, amplifier));
}
/**
* Creates a copy of this effect.
*/
public AbilityPotionEffect copy() {
AbilityPotionEffect copy = new AbilityPotionEffect(type, durationTicks, amplifier);
copy.manualPotionId = this.manualPotionId;
return copy;
}
/**
* Applies this effect to the given entity.
* Does nothing if type is None. Validates potion IDs before applying.
*/
public void apply(EntityLivingBase entity) {
if (entity == null || type == EnumPotionType.None) {
return;
}
if (type == EnumPotionType.Fire) {
entity.setFire(Math.max(1, durationTicks / 20));
return;
}
int potionId = type.getResolvedPotionId(manualPotionId);
if (EnumPotionType.isValidPotionId(potionId)) {
entity.addPotionEffect(new PotionEffect(potionId, durationTicks, amplifier));
}
}
/**
* Writes this effect to NBT.
*/
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setInteger("potionType", type.ordinal());
nbt.setInteger("duration", durationTicks);
nbt.setInteger("amplifier", amplifier);
if (type == EnumPotionType.Manual) {
nbt.setInteger("manualPotionId", manualPotionId);
}
return nbt;
}
/**
* Reads this effect from NBT.
*/
public void readNBT(NBTTagCompound nbt) {
this.type = EnumPotionType.fromOrdinal(nbt.getInteger("potionType"));
this.durationTicks = nbt.getInteger("duration");
this.amplifier = nbt.getInteger("amplifier");
if (type == EnumPotionType.Manual) {
this.manualPotionId = nbt.getInteger("manualPotionId");
}
}
/**
* Creates an AbilityPotionEffect from NBT.
*/
public static AbilityPotionEffect fromNBT(NBTTagCompound nbt) {
AbilityPotionEffect effect = new AbilityPotionEffect();
effect.readNBT(nbt);
return effect;
}
// Getters & Setters
public EnumPotionType getType() {
return type;
}
public void setType(EnumPotionType type) {
this.type = type != null ? type : EnumPotionType.None;
}
public int getManualPotionId() {
return manualPotionId;
}
public void setManualPotionId(int manualPotionId) {
this.manualPotionId = Math.max(0, manualPotionId);
}
public int getDurationTicks() {
return durationTicks;
}
public void setDurationTicks(int durationTicks) {
this.durationTicks = Math.max(1, durationTicks);
}
public int getAmplifier() {
return amplifier;
}
public void setAmplifier(int amplifier) {
this.amplifier = Math.max(0, Math.min(255, amplifier));
}
/**
* Returns true if this effect is configured (not None).
*/
public boolean isValid() {
return type != EnumPotionType.None;
}
}
@@ -0,0 +1,42 @@
package kamkeel.npcs.controllers.data.ability.data.effect;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
/**
* Interface for mod-registered effect actions that can be applied by AbilityEffect.
* <p>
* Mods register implementations via {@code Register.EffectActions} or
* {@code AbilityController.Instance.registerEffectAction()}.
* Each action has a unique ID, display name, and apply logic.
* Actions can optionally provide custom configuration fields for the GUI.
*/
public interface IEffectAction {
/**
* Unique identifier, e.g. "dbc:kiRestore", "mymod:buffSpeed".
*/
String getId();
/**
* Localized display name shown in the GUI selector.
*/
String getDisplayName();
/**
* Apply this action to a target entity.
* Called once per affected entity during ability execution.
*
* @param caster The entity that used the ability
* @param target The entity being affected
* @param config Action-specific configuration NBT (from GUI)
*/
void apply(EntityLivingBase caster, EntityLivingBase target, NBTTagCompound config);
/**
* Create default configuration NBT for a new instance of this action.
*/
default NBTTagCompound createDefaultConfig() {
return new NBTTagCompound();
}
}
@@ -1,6 +1,6 @@
package kamkeel.npcs.controllers.data.ability.data;
package kamkeel.npcs.controllers.data.ability.data.energy;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.enums.AnchorPoint;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyAnchorData;
@@ -9,6 +9,7 @@ public class EnergyAnchorData implements IEnergyAnchorData {
public float anchorOffsetX = 0;
public float anchorOffsetY = 0;
public float anchorOffsetZ = 0;
public boolean launchFromAnchor = false;
public EnergyAnchorData() {
}
@@ -83,21 +84,35 @@ public class EnergyAnchorData implements IEnergyAnchorData {
this.anchorOffsetZ = anchorOffsetZ;
}
@Override
public boolean getLaunchFromAnchor() {
return launchFromAnchor;
}
@Override
public void setLaunchFromAnchor(boolean launchFromAnchor) {
this.launchFromAnchor = launchFromAnchor;
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setInteger("anchorPoint", anchorPoint.ordinal());
nbt.setFloat("anchorOffsetX", anchorOffsetX);
nbt.setFloat("anchorOffsetY", anchorOffsetY);
nbt.setFloat("anchorOffsetZ", anchorOffsetZ);
nbt.setBoolean("launchFromAnchor", launchFromAnchor);
}
public void readNBT(NBTTagCompound nbt) {
this.anchorPoint = nbt.hasKey("anchorPoint") ? AnchorPoint.fromOrdinal(nbt.getInteger("anchorPoint")) : AnchorPoint.FRONT;
this.anchorOffsetX = nbt.hasKey("anchorOffsetX") ? nbt.getFloat("anchorOffsetX") : 0;
this.anchorOffsetY = nbt.hasKey("anchorOffsetY") ? nbt.getFloat("anchorOffsetY") : 0;
this.anchorOffsetZ = nbt.hasKey("anchorOffsetZ") ? nbt.getFloat("anchorOffsetZ") : 0;
this.anchorPoint = AnchorPoint.fromOrdinal(nbt.getInteger("anchorPoint"));
this.anchorOffsetX = nbt.getFloat("anchorOffsetX");
this.anchorOffsetY = nbt.getFloat("anchorOffsetY");
this.anchorOffsetZ = nbt.getFloat("anchorOffsetZ");
this.launchFromAnchor = nbt.getBoolean("launchFromAnchor");
}
public EnergyAnchorData copy() {
return new EnergyAnchorData(anchorPoint, anchorOffsetX, anchorOffsetY, anchorOffsetZ);
EnergyAnchorData copy = new EnergyAnchorData(anchorPoint, anchorOffsetX, anchorOffsetY, anchorOffsetZ);
copy.launchFromAnchor = this.launchFromAnchor;
return copy;
}
}
@@ -0,0 +1,234 @@
package kamkeel.npcs.controllers.data.ability.data.energy;
import net.minecraft.nbt.NBTTagCompound;
import java.util.HashMap;
import java.util.Map;
/**
* Groups barrier properties shared by energy barrier abilities (Dome, Wall, Shield).
* Handles health/durability, duration, and per-projectile-type damage multipliers.
*
* Properties:
* - Solid: Hard wall — entities cannot pass through the barrier boundary (either direction)
* - Knockback: Repulsion field — entities near the surface get pushed away
* - Absorbing: Caster's incoming damage is redirected to the barrier
* - Allows Melee: Barrier can be hit by melee attacks (punching)
*/
public class EnergyBarrierData {
public float maxHealth = 100.0f;
public boolean useHealth = true;
public int durationTicks = 200;
public boolean useDuration = true;
public float defaultMultiplier = 1.0f;
// Solid: entities cannot pass through the barrier boundary
public boolean solid = false;
// Knockback: repulsion field pushing entities away from surface
public boolean knockbackEnabled = false;
public float knockbackStrength = 1.0f;
// Absorbing: caster's damage is redirected to the barrier
public boolean absorbing = false;
// Absorb radius: max distance from barrier's current position for absorption to work
// -1 = no radius limit (absorb regardless of distance)
// 0 = use barrier's own extent as the radius (dome radius, panel half-size, etc.)
// positive = owner must be within this many blocks of the barrier entity
public float absorbRadius = 0.0f;
// Melee: barrier can be hit by melee attacks
public boolean meleeEnabled = false;
public float meleeDamageMultiplier = 1.0f;
// Reflection: rebound projectiles that fail to break the barrier
public boolean reflect = false;
public float reflectStrengthPct = 25.0f;
public boolean targetOwner = false;
/**
* Per-projectile-type damage multipliers.
* Key is the ability typeId (e.g., "ability.cnpc.orb", "ability.cnpc.beam").
* Value is the multiplier applied to damage dealt to this barrier.
*/
private Map<String, Float> damageMultipliers = new HashMap<>();
public EnergyBarrierData() {
}
public EnergyBarrierData(float maxHealth, boolean useHealth, int durationTicks, boolean useDuration) {
this.maxHealth = maxHealth;
this.useHealth = useHealth;
this.durationTicks = durationTicks;
this.useDuration = useDuration;
}
// ==================== MULTIPLIER METHODS ====================
public float getMultiplier(String abilityTypeId) {
Float mult = damageMultipliers.get(abilityTypeId);
return mult != null ? mult : defaultMultiplier;
}
public void setMultiplier(String abilityTypeId, float multiplier) {
damageMultipliers.put(abilityTypeId, multiplier);
}
public void removeMultiplier(String abilityTypeId) {
damageMultipliers.remove(abilityTypeId);
}
public Map<String, Float> getDamageMultipliers() {
return damageMultipliers;
}
public void setDamageMultipliers(Map<String, Float> multipliers) {
this.damageMultipliers = multipliers != null ? multipliers : new HashMap<>();
}
// ==================== GETTERS & SETTERS ====================
public float getMaxHealth() {
return maxHealth;
}
public void setMaxHealth(float maxHealth) {
this.maxHealth = Math.max(1.0f, maxHealth);
}
public boolean isUseHealth() {
return useHealth;
}
public void setUseHealth(boolean useHealth) {
this.useHealth = useHealth;
}
public int getDurationTicks() {
return durationTicks;
}
public void setDurationTicks(int durationTicks) {
this.durationTicks = Math.max(1, durationTicks);
}
public boolean isUseDuration() {
return useDuration;
}
public void setUseDuration(boolean useDuration) {
this.useDuration = useDuration;
}
public float getDefaultMultiplier() {
return defaultMultiplier;
}
public void setDefaultMultiplier(float defaultMultiplier) {
this.defaultMultiplier = defaultMultiplier;
}
public boolean isReflect() {
return reflect;
}
public void setReflect(boolean reflect) {
this.reflect = reflect;
}
public float getReflectStrengthPct() {
return reflectStrengthPct;
}
public void setReflectStrengthPct(float reflectStrengthPct) {
this.reflectStrengthPct = Math.max(0.0f, Math.min(100.0f, reflectStrengthPct));
}
public boolean isTargetOwner() {
return targetOwner;
}
public void setTargetOwner(boolean targetOwner) {
this.targetOwner = targetOwner;
}
public float getAbsorbRadius() {
return absorbRadius;
}
public void setAbsorbRadius(float absorbRadius) {
this.absorbRadius = absorbRadius;
}
// ==================== NBT ====================
public void writeNBT(NBTTagCompound nbt) {
nbt.setFloat("barrierMaxHealth", maxHealth);
nbt.setBoolean("barrierUseHealth", useHealth);
nbt.setInteger("barrierDuration", durationTicks);
nbt.setBoolean("barrierUseDuration", useDuration);
nbt.setFloat("barrierDefaultMult", defaultMultiplier);
nbt.setBoolean("barrierSolid", solid);
nbt.setBoolean("barrierKnockback", knockbackEnabled);
nbt.setFloat("barrierKnockbackStr", knockbackStrength);
nbt.setBoolean("barrierAbsorbing", absorbing);
nbt.setFloat("barrierAbsorbRadius", absorbRadius);
nbt.setBoolean("barrierMelee", meleeEnabled);
nbt.setFloat("barrierMeleeMult", meleeDamageMultiplier);
nbt.setBoolean("barrierReflect", reflect);
nbt.setFloat("barrierReflectStrPct", reflectStrengthPct);
nbt.setBoolean("barrierTargetOwner", targetOwner);
NBTTagCompound multNbt = new NBTTagCompound();
for (Map.Entry<String, Float> entry : damageMultipliers.entrySet()) {
multNbt.setFloat(entry.getKey(), entry.getValue());
}
nbt.setTag("barrierMultipliers", multNbt);
}
public void readNBT(NBTTagCompound nbt) {
maxHealth = nbt.hasKey("barrierMaxHealth") ? nbt.getFloat("barrierMaxHealth") : 100.0f;
useHealth = !nbt.hasKey("barrierUseHealth") || nbt.getBoolean("barrierUseHealth");
durationTicks = nbt.hasKey("barrierDuration") ? nbt.getInteger("barrierDuration") : 200;
useDuration = !nbt.hasKey("barrierUseDuration") || nbt.getBoolean("barrierUseDuration");
defaultMultiplier = nbt.hasKey("barrierDefaultMult") ? nbt.getFloat("barrierDefaultMult") : 1.0f;
solid = nbt.hasKey("barrierSolid") && nbt.getBoolean("barrierSolid");
knockbackEnabled = nbt.hasKey("barrierKnockback") && nbt.getBoolean("barrierKnockback");
knockbackStrength = nbt.hasKey("barrierKnockbackStr") ? nbt.getFloat("barrierKnockbackStr") : 1.0f;
absorbing = nbt.hasKey("barrierAbsorbing") && nbt.getBoolean("barrierAbsorbing");
absorbRadius = nbt.hasKey("barrierAbsorbRadius") ? nbt.getFloat("barrierAbsorbRadius") : 0.0f;
meleeEnabled = nbt.hasKey("barrierMelee") && nbt.getBoolean("barrierMelee");
meleeDamageMultiplier = nbt.hasKey("barrierMeleeMult") ? nbt.getFloat("barrierMeleeMult") : 1.0f;
reflect = nbt.hasKey("barrierReflect") && nbt.getBoolean("barrierReflect");
setReflectStrengthPct(nbt.hasKey("barrierReflectStrPct") ? nbt.getFloat("barrierReflectStrPct") : 25.0f);
targetOwner = nbt.hasKey("barrierTargetOwner") && nbt.getBoolean("barrierTargetOwner");
damageMultipliers.clear();
if (nbt.hasKey("barrierMultipliers")) {
NBTTagCompound multNbt = nbt.getCompoundTag("barrierMultipliers");
@SuppressWarnings("unchecked")
java.util.Set<String> keys = multNbt.func_150296_c();
for (String key : keys) {
damageMultipliers.put(key, multNbt.getFloat(key));
}
}
}
public EnergyBarrierData copy() {
EnergyBarrierData copy = new EnergyBarrierData(maxHealth, useHealth, durationTicks, useDuration);
copy.defaultMultiplier = defaultMultiplier;
copy.solid = solid;
copy.knockbackEnabled = knockbackEnabled;
copy.knockbackStrength = knockbackStrength;
copy.absorbing = absorbing;
copy.absorbRadius = absorbRadius;
copy.meleeEnabled = meleeEnabled;
copy.meleeDamageMultiplier = meleeDamageMultiplier;
copy.reflect = reflect;
copy.reflectStrengthPct = reflectStrengthPct;
copy.targetOwner = targetOwner;
copy.damageMultipliers = new HashMap<>(damageMultipliers);
return copy;
}
}
@@ -0,0 +1,83 @@
package kamkeel.npcs.controllers.data.ability.data.energy;
import net.minecraft.nbt.NBTTagCompound;
public class EnergyChargingData {
public int chargeDuration = 60;
public int chargeDelay = 0;
public int maxCharge = 100;
public boolean hasCharge = true;
public boolean chargeWindUpSync = true;
public EnergyChargingData() {
}
public EnergyChargingData(int chargeDuration, int chargeDelay, int maxCharge, boolean hasCharge, boolean chargeWindUpSync) {
this.chargeDuration = chargeDuration;
this.chargeDelay = chargeDelay;
this.maxCharge = maxCharge;
this.hasCharge = hasCharge;
this.chargeWindUpSync = chargeWindUpSync;
}
public boolean hasCharge() {
return hasCharge;
}
public void setHasCharge(boolean hasCharge) {
this.hasCharge = hasCharge;
}
public boolean isChargeWindUpSync() {
return chargeWindUpSync;
}
public void setChargeWindUpSync(boolean chargeWindUpSync) {
this.chargeWindUpSync = chargeWindUpSync;
}
public int getChargeDuration() {
return chargeDuration;
}
public void setChargeDuration(int chargeDuration) {
this.chargeDuration = chargeDuration;
}
public int getChargeDelay() {
return chargeDelay;
}
public void setChargeDelay(int chargeDelay) {
this.chargeDelay = chargeDelay;
}
public int getMaxCharge() {
return maxCharge;
}
public void setMaxCharge(int maxCharge) {
this.maxCharge = Math.max(0, maxCharge);
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setInteger("chargeDuration", chargeDuration);
nbt.setInteger("chargeDelay", chargeDelay);
nbt.setInteger("maxCharge", maxCharge);
nbt.setBoolean("hasCharge", hasCharge);
nbt.setBoolean("chargeWindUpSync", chargeWindUpSync);
}
public void readNBT(NBTTagCompound nbt) {
chargeDuration = nbt.hasKey("chargeDuration") ? nbt.getInteger("chargeDuration") : 60;
chargeDelay = nbt.hasKey("chargeDelay") ? nbt.getInteger("chargeDelay") : 0;
maxCharge = nbt.hasKey("maxCharge") ? nbt.getInteger("maxCharge") : 100;
hasCharge = !nbt.hasKey("hasCharge") || nbt.getBoolean("hasCharge");
chargeWindUpSync = !nbt.hasKey("chargeWindUpSync") || nbt.getBoolean("chargeWindUpSync");
}
public EnergyChargingData copy() {
return new EnergyChargingData(chargeDuration, chargeDelay, maxCharge, hasCharge, chargeWindUpSync);
}
}
@@ -0,0 +1,176 @@
package kamkeel.npcs.controllers.data.ability.data.energy;
import kamkeel.npcs.controllers.data.ability.enums.HitType;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyCombatData;
/**
* Groups combat properties shared by energy projectile abilities.
* Used as a parameter object for entity constructors and ability configuration.
*/
public class EnergyCombatData implements IEnergyCombatData {
public static final float MAX_EXPLOSION_RADIUS = 15.0f;
public static final int DEFAULT_MAX_HITS = 5;
public static final int MAX_HITS = 200;
public float damage = 7.0f;
public float knockback = 1.0f;
public float knockbackUp = 0.1f;
public boolean explosive = false;
public float explosionRadius = 3.0f;
public float explosionDamageFalloff = 0.5f;
public HitType hitType = HitType.SINGLE;
public int multiHitDelayTicks = 5;
public int maxHits = DEFAULT_MAX_HITS;
public EnergyCombatData() {
}
public EnergyCombatData(float damage, float knockback, float knockbackUp,
boolean explosive, float explosionRadius, float explosionDamageFalloff,
HitType hitType, int multiHitDelay) {
this(damage, knockback, knockbackUp, explosive, explosionRadius, explosionDamageFalloff, hitType, multiHitDelay, DEFAULT_MAX_HITS);
}
public EnergyCombatData(float damage, float knockback, float knockbackUp,
boolean explosive, float explosionRadius, float explosionDamageFalloff,
HitType hitType, int multiHitDelay, int maxHits) {
this.damage = damage;
this.knockback = knockback;
this.knockbackUp = knockbackUp;
this.explosive = explosive;
this.explosionRadius = clampExplosionRadius(explosionRadius);
this.explosionDamageFalloff = explosionDamageFalloff;
this.hitType = hitType;
this.multiHitDelayTicks = multiHitDelay;
this.maxHits = clampMaxHits(maxHits);
}
public EnergyCombatData(float damage, float knockback, float knockbackUp,
boolean explosive, float explosionRadius, float explosionDamageFalloff) {
this.damage = damage;
this.knockback = knockback;
this.knockbackUp = knockbackUp;
this.explosive = explosive;
this.explosionRadius = clampExplosionRadius(explosionRadius);
this.explosionDamageFalloff = explosionDamageFalloff;
}
@Override
public float getDamage() {
return damage;
}
@Override
public void setDamage(float damage) {
this.damage = damage;
}
@Override
public float getKnockback() {
return knockback;
}
@Override
public void setKnockback(float knockback) {
this.knockback = knockback;
}
@Override
public float getKnockbackUp() {
return knockbackUp;
}
@Override
public void setKnockbackUp(float knockbackUp) {
this.knockbackUp = knockbackUp;
}
@Override
public boolean isExplosive() {
return explosive;
}
@Override
public void setExplosive(boolean explosive) {
this.explosive = explosive;
}
@Override
public float getExplosionRadius() {
return explosionRadius;
}
@Override
public void setExplosionRadius(float explosionRadius) {
this.explosionRadius = clampExplosionRadius(explosionRadius);
}
@Override
public float getExplosionDamageFalloff() {
return explosionDamageFalloff;
}
@Override
public void setExplosionDamageFalloff(float explosionDamageFalloff) {
this.explosionDamageFalloff = explosionDamageFalloff;
}
public int getMaxHits() {
return maxHits;
}
public void setMaxHits(int maxHits) {
this.maxHits = clampMaxHits(maxHits);
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setFloat("damage", damage);
nbt.setFloat("knockback", knockback);
nbt.setFloat("knockbackUp", knockbackUp);
nbt.setBoolean("explosive", explosive);
nbt.setFloat("explosionRadius", explosionRadius);
nbt.setFloat("explosionDamageFalloff", explosionDamageFalloff);
nbt.setInteger("hitType", hitType.ordinal());
nbt.setInteger("multiHitDelayTicks", multiHitDelayTicks);
nbt.setInteger("maxHits", maxHits);
}
public void readNBT(NBTTagCompound nbt) {
damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 7.0f;
knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 1.0f;
knockbackUp = nbt.hasKey("knockbackUp") ? nbt.getFloat("knockbackUp") : 0.1f;
explosive = nbt.hasKey("explosive") && nbt.getBoolean("explosive");
explosionRadius = nbt.hasKey("explosionRadius") ? nbt.getFloat("explosionRadius") : 3.0f;
explosionDamageFalloff = nbt.hasKey("explosionDamageFalloff") ? nbt.getFloat("explosionDamageFalloff") : 0.5f;
hitType = HitType.fromOrdinal(nbt.hasKey("hitType") ? nbt.getInteger("hitType") : 0);
multiHitDelayTicks = nbt.hasKey("multiHitDelayTicks") ? nbt.getInteger("multiHitDelayTicks") : 5;
maxHits = nbt.hasKey("maxHits") ? nbt.getInteger("maxHits") : DEFAULT_MAX_HITS;
// Sanitize
if (Float.isNaN(damage) || Float.isInfinite(damage)) damage = 7.0f;
if (Float.isNaN(knockback) || Float.isInfinite(knockback) || knockback < 0) knockback = 1.0f;
if (Float.isNaN(explosionRadius) || Float.isInfinite(explosionRadius) || explosionRadius < 0) explosionRadius = 3.0f;
explosionRadius = clampExplosionRadius(explosionRadius);
if (multiHitDelayTicks < 1) multiHitDelayTicks = 1;
maxHits = clampMaxHits(maxHits);
}
private static float clampExplosionRadius(float explosionRadius) {
if (Float.isNaN(explosionRadius) || Float.isInfinite(explosionRadius)) return 0.0f;
return Math.max(0.0f, Math.min(MAX_EXPLOSION_RADIUS, explosionRadius));
}
private static int clampMaxHits(int maxHits) {
return Math.max(1, Math.min(MAX_HITS, maxHits));
}
public EnergyCombatData copy() {
EnergyCombatData copy = new EnergyCombatData(damage, knockback, knockbackUp,
explosive, explosionRadius, explosionDamageFalloff);
copy.hitType = hitType;
copy.multiHitDelayTicks = multiHitDelayTicks;
copy.maxHits = maxHits;
return copy;
}
}
@@ -1,4 +1,4 @@
package kamkeel.npcs.controllers.data.ability.data;
package kamkeel.npcs.controllers.data.ability.data.energy;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyDisplayData;
@@ -13,9 +13,11 @@ public class EnergyDisplayData implements IEnergyDisplayData {
public boolean outerColorEnabled = true;
public float outerColorWidth = 0.4f;
public float outerColorAlpha = 0.5f;
public float innerAlpha = 1.0f;
public float rotationSpeed = 4.0f;
public EnergyDisplayData() {}
public EnergyDisplayData() {
}
public EnergyDisplayData(int innerColor, int outerColor) {
this.innerColor = innerColor;
@@ -32,6 +34,12 @@ public class EnergyDisplayData implements IEnergyDisplayData {
this.rotationSpeed = rotationSpeed;
}
public EnergyDisplayData(int innerColor, int outerColor, boolean outerColorEnabled,
float outerColorWidth, float outerColorAlpha, float innerAlpha, float rotationSpeed) {
this(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, rotationSpeed);
this.innerAlpha = innerAlpha;
}
@Override
public int getInnerColor() {
return innerColor;
@@ -82,6 +90,16 @@ public class EnergyDisplayData implements IEnergyDisplayData {
this.outerColorAlpha = outerColorAlpha;
}
@Override
public float getInnerAlpha() {
return innerAlpha;
}
@Override
public void setInnerAlpha(float innerAlpha) {
this.innerAlpha = innerAlpha;
}
@Override
public float getRotationSpeed() {
return rotationSpeed;
@@ -98,6 +116,7 @@ public class EnergyDisplayData implements IEnergyDisplayData {
nbt.setBoolean("outerColorEnabled", outerColorEnabled);
nbt.setFloat("outerColorWidth", outerColorWidth);
nbt.setFloat("outerColorAlpha", outerColorAlpha);
nbt.setFloat("innerAlpha", innerAlpha);
nbt.setFloat("rotationSpeed", rotationSpeed);
}
@@ -107,10 +126,12 @@ public class EnergyDisplayData implements IEnergyDisplayData {
outerColorEnabled = !nbt.hasKey("outerColorEnabled") || nbt.getBoolean("outerColorEnabled");
outerColorWidth = nbt.hasKey("outerColorWidth") ? nbt.getFloat("outerColorWidth") : 0.4f;
outerColorAlpha = nbt.hasKey("outerColorAlpha") ? nbt.getFloat("outerColorAlpha") : 0.5f;
innerAlpha = nbt.hasKey("innerAlpha") ? nbt.getFloat("innerAlpha") : 1.0f;
rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f;
}
public EnergyDisplayData copy() {
return new EnergyDisplayData(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, rotationSpeed);
EnergyDisplayData copy = new EnergyDisplayData(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, innerAlpha, rotationSpeed);
return copy;
}
}
@@ -1,4 +1,4 @@
package kamkeel.npcs.controllers.data.ability.data;
package kamkeel.npcs.controllers.data.ability.data.energy;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyHomingData;
@@ -14,7 +14,8 @@ public class EnergyHomingData implements IEnergyHomingData {
public float homingStrength = 0.15f;
public float homingRange = 20.0f;
public EnergyHomingData() {}
public EnergyHomingData() {
}
public EnergyHomingData(float speed, boolean homing, float homingStrength, float homingRange) {
this.speed = speed;
@@ -30,7 +31,7 @@ public class EnergyHomingData implements IEnergyHomingData {
@Override
public void setSpeed(float speed) {
this.speed = speed;
this.speed = Math.max(0.01f, speed);
}
@Override
@@ -75,6 +76,9 @@ public class EnergyHomingData implements IEnergyHomingData {
homing = !nbt.hasKey("homing") || nbt.getBoolean("homing");
homingStrength = nbt.hasKey("homingStrength") ? nbt.getFloat("homingStrength") : 0.15f;
homingRange = nbt.hasKey("homingRange") ? nbt.getFloat("homingRange") : 20.0f;
// Sanitize speed to prevent stuck projectiles
if (Float.isNaN(speed) || Float.isInfinite(speed) || speed <= 0) speed = 0.5f;
}
public EnergyHomingData copy() {
@@ -1,4 +1,4 @@
package kamkeel.npcs.controllers.data.ability.data;
package kamkeel.npcs.controllers.data.ability.data.energy;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyLifespanData;
@@ -8,10 +8,11 @@ import noppes.npcs.api.ability.data.IEnergyLifespanData;
* Used as a parameter object for entity constructors and ability configuration.
*/
public class EnergyLifespanData implements IEnergyLifespanData {
public float maxDistance = 30.0f;
public float maxDistance = 150.0f;
public int maxLifetime = 200;
public EnergyLifespanData() {}
public EnergyLifespanData() {
}
public EnergyLifespanData(float maxDistance, int maxLifetime) {
this.maxDistance = maxDistance;
@@ -25,7 +26,7 @@ public class EnergyLifespanData implements IEnergyLifespanData {
@Override
public void setMaxDistance(float maxDistance) {
this.maxDistance = maxDistance;
this.maxDistance = Float.isNaN(maxDistance) || maxDistance <= 0 ? 150.0f : maxDistance;
}
@Override
@@ -35,7 +36,7 @@ public class EnergyLifespanData implements IEnergyLifespanData {
@Override
public void setMaxLifetime(int maxLifetime) {
this.maxLifetime = maxLifetime;
this.maxLifetime = maxLifetime <= 0 ? 200 : maxLifetime;
}
public void writeNBT(NBTTagCompound nbt) {
@@ -44,8 +45,12 @@ public class EnergyLifespanData implements IEnergyLifespanData {
}
public void readNBT(NBTTagCompound nbt) {
maxDistance = nbt.hasKey("maxDistance") ? nbt.getFloat("maxDistance") : 30.0f;
maxLifetime = nbt.hasKey("maxLifetime") ? nbt.getInteger("maxLifetime") : 200;
maxDistance = nbt.getFloat("maxDistance");
maxLifetime = nbt.getInteger("maxLifetime");
// Sanitize: ensure minimum values so entities don't die instantly or live forever
if (Float.isNaN(maxDistance) || Float.isInfinite(maxDistance) || maxDistance <= 0) maxDistance = 150.0f;
if (maxLifetime <= 0) maxLifetime = 200;
}
public EnergyLifespanData copy() {
@@ -1,4 +1,4 @@
package kamkeel.npcs.controllers.data.ability.data;
package kamkeel.npcs.controllers.data.ability.data.energy;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyLightningData;
@@ -13,7 +13,8 @@ public class EnergyLightningData implements IEnergyLightningData {
public float lightningRadius = 0.5f;
public int lightningFadeTime = 6;
public EnergyLightningData() {}
public EnergyLightningData() {
}
public EnergyLightningData(boolean lightningEffect, float lightningDensity,
float lightningRadius, int lightningFadeTime) {
@@ -60,7 +61,7 @@ public class EnergyLightningData implements IEnergyLightningData {
@Override
public void setLightningFadeTime(int lightningFadeTime) {
this.lightningFadeTime = lightningFadeTime;
this.lightningFadeTime = Math.max(1, lightningFadeTime);
}
public void writeNBT(NBTTagCompound nbt) {
@@ -75,6 +76,7 @@ public class EnergyLightningData implements IEnergyLightningData {
lightningDensity = nbt.hasKey("lightningDensity") ? nbt.getFloat("lightningDensity") : 0.15f;
lightningRadius = nbt.hasKey("lightningRadius") ? nbt.getFloat("lightningRadius") : 0.5f;
lightningFadeTime = nbt.hasKey("lightningFadeTime") ? nbt.getInteger("lightningFadeTime") : 6;
if (lightningFadeTime <= 0) lightningFadeTime = 1;
}
public EnergyLightningData copy() {
@@ -0,0 +1,125 @@
package kamkeel.npcs.controllers.data.ability.data.energy;
import net.minecraft.nbt.NBTTagCompound;
/**
* Groups panel-specific properties for energy wall/shield abilities.
* Handles dimensions, positioning, and launch behavior.
*/
public class EnergyPanelData {
public float panelWidth = 3.0f;
public float panelHeight = 3.0f;
public float heightOffset = 0.0f;
public float offsetX = 0.0f;
public float offsetZ = 0.0f;
// Launch properties (Wall only)
public boolean launching = false;
public float launchSpeed = 0.5f;
public float launchDamage = 8.0f;
public float launchKnockback = 2.0f;
public EnergyPanelData() {
}
public EnergyPanelData(float panelWidth, float panelHeight, float heightOffset) {
this.panelWidth = panelWidth;
this.panelHeight = panelHeight;
this.heightOffset = heightOffset;
}
// ==================== GETTERS & SETTERS ====================
public float getPanelWidth() {
return panelWidth;
}
public void setPanelWidth(float panelWidth) {
this.panelWidth = Math.max(0.5f, panelWidth);
}
public float getPanelHeight() {
return panelHeight;
}
public void setPanelHeight(float panelHeight) {
this.panelHeight = Math.max(0.5f, panelHeight);
}
public float getHeightOffset() {
return heightOffset;
}
public void setHeightOffset(float heightOffset) {
this.heightOffset = heightOffset;
}
public boolean isLaunching() {
return launching;
}
public void setLaunching(boolean launching) {
this.launching = launching;
}
public float getLaunchSpeed() {
return launchSpeed;
}
public void setLaunchSpeed(float launchSpeed) {
this.launchSpeed = Math.max(0.1f, launchSpeed);
}
public float getLaunchDamage() {
return launchDamage;
}
public void setLaunchDamage(float launchDamage) {
this.launchDamage = Math.max(0, launchDamage);
}
public float getLaunchKnockback() {
return launchKnockback;
}
public void setLaunchKnockback(float launchKnockback) {
this.launchKnockback = Math.max(0, launchKnockback);
}
// ==================== NBT ====================
public void writeNBT(NBTTagCompound nbt) {
nbt.setFloat("panelWidth", panelWidth);
nbt.setFloat("panelHeight", panelHeight);
nbt.setFloat("panelHeightOffset", heightOffset);
nbt.setFloat("panelOffsetX", offsetX);
nbt.setFloat("panelOffsetZ", offsetZ);
nbt.setBoolean("panelLaunching", launching);
nbt.setFloat("panelLaunchSpeed", launchSpeed);
nbt.setFloat("panelLaunchDamage", launchDamage);
nbt.setFloat("panelLaunchKnockback", launchKnockback);
}
public void readNBT(NBTTagCompound nbt) {
panelWidth = nbt.hasKey("panelWidth") ? nbt.getFloat("panelWidth") : 3.0f;
panelHeight = nbt.hasKey("panelHeight") ? nbt.getFloat("panelHeight") : 3.0f;
heightOffset = nbt.hasKey("panelHeightOffset") ? nbt.getFloat("panelHeightOffset") : 0.0f;
offsetX = nbt.hasKey("panelOffsetX") ? nbt.getFloat("panelOffsetX") : 0.0f;
offsetZ = nbt.hasKey("panelOffsetZ") ? nbt.getFloat("panelOffsetZ") : 0.0f;
launching = nbt.hasKey("panelLaunching") && nbt.getBoolean("panelLaunching");
launchSpeed = nbt.hasKey("panelLaunchSpeed") ? nbt.getFloat("panelLaunchSpeed") : 0.5f;
launchDamage = nbt.hasKey("panelLaunchDamage") ? nbt.getFloat("panelLaunchDamage") : 8.0f;
launchKnockback = nbt.hasKey("panelLaunchKnockback") ? nbt.getFloat("panelLaunchKnockback") : 2.0f;
}
public EnergyPanelData copy() {
EnergyPanelData copy = new EnergyPanelData(panelWidth, panelHeight, heightOffset);
copy.offsetX = offsetX;
copy.offsetZ = offsetZ;
copy.launching = launching;
copy.launchSpeed = launchSpeed;
copy.launchDamage = launchDamage;
copy.launchKnockback = launchKnockback;
return copy;
}
}
@@ -0,0 +1,87 @@
package kamkeel.npcs.controllers.data.ability.data.entry;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.data.effect.IEffectAction;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
/**
* A configured instance of an {@link IEffectAction} stored on an ability.
* Holds the action ID and its configuration NBT.
*/
public class AbilityEffectActionEntry {
private String actionId = "";
private NBTTagCompound config = new NBTTagCompound();
public AbilityEffectActionEntry() {
}
public AbilityEffectActionEntry(String actionId) {
this.actionId = actionId != null ? actionId : "";
IEffectAction action = AbilityController.Instance.getEffectAction(this.actionId);
if (action != null) {
this.config = action.createDefaultConfig();
}
}
public AbilityEffectActionEntry copy() {
AbilityEffectActionEntry copy = new AbilityEffectActionEntry();
copy.actionId = this.actionId;
copy.config = (NBTTagCompound) this.config.copy();
return copy;
}
/**
* Apply this action to a target entity.
*/
public void apply(EntityLivingBase caster, EntityLivingBase target) {
if (actionId.isEmpty()) return;
IEffectAction action = AbilityController.Instance.getEffectAction(actionId);
if (action != null) {
action.apply(caster, target, config);
}
}
public boolean isValid() {
return !actionId.isEmpty() && AbilityController.Instance.getEffectAction(actionId) != null;
}
// ── NBT ──
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("actionId", actionId);
nbt.setTag("config", config);
return nbt;
}
public void readNBT(NBTTagCompound nbt) {
this.actionId = nbt.getString("actionId");
this.config = nbt.hasKey("config") ? nbt.getCompoundTag("config") : new NBTTagCompound();
}
public static AbilityEffectActionEntry fromNBT(NBTTagCompound nbt) {
AbilityEffectActionEntry entry = new AbilityEffectActionEntry();
entry.readNBT(nbt);
return entry;
}
// ── Getters/Setters ──
public String getActionId() {
return actionId;
}
public void setActionId(String actionId) {
this.actionId = actionId != null ? actionId : "";
}
public NBTTagCompound getConfig() {
return config;
}
public void setConfig(NBTTagCompound config) {
this.config = config != null ? config : new NBTTagCompound();
}
}
@@ -0,0 +1,42 @@
package kamkeel.npcs.controllers.data.ability.data.entry;
import kamkeel.npcs.controllers.data.ability.Ability;
/**
* Tracks the state of a single active toggle for an entity.
* Stored in AbstractDataAbilities.activeToggles map.
* <p>
* State is 1-based: state 1 = first ON state, state 2 = second, etc.
* State 0 means OFF (entry should not exist in the map).
*/
public class AbilityToggleEntry {
private final Ability ability;
private int tickCount;
private int state;
public AbilityToggleEntry(Ability ability, int state) {
this.ability = ability;
this.tickCount = 0;
this.state = Math.max(1, state);
}
public Ability getAbility() {
return ability;
}
public int getTickCount() {
return tickCount;
}
public void incrementTick() {
tickCount++;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = Math.max(1, state);
}
}
@@ -0,0 +1,223 @@
package kamkeel.npcs.controllers.data.ability.data.entry;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import net.minecraft.nbt.NBTTagCompound;
import java.util.UUID;
/**
* A single entry in a {@link ChainedAbility}, representing one ability
* to execute in sequence along with its delay configuration.
* <p>
* Entries can be either a <b>reference</b> to a registered ability (by name/key)
* or an <b>inline</b> ability that is owned directly by this entry.
*/
public class ChainedAbilityEntry {
public enum EntryType {REFERENCE, INLINE}
private EntryType entryType = EntryType.REFERENCE;
/**
* Reference key (built-in name or custom ability name). Used when entryType == REFERENCE.
*/
private String abilityReference = "";
/**
* Inline ability data. Used when entryType == INLINE.
*/
private Ability inlineAbility = null;
/**
* Delay in ticks BEFORE this ability starts (after previous entry completes).
*/
private int delayTicks = 0;
/**
* Whether this entry should execute concurrently (alongside the previous ability)
* rather than sequentially. Only takes effect if the resolved ability isConcurrentCapable().
*/
private boolean concurrentEnabled = true;
public ChainedAbilityEntry() {
}
public ChainedAbilityEntry(String abilityReference, int delayTicks) {
this.entryType = EntryType.REFERENCE;
this.abilityReference = abilityReference != null ? abilityReference : "";
this.delayTicks = Math.max(0, delayTicks);
}
// ═══════════════════════════════════════════════════════════════════
// FACTORY METHODS
// ═══════════════════════════════════════════════════════════════════
public static ChainedAbilityEntry reference(String ref, int delay) {
ChainedAbilityEntry entry = new ChainedAbilityEntry();
entry.entryType = EntryType.REFERENCE;
entry.abilityReference = ref != null ? ref : "";
entry.delayTicks = Math.max(0, delay);
return entry;
}
public static ChainedAbilityEntry inline(Ability ability, int delay) {
ChainedAbilityEntry entry = new ChainedAbilityEntry();
entry.entryType = EntryType.INLINE;
entry.inlineAbility = ability;
entry.delayTicks = Math.max(0, delay);
return entry;
}
// ═══════════════════════════════════════════════════════════════════
// TYPE QUERIES
// ═══════════════════════════════════════════════════════════════════
public EntryType getEntryType() {
return entryType;
}
public boolean isInline() {
return entryType == EntryType.INLINE;
}
public boolean isReference() {
return entryType == EntryType.REFERENCE;
}
// ═══════════════════════════════════════════════════════════════════
// GETTERS / SETTERS
// ═══════════════════════════════════════════════════════════════════
public String getAbilityReference() {
return abilityReference;
}
public void setAbilityReference(String abilityReference) {
this.abilityReference = abilityReference != null ? abilityReference : "";
}
public Ability getInlineAbility() {
return inlineAbility;
}
public void setInlineAbility(Ability ability) {
this.inlineAbility = ability;
}
public int getDelayTicks() {
return delayTicks;
}
public void setDelayTicks(int delayTicks) {
this.delayTicks = Math.max(0, delayTicks);
}
public boolean isConcurrentEnabled() {
return concurrentEnabled;
}
public void setConcurrentEnabled(boolean concurrentEnabled) {
this.concurrentEnabled = concurrentEnabled;
}
// ═══════════════════════════════════════════════════════════════════
// RESOLUTION
// ═══════════════════════════════════════════════════════════════════
/**
* Resolve this entry to an Ability instance.
* Inline entries return their ability directly.
* Reference entries resolve via AbilityController.
*/
public Ability resolve() {
if (entryType == EntryType.INLINE) {
return inlineAbility;
}
AbilityController ctrl = AbilityController.Instance;
if (ctrl == null) return null;
return ctrl.resolveAbility(abilityReference);
}
// ═══════════════════════════════════════════════════════════════════
// CONVERSION
// ═══════════════════════════════════════════════════════════════════
/**
* Convert a reference entry to inline by cloning the resolved ability.
* Returns false if already inline or the reference cannot be resolved.
*/
public boolean convertToInline() {
if (entryType != EntryType.REFERENCE) return false;
AbilityController ctrl = AbilityController.Instance;
if (ctrl == null) return false;
Ability resolved = ctrl.resolveAbility(abilityReference);
if (resolved == null) return false;
NBTTagCompound nbt = resolved.writeNBT(true);
nbt.setString("id", UUID.randomUUID().toString());
inlineAbility = ctrl.fromNBT(nbt);
entryType = EntryType.INLINE;
abilityReference = "";
return true;
}
// ═══════════════════════════════════════════════════════════════════
// DEEP COPY
// ═══════════════════════════════════════════════════════════════════
/**
* Create a deep copy of this entry. Inline abilities are copied via NBT round-trip.
*/
public ChainedAbilityEntry deepCopy() {
ChainedAbilityEntry copy = new ChainedAbilityEntry();
copy.entryType = this.entryType;
copy.abilityReference = this.abilityReference;
copy.delayTicks = this.delayTicks;
copy.concurrentEnabled = this.concurrentEnabled;
if (this.inlineAbility != null) {
copy.inlineAbility = AbilityController.Instance.fromNBT(this.inlineAbility.writeNBT(true));
}
return copy;
}
// ═══════════════════════════════════════════════════════════════════
// NBT
// ═══════════════════════════════════════════════════════════════════
public NBTTagCompound writeNBT(boolean saveScripts) {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setInteger("Delay", delayTicks);
nbt.setBoolean("Concurrent", concurrentEnabled);
if (entryType == EntryType.INLINE && inlineAbility != null) {
nbt.setTag("InlineAbility", inlineAbility.writeNBT(saveScripts));
} else {
nbt.setString("Reference", abilityReference);
}
return nbt;
}
public static ChainedAbilityEntry fromNBT(NBTTagCompound nbt) {
if (nbt == null) return null;
ChainedAbilityEntry entry = new ChainedAbilityEntry();
entry.delayTicks = Math.max(0, nbt.getInteger("Delay"));
entry.concurrentEnabled = nbt.hasKey("Concurrent") ? nbt.getBoolean("Concurrent") : true;
if (nbt.hasKey("InlineAbility")) {
NBTTagCompound abilityNBT = nbt.getCompoundTag("InlineAbility");
entry.entryType = EntryType.INLINE;
entry.inlineAbility = AbilityController.Instance != null
? AbilityController.Instance.fromNBT(abilityNBT) : null;
} else {
entry.entryType = EntryType.REFERENCE;
entry.abilityReference = nbt.getString("Reference");
}
return entry;
}
}
@@ -1,4 +1,4 @@
package kamkeel.npcs.controllers.data.ability;
package kamkeel.npcs.controllers.data.ability.enums;
public enum AbilityPhase {
IDLE, // Not executing
@@ -1,4 +1,4 @@
package kamkeel.npcs.controllers.data.ability;
package kamkeel.npcs.controllers.data.ability.enums;
/**
* Defines anchor points for ability charging effects.
@@ -10,7 +10,8 @@ public enum AnchorPoint {
RIGHT_HAND("Right Hand"), // Right arm/hand position
LEFT_HAND("Left Hand"), // Left arm/hand position
ABOVE_HEAD("Above Head"), // Above the entity
CHEST("Chest"); // Chest level, centered
CHEST("Chest"), // Chest level, centered
EYE("Eye"); // Eye level, centered
private final String displayName;
@@ -49,13 +50,22 @@ public enum AnchorPoint {
@Override
public String toString() {
switch (this) {
case FRONT: return "ability.anchor.front";
case CENTER: return "ability.anchor.center";
case RIGHT_HAND: return "ability.anchor.rightHand";
case LEFT_HAND: return "ability.anchor.leftHand";
case ABOVE_HEAD: return "ability.anchor.aboveHead";
case CHEST: return "ability.anchor.chest";
default: return name();
case FRONT:
return "ability.anchor.front";
case CENTER:
return "ability.anchor.center";
case RIGHT_HAND:
return "ability.anchor.rightHand";
case LEFT_HAND:
return "ability.anchor.leftHand";
case ABOVE_HEAD:
return "ability.anchor.aboveHead";
case CHEST:
return "ability.anchor.chest";
case EYE:
return "ability.anchor.eye";
default:
return name();
}
}
}
@@ -0,0 +1,32 @@
package kamkeel.npcs.controllers.data.ability.enums;
/**
* Shared hit behavior for energy projectiles.
*/
public enum HitType {
SINGLE,
PIERCE,
MULTI;
public static HitType fromOrdinal(int ordinal) {
HitType[] values = values();
if (ordinal >= 0 && ordinal < values.length) {
return values[ordinal];
}
return SINGLE;
}
@Override
public String toString() {
switch (this) {
case SINGLE:
return "ability.hitType.single";
case PIERCE:
return "ability.hitType.pierce";
case MULTI:
return "ability.hitType.multi";
default:
return name();
}
}
}
@@ -0,0 +1,66 @@
package kamkeel.npcs.controllers.data.ability.enums;
/**
* Defines when a caster is invulnerable while an ability is executing.
*/
public enum InvulnerableMode {
NONE,
WINDUP,
ACTIVE,
BOTH;
public boolean invulnerableDuringWindup() {
return this == WINDUP || this == BOTH;
}
public boolean invulnerableDuringActive() {
return this == ACTIVE || this == BOTH;
}
/**
* Treat BURST_DELAY as windup-like for interruption/damage immunity checks.
*/
public boolean isInvulnerableInPhase(AbilityPhase phase) {
if (phase == null) return false;
switch (phase) {
case WINDUP:
case BURST_DELAY:
return invulnerableDuringWindup();
case ACTIVE:
return invulnerableDuringActive();
default:
return false;
}
}
public String getDisplayKey() {
switch (this) {
case WINDUP:
return "ability.invulnerable.windup";
case ACTIVE:
return "ability.invulnerable.active";
case BOTH:
return "ability.invulnerable.both";
case NONE:
default:
return "ability.invulnerable.none";
}
}
public static String[] getDisplayKeys() {
return new String[]{
"ability.invulnerable.none",
"ability.invulnerable.windup",
"ability.invulnerable.active",
"ability.invulnerable.both"
};
}
public static InvulnerableMode fromOrdinal(int ordinal) {
InvulnerableMode[] values = values();
if (ordinal >= 0 && ordinal < values.length) {
return values[ordinal];
}
return NONE;
}
}
@@ -1,9 +1,9 @@
package kamkeel.npcs.controllers.data.ability;
package kamkeel.npcs.controllers.data.ability.enums;
/**
* Defines when an ability locks NPC movement and rotation.
*/
public enum LockMovementType {
public enum LockMode {
/**
* No movement lock - NPC can move freely during both phases.
*/
@@ -71,10 +71,10 @@ public enum LockMovementType {
}
/**
* Get LockMovementType from ordinal, with fallback to WINDUP.
* Get LockMode from ordinal, with fallback to WINDUP.
*/
public static LockMovementType fromOrdinal(int ordinal) {
LockMovementType[] values = values();
public static LockMode fromOrdinal(int ordinal) {
LockMode[] values = values();
if (ordinal >= 0 && ordinal < values.length) {
return values[ordinal];
}
@@ -1,8 +1,8 @@
package kamkeel.npcs.controllers.data.ability;
package kamkeel.npcs.controllers.data.ability.enums;
/**
* Defines what happens to NPC rotation during ability phases.
* Used with a LockMovementType to control WHEN it applies.
* Used with a LockMode to control WHEN it applies.
*/
public enum RotationMode {
/**
@@ -0,0 +1,32 @@
package kamkeel.npcs.controllers.data.ability.enums;
/**
* Filter for determining which entities an ability should affect in AOE mode.
*/
public enum TargetFilter {
ALLIES,
ENEMIES,
ALL;
@Override
public String toString() {
switch (this) {
case ALLIES:
return "ability.targetFilter.allies";
case ENEMIES:
return "ability.targetFilter.enemies";
case ALL:
return "ability.targetFilter.all";
default:
return name();
}
}
public static TargetFilter fromString(String name) {
try {
return valueOf(name);
} catch (Exception e) {
return ALLIES;
}
}
}
@@ -1,4 +1,4 @@
package kamkeel.npcs.controllers.data.ability;
package kamkeel.npcs.controllers.data.ability.enums;
/**
* Defines how an ability selects its target(s).
@@ -27,11 +27,16 @@ public enum TargetingMode {
@Override
public String toString() {
switch (this) {
case AGGRO_TARGET: return "ability.target.aggro_target";
case SELF: return "ability.target.self";
case AOE_SELF: return "ability.target.aoe_self";
case AOE_TARGET: return "ability.target.aoe_target";
default: return name();
case AGGRO_TARGET:
return "ability.target.aggro_target";
case SELF:
return "ability.target.self";
case AOE_SELF:
return "ability.target.aoe_self";
case AOE_TARGET:
return "ability.target.aoe_target";
default:
return name();
}
}
}
@@ -1,4 +1,4 @@
package kamkeel.npcs.controllers.data.ability;
package kamkeel.npcs.controllers.data.ability.enums;
/**
* Defines which entity types can use an ability.
@@ -6,7 +6,8 @@ package kamkeel.npcs.controllers.data.ability;
public enum UserType {
NPC_ONLY,
PLAYER_ONLY,
BOTH;
BOTH,
NONE;
public boolean allowsNpc() {
return this == NPC_ONLY || this == BOTH;
@@ -0,0 +1,149 @@
package kamkeel.npcs.controllers.data.ability.extender;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import net.minecraft.entity.EntityLivingBase;
/**
* General-purpose extension point for abilities. Multiple extenders can be registered.
* Covers lifecycle hooks (start/tick/complete) and damage handling.
* <p>
* All methods have no-op defaults so extenders only override what they need.
*/
public interface IAbilityExtender {
/**
* Called before an ability starts executing.
* Return false to cancel the ability (e.g., insufficient resources).
*
* @param ability The ability about to start
* @param caster The entity executing the ability (NPC or Player)
* @param target The target entity (may be null for player self-cast)
* @return true to allow, false to cancel
*/
default boolean onAbilityStart(Ability ability, EntityLivingBase caster, EntityLivingBase target) {
return true;
}
/**
* Called each tick during ability execution.
* Return false to interrupt the ability (e.g., resource depleted).
*
* @param ability The executing ability
* @param caster The entity executing the ability
* @param target The target entity (may be null)
* @param phase The current ability phase (WINDUP, ACTIVE, DAZED, BURST_DELAY)
* @param tick The current tick within the phase
* @return true to continue, false to interrupt
*/
default boolean onAbilityTick(Ability ability, EntityLivingBase caster, EntityLivingBase target,
AbilityPhase phase, int tick) {
return true;
}
/**
* Called when an ability completes (normally or via interruption).
*
* @param ability The completed ability
* @param caster The entity that was executing the ability
* @param target The target entity (may be null)
* @param interrupted true if the ability was interrupted, false if it completed normally
*/
default void onAbilityComplete(Ability ability, EntityLivingBase caster, EntityLivingBase target,
boolean interrupted) {
}
/**
* Called when an ability deals damage, AFTER script events but BEFORE default attackEntityFrom.
* Return true to handle the damage (skips default damage application).
* <p>
* Chain of responsibility: extenders are called in registration order.
* The first extender returning true claims the damage; remaining extenders are skipped.
*
* @param ability The ability dealing damage
* @param caster The entity executing the ability
* @param target The entity being hit
* @param damage The damage amount (after script event modifications)
* @param knockback The horizontal knockback
* @param knockbackUp The vertical knockback
* @param knockbackDirX The X component of knockback direction
* @param knockbackDirZ The Z component of knockback direction
* @param damageMultiplier Accumulated proportional damage multiplier (0.0-1.0).
* 1.0 means full damage (no reduction). Extenders that recalculate
* damage from stats should multiply by this value.
* @return true if damage was handled (skip default), false to pass to next extender or default
*/
default boolean onAbilityDamage(Ability ability, EntityLivingBase caster, EntityLivingBase target,
float damage, float knockback, float knockbackUp,
double knockbackDirX, double knockbackDirZ,
float damageMultiplier) {
return false;
}
/**
* Called to modify outgoing projectile damage before it hits a barrier or is used in other contexts.
* Unlike onAbilityDamage (chain of responsibility), this is cumulative — all extenders apply their
* modifications in sequence, each receiving the previous extender's output.
*
* @param ability The source ability of the projectile
* @param caster The entity that fired the projectile
* @param baseDamage The base damage from the ability configuration
* @return The modified damage value
*/
default float modifyProjectileDamage(Ability ability, EntityLivingBase caster, float baseDamage) {
return baseDamage;
}
/**
* Called when a barrier entity is about to be created, allowing extenders to modify its max health.
* Cumulative: all extenders apply in sequence, each receiving the previous output.
*
* @param ability The barrier ability being executed
* @param caster The entity creating the barrier
* @param baseHealth The base max health from EnergyBarrierData.maxHealth
* @return The modified max health value
*/
default float modifyBarrierHealth(Ability ability, EntityLivingBase caster, float baseHealth) {
return baseHealth;
}
/**
* Called when a barrier entity takes a melee hit, allowing extenders to scale the damage.
* A barrier is a plain Entity, so no LivingHurtEvent fires for it and an extender has no
* other opportunity to scale melee against it the way it scales {@link #modifyBarrierHealth}.
* Cumulative: all extenders apply in sequence, each receiving the previous output.
*
* @param barrier The barrier being hit
* @param attacker The entity dealing the hit
* @param baseDamage The damage after the barrier's own melee multiplier
* @return The modified damage value
*/
default float modifyBarrierMeleeDamage(EntityEnergyBarrier barrier, EntityLivingBase attacker, float baseDamage) {
return baseDamage;
}
/**
* Called when an ability is about to heal an entity.
* Return true to handle the healing (skip default entity.heal()).
* Chain of responsibility: first returning true wins.
*
* @param ability The ability performing the heal
* @param caster The entity casting the ability
* @param target The entity being healed
* @param healAmount The heal amount calculated by the ability
* @return true if healing was handled (skip default), false to pass to next extender or default
*/
default boolean onAbilityHeal(Ability ability, EntityLivingBase caster, EntityLivingBase target, float healAmount) {
return false;
}
default Boolean onCheckCondition(AbilityCondition condition, EntityLivingBase caster, EntityLivingBase target) {
return null;
}
default Boolean onCheckConditionForPlayer(AbilityCondition condition, EntityLivingBase player) {
return null;
}
}
@@ -2,9 +2,14 @@ package kamkeel.npcs.controllers.data.ability.gui;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.data.effect.AbilityCustomEffect;
import kamkeel.npcs.controllers.data.ability.data.entry.AbilityEffectActionEntry;
import kamkeel.npcs.controllers.data.ability.data.effect.AbilityPotionEffect;
import kamkeel.npcs.controllers.data.ability.data.effect.IEffectAction;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.advanced.SubGuiCustomEffectSelect;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.builder.FieldType;
import noppes.npcs.client.gui.builder.GuiFieldBuilder;
@@ -12,23 +17,37 @@ import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.constants.EnumPotionType;
import noppes.npcs.controllers.CustomEffectController;
import noppes.npcs.controllers.data.CustomEffect;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Ability-specific extension of {@link GuiFieldBuilder} that handles
* the EFFECTS_LIST field type.
* the EFFECTS_LIST, CUSTOM_EFFECTS_LIST, and EFFECT_ACTIONS_LIST field types.
*/
@SideOnly(Side.CLIENT)
public class AbilityFieldBuilder extends GuiFieldBuilder {
// Effects list metadata: widgetId -> [effectIndex, action]
// action: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add
// Unified metadata: widgetId -> [index, action]
// EFFECTS_LIST actions: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add, 5=manualId(text)
// CUSTOM_EFFECTS_LIST actions: 0=effectName, 1=duration(text), 2=level, 3=delete, 4=add
// EFFECT_ACTIONS_LIST actions: 0=actionSelector, 3=delete, 4=add
private final Map<Integer, int[]> effectWidgetMeta = new HashMap<>();
// Cached sorted custom effect data for GUI selectors
private int[] sortedCustomEffectIds;
private String[] sortedCustomEffectNames;
// Cached effect action data for GUI selectors
private String[] effectActionIds;
private String[] effectActionDisplayNames;
public AbilityFieldBuilder(GuiNPCInterface parent, FontRenderer fontRenderer) {
super(parent, fontRenderer);
}
@@ -36,6 +55,10 @@ public class AbilityFieldBuilder extends GuiFieldBuilder {
@Override
protected int build(List<FieldDef> fields) {
effectWidgetMeta.clear();
sortedCustomEffectIds = null;
sortedCustomEffectNames = null;
effectActionIds = null;
effectActionDisplayNames = null;
return super.build(fields);
}
@@ -44,33 +67,184 @@ public class AbilityFieldBuilder extends GuiFieldBuilder {
if (def.getType() == FieldType.EFFECTS_LIST) {
return renderEffectsList(def, y);
}
if (def.getType() == FieldType.CUSTOM_EFFECTS_LIST) {
return renderCustomEffectsList(def, y);
}
if (def.getType() == FieldType.EFFECT_ACTIONS_LIST) {
return renderEffectActionsList(def, y);
}
return -1; // not handled
}
// ═══════════════════════════════════════════════════════════════════
// POTION EFFECTS LIST (existing)
// ═══════════════════════════════════════════════════════════════════
@SuppressWarnings("unchecked")
private int renderEffectsList(FieldDef def, int y) {
// Section header
y += 3;
sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55));
y += 15;
List<AbilityEffect> effects = (List<AbilityEffect>) def.getValue();
List<AbilityPotionEffect> effects = (List<AbilityPotionEffect>) def.getValue();
if (effects == null) effects = new ArrayList<>();
String[] typeNames = AbilityEffect.EffectType.getLangKeys();
String[] typeNames = EnumPotionType.getLangKeysNoNone();
String[] ampValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
for (int e = 0; e < effects.size() && e < 5; e++) {
AbilityEffect effect = effects.get(e);
AbilityPotionEffect effect = effects.get(e);
// Type selector button
int typeIdx = effect.getType().ordinal();
GuiNpcButton typeBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, typeNames, typeIdx);
int typeIdx = effect.getType().ordinal() - 1;
GuiNpcButton typeBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, typeNames, Math.max(0, typeIdx));
sw.addButton(typeBtn);
buttonFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{e, 0});
widgetId++;
GuiNpcTextField durField = new GuiNpcTextField(widgetId, parent, fontRenderer,
colLLabel + 104, y, 50, 20, String.valueOf(effect.getDurationTicks()));
durField.setIntegersOnly();
durField.setMinMaxDefault(1, 12000, 60);
sw.addTextField(durField);
textFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{e, 1});
widgetId++;
if (effect.getType() != EnumPotionType.Fire) {
if (effect.getType() == EnumPotionType.Manual) {
GuiNpcTextField ampField = new GuiNpcTextField(widgetId, parent, fontRenderer,
colLLabel + 158, y, 40, 20, String.valueOf(effect.getAmplifier()));
ampField.setIntegersOnly();
ampField.setMinMaxDefault(0, 255, 0);
sw.addTextField(ampField);
textFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{e, 2});
widgetId++;
} else {
GuiNpcButton ampBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, ampValues, effect.getAmplifier());
sw.addButton(ampBtn);
buttonFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{e, 2});
widgetId++;
}
} else {
widgetId++;
}
GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X");
sw.addButton(delBtn);
clearFieldMap.put(clearId, def);
effectWidgetMeta.put(clearId, new int[]{e, 3});
clearId++;
y += rowHeight;
if (effect.getType() == EnumPotionType.Manual) {
sw.addLabel(new GuiNpcLabel(labelId++, "effect.potionid", colLLabel, y + 5, 0xFFFFFF));
GuiNpcTextField idField = new GuiNpcTextField(widgetId, parent, fontRenderer,
colLLabel + 80, y, 50, 20, String.valueOf(effect.getManualPotionId()));
idField.setIntegersOnly();
idField.setMinMaxDefault(0, Integer.MAX_VALUE, 0);
sw.addTextField(idField);
textFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{e, 5});
widgetId++;
y += rowHeight;
}
}
if (effects.size() < 5) {
GuiNpcButton addBtn = new GuiNpcButton(widgetId, colLLabel, y, 50, 20, "gui.add");
sw.addButton(addBtn);
buttonFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{effects.size(), 4});
widgetId++;
clearId++;
y += rowHeight;
}
return y;
}
// ═══════════════════════════════════════════════════════════════════
// CUSTOM EFFECTS LIST
// ═══════════════════════════════════════════════════════════════════
private void ensureCustomEffectCache() {
if (sortedCustomEffectIds != null) return;
HashMap<Integer, CustomEffect> allEffects = CustomEffectController.getInstance().getCustomEffects();
// Sort by name for consistent ordering
TreeMap<String, Integer> nameToId = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
for (CustomEffect ce : allEffects.values()) {
if (ce.getName() != null && !ce.getName().isEmpty()) {
nameToId.put(ce.getName(), ce.id);
}
}
sortedCustomEffectIds = new int[nameToId.size()];
sortedCustomEffectNames = new String[nameToId.size()];
int i = 0;
for (Map.Entry<String, Integer> entry : nameToId.entrySet()) {
sortedCustomEffectIds[i] = entry.getValue();
sortedCustomEffectNames[i] = entry.getKey();
i++;
}
}
private String getCustomEffectName(int effectId, int index) {
HashMap<Integer, CustomEffect> allEffects = CustomEffectController.getInstance().getEffectMap(index);
if (allEffects != null) {
CustomEffect ce = allEffects.get(effectId);
if (ce != null && ce.getName() != null && !ce.getName().isEmpty()) {
return ce.getName();
}
}
// Fallback: check index 0
if (index != 0) {
return getCustomEffectName(effectId, 0);
}
return "?";
}
private boolean hasAnyEffects() {
for (HashMap<Integer, CustomEffect> map : CustomEffectController.getInstance().indexMapper.values()) {
if (map != null && !map.isEmpty()) return true;
}
return false;
}
@SuppressWarnings("unchecked")
private int renderCustomEffectsList(FieldDef def, int y) {
ensureCustomEffectCache();
y += 3;
sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55));
y += 15;
if (!hasAnyEffects()) {
sw.addLabel(new GuiNpcLabel(labelId++, "ability.noCustomEffects", colLLabel, y + 5, 0x888888));
y += rowHeight;
return y;
}
List<AbilityCustomEffect> effects = (List<AbilityCustomEffect>) def.getValue();
if (effects == null) effects = new ArrayList<>();
String[] levelValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
for (int e = 0; e < effects.size() && e < 5; e++) {
AbilityCustomEffect effect = effects.get(e);
// Effect name button — opens SubGui picker
String effectName = getCustomEffectName(effect.getEffectId(), effect.getIndex());
GuiNpcButton nameBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, effectName);
sw.addButton(nameBtn);
buttonFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{e, 0});
widgetId++;
// Duration text field
GuiNpcTextField durField = new GuiNpcTextField(widgetId, parent, fontRenderer,
colLLabel + 104, y, 50, 20, String.valueOf(effect.getDurationTicks()));
@@ -81,9 +255,9 @@ public class AbilityFieldBuilder extends GuiFieldBuilder {
effectWidgetMeta.put(widgetId, new int[]{e, 1});
widgetId++;
// Amplifier selector (0-10)
GuiNpcButton ampBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, ampValues, effect.getAmplifier());
sw.addButton(ampBtn);
// Level selector (0-10)
GuiNpcButton lvlBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, levelValues, effect.getLevel());
sw.addButton(lvlBtn);
buttonFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{e, 2});
widgetId++;
@@ -98,7 +272,6 @@ public class AbilityFieldBuilder extends GuiFieldBuilder {
y += rowHeight;
}
// Add button (if < 5 effects)
if (effects.size() < 5) {
GuiNpcButton addBtn = new GuiNpcButton(widgetId, colLLabel, y, 50, 20, "gui.add");
sw.addButton(addBtn);
@@ -112,6 +285,77 @@ public class AbilityFieldBuilder extends GuiFieldBuilder {
return y;
}
// ═══════════════════════════════════════════════════════════════════
// EFFECT ACTIONS LIST
// ═══════════════════════════════════════════════════════════════════
private void ensureEffectActionCache() {
if (effectActionIds != null) return;
String[] ids = AbilityController.Instance.getEffectActionIds();
effectActionIds = ids;
effectActionDisplayNames = new String[ids.length];
for (int i = 0; i < ids.length; i++) {
IEffectAction action = AbilityController.Instance.getEffectAction(ids[i]);
effectActionDisplayNames[i] = action != null ? action.getDisplayName() : ids[i];
}
}
private int findEffectActionIndex(String actionId) {
ensureEffectActionCache();
for (int i = 0; i < effectActionIds.length; i++) {
if (effectActionIds[i].equals(actionId)) return i;
}
return -1;
}
@SuppressWarnings("unchecked")
private int renderEffectActionsList(FieldDef def, int y) {
ensureEffectActionCache();
if (effectActionIds.length == 0) return y;
y += 3;
sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55));
y += 15;
List<AbilityEffectActionEntry> entries = (List<AbilityEffectActionEntry>) def.getValue();
if (entries == null) entries = new ArrayList<>();
for (int e = 0; e < entries.size() && e < 5; e++) {
AbilityEffectActionEntry entry = entries.get(e);
// Action selector
int selectedIdx = Math.max(0, findEffectActionIndex(entry.getActionId()));
GuiNpcButton actionBtn = new GuiNpcButton(widgetId, colLLabel, y, 180, 20, effectActionDisplayNames, selectedIdx);
sw.addButton(actionBtn);
buttonFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{e, 0});
widgetId++;
// Delete button
GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X");
sw.addButton(delBtn);
clearFieldMap.put(clearId, def);
effectWidgetMeta.put(clearId, new int[]{e, 3});
clearId++;
y += rowHeight;
}
if (entries.size() < 5) {
GuiNpcButton addBtn = new GuiNpcButton(widgetId, colLLabel, y, 50, 20, "gui.add");
sw.addButton(addBtn);
buttonFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{entries.size(), 4});
widgetId++;
clearId++;
y += rowHeight;
}
return y;
}
// ═══════════════════════════════════════════════════════════════════
// EVENT HANDLING OVERRIDES
// ═══════════════════════════════════════════════════════════════════
@@ -119,36 +363,106 @@ public class AbilityFieldBuilder extends GuiFieldBuilder {
@Override
@SuppressWarnings("unchecked")
public boolean handleButtonEvent(int buttonId, GuiButton button) {
// Check effects list buttons via metadata
int[] meta = effectWidgetMeta.get(buttonId);
if (meta != null) {
FieldDef def = buttonFieldMap.get(buttonId);
if (def == null) def = clearFieldMap.get(buttonId);
if (def != null && def.getType() == FieldType.EFFECTS_LIST) {
List<AbilityEffect> effects = (List<AbilityEffect>) def.getValue();
if (effects == null) return false;
int effectIdx = meta[0];
int action = meta[1];
if (def == null) return false;
int idx = meta[0];
int action = meta[1];
// ── Potion Effects ──
if (def.getType() == FieldType.EFFECTS_LIST) {
List<AbilityPotionEffect> effects = (List<AbilityPotionEffect>) def.getValue();
if (effects == null) return false;
switch (action) {
case 0: // Type changed
if (effectIdx < effects.size()) {
effects.get(effectIdx).setType(AbilityEffect.EffectType.fromOrdinal(((GuiNpcButton) button).getValue()));
case 0:
if (idx < effects.size()) {
EnumPotionType oldType = effects.get(idx).getType();
EnumPotionType newType = EnumPotionType.fromIndexNoNone(((GuiNpcButton) button).getValue());
if (oldType == EnumPotionType.Manual && newType != EnumPotionType.Manual) {
effects.get(idx).setAmplifier(0);
}
effects.get(idx).setType(newType);
}
return true;
case 2: // Amp changed
if (effectIdx < effects.size()) {
effects.get(effectIdx).setAmplifier(((GuiNpcButton) button).getValue());
case 2:
if (idx < effects.size())
effects.get(idx).setAmplifier(((GuiNpcButton) button).getValue());
return true;
case 3:
if (idx < effects.size()) effects.remove(idx);
return true;
case 4:
if (effects.size() < 5) effects.add(new AbilityPotionEffect(EnumPotionType.Slowness, 60, 0));
return true;
}
}
// ── Custom Effects ──
if (def.getType() == FieldType.CUSTOM_EFFECTS_LIST) {
List<AbilityCustomEffect> effects = (List<AbilityCustomEffect>) def.getValue();
if (effects == null) return false;
ensureCustomEffectCache();
switch (action) {
case 0: // Open effect picker SubGui
if (idx < effects.size()) {
int currentId = effects.get(idx).getEffectId();
int currentIndex = effects.get(idx).getIndex();
parent.setSubGuiWithResult(new SubGuiCustomEffectSelect(currentId, currentIndex), sub -> {
SubGuiCustomEffectSelect select = (SubGuiCustomEffectSelect) sub;
int selectedId = select.getSelectedEffectId();
if (selectedId >= 0 && idx < effects.size()) {
effects.get(idx).setEffectId(selectedId);
effects.get(idx).setIndex(select.getSelectedIndex());
}
});
}
return true;
case 2: // Level changed
if (idx < effects.size())
effects.get(idx).setLevel((byte) ((GuiNpcButton) button).getValue());
return true;
case 3: // Delete
if (effectIdx < effects.size()) {
effects.remove(effectIdx);
}
if (idx < effects.size()) effects.remove(idx);
return true;
case 4: // Add
if (effects.size() < 5) {
effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 60, 0));
parent.setSubGuiWithResult(new SubGuiCustomEffectSelect(-1), sub -> {
SubGuiCustomEffectSelect select = (SubGuiCustomEffectSelect) sub;
int selectedId = select.getSelectedEffectId();
if (selectedId >= 0 && effects.size() < 5) {
effects.add(new AbilityCustomEffect(selectedId, 60, (byte) 0, select.getSelectedIndex()));
}
});
}
return true;
}
}
// ── Effect Actions ──
if (def.getType() == FieldType.EFFECT_ACTIONS_LIST) {
List<AbilityEffectActionEntry> entries = (List<AbilityEffectActionEntry>) def.getValue();
if (entries == null) return false;
ensureEffectActionCache();
switch (action) {
case 0: // Action selector changed
if (idx < entries.size()) {
int btnVal = ((GuiNpcButton) button).getValue();
if (btnVal >= 0 && btnVal < effectActionIds.length) {
entries.get(idx).setActionId(effectActionIds[btnVal]);
IEffectAction ea = AbilityController.Instance.getEffectAction(effectActionIds[btnVal]);
if (ea != null) entries.get(idx).setConfig(ea.createDefaultConfig());
}
}
return true;
case 3: // Delete
if (idx < entries.size()) entries.remove(idx);
return true;
case 4: // Add
if (entries.size() < 5 && effectActionIds.length > 0) {
entries.add(new AbilityEffectActionEntry(effectActionIds[0]));
}
return true;
}
@@ -162,12 +476,29 @@ public class AbilityFieldBuilder extends GuiFieldBuilder {
@SuppressWarnings("unchecked")
public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) {
int[] meta = effectWidgetMeta.get(textFieldId);
if (meta != null && meta[1] == 1) { // duration field
if (meta != null) {
FieldDef def = textFieldMap.get(textFieldId);
if (def != null && def.getType() == FieldType.EFFECTS_LIST) {
List<AbilityEffect> effects = (List<AbilityEffect>) def.getValue();
if (effects != null && meta[0] < effects.size()) {
effects.get(meta[0]).setDurationTicks(field.getInteger());
if (def == null) return false;
int idx = meta[0];
int action = meta[1];
// ── Potion Effects ──
if (def.getType() == FieldType.EFFECTS_LIST) {
List<AbilityPotionEffect> effects = (List<AbilityPotionEffect>) def.getValue();
if (effects != null && idx < effects.size()) {
if (action == 1) effects.get(idx).setDurationTicks(field.getInteger());
else if (action == 2) effects.get(idx).setAmplifier(field.getInteger());
else if (action == 5) effects.get(idx).setManualPotionId(field.getInteger());
}
return true;
}
// ── Custom Effects ──
if (def.getType() == FieldType.CUSTOM_EFFECTS_LIST) {
List<AbilityCustomEffect> effects = (List<AbilityCustomEffect>) def.getValue();
if (effects != null && idx < effects.size()) {
if (action == 1) effects.get(idx).setDurationTicks(field.getInteger());
}
return true;
}
@@ -176,5 +507,7 @@ public class AbilityFieldBuilder extends GuiFieldBuilder {
return super.handleTextFieldEvent(textFieldId, field);
}
public Map<Integer, int[]> getEffectWidgetMeta() { return effectWidgetMeta; }
public Map<Integer, int[]> getEffectWidgetMeta() {
return effectWidgetMeta;
}
}
@@ -2,7 +2,9 @@ package kamkeel.npcs.controllers.data.ability.gui;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.data.effect.AbilityCustomEffect;
import kamkeel.npcs.controllers.data.ability.data.entry.AbilityEffectActionEntry;
import kamkeel.npcs.controllers.data.ability.data.effect.AbilityPotionEffect;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.builder.FieldType;
@@ -18,10 +20,23 @@ import java.util.function.Supplier;
public class AbilityFieldDefs {
@SuppressWarnings("unchecked")
public static FieldDef effectsListField(String label, Supplier<List<AbilityEffect>> getter, Consumer<List<AbilityEffect>> setter) {
public static FieldDef effectsListField(String label, Supplier<List<AbilityPotionEffect>> getter, Consumer<List<AbilityPotionEffect>> setter) {
return FieldDef.custom(label, FieldType.EFFECTS_LIST,
() -> getter.get(),
v -> setter.accept((List<AbilityEffect>) v));
v -> setter.accept((List<AbilityPotionEffect>) v));
}
@SuppressWarnings("unchecked")
public static FieldDef customEffectsListField(String label, Supplier<List<AbilityCustomEffect>> getter, Consumer<List<AbilityCustomEffect>> setter) {
return FieldDef.custom(label, FieldType.CUSTOM_EFFECTS_LIST,
() -> getter.get(),
v -> setter.accept((List<AbilityCustomEffect>) v));
}
@SuppressWarnings("unchecked")
public static FieldDef effectActionsListField(String label, Supplier<List<AbilityEffectActionEntry>> getter, Consumer<List<AbilityEffectActionEntry>> setter) {
return FieldDef.custom(label, FieldType.EFFECT_ACTIONS_LIST,
() -> getter.get(),
v -> setter.accept((List<AbilityEffectActionEntry>) v));
}
}
@@ -1,4 +1,4 @@
package noppes.npcs.client.gui.util;
package kamkeel.npcs.controllers.data.ability.gui;
import kamkeel.npcs.client.renderer.TelegraphRenderer;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
@@ -11,6 +11,8 @@ import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import noppes.npcs.client.ClientEventHandler;
import noppes.npcs.client.gui.util.GuiNPCInterface2;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.entity.EntityNPCInterface;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
@@ -21,7 +23,7 @@ import java.util.List;
/**
* Base GUI class for ability preview with fixed camera.
*
* <p>
* Key concepts:
* - NPC positioned on left side of preview area
* - NPC faces a fixed direction (NPC_FACING_YAW)
@@ -33,15 +35,23 @@ import java.util.List;
public class GuiAbilityInterface extends GuiNPCInterface2 {
// ==================== FIXED CAMERA SETTINGS ====================
/** Fixed camera zoom level (higher = more zoomed in) */
/**
* Fixed camera zoom level (higher = more zoomed in)
*/
protected static float CAMERA_ZOOM = 45.0f;
/** NPC facing direction - affects anchor points and visual facing */
protected static float NPC_FACING_YAW = 160.0f;
/** Camera pitch (slight downward angle) */
/**
* NPC facing direction - affects anchor points and visual facing
*/
public static float NPC_FACING_YAW = 160.0f;
/**
* Camera pitch (slight downward angle)
*/
protected static float CAMERA_PITCH = 10.0f;
// ==================== VIEWING ROTATION ====================
/** Viewing direction rotation (rotates entire 3D space) */
/**
* Viewing direction rotation (rotates entire 3D space)
*/
protected static float viewRotation = 0.0f;
private GuiNpcButton btnLeft, btnRight;
@@ -49,21 +59,33 @@ public class GuiAbilityInterface extends GuiNPCInterface2 {
// ==================== NPC STATE ====================
public EntityNPCInterface npc;
/** NPC starting position (saved when preview starts, used to track movement) */
/**
* NPC starting position (saved when preview starts, used to track movement)
*/
protected double npcStartX, npcStartY, npcStartZ;
/** Whether we're tracking NPC movement */
/**
* Whether we're tracking NPC movement
*/
protected boolean trackingNpcMovement = false;
/** Entities to render in preview space */
/**
* Entities to render in preview space
*/
protected List<Entity> previewEntities = new ArrayList<>();
/** Current telegraph to render in preview */
/**
* Current telegraph to render in preview
*/
protected TelegraphInstance previewTelegraph;
// ==================== LAYOUT ====================
/** Preview area bounds */
/**
* Preview area bounds
*/
protected int previewX, previewY, previewWidth, previewHeight;
/** NPC render position on screen */
/**
* NPC render position on screen
*/
protected int npcScreenX, npcScreenY;
public int xOffset = 0;
@@ -74,7 +96,7 @@ public class GuiAbilityInterface extends GuiNPCInterface2 {
}
/**
* @param npc The NPC for preview rendering
* @param npc The NPC for preview rendering
* @param hasMenuNpc If false, the top menu tabs (Display, Stats, etc.) are hidden.
* Use false when opened from the global menu without a real NPC.
*/
@@ -99,8 +121,8 @@ public class GuiAbilityInterface extends GuiNPCInterface2 {
previewHeight = 180;
// NPC position: left side of preview, slightly below center
npcScreenX = previewX + (int)(previewWidth * 0.33f) + xOffset;
npcScreenY = previewY + (int)(previewHeight * 0.85f) + yOffset;
npcScreenX = previewX + (int) (previewWidth * 0.33f) + xOffset;
npcScreenY = previewY + (int) (previewHeight * 0.85f) + yOffset;
// Viewing rotation buttons (below preview area)
int btnY = guiTop + 192;
@@ -351,7 +373,7 @@ public class GuiAbilityInterface extends GuiNPCInterface2 {
super.drawBackground();
drawGradientRect(previewX, previewY, previewX + previewWidth, previewY + previewHeight,
0xc0101010, 0xd0101010);
0xc0101010, 0xd0101010);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
@@ -364,8 +386,9 @@ public class GuiAbilityInterface extends GuiNPCInterface2 {
@Override
public void keyTyped(char par1, int par2) {
boolean hadSubGui = hasSubGui();
super.keyTyped(par1, par2);
if (par2 == 1) {
if (par2 == 1 && !hadSubGui) {
close();
}
}
@@ -1,5 +1,6 @@
package kamkeel.npcs.controllers.data.ability;
package kamkeel.npcs.controllers.data.ability.gui;
import kamkeel.npcs.controllers.data.ability.Ability;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.List;
@@ -0,0 +1,26 @@
package kamkeel.npcs.controllers.data.ability.gui;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.List;
/**
* External field definition provider for chained abilities.
* Called during GUI initialization to allow mods to inject custom tabs/fields
* into the chained ability configuration GUI.
* <p>
* Note: Although this interface references FieldDef (client-only), it is safe to
* register on both sides because the generic type is erased at bytecode level.
* The addFieldDefinitions method is only ever called from client-side GUI code.
*/
public interface IChainedAbilityFieldProvider {
/**
* Add field definitions to the chained ability's GUI.
* Fields added here should use .tab() to assign them to a custom tab.
*
* @param chain The chained ability being configured
* @param defs The mutable list of field definitions to add to
*/
void addFieldDefinitions(ChainedAbility chain, List<FieldDef> defs);
}
@@ -1,13 +1,16 @@
package noppes.npcs.client.gui.util;
package kamkeel.npcs.controllers.data.ability.preview;
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.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.PreviewEntityHandler;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import kamkeel.npcs.controllers.data.ability.gui.GuiAbilityInterface;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.controllers.data.AnimationData;
import noppes.npcs.entity.EntityCustomNpc;
@@ -19,10 +22,10 @@ import java.util.List;
/**
* Client-side executor for previewing abilities in the GUI.
*
* <p>
* Uses unified execution: calls the REAL ability methods (onWindUpTick, onExecute, onActiveTick)
* with previewMode=true. Abilities skip damage/effects/sounds when isPreview() returns true.
*
* <p>
* Lifecycle:
* 1. WINDUP phase - real onWindUpTick() called, telegraph shown, entities may spawn
* 2. ACTIVE phase - real onExecute() then onActiveTick() called, physics simulated
@@ -36,8 +39,11 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
private Ability previewAbility;
private EntityNPCInterface previewNpc;
/** Executor's own phase tracking (separate from ability.getPhase()) */
private enum ExecutorPhase { IDLE, WINDUP, ACTIVE, EXTENDED }
/**
* Executor's own phase tracking (separate from ability.getPhase())
*/
private enum ExecutorPhase {IDLE, WINDUP, ACTIVE, EXTENDED, CHAIN_DELAY}
private ExecutorPhase executorPhase = ExecutorPhase.IDLE;
private int currentTick = 0;
@@ -54,11 +60,20 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
// ==================== NPC START POSITION ====================
private double npcStartX, npcStartY, npcStartZ;
private boolean hasStartPosition = false;
// ==================== PREVIEW CONTENT ====================
private TelegraphInstance previewTelegraph;
private List<Entity> previewEntities = new ArrayList<>();
// ==================== CHAIN PREVIEW ====================
private ChainedAbility previewChain;
private List<Ability> chainAbilities;
private List<Integer> chainDelays;
private int chainIndex = -1;
private int chainDelayRemaining = 0;
private boolean chainWindUpAll = true;
// ==================== CALLBACKS ====================
private GuiAbilityInterface parentGui;
@@ -70,27 +85,21 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
}
/**
* Start previewing an ability using unified execution.
* Start previewing a single ability using unified execution.
* Sets previewMode=true on the ability, then calls its real methods.
*/
public void startPreview(Ability ability, EntityNPCInterface npc) {
stop();
this.previewAbility = ability;
this.previewNpc = npc;
this.currentTick = 0;
this.playing = true;
this.paused = false;
this.maxPreviewDuration = ability.getMaxPreviewDuration();
// Save NPC start position for restoring later
this.npcStartX = npc.posX;
this.npcStartY = npc.posY;
this.npcStartZ = npc.posZ;
// Enable preview mode on the ability
ability.setPreviewMode(true);
ability.setPreviewEntityHandler(this);
this.hasStartPosition = true;
// Create invisible fake target NPC for targeting
createFakeTarget(npc);
@@ -100,10 +109,87 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
parentGui.startTrackingMovement();
}
beginAbilityPreview(ability);
}
/**
* Start previewing a chained ability — plays all entries in sequence with delays.
* Each entry is resolved and deep-copied to avoid modifying originals.
*/
public void startChainPreview(ChainedAbility chain, EntityNPCInterface npc) {
stop();
this.previewNpc = npc;
this.playing = true;
this.paused = false;
this.previewChain = chain;
this.chainWindUpAll = chain.isWindUpAll();
// Save NPC start position for restoring later
this.npcStartX = npc.posX;
this.npcStartY = npc.posY;
this.npcStartZ = npc.posZ;
this.hasStartPosition = true;
// Resolve all entries to deep-copied abilities
chainAbilities = new ArrayList<>();
chainDelays = new ArrayList<>();
for (ChainedAbilityEntry entry : chain.getEntries()) {
Ability resolved = entry.resolve();
if (resolved != null && AbilityController.Instance != null) {
Ability copy = AbilityController.Instance.fromNBT(resolved.writeNBT(true));
if (copy != null) {
chainAbilities.add(copy);
chainDelays.add(entry.getDelayTicks());
}
}
}
if (chainAbilities.isEmpty()) {
playing = false;
return;
}
// Create invisible fake target NPC for targeting
createFakeTarget(npc);
// Start tracking NPC movement
if (parentGui != null) {
parentGui.startTrackingMovement();
}
chainIndex = 0;
beginAbilityPreview(chainAbilities.get(0));
}
/**
* Begin previewing a single ability (shared by single and chain preview).
* Cleans up the previous ability if any (for chain advancement).
*/
private void beginAbilityPreview(Ability ability) {
// Clean up previous ability if any (for chain advancement)
if (previewAbility != null) {
previewAbility.cleanup();
previewAbility.setPreviewMode(false);
previewAbility.setPreviewEntityHandler(null);
previewAbility.reset();
}
this.previewAbility = ability;
this.currentTick = 0;
this.maxPreviewDuration = ability.getMaxPreviewDuration();
// Enable preview mode on the ability
ability.setPreviewMode(true);
ability.setPreviewEntityHandler(this);
// Use the ability's real start() method with the fake target
ability.start(fakeTarget);
if (ability.getWindUpTicks() <= 0) {
// Skip windup for non-first chain entries when windUpAll is false
boolean skipWindup = previewChain != null && !chainWindUpAll && chainIndex > 0;
if (ability.getWindUpTicks() <= 0 || skipWindup) {
// No windup — go straight to active
this.executorPhase = ExecutorPhase.ACTIVE;
transitionToActive();
@@ -112,12 +198,12 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
this.executorPhase = ExecutorPhase.WINDUP;
// Create telegraph for preview
previewTelegraph = ability.createTelegraph(npc, fakeTarget);
previewTelegraph = ability.createTelegraph(previewNpc, fakeTarget);
// Start windup animation
Animation windUpAnim = ability.getWindUpAnimation();
if (windUpAnim != null) {
AnimationData data = npc.display.animationData;
AnimationData data = previewNpc.display.animationData;
data.setEnabled(true);
data.setAnimation(windUpAnim);
data.animation.paused = false;
@@ -213,6 +299,13 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
executorPhase = ExecutorPhase.IDLE;
currentTick = 0;
// Clear chain state
previewChain = null;
chainAbilities = null;
chainDelays = null;
chainIndex = -1;
chainDelayRemaining = 0;
previewTelegraph = null;
if (parentGui != null) {
@@ -225,7 +318,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
previewEntities.clear();
// Reset NPC position to start position (undo movement from Slam/Charge/Dash)
if (previewNpc != null && npcStartX != 0 && npcStartY != 0 && npcStartZ != 0) {
if (previewNpc != null && hasStartPosition) {
previewNpc.posX = npcStartX;
previewNpc.posY = npcStartY;
previewNpc.posZ = npcStartZ;
@@ -283,6 +376,9 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
case EXTENDED:
tickExtended();
break;
case CHAIN_DELAY:
tickChainDelay();
break;
default:
break;
}
@@ -290,7 +386,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
private void tickWindup() {
// Call the REAL windup tick method
previewAbility.onWindUpTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick);
previewAbility.onWindUpTick(previewNpc, fakeTarget, currentTick);
if (currentTick >= previewAbility.getWindUpTicks()) {
transitionToActive();
@@ -299,20 +395,28 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
private void tickActive() {
// Call the REAL active tick method
previewAbility.onActiveTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick);
previewAbility.onActiveTick(previewNpc, fakeTarget, currentTick);
// Simulate physics for movement abilities
simulatePhysics();
// Check if the ability signaled completion (phase went to IDLE)
if (previewAbility.getPhase() == AbilityPhase.IDLE) {
transitionToExtended();
if (hasNextChainEntry()) {
transitionToChainDelay();
} else {
transitionToExtended();
}
return;
}
// Safety timeout
if (currentTick >= maxPreviewDuration) {
transitionToExtended();
if (hasNextChainEntry()) {
transitionToChainDelay();
} else {
transitionToExtended();
}
}
}
@@ -323,6 +427,44 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
}
}
// ==================== CHAIN ADVANCEMENT ====================
private boolean hasNextChainEntry() {
return previewChain != null && chainAbilities != null && chainIndex < chainAbilities.size() - 1;
}
private void transitionToChainDelay() {
executorPhase = ExecutorPhase.CHAIN_DELAY;
currentTick = 0;
// Use the NEXT entry's delay
int nextIndex = chainIndex + 1;
chainDelayRemaining = (nextIndex < chainDelays.size()) ? chainDelays.get(nextIndex) : 0;
// Clear current animation
if (previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
data.setAnimation(new Animation());
}
}
private void tickChainDelay() {
if (chainDelayRemaining > 0) {
chainDelayRemaining--;
return;
}
advanceChainEntry();
}
private void advanceChainEntry() {
chainIndex++;
if (chainIndex >= chainAbilities.size()) {
transitionToExtended();
return;
}
beginAbilityPreview(chainAbilities.get(chainIndex));
}
private void transitionToActive() {
executorPhase = ExecutorPhase.ACTIVE;
currentTick = 0;
@@ -330,7 +472,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
previewTelegraph = null;
// Call the REAL onExecute method (fires entities, initiates movement, etc.)
previewAbility.onExecute(previewNpc, fakeTarget, previewNpc.worldObj);
previewAbility.onExecute(previewNpc, fakeTarget);
// Start active animation
Animation activeAnim = previewAbility.getActiveAnimation();
@@ -424,33 +566,73 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
// ==================== GETTERS ====================
public boolean isPlaying() { return playing; }
public boolean isPaused() { return paused; }
public boolean isActive() { return playing || paused; }
public boolean isPlaying() {
return playing;
}
public boolean isPaused() {
return paused;
}
public boolean isActive() {
return playing || paused;
}
public boolean isChainPreview() {
return previewChain != null;
}
public AbilityPhase getPhase() {
switch (executorPhase) {
case WINDUP: return AbilityPhase.WINDUP;
case ACTIVE: return AbilityPhase.ACTIVE;
default: return AbilityPhase.IDLE;
case WINDUP:
return AbilityPhase.WINDUP;
case ACTIVE:
return AbilityPhase.ACTIVE;
default:
return AbilityPhase.IDLE;
}
}
public int getCurrentTick() { return currentTick; }
public TelegraphInstance getTelegraph() { return previewTelegraph; }
public List<Entity> getPreviewEntities() { return previewEntities; }
public Ability getPreviewAbility() { return previewAbility; }
public EntityNPCInterface getPreviewNpc() { return previewNpc; }
public int getCurrentTick() {
return currentTick;
}
public TelegraphInstance getTelegraph() {
return previewTelegraph;
}
public List<Entity> getPreviewEntities() {
return previewEntities;
}
public Ability getPreviewAbility() {
return previewAbility;
}
public EntityNPCInterface getPreviewNpc() {
return previewNpc;
}
public String getStatusString() {
if (!playing && !paused) {
return "Stopped";
} else if (paused) {
return "Paused";
}
String chainPrefix = "";
if (previewChain != null && chainAbilities != null) {
chainPrefix = "Chain " + (chainIndex + 1) + "/" + chainAbilities.size() + " - ";
}
if (paused) {
return chainPrefix + "Paused";
} else if (executorPhase == ExecutorPhase.WINDUP) {
return "Windup: " + currentTick + "/" + (previewAbility != null ? previewAbility.getWindUpTicks() : 0);
return chainPrefix + "Windup: " + currentTick + "/" + (previewAbility != null ? previewAbility.getWindUpTicks() : 0);
} else if (executorPhase == ExecutorPhase.ACTIVE) {
return "Active: " + currentTick + "/" + maxPreviewDuration;
return chainPrefix + "Active: " + currentTick + "/" + maxPreviewDuration;
} else if (executorPhase == ExecutorPhase.EXTENDED) {
return "Extended: " + currentTick + "/" + EXTENDED_DURATION;
return chainPrefix + "Extended: " + currentTick + "/" + EXTENDED_DURATION;
} else if (executorPhase == ExecutorPhase.CHAIN_DELAY) {
return chainPrefix + "Delay: " + chainDelayRemaining;
}
return "";
}
@@ -1,4 +1,4 @@
package kamkeel.npcs.controllers.data.ability;
package kamkeel.npcs.controllers.data.ability.preview;
import net.minecraft.entity.Entity;
@@ -9,5 +9,6 @@ import net.minecraft.entity.Entity;
*/
public interface PreviewEntityHandler {
void onEntitySpawned(Entity entity);
void onEntityRemoved(Entity entity);
}
@@ -1,637 +0,0 @@
package kamkeel.npcs.controllers.data.ability.type;
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.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.RotationMode;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
import kamkeel.npcs.controllers.data.ability.data.*;
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import noppes.npcs.api.ability.type.IAbilityEnergyBeam;
import java.util.Arrays;
import java.util.List;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
/**
* Energy Beam ability: A homing head with a trailing path.
* Supports 1-8 projectiles with shared visuals and per-projectile anchor points.
*/
public class AbilityBeam extends Ability implements IAbilityEnergyBeam {
private static final int MAX_PROJECTILES = 8;
// Beam shape properties (shared)
private float beamWidth = 0.4f;
private float headSize = 0.6f;
// Projectile count and fire stagger
private int projectileCount = 1;
private int fireDelay = 0;
// Shared visual data (all projectiles use these)
private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f);
private EnergyLightningData lightningData = new EnergyLightningData();
private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData();
// Shared combat/movement data
private final EnergyCombatData combatData = new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f);
private final EnergyHomingData homingData = new EnergyHomingData(0.4f, true, 0.1f, 15.0f);
private final EnergyLifespanData lifespanData = new EnergyLifespanData(25.0f, 200);
// Per-projectile data (anchor + optional color override)
private ProjectileData[] projectiles;
// Transient entity state
private transient EntityAbilityBeam[] beamEntities;
public AbilityBeam() {
this.typeId = "ability.cnpc.beam";
this.name = "Beam";
this.targetingMode = TargetingMode.AGGRO_TARGET;
this.maxRange = 20.0f;
this.minRange = 5.0f;
this.cooldownTicks = 0;
this.windUpTicks = 40;
this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE;
this.rotationMode = RotationMode.TRACK;
this.rotationPhase = LockMovementType.WINDUP_AND_ACTIVE;
this.telegraphType = TelegraphType.CIRCLE;
this.showTelegraph = true;
this.windUpAnimationName = "Ability_Beam_Windup";
this.activeAnimationName = "Ability_Beam_Active";
initProjectiles(1);
}
private void initProjectiles(int count) {
this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES));
this.projectiles = new ProjectileData[projectileCount];
for (int i = 0; i < projectileCount; i++) {
projectiles[i] = new ProjectileData(getDefaultAnchor(i));
}
}
private AnchorPoint getDefaultAnchor(int index) {
switch (index) {
case 0: return AnchorPoint.RIGHT_HAND;
case 1: return AnchorPoint.LEFT_HAND;
default: return AnchorPoint.FRONT;
}
}
public void setProjectileCount(int count) {
int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES));
if (newCount == projectileCount) return;
ProjectileData[] oldProjectiles = projectiles;
initProjectiles(newCount);
if (oldProjectiles != null) {
int copyCount = Math.min(oldProjectiles.length, newCount);
for (int i = 0; i < copyCount; i++) {
if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i];
}
}
}
public int getProjectileCount() {
return projectileCount;
}
public int getFireDelay() {
return fireDelay;
}
public void setFireDelay(int delay) {
this.fireDelay = Math.max(0, delay);
}
// Legacy compat
public int getDualFireDelay() { return fireDelay; }
public void setDualFireDelay(int delay) { setFireDelay(delay); }
@Override
public List<AbilityVariant> getVariants() {
return Arrays.asList(
new AbilityVariant("ability.variant.single", a -> {
a.setName("Beam");
}),
new AbilityVariant("ability.variant.dual", a -> {
AbilityBeam beam = (AbilityBeam) a;
a.setName("Dual Beam");
beam.setProjectileCount(2);
beam.setFireDelay(0);
// Set color override for second beam
beam.projectiles[1].colorOverride = true;
beam.projectiles[1].innerColor = 0xFFFFFF;
beam.projectiles[1].outerColor = 0xFF0000;
a.setWindUpTicks(80);
a.setWindUpAnimationName("Ability_BeamDual_Windup");
a.setActiveAnimationName("Ability_BeamDual_Active");
})
);
}
@Override
public boolean allowOverlap() {
return true;
}
@Override
public boolean isReadyForBurstCompletion(int activeTick) {
return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1);
}
@Override
public boolean isTargetingModeLocked() {
return true;
}
@Override
public TargetingMode[] getAllowedTargetingModes() {
return new TargetingMode[]{TargetingMode.AGGRO_TARGET};
}
/**
* Create beam entities.
* NPC: target is the aggro target — beams will home toward it.
* Player: target is null — beams fire in caster's look direction.
*/
private EntityAbilityBeam[] createBeamEntities(EntityLivingBase caster, EntityLivingBase target, World world) {
EntityAbilityBeam[] entities = new EntityAbilityBeam[projectileCount];
float offsetDist = 1.0f;
for (int i = 0; i < projectileCount; i++) {
Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor, offsetDist);
EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData);
entities[i] = new EntityAbilityBeam(
world, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord,
beamWidth, headSize,
resolved, combatData, homingData, lightningData, lifespanData, trajectoryData,
lockMovement.locksActive());
entities[i].setEffects(this.effects);
entities[i].setSourceAbility(this);
}
if (projectileCount == 2 && entities[0] != null && entities[1] != null) {
entities[0].setSiblingEntityId(entities[1].getEntityId());
entities[1].setSiblingEntityId(entities[0].getEntityId());
}
return entities;
}
private void fireBeamEntity(EntityAbilityBeam beam, EntityLivingBase target) {
if (beam == null || beam.isDead) return;
if (isPreview()) {
beam.startPreviewFiring();
} else {
beam.startFiring(target);
}
}
@Override
public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (world.isRemote && !isPreview()) return;
if (tick == 1) {
beamEntities = createBeamEntities(caster, target, world);
float offsetDist = 1.0f;
for (int i = 0; i < projectileCount; i++) {
EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData);
if (isPreview()) {
beamEntities[i].setupPreview(caster, beamWidth, headSize, resolved, lightningData, projectiles[i].anchor, windUpTicks, offsetDist);
} else {
beamEntities[i].setupCharging(projectiles[i].anchor, windUpTicks, offsetDist);
}
spawnAbilityEntity(world, beamEntities[i]);
}
}
}
@Override
public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) {
beamEntities = createBeamEntities(caster, target, world);
for (EntityAbilityBeam beam : beamEntities) {
spawnAbilityEntity(world, beam);
}
for (EntityAbilityBeam beam : beamEntities) {
fireBeamEntity(beam, target);
}
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote && !isPreview()) {
signalCompletion();
return;
}
if (beamEntities == null) return;
fireBeamEntity(beamEntities[0], target);
if (fireDelay <= 0) {
for (int i = 1; i < projectileCount; i++) {
fireBeamEntity(beamEntities[i], target);
}
}
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (beamEntities == null) {
signalCompletion();
return;
}
if (fireDelay > 0) {
for (int i = 1; i < projectileCount; i++) {
if (tick == fireDelay * i) {
fireBeamEntity(beamEntities[i], target);
}
}
}
boolean allDead = true;
for (EntityAbilityBeam beam : beamEntities) {
if (beam != null && !beam.isDead) {
allDead = false;
break;
}
}
if (allDead) {
signalCompletion();
}
}
@Override
public void onComplete(EntityLivingBase caster, EntityLivingBase target) {
}
@Override
public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) {
cleanup();
}
@Override
public void cleanup() {
if (beamEntities != null) {
for (int i = 0; i < beamEntities.length; i++) {
if (beamEntities[i] != null && !beamEntities[i].isDead) {
beamEntities[i].setDead();
}
beamEntities[i] = null;
}
}
beamEntities = null;
}
@Override
public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) {
// NPC: telegraph on aggro target position
// Player: no telegraph (beam fires in look direction, no fixed position to mark)
if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) {
return null;
}
Telegraph telegraph = Telegraph.circle(headSize * 2.0f);
telegraph.setDurationTicks(windUpTicks);
telegraph.setColor(windUpColor);
telegraph.setWarningColor(activeColor);
telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4));
telegraph.setHeightOffset(telegraphHeightOffset);
TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw);
instance.setCasterEntityId(caster.getEntityId());
instance.setEntityIdToFollow(target.getEntityId());
return instance;
}
@Override
public float getTelegraphRadius() {
return headSize * 2.0f;
}
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setFloat("beamWidth", beamWidth);
nbt.setFloat("headSize", headSize);
nbt.setInteger("projectileCount", projectileCount);
nbt.setInteger("fireDelay", fireDelay);
// Shared visual data
displayData.writeNBT(nbt);
lightningData.writeNBT(nbt);
// Shared combat/movement data
combatData.writeNBT(nbt);
homingData.writeNBT(nbt);
lifespanData.writeNBT(nbt);
// Per-projectile data
for (int i = 0; i < projectileCount; i++) {
NBTTagCompound projNbt = new NBTTagCompound();
projectiles[i].writeNBT(projNbt);
nbt.setTag("Projectile_" + i, projNbt);
}
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f;
this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f;
int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1;
initProjectiles(count);
if (nbt.hasKey("fireDelay")) {
this.fireDelay = nbt.getInteger("fireDelay");
} else if (nbt.hasKey("dualFireDelay")) {
this.fireDelay = nbt.getInteger("dualFireDelay");
} else {
this.fireDelay = 0;
}
combatData.readNBT(nbt);
homingData.readNBT(nbt);
lifespanData.readNBT(nbt);
if (nbt.hasKey("Projectile_0")) {
NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0");
if (proj0.hasKey("colorOverride")) {
// NEW format
displayData.readNBT(nbt);
lightningData.readNBT(nbt);
for (int i = 0; i < projectileCount; i++) {
if (nbt.hasKey("Projectile_" + i)) {
projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i));
}
}
} else {
// OLD per-projectile format
displayData.readNBT(proj0);
lightningData.readNBT(proj0);
projectiles[0].anchor.readNBT(proj0);
for (int i = 1; i < projectileCount; i++) {
if (nbt.hasKey("Projectile_" + i)) {
NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i);
projectiles[i].anchor.readNBT(projNbt);
EnergyDisplayData tempDisplay = new EnergyDisplayData();
tempDisplay.readNBT(projNbt);
if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) {
projectiles[i].colorOverride = true;
projectiles[i].innerColor = tempDisplay.innerColor;
projectiles[i].outerColor = tempDisplay.outerColor;
}
}
}
}
} else {
// LEGACY flat format
displayData.readNBT(nbt);
lightningData.readNBT(nbt);
projectiles[0].anchor.readNBT(nbt);
}
}
// ═══════════════════════════════════════════════════════════════════
// API GETTERS & SETTERS
// ═══════════════════════════════════════════════════════════════════
public float getBeamWidth() { return beamWidth; }
public void setBeamWidth(float beamWidth) { this.beamWidth = beamWidth; }
public float getHeadSize() { return headSize; }
public void setHeadSize(float headSize) { this.headSize = headSize; }
public float getSpeed() { return homingData.speed; }
public void setSpeed(float speed) { this.homingData.speed = speed; }
public float getMaxDistance() { return lifespanData.maxDistance; }
public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; }
public int getMaxLifetime() { return lifespanData.maxLifetime; }
public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; }
public float getDamage() { return combatData.damage; }
public void setDamage(float damage) { this.combatData.damage = damage; }
public float getKnockback() { return combatData.knockback; }
public void setKnockback(float knockback) { this.combatData.knockback = knockback; }
public float getKnockbackUp() { return combatData.knockbackUp; }
public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; }
public boolean isHoming() { return homingData.homing; }
public void setHoming(boolean homing) { this.homingData.homing = homing; }
public float getHomingStrength() { return homingData.homingStrength; }
public void setHomingStrength(float homingStrength) { this.homingData.homingStrength = homingStrength; }
public float getHomingRange() { return homingData.homingRange; }
public void setHomingRange(float homingRange) { this.homingData.homingRange = homingRange; }
public boolean isExplosive() { return combatData.explosive; }
public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; }
public float getExplosionRadius() { return combatData.explosionRadius; }
public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; }
public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; }
public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; }
// Shared display data (primary colors)
public int getInnerColor() { return displayData.innerColor; }
public void setInnerColor(int innerColor) { displayData.innerColor = innerColor; }
public int getOuterColor() { return displayData.outerColor; }
public void setOuterColor(int outerColor) { displayData.outerColor = outerColor; }
public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; }
public void setOuterColorEnabled(boolean outerColorEnabled) { displayData.outerColorEnabled = outerColorEnabled; }
public float getOuterColorWidth() { return displayData.outerColorWidth; }
public void setOuterColorWidth(float outerColorWidth) { displayData.outerColorWidth = outerColorWidth; }
public float getOuterColorAlpha() { return displayData.outerColorAlpha; }
public void setOuterColorAlpha(float outerColorAlpha) { displayData.outerColorAlpha = outerColorAlpha; }
public float getRotationSpeed() { return displayData.rotationSpeed; }
public void setRotationSpeed(float rotationSpeed) { displayData.rotationSpeed = rotationSpeed; }
// Shared lightning data
public boolean hasLightningEffect() { return lightningData.lightningEffect; }
public void setLightningEffect(boolean lightningEffect) { lightningData.lightningEffect = lightningEffect; }
public float getLightningDensity() { return lightningData.lightningDensity; }
public void setLightningDensity(float lightningDensity) { lightningData.lightningDensity = lightningDensity; }
public float getLightningRadius() { return lightningData.lightningRadius; }
public void setLightningRadius(float lightningRadius) { lightningData.lightningRadius = lightningRadius; }
public int getLightningFadeTime() { return lightningData.lightningFadeTime; }
public void setLightningFadeTime(int lightningFadeTime) { lightningData.lightningFadeTime = lightningFadeTime; }
// Anchor - default to projectile 0
public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; }
public void setAnchorPointEnum(AnchorPoint anchorPoint) { projectiles[0].anchor.anchorPoint = anchorPoint; }
public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; }
public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; }
public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; }
public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; }
public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; }
public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; }
@Override
public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); }
@Override
public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); }
// Indexed API methods
public int getInnerColor(int index) {
ProjectileData p = projectiles[clampIndex(index)];
return p.colorOverride ? p.innerColor : displayData.innerColor;
}
public void setInnerColor(int index, int color) {
ProjectileData p = projectiles[clampIndex(index)];
p.colorOverride = true;
p.innerColor = color;
}
public int getOuterColor(int index) {
ProjectileData p = projectiles[clampIndex(index)];
return p.colorOverride ? p.outerColor : displayData.outerColor;
}
public void setOuterColor(int index, int color) {
ProjectileData p = projectiles[clampIndex(index)];
p.colorOverride = true;
p.outerColor = color;
}
public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); }
public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); }
public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; }
public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; }
public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; }
private int clampIndex(int index) {
return Math.max(0, Math.min(index, projectileCount - 1));
}
@Override
public int getMaxPreviewDuration() {
return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100;
}
// ═══════════════════════════════════════════════════════════════════
// GUI FIELD DEFINITIONS
// ═══════════════════════════════════════════════════════════════════
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.add(FieldDef.row(
FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES),
FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay)
.range(0, 200).visibleWhen(() -> projectileCount > 1)
));
defs.add(FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed)
));
defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback));
defs.add(FieldDef.section("ability.section.beam"));
defs.add(FieldDef.row(
FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth),
FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize)
));
defs.add(FieldDef.row(
FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance),
FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime)
));
defs.add(FieldDef.section("ability.section.homing"));
defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"));
defs.add(FieldDef.row(
FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming),
FieldDef.floatField("gui.range", this::getHomingRange, this::setHomingRange).visibleWhen(this::isHoming)
));
defs.add(FieldDef.section("ability.section.explosive"));
defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"));
defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive));
defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects));
// Visual tab - shared primary colors
defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual"));
defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor)
.tab("ability.tab.visual"));
defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled)
.tab("ability.tab.visual"));
defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor)
.tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled));
defs.add(FieldDef.row(
FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth)
.visibleWhen(this::isOuterColorEnabled),
FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha)
.range(0, 1).visibleWhen(this::isOuterColorEnabled)
).tab("ability.tab.visual"));
// Visual tab - shared effects
defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual"));
defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed)
.tab("ability.tab.visual"));
defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect)
.tab("ability.tab.visual"));
defs.add(FieldDef.row(
FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity)
.visibleWhen(this::hasLightningEffect).range(0.01f, 100f),
FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius)
.range(0.1f, 100f).visibleWhen(this::hasLightningEffect)
).tab("ability.tab.visual"));
// Visual tab - per-projectile sections
for (int i = 0; i < MAX_PROJECTILES; i++) {
final int idx = i;
String sectionKey = "ability.section.projectile" + (i + 1);
defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual")
.visibleWhen(() -> idx < projectileCount));
defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class,
() -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
defs.add(FieldDef.row(
FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v),
FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v)
).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
// Color override (only when multiple projectiles)
defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1));
defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride));
defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride));
}
}
}
@@ -2,9 +2,11 @@ package kamkeel.npcs.controllers.data.ability.type;
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.LockMovementType;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper;
import kamkeel.npcs.controllers.data.ability.enums.LockMode;
import kamkeel.npcs.controllers.data.ability.enums.TargetFilter;
import kamkeel.npcs.controllers.data.ability.enums.TargetingMode;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
@@ -12,13 +14,8 @@ import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import noppes.npcs.api.ability.type.IAbilityCharge;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.Arrays;
import java.util.HashSet;
@@ -26,9 +23,10 @@ import java.util.List;
import java.util.Set;
/**
* Charge ability: Rush attack where NPC charges in a line, damaging all targets hit.
* Charge ability: Rush attack where the caster charges in a line, damaging all targets hit.
* Extends AbilityMovement for shared direction locking, stall detection, and velocity application.
*/
public class AbilityCharge extends Ability implements IAbilityCharge {
public class AbilityCharge extends AbilityMovement implements IAbilityCharge {
// Type-specific parameters
private float chargeSpeed = 0.8f;
@@ -36,11 +34,8 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
private float knockback = 3.0f;
private float hitWidth = 1.5f;
// Runtime state (transient)
private transient double startX, startY, startZ;
private transient Vec3 chargeDirection;
// Type-specific runtime state
private transient Set<Integer> hitEntities = new HashSet<>();
private transient float lockedYaw;
public AbilityCharge() {
this.typeId = "ability.cnpc.charge";
@@ -48,7 +43,7 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
this.targetingMode = TargetingMode.AGGRO_TARGET;
this.maxRange = 20.0f;
this.minRange = 4.0f;
this.lockMovement = LockMovementType.WINDUP;
this.lockMovement = LockMode.WINDUP_AND_ACTIVE;
this.cooldownTicks = 0;
this.windUpTicks = 20;
// LINE telegraph showing charge path
@@ -56,6 +51,16 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
this.showTelegraph = true;
this.windUpSound = "mob.zombie.wood";
this.activeSound = "mob.zombie.attack";
this.windUpAnimationName = "Ability_Charge_Windup";
this.activeAnimationName = "Ability_Charge_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/charge.png")
};
}
@Override
public boolean hasAbilityMovement() {
return true; // This ability drives the NPC's motion itself
}
@Override
@@ -68,139 +73,92 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
return new TargetingMode[]{TargetingMode.AGGRO_TARGET};
}
@Override
public boolean hasAbilityMovement() {
return true; // This ability moves the NPC
}
/**
* Called on the first tick of windup - lock direction here so it matches telegraph.
* During windup, NPCs face toward their target for animation purposes.
* Players aim freely — the telegraph follows their look direction on the client,
* and direction is locked at the end of windup in onExecute().
*/
@Override
public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (tick == 1) {
// Lock direction on first windup tick (same time telegraph is created)
lockChargeDirection(caster, target);
}
// Keep caster facing the locked direction during windup
enforceLockedRotation(caster);
}
/**
* Locks the charge direction. Called once at windup start — direction won't change even if target moves.
* NPC: charges toward aggro target.
* Player: charges in look direction.
*/
private void lockChargeDirection(EntityLivingBase caster, EntityLivingBase target) {
public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) {
if (!isPlayerCaster(caster) && target != null) {
// NPC: charge toward aggro target
double dx = target.posX - caster.posX;
double dz = target.posZ - caster.posZ;
double len = Math.sqrt(dx * dx + dz * dz);
if (len > 0) {
chargeDirection = Vec3.createVectorHelper(dx / len, 0, dz / len);
} else {
float yaw = (float) Math.toRadians(caster.rotationYaw);
chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw));
}
} else {
// Player: charge in look direction
float yaw = (float) Math.toRadians(caster.rotationYaw);
chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw));
}
lockedYaw = (float) Math.toDegrees(Math.atan2(-chargeDirection.xCoord, chargeDirection.zCoord));
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
// Initialize charge - direction was already locked during windup
startX = caster.posX;
startY = caster.posY;
startZ = caster.posZ;
hitEntities.clear();
// If direction wasn't set during windup (shouldn't happen), set it now
if (chargeDirection == null) {
lockChargeDirection(caster, target);
}
enforceLockedRotation(caster);
}
private void enforceLockedRotation(EntityLivingBase caster) {
caster.rotationYaw = lockedYaw;
caster.rotationYawHead = lockedYaw;
caster.prevRotationYaw = lockedYaw;
caster.prevRotationYawHead = lockedYaw;
caster.renderYawOffset = lockedYaw;
caster.prevRenderYawOffset = lockedYaw;
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (chargeDirection == null) return;
// Enforce rotation every tick
if (!isPreview()) {
lockDirectionToTarget(caster, target);
enforceLockedRotation(caster);
}
}
// Calculate distance traveled
double distanceTraveled = Math.sqrt(
Math.pow(caster.posX - startX, 2) +
Math.pow(caster.posZ - startZ, 2)
);
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target) {
// Lock final direction at end of windup so it matches the telegraph
lockDirection(caster, target);
initMovement(caster, maxRange, chargeSpeed);
hitEntities.clear();
// Check if reached max distance
if (distanceTraveled >= maxRange) {
caster.motionX = 0;
caster.motionZ = 0;
if (!isPreview()) {
caster.velocityChanged = true;
}
signalCompletion();
return;
}
enforceLockedRotation(caster);
}
// Block detection (skip in preview - no real world collision)
if (!isPreview() && isChargeBlocked(caster)) {
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) {
if (checkTimeout(tick)) {
stopMomentum(caster);
signalCompletion();
return;
}
// Move caster
caster.motionX = chargeDirection.xCoord * chargeSpeed;
caster.motionY = 0;
caster.motionZ = chargeDirection.zCoord * chargeSpeed;
if (!isPreview()) {
caster.velocityChanged = true;
if (movementDirection == null) {
stopMomentum(caster);
signalCompletion();
return;
}
if (!isPreview()) {
enforceLockedRotation(caster);
}
if (checkStall(caster, tick)) {
stopMomentum(caster);
signalCompletion();
return;
}
updatePrevPosition(caster);
if (getDistanceTraveled(caster) >= maxRange) {
stopMomentum(caster);
signalCompletion();
return;
}
if (checkBlocked(caster, chargeSpeed)) {
stopMomentum(caster);
signalCompletion();
return;
}
// Move caster (flat: zero vertical motion)
applyVelocityFlat(caster, chargeSpeed);
// Server-side collision damage (skip in preview)
if (!world.isRemote && !isPreview()) {
if (!caster.worldObj.isRemote && !isPreview()) {
AxisAlignedBB hitBox = caster.boundingBox.expand(hitWidth, hitWidth * 0.5, hitWidth);
@SuppressWarnings("unchecked")
List<Entity> entities = world.getEntitiesWithinAABB(EntityLivingBase.class, hitBox);
List<Entity> entities = caster.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, hitBox);
for (Entity entity : entities) {
if (!(entity instanceof EntityLivingBase)) continue;
if (entity == caster) continue;
if (hitEntities.contains(entity.getEntityId())) continue;
if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue;
EntityLivingBase livingEntity = (EntityLivingBase) entity;
// Hit this entity
hitEntities.add(entity.getEntityId());
// Apply damage with scripted event support
boolean wasHit = applyAbilityDamageWithDirection(caster, livingEntity, damage, knockback,
chargeDirection.xCoord, chargeDirection.zCoord);
movementDirection.xCoord, movementDirection.zCoord);
// Play impact sound if hit wasn't cancelled
if (wasHit) {
world.playSoundAtEntity(livingEntity, "random.explode", 0.5f, 1.2f);
applyEffects(livingEntity);
caster.worldObj.playSoundAtEntity(livingEntity, "random.explode", 0.5f, 1.2f);
}
}
}
@@ -218,25 +176,15 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
super.onInterrupt(caster, source, damage);
}
private void stopMomentum(EntityLivingBase caster) {
caster.motionX = 0;
caster.motionZ = 0;
if (!isPreview()) {
caster.velocityChanged = true;
}
}
private boolean isChargeBlocked(EntityLivingBase caster) {
double nextX = chargeDirection.xCoord * chargeSpeed;
double nextZ = chargeDirection.zCoord * chargeSpeed;
AxisAlignedBB nextBox = caster.boundingBox.copy().offset(nextX, 0, nextZ);
return !caster.worldObj.getCollidingBoundingBoxes(caster, nextBox).isEmpty();
@Override
public void cleanup() {
super.cleanup();
hitEntities.clear();
}
@Override
public void reset() {
super.reset();
chargeDirection = null;
public void resetForBurst() {
super.resetForBurst();
hitEntities.clear();
}
@@ -287,6 +235,11 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
// Telegraph follows caster during windup - allows caster to reposition
instance.setEntityIdToFollow(caster.getEntityId());
// For player casters, track their rotation so telegraph follows look direction
if (isPlayerCaster(caster)) {
instance.setTrackFollowedEntityYaw(true);
}
return instance;
}
@@ -305,16 +258,10 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.chargeSpeed = nbt.hasKey("chargeSpeed") ? nbt.getFloat("chargeSpeed") : 0.8f;
this.chargeSpeed = nbt.hasKey("chargeSpeed") ? Math.max(0.01f, nbt.getFloat("chargeSpeed")) : 0.8f;
this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f;
this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 3.0f;
if (nbt.hasKey("hitWidth")) {
this.hitWidth = nbt.getFloat("hitWidth");
} else if (nbt.hasKey("hitRadius")) {
this.hitWidth = nbt.getFloat("hitRadius");
} else {
this.hitWidth = 1.5f;
}
this.hitWidth = nbt.hasKey("hitWidth") ? nbt.getFloat("hitWidth") : 1.5f;
}
// Getters & Setters
@@ -334,6 +281,9 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
this.damage = damage;
}
@Override
public float getDisplayDamage() { return damage; }
public float getKnockback() {
return knockback;
}
Loaded 100 of 791 files, more files were not shown because too many files have changed in this diff. Show more