Usage Guide v1.6.0

Learn how to use ChosenLib utilities effectively in your Fabric mods with practical examples and best practices.

🚀 Quick Start

Get started with ChosenLib v1.6.0 in just a few steps:

1. Import the Utilities

// NEW in v1.6.0
import com.chosen.lib.util.FileUtils;
import com.chosen.lib.command.Command;
import com.chosen.lib.command.CommandManager;

// NEW in v1.5.0
import com.chosen.lib.util.AdvancedBlockOps;
import com.chosen.lib.util.EntityAIUtils;
import com.chosen.lib.util.DataPersistence;
import com.chosen.lib.util.EffectsUtils;
import com.chosen.lib.util.AdvancedNetworking;
import com.chosen.lib.util.DimensionUtils;
import com.chosen.lib.util.RedstoneUtils;
import com.chosen.lib.util.PerformanceMonitor;

// Enhanced existing utilities
import com.chosen.lib.util.WorldUtils;
import com.chosen.lib.util.EntityUtils;
import com.chosen.lib.util.NetworkUtils;
import com.chosen.lib.util.TextUtils;
import com.chosen.lib.util.GuiUtils;
import com.chosen.lib.util.ItemUtils;

2. Use Basic Functions

// File operations (NEW v1.6.0!)
FileUtils.writeFile(Paths.get("my-file.txt"), "Hello, world!");

// Command framework (NEW v1.6.0!)
CommandManager.registerCommand(new MyCommand());

// Advanced block operations (NEW v1.5.0!)
TransactionId transaction = AdvancedBlockOps.startTransaction(world);
AdvancedBlockOps.safeSetBlock(world, pos, newState);

// AI operations (NEW v1.5.0!)
EntityAIUtils.addGoal(mob, goal, 1);
EntityAIUtils.setBehaviorState(mob, "aggressive");

// Data persistence (NEW v1.5.0!)
DataPersistence.saveWorldData(world, "config", configData);

// Effects and particles (NEW v1.5.0!)
EffectsUtils.playSound(world, pos, sound, 1.0f, 1.0f);
EffectsUtils.spawnParticleSphere(world, particle, center, 2.0, 20);

// Performance monitoring (NEW v1.5.0!)
PerformanceMonitor.startProfiling("myOperation");
PerformanceMonitor.getMemoryUsage();

// Enhanced text operations
Text interactive = TextUtils.interactiveText("Click me", "Tooltip", "https://example.com");

// Enhanced item operations
ItemUtils.insertStack(inventory, stack);

🔧 AdvancedBlockOps Examples NEW v1.5.0

AdvancedBlockOps provides enhanced block manipulation with safety checks and transactional editing.

Transactional Operations

// Start a transaction for safe operations
TransactionId transaction = AdvancedBlockOps.startTransaction(world);

try {
    // Perform multiple block operations
    AdvancedBlockOps.safeSetBlock(world, pos1, Blocks.STONE.getDefaultState());
    AdvancedBlockOps.safeSetBlock(world, pos2, Blocks.COBBLESTONE.getDefaultState());
    AdvancedBlockOps.safeSetBlock(world, pos3, Blocks.GRANITE.getDefaultState());
    
    // Commit all changes at once
    AdvancedBlockOps.commitTransaction(transaction);
    TextUtils.success("All blocks placed successfully!");
} catch (Exception e) {
    // Rollback on error
    AdvancedBlockOps.rollbackTransaction(transaction);
    TextUtils.error("Transaction failed, all changes rolled back");
}

Area Operations

// Fill area with specific block
AdvancedBlockOps.fillArea(world, pos1, pos2, Blocks.GLASS.getDefaultState());

// Replace blocks in area
int replaced = AdvancedBlockOps.replaceInArea(world, pos1, pos2,
    Blocks.STONE.getDefaultState(), Blocks.COBBLESTONE.getDefaultState());
TextUtils.info("Replaced " + replaced + " blocks");

// Copy area to new location
AdvancedBlockOps.copyArea(world, sourcePos1, sourcePos2, destinationPos);

// Analyze area for patterns
AreaAnalysis analysis = AdvancedBlockOps.analyzeArea(world, pos1, pos2);
TextUtils.info("Area contains " + analysis.getBlockCount() + " blocks");

Safe Block Operations

// Safe block setting with validation
boolean success = AdvancedBlockOps.safeSetBlock(world, pos, newState);
if (success) {
    TextUtils.success("Block placed successfully");
} else {
    TextUtils.error("Failed to place block");
}

// Validate before placing
if (AdvancedBlockOps.canPlaceBlock(world, pos, newState)) {
    AdvancedBlockOps.safeSetBlock(world, pos, newState);
}

🤖 EntityAIUtils Examples NEW v1.5.0

EntityAIUtils provides AI utilities for custom mobs and behavior management.

Goal Management

// Add AI goals with priorities
EntityAIUtils.addGoal(mob, new FollowPlayerGoal(), 1);
EntityAIUtils.addGoal(mob, new AttackGoal(), 2);
EntityAIUtils.addGoal(mob, new WanderAroundGoal(), 3);

// Remove specific goal type
EntityAIUtils.removeGoal(mob, FollowPlayerGoal.class);

// Clear all goals
EntityAIUtils.clearGoals(mob);

// Get active goals
List<Goal> activeGoals = EntityAIUtils.getActiveGoals(mob);
TextUtils.info("Mob has " + activeGoals.size() + " active goals");

Behavior States

// Set custom behavior states
EntityAIUtils.setBehaviorState(mob, "aggressive");
EntityAIUtils.setBehaviorState(mob, "defensive");
EntityAIUtils.setBehaviorState(mob, "passive");

// Get current behavior state
String currentState = EntityAIUtils.getBehaviorState(mob);
TextUtils.info("Mob is in " + currentState + " state");

// Add AI memory
EntityAIUtils.addMemory(mob, "lastPlayer", player);
EntityAIUtils.addMemory(mob, "lastAttackTime", System.currentTimeMillis());

// Retrieve AI memory
PlayerEntity lastPlayer = EntityAIUtils.getMemory(mob, "lastPlayer");
if (lastPlayer != null) {
    TextUtils.info("Mob remembers player: " + lastPlayer.getName().getString());
}

Pathfinding Integration

// Add pathfinding goals
EntityAIUtils.addPathfindingGoal(mob, new MoveToTargetGoal(target, 1.0));
EntityAIUtils.addPathfindingGoal(mob, new AvoidEntityGoal(PlayerEntity.class, 5.0f, 1.0, 1.2));

// Set pathfinding parameters
EntityAIUtils.setPathfindingSpeed(mob, 1.5f);
EntityAIUtils.setPathfindingRange(mob, 20.0);

💾 DataPersistence Examples NEW v1.5.0

DataPersistence provides world, player, and global data storage with compression.

World Data

// Save world configuration data
ConfigData config = new ConfigData();
config.setDifficulty(2);
config.setWeatherEnabled(true);
DataPersistence.saveWorldData(world, "config", config);

// Load world data
Optional<ConfigData> loadedConfig = DataPersistence.loadWorldData(world, "config", ConfigData.class);
if (loadedConfig.isPresent()) {
    ConfigData config = loadedConfig.get();
    TextUtils.info("World difficulty: " + config.getDifficulty());
}

// Check if world data exists
if (DataPersistence.hasWorldData(world, "config")) {
    TextUtils.info("World has configuration data");
}

// Delete world data
DataPersistence.deleteWorldData(world, "oldConfig");

Player Data

// Save player statistics
PlayerStats stats = new PlayerStats();
stats.setKills(10);
stats.setDeaths(2);
stats.setPlayTime(3600000); // 1 hour
DataPersistence.savePlayerData(player, "stats", stats);

// Load player data
Optional<PlayerStats> loadedStats = DataPersistence.loadPlayerData(player, "stats", PlayerStats.class);
if (loadedStats.isPresent()) {
    PlayerStats stats = loadedStats.get();
    TextUtils.info("Player K/D: " + stats.getKills() + "/" + stats.getDeaths());
}

// Migrate player data
DataPersistence.migratePlayerData(player.getUuid(), "oldStats", "stats");

Global Data

// Save global server data
ServerData serverData = new ServerData();
serverData.setTotalPlayers(50);
serverData.setServerStartTime(System.currentTimeMillis());
DataPersistence.saveGlobalData("server", serverData);

// Load global data
Optional<ServerData> loadedServerData = DataPersistence.loadGlobalData("server", ServerData.class);
if (loadedServerData.isPresent()) {
    ServerData data = loadedServerData.get();
    TextUtils.info("Server has " + data.getTotalPlayers() + " total players");
}

✨ EffectsUtils Examples NEW v1.5.0

EffectsUtils provides sound and particle effect utilities with timing control.

Sound Effects

// Play sound at position
EffectsUtils.playSound(world, pos, SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, 1.0f, 1.0f);

// Play sound to specific player
EffectsUtils.playSoundToPlayer(player, SoundEvents.ENTITY_PLAYER_LEVELUP, 1.0f, 1.0f);

// Delayed sound effects
EffectsUtils.playDelayedSound(world, pos, SoundEvents.ENTITY_TNT_PRIMED, 20); // 1 second delay

// Create sound sequences
SoundEvent[] sounds = {SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, SoundEvents.ENTITY_PLAYER_LEVELUP};
int[] delays = {0, 10}; // 0.5 second between sounds
SoundSequence sequence = EffectsUtils.createSoundSequence(sounds, delays);
sequence.play(world, pos);

Particle Effects

// Spawn single particle
EffectsUtils.spawnParticle(world, ParticleTypes.EXPLOSION, pos);

// Spawn particles in line
EffectsUtils.spawnParticleLine(world, ParticleTypes.FLAME, startPos, endPos, 10);

// Spawn particles in sphere
EffectsUtils.spawnParticleSphere(world, ParticleTypes.HEART, center, 2.0, 20);

// Create persistent particle system
ParticleSystem system = EffectsUtils.createParticleSystem(ParticleTypes.FLAME, center, 100);
system.start(world);

// Stop particle system
system.stop();

Combined Effects

// Create explosion effect with sound and particles
public void createExplosionEffect(World world, Vec3d pos) {
    // Sound effect
    EffectsUtils.playSound(world, pos, SoundEvents.ENTITY_GENERIC_EXPLODE, 1.0f, 1.0f);
    
    // Particle explosion
    EffectsUtils.spawnParticleSphere(world, ParticleTypes.EXPLOSION, pos, 3.0, 30);
    
    // Delayed smoke effect
    EffectsUtils.playDelayedSound(world, pos, SoundEvents.BLOCK_FIRE_EXTINGUISH, 10);
    EffectsUtils.spawnParticleSphere(world, ParticleTypes.SMOKE, pos, 2.0, 15);
}

🌐 AdvancedNetworking Examples NEW v1.5.0

AdvancedNetworking provides sophisticated packet handling with routing and encryption.

Packet Creation and Routing

// Create typed packets
PacketByteBuf dataPacket = AdvancedNetworking.createPacket("data", dataObject);
PacketByteBuf configPacket = AdvancedNetworking.createPacket("config", configObject);

// Custom packet routing
PacketRoute customRoute = (player, buffer) -> {
    // Custom logic for packet delivery
    if (player.hasPermissionLevel(2)) {
        AdvancedNetworking.sendToPlayer(player, CHANNEL_ID, buffer);
    }
};
AdvancedNetworking.routePacket(CHANNEL_ID, dataPacket, customRoute);

// Broadcast with filter
AdvancedNetworking.broadcastPacket(CHANNEL_ID, configPacket, 
    player -> player.hasPermissionLevel(1));

// Synchronize data across clients
AdvancedNetworking.syncData(CHANNEL_ID, "playerStats", playerStats);

Compression and Encryption

// Compress large packets
PacketByteBuf largePacket = NetworkUtils.createBuffer();
// ... write large amount of data ...
PacketByteBuf compressed = AdvancedNetworking.compressPacket(largePacket);

// Decompress on receiving end
PacketByteBuf decompressed = AdvancedNetworking.decompressPacket(compressed);

// Encrypt sensitive data
PacketByteBuf sensitiveData = NetworkUtils.createBuffer();
// ... write sensitive data ...
PacketByteBuf encrypted = AdvancedNetworking.encryptPacket(sensitiveData, "secretKey");

// Decrypt on receiving end
PacketByteBuf decrypted = AdvancedNetworking.decryptPacket(encrypted, "secretKey");

Reliable Packet Delivery

// Send reliable packet with acknowledgment
AdvancedNetworking.sendReliablePacket(player, CHANNEL_ID, buffer, 
    () -> TextUtils.info("Packet delivered successfully"),
    () -> TextUtils.error("Packet delivery failed"));

// Batch multiple packets
List<PacketByteBuf> packets = Arrays.asList(packet1, packet2, packet3);
AdvancedNetworking.sendBatch(player, CHANNEL_ID, packets);

🌍 DimensionUtils Examples NEW v1.5.0

DimensionUtils provides custom dimension management and portal systems.

Dimension Management

// Create custom dimension
Identifier customDimensionId = new Identifier("mymod", "custom_world");
DimensionType customDimensionType = DimensionType.builder()
    .natural(true)
    .ambientLight(0.1f)
    .build();
DimensionUtils.createDimension(customDimensionId, customDimensionType);

// Get dimension information
DimensionInfo info = DimensionUtils.getDimensionInfo(customDimensionId);
TextUtils.info("Dimension: " + info.getName() + ", Type: " + info.getType());

// List all custom dimensions
List<Identifier> customDimensions = DimensionUtils.listCustomDimensions();
TextUtils.info("Custom dimensions: " + customDimensions.size());

// Delete custom dimension
DimensionUtils.deleteDimension(customDimensionId);

Teleportation

// Teleport entity to custom dimension
Vec3d spawnPos = new Vec3d(0, 64, 0);
boolean success = DimensionUtils.teleportToDimension(entity, customDimensionId, spawnPos);
if (success) {
    TextUtils.success("Teleported to custom dimension");
} else {
    TextUtils.error("Failed to teleport to custom dimension");
}

// Create portal to custom dimension
BlockPos portalPos = new BlockPos(100, 64, 100);
DimensionUtils.createPortal(world, portalPos, customDimensionId);

// Find existing portal
Optional<BlockPos> portal = DimensionUtils.findPortal(world, customDimensionId);
if (portal.isPresent()) {
    TextUtils.info("Found portal at: " + portal.get());
}

Portal Systems

// Create bidirectional portal
DimensionUtils.createBidirectionalPortal(world, pos1, customDimensionId, pos2);

// Link existing portals
DimensionUtils.linkPortals(world, portalPos1, customDimensionId, portalPos2);

// Portal activation system
public void activatePortal(World world, BlockPos pos) {
    if (DimensionUtils.isValidPortalLocation(world, pos)) {
        DimensionUtils.activatePortal(world, pos);
        EffectsUtils.spawnParticleSphere(world, ParticleTypes.PORTAL, 
            Vec3d.ofCenter(pos), 2.0, 20);
        EffectsUtils.playSound(world, Vec3d.ofCenter(pos), 
            SoundEvents.BLOCK_PORTAL_TRIGGER, 1.0f, 1.0f);
    }
}

🔴 RedstoneUtils Examples NEW v1.5.0

RedstoneUtils provides circuit analysis and automation with logic gates.

Circuit Analysis

// Analyze redstone circuit
CircuitAnalysis analysis = RedstoneUtils.analyzeCircuit(world, pos, 10);
TextUtils.info("Circuit has " + analysis.getComponentCount() + " components");
TextUtils.info("Max signal strength: " + analysis.getMaxSignalStrength());

// Get signal strength at position
int signal = RedstoneUtils.getSignalStrength(world, pos);
TextUtils.info("Signal strength: " + signal);

// Set signal strength
RedstoneUtils.setSignalStrength(world, pos, 15);

// Find redstone components
List<BlockPos> components = RedstoneUtils.findRedstoneComponents(world, center, 5);
TextUtils.info("Found " + components.size() + " redstone components");

Logic Gates

// Create AND gate
List<BlockPos> andInputs = Arrays.asList(input1, input2, input3);
RedstoneUtils.createANDGate(world, andOutputPos, andInputs);

// Create OR gate
List<BlockPos> orInputs = Arrays.asList(input1, input2);
RedstoneUtils.createORGate(world, orOutputPos, orInputs);

// Create NOT gate
RedstoneUtils.createNOTGate(world, notOutputPos, notInputPos);

// Simulate logic gates
int[] inputs = {15, 0, 15}; // High, Low, High
int andResult = RedstoneUtils.simulateLogicGate(LogicGateType.AND, inputs); // 0 (Low)
int orResult = RedstoneUtils.simulateLogicGate(LogicGateType.OR, inputs); // 15 (High)
int notResult = RedstoneUtils.simulateLogicGate(LogicGateType.NOT, new int[]{15}); // 0 (Low)

Automation Systems

// Create automated door system
public void createAutomatedDoor(World world, BlockPos doorPos, BlockPos buttonPos) {
    // Create NOT gate for button
    RedstoneUtils.createNOTGate(world, doorPos, buttonPos);
    
    // Add delay for smooth operation
    RedstoneUtils.addDelay(world, doorPos, 10); // 0.5 second delay
}

// Create redstone clock
public void createRedstoneClock(World world, BlockPos clockPos, int period) {
    RedstoneUtils.createClock(world, clockPos, period);
    TextUtils.info("Created redstone clock with " + period + " tick period");
}

// Analyze and optimize circuit
public void optimizeCircuit(World world, BlockPos pos, int radius) {
    CircuitAnalysis analysis = RedstoneUtils.analyzeCircuit(world, pos, radius);
    if (analysis.getEfficiency() < 0.8) {
        RedstoneUtils.optimizeCircuit(world, pos, radius);
        TextUtils.success("Circuit optimized for better efficiency");
    }
}

📊 PerformanceMonitor Examples NEW v1.5.0

PerformanceMonitor provides built-in performance profiling and monitoring.

Memory Monitoring

// Get current memory usage
MemoryUsageInfo memoryInfo = PerformanceMonitor.getMemoryUsage();
TextUtils.info("Memory: " + memoryInfo.getFormattedUsedMemory() + 
    " / " + memoryInfo.getFormattedMaxMemory() + 
    " (" + String.format("%.1f", memoryInfo.getUsagePercentage()) + "%)");

// Get heap usage specifically
HeapUsageInfo heapInfo = PerformanceMonitor.getHeapUsage();
TextUtils.info("Heap: " + heapInfo.getFormattedUsedHeap() + 
    " / " + heapInfo.getFormattedMaxHeap());

// Start memory tracking
PerformanceMonitor.startMemoryTracking();

// Perform operations...
// ...

// Stop tracking and get report
MemoryTrackingReport report = PerformanceMonitor.stopMemoryTracking();
TextUtils.info("Memory usage during operation: " + report.getFormattedPeakUsage());

Performance Profiling

// Start profiling an operation
PerformanceMonitor.startProfiling("blockPlacement");

try {
    // Perform expensive operation
    for (int i = 0; i < 1000; i++) {
        WorldUtils.setBlockState(world, pos.add(i, 0, 0), Blocks.STONE.getDefaultState());
    }
} finally {
    // End profiling
    PerformanceMonitor.endProfiling("blockPlacement");
}

// Get profiling results
ProfilingResult result = PerformanceMonitor.getProfilingResult("blockPlacement");
TextUtils.info("Operation took " + result.getDuration() + "ms");
TextUtils.info("Average time per operation: " + result.getAverageTime() + "ms");

TPS Monitoring

// Get TPS data
TPSData tpsData = PerformanceMonitor.getTPSData(world);
TextUtils.info("Current TPS: " + String.format("%.2f", tpsData.getCurrentTPS()));
TextUtils.info("Average TPS: " + String.format("%.2f", tpsData.getAverageTPS()));
TextUtils.info("Min TPS: " + String.format("%.2f", tpsData.getMinTPS()));

// Monitor TPS over time
if (tpsData.getCurrentTPS() < 18.0) {
    TextUtils.warning("Server TPS is low: " + String.format("%.2f", tpsData.getCurrentTPS()));
}

Comprehensive Reporting

// Generate comprehensive performance report
String report = PerformanceMonitor.generatePerformanceReport(world);

// Report includes:
// - Memory usage statistics
// - TPS data and trends
// - Entity and chunk statistics
// - Profiling results
// - Recommendations for optimization

TextUtils.info("=== PERFORMANCE REPORT ===");
String[] lines = report.split("\n");
for (String line : lines) {
    if (!line.trim().isEmpty()) {
        TextUtils.info(line);
    }
}

📂 FileUtils Examples NEW v1.6.0

FileUtils provides utilities for safe file operations and data management.

File Operations

// Read a file
String content = FileUtils.readFile(Paths.get("config.txt"));

// Write to a file
boolean success = FileUtils.writeFile(Paths.get("data.json"), "{ \"key\": \"value\" }");

// Copy a file
FileUtils.copyFile(Paths.get("source.txt"), Paths.get("destination.txt"));

// Move a file
FileUtils.moveFile(Paths.get("old.txt"), Paths.get("new.txt"));

// Delete a file
FileUtils.deleteFile(Paths.get("temp.txt"));

Directory Operations

// Create a directory
FileUtils.createDirectory(Paths.get("my_folder"));

// List files in a directory
List files = FileUtils.listFiles(Paths.get("."));
for (Path file : files) {
    System.out.println(file.getFileName());
}

// Search for files
List jsonFiles = FileUtils.searchFiles(Paths.get("."), "*.json");
System.out.println("Found " + jsonFiles.size() + " JSON files.");

💻 Command Framework Examples NEW v1.6.0

The command framework simplifies command creation and management.

Creating a Command

// 1. Create a class that implements the Command interface
public class MyCommand implements com.chosen.lib.command.Command {
    @Override
    public void register(CommandDispatcher dispatcher) {
        dispatcher.register(CommandManager.literal("mycommand")
            .executes(context -> {
                context.getSource().sendFeedback(() -> Text.literal("Hello from MyCommand!"), false);
                return Command.SINGLE_SUCCESS;
            })
        );
    }
}

// 2. Register the command in your mod's onInitialize method
CommandManager.registerCommand(new MyCommand());

🌍 Enhanced WorldUtils Examples ENHANCED v1.5.0

WorldUtils provides safe world and block manipulation utilities.

Block Operations

// Safe block operations with validation
BlockState state = WorldUtils.getBlockState(world, pos);
boolean success = WorldUtils.setBlockState(world, pos, newState);

// Check if position is loaded
if (WorldUtils.isPositionLoaded(world, pos)) {
    // Safe to operate on this position
}

// Check if block can be placed
if (WorldUtils.canPlaceBlock(world, pos, state)) {
    WorldUtils.setBlockState(world, pos, state);
}

Area Operations

// Get blocks in different shapes
List<BlockPos> cubeBlocks = WorldUtils.getBlocksInCube(center, 5);
List<BlockPos> sphereBlocks = WorldUtils.getBlocksInSphere(center, 5.0);
List<BlockPos> areaBlocks = WorldUtils.getBlocksInArea(pos1, pos2);

// Find specific blocks
List<BlockPos> ores = WorldUtils.findBlocks(world, center, 10, 
    state -> state.isOf(Blocks.DIAMOND_ORE));

// Find nearest block
BlockPos nearest = WorldUtils.findNearestBlock(world, center, 20,
    state -> state.isOf(Blocks.WATER));

// Replace blocks in area
int replaced = WorldUtils.replaceBlocks(world, center, 5,
    Blocks.STONE.getDefaultState(), Blocks.COBBLESTONE.getDefaultState());

World Properties

// Get world information
RegistryEntry<Biome> biome = WorldUtils.getBiome(world, pos);
int lightLevel = WorldUtils.getLightLevel(world, pos);
boolean canSeeSky = WorldUtils.canSeeSky(world, pos);
BlockPos highest = WorldUtils.getHighestBlock(world, x, z);

// Chunk operations
Chunk chunk = WorldUtils.getChunk(world, pos);
boolean loaded = WorldUtils.isChunkLoaded(world, pos);
ChunkPos chunkPos = WorldUtils.getChunkPos(pos);

// Fluid operations
FluidState fluidState = WorldUtils.getFluidState(world, pos);
boolean hasFluid = WorldUtils.hasFluid(world, pos, Fluids.WATER);

👤 EntityUtils Examples NEW

EntityUtils provides comprehensive entity management utilities.

Health Management

// Health operations
float health = EntityUtils.getHealth(entity);
EntityUtils.setHealth(entity, 20.0f);
EntityUtils.heal(entity, 10.0f);
EntityUtils.damage(entity, damageSource, 5.0f);

// Health validation
float maxHealth = EntityUtils.getMaxHealth(entity);
boolean isAlive = EntityUtils.isAlive(entity);
boolean isFullHealth = EntityUtils.isFullHealth(entity);

Status Effects

// Status effect management
boolean hasEffect = EntityUtils.hasStatusEffect(entity, StatusEffects.SPEED);
EntityUtils.addStatusEffect(entity, new StatusEffectInstance(StatusEffects.SPEED, 200, 1));
EntityUtils.removeStatusEffect(entity, StatusEffects.POISON);
EntityUtils.clearStatusEffects(entity);

// Get effect information
StatusEffectInstance effect = EntityUtils.getStatusEffect(entity, StatusEffects.SPEED);
int duration = EntityUtils.getStatusEffectDuration(entity, StatusEffects.SPEED);

Teleportation

// Teleportation methods
EntityUtils.teleport(entity, new Vec3d(100, 64, 100));
EntityUtils.teleport(entity, new BlockPos(100, 64, 100));
EntityUtils.teleportToEntity(entity, targetEntity);

// Safe teleportation with validation
boolean success = EntityUtils.safeTeleport(entity, targetPos);

Entity Finding

// Find entities in area
List<Entity> nearbyEntities = EntityUtils.getEntitiesInRadius(world, center, 10.0, null);
List<PlayerEntity> players = EntityUtils.getPlayersInRadius(world, center, 20.0);
PlayerEntity nearest = EntityUtils.findNearestPlayer(world, center, 50.0);

// Find specific entity types
List<MobEntity> mobs = EntityUtils.getEntitiesOfType(world, center, 15.0, MobEntity.class);
List<ItemEntity> items = EntityUtils.getEntitiesOfType(world, center, 5.0, ItemEntity.class);

Physics Operations

// Velocity and movement
EntityUtils.setVelocity(entity, new Vec3d(0, 1, 0));
EntityUtils.launchTowards(entity, targetPos, 2.0);
EntityUtils.knockback(entity, sourcePos, 1.5);

// Launch entity upward
EntityUtils.launchUp(entity, 1.0);

🌐 NetworkUtils Examples NEW

NetworkUtils provides easy networking and packet utilities.

Packet Creation

// Create empty buffer
PacketByteBuf buffer = NetworkUtils.createBuffer();

// Create buffer with data
PacketByteBuf buffer = NetworkUtils.createBuffer(buf -> {
    buf.writeString("Hello World");
    buf.writeInt(42);
});

// Create simple packets
PacketByteBuf simplePacket = NetworkUtils.createSimplePacket("test message");
PacketByteBuf posPacket = NetworkUtils.createPositionPacket(blockPos);

Data Serialization

// Write different data types
NetworkUtils.writeString(buffer, "Hello World");
NetworkUtils.writeBlockPos(buffer, new BlockPos(100, 64, 100));
NetworkUtils.writeVec3d(buffer, new Vec3d(1.0, 2.0, 3.0));
NetworkUtils.writeUuid(buffer, player.getUuid());

// Write arrays
NetworkUtils.writeBooleanArray(buffer, new boolean[]{true, false, true});
NetworkUtils.writeIntArray(buffer, new int[]{1, 2, 3, 4, 5});
NetworkUtils.writeStringArray(buffer, new String[]{"hello", "world"});

// Write collections
NetworkUtils.writeStringList(buffer, Arrays.asList("item1", "item2", "item3"));

Packet Sending

// Send to specific player
NetworkUtils.sendToPlayer(player, channelId, buffer);

// Send to multiple players
List<ServerPlayerEntity> players = Arrays.asList(player1, player2);
NetworkUtils.sendToPlayers(players, channelId, buffer);

// Send to all players in world
NetworkUtils.sendToWorld(world, channelId, buffer);

// Send to players in radius
NetworkUtils.sendToPlayersInRadius(world, center, 50.0, channelId, buffer);

Safe Operations

// Safe buffer operations with error handling
boolean success = NetworkUtils.safeBufferOperation(buffer, buf -> {
    buf.writeString("data");
    buf.writeInt(123);
    return true;
});

// Check buffer state
boolean hasData = NetworkUtils.hasReadableBytes(buffer, 4);
int remaining = NetworkUtils.getRemainingBytes(buffer);

📝 Enhanced TextUtils Examples ENHANCED

TextUtils now includes interactive components and performance improvements.

Interactive Text Components

// Create interactive text
Text clickableUrl = TextUtils.clickable("Visit website", "https://example.com");
Text clickableCommand = TextUtils.clickableCommand("Run help", "/help");
Text withTooltip = TextUtils.withTooltip("Hover me", "This is a tooltip");

// Combined interactive text
Text interactive = TextUtils.interactiveText("Click me", "Tooltip text", "https://example.com");

Text Wrapping and Formatting

// Text wrapping
List<String> wrapped = TextUtils.wrapText(longText, 40);
Text multiLineBox = TextUtils.createMultiLineTextBox(lines, 50);

// Number and duration formatting
String formatted = TextUtils.formatNumber(1234567); // "1,234,567"
String decimal = TextUtils.formatDecimal(123.456, 2); // "123.46"
String duration = TextUtils.formatDuration(90000); // "1m 30s"

Enhanced Validation (with caching)

// Cached pattern matching for better performance
boolean isBlank = TextUtils.isBlank("   "); // true
boolean matches = TextUtils.matches("abc123", "[a-z0-9]+"); // Cached regex

// Progress bars with percentages
Text progressBar = TextUtils.progressBar(0.75, 20); // 75% progress

Legacy Text Operations

// Basic text operations (still available)
TextUtils.success("Operation completed!");
TextUtils.error("Something went wrong!");
String capitalized = TextUtils.capitalize("hello world");
boolean isEmail = TextUtils.isValidEmail("user@example.com");

🎒 Enhanced ItemUtils Examples ENHANCED

ItemUtils now includes inventory operations and performance optimizations.

Enhanced Item Operations

// Enhanced validation
boolean canMerge = ItemUtils.canMerge(stack1, stack2);
boolean isDamageable = ItemUtils.isDamageable(stack);
boolean isEnchanted = ItemUtils.isEnchanted(stack);

// Item lookup by ID
Item item = ItemUtils.getItemById("minecraft:diamond_sword");
Item item2 = ItemUtils.getItemById(new Identifier("minecraft", "diamond_sword"));

// Enhanced durability operations
double durabilityPercent = ItemUtils.getDurabilityPercentage(stack);
ItemUtils.damageItem(stack, 10);
ItemUtils.repairItem(stack, 50);
ItemUtils.fullyRepairItem(stack);

Inventory Management

// Insert items into inventory
ItemStack remaining = ItemUtils.insertStack(inventory, stack);

// Consume items from inventory
int consumed = ItemUtils.consumeItem(inventory, Items.DIAMOND, 5);

// Count items in inventory
int total = ItemUtils.countItem(inventory, Items.DIAMOND);

// Find items in inventory
Optional<ItemStack> found = ItemUtils.findFirst(inventory, 
    stack -> stack.isEnchanted());
List<ItemStack> enchanted = ItemUtils.findAll(inventory,
    stack -> stack.isEnchanted());

NBT and Enchantments

// NBT operations
NbtCompound nbt = ItemUtils.getNbt(stack);
ItemUtils.setNbt(stack, nbtData);
boolean hasNbt = ItemUtils.hasNbt(stack);

// Enchantment operations
int level = ItemUtils.getEnchantmentLevel(stack, enchantment);
boolean hasEnchant = ItemUtils.hasEnchantment(stack, enchantment);

// Get all enchantments
Map<RegistryEntry<Enchantment>, Integer> enchantments = ItemUtils.getEnchantments(stack);

Performance Features

// Cached operations for better performance
String itemId = ItemUtils.getItemId(stack); // Cached
int maxStack = ItemUtils.getMaxStackSize(item); // Cached

// Cache management
String stats = ItemUtils.getCacheStats();
ItemUtils.clearCache();

🎨 Enhanced GuiUtils Examples ENHANCED

GuiUtils is now server-side compatible with client-side extensions.

Server-Side Color Operations

// Color creation (works on both client and server)
int red = GuiUtils.rgb(255, 0, 0);
int transparent = GuiUtils.rgba(255, 0, 0, 128);

// Color component extraction
int redComponent = GuiUtils.getRed(color);
int greenComponent = GuiUtils.getGreen(color);
int blueComponent = GuiUtils.getBlue(color);
int alphaComponent = GuiUtils.getAlpha(color);

// Color interpolation
int interpolated = GuiUtils.interpolateColor(red, blue, 0.5f);

Mathematical Operations

// Positioning (server-side compatible)
int centerX = GuiUtils.centerX(elementWidth, containerWidth);
int centerY = GuiUtils.centerY(elementHeight, containerHeight);

// Collision detection
boolean overlaps = GuiUtils.rectanglesOverlap(x1, y1, w1, h1, x2, y2, w2, h2);
boolean pointInRect = GuiUtils.isPointInRect(x, y, rectX, rectY, rectW, rectH);

// Distance calculation
double distance = GuiUtils.distance(x1, y1, x2, y2);

Client-Side Rendering (ClientGuiUtils)

// Import client-side utilities
import com.chosen.lib.util.client.ClientGuiUtils;

// Drawing operations (client-side only)
ClientGuiUtils.drawRect(context, x, y, width, height, color);
ClientGuiUtils.drawProgressBar(context, x, y, width, height, 0.75, bgColor, fgColor);
ClientGuiUtils.drawCenteredText(context, "Hello", centerX, y, color);

// Advanced drawing
ClientGuiUtils.drawBorderedRect(context, x, y, w, h, fillColor, borderColor, borderWidth);
ClientGuiUtils.drawGradient(context, x, y, w, h, startColor, endColor, horizontal);

🎯 Real-World Examples

Here are some practical examples using v1.6.0 features:

World Modification Tool

public class WorldTool {
    public void replaceOresInArea(ServerWorld world, BlockPos center, int radius) {
        // Find all diamond ores in area
        List<BlockPos> ores = WorldUtils.findBlocks(world, center, radius,
            state -> state.isOf(Blocks.DIAMOND_ORE));
        
        // Replace with emerald ore
        for (BlockPos pos : ores) {
            if (WorldUtils.canPlaceBlock(world, pos, Blocks.EMERALD_ORE.getDefaultState())) {
                WorldUtils.setBlockState(world, pos, Blocks.EMERALD_ORE.getDefaultState());
            }
        }
        
        TextUtils.success("Replaced " + ores.size() + " diamond ores with emerald ore!");
    }
}

Entity Management System

public class EntityManager {
    public void healNearbyPlayers(ServerWorld world, Vec3d center, double radius) {
        List<PlayerEntity> players = EntityUtils.getPlayersInRadius(world, center, radius);
        
        for (PlayerEntity player : players) {
            if (!EntityUtils.isFullHealth(player)) {
                EntityUtils.heal(player, 10.0f);
                
                // Send feedback
                Text message = TextUtils.success("You have been healed!");
                player.sendMessage(message, false);
            }
        }
    }
    
    public void teleportToSafety(Entity entity) {
        BlockPos safePos = WorldUtils.getHighestBlock(entity.getWorld(), 
            (int)entity.getX(), (int)entity.getZ());
        
        if (EntityUtils.safeTeleport(entity, safePos.up())) {
            TextUtils.success("Teleported to safety!");
        } else {
            TextUtils.error("Could not find safe location!");
        }
    }
}

Network Communication System

public class NetworkManager {
    public static final Identifier CHANNEL_ID = new Identifier("mymod", "data");
    
    public void sendPlayerData(ServerPlayerEntity player, String data, int value) {
        PacketByteBuf buffer = NetworkUtils.createBuffer(buf -> {
            NetworkUtils.writeString(buf, data);
            buf.writeInt(value);
            NetworkUtils.writeBlockPos(buf, player.getBlockPos());
        });
        
        NetworkUtils.sendToPlayer(player, CHANNEL_ID, buffer);
    }
    
    public void broadcastToArea(ServerWorld world, Vec3d center, String message) {
        PacketByteBuf buffer = NetworkUtils.createSimplePacket(message);
        NetworkUtils.sendToPlayersInRadius(world, center, 100.0, CHANNEL_ID, buffer);
    }
}

Advanced Inventory System

public class InventoryManager {
    public boolean processRecipe(Inventory inventory, Item input, Item output, int count) {
        // Check if we have enough input items
        int available = ItemUtils.countItem(inventory, input);
        if (available < count) {
            TextUtils.error("Not enough " + ItemUtils.getItemId(input.getDefaultStack()));
            return false;
        }
        
        // Consume input items
        int consumed = ItemUtils.consumeItem(inventory, input, count);
        
        // Create output stack
        ItemStack outputStack = new ItemStack(output, consumed);
        
        // Try to insert output
        ItemStack remaining = ItemUtils.insertStack(inventory, outputStack);
        
        if (remaining.isEmpty()) {
            TextUtils.success("Recipe processed successfully!");
            return true;
        } else {
            TextUtils.error("Not enough space for output!");
            return false;
        }
    }
}

⚡ Performance Features

ChosenLib v1.5.0 includes comprehensive performance optimizations:

Caching Systems

// ItemUtils caching
String itemId = ItemUtils.getItemId(stack); // Cached for performance
int maxStack = ItemUtils.getMaxStackSize(item); // Cached

// TextUtils caching
boolean matches = TextUtils.matches(text, regex); // Regex patterns cached
String formatted = TextUtils.formatNumber(123456); // Formatters cached

// Cache management
String itemStats = ItemUtils.getCacheStats();
String textStats = TextUtils.getCacheStats();

// Clear caches if needed
ItemUtils.clearCache();
TextUtils.clearCache();

Thread Safety

  • All caches use ConcurrentHashMap for thread-safe operations
  • Utility methods are designed to be thread-safe
  • No shared mutable state between method calls

💡 Best Practices

Performance Tips

  • Use caching features: ItemUtils and TextUtils cache frequently used data
  • Batch operations: Use area operations instead of individual block operations
  • Validate before processing: Check if positions are loaded before world operations
  • Use appropriate radius: Don't use unnecessarily large search radii

Code Organization

  • Separate client and server: Use ClientGuiUtils for client-side rendering
  • Handle errors gracefully: Always check return values and handle failures
  • Use meaningful feedback: Provide clear messages to users
  • Validate inputs: Check for null values and valid ranges

Network Best Practices

  • Minimize packet size: Only send necessary data
  • Use appropriate targeting: Don't broadcast when you can send to specific players
  • Handle packet failures: Use safe operations when possible
  • Validate packet data: Always validate received data

📚 API Stability: The current API (v1.6.0) is stable for production use. All features are production-ready with comprehensive documentation. See our changelog for detailed information about all new features.

🔗 Next Steps

Now that you understand the v1.6.0 features, explore these resources:

📚 API Reference

Complete documentation for all v1.6.0 methods and classes.

View API

📋 Changelog

See detailed information about v1.6.0 changes and improvements.

View Changelog

🚀 Getting Started

Learn how to set up ChosenLib v1.6.0 in your project.

Get Started