[WIP] Multiple Profile Handlers

This commit is contained in:
Kam committed 2025-01-23 16:10:01 -05:00
1 parent b2b9248c55
commit bf604774c0
11 files changed
+750

No files matched your search

@@ -0,0 +1,70 @@
package kamkeel.command.profile;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentTranslation;
import java.lang.reflect.Method;
import java.util.Map.Entry;
public class CommandHelpProfile extends CommandProfileBase {
private CommandProfile parent;
public CommandHelpProfile(CommandProfile parent){
this.parent = parent;
}
@Override
public String getCommandName() {
return "help";
}
@Override
public String getDescription() {
return "help [command]";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if(args.length == 0){
sendMessage(sender, "\u00A78------ \u00A7aProfile Commands \u00A78------");
for(Entry<String, CommandProfileBase> entry : parent.map.entrySet()){
sendMessage(sender, "\u00A77> " + "\u00A7e" + entry.getKey() + "\u00A78: \u00A77" + entry.getValue().getCommandUsage(sender));
}
return;
}
CommandProfileBase command = parent.getCommand(args);
if(command == null){
sendError(sender, "Unknown command " + args[0]);
return;
}
if(command.subcommands.isEmpty()){
sender.addChatMessage(new ChatComponentTranslation(command.getCommandUsage(sender)));
return;
}
Method m = null;
if(args.length > 1){
m = command.subcommands.get(args[1].toLowerCase());
}
if(m == null){
sendMessage(sender, "\u00A78------ \u00A7a" + command.getCommandName().toUpperCase() + " SubCommands \u00A78------");
sendMessage(sender, "\u00A77Usage: \u00A76" + command.getUsage());
for(Entry<String, Method> entry : command.subcommands.entrySet()){
sender.addChatMessage(new ChatComponentTranslation("\u00A77> " + "\u00A7e" + entry.getKey() + "\u00A78: \u00A77" + entry.getValue().getAnnotation(SubCommand.class).desc()));
}
sender.addChatMessage(new ChatComponentTranslation("\u00A78Permission:\u00A77 " + CommandProfile.getCommandPermission(command.getCommandName())));
}
else{
sendMessage(sender, "\u00A78------ \u00A7b" + command.getCommandName().toUpperCase() + "." + args[1].toUpperCase() + " Command \u00A78------");
SubCommand sc = m.getAnnotation(SubCommand.class);
sender.addChatMessage(new ChatComponentTranslation("\u00A77" + sc.desc()));
if(!sc.usage().isEmpty())
sender.addChatMessage(new ChatComponentTranslation("\u00A77Usage: \u00A76" + sc.usage()));
sender.addChatMessage(new ChatComponentTranslation("\u00A78Permission:\u00A77 " + getSubCommandPermission(args[1])));
}
}
}
@@ -0,0 +1,140 @@
package kamkeel.command.profile;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.scripted.CustomNPCsException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CommandProfile extends CommandBase {
public Map<String, CommandProfileBase> map = new HashMap<String, CommandProfileBase>();
public CommandHelpProfile help = new CommandHelpProfile(this);
public String[] alias = {"profile"};
public CommandProfile(){
registerCommand(help);
}
public void registerCommand(CommandProfileBase command){
String name = command.getCommandName().toLowerCase();
if(map.containsKey(name))
throw new CustomNPCsException("Already a subcommand with the name: " + name);
map.put(name, command);
}
@Override
public String getCommandName() {
return "profile";
}
@Override
public List getCommandAliases()
{
return Arrays.asList(alias);
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "Use as /profile subcommand";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if(args.length == 0){
help.processCommand(sender, args);
return;
}
CommandProfileBase command = getCommand(args);
if(command == null)
throw new CommandException("Unknown command " + args[0]);
args = Arrays.copyOfRange(args, 1, args.length);
if(command.subcommands.isEmpty() || !command.runSubCommands()){
if(!canSendCommand(sender, command))
throw new CommandException("You are not allowed to use this command: " + command);
command.canRun(sender, command.getUsage(), args);
command.processCommand(sender, args);
return;
}
if(args.length == 0){
help.processCommand(sender, new String[]{command.getCommandName()});
return;
}
command.processSubCommand(sender, args[0], Arrays.copyOfRange(args, 1, args.length));
}
@Override
public List addTabCompletionOptions(ICommandSender sender, String[] args){
if(args.length == 1)
return CommandBase.getListOfStringsMatchingLastWord(args, map.keySet().toArray(new String[map.size()]));
CommandProfileBase command = getCommand(args);
if(command == null)
return null;
if(args.length == 2 && command.runSubCommands())
return CommandBase.getListOfStringsMatchingLastWord(args, command.subcommands.keySet().toArray(new String[command.subcommands.keySet().size()]));
String[] useArgs = command.getUsage().split(" ");
if(command.runSubCommands()) {
Method m = command.subcommands.get(args[1].toLowerCase());
if(m != null) {
useArgs = m.getAnnotation(CommandProfileBase.SubCommand.class).usage().split(" ");
}
}
if(args.length <= useArgs.length + 2) {
if(args.length - 3 >= 0){
String usage = useArgs[args.length - 3];
if(usage.equals("<player>") || usage.equals("[player]")) {
return CommandBase.getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames());
}
}
}
return command.addTabCompletionOptions(sender, Arrays.copyOfRange(args, 1, args.length));
}
public CommandProfileBase getCommand(String[] args){
if(args.length == 0)
return null;
return map.get(args[0].toLowerCase());
}
@Override
public int getRequiredPermissionLevel(){
return 0;
}
public static String getCommandPermission(String command){
return "profile.kamkeel." + command.toLowerCase();
}
public static String getUniversalPermission(){
return "profile.kamkeel.*";
}
public static boolean canSendCommand(ICommandSender sender, CommandProfileBase command){
if(sender.canCommandSenderUseCommand(command.getRequiredPermissionLevel(), getUniversalPermission())){
return true;
}
if(sender.canCommandSenderUseCommand(command.getRequiredPermissionLevel(), getCommandPermission(command.getCommandName()))){
return true;
}
if(sender instanceof EntityPlayer){
return CustomNpcsPermissions.hasCustomPermission((EntityPlayer) sender, getCommandPermission(command.getCommandName()));
}
return false;
}
}
@@ -0,0 +1,148 @@
package kamkeel.command.profile;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentTranslation;
import noppes.npcs.CustomNpcsPermissions;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class CommandProfileBase extends CommandBase{
public Map<String, Method> subcommands = new HashMap<String, Method>();
public CommandProfileBase(){
for (Method m : this.getClass().getDeclaredMethods()) {
SubCommand sc = m.getAnnotation(SubCommand.class);
if (sc != null) {
String name = sc.name();
if (name.equals(""))
name = m.getName();
subcommands.put(name.toLowerCase(), m);
}
}
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
}
@Override
public String getCommandUsage(ICommandSender sender) {
return getDescription();
}
public abstract String getDescription();
/**
* @return Should return a string in the format of <arg> <arg2> <arg3> [arg4] where <> is a required parameter and [] optional
*/
public String getUsage(){
return "";
}
public boolean runSubCommands(){
return !subcommands.isEmpty();
}
protected static void sendMessage(ICommandSender sender, String message, Object... obs) {
sender.addChatMessage(new ChatComponentTranslation(message, obs));
}
protected static void sendResult(ICommandSender sender, String message, Object... obs) {
sender.addChatMessage(new ChatComponentTranslation("\u00A76[\u00A7eCNPC+\u00A76]\u00A77 " + message, obs));
}
protected static void sendError(ICommandSender sender, String message, Object... obs) {
sender.addChatMessage(new ChatComponentTranslation("\u00A76[\u00A7eCNPC+\u00A76]\u00A74 Error:\u00A7c " + message, obs));
}
@Retention(value = RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SubCommand {
String name() default "";
/**
* @return Should return a string in the format of <arg> <arg2> <arg3> [arg4] where <> is a required parameter and [] optional
*/
String usage() default "";
String desc();
int permission() default 2;
}
public void processSubCommand(ICommandSender sender, String command, String[] args) throws CommandException {
Method m = subcommands.get(command.toLowerCase());
if(m == null)
throw new CommandException("Unknown subcommand " + command);
SubCommand sc = m.getAnnotation(SubCommand.class);
if(!canSendCommand(sender, sc, command))
throw new CommandException("You are not allowed to use this command: " + command);
canRun(sender, sc.usage(), args);
try {
m.invoke(this, sender, args);
} catch (Exception e) {
e.printStackTrace();
}
}
public void canRun(ICommandSender sender, String usage, String[] args) throws CommandException{
String[] np = usage.split(" ");
List<String> required = new ArrayList<String>();
for(int i = 0; i < np.length; i++){
String command = np[i];
if(command.startsWith("<")){
required.add(command);
}
if(command.equals("<player>") && args.length > i){
CommandBase.getPlayer(sender, args[i]); //throws PlayerNotFoundException if no player is found
}
}
if (args.length < required.size()) {
throw new CommandException("Missing parameter: " + required.get(args.length));
}
}
public int getRequiredPermissionLevel(){
return 2;
}
public String getSubCommandPermission(String subCommand){
return "cnpc.kamkeel." + getCommandName().toLowerCase() + "." + subCommand.toLowerCase();
}
public String getSubUniversalPermission(){
return "cnpc.kamkeel." + getCommandName().toLowerCase() + "*";
}
public boolean canSendCommand(ICommandSender sender, SubCommand command, String subCommand){
if(sender.canCommandSenderUseCommand(command.permission(), getSubUniversalPermission())){
return true;
}
if(sender.canCommandSenderUseCommand(command.permission(), getSubCommandPermission(subCommand))){
return true;
}
if(sender instanceof EntityPlayer){
return CustomNpcsPermissions.hasCustomPermission((EntityPlayer) sender, getSubCommandPermission(subCommand));
}
return false;
}
}
@@ -0,0 +1,179 @@
package kamkeel.controllers;
import kamkeel.controllers.data.IProfileData;
import kamkeel.controllers.data.Profile;
import kamkeel.controllers.data.Slot;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcs;
import noppes.npcs.LogWriter;
import noppes.npcs.util.CustomNPCsThreader;
import noppes.npcs.util.NBTJsonUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.UUID;
public class ProfileController {
public static HashMap<String, IProfileData> profileTypes;
public static HashMap<UUID, Profile> activeProfiles;
public static String profile_directory = "profiles";
public ProfileController(){
profileTypes = new HashMap<>();
activeProfiles = new HashMap<>();
}
/**
* Register during ServerStartEvent()
*
* @param type - IProfile Type to always Save/Load
* @return true/false if profile was successfully added
*/
public static boolean registerProfileType(IProfileData type){
if(profileTypes.containsKey(type.getTagName()))
return false;
profileTypes.put(type.getTagName(), type);
return true;
}
public static File getProfileDir(){
try{
File file = new File(CustomNpcs.getWorldSaveDirectory(), profile_directory);
if(!file.exists())
file.mkdir();
return file;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static synchronized void login(EntityPlayer player){
if(player == null)
return;
Profile profile;
if(activeProfiles.containsKey(player.getUniqueID())){
profile = activeProfiles.get(player.getUniqueID());
profile.player = player;
} else {
NBTTagCompound profileCompound = load(player);
profile = new Profile(player, profileCompound);
activeProfiles.put(player.getUniqueID(), profile);
}
}
public static synchronized NBTTagCompound load(EntityPlayer player) {
File saveDir = getProfileDir();
String filename = player.getUniqueID().toString();
filename += ".dat";
try {
File file = new File(saveDir, filename);
if(file.exists()){
return NBTJsonUtil.loadNBTData(file);
}
} catch (Exception e) {
LogWriter.error("Error loading profile file: " + filename, e);
}
return new NBTTagCompound();
}
public static synchronized void save(EntityPlayer player, Profile profile) {
CustomNPCsThreader.customNPCThread.execute(() -> {
final NBTTagCompound compound = profile.writeToNBT();
final String filename = player.getUniqueID() + ".dat";
try {
File saveDir = getProfileDir();
File file = new File(saveDir, filename + "_new");
File file1 = new File(saveDir, filename);
CompressedStreamTools.writeCompressed(compound, new FileOutputStream(file));
if(file1.exists()){
file1.delete();
}
file.renameTo(file1);
} catch (Exception e) {
LogWriter.except(e);
}
});
}
public void changeSlot(EntityPlayer player, int slotNumber){
if(!activeProfiles.containsKey(player.getUniqueID()))
return;
Profile profile = activeProfiles.get(player.getUniqueID());
if(profile.currentID == slotNumber)
return;
// Saves Current Slot Data
saveSlotData(player);
// Sets Player to New Slot
changePlayerSlot(player, slotNumber);
// Save Slot File
save(player, profile);
}
public void saveSlotData(EntityPlayer player){
if(!activeProfiles.containsKey(player.getUniqueID()))
return;
NBTTagCompound dataCompound;
Slot slot;
Profile profile = activeProfiles.get(player.getUniqueID());
if(!profile.slots.isEmpty() && profile.slots.containsKey(profile.currentID)){
slot = profile.slots.get(profile.currentID);
dataCompound = (NBTTagCompound) slot.getCompound().copy();
} else {
slot = new Slot(profile.currentID, "Slot 1");
dataCompound = new NBTTagCompound();
}
for(IProfileData profileData : profileTypes.values()){
NBTTagCompound cloned = (NBTTagCompound) profileData.getCurrentNBT(player).copy();
dataCompound.setTag(profileData.getTagName(), cloned);
}
slot.setCompound(dataCompound);
}
public void changePlayerSlot(EntityPlayer player, int id){
if(!activeProfiles.containsKey(player.getUniqueID()))
return;
NBTTagCompound slotCompound;
Slot slot;
Profile profile = activeProfiles.get(player.getUniqueID());
if(!profile.slots.isEmpty() && profile.slots.containsKey(id)){
slot = profile.slots.get(id);
slotCompound = (NBTTagCompound) slot.getCompound().copy();
} else {
slot = new Slot(id, "Slot " + id);
slot.setCompound(new NBTTagCompound());
slotCompound = new NBTTagCompound();
}
slot.setLastLoaded(System.currentTimeMillis());
profile.slots.put(id, slot);
for(IProfileData profileData : profileTypes.values()){
if(slotCompound.hasKey(profileData.getTagName())){
profileData.setNBT(player, slotCompound.getCompoundTag(profileData.getTagName()));
} else {
profileData.setNBT(player, new NBTTagCompound());
}
profileData.save(player);
}
profile.currentID = id;
}
}
@@ -0,0 +1,38 @@
package kamkeel.controllers.data;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.controllers.data.PlayerData;
public class CNPCData implements IProfileData {
@Override
public String getTagName() {
return "CustomNPC+";
}
@Override
public NBTTagCompound getCurrentNBT(EntityPlayer player) {
PlayerData customNPCData = PlayerData.get(player);
return customNPCData.getNBT();
}
@Override
public void save(EntityPlayer player) {
PlayerData customNPCData = PlayerData.get(player);
customNPCData.save();
}
@Override
public void setNBT(EntityPlayer player, NBTTagCompound replace) {
PlayerData customNPCData = PlayerData.get(player);
if(replace.hasNoTags()){
PlayerData newData = new PlayerData();
newData.player = player;
customNPCData.setNBT((NBTTagCompound) newData.getNBT().copy());
}
else {
customNPCData.setNBT(replace);
}
}
}
@@ -0,0 +1,29 @@
package kamkeel.controllers.data;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
public interface IProfileData {
/**
* Do not use the tag: - Name, lastLoaded, ID
*
* @return The Save Tag utilized in the Profile
*/
public String getTagName();
/**
* @return NBTTagCompound of their Current Data for a given Entity Player
*/
public NBTTagCompound getCurrentNBT(EntityPlayer player);
/**
* Called immediately after setNBT() Replaces existing NBT
*/
public void save(EntityPlayer player);
/**
* Replaces their Current Data operation when changing Profiles
*/
public void setNBT(EntityPlayer player, NBTTagCompound replace);
}
@@ -0,0 +1,64 @@
package kamkeel.controllers.data;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import java.util.HashMap;
import java.util.Set;
import java.util.UUID;
public class Profile {
public EntityPlayer player;
public int currentID;
public HashMap<Integer, Slot> slots = new HashMap<>();
private NBTTagCompound profileCompound;
public Profile(EntityPlayer player, NBTTagCompound compound){
this.player = player;
this.profileCompound = compound;
if(compound.hasKey("CurrentID")){
this.currentID = compound.getInteger("CurrentID");
} else {
this.currentID = 1;
}
if (compound.hasKey("Slots")) {
// Load Slots
NBTTagCompound slotsCompound = compound.getCompoundTag("Slots");
for (String key : (Set<String>) slotsCompound.func_150296_c()) {
int slotID = Integer.parseInt(key);
NBTTagCompound slotNBT = slotsCompound.getCompoundTag(key);
Slot slot = Slot.fromNBT(slotID, slotNBT);
slots.put(slotID, slot);
}
}
}
public NBTTagCompound writeToNBT() {
NBTTagCompound fullCompound = new NBTTagCompound();
if(this.player != null)
fullCompound.setString("Name", player.getCommandSenderName());
fullCompound.setInteger("CurrentID", currentID);
if(!slots.isEmpty()){
NBTTagCompound slotsCompound = new NBTTagCompound();
for (HashMap.Entry<Integer, Slot> entry : slots.entrySet()) {
int id = entry.getKey();
Slot slot = entry.getValue();
slot.setId(id);
NBTTagCompound slotTag = slot.toNBT();
slotsCompound.setTag(String.valueOf(id), slotTag);
}
fullCompound.setTag("Slots", slotsCompound);
}
return fullCompound;
}
}
@@ -0,0 +1,72 @@
package kamkeel.controllers.data;
import kamkeel.controllers.ProfileController;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
public class Slot {
private int id;
private String name;
private long lastLoaded;
private NBTTagCompound compound;
public Slot(int id, String name) {
this.id = id;
this.name = name;
}
public Slot(int id, String name, NBTTagCompound compound, long last) {
this.id = id;
this.name = name;
this.compound = compound;
this.lastLoaded = last;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getLastLoaded() {
return lastLoaded;
}
public void setLastLoaded(long lastLoaded) {
this.lastLoaded = lastLoaded;
}
public NBTTagCompound getCompound() {
return compound;
}
public void setCompound(NBTTagCompound compound) {
this.compound = compound;
}
public NBTTagCompound toNBT() {
NBTTagCompound slotNBT = new NBTTagCompound();
slotNBT.setString("Name", name);
slotNBT.setLong("LastLoaded", lastLoaded);
slotNBT.setTag("Data", compound);
return slotNBT;
}
public static Slot fromNBT(int id, NBTTagCompound slotNBT) {
String name = slotNBT.getString("Name");
long lastLoaded = slotNBT.getLong("LastLoaded");
NBTTagCompound compound = slotNBT.getCompoundTag("Data");
return new Slot(id, name, compound, lastLoaded);
}
}
@@ -11,6 +11,8 @@ import cpw.mods.fml.common.registry.EntityRegistry;
import foxz.command.CommandNoppes;
import kamkeel.addon.AddonManager;
import kamkeel.command.CommandKamkeel;
import kamkeel.controllers.ProfileController;
import kamkeel.controllers.data.CNPCData;
import kamkeel.developer.Developer;
import net.minecraft.block.Block;
import net.minecraft.block.BlockIce;
@@ -205,6 +207,11 @@ public class CustomNpcs {
new SpawnController();
new LinkedNpcController();
new AnimationController();
// Profile Controller
new ProfileController();
ProfileController.registerProfileType(new CNPCData());
ScriptController.Instance.loadStoredData();
ScriptController.Instance.loadForgeScripts();
ScriptController.Instance.loadGlobalNPCScripts();
@@ -5,6 +5,7 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.relauncher.Side;
import kamkeel.controllers.ProfileController;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -4,6 +4,7 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import kamkeel.controllers.ProfileController;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
@@ -52,6 +53,7 @@ public class ServerTickHandler {
}
SyncController.syncPlayer(player);
ProfileController.login(player);
}
@SubscribeEvent